@coderline/alphatab 1.4.0 → 1.4.3
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.
- package/dist/alphaTab.core.min.mjs +1 -1
- package/dist/alphaTab.core.mjs +57 -23
- package/dist/alphaTab.d.ts +22 -1
- package/dist/alphaTab.js +57 -23
- package/dist/alphaTab.min.js +1 -1
- package/dist/alphaTab.mjs +1 -1
- package/dist/alphaTab.vite.js +1 -1
- package/dist/alphaTab.vite.mjs +1 -1
- package/dist/alphaTab.webpack.js +1 -1
- package/dist/alphaTab.webpack.mjs +1 -1
- package/dist/alphaTab.worker.mjs +1 -1
- package/dist/alphaTab.worklet.mjs +1 -1
- package/dist/font/Bravura-FONTLOG.txt +345 -345
- package/dist/font/Bravura-OFL-FAQ.txt +369 -369
- package/dist/font/Bravura-OFL.txt +94 -94
- package/dist/font/Bravura.svg +3864 -3864
- package/dist/soundfont/LICENSE +10 -10
- package/dist/soundfont/README.md +19 -19
- package/package.json +1 -1
package/dist/alphaTab.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).alphaTab={})}(this,(function(e){"use strict";var t,s,i,a,r,n,o,h,l,d,c,u,p,g,m,f,y,b,S,_,w,B,T,k,N,x,v,P,C,E,F,D,L,M,I,A,R,O,V,H,G,W,z,U,X,J,Y;e.LayoutMode=void 0,(t=e.LayoutMode||(e.LayoutMode={}))[t.Page=0]="Page",t[t.Horizontal=1]="Horizontal",e.StaveProfile=void 0,(s=e.StaveProfile||(e.StaveProfile={}))[s.Default=0]="Default",s[s.ScoreTab=1]="ScoreTab",s[s.Score=2]="Score",s[s.Tab=3]="Tab",s[s.TabMixed=4]="TabMixed";class q{static getValue(e){return q._values||(q._values=new Map),e=e.toLowerCase().replaceAll(" ",""),q._values.has(e)?q._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}}q._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]]);class j{init(e,t){this.data=e,this.settings=t}}e.AlphaTabErrorType=void 0,(i=e.AlphaTabErrorType||(e.AlphaTabErrorType={}))[i.General=0]="General",i[i.Format=1]="Format",i[i.AlphaTex=2]="AlphaTex";class K extends Error{constructor(e,t="",s){super(t??"",{cause:s}),this.type=e,Object.setPrototypeOf(this,K.prototype)}}class Q extends K{constructor(t=null,s){super(e.AlphaTabErrorType.Format,t??"Unsupported format",s),Object.setPrototypeOf(this,Q.prototype)}}!function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy",e[e.Tenuto=3]="Tenuto"}(a||(a={})),function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(r||(r={}));class ${constructor(){this.isLinear=!1,this.type=r.Tempo,this.value=0,this.ratioPosition=0,this.text=""}static buildTempoAutomation(e,t,s,i){(i<1||i>5)&&(i=2);let a=new Float32Array([1,.5,1,1.5,2,3]),n=new $;return n.type=r.Tempo,n.isLinear=e,n.ratioPosition=t,n.value=s*a[i],n}static buildInstrumentAutomation(e,t,s){let i=new $;return i.type=r.Instrument,i.isLinear=e,i.ratioPosition=t,i.value=s,i}}!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.Down=0]="Down",e[e.Hold=1]="Hold",e[e.Up=2]="Up"}(l||(l={}));class Z{constructor(){this.ratioPosition=0,this.pedalType=l.Down,this.nextPedalMarker=null,this.previousPedalMarker=null}}class ee{constructor(){this.id=ee._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=[]}get masterBar(){return this.staff.track.score.masterBars[this.index]}get isEmpty(){for(let e=0,t=this.voices.length;e<t;e++)if(!this.voices[e].isEmpty)return!1;return!0}addVoice(e){e.bar=this,e.index=this.voices.length,this.voices.push(e)}finish(e,t=null){this.isMultiVoice=!1;for(let s=0,i=this.voices.length;s<i;s++){let i=this.voices[s];i.finish(e,t),s>0&&!i.isEmpty&&(this.isMultiVoice=!0)}if(this.sustainPedals.length>0){let e=null;this.previousBar&&this.previousBar.sustainPedals.length>0&&(e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1]);for(const t of this.sustainPedals)e&&e.pedalType!==l.Up&&(e.nextPedalMarker=t,t.previousPedalMarker=e),t.bar=this,e=t}else if(this.previousBar&&this.previousBar.sustainPedals.length>0){const e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1];if(e.pedalType!==l.Up){const t=new Z;t.ratioPosition=0,t.bar=this,t.pedalType=l.Hold,this.sustainPedals.push(t),e.nextPedalMarker=t,t.previousPedalMarker=e}}}calculateDuration(){let e=0;for(let t of this.voices){let s=t.calculateDuration();s>e&&(e=s)}return e}}ee._globalBarId=0;class te{static ticksToMillis(e,t){return e*(6e4/(t*te.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*te.QuarterTime))|0}static toTicks(e){return te.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),te.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){return te.MinVelocity+e*te.VelocityIncrement}}te.QuarterTime=960,te.MinVelocity=15,te.VelocityIncrement=16;class se{constructor(e=0,t=0){this.offset=e,this.value=t}}se.MaxPosition=60,se.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(d||(d={})),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"}(c||(c={})),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"}(u||(u={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(p||(p={})),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"}(g||(g={})),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"}(m||(m={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(f||(f={})),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"}(y||(y={})),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"}(b||(b={})),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"}(S||(S={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(_||(_={})),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"}(w||(w={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(B||(B={})),e.TabRhythmMode=void 0,(T=e.TabRhythmMode||(e.TabRhythmMode={}))[T.Hidden=0]="Hidden",T[T.ShowWithBeams=1]="ShowWithBeams",T[T.ShowWithBars=2]="ShowWithBars",T[T.Automatic=3]="Automatic",e.FingeringMode=void 0,(k=e.FingeringMode||(e.FingeringMode={}))[k.ScoreDefault=0]="ScoreDefault",k[k.ScoreForcePiano=1]="ScoreForcePiano",k[k.SingleNoteEffectBand=2]="SingleNoteEffectBand",k[k.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano",e.NotationMode=void 0,(N=e.NotationMode||(e.NotationMode={}))[N.GuitarPro=0]="GuitarPro",N[N.SongBook=1]="SongBook",e.NotationElement=void 0,(x=e.NotationElement||(e.NotationElement={}))[x.ScoreTitle=0]="ScoreTitle",x[x.ScoreSubTitle=1]="ScoreSubTitle",x[x.ScoreArtist=2]="ScoreArtist",x[x.ScoreAlbum=3]="ScoreAlbum",x[x.ScoreWords=4]="ScoreWords",x[x.ScoreMusic=5]="ScoreMusic",x[x.ScoreWordsAndMusic=6]="ScoreWordsAndMusic",x[x.ScoreCopyright=7]="ScoreCopyright",x[x.GuitarTuning=8]="GuitarTuning",x[x.TrackNames=9]="TrackNames",x[x.ChordDiagrams=10]="ChordDiagrams",x[x.ParenthesisOnTiedBends=11]="ParenthesisOnTiedBends",x[x.TabNotesOnTiedBends=12]="TabNotesOnTiedBends",x[x.ZerosOnDiveWhammys=13]="ZerosOnDiveWhammys",x[x.EffectAlternateEndings=14]="EffectAlternateEndings",x[x.EffectCapo=15]="EffectCapo",x[x.EffectChordNames=16]="EffectChordNames",x[x.EffectCrescendo=17]="EffectCrescendo",x[x.EffectDynamics=18]="EffectDynamics",x[x.EffectFadeIn=19]="EffectFadeIn",x[x.EffectFermata=20]="EffectFermata",x[x.EffectFingering=21]="EffectFingering",x[x.EffectHarmonics=22]="EffectHarmonics",x[x.EffectLetRing=23]="EffectLetRing",x[x.EffectLyrics=24]="EffectLyrics",x[x.EffectMarker=25]="EffectMarker",x[x.EffectOttavia=26]="EffectOttavia",x[x.EffectPalmMute=27]="EffectPalmMute",x[x.EffectPickSlide=28]="EffectPickSlide",x[x.EffectPickStroke=29]="EffectPickStroke",x[x.EffectSlightBeatVibrato=30]="EffectSlightBeatVibrato",x[x.EffectSlightNoteVibrato=31]="EffectSlightNoteVibrato",x[x.EffectTap=32]="EffectTap",x[x.EffectTempo=33]="EffectTempo",x[x.EffectText=34]="EffectText",x[x.EffectTrill=35]="EffectTrill",x[x.EffectTripletFeel=36]="EffectTripletFeel",x[x.EffectWhammyBar=37]="EffectWhammyBar",x[x.EffectWideBeatVibrato=38]="EffectWideBeatVibrato",x[x.EffectWideNoteVibrato=39]="EffectWideNoteVibrato",x[x.EffectLeftHandTap=40]="EffectLeftHandTap",x[x.EffectFreeTime=41]="EffectFreeTime",x[x.EffectSustainPedal=42]="EffectSustainPedal",x[x.EffectGolpe=43]="EffectGolpe",x[x.EffectWahPedal=44]="EffectWahPedal",x[x.EffectBeatBarre=45]="EffectBeatBarre",x[x.EffectNoteOrnament=46]="EffectNoteOrnament",x[x.EffectRasgueado=47]="EffectRasgueado",x[x.EffectDirections=48]="EffectDirections",x[x.EffectBeatTimer=49]="EffectBeatTimer";class ie{constructor(){this.notationMode=e.NotationMode.GuitarPro,this.fingeringMode=e.FingeringMode.ScoreDefault,this.elements=new Map,this.rhythmMode=e.TabRhythmMode.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):!ie.defaultElements.has(e)||ie.defaultElements.get(e)}}ie.defaultElements=new Map([[e.NotationElement.ZerosOnDiveWhammys,!1]]);class ae{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}e.LogLevel=void 0,(v=e.LogLevel||(e.LogLevel={}))[v.None=0]="None",v[v.Debug=1]="Debug",v[v.Info=2]="Info",v[v.Warning=3]="Warning",v[v.Error=4]="Error";class re{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...s){console.debug(re.format(e,t),...s)}warning(e,t,...s){console.warn(re.format(e,t),...s)}info(e,t,...s){console.info(re.format(e,t),...s)}error(e,t,...s){console.error(re.format(e,t),...s)}}re.logLevel=e.LogLevel.Info;class ne{static shouldLog(t){return ne.logLevel!==e.LogLevel.None&&t>=ne.logLevel}static debug(t,s,...i){ne.shouldLog(e.LogLevel.Debug)&&ne.log.debug(t,s,...i)}static warning(t,s,...i){ne.shouldLog(e.LogLevel.Warning)&&ne.log.warning(t,s,...i)}static info(t,s,...i){ne.shouldLog(e.LogLevel.Info)&&ne.log.info(t,s,...i)}static error(t,s,...i){ne.shouldLog(e.LogLevel.Error)&&ne.log.error(t,s,...i)}}ne.logLevel=e.LogLevel.Info,ne.log=new re,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"}(P||(P={})),function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(C||(C={})),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"}(E||(E={}));class oe{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=P.C,this.keySignatureType=C.Major,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.isFreeTime=!1,this.tripletFeel=E.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 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(let t of this.score.tracks)for(let s of t.staves){let t=this.index<s.bars.length?s.bars[this.index].calculateDuration():0;t>e&&(e=t)}return e}return this.timeSignatureNumerator*te.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}}oe.MaxAlternateEndings=8;class he{constructor(){this.note=null,this.tone=new le,this.octave=0}get realValue(){return 12*this.octave+this.tone.noteValue}}class le{constructor(e=0,t=S.Default){this.noteValue=e,this.accidentalMode=t}}class de{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(let i of t.tracks[s].staves)i.displayTranspositionPitch=-e.notation.displayTranspositionPitches[s];if(s<e.notation.transpositionPitches.length)for(let i of t.tracks[s].staves)i.transpositionPitch=-e.notation.transpositionPitches[s]}}static fingerToString(t,s,i,a){if(t.notation.fingeringMode===e.FingeringMode.ScoreForcePiano||t.notation.fingeringMode===e.FingeringMode.SingleNoteEffectBandForcePiano||q.isPiano(s.voice.bar.staff.track.playbackInfo.program))switch(i){case y.Unknown:case y.NoOrDead:return null;case y.Thumb:return"1";case y.IndexFinger:return"2";case y.MiddleFinger:return"3";case y.AnnularFinger:return"4";case y.LittleFinger:return"5";default:return null}if(a)switch(i){case y.Unknown:return null;case y.NoOrDead:return"0";case y.Thumb:return"t";case y.IndexFinger:return"1";case y.MiddleFinger:return"2";case y.AnnularFinger:return"3";case y.LittleFinger:return"4";default:return null}switch(i){case y.Unknown:case y.NoOrDead:return null;case y.Thumb:return"p";case y.IndexFinger:return"i";case y.MiddleFinger:return"m";case y.AnnularFinger:return"a";case y.LittleFinger:return"c";default:return null}}static isTuning(e){return!!de.parseTuning(e)}static parseTuning(e){let t="",s="";for(let i=0;i<e.length;i++){let a=e.charCodeAt(i);if(a>=48&&a<=57){if(!t)return null;s+=String.fromCharCode(a)}else{if(!de.TuningLetters.has(a))return null;t+=String.fromCharCode(a)}}if(!s||!t)return null;let i=new he;return i.octave=parseInt(s)+1,i.note=t.toLowerCase(),i.tone=de.getToneForText(i.note),i.tone.noteValue<0&&(i.octave--,i.tone.noteValue+=12),i}static getTuningForText(e){let t=de.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=de.parseAccidentalMode(s),a){case S.Default:case S.ForceNone:case S.ForceNatural:break;case S.ForceSharp:i++;break;case S.ForceDoubleSharp:i+=2;break;case S.ForceFlat:i--;break;case S.ForceDoubleFlat:i-=2}return new le(i,a)}static parseAccidentalMode(e){const t=e.toLowerCase();return de.accidentalModeMapping.has(t)?de.accidentalModeMapping.get(t):S.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<oe.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}}de.TuningLetters=new Set([67,68,69,70,71,65,66,99,100,101,102,103,97,98,35]),de.accidentalModeMapping=new Map([["default",S.Default],["d",S.Default],["forcenone",S.ForceNone],["-",S.ForceNone],["forcenatural",S.ForceNatural],["n",S.ForceNatural],["forcesharp",S.ForceSharp],["#",S.ForceSharp],["forcedoublesharp",S.ForceDoubleSharp],["##",S.ForceDoubleSharp],["x",S.ForceDoubleSharp],["forceflat",S.ForceFlat],["b",S.ForceFlat],["forcedoubleflat",S.ForceDoubleFlat],["bb",S.ForceDoubleFlat]]),function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(F||(F={})),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.NoteheadTriangleUpWhole=57531]="NoteheadTriangleUpWhole",e[e.NoteheadTriangleUpHalf=57532]="NoteheadTriangleUpHalf",e[e.NoteheadTriangleUpBlack=57534]="NoteheadTriangleUpBlack",e[e.NoteheadDiamondBlackWide=57564]="NoteheadDiamondBlackWide",e[e.NoteheadDiamondWhite=57565]="NoteheadDiamondWhite",e[e.NoteheadDiamondWhiteWide=57566]="NoteheadDiamondWhiteWide",e[e.NoteheadCircleX=57523]="NoteheadCircleX",e[e.NoteheadXWhole=57511]="NoteheadXWhole",e[e.NoteheadXHalf=57512]="NoteheadXHalf",e[e.NoteheadXBlack=57513]="NoteheadXBlack",e[e.NoteheadParenthesis=57550]="NoteheadParenthesis",e[e.NoteheadSlashedBlack2=57552]="NoteheadSlashedBlack2",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.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.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.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.DynamicForte=58658]="DynamicForte",e[e.DynamicFF=58671]="DynamicFF",e[e.DynamicFFF=58672]="DynamicFFF",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"}(D||(D={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(L||(L={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(M||(M={}));class ce{constructor(e,t){this.width=e,this.height=t}}class ue{constructor(e="",t=0,s=0,i=D.None,a=D.None,r=D.None,n=D.None,o=M.Middle){this.elementType=e,this.outputMidiNumber=s,this.staffLine=t,this.noteHeadDefault=i,this.noteHeadHalf=a!==D.None?a:i,this.noteHeadWhole=r!==D.None?r:i,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case g.Whole:return this.noteHeadWhole;case g.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class pe{static articulationFromElementVariation(e,t){return e<pe.gp6ElementAndVariationToArticulation.length?(t>=pe.gp6ElementAndVariationToArticulation.length&&(t=0),pe.gp6ElementAndVariationToArticulation[e][t]):38}static getArticulation(e){const t=e.percussionArticulation,s=e.beat.voice.bar.staff.track.percussionArticulations;return t<s.length?s[t]:pe.getArticulationByValue(t)}static getElementAndVariation(e){const t=pe.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<pe.gp6ElementAndVariationToArticulation.length;e++){const s=pe.gp6ElementAndVariationToArticulation[e];for(let i=0;i<s.length;i++){const a=pe.getArticulationByValue(s[i]);if(a?.outputMidiNumber===t.outputMidiNumber)return[e,i]}}return[-1,-1]}static getArticulationByValue(e){return pe.instrumentArticulations.has(e)?pe.instrumentArticulations.get(e):null}}pe.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]],pe.instrumentArticulations=new Map([[38,new ue("snare",3,38,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[37,new ue("snare",3,37,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[91,new ue("snare",3,38,D.NoteheadDiamondWhite,D.NoteheadDiamondWhite,D.NoteheadDiamondWhite)],[42,new ue("hiHat",-1,42,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[92,new ue("hiHat",-1,46,D.NoteheadCircleSlash,D.NoteheadCircleSlash,D.NoteheadCircleSlash)],[46,new ue("hiHat",-1,46,D.NoteheadCircleX,D.NoteheadCircleX,D.NoteheadCircleX)],[44,new ue("hiHat",9,44,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[35,new ue("kickDrum",8,35,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[36,new ue("kickDrum",7,36,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[50,new ue("tom",1,50,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[48,new ue("tom",2,48,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[47,new ue("tom",4,47,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[45,new ue("tom",5,45,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[43,new ue("tom",6,43,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[93,new ue("ride",0,51,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack,D.PictEdgeOfCymbal,M.Bottom)],[51,new ue("ride",0,51,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[53,new ue("ride",0,53,D.NoteheadDiamondWhite,D.NoteheadDiamondWhite,D.NoteheadDiamondWhite)],[94,new ue("ride",0,51,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack,D.ArticStaccatoAbove,M.Top)],[55,new ue("splash",-2,55,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[95,new ue("splash",-2,55,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack,D.ArticStaccatoAbove,M.Bottom)],[52,new ue("china",-3,52,D.NoteheadHeavyXHat,D.NoteheadHeavyXHat,D.NoteheadHeavyXHat)],[96,new ue("china",-3,52,D.NoteheadHeavyXHat,D.NoteheadHeavyXHat,D.NoteheadHeavyXHat)],[49,new ue("crash",-2,49,D.NoteheadHeavyX,D.NoteheadHeavyX,D.NoteheadHeavyX)],[97,new ue("crash",-2,49,D.NoteheadHeavyX,D.NoteheadHeavyX,D.NoteheadHeavyX,D.ArticStaccatoAbove,M.Bottom)],[57,new ue("crash",-1,57,D.NoteheadHeavyX,D.NoteheadHeavyX,D.NoteheadHeavyX)],[98,new ue("crash",-1,57,D.NoteheadHeavyX,D.NoteheadHeavyX,D.NoteheadHeavyX,D.ArticStaccatoAbove,M.Bottom)],[99,new ue("cowbell",1,56,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpHalf,D.NoteheadTriangleUpWhole)],[100,new ue("cowbell",1,56,D.NoteheadXBlack,D.NoteheadXHalf,D.NoteheadXWhole)],[56,new ue("cowbell",0,56,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpHalf,D.NoteheadTriangleUpWhole)],[101,new ue("cowbell",0,56,D.NoteheadXBlack,D.NoteheadXHalf,D.NoteheadXWhole)],[102,new ue("cowbell",-1,56,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpHalf,D.NoteheadTriangleUpWhole)],[103,new ue("cowbell",-1,56,D.NoteheadXBlack,D.NoteheadXHalf,D.NoteheadXWhole)],[77,new ue("woodblock",-9,77,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack)],[76,new ue("woodblock",-10,76,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack)],[60,new ue("bongo",-4,60,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[104,new ue("bongo",-5,60,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.NoteheadParenthesis,M.Middle)],[105,new ue("bongo",-6,60,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[61,new ue("bongo",-7,61,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[106,new ue("bongo",-8,61,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.NoteheadParenthesis,M.Middle)],[107,new ue("bongo",-16,61,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[66,new ue("timbale",10,66,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[65,new ue("timbale",9,65,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[68,new ue("agogo",12,68,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[67,new ue("agogo",11,67,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[64,new ue("conga",17,64,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[108,new ue("conga",16,64,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[109,new ue("conga",15,64,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.NoteheadParenthesis,M.Middle)],[63,new ue("conga",14,63,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[110,new ue("conga",13,63,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[62,new ue("conga",19,62,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.NoteheadParenthesis,M.Middle)],[72,new ue("whistle",-11,72,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[71,new ue("whistle",-17,71,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[73,new ue("guiro",38,73,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[74,new ue("guiro",37,74,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[86,new ue("surdo",36,86,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[87,new ue("surdo",35,87,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadParenthesis,M.Middle)],[54,new ue("tambourine",3,54,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack)],[111,new ue("tambourine",2,54,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack,D.StringsUpBow,M.Bottom)],[112,new ue("tambourine",1,54,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack,D.StringsDownBow,M.Bottom)],[113,new ue("tambourine",-7,54,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[79,new ue("cuica",30,79,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[78,new ue("cuica",29,78,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[58,new ue("vibraslap",28,58,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[81,new ue("triangle",27,81,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[80,new ue("triangle",26,80,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadParenthesis,M.Middle)],[114,new ue("grancassa",25,43,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[115,new ue("piatti",18,49,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[116,new ue("piatti",24,49,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[69,new ue("cabasa",23,69,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[117,new ue("cabasa",22,69,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.StringsUpBow,M.Bottom)],[85,new ue("castanets",21,85,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[75,new ue("claves",20,75,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[70,new ue("maraca",-12,70,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[118,new ue("maraca",-13,70,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.StringsUpBow,M.Bottom)],[119,new ue("maraca",-14,70,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[120,new ue("maraca",-15,70,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.StringsUpBow,M.Bottom)],[82,new ue("shaker",-23,54,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[122,new ue("shaker",-24,54,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.StringsUpBow,M.Bottom)],[84,new ue("bellTree",-18,53,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[123,new ue("bellTree",-19,53,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.StringsUpBow,M.Bottom)],[83,new ue("jingleBell",-20,53,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[124,new ue("unpitched",-21,62,D.NoteheadNull,D.NoteheadNull,D.NoteheadNull,D.GuitarGolpe,M.Top)],[125,new ue("unpitched",-22,62,D.NoteheadNull,D.NoteheadNull,D.NoteheadNull,D.GuitarGolpe,M.Bottom)],[39,new ue("handClap",3,39,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[40,new ue("snare",3,40,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[31,new ue("snare",3,40,D.NoteheadSlashedBlack2,D.NoteheadSlashedBlack2,D.NoteheadSlashedBlack2)],[41,new ue("tom",5,41,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[59,new ue("ride",2,59,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack,D.PictEdgeOfCymbal,M.Bottom)],[126,new ue("ride",2,59,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[127,new ue("ride",2,59,D.NoteheadDiamondWhite,D.NoteheadDiamondWhite,D.NoteheadDiamondWhite)],[29,new ue("ride",2,59,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack,D.ArticStaccatoAbove,M.Top)],[30,new ue("crash",-3,49,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[33,new ue("snare",3,37,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[34,new ue("snare",3,38,D.NoteheadBlack,D.NoteheadBlack,D.NoteheadBlack)]]),pe.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"}(I||(I={}));class ge{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1}}class me{constructor(){this.id=me.GlobalNoteId++,this.index=0,this.accentuated=a.None,this.bendType=c.None,this.bendStyle=d.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=b.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=_.None,this.slideOutType=w.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=B.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=y.Unknown,this.rightHandFinger=y.Unknown,this.trillValue=-1,this.trillSpeed=g.ThirtySecond,this.durationPercent=1,this.accidentalMode=S.Default,this.dynamics=m.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.ornament=I.None,this._noteIdBag=null}get hasBend(){return null!==this.bendPoints&&this.bendType!==c.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?pe.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?pe.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==b.None}get isTieOrigin(){return null!==this.tieDestination}get isFingering(){return this.leftHandFinger!==y.Unknown||this.rightHandFinger!==y.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+me.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===b.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===b.None||!this.isStringed)return 0;let e=this.harmonicValue;return de.isAlmostEqualTo(e,2.4)?36:de.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!==b.Natural&&this.harmonicType!==b.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===c.None&&(this.bendType=c.Custom)}finish(t,s=null){let i=new ae((()=>me.nextNoteOnSameLine(this))),a=t&&t.notation.notationMode===e.NotationMode.SongBook;if(this.isTieDestination&&(this.chain(s),a&&this.tieOrigin&&this.tieOrigin.isLetRing&&(this.isLetRing=!0)),this.isLetRing&&(i.value&&i.value.isLetRing?this.letRingDestination=i.value:this.letRingDestination=this,a&&this.isTieDestination&&!this.tieOrigin.hasBend&&(this.isVisible=!1)),this.isPalmMute&&(i.value&&i.value.isPalmMute?this.palmMuteDestination=i.value:this.palmMuteDestination=this),this.isHammerPullOrigin){let e=me.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case w.Shift:case w.Legato:this.slideTarget=i.value,this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=w.None}let r=null;this.isHammerPullOrigin&&this.hammerPullDestination?r=this.hammerPullDestination:this.slideOutType===w.Legato&&this.slideTarget&&(r=this.slideTarget),r&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===F.None?(this.effectSlurOrigin.effectSlurDestination=r,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=r,this.effectSlurDestination.effectSlurOrigin=this));const n=this.bendPoints,o=null!=n&&n.length>0;if(o){let e=this.isTieDestination&&this.tieOrigin.hasBend;this.isContinuedBend=e}else this.bendType=c.None;if(o&&this.bendType===c.Custom)if(4===n.length){let e=n[0],t=n[1],s=n[2],i=n[3];t.value===s.value?i.value>e.value?t.value>i.value?this.bendType=c.BendRelease:!this.isContinuedBend&&e.value>0?(this.bendType=c.PrebendBend,n.splice(2,1),n.splice(1,1)):(this.bendType=c.Bend,n.splice(2,1),n.splice(1,1)):i.value<e.value?this.isContinuedBend?(this.bendType=c.Release,n.splice(2,1),n.splice(1,1)):(this.bendType=c.PrebendRelease,n.splice(2,1),n.splice(1,1)):t.value>e.value?this.bendType=c.BendRelease:e.value>0&&!this.isContinuedBend?(this.bendType=c.Prebend,n.splice(2,1),n.splice(1,1)):(this.bendType=c.Hold,n.splice(2,1),n.splice(1,1)):ne.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===n.length){let e=n[0],t=n[1];t.value>e.value?!this.isContinuedBend&&e.value>0?this.bendType=c.PrebendBend:this.bendType=c.Bend:t.value<e.value?this.isContinuedBend?this.bendType=c.Release:this.bendType=c.PrebendRelease:e.value>0&&!this.isContinuedBend?this.bendType=c.Prebend:this.bendType=c.Hold}this.initialBendValue>0&&(this.accidentalMode=S.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+me.MaxOffsetForSameLineSearch;){let 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+me.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-me.MaxOffsetForSameLineSearch;){if(e.isStringed){let 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{let 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(me.NoteIdLookupKey)?t=e.get(me.NoteIdLookupKey):(t=new Map,e.set(me.NoteIdLookupKey,t)),-1===this._noteIdBag.hammerPullDestinationNoteId&&-1===this._noteIdBag.tieDestinationNoteId&&-1===this._noteIdBag.slurDestinationNoteId||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),this._noteIdBag=null}else{if(!this.isTieDestination&&null===this.tieOrigin)return;let e=this.tieOrigin??me.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)}setProperty(e,t){switch(e){case"tiedestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new ge),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new ge),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new ge),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new ge),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new ge),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new ge),this._noteIdBag.hammerPullDestinationNoteId=t,!0}return!1}}me.GlobalNoteId=0,me.MaxOffsetForSameLineSearch=3,me.NoteIdLookupKey="NoteIdLookup";class fe{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!==f.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{let e=this.beats[0].tupletNumerator/this.beats[0].tupletDenominator|0;for(let t of fe.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}fe.HalfTicks=1920,fe.QuarterTicks=960,fe.EighthTicks=480,fe.SixteenthTicks=240,fe.ThirtySecondTicks=120,fe.SixtyFourthTicks=60,fe.OneHundredTwentyEighthTicks=30,fe.TwoHundredFiftySixthTicks=15,fe.AllTicks=[fe.HalfTicks,fe.QuarterTicks,fe.EighthTicks,fe.SixteenthTicks,fe.ThirtySecondTicks,fe.SixtyFourthTicks,fe.OneHundredTwentyEighthTicks,fe.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"}(A||(A={}));class ye{static clone(e){const t=new se;return t.offset=e.offset,t.value=e.value,t}}class be{static clone(e){const t=new me;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(ye.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 Se{static clone(e){const t=new $;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class _e{static clone(e){const t=new Be;t.index=e.index,t.notes=[];for(const s of e.notes)t.addNote(be.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(Se.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(ye.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.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}}class we{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.None=0]="None",e[e.Thumb=1]="Thumb",e[e.Finger=2]="Finger"}(R||(R={})),function(e){e[e.None=0]="None",e[e.FadeIn=1]="FadeIn",e[e.FadeOut=2]="FadeOut",e[e.VolumeSwell=3]="VolumeSwell"}(O||(O={})),function(e){e[e.None=0]="None",e[e.Open=1]="Open",e[e.Closed=2]="Closed"}(V||(V={})),function(e){e[e.None=0]="None",e[e.Full=1]="Full",e[e.Half=2]="Half"}(H||(H={})),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"}(G||(G={})),function(e){e[e.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext",e[e.ForceSplitOnSecondaryToNext=3]="ForceSplitOnSecondaryToNext"}(W||(W={}));class Be{constructor(){this.id=Be._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=d.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=g.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fade=O.None,this.lyrics=null,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.slashed=!1,this.deadSlapped=!1,this.brushType=u.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=A.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=B.None,this.chordId=null,this.graceType=f.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=F.None,this.tremoloSpeed=null,this.crescendo=p.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.golpe=R.None,this.dynamics=m.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=W.Auto,this.wahPedal=V.None,this.barreFret=-1,this.barreShape=H.None,this.rasgueado=G.None,this.showTimer=!1,this.timer=null}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===g.Whole}get fadeIn(){return this.fade===O.FadeIn}set fadeIn(e){this.fade=e?O.FadeIn:O.None}get hasRasgueado(){return this.rasgueado!==G.None}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==A.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 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!==H.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===A.None&&(this.whammyBarType=A.Custom)}removeWhammyBarPoint(e){const t=this.whammyBarPoints;if(null===t||e<0||e>=t.length)return;t.splice(e,1);let s=t[e];if(s===this.maxWhammyPoint){this.maxWhammyPoint=null;for(let e of t)(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e)}if(s===this.minWhammyPoint){this.minWhammyPoint=null;for(let 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){let 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++){let 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(this.isFullBarRest)return this.voice.bar.masterBar.calculateDuration();let e=te.toTicks(this.duration);return 2===this.dots?e=te.applyDot(e,!0):1===this.dots&&(e=te.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=te.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){let e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case f.BeforeBeat:case f.OnBeat:switch(this.duration){case g.Sixteenth:this.playbackDuration=te.toTicks(g.SixtyFourth);break;case g.ThirtySecond:this.playbackDuration=te.toTicks(g.OneHundredTwentyEighth);break;default:this.playbackDuration=te.toTicks(g.ThirtySecond)}this.displayDuration=0;break;case f.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;let t=this.previousBeat;t&&t.graceType===f.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){let e=this.previousBeat,t=e?e.tupletGroup:null;if((this.hasTuplet||this.graceType!==f.None&&t)&&(e&&t&&t.check(this)||(t=new fe(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!==r.Volume&&t.push(s);this.automations=t}}finish(t,s=null){switch(null===this.getAutomation(r.Instrument)&&0===this.index&&0===this.voice.index&&0===this.voice.bar.index&&0===this.voice.bar.staff.index&&this.automations.push($.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case f.OnBeat:case f.BeforeBeat:let e=this.graceGroup.beats.length;this.duration=1===e?g.Eighth:2===e?g.Sixteenth:g.ThirtySecond}let i=t?t.notation.notationMode:e.NotationMode.GuitarPro,a="grad"===this.text||"grad."===this.text;a&&i===e.NotationMode.SongBook&&(this.text="");let n=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let o=0,h=!1;for(let r=0,l=this.notes.length;r<l;r++){let l=this.notes[r];if(l.dynamics=this.dynamics,l.finish(t,s),l.isLetRing&&(this.isLetRing=!0),l.isPalmMute&&(this.isPalmMute=!0),i===e.NotationMode.SongBook&&l.hasBend&&this.graceType!==f.BendGrace){if(!l.isTieOrigin)switch(l.bendType){case c.Bend:case c.PrebendRelease:case c.PrebendBend:n=!0}a||l.bendStyle===d.Gradual?(a=!0,l.bendStyle=d.Gradual,n=!1):l.bendStyle=d.Fast}l.isVisible&&(o++,(!this.minNote||l.realValue<this.minNote.realValue)&&(this.minNote=l),(!this.maxNote||l.realValue>this.maxNote.realValue)&&(this.maxNote=l),(!this.minStringNote||l.string<this.minStringNote.string)&&(this.minStringNote=l),(!this.maxStringNote||l.string>this.maxStringNote.string)&&(this.maxStringNote=l),l.hasEffectSlur&&(h=!0))}if(h&&(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===o&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&t&&t.notation.notationMode===e.NotationMode.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 l=this.whammyBarPoints,u=null!==l&&l.length>0;if(u){const e=!!this.previousBeat&&this.previousBeat.hasWhammyBar;this.isContinuedWhammy=e}else this.whammyBarType=A.None;if(u&&this.whammyBarType===A.Custom&&(i===e.NotationMode.SongBook&&(this.whammyStyle=a?d.Gradual:d.Fast),4===l.length)){let t=l[0],s=l[1],a=l[2],r=l[3];s.value===a.value&&(t.value<s.value&&s.value<r.value||t.value>s.value&&s.value>r.value?(0===t.value||this.isContinuedWhammy?this.whammyBarType=A.Dive:this.whammyBarType=A.PrediveDive,l.splice(2,1),l.splice(1,1)):t.value>s.value&&s.value<r.value||t.value<s.value&&s.value>r.value?(this.whammyBarType=A.Dip,s.offset!==a.offset&&i!==e.NotationMode.SongBook||l.splice(2,1)):t.value===s.value&&s.value===r.value&&(0===t.value||this.isContinuedWhammy?this.whammyBarType=A.Hold:this.whammyBarType=A.Predive,l.splice(2,1),l.splice(1,1)))}if(this.updateDurations(),n){let e=_e.clone(this);e.id=Be._globalBeatId++,e.pickStroke=F.None;for(let t=0,s=e.notes.length;t<s;t++){let s=e.notes[t],i=this.notes[t];if(s.bendType=c.None,s.maxBendPoint=null,s.bendPoints=null,s.bendStyle=d.Default,s.id=me.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){let e=me.findTieOrigin(i);if(e&&e.hasBend){s.bendType=c.Hold;let e=i.bendPoints[i.bendPoints.length-1];s.addBendPoint(new se(0,e.value)),s.addBendPoint(new se(se.MaxPosition,e.value))}}s.isTieDestination=!0}this.graceType=f.BendGrace,this.graceGroup=new we,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new we,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)}}Be._globalBeatId=0;class Te{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"}(z||(z={}));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=z.Begin,r=z.Begin,n=!1,o=0;for(;t<e.length;){let s=e.charCodeAt(t);switch(a){case z.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 z.Begin:if(s!==ke.CharCodeBrackedOpen){o=t,a=z.Text;continue}a=z.Comment;break;case z.Comment:if(s===ke.CharCodeBrackedClose)a=z.Begin;break;case z.Text:switch(s){case ke.CharCodeDash:a=z.Dash;break;case ke.CharCodeCR:case ke.CharCodeLF:case ke.CharCodeSpace:let s=e.substr(o,t-o);this.addChunk(s,i),a=z.IgnoreSpaces,r=z.Begin}break;case z.Dash:if(s!==ke.CharCodeDash){let s=e.substr(o,t-o);this.addChunk(s,i),n=!0,a=z.IgnoreSpaces,r=z.Begin;continue}}t+=1}a===z.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){let t=e.split("+").join(" "),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,function(e){e[e.NoBrackets=0]="NoBrackets",e[e.GroupStaves=1]="GroupStaves",e[e.GroupSimilarInstruments=2]="GroupSimilarInstruments"}(U||(U={})),function(e){e[e.Hidden=0]="Hidden",e[e.FirstSystem=1]="FirstSystem",e[e.AllSystems=2]="AllSystems"}(X||(X={})),function(e){e[e.FullName=0]="FullName",e[e.ShortName=1]="ShortName"}(J||(J={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical"}(Y||(Y={}));class Ne{constructor(){this.hideDynamics=!1,this.bracketExtendMode=U.GroupStaves,this.useSystemSignSeparator=!1,this.globalDisplayTuning=!0,this.perTrackDisplayTuning=null,this.globalDisplayChordDiagramsOnTop=!0,this.perTrackChordDiagramsOnTop=null,this.singleTrackTrackNamePolicy=X.FirstSystem,this.multiTrackTrackNamePolicy=X.FirstSystem,this.firstSystemTrackNameMode=J.ShortName,this.otherSystemsTrackNameMode=J.ShortName,this.firstSystemTrackNameOrientation=Y.Vertical,this.otherSystemsTrackNameOrientation=Y.Vertical}}class xe{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 ve{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 Ne}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 xe,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new xe,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 Pe{constructor(){this.marker="",this.text=""}}class Ce extends K{constructor(t){super(e.AlphaTabErrorType.Format,t),Object.setPrototypeOf(this,Ce.prototype)}}class Ee{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="#"+de.toHexString(this.r,2)+de.toHexString(this.g,2)+de.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 Ee(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){if(e instanceof Ee)return e;switch(typeof e){case"number":{const t=new Ee(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 Ee(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16));if(5===t.length)return new Ee(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16),17*parseInt(t[4],16));if(7===t.length)return new Ee(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16));if(9===t.length)return new Ee(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16),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 Ce("No values specified for rgb/rgba function");const i=t.substring(e+1,s).split(",");if(3===i.length)return new Ee(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]));if(4===i.length)return new Ee(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]),255*parseFloat(i[3]))}return null}}throw new Ce("Unsupported format for color")}static toJson(e){return e.raw}}Ee.BlackRgb="#000000";class Fe{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 De{static getTextForTuning(e,t){let s=De.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 De._defaultTunings.has(e)?De._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return De._sevenStrings;case 6:return De._sixStrings;case 5:return De._fiveStrings;case 4:return De._fourStrings}return[]}static initialize(){De._defaultTunings.set(7,new De("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),De._sevenStrings.push(De._defaultTunings.get(7)),De._defaultTunings.set(6,new De("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),De._sixStrings.push(De._defaultTunings.get(6)),De._sixStrings.push(new De("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),De._sixStrings.push(new De("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),De._sixStrings.push(new De("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),De._sixStrings.push(new De("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),De._sixStrings.push(new De("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),De._sixStrings.push(new De("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),De._sixStrings.push(new De("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),De._sixStrings.push(new De("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),De._sixStrings.push(new De("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),De._sixStrings.push(new De("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),De._sixStrings.push(new De("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),De._sixStrings.push(new De("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),De._sixStrings.push(new De("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),De._sixStrings.push(new De("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),De._sixStrings.push(new De("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),De._sixStrings.push(new De("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),De._sixStrings.push(new De("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),De._sixStrings.push(new De("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),De._sixStrings.push(new De("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),De._sixStrings.push(new De("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),De._sixStrings.push(new De("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),De._sixStrings.push(new De("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),De._sixStrings.push(new De("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),De._sixStrings.push(new De("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),De._sixStrings.push(new De("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),De._sixStrings.push(new De("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),De._sixStrings.push(new De("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),De._sixStrings.push(new De("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),De._sixStrings.push(new De("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),De._sixStrings.push(new De("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),De._defaultTunings.set(5,new De("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),De._fiveStrings.push(De._defaultTunings.get(5)),De._fiveStrings.push(new De("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),De._fiveStrings.push(new De("Banjo Open D Tuning",[62,57,54,50,69],!1)),De._fiveStrings.push(new De("Banjo Open G Tuning",[62,59,55,50,67],!1)),De._fiveStrings.push(new De("Banjo G Minor Tuning",[62,58,55,50,67],!1)),De._fiveStrings.push(new De("Banjo G Modal Tuning",[62,57,55,50,67],!1)),De._defaultTunings.set(4,new De("Bass Standard Tuning",[43,38,33,28],!0)),De._fourStrings.push(De._defaultTunings.get(4)),De._fourStrings.push(new De("Bass Tune down ½ step",[42,37,32,27],!1)),De._fourStrings.push(new De("Bass Tune down 1 step",[41,36,31,26],!1)),De._fourStrings.push(new De("Bass Tune down 2 step",[39,34,29,24],!1)),De._fourStrings.push(new De("Bass Dropped D Tuning",[43,38,33,26],!1)),De._fourStrings.push(new De("Ukulele C Tuning",[45,40,36,43],!1)),De._fourStrings.push(new De("Ukulele G Tuning",[52,47,43,38],!1)),De._fourStrings.push(new De("Mandolin Standard Tuning",[64,57,50,43],!1)),De._fourStrings.push(new De("Mandolin or Violin Tuning",[76,69,62,55],!1)),De._fourStrings.push(new De("Viola Tuning",[69,62,55,48],!1)),De._fourStrings.push(new De("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){let t=De.getPresetsFor(e.length);for(let s=0,i=t.length;s<i;s++){let i=t[s],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=De.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}De._sevenStrings=[],De._sixStrings=[],De._fiveStrings=[],De._fourStrings=[],De._defaultTunings=new Map,De.defaultAccidentals=["","#","","#","","","#","","#","","#",""],De.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],De.initialize();class Le{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new De("",[],!1),this.showSlash=!1,this.showNumbered=!1,this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=Le.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){let 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)}}Le.DefaultStandardNotationLineCount=5;class Me{constructor(){this.index=0,this.staves=[],this.playbackInfo=new Fe,this.color=new Ee(200,0,0,255),this.name="",this.isVisibleOnMultiTrack=!0,this.shortName="",this.defaultSystemsLayout=3,this.systemsLayout=[],this.percussionArticulations=[]}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new Le)}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>Me.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,Me.ShortNameMaxLength)));for(let s=0,i=this.staves.length;s<i;s++)this.staves[s].finish(e,t)}applyLyrics(e){for(let t of e)t.finish();let t=this.staves[0];for(let s=0;s<e.length;s++){let 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)}}}}}Me.ShortNameMaxLength=10;let Ie=class e{constructor(){this.id=e._globalBarId++,this.index=0,this.beats=[],this.isEmpty=!0}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)}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){let 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);let t=this.beats[this.beats.length-1];this.beats.splice(this.beats.length-1,1),this.addBeat(e),this.addBeat(t),this.isEmpty=!1}getBeatAtPlaybackStart(e){return this._beatLookup.has(e)?this._beatLookup.get(e):null}finish(e,t=null){this._beatLookup=new Map;let s=null;for(let e=0;e<this.beats.length;e++){let i=this.beats[e];i.index=e,this.chain(i,t),i.graceType===f.None?(i.graceGroup=s,s&&(s.isComplete=!0),s=null):(s||(s=new we),s.addBeat(i))}let i=0,a=0;for(let s=0;s<this.beats.length;s++){let r=this.beats[s];if(r.index=s,r.finish(e,t),r.graceType===f.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==f.BendGrace){let s=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case f.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 f.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;let e=this.beats[this.beats.length-1],t=this.beats[0];return e.playbackStart+e.playbackDuration-t.playbackStart}};Ie._globalBarId=0;class Ae{static float64ToBytes(e){return Ae._dataView.setFloat64(0,e,!0),this._conversionByteArray}static bytesToInt64LE(e){Ae._conversionByteArray.set(e,0);const t=Ae._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 Ae._conversionByteArray.set(e,0),Ae._dataView.getFloat64(0,!0)}static bytesToFloat32LE(e){return Ae._conversionByteArray.set(e,0),Ae._dataView.getFloat32(0,!0)}static float32BEToBytes(e){return Ae._dataView.setFloat32(0,e,!1),Ae._conversionByteArray.slice(0,4)}static uint16ToInt16(e){return Ae._dataView.setUint16(0,e,!0),Ae._dataView.getInt16(0,!0)}static int16ToUint32(e){return Ae._dataView.setInt16(0,e,!0),Ae._dataView.getUint32(0,!0)}static int32ToUint16(e){return Ae._dataView.setInt32(0,e,!0),Ae._dataView.getUint16(0,!0)}static int32ToInt16(e){return Ae._dataView.setInt32(0,e,!0),Ae._dataView.getInt16(0,!0)}static int32ToUint32(e){return Ae._dataView.setInt32(0,e,!0),Ae._dataView.getUint32(0,!0)}static uint8ToInt8(e){return Ae._dataView.setUint8(0,e),Ae._dataView.getInt8(0)}}Ae._conversionBuffer=new ArrayBuffer(8),Ae._conversionByteArray=new Uint8Array(Ae._conversionBuffer),Ae._dataView=new DataView(Ae._conversionBuffer);class Re{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(),Ae.bytesToFloat32LE(t)}static readFloat64BE(e){const t=new Uint8Array(8);return e.read(t,0,t.length),t.reverse(),Ae.bytesToFloat64LE(t)}static readInt32LE(e){let 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),Ae.bytesToInt64LE(t)}static readUInt32LE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static decodeUInt32LE(e,t){let s=e[t],i=e[t+1],a=e[t+2];return e[t+3]<<24|a<<16|i<<8|s}static readUInt16LE(e){let t=e.readByte(),s=e.readByte();return Ae.int32ToUint16(s<<8|t)}static readInt16LE(e){let t=e.readByte(),s=e.readByte();return Ae.int32ToInt16(s<<8|t)}static readUInt32BE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte(),a=e.readByte();return Ae.int32ToUint32(t<<24|s<<16|i<<8|a)}static readUInt16BE(e){let t=e.readByte(),s=e.readByte();return Ae.int32ToInt16(t<<8|s)}static readInt16BE(e){let t=e.readByte(),s=e.readByte();return Ae.int32ToInt16(t<<8|s)}static readByteArray(e,t){let s=new Uint8Array(t);return e.read(s,0,t),s}static read8BitChars(e,t){let s=new Uint8Array(t);return e.read(s,0,s.length),Re.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++){let t=e.readByte();0===t&&-1===i&&(i=a),s+=String.fromCharCode(t)}let a=s;return i>=0?a.substr(0,i):a}static readSInt8(e){let 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 Ae.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){let s=Re.detectEncoding(e);return s&&(t=s),t||(t="utf-8"),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=Ae.float32BEToBytes(t);e.write(s,0,s.length)}}class Oe{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return Oe.withCapacity(0)}static withCapacity(e){let t=new Oe;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){let t=new Oe;return t._buffer=e,t.length=e.length,t}static fromString(e){let t=Re.stringToBytes(e);return Oe.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){let 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){let i=this.position+s;this.ensureCapacity(i);let 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);let 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(){let 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)}}class Ve{}var He,Ge,We,ze,Ue,Xe,Je,Ye,qe,je,Ke,Qe,$e,Ze;Ve.DefaultChannelCount=17,Ve.MetronomeChannel=Ve.DefaultChannelCount-1,Ve.MetronomeKey=33,Ve.AudioChannels=2,Ve.MinVolume=0,Ve.MinProgram=0,Ve.MaxProgram=127,Ve.MinPlaybackSpeed=.125,Ve.MaxPlaybackSpeed=8,Ve.PercussionChannel=9,Ve.PercussionBank=128,Ve.MaxPitchWheel=16384,Ve.MaxPitchWheel20=4294967296,Ve.DefaultPitchWheel=Ve.MaxPitchWheel/2,Ve.MicroBufferCount=32,Ve.MicroBufferSize=64,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"}(He||(He={})),function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(Ge||(Ge={}));class et{constructor(){this.type=Ge.Short,this.length=0}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(We||(We={})),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"}(ze||(ze={})),function(e){e[e.KnownStaffMeta=0]="KnownStaffMeta",e[e.UnknownStaffMeta=1]="UnknownStaffMeta",e[e.EndOfMetaDetected=2]="EndOfMetaDetected"}(Ue||(Ue={}));class tt extends K{constructor(t,s,i,a,r,n,o,h=null){super(e.AlphaTabErrorType.AlphaTex,t),this.position=s,this.line=i,this.col=a,this.nonTerm=r??"",this.expected=n??ze.No,this.symbol=o??ze.No,this.symbolData=h,Object.setPrototypeOf(this,tt.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 ${ze[a]} found a ${ze[r]}`,null!==n&&(o+=`: '${n}'`)):o+=`, invalid value: '${n}'`,new tt(o,e,t,s,i,a,r,n)}static errorMessage(e,t,s,i){return new tt(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"}(Xe||(Xe={}));class st extends j{constructor(){super(),this._trackChannel=0,this._barIndex=0,this._voiceIndex=0,this._input="",this._ch=st.Eof,this._curChPos=0,this._line=1,this._col=0,this._lastValidSpot=[0,1,0],this._sy=ze.No,this._syData="",this._allowNegatives=!1,this._allowFloat=!1,this._allowTuning=!1,this._currentDuration=g.QuadrupleWhole,this._currentDynamics=m.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._accidentalMode=Xe.Explicit,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=Oe.empty(),this._input=e,this.settings=t}readScore(){try{if(this.data.length>0&&(this._input=Re.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=g.Quarter,this._currentDynamics=m.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===ze.LowerThan)throw new Q("Unknown start sign '<' (meant to import as XML?)");if(this._sy!==ze.Eof){const e=this.metaData(),t=this.bars();if(!e&&!t)throw new Q("No alphaTex data found")}this.consolidate(),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)if(0===e.ratioPosition){const s=t.voice.bar.masterBar.calculateDuration();e.ratioPosition=t.playbackStart/s}return this._score}catch(e){throw e instanceof tt?new Q(e.message,e):e}}consolidate(){if(0===this._score.masterBars.length){const e=new oe;this._score.addMasterBar(e);const t=new $;t.isLinear=!1,t.type=r.Tempo,t.value=this._score.tempo,e.tempoAutomations.push(t);const s=new ee;this._score.tracks[0].staves[0].addBar(s);const i=new Ie;s.addVoice(i);const a=new Be;return a.isEmpty=!0,void i.addBeat(a)}for(let e of this._score.tracks)for(let t of e.staves){for(const e of t.bars)for(const t of e.voices)if(t.isEmpty&&0==t.beats.length){const e=new Be;e.isEmpty=!0,t.addBeat(e)}const e=0===t.bars.length?1:t.bars[0].voices.length;for(;t.bars.length<this._score.masterBars.length;){const s=new ee;t.addBar(s);for(let t=0;t<e;t++){const e=new Ie;s.addVoice(e);const t=new Be;t.isEmpty=!0,e.addBeat(t)}}}}error(e,t,s=!0){let i,a=!1;s?(i=this._sy,i!==ze.String&&i!==ze.Number&&i!==ze.MetaCommand||(a=!0)):i=t;let r=tt.symbolError(this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2],e,t,i,a?this._syData:null);throw this.logErrors&&ne.error(this.name,r.message),r}errorMessage(e){let t=tt.errorMessage(e,this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2]);throw this.logErrors&&ne.error(this.name,t.message),t}createDefaultScore(){this._score=new ve,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new Me,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=De.getDefaultTuningFor(6).tunings,this.beginStaff(e),this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=m.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 E.NoTripletFeel;case"t16":case"triplet-16th":return E.Triplet16th;case"t8":case"triplet-8th":return E.Triplet8th;case"d16":case"dotted-16th":return E.Dotted16th;case"d8":case"dotted-8th":return E.Dotted8th;case"s16":case"scottish-16th":return E.Scottish16th;case"s8":case"scottish-8th":return E.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return E.NoTripletFeel;case 1:return E.Triplet16th;case 2:return E.Triplet8th;case 3:return E.Dotted16th;case 4:return E.Dotted8th;case 5:return E.Scottish16th;case 6:return E.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":case"abminor":return P.Cb;case"gb":case"gbmajor":case"ebminor":return P.Gb;case"db":case"dbmajor":case"bbminor":return P.Db;case"ab":case"abmajor":case"fminor":return P.Ab;case"eb":case"ebmajor":case"cminor":return P.Eb;case"bb":case"bbmajor":case"gminor":return P.Bb;case"f":case"fmajor":case"dminor":return P.F;case"c":case"cmajor":case"aminor":default:return P.C;case"g":case"gmajor":case"eminor":return P.G;case"d":case"dmajor":case"bminor":return P.D;case"a":case"amajor":case"f#minor":return P.A;case"e":case"emajor":case"c#minor":return P.E;case"b":case"bmajor":case"g#minor":return P.B;case"f#":case"f#major":case"d#minor":return P.FSharp;case"c#":case"c#major":case"a#minor":return P.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=st.Eof,this._ch}saveValidSpot(){this._lastValidSpot=[this._curChPos,this._line,this._col]}newSy(){for(this.saveValidSpot(),this._sy=ze.No;this._sy===ze.No;)if(this._ch===st.Eof)this._sy=ze.Eof;else if(st.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!==st.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;this._ch!==st.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",ze.String,!1);this.saveValidSpot()}else if(34===this._ch||39===this._ch){let e=this._ch;this._ch=this.nextChar();let t="";for(this._sy=ze.String;this._ch!==e&&this._ch!==st.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===st.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=ze.String,this._syData=this.readName());else if(46===this._ch)this._sy=ze.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=ze.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=ze.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=ze.MetaCommand,92===this._ch&&(this._ch=this.nextChar()),this._syData=this.readName();else if(41===this._ch)this._sy=ze.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=ze.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=ze.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=ze.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=ze.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=ze.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this.readNumberOrName();else if(st.isNameLetter(this._ch)){let e=this.readName(),t=this._allowTuning?de.parseTuning(e):null;t?(this._sy=ze.Tuning,this._syData=t):(this._sy=ze.String,this._syData=e)}else this.error("symbol",ze.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)||st.isNameLetter(this._ch));t?(this._sy=ze.Number,this._syData=this._allowFloat?parseFloat(e):parseInt(e)):(this._sy=ze.String,this._syData=e)}static isNameLetter(e){return!st.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(st.isNameLetter(this._ch)||this.isDigit(this._ch));return e}metaData(){let e=!1,t=!1,s=!0;for(;this._sy===ze.MetaCommand&&s;){let 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!==ze.String&&this.error(i,ze.String,!0);let a=this._syData;switch(i){case"title":this._score.title=a;break;case"subtitle":this._score.subTitle=a;break;case"artist":this._score.artist=a;break;case"album":this._score.album=a;break;case"words":this._score.words=a;break;case"music":this._score.music=a;break;case"copyright":this._score.copyright=a;break;case"instructions":this._score.instructions=a;break;case"notices":this._score.notices=a;break;case"tab":this._score.tab=a}this._sy=this.newSy(),e=!0;break;case"tempo":this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy===ze.Number?this._score.tempo=this._syData:this.error("tempo",ze.Number,!0),this._sy=this.newSy(),this._sy===ze.String&&(this._score.tempoLabel=this._syData,this._sy=this.newSy()),e=!0;break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===ze.Number?(this._score.defaultSystemsLayout=this._syData,this._sy=this.newSy(),e=!0):this.error("default-systems-layout",ze.Number,!0);break;case"systemslayout":for(this._sy=this.newSy(),e=!0;this._sy===ze.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!==ze.String&&this.error("bracketExtendMode",ze.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"singletracktracknamepolicy":this._sy=this.newSy(),this._sy!==ze.String&&this.error("singleTrackTrackNamePolicy",ze.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!==ze.String&&this.error("multiTrackTrackNamePolicy",ze.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!==ze.String&&this.error("firstSystemTrackNameMode",ze.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!==ze.String&&this.error("otherSystemsTrackNameMode",ze.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!==ze.String&&this.error("firstSystemTrackNameOrientation",ze.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!==ze.String&&this.error("otherSystemsTrackNameOrientation",ze.String,!0),this._score.stylesheet.otherSystemsTrackNameOrientation=this.parseTrackNameOrientation(this._syData),this._sy=this.newSy(),e=!0;break;default:switch(this.handleStaffMeta()){case Ue.KnownStaffMeta:t=!0;break;case Ue.UnknownStaffMeta:e||t?this.error("metaDataTags",ze.String,!1):s=!1;break;case Ue.EndOfMetaDetected:s=!1}}}return e?(this._sy!==ze.Dot&&this.error("song",ze.Dot,!0),this._sy=this.newSy()):this._sy===ze.Dot&&(this._sy=this.newSy(),e=!0),e||t}parseTrackNamePolicy(e){switch(e.toLowerCase()){case"hidden":return X.Hidden;case"allsystems":return X.AllSystems;default:return X.FirstSystem}}parseTrackNameMode(e){return"fullname"===e.toLowerCase()?J.FullName:J.ShortName}parseTrackNameOrientation(e){return"horizontal"===e.toLowerCase()?Y.Horizontal:Y.Vertical}handleStaffMeta(){switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===ze.Number?this._currentStaff.capo=this._syData:this.error("capo",ze.Number,!0),this._sy=this.newSy(),Ue.KnownStaffMeta;case"tuning":this._sy=this.newSy();let e=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case ze.String:let e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?this.makeCurrentStaffPitched():this.error("tuning",ze.Tuning,!0),this._sy=this.newSy();break;case ze.Tuning:let t=[];do{let e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===ze.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",ze.Tuning,!0)}return this._sy===ze.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"),Ue.KnownStaffMeta;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===ze.Number){let e=this._syData;e>=0&&e<=127?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",ze.Number,!1)}else if(this._sy===ze.String){let e=this._syData.toLowerCase();if("percussion"===e){for(const e of this._currentTrack.staves)this.applyPercussionStaff(e);this._currentTrack.playbackInfo.primaryChannel=Ve.PercussionChannel,this._currentTrack.playbackInfo.secondaryChannel=Ve.PercussionChannel}else this._currentTrack.playbackInfo.program=q.getValue(e)}else this.error("instrument",ze.Number,!0);return this._sy=this.newSy(),Ue.KnownStaffMeta;case"lyrics":this._sy=this.newSy();let t=new ke;return t.startBar=0,t.text="",this._sy===ze.Number&&(t.startBar=this._syData,this._sy=this.newSy()),this._sy===ze.String?(t.text=this._syData,this._sy=this.newSy()):this.error("lyrics",ze.String,!0),this._lyrics.get(this._currentTrack.index).push(t),Ue.KnownStaffMeta;case"chord":this._sy=this.newSy();let s=new Te;this.chordProperties(s),this._sy===ze.String?(s.name=this._syData,this._sy=this.newSy()):this.error("chord-name",ze.String,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===ze.Number?s.strings.push(this._syData):this._sy===ze.String&&"x"===this._syData.toLowerCase()&&s.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,s.name),s),Ue.KnownStaffMeta;case"articulation":this._sy=this.newSy();let i="";if(this._sy===ze.String?(i=this._syData,this._sy=this.newSy()):this.error("articulation-name",ze.String,!0),"defaults"===i){for(const[e,t]of pe.instrumentArticulationNames)this._percussionArticulationNames.set(e.toLowerCase(),t),this._percussionArticulationNames.set(st.toArticulationId(e),t);return Ue.KnownStaffMeta}let a=0;return this._sy===ze.Number?(a=this._syData,this._sy=this.newSy()):this.error("articulation-number",ze.Number,!0),pe.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),Ue.KnownStaffMeta;case"accidentals":return this.handleAccidentalMode(),Ue.KnownStaffMeta;case"displaytranspose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===ze.Number?(this._currentStaff.displayTranspositionPitch=-1*this._syData,this._staffHasExplicitDisplayTransposition=!0):this.error("displaytranspose",ze.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),Ue.KnownStaffMeta;case"transpose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===ze.Number?this._currentStaff.transpositionPitch=-1*this._syData:this.error("transpose",ze.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),Ue.KnownStaffMeta;case"track":case"staff":return Ue.EndOfMetaDetected;case"voice":return this._sy=this.newSy(),this.handleNewVoice()?Ue.EndOfMetaDetected:Ue.KnownStaffMeta;default:return Ue.UnknownStaffMeta}}handleAccidentalMode(){switch(this._sy=this.newSy(),this._sy!==ze.String&&this.error("accidental-mode",ze.String,!0),this._syData){case"auto":this._accidentalMode=Xe.Auto;break;case"explicit":this._accidentalMode=Xe.Explicit}this._sy=this.newSy()}makeCurrentStaffPitched(){this._currentStaff.stringTuning.tunings=[],this._staffHasExplicitDisplayTransposition||(this._currentStaff.displayTranspositionPitch=0)}static toArticulationId(e){return e.replace(new RegExp("[^a-zA-Z0-9]","g"),"").toLowerCase()}applyPercussionStaff(e){e.isPercussion=!0,e.showTablature=!1}chordProperties(e){if(this._sy===ze.LBrace){for(this._sy=this.newSy();this._sy===ze.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===ze.Number)e.firstFret=this._syData;else this.error("chord-firstfret",ze.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case ze.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case ze.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",ze.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case ze.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case ze.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",ze.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case ze.String:e.showName="false"!==this._syData.toLowerCase();break;case ze.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",ze.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===ze.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",ze.String,!1)}this._sy!==ze.RBrace&&this.error("chord-properties",ze.RBrace,!0),this._sy=this.newSy()}}bars(){let e=this.bar();for(;this._sy!==ze.Eof;)if(this._sy===ze.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==ze.MetaCommand)break;this.bar()}return e}trackStaffMeta(){if(this._sy!==ze.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===ze.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===ze.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy()),this.trackProperties()),this._sy===ze.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=m.F}this.staffProperties()}return this._sy===ze.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 Ie;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===ze.LBrace){for(this._sy=this.newSy();this._sy===ze.String;)switch(this._syData.toLowerCase()){case"color":this._sy=this.newSy(),this._sy!==ze.String&&this.error("track-color",ze.String,!0),this._currentTrack.color=Ee.fromJson(this._syData),this._sy=this.newSy();break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===ze.Number?(this._currentTrack.defaultSystemsLayout=this._syData,this._sy=this.newSy()):this.error("default-systems-layout",ze.Number,!0);break;case"systemslayout":for(this._sy=this.newSy();this._sy===ze.Number;)this._currentTrack.systemsLayout.push(this._syData),this._sy=this.newSy();break;case"volume":this._sy=this.newSy(),this._sy!==ze.Number&&this.error("track-volume",ze.Number,!0),this._currentTrack.playbackInfo.volume=de.clamp(this._syData,0,16),this._sy=this.newSy();break;case"balance":this._sy=this.newSy(),this._sy!==ze.Number&&this.error("track-balance",ze.Number,!0),this._currentTrack.playbackInfo.balance=de.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;default:this.error("track-properties",ze.String,!1)}this._sy!==ze.RBrace&&this.error("track-properties",ze.RBrace,!0),this._sy=this.newSy()}}staffProperties(){if(this._sy!==ze.LBrace)return;this._sy=this.newSy();let e=!1,t=!1,s=!1,i=!1;for(;this._sy===ze.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy(),this._sy===ze.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",ze.String,!1)}(e||t||s||i)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t,this._currentStaff.showSlash=s,this._currentStaff.showNumbered=i),this._sy!==ze.RBrace&&this.error("staff-properties",ze.RBrace,!0),this._sy=this.newSy()}bar(){const e=this.trackStaffMeta();let t=this.newBar(this._currentStaff);if(this._currentStaff.bars.length>this._score.masterBars.length){let e=new oe;this._score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,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=De.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,r=t.voices[this._voiceIndex];if(!(this._sy===ze.MetaCommand&&("track"===this._syData.toLowerCase()||"staff"===this._syData.toLowerCase())))for(;this._sy!==ze.Pipe&&this._sy!==ze.Eof&&this.beat(r);)a=!0;if(0===r.beats.length){let e=new Be;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 ee;e.addBar(s),s.previousBar&&(s.clef=s.previousBar.clef,s.clefOttava=s.previousBar.clefOttava),this._barIndex++;for(let e=0;e<t;e++){let e=new Ie;s.addVoice(e)}return s}beat(e){this.beatDuration();let t=new Be;if(e.addBeat(t),this._allowTuning=!this._currentStaff.isPercussion,this._sy===ze.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==ze.RParensis&&this._sy!==ze.Eof&&(this._allowTuning=!this._currentStaff.isPercussion,this.note(t)););this._sy!==ze.RParensis&&this.error("note-list",ze.RParensis,!0),this._sy=this.newSy()}else if(this._sy===ze.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===ze.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==ze.Number&&this.error("duration",ze.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||st.applyTuplet(t,this._currentTuplet);let s=1;this._sy===ze.Multiply&&(this._sy=this.newSy(),this._sy!==ze.Number?this.error("multiplier",ze.Number,!0):s=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let i=0;i<s-1;i++)e.addBeat(_e.clone(t));return!0}beatDuration(){if(this._sy===ze.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==ze.Number&&this.error("duration",ze.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===ze.LBrace)){for(this._sy=this.newSy();this._sy===ze.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==ze.Number&&this.error("duration-tuplet",ze.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",ze.String,!1)}this._sy!==ze.RBrace&&this.error("beat-duration",ze.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===ze.LBrace){for(this._sy=this.newSy();this._sy===ze.String;)this.applyBeatEffect(e)||this.error("beat-effects",ze.String,!1);this._sy!==ze.RBrace&&this.error("beat-effects",ze.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){let t=this._syData.toLowerCase();if("f"===t)e.fade=O.FadeIn;else if("fo"===t)e.fade=O.FadeOut;else if("vs"===t)e.fade=O.VolumeSwell;else if("v"===t)e.vibrato=B.Slight;else if("vw"===t)e.vibrato=B.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!==ze.String)return this.error("beat-text",ze.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=F.Up;else if("sd"===t)e.pickStroke=F.Down;else{if("tu"===t){if(this._sy=this.newSy(),this._sy!==ze.Number)return this.error("tuplet",ze.Number,!0),!1;const t=this._syData;if(this._sy=this.newSy(),this._sy===ze.Number){const s=this._syData;this._sy=this.newSy(),e.tupletNumerator=t,e.tupletDenominator=s}else st.applyTuplet(e,t);return!0}if("tb"===t||"tbe"===t){this._sy=this.newSy();let s="tbe"===t;for(this._sy===ze.String&&(e.whammyBarType=this.parseWhammyType(this._syData),this._sy=this.newSy()),this._sy===ze.String&&(e.whammyStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==ze.LParensis&&this.error("tremolobar-effect",ze.LParensis,!0),this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy();this._sy!==ze.RParensis&&this._sy!==ze.Eof;){let t=0,i=0;s?(this._sy!==ze.Number&&this.error("tremolobar-effect",ze.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==ze.Number&&this.error("tremolobar-effect",ze.Number,!0),i=this._syData):(this._sy!==ze.Number&&this.error("tremolobar-effect",ze.Number,!0),t=0,i=this._syData),e.addWhammyBarPoint(new se(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{let t=e.whammyBarPoints.length,s=60/t|0,i=0;for(;i<t;)e.whammyBarPoints[i].offset=Math.min(60,i*s),i++}}this._allowNegatives=!1,this._allowFloat=!1,this._sy!==ze.RParensis&&this.error("tremolobar-effect",ze.RParensis,!0)}else{if("bu"===t||"bd"===t||"au"===t||"ad"===t){switch(t){case"bu":e.brushType=u.BrushUp;break;case"bd":e.brushType=u.BrushDown;break;case"au":e.brushType=u.ArpeggioUp;break;case"ad":e.brushType=u.ArpeggioDown}return this._sy=this.newSy(),this._sy===ze.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();let t=this._syData,s=this.getChordId(this._currentStaff,t);if(!this._currentStaff.hasChord(s)){let e=new Te;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=f.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=f.BendGrace,this._sy=this.newSy()):e.graceType=f.BeforeBeat,!0;if("dy"===t){switch(this._sy=this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=m.PPP;break;case"pp":e.dynamics=m.PP;break;case"p":e.dynamics=m.P;break;case"mp":e.dynamics=m.MP;break;case"mf":e.dynamics=m.MF;break;case"f":e.dynamics=m.F;break;case"ff":e.dynamics=m.FF;break;case"fff":e.dynamics=m.FFF}this._currentDynamics=e.dynamics}else if("cre"===t)e.crescendo=p.Crescendo;else if("dec"===t)e.crescendo=p.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=g.Eighth,this._sy===ze.Number){switch(this._syData){case 8:default:e.tremoloSpeed=g.Eighth;break;case 16:e.tremoloSpeed=g.Sixteenth;break;case 32:e.tremoloSpeed=g.ThirtySecond}this._sy=this.newSy()}return!0}if("spd"===t){const t=new Z;return t.pedalType=l.Down,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spu"===t){const t=new Z;return t.pedalType=l.Up,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spe"===t){const t=new Z;return t.pedalType=l.Up,t.ratioPosition=1,this._sustainPedalToBeat.set(t,e),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=R.Finger,!0;if("glpt"===t)return this._sy=this.newSy(),e.golpe=R.Thumb,!0;if("waho"===t)return this._sy=this.newSy(),e.wahPedal=V.Open,!0;if("wahc"===t)return this._sy=this.newSy(),e.wahPedal=V.Closed,!0;if("barre"===t){if(this._sy=this.newSy(),this._sy!==ze.Number&&this.error("beat-barre",ze.Number,!0),e.barreFret=this._syData,e.barreShape=H.Full,this._sy=this.newSy(),this._sy===ze.String)switch(this._syData.toLowerCase()){case"full":e.barreShape=H.Full,this._sy=this.newSy();break;case"half":e.barreShape=H.Half,this._sy=this.newSy()}return!0}if("rasg"===t){switch(this._sy=this.newSy(),this._sy!==ze.String&&this.error("rasgueado",ze.String,!0),this._syData.toLowerCase()){case"ii":e.rasgueado=G.Ii;break;case"mi":e.rasgueado=G.Mi;break;case"miitriplet":e.rasgueado=G.MiiTriplet;break;case"miianapaest":e.rasgueado=G.MiiAnapaest;break;case"pmptriplet":e.rasgueado=G.PmpTriplet;break;case"pmpanapaest":e.rasgueado=G.PmpAnapaest;break;case"peitriplet":e.rasgueado=G.PeiTriplet;break;case"peianapaest":e.rasgueado=G.PeiAnapaest;break;case"paitriplet":e.rasgueado=G.PaiTriplet;break;case"paianapaest":e.rasgueado=G.PaiAnapaest;break;case"amitriplet":e.rasgueado=G.AmiTriplet;break;case"amianapaest":e.rasgueado=G.AmiAnapaest;break;case"ppp":e.rasgueado=G.Ppp;break;case"amii":e.rasgueado=G.Amii;break;case"amip":e.rasgueado=G.Amip;break;case"eami":e.rasgueado=G.Eami;break;case"eamii":e.rasgueado=G.Eamii;break;case"peami":e.rasgueado=G.Peami}return this._sy=this.newSy(),!0}if("ot"===t)this._sy=this.newSy(),this._sy!==ze.String&&this.error("beat-ottava",ze.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!==ze.String&&this.error("fermata",ze.Number,!0);const t=new et;return t.type=this.parseFermataFromString(this._syData),this._allowFloat=!0,this._sy=this.newSy(),this._sy===ze.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!==ze.String&&this.error("beam",ze.Number,!0),this._syData.toLowerCase()){case"invert":e.invertBeamDirection=!0;break;case"up":e.preferredBeamDirection=We.Up;break;case"down":e.preferredBeamDirection=We.Down;break;case"auto":e.beamingMode=W.Auto;break;case"split":e.beamingMode=W.ForceSplitToNext;break;case"merge":e.beamingMode=W.ForceMergeWithNext;break;case"splitsecondary":e.beamingMode=W.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===ze.Number?t=this._syData:this._sy===ze.String?t=q.getValue(this._syData):this.error("instrument-change",ze.Number,!0);const s=new $;s.isLinear=!1,s.type=r.Instrument,s.value=t,e.automations.push(s)}}}}}}return this._sy=this.newSy(),!0}parseBracketExtendMode(e){switch(e.toLowerCase()){case"nobrackets":return U.NoBrackets;case"groupstaves":default:return U.GroupStaves;case"groupsimilarinstruments":return U.GroupSimilarInstruments}}parseFermataFromString(e){switch(e.toLowerCase()){case"short":return Ge.Short;case"medium":default:return Ge.Medium;case"long":return Ge.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=S.Default;switch(this._sy){case ze.Number:i=this._syData,this._currentStaff.isPercussion&&!pe.instrumentArticulations.has(i)&&this.errorMessage(`Unknown percussion articulation ${i}`);break;case ze.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",ze.Number,!0);break;case ze.Tuning:0===e.index&&0===e.voice.index&&0===e.voice.bar.index&&this.makeCurrentStaffPitched();let o=this._syData;a=o.octave,r=o.tone.noteValue,this._accidentalMode==Xe.Explicit&&(n=o.tone.accidentalMode);break;default:return!1}this._sy=this.newSy();let o=-1===a&&this._currentStaff.tuning.length>0&&!this._currentStaff.isPercussion,h=-1;o&&(this._sy!==ze.Dot&&this.error("note",ze.Dot,!0),this._sy=this.newSy(),this._sy!==ze.Number&&this.error("note-string",ze.Number,!0),h=this._syData,(h<1||h>this._currentStaff.tuning.length)&&this.error("note-string",ze.Number,!1),this._sy=this.newSy());let l=new me;return o?(l.string=this._currentStaff.tuning.length-(h-1),l.isDead=t,l.isTieDestination=s,s||(l.fret=i)):this._currentStaff.isPercussion?l.percussionArticulation=i:(l.octave=a,l.tone=r,l.accidentalMode=n,l.isTieDestination=s),e.addNote(l),this.noteEffects(l),!0}noteEffects(e){if(this._sy===ze.LBrace){for(this._sy=this.newSy();this._sy===ze.String;){let t=this._syData.toLowerCase();if("b"===t||"be"===t){this._sy=this.newSy();let s="be"===t;for(this._sy===ze.String&&(e.bendType=this.parseBendType(this._syData),this._sy=this.newSy()),this._sy===ze.String&&(e.bendStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==ze.LParensis&&this.error("bend-effect",ze.LParensis,!0),this._sy=this.newSy();this._sy!==ze.RParensis&&this._sy!==ze.Eof;){let t=0,i=0;s?(this._sy!==ze.Number&&this.error("bend-effect-value",ze.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==ze.Number&&this.error("bend-effect-value",ze.Number,!0),i=this._syData):(this._sy!==ze.Number&&this.error("bend-effect-value",ze.Number,!0),i=this._syData),e.addBendPoint(new se(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{let e=i.length,t=60/(e-1)|0,s=0;for(;s<e;)i[s].offset=Math.min(60,s*t),s++}}this._sy!==ze.RParensis&&this.error("bend-effect",ze.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=b.Natural,e.harmonicValue=de.deltaFretToHarmonicValue(e.fret),this._sy=this.newSy();else if("ah"===t)e.harmonicType=b.Artificial,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("th"===t)e.harmonicType=b.Tap,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("ph"===t)e.harmonicType=b.Pinch,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("sh"===t)e.harmonicType=b.Semi,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("fh"===t)e.harmonicType=b.Feedback,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("tr"===t){this._sy=this.newSy(),this._sy!==ze.Number&&this.error("trill-effect",ze.Number,!0);let t=this._syData;this._sy=this.newSy();let s=g.Sixteenth;if(this._sy===ze.Number){switch(this._syData){case 16:default:s=g.Sixteenth;break;case 32:s=g.ThirtySecond;break;case 64:s=g.SixtyFourth}this._sy=this.newSy()}e.trillValue=t+e.stringTuning,e.trillSpeed=s}else if("v"===t)this._sy=this.newSy(),e.vibrato=B.Slight;else if("sl"===t)this._sy=this.newSy(),e.slideOutType=w.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=w.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=_.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=_.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=w.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=w.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=w.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=w.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=a.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=a.Heavy;else if("ten"===t)this._sy=this.newSy(),e.accentuated=a.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=y.Thumb;this._sy===ze.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.leftHandFinger=t}else if("rf"===t){this._sy=this.newSy();let t=y.Thumb;this._sy===ze.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else if("acc"===t)this._sy=this.newSy(),this._sy!==ze.String&&this.error("note-accidental",ze.String,!0),e.accidentalMode=de.parseAccidentalMode(this._syData),this._sy=this.newSy();else if("turn"===t)this._sy=this.newSy(),e.ornament=I.Turn;else if("iturn"===t)this._sy=this.newSy(),e.ornament=I.InvertedTurn;else if("umordent"===t)this._sy=this.newSy(),e.ornament=I.UpperMordent;else if("lmordent"===t)this._sy=this.newSy(),e.ornament=I.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!==ze.String&&this.error("slur",ze.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,ze.String,!1)}this._sy!==ze.RBrace&&this.error("note-effect",ze.RBrace,!1),this._sy=this.newSy()}}harmonicValue(e){return this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy(),this._sy===ze.Number&&(e=this._syData,this._sy=this.newSy()),this._allowNegatives=!1,this._allowFloat=!1,e}toFinger(e){switch(e){case 1:return y.Thumb;case 2:return y.IndexFinger;case 3:return y.MiddleFinger;case 4:return y.AnnularFinger;case 5:return y.LittleFinger}return y.Thumb}parseDuration(e){switch(e){case-4:return g.QuadrupleWhole;case-2:return g.DoubleWhole;case 1:return g.Whole;case 2:return g.Half;case 4:return g.Quarter;case 8:return g.Eighth;case 16:return g.Sixteenth;case 32:return g.ThirtySecond;case 64:return g.SixtyFourth;case 128:return g.OneHundredTwentyEighth;case 256:return g.TwoHundredFiftySixth;default:return g.Quarter}}parseBendStyle(e){switch(e.toLowerCase()){case"gradual":return d.Gradual;case"fast":return d.Fast;default:return d.Default}}parseBendType(e){switch(e.toLowerCase()){case"none":return c.None;case"custom":default:return c.Custom;case"bend":return c.Bend;case"release":return c.Release;case"bendrelease":return c.BendRelease;case"hold":return c.Hold;case"prebend":return c.Prebend;case"prebendbend":return c.PrebendBend;case"prebendrelease":return c.PrebendRelease}}barMeta(e){let t=!1,s=e.masterBar,i=!1;for(;!i&&this._sy===ze.MetaCommand;){t=!0;let a=this._syData.toLowerCase();if("ts"===a)this._sy=this.newSy(),this._sy===ze.String?"common"===this._syData.toLowerCase()?(s.timeSignatureCommon=!0,s.timeSignatureNumerator=4,s.timeSignatureDenominator=4,this._sy=this.newSy()):this.error("timesignature-numerator",ze.String,!0):(this._sy!==ze.Number&&this.error("timesignature-numerator",ze.Number,!0),s.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==ze.Number&&this.error("timesignature-denominator",ze.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!==ze.Number&&this.error("repeatclose",ze.Number,!0),this._syData>2048&&this.error("repeatclose",ze.Number,!1),s.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===a)if(this._sy=this.newSy(),this._sy===ze.LParensis){for(this._sy=this.newSy(),this._sy!==ze.Number&&this.error("alternateending",ze.Number,!0),this.applyAlternateEnding(s);this._sy===ze.Number;)this.applyAlternateEnding(s);this._sy!==ze.RParensis&&this.error("alternateending-list",ze.RParensis,!0),this._sy=this.newSy()}else this._sy!==ze.Number&&this.error("alternateending",ze.Number,!0),this.applyAlternateEnding(s);else if("ks"===a)this._sy=this.newSy(),this._sy!==ze.String&&this.error("keysignature",ze.String,!0),s.keySignature=this.parseKeySignature(this._syData),s.keySignatureType=this.parseKeySignatureType(this._syData),this._sy=this.newSy();else if("clef"===a){switch(this._sy=this.newSy(),this._sy){case ze.String:e.clef=this.parseClefFromString(this._syData);break;case ze.Number:e.clef=this.parseClefFromInt(this._syData);break;case ze.Tuning:let t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",ze.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!==ze.String&&this.error("section",ze.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==ze.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());let i=new Pe;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 ze.String:s.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case ze.Number:s.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",ze.String,!0)}this._sy=this.newSy()}else if("ac"===a)s.isAnacrusis=!0,this._sy=this.newSy();else if("db"===a)s.isDoubleBar=!0,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!==ze.String&&this.error("ottava",ze.String,!0),e.clefOttava=this.parseClefOttavaFromString(this._syData),this._sy=this.newSy();else if("simile"===a)this._sy=this.newSy(),this._sy!==ze.String&&this.error("simile",ze.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!==ze.Number&&this.error("scale",ze.Number,!0),s.displayScale=this._syData,e.displayScale=this._syData,this._sy=this.newSy();else if("width"===a)this._sy=this.newSy(),this._sy!==ze.Number&&this.error("width",ze.Number,!0),s.displayWidth=this._syData,e.displayWidth=this._syData,this._sy=this.newSy();else if(0===e.index)switch(this.handleStaffMeta()){case Ue.KnownStaffMeta:break;case Ue.UnknownStaffMeta:this.error("measure-effects",ze.String,!1);break;case Ue.EndOfMetaDetected:i=!0}else this.error("measure-effects",ze.String,!1)}if(0===s.index&&0===s.tempoAutomations.length){let e=new $;e.isLinear=!1,e.type=r.Tempo,e.value=this._score.tempo,e.text=this._score.tempoLabel,s.tempoAutomations.push(e)}return t}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!==ze.String&&this.error("direction",ze.String,!0),this._syData.toLowerCase()){case"fine":e.addDirection(He.TargetFine);break;case"segno":e.addDirection(He.TargetSegno);break;case"segnosegno":e.addDirection(He.TargetSegnoSegno);break;case"coda":e.addDirection(He.TargetCoda);break;case"doublecoda":e.addDirection(He.TargetDoubleCoda);break;case"dacapo":e.addDirection(He.JumpDaCapo);break;case"dacapoalcoda":e.addDirection(He.JumpDaCapoAlCoda);break;case"dacapoaldoublecoda":e.addDirection(He.JumpDaCapoAlDoubleCoda);break;case"dacapoalfine":e.addDirection(He.JumpDaCapoAlFine);break;case"dalsegno":e.addDirection(He.JumpDalSegno);break;case"dalsegnoalcoda":e.addDirection(He.JumpDalSegnoAlCoda);break;case"dalsegnoaldoublecoda":e.addDirection(He.JumpDalSegnoAlDoubleCoda);break;case"dalsegnoalfine":e.addDirection(He.JumpDalSegnoAlFine);break;case"dalsegnosegno":e.addDirection(He.JumpDalSegnoSegno);break;case"dalsegnosegnoalcoda":e.addDirection(He.JumpDalSegnoSegnoAlCoda);break;case"dalsegnosegnoaldoublecoda":e.addDirection(He.JumpDalSegnoSegnoAlDoubleCoda);break;case"dalsegnosegnoalfine":e.addDirection(He.JumpDalSegnoSegnoAlFine);break;case"dacoda":e.addDirection(He.JumpDaCoda);break;case"dadoublecoda":e.addDirection(He.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!==ze.Number&&this.error("tempo",ze.Number,!0);const e=new $;return e.isLinear=!1,e.type=r.Tempo,e.value=this._syData,this._sy=this.newSy(),this._sy===ze.String&&(e.text=this._syData,this._sy=this.newSy()),e}applyAlternateEnding(e){let t=this._syData;t<1&&this.error("alternateending",ze.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}parseWhammyType(e){switch(e.toLowerCase()){case"none":return A.None;case"custom":default:return A.Custom;case"dive":return A.Dive;case"dip":return A.Dip;case"hold":return A.Hold;case"predive":return A.Predive;case"predivedive":return A.PrediveDive}}}st.Eof=0,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"}(Je||(Je={}));class it{static parseEnum(t,s){switch(typeof t){case"string":const e=parseInt(t);return isNaN(e)?s[Object.keys(s).find((e=>e.toLowerCase()===t.toLowerCase()))]:e;case"number":return t;case"undefined":case"object":return null}throw new K(e.AlphaTabErrorType.Format,`Could not parse enum value '${t}'`)}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 at{constructor(e,t,s){this.text=e,this.startPos=t,this.endPos=s}}class rt{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 at(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 rt(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;){let 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,a=[];for(;;){if(!this._currentToken)return;let 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"}(Ye||(Ye={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(qe||(qe={}));class nt{reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=rt.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===qe.Bold}get isItalic(){return this.style===Ye.Italic}constructor(e,t,s=Ye.Plain,i=qe.Regular){this._cssScale=0,this._families=rt.parseFamilies(e),this._size=t,this._style=s,this._weight=i,this._css=this.toCssString()}withSize(e){return nt.withFamilyList(this._families,e,this._style,this._weight)}static withFamilyList(e,t,s=Ye.Plain,i=qe.Regular){const a=new nt("",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=>rt.quoteFont(e))).join(", "),this._css=t,this._cssScale=e}return this._css}static fromJson(e){if(e instanceof nt)return e;switch(typeof e){case"undefined":default:return null;case"object":{const t=e;let s=t.get("families"),i=t.get("size"),a=it.parseEnum(t.get("style"),Ye),r=it.parseEnum(t.get("weight"),qe);return nt.withFamilyList(s,i,a,r)}case"string":{const t=new rt(e);t.parse();let s=t.families,i=t.size.toLowerCase(),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*parseFloat(i.substr(0,i.length-2)):i.endsWith("pt")?16*parseFloat(i.substr(0,i.length-2))/12:i.endsWith("px")?parseFloat(i.substr(0,i.length-2)):12}catch(e){a=12}}let r=Ye.Plain;"italic"===t.style&&(r=Ye.Italic);let n=qe.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=qe.Bold}return nt.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}}!function(e){e[e.SingleTrackMultiChannel=0]="SingleTrackMultiChannel",e[e.MultiTrack=1]="MultiTrack"}(je||(je={}));class ot{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){let t=Oe.empty(),s=0;for(let e of this.events){let i=e.tick-s;ht.writeVariableInt(t,i),e.writeTo(t),s=e.tick}const i=new Uint8Array([77,84,114,107]);e.write(i,0,i.length);let a=t.toArray();Re.writeInt32BE(e,a.length),e.write(a,0,a.length)}}class ht{constructor(){this.format=je.SingleTrackMultiChannel,this.division=te.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 ot)}addEvent(e){this.format==je.SingleTrackMultiChannel?(this.ensureTracks(1),this.tracks[0].addEvent(e)):(this.ensureTracks(e.track+1),this.tracks[e.track].addEvent(e))}toBinary(){let e=Oe.empty();return this.writeTo(e),e.toArray()}writeTo(e){let t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),Re.writeInt32BE(e,6),Re.writeInt16BE(e,this.format),Re.writeInt16BE(e,this.tracks.length),Re.writeInt16BE(e,this.division);for(const t of this.tracks)t.writeTo(e)}static writeVariableInt(e,t){let s=new Uint8Array(4),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"}(Ke||(Ke={}));class lt{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 dt extends lt{constructor(e,t,s,i,a,r){super(e,t,Ke.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),ht.writeVariableInt(e,4),e.writeByte(255&this.numerator),e.writeByte(255&this.denominatorIndex),e.writeByte(255&this.midiClocksPerMetronomeClick),e.writeByte(255&this.thirtySecondNodesInQuarter)}}class ct extends lt{constructor(e,t,s){super(e,t,s)}writeTo(e){e.writeByte(240);const t=Oe.withCapacity(16);t.writeByte(ct.AlphaTabManufacturerId),this.writeEventData(t),t.writeByte(247),ht.writeVariableInt(e,t.length),t.copyTo(e)}}ct.AlphaTabManufacturerId=125,ct.MetronomeEventId=0,ct.RestEventId=1;class ut extends ct{constructor(e,t,s,i,a){super(e,t,Ke.AlphaTabMetronome),this.isMetronome=!0,this.metronomeNumerator=s,this.metronomeDurationInMilliseconds=a,this.metronomeDurationInTicks=i}writeEventData(e){e.writeByte(ct.MetronomeEventId),e.writeByte(this.metronomeNumerator),Re.writeInt32LE(e,this.metronomeDurationInTicks),Re.writeInt32LE(e,this.metronomeDurationInMilliseconds)}}class pt extends ct{constructor(e,t,s){super(e,t,Ke.AlphaTabRest),this.channel=s}writeEventData(e){e.writeByte(ct.RestEventId),e.writeByte(this.channel)}}class gt extends lt{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 mt extends gt{constructor(e,t,s,i,a){super(e,t,Ke.NoteOn,s,i,a)}writeTo(e){e.writeByte(15&this.channel|144),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class ft extends gt{constructor(e,t,s,i,a){super(e,t,Ke.NoteOff,s,i,a)}writeTo(e){e.writeByte(15&this.channel|128),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class yt extends lt{constructor(e,t,s,i,a){super(e,t,Ke.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 bt extends lt{constructor(e,t,s,i){super(e,t,Ke.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 St extends lt{constructor(e,t){super(0,e,Ke.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 _t extends lt{constructor(e,t,s,i){super(e,t,Ke.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 wt extends lt{constructor(e,t,s,i,a){super(e,t,Ke.PerNotePitchBend),this.channel=s,this.noteKey=i,this.value=a}writeTo(t){throw new K(e.AlphaTabErrorType.General,"Note Bend (Midi2.0) events cannot be exported to SMF1.0")}}class Bt extends lt{constructor(e,t){super(e,t,Ke.EndOfTrack)}writeTo(e){e.writeByte(255),e.writeByte(47),e.writeByte(0)}}class Tt{constructor(){this.copyrightFont=new nt(Tt.sansFont,12,Ye.Plain,qe.Bold),this.titleFont=new nt(Tt.serifFont,32,Ye.Plain),this.subTitleFont=new nt(Tt.serifFont,20,Ye.Plain),this.wordsFont=new nt(Tt.serifFont,15,Ye.Plain),this.effectFont=new nt(Tt.serifFont,12,Ye.Italic),this.timerFont=new nt(Tt.serifFont,12,Ye.Plain),this.directionsFont=new nt(Tt.serifFont,14,Ye.Plain),this.fretboardNumberFont=new nt(Tt.sansFont,11,Ye.Plain),this.numberedNotationFont=new nt(Tt.sansFont,16,Ye.Plain),this.numberedNotationGraceFont=new nt(Tt.sansFont,14,Ye.Plain),this.tablatureFont=new nt(Tt.sansFont,13,Ye.Plain),this.graceFont=new nt(Tt.sansFont,11,Ye.Plain),this.staffLineColor=new Ee(165,165,165,255),this.barSeparatorColor=new Ee(34,34,17,255),this.barNumberFont=new nt(Tt.sansFont,11,Ye.Plain),this.barNumberColor=new Ee(200,0,0,255),this.fingeringFont=new nt(Tt.serifFont,14,Ye.Plain),this.inlineFingeringFont=new nt(Tt.serifFont,12,Ye.Plain),this.markerFont=new nt(Tt.serifFont,14,Ye.Plain,qe.Bold),this.mainGlyphColor=new Ee(0,0,0,255),this.secondaryGlyphColor=new Ee(0,0,0,100),this.scoreInfoColor=new Ee(0,0,0,255)}}Tt.sansFont="Arial, sans-serif",Tt.serifFont="Georgia, serif",e.SystemsLayoutMode=void 0,(Qe=e.SystemsLayoutMode||(e.SystemsLayoutMode={}))[Qe.Automatic=0]="Automatic",Qe[Qe.UseModelLayout=1]="UseModelLayout";class kt{constructor(){this.scale=1,this.stretchForce=1,this.layoutMode=e.LayoutMode.Page,this.staveProfile=e.StaveProfile.Default,this.barsPerRow=-1,this.startBar=1,this.barCount=-1,this.barCountPerPartial=10,this.justifyLastSystem=!1,this.resources=new Tt,this.padding=[35,35],this.firstSystemPaddingTop=5,this.systemPaddingTop=10,this.systemPaddingBottom=20,this.lastSystemPaddingBottom=0,this.systemLabelPaddingLeft=0,this.systemLabelPaddingRight=5,this.accoladeBarPaddingRight=3,this.notationStaffPaddingTop=5,this.notationStaffPaddingBottom=5,this.effectStaffPaddingTop=0,this.effectStaffPaddingBottom=0,this.firstStaffPaddingLeft=6,this.staffPaddingLeft=2,this.systemsLayoutMode=e.SystemsLayoutMode.Automatic}}class Nt{constructor(){this.encoding="utf-8",this.mergePartGroupsInMusicXml=!1,this.beatTextAsLyrics=!1}}e.ScrollMode=void 0,($e=e.ScrollMode||(e.ScrollMode={}))[$e.Off=0]="Off",$e[$e.Continuous=1]="Continuous",$e[$e.OffScreen=2]="OffScreen";class xt{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 vt{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}e.PlayerOutputMode=void 0,(Ze=e.PlayerOutputMode||(e.PlayerOutputMode={}))[Ze.WebAudioAudioWorklets=0]="WebAudioAudioWorklets",Ze[Ze.WebAudioScriptProcessor=1]="WebAudioScriptProcessor";class Pt{constructor(){this.soundFont=null,this.scrollElement="html,body",this.outputMode=e.PlayerOutputMode.WebAudioAudioWorklets,this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=e.ScrollMode.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new xt,this.slide=new vt,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}class Ct{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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(t,s,i){switch(s){case"scriptfile":return t.scriptFile=i,!0;case"fontdirectory":return t.fontDirectory=i,!0;case"file":return t.file=i,!0;case"tex":return t.tex=i,!0;case"tracks":return t.tracks=i,!0;case"enablelazyloading":return t.enableLazyLoading=i,!0;case"engine":return t.engine=i,!0;case"loglevel":return t.logLevel=it.parseEnum(i,e.LogLevel),!0;case"useworkers":return t.useWorkers=i,!0;case"includenotebounds":return t.includeNoteBounds=i,!0}return!1}}class Et{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("copyrightfont",nt.toJson(e.copyrightFont)),t.set("titlefont",nt.toJson(e.titleFont)),t.set("subtitlefont",nt.toJson(e.subTitleFont)),t.set("wordsfont",nt.toJson(e.wordsFont)),t.set("effectfont",nt.toJson(e.effectFont)),t.set("timerfont",nt.toJson(e.timerFont)),t.set("directionsfont",nt.toJson(e.directionsFont)),t.set("fretboardnumberfont",nt.toJson(e.fretboardNumberFont)),t.set("numberednotationfont",nt.toJson(e.numberedNotationFont)),t.set("numberednotationgracefont",nt.toJson(e.numberedNotationGraceFont)),t.set("tablaturefont",nt.toJson(e.tablatureFont)),t.set("gracefont",nt.toJson(e.graceFont)),t.set("stafflinecolor",Ee.toJson(e.staffLineColor)),t.set("barseparatorcolor",Ee.toJson(e.barSeparatorColor)),t.set("barnumberfont",nt.toJson(e.barNumberFont)),t.set("barnumbercolor",Ee.toJson(e.barNumberColor)),t.set("fingeringfont",nt.toJson(e.fingeringFont)),t.set("inlinefingeringfont",nt.toJson(e.inlineFingeringFont)),t.set("markerfont",nt.toJson(e.markerFont)),t.set("mainglyphcolor",Ee.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",Ee.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",Ee.toJson(e.scoreInfoColor)),t}static setProperty(e,t,s){switch(t){case"copyrightfont":return e.copyrightFont=nt.fromJson(s),!0;case"titlefont":return e.titleFont=nt.fromJson(s),!0;case"subtitlefont":return e.subTitleFont=nt.fromJson(s),!0;case"wordsfont":return e.wordsFont=nt.fromJson(s),!0;case"effectfont":return e.effectFont=nt.fromJson(s),!0;case"timerfont":return e.timerFont=nt.fromJson(s),!0;case"directionsfont":return e.directionsFont=nt.fromJson(s),!0;case"fretboardnumberfont":return e.fretboardNumberFont=nt.fromJson(s),!0;case"numberednotationfont":return e.numberedNotationFont=nt.fromJson(s),!0;case"numberednotationgracefont":return e.numberedNotationGraceFont=nt.fromJson(s),!0;case"tablaturefont":return e.tablatureFont=nt.fromJson(s),!0;case"gracefont":return e.graceFont=nt.fromJson(s),!0;case"stafflinecolor":return e.staffLineColor=Ee.fromJson(s),!0;case"barseparatorcolor":return e.barSeparatorColor=Ee.fromJson(s),!0;case"barnumberfont":return e.barNumberFont=nt.fromJson(s),!0;case"barnumbercolor":return e.barNumberColor=Ee.fromJson(s),!0;case"fingeringfont":return e.fingeringFont=nt.fromJson(s),!0;case"inlinefingeringfont":return e.inlineFingeringFont=nt.fromJson(s),!0;case"markerfont":return e.markerFont=nt.fromJson(s),!0;case"mainglyphcolor":return e.mainGlyphColor=Ee.fromJson(s),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=Ee.fromJson(s),!0;case"scoreinfocolor":return e.scoreInfoColor=Ee.fromJson(s),!0}return!1}}class Ft{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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",Et.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(t,s,i){switch(s){case"scale":return t.scale=i,!0;case"stretchforce":return t.stretchForce=i,!0;case"layoutmode":return t.layoutMode=it.parseEnum(i,e.LayoutMode),!0;case"staveprofile":return t.staveProfile=it.parseEnum(i,e.StaveProfile),!0;case"barsperrow":return t.barsPerRow=i,!0;case"startbar":return t.startBar=i,!0;case"barcount":return t.barCount=i,!0;case"barcountperpartial":return t.barCountPerPartial=i,!0;case"justifylastsystem":return t.justifyLastSystem=i,!0;case"padding":return t.padding=i,!0;case"firstsystempaddingtop":return t.firstSystemPaddingTop=i,!0;case"systempaddingtop":return t.systemPaddingTop=i,!0;case"systempaddingbottom":return t.systemPaddingBottom=i,!0;case"lastsystempaddingbottom":return t.lastSystemPaddingBottom=i,!0;case"systemlabelpaddingleft":return t.systemLabelPaddingLeft=i,!0;case"systemlabelpaddingright":return t.systemLabelPaddingRight=i,!0;case"accoladebarpaddingright":return t.accoladeBarPaddingRight=i,!0;case"notationstaffpaddingtop":return t.notationStaffPaddingTop=i,!0;case"notationstaffpaddingbottom":return t.notationStaffPaddingBottom=i,!0;case"effectstaffpaddingtop":return t.effectStaffPaddingTop=i,!0;case"effectstaffpaddingbottom":return t.effectStaffPaddingBottom=i,!0;case"firststaffpaddingleft":return t.firstStaffPaddingLeft=i,!0;case"staffpaddingleft":return t.staffPaddingLeft=i,!0;case"systemslayoutmode":return t.systemsLayoutMode=it.parseEnum(i,e.SystemsLayoutMode),!0}if(["resources"].indexOf(s)>=0)return Et.fromJson(t.resources,i),!0;for(const e of["resources"])if(0===s.indexOf(e)&&Et.setProperty(t.resources,s.substring(e.length),i))return!0;return!1}}class Dt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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(t,s,i){switch(s){case"notationmode":return t.notationMode=it.parseEnum(i,e.NotationMode),!0;case"fingeringmode":return t.fingeringMode=it.parseEnum(i,e.FingeringMode),!0;case"elements":return t.elements=new Map,it.forEach(i,((s,i)=>{t.elements.set(it.parseEnum(i,e.NotationElement),s)})),!0;case"rhythmmode":return t.rhythmMode=it.parseEnum(i,e.TabRhythmMode),!0;case"rhythmheight":return t.rhythmHeight=i,!0;case"transpositionpitches":return t.transpositionPitches=i,!0;case"displaytranspositionpitches":return t.displayTranspositionPitches=i,!0;case"smallgracetabnotes":return t.smallGraceTabNotes=i,!0;case"extendbendarrowsontiednotes":return t.extendBendArrowsOnTiedNotes=i,!0;case"extendlineeffectstobeatend":return t.extendLineEffectsToBeatEnd=i,!0;case"slurheight":return t.slurHeight=i,!0}return!1}}class Lt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 Mt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 It{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 At{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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",Mt.toJson(e.vibrato)),t.set("slide",It.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t.set("buffertimeinmilliseconds",e.bufferTimeInMilliseconds),t}static setProperty(t,s,i){switch(s){case"soundfont":return t.soundFont=i,!0;case"scrollelement":return t.scrollElement=i,!0;case"outputmode":return t.outputMode=it.parseEnum(i,e.PlayerOutputMode),!0;case"enableplayer":return t.enablePlayer=i,!0;case"enablecursor":return t.enableCursor=i,!0;case"enableanimatedbeatcursor":return t.enableAnimatedBeatCursor=i,!0;case"enableelementhighlighting":return t.enableElementHighlighting=i,!0;case"enableuserinteraction":return t.enableUserInteraction=i,!0;case"scrolloffsetx":return t.scrollOffsetX=i,!0;case"scrolloffsety":return t.scrollOffsetY=i,!0;case"scrollmode":return t.scrollMode=it.parseEnum(i,e.ScrollMode),!0;case"scrollspeed":return t.scrollSpeed=i,!0;case"nativebrowsersmoothscroll":return t.nativeBrowserSmoothScroll=i,!0;case"songbookbendduration":return t.songBookBendDuration=i,!0;case"songbookdipduration":return t.songBookDipDuration=i,!0;case"playtripletfeel":return t.playTripletFeel=i,!0;case"buffertimeinmilliseconds":return t.bufferTimeInMilliseconds=i,!0}if(["vibrato"].indexOf(s)>=0)return Mt.fromJson(t.vibrato,i),!0;for(const e of["vibrato"])if(0===s.indexOf(e)&&Mt.setProperty(t.vibrato,s.substring(e.length),i))return!0;if(["slide"].indexOf(s)>=0)return It.fromJson(t.slide,i),!0;for(const e of["slide"])if(0===s.indexOf(e)&&It.setProperty(t.slide,s.substring(e.length),i))return!0;return!1}}class Rt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("core",Ct.toJson(e.core)),t.set("display",Ft.toJson(e.display)),t.set("notation",Dt.toJson(e.notation)),t.set("importer",Lt.toJson(e.importer)),t.set("player",At.toJson(e.player)),t}static setProperty(e,t,s){if(["core",""].indexOf(t)>=0)return Ct.fromJson(e.core,s),!0;for(const i of["core",""])if(0===t.indexOf(i)&&Ct.setProperty(e.core,t.substring(i.length),s))return!0;if(["display",""].indexOf(t)>=0)return Ft.fromJson(e.display,s),!0;for(const i of["display",""])if(0===t.indexOf(i)&&Ft.setProperty(e.display,t.substring(i.length),s))return!0;if(["notation"].indexOf(t)>=0)return Dt.fromJson(e.notation,s),!0;for(const i of["notation"])if(0===t.indexOf(i)&&Dt.setProperty(e.notation,t.substring(i.length),s))return!0;if(["importer"].indexOf(t)>=0)return Lt.fromJson(e.importer,s),!0;for(const i of["importer"])if(0===t.indexOf(i)&&Lt.setProperty(e.importer,t.substring(i.length),s))return!0;if(["player"].indexOf(t)>=0)return At.fromJson(e.player,s),!0;for(const i of["player"])if(0===t.indexOf(i)&&At.setProperty(e.player,t.substring(i.length),s))return!0;return!1}}class Ot{constructor(){this.core=new xl,this.display=new kt,this.notation=new ie,this.importer=new Nt,this.player=new Pt}setSongBookModeSettings(){this.notation.notationMode=e.NotationMode.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=e.FingeringMode.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(e.NotationElement.ParenthesisOnTiedBends,!1),this.notation.elements.set(e.NotationElement.TabNotesOnTiedBends,!1),this.notation.elements.set(e.NotationElement.ZerosOnDiveWhammys,!0)}static get songBook(){let e=new Ot;return e.setSongBookModeSettings(),e}fillFromJson(e){Rt.fromJson(this,e)}}class Vt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 Ht{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=it.parseEnum(s,r),!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 Gt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=it.parseEnum(s,Ge),!0;case"length":return e.length=s,!0}return!1}}class Wt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("alternateendings",e.alternateEndings),t.set("keysignature",e.keySignature),t.set("keysignaturetype",e.keySignatureType),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),t.set("section",Vt.toJson(e.section)),t.set("tempoautomations",e.tempoAutomations.map((e=>Ht.toJson(e)))),null!==e.fermata){const s=new Map;t.set("fermata",s);for(const[t,i]of e.fermata)s.set(t.toString(),Gt.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"keysignature":return e.keySignature=it.parseEnum(s,P),!0;case"keysignaturetype":return e.keySignatureType=it.parseEnum(s,C),!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=it.parseEnum(s,E),!0;case"tempoautomations":e.tempoAutomations=[];for(const t of s){const s=new $;Ht.fromJson(s,t),e.tempoAutomations.push(s)}return!0;case"fermata":return e.fermata=new Map,it.forEach(s,((t,s)=>{const i=new et;Gt.fromJson(i,t),e.addFermata(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(it.parseEnum(t,He));return!0}return["section"].indexOf(t)>=0&&(s?(e.section=new Pe,Vt.fromJson(e.section,s)):e.section=null,!0)}}class zt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 Ut{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=>zt.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.toJson(t),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"accentuated":return e.accentuated=it.parseEnum(s,a),!0;case"bendtype":return e.bendType=it.parseEnum(s,c),!0;case"bendstyle":return e.bendStyle=it.parseEnum(s,d),!0;case"iscontinuedbend":return e.isContinuedBend=s,!0;case"bendpoints":if(s){e.bendPoints=[];for(const t of s){const s=new se;zt.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=it.parseEnum(s,b),!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=it.parseEnum(s,_),!0;case"slideouttype":return e.slideOutType=it.parseEnum(s,w),!0;case"vibrato":return e.vibrato=it.parseEnum(s,B),!0;case"istiedestination":return e.isTieDestination=s,!0;case"lefthandfinger":return e.leftHandFinger=it.parseEnum(s,y),!0;case"righthandfinger":return e.rightHandFinger=it.parseEnum(s,y),!0;case"trillvalue":return e.trillValue=s,!0;case"trillspeed":return e.trillSpeed=it.parseEnum(s,g),!0;case"durationpercent":return e.durationPercent=s,!0;case"accidentalmode":return e.accidentalMode=it.parseEnum(s,S),!0;case"dynamics":return e.dynamics=it.parseEnum(s,m),!0;case"ornament":return e.ornament=it.parseEnum(s,I),!0}return e.setProperty(t,s)}}class Xt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=>Ut.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=>Ht.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=>zt.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("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),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 me;Ut.fromJson(s,t),e.addNote(s)}return!0;case"isempty":return e.isEmpty=s,!0;case"whammystyle":return e.whammyStyle=it.parseEnum(s,d),!0;case"ottava":return e.ottava=it.parseEnum(s,o),!0;case"islegatoorigin":return e.isLegatoOrigin=s,!0;case"duration":return e.duration=it.parseEnum(s,g),!0;case"automations":e.automations=[];for(const t of s){const s=new $;Ht.fromJson(s,t),e.automations.push(s)}return!0;case"dots":return e.dots=s,!0;case"fade":return e.fade=it.parseEnum(s,O),!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=it.parseEnum(s,u),!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=it.parseEnum(s,A),!0;case"whammybarpoints":if(s){e.whammyBarPoints=[];for(const t of s){const s=new se;zt.fromJson(s,t),e.addWhammyBarPoint(s)}}return!0;case"vibrato":return e.vibrato=it.parseEnum(s,B),!0;case"chordid":return e.chordId=s,!0;case"gracetype":return e.graceType=it.parseEnum(s,f),!0;case"pickstroke":return e.pickStroke=it.parseEnum(s,F),!0;case"tremolospeed":return e.tremoloSpeed=it.parseEnum(s,g),!0;case"crescendo":return e.crescendo=it.parseEnum(s,p),!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"golpe":return e.golpe=it.parseEnum(s,R),!0;case"dynamics":return e.dynamics=it.parseEnum(s,m),!0;case"invertbeamdirection":return e.invertBeamDirection=s,!0;case"preferredbeamdirection":return e.preferredBeamDirection=it.parseEnum(s,We),!0;case"beamingmode":return e.beamingMode=it.parseEnum(s,W),!0;case"wahpedal":return e.wahPedal=it.parseEnum(s,V),!0;case"barrefret":return e.barreFret=s,!0;case"barreshape":return e.barreShape=it.parseEnum(s,H),!0;case"rasgueado":return e.rasgueado=it.parseEnum(s,G),!0;case"showtimer":return e.showTimer=s,!0;case"timer":return e.timer=s,!0}return!1}}class Jt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=>Xt.toJson(e)))),t.set("isempty",e.isEmpty),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 Be;Xt.fromJson(s,t),e.addBeat(s)}return!0;case"isempty":return e.isEmpty=s,!0}return!1}}class Yt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=it.parseEnum(s,l),!0}return!1}}class qt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=>Jt.toJson(e)))),t.set("similemark",e.simileMark),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t.set("sustainpedals",e.sustainPedals.map((e=>Yt.toJson(e)))),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"clef":return e.clef=it.parseEnum(s,n),!0;case"clefottava":return e.clefOttava=it.parseEnum(s,o),!0;case"voices":e.voices=[];for(const t of s){const s=new Ie;Jt.fromJson(s,t),e.addVoice(s)}return!0;case"similemark":return e.simileMark=it.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 Z;Yt.fromJson(s,t),e.sustainPedals.push(s)}return!0}return!1}}class jt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 Kt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 Qt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("bars",e.bars.map((e=>qt.toJson(e)))),null!==e.chords){const s=new Map;t.set("chords",s);for(const[t,i]of e.chords)s.set(t.toString(),jt.toJson(i))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",Kt.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 ee;qt.fromJson(s,t),e.addBar(s)}return!0;case"chords":return e.chords=new Map,it.forEach(s,((t,s)=>{const i=new Te;jt.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"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["stringtuning"].indexOf(t)>=0&&(Kt.fromJson(e.stringTuning,s),!0)}}class $t{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 Zt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=it.parseEnum(s,D),!0;case"noteheadhalf":return e.noteHeadHalf=it.parseEnum(s,D),!0;case"noteheadwhole":return e.noteHeadWhole=it.parseEnum(s,D),!0;case"techniquesymbol":return e.techniqueSymbol=it.parseEnum(s,D),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=it.parseEnum(s,M),!0;case"outputmidinumber":return e.outputMidiNumber=s,!0}return!1}}class es{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("staves",e.staves.map((e=>Qt.toJson(e)))),t.set("playbackinfo",$t.toJson(e.playbackInfo)),t.set("color",Ee.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),t.set("percussionarticulations",e.percussionArticulations.map((e=>Zt.toJson(e)))),t}static setProperty(e,t,s){switch(t){case"staves":e.staves=[];for(const t of s){const s=new Le;Qt.fromJson(s,t),e.addStaff(s)}return!0;case"color":return e.color=Ee.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"percussionarticulations":e.percussionArticulations=[];for(const t of s){const s=new ue;Zt.fromJson(s,t),e.percussionArticulations.push(s)}return!0}return["playbackinfo"].indexOf(t)>=0&&($t.fromJson(e.playbackInfo,s),!0)}}class ts{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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)}return 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}static setProperty(e,t,s){switch(t){case"hidedynamics":return e.hideDynamics=s,!0;case"bracketextendmode":return e.bracketExtendMode=it.parseEnum(s,U),!0;case"usesystemsignseparator":return e.useSystemSignSeparator=s,!0;case"globaldisplaytuning":return e.globalDisplayTuning=s,!0;case"pertrackdisplaytuning":return e.perTrackDisplayTuning=new Map,it.forEach(s,((t,s)=>{e.perTrackDisplayTuning.set(parseInt(s),t)})),!0;case"globaldisplaychorddiagramsontop":return e.globalDisplayChordDiagramsOnTop=s,!0;case"pertrackchorddiagramsontop":return e.perTrackChordDiagramsOnTop=new Map,it.forEach(s,((t,s)=>{e.perTrackChordDiagramsOnTop.set(parseInt(s),t)})),!0;case"singletracktracknamepolicy":return e.singleTrackTrackNamePolicy=it.parseEnum(s,X),!0;case"multitracktracknamepolicy":return e.multiTrackTrackNamePolicy=it.parseEnum(s,X),!0;case"firstsystemtracknamemode":return e.firstSystemTrackNameMode=it.parseEnum(s,J),!0;case"othersystemstracknamemode":return e.otherSystemsTrackNameMode=it.parseEnum(s,J),!0;case"firstsystemtracknameorientation":return e.firstSystemTrackNameOrientation=it.parseEnum(s,Y),!0;case"othersystemstracknameorientation":return e.otherSystemsTrackNameOrientation=it.parseEnum(s,Y),!0}return!1}}class ss{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=>Wt.toJson(e)))),t.set("tracks",e.tracks.map((e=>es.toJson(e)))),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("stylesheet",ts.toJson(e.stylesheet)),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 oe;Wt.fromJson(s,t),e.addMasterBar(s)}return!0;case"tracks":e.tracks=[];for(const t of s){const s=new Me;es.fromJson(s,t),e.addTrack(s)}return!0;case"defaultsystemslayout":return e.defaultSystemsLayout=s,!0;case"systemslayout":return e.systemsLayout=s,!0}return["stylesheet"].indexOf(t)>=0&&(ts.fromJson(e.stylesheet,s),!0)}}class is{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){let t=is.scoreToJsObject(e);return JSON.stringify(t,is.jsonReplacer)}static jsonToScore(e,t){return is.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return ss.toJson(e)}static jsObjectToScore(e,t){let s=new ve;return ss.fromJson(s,e),s.finish(t??new Ot),s}static settingsToJson(e){let t=is.settingsToJsObject(e);return JSON.stringify(t,is.jsonReplacer)}static jsonToSettings(e){return is.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return Rt.toJson(e)}static jsObjectToSettings(e){let t=new Ot;return Rt.fromJson(t,e),t}static jsObjectToMidiFile(e){let t=new ht;return it.forEach(e,((e,s)=>{switch(s){case"division":t.division=e;break;case"tracks":for(let s of e){let e=is.jsObjectToMidiTrack(s);t.tracks.push(e)}}})),t}static jsObjectToMidiTrack(e){let t=new ot;return it.forEach(e,((e,s)=>{if("events"===s)for(let s of e){let e=is.jsObjectToMidiEvent(s);t.events.push(e)}})),t}static jsObjectToMidiEvent(t){let s=it.getValue(t,"track"),i=it.getValue(t,"tick"),a=it.getValue(t,"type");switch(a){case Ke.TimeSignature:return new dt(s,i,it.getValue(t,"numerator"),it.getValue(t,"denominatorIndex"),it.getValue(t,"midiClocksPerMetronomeClick"),it.getValue(t,"thirdySecondNodesInQuarter"));case Ke.AlphaTabRest:return new pt(s,i,it.getValue(t,"channel"));case Ke.AlphaTabMetronome:return new ut(s,i,it.getValue(t,"metronomeNumerator"),it.getValue(t,"metronomeDurationInTicks"),it.getValue(t,"metronomeDurationInMilliseconds"));case Ke.NoteOn:return new mt(s,i,it.getValue(t,"channel"),it.getValue(t,"noteKey"),it.getValue(t,"noteVelocity"));case Ke.NoteOff:return new ft(s,i,it.getValue(t,"channel"),it.getValue(t,"noteKey"),it.getValue(t,"noteVelocity"));case Ke.ControlChange:return new yt(s,i,it.getValue(t,"channel"),it.getValue(t,"controller"),it.getValue(t,"value"));case Ke.ProgramChange:return new bt(s,i,it.getValue(t,"channel"),it.getValue(t,"program"));case Ke.TempoChange:return new St(i,it.getValue(t,"microSecondsPerQuarterNote"));case Ke.PitchBend:return new _t(s,i,it.getValue(t,"channel"),it.getValue(t,"value"));case Ke.PerNotePitchBend:return new wt(s,i,it.getValue(t,"channel"),it.getValue(t,"noteKey"),it.getValue(t,"value"));case Ke.EndOfTrack:return new Bt(s,i)}throw new K(e.AlphaTabErrorType.Format,"Unknown Midi Event type: "+a)}static midiFileToJsObject(e){const t=new Map;t.set("division",e.division);const s=[];for(let t of e.tracks)s.push(is.midiTrackToJsObject(t));return t.set("tracks",s),t}static midiTrackToJsObject(e){const t=new Map,s=[];for(let t of e.events)s.push(is.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 Ke.TimeSignature:t.set("numerator",e.numerator),t.set("denominatorIndex",e.denominatorIndex),t.set("midiClocksPerMetronomeClick",e.midiClocksPerMetronomeClick),t.set("thirdySecondNodesInQuarter",e.thirtySecondNodesInQuarter);break;case Ke.AlphaTabRest:t.set("channel",e.channel);break;case Ke.AlphaTabMetronome:t.set("metronomeNumerator",e.metronomeNumerator),t.set("metronomeDurationInMilliseconds",e.metronomeDurationInMilliseconds),t.set("metronomeDurationInTicks",e.metronomeDurationInTicks);break;case Ke.NoteOn:case Ke.NoteOff:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("noteVelocity",e.noteVelocity);break;case Ke.ControlChange:t.set("channel",e.channel),t.set("controller",e.controller),t.set("value",e.value);break;case Ke.ProgramChange:t.set("channel",e.channel),t.set("program",e.program);break;case Ke.TempoChange:t.set("microSecondsPerQuarterNote",e.microSecondsPerQuarterNote);break;case Ke.PitchBend:t.set("channel",e.channel),t.set("value",e.value);break;case Ke.PerNotePitchBend:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("value",e.value);case Ke.EndOfTrack:}return t}}var as,rs,ns,os=Object.freeze({__proto__:null,get AccentuationType(){return a},get AccidentalType(){return Je},Automation:$,get AutomationType(){return r},Bar:ee,get BarreShape(){return H},Beat:Be,get BeatBeamingMode(){return W},BendPoint:se,get BendStyle(){return d},get BendType(){return c},get BracketExtendMode(){return U},get BrushType(){return u},Chord:Te,get Clef(){return n},Color:Ee,get CrescendoType(){return p},get Duration(){return g},get DynamicValue(){return m},get FadeType(){return O},Fermata:et,get FermataType(){return Ge},get Fingers(){return y},Font:nt,get FontStyle(){return Ye},get FontWeight(){return qe},get GraceType(){return f},get HarmonicType(){return b},InstrumentArticulation:ue,JsonConverter:is,get KeySignature(){return P},get KeySignatureType(){return C},Lyrics:ke,MasterBar:oe,get MusicFontSymbol(){return D},Note:me,get NoteAccidentalMode(){return S},get NoteOrnament(){return I},get Ottavia(){return o},get PickStroke(){return F},PlaybackInformation:Fe,get Rasgueado(){return G},RenderStylesheet:Ne,RepeatGroup:xe,Score:ve,Section:Pe,get SimileMark(){return h},get SlideInType(){return _},get SlideOutType(){return w},Staff:Le,SustainPedalMarker:Z,get SustainPedalMarkerType(){return l},Track:Me,get TrackNameMode(){return J},get TrackNameOrientation(){return Y},get TrackNamePolicy(){return X},get TripletFeel(){return E},Tuning:De,TupletGroup:fe,get VibratoType(){return B},Voice:Ie,get WahPedal(){return V},get WhammyType(){return A}});class hs extends j{get name(){return"Guitar Pro 3-5"}constructor(){super(),this._versionNumber=0,this._globalTripletFeel=E.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._beatTextChunksByTrack=new Map,this._directionLookup=new Map}readScore(){if(this._directionLookup.clear(),this.readVersion(),this._score=new ve,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=ls.gpReadBool(this.data)?E.Triplet8th:E.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=ls.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=Re.readInt32LE(this.data),this._versionNumber>=510&&ls.gpReadBool(this.data),Re.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.readDirection(He.TargetCoda),this.readDirection(He.TargetDoubleCoda),this.readDirection(He.TargetSegno),this.readDirection(He.TargetSegnoSegno),this.readDirection(He.TargetFine),this.readDirection(He.JumpDaCapo),this.readDirection(He.JumpDaCapoAlCoda),this.readDirection(He.JumpDaCapoAlDoubleCoda),this.readDirection(He.JumpDaCapoAlFine),this.readDirection(He.JumpDalSegno),this.readDirection(He.JumpDalSegnoAlCoda),this.readDirection(He.JumpDalSegnoAlDoubleCoda),this.readDirection(He.JumpDalSegnoAlFine),this.readDirection(He.JumpDalSegnoSegno),this.readDirection(He.JumpDalSegnoSegnoAlCoda),this.readDirection(He.JumpDalSegnoSegnoAlDoubleCoda),this.readDirection(He.JumpDalSegnoSegnoAlFine),this.readDirection(He.JumpDaCoda),this.readDirection(He.JumpDaDoubleCoda),this.data.skip(4)),this._barCount=Re.readInt32LE(this.data),this._trackCount=Re.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0){const e=$.buildTempoAutomation(!1,0,this._score.tempo,2);e.text=this._score.tempoLabel,this._score.masterBars[0].tempoAutomations.push(e)}return 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=Re.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=ls.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(hs.VersionString))throw new Q("Unsupported format");e=e.substr(hs.VersionString.length+1);let t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*parseInt(e.substr(0,t))+parseInt(e.substr(t+1)),ne.debug(this.name,"Guitar Pro version "+e+" detected")}readScoreInformation(){this._score.title=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding);let e=Re.readInt32LE(this.data),t="";for(let s=0;s<e;s++)s>0&&(t+="\r\n"),t+=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding)?.toString();this._score.notices=t}readLyrics(){this._lyrics=[],this._lyricsTrack=Re.readInt32LE(this.data)-1;for(let e=0;e<5;e++){let e=new ke;e.startBar=Re.readInt32LE(this.data)-1,e.text=ls.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(30);for(let e=0;e<10;e++)ls.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){let t=new Fe;t.primaryChannel=e,t.secondaryChannel=e,t.program=Re.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]);let t=new oe,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,r=this.data.readByte();for(let e=0;e<8;e++){let t=1<<e;r>e&&!(i&t)&&(a|=t)}t.alternateEndings=a}if(32&s){let e=new Pe;e.text=ls.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",ls.gpReadColor(this.data,!1),t.section=e}if(64&s?(t.keySignature=Re.readSInt8(this.data),t.keySignatureType=this.data.readByte()):e&&(t.keySignature=e.keySignature,t.keySignatureType=e.keySignatureType),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=E.Triplet8th;break;case 2:t.tripletFeel=E.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=!!(128&s);const i=this._score.masterBars.length;if(this._directionLookup.has(i))for(const e of this._directionLookup.get(i))t.addDirection(e);this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){let e=new Me;e.ensureStaveCount(1),this._score.addTrack(e);let t=e.staves[0],s=this.data.readByte();e.name=ls.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));let i=Re.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){let t=Re.readInt32LE(this.data);i>e&&a.push(t)}t.stringTuning.tunings=a;let r=Re.readInt32LE(this.data),n=Re.readInt32LE(this.data)-1,o=Re.readInt32LE(this.data)-1;if(this.data.skip(4),n>=0&&n<this._playbackInfos.length){let i=this._playbackInfos[n];i.port=r,i.isSolo=!!(16&s),i.isMute=!!(32&s),i.secondaryChannel=o,q.isGuitar(i.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=i}if(t.capo=Re.readInt32LE(this.data),e.color=ls.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),ls.gpReadStringIntByte(this.data,this.settings.importer.encoding),ls.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){let t=new ee,s=e.staves[0];s.isPercussion&&(t.clef=n.Neutral),s.addBar(t);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){let s=Re.readInt32LE(this.data);if(0===s)return;let i=new Ie;t.addVoice(i);for(let a=0;a<s;a++)this.readBeat(e,t,i)}readBeat(e,t,s){let i=new Be,a=this.data.readByte();if(1&a&&(i.dots=1),64&a){let e=this.data.readByte();i.isEmpty=!(2&e)}switch(s.addBeat(i),Re.readSInt8(this.data)){case-2:i.duration=g.Whole;break;case-1:i.duration=g.Half;break;case 0:i.duration=g.Quarter;break;case 1:i.duration=g.Eighth;break;case 2:i.duration=g.Sixteenth;break;case 3:i.duration=g.ThirtySecond;break;case 4:i.duration=g.SixtyFourth;break;default:i.duration=g.Quarter}if(32&a)switch(i.tupletNumerator=Re.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);let r=this.settings.importer.beatTextAsLyrics&&e.index!==this._lyricsTrack;if(4&a){const t=ls.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=b.None;8&a&&(n=this.readBeatEffects(i)),16&a&&this.readMixTableChange(i);let 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!==b.None&&(r.harmonicType=n,r.harmonicType===b.Natural&&(r.harmonicValue=de.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){const e=Re.readInt16LE(this.data);if(1&e&&i.index>0&&(s.beats[i.index-1].beamingMode=W.ForceSplitToNext),2&e&&(i.preferredBeamDirection=We.Down),4&e&&i.index>0&&(s.beats[i.index-1].beamingMode=W.ForceMergeWithNext),8&e&&(i.preferredBeamDirection=We.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=W.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){let t=new Te,s=de.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=ls.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Re.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Re.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}let 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=ls.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Re.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Re.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}let 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=ls.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=Re.readInt32LE(this.data);for(let s=0;s<6;s++){let i=Re.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}this.data.skip(36)}else{let s=this._versionNumber>=406?7:6;if(t.name=ls.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=Re.readInt32LE(this.data),t.firstFret>0)for(let i=0;i<s;i++){let s=Re.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){let t=this.data.readByte(),s=0;if(this._versionNumber>=400&&(s=this.data.readByte()),16&t&&(e.fade=O.FadeIn),(this._versionNumber<400&&1&t||2&t)&&(e.vibrato=B.Slight),1&s&&(e.rasgueado=G.Ii),32&t&&this._versionNumber>=400){switch(Re.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(Re.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=u.BrushUp,e.brushDuration=hs.toStrokeValue(t)):s>0&&(e.brushType=u.BrushDown,e.brushDuration=hs.toStrokeValue(s))}if(2&s)switch(Re.readSInt8(this.data)){case 0:e.pickStroke=F.None;break;case 1:e.pickStroke=F.Up;break;case 2:e.pickStroke=F.Down}if(this._versionNumber<400){if(4&t)return b.Natural;if(8&t)return b.Artificial}return b.None}readTremoloBarEffect(e){this.data.readByte(),Re.readInt32LE(this.data);let t=Re.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new se(0,0);t.offset=Re.readInt32LE(this.data),t.value=Re.readInt32LE(this.data)/hs.BendStep|0,ls.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){let t=new ds;t.instrument=Re.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=Re.readSInt8(this.data),t.balance=Re.readSInt8(this.data);let s=Re.readSInt8(this.data),i=Re.readSInt8(this.data),a=Re.readSInt8(this.data),n=Re.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=ls.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=Re.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(),n>=0&&this.data.readByte(),t.tempo>=0&&(t.duration=Re.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500){const t=Re.readSInt8(this.data);t>=100?e.wahPedal=V.Closed:t>=0&&(e.wahPedal=V.Open)}if(this._versionNumber>=510&&(ls.gpReadStringIntByte(this.data,this.settings.importer.encoding),ls.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){let s=new $;s.isLinear=!0,s.type=r.Volume,s.value=t.volume,e.automations.push(s)}if(t.balance>=0){let s=new $;s.isLinear=!0,s.type=r.Balance,s.value=t.balance,e.automations.push(s)}if(t.instrument>=0){let s=new $;s.isLinear=!0,s.type=r.Instrument,s.value=t.instrument,e.automations.push(s)}if(t.tempo>=0){let s=new $;s.isLinear=!0,s.type=r.Tempo,s.value=t.tempo,e.automations.push(s),e.voice.bar.masterBar.tempoAutomations.push(s)}}readNote(e,t,s,i,r){let n=new me;n.string=t.staff.tuning.length-r;let o=this.data.readByte();if(2&o?n.accentuated=a.Heavy:64&o&&(n.accentuated=a.Normal),n.isGhost=!!(4&o),32&o){let e=this.data.readByte();3===e?n.isDead=!0:2===e&&(n.isTieDestination=!0)}if(1&o&&this._versionNumber<500&&(this.data.readByte(),this.data.readByte()),16&o){let e=Re.readSInt8(this.data);n.dynamics=this.toDynamicValue(e),i.dynamics=n.dynamics}32&o&&(n.fret=Re.readSInt8(this.data)),128&o&&(n.leftHandFinger=Re.readSInt8(this.data),n.rightHandFinger=Re.readSInt8(this.data));let h=!1;if(this._versionNumber>=500){1&o&&(n.durationPercent=Re.readFloat64BE(this.data)),h=!!(2&this.data.readByte())}if(i.addNote(n),8&o&&this.readNoteEffects(e,s,i,n),t.staff.isPercussion&&(n.percussionArticulation=n.fret,n.string=-1,n.fret=-1),h){const e=De.defaultAccidentals[n.realValueWithoutHarmonic%12];"#"===e?n.accidentalMode=S.ForceFlat:"b"===e&&(n.accidentalMode=S.ForceSharp)}return n}toDynamicValue(e){switch(e){case 1:return m.PPP;case 2:return m.PP;case 3:return m.P;case 4:return m.MP;case 5:return m.MF;case 6:default:return m.F;case 7:return m.FF;case 8:return m.FFF}}readNoteEffects(e,t,s,i){let a=this.data.readByte(),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=w.Shift),16&r&&this.readArtificialHarmonic(i),32&r&&this.readTrill(i),i.isLetRing=!!(8&a),i.isHammerPullOrigin=!!(2&a),64&r&&(i.vibrato=B.Slight),i.isPalmMute=!!(2&r),i.isStaccato=!!(1&r)}readBend(e){this.data.readByte(),Re.readInt32LE(this.data);let t=Re.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new se(0,0);t.offset=Re.readInt32LE(this.data),t.value=Re.readInt32LE(this.data)/hs.BendStep|0,ls.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){let s=new Be,i=new me;switch(i.string=t.string,i.fret=Re.readSInt8(this.data),s.duration=g.ThirtySecond,s.dynamics=this.toDynamicValue(Re.readSInt8(this.data)),Re.readSInt8(this.data)){case 0:case 2:break;case 1:i.slideOutType=w.Legato,i.slideTarget=t;break;case 3:i.isHammerPullOrigin=!0}if(i.dynamics=s.dynamics,this.data.skip(1),this._versionNumber<500)s.graceType=f.BeforeBeat;else{let e=this.data.readByte();i.isDead=!!(1&e),s.graceType=2&e?f.OnBeat:f.BeforeBeat}e.addGraceBeat(s),s.addNote(i)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=g.Eighth;break;case 2:e.tremoloSpeed=g.Sixteenth;break;case 3:e.tremoloSpeed=g.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){let t=Re.readSInt8(this.data);1&t?e.slideOutType=w.Shift:2&t?e.slideOutType=w.Legato:4&t?e.slideOutType=w.OutDown:8&t&&(e.slideOutType=w.OutUp),16&t?e.slideInType=_.IntoFromBelow:32&t&&(e.slideInType=_.IntoFromAbove)}else{switch(Re.readSInt8(this.data)){case 1:e.slideOutType=w.Shift;break;case 2:e.slideOutType=w.Legato;break;case 3:e.slideOutType=w.OutDown;break;case 4:e.slideOutType=w.OutUp;break;case-1:e.slideInType=_.IntoFromBelow;break;case-2:e.slideInType=_.IntoFromAbove}}}readArtificialHarmonic(e){let t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=b.Natural,e.harmonicValue=de.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=b.Artificial;break;case 3:e.harmonicType=b.Tap,e.harmonicValue=de.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=b.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=b.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=b.Natural;break;case 3:e.harmonicType=b.Tap;break;case 4:e.harmonicType=b.Pinch;break;case 5:e.harmonicType=b.Semi;break;case 15:case 17:case 22:e.harmonicType=b.Artificial}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=g.Sixteenth;break;case 2:e.trillSpeed=g.ThirtySecond;break;case 3:e.trillSpeed=g.SixtyFourth}}}hs.VersionString="FICHIER GUITAR PRO ",hs.BendStep=25;class ls{static gpReadColor(e,t=!1){let s=e.readByte(),i=e.readByte(),a=e.readByte(),r=255;return t?r=e.readByte():e.skip(1),new Ee(s,i,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),ls.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return ls.gpReadString(e,Re.readInt32LE(e),t)}static gpReadStringIntByte(e,t){let s=Re.readInt32LE(e)-1;return e.readByte(),ls.gpReadString(e,s,t)}static gpReadString(e,t,s){let i=new Uint8Array(t);return e.read(i,0,i.length),Re.toString(i,s)}static gpWriteString(e,t){const s=Re.stringToBytes(t);e.writeByte(t.length),e.write(s,0,s.length)}static gpReadStringByteLength(e,t,s){let i=e.readByte(),a=ls.gpReadString(e,i,s);return i<t&&e.skip(t-i),a}}class ds{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class cs{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"}(as||(as={}));class us{constructor(e){this._types=new Map,this.raw=new Map,e&&this.read(e)}read(e){let t=Oe.fromBuffer(e),s=Re.readInt32BE(t);for(let e=0;e<s;e++){let e=ls.gpReadString(t,t.readByte(),"utf-8"),s=t.readByte();switch(this._types.set(e,s),s){case as.Boolean:let s=1===t.readByte();this.addValue(e,s);break;case as.Integer:let i=Re.readInt32BE(t);this.addValue(e,i);break;case as.Float:let a=Re.readFloat32BE(t);this.addValue(e,a);break;case as.String:let r=ls.gpReadString(t,Re.readInt16BE(t),"utf-8");this.addValue(e,r);break;case as.Point:let n=Re.readInt32BE(t),o=Re.readInt32BE(t);this.addValue(e,new se(n,o));break;case as.Size:let h=Re.readInt32BE(t),l=Re.readInt32BE(t);this.addValue(e,new se(h,l));break;case as.Rectangle:let d=new cs;d.x=Re.readInt32BE(t),d.y=Re.readInt32BE(t),d.w=Re.readInt32BE(t),d.h=Re.readInt32BE(t),this.addValue(e,d);break;case as.Color:let c=ls.gpReadColor(t,!0);this.addValue(e,c)}}}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=X.Hidden);break;case"System/showTrackNameMulti":s||(e.stylesheet.multiTrackTrackNamePolicy=X.Hidden);break;case"System/trackNameModeSingle":if(e.stylesheet.singleTrackTrackNamePolicy!==X.Hidden)switch(s){case 0:case 1:e.stylesheet.singleTrackTrackNamePolicy=X.FirstSystem;break;case 2:e.stylesheet.singleTrackTrackNamePolicy=X.AllSystems}break;case"System/trackNameModeMulti":if(e.stylesheet.multiTrackTrackNamePolicy!==X.Hidden)switch(s){case 0:case 1:e.stylesheet.multiTrackTrackNamePolicy=X.FirstSystem;break;case 2:e.stylesheet.multiTrackTrackNamePolicy=X.AllSystems}break;case"System/shortTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameMode=s?J.ShortName:J.FullName;break;case"System/shortTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameMode=s?J.ShortName:J.FullName;break;case"System/horizontalTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameOrientation=s?Y.Horizontal:Y.Vertical;break;case"System/horizontalTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameOrientation=s?Y.Horizontal:Y.Vertical}}addValue(e,t,s){this.raw.set(e,t),void 0!==s&&this._types.set(e,s)}writeTo(e){Re.writeInt32BE(e,this.raw.size);for(const[t,s]of this.raw){const i=this.getDataType(t,s);switch(ls.gpWriteString(e,t),e.writeByte(i),i){case as.Boolean:e.writeByte(s?1:0);break;case as.Integer:Re.writeInt32BE(e,s);break;case as.Float:Re.writeFloat32BE(e,s);break;case as.String:const t=Re.stringToBytes(s);Re.writeInt16BE(e,t.length),e.write(t,0,t.length);break;case as.Point:case as.Size:Re.writeInt32BE(e,s.offset),Re.writeInt32BE(e,s.value);break;case as.Rectangle:Re.writeInt32BE(e,s.x),Re.writeInt32BE(e,s.y),Re.writeInt32BE(e,s.w),Re.writeInt32BE(e,s.h);break;case as.Color:e.writeByte(s.r),e.writeByte(s.g),e.writeByte(s.b),e.writeByte(s.a)}}}getDataType(t,s){if(this._types.has(t))return this._types.get(t);const i=typeof s;switch(typeof s){case"string":return as.String;case"number":return s==(0|s)?as.Integer:as.Float;case"object":if(s instanceof se)return as.Point;if(s instanceof cs)return as.Rectangle;if(s instanceof Ee)return as.Color}throw new K(e.AlphaTabErrorType.General,`Unknown value type in BinaryStylesheet: ${i}`)}static writeForScore(e){const t=new us;switch(t.addValue("StandardNotation/hideDynamics",e.stylesheet.hideDynamics,as.Boolean),t.addValue("System/bracketExtendMode",e.stylesheet.bracketExtendMode,as.Integer),t.addValue("Global/useSystemSignSeparator",e.stylesheet.useSystemSignSeparator,as.Boolean),t.addValue("Global/DisplayTuning",e.stylesheet.globalDisplayTuning,as.Boolean),t.addValue("Global/DrawChords",e.stylesheet.globalDisplayChordDiagramsOnTop,as.Boolean),e.stylesheet.singleTrackTrackNamePolicy){case X.Hidden:t.addValue("System/showTrackNameSingle",!1,as.Boolean);break;case X.FirstSystem:t.addValue("System/trackNameModeSingle",0,as.Integer);break;case X.AllSystems:t.addValue("System/trackNameModeSingle",2,as.Integer)}switch(e.stylesheet.multiTrackTrackNamePolicy){case X.Hidden:t.addValue("System/trackNameModeMulti",!1,as.Boolean);break;case X.FirstSystem:t.addValue("System/trackNameModeMulti",0,as.Integer);break;case X.AllSystems:t.addValue("System/trackNameModeMulti",2,as.Integer)}switch(e.stylesheet.firstSystemTrackNameMode){case J.FullName:t.addValue("System/shortTrackNameOnFirstSystem",!1,as.Boolean);break;case J.ShortName:t.addValue("System/shortTrackNameOnFirstSystem",!0,as.Boolean)}switch(e.stylesheet.otherSystemsTrackNameMode){case J.FullName:t.addValue("System/shortTrackNameOnOtherSystems",!1,as.Boolean);break;case J.ShortName:t.addValue("System/shortTrackNameOnOtherSystems",!0,as.Boolean)}switch(e.stylesheet.firstSystemTrackNameOrientation){case Y.Horizontal:t.addValue("System/horizontalTrackNameOnFirstSystem",!0,as.Boolean);break;case Y.Vertical:t.addValue("System/horizontalTrackNameOnFirstSystem",!1,as.Boolean)}switch(e.stylesheet.otherSystemsTrackNameOrientation){case Y.Horizontal:t.addValue("System/horizontalTrackNameOnOtherSystems",!0,as.Boolean);break;case Y.Vertical:t.addValue("System/horizontalTrackNameOnOtherSystems",!1,as.Boolean)}const s=Oe.withCapacity(128);return t.writeTo(s),s.toArray()}}!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"}(rs||(rs={}));class ps{constructor(){this.nodeType=rs.None,this.localName=null,this.value=null,this.childNodes=[],this.attributes=new Map,this.firstChild=null,this.firstElement=null}addChild(e){this.childNodes.push(e),this.firstChild=e,e.nodeType!==rs.Element&&e.nodeType!==rs.CDATA||(this.firstElement=e)}getAttribute(e){return this.attributes.has(e)?this.attributes.get(e):""}getElementsByTagName(e,t=!1){let s=[];return this.searchElementsByTagName(this.childNodes,s,e,t),s}searchElementsByTagName(e,t,s,i=!1){for(let a of e)a&&a.nodeType===rs.Element&&a.localName===s&&t.push(a),i&&this.searchElementsByTagName(a.childNodes,t,s,!0)}findChildElement(e){for(let t of this.childNodes)if(t&&t.nodeType===rs.Element&&t.localName===e)return t;return null}addElement(e){const t=new ps;return t.nodeType=rs.Element,t.localName=e,this.addChild(t),t}get innerText(){if(this.nodeType===rs.Element||this.nodeType===rs.Document){if(this.firstElement&&this.firstElement.nodeType===rs.CDATA)return this.firstElement.innerText;let e="";for(let t of this.childNodes)e+=t.innerText?.toString();return e.trim()}return this.value??""}set innerText(e){const t=new ps;t.nodeType=rs.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new ps;t.nodeType=rs.CDATA,t.value=e,this.childNodes=[t]}}class gs extends K{constructor(t,s,i){super(e.AlphaTabErrorType.Format,t),this.pos=0,this.xml=s,this.pos=i,Object.setPrototypeOf(this,gs.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"}(ns||(ns={}));class ms{static parse(e,t,s){let i=e.charCodeAt(t),a=ns.Begin,r=ns.Begin,n=0,o="",h=ns.Begin,l=null,d=null,c=0,u=0;for(;t<e.length;){switch(i=e.charCodeAt(t),a){case ns.IgnoreSpaces:switch(i){case ms.CharCodeLF:case ms.CharCodeCR:case ms.CharCodeTab:case ms.CharCodeSpace:break;default:a=r;continue}break;case ns.Begin:if(i!==ms.CharCodeLowerThan){n=t,a=ns.Pcdata;continue}a=ns.IgnoreSpaces,r=ns.BeginNode;break;case ns.Pcdata:if(i===ms.CharCodeLowerThan){o+=e.substr(n,t-n);let i=new ps;i.nodeType=rs.Text,i.value=o,o="",s.addChild(i),a=ns.IgnoreSpaces,r=ns.BeginNode}else i===ms.CharCodeAmp&&(o+=e.substr(n,t-n),a=ns.Escape,h=ns.Pcdata,n=t+1);break;case ns.Cdata:if(i===ms.CharCodeBrackedClose&&e.charCodeAt(t+1)===ms.CharCodeBrackedClose&&e.charCodeAt(t+2)===ms.CharCodeGreaterThan){let i=new ps;i.nodeType=rs.CDATA,i.value=e.substr(n,t-n),s.addChild(i),t+=2,a=ns.Begin}break;case ns.BeginNode:switch(i){case ms.CharCodeExclamation:if(e.charCodeAt(t+1)===ms.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new gs("Expected <![CDATA[",e,t);t+=5,a=ns.Cdata,n=t+1}else if(e.charCodeAt(t+1)===ms.CharCodeUpperD||e.charCodeAt(t+1)===ms.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new gs("Expected <!DOCTYPE",e,t);t+=8,a=ns.Doctype,n=t+1}else{if(e.charCodeAt(t+1)!==ms.CharCodeMinus||e.charCodeAt(t+2)!==ms.CharCodeMinus)throw new gs("Expected \x3c!--",e,t);t+=2,a=ns.Comment,n=t+1}break;case ms.CharCodeQuestion:a=ns.Header,n=t;break;case ms.CharCodeSlash:if(!s)throw new gs("Expected node name",e,t);n=t+1,a=ns.IgnoreSpaces,r=ns.Close;break;default:a=ns.TagName,n=t;continue}break;case ns.TagName:if(!ms.isValidChar(i)){if(t===n)throw new gs("Expected node name",e,t);l=new ps,l.nodeType=rs.Element,l.localName=e.substr(n,t-n),s.addChild(l),a=ns.IgnoreSpaces,r=ns.Body;continue}break;case ns.Body:switch(i){case ms.CharCodeSlash:a=ns.WaitEnd;break;case ms.CharCodeGreaterThan:a=ns.Childs;break;default:a=ns.AttribName,n=t;continue}break;case ns.AttribName:if(!ms.isValidChar(i)){if(n===t)throw new gs("Expected attribute name",e,t);if(d=e.substr(n,t-n),l.attributes.has(d))throw new gs(`Duplicate attribute [${d}]`,e,t);a=ns.IgnoreSpaces,r=ns.Equals;continue}break;case ns.Equals:if(i!==ms.CharCodeEquals)throw new gs("Expected =",e,t);a=ns.IgnoreSpaces,r=ns.AttvalBegin;break;case ns.AttvalBegin:switch(i){case ms.CharCodeDoubleQuote:case ms.CharCodeSingleQuote:o="",a=ns.AttribVal,n=t+1,u=i}break;case ns.AttribVal:if(i===ms.CharCodeAmp)o+=e.substr(n,t-n),a=ns.Escape,h=ns.AttribVal,n=t+1;else if(i===u){o+=e.substr(n,t-n);let s=o;o="",l.attributes.set(d,s),a=ns.IgnoreSpaces,r=ns.Body}break;case ns.Childs:n=t=ms.parse(e,t,l),a=ns.Begin;break;case ns.WaitEnd:if(i!==ms.CharCodeGreaterThan)throw new gs("Expected >",e,t);a=ns.Begin;break;case ns.WaitEndRet:if(i===ms.CharCodeGreaterThan)return t;throw new gs("Expected >",e,t);case ns.Close:if(!ms.isValidChar(i)){if(n===t)throw new gs("Expected node name",e,t);if(e.substr(n,t-n)!==s.localName)throw new gs("Expected </"+s.localName+">",e,t);a=ns.IgnoreSpaces,r=ns.WaitEndRet;continue}break;case ns.Comment:i===ms.CharCodeMinus&&e.charCodeAt(t+1)===ms.CharCodeMinus&&e.charCodeAt(t+2)===ms.CharCodeGreaterThan&&(t+=2,a=ns.Begin);break;case ns.Doctype:if(i===ms.CharCodeBrackedOpen)c++;else if(i===ms.CharCodeBrackedClose)c--;else if(i===ms.CharCodeGreaterThan&&0===c){let i=new ps;i.nodeType=rs.DocumentType,i.value=e.substr(n,t-n),s.addChild(i),a=ns.Begin}break;case ns.Header:i===ms.CharCodeQuestion&&e.charCodeAt(t+1)===ms.CharCodeGreaterThan&&(t++,a=ns.Begin);break;case ns.Escape:if(i===ms.CharCodeSemi){let s=e.substr(n,t-n);if(s.charCodeAt(0)===ms.CharCodeSharp){let e=s.charCodeAt(1)===ms.CharCodeLowerX?parseInt("0"+s.substr(1,s.length-1)):parseInt(s.substr(1,s.length-1));o+=String.fromCharCode(e)}else ms.Escapes.has(s)?o+=ms.Escapes.get(s):o+=("&"+s+";")?.toString();n=t+1,a=h}else ms.isValidChar(i)||i===ms.CharCodeSharp||(o+="&",o+=e.substr(n,t-n),n=--t+1,a=h)}t++}if(a===ns.Begin&&(n=t,a=ns.Pcdata),a===ns.Pcdata){if(t!==n){o+=e.substr(n,t-n);let i=new ps;i.nodeType=rs.Text,i.value=o,s.addChild(i)}return t}if(a===ns.Escape&&h===ns.Pcdata){o+="&",o+=e.substr(n,t-n);let i=new ps;return i.nodeType=rs.Text,i.value=o,s.addChild(i),t}throw new gs("Unexpected end",e,t)}static isValidChar(e){return e>=ms.CharCodeLowerA&&e<=ms.CharCodeLowerZ||e>=ms.CharCodeUpperA&&e<=ms.CharCodeUpperZ||e>=ms.CharCode0&&e<=ms.CharCode9||e===ms.CharCodeColon||e===ms.CharCodeDot||e===ms.CharCodeUnderscore||e===ms.CharCodeMinus}}ms.CharCodeLF=10,ms.CharCodeTab=9,ms.CharCodeCR=13,ms.CharCodeSpace=32,ms.CharCodeLowerThan=60,ms.CharCodeAmp=38,ms.CharCodeBrackedClose=93,ms.CharCodeBrackedOpen=91,ms.CharCodeGreaterThan=62,ms.CharCodeExclamation=33,ms.CharCodeUpperD=68,ms.CharCodeLowerD=100,ms.CharCodeMinus=45,ms.CharCodeQuestion=63,ms.CharCodeSlash=47,ms.CharCodeEquals=61,ms.CharCodeDoubleQuote=34,ms.CharCodeSingleQuote=39,ms.CharCodeSharp=35,ms.CharCodeLowerX=120,ms.CharCodeLowerA=97,ms.CharCodeLowerZ=122,ms.CharCodeUpperA=65,ms.CharCodeUpperZ=90,ms.CharCode0=48,ms.CharCode9=57,ms.CharCodeColon=58,ms.CharCodeDot=46,ms.CharCodeUnderscore=95,ms.CharCodeSemi=59,ms.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class fs{static write(e,t,s){const i=new fs(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 rs.None:break;case rs.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===rs.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case rs.Text:e.value&&this.write(e.value);break;case rs.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case rs.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case rs.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("<");break;case">":this._result.push(">");break;case"&":this._result.push("&");break;case"'":this._result.push("'");break;case'"':this._result.push(""");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 ys extends ps{constructor(){super(),this.nodeType=rs.Document}parse(e){ms.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return fs.write(this,e,t)}}class bs{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=g.Quarter}}class Ss{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return this.path+";"+this.name+";"+this.role}}class _s{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1}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;let s=new ys;try{s.parse(e)}catch(e){throw new Q("Could not parse XML",e)}if(this.parseDom(s),this.buildModel(),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){let t=e.firstElement;if(t){if("GPIF"!==t.localName)throw new Q("Root node of XML was not GPIF");this.score=new ve;for(let e of t.childNodes)if(e.nodeType===rs.Element)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(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"Title":this.score.title=t.firstChild.innerText;break;case"SubTitle":this.score.subTitle=t.firstChild.innerText;break;case"Artist":this.score.artist=t.firstChild.innerText;break;case"Album":this.score.album=t.firstChild.innerText;break;case"Words":this.score.words=t.firstChild.innerText;break;case"Music":this.score.music=t.firstChild.innerText;break;case"WordsAndMusic":if(t.firstChild&&""!==t.firstChild.innerText){let e=t.firstChild.innerText;e&&!this.score.words&&(this.score.words=e),e&&!this.score.music&&(this.score.music=e)}break;case"Copyright":this.score.copyright=t.firstChild.innerText;break;case"Tabber":this.score.tab=t.firstChild.innerText;break;case"Instructions":this.score.instructions=t.firstChild.innerText;break;case"Notices":this.score.notices=t.firstChild.innerText;break;case"ScoreSystemsDefaultLayout":this.score.defaultSystemsLayout=parseInt(t.innerText);break;case"ScoreSystemsLayout":this.score.systemsLayout=t.innerText.split(" ").map((e=>parseInt(e)))}}parseMasterTrackNode(e){for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null,null);break;case"Tracks":this._tracksMapping=t.innerText.split(" ");break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,s,i){for(let a of e.childNodes)if(a.nodeType===rs.Element&&"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,d=null,c=0,u=null;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"Type":a=t.innerText;break;case"Linear":r="true"===t.innerText.toLowerCase();break;case"Bar":n=parseInt(t.innerText);break;case"Position":o=parseFloat(t.innerText);break;case"Value":if(t.firstElement&&t.firstElement.nodeType===rs.CDATA)d=t.innerText;else{let e=t.innerText.split(" ");1===e.length?(h=parseFloat(e[0]),c=1):(h=parseFloat(e[0]),c=parseInt(e[1]))}break;case"Text":u=t.innerText}if(!a)return;let p=null;switch(a){case"Tempo":p=$.buildTempoAutomation(r,o,h,c);break;case"Sound":d&&s&&s.has(d)&&(p=$.buildInstrumentAutomation(r,o,s.get(d).program));break;case"SustainPedal":if(i){let e;i.has(n)?e=i.get(n):(e=[],i.set(n,e));const t=new Z;switch(t.ratioPosition=o,c){case 1:t.pedalType=l.Down;break;case 3:t.pedalType=l.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(let t of e.childNodes)if(t.nodeType===rs.Element&&"Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;let t=new Me;t.ensureStaveCount(1),t.staves[0].showStandardNotation=!0;let s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"Name":t.name=i.innerText;break;case"Color":let e=i.innerText.split(" ");if(e.length>=3){let s=parseInt(e[0]),i=parseInt(e[1]),a=parseInt(e[2]);t.color=new Ee(s,i,a,255)}break;case"Instrument":let 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=parseInt(i.innerText);break;case"SystemsLayout":t.systemsLayout=i.innerText.split(" ").map((e=>parseInt(e)));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":let 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(let s of t.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"LineCount":const t=parseInt(s.innerText);for(let s of e.staves)s.standardNotationLineCount=t;break;case"Elements":this.parseElements(e,s)}}parseInstrumentSet(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"Type":if("drumKit"===s.innerText)for(let t of e.staves)t.isPercussion=!0;if("drumKit"===s.innerText)for(let t of e.staves)t.isPercussion=!0;break;case"Elements":this.parseElements(e,s);break;case"LineCount":const t=parseInt(s.innerText);for(let s of e.staves)s.standardNotationLineCount=t}}parseElements(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"Element"===s.localName)this.parseElement(e,s)}parseElement(e,t){const s=t.findChildElement("Type"),i=s?s.innerText:"";for(let s of t.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"Name":case"Articulations":this.parseArticulations(e,s,i)}}parseArticulations(e,t,s){for(let i of t.childNodes)if(i.nodeType===rs.Element&&"Articulation"===i.localName)this.parseArticulation(e,i,s)}parseArticulation(e,t,s){const i=new ue;i.outputMidiNumber=-1,i.elementType=s;let a="";for(let e of t.childNodes)if(e.nodeType===rs.Element){const t=e.innerText;switch(e.localName){case"Name":a=e.innerText;break;case"OutputMidiNumber":t.length>0&&(i.outputMidiNumber=parseInt(t));break;case"TechniqueSymbol":i.techniqueSymbol=this.parseTechniqueSymbol(t);break;case"TechniquePlacement":switch(t){case"outside":case"above":i.techniqueSymbolPlacement=M.Bottom;break;case"inside":i.techniqueSymbolPlacement=M.Middle;break;case"below":i.techniqueSymbolPlacement=M.Top}break;case"Noteheads":const s=t.split(" ");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==D.None&&(i.noteHeadHalf=i.noteHeadDefault),i.noteHeadWhole==D.None&&(i.noteHeadWhole=i.noteHeadDefault);break;case"StaffLine":t.length>0&&(i.staffLine=parseInt(t))}}-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 D.PictEdgeOfCymbal;case"articStaccatoAbove":return D.ArticStaccatoAbove;case"noteheadParenthesis":return D.NoteheadParenthesis;case"stringsUpBow":return D.StringsUpBow;case"stringsDownBow":return D.StringsDownBow;case"guitarGolpe":return D.GuitarGolpe;default:return D.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return D.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return D.NoteheadDoubleWhole;case"noteheadWhole":return D.NoteheadWhole;case"noteheadHalf":return D.NoteheadHalf;case"noteheadBlack":return D.NoteheadBlack;case"noteheadNull":return D.NoteheadNull;case"noteheadXOrnate":return D.NoteheadXOrnate;case"noteheadTriangleUpWhole":return D.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return D.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return D.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return D.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return D.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return D.NoteheadDiamondWhiteWide;case"noteheadCircleX":return D.NoteheadCircleX;case"noteheadXWhole":return D.NoteheadXWhole;case"noteheadXHalf":return D.NoteheadXHalf;case"noteheadXBlack":return D.NoteheadXBlack;case"noteheadParenthesis":return D.NoteheadParenthesis;case"noteheadSlashedBlack2":return D.NoteheadSlashedBlack2;case"noteheadCircleSlash":return D.NoteheadCircleSlash;case"noteheadHeavyX":return D.NoteheadHeavyX;case"noteheadHeavyXHat":return D.NoteheadHeavyXHat;default:return ne.warning("GPIF","Unknown notehead symbol",e),D.None}}parseStaves(e,t){let s=0;for(let i of t.childNodes)if(i.nodeType===rs.Element&&"Staff"===i.localName){e.ensureStaveCount(s+1);let t=e.staves[s];this.parseStaff(t,i),s++}}parseStaff(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"Properties"===s.localName)this.parseStaffProperties(e,s)}parseStaffProperties(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"Property"===s.localName)this.parseStaffProperty(e,s)}parseStaffProperty(e,t){switch(t.getAttribute("name")){case"Tuning":for(let s of t.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"Pitches":let i=t.findChildElement("Pitches").innerText.split(" "),a=new Array(i.length);for(let e=0;e<a.length;e++)a[a.length-1-e]=parseInt(i[e]);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":let s=parseInt(t.findChildElement("Fret").innerText);e.capo=s}}parseLyrics(e,t){let s=[];for(let e of t.childNodes)if(e.nodeType===rs.Element&&"Line"===e.localName)s.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,s)}parseLyricsLine(e){let t=new ke;for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"Offset":t.startBar=parseInt(s.innerText);break;case"Text":t.text=s.innerText}return t}parseDiagramCollectionForTrack(e,t){let s=t.findChildElement("Items");for(let t of s.childNodes)if(t.nodeType===rs.Element&&"Item"===t.localName)this.parseDiagramItemForTrack(e,t)}parseDiagramCollectionForStaff(e,t){let s=t.findChildElement("Items");for(let t of s.childNodes)if(t.nodeType===rs.Element&&"Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){let s=new Te,i=t.getAttribute("id");for(let t of e.staves)t.addChord(i,s);this.parseDiagramItemForChord(s,t)}parseDiagramItemForStaff(e,t){let s=new Te,i=t.getAttribute("id");e.addChord(i,s),this.parseDiagramItemForChord(s,t)}parseDiagramItemForChord(e,t){e.name=t.getAttribute("name");let s=t.findChildElement("Diagram");if(!s)return e.showDiagram=!1,void(e.showFingering=!1);let i=parseInt(s.getAttribute("stringCount")),a=s.attributes.has("baseFret")?parseInt(s.getAttribute("baseFret")):0;e.firstFret=a+1;for(let t=0;t<i;t++)e.strings.push(-1);for(let t of s.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"Fret":let s=parseInt(t.getAttribute("string"));e.strings[i-s-1]=a+parseInt(t.getAttribute("fret"));break;case"Fingering":let r=new Map;for(let s of t.childNodes)if(s.nodeType===rs.Element&&"Position"===s.localName){let t=y.Unknown,i=a+parseInt(s.getAttribute("fret"));switch(s.getAttribute("finger")){case"Index":t=y.IndexFinger;break;case"Middle":t=y.MiddleFinger;break;case"Rank":t=y.AnnularFinger;break;case"Pinky":t=y.LittleFinger;break;case"Thumb":t=y.Thumb}t!==y.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(let s of t.childNodes)if(s.nodeType===rs.Element&&"Property"===s.localName)this.parseTrackProperty(e,s)}parseTrackProperty(e,t){switch(t.getAttribute("name")){case"Tuning":let s=t.findChildElement("Pitches").innerText.split(" "),i=new Array(s.length);for(let e=0;e<i.length;e++)i[i.length-1-e]=parseInt(s[e]);for(let 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":let a=parseInt(t.findChildElement("Fret").innerText);for(let t of e.staves)t.capo=a}}parseGeneralMidi(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"Program":e.playbackInfo.program=parseInt(s.innerText);break;case"Port":e.playbackInfo.port=parseInt(s.innerText);break;case"PrimaryChannel":e.playbackInfo.primaryChannel=parseInt(s.innerText);break;case"SecondaryChannel":e.playbackInfo.secondaryChannel=parseInt(s.innerText)}if("Percussion"===t.getAttribute("table"))for(let t of e.staves)t.isPercussion=!0}parseSounds(e,t,s){for(let i of s.childNodes)if(i.nodeType===rs.Element&&"Sound"===i.localName)this.parseSound(e,t,i)}parseSound(e,t,s){const i=new Ss;for(let e of s.childNodes)if(e.nodeType===rs.Element)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(let s of t.childNodes)if(s.nodeType===rs.Element&&"Program"===s.localName)e.program=parseInt(s.innerText)}parsePartSounding(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"TranspositionPitch"===s.localName)for(let t of e.staves)t.displayTranspositionPitch=parseInt(s.innerText)}parseTranspose(e,t){let s=0,i=0;for(let e of t.childNodes)if(e.nodeType===rs.Element)switch(e.localName){case"Chromatic":i=parseInt(e.innerText);break;case"Octave":s=parseInt(e.innerText)}for(let t of e.staves)t.displayTranspositionPitch=12*s+i}parseRSE(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"ChannelStrip"===s.localName)this.parseChannelStrip(e,s)}parseChannelStrip(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"Parameters"===s.localName)this.parseChannelStripParameters(e,s)}parseChannelStripParameters(e,t){if(t.firstChild&&t.firstChild.value){let s=t.firstChild.value.split(" ");s.length>=12&&(e.playbackInfo.balance=Math.floor(16*parseFloat(s[11])),e.playbackInfo.volume=Math.floor(16*parseFloat(s[12])))}}parseMasterBarsNode(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){let t=new oe;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"Time":let e=s.innerText.split("/");t.timeSignatureNumerator=parseInt(e[0]),t.timeSignatureDenominator=parseInt(e[1]);break;case"FreeTime":t.isFreeTime=!0;break;case"DoubleBar":t.isDoubleBar=!0;break;case"Section":t.section=new Pe,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=parseInt(s.getAttribute("count")));break;case"AlternateEndings":let i=s.innerText.split(" "),a=0;for(let e=0;e<i.length;e++)a|=1<<-1+parseInt(i[e]);t.alternateEndings=a;break;case"Bars":this._barsOfMasterBar.push(s.innerText.split(" "));break;case"TripletFeel":switch(s.innerText){case"NoTripletFeel":t.tripletFeel=E.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=E.Triplet8th;break;case"Triplet16th":t.tripletFeel=E.Triplet16th;break;case"Dotted8th":t.tripletFeel=E.Dotted8th;break;case"Dotted16th":t.tripletFeel=E.Dotted16th;break;case"Scottish8th":t.tripletFeel=E.Scottish8th;break;case"Scottish16th":t.tripletFeel=E.Scottish16th}break;case"Key":t.keySignature=parseInt(s.findChildElement("AccidentalCount").innerText);let r=s.findChildElement("Mode");if(r)switch(r.innerText.toLowerCase()){case"major":t.keySignatureType=C.Major;break;case"minor":t.keySignatureType=C.Minor}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(let s of t.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"Target":switch(s.innerText){case"Coda":e.addDirection(He.TargetCoda);break;case"DoubleCoda":e.addDirection(He.TargetDoubleCoda);break;case"Segno":e.addDirection(He.TargetSegno);break;case"SegnoSegno":e.addDirection(He.TargetSegnoSegno);break;case"Fine":e.addDirection(He.TargetFine)}break;case"Jump":switch(s.innerText){case"DaCapo":e.addDirection(He.JumpDaCapo);break;case"DaCapoAlCoda":e.addDirection(He.JumpDaCapoAlCoda);break;case"DaCapoAlDoubleCoda":e.addDirection(He.JumpDaCapoAlDoubleCoda);break;case"DaCapoAlFine":e.addDirection(He.JumpDaCapoAlFine);break;case"DaSegno":e.addDirection(He.JumpDalSegno);break;case"DaSegnoAlCoda":e.addDirection(He.JumpDalSegnoAlCoda);break;case"DaSegnoAlDoubleCoda":e.addDirection(He.JumpDalSegnoAlDoubleCoda);break;case"DaSegnoAlFine":e.addDirection(He.JumpDalSegnoAlFine);break;case"DaSegnoSegno":e.addDirection(He.JumpDalSegnoSegno);break;case"DaSegnoSegnoAlCoda":e.addDirection(He.JumpDalSegnoSegnoAlCoda);break;case"DaSegnoSegnoAlDoubleCoda":e.addDirection(He.JumpDalSegnoSegnoAlDoubleCoda);break;case"DaSegnoSegnoAlFine":e.addDirection(He.JumpDalSegnoSegnoAlFine);break;case"DaCoda":e.addDirection(He.JumpDaCoda);break;case"DaDoubleCoda":e.addDirection(He.JumpDaDoubleCoda)}}}parseFermatas(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"Fermata"===s.localName)this.parseFermata(e,s)}parseFermata(e,t){let s=0,i=new et;for(let e of t.childNodes)if(e.nodeType===rs.Element)switch(e.localName){case"Type":switch(e.innerText){case"Short":i.type=Ge.Short;break;case"Medium":i.type=Ge.Medium;break;case"Long":i.type=Ge.Long}break;case"Length":i.length=parseFloat(e.innerText);break;case"Offset":let t=e.innerText.split("/");if(2===t.length){s=parseInt(t[0])/parseInt(t[1])*te.QuarterTime|0}}e.addFermata(s,i)}parseBars(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"Bar"===t.localName)this.parseBar(t)}parseBar(e){let t=new ee,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"Voices":this._voicesOfBar.set(s,i.innerText.split(" "));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(let t of e.childNodes)if(t.nodeType===rs.Element&&"Voice"===t.localName)this.parseVoice(t)}parseVoice(e){let t=new Ie,s=e.getAttribute("id");for(let t of e.childNodes)if(t.nodeType===rs.Element&&"Beats"===t.localName)this._beatsOfVoice.set(s,t.innerText.split(" "));this._voiceById.set(s,t)}parseBeats(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"Beat"===t.localName)this.parseBeat(t)}parseBeat(e){let t=new Be,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"Notes":this._notesOfBeat.set(s,i.innerText.split(" "));break;case"Rhythm":this._rhythmOfBeat.set(s,i.getAttribute("ref"));break;case"Fadding":switch(i.innerText){case"FadeIn":t.fade=O.FadeIn;break;case"FadeOut":t.fade=O.FadeOut;break;case"VolumeSwell":t.fade=O.VolumeSwell}break;case"Tremolo":switch(i.innerText){case"1/2":t.tremoloSpeed=g.Eighth;break;case"1/4":t.tremoloSpeed=g.Sixteenth;break;case"1/8":t.tremoloSpeed=g.ThirtySecond}break;case"Chord":t.chordId=i.innerText;break;case"Hairpin":switch(i.innerText){case"Crescendo":t.crescendo=p.Crescendo;break;case"Decrescendo":t.crescendo=p.Decrescendo}break;case"Arpeggio":"Up"===i.innerText?t.brushType=u.ArpeggioUp:t.brushType=u.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=We.Up;break;case"Downward":t.preferredBeamDirection=We.Down}break;case"Dynamic":switch(i.innerText){case"PPP":t.dynamics=m.PPP;break;case"PP":t.dynamics=m.PP;break;case"P":t.dynamics=m.P;break;case"MP":t.dynamics=m.MP;break;case"MF":t.dynamics=m.MF;break;case"F":t.dynamics=m.F;break;case"FF":t.dynamics=m.FF;break;case"FFF":t.dynamics=m.FFF}break;case"GraceNotes":switch(i.innerText){case"OnBeat":t.graceType=f.OnBeat;break;case"BeforeBeat":t.graceType=f.BeforeBeat}break;case"Legato":"true"===i.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":let e=new se(0,0);e.value=this.toBendValue(parseFloat(i.getAttribute("originValue"))),e.offset=this.toBendOffset(parseFloat(i.getAttribute("originOffset"))),t.addWhammyBarPoint(e);let a=new se(0,0);a.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),a.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);let r=new se(0,0);r.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),r.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);let n=new se(0,0);n.value=this.toBendValue(parseFloat(i.getAttribute("destinationValue"))),n.offset=this.toBendOffset(parseFloat(i.getAttribute("destinationOffset"))),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=R.Finger;break;case"Thumb":t.golpe=R.Thumb}break;case"Wah":switch(i.innerText){case"Open":t.wahPedal=V.Open;break;case"Closed":t.wahPedal=V.Closed}break;case"UserTransposedPitchStemOrientation":switch(i.innerText){case"Downward":t.preferredBeamDirection=We.Down;break;case"Upward":t.preferredBeamDirection=We.Up}break;case"Timer":t.showTimer=!0,i.innerText.length>0&&(t.timer=parseInt(i.innerText))}this._beatById.set(s,t)}parseBeatLyrics(e){const t=[];for(let s of e.childNodes)if(s.nodeType===rs.Element&&"Line"===s.localName)t.push(s.innerText);return t}parseBeatXProperties(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element&&"XProperty"===s.localName){let e=0;switch(s.getAttribute("id")){case"1124204546":switch(e=parseInt(s.findChildElement("Int").innerText),e){case 1:t.beamingMode=W.ForceMergeWithNext;break;case 2:t.beamingMode=W.ForceSplitToNext}break;case"1124204552":if(e=parseInt(s.findChildElement("Int").innerText),1===e)t.beamingMode!==W.ForceSplitToNext&&(t.beamingMode=W.ForceSplitOnSecondaryToNext);break;case"1124204545":e=parseInt(s.findChildElement("Int").innerText),t.invertBeamDirection=1===e;break;case"687935489":e=parseInt(s.findChildElement("Int").innerText),t.brushDuration=e}}}parseBarXProperties(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element&&"XProperty"===s.localName){if("1124139520"===s.getAttribute("id")){const e=s.findChildElement("Double")??s.findChildElement("Float");t.displayScale=parseFloat(e.innerText)}}}parseMasterBarXProperties(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"XProperty"===s.localName){if("1124073984"===s.getAttribute("id"))e.displayScale=parseFloat(s.findChildElement("Double").innerText)}}parseBeatProperties(e,t){let s=!1,i=null,a=null,r=null,n=null,o=null;for(let h of e.childNodes)if(h.nodeType===rs.Element&&"Property"===h.localName){switch(h.getAttribute("name")){case"Brush":"Up"===h.findChildElement("Direction").innerText?t.brushType=u.BrushUp:t.brushType=u.BrushDown;break;case"PickStroke":"Up"===h.findChildElement("Direction").innerText?t.pickStroke=F.Up:t.pickStroke=F.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=B.Wide;break;case"Slight":t.vibrato=B.Slight}break;case"WhammyBar":s=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":i||(i=new se(0,0)),i.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":i||(i=new se(0,0)),i.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleValue":a=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleOffset1":r=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleOffset2":n=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationValue":o||(o=new se(se.MaxPosition,0)),o.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new se(0,0)),o.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"BarreFret":t.barreFret=parseInt(h.findChildElement("Fret").innerText);break;case"BarreString":switch(h.findChildElement("String").innerText){case"0":t.barreShape=H.Full;break;case"1":t.barreShape=H.Half}break;case"Rasgueado":switch(h.findChildElement("Rasgueado").innerText){case"ii_1":t.rasgueado=G.Ii;break;case"mi_1":t.rasgueado=G.Mi;break;case"mii_1":t.rasgueado=G.MiiTriplet;break;case"mii_2":t.rasgueado=G.MiiAnapaest;break;case"pmp_1":t.rasgueado=G.PmpTriplet;break;case"pmp_2":t.rasgueado=G.PmpAnapaest;break;case"pei_1":t.rasgueado=G.PeiTriplet;break;case"pei_2":t.rasgueado=G.PeiAnapaest;break;case"pai_1":t.rasgueado=G.PaiTriplet;break;case"pai_2":t.rasgueado=G.PaiAnapaest;break;case"ami_1":t.rasgueado=G.AmiTriplet;break;case"ami_2":t.rasgueado=G.AmiAnapaest;break;case"ppp_1":t.rasgueado=G.Ppp;break;case"amii_1":t.rasgueado=G.Amii;break;case"amip_1":t.rasgueado=G.Amip;break;case"eami_1":t.rasgueado=G.Eami;break;case"eamii_1":t.rasgueado=G.Eamii;break;case"peami_1":t.rasgueado=G.Peami}}}s&&(i||(i=new se(0,0)),o||(o=new se(se.MaxPosition,0)),t.addWhammyBarPoint(i),r&&a&&t.addWhammyBarPoint(new se(r,a)),n&&a&&t.addWhammyBarPoint(new se(n,a)),r||n||!a||t.addWhammyBarPoint(new se(se.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"Note"===t.localName)this.parseNote(t)}parseNote(e){let t=new me,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===rs.Element)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=parseInt(i.innerText),t.trillSpeed=g.Sixteenth;break;case"Accent":let e=parseInt(i.innerText);1&e&&(t.isStaccato=!0),4&e&&(t.accentuated=a.Heavy),8&e&&(t.accentuated=a.Normal),16&e&&(t.accentuated=a.Tenuto);break;case"Tie":"true"===i.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(i.innerText){case"Slight":t.vibrato=B.Slight;break;case"Wide":t.vibrato=B.Wide}break;case"LeftFingering":switch(i.innerText){case"P":t.leftHandFinger=y.Thumb;break;case"I":t.leftHandFinger=y.IndexFinger;break;case"M":t.leftHandFinger=y.MiddleFinger;break;case"A":t.leftHandFinger=y.AnnularFinger;break;case"C":t.leftHandFinger=y.LittleFinger}break;case"RightFingering":switch(i.innerText){case"P":t.rightHandFinger=y.Thumb;break;case"I":t.rightHandFinger=y.IndexFinger;break;case"M":t.rightHandFinger=y.MiddleFinger;break;case"A":t.rightHandFinger=y.AnnularFinger;break;case"C":t.rightHandFinger=y.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=parseInt(i.innerText);break;case"Ornament":switch(i.innerText){case"Turn":t.ornament=I.Turn;break;case"InvertedTurn":t.ornament=I.InvertedTurn;break;case"UpperMordent":t.ornament=I.UpperMordent;break;case"LowerMordent":t.ornament=I.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,d=-1;for(let c of e.childNodes)if(c.nodeType===rs.Element&&"Property"===c.localName){switch(c.getAttribute("name")){case"ShowStringNumber":c.findChildElement("Enable")&&(t.showStringNumber=!0);break;case"String":t.string=parseInt(c.findChildElement("String").innerText)+1;break;case"Fret":t.fret=parseInt(c.findChildElement("Fret").innerText);break;case"Element":l=parseInt(c.findChildElement("Element").innerText);break;case"Variation":d=parseInt(c.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(s,!0);break;case"HarmonicType":let e=c.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=b.None;break;case"Natural":t.harmonicType=b.Natural;break;case"Artificial":t.harmonicType=b.Artificial;break;case"Pinch":t.harmonicType=b.Pinch;break;case"Tap":t.harmonicType=b.Tap;break;case"Semi":t.harmonicType=b.Semi;break;case"Feedback":t.harmonicType=b.Feedback}break;case"HarmonicFret":let u=c.findChildElement("HFret");u&&(t.harmonicValue=parseFloat(u.innerText));break;case"Muted":c.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":c.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=parseInt(c.findChildElement("Number").innerText),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=parseInt(c.findChildElement("Step").innerText);break;case"ConcertPitch":this.parseConcertPitch(c,t);break;case"Bended":i=!0;break;case"BendOriginValue":a||(a=new se(0,0)),a.value=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new se(0,0)),a.offset=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleValue":r=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleOffset1":n=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleOffset2":o=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendDestinationValue":h||(h=new se(se.MaxPosition,0)),h.value=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new se(0,0)),h.offset=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"HopoOrigin":c.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":let p=parseInt(c.findChildElement("Flags").innerText);1&p?t.slideOutType=w.Shift:2&p?t.slideOutType=w.Legato:4&p?t.slideOutType=w.OutDown:8&p&&(t.slideOutType=w.OutUp),16&p?t.slideInType=_.IntoFromBelow:32&p&&(t.slideInType=_.IntoFromAbove),64&p?t.slideOutType=w.PickSlideDown:128&p&&(t.slideOutType=w.PickSlideUp)}}i&&(a||(a=new se(0,0)),h||(h=new se(se.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new se(n,r)),o&&r&&t.addBendPoint(new se(o,r)),n||o||!r||t.addBendPoint(new se(se.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==d&&(t.percussionArticulation=pe.articulationFromElementVariation(l,d))}parseConcertPitch(e,t){const s=e.findChildElement("Pitch");if(s)for(let e of s.childNodes)if(e.nodeType===rs.Element&&"Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=S.ForceDoubleSharp;break;case"#":t.accidentalMode=S.ForceSharp;break;case"b":t.accidentalMode=S.ForceFlat;break;case"bb":t.accidentalMode=S.ForceDoubleFlat}}toBendValue(e){return e*_s.BendPointValueFactor|0}toBendOffset(e){return e*_s.BendPointPositionFactor}parseRhythms(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){let t=new bs,s=e.getAttribute("id");t.id=s;for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"NoteValue":switch(s.innerText){case"Long":t.value=g.QuadrupleWhole;break;case"DoubleWhole":t.value=g.DoubleWhole;break;case"Whole":t.value=g.Whole;break;case"Half":t.value=g.Half;break;case"Quarter":t.value=g.Quarter;break;case"Eighth":t.value=g.Eighth;break;case"16th":t.value=g.Sixteenth;break;case"32nd":t.value=g.ThirtySecond;break;case"64th":t.value=g.SixtyFourth;break;case"128th":t.value=g.OneHundredTwentyEighth;break;case"256th":t.value=g.TwoHundredFiftySixth}break;case"PrimaryTuplet":t.tupletNumerator=parseInt(s.getAttribute("num")),t.tupletDenominator=parseInt(s.getAttribute("den"));break;case"AugmentationDot":t.dots=parseInt(s.getAttribute("count"))}this._rhythmById.set(s,t)}buildModel(){for(let e=0,t=this._masterBars.length;e<t;e++){let t=this._masterBars[e];this.score.addMasterBar(t)}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e);this.score.addTrack(t)}for(let e of this._barsOfMasterBar){let t=0;for(let s=0,i=0;s<e.length&&i<this.score.tracks.length;s++){let a=e[s];if(a!==_s.InvalidId){let e=this._barsById.get(a),s=this.score.tracks[i],r=s.staves[t];if(r.addBar(e),this._voicesOfBar.has(a))for(let t of this._voicesOfBar.get(a))if(t!==_s.InvalidId){let s=this._voiceById.get(t);if(e.addVoice(s),this._beatsOfVoice.has(t))for(let e of this._beatsOfVoice.get(t))if(e!==_s.InvalidId){let t=_e.clone(this._beatById.get(e));s.addBeat(t);let 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(let s of this._notesOfBeat.get(e))if(s!==_s.InvalidId){const e=be.clone(this._noteById.get(s));r.isPercussion?(e.fret=-1,e.string=-1):e.percussionArticulation=-1,t.addNote(e),this._tappedNotes.has(s)&&(t.tap=!0)}}}else{let t=new Ie;e.addVoice(t);let s=new Be;s.isEmpty=!0,s.duration=g.Quarter,t.addBeat(s)}t===s.staves.length-1?(i++,t=0):t++}else i++}}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e),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){let s=this.score.masterBars[e];for(let i=0,a=t.length;i<a;i++){let a=t[i];a.type===r.Tempo&&(0===e&&(this.score.tempo=0|a.value,a.text&&(this.score.tempoLabel=a.text)),s.tempoAutomations.push(a))}}}}_s.InvalidId="-1",_s.BendPointPositionFactor=se.MaxPosition/100,_s.BendPointValueFactor=.04;class ws{constructor(){this.isMultiRest=!1,this.trackViewGroups=[]}}class Bs{constructor(){this.showNumbered=!1,this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class Ts{apply(e){if(this.scoreViews.length>0){let t=0;for(let 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++}}}constructor(e){this.scoreViews=[];let t=Oe.fromBuffer(e);const s=Re.readInt32BE(t);for(let e=0;e<s;e++){const e=new ws;this.scoreViews.push(e),e.isMultiRest=ls.gpReadBool(t);const s=Re.readInt32BE(t);for(let i=0;i<s;i++){let s=t.readByte();0===s&&(s=1);let i=new Bs;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=Oe.withCapacity(128),s=[new ws];for(const t of e.tracks){const e=new Bs;e.showStandardNotation=t.staves[0].showStandardNotation,e.showTablature=t.staves[0].showTablature,e.showSlash=t.staves[0].showSlash,e.showNumbered=t.staves[0].showNumbered,s[0].trackViewGroups.push(e);const i=new ws;i.trackViewGroups.push(e),s.push(i)}Re.writeInt32BE(t,s.length);for(const e of s){t.writeByte(e.isMultiRest?1:0),Re.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 Re.writeInt32BE(t,1),t.toArray()}}let ks=class{};class Ns extends ks{constructor(e){super(),this.n=e}}class xs extends ks{constructor(e,t){super(),this.left=e,this.right=t}}class vs extends ks{constructor(e,t){super(),this.n=e,this.table=t}}class Ps{static make(e,t,s,i){let a=[],r=[];if(i>32)throw new Ce("Invalid huffman");for(let e=0;e<i;e++)a.push(0),r.push(0);for(let r=0;r<s;r++){let s=e[r+t];if(s>=i)throw new Ce("Invalid huffman");a[s]++}let n=0;for(let e=1;e<i-1;e++)n=n+a[e]<<1,r[e]=n;let o=new Map;for(let i=0;i<s;i++){let s=e[i+t];if(0!==s){let e=r[s-1];r[s-1]=e+1,o.set(e<<5|s,i)}}return Ps.treeCompress(new xs(Ps.treeMake(o,i,0,1),Ps.treeMake(o,i,1,1)))}static treeMake(e,t,s,i){if(i>t)throw new Ce("Invalid huffman");let a=s<<5|i;return e.has(a)?new Ns(e.get(a)):(s<<=1,i+=1,new xs(Ps.treeMake(e,t,s,i),Ps.treeMake(e,t,1|s,i)))}static treeCompress(e){let t=Ps.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof xs)return new xs(Ps.treeCompress(e.left),Ps.treeCompress(e.right));throw new Ce("assert")}let s=1<<t,i=[];for(let e=0;e<s;e++)i.push(new Ns(-1));return Ps.treeWalk(i,0,0,t,e),new vs(t,i)}static treeWalk(e,t,s,i,a){a instanceof xs&&i>0?(Ps.treeWalk(e,t,s+1,i-1,a.left),Ps.treeWalk(e,t|1<<s,s+1,i-1,a.right)):e[t]=Ps.treeCompress(a)}static treeDepth(e){if(e instanceof Ns)return 0;if(e instanceof vs)throw new Ce("assert");if(e instanceof xs){let t=Ps.treeDepth(e.left),s=Ps.treeDepth(e.right);return 1+(t<s?t:s)}return 0}}var Cs,Es,Fs,Ds,Ls,Ms,Is,As,Rs,Os,Vs,Hs,Gs,Ws,zs,Us,Xs,Js;!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"}(Cs||(Cs={}));class Ys{constructor(){this.buffer=new Uint8Array(Ys.BufferSize),this.pos=0}slide(){let e=new Uint8Array(Ys.BufferSize);this.pos-=Ys.Size,e.set(this.buffer.subarray(Ys.Size,Ys.Size+this.pos),0),this.buffer=e}addBytes(e,t,s){this.pos+s>Ys.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+s),this.pos),this.pos+=s}addByte(e){this.pos===Ys.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}Ys.Size=32768,Ys.BufferSize=65536;class qs{static buildFixedHuffman(){let e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return Ps.make(e,0,288,10)}constructor(e){this._nbits=0,this._bits=0,this._state=Cs.Block,this._isFinal=!1,this._huffman=qs._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new Ys,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 Cs.Head:let e=this._input.readByte();if(8!==(15&e))throw new Ce("Invalid data");let t=this._input.readByte(),s=!!(32&t);if(((e<<8)+t)%31!=0)throw new Ce("Invalid data");if(s)throw new Ce("Unsupported dictionary");return this._state=Cs.Block,!0;case Cs.Crc:return this._state=Cs.Done,!0;case Cs.Done:return!1;case Cs.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:if(this._len=Re.readUInt16LE(this._input),Re.readUInt16LE(this._input)!==65535-this._len)throw new Ce("Invalid data");this._state=Cs.Flat;let e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=qs._fixedHuffman,this._huffdist=null,this._state=Cs.CData,!0;case 2:let t=this.getBits(5)+257,s=this.getBits(5)+1,i=this.getBits(4)+4;for(let e=0;e<i;e++)this._lengths[qs.CodeLengthsPos[e]]=this.getBits(3);for(let e=i;e<19;e++)this._lengths[qs.CodeLengthsPos[e]]=0;this._huffman=Ps.make(this._lengths,0,19,8);let a=[];for(let e=0;e<t+s;e++)a.push(0);return this.inflateLengths(a,t+s),this._huffdist=Ps.make(a,t,s,16),this._huffman=Ps.make(a,0,t,16),this._state=Cs.CData,!0;default:throw new Ce("Invalid data")}case Cs.Flat:{let e=this._len<this._needed?this._len:this._needed,t=Re.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?Cs.Crc:Cs.Block),this._needed>0}case Cs.DistOne:{let e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=Cs.CData),this._needed>0}case Cs.Dist:for(;this._len>0&&this._needed>0;){let 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=Cs.CData),this._needed>0;case Cs.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?Cs.Crc:Cs.Block,!0;{i=i-257&255;let e=qs.LenExtraBitsTbl[i];if(-1===e)throw new Ce("Invalid data");this._len=qs.LenBaseValTbl[i]+this.getBits(e);let t=this._huffdist,s=t?this.applyHuffman(t):this.getRevBits(5);if(e=qs.DistExtraBitsTbl[s],-1===e)throw new Ce("Invalid data");if(this._dist=qs.DistBaseValTbl[s]+this.getBits(e),this._dist>this._window.available())throw new Ce("Invalid data");return this._state=1===this._dist?Cs.DistOne:Cs.Dist,!0}}return!1}addDistOne(e){let 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());let 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;let 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;){let 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:let r=s+3+this.getBits(2);if(r>t)throw new Ce("Invalid data");for(;s<r;)e[s]=i,s++;break;case 17:if(s+=3+this.getBits(3),s>t)throw new Ce("Invalid data");break;case 18:if(s+=11+this.getBits(7),s>t)throw new Ce("Invalid data");break;default:throw new Ce("Invalid data")}}}applyHuffman(e){if(e instanceof Ns)return e.n;if(e instanceof xs)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof vs)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new Ce("Invalid data")}}qs.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],qs.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],qs.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],qs.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],qs.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],qs._fixedHuffman=qs.buildFixedHuffman();class js{constructor(e,t){this.fullName=e;let s=e.lastIndexOf("/");this.fileName=-1===s||s===e.length-1?this.fullName:e.substr(s+1),this.data=t}}js.OptionalDataDescriptorSignature=134695760,js.CompressionMethodDeflate=8,js.LocalFileHeaderSignature=67324752,js.CentralFileHeaderSignature=33639248,js.EndOfCentralDirSignature=101010256;class Ks{constructor(e){this._readable=e}read(){let e=[];for(;;){let t=this.readEntry();if(!t)break;e.push(t)}return e}readEntry(){let e=this._readable;if(Re.readInt32LE(e)!==js.LocalFileHeaderSignature)return null;Re.readUInt16LE(e);let t=Re.readUInt16LE(e),s=Re.readUInt16LE(e),i=0!==s;if(i&&s!==js.CompressionMethodDeflate)return null;Re.readInt16LE(this._readable),Re.readInt16LE(this._readable),Re.readInt32LE(e),Re.readInt32LE(e);let a,r=Re.readInt32LE(e),n=Re.readInt16LE(e),o=Re.readInt16LE(e),h=Re.toString(Re.readByteArray(e,n),"utf-8");if(e.skip(o),i){let e=Oe.empty(),t=new qs(this._readable),s=new Uint8Array(65536);for(;;){let i=t.readBytes(s,0,s.length);if(e.write(s,0,i),i<s.length)break}a=e.toArray()}else a=Re.readByteArray(this._readable,r);if(8&t){Re.readInt32LE(this._readable)===js.OptionalDataDescriptorSignature&&Re.readInt32LE(this._readable),Re.readInt32LE(this._readable),Re.readInt32LE(this._readable)}return new js(h,a)}}class Qs{constructor(){this.trackViewGroups=[]}}class $s{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"}(Es||(Es={}));class Zs{constructor(e,t){this.zoomLevel=4,this.view=Es.PageVertical,this.muiltiVoiceCursor=!1,this.scoreViews=[];const s=Oe.fromBuffer(t);this.zoomLevel=Re.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 Qs;this.scoreViews.push(i);const a=e.scoreViews[t];for(let e=0;e<a.trackViewGroups.length;e++){const e=new $s;e.isVisible=0!=s.readByte(),i.trackViewGroups.push(e)}}}apply(e){if(this.scoreViews.length>0){let t=0;for(let s of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){e.tracks[t].isVisibleOnMultiTrack=s.isVisible}t++}}}static writeForScore(e){const t=Oe.withCapacity(128);Re.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 ei extends j{get name(){return"Guitar Pro 7-8"}constructor(){super()}readScore(){ne.debug(this.name,"Loading ZIP entries");let e,t=new Ks(this.data);try{e=t.read()}catch(e){throw new Q("No Zip archive",e)}ne.debug(this.name,"Zip entries loaded");let s=null,i=null,a=null,r=null;for(let t of e)switch(t.fileName){case"score.gpif":s=Re.toString(t.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=t.data;break;case"PartConfiguration":a=t.data;break;case"LayoutConfiguration":r=t.data}if(!s)throw new Q("No score.gpif found in zip archive");ne.debug(this.name,"Start Parsing score.gpif");let n=new _s;n.parseXml(s,this.settings),ne.debug(this.name,"score.gpif parsed");let o=n.score;if(i){ne.debug(this.name,"Start Parsing BinaryStylesheet"),new us(i).apply(o),ne.debug(this.name,"BinaryStylesheet parsed")}let h=null;if(a&&(ne.debug(this.name,"Start Parsing Part Configuration"),h=new Ts(a),h.apply(o),ne.debug(this.name,"Part Configuration parsed")),r&&null!=h){ne.debug(this.name,"Start Parsing Layout Configuration"),new Zs(h,r).apply(o),ne.debug(this.name,"Layout Configuration parsed")}return o}}class ti extends K{constructor(){super(e.AlphaTabErrorType.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,ti.prototype)}}class si{constructor(e){this._currentByte=0,this._position=si.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 ti;this._position=0}const e=this._currentByte>>si.ByteSize-this._position-1&1;return this._position++,e}readAll(){let e=Oe.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof ti))throw e}return e.toArray()}}si.ByteSize=8;class ii{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class ai{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){let t=new si(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){let s,i=Oe.empty(),a=this.getInteger(e.readBytes(4),0);try{for(;i.length<a;){if(1===e.readBits(1)){let t=e.readBits(4),a=e.readBitsReversed(t),r=e.readBitsReversed(t),n=i.length-a,o=Math.min(a,r);s=i.getBuffer(),i.write(s,n,o)}else{let t=e.readBitsReversed(2);for(let s=0;s<t;s++)i.writeByte(e.readByte())}}}catch(e){if(!(e instanceof ti))throw e}s=i.getBuffer();let r=t?4:0,n=i.length-r,o=new Uint8Array(n),h=n;return o.set(s.subarray(r,r+h),0),o}readBlock(e){let t=this.readHeader(e);if("BCFZ"===t)this.readUncompressedBlock(this.decompress(e,!0));else{if("BCFS"!==t)throw new Q("Unsupported format");this.readUncompressedBlock(e.readAll())}}readUncompressedBlock(e){let t=4096,s=t;for(;s+3<e.length;){if(2===this.getInteger(e,s)){let i=new ii;i.fileName=this.getString(e,s+4,127),i.fileSize=this.getInteger(e,s+140);let a=!this.fileFilter||this.fileFilter(i.fileName);a&&this.files.push(i);let r=s+148,n=0,o=0,h=a?Oe.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));let 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++){let 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]}}ai.HeaderBcFs="BCFS",ai.HeaderBcFz="BCFZ";class ri extends j{get name(){return"Guitar Pro 6"}constructor(){super()}readScore(){ne.debug(this.name,"Loading GPX filesystem");let e=new ai;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration")||e.endsWith("LayoutConfiguration"),e.load(this.data),ne.debug(this.name,"GPX filesystem loaded");let t=null,s=null,i=null,a=null;for(let r of e.files)switch(r.fileName){case"score.gpif":t=Re.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 Q("No score.gpif found in GPX");ne.debug(this.name,"Start Parsing score.gpif");let r=new _s;r.parseXml(t,this.settings),ne.debug(this.name,"score.gpif parsed");let n=r.score;if(s){ne.debug(this.name,"Start Parsing BinaryStylesheet"),new us(s).apply(n),ne.debug(this.name,"BinaryStylesheet parsed")}let o=null;if(i&&(ne.debug(this.name,"Start Parsing Part Configuration"),o=new Ts(i),o.apply(n),ne.debug(this.name,"Part Configuration parsed")),a&&null!=o){ne.debug(this.name,"Start Parsing Layout Configuration"),new Zs(o,a).apply(n),ne.debug(this.name,"Layout Configuration parsed")}return n}}class ni extends j{get name(){return"MusicXML"}constructor(){super(),this._currentPartGroup=null,this._trackFirstMeasureNumber=0,this._maxVoices=0,this._currentDirection=null,this._currentChord=null,this._divisionsPerQuarterNote=0,this._voiceOfStaff=new Map,this._isBeamContinue=!1,this._previousBeatWasPulled=!1,this._previousBeat=null}readScore(){this._trackById=new Map,this._partGroups=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._slurStarts=new Map;let e=this.extractMusicXml(),t=new ys;try{t.parse(e)}catch(e){throw new Q("Unsupported format")}return this._score=new ve,this._score.tempo=120,this.parseDom(t),this.settings.importer.mergePartGroupsInMusicXml&&this.mergePartGroups(),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}extractMusicXml(){const e=new Ks(this.data);let t;try{t=e.read()}catch(e){t=[]}if(0===t.length)return this.data.reset(),Re.toString(this.data.readAll(),this.settings.importer.encoding);const s=t.find((e=>"META-INF/container.xml"===e.fullName));if(!s)throw new Q("No compressed MusicXML");const i=new ys;try{i.parse(Re.toString(s.data,this.settings.importer.encoding))}catch(e){throw new Q("Malformed container.xml, could not parse as XML",e)}let a=i.firstElement;if(!a||"container"!==a.localName)throw new Q("Malformed container.xml, root element not 'container'");const r=a.findChildElement("rootfiles");if(!r)throw new Q("Malformed container.xml, 'container/rootfiles' not found");let n="";for(const e of r.childNodes)if(e.nodeType==rs.Element&&"rootfile"===e.localName){n=e.getAttribute("full-path");break}if(!n)throw new Q("Unsupported compressed MusicXML, missing rootfile");const o=t.find((e=>e.fullName===n));if(!o)throw new Q(`Malformed container.xml, '${n}' not contained in zip`);return Re.toString(o.data,this.settings.importer.encoding)}mergePartGroups(){let e=!1;for(const t of this._partGroups.values())t.length>1&&(this.mergeGroup(t),e=!0);if(e)for(let e=0;e<this._score.tracks.length;e++)this._score.tracks[e].index=e}mergeGroup(e){let t=e[0];for(let s=1;s<e.length;s++){let i=e[s];for(let e of i.staves)t.addStaff(e);let a=this._score.tracks.indexOf(i);this._score.tracks.splice(a,1)}}parseDom(e){let t=e.firstElement;if(!t)throw new Q("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":break;default:throw new Q("Unsupported format")}}parsePartwise(e){for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"work":this.parseWork(t);break;case"movement-title":this._score.title=t.innerText;break;case"identification":this.parseIdentification(t);break;case"part-list":this.parsePartList(t);break;case"part":this.parsePart(t)}}parseWork(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"work-title"===t.localName)this._score.title=t.innerText}parsePart(e){let t=e.getAttribute("id");if(!this._trackById.has(t)){if(1!==this._trackById.size)return;for(const[e,s]of this._trackById)0!==s.staves.length&&0!==s.staves[0].bars.length||(t=e);if(!this._trackById.has(t))return}let s=this._trackById.get(t),i=!0;this._maxVoices=0;for(let t of e.childNodes)if(t.nodeType===rs.Element&&"measure"===t.localName)this.parseMeasure(t,s,i)&&(i=!1);for(let e of s.staves)for(let t of e.bars)this.ensureVoices(t)}parseMeasure(e,t,s){if("yes"===e.getAttribute("implicit")&&0===e.getElementsByTagName("note",!1).length)return!1;let i=0;if(s)this._divisionsPerQuarterNote=0,this._trackFirstMeasureNumber=parseInt(e.getAttribute("number")),this._trackFirstMeasureNumber||(this._trackFirstMeasureNumber=0),i=0;else{if(i=parseInt(e.getAttribute("number")),!i)return!1;i-=this._trackFirstMeasureNumber}if(s){let s=e.getElementsByTagName("attributes",!1);if(s.length>0){let e=s[0].getElementsByTagName("staves",!1);if(e.length>0){let s=parseInt(e[0].innerText);t.ensureStaveCount(s)}}}let a=new Array(t.staves.length),r=null;for(let e=t.staves[0].bars.length;e<=i;e++)for(let e=0;e<t.staves.length;e++){let s=new ee;if(a[e]=s,t.staves[e].bars.length>0){let i=t.staves[e].bars[t.staves[e].bars.length-1];s.clef=i.clef}r=this.getOrCreateMasterBar(i),t.staves[e].addBar(s),this.ensureVoices(s)}let n=new Map;if(r){let s=!1;for(let i of e.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"note":this.parseNoteBeat(i,a);break;case"forward":this.parseForward(i,a);break;case"direction":this.parseDirection(i,r);break;case"attributes":s||(this.parseAttributes(i,a,r,t),s=!0);break;case"harmony":this.parseHarmony(i,t,n);break;case"sound":break;case"barline":this.parseBarline(i,r)}}return!0}ensureVoices(e){for(;e.voices.length<this._maxVoices;){let t=new Ie;e.addVoice(t);let s=new Be;s.isEmpty=!0,s.chordId=this._currentChord,t.addBeat(s)}}getOrCreateBeat(e,t,s){let i=0,a=e.getElementsByTagName("voice",!1);a.length>0&&(i=parseInt(a[0].innerText)-1);let r=this._previousBeatWasPulled;this._previousBeatWasPulled=!1;let n,o,h=e.getElementsByTagName("staff",!1),l=1;if(h.length>0){l=parseInt(h[0].innerText),(this._isBeamContinue||r)&&this._previousBeat.voice.bar.staff.index!==l-1&&(l=this._previousBeat.voice.bar.staff.index+1,this._previousBeatWasPulled=!0);let e=t[0].staff.track.index+"-"+l;this._voiceOfStaff.has(e)||this._voiceOfStaff.set(e,i)}l--,n=l<0?t[0]:l>=t.length?t[t.length-1]:t[l];let d=this.getOrCreateVoice(n,i);return s&&d.beats.length>0||1===d.beats.length&&d.isEmpty?o=d.beats[d.beats.length-1]:(o=new Be,o.isEmpty=!1,d.addBeat(o)),this._isBeamContinue=!1,this._previousBeat=o,o}parseForward(e,t){let s=this.getOrCreateBeat(e,t,!1),i=parseInt(e.findChildElement("duration").innerText)*g.Quarter/this._divisionsPerQuarterNote,a=[g.SixtyFourth,g.ThirtySecond,g.Sixteenth,g.Eighth,g.Quarter,g.Half,g.Whole];for(let e of a)if(i>=e){s.duration=e,i-=e;break}s.isEmpty=!1}parseStaffDetails(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"staff-lines":for(let e of t.staves)e.stringTuning.tunings=new Array(parseInt(s.innerText)).fill(0);break;case"staff-tuning":this.parseStaffTuning(s,t)}for(let e of t.staves)this.isEmptyTuning(e.tuning)&&(e.stringTuning.tunings=[])}parseStaffTuning(e,t){let s=parseInt(e.getAttribute("line")),i="C",a="",r=0;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"tuning-step":i=t.innerText;break;case"tuning-alter":r=parseInt(t.innerText);break;case"tuning-octave":a=t.innerText}let n=de.getTuningForText(i+a)+r;for(let e of t.staves)e.tuning[e.tuning.length-s]=n}parseHarmony(e,t,s){let i=new Te;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"root":i.name=this.parseHarmonyRoot(t);break;case"kind":i.name=i.name+this.parseHarmonyKind(t);break;case"frame":this.parseHarmonyFrame(t,i)}this._currentChord=de.newGuid();const a=i.uniqueId;s.has(a)&&(i.showDiagram=!1);for(let e of t.staves)e.addChord(this._currentChord,i);s.set(a,i)}parseHarmonyRoot(e){let t="",s="";for(let i of e.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"root-step":t=i.innerText;break;case"root-alter":switch(parseInt(e.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{switch(e.innerText){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"}}return s}parseHarmonyFrame(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"frame-strings":const e=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=parseInt(s.innerText);break;case"frame-note":let i=null,a=null;for(let e of s.childNodes)switch(e.localName){case"string":i=parseInt(e.innerText);break;case"fret":a=parseInt(e.innerText),i&&a>=0&&(t.strings[i-1]=a);break;case"barre":i&&a&&"start"===e.getAttribute("type")&&t.barreFrets.push(a)}}}parseBarline(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"repeat":this.parseRepeat(s,t);break;case"ending":this.parseEnding(s,t)}}parseEnding(e,t){let s=parseInt(e.getAttribute("number"));s>0&&(--s,t.alternateEndings=t.alternateEndings|1<<s&255)}parseRepeat(e,t){let s=e.getAttribute("direction"),i=parseInt(e.getAttribute("times"));(i<0||isNaN(i))&&(i=2),"backward"===s?t.repeatCount=i:"forward"===s&&(t.isRepeatStart=!0)}parseNoteBeat(e,t){let s=e.getElementsByTagName("chord",!1).length>0,i=this.getOrCreateBeat(e,t,s);!i.chordId&&this._currentChord&&(i.chordId=this._currentChord,this._currentChord=null),this._currentDirection&&(i.text=this._currentDirection,this._currentDirection=null);let a=new me;i.voice.isEmpty=!1,i.isEmpty=!1,i.addNote(a),i.dots=0;let r=!1;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"grace":i.graceType=f.BeforeBeat,i.duration=g.ThirtySecond;break;case"duration":if(i.isRest&&!r){switch(parseInt(t.innerText)){case 1:i.duration=g.Whole;break;case 2:i.duration=g.Half;break;case 4:default:i.duration=g.Quarter;break;case 8:i.duration=g.Eighth;break;case 16:i.duration=g.Sixteenth;break;case 32:i.duration=g.ThirtySecond;break;case 64:i.duration=g.SixtyFourth}}break;case"tie":this.parseTied(t,a);break;case"cue":case"instrument":case"stem":break;case"type":i.duration=this.getDuration(t.innerText),i.graceType!==f.None&&i.duration<g.Sixteenth&&(i.duration=g.Eighth);break;case"dot":i.dots++;break;case"accidental":this.parseAccidental(t,a);break;case"time-modification":this.parseTimeModification(t,i);break;case"notehead":"yes"===t.getAttribute("parentheses")&&(a.isGhost=!0);break;case"beam":"continue"===t.innerText&&(this._isBeamContinue=!0);break;case"notations":this.parseNotations(t,i,a);break;case"lyric":this.parseLyric(t,i);break;case"pitch":this.parsePitch(t,a);break;case"unpitched":this.parseUnpitched(t,a);break;case"rest":r="yes"===t.getAttribute("measure"),i.isEmpty=!1,i.notes=[],i.duration=g.Whole}if(a.isStringed)for(let e=0;e<i.notes.length;e++)if(i.notes[e].string===a.string&&i.notes[e]!==a){i.removeNote(a);break}}getDuration(e){switch(e){case"256th":case"128th":case"64th":return g.SixtyFourth;case"32nd":return g.ThirtySecond;case"16th":return g.Sixteenth;case"eighth":return g.Eighth;case"quarter":return g.Quarter;case"half":return g.Half;case"long":case"breve":case"whole":return g.Whole}return g.Quarter}parseLyric(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element&&"text"===s.localName)t.text?t.text+=" "+s.innerText:t.text=s.innerText}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=S.ForceSharp;break;case"natural":t.accidentalMode=S.ForceNatural;break;case"flat":t.accidentalMode=S.ForceFlat}}parseTied(e,t){if("start"===e.getAttribute("type"))this._tieStartIds.has(t.id)||(this._tieStartIds.set(t.id,!0),this._tieStarts.push(t));else if("stop"===e.getAttribute("type")&&this._tieStarts.length>0&&!t.isTieDestination){const e=this._tieStarts[0];e.beat.voice.index===t.beat.voice.index&&e.beat.voice.bar.staff.index===t.beat.voice.bar.staff.index&&e.beat.voice.bar.staff.track.index===t.beat.voice.bar.staff.track.index&&(t.isTieDestination=!0,t.tieOrigin=this._tieStarts[0]),this._tieStarts.splice(0,1),this._tieStartIds.delete(t.id)}}parseNotations(e,t,s){for(let i of e.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"articulations":this.parseArticulations(i,s);break;case"tied":this.parseTied(i,s);break;case"slide":case"glissando":"start"===i.getAttribute("type")&&(s.slideOutType=w.Shift);break;case"dynamics":this.parseDynamics(i,t);break;case"technical":this.parseTechnical(i,s);break;case"ornaments":this.parseOrnaments(i,s);break;case"slur":let e=i.getAttribute("number");switch(e||(e="1"),e=t.voice.bar.staff.index+"_"+e,i.getAttribute("type")){case"start":this._slurStarts.set(e,s);break;case"stop":if(this._slurStarts.has(e)){s.isSlurDestination=!0;let t=this._slurStarts.get(e);t.slurDestination=s,s.slurOrigin=t}}}}parseOrnaments(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element&&"tremolo"===s.localName){switch(parseInt(s.innerText)){case 1:t.beat.tremoloSpeed=g.Eighth;break;case 2:t.beat.tremoloSpeed=g.Sixteenth;break;case 3:t.beat.tremoloSpeed=g.ThirtySecond}}}parseTechnical(e,t){let s=[];for(let i of e.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"string":t.string=parseInt(i.innerText),-2147483648!==t.string&&(t.string=t.beat.voice.bar.staff.tuning.length-t.string+1);break;case"fret":t.fret=parseInt(i.innerText);break;case"down-bow":t.beat.pickStroke=F.Down;break;case"up-bow":t.beat.pickStroke=F.Up;break;case"bend":s.push(i)}s.length>0&&this.parseBends(s,t),-2147483648!==t.string&&-2147483648!==t.fret||(t.string=-1,t.fret=-1)}parseBends(e,t){let s=se.MaxPosition/e.length,i=0,a=0,r=!0;for(let n of e){let e=n.findChildElement("bend-alter");if(e){let o=Math.round(2*Math.abs(parseFloat(e.innerText)));n.findChildElement("pre-bend")?r?(i+=o,t.addBendPoint(new se(a,i)),a+=s,t.addBendPoint(new se(a,i)),r=!1):a+=s:n.findChildElement("release")?(r&&(i+=o),t.addBendPoint(new se(a,i)),a+=s,i-=o,t.addBendPoint(new se(a,i)),r=!1):(t.addBendPoint(new se(a,i)),i+=o,a+=s,t.addBendPoint(new se(a,i)),r=!1)}}}parseArticulations(e,t){for(let s of e.childNodes)switch(s.localName){case"accent":t.accentuated=a.Normal;break;case"strong-accent":t.accentuated=a.Heavy;break;case"staccato":case"detached-legato":t.isStaccato=!0;break;case"tenuto":t.accentuated=a.Tenuto}}parseDynamics(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"p":t.dynamics=m.P;break;case"pp":t.dynamics=m.PP;break;case"ppp":t.dynamics=m.PPP;break;case"f":t.dynamics=m.F;break;case"ff":t.dynamics=m.FF;break;case"fff":t.dynamics=m.FFF;break;case"mp":t.dynamics=m.MP;break;case"mf":t.dynamics=m.MF}}parseTimeModification(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"actual-notes":t.tupletNumerator=parseInt(s.innerText);break;case"normal-notes":t.tupletDenominator=parseInt(s.innerText)}}parseUnpitched(e,t){let s="",i=0,a=0;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"display-step":s=t.innerText;break;case"display-alter":i=parseInt(t.innerText);break;case"display-octave":a=parseInt(t.innerText)}let r=12*a+de.getToneForText(s).noteValue+i;t.octave=r/12|0,t.tone=r-12*t.octave}parsePitch(e,t){let s="",i=0,a=0;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"step":s=t.innerText;break;case"alter":i=parseFloat(t.innerText),isNaN(i)&&(i=0);break;case"octave":a=parseInt(t.innerText)+1}let r=12*a+de.getToneForText(s).noteValue+(0|i);t.octave=r/12|0,t.tone=r-12*t.octave}getOrCreateVoice(e,t){if(t<e.voices.length)return e.voices[t];for(let s=e.voices.length;s<=t;s++)e.addVoice(new Ie);return this._maxVoices=Math.max(this._maxVoices,e.voices.length),e.voices[t]}parseDirection(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"sound":let e=s.getAttribute("tempo");if(e){let s=new $;s.isLinear=!0,s.type=r.Tempo,s.value=parseInt(e),t.tempoAutomations.push(s),0===t.index&&(t.score.tempo=s.value)}break;case"direction-type":let i=s.firstElement;switch(i.localName){case"words":this._currentDirection=i.innerText;break;case"metronome":this.parseMetronome(i,t)}}}parseMetronome(e,t){let s=g.Quarter,i=120;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"beat-unit":s=this.getDuration(t.innerText);break;case"per-minute":i=parseInt(t.innerText)}let a=new $;a.type=r.Tempo,a.value=i*(s/4)|0,this.hasSameTempo(t,a)||(t.tempoAutomations.push(a),0===t.index&&(t.score.tempo=a.value))}hasSameTempo(e,t){for(const s of e.tempoAutomations)if(t.ratioPosition===s.ratioPosition&&t.value==s.value)return!0;return!1}parseAttributes(e,t,s,i){let a=0,r=!1;for(let n of e.childNodes)if(n.nodeType===rs.Element)switch(n.localName){case"divisions":this._divisionsPerQuarterNote=parseInt(n.innerText);break;case"key":this.parseKey(n,s);break;case"time":this.parseTime(n,s),r=!0;break;case"clef":a=parseInt(n.getAttribute("number")),isNaN(a)&&(a=1),this.parseClef(n,t[a-1]);break;case"staff-details":this.parseStaffDetails(n,i);break;case"transpose":this.parseTranspose(n,i)}r||(s.timeSignatureCommon=!0)}parseTranspose(e,t){let s=0;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"chromatic":s+=parseInt(t.innerText);break;case"octave-change":s+=12*parseInt(t.innerText)}for(let e of t.staves)e.transpositionPitch=s}parseClef(e,t){let s="s",i=0;for(let a of e.childNodes)if(a.nodeType===rs.Element)switch(a.localName){case"sign":s=a.innerText.toLowerCase();break;case"line":i=parseInt(a.innerText);break;case"clef-octave-change":switch(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){"common"===e.getAttribute("symbol")&&(t.timeSignatureCommon=!0);let s=!1,i=!1;for(let a of e.childNodes)if(a.nodeType===rs.Element){let e=a.innerText;switch(a.localName){case"beats":s||(-1===e.indexOf("+")?t.timeSignatureNumerator=parseInt(e):t.timeSignatureNumerator=4,s=!0);break;case"beat-type":i||(-1===e.indexOf("+")?t.timeSignatureDenominator=parseInt(e):t.timeSignatureDenominator=4,i=!0)}}}parseKey(e,t){let s=-2147483648,i="";for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"fifths":s=parseInt(t.innerText);break;case"key-step":case"key-alter":break;case"mode":i=t.innerText}t.keySignature=-7<=s&&s<=7?s:P.C,t.keySignatureType="minor"===i?C.Minor:C.Major}getOrCreateMasterBar(e){if(e<this._score.masterBars.length)return this._score.masterBars[e];for(let t=this._score.masterBars.length;t<=e;t++){let e=new oe;if(this._score.masterBars.length>0){let t=this._score.masterBars[this._score.masterBars.length-1];e.timeSignatureDenominator=t.timeSignatureDenominator,e.timeSignatureNumerator=t.timeSignatureNumerator,e.keySignature=t.keySignature,e.keySignatureType=t.keySignatureType}this._score.addMasterBar(e)}return this._score.masterBars[e]}parseIdentification(e){for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"creator":"composer"===t.getAttribute("type")&&(this._score.music=t.innerText);break;case"rights":this._score.copyright&&(this._score.copyright+="\n"),this._score.copyright+=t.innerText}}parsePartList(e){for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"part-group":this.parsePartGroup(t);break;case"score-part":this.parseScorePart(t)}}parsePartGroup(e){switch(e.getAttribute("type")){case"start":this._currentPartGroup=e.getAttribute("number"),this._partGroups.set(this._currentPartGroup,[]);break;case"stop":this._currentPartGroup=null}}parseScorePart(e){let t=e.getAttribute("id"),s=new Me;s.ensureStaveCount(1),s.staves[0].showStandardNotation=!0,this._trackById.set(t,s),this._score.addTrack(s),this._currentPartGroup&&this._partGroups.get(this._currentPartGroup).push(s);for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"part-name":s.name=t.innerText;break;case"part-abbreviation":s.shortName=t.innerText;break;case"midi-instrument":this.parseMidiInstrument(t,s)}this.isEmptyTuning(s.staves[0].tuning)&&(s.staves[0].stringTuning.tunings=[])}isEmptyTuning(e){if(!e)return!0;for(let t=0;t<e.length;t++)if(0!==e[t])return!1;return!0}parseMidiInstrument(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"midi-channel":t.playbackInfo.primaryChannel=parseInt(s.innerText);break;case"midi-program":t.playbackInfo.program=parseInt(s.innerText);break;case"volume":t.playbackInfo.volume=Math.floor(parseInt(s.innerText)/100*16);break;case"pan":t.playbackInfo.balance=Math.max(0,Math.min(16,Math.floor((parseInt(s.innerText)+90)/180*16)))}}}class oi{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event.type==Ke.AlphaTabMetronome}static newMetronomeEvent(e,t,s,i,a){const r=new ut(0,t,s,i,a);return new oi(e,r)}}class hi{constructor(e,t,s){this.bpm=e,this.ticks=t,this.time=s}}class li{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=te.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class di{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 li,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){let e=this._synthesizer.metronomeVolume;this._synthesizer.noteOffAll(!0),this._synthesizer.resetSoft(),this._synthesizer.setupMetronomeChannel(e)}this.mainSilentProcess(e)}}mainSilentProcess(e){if(e<=0)return;let 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(Ve.MicroBufferSize);this._mainState.currentTime=s;let i=Date.now()-t;ne.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 li;this.percussionKeys.add(Ve.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,d=0;for(let c of e.events){let u=new oi(t.synthData.length,c);t.synthData.push(u);let p=c.tick-d;if(i+=p,a+=p*(6e4/(s*e.division)),u.time=a,d=c.tick,n>0)for(;h<i;){let e=oi.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(c.type===Ke.TempoChange){s=6e7/c.microSecondsPerQuarterNote,t.tempoChanges.push(new hi(s,i,a)),o=n*(6e4/(s*e.division))}else if(c.type===Ke.TimeSignature){let i=c,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(c.type===Ke.ProgramChange){const e=c;let s=e.channel;t.firstProgramEventPerChannel.has(s)||t.firstProgramEventPerChannel.set(s,u);s===Ve.PercussionChannel||this.instrumentPrograms.add(e.program)}else if(c.type==Ke.NoteOn){const e=c;e.channel===Ve.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=Ve.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 li;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 hi(t,0,0));let a=e.division*(4/i)|0,r=a*(6e4/(t*this._mainState.division)),n=0,o=0;for(let t=0;t<s;t++){let s=oi.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"}(Fs||(Fs={}));class ci{constructor(e,t){this.state=e,this.stopped=t}}class ui{constructor(e,t,s,i,a){this.currentTime=e,this.endTime=t,this.currentTick=s,this.endTick=i,this.isSeek=a}}class pi{constructor(){this.id="",this.size=0}static load(e,t,s){if(e&&pi.HeaderSize>e.size)return!1;if(s.position+pi.HeaderSize>=s.length)return!1;if(t.id=Re.read8BitStringLength(s,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=Re.readUInt32LE(s),e&&pi.HeaderSize+t.size>e.size)return!1;e&&(e.size-=pi.HeaderSize+t.size);let i="RIFF"===t.id,a="LIST"===t.id;return(!i||!e)&&(!i&&!a||(t.id=Re.read8BitStringLength(s,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}pi.HeaderSize=8;class gi{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"}(Ds||(Ds={}));class mi{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==Re.readInt32LE(this._readable))return!0;this._readable.position-=3}return!1}readPage(t){const s=this._readable.readByte();if(-1===s||0!==s)return!1;const i=this._readable.readByte(),a=Re.readInt64LE(this._readable);this._readable.skip(4),this._readable.skip(4),this._readable.skip(4);const r=this._readable.readByte();if(-1==r)return!1;const n=[];let o=0;for(let e=0;e<r;e++){const e=this._readable.readByte();o==n.length&&n.push(0),n[o]+=e,e<255&&o++}for(let s=0;s<n.length;s++){const r=new Uint8Array(n[s]);if(this._readable.read(r,0,r.length)!=r.length)return!1;if(i&Ds.ContinuesPacket){if(0==t.length)throw new K(e.AlphaTabErrorType.Format,"OGG: Continuation page without any previous packets");t[t.length-1].addData(r)}else{const e=new gi(r,!!(i&Ds.BeginningOfStream)&&0==s,!!(i&Ds.EndOfStream)&&s==n.length-1,a);t.push(e)}}return!0}}class fi{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 yi{constructor(){this.value=0,this.bitsRead=0}}class bi{constructor(e){this._bitBucket=0n,this._bitCount=0n,this._overflowBits=0n,this._source=e}readByte(){return this.readBits(bi.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(t){if(t<0||t>32)throw new K(e.AlphaTabErrorType.General,"IO: Cannot read more than 32 bits in one go");if(0==t)return new yi;const s=new yi;for(;this._bitCount<t;){const e=BigInt(this._source.readByte());if(-1n==e)return s.bitsRead=Number(this._bitCount),s.value=Number(this._bitBucket),this._bitBucket=0n,this._bitCount=0n,s;this._bitBucket=(0xffn&e)<<this._bitCount|this._bitBucket,this._bitCount+=8n,this._bitCount>32&&(this._overflowBits=e>>40n-this._bitCount&0xffn)}let i=this._bitBucket;return t<64&&(i&=(1n<<BigInt(t))-1n),s.value=Number(i),s.bitsRead=t,s}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)}}}}bi.ByteSize=8;class Si{constructor(){this.codebooks=[],this.timeDomainTransforms=[],this.floors=[],this.residues=[],this.mappings=[],this.modes=[]}}class _i{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 wi{constructor(e){this._data=e}get(e){return this._data[e]}}class Bi{get(e){return e}}Bi.instance=new Bi;class Ti{constructor(t,s){this._maxBits=0,this._overflowList=null,this._prefixList=null,this._prefixBitLength=0,this.dimensions=0,this.entries=0,this.mapType=0;if(5653314!=t.readBits(24))throw new K(e.AlphaTabErrorType.Format,"Vorbis: Book header had invalid signature!");this.dimensions=t.readBits(16),this.entries=t.readBits(24),this._lengths=new Int32Array(this.entries),this.initTree(t,s),this.initLookupTable(t)}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(t,s){let i,a,r=0;if(t.readBit()){let e=t.readBits(5)+1;for(let s=0;s<this.entries;){let i=t.readBits(_i.ilog(this.entries-s));for(;--i>=0;)this._lengths[s++]=e;++e}r=0,i=!1,a=e}else{a=-1,i=t.readBit();for(let e=0;e<this.entries;e++)!i||t.readBit()?(this._lengths[e]=t.readBits(5)+1,++r):this._lengths[e]=-1,this._lengths[e]>a&&(a=this._lengths[e])}if(this._maxBits=a,a>-1){let t,a=null;i&&r>=this.entries>>2&&(a=new Int32Array(this.entries),a.set(this._lengths.subarray(0,this.entries),0),i=!1),t=i?r:0;let n=null,o=null;if(i?0!=t&&(a=new Int32Array(t),o=new Int32Array(t),n=new Int32Array(t)):o=new Int32Array(this.entries),!this.computeCodewords(i,o,a,this._lengths,this.entries,n))throw new K(e.AlphaTabErrorType.Format,"Vorbis: Failed to compute codewords");const h=null==n?Bi.instance:new wi(n);s.generateTable(h,a??this._lengths,o),this._prefixList=s.prefixTree,this._prefixBitLength=s.tableBits,this._overflowList=s.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;let o=n[a];if(n[a]=0,this.addEntry(e,t,s,_i.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=_i.convertFromVorbisFloat32(e.readBits(32)),s=_i.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 d=o[e/h%r|0]*s+t+i;n[e*this.dimensions+l]=d,a&&(i=d),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 ki{constructor(){this.value=0,this.length=0,this.bits=0,this.mask=0}}class Ni{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 ki;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>Ni.MAX_TABLE_BITS?Ni.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}}Ni.MAX_TABLE_BITS=10;class xi{constructor(e){e.readBits(16)}}class vi{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 Pi{constructor(t,s,i,a){if(this._order=t.readBits(8),this._rate=t.readBits(16),this._bark_map_size=t.readBits(16),this._ampBits=t.readBits(6),this._ampOfs=t.readBits(8),this._books=new Array(t.readBits(4)+1),this._order<1||this._rate<1||this._bark_map_size<1||0==this._books.length)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Floor0 Data");this._ampDiv=(1<<this._ampBits)-1;for(let s=0;s<this._books.length;s++){const i=t.readBits(8);if(i<0||i>=a.length)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Floor0 Data");const r=a[i];if(0==r.mapType||r.dimensions<1)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Floor0 Data");this._books[s]=r}this._bookBits=_i.ilog(this._books.length),this._barkMaps=new Map([[s,this.synthesizeBarkCurve(s/2)],[i,this.synthesizeBarkCurve(i/2)]]),this._wMap=new Map([[s,this.synthesizeWDelMap(s/2)],[i,this.synthesizeWDelMap(i/2)]])}synthesizeBarkCurve(e){const t=this._bark_map_size/Pi.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(Pi.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){var i=new vi(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;var 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,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 Ci{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 Ei{constructor(t,s){let i=-1;this._partitionClass=new Int32Array(t.readBits(5));for(let e=0;e<this._partitionClass.length;e++)this._partitionClass[e]=t.readBits(4),this._partitionClass[e]>i&&(i=this._partitionClass[e]);++i,this._classDimensions=new Int32Array(i),this._classSubclasses=new Int32Array(i),this._classMasterbooks=new Array(i),this._classMasterBookIndex=new Int32Array(i),this._subclassBooks=new Array(i),this._subclassBookIndex=new Array(i);for(let e=0;e<i;e++){this._classDimensions[e]=t.readBits(3)+1,this._classSubclasses[e]=t.readBits(2),this._classSubclasses[e]>0&&(this._classMasterBookIndex[e]=t.readBits(8),this._classMasterbooks[e]=s[this._classMasterBookIndex[e]]),this._subclassBooks[e]=new Array(1<<this._classSubclasses[e]),this._subclassBookIndex[e]=new Int32Array(this._subclassBooks[e].length);for(let i=0;i<this._subclassBooks[e].length;i++){const a=t.readBits(8)-1;a>=0&&(this._subclassBooks[e][i]=s[a]),this._subclassBookIndex[e][i]=a}}this._multiplier=t.readBits(2),this._range=Ei._rangeLookup[this._multiplier],this._yBits=Ei._yBitsLookup[this._multiplier],++this._multiplier;const a=t.readBits(4),r=[];r.push(0),r.push(1<<a);for(let e=0;e<this._partitionClass.length;e++){const s=this._partitionClass[e];for(let e=0;e<this._classDimensions[s];e++)r.push(t.readBits(a))}this._xList=new Int32Array(r),this._lNeigh=new Int32Array(r.length),this._hNeigh=new Int32Array(r.length),this._sortIdx=new Int32Array(r.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 t=0;t<this._sortIdx.length-1;t++)for(let s=t+1;s<this._sortIdx.length;s++){if(this._xList[t]==this._xList[s])throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Floor1 Data");if(this._xList[this._sortIdx[t]]>this._xList[this._sortIdx[s]]){const e=this._sortIdx[t];this._sortIdx[t]=this._sortIdx[s],this._sortIdx[s]=e}}}unpack(e,t,s){var i=new Ci;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,h=i.posts[0]*this._multiplier;for(let l=1;l<i.postCount;l++){var r=this._sortIdx[l];if(e[r]){var n=this._xList[r],o=i.posts[r]*this._multiplier;t<a&&this.renderLineMulti(t,h,Math.min(n,a),o,s),t=n,h=o}if(t>=a)break}t<a&&this.renderLineMulti(t,h,a,h,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 d;d=h<l?2*h:2*l,0!=o?(t[a]=!0,t[r]=!0,t[i]=!0,s[i]=o>=d?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){var 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 d=e,c=t,u=-n;for(a[e]*=Ei.inverse_dB_table[t],o-=Math.abs(l)*n;++d<s;)c+=l,u+=o,u>=0&&(u-=n,c+=h),a[d]*=Ei.inverse_dB_table[c]}}Ei._rangeLookup=[256,128,86,64],Ei._yBitsLookup=[8,7,7,6],Ei.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 Fi{constructor(t,s,i,a){const r=t.readBits(16);switch(r){case 0:this.floor=new Pi(t,s,i,a);break;case 1:this.floor=new Ei(t,a);break;default:throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Floor type: "+r)}}apply(e,t,s){this.floor.apply(e,t,s)}unpack(e,t,s){return this.floor.unpack(e,t,s)}}class Di{constructor(t,s,i){this._begin=t.readBits(24),this._end=t.readBits(24),this._partitionSize=t.readBits(24)+1,this._classifications=t.readBits(6)+1,this._classBook=i[t.readBits(8)],this._cascade=new Int32Array(this._classifications);let a=0;for(let e=0;e<this._classifications;e++){const s=t.readBits(3);t.readBit()?this._cascade[e]=t.readBits(5)<<3|s:this._cascade[e]=s,a+=Di.icount(this._cascade[e])}const r=new Int32Array(a);for(let s=0;s<a;s++)if(r[s]=t.readBits(8),0==i[r[s]].mapType)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Residue 0");const n=this._classBook.entries;let o=this._classBook.dimensions,h=1;for(;o>0;){if(h*=this._classifications,h>n)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Residue 0");--o}this._books=new Array(this._classifications),a=0;let l,d=0;for(let e=0;e<this._classifications;e++)if(l=_i.ilog(this._cascade[e]),this._books[e]=new Array(l),l>0){d=Math.max(d,l);for(let t=0;t<l;t++)(this._cascade[e]&1<<t)>0&&(this._books[e][t]=i[r[a++]])}this._maxStages=d,this._decodeMap=new Array(h);for(let e=0;e<h;e++){let t=e,s=h/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=s}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 d=r[l][n][o];if(this._cascade[d]&1<<s){const r=this._books[d][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 Li extends Di{constructor(e,t,s){super(e,t,s)}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 Mi extends Di{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 Ii{constructor(t,s,i){const a=t.readBits(16);switch(a){case 0:this.residue=new Di(t,s,i);break;case 1:this.residue=new Li(t,s,i);break;case 2:this.residue=new Mi(t,s,i);break;default:throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Residue type: "+a)}}decode(e,t,s,i){this.residue.decode(e,t,s,i)}}class Ai{constructor(t,s,i,a,r){if(0!==t.readBits(16))throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid mapping type!");let n=1;t.readBit()&&(n+=t.readBits(4));let o=0;t.readBit()&&(o=t.readBits(8)+1);const h=_i.ilog(s-1);this._couplingAngle=new Int32Array(o),this._couplingMangitude=new Int32Array(o);for(let i=0;i<o;i++){const a=t.readBits(h),r=t.readBits(h);if(a==r||a>s-1||r>s-1)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid magnitude or angle in mapping header!");this._couplingAngle[i]=r,this._couplingMangitude[i]=a}if(0!=t.readBits(2))throw new K(e.AlphaTabErrorType.Format,"Vorbis: Reserved bits not 0 in mapping header.");const l=new Int32Array(s);if(n>1)for(let i=0;i<s;i++)if(l[i]=t.readBits(4),l[i]>n)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid channel mux submap index in mapping header!");this._submapFloor=new Array(n),this._submapResidue=new Array(n);for(let s=0;s<n;s++){t.skipBits(8);const r=t.readBits(8);if(r>=i.length)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid floor number in mapping header!");const n=t.readBits(8);if(n>=a.length)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid residue number in mapping header!");this._submapFloor[s]=i[r],this._submapResidue[s]=a[n]}this._channelFloor=new Array(s),this._channelResidue=new Array(s);for(let e=0;e<s;e++)this._channelFloor[e]=this._submapFloor[l[e]],this._channelResidue[e]=this._submapResidue[l[e]];this._mdct=r}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(var n=0;n<i;n++){let e,s;const i=t[n],r=a[n];i>0?r>0?(e=i,s=i-r):(s=i,e=i+r):r>0?(e=i,s=i+r):(s=i,e=i-r),t[n]=e,a[n]=s}}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 Ri{constructor(){this.packetStartIndex=0,this.packetTotalLength=0,this.packetValidLength=0}}class Oi{constructor(){this.overlapInfo=new Ri,this.windowIndex=0}}class Vi{constructor(e=null){this.samplePosition=null,this.samplePosition=e}}class Hi{constructor(t,s,i,a,r){if(this._overlapInfo=null,this._channels=s,this._blockFlag=t.readBit(),0!=t.readBits(32))throw new K(e.AlphaTabErrorType.Format,"Vorbis: Mode header had invalid window or transform type!");const n=t.readBits(8);if(n>=r.length)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Mode header had invalid mapping index!");this._mapping=r[n],this._blockFlag?(this._blockSize=a,this._windows=[Hi.calcWindow(i,a,i),Hi.calcWindow(a,a,i),Hi.calcWindow(i,a,a),Hi.calcWindow(a,a,a)],this._overlapInfo=[Hi.calcOverlap(i,a,i),Hi.calcOverlap(a,a,i),Hi.calcOverlap(i,a,a),Hi.calcOverlap(a,a,a)]):(this._blockSize=i,this._windows=[Hi.calcWindow(i,i,i)])}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 Oi;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*Hi.M_PI2);t*=t,i[n+e]=Math.sin(t*Hi.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*Hi.M_PI2);t*=t,i[o+e]=Math.sin(t*Hi.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 Ri;return o.packetStartIndex=a,o.packetValidLength=n,o.packetTotalLength=r,o}}Hi.M_PI2=1.57079632695;class Gi{constructor(e){this._n=e,this._n2=e>>1,this._n4=this._n2>>1,this._n8=this._n4>>1,this._ld=_i.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*Gi.M_PI/e),this._a[s+1]=-Math.sin(4*t*Gi.M_PI/e),this._b[s]=.5*Math.cos((s+1)*Gi.M_PI/e/2),this._b[s+1]=.5*Math.sin((s+1)*Gi.M_PI/e/2);for(t=0,s=0;t<this._n8;++t,s+=2)this._c[s]=Math.cos(2*(s+1)*Gi.M_PI/e),this._c[s+1]=-Math.sin(2*(s+1)*Gi.M_PI/e);this._bitrev=new Uint16Array(this._n8);for(let e=0;e<this._n8;++e)this._bitrev[e]=Ae.int32ToUint16(_i.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,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}}for(var r=0,n=0,o=this._n2-4;n<o;){let e,t,i,a,h,l;e=s[n]-s[o+2],t=s[n+1]+s[o+3],i=this._c[r+1]*e+this._c[r]*t,a=this._c[r+1]*t-this._c[r]*e,h=s[n]+s[o+2],l=s[n+1]-s[o+3],s[n]=h+i,s[n+1]=l+a,s[o+2]=h-i,s[o+3]=a-l,e=s[n+2]-s[o],t=s[n+3]+s[o+1],i=this._c[r+3]*e+this._c[r+2]*t,a=this._c[r+3]*t-this._c[r+2]*e,h=s[n+2]+s[o],l=s[n+3]-s[o+1],s[n+2]=h+i,s[n+3]=l+a,s[o]=h-i,s[o+1]=a-l,r+=4,n+=4,o-=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,d,c;c=i[s+6]*this._b[t+7]-i[s+7]*this._b[t+6],d=-i[s+6]*this._b[t+6]-i[s+7]*this._b[t+7],e[a]=c,e[r+3]=-c,e[n]=d,e[o+3]=d,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,c=i[s+2]*this._b[t+3]-i[s+3]*this._b[t+2],d=-i[s+2]*this._b[t+2]-i[s+3]*this._b[t+3],e[a+2]=c,e[r+1]=-c,e[n+2]=d,e[o+1]=d,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){var 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){var o=this._a[a],h=this._a[a+1],l=this._a[a+r],d=this._a[a+r+1],c=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*d,t[b-3]=f*l+m*d,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*c-f*u,t[b-5]=f*c+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){let s,i,a,r,n,o,h,l;s=e[t]-e[t-4],n=e[t]+e[t-4],h=e[t-2]+e[t-6],a=e[t-2]-e[t-6],e[t]=n+h,e[t-2]=n-h,r=e[t-3]-e[t-7],e[t-4]=s+r,e[t-6]=s-r,i=e[t-1]-e[t-5],o=e[t-1]+e[t-5],l=e[t-3]+e[t-7],e[t-1]=o+l,e[t-3]=o-l,e[t-5]=i-a,e[t-7]=i+a}}Gi.M_PI=3.141592653589793;class Wi{constructor(){this._setupCache=new Map}reverse(e,t){let s;this._setupCache.has(t)?s=this._setupCache.get(t):(s=new Gi(t),this._setupCache.set(t,s)),s.calcReverse(e)}}class zi{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=_i.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?(zi.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 Vi(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 Ui;let t=null;if(this._packetIndex>=this._packets.length)e.isEndOfStream=!0;else{t=this._packets[this._packetIndex++];const s=new bi(Oe.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 Ui{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"}(Ls||(Ls={}));class Xi{constructor(e){this._packetIndex=-1,this._packets=e}read(){let e;for(;;){if(e=this.nextPacket(),null==e)return null;if(e.isBeginningOfStream){var 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 fi;if(!this.readIdentificationHeader(t,e))return null;if(!this.readComments(this.nextPacket()))return null;const s=new Si;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 zi(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<Xi.VorbisHeaderMarker.length;e++)if(s[1+e]!==Xi.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<Xi.VorbisHeaderMarker.length;e++)if(s[1+e]!==Xi.VorbisHeaderMarker[e])return!1;return!0}readIdentificationHeader(e,t){const s=Oe.fromBuffer(t.packetData);if(!this.comonHeaderDecode(Ls.IdentificationHeader,s))return!1;if(0!=Re.readUInt32LE(s))return!1;if(e.audioChannels=s.readByte(),e.audioSampleRate=Re.readUInt32LE(s),e.audioChannels<=0||e.audioSampleRate<=0)return!1;e.bitrateMaximum=Re.readInt32LE(s),e.bitrateNominal=Re.readInt32LE(s),e.bitrateMinimum=Re.readInt32LE(s);var i=s.readByte();if(e.blocksize0=1<<(15&i),e.blocksize1=1<<(i>>4),e.blocksize0>e.blocksize1||!Xi.isAllowedBlockSize(e.blocksize0)||!Xi.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;var t=Oe.fromBuffer(e.packetData);if(!this.comonHeaderDecode(Ls.Comment,t))return!1;const s=Re.readUInt32LE(t);t.skip(s);var i=Re.readUInt32LE(t);for(let e=0;e<i;e++){const e=Re.readUInt32LE(t);t.skip(e)}return 0!=t.readByte()}readSetupHeader(e,t,s){if(null==s)return!1;const i=new bi(Oe.fromBuffer(s.packetData)),a=new Wi,r=new Ni;if(!this.comonHeaderDecodeBit(Ls.SetupHeader,i))return!1;let n=i.readByte()+1;for(let e=0;e<n;e++)t.codebooks.push(new Ti(i,r));n=i.readBits(6)+1;for(let e=0;e<n;e++)t.timeDomainTransforms.push(new xi(i));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.floors.push(new Fi(i,e.blocksize0,e.blocksize1,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.residues.push(new Ii(i,e.audioChannels,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.mappings.push(new Ai(i,e.audioChannels,t.floors,t.residues,a));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.modes.push(new Hi(i,e.audioChannels,e.blocksize0,e.blocksize1,t.mappings));return!!i.readBit()}}Xi.VorbisHeaderMarker=new Uint8Array(["v".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"b".charCodeAt(0),"i".charCodeAt(0),"s".charCodeAt(0)]);class Ji{constructor(e){this.streams=[];for(var t=new mi(e).read(),s=new Xi(t);;){let e=s.read();if(null==e)break;this.streams.push(e)}}}class Yi{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 Ji(Oe.fromBuffer(r)).streams[0].samples}else{let e=new Int16Array(r.buffer);a=new Float32Array(e.length);for(let t=0;t<e.length;t++)a[t]=e[t]/32767}return this._sampleCache.set(i,a),a}return this._sampleCache.get(i)}load(e){const t=new pi,s=new pi;if(!pi.load(null,t,e)||"sfbk"!==t.id)throw new Ce("Soundfont is not a valid Soundfont2 file");for(;pi.load(t,s,e);){let t=new pi;if("pdta"===s.id)for(;pi.load(s,t,e);)switch(t.id){case"phdr":for(let s=0,i=t.size/ea.SizeInFile|0;s<i;s++)this.phdrs.push(new ea(e));break;case"pbag":for(let s=0,i=t.size/$i.SizeInFile|0;s<i;s++)this.pbags.push(new $i(e));break;case"pmod":for(let s=0,i=t.size/ta.SizeInFile|0;s<i;s++)this.pmods.push(new ta(e));break;case"pgen":for(let s=0,i=t.size/Zi.SizeInFile|0;s<i;s++)this.pgens.push(new Zi(e));break;case"inst":for(let s=0,i=t.size/Qi.SizeInFile|0;s<i;s++)this.insts.push(new Qi(e));break;case"ibag":for(let s=0,i=t.size/qi.SizeInFile|0;s<i;s++)this.ibags.push(new qi(e));break;case"imod":for(let s=0,i=t.size/ji.SizeInFile|0;s<i;s++)this.imods.push(new ji(e));break;case"igen":for(let s=0,i=t.size/Ki.SizeInFile|0;s<i;s++)this.igens.push(new Ki(e));break;case"shdr":for(let s=0,i=t.size/sa.SizeInFile|0;s<i;s++)this.sHdrs.push(new sa(e));break;default:e.position+=t.size}else if("sdta"===s.id)for(;pi.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 qi{constructor(e){this.instGenNdx=Re.readUInt16LE(e),this.instModNdx=Re.readUInt16LE(e)}}qi.SizeInFile=4;class ji{constructor(e){this.modSrcOper=Re.readUInt16LE(e),this.modDestOper=Re.readUInt16LE(e),this.modAmount=Re.readInt16LE(e),this.modAmtSrcOper=Re.readUInt16LE(e),this.modTransOper=Re.readUInt16LE(e)}}ji.SizeInFile=10;class Ki{constructor(e){this.genOper=Re.readUInt16LE(e),this.genAmount=new ia(e)}}Ki.SizeInFile=4;class Qi{constructor(e){this.instName=Re.read8BitStringLength(e,20),this.instBagNdx=Re.readUInt16LE(e)}}Qi.SizeInFile=22;class $i{constructor(e){this.genNdx=Re.readUInt16LE(e),this.modNdx=Re.readUInt16LE(e)}}$i.SizeInFile=4;class Zi{constructor(e){this.genOper=Re.readUInt16LE(e),this.genAmount=new ia(e)}}Zi.SizeInFile=4,Zi.GenInstrument=41,Zi.GenKeyRange=43,Zi.GenVelRange=44,Zi.GenSampleId=53;class ea{constructor(e){this.presetName=Re.read8BitStringLength(e,20),this.preset=Re.readUInt16LE(e),this.bank=Re.readUInt16LE(e),this.presetBagNdx=Re.readUInt16LE(e),this.library=Re.readUInt32LE(e),this.genre=Re.readUInt32LE(e),this.morphology=Re.readUInt32LE(e)}}ea.SizeInFile=38;class ta{constructor(e){this.modSrcOper=Re.readUInt16LE(e),this.modDestOper=Re.readUInt16LE(e),this.modAmount=Re.readUInt16LE(e),this.modAmtSrcOper=Re.readUInt16LE(e),this.modTransOper=Re.readUInt16LE(e)}}ta.SizeInFile=10;class sa{constructor(e){this.sampleName=Re.read8BitStringLength(e,20),this.start=Re.readUInt32LE(e),this.end=Re.readUInt32LE(e),this.startLoop=Re.readUInt32LE(e),this.endLoop=Re.readUInt32LE(e),this.sampleRate=Re.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=Re.readSInt8(e),this.sampleLink=Re.readUInt16LE(e),this.sampleType=Re.readUInt16LE(e)}}sa.SizeInFile=46;class ia{get shortAmount(){return Ae.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}constructor(e){this.wordAmount=Re.readUInt16LE(e)}}class aa{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 ra{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"}(Ms||(Ms={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(Is||(Is={}));class na{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null}}class oa{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 ha{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:oa.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:oa.timecents2Secs(this.attack),this.release=this.release<-11950?0:oa.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:oa.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:oa.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?oa.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"}(As||(As={}));class la{constructor(e){this.loopMode=Ms.None,this.samples=la.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 ha,this.modEnv=new ha,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 ha(e.ampEnv),this.modEnv=new ha(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=Ms.None,this.samples=la.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 As.StartAddrsOffset:this.offset+=Ae.int16ToUint32(t.shortAmount);break;case As.EndAddrsOffset:this.end+=Ae.int16ToUint32(t.shortAmount);break;case As.StartloopAddrsOffset:this.loopStart+=Ae.int16ToUint32(t.shortAmount);break;case As.EndloopAddrsOffset:this.loopEnd+=Ae.int16ToUint32(t.shortAmount);break;case As.StartAddrsCoarseOffset:this.offset+=32768*Ae.int16ToUint32(t.shortAmount);break;case As.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case As.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case As.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case As.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case As.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case As.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case As.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case As.EndAddrsCoarseOffset:this.end+=32768*Ae.int16ToUint32(t.shortAmount);break;case As.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case As.Pan:this.pan=t.shortAmount/1e3;break;case As.DelayModLFO:this.delayModLFO=t.shortAmount;break;case As.FreqModLFO:this.freqModLFO=t.shortAmount;break;case As.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case As.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case As.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case As.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case As.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case As.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case As.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case As.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case As.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case As.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case As.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case As.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case As.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case As.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case As.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case As.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case As.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case As.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case As.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case As.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case As.StartloopAddrsCoarseOffset:this.loopStart+=32768*Ae.int16ToUint32(t.shortAmount);break;case As.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case As.EndloopAddrsCoarseOffset:this.loopEnd+=32768*Ae.int16ToUint32(t.shortAmount);break;case As.CoarseTune:this.transpose+=t.shortAmount;break;case As.FineTune:this.tune+=t.shortAmount;break;case As.SampleModes:this.loopMode=3&~t.wordAmount?1==(3&t.wordAmount)?Ms.Continuous:Ms.None:Ms.Sustain;break;case As.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case As.ExclusiveClass:this.group=t.wordAmount;break;case As.OverridingRootKey:this.pitchKeyCenter=t.shortAmount}}}la.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"}(Rs||(Rs={}));class da{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=Rs.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case Rs.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=Rs.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=Rs.Delay;break;case Rs.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=Rs.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=Rs.Attack;break;case Rs.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=Rs.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=Rs.Hold;break;case Rs.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=Rs.Decay,this.level=1,this.isAmpEnv){let 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=Rs.Decay;break;case Rs.Decay:return this.segment=Rs.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case Rs.Sustain:if(this.segment=Rs.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?da.FastReleaseTime:this.parameters.release)*t|0,this.isAmpEnv){let 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=Rs.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,s,i,a){this.parameters=new ha(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:oa.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:oa.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|s,this.isAmpEnv=i,this.nextSegment(Rs.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)}}da.FastReleaseTime=.01;class ca{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,s){this.samplesUntil=e*s|0,this.delta=4*oa.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 ua{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){let 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){let 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 pa{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 da,this.modEnv=new da,this.lowPass=new ua,this.modLfo=new ca,this.vibLfo=new ca,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/(oa.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(Rs.Sustain,e),this.modEnv.nextSegment(Rs.Sustain,e),this.region.loopMode===Ms.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(Rs.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(Rs.Sustain,e)}render(e,t,s,i,a){if(!this.region)return;let r=this.region,n=r.samples,o=0,h=e.outputMode===Is.StereoUnweaved?i:-1,l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,d=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),c=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,m=r.end,f=g+1,y=this.sourceSamplePosition,b=new ua(this.lowPass),S=0!==r.modLfoToFilterFc||0!==r.modEnvToFilterFc,_=0,w=0,B=0,T=0,k=0!==r.modLfoToPitch||0!==r.modEnvToPitch||0!==r.vibLfoToPitch,N=0,x=0,v=0,P=0,C=0!==r.modLfoToVolume,E=0,F=0;for(S?(_=e.outSampleRate,w=r.initialFilterFc,B=r.modLfoToFilterFc,T=r.modEnvToFilterFc):(_=0,w=0,B=0,T=0),k?(N=0,x=r.modLfoToPitch,v=r.vibLfoToPitch,P=r.modEnvToPitch):(N=oa.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,x=0,v=0,P=0),C?F=.1*r.modLfoToVolume:(E=oa.decibelsToGain(this.noteGainDb),F=0);i>0;){let r,D,L=0,M=i>pa.RenderEffectSampleBlock?pa.RenderEffectSampleBlock:i;if(i-=M,S){let e=w+this.modLfo.level*B+this.modEnv.level*T;b.active=e<=13500,b.active&&b.setup(oa.cents2Hertz(e)/_)}switch(k&&(N=oa.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*x+this.vibLfo.level*v+this.modEnv.level*P))*this.pitchOutputFactor),C&&(E=oa.decibelsToGain(this.noteGainDb+this.modLfo.level*F)),r=E*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(M,e.outSampleRate),l&&this.modEnv.process(M,e.outSampleRate),d&&this.modLfo.process(M),c&&this.vibLfo.process(M),e.outputMode){case Is.StereoInterleaved:for(D=r*this.panFactorLeft,L=r*this.panFactorRight;M-- >0&&y<m;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*D,o++,t[s+o]+=r*L,o++,y+=N,y>=f&&u&&(y-=g-p+1)}break;case Is.StereoUnweaved:for(D=r*this.panFactorLeft,L=r*this.panFactorRight;M-- >0&&y<m;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*D,o++,t[s+h]+=r*L,h++,y+=N,y>=f&&u&&(y-=g-p+1)}break;case Is.Mono:for(;M-- >0&&y<m;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,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===Rs.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}pa.RenderEffectSampleBlock=Ve.MicroBufferSize;class ga{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"}(Os||(Os={}));class ma{constructor(e){this._midiEventQueue=new ga,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=Is.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){let s=this.channelInit(e);for(let 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;){let e=this._midiEventQueue.dequeue();e.isMetronome&&this.metronomeVolume>0?(this.channelNoteOff(Ve.MetronomeChannel,Ve.MetronomeKey),this.channelNoteOn(Ve.MetronomeChannel,Ve.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!=Ve.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,s,n):a.kill()}return a}processMidiMessage(e){ne.debug("Midi","Processing Midi message "+Ke[e.type]+"/"+e.tick);switch(e.type){case Ke.TimeSignature:const t=e;this.timeSignatureNumerator=t.numerator,this.timeSignatureDenominator=Math.pow(2,t.denominatorIndex);break;case Ke.NoteOn:const s=e;this.channelNoteOn(s.channel,s.noteKey,s.noteVelocity/127);break;case Ke.NoteOff:const i=e;this.channelNoteOff(i.channel,i.noteKey);break;case Ke.ControlChange:const a=e;this.channelMidiControl(a.channel,a.controller,a.value);break;case Ke.ProgramChange:const r=e;this.channelSetPresetNumber(r.channel,r.program,9===r.channel);break;case Ke.TempoChange:const n=e;this.currentTempo=6e7/n.microSecondsPerQuarterNote;break;case Ke.PitchBend:const o=e;this.channelSetPitchWheel(o.channel,o.value);break;case Ke.PerNotePitchBend:const h=e;let l=h.value;l=l*Ve.MaxPitchWheel/Ve.MaxPitchWheel20,this.channelSetPerNotePitchWheel(h.channel,h.noteKey,l)}}get metronomeVolume(){return this.channelGetMixVolume(Ve.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Ve.MetronomeChannel,e),e>0&&(this.channelSetVolume(Ve.MetronomeChannel,1),this.channelSetPresetNumber(Ve.MetronomeChannel,0,!0))}get masterVolume(){return oa.decibelsToGain(this.globalGainDb)}set masterVolume(e){var t=oa.gainToDecibels(e);const 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<Rs.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(let e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<Rs.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(let e of this._voices)-1===e.playingPreset&&(n=e);if(!n){for(let e=0;e<4;e++){const e=new pa;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-oa.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!==Ms.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(oa.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){let a=this.getPresetIndex(e,t);return-1!==a&&(this.noteOn(a,s,i),!0)}noteOff(e,t){let s=null,i=null,a=[];for(let r of this._voices)r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=Rs.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>=Rs.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<Rs.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 ra);for(let t=this._channels.channelList.length;t<=e;t++){let e=new aa;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--){let 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>=Rs.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>=Rs.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<Rs.Release&&t.end(this.outSampleRate)}channelSoundsOffAll(e){this.channelInit(e).perNotePitchWheel.clear();for(let t of this._voices)-1!==t.playingPreset&&t.playingChannel===e&&(t.ampEnv.segment<Rs.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=Ae.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=Ae.int32ToUint16(t)}channelSetBankPreset(e,t,s){const i=this.channelInit(e),a=this.getPresetIndex(t,s);return-1!==a&&(i.presetIndex=Ae.int32ToUint16(a),i.bank=Ae.int32ToUint16(t),!0)}channelSetPan(e,t){for(const s of this._voices)if(s.playingChannel===e&&-1!==s.playingPreset){let 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=oa.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=Ae.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){let i=this.channelInit(e);switch(t){case Os.DataEntryFine:return i.midiData=Ae.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 Os.VolumeCoarse:return i.midiVolume=Ae.int32ToUint16(127&i.midiVolume|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.VolumeFine:return i.midiVolume=Ae.int32ToUint16(16256&i.midiVolume|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.ExpressionControllerCoarse:return i.midiExpression=Ae.int32ToUint16(127&i.midiExpression|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.ExpressionControllerFine:return i.midiExpression=Ae.int32ToUint16(16256&i.midiExpression|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.PanCoarse:return i.midiPan=Ae.int32ToUint16(127&i.midiPan|s<<7),void this.channelSetPan(e,i.midiPan/16383);case Os.PanFine:return i.midiPan=Ae.int32ToUint16(16256&i.midiPan|s),void this.channelSetPan(e,i.midiPan/16383);case Os.DataEntryCoarse:return i.midiData=Ae.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===Os.DataEntryCoarse&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Os.BankSelectCoarse:return void(i.bank=Ae.int32ToUint16(32768|s));case Os.BankSelectFine:return void(i.bank=Ae.int32ToUint16((32768&i.bank?(127&i.bank)<<7:0)|s));case Os.RegisteredParameterCourse:return void(i.midiRpn=Ae.int32ToUint16(127&(65535===i.midiRpn?0:i.midiRpn)|s<<7));case Os.RegisteredParameterFine:return void(i.midiRpn=Ae.int32ToUint16(16256&(65535===i.midiRpn?0:i.midiRpn)|s));case Os.NonRegisteredParameterFine:case Os.NonRegisteredParameterCourse:return void(i.midiRpn=65535);case Os.AllSoundOff:return void this.channelSoundsOffAll(e);case Os.AllNotesOff:return void this.channelNoteOffAll(e);case Os.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?oa.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 na;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++){let t=e.pgens[n];if(t.genOper!==Zi.GenKeyRange)if(t.genOper!==Zi.GenVelRange){if(t.genOper===Zi.GenInstrument&&!(t.genAmount.wordAmount>=e.insts.length))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,d=127;for(let c=e.ibags[n].instGenNdx;c<e.ibags[n+1].instGenNdx;c++){let n=e.igens[c];n.genOper!==Zi.GenKeyRange?n.genOper!==Zi.GenVelRange?53===n.genOper&&o>=s&&t<=i&&d>=a&&l<=r&&h++:(l=n.genAmount.lowByteAmount,d=n.genAmount.highByteAmount):(t=n.genAmount.lowByteAmount,o=n.genAmount.highByteAmount)}}}else a=t.genAmount.lowByteAmount,r=t.genAmount.highByteAmount;else s=t.genAmount.lowByteAmount,i=t.genAmount.highByteAmount}}o.regions=new Array(h);let l=new la;l.clear(!0);for(let a=r.presetBagNdx;a<e.phdrs[i+1].presetBagNdx;a++){const i=e.pbags[a],h=new la(l);let d=!1;for(let l=i.genNdx;l<e.pbags[a+1].genNdx;l++){const i=e.pgens[l];if(i.genOper===Zi.GenInstrument){let a=i.genAmount.wordAmount;if(a>=e.insts.length)continue;let l=new la;l.clear(!1);let c=e.insts[a];for(let i=c.instBagNdx;i<e.insts[a+1].instBagNdx;i++){let a=e.ibags[i],d=new la(l),u=!1;for(let l=a.instGenNdx;l<e.ibags[i+1].instGenNdx;l++){let i=e.igens[l];if(i.genOper===Zi.GenSampleId){if(d.hiKey<h.loKey||d.loKey>h.hiKey)continue;if(d.hiVel<h.loVel||d.loVel>h.hiVel)continue;h.loKey>d.loKey&&(d.loKey=h.loKey),h.hiKey<d.hiKey&&(d.hiKey=h.hiKey),h.loVel>d.loVel&&(d.loVel=h.loVel),h.hiVel<d.hiVel&&(d.hiVel=h.hiVel),d.offset+=h.offset,d.end+=h.end,d.loopStart+=h.loopStart,d.loopEnd+=h.loopEnd,d.transpose+=h.transpose,d.tune+=h.tune,d.pitchKeyTrack+=h.pitchKeyTrack,d.attenuation+=h.attenuation,d.pan+=h.pan,d.ampEnv.delay+=h.ampEnv.delay,d.ampEnv.attack+=h.ampEnv.attack,d.ampEnv.hold+=h.ampEnv.hold,d.ampEnv.decay+=h.ampEnv.decay,d.ampEnv.sustain+=h.ampEnv.sustain,d.ampEnv.release+=h.ampEnv.release,d.modEnv.delay+=h.modEnv.delay,d.modEnv.attack+=h.modEnv.attack,d.modEnv.hold+=h.modEnv.hold,d.modEnv.decay+=h.modEnv.decay,d.modEnv.sustain+=h.modEnv.sustain,d.modEnv.release+=h.modEnv.release,d.initialFilterQ+=h.initialFilterQ,d.initialFilterFc+=h.initialFilterFc,d.modEnvToPitch+=h.modEnvToPitch,d.modEnvToFilterFc+=h.modEnvToFilterFc,d.delayModLFO+=h.delayModLFO,d.freqModLFO+=h.freqModLFO,d.modLfoToPitch+=h.modLfoToPitch,d.modLfoToFilterFc+=h.modLfoToFilterFc,d.modLfoToVolume+=h.modLfoToVolume,d.delayVibLFO+=h.delayVibLFO,d.freqVibLFO+=h.freqVibLFO,d.vibLfoToPitch+=h.vibLfoToPitch,d.ampEnv.envToSecs(!0),d.modEnv.envToSecs(!1),d.delayModLFO=d.delayModLFO<-11950?0:oa.timecents2Secs(d.delayModLFO),d.delayVibLFO=d.delayVibLFO<-11950?0:oa.timecents2Secs(d.delayVibLFO),d.pan<-.5?d.pan=-.5:d.pan>.5&&(d.pan=.5),(d.initialFilterQ<1500||d.initialFilterQ>13500)&&(d.initialFilterQ=0);let a=e.sHdrs[i.genAmount.wordAmount];d.offset+=a.start,d.end+=a.end,d.loopStart+=a.startLoop,d.loopEnd+=a.endLoop,a.endLoop>0&&(d.loopEnd-=1),-1===d.pitchKeyCenter&&(d.pitchKeyCenter=a.originalPitch),d.tune+=a.pitchCorrection,d.sampleRate=a.sampleRate;const l=r.bank==Ve.PercussionBank;if(l&&ma.setContainsRange(s,d.loKey,d.hiKey)||!l&&t.has(r.preset))if(1&a.sampleType){ne.debug("AlphaSynth",`Loading of used sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`);!!(16&a.sampleType)?d.samples=e.decodeSamples(a.start,a.end,!0):(d.samples=e.decodeSamples(2*d.offset,2*d.end,!1),d.loopStart>0&&(d.loopStart-=d.offset),d.loopEnd>0&&(d.loopEnd-=d.offset)),d.offset=0,d.end=d.samples.length-1}else ne.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})`),d.samples=new Float32Array(0);else ne.debug("AlphaSynth",`Skipping load of unused sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`),d.samples=new Float32Array(0);o.regions[n]=new la(d),n++,u=!0}else d.operator(i.genOper,i.genAmount)}a!==e.ibags[c.instBagNdx]||u||(l=new la(d))}d=!0}else h.operator(i.genOper,i.genAmount)}i!==e.pbags[r.presetBagNdx]||d||(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==Ve.PercussionBank)for(const t of s.regions)if(t.loKey>=e&&t.hiKey<=e&&t.samples.length>0)return!0;return!1}}class fa{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 ya{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 ba{constructor(e){this.events=e}}class Sa{constructor(e){this.playbackRange=e}}class _a{get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return ne.logLevel}set logLevel(e){ne.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Ve.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Ve.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Ve.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=de.clamp(e,Ve.MinPlaybackSpeed,Ve.MaxPlaybackSpeed);let 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){ne.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 Sa(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){ne.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 ga,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this._synthStopping=!1,this.isReady=!1,this.state=Fs.Paused,this._loadedSoundFonts=[],this.ready=new fa,this.readyForPlayback=new fa,this.finished=new fa,this.soundFontLoaded=new fa,this.soundFontLoadFailed=new ya,this.midiLoaded=new ya,this.midiLoadFailed=new ya,this.stateChanged=new ya,this.positionChanged=new ya,this.midiEventsPlayed=new ya,this.playbackRangeChanged=new ya,ne.debug("AlphaSynth","Initializing player"),this.state=Fs.Paused,ne.debug("AlphaSynth","Creating output"),this.output=e,ne.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new ma(this.output.sampleRate),this._sequencer=new di(this._synthesizer),ne.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this.state==Fs.Playing&&(!this._sequencer.isFinished||this._synthesizer.activeVoiceCount>0)){let e=new Float32Array(Ve.MicroBufferSize*Ve.MicroBufferCount*Ve.AudioChannels),t=0;for(let s=0;s<Ve.MicroBufferCount;s++){this._sequencer.fillMidiEventQueue();const s=this._synthesizer.synthesize(e,t,Ve.MicroBufferSize);t+=Ve.MicroBufferSize*Ve.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{let e=new Float32Array(0);this.output.addSamples(e)}})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open(t)}play(){return!(this.state!==Fs.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(ne.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(ne.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),ne.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this._synthStopping=!1,this.state=Fs.Playing,this.stateChanged.trigger(new ci(this.state,!1))}pause(){this.state!==Fs.Paused&&this._isMidiLoaded&&(ne.debug("AlphaSynth","Pausing playback"),this.state=Fs.Paused,this.stateChanged.trigger(new ci(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===Fs.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(ne.debug("AlphaSynth","Stopping playback"),this.state=Fs.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 ci(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();let s=Oe.fromBuffer(e);try{ne.debug("AlphaSynth","Loading soundfont from bytes");let e=new Yi;e.load(s),t||(this._loadedSoundFonts=[]),this._loadedSoundFonts.push(e),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),ne.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){ne.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{ne.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new ui(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),ne.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){ne.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,Ve.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;let t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*Ve.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?(ne.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(ne.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=Fs.Paused,this.stopOneTimeMidi()):this.isLooping?(ne.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,ne.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(ne.debug("AlphaSynth",`Position changed: (time: ${s}/${a}, tick: ${i}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new ui(s,a,i,r,t)),t)this._playedEventsQueue.clear();else{const e=new ga;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<s;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new ba(e.toArray()))}}hasSamplesForProgram(e){return this._synthesizer.hasSamplesForProgram(e)}hasSamplesForPercussion(e){return this._synthesizer.hasSamplesForPercussion(e)}}class wa{constructor(){this.ready=new fa,this.samplesPlayed=new ya,this.sampleRequest=new fa}get sampleRate(){return wa.preferredSampleRate}open(){ne.debug("AlphaSynth","Initializing synth worker"),this._worker=Nl.globalThis,this._worker.addEventListener("message",this.handleMessage.bind(this)),this.ready.trigger()}destroy(){this._worker.postMessage({cmd:"alphaSynth.output.destroy"})}handleMessage(e){let t=e.data;switch(t.cmd){case wa.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case wa.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(){}}wa.CmdOutputPrefix="alphaSynth.output.",wa.CmdOutputAddSamples=wa.CmdOutputPrefix+"addSamples",wa.CmdOutputPlay=wa.CmdOutputPrefix+"play",wa.CmdOutputPause=wa.CmdOutputPrefix+"pause",wa.CmdOutputResetSamples=wa.CmdOutputPrefix+"resetSamples",wa.CmdOutputStop=wa.CmdOutputPrefix+"stop",wa.CmdOutputSampleRequest=wa.CmdOutputPrefix+"sampleRequest",wa.CmdOutputSamplesPlayed=wa.CmdOutputPrefix+"samplesPlayed",wa.preferredSampleRate=0;class Ba{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new _a(new wa,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(){let e=Nl.globalThis;e.addEventListener("message",(t=>{let s=t.data;if("alphaSynth.initialize"===s.cmd)wa.preferredSampleRate=s.sampleRate,ne.logLevel=s.logLevel,Nl.globalThis.alphaSynthWebWorker=new Ba(e,s.bufferTimeInMilliseconds)}))}handleMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":ne.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(is.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(is.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){let 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(is.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}e.WebPlatform=void 0,(Vs=e.WebPlatform||(e.WebPlatform={}))[Vs.Browser=0]="Browser",Vs[Vs.NodeJs=1]="NodeJs",Vs[Vs.BrowserModule=2]="BrowserModule";class Ta{constructor(e,t){this.characterWidths=e,this.fontSizeToHeight=t}}class ka{static generateFontLookup(t){if(!ka.FontSizeLookupTables.has(t))if(Nl.isRunningInWorker||Nl.webPlatform==e.WebPlatform.NodeJs){const e=new Ta(new Uint8Array([8]),1.2);ka.FontSizeLookupTables.set(t,e)}else{let e=document.createElement("canvas").getContext("2d");const s=11;e.font=`${s}px ${t}`;const i=[];let a="";for(let t=ka.ControlChars;t<255;t++){let s=String.fromCharCode(t);a+=s;const r=e.measureText(s);i.push(r.width)}const r=e.measureText(a+"ÄÖÜÁÈ"),n=0-Math.abs(r.fontBoundingBoxAscent),o=0+Math.abs(r.fontBoundingBoxDescent)-n,h=new Ta(new Uint8Array(i),o/s);ka.FontSizeLookupTables.set(t,h)}}static measureString(e,t,s,i,a){let r,n=t[0];for(let e=0;e<t.length;e++)if(ka.FontSizeLookupTables.has(t[e])){n=t[e];break}ka.FontSizeLookupTables.has(n)||ka.generateFontLookup(n),r=ka.FontSizeLookupTables.get(n);let o=1;i===Ye.Italic&&(o*=1.1),a===qe.Bold&&(o*=1.1);let h=0;for(let t=0;t<e.length;t++){let i=Math.min(r.characterWidths.length-1,e.charCodeAt(t)-ka.ControlChars);i>=0&&(h+=r.characterWidths[i]*s/11)}return o*=1.07,new ce(h*o,s*r.fontSizeToHeight)}}ka.FontSizeLookupTables=new Map,ka.ControlChars=32;class Na{constructor(){this.id=de.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 xa{constructor(){this.beats=[]}addBeat(e){e.barBounds=this,this.beats.push(e),this.masterBarBounds.addBeat(e)}findBeatAtPos(e){let t=null;for(let 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 va{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(let i of s){let 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.notes)for(const t of this.notes)t.finish(e)}}class Pa{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(let t of this.bars){let 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 Ca{finish(e=1){this.noteHeadBounds.scaleWith(e)}}class Ea{constructor(){this.index=0,this.bars=[]}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e);for(let 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(let 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 Fa{constructor(){this._beatLookup=new Map,this._masterBarLookup=new Map,this._currentStaffSystem=null,this.staffSystems=[],this.isFinished=!1}toJson(){let e={},t=[];e.staffSystems=t;for(let e of this.staffSystems){let s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.bars=[];for(let t of e.bars){let 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(let s of t.bars){let t={};t.visualBounds=this.boundsToJson(s.visualBounds),t.realBounds=this.boundsToJson(s.realBounds),t.beats=[];for(let e of s.beats){let s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.onNotesX=e.onNotesX;let 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){let t=s.notes=[];for(let s of e.notes){let 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){let s=new Fa,i=e.staffSystems;for(let e of i){let i=new Ea;i.visualBounds=Fa.boundsFromJson(e.visualBounds),i.realBounds=Fa.boundsFromJson(e.realBounds),s.addStaffSystem(i);for(let s of e.bars){let e=new Pa;e.index=s.index,e.isFirstOfLine=s.isFirstOfLine,e.lineAlignedBounds=Fa.boundsFromJson(s.lineAlignedBounds),e.visualBounds=Fa.boundsFromJson(s.visualBounds),e.realBounds=Fa.boundsFromJson(s.realBounds),i.addBar(e);for(let i of s.bars){let s=new xa;s.visualBounds=Fa.boundsFromJson(i.visualBounds),s.realBounds=Fa.boundsFromJson(i.realBounds),e.addBar(s);for(let e of i.beats){let i=new va;i.visualBounds=Fa.boundsFromJson(e.visualBounds),i.realBounds=Fa.boundsFromJson(e.realBounds),i.onNotesX=e.onNotesX;let 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(let t of e.notes){let e=new Ca,s=t;e.note=i.beat.notes[s.index],e.noteHeadBounds=Fa.boundsFromJson(t.noteHeadBounds),i.addNote(e)}}s.addBeat(i)}}}}return s}static boundsFromJson(e){const t=new cs;return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}boundsToJson(e){let t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(e=1){for(let 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){let 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){let 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;){let 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;let 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 Da{constructor(t){this._currentLayoutMode=e.LayoutMode.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 ya,this.renderFinished=new ya,this.partialRenderFinished=new ya,this.partialLayoutFinished=new ya,this.postRenderFinished=new fa,this.error=new ya,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=Nl.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=Nl.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(let 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?(ne.debug("Rendering","Request render of lazy partial "+e),t.renderLazyPartial(e)):ne.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 Fa,this.recreateCanvas(),this.canvas.lineWidth=1,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){ne.debug("Rendering","Rendering "+this.tracks.length+" tracks");for(let e=0;e<this.tracks.length;e++){let t=this.tracks[e];ne.debug("Rendering","Track "+e+": "+t.name)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),ne.debug("Rendering","Rendering finished")}else ne.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),ne.debug("Rendering","Clearing finished");else ne.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(ne.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(ne.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new Fa,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):ne.debug("Rendering","Current layout does not support dynamic resizing, nothing was done",null),ne.debug("Rendering","Resize finished")}layoutAndRender(){ne.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 Na;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}class La{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){Nl.globalThis.alphaTabWebWorker=new La(Nl.globalThis)}handleMessage(e){let t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":let e=is.jsObjectToSettings(t.settings);ne.logLevel=e.core.logLevel,this._renderer=new Da(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);let s=null==t.score?null:is.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){ka.FontSizeLookupTables||(ka.FontSizeLookupTables=new Map);for(let[t,s]of e)ka.FontSizeLookupTables.set(t,s)}}updateSettings(e){Rt.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){ne.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class Ma{constructor(){this._canvas=null,this._color=new Ee(0,0,0,255),this._font=new nt("Arial",10,Ye.Plain),this._lineWidth=0;let e=document.createElement("span");e.classList.add("at"),document.body.appendChild(e);let t=window.getComputedStyle(e),s=t.fontFamily;(s.startsWith('"')||s.startsWith("'"))&&(s=s.substr(1,s.length-2)),this._musicFont=new nt(s,parseFloat(t.fontSize),Ye.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*Nl.HighDpiFactor|0,this._canvas.height=t*Nl.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(Nl.HighDpiFactor*s,Nl.HighDpiFactor*s),this._context.lineWidth=this._lineWidth}endRender(){let 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 L.Left;case"center":return L.Center;case"right":return L.Right}}set textAlign(e){switch(e){case L.Left:this._context.textAlign="left";break;case L.Center:this._context.textAlign="center";break;case L.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return M.Top;case"middle":return M.Middle;case"bottom":return M.Bottom}}set textBaseline(e){switch(e){case M.Top:this._context.textBaseline="hanging";break;case M.Middle:this._context.textBaseline="middle";break;case M.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 ce(t.width,t.actualBoundingBoxDescent-t.actualBoundingBoxAscent)}fillMusicFontSymbol(e,t,s,i,a=!1){i!==D.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a=!1){let r="";for(let e of i)e!==D.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){let 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 Ia{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 dt(0,e,t,i,48,8))}addRest(e,t,s){this._smf1Mode||this._midiFile.addEvent(new pt(e,t,s))}addNote(e,t,s,i,a,r){this._midiFile.addEvent(new mt(e,t,r,Ia.fixValue(i),Ia.fixValue(a))),this._midiFile.addEvent(new ft(e,t+s,r,Ia.fixValue(i),Ia.fixValue(a)))}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,s,i,a){this._midiFile.addEvent(new yt(e,t,s,i,Ia.fixValue(a)))}addProgramChange(e,t,s,i){this._midiFile.addEvent(new bt(e,t,s,i))}addTempo(e,t){const s=6e7/t|0;this._midiFile.addEvent(new St(e,s))}addBend(e,t,s,i){i=i>=Ve.MaxPitchWheel?Ve.MaxPitchWheel:Math.floor(i),this._midiFile.addEvent(new _t(e,t,s,i))}addNoteBend(e,t,s,i,a){this._smf1Mode?this.addBend(e,t,s,a):(a=a*Ve.MaxPitchWheel20/Ve.MaxPitchWheel,this._midiFile.addEvent(new wt(e,t,s,i,a)))}finishTrack(e,t){this._midiFile.format!=je.MultiTrack&&0!=e||this._midiFile.addEvent(new Bt(e,t))}}class Aa{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"}(Hs||(Hs={}));class Ra{get finished(){return this.index>=this._score.masterBars.length}constructor(e){this._repeatStack=[],this._groupsOnStack=new Set,this._previousAlternateEndings=0,this._state=Hs.PlayingNormally,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}processCurrent(){const e=this._score.masterBars[this.index];if(this._state===Hs.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 Aa(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=Hs.PlayingNormally,!0)}return!1}moveNextWithDirections(){const e=this._score.masterBars[this.index],t=null!==e.directions&&e.directions.size>0;if(this._state===Hs.PlayingNormally&&!t)return!1;if(!t)return this.index++,!0;switch(this._state){case Hs.PlayingNormally:return!!(this.handleDaCapo(e.directions,He.JumpDaCapo,Hs.DirectionJumped)||this.handleDaCapo(e.directions,He.JumpDaCapoAlCoda,Hs.DirectionJumpedAlCoda)||this.handleDaCapo(e.directions,He.JumpDaCapoAlDoubleCoda,Hs.DirectionJumpedAlDoubleCoda)||this.handleDaCapo(e.directions,He.JumpDaCapoAlFine,Hs.DirectionJumpedAlFine))||(!!(this.handleDalSegno(e.directions,He.JumpDalSegno,Hs.DirectionJumped,He.TargetSegno)||this.handleDalSegno(e.directions,He.JumpDalSegnoAlCoda,Hs.DirectionJumpedAlCoda,He.TargetSegno)||this.handleDalSegno(e.directions,He.JumpDalSegnoAlDoubleCoda,Hs.DirectionJumpedAlDoubleCoda,He.TargetSegno)||this.handleDalSegno(e.directions,He.JumpDalSegnoAlFine,Hs.DirectionJumpedAlFine,He.TargetSegno))||!!(this.handleDalSegno(e.directions,He.JumpDalSegnoSegno,Hs.DirectionJumped,He.TargetSegnoSegno)||this.handleDalSegno(e.directions,He.JumpDalSegnoSegnoAlCoda,Hs.DirectionJumpedAlCoda,He.TargetSegnoSegno)||this.handleDalSegno(e.directions,He.JumpDalSegnoSegnoAlDoubleCoda,Hs.DirectionJumpedAlDoubleCoda,He.TargetSegnoSegno)||this.handleDalSegno(e.directions,He.JumpDalSegnoSegnoAlFine,Hs.DirectionJumpedAlFine,He.TargetSegnoSegno)));case Hs.DirectionJumped:return this.index++,!0;case Hs.DirectionJumpedAlCoda:return this.handleDaCoda(e.directions,He.JumpDaCoda,He.TargetCoda)||this.index++,!0;case Hs.DirectionJumpedAlDoubleCoda:return this.handleDaCoda(e.directions,He.JumpDaDoubleCoda,He.TargetDoubleCoda)||this.index++,!0;case Hs.DirectionJumpedAlFine:return e.directions.has(He.TargetFine)?(this.index=this._score.masterBars.length,!0):(this.index++,!0)}return!0}findJumpTarget(e,t,s){if(s){let s=this.findJumpTargetBackwards(e,t);return-1===s&&(s=this.findJumpTargetForwards(e,t)),s}{let s=this.findJumpTargetForwards(e,t);return-1===s&&(s=this.findJumpTargetBackwards(e,t)),s}}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 Oa{constructor(e,t){this.beat=e,this.playbackStart=t}}class Va{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 Oa(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 Ha{constructor(e,t){this.tick=e,this.tempo=t}}class Ga{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(t,s,i,a){const r=i+a;if(null==this.firstBeat){const e=new Va(i,r);e.highlightBeat(t,s),this.insertAfter(this.firstBeat,e)}else if(i>=this.lastBeat.end){const e=new Va(this.lastBeat.end,r);e.highlightBeat(t,s),this.insertAfter(this.lastBeat,e)}else{let a=null;if(i<this.firstBeat.start)a=this.firstBeat;else{let t=this.firstBeat;for(;null!=t;){if(i>=t.start&&i<t.end){a=t;break}t=t.nextBeat}if(null===a)throw new K(e.AlphaTabErrorType.General,"Error on building lookup, unknown variant")}if(i<a.start)if(r==a.start){const e=new Va(i,a.start);e.highlightBeat(t,s),this.insertBefore(this.firstBeat,e)}else if(r<a.end){const e=new Va(i,a.start);e.highlightBeat(t,s),this.insertBefore(a,e);const n=new Va(a.start,r);for(const e of a.highlightedBeats)n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(t,s),this.insertBefore(a,n),a.start=r}else if(r==a.end){const e=new Va(i,a.start);e.highlightBeat(t,s),a.highlightBeat(t,s),this.insertBefore(a,e)}else{const e=new Va(i,a.start);e.highlightBeat(t,s),a.highlightBeat(t,s),this.insertBefore(a,e),this.addBeat(t,s,a.end,r-a.end)}else if(i>a.start)if(r==a.end){const e=new Va(a.start,i);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart);a.start=i,a.highlightBeat(t,s),this.insertBefore(a,e)}else if(r<a.end){const e=new Va(a.start,i);this.insertBefore(a,e);const n=new Va(i,r);this.insertBefore(a,n);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart),n.highlightBeat(t.beat,t.playbackStart);n.highlightBeat(t,s),a.start=r}else{const e=new Va(a.start,i);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart);a.start=i,a.highlightBeat(t,s),this.insertBefore(a,e),this.addBeat(t,s,a.end,r-a.end)}else if(r===a.end)a.highlightBeat(t,s);else if(r<a.end){const e=new Va(a.start,r);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart);e.highlightBeat(t,s),a.start=r,this.insertBefore(a,e)}else a.highlightBeat(t,s),this.addBeat(t,s,a.end,r-a.end)}}}class Wa{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.masterBar=e}calculateDuration(){if(1===this.masterBar.tempoChanges.length)this.duration=te.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+=te.ticksToMillis(a.tick-t,s),s=a.tempo,t=a.tick}i>t&&(e+=te.ticksToMillis(i-t,s)),this.duration=e}}}class za{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[]}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}fillNextBeat(e,t){e.nextBeat=this.findBeatInMasterBar(e.masterBar,e.beatLookup.nextBeat,e.end,t,!1,!0),null==e.nextBeat&&(e.nextBeat=this.findBeatSlow(t,e,e.end,!0)),e.nextBeat&&(e.tickDuration=e.nextBeat.start-e.start,e.calculateDuration()),e.nextBeat||(e.tickDuration=e.masterBar.end-e.start,e.calculateDuration())}findBeatSlow(e,t,s,i){let a=null;if(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)return null;for(;a;){if(a.firstBeat){let t=this.findBeatInMasterBar(a,a.firstBeat,s,e,!0,i);if(t)return t}a=a.nextMasterBar}return null}findBeatInMasterBar(e,t,s,i,a,r){if(!t)return null;let n=null,o=null;const h=s-e.start;for(;null!=t&&null==o;){if(t.start<=h&&h<t.end){if(n=t,o=t.getVisibleBeatAtStart(i),!o)if(r){let s=e;for(;null!=s&&null==o;){for(;null!=t;){if(o=t.getVisibleBeatAtStart(i),o){n=t,e=s;break}t=t.nextBeat}o&&n||(s=s.nextMasterBar,t=s?.firstBeat??null)}}else{let s=e;for(;null!=s&&null==o;){for(;null!=t;){if(o=t.getVisibleBeatAtStart(i),o){n=t,e=s;break}t=t.previousBeat}o&&n||(s=s.previousMasterBar,t=s?.firstBeat??null)}}}else if(t.end>h)break;t=t?.nextBeat??null}if(null==o)return null;return this.createResult(e,n,o,a,i)}createResult(e,t,s,i,a){const r=new Wa(e);return r.beat=s,r.beatLookup=t,r.tickDuration=t.end-t.start,i&&this.fillNextBeat(r,a),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 Ga;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 Ua{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Xa{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class Ja{constructor(){this.durations=[],this.brushInfos=[]}}class Ya{constructor(e,t,s){this._programsPerChannel=new Map,this._currentTime=0,this._calculatedBeatTimers=new Set,this.tickLookup=new za,this.applyTranspositionPitches=!0,this.transpositionPitches=new Map,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new Ot,this._handler=s}generate(){this.transpositionPitches.clear(),this._calculatedBeatTimers.clear(),this._currentTime=0;for(const e of this._score.tracks)this.generateTrack(e);ne.debug("Midi","Begin midi generation");const e=new Ra(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);ne.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);let a=Ya.toChannelShort(s.volume),r=Ya.toChannelShort(s.balance);this._handler.addControlChange(e.index,0,t,Os.VolumeCoarse,a),this._handler.addControlChange(e.index,0,t,Os.PanCoarse,r),this._handler.addControlChange(e.index,0,t,Os.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,Os.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,Os.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,Os.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,Os.DataEntryCoarse,Ya.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 Ga;if(e.tempoAutomations.length>0){e.tempoAutomations[0].ratioPosition>0&&r.tempoChanges.push(new Ha(s,i));for(const t of e.tempoAutomations){const e=s+a*t.ratioPosition;this._handler.addTempo(e,t.value),r.tempoChanges.push(new Ha(e,t.value))}}else t?r.tempoChanges.push(new Ha(s,i)):(this._handler.addTempo(s,e.score.tempo),r.tempoChanges.push(new Ha(s,e.score.tempo)));r.masterBar=e,r.start=s,r.end=r.start+a,this.tickLookup.addMasterBar(r)}generateBar(e,t,s){let i=this.getPlaybackBar(e);const 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+te.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+=te.ticksToMillis(s,i)),i=t.value,e+=s}const h=r-e;h>0&&(this._currentTime+=te.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!==E.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(a-=this._currentTripletFeel.secondBeatStartOffset,r=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=Ya.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+=te.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{let 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!==O.None&&this.generateFade(e,t+a,r),e.vibrato!==B.None){let s=240,i=3;switch(e.vibrato){case B.Slight:s=this._settings.player.vibrato.beatSlightLength,i=this._settings.player.vibrato.beatSlightAmplitude;break;case B.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 E.Triplet8th:case E.Dotted8th:case E.Scottish8th:i=g.Eighth;break;case E.Triplet16th:case E.Dotted16th:case E.Scottish16th:i=g.Sixteenth;break;default:return null}const a=te.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 Xa;switch(s.voice.bar.masterBar.tripletFeel){case E.Triplet8th:r.firstBeatDuration=te.applyTuplet(te.toTicks(g.Quarter),3,2),r.secondBeatDuration=te.applyTuplet(te.toTicks(g.Eighth),3,2);break;case E.Dotted8th:r.firstBeatDuration=te.applyDot(te.toTicks(g.Eighth),!1),r.secondBeatDuration=te.toTicks(g.Sixteenth);break;case E.Scottish8th:r.firstBeatDuration=te.toTicks(g.Sixteenth),r.secondBeatDuration=te.applyDot(te.toTicks(g.Eighth),!1);break;case E.Triplet16th:r.firstBeatDuration=te.applyTuplet(te.toTicks(g.Eighth),3,2),r.secondBeatDuration=te.applyTuplet(te.toTicks(g.Sixteenth),3,2);break;case E.Dotted16th:r.firstBeatDuration=te.applyDot(te.toTicks(g.Sixteenth),!1),r.secondBeatDuration=te.toTicks(g.ThirtySecond);break;case E.Scottish16th:r.firstBeatDuration=te.toTicks(g.ThirtySecond),r.secondBeatDuration=te.applyDot(te.toTicks(g.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateDeadSlap(e,t){const s=te.toTicks(g.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,te.dynamicToVelocity(m.F),i.track.playbackInfo.primaryChannel)}needsSecondaryChannel(e){return e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==B.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=pe.getArticulation(e);t&&(h=t.outputMidiNumber)}const l=null==r&&e.isStringed&&e.string<=a.length?a[e.string-1]:0,d=t+l,c=this.getNoteDuration(e,s,i);c.untilTieOrSlideEnd-=l,c.noteOnly-=l,c.letRingEnd-=l;const u=Ya.getNoteVelocity(e),p=this.determineChannel(n,e);let g=0,m=Math.max(c.untilTieOrSlideEnd,c.letRingEnd);g=e.hasBend?Ya.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?Ya.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===w.Legato?-1:Ya.getPitchWheel(0),g>=0&&this._handler.addNoteBend(n.index,d,p,h,g),e.beat.hasRasgueado?this.generateRasgueado(n,e,d,h,u,p,r):e.ornament===I.None?!e.isTrill||o.isPercussion?e.beat.isTremolo?this.generateTremoloPicking(e,d,c,h,u,p):(e.hasBend?this.generateBend(e,d,c,h,p,i):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,d,c,p,i):e.slideInType!==_.None||e.slideOutType!==w.None?this.generateSlide(e,d,c,h,p,i):(e.vibrato!==B.None||e.isTieDestination&&e.tieOrigin.vibrato!==B.None)&&this.generateVibrato(e,d,c,h,p),e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===w.Legato||this._handler.addNote(n.index,d,m,h,u,p)):this.generateTrill(e,d,c,h,u,p):this.generateOrnament(n,e,d,m,h,u,p)}generateOrnament(e,t,s,i,a,r,n){let o,h;const l=a%12,d=1/3;switch(t.ornament){case I.Turn:o=[a+Ya.OrnamentKeysUp[l],a,a+Ya.OrnamentKeysDown[l]],h=[te.toTicks(g.Sixteenth)*d,te.toTicks(g.Sixteenth)*d,te.toTicks(g.Sixteenth)*d];break;case I.InvertedTurn:o=[a+Ya.OrnamentKeysDown[l],a,a+Ya.OrnamentKeysUp[l]],h=[te.toTicks(g.Sixteenth)*d,te.toTicks(g.Sixteenth)*d,te.toTicks(g.Sixteenth)*d];break;case I.UpperMordent:o=[a,a+Ya.OrnamentKeysUp[l]],h=[te.toTicks(g.ThirtySecond),te.toTicks(g.ThirtySecond)];break;case I.LowerMordent:o=[a,a+Ya.OrnamentKeysDown[l]],h=[te.toTicks(g.ThirtySecond),te.toTicks(g.ThirtySecond)];break;default:return}let c=1;i<te.QuarterTime&&(c=i/te.QuarterTime),r-=te.VelocityIncrement;let u=0;for(let t=0;t<o.length;t++){const i=h[t]*c;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(t,s,i){const a=new Ua;if(a.noteOnly=s,a.untilTieOrSlideEnd=s,a.letRingEnd=s,t.isDead)return a.noteOnly=this.applyStaticDuration(Ya.DefaultDurationDead,s,i),a.untilTieOrSlideEnd=a.noteOnly,a.letRingEnd=a.noteOnly,a;if(t.isPalmMute)return a.noteOnly=this.applyStaticDuration(Ya.DefaultDurationPalmMute,s,i),a.untilTieOrSlideEnd=a.noteOnly,a.letRingEnd=a.noteOnly,a;if(t.isStaccato)return a.noteOnly=s/2|0,a.untilTieOrSlideEnd=a.noteOnly,a.letRingEnd=a.noteOnly,a;if(t.isTieOrigin){const e=t.tieDestination;if(e)if(t.isTieDestination){const t=this.getNoteDuration(e,e.beat.playbackDuration,i);a.untilTieOrSlideEnd=s+t.untilTieOrSlideEnd}else{const s=t.beat.absolutePlaybackStart,r=this.getNoteDuration(e,e.beat.playbackDuration,i),n=e.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;a.untilTieOrSlideEnd=n-s}}else if(t.slideOutType===w.Legato){const e=t.slideTarget;if(e){const s=t.beat.absolutePlaybackStart,r=this.getNoteDuration(e,e.beat.playbackDuration,i),n=e.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;a.untilTieOrSlideEnd=n-s}}if(t.isLetRing&&this._settings.notation.notationMode===e.NotationMode.GuitarPro){let e=t.beat,i=0;const r=t.beat.voice.bar.masterBar.calculateDuration();for(;e.nextBeat;){let s=e.nextBeat;if(s.isRest)break;if(t.isStringed&&s.hasNoteOnString(t.string))break;if(e=e.nextBeat,i=e.absolutePlaybackStart-t.beat.absolutePlaybackStart+e.playbackDuration,i>r){i=r;break}}e===t.beat?a.letRingEnd=s:a.letRingEnd=i}else a.letRingEnd=a.untilTieOrSlideEnd;return a}applyStaticDuration(e,t,s){const i=s*e/se.MaxPosition|0;return Math.min(i,t)}static getNoteVelocity(e){let t=e.dynamics;switch(!e.beat.voice.bar.staff.isPercussion&&e.hammerPullOrigin&&t--,e.isGhost&&t--,e.accentuated){case a.Normal:t++;break;case a.Heavy:t+=2}return te.dynamicToVelocity(t)}generateFade(e,t,s){const i=e.voice.bar.staff.track;switch(e.fade){case O.FadeIn:this.generateFadeSteps(i,t,s,0,Ya.toChannelShort(i.playbackInfo.volume));break;case O.FadeOut:this.generateFadeSteps(i,t,s,Ya.toChannelShort(i.playbackInfo.volume),0);break;case O.VolumeSwell:const e=s/2|0;this.generateFadeSteps(i,t,e,0,Ya.toChannelShort(i.playbackInfo.volume)),this.generateFadeSteps(i,t+e,e,Ya.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,d=h?a:Math.round(i+(l-t)*r);this._handler.addControlChange(e.index,l,e.playbackInfo.primaryChannel,Os.VolumeCoarse,d),this._handler.addControlChange(e.index,l,e.playbackInfo.secondaryChannel,Os.VolumeCoarse,d)}}generateVibrato(e,t,s,i,a){let r=0,n=0;switch(e.vibrato!==B.None?e.vibrato:e.isTieDestination?e.tieOrigin.vibrato:B.Slight){case B.Slight:r=this._settings.player.vibrato.noteSlightLength,n=this._settings.player.vibrato.noteSlightAmplitude;break;case B.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;){let s=i+a*Math.sin(t*Math.PI/o);r(e+t|0,Ya.getPitchWheel(s)),t+=n}e+=s}r(0|h,Ya.getPitchWheel(i))}static getPitchWheel(e){return Ve.DefaultPitchWheel+e/2*Ya.PitchValuePerSemitone}generateSlide(e,t,s,i,a,r){let n=e.slideOutType===w.Legato?s.noteOnly:s.untilTieOrSlideEnd,o=[],h=e.beat.voice.bar.staff.track;const l=this._settings.player.slide.simpleSlidePitchOffset,d=Math.floor(se.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),c=Math.floor(se.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case _.IntoFromAbove:o.push(new se(0,l)),o.push(new se(d,0));break;case _.IntoFromBelow:o.push(new se(0,-l)),o.push(new se(d,0))}switch(e.slideOutType){case w.Legato:case w.Shift:o.push(new se(c,0));const t=2*(e.slideTarget.calculateRealValue(this.applyTranspositionPitches,!0)-e.calculateRealValue(this.applyTranspositionPitches,!0));o.push(new se(se.MaxPosition,t));break;case w.OutDown:o.push(new se(se.MaxPosition-d,0)),o.push(new se(se.MaxPosition,-l));break;case w.OutUp:o.push(new se(se.MaxPosition-d,0)),o.push(new se(se.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){let n=e.bendPoints,o=e.beat.voice.bar.staff.track;const h=(e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)};let l,u=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend&&t.tieDestination.vibrato==B.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!==f.None){switch(e.tieDestination.bendType){case c.Bend:case c.BendRelease:case c.PrebendBend:u=e.tieDestination.bendPoints[1].value;break;case c.Prebend:case c.PrebendRelease:u=e.tieDestination.bendPoints[0].value}l=Math.max(s.noteOnly,te.millisToTicks(this._settings.player.songBookBendDuration,r))}else l=s.noteOnly;n[0].value>0&&!e.isContinuedBend&&t>0&&t--;const p=Math.min(l,te.millisToTicks(this._settings.player.songBookBendDuration,r));let g=[];switch(e.bendType){case c.Custom:g=n;break;case c.Bend:case c.Release:switch(e.bendStyle){case d.Default:g=n;break;case d.Gradual:g.push(new se(0,e.bendPoints[0].value)),(!u||u<e.bendPoints[1].value)&&(u=e.bendPoints[1].value),g.push(new se(se.MaxPosition,u));break;case d.Fast:return(!u||u<e.bendPoints[1].value)&&(u=e.bendPoints[1].value),void(e.beat.graceType===f.BendGrace?this.generateSongBookWhammyOrBend(t,l,!0,[e.bendPoints[0].value,u],p,r,h):this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,u],p,r,h))}break;case c.BendRelease:switch(e.bendStyle){case d.Default:g=n;break;case d.Gradual:g.push(new se(0,e.bendPoints[0].value)),g.push(new se(se.MaxPosition/2|0,e.bendPoints[1].value)),g.push(new se(se.MaxPosition,e.bendPoints[2].value));break;case d.Fast:return void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],p,r,h)}break;case c.Hold:case c.Prebend:g=n;break;case c.PrebendBend:switch(e.bendStyle){case d.Default:g=n;break;case d.Gradual:g.push(new se(0,e.bendPoints[0].value)),g.push(new se(se.MaxPosition,e.bendPoints[1].value));break;case d.Fast:return h(t,0|Ya.getPitchWheel(e.bendPoints[0].value)),(!u||u<e.bendPoints[1].value)&&(u=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,u],p,r,h)}break;case c.PrebendRelease:switch(e.bendStyle){case d.Default:g=n;break;case d.Gradual:g.push(new se(0,e.bendPoints[0].value)),g.push(new se(se.MaxPosition,e.bendPoints[1].value));break;case d.Fast:return h(t,0|Ya.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,e.bendPoints[1].value],p,r,h)}}this.generateWhammyOrBend(t,l,g,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=Ya.getPitchWheel(i[e]),s=Ya.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 A.Custom:l=r;break;case A.Dive:switch(e.whammyStyle){case d.Default:l=r;break;case d.Gradual:l.push(new se(0,r[0].value)),l.push(new se(se.MaxPosition,r[1].value));break;case d.Fast:const e=Math.min(o,te.millisToTicks(this._settings.player.songBookBendDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!1,[r[0].value,r[1].value],e,a,h)}break;case A.Dip:switch(e.whammyStyle){case d.Default:l=r;break;case d.Gradual:l.push(new se(0,r[0].value)),l.push(new se(se.MaxPosition/2|0,r[1].value)),l.push(new se(se.MaxPosition,r[2].value));break;case d.Fast:const e=Math.min(o,te.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 A.Hold:case A.Predive:l=r;break;case A.PrediveDive:switch(e.whammyStyle){case d.Default:l=r;break;case d.Gradual:l.push(new se(0,r[0].value)),l.push(new se(se.MaxPosition/2|0,r[0].value)),l.push(new se(se.MaxPosition,r[1].value));break;case d.Fast:const e=Ya.getPitchWheel(r[0].value);this._handler.addBend(n.index,t,i,0|e);const s=Math.min(o,te.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/se.MaxPosition;for(let t=0;t<s.length-1;t++){const n=s[t],o=s[t+1],h=Ya.getPitchWheel(n.value),l=Ya.getPitchWheel(o.value),d=r*(o.offset-n.offset),c=e+r*n.offset;this.generateBendValues(c,d,h,l,i,a)}}generateBendValues(e,t,s,i,a,r){const n=te.ticksToMillis(t,a),o=Math.abs(i-s)/Ya.PitchValuePerSemitone,h=Math.max(Ya.MinBreakpointsPerSemitone*o,n/Ya.MillisecondsPerBreakpoint),l=t/h,d=(i-s)/h,c=e+t;for(let t=0;t<h;t++)r(0|e,Math.round(s)),s+=d,e+=l;r(0|c,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,d=n.durations[s];this._handler.addNote(e.index,o+l,d-l,i,a,r),o+=d}}generateTrill(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=te.toTicks(e.trillSpeed),l=!0,d=t,c=t+s.untilTieOrSlideEnd;for(;d+10<c;)d+h>=c&&(h=c-d),this._handler.addNote(n.index,d,h,l?o:i,a,r),l=!l,d+=h}generateTremoloPicking(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track;let o=te.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 Ja,i=Ya.RasgueadoDurations.get(e.rasgueado).reduce(((e,t)=>e+t),0);s.durations=Ya.RasgueadoDurations.get(e.rasgueado).map((e=>t*e/i)),s.brushInfos=new Array(s.durations.length);const a=te.toTicks(g.Sixteenth);let r=0,n=0;for(const t of e.notes)t.isTieDestination||(r|=1<<t.string-1,n++);const o=Ya.RasgueadoDirections.get(e.rasgueado);for(let t=0;t<s.durations.length;t++){const i=s.durations[t]*a/te.QuarterTime,h=new Int32Array(e.voice.bar.staff.tuning.length);s.brushInfos[t]=h;const l=o[t];l!==u.None&&this.fillBrushInfo(e,h,l===u.ArpeggioDown||l===u.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===u.ArpeggioDown||e.brushType===u.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++){let 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 r.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 r.Balance:let i=Ya.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Os.PanCoarse,i),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Os.PanCoarse,i);break;case r.Volume:let a=Ya.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Os.VolumeCoarse,a),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Os.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 r.Instrument:s=i.value;break;case r.Tempo:t=i.value}i=i.previousBeat}const a=e.voice.bar.staff.track,n=e.voice.bar.masterBar;-1===t&&(t=n.score.tempo);const o=e.playbackStart/n.calculateDuration();for(const e of n.tempoAutomations){if(!(e.ratioPosition<=o))break;t=e.value}-1===s&&(s=a.playbackInfo.program);const h=a.playbackInfo.volume;this.generateTrack(a),this._handler.addTimeSignature(0,n.timeSignatureNumerator,n.timeSignatureDenominator),this._handler.addTempo(0,t);let l=Ya.toChannelShort(h);return this._handler.addControlChange(0,0,a.playbackInfo.primaryChannel,Os.VolumeCoarse,l),this._handler.addControlChange(0,0,a.playbackInfo.secondaryChannel,Os.VolumeCoarse,l),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)}}Ya.DefaultDurationDead=30,Ya.DefaultDurationPalmMute=80,Ya.OrnamentKeysUp=[2,2,2,1,1,2,2,2,2,2,1,1],Ya.OrnamentKeysDown=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],Ya.PitchBendRangeInSemitones=16,Ya.PitchValuePerSemitone=Ve.DefaultPitchWheel/Ya.PitchBendRangeInSemitones,Ya.MinBreakpointsPerSemitone=6,Ya.MillisecondsPerBreakpoint=150,Ya.RasgueadoDirections=new Map([[G.Ii,[u.BrushDown,u.BrushUp]],[G.Mi,[u.BrushDown,u.BrushDown]],[G.MiiTriplet,[u.BrushDown,u.BrushDown,u.BrushUp]],[G.MiiAnapaest,[u.BrushDown,u.BrushDown,u.BrushUp]],[G.PmpTriplet,[u.BrushUp,u.BrushDown,u.BrushDown]],[G.PmpAnapaest,[u.BrushUp,u.BrushDown,u.BrushDown]],[G.PeiTriplet,[u.BrushUp,u.BrushDown,u.BrushDown]],[G.PeiAnapaest,[u.BrushUp,u.BrushDown,u.BrushDown]],[G.PaiTriplet,[u.BrushUp,u.BrushDown,u.BrushDown]],[G.PaiAnapaest,[u.BrushUp,u.BrushDown,u.BrushDown]],[G.AmiTriplet,[u.BrushDown,u.BrushDown,u.BrushDown]],[G.AmiAnapaest,[u.BrushDown,u.BrushDown,u.BrushDown]],[G.Ppp,[u.None,u.BrushDown,u.BrushUp]],[G.Amii,[u.BrushDown,u.BrushDown,u.BrushDown,u.BrushUp]],[G.Amip,[u.BrushDown,u.BrushDown,u.BrushDown,u.BrushUp]],[G.Eami,[u.BrushDown,u.BrushDown,u.BrushDown,u.BrushDown]],[G.Eamii,[u.BrushDown,u.BrushDown,u.BrushDown,u.BrushDown,u.BrushUp]],[G.Peami,[u.BrushDown,u.BrushDown,u.BrushDown,u.BrushDown,u.BrushUp]]]),Ya.RasgueadoDurations=new Map([[G.Ii,[te.toTicks(g.Eighth),te.toTicks(g.Eighth)]],[G.Mi,[te.toTicks(g.Eighth),te.toTicks(g.Eighth)]],[G.MiiTriplet,[te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3]],[G.MiiAnapaest,[te.toTicks(g.Sixteenth),te.toTicks(g.Sixteenth),te.toTicks(g.Eighth)]],[G.PmpTriplet,[te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3]],[G.PmpAnapaest,[te.toTicks(g.Sixteenth)/3,te.toTicks(g.Sixteenth)/3,te.toTicks(g.Eighth)/3]],[G.PeiTriplet,[te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3]],[G.PeiAnapaest,[te.toTicks(g.Sixteenth),te.toTicks(g.Sixteenth),te.toTicks(g.Eighth)]],[G.PaiTriplet,[te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3]],[G.PaiAnapaest,[te.toTicks(g.Sixteenth),te.toTicks(g.Sixteenth),te.toTicks(g.Eighth)]],[G.AmiTriplet,[te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3]],[G.AmiAnapaest,[te.toTicks(g.Sixteenth)/3,te.toTicks(g.Sixteenth)/3,te.toTicks(g.Eighth)/3]],[G.Ppp,[te.toTicks(g.Sixteenth)/3,te.toTicks(g.Sixteenth)/3,te.toTicks(g.Eighth)/3]],[G.Amii,[te.toTicks(g.Sixteenth)/3,te.toTicks(g.Sixteenth)/3,te.toTicks(g.Sixteenth)/3,te.toTicks(g.Eighth)]],[G.Amip,[te.toTicks(g.Sixteenth)/3,te.toTicks(g.Sixteenth)/3,te.toTicks(g.Sixteenth)/3,te.toTicks(g.Eighth)]],[G.Eami,[te.toTicks(g.Sixteenth),te.toTicks(g.Sixteenth),te.toTicks(g.Sixteenth),te.toTicks(g.Sixteenth)]],[G.Eamii,[te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5]],[G.Peami,[te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5]]]);class qa{constructor(){this.startTick=0,this.endTick=0}}class ja{constructor(e,t){this.width=0,this.height=0,this.x=e,this.y=t}doLayout(){}paint(e,t,s){}}class Ka extends ja{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Qa extends Ka{constructor(e,t,s,i){super(e,t),this.glyphScale=0,this.center=!1,this.glyphScale=s,this.symbol=i}paint(e,t,s){s.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale,this.symbol,this.center)}}class $a extends Qa{constructor(e,t,s,i){super(e,t,i?$a.GraceScale:1,$a.getSymbol(s)),this._isGrace=i,this._duration=s}paint(e,t,s){let i=this._isGrace?1:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale,this.symbol,!1)}doLayout(){let e=this._isGrace?$a.GraceScale:1;switch(this._duration){case g.QuadrupleWhole:this.width=14*e;break;case g.DoubleWhole:case g.Whole:this.width=14*(this._isGrace?$a.GraceScale:1);break;default:this.width=$a.QuarterNoteHeadWidth*(this._isGrace?$a.GraceScale:1)}this.height=$a.NoteHeadHeight*e}static getSymbol(e){switch(e){case g.QuadrupleWhole:return D.NoteheadDoubleWholeSquare;case g.DoubleWhole:return D.NoteheadDoubleWhole;case g.Whole:return D.NoteheadWhole;case g.Half:return D.NoteheadHalf;default:return D.NoteheadBlack}}}$a.GraceScale=.75,$a.NoteHeadHeight=8,$a.QuarterNoteHeadWidth=9;class Za extends Qa{constructor(e,t,s,i,a){super(e,t,a?$a.GraceScale:1,Za.getSymbol(s,i,a))}doLayout(){this.width=0}static getSymbol(e,t,s){if(s&&(e=g.Eighth),t===We.Up)switch(e){case g.Eighth:return D.FlagEighthUp;case g.Sixteenth:return D.FlagSixteenthUp;case g.ThirtySecond:return D.FlagThirtySecondUp;case g.SixtyFourth:return D.FlagSixtyFourthUp;case g.OneHundredTwentyEighth:return D.FlagOneHundredTwentyEighthUp;case g.TwoHundredFiftySixth:return D.FlagTwoHundredFiftySixthUp;default:return D.FlagEighthUp}switch(e){case g.Eighth:return D.FlagEighthDown;case g.Sixteenth:return D.FlagSixteenthDown;case g.ThirtySecond:return D.FlagThirtySecondDown;case g.SixtyFourth:return D.FlagSixtyFourthDown;case g.OneHundredTwentyEighth:case g.TwoHundredFiftySixth:return D.FlagOneHundredTwentyEighthDown;default:return D.FlagEighthDown}}}Za.FlagWidth=11;class er extends ja{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){let t=this.preNotes.computedWidth+this.onNotes.centerX,s=this.onNotes.computedWidth-this.onNotes.centerX;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);this.beat.graceType!==f.None?1===this.beat.graceGroup.beats.length?s+=Za.FlagWidth*$a.GraceScale:this.beat.graceIndex<this.beat.graceGroup.beats.length-1?s+=7:s+=er.GraceBeatPadding:i&&this.drawBeamHelperAsFlags(i)&&(s+=Za.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>=g.Eighth&&(this.minWidth+=20);else switch(this.beat.duration){case g.OneHundredTwentyEighth:case g.TwoHundredFiftySixth:this.minWidth+=10}let e=0;for(let 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.beat.voice.isEmpty)return;if(this.preNotes.isEmpty&&this.onNotes.isEmpty&&0===this.ties.length)return;s.beginGroup(er.getGroupId(this.beat)),this.preNotes.paint(e+this.x,t+this.y,s),this.onNotes.paint(e+this.x,t+this.y,s);let 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++){let t=this.ties[e];t.renderer=this.renderer,t.paint(i,a,s)}s.endGroup()}buildBoundingsLookup(e,t,s,i){let a=new va;if(a.beat=this.beat,this.beat.isEmpty)a.visualBounds=new cs,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 cs,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 cs,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!==f.None)&&(a.visualBounds.w+=Za.FlagWidth*(this.beat.graceType!==f.None?$a.GraceScale:1)),a.visualBounds.y=e.visualBounds.y,a.visualBounds.h=e.visualBounds.h,a.realBounds=new cs,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)}}er.GraceBeatPadding=3;class tr{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new xl}causeIssue(){return this.settings=null,!0}}class sr{constructor(e){this.activeBeats=e}}class ir{constructor(e){this.bounds=null,this.beat=e}}class ar{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=Fs.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=Fs.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new ya,this.activeBeatsChanged=new ya,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new ya,this.beatMouseMove=new ya,this.beatMouseUp=new ya,this.noteMouseDown=new ya,this.noteMouseMove=new ya,this.noteMouseUp=new ya,this.scoreLoaded=new ya,this.resize=new ya,this.renderStarted=new ya,this.renderFinished=new ya,this.postRenderFinished=new fa,this.error=new ya,this.playerReady=new fa,this.playerFinished=new fa,this.soundFontLoaded=new fa,this.midiLoad=new ya,this.midiLoaded=new ya,this.playerStateChanged=new ya,this.playerPositionChanged=new ya,this.midiEventsPlayed=new ya,this.playbackRangeChanged=new ya,this.settingsUpdated=new fa,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),ne.logLevel=this.settings.core.logLevel,this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&Nl.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new Da(this.settings),this.container.resize.on(Nl.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));let s=new tr;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((()=>{let e=Date.now()-this._startTime;ne.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&&de.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?(this.setupPlayer(),e&&this.player?.applyTranspositionPitches(Ya.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){let 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(let t of e.tracks)s.push(t);else for(let 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(t){if(t.length>0){let s=t[0].score;for(let i of t)if(i.score!==s)return void this.onError(new K(e.AlphaTabErrorType.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(s,t)}}internalRenderTracks(e,t){if(de.applyPitchOffsets(this.settings,e),e!==this.score){this.score=e,this.tracks=t,this._trackIndexes=[];for(let 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,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this._trackIndexLookup=new Set(this._trackIndexes),this.render()}}triggerResize(){if(this.container.isVisible){let e=new tr;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 ne.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{ne.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{let s=new st;s.logErrors=!0,s.initFromString(e,this.settings);let 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 isReadyForPlayback(){return!!this.player&&this.player.isReadyForPlayback}get playerState(){return this.player?this.player.state:Fs.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=Fs.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(let e of this.tracks){let 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;ne.debug("AlphaTab","Generating Midi");let e=new ht,t=new Ia(e),s=new Ya(this.score,this.settings,t);s.applyTranspositionPitches=!1,s.generate(),this._tickCache=s.tickLookup,this.onMidiLoad(e);const i=this.player;i&&(i.loadMidiFile(e),i.applyTranspositionPitches(s.transpositionPitches))}changeTrackVolume(e,t){if(this.player)for(let s of e)this.player.setChannelVolume(s.playbackInfo.primaryChannel,t),this.player.setChannelVolume(s.playbackInfo.secondaryChannel,t)}changeTrackSolo(e,t){if(this.player)for(let s of e)this.player.setChannelSolo(s.playbackInfo.primaryChannel,t),this.player.setChannelSolo(s.playbackInfo.secondaryChannel,t)}changeTrackMute(e,t){if(this.player)for(let s of e)this.player.setChannelMute(s.playbackInfo.primaryChannel,t),this.player.setChannelMute(s.playbackInfo.secondaryChannel,t)}changeTrackTranspositionPitch(e,t){if(this.player)for(let 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;let t=new ht,s=new Ia(t);new Ya(e.voice.bar.staff.track.score,this.settings,s).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;let t=new ht,s=new Ia(t);new Ya(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){let 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=Fs.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)}))})),this.player.stateChanged.on((e=>{if(this._playerState=e.state,!e.stopped&&e.state===Fs.Paused){let e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getBeatStart(e.beat))}})))}cursorUpdateTick(e,t,s=!1){let i=this._tickCache;if(i){let a=this._trackIndexLookup;if(null!=a&&a.size>0){let r=i.findBeat(a,e,this._currentBeat);r&&this.cursorUpdateBeat(r,t,s)}}}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;let h=this.renderer.boundsLookup;if(!h)return;let l=this._currentBeat,d=this._previousCursorCache,c=this._previousStateForCursor;if(!i&&a===l?.beat&&h===d&&c===this._playerState)return;let 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)})))}scrollToCursor(){const e=this._currentBarBounds;e&&this.internalScrollToCursor(e)}internalScrollToCursor(t){let s=this.uiFacade.getScrollContainer(),i=Nl.getLayoutEngineFactory(this.settings.display.layoutMode).vertical,a=this.settings.player.scrollMode;if(i){let i=t.realBounds.y+this.settings.player.scrollOffsetY;if(i!==this._lastScroll)switch(this._lastScroll=i,a){case e.ScrollMode.Continuous:let a=this.uiFacade.getOffset(s,this.container);this.uiFacade.scrollToY(s,a.y+i,this.settings.player.scrollSpeed);break;case e.ScrollMode.OffScreen:let r=s.scrollTop+this.uiFacade.getOffset(null,s).h;if(t.visualBounds.y+t.visualBounds.h>=r||t.visualBounds.y<s.scrollTop){let e=t.realBounds.y+this.settings.player.scrollOffsetY;this.uiFacade.scrollToY(s,e,this.settings.player.scrollSpeed)}}}else{let i=t.visualBounds.x;if(i!==this._lastScroll)switch(this._lastScroll=i,a){case e.ScrollMode.Continuous:let i=t.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=t.visualBounds.x,this.uiFacade.scrollToX(s,i,this.settings.player.scrollSpeed);break;case e.ScrollMode.OffScreen:let a=s.scrollLeft+this.uiFacade.getOffset(null,s).w;if(t.visualBounds.x+t.visualBounds.w>=a||t.visualBounds.x<s.scrollLeft){let e=t.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=t.visualBounds.x,this.uiFacade.scrollToX(s,e,this.settings.player.scrollSpeed)}}}}internalCursorUpdateBeat(t,s,i,a,r,n,o,h){const l=this._barCursor,d=this._beatCursor;let c=o.barBounds.masterBarBounds,u=c.visualBounds;this._currentBarBounds=c,l&&l.setBounds(u.x,u.y,u.w,u.h),d&&(this.settings.player.enableAnimatedBeatCursor&&d.stopAnimation(),d.setBounds(o.onNotesX,u.y,1,u.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let p=!1;if(this._playerState===Fs.Playing&&!a){if(this.settings.player.enableElementHighlighting)for(let e of r){let s=er.getGroupId(e.beat);this.uiFacade.highlightElements(s,t.voice.bar.index)}if(this.settings.player.enableAnimatedBeatCursor){let e=c.visualBounds.x+c.visualBounds.w;if(s){let t=n.findBeat(s);t&&t.barBounds.masterBarBounds.staffSystemBounds===c.staffSystemBounds&&(e=t.onNotesX)}this.uiFacade.beginInvoke((()=>{d&&d.transitionToX(i/this.playbackSpeed,e)}))}h=!a,p=!0}h&&!this._beatMouseDown&&this.settings.player.scrollMode!==e.ScrollMode.Off&&this.internalScrollToCursor(c),p&&(this.onPlayedBeatChanged(t),this.onActiveBeatsChanged(new sr(r.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 ir(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 ir(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){let e=this._tickCache?.getBeatStart(this._selectionStart.beat)??this._selectionStart.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(this._selectionEnd.beat)??this._selectionEnd.beat.absolutePlaybackStart)<e){let e=this._selectionStart;this._selectionStart=this._selectionEnd,this._selectionEnd=e}}if(this._selectionStart&&this._tickCache){let e=this._tickCache,t=e.getMasterBarStart(this._selectionStart.beat.voice.bar.masterBar);if(this._currentBeat=null,this._playerState===Fs.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){let s=e.getMasterBarStart(this._selectionEnd.beat.voice.bar.masterBar),i=new qa;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 ir(t.beat),i=new ir(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();let 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;let 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();let 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){let s=this.renderer.boundsLookup;if(!s)return;let 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));let a=this._tickCache?.getBeatStart(e.beat)??e.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(t.beat)??t.beat.absolutePlaybackStart)<a){let s=e;e=t,t=s}let r=e.bounds.realBounds.x,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){let 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);let l=e.bounds.barBounds.masterBarBounds.staffSystemBounds.index+1,d=t.bounds.barBounds.masterBarBounds.staffSystemBounds.index;for(let e=l;e<d;e++){let t=s.staffSystems[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),i.appendChild(r)}let c=this.uiFacade.createSelectionElement();c.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(c)}else{let 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||(ne.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))}}class rr extends K{constructor(t,s){super(e.AlphaTabErrorType.General,t),this.xhr=s,Object.setPrototypeOf(this,rr.prototype)}}class nr{static loadScoreAsync(e,t,s,i){let a=new XMLHttpRequest;a.open("GET",e,!0,null,null),a.responseType="arraybuffer",a.onreadystatechange=()=>{if(a.readyState===XMLHttpRequest.DONE){let e=a.response;if(200===a.status||0===a.status&&e)try{let e=a.response,s=new Uint8Array(e),r=nr.loadScoreFromBytes(s,i);t(r)}catch(e){s(e)}else 0===a.status?s(new rr("You are offline!!\n Please Check Your Network.",a)):404===a.status?s(new rr("Requested URL not found.",a)):500===a.status?s(new rr("Internel Server Error.",a)):"parsererror"===a.statusText?s(new rr("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?s(new rr("Request Time out.",a)):s(new rr("Unknow Error: "+a.responseText,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Ot);let s=Nl.buildImporters();ne.debug("ScoreLoader",`Loading score from ${e.length} bytes using ${s.length} importers`);let i=null,a=Oe.fromBuffer(e);for(let e of s){a.reset();try{ne.debug("ScoreLoader","Importing using importer "+e.name),e.init(a,t),i=e.readScore(),ne.debug("ScoreLoader","Score imported using "+e.name);break}catch(t){if(!(t instanceof Q))throw ne.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;ne.debug("ScoreLoader",e.name+" does not support the file")}}if(i)return i;throw new Q("No compatible importer found for file")}}class or{get isLeftMouseButton(){return 0===this.mouseEvent.button}getX(e){let t=e.element,s=t.getBoundingClientRect().left+t.ownerDocument.defaultView.pageXOffset;return this.mouseEvent.pageX-s}getY(e){let 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 hr{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 cs,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new or(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new or(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new or(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&hr.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,hr.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,NaN,NaN,NaN)}setBounds(e,t,s,i){isNaN(e)&&(e=this.lastBounds.x),isNaN(t)&&(t=this.lastBounds.y),isNaN(s)&&(s=this.lastBounds.w),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=""}}hr.resizeObserver=new ae((()=>new ResizeObserver((e=>{for(const t of e){let e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class lr{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new ya,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(Nl.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0,t=window.setInterval((()=>{ne.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);ne.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);let s=e=>{this._families.length>1?(ne.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(ne.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},i=e=>{ne.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 ne.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){ne.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 dr{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 cr{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new fa,this.samplesPlayed=new ya,this.sampleRequest=new fa}get sampleRate(){return this._context?this._context.sampleRate:cr.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(ne.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{ne.debug("WebAudio",`Audio Context resume success: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}`),e&&e()}),(e=>{ne.warning("WebAudio",`Audio Context resume failed: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}, reason=${e}`)})))}patchIosSampleRate(){let e=navigator.userAgent;if(-1!==e.indexOf("iPhone")||-1!==e.indexOf("iPad")){let e=this.createAudioContext(),t=e.createBuffer(1,1,cr.PreferredSampleRate),s=e.createBufferSource();s.buffer=t,s.connect(e.destination),s.start(0),s.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in Nl.globalThis)return new AudioContext;if("webkitAudioContext"in Nl.globalThis)return new webkitAudioContext;throw new K(e.AlphaTabErrorType.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(){let e=this._context;this.activate(),this._buffer=e.createBuffer(2,cr.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()}}cr.BufferSize=4096,cr.PreferredSampleRate=44100;class ur extends cr{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/cr.BufferSize),this._circularBuffer=new dr(cr.BufferSize*this._bufferCount),this.onReady()}play(){super.play();let 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;let t=e*cr.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*cr.BufferSize<t){for(let t=0;t<e;t++)this.onSampleRequest();this._requestedBufferCount+=e}}generateSound(e){let t=e.outputBuffer.getChannelData(0),s=e.outputBuffer.getChannelData(1),i=t.length+s.length,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/Ve.AudioChannels),this.requestBuffers()}}class pr{constructor(e,t){this.loaded=e,this.total=t}}class gr{get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return ne.logLevel}set logLevel(e){ne.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Ve.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Ve.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Ve.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=de.clamp(e,Ve.MinPlaybackSpeed,Ve.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=Fs.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 fa,this.readyForPlayback=new fa,this.finished=new fa,this.soundFontLoaded=new fa,this.soundFontLoadFailed=new ya,this.midiLoaded=new ya,this.midiLoadFailed=new ya,this.stateChanged=new ya,this.positionChanged=new ya,this.midiEventsPlayed=new ya,this.playbackRangeChanged=new ya,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Fs.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=Nl.createWebWorker(t)}catch(e){ne.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:is.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,s){ne.debug("AlphaSynth",`Start loading Soundfont from url ${e}`);let i=new XMLHttpRequest;i.open("GET",e,!0,null,null),i.responseType="arraybuffer",i.onload=e=>{let s=new Uint8Array(i.response);this.loadSoundFont(s,t)},i.onerror=e=>{ne.error("AlphaSynth","Loading failed: "+e.message),this.soundFontLoadFailed.trigger(new rr(e.message,i))},i.onprogress=e=>{ne.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),s(new pr(e.loaded,e.total))},i.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:is.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,Ve.MinVolume),this._synth.postMessage({cmd:"alphaSynth.setChannelVolume",channel:e,volume:t})}handleWorkerMessage(e){let 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 ui(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new ba(t.events.map(is.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new ci(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new Sa(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 ui(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 mr{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new ya,this.partialRenderFinished=new ya,this.partialLayoutFinished=new ya,this.renderFinished=new ya,this.postRenderFinished=new fa,this.error=new ya,this._api=e;try{this._worker=Nl.createWebWorker(t)}catch(e){return void ne.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=is.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){let 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=Fa.fromJson(t.boundsLookup,this._api.score),this.boundsLookup.finish(),this.postRenderFinished.trigger();break;case"alphaTab.error":this.error.trigger(t.error)}}renderScore(e,t){let s=null==e?null:is.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:s,trackIndexes:t,fontSizes:ka.FontSizeLookupTables})}}class fr{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,ne.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new dr(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){let t=e.data;switch(t.cmd){case wa.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case wa.CmdOutputResetSamples:this._circularBuffer.clear();break;case wa.CmdOutputStop:this._isStopped=!0}}process(e,t,s){if(1!==t.length&&2!==t[0].length)return!1;let i=t[0][0],a=t[0][1];if(!i||!a)return!0;let r=i.length+a.length,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:wa.CmdOutputSamplesPlayed,samples:o/Ve.AudioChannels}),this.requestBuffers(),this._circularBuffer.count>0||!this._isStopped}requestBuffers(){const t=this._bufferCount/2|0;let s=t*e.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*e.BufferSize<s){for(let e=0;e<t;e++)this.port.postMessage({cmd:wa.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}yr._isRegistered=!1;class br extends cr{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();let e=this._context;Nl.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=>{ne.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){let t=e.data;switch(t.cmd){case wa.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case wa.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.postMessage({cmd:wa.CmdOutputStop}),this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){this._worklet?.port.postMessage({cmd:wa.CmdOutputAddSamples,samples:e})}resetSamples(){this._worklet?.port.postMessage({cmd:wa.CmdOutputResetSamples})}}class Sr extends hr{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){isNaN(e)&&(e=this.lastBounds.x),isNaN(t)&&(t=this.lastBounds.y),isNaN(s)?s=this.lastBounds.w:s/=this._xscale,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"}(Gs||(Gs={}));class _r{get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(Nl.bravuraFontChecker.checkForFontAvailability(),!Nl.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(ne.debug("Font","All fonts loaded: "+this._fontCheckers.size),!0)}onFontLoaded(e){ka.generateFontLookup(e),this.areAllFontsLoaded()&&this.canRenderChanged.trigger()}constructor(t){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 fa,this.canRenderChanged=new fa,this._highlightedElements=[],this._scrollContainer=null,Nl.webPlatform!==e.WebPlatform.Browser&&Nl.webPlatform!==e.WebPlatform.BrowserModule)throw new K(e.AlphaTabErrorType.General,"Usage of AlphaTabApi is only possible in browser environments. For usage in node use the Low Level APIs");t.classList.add("alphaTab"),this.rootContainer=new hr(t),this.areWorkersSupported="Worker"in window,Nl.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(t)}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!==Gs.RenderRequested&&(s.resultState=Gs.RenderRequested,this._api.renderer.renderResult(s.layoutResultId)):e.replaceChildren():s.resultState===Gs.Detached&&(e.replaceChildren(...s.renderedResult),s.resultState=Gs.RenderDone):s.resultState===Gs.RenderDone&&(s.resultState=Gs.Detached,s.replaceChildren())}}}createWorkerRenderer(){return new mr(this._api,this._api.settings)}initialize(t,s){let i;this._api=t,i=s instanceof Ot?s:is.jsObjectToSettings(s);let a=this.getDataAttributes();Rt.fromJson(i,a),i.notation.notationMode===e.NotationMode.SongBook&&i.setSongBookModeSettings(),t.settings=i,this.setupFontCheckers(i),this._initialTrackIndexes=this.parseTracks(i.core.tracks),this._contents="";let r=t.container;i.core.tex&&(this._contents=r.element.innerHTML,r.element.innerHTML=""),this.createStyleElement(i),this._file=i.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(", "))){let t=new lr(e.families);this._fontCheckers.set(e.families.join(", "),t),t.fontLoaded.on(this.onFontLoaded.bind(this)),t.checkForFontAvailability()}}destroy(){this.rootContainer.element.innerHTML=""}createCanvasElement(){let 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 hr(e)}triggerEvent(e,t,s=null,i){let a=e.element;t="alphaTab."+t;let 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){let e=window.jQuery,i=[];i.push(s),n&&i.push(n),e(a).trigger(t,i)}}load(e,t,s){if(e instanceof ve)return t(e),!0;if(e instanceof ArrayBuffer){let s=new Uint8Array(e);return t(nr.loadScoreFromBytes(s,this._api.settings)),!0}return e instanceof Uint8Array?(t(nr.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(nr.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&&nr.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){let t=this._api.container.element.ownerDocument;Nl.createStyleElement(t,e.core.fontDirectory)}parseTracks(e){if(!e)return[];let 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){let s=e.length,i=e;for(let e=0;e<s;e++){let s=i[e],a=0;a="number"==typeof s?s:"index"in s?s.index:parseInt(s.toString()),(a>=0||-1===a)&&t.push(a)}}else"index"in e&&t.push(e.index);return t}getDataAttributes(){let e=new Map,t=this._api.container.element;if(t.dataset)for(let s of Object.keys(t.dataset)){let i=t.dataset[s];try{let 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++){let i=t.attributes.item(s),a=i.nodeName;if(a.startsWith("data-")){let t=a.substr(5).split("-"),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=Gs.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=Gs.LayoutDone,delete s.renderedResultId,delete s.renderedResult,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 t=null,s="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window&&this._api.settings.player.outputMode===e.PlayerOutputMode.WebAudioAudioWorklets?(ne.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),t=new gr(new br(this._api.settings),this._api.settings)):s&&(ne.debug("Player","Will use webworkers for synthesizing and web audio api with ScriptProcessor for playback"),t=new gr(new ur,this._api.settings)),t?t.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):ne.error("Player","Player requires webworkers and web audio api, browser unsupported",null),t}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const s=this._barToElementLookup.get(t);if(s){let 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(){let e=this._api.container.element,t=e.querySelector(".at-cursors");e.removeChild(t)}createCursors(){let e=this._api.container.element,t=document.createElement("div");t.classList.add("at-cursors");let s=document.createElement("div");s.classList.add("at-selection");const i=this.createScalingElement(),a=this.createScalingElement();let r=i.element;r.classList.add("at-cursor-bar");let 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 fr(new hr(t),i,a,new hr(s))}getOffset(e,t){let s=t.element,i=s.getBoundingClientRect(),a=i.top+s.ownerDocument.defaultView.pageYOffset,r=i.left+s.ownerDocument.defaultView.pageXOffset;if(e){let t=e.element,s=t.nodeName.toLowerCase();if("html"!==s&&"body"!==s){let s=this.getOffset(null,e);a=a+t.scrollTop-s.y,r=r+t.scrollLeft-s.x}}let n=new cs;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,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 hr(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new Sr(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{let i=e.scrollTop,a=t-i,r=0,n=t=>{0===r&&(r=t);let 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{let i=e.scrollLeft,a=t-i,r=0,n=t=>{0===r&&(r=t);let o=t-r,h=Math.min(o/s,1);e.scrollLeft=i+a*h|0,o<s&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}}class wr extends ar{constructor(e,t){super(new _r(e),t),this.soundFontLoad=new ya}tex(e,t){let s=this.uiFacade;super.tex(e,s.parseTracks(t))}print(t,s=null){let i=window.open("","","width=0,height=0"),a=i.document.createElement("div");t?a.style.width=t:this.settings.display.layoutMode===e.LayoutMode.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);let 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,d=a.offsetWidth+50,c=window.innerHeight,u=(h/2|0)-(d/2|0)+n,p=(l/2|0)-(c/2|0)+o;i.resizeTo(d,c),i.moveTo(u,p),i.focus();let g=is.jsObjectToSettings(is.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,Rt.fromJson(g,s);let m=new wr(a,g);i.onunload=()=>{m.destroy()},m.renderer.postRenderFinished.on((()=>{i.print()})),m.renderTracks(this.tracks)}downloadMidi(e=je.SingleTrackMultiChannel){if(!this.score)return;let t=new ht;t.format=e;let s=new Ia(t,!0);new Ya(this.score,this.settings,s).generate();let i=t.toBinary(),a=this.score.title?`${this.score.title}.mid`:"File.mid",r=document.createElement("a");r.download=a;let 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){let s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackMute(s,t)}changeTrackSolo(e,t){let s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackSolo(s,t)}changeTrackVolume(e,t){let s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackVolume(s,t)}trackIndexesToTracks(e){if(!this.score)return[];let t=[];if(1===e.length&&-1===e[0])for(let e of this.score.tracks)t.push(e);else for(let 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 Br{constructor(){this._initListeners=[]}exec(e,t,s){if("string"!=typeof t&&(s=[t],t="init"),95===t.charCodeAt(0)||"exec"===t)return null;let i=new jQuery(e),a=i.data("alphaTab");if("destroy"===t&&!a)return null;if("init"!==t&&!a)throw new Error("alphaTab not initialized");let r=this[t];if(r){let e=[i,a].concat(s);return r.apply(this,e)}return ne.error("Api","Method '"+t+"' does not exist on jQuery.alphaTab"),null}init(e,t,s){if(!t){t=new wr(e[0],s),e.data("alphaTab",t);for(let 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 Tr{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.scale=1,this.color=new Ee(255,255,255,255),this.lineWidth=1,this.font=new nt("Arial",10,Ye.Plain),this.textAlign=L.Left,this.textBaseline=M.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=M.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!==L.Left&&(i+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),i+=`>${Tr.escapeText(e)}</text>`,this.buffer+=i}static escapeText(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}getSvgTextAlignment(e){switch(e){case L.Left:return"start";case L.Center:return"middle";case L.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case M.Top:return"dominant-baseline: hanging";case M.Bottom:return"dominant-baseline: ideographic";default:return""}}measureText(e){return e?ka.measureString(e,this.font.families,this.font.size*this.scale,this.font.style,this.font.weight):new ce(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 kr extends Tr{constructor(){super()}fillMusicFontSymbol(e,t,s,i,a){i!==D.None&&this.fillMusicFontSymbolText(e,t,s,`&#${i};`,a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(let e of i)e!==D.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(L.Center)+'"'),this.buffer+=`>${i}</text></g>`}}class Nr{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"}(Ws||(Ws={}));class xr extends ja{get isEmpty(){return!this.glyphs||0===this.glyphs.length}constructor(e,t){super(e,t),this.glyphs=null}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++){let 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){let i=this.glyphs;if(i&&0!==i.length)for(let a of i)a.paint(e+this.x,t+this.y,s)}}class vr extends xr{constructor(){super(0,0),this.glyphs=[]}addGlyph(e){e.x=0===this.glyphs.length?0:this.glyphs[this.glyphs.length-1].x+this.glyphs[this.glyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.width=e.x+e.width,super.addGlyph(e)}}class Pr extends xr{constructor(e,t,s){super(e,t),this.voice=s,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){let t=this.renderer.layoutingInfo.spaceToForce(e);this.scaleToForce(t)}scaleToForce(e){this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e);let t=this.renderer.layoutingInfo.buildOnTimePositions(e),s=this.beatGlyphs;for(let e=0,i=s.length;e<i;e++){let a=s[e];if(a.beat.graceType===f.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;let e=this.renderer.layoutingInfo.allGraceRods.get(r);const s=a.beat.graceGroup.beats[a.beat.graceGroup.beats.length-1].nextBeat,n=s?this.renderer.layoutingInfo.getPreBeatSize(s)+er.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{let t=this.renderer.layoutingInfo.incompleteGraceRods.get(r);const 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){let t=a.x-s[e-1].x;s[e-1].scaleToWidth(t)}if(e===i-1){let e=this.width-s[s.length-1].x;a.scaleToWidth(e)}}}registerLayoutingInfo(e){let t=this.beatGlyphs;for(let s of t)s.registerLayoutingInfo(e)}applyLayoutingInfo(e){let t=this.beatGlyphs;for(let s of t)s.applyLayoutingInfo(e);this.scaleToForce(Math.max(this.renderer.settings.display.stretchForce,e.minStretchForce))}addGlyph(e){let 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){s.color=0===this.voice.index?this.renderer.resources.mainGlyphColor:this.renderer.resources.secondaryGlyphColor;for(let i=0,a=this.beatGlyphs.length;i<a;i++)this.beatGlyphs[i].paint(e+this.x,t+this.y,s)}}Pr.KeySizeBeat="Beat";class Cr{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class Er{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:pe.getArticulationByValue(t)?.staffLine??0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case S.ForceDoubleFlat:t+=2;break;case S.ForceDoubleSharp:t-=2;break;case S.ForceFlat:t+=1;break;case S.ForceSharp:t-=1}return t}applyAccidental(e){const t=Er.getNoteValue(e);let 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=Er.getNoteValue(t);return s=e.staff.isPercussion?Er.getPercussionLine(e,i):Er.calculateNoteLine(e,i),s}static computeAccidental(e,t,s,i,a=null){let r=e+7,n=s%12,o=r<7?Je.Flat:Je.Sharp,h=Er.KeySignatureLookup[r][n],l=Er.AccidentalNotes[n],d=Je.None;if(i)switch(d=l?o:Je.Natural,d){case Je.Natural:d=Je.NaturalQuarterNoteUp;break;case Je.Sharp:d=Je.SharpQuarterNoteUp;break;case Je.Flat:d=Je.FlatQuarterNoteUp}else{switch(t){case S.ForceSharp:d=Je.Sharp;break;case S.ForceDoubleSharp:d=Je.DoubleSharp;break;case S.ForceFlat:d=Je.Flat;break;case S.ForceDoubleFlat:d=Je.DoubleFlat;break;default:l?d=o:h&&(d=Je.Natural)}d!==Je.None?null!=a?a===d&&(d=Je.None):h&&d===o&&(d=Je.None):null!==a&&(d=a===Je.Natural?Je.None:Je.Natural)}return d}getAccidental(e,t,s,i,a=null){let r=0,n=Je.None;if(this._bar.staff.isPercussion)r=Er.getPercussionLine(this._bar,e);else{const s=a?a.accidentalMode:S.Default;r=Er.calculateNoteLine(this._bar,e);const i=this._registeredAccidentals.has(r)?this._registeredAccidentals.get(r):null;n=Er.computeAccidental(this._bar.masterBar.keySignature,s,e,t,i);let o=!1;switch(n){case Je.NaturalQuarterNoteUp:case Je.SharpQuarterNoteUp:case Je.FlatQuarterNoteUp:break;default:if(a&&a.isTieDestination&&0===a.beat.index){const e=this._barRenderer.previousRenderer;if(e){e.accidentalHelper.getNoteLine(a.tieOrigin)===r&&(o=!0)}}o?n=Je.None:n!==Je.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 Cr,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 calculateNoteLine(e,t){let s=t,i=e.masterBar.keySignature,a=e.clef,r=s%12,n=(s/12|0)-1,o=Er.OctaveSteps[a];return o-=n*Er.StepsPerOctave,o-=(de.keySignatureIsSharp(i)||de.keySignatureIsNatural(i)?Er.SharpNoteSteps:Er.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}}Er.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]],Er.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],Er.StepsPerOctave=7,Er.OctaveSteps=[38,32,30,26,38],Er.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],Er.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class Fr{constructor(){this.staffId="",this.up=0,this.down=0}}class Dr{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 Lr{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>g.Whole}hasFlag(e,t){return e&&this.beatHasFlag(t)||!e&&1===this.beats.length&&this.beatHasFlag(this.beats[0])}beatHasFlag(e){return!e.isRest&&(e.duration>g.Quarter||e.graceType!==f.None)}constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=g.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=We.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===We.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){let 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 Fr),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(We.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==f.None)&&(e=this.invert(We.Up)):e=We.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){let t=this._renderer.getNoteY(this.highestNoteInHelper,Us.Center),s=this._renderer.getNoteY(this.lowestNoteInHelper,Us.Center);if(null===e){const i=(t+s)/2;e=this.invert(this._renderer.middleYPosition<i?We.Up:We.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(We.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case g.QuadrupleWhole:case g.DoubleWhole:return[2,2];case g.Whole:return[0,1];case g.Half:return[1,0];case g.Quarter:return[3,3];case g.Eighth:return[2,2];case g.Sixteenth:return[2,4];case g.ThirtySecond:return[4,4];case g.SixtyFourth:return[4,6];case g.OneHundredTwentyEighth:return[6,6];case g.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=Lr.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===We.Down?We.Up:We.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 W.Auto:case W.ForceSplitOnSecondaryToNext:t=Lr.canJoin(this.beats[this.beats.length-1],e);break;case W.ForceSplitToNext:t=!1;break;case W.ForceMergeWithNext:t=!0}return t&&(null==this.preferredBeamDirection&&null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.hasTuplet&&(this.hasTuplet=!0),e.graceType!==f.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=-Er.getPercussionLine(this.voice.bar,Er.getNoteValue(e)),s=t):(t=Er.getNoteValue(e),s=t,e.harmonicType!==b.None&&e.harmonicType!==b.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===f.BendGrace||t.graceType===f.BendGrace)return!1;if(e.graceType!==f.None&&t.graceType!==f.None)return!0;let s=e.voice.bar;if(s!==t.voice.bar)return!1;let i=e.playbackStart,a=t.playbackStart;if(!Lr.canJoinDuration(e.duration)||!Lr.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=te.QuarterTime;if(8===s.masterBar.timeSignatureDenominator)s.masterBar.timeSignatureNumerator%3==0&&(r+=te.QuarterTime/2|0);return((r+i)/r|0)===((r+a)/r|0)}static canJoinDuration(e){switch(e){case g.Whole:case g.Half:case g.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,s){return de.getIndex(e.duration)-2-s>0&&de.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 Mr{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class Ir{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new Mr(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 Ar{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 Ir(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=Lr.computeLineHeightsForRest(e.duration).map((e=>e*s));let a=t-i[0],r=t+i[1],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;let t=n+i[0]+i[1];const r=2*s;let h=Math.ceil(Math.abs(n-a)/r);return o.addSlot(n,t),n<a?h*-r:h*r}}return 0}}class Rr{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this.preferredBeamDirection=null,this._renderer=e,this.collisionHelper=new Ar}initialize(){var e=this._renderer,t=this._renderer.bar;let s=null,i=null;for(let a=0,r=t.voices.length;a<r;a++){let r=t.voices[a];this.beamHelpers.push([]),this.beamHelperLookup.push(new Map);for(let a=0,n=r.beats.length;a<n;a++){let n,o=r.beats[a];o.graceType!==f.None?n=i:(n=s,i=null),n&&n.checkBeat(o)||(n&&n.finish(),n=new Lr(t.staff,e),n.preferredBeamDirection=this.preferredBeamDirection,n.checkBeat(o),o.graceType!==f.None?i=n:s=n,this.beamHelpers[r.index].push(n)),this.beamHelperLookup[r.index].set(o.index,n)}s&&s.finish(),i&&i.finish(),s=null,i=null}}getBeamingHelperForBeat(e){return this.beamHelperLookup[e.voice.index].get(e.index)}}class Or extends Ka{constructor(e,t,s){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=s}doLayout(){super.doLayout();let e=this.renderer.resources;this._textRow=1.5*e.effectFont.size,this._fretRow=1.5*e.effectFont.size,this._chord.firstFret>1?this._firstFretSpacing=Or.FretSpacing:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+Or.Frets*Or.FretSpacing+2*Or.Padding[1],this.width=this._firstFretSpacing+(this._chord.staff.tuning.length-1)*Or.StringSpacing+2*Or.Padding[0]}paint(e,t,s){e+=this.x+Or.Padding[0]+this._firstFretSpacing,t+=this.y;let i=Or.StringSpacing,a=Or.FretSpacing,r=this.renderer.resources,n=Or.CircleRadius,o=this.width-2*Or.Padding[0]-this._firstFretSpacing,h=s.textAlign,l=s.textBaseline;s.font=r.effectFont,s.textAlign=L.Center,s.textBaseline=M.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=M.Middle;for(let a=0;a<this._chord.staff.tuning.length;a++){let r=e+a*i,n=t+this._fretRow/2,o=this._chord.strings[this._chord.staff.tuning.length-a-1];o<0?s.fillMusicFontSymbol(r,n,1,D.FretboardX,!0):0===o?s.fillMusicFontSymbol(r,n,1,D.FretboardO,!0):(o-=this._chord.firstFret-1,s.fillText(o.toString(),r,n))}t+=this._fretRow;for(let r=0;r<this._chord.staff.tuning.length;r++){let n=e+r*i;s.fillRect(n,t,1,a*Or.Frets+1)}this._chord.firstFret>1&&(s.textAlign=L.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<=Or.Frets;i++){let r=t+i*a;s.fillRect(e,r,o,1)}let d=new Map;for(let e of this._chord.barreFrets){let t=[-1,-1];d.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,d.has(o)){let e=d.get(o);(-1===e[0]||r<e[0])&&(e[0]=r),(-1===e[1]||r>e[1])&&(e[1]=r)}let 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 d){let h=t+r*a+a/2+.5,l=e+(this._chord.strings.length-o[1]-1)*i,d=e+(this._chord.strings.length-o[0]-1)*i;s.fillRect(l,h-n,d-l,2*n)}s.textAlign=h,s.textBaseline=l}}Or.Padding=[5,2],Or.Frets=5,Or.CircleRadius=2.5,Or.StringSpacing=10,Or.FretSpacing=12;class Vr extends xr{constructor(e,t,s=L.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=s}doLayout(){let e=0;switch(this._align){case L.Left:e=0;break;case L.Center:e=(this.width-this._glyphWidth)/2;break;case L.Right:e=this.width-this._glyphWidth}for(let 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 Hr extends xr{constructor(e,t,s=L.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=s}doLayout(){let e=0,t=0,s=Hr.Padding;this._rows=[];let i=new Vr(e,t,this._align);i.width=this.width;for(let 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 Vr(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(let i of this._rows)i.paint(e+this.x,t+this.y,s)}}Hr.Padding=3;class Gr extends Hr{constructor(e,t){super(e,t)}addChord(e){if(e.strings.length>0){let t=new Or(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}}class Wr extends Ka{constructor(e,t,s,i,a=L.Left,r=null){super(e,t),this._lineHeights=null,this._lines=s.split("\n"),this.font=i,this.textAlign=a,this.textBaseline=r}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){let i=s.color;s.color=i,s.font=this.font;let 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}}class zr{get staveId(){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.staveId,e)}addBar(e,t){let s;s=e?this._factory.create(this.system.layout.renderer,e):new sn(this.system.layout.renderer,e),s.staff=this,s.index=this.barRenderers.length,s.layoutingInfo=t,s.doLayout(),s.registerLayoutingInfo();const i=s.barDisplayWidth;i>0&&this.system.layout.systemsLayoutMode==zs.FromModelWithWidths&&(s.width=i),this.barRenderers.push(s),e&&this.system.layout.registerBarRenderer(this.staveId,s)}revertLastBar(){let e=this.barRenderers[this.barRenderers.length-1];this.barRenderers.splice(this.barRenderers.length-1,1),this.system.layout.unregisterBarRenderer(this.staveId,e);for(const e of this.barRenderers)e.applyLayoutingInfo();return e}scaleToWidth(e){this._sharedLayoutData=new Map;let t=this.topOverflow,s=0;switch(this.system.layout.systemsLayoutMode){case zs.Automatic:let i=(e-this.system.computedWidth)/this.barRenderers.length;for(const e of this.barRenderers){e.x=s,e.y=this.topSpacing+t;let a=e.computedWidth+i;e.scaleToWidth(a),s+=e.width}break;case zs.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 zs.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++){let 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++){let 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,this.height=Math.max(this.height,this.barRenderers[e].height),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 Ur{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 Xr{constructor(){this._timeSortedSprings=[],this._xMin=0,this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,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!==f.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!==f.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 Ur,r.timePosition=e,r.allDurations.add(t),this._timeSortedSprings.length>0){let e=this._timeSortedSprings[this._timeSortedSprings.length-1];for(const t of e.allDurations)e.timePosition}r.longestDuration=t,r.postSpringWidth=a,r.graceBeatWidth=s,r.preBeatWidth=i,this.springs.set(e,r);let n=this._timeSortedSprings,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){let i=e.absoluteDisplayStart;if(e.graceType!==f.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));let 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 Ur;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(){this._xMin=0;let e=this.springs;for(const t of e.values())t.springWidth<this._xMin&&(this._xMin=t.springWidth);let t=0,s=this._timeSortedSprings;if(0===s.length)return this.totalSpringConstant=-1,void(this.minStretchForce=-1);for(let e=0;e<s.length;e++){let i=s[e],a=0;if(e===s.length-1)a=i.longestDuration;else{let t=s[e+1];a=Math.abs(t.timePosition-i.timePosition)}i.springConstant=this.calculateSpringConstant(i,a),t+=1/i.springConstant}this.totalSpringConstant=1/t,this.minStretchForce=0;for(let e=0;e<s.length;e++){let t=s[e],i=0;if(e===s.length-1)i=t.postSpringWidth;else{let a=s[e+1];i=t.postSpringWidth+a.preSpringWidth}0===e&&(i+=t.preSpringWidth);let a=i*t.springConstant;this.updateMinStretchForce(a)}}paint(e,t,s){}calculateSpringConstant(e,t){return t<=0&&(t=te.toTicks(g.SixtyFourth)),0===e.smallestDuration&&(e.smallestDuration=t),e.smallestDuration/t*(1/((1+.85*Math.log2(t/Xr.MinDuration))*Xr.MinDurationWidth))}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(de.isAlmostEqualTo(this._onTimePositionsForce,e)&&this._onTimePositions)return this._onTimePositions;this._onTimePositionsForce=e;let t=new Map;this._onTimePositions=t;let 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}}Xr.MinDuration=30,Xr.MinDurationWidth=7;class Jr{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.renderers=[]}}class Yr{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 qr{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);if(this.width=3,!this.drawAsBrace||!this.firstStaffInBracket||!this.lastStaffInBracket)return;const e=this.firstStaffInBracket.contentTop,t=(this.lastStaffInBracket.contentBottom-e)/Nl.MusicFontSize;this.braceScale=t,this.width=3*this.braceScale}}class jr extends qr{constructor(e){super(),this.track=e,this.drawAsBrace=jr.isTrackDrawAsBrace(e)}includesStaff(e){return e.modelStaff.track===this.track}static isTrackDrawAsBrace(e){return e.staves.filter((e=>e.showStandardNotation)).length>1}}class Kr extends jr{constructor(e){super(e)}includesStaff(e){return e.modelStaff.track===this.track||!this.drawAsBrace&&this.track.playbackInfo.program==e.modelStaff.track.playbackInfo.program}}class Qr{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++){let i=this.staves[e];for(let e=0,a=i.staves.length;e<a;e++){let a=i.staves[e],r=t.renderers[s++];a.addBarRenderer(r)}}return this.calculateAccoladeSpacing(e),this.updateWidthFromLastBar(),t}addBars(e,t){if(0===e.length)return null;let s=new Jr;s.layoutingInfo=new Xr,s.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(s);let i=s.layoutingInfo;for(let e of this.staves)for(let a of e.staves){let r=e.track.staves[a.modelStaff.index].bars[t];a.addBar(r,i);let n=a.barRenderers[a.barRenderers.length-1];s.renderers.push(n),n.isLinkedToPrevious&&(s.isLinkedToPrevious=!0),n.canWrap||(s.canWrap=!1)}return this.calculateAccoladeSpacing(e),i.finish(),s.width=this.updateWidthFromLastBar(),s}revertLastBar(){if(this.masterBarsRenderers.length>1){let 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++){let i=this._allStaves[e].revertLastBar();const 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++){let i=this._allStaves[s];const 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(t){const s=this.layout.renderer.settings;if(!this._accoladeSpacingCalculated){this._accoladeSpacingCalculated=!0,this.accoladeWidth=0;const i=this.layout.renderer.score.stylesheet;if(this.layout.renderer.settings.notation.isNotationElementVisible(e.NotationElement.TrackNames)){const e=1===this.layout.renderer.tracks.length?i.singleTrackTrackNamePolicy:i.multiTrackTrackNamePolicy,a=0===this.index?i.firstSystemTrackNameMode:i.otherSystemsTrackNameMode,r=0===this.index?i.firstSystemTrackNameOrientation:i.otherSystemsTrackNameOrientation;let n=!1;switch(e){case X.Hidden:break;case X.FirstSystem:n=0===this.index;break;case X.AllSystems:n=!0}let o=!1;if(n){let e=this.layout.renderer.canvas,i=s.display.resources.effectFont;e.font=i;for(let s of t){let t="";switch(a){case J.FullName:t=s.name;break;case J.ShortName:t=s.shortName}if(t.length>0){o=!0;const s=e.measureText(t);switch(r){case Y.Horizontal:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,s.width));break;case Y.Vertical:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,s.height))}}}o&&(this.accoladeWidth+=s.display.systemLabelPaddingLeft,this.accoladeWidth+=s.display.systemLabelPaddingRight)}}let a=0;for(let e of this._allStaves)e.y=a,e.calculateHeightForAccolade(),a+=e.height;let r=0;for(const e of this._brackets)e.finalizeBracket(),r=Math.max(r,e.width);this.accoladeWidth+=r,this.width+=this.accoladeWidth,this.computedWidth+=this.accoladeWidth}}getStaffTrackGroup(e){for(let t=0,s=this.staves.length;t<s;t++){let s=this.staves[t];if(s.track===e)return s}return null}addStaff(e,t){let s=this.getStaffTrackGroup(e);if(s||(s=new Yr(this,e),this.staves.push(s)),t.staffTrackGroup=s,t.system=this,t.index=this._allStaves.length,this._allStaves.push(t),s.addStaff(t),t.isInsideBracket){this._firstStaffInBrackets||(this._firstStaffInBrackets=t,t.isFirstInSystem=!0),s.firstStaffInBracket||(s.firstStaffInBracket=t),this._lastStaffInBrackets=t,s.lastStaffInBracket=t;let i=this._brackets.find((e=>e.includesStaff(t)));if(!i)switch(e.score.stylesheet.bracketExtendMode){case U.NoBrackets:break;case U.GroupStaves:i=new jr(e),i.index=this._brackets.length,this._brackets.push(i);break;case U.GroupSimilarInstruments:i=new Kr(e),i.index=this._brackets.length,this._brackets.push(i)}i&&(i.firstStaffInBracket||(i.firstStaffInBracket=t),i.lastStaffInBracket=t,s.bracket=i)}}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){t+=this.topPadding,this.paintPartial(e+this.x,t+this.y,s,0,this.masterBarsRenderers.length),this._hasSystemSeparator&&(s.fillMusicFontSymbol(e+this.x,t+this.y+this.height-10,1,D.SystemDivider,!1),s.fillMusicFontSymbol(e+this.x+this.width-Qr.SystemSignSeparatorWidth,t+this.y+this.height-Qr.SystemSignSeparatorPadding,1,D.SystemDivider,!1))}paintPartial(t,s,i,a,r){for(let e=0,n=this._allStaves.length;e<n;e++)this._allStaves[e].paint(t,s,i,a,r);let n=this.layout.renderer.settings.display.resources;if(this.staves.length>0&&0===a){i.color=n.barSeparatorColor;const a=this._firstStaffInBrackets,r=this._lastStaffInBrackets;if(a&&r){let e=s+a.contentTop,n=s+r.contentBottom,o=t+a.x;i.beginPath(),i.moveTo(o,e),i.lineTo(o,n),i.stroke()}const o=this.layout.renderer.settings,h=this.layout.renderer.settings.notation.isNotationElementVisible(e.NotationElement.TrackNames);if(i.font=n.effectFont,h){const e=this.layout.renderer.score.stylesheet,a=1===this.layout.renderer.tracks.length?e.singleTrackTrackNamePolicy:e.multiTrackTrackNamePolicy,r=0===this.index?e.firstSystemTrackNameMode:e.otherSystemsTrackNameMode,n=0===this.index?e.firstSystemTrackNameOrientation:e.otherSystemsTrackNameOrientation;let h=!1;switch(a){case X.Hidden:break;case X.FirstSystem:h=0===this.index;break;case X.AllSystems:h=!0}if(h){const e=i.textBaseline,a=i.textAlign;for(const e of this.staves)if(e.firstStaffInBracket&&e.lastStaffInBracket){let a=s+e.firstStaffInBracket.contentTop,h=s+e.lastStaffInBracket.contentBottom,l="";switch(r){case J.FullName:l=e.track.name;break;case J.ShortName:l=e.track.shortName}if(l.length>0){const s=t+e.firstStaffInBracket.x-o.display.accoladeBarPaddingRight-(e.bracket?.width??0)-o.display.systemLabelPaddingRight;switch(n){case Y.Horizontal:i.textBaseline=M.Middle,i.textAlign=L.Right,i.fillText(l,s,(a+h)/2);break;case Y.Vertical:i.textBaseline=M.Bottom,i.textAlign=L.Center;const e=.1;i.beginRotate(s,(a+h)/2,-90-e),i.fillText(l,0,0),i.endRotate()}}}i.textBaseline=e,i.textAlign=a}}for(const e of this._brackets)if(e.firstStaffInBracket&&e.lastStaffInBracket){const a=t+e.firstStaffInBracket.x,r=e.width,n=o.display.accoladeBarPaddingRight;let h=s+e.firstStaffInBracket.contentTop,l=s+e.lastStaffInBracket.contentBottom;if(e.drawAsBrace)i.fillMusicFontSymbol(a-n-r,l,e.braceScale,D.Brace);else if(e.firstStaffInBracket!==e.lastStaffInBracket){const e=r/2;h-=e,l+=2*e,i.fillRect(a-n-r,h,r,Math.ceil(l-h));let t=a-n-r-.5;i.fillMusicFontSymbol(t,h,1,D.BracketTop),i.fillMusicFontSymbol(t,Math.floor(l),1,D.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+=Qr.SystemSignSeparatorHeight,this._hasSystemSeparator=!0);let t=0;for(let 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;let 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),d=n-r,c=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 Ea;g.visualBounds=new cs,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 cs,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);let m=new Map;for(let e=0;e<this.staves.length;e++)for(let s of this.staves[e].stavesRelevantForBoundsLookup)for(let e of s.barRenderers){let i;m.has(e.bar.masterBar.index)?i=m.get(e.bar.masterBar.index):(i=new Pa,i.index=e.bar.masterBar.index,i.isFirstOfLine=e.isFirstOfLine,i.realBounds=new cs,i.realBounds.x=p+e.x,i.realBounds.y=o,i.realBounds.w=e.width,i.realBounds.h=u,i.visualBounds=new cs,i.visualBounds.x=p+e.x,i.visualBounds.y=r,i.visualBounds.w=e.width,i.visualBounds.h=d,i.lineAlignedBounds=new cs,i.lineAlignedBounds.x=p+e.x,i.lineAlignedBounds.y=l,i.lineAlignedBounds.w=e.width,i.lineAlignedBounds.h=c,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;let t=this.layout.renderer.tracks[0].staves[0].bars[e];return this.layout.getRendererForBar(this._firstStaffInBrackets.staveId,t).x}}Qr.SystemSignSeparatorHeight=40,Qr.SystemSignSeparatorPadding=10,Qr.SystemSignSeparatorWidth=36;class $r extends xr{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=M.Middle,super.paint(e,t,s)}createGlyphs(e){const t=this.renderer.resources;this.height=0;if(this._trackLabel.length>0){const e=new Wr(0,this.height,this._trackLabel,t.effectFont,L.Left);e.renderer=this.renderer,e.doLayout(),this.height+=e.height,e.y+=e.height/2,this.addGlyph(e)}const s=new Wr(0,this.height,e.name,t.effectFont,L.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=$r.CircleNumberScale,i=$r.CircleNumberHeight*s;let a=0|Math.ceil(e.tunings.length/2),r=0,n=this.height;for(let o=0,h=e.tunings.length;o<h;o++){const h=D.GuitarString0+(o+1);this.addGlyph(new Qa(r,n+i/2.5,s,h));const l="= "+De.getTextForTuning(e.tunings[o],!1);this.addGlyph(new Wr(r+i+1,n,l,t.effectFont,L.Left)),n+=15,o===a-1&&(n=this.height,r+=64)}this.height+=15*a}this.width+=15}}$r.CircleNumberHeight=20,$r.CircleNumberScale=.7;class Zr extends Hr{constructor(e,t){super(e,t,L.Left)}addTuning(e,t){if(e.tunings.length>0){let s=new $r(0,0,e,t);s.renderer=this.renderer,s.doLayout(),this.glyphs.push(s)}}}class en{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"}(zs||(zs={}));class tn{get scaledWidth(){return this.width/this.renderer.settings.display.scale}constructor(e){this._barRendererLookup=new Map,this.width=0,this.height=0,this.scoreInfoGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this.systemsLayoutMode=zs.Automatic,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t)),this.firstBarIndex=t;let s=this.renderer.settings.display.barCount;s<0&&(s=e.masterBars.length),s=t+s-1,s=Math.min(e.masterBars.length-1,Math.max(0,s)),this.lastBarIndex=s,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 en(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)}}createScoreInfoGlyphs(){ne.debug("ScoreLayout","Creating score info glyphs");let t=this.renderer.settings.notation,s=this.renderer.score,i=this.renderer.settings.display.resources;this.scoreInfoGlyphs=new Map,s.title&&t.isNotationElementVisible(e.NotationElement.ScoreTitle)&&this.scoreInfoGlyphs.set(e.NotationElement.ScoreTitle,new Wr(0,0,s.title,i.titleFont,L.Center)),s.subTitle&&t.isNotationElementVisible(e.NotationElement.ScoreSubTitle)&&this.scoreInfoGlyphs.set(e.NotationElement.ScoreSubTitle,new Wr(0,0,s.subTitle,i.subTitleFont,L.Center)),s.artist&&t.isNotationElementVisible(e.NotationElement.ScoreArtist)&&this.scoreInfoGlyphs.set(e.NotationElement.ScoreArtist,new Wr(0,0,s.artist,i.subTitleFont,L.Center)),s.album&&t.isNotationElementVisible(e.NotationElement.ScoreAlbum)&&this.scoreInfoGlyphs.set(e.NotationElement.ScoreAlbum,new Wr(0,0,s.album,i.subTitleFont,L.Center)),s.music&&s.music===s.words&&t.isNotationElementVisible(e.NotationElement.ScoreWordsAndMusic)?this.scoreInfoGlyphs.set(e.NotationElement.ScoreWordsAndMusic,new Wr(0,0,"Music and Words by "+s.words,i.wordsFont,L.Center)):(s.music&&t.isNotationElementVisible(e.NotationElement.ScoreMusic)&&this.scoreInfoGlyphs.set(e.NotationElement.ScoreMusic,new Wr(0,0,"Music by "+s.music,i.wordsFont,L.Right)),s.words&&t.isNotationElementVisible(e.NotationElement.ScoreWords)&&this.scoreInfoGlyphs.set(e.NotationElement.ScoreWords,new Wr(0,0,"Words by "+s.words,i.wordsFont,L.Left)));const a=new sn(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);for(const[e,t]of this.scoreInfoGlyphs)t.renderer=a,t.doLayout();if(t.isNotationElementVisible(e.NotationElement.GuitarTuning)){let e=[];for(let t of this.renderer.tracks)for(let i of t.staves){let a=!i.isPercussion&&i.isStringed&&i.tuning.length>0&&i.showTablature;if(s.stylesheet.perTrackDisplayTuning&&s.stylesheet.perTrackDisplayTuning.has(t.index)&&!1===s.stylesheet.perTrackDisplayTuning.get(t.index)&&(a=!1),a){e.push(i);break}}if(e.length>0&&s.stylesheet.globalDisplayTuning){this.tuningGlyph=new Zr(0,0),this.tuningGlyph.renderer=a;for(const t of e)this.tuningGlyph.addTuning(t.stringTuning,e.length>1?t.track.name:"")}}if(t.isNotationElementVisible(e.NotationElement.ChordDiagrams)){this.chordDiagrams=new Gr(0,0),this.chordDiagrams.renderer=a;let e=new Set;for(let t of this.renderer.tracks){if(s.stylesheet.globalDisplayChordDiagramsOnTop&&(null==s.stylesheet.perTrackChordDiagramsOnTop||!s.stylesheet.perTrackChordDiagramsOnTop.has(t.index)||s.stylesheet.perTrackChordDiagramsOnTop.get(t.index)))for(let s of t.staves){const t=s.chords;if(t)for(const[,s]of t)e.has(s.uniqueId)||s.showDiagram&&(e.add(s.uniqueId),this.chordDiagrams.addChord(s))}}}}createEmptyStaffSystem(){let e=new Qr(this);for(let t=0;t<this.renderer.tracks.length;t++){let s=this.renderer.tracks[t];for(let i=0;i<s.staves.length;i++){let a=s.staves[i],r=Nl.staveProfiles.get(this.renderer.settings.display.staveProfile);for(let i of r)i.canCreate(s,a)&&e.addStaff(s,new zr(t,a,i))}}return e}registerBarRenderer(e,t){this._barRendererLookup.has(e)||this._barRendererLookup.set(e,new Map),this._barRendererLookup.get(e).set(t.bar.id,t)}unregisterBarRenderer(e,t){if(this._barRendererLookup.has(e)){this._barRendererLookup.get(e).delete(t.bar.id)}}getRendererForBar(e,t){let s=t.id;return this._barRendererLookup.has(e)&&this._barRendererLookup.get(e).has(s)?this._barRendererLookup.get(e).get(s):null}layoutAndRenderAnnotation(e){let t="rendered by alphaTab",s=this.renderer.settings.display.resources,i=Math.floor(12);const a=new Na,r=nt.withFamilyList(s.copyrightFont.families,12,Ye.Plain,qe.Bold);this.renderer.canvas.font=r;const n=Nl.getLayoutEngineFactory(this.renderer.settings.display.layoutMode).vertical;return a.width=this.renderer.canvas.measureText(t).width/this.renderer.settings.display.scale,a.height=i,a.x=n?(this.scaledWidth-a.width)/2:this.firstBarX,a.y=e,a.totalWidth=this.scaledWidth,a.totalHeight=e+i,a.firstMasterBarIndex=-1,a.lastMasterBarIndex=-1,this.registerPartial(a,(e=>{e.color=s.mainGlyphColor,e.font=r,e.textAlign=L.Left,e.textBaseline=M.Top,e.fillText(t,0,0)})),e+i}}!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"}(Us||(Us={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Xs||(Xs={}));class sn{get nextRenderer(){return this.bar&&this.bar.nextBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.nextBar):null}get previousRenderer(){return this.bar&&this.bar.previousBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.previousBar):null}constructor(e,t){this._preBeatGlyphs=new vr,this._voiceContainers=new Map,this._postBeatGlyphs=new vr,this._ties=[],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 Rr(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){let 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(){let 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;let 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);let 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==zs.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 vr,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new vr,this._postBeatGlyphs.renderer=this;for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];if(this.hasVoiceContainer(t)){let s=new Pr(0,0,t);s.renderer=this,this._voiceContainers.set(this.bar.voices[e].index,s)}}this.bar.simileMark===h.SecondOfDouble&&(this.canWrap=!1),this.createPreBeatGlyphs(),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!e.isEmpty||0===e.index}updateSizes(){this.staff.registerStaffTop(this.topPadding),this.staff.registerStaffBottom(this.height-this.bottomPadding);let e=this._voiceContainers,t=this.beatGlyphsStart,s=t;for(const i of e.values()){i.x=t,i.doLayout();let 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())s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,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){let i=new xa;i.bar=this.bar,i.visualBounds=new cs,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 cs,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){let 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=Ws.PreNotes){let s=this.getBeatContainer(e);if(s)switch(t){case Ws.PreNotes:return s.voiceContainer.x+s.x;case Ws.OnNotes:return s.voiceContainer.x+s.x+s.onNotes.x;case Ws.MiddleNotes:return s.voiceContainer.x+s.x+s.onTimeX;case Ws.Stem:const t=s.onNotes.beamingHelper?s.onNotes.beamingHelper.getBeatLineX(e):s.onNotes.x+s.onNotes.width/2;return s.voiceContainer.x+t;case Ws.PostNotes:return s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.width;case Ws.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],Ws.OnNotes);return t+(this.postBeatGlyphsStart-t)*e}getNoteX(e,t){let s=this.getBeatContainer(e.beat);return s?s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.getNoteX(e,t):0}getNoteY(e,t){let s=this.getOnNotesGlyphForBeat(e.beat);return s?s.getNoteY(e,t):NaN}reLayout(){(this._wasFirstOfLine&&!this.isFirstOfLine||!this._wasFirstOfLine&&this.isFirstOfLine)&&this.recreatePreBeatGlyphs(),this.updateSizes(),this.registerLayoutingInfo()}recreatePreBeatGlyphs(){this._preBeatGlyphs=new vr,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()}paintSimileMark(e,t,s){switch(this.bar.simileMark){case h.Simple:s.fillMusicFontSymbol(e+this.x+(this.width-20)/2,t+this.y+this.height/2,1,D.Repeat1Bar,!1);break;case h.SecondOfDouble:s.fillMusicFontSymbol(e+this.x-14,t+this.y+this.height/2,1,D.Repeat2Bars,!1)}}completeBeamingHelper(e){}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}}sn.RawLineSpacing=8,sn.StemWidth=.12*sn.RawLineSpacing,sn.StaffLineThickness=.13*sn.RawLineSpacing,sn.BeamThickness=.5*sn.RawLineSpacing,sn.BeamSpacing=.25*sn.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"}(Js||(Js={}));class an extends ja{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 Js.SingleOnBeatToEnd:case Js.GroupedOnBeatToEnd:this.lastBeat.nextBeat&&(this.lastBeat=this.lastBeat.nextBeat)}let 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 Js.FullBar:case Js.SinglePreBeat:case Js.SingleOnBeat:case Js.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 Js.GroupedOnBeat:case Js.GroupedOnBeatToEnd:let i=e===Js.GroupedOnBeat?Js.SingleOnBeat:Js.SingleOnBeatToEnd;if(t.index>0||this.renderer.index>0){let 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){let t=this.renderer.previousRenderer.getBand(e.voice,this.info.effectId);if(t){let i=t._effectGlyphs[e.voice.index];i.has(e.index)&&(s=i.get(e.index))}}let 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(Js.SingleOnBeat,t)}}paint(e,t,s){super.paint(e,t,s);for(let i=0,a=this._uniqueEffectGlyphs.length;i<a;i++){let a=this._uniqueEffectGlyphs[i];for(let i=0,r=a.length;i<r;i++){a[i].paint(e+this.x,t+this.y,s)}}}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){let s=this._effectGlyphs[t.voice.index].get(t.index),i=this.renderer.getBeatContainer(t);switch(e){case Js.SinglePreBeat:const e=this.renderer.layoutingInfo.getPreBeatSize(t);s.x=this.renderer.beatGlyphsStart+i.x-e;break;case Js.SingleOnBeat:case Js.GroupedOnBeat:s.x=this.renderer.beatGlyphsStart+i.x;break;case Js.SingleOnBeatToEnd:case Js.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 Js.FullBar:s.width=this.renderer.width}}}class rn{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class nn{constructor(){this.bands=[],this.shared=new rn}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 on{constructor(){this.slots=[],this._effectSlot=new Map}getOrCreateSlot(e){if(this._effectSlot.has(e.info.effectId)){let t=this._effectSlot.get(e.info.effectId);if(t.canBeUsed(e))return t}for(let t of this.slots)if(t.canBeUsed(e))return t;let t=new nn;return this.slots.push(t),t}register(e){let t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class hn extends xr{constructor(){super(0,0),this.computedWidth=0}doLayout(){let e=0;if(this.glyphs)for(let t=0,s=this.glyphs.length;t<s;t++){let 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])}}class ln extends hn{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,s){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class dn extends sn{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(let t of this.sizingInfo.slots){t.shared.y=e;for(let 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){let e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new on;for(let e of this._bands)e.resetHeight(),e.alignGlyphs(),e.isEmpty||this.sizingInfo.register(e);return this.updateHeight(),e}scaleToWidth(e){super.scaleToWidth(e);for(let e of this._bands)e.alignGlyphs()}createBeatGlyphs(){this._bands=[],this._bandLookup=new Map;for(let e of this.bar.voices)if(this.hasVoiceContainer(e))for(let t of this._infos){let s=new an(e,t);s.renderer=this,s.doLayout(),this._bands.push(s),this._bandLookup.set(e.index+"."+t.effectId,s)}for(let e of this.bar.voices)this.hasVoiceContainer(e)&&this.createVoiceGlyphs(e);for(let e of this._bands)e.isLinkedToPrevious&&(this.isLinkedToPrevious=!0)}createVoiceGlyphs(e){for(let t of e.beats){let s=new er(t,this.getVoiceContainer(e));s.preNotes=new hn,s.onNotes=new ln,this.addBeatGlyph(s);for(let e of this._bands)e.createGlyph(t)}}paint(e,t,s){this.paintBackground(e,t,s);for(let 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){let s=e.index+"."+t;return this._bandLookup.has(s)?this._bandLookup.get(s):null}}class cn extends Nr{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 dn(e,t,this.infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class un extends Ka{constructor(e,t,s){super(e,t),this._endingsString="",this._endings=de.getAlternateEndingsList(s)}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(un.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){super.paint(e,t,s);let i=s.textBaseline;if(s.textBaseline=M.Top,this._endings.length>0){let i=this.renderer.resources;s.font=i.wordsFont,s.moveTo(e+this.x,t+this.y+this.height),s.lineTo(e+this.x,t+this.y),s.lineTo(e+this.x+this.width,t+this.y),s.stroke(),s.fillText(this._endingsString,e+this.x+un.Padding,t+this.y)}s.textBaseline=i}}un.Padding=3;class pn{get effectId(){return this.notationElement.toString()}}class gn extends pn{get notationElement(){return e.NotationElement.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Js.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){return new un(0,0,t.voice.bar.masterBar.alternateEndings)}canExpand(e,t){return!0}}class mn extends pn{get notationElement(){return e.NotationElement.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Js.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Wr(0,0,"Capo. fret "+t.voice.bar.staff.capo,e.resources.effectFont,L.Left)}canExpand(e,t){return!1}}class fn extends pn{get notationElement(){return e.NotationElement.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Js.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Wr(0,0,t.chord.name,e.resources.effectFont,L.Center)}canExpand(e,t){return!1}}class yn extends Ka{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;let 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){let i=e-this.renderer.x,a=this.calculateEndX(this.renderer,this.beat,i,this.endPosition);this.paintGrouped(e,t,a,s)}}class bn extends yn{constructor(e,t,s){super(Ws.EndBeat),this._crescendo=p.None,this._crescendo=s,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17}paintGrouped(e,t,s,i){let a=e+this.x,r=this.height;i.beginPath(),this._crescendo===p.Crescendo?(s-=bn.Padding,i.moveTo(s,t+this.y),i.lineTo(a,t+this.y+r/2),i.lineTo(s,t+this.y+r)):(s-=bn.Padding,i.moveTo(a,t+this.y),i.lineTo(s,t+this.y+r/2),i.lineTo(a,t+this.y+r)),i.stroke()}}bn.Padding=$a.QuarterNoteHeadWidth/2|0;class Sn extends pn{get notationElement(){return e.NotationElement.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Js.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==p.None}createNewGlyph(e,t){return new bn(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class _n extends Qa{constructor(e,t,s){super(e,t,.6,_n.getSymbol(s))}doLayout(){super.doLayout(),this.height=17,this.y+=this.height/2}static getSymbol(e){switch(e){case m.PPP:return D.DynamicPPP;case m.PP:return D.DynamicPP;case m.P:return D.DynamicPiano;case m.MP:return D.DynamicMP;case m.MF:return D.DynamicMF;case m.F:return D.DynamicForte;case m.FF:return D.DynamicFF;case m.FFF:return D.DynamicFFF;default:return D.None}}}class wn extends pn{get notationElement(){return e.NotationElement.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Js.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||e.graceType!==f.None)return!1;let t=this.getPreviousDynamicsBeat(e),s=0===e.voice.index&&!t||e.dynamics!==t?.dynamics;if(s&&e.voice.index>0)for(let t of e.voice.bar.voices)if(t.index<e.voice.index){let 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&&t.graceType===f.None)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new _n(0,0,t.dynamics)}canExpand(e,t){return!0}}class Bn extends Qa{constructor(e){super(0,0,1,Bn.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case O.FadeIn:return D.GuitarFadeIn;case O.FadeOut:return D.GuitarFadeOut;case O.VolumeSwell:return D.GuitarVolumeSwell}return D.None}doLayout(){this.width=13,this.symbol==D.GuitarVolumeSwell&&(this.width*=2),this.height=13}paint(e,t,s){super.paint(e,t+this.height,s)}}class Tn extends pn{get notationElement(){return e.NotationElement.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Js.SingleOnBeat}shouldCreateGlyph(e,t){return t.fade!=O.None}createNewGlyph(e,t){return new Bn(t.fade)}canExpand(e,t){return!0}}class kn extends Qa{constructor(e,t,s){super(e,t,1,kn.getSymbol(s))}static getSymbol(e){switch(e){case Ge.Short:return D.FermataShortAbove;case Ge.Medium:return D.FermataAbove;case Ge.Long:return D.FermataLongAbove;default:return D.None}}doLayout(){this.width=23,this.height=12}paint(e,t,s){super.paint(e-this.width/2,t+this.height,s)}}class Nn extends pn{get notationElement(){return e.NotationElement.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Js.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new kn(0,0,t.fermata.type)}canExpand(e,t){return!0}}class xn extends pn{get notationElement(){return e.NotationElement.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Js.SingleOnBeat}shouldCreateGlyph(t,s){return!(0!==s.voice.index||s.isRest||t.notation.fingeringMode!==e.FingeringMode.SingleNoteEffectBand&&t.notation.fingeringMode!==e.FingeringMode.SingleNoteEffectBandForcePiano)&&(1===s.notes.length&&s.notes[0].isFingering)}createNewGlyph(e,t){let s=y.Unknown,i=!1,a=t.notes[0];a.leftHandFinger!==y.Unknown?(s=a.leftHandFinger,i=!0):a.rightHandFinger!==y.Unknown&&(s=a.rightHandFinger);let r=de.fingerToString(e.settings,t,s,i)??"";return new Wr(0,0,r,e.resources.fingeringFont,L.Left)}canExpand(e,t){return!0}}class vn extends pn{constructor(){super(...arguments),this.lastCreateInfo=null}shouldCreateGlyph(e,t){this.lastCreateInfo=[];for(let e=0,s=t.notes.length;e<s;e++){let 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 Pn extends yn{constructor(e,t=!0){super(Ws.OnNotes),this._label=e,this._dashed=t}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=Ws.EndBeat,this.forceGroupedRendering=!0),super.doLayout(),this.height=this.renderer.resources.effectFont.size}paintNonGrouped(e,t,s){let i=this.renderer.resources;s.font=i.effectFont;let a=s.textAlign;s.textAlign=L.Center,s.fillText(this._label,e+this.x,t+this.y),s.textAlign=a}paintGrouped(e,t,s,i){this.paintNonGrouped(e,t,i);let 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()}}Pn.LineSpacing=3,Pn.LineTopPadding=4,Pn.LineTopOffset=5,Pn.LineSize=8;class Cn extends vn{get effectId(){return this._effectId}get notationElement(){return e.NotationElement.EffectHarmonics}constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case b.None:this._effectId="harmonics-none";break;case b.Natural:this._effectId="harmonics-natural";break;case b.Artificial:this._effectId="harmonics-artificial";break;case b.Pinch:this._effectId="harmonics-pinch";break;case b.Tap:this._effectId="harmonics-tap";break;case b.Semi:this._effectId="harmonics-semi";break;case b.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 Js.GroupedOnBeat}createNewGlyph(e,t){return new Pn(Cn.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case b.Natural:return"N.H.";case b.Artificial:return"A.H.";case b.Pinch:return"P.H.";case b.Tap:return"T.H.";case b.Semi:return"S.H.";case b.Feedback:return"Fdbk."}return""}}class En extends pn{get notationElement(){return e.NotationElement.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return Js.GroupedOnBeat}createNewGlyph(e,t){return new Pn("LetRing")}canExpand(e,t){return!0}}class Fn extends Ka{constructor(e,t,s,i,a=L.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;let 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 Dn extends pn{get notationElement(){return e.NotationElement.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Js.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new Fn(0,0,t.lyrics,e.resources.effectFont,L.Center)}canExpand(e,t){return!0}}class Ln extends pn{get notationElement(){return e.NotationElement.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return Js.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 Wr(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,L.Left)}canExpand(e,t){return!0}}class Mn extends yn{constructor(e,t){super(Ws.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=13}paintNonGrouped(e,t,s){this.paintOttava(e,t,s)}paintOttava(e,t,s){let i=0;switch(this._ottava){case o._15ma:i=37,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,D.QuindicesimaAlta,!1);break;case o._8va:i=26,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,D.OttavaAlta,!1);break;case o._8vb:i=23,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,D.OttavaBassaVb,!1);break;case o._15mb:i=36,s.fillMusicFontSymbols(e+this.x-i/2,t+this.y+this.height,.8,[D.Quindicesima,D.OctaveBaselineM,D.OctaveBaselineB],!1)}return i/2}paintGrouped(e,t,s,i){let a=this.paintOttava(e,t,i),r=e+this.x+a+3,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 In extends pn{get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return e.NotationElement.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Js.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 Mn(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class An extends vn{get notationElement(){return e.NotationElement.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return Js.GroupedOnBeat}createNewGlyph(e,t){return new Pn("P.M.")}constructor(){super()}}class Rn extends vn{get notationElement(){return e.NotationElement.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===w.PickSlideDown||e.slideOutType===w.PickSlideUp}get sizingMode(){return Js.GroupedOnBeat}createNewGlyph(e,t){return new Pn("P.S.")}constructor(){super()}}class On extends Qa{constructor(e,t,s){super(e,t,$a.GraceScale,On.getSymbol(s))}doLayout(){this.width=9,this.height=13}paint(e,t,s){super.paint(e,t+this.height,s)}static getSymbol(e){switch(e){case F.Up:return D.StringsUpBow;case F.Down:return D.StringsDownBow;default:return D.None}}}class Vn extends pn{get notationElement(){return e.NotationElement.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Js.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==F.None}createNewGlyph(e,t){return new On(0,0,t.pickStroke)}canExpand(e,t){return!0}}class Hn extends yn{constructor(e){super(Ws.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case B.Slight:this._stepSize=12;break;case B.Wide:this._stepSize=23}this.height=18}paintGrouped(e,t,s,i){let a=e+this.x,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 Gn extends pn{get notationElement(){return e.NotationElement.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Js.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===B.Slight}createNewGlyph(e,t){return new Hn(B.Slight)}canExpand(e,t){return!0}}class Wn extends yn{constructor(e,t,s,i=1.2,a=!1){super(Ws.EndBeat),this._scale=0,this._symbol=D.None,this._symbolSize=0,this._type=s,this._scale=i,this.x=e,this.y=t,this._partialWaves=a}doLayout(){super.doLayout();let e=0;switch(this._type){case B.Slight:this._symbol=D.WiggleTrill,this._symbolSize=9*this._scale,e=6*this._scale;break;case B.Wide:this._symbol=D.WiggleVibratoMediumFast,this._symbolSize=10*this._scale,e=10*this._scale}this.height=e}paintGrouped(e,t,s,i){let a=s-(e+this.x),r=this._symbolSize,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 zn extends vn{get notationElement(){return e.NotationElement.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){let t=e.vibrato===B.Slight||e.isTieDestination&&e.tieOrigin.vibrato===B.Slight;return this._hideOnTiedBend&&t&&e.isTieDestination&&e.tieOrigin.hasBend&&(t=!1),t}get sizingMode(){return Js.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Wn(0,0,B.Slight,1.2)}constructor(e){super(),this._hideOnTiedBend=e}}class Un extends pn{get notationElement(){return e.NotationElement.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Js.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){let s=e.resources;return t.slap?new Wr(0,0,"S",s.effectFont,L.Left):t.pop?new Wr(0,0,"P",s.effectFont,L.Left):new Wr(0,0,"T",s.effectFont,L.Left)}canExpand(e,t){return!0}}var Xn,Jn,Yn=Object.freeze({__proto__:null,CssFontSvgCanvas:kr,Cursors:fr,FontSizes:ka,SvgCanvas:Tr,get TextAlign(){return L},get TextBaseline(){return M}});class qn extends Ka{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=M.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,D.NoteQuarterUp,!0),s.fillText("= "+i.value.toString(),a+8,t+this.y+s.font.size/2)}}}class jn extends pn{get notationElement(){return e.NotationElement.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Js.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 qn(t.voice.bar.masterBar.tempoAutomations)}canExpand(e,t){return!0}}class Kn extends pn{get notationElement(){return e.NotationElement.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Js.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Wr(0,0,t.text,e.resources.effectFont,L.Left)}canExpand(e,t){return!0}}class Qn extends Ka{constructor(e,t){super(e,t)}doLayout(){super.doLayout(),this.height=this.renderer.resources.markerFont.size}paint(e,t,s){let i=this.renderer.resources;s.font=i.markerFont;let a=s.measureText("tr").width;s.fillText("tr",e+this.x,t+this.y);let r=a+3,n=this.width-r,o=Math.max(1,(n-r)/13.2),h=r,l=t+this.y+1.2*this.height;for(let t=0;t<o;t++)s.fillMusicFontSymbol(e+this.x+h,l,1.2,D.WiggleTrill,!1),h+=13.2}}class $n extends vn{get notationElement(){return e.NotationElement.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return Js.SingleOnBeat}createNewGlyph(e,t){return new Qn(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(Xn||(Xn={}));class Zn extends Ka{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25}paint(e,t,s){e+=this.x;let i=(t+=this.y)+this.height*$a.GraceScale,a=i+8;s.font=this.renderer.resources.effectFont,s.fillText("(",e,t+.3*this.height);let r=e+10,n=e+40,o=[],h=[],l=[],d=[];switch(this._tripletFeel){case E.NoTripletFeel:o=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac8thLongStem],l=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac8thLongStem];break;case E.Triplet8th:o=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac8thLongStem],l=[D.TextBlackNoteLongStem,D.Space,D.NoteEighthUp],d=[D.TextTupletBracketStartLongStem,D.TextTuplet3LongStem,D.TextTupletBracketEndLongStem];break;case E.Triplet16th:o=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac8thLongStem],l=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac16thLongStem],d=[D.TextTupletBracketStartLongStem,D.TextTuplet3LongStem,D.TextTupletBracketEndLongStem];break;case E.Dotted8th:o=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac8thLongStem],h=[D.TextAugmentationDot],l=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac16thLongStem];break;case E.Dotted16th:o=[D.TextBlackNoteLongStem,D.TextCont16thBeamLongStem,D.TextBlackNoteFrac16thLongStem],h=[D.TextAugmentationDot],l=[D.TextBlackNoteLongStem,D.TextCont16thBeamLongStem,D.TextBlackNoteFrac32ndLongStem],s.fillCircle(n+9,i,1);break;case E.Scottish8th:o=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac8thLongStem],l=[D.TextBlackNoteLongStem,D.TextCont16thBeamLongStem,D.TextBlackNoteFrac8thLongStem,D.TextAugmentationDot];break;case E.Scottish16th:o=[D.TextBlackNoteLongStem,D.TextCont16thBeamLongStem,D.TextBlackNoteFrac16thLongStem],l=[D.TextBlackNoteLongStem,D.TextCont32ndBeamLongStem,D.TextBlackNoteFrac16thLongStem,D.TextAugmentationDot]}s.fillMusicFontSymbols(r,i,Zn.NoteScale,o,!1),s.fillText("=",e+32,t+5),s.fillMusicFontSymbols(n,i,Zn.NoteScale,l,!1),h.length>0&&s.fillMusicFontSymbols(n+7,i,Zn.NoteScale,h,!1),d.length>0&&s.fillMusicFontSymbols(n,a,Zn.TupletScale,d,!1),s.fillText(")",e+65,t+.3*this.height)}}Zn.NoteScale=.5,Zn.TupletScale=.7;class eo extends pn{get notationElement(){return e.NotationElement.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Js.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==E.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new Zn(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class to extends pn{get notationElement(){return e.NotationElement.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Js.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new Pn("w/bar")}canExpand(e,t){return!0}}class so extends pn{get notationElement(){return e.NotationElement.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Js.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===B.Wide}createNewGlyph(e,t){return new Hn(B.Wide)}canExpand(e,t){return!0}}class io extends vn{get notationElement(){return e.NotationElement.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===B.Wide||e.isTieDestination&&e.tieOrigin.vibrato===B.Wide}get sizingMode(){return Js.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Wn(0,0,B.Wide,1.2)}}class ao{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class ro extends tn{get name(){return"HorizontalScreen"}constructor(e){super(e),this._system=null,this._pagePadding=null}get supportsResize(){return!1}get firstBarX(){let e=this._pagePadding[0];return this._system&&(e+=this._system.accoladeWidth),e}doResize(){}doLayoutAndRender(){switch(this._pagePadding=this.renderer.settings.display.padding,this.renderer.settings.display.systemsLayoutMode){case e.SystemsLayoutMode.Automatic:this.systemsLayoutMode=zs.Automatic;break;case e.SystemsLayoutMode.UseModelLayout:this.systemsLayoutMode=zs.FromModelWithWidths}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]]);let t=this.renderer.score,s=this.renderer.settings.display.startBar;s--,s=Math.min(t.masterBars.length-1,Math.max(0,s));let i=s,a=this.renderer.settings.display.barCount;a<=0&&(a=t.masterBars.length),a=s+a-1,a=Math.min(t.masterBars.length-1,Math.max(0,a)),this._system=this.createEmptyStaffSystem(),this._system.isLast=!0,this._system.x=this._pagePadding[0],this._system.y=this._pagePadding[1];let r=this.renderer.settings.display.barCountPerPartial,n=[],o=new ao,h=0;for(;i<=a;){let e=this._system.addBars(this.renderer.tracks,i);if(e)if(0===o.masterBars.length&&e.isLinkedToPrevious&&n.length>0){let s=n[n.length-1];s.masterBars.push(t.masterBars[i]),s.width+=e.width,h+=e.width,o.x+=h}else o.masterBars.push(t.masterBars[i]),o.width+=e.width,o.masterBars.length>=r&&(0===n.length&&(o.width+=this._system.accoladeWidth+this._pagePadding[0]),h+=o.width,n.push(o),ne.debug(this.name,"Finished partial from bar "+o.masterBars[0].index+" to "+o.masterBars[o.masterBars.length-1].index,null),o=new ao,o.x=h);i++}o.masterBars.length>0&&(0===n.length&&(o.width+=this._system.accoladeWidth+this._pagePadding[0]),n.push(o),ne.debug(this.name,"Finished partial from bar "+o.masterBars[0].index+" to "+o.masterBars[o.masterBars.length-1].index,null)),this.finalizeStaffSystem();const l=this.renderer.settings.display.scale;this.height=Math.floor(this._system.y+this._system.height)*l,this.width=(this._system.x+this._system.width+this._pagePadding[2])*l,i=0;let d=0;for(let e=0;e<n.length;e++){const t=n[e],s=new Na;s.x=d,s.y=0,s.totalWidth=this.width/l,s.totalHeight=this.height/l,s.width=t.width,s.height=this.height/l,s.firstMasterBarIndex=t.masterBars[0].index,s.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,d+=t.width;const a=i,r=e;this._system.buildBoundingsLookup(0,0),this.registerPartial(s,(e=>{let s=this._system.getBarX(t.masterBars[0].index)+this._system.accoladeWidth;0===r&&(s-=this._system.x+this._system.accoladeWidth),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=L.Left,ne.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)})),i+=t.masterBars.length}this.height=this.layoutAndRenderAnnotation(this.height)+this._pagePadding[3]}finalizeStaffSystem(){this._system.scaleToWidth(this._system.width),this._system.finalizeSystem()}}class no extends tn{get name(){return"PageView"}constructor(e){super(e),this._systems=[],this._allMasterBarRenderers=[],this._barsFromPreviousSystem=[],this._pagePadding=null}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case e.SystemsLayoutMode.Automatic:this.systemsLayoutMode=zs.Automatic;break;case e.SystemsLayoutMode.UseModelLayout:this.systemsLayoutMode=zs.FromModelWithScale}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]]);let t=this._pagePadding[1];this.width=this.renderer.width,this._allMasterBarRenderers=[],t=this.layoutAndRenderScoreInfo(t,-1),t=this.layoutAndRenderTunings(t,-1),t=this.layoutAndRenderChordDiagrams(t,-1),t=this.layoutAndRenderScore(t),t=this.layoutAndRenderAnnotation(t),this.height=(t+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;let 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.layoutAndRenderAnnotation(e),this.height=(e+this._pagePadding[3])*this.renderer.settings.display.scale}layoutAndRenderTunings(e,t=-1){if(!this.tuningGlyph)return e;let s=this.renderer.settings.display.resources;this.tuningGlyph.x=this._pagePadding[0],this.tuningGlyph.width=this.scaledWidth,this.tuningGlyph.doLayout();let i=this.tuningGlyph.height;const a=new Na;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=L.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.floor(this.chordDiagrams.height),a=new Na;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=L.Center,this.chordDiagrams.paint(0,0,e)})),e+i}layoutAndRenderScoreInfo(t,s=-1){ne.debug(this.name,"Layouting score info");const i=new Na;i.x=0,i.y=t;let a=0,r=this.renderer.settings.display.resources,n=[e.NotationElement.ScoreTitle,e.NotationElement.ScoreSubTitle,e.NotationElement.ScoreArtist,e.NotationElement.ScoreAlbum,e.NotationElement.ScoreWordsAndMusic];for(let e=0;e<n.length;e++)if(this.scoreInfoGlyphs.has(n[e])){let t=this.scoreInfoGlyphs.get(n[e]);t.x=this.scaledWidth/2,t.y=a,t.textAlign=L.Center,a+=t.font.size}let o=!1,h=0;if(this.scoreInfoGlyphs.has(e.NotationElement.ScoreMusic)){let t=this.scoreInfoGlyphs.get(e.NotationElement.ScoreMusic);t.x=this.scaledWidth-this._pagePadding[2],t.y=a,t.textAlign=L.Right,o=!0,h=t.font.size}if(this.scoreInfoGlyphs.has(e.NotationElement.ScoreWords)){let t=this.scoreInfoGlyphs.get(e.NotationElement.ScoreWords);t.x=this._pagePadding[0],t.y=a,t.textAlign=L.Left,o=!0,h=t.font.size}return o&&(a+=h),this.scoreInfoGlyphs.size>0&&(a=Math.floor(a+17),i.width=this.scaledWidth,i.height=a,i.totalWidth=this.scaledWidth,i.totalHeight=s<0?t+i.height:s,this.registerPartial(i,(e=>{e.color=r.scoreInfoColor,e.textAlign=L.Center;for(const t of this.scoreInfoGlyphs.values())t.paint(0,0,e)}))),t+a}resizeAndRenderScore(e,t){if(this.renderer.settings.display.barsPerRow>0||this.systemsLayoutMode==zs.FromModelWithScale)for(let s=0;s<this._systems.length;s++){let i=this._systems[s];this.fitSystem(i),e+=this.paintSystem(i,t)}else{this._systems=[];let s=0,i=this.maxWidth,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,s=this.lastBarIndex;for(this._systems=[];t<=s;){let i=this.createStaffSystem(t,s);this._systems.push(i),i.x=this._pagePadding[0],i.y=e,t=i.lastBarIndex+1,this.fitSystem(i),ne.debug(this.name,"Rendering partial from bar "+i.firstBarIndex+" to "+i.lastBarIndex,null),e+=this.paintSystem(i,e)}return e}paintSystem(e,t){let s=Math.floor(e.height);const i=new Na;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=L.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==zs.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){let s=this.createEmptyStaffSystem();s.index=this._systems.length;let i=this.getBarsPerSystem(s.index),a=this.maxWidth,r=t+1,n=e;for(;n<r;){if(this._barsFromPreviousSystem.length>0)for(let e of this._barsFromPreviousSystem)s.addMasterBarRenderers(this.renderer.tracks,e),n=e.masterBar.index;else{let e=s.addBars(this.renderer.tracks,n);e&&this._allMasterBarRenderers.push(e)}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}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 Qa{constructor(e,t,s,i){super(e,t,i,oo.getMusicSymbol(s)),this._accidentalType=s}static getMusicSymbol(e){switch(e){case Je.Natural:return D.AccidentalNatural;case Je.Sharp:return D.AccidentalSharp;case Je.Flat:return D.AccidentalFlat;case Je.NaturalQuarterNoteUp:return D.AccidentalQuarterToneNaturalArrowUp;case Je.SharpQuarterNoteUp:return D.AccidentalQuarterToneSharpArrowUp;case Je.FlatQuarterNoteUp:return D.AccidentalQuarterToneFlatArrowUp;case Je.DoubleSharp:return D.AccidentalDoubleSharp;case Je.DoubleFlat:return D.AccidentalDoubleFlat}return D.None}doLayout(){if(this._accidentalType===Je.DoubleFlat)this.width=18;else this.width=8;this.width=this.width*this.glyphScale}}class ho extends Qa{constructor(e,t,s,i){super(e,t,1,ho.getSymbol(s)),this._clef=s,this._clefOttava=i}doLayout(){switch(this._clef){case n.Neutral:this.width=15;break;case n.C3:case n.C4:case n.F4:case n.G2:this.width=28}}static getSymbol(e){switch(e){case n.Neutral:return D.UnpitchedPercussionClef1;case n.C3:case n.C4:return D.CClef;case n.F4:return D.FClef;case n.G2:return D.GClef;default:return D.None}}paint(e,t,s){let i;super.paint(e,t,s);let a=!1;switch(this._clefOttava){case o._15ma:i=new Qa(-4,0,.5,D.Quindicesima),a=!0;break;case o._8va:i=new Qa(-2,0,.5,D.Ottava),a=!0;break;case o._8vb:i=new Qa(-6,0,.5,D.Ottava);break;case o._15mb:i=new Qa(-8,0,.5,D.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();let l=this.width/2;i.paint(e+this.x+l+h,t+this.y+r,s)}}class lo extends Ka{constructor(e,t,s){super(e,t),this._note=s}static getSymbol(e,t){switch(e){case a.None:return D.None;case a.Normal:return t?D.ArticAccentAbove:D.ArticAccentBelow;case a.Heavy:return t?D.ArticMarcatoAbove:D.ArticMarcatoBelow;case a.Tenuto:return t?D.ArticTenutoAbove:D.ArticTenutoBelow;default:return D.None}}doLayout(){this.width=9,this.height=9}paint(e,t,s){const i=this.renderer.getBeatDirection(this._note.beat),a=lo.getSymbol(this._note.accentuated,i==We.Down),r=i==We.Up?t+this.y:t+this.y+this.height-2;s.fillMusicFontSymbol(e+this.x-2,r,1,a,!1)}}class co extends ja{constructor(e,t,s){super(e,t),this._size=0,this._size=s}doLayout(){this.width=this._size+3}paint(e,t,s){s.fillCircle(e+this.x,t+this.y,this._size)}}class uo extends Qa{constructor(e,t,s){super(e,t,s?$a.GraceScale:1,D.NoteheadXOrnate),this._isGrace=s}doLayout(){this.width=9*(this._isGrace?$a.GraceScale:1),this.height=$a.NoteHeadHeight}}class po extends Qa{constructor(e,t,s,i){super(e,t,i?$a.GraceScale:1,po.getSymbol(s)),this._isGrace=i}static getSymbol(e){switch(e){case g.QuadrupleWhole:case g.DoubleWhole:case g.Whole:case g.Half:return D.NoteheadDiamondWhiteWide;default:return D.NoteheadDiamondBlackWide}}doLayout(){this.width=9*(this._isGrace?$a.GraceScale:1),this.height=$a.NoteHeadHeight}}class go extends ja{constructor(e,t,s){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=We.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);let e=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar);this.startNoteRenderer=e;let t=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.endBeat.voice.bar);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&&(this.y=Math.min(this._startY,this._endY),this.shouldDrawBendSlur()?this._tieHeight=0:(this._tieHeight=this.getTieHeight(this._startX,this._startY,this._endX,this._endY),this.height=go.calculateActualTieHeight(1,this._startX,this._startY,this._endX,this._endY,this.tieDirection===We.Down,this._tieHeight,4).h),this.tieDirection===We.Up&&(this.y-=this.height))}paint(e,t,s){this._shouldDraw&&(this.shouldDrawBendSlur()?go.drawBendSlur(s,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===We.Down,1):go.paintTie(s,1,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===We.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,s,i){return 22}getBeamDirection(e,t){return We.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=go.computeBezierControlPoints(e,t,s,i,a,r,n,o);t=h[0],s=h[1];const l=h[2],d=h[3];i=h[6],a=h[7];const c=(t-l)/(t-2*l+i),u=go.calculateExtrema(t,s,l,d,i,a,c),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-d)/(s-2*d+a),f=go.calculateExtrema(t,s,l,d,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 cs;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,d=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=d,l/=d;let c=(i+t)/2,u=(a+s)/2;return[t,s,c+n*h,u+n*l,c+(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=go.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,d=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=d,l/=d;let c=(i+t)/2,u=(a+s)/2,p=go.BendSlurHeight*n;i-t<20&&(p/=2);let g=c+p*h,m=u+p*l;if(e.beginPath(),e.moveTo(t,s),e.lineTo(g,m),e.lineTo(i,a),e.stroke(),o){let t=e.measureText(o).width,s=r?0:-e.font.size;e.fillText(o,g-t/2,m+s)}}}go.BendSlurHeight=11;class mo extends ja{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=mo.Size}paint(e,t,s){this._isOpen?go.paintTie(s,1,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):go.paintTie(s,1,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3)}}mo.Size=6;class fo{constructor(e,t){this.line=0,this.line=e,this.isGhost=t}}class yo extends ja{constructor(e){super(0,0),this._infos=[],this._glyphs=[],this.isEmpty=!0,this._isOpen=e}addParenthesis(t){let s=this.renderer,i=s.getNoteLine(t),a=t.isGhost||this.isTiedBend(t)&&s.settings.notation.isNotationElementVisible(e.NotationElement.ParenthesisOnTiedBends);this.addParenthesisOnLine(i,a)}addParenthesisOnLine(e,t){let s=new fo(e,t);this._infos.push(s),t&&(this.isEmpty=!1)}isTiedBend(e){return!!e.isTieDestination&&(!!e.tieOrigin.hasBend||this.isTiedBend(e.tieOrigin))}doLayout(){let e=this.renderer;this._infos.sort(((e,t)=>e.line-t.line));let t=null,s=e.getScoreHeight(1);for(let i=0,a=this._infos.length;i<a;i++){let a;if(this._infos[i].isGhost)if(t){let a=e.getScoreY(this._infos[i].line)+s;t.height=a-t.y}else a=new mo(this._isOpen),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(let i of this._glyphs)i.paint(e+this.x,t+this.y,s)}}class bo{constructor(e,t){this.line=0,this.glyph=e,this.line=t}}class So extends ja{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new fa,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){let s=new bo(e,t);this._infos.push(s),(!this.minNote||this.minNote.line>s.line)&&(this.minNote=s),(!this.maxNote||this.maxNote.line<s.line)&&(this.maxNote=s)}get hasTopOverflow(){return!!this.minNote&&this.minNote.line<=0}get hasBottomOverflow(){return!!this.maxNote&&this.maxNote.line>8}doLayout(){this._infos.sort(((e,t)=>t.line-e.line));let e=0,t=!1,s=0,i=!1,a=this.direction,r=0;for(let n=0,o=this._infos.length;n<o;n++){let 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].line)<=1?t?t=!1:(h=!0,o.x=e,i=!0,t=!0):t=!1,a===We.Down?o.x=h?0:e:o.x=h?e:0,o.x+=this.noteStartX,s=this._infos[n].line,r=Math.max(r,o.x+o.width)}i?(this._noteHeadPadding=0,this.upLineX=e,this.downLineX=e):(this._noteHeadPadding=a===We.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;let i=this.renderer,a=this.width-this.noteStartX+6;if(this.hasTopOverflow){let r=s.color;s.color=i.resources.staffLineColor;let n=-2;for(;n>=this.minNote.line;){let r=t+i.getScoreY(n);s.fillRect(e-3+this.noteStartX,r,a,1),n-=2}s.color=r}if(this.hasBottomOverflow){let r=s.color;s.color=i.resources.staffLineColor;let n=10;for(;n<=this.maxNote.line;){let r=t+i.getScoreY(n);s.fillRect(e-3+this.noteStartX,r,a,1),n+=2}s.color=r}let r=this._infos,n=e+this._noteHeadPadding;for(let e of r)e.glyph.renderer=this.renderer,e.glyph.paint(n,t,s)}}class _o extends Qa{constructor(e,t,s){super(e,t,1,_o.getSymbol(s))}doLayout(){this.width=12}static getSymbol(e){switch(e){case g.ThirtySecond:return D.Tremolo3;case g.Sixteenth:return D.Tremolo2;case g.Eighth:return D.Tremolo1;default:return D.None}}}class wo extends ja{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 Bo extends So{constructor(){super(),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)){let s=this._noteGlyphLookup.get(e.id),i=this.x+s.x+this._noteHeadPadding;switch(t){case Xs.Left:break;case Xs.Center:i+=s.width/2;break;case Xs.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 Us.TopWithStem:i-=this.renderer.getStemSize(this.beamingHelper);break;case Us.Top:i-=s.height/2;break;case Us.Center:break;case Us.Bottom:i+=s.height/2;break;case Us.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();let e=this.renderer;this.beat.deadSlapped&&(this._deadSlapped=new wo,this._deadSlapped.renderer=this.renderer,this._deadSlapped.doLayout(),this.width=this._deadSlapped.width);let t=this.direction,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===We.Up?(n=!1,o=!0,i=e.getScoreY(this.maxNote.line+2),s=e.getScoreY(this.minNote.line)-e.getStemSize(this.beamingHelper,!0)):(n=!0,o=!1,i=e.getScoreY(this.minNote.line-1),a*=-1,r*=-1,s=e.getScoreY(this.maxNote.line)+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,s=t===We.Up?this.minNote:this.maxNote,i=t===We.Up?this.displacedX:0,a=this.beat.tremoloSpeed;switch(a){case g.ThirtySecond:e=t===We.Up?-15:15;break;case g.Sixteenth:e=t===We.Up?-12:15;break;case g.Eighth:e=t===We.Up?-10:10;break;default:e=t===We.Up?-10:15}this.beat.duration<g.Half&&(i=this.width/2),this._tremoloPicking=new _o(i,s.glyph.y+e,a),this._tremoloPicking.renderer=this.renderer,this._tremoloPicking.doLayout()}}buildBoundingsLookup(e,t,s){for(let i of this._notes)if(this._noteGlyphLookup.has(i.id)){let a=this._noteGlyphLookup.get(i.id),r=new Ca;r.note=i,r.noteHeadBounds=new cs,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){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);super.paint(e,t,s),this._tremoloPicking&&this._tremoloPicking.paint(e,t,s),this._deadSlapped&&this._deadSlapped.paint(e,t,s)}}class To extends Qa{constructor(e,t,s){super(e,t,1,To.getSymbol(s)),this._duration=s}static getSymbol(e){switch(e){case g.QuadrupleWhole:return D.RestLonga;case g.DoubleWhole:return D.RestDoubleWhole;case g.Whole:return D.RestWhole;case g.Half:return D.RestHalf;case g.Quarter:return D.RestQuarter;case g.Eighth:return D.RestEighth;case g.Sixteenth:return D.RestSixteenth;case g.ThirtySecond:return D.RestThirtySecond;case g.SixtyFourth:return D.RestSixtyFourth;case g.OneHundredTwentyEighth:return D.RestOneHundredTwentyEighth;case g.TwoHundredFiftySixth:return D.RestTwoHundredFiftySixth;default:return D.None}}static getSize(e){switch(e){case g.QuadrupleWhole:case g.DoubleWhole:case g.Whole:case g.Half:case g.Quarter:case g.Eighth:case g.Sixteenth:return 9;case g.ThirtySecond:return 12;case g.SixtyFourth:return 14;case g.OneHundredTwentyEighth:case g.TwoHundredFiftySixth:return 20}return 10}doLayout(){this.width=To.getSize(this._duration)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class ko{constructor(){this.x=0,this.y=-3e3,this.width=0}}class No extends xr{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));let e=[];e.push(new ko);for(let t=0,s=this.glyphs.length;t<s;t++){let 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 ko);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++){let s=this.glyphs[t];const i=e[s.x];s.x=this.width-i.x}}}class xo extends So{get direction(){return We.Up}constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new No,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=!1){let s=this.renderer,i=new $a(0,0,g.Quarter,!0),a=s.accidentalHelper.applyAccidentalForValue(this._beat,e,t,!0),r=s.accidentalHelper.getNoteLineForValue(e,!1);if(i.y=s.getScoreY(r),this._showParenthesis&&(this._preNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.addParenthesisOnLine(r,!0),this._postNoteParenthesis.addParenthesisOnLine(r,!0)),a!==Je.None){let e=new oo(0,i.y,a,$a.GraceScale);e.renderer=this.renderer,this._accidentals.renderer=this.renderer,this._accidentals.addGlyph(e)}this._noteValueLookup.set(e,i),this.add(i,r),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+xo.ElementPadding),this._accidentals.isEmpty||(e+=this._accidentals.width+xo.ElementPadding,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+xo.ElementPadding),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+xo.ElementPadding,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+xo.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)}}xo.ElementPadding=2;class vo extends ja{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,s,i,a,r,n,o){go.drawBendSlur(e,t,s,i,a,r,n,o)}doLayout(){super.doLayout(),this.width=0;for(let e of this.BendNoteHeads)e.doLayout(),this.width+=e.width+10}getTieDirection(e,t){return t.getBeatDirection(e)===We.Up?We.Down:We.Up}}vo.EndPadding=8;class Po extends se{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class Co extends ja{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);let 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 c.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 c.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 c.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 c.Prebend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s);break;case c.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 c.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();let e=this._maxBendValue*Co.BendValueHeight;this.renderer.registerOverflowTop(e);let t=0;for(let e of this._notes){let s=this._renderPoints.get(e.id);switch(e.bendType){case c.Bend:s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case c.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t);break;case c.BendRelease:s[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[2].lineValue=t);break;case c.Prebend:s[0].lineValue=this._preBendMinValue;break;case c.PrebendBend:s[0].lineValue=this._preBendMinValue,s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case c.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){let t=[];switch(e.bendType){case c.Custom:for(let s of e.bendPoints)t.push(new Po(s.offset,s.value));break;case c.BendRelease:t.push(new Po(0,e.bendPoints[0].value)),t.push(new Po(se.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new Po(se.MaxPosition,e.bendPoints[3].value));break;case c.Bend:case c.Hold:case c.Prebend:case c.PrebendBend:case c.PrebendRelease:case c.Release:t.push(new Po(0,e.bendPoints[0].value)),t.push(new Po(se.MaxPosition,e.bendPoints[1].value))}return t}paint(e,t,s){let i=s.color;this._notes.length>1&&(s.color=this.renderer.resources.secondaryGlyphColor);for(let a of this._notes){let r=this._renderPoints.get(a.id),n=this.renderer,o=a,h=!1,l=null,u=!1,p=a.bendStyle===d.Gradual?"grad.":"",g=null;for(;o.isTieOrigin;){let e=o.tieDestination;if(l=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,e.beat.voice.bar),!l||n.staff!==l.staff)break;if(o=e,h=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes||o.vibrato!=B.None){u=!0;break}}g=o.beat,l=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,g.voice.bar),g.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(g=null);let m=0,f=0,y=t+n.y;m=e+n.x,r[0].value>0||a.isContinuedBend?m+=n.getBeatX(a.beat,Ws.MiddleNotes):m+=n.getNoteX(a,Xs.Right),f=!g||g.isLastOfVoice&&!u?e+l.x+l.postBeatGlyphsStart:u||!g.nextBeat?e+l.x+l.getBeatX(g,Ws.MiddleNotes):a.bendType===c.Hold?e+l.x+l.getBeatX(g.nextBeat,Ws.OnNotes):e+l.x+l.getBeatX(g.nextBeat,Ws.PreNotes),h||(f-=Co.ArrowSize);let b=(f-m)/se.MaxPosition;s.beginPath();for(let e=0,t=r.length-1;e<t;e++){let t=r[e],i=r[e+1];0!==e||0===t.value||a.isTieDestination||this.paintBend(a,new Po(0,0),t,m,y,b,p,s),a.bendType!==c.Prebend?(0===e&&(m+=2),this.paintBend(a,t,i,m,y,b,p,s)):a.isTieOrigin&&a.tieDestination.hasBend&&(i=new Po(se.MaxPosition,t.value),i.lineValue=t.lineValue,this.paintBend(a,t,i,m,y,b,p,s))}if(o.vibrato!==B.None){const i=f-e+Co.ArrowSize-l.x,a=y-t-Co.BendValueHeight*r[r.length-1].lineValue,n=new Wn(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){let h=this.renderer,l=this.renderer.resources,d=h.lineOffset/2,c=i+r*t.offset,u=Co.BendValueHeight,p=a-u*t.lineValue;0===t.value?s.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,Us.Top):p+=h.getNoteY(e,Us.Center):p+=d;let g=i+r*s.offset,m=a-u*s.lineValue;0===s.lineValue?m+=h.getNoteY(e,Us.Center):m+=d;let f=0,y=Co.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,t=Co.DashSize,s=c+t;if((e-c)/(2*t)<1)o.moveTo(e,p),o.lineTo(c,p);else for(;e>s;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>c?(o.moveTo(c,p),o.bezierCurveTo((c+g)/2,p,g,p,g,m+f),o.stroke()):(o.moveTo(c,p),o.lineTo(g,m),o.stroke());if(n&&t.offset<s.offset){o.font=l.graceFont;let e=o.measureText(n).width,t=0,s=0;if(p>m){let i=Math.abs(p-m);t=i>1.3*o.font.size?p-i/2:p,s=(c+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,i=s.value>t.value;e=Math.abs(e);let r="";if(4===e)r="full",e-=4;else if(e>=4||e<=-4){let t=e/4|0;r+=t,e-=4*t}if(e>0&&(r+=Co.getFractionSign(e)),""!==r){m=a-u*s.value;let e=m;i||(e=p+1*Math.abs(m-p)/3),o.font=l.tablatureFont;let 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"}}}Co.ArrowSize=6,Co.DashSize=3,Co.BendValueHeight=6;class Eo extends ja{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===A.Custom)return e.whammyBarPoints;let t=[];switch(e.whammyBarType){case A.Dive:case A.Hold:case A.PrediveDive:case A.Predive:t.push(new se(0,e.whammyBarPoints[0].value)),t.push(new se(se.MaxPosition,e.whammyBarPoints[1].value));break;case A.Dip:t.push(new se(0,e.whammyBarPoints[0].value)),t.push(new se(se.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new se(se.MaxPosition,e.whammyBarPoints[e.whammyBarPoints.length-1].value))}return t}doLayout(){super.doLayout(),this._isSimpleDip=this.renderer.settings.notation.notationMode===e.NotationMode.SongBook&&this._beat.whammyBarType===A.Dip;let t=null,s=null,i=this._beat;for(;i&&i.hasWhammyBar;)(!t||t.value>i.minWhammyPoint.value)&&(t=i.minWhammyPoint),(!s||s.value<i.maxWhammyPoint.value)&&(s=i.maxWhammyPoint),i=i.nextBeat;let a=s.value>0?Math.abs(this.getOffset(s.value)):0;(a>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(e.NotationElement.ZerosOnDiveWhammys))&&(a+=2*this.renderer.resources.tablatureFont.size);let r=t.value<0?Math.abs(this.getOffset(t.value)):0;this.renderer.registerOverflowTop(a+r),a>this.renderer.staff.getSharedLayoutData(Eo.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(Eo.TopOffsetSharedDataKey,a)}getOffset(e){if(0===e)return 0;let t=Eo.PerHalfSize+Math.log2(Math.abs(e)/2)*Eo.PerHalfSize;return e<0&&(t=-t),t}paint(t,s,i){let a=this.renderer,r=this._beat.nextBeat,n=null,o=Ws.PreNotes;r&&(n=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.voice.bar),n&&n.staff===a.staff&&(n===a||r.hasWhammyBar)?o=!r.hasWhammyBar||a.settings.notation.notationMode===e.NotationMode.SongBook&&r.whammyBarType===A.Dip?Ws.PreNotes:Ws.MiddleNotes:(r=null,n=null));let h=0,l=0;this._isSimpleDip?(h=t+a.x+a.getBeatX(this._beat,Ws.OnNotes)-2,l=t+a.x+a.getBeatX(this._beat,Ws.PostNotes)+2):(h=t+a.x+a.getBeatX(this._beat,Ws.MiddleNotes),l=n?t+n.x+n.getBeatX(r,o):t+a.x+a.width-2);let c=i.textAlign;if(i.textAlign=L.Center,this._renderPoints.length>=2){let e=(l-h)/se.MaxPosition;i.beginPath();let t=s+this.renderer.staff.getSharedLayoutData(Eo.TopOffsetSharedDataKey,0),a=this._beat.whammyStyle===d.Gradual?"grad.":"";for(let s=0,r=this._renderPoints.length-1;s<r;s++){let n=this._renderPoints[s],o=this._renderPoints[s+1],l=s<r-2?this._renderPoints[s+2]:null,d=0===s;0!==s||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new se(0,0),n,o,h,t,e,i),d=!1),this.paintWhammy(d,n,o,l,h,t,e,i,a),a=""}i.stroke()}i.textAlign=c}paintWhammy(t,s,i,a,r,n,o,h,l){let d=r+o*s.offset,c=r+o*i.offset,u=n-this.getOffset(s.value),p=n-this.getOffset(i.value);if(s.offset===i.offset){let e=Eo.DashSize;if(Math.abs(p-u)/(2*e)<1)h.moveTo(d,u),h.lineTo(c,p);else{let t=Math.max(u,p),s=Math.min(u,p);for(;t>s;)h.moveTo(d,s),h.lineTo(d,s+e),s+=2*e}h.stroke()}else if(s.value===i.value){let e=Eo.DashSize;if(Math.abs(c-d)/(2*e)<1)h.moveTo(d,u),h.lineTo(c,p);else{let t=Math.max(d,c),s=Math.min(d,c);for(;t>s;)h.moveTo(t,u),h.lineTo(t-e,u),t-=2*e}h.stroke()}else h.moveTo(d,u),h.lineTo(c,p);let g=this.renderer.resources;if(t&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let t=u;t-=g.tablatureFont.size+2,this.renderer.settings.notation.isNotationElementVisible(e.NotationElement.ZerosOnDiveWhammys)&&h.fillText("0",d,t),l&&(t-=g.tablatureFont.size+2,h.fillText(l,d,t))}let m=Math.abs(i.value);if((0!==m||this.renderer.settings.notation.isNotationElementVisible(e.NotationElement.ZerosOnDiveWhammys)&&!this._isSimpleDip)&&s.value!==i.value){let e="";if(i.value<0&&(e+="-"),m>=4){let t=m/4|0;e+=t,m-=4*t}else 0===m&&(e+="0");m>0&&(e+=Co.getFractionSign(m));let t=0;this._isSimpleDip?t=Math.min(u,p)-g.tablatureFont.size-2:(t=s.offset===i.offset?Math.min(u,p):p,t-=g.tablatureFont.size+2,a&&a.value>i.value&&(t-=2));let r=c;h.fillText(e,r,t)}}}Eo.TopOffsetSharedDataKey="tab.whammy.topoffset",Eo.PerHalfSize=6,Eo.DashSize=3;class Fo extends vo{constructor(e){super(0,0),this._beat=e}doLayout(){let t=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case A.None:case A.Custom:case A.Hold:return;case A.Dive:case A.PrediveDive:{let e=new xo(this._beat,!1);e.renderer=this.renderer;let t=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let s of this._beat.notes)s.isTieOrigin||e.addGlyph(this.getBendNoteValue(s,t),t.value%2!=0);e.doLayout(),this.BendNoteHeads.push(e)}break;case A.Dip:if(t===e.NotationMode.SongBook){let e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+Fo.SimpleDipHeight+Fo.SimpleDipPadding}else{let t=new xo(this._beat,!1);if(t.renderer=this.renderer,this.renderer.settings.notation.notationMode===e.NotationMode.GuitarPro){let e=this._beat.whammyBarPoints[1];for(let s of this._beat.notes)t.addGlyph(this.getBendNoteValue(s,this._beat.whammyBarPoints[1]),e.value%2!=0)}t.doLayout(),this.BendNoteHeads.push(t);let s=new xo(this._beat,!1);if(s.renderer=this.renderer,this.renderer.settings.notation.notationMode===e.NotationMode.GuitarPro){let e=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let t of this._beat.notes)s.addGlyph(this.getBendNoteValue(t,e),e.value%2!=0)}s.doLayout(),this.BendNoteHeads.push(s)}case A.Predive:}super.doLayout()}paint(t,s,i){let a=this._beat;switch(a.whammyBarType){case A.None:case A.Custom:return}let r=this.renderer.settings.notation.notationMode,n=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,a.voice.bar),o=t+n.x+n.getBeatX(a,Ws.MiddleNotes),h=this.getTieDirection(a,n),l=1===this._beat.notes.length?h:We.Up,c=i.textAlign;for(let c=0;c<a.notes.length;c++){let u=a.notes[c],p=s+n.y;c>0&&c>=(this._beat.notes.length/2|0)&&(l=We.Down),l===We.Down?p+=n.getNoteY(u,Us.Bottom):p+=n.getNoteY(u,Us.Top);let g=t+n.x;a.isLastOfVoice?g+=n.width:g+=n.getBeatX(a,Ws.EndBeat),g-=8;let m=a.whammyStyle===d.Gradual&&0===c?"grad.":"",f=null;u.isTieOrigin&&(f=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,u.tieDestination.beat.voice.bar),f&&f.staff===n.staff?g=t+f.x+f.getBeatX(u.tieDestination.beat,Ws.MiddleNotes):f=null);let y=$a.NoteHeadHeight*$a.GraceScale*.5;l===We.Up&&(y=-y);let b=a.whammyBarPoints.length>0?this.getBendNoteValue(u,a.whammyBarPoints[a.whammyBarPoints.length-1]):0,S=0,_=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(b)?(S=this.BendNoteHeads[0].getNoteValueY(b)+y,_=!0):f&&(u.isTieOrigin&&u.tieDestination.beat.hasWhammyBar||u.beat.isContinuedWhammy)?(S=s+f.y+f.getNoteY(u.tieDestination,Us.Top),_=!0,l===We.Down&&(S+=$a.NoteHeadHeight)):u.isTieOrigin&&(S=f?s+f.y+f.getNoteY(u.tieDestination,Us.Top):p,l===We.Down&&(S+=$a.NoteHeadHeight)),a.whammyBarType){case A.Hold:u.isTieOrigin&&go.paintTie(i,1,o,p,g,S,h===We.Down,22,4);break;case A.Dive:0===c&&(this.BendNoteHeads[0].x=g-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=s+n.y,this.BendNoteHeads[0].paint(0,0,i),this.BendNoteHeads[0].containsNoteValue(b)&&(S+=this.BendNoteHeads[0].y)),_?this.drawBendSlur(i,o,p,g,S,l===We.Down,1,m):u.isTieOrigin&&go.paintTie(i,1,o,p,g,S,h===We.Down,22,4);break;case A.Dip:if(r===e.NotationMode.SongBook){if(0===c){let e=t+n.x+n.getBeatX(this._beat,Ws.OnNotes)-2,a=t+n.x+n.getBeatX(this._beat,Ws.PostNotes)+2,r=(e+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();i.font=this.renderer.resources.tablatureFont,i.fillText(o,r,s+this.y);let h=s+this.y+i.font.size+2,l=h+Fo.SimpleDipHeight;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(i.moveTo(e,l),i.lineTo(r,h),i.lineTo(a,l)):(i.moveTo(e,h),i.lineTo(r,l),i.lineTo(a,h)),i.stroke()}u.isTieOrigin&&go.paintTie(i,1,o,p,g,S,h===We.Down,22,4)}else{let e=(o+g)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=s+n.y,this.BendNoteHeads[0].paint(0,0,i);let t=this.getBendNoteValue(u,a.whammyBarPoints[1]),r=this.BendNoteHeads[0].getNoteValueY(t)+y;this.drawBendSlur(i,o,p,e,r,l===We.Down,1,m),this.BendNoteHeads[1].x=g-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=s+n.y,this.BendNoteHeads[1].paint(0,0,i),S=this.BendNoteHeads[1].getNoteValueY(b)+y,this.drawBendSlur(i,e,r,g,S,l===We.Down,1,m)}break;case A.PrediveDive:case A.Predive:let d=t+n.x+n.getBeatX(u.beat,Ws.PreNotes);d+=n.getPreNotesGlyphForBeat(u.beat).prebendNoteHeadOffset;let f=s+n.y+n.getScoreY(n.accidentalHelper.getNoteLineForValue(u.displayValue-(u.beat.whammyBarPoints[0].value/2|0),!1))+y;this.drawBendSlur(i,d,f,o,p,l===We.Down,1,m),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=g-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=s+n.y,this.BendNoteHeads[0].paint(0,0,i),this.drawBendSlur(i,o,p,g,S,l===We.Down,1,m))}}i.textAlign=c}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}Fo.SimpleDipHeight=2*Eo.PerHalfSize,Fo.SimpleDipPadding=2;class Do extends ja{constructor(e,t,s){super(e,t),this.width=s}}class Lo extends Qa{constructor(e,t,s,i,a){super(e,t,a?$a.GraceScale:1,s.getSymbol(i)),this._isGrace=a,this._articulation=s}paint(e,t,s){let i=this._isGrace?1:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale,this.symbol,!1),this._articulation.techniqueSymbol!==D.None&&this._articulation.techniqueSymbolPlacement===M.Middle&&s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale,this._articulation.techniqueSymbol,!1)}doLayout(){const e=this._isGrace?$a.GraceScale:1;switch(this.symbol){case D.NoteheadWhole:this.width=14;break;case D.NoteheadCircleX:case D.NoteheadDiamondWhite:this.width=9;break;case D.NoteheadHeavyXHat:case D.NoteheadHeavyX:this.width=13;break;default:this.width=10}this.width=this.width*e,this.height=$a.NoteHeadHeight*e}}class Mo extends Qa{constructor(e,t){super(e,t,$a.GraceScale,D.ArticStaccatoAbove)}doLayout(){this.width=$a.QuarterNoteHeadWidth,this.height=7}paint(e,t,s){super.paint(e+3,t+5,s)}}class Io extends Qa{constructor(e,t){super(e,t,.5,D.PictEdgeOfCymbal)}doLayout(){this.width=22,this.height=15}paint(e,t,s){super.paint(e-3,t+this.height,s)}}class Ao extends Ka{constructor(e,t,s=!1){super(e,t),this._center=s}doLayout(){this.width=9,this.height=10}paint(e,t,s){s.fillMusicFontSymbol(e+this.x,t+this.y+this.height,$a.GraceScale,D.GuitarGolpe,this._center)}}class Ro extends Ka{constructor(){super(...arguments),this._strings=new Set}addString(e){this._strings.add(e)}doLayout(){const e=$r.CircleNumberHeight*$r.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=$r.CircleNumberHeight*$r.CircleNumberScale;for(const n of this._strings){const o=i-n,h=D.GuitarString1+o;s.fillMusicFontSymbol(e+this.x+$a.NoteHeadHeight/2,t+this.y+r+a,$r.CircleNumberScale,h,!0),a+=r+3}}}class Oo extends Ka{constructor(e,t,s,i){super(e,t),this.beatEffects=new Map,this._isGrace=i,this._duration=s,this._symbol=Oo.getSymbol(s)}paint(e,t,s){let i=this._isGrace?1:0;const a=this._isGrace?$a.GraceScale:1;s.fillMusicFontSymbol(e+this.x,t+this.y+i,a,this._symbol,!1);for(const i of this.beatEffects.values())i.paint(e+this.x,t+this.y,s)}doLayout(){const e=this._isGrace?$a.GraceScale:1;switch(this._duration){case g.QuadrupleWhole:case g.DoubleWhole:case g.Whole:this.width=Oo.WholeNoteHeadWidth*e;break;case g.Half:this.width=Oo.HalfNoteHeadWidth*e;break;default:this.width=Oo.QuarterNoteHeadWidth*e}this.height=Oo.NoteHeadHeight*e;let t=Oo.NoteHeadHeight;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 g.QuadrupleWhole:case g.DoubleWhole:case g.Whole:return D.NoteheadSlashWhiteWhole;case g.Half:return D.NoteheadSlashWhiteHalf;default:return D.NoteheadSlashVerticalEnds}}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width,e+this.x)}}Oo.NoteHeadHeight=17,Oo.QuarterNoteHeadWidth=12,Oo.HalfNoteHeadWidth=25,Oo.WholeNoteHeadWidth=32;class Vo extends ln{constructor(){super(...arguments),this._collisionOffset=-1e3,this._skipPaint=!1,this.slash=null,this.noteHeads=null,this.restGlyph=null}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(){let 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===g.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const s=new To(0,e.getScoreY(t),this.container.beat.duration);if(this.restGlyph=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper,this.addGlyph(s),this.renderer.bar.isMultiVoice)if(0===this.container.beat.voice.index){const t=Lr.computeLineHeightsForRest(this.container.beat.duration);let 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.addGlyph(new Do(0,0,5));for(let e=0;e<this.container.beat.dots;e++){let e=new xr(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addGlyph(e)}}}else{if(this.container.beat.slashed){const t=this.container.beat.graceType!==f.None,s=(e.heightLineCount-1)/2,i=e.getLineY(s),a=new Oo(0,i,this.container.beat.duration,t);this.slash=a,a.beat=this.container.beat,a.beamingHelper=this.beamingHelper,this.addGlyph(a)}else{const e=new Bo;this.noteHeads=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;let t=new yo(!1);t.renderer=this.renderer;for(let e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),t.addParenthesis(e));this.addGlyph(e),t.isEmpty||(this.addGlyph(new Do(0,0,4*(this.container.beat.graceType!==f.None?$a.GraceScale:1))),this.addGlyph(t))}if(this.container.beat.hasWhammyBar){let e=new Fo(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addGlyph(new Do(0,0,5));for(let t=0;t<this.container.beat.dots;t++){let t=new xr(0,0);t.renderer=this.renderer;for(let s of this.container.beat.notes)this.createBeatDot(e.getNoteLine(s),t);this.addGlyph(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){let s=this.renderer;t.addGlyph(new co(0,s.getScoreY(e),1.5))}createNoteHeadGlyph(e){let t=this.container.beat.graceType!==f.None;if(e.beat.voice.bar.staff.isPercussion){const s=pe.getArticulation(e);if(s)return new Lo(0,0,s,e.beat.duration,t);ne.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new uo(0,0,t):e.beat.graceType===f.BendGrace?new $a(0,0,g.Quarter,!0):e.harmonicType===b.Natural?new po(0,0,e.beat.duration,t):new $a(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===f.BendGrace&&!e.hasBend)return;let t=this.renderer,s=this.createNoteHeadGlyph(e),i=t.getNoteLine(e);if(s.y=t.getScoreY(i),this.noteHeads.addNoteGlyph(s,e,i),e.harmonicType!==b.None&&e.harmonicType!==b.Natural){let a=e.displayValue+e.harmonicPitch;s=new po(0,0,e.beat.duration,this.container.beat.graceType!==f.None),i=t.accidentalHelper.getNoteLineForValue(a,!1),s.y=t.getScoreY(i),this.noteHeads.addNoteGlyph(s,e,i)}const r=this.noteHeads.belowBeatEffects,n=this.noteHeads.aboveBeatEffects;if(e.isStaccato&&!r.has("Staccato")&&r.set("Staccato",new Mo(0,0)),e.accentuated!==a.Normal||r.has("Accent")||r.set("Accent",new lo(0,0,e)),e.accentuated!==a.Heavy||r.has("HAccent")||r.set("HAccent",new lo(0,0,e)),e.accentuated!==a.Tenuto||r.has("Tenuto")||r.set("Tenuto",new lo(0,0,e)),e.showStringNumber&&e.isStringed){let t;n.has("StringNumber")?t=n.get("StringNumber"):(t=new Ro(0,0),n.set("StringNumber",t)),t.addString(e.string)}if(e.isPercussion){const t=pe.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==M.Middle){const e=t.techniqueSymbolPlacement===M.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case D.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new Io(0,0));break;case D.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new Mo(0,0));break;case D.StringsUpBow:e.set("StringsUpBow",new On(0,0,F.Up));break;case D.StringsDownBow:e.set("StringsDownBow",new On(0,0,F.Down));break;case D.GuitarGolpe:e.set("GuitarGolpe",new Ao(0,0))}}}}}class Ho extends ja{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=this._beat.brushType===u.ArpeggioUp||this._beat.brushType===u.ArpeggioDown?10:0}paint(e,t,s){if(this._beat.brushType===u.ArpeggioUp||this._beat.brushType===u.ArpeggioDown){let i=this.renderer,a=i.lineOffset,r=t+this.y+(i.getNoteY(this._beat.maxNote,Us.Bottom)-a),n=t+this.y+i.getNoteY(this._beat.minNote,Us.Top)+a,o=e+this.x+this.width/2,h=8,l=new Wn(0,0,B.Slight,1.2,!0);l.renderer=this.renderer,l.doLayout();let d=-l.height/2;if(this._beat.brushType===u.ArpeggioUp){let t=r+h,i=n-h;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5,i,-90),l.paint(0,d,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===u.ArpeggioDown){let t=r+h,i=n;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5,t,90),l.paint(0,d,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 Go{constructor(e,t){this.line=0,this.line=e,this.text=t}}class Wo extends xr{constructor(){super(0,0),this._infos=new Map}get isEmpty(){return 0===this._infos.size}addFingers(t){const s=this.renderer.settings;if(s.notation.fingeringMode!==e.FingeringMode.ScoreDefault&&s.notation.fingeringMode!==e.FingeringMode.ScoreForcePiano)return;const i=de.fingerToString(this.renderer.settings,t.beat,t.leftHandFinger,!0);i&&this.addFinger(t,i);const a=de.fingerToString(this.renderer.settings,t.beat,t.rightHandFinger,!1);a&&this.addFinger(t,a)}addFinger(e,t){let s=this.renderer.getNoteLine(e);if(this._infos.has(s)){this._infos.get(s).text+=t}else{const e=new Go(s,t);this._infos.set(s,e)}}doLayout(){let e=this.renderer;for(const[t,s]of this._infos){const t=new Wr(0,0,s.text,e.resources.inlineFingeringFont,L.Left,M.Middle);t.renderer=e,t.y=e.getScoreY(s.line),t.doLayout(),this.addGlyph(t),this.width=Math.max(this.width,t.width)}}}class zo extends hn{get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}doLayout(){if(!this.container.beat.isRest){let e=new No;e.renderer=this.renderer;let t=new Wo;t.renderer=this.renderer;let s=new yo(!0);s.renderer=this.renderer;const i=new xo(this.container.beat,!0);this._prebends=i,i.renderer=this.renderer;for(let a of this.container.beat.notes)if(a.isVisible){if(a.hasBend)switch(a.bendType){case c.PrebendBend:case c.Prebend:case c.PrebendRelease:i.addGlyph(a.displayValue-(a.bendPoints[0].value/2|0),!1)}else if(a.beat.hasWhammyBar)switch(a.beat.whammyBarType){case A.PrediveDive:case A.Predive:this._prebends.addGlyph(a.displayValue-(a.beat.whammyBarPoints[0].value/2|0),!1)}this.createAccidentalGlyph(a,e),s.addParenthesis(a),t.addFingers(a)}i.isEmpty||(this.addGlyph(i),this.addGlyph(new Do(0,0,4*(this.container.beat.graceType!==f.None?$a.GraceScale:1)))),this.container.beat.brushType!==u.None&&(this.addGlyph(new Ho(this.container.beat)),this.addGlyph(new Do(0,0,4))),t.isEmpty||(this.isEmpty||this.addGlyph(new Do(0,0,2*(this.container.beat.graceType!==f.None?$a.GraceScale:1))),this.addGlyph(t),this.addGlyph(new Do(0,0,2*(this.container.beat.graceType!==f.None?$a.GraceScale:1)))),s.isEmpty||(this.addGlyph(s),this.addGlyph(new Do(0,0,4*(this.container.beat.graceType!==f.None?$a.GraceScale:1)))),e.isEmpty||(this.accidentals=e,this.isEmpty||this.addGlyph(new Do(0,0,2*(this.container.beat.graceType!==f.None?$a.GraceScale:1))),this.addGlyph(e),this.addGlyph(new Do(0,0,2*(this.container.beat.graceType!==f.None?$a.GraceScale:1))))}super.doLayout()}createAccidentalGlyph(e,t){let s=this.renderer,i=s.accidentalHelper.applyAccidental(e),a=s.getNoteLine(e),r=this.container.beat.graceType!==f.None;const n=r?$a.GraceScale:1;if(i!==Je.None){let e=new oo(0,s.getScoreY(a),i,n);e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==b.None&&e.harmonicType!==b.Natural){let o=e.displayValue+e.harmonicPitch;i=s.accidentalHelper.applyAccidentalForValue(e.beat,o,r,!1),a=s.accidentalHelper.getNoteLineForValue(o,!1);let h=new oo(0,s.getScoreY(a),i,n);h.renderer=this.renderer,t.addGlyph(h)}}constructor(){super(),this._prebends=null,this.accidentals=null}}class Uo extends Qa{constructor(e,t,s,i){super(e,t,i,Uo.getSymbol(s)),this._digit=0,this._scale=0,this._digit=s,this._scale=i}doLayout(){this.width=this.getDigitWidth(this._digit)*this._scale}getDigitWidth(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:return 14;case 1:return 10;default:return 0}}static getSymbol(e){switch(e){case 0:return D.TimeSig0;case 1:return D.TimeSig1;case 2:return D.TimeSig2;case 3:return D.TimeSig3;case 4:return D.TimeSig4;case 5:return D.TimeSig5;case 6:return D.TimeSig6;case 7:return D.TimeSig7;case 8:return D.TimeSig8;case 9:return D.TimeSig9;default:return D.None}}}class Xo extends xr{constructor(e,t,s,i=1){super(e,t),this._number=0,this._scale=0,this._number=s,this._scale=i}doLayout(){let e=this._number;for(;e>0;){let t=new Uo(0,0,e%10,this._scale);this.addGlyph(t),e=e/10|0}if(this.glyphs){this.glyphs.reverse();let e=0;for(let t=0,s=this.glyphs.length;t<s;t++){let s=this.glyphs[t];s.x=e,s.y=0,s.renderer=this.renderer,s.doLayout(),e+=s.width}this.width=e}}}Xo.numberHeight=18;class Jo extends xr{constructor(e,t,s,i,a,r){super(e,t),this._numerator=0,this._denominator=0,this._numerator=s,this._denominator=i,this._isCommon=a,this._isFreeTime=r}doLayout(){let e=0;const t=Xo.numberHeight;if(this._isFreeTime){const s=new mo(!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){let t=new Qa(e,0,this.commonScale,D.TimeSigCutCommon);t.width=14,this.addGlyph(t),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){let t=new Qa(e,0,this.commonScale,D.TimeSigCommon);t.width=14,this.addGlyph(t),super.doLayout()}else{let s=new Xo(e,-t/2,this._numerator,this.numberScale),i=new Xo(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 mo(!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 Yo extends Jo{get commonScale(){return 1}get numberScale(){return 1}}class qo extends vo{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)switch(e.bendType){case c.Bend:case c.PrebendRelease:case c.PrebendBend:{let t=this._endNoteGlyph;t||(t=new xo(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let s=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,s),s.value%2!=0)}break;case c.Release:if(!e.isTieOrigin){let t=this._endNoteGlyph;t||(t=new xo(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let s=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,s),s.value%2!=0)}break;case c.BendRelease:{let t=this._middleNoteGlyph;t||(t=new xo(e.beat,!1),this._middleNoteGlyph=t,t.renderer=this.renderer,this.BendNoteHeads.push(t));let s=e.bendPoints[1];t.addGlyph(this.getBendNoteValue(e,e.bendPoints[1]),s.value%2!=0);let i=this._endNoteGlyph;i||(i=new xo(e.beat,!1),i.renderer=this.renderer,this._endNoteGlyph=i,this.BendNoteHeads.push(i));let a=e.bendPoints[e.bendPoints.length-1];i.addGlyph(this.getBendNoteValue(e,a),a.value%2!=0)}}}paint(e,t,s){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._beat.voice.bar),a=e+i.x+i.getBeatX(this._beat,Ws.MiddleNotes),r=e+i.x;this._beat.isLastOfVoice?r+=i.postBeatGlyphsStart:r+=i.getBeatX(this._beat.nextBeat,Ws.PreNotes),r-=8;let 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));let o=this._beat.graceType===f.BendGrace?this._beat.nextBeat:this._beat,h=1===this._notes.length?this.getTieDirection(o,i):We.Up;for(let o=0;o<this._notes.length;o++){let l=this._notes[o];o>0&&o>=(this._notes.length/2|0)&&(h=We.Down);let u=t+i.y+i.getNoteY(l,Us.Top),p=$a.NoteHeadHeight*$a.GraceScale*.5;h===We.Down&&(u+=$a.NoteHeadHeight);let g=l.bendStyle===d.Gradual?"grad.":"";if(l.isTieOrigin){let r=l.tieDestination,n=r?this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.beat.voice.bar):null;if(n&&n.staff===i.staff){let i=e+n.x+n.getBeatX(r.beat,Ws.MiddleNotes),o=t+n.y+n.getNoteY(r,Us.Top);h===We.Down&&(o+=$a.NoteHeadHeight),l.bendType===c.Hold||l.bendType===c.Prebend?go.paintTie(s,1,a,u,i,o,h===We.Down,22,4):this.drawBendSlur(s,a,u,i,o,h===We.Down,1,g)}else{let r=e+i.x+i.width,n=l.tieDestination.realValue;i.accidentalHelper.applyAccidentalForValue(l.beat,n,!1,!0);let o=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(n,!1));l.bendType===c.Hold||l.bendType===c.Prebend?go.paintTie(s,1,a,u,r,o,h===We.Down,22,4):this.drawBendSlur(s,a,u,r,o,h===We.Down,1,g)}switch(l.bendType){case c.Prebend:case c.PrebendBend:case c.PrebendRelease:let r=e+i.x+i.getBeatX(l.beat,Ws.PreNotes);r+=i.getPreNotesGlyphForBeat(l.beat).prebendNoteHeadOffset;let n=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(l.displayValue-(l.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,r,n,a,u,h===We.Down,1)}}else{h===We.Up&&(p=-p);let o=0,d=0;switch(l.bendType){case c.Bend:o=this.getBendNoteValue(l,l.bendPoints[l.bendPoints.length-1]),d=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,d,h===We.Down,1,g);break;case c.BendRelease:let m=this.getBendNoteValue(l,l.bendPoints[1]),f=this._middleNoteGlyph.getNoteValueY(m)+p;this.drawBendSlur(s,a,u,n,f,h===We.Down,1,g),o=this.getBendNoteValue(l,l.bendPoints[l.bendPoints.length-1]),d=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,n,f,r,d,h===We.Down,1,g);break;case c.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(l,l.bendPoints[l.bendPoints.length-1]),d=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,d,h===We.Down,1,g));break;case c.Prebend:case c.PrebendBend:case c.PrebendRelease:let y=e+i.x+i.getBeatX(l.beat,Ws.PreNotes);y+=i.getPreNotesGlyphForBeat(l.beat).prebendNoteHeadOffset;let b=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(l.displayValue-(l.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,y,b,a,u,h===We.Down,1),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(l,l.bendPoints[l.bendPoints.length-1]),d=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,d,h===We.Down,1,g))}}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class jo extends go{constructor(e,t,s=!1){super(e,t,s)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?We.Up:t.getBeatDirection(e)===We.Up?We.Down:We.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===We.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,Us.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,Us.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===We.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===f.None?s===this.tieDirection?this.tieDirection===We.Up?e.getNoteY(this.endBeat.maxNote,Us.TopWithStem):e.getNoteY(this.endBeat.minNote,Us.BottomWithStem):this.tieDirection===We.Up?e.getNoteY(this.endBeat.maxNote,Us.BottomWithStem):e.getNoteY(this.endBeat.minNote,Us.TopWithStem):this.tieDirection===We.Up?e.getNoteY(this.endBeat.maxNote,Us.Top):e.getNoteY(this.endBeat.minNote,Us.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,Ws.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>g.Whole&&e===this.tieDirection?Ws.Stem:Ws.MiddleNotes)}}class Ko extends ja{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){let i=this.renderer,a=e+i.x+i.getNoteX(this._startNote,Xs.Left)-2,r=t+i.y+i.getNoteY(this._startNote,Us.Center),n=a-12,o=t+i.y;switch(this._inType){case _.IntoFromBelow:o+=i.getNoteY(this._startNote,Us.Bottom);break;case _.IntoFromAbove:o+=i.getNoteY(this._startNote,Us.Top);break;default:return}let h=this.getAccidentalsWidth(i,this._startNote.beat);n-=h,a-=h,this.paintSlideLine(s,!1,n,a,o,r)}getAccidentalsWidth(e,t){let s=e.getPreNotesGlyphForBeat(t);return s&&s.accidentals?s.accidentals.width:0}drawSlideOut(e,t,s){let i=this.renderer,a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case w.Shift:case w.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,Ws.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,Us.Center),this._startNote.slideTarget){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,Ws.PreNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,Us.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 w.OutUp:a=e+i.x+i.getNoteX(this._startNote,Xs.Right)+2,r=t+i.y+i.getNoteY(this._startNote,Us.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,Us.Top);break;case w.OutDown:a=e+i.x+i.getNoteX(this._startNote,Xs.Right)+2,r=t+i.y+i.getNoteY(this._startNote,Us.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,Us.Bottom);break;case w.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,Xs.Right)+4,r=t+i.y+i.getNoteY(this._startNote,Us.Center),o=t+i.y+i.getNoteY(this._startNote,Us.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,Ws.PreNotes)),h=!0;break;case w.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,Xs.Right)+4,r=t+i.y+i.getNoteY(this._startNote,Us.Center),o=t+i.y+i.getNoteY(this._startNote,Us.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,Ws.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new Wn(0,0,B.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;let n=i-s,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;let 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 Qo extends jo{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===We.Up?this.startNoteRenderer.getNoteY(this._startNote,Us.Top):this.startNoteRenderer.getNoteY(this._startNote,Us.Bottom):this.startNoteRenderer.getNoteY(this._startNote,Us.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===We.Up?this.endNoteRenderer.getNoteY(this._endNote,Us.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,Us.BottomWithStem):this.tieDirection===We.Up?this.endNoteRenderer.getNoteY(this._endNote,Us.Top):this.endNoteRenderer.getNoteY(this._endNote,Us.Bottom):this.endNoteRenderer.getNoteY(this._endNote,Us.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===We.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===We.Down}isEndCentered(){return this._startNote.beat.graceType===f.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===We.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===We.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===f.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,Ws.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,Xs.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,Ws.Stem):this.endNoteRenderer.getNoteX(this._endNote,Xs.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,Ws.PreNotes)}}class $o extends go{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)===We.Up?We.Down:We.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===We.Up?this.startNoteRenderer.getNoteY(this.startNote,Us.Top):this.startNoteRenderer.getNoteY(this.startNote,Us.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===We.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===We.Up?e.getNoteY(this.endNote,Us.Top):e.getNoteY(this.endNote,Us.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,Ws.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,Ws.PreNotes)}}class Zo extends er{constructor(e,t){super(e,t),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!==f.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){let t=new $o(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){let t=new $o(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==_.None||e.slideOutType!==w.None){let t=new Ko(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){let t=new Qo(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){let t=new Qo(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new Qo(e,e.effectSlurDestination,!1);this._effectSlur=t,this.addTie(t)}if(!this._effectEndSlur&&e.beat.isEffectSlurDestination&&e.beat.effectSlurOrigin){let t=this.onNotes.beamingHelper.direction,s=t===We.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,i=t===We.Up?e.beat.minNote:e.beat.maxNote;const a=new Qo(s,i,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new qo(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 jo(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 jo(e,this.beat,!0))}}}}class eh extends ja{constructor(e,t,s,i){super(e,t),this._dotOffset=0,this._circleSize=0,this._dotOffset=0,this._circleSize=0,this._dotOffset=i,this._circleSize=s}doLayout(){this.width=13}paint(e,t,s){let i=t+this.y+this.renderer.topPadding,a=t+this.y+this.renderer.height-this.renderer.bottomPadding,r=e+this.x+.5,n=a-i;s.fillRect(r,i,4,n),r+=7.5,s.beginPath(),s.moveTo(r,i),s.lineTo(r,a),s.stroke(),r+=3;let o=this._circleSize,h=(i+a)/2;s.fillCircle(r,h-o*this._dotOffset,o),s.fillCircle(r,h+o*this._dotOffset,o)}}class th extends ja{constructor(e,t){super(e,t)}doLayout(){this.renderer.isLast?this.width=15:this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart?this.width=2:(this.width=2,this.renderer.bar.masterBar.isDoubleBar&&(this.width+=2))}paint(e,t,s){let i=t+this.y+this.renderer.topPadding,a=t+this.y+this.renderer.height-this.renderer.bottomPadding,r=e+this.x,n=a-i;if(this.renderer.isLast)s.fillRect(r+this.width-4-4,i,1,n),s.fillRect(r+this.width-4,i,4,n);else if(!this.renderer.nextRenderer||this.renderer.nextRenderer.staff!==this.renderer.staff||!this.renderer.nextRenderer.bar.masterBar.isRepeatStart)if(this.renderer.bar.masterBar.isFreeTime){const e=th.DashSize,t=.5+(r+this.width-1|0),o=Math.ceil(n/2/e);if(s.beginPath(),o<1)s.moveTo(t,i),s.lineTo(t,a);else{let r=i;const h=(n-o*e)/(o-1);for(;r<a;)s.moveTo(t,r),s.lineTo(t,r+e),r+=e+h}s.stroke()}else s.fillRect(r+this.width-1,i,1,n),this.renderer.bar.masterBar.isDoubleBar&&s.fillRect(r+this.width-5,i,1,n)}}th.DashSize=4;class sh extends ja{constructor(e,t){super(e,t)}doLayout(){this.width=11}paint(e,t,s){let i=t+this.y+this.renderer.topPadding,a=t+this.y+this.renderer.height-this.renderer.bottomPadding,r=e+this.x,n=a-i,o=1.5,h=(i+a)/2;s.fillCircle(r,h-4.5,o),s.fillCircle(r,h+4.5,o),r+=4,s.beginPath(),s.moveTo(r,i),s.lineTo(r,a),s.stroke(),r+=3.5,s.fillRect(r,i,4,n)}}class ih extends ja{constructor(e,t,s){super(e,t),this._count=0,this._count=0,this._count=s}doLayout(){this.width=0}paint(e,t,s){let i=this.renderer.resources,a=s.textAlign;s.font=i.barNumberFont,s.textAlign=L.Right;let r="x"+this._count,n=s.measureText(r).width/1.5;s.fillText(r,e+this.x-n,t+this.y),s.textAlign=a}}class ah extends ja{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;let i=this.renderer.resources,a=s.color;const r=s.textBaseline;s.textBaseline=M.Top,s.color=i.barNumberColor,s.font=i.barNumberFont,s.fillText(this._number.toString(),e+this.x,t+this.y),s.color=a,s.textBaseline=r}}class rh extends sn{constructor(e,t){super(e,t),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(){let 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);const i=this.resources;s.color=i.staffLineColor;const a=[];for(let e=0,t=this.drawnLineCount;e<t;e++)a.push([]);this.collectSpaces(a);for(const e of a)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));for(let i=0;i<this.drawnLineCount;i++){const r=this.getLineY(i);let n=0;for(let o of a[i])s.fillRect(e+this.x+n,t+this.y+r|0,o[0]-n,sn.StaffLineThickness),n=o[0]+o[1];s.fillRect(e+this.x+n,t+this.y+r|0,this.width-n,sn.StaffLineThickness)}s.color=i.mainGlyphColor,this.paintSimileMark(e,t,s)}collectSpaces(e){}createStartSpacing(){if(this._startSpacing)return;const e=0===this.index?this.settings.display.firstStaffPaddingLeft:this.settings.display.staffPaddingLeft;this.addPreBeatGlyph(new Do(0,0,e)),this._startSpacing=!0}paintTuplets(e,t,s,i=!1){for(const a of this.bar.voices)if(this.hasVoiceContainer(a)){const r=this.getVoiceContainer(a);for(const a of r.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,a,i)}}getTupletBeamDirection(e){return this.getBeamDirection(e)}paintTupletHelper(e,t,s,i,a){const r=this.resources;let n,o=s.textAlign,h=s.textBaseline;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=L.Center,s.textBaseline=M.Middle;let l=i.beats[0].tupletNumerator,d=i.beats[0].tupletDenominator;n=2===l&&3===d?"2":3===l&&2===d?"3":4===l&&6===d?"4":5===l&&4===d?"5":6===l&&4===d?"6":7===l&&4===d?"7":9===l&&8===d?"9":10===l&&8===d?"10":11===l&&8===d?"11":12===l&&8===d?"12":13===l&&8===d?"13":l+":"+d;let c=this.tupletOffset,u=5;if(1!==i.beats.length&&i.isFull){let o=i.beats[0],h=i.beats[i.beats.length-1],l=null,d=null;for(let e=0;e<i.beats.length;e++)if(!i.beats[e].isRest){l=i.beats[e];break}for(let e=i.beats.length-1;e>=0;e--)if(!i.beats[e].isRest){d=i.beats[e];break}let p=!1;l||(l=o,p=!0),d||(d=h);let g=this.helpers.beamHelperLookup[i.voice.index].get(o.index),m=this.helpers.beamHelperLookup[i.voice.index].get(h.index),f=g.getBeatLineX(o),y=m.getBeatLineX(h),b=this.helpers.beamHelperLookup[i.voice.index].get(l.index),S=this.helpers.beamHelperLookup[i.voice.index].get(d.index),_=this.getTupletBeamDirection(g),w=this.calculateBeamYWithDirection(b,f,_),B=this.calculateBeamYWithDirection(S,y,_);p&&(w=Math.max(w,B),B=w),s.font=r.effectFont;let T=s.measureText(n).width,k=3,N=(f+y)/2,x=N-T/2-k,v=N+T/2+k,P=(B-w)/(y-f),C=w-P*f,E=P*x+C,F=P*N+C,D=P*v+C;_===We.Down&&(c*=-1,u*=-1),s.beginPath(),s.moveTo(e+this.x+f,t+this.y+w-c|0),a?s.quadraticCurveTo(e+this.x+(x+f)/2,t+this.y+E-c-u|0,e+this.x+x,t+this.y+E-c-u|0):(s.lineTo(e+this.x+f,t+this.y+w-c-u|0),s.lineTo(e+this.x+x,t+this.y+E-c-u|0)),s.stroke(),s.beginPath(),s.moveTo(e+this.x+v,t+this.y+D-c-u|0),a?s.quadraticCurveTo(e+this.x+(y+v)/2,t+this.y+D-c-u|0,e+this.x+y,t+this.y+B-c|0):(s.lineTo(e+this.x+y,t+this.y+B-c-u|0),s.lineTo(e+this.x+y,t+this.y+B-c|0)),s.stroke(),s.fillText(n,e+this.x+N,t+this.y+F-c-u)}else for(const a of i.beats){let o=this.helpers.beamHelperLookup[i.voice.index].get(a.index);if(!o)continue;let h=this.getTupletBeamDirection(o),l=o.getBeatLineX(a),d=this.calculateBeamYWithDirection(o,l,h);h===We.Down?d+=c+u:d-=c+u,s.font=r.effectFont,s.fillText(n,e+this.x+l,t+this.y+d)}s.textAlign=o,s.textBaseline=h}paintBeams(e,t,s){for(const i of this.helpers.beamHelpers)for(const a of i)this.paintBeamHelper(e+this.beatGlyphsStart,t,s,a)}drawBeamHelperAsFlags(e){return 1===e.beats.length}paintBeamHelper(e,t,s,i){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(this.drawBeamHelperAsFlags(i)?this.paintFlag(e,t,s,i):this.paintBar(e,t,s,i))}shouldPaintFlag(t,s){return t.graceType!==f.BendGrace&&(!t.deadSlapped&&(!!s.hasBeatLineX(t)&&((t.graceType===f.None||this.settings.notation.notationMode!==e.NotationMode.SongBook)&&(t.duration!==g.Whole&&t.duration!==g.DoubleWhole&&t.duration!==g.QuadrupleWhole))))}paintFlag(e,t,s,i){for(const a of i.beats){if(!this.shouldPaintFlag(a,i))continue;let r=a.graceType!==f.None,n=r?$a.GraceScale:1,o=this.getFlagStemSize(i.shortestDuration),h=i.getBeatLineX(a),l=this.getBeamDirection(i),d=this.getFlagTopY(a,l),c=this.getFlagBottomY(a,l),u=0;if(l===We.Down?(c+=o*n,u=c):(d-=o*n,u=d),i.hasLine(!0,a)){if(this.paintBeamingStem(a,t+this.y,e+this.x+h,t+this.y+d,t+this.y+c,s),a.graceType===f.BeforeBeat){let i=15,a=12;s.beginPath(),l===We.Down?(s.moveTo(e+this.x+h-a/2,t+this.y+c-i),s.lineTo(e+this.x+h+a/2,t+this.y+c)):(s.moveTo(e+this.x+h-a/2,t+this.y+d+i),s.lineTo(e+this.x+h+a/2,t+this.y+d)),s.stroke()}if(i.hasFlag(!0,a)){let i=new Za(h-.5,u,a.duration,l,r);i.renderer=this,i.doLayout(),i.paint(e+this.x,t+this.y,s)}}}}getFlagStemSize(e,t=!1){let s=0;switch(e){case g.QuadrupleWhole:case g.Half:case g.Quarter:case g.Eighth:case g.Sixteenth:case g.ThirtySecond:case g.SixtyFourth:case g.OneHundredTwentyEighth:case g.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.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new eh(0,0,1.5,3)),this.createLinePreBeatGlyphs(),this.addPreBeatGlyph(new ah(0,this.getLineHeight(-.25),this.bar.index+1))}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new sh(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new ih(0,this.getLineHeight(-.25),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new th(0,0))}paintBar(e,t,s,i){for(let a=0,r=i.beats.length;a<r;a++){let r=i.beats[a];if(!i.hasBeatLineX(r)||r.deadSlapped)continue;let n=r.graceType!==f.None?$a.GraceScale:1,o=i.getBeatLineX(r),h=this.getBeamDirection(i),l=t+this.y+this.getBarLineStart(r,h),d=t+this.y+this.calculateBeamY(i,o);this.paintBeamingStem(r,t+this.y,e+this.x+o,l,d,s);let c=d;h===We.Down?c+=2*s.font.size:0!==a&&(c-=1.5*s.font.size);let u=6*n,p=(sn.BeamSpacing+sn.BeamThickness)*n,g=sn.BeamThickness*n,m=de.getIndex(r.duration)-2,y=t+this.y;h===We.Down&&(p=-p,g=-g);for(let t=0;t<m;t++){let n=0,h=0,l=0,d=0,c=y+t*p;if(a<i.beats.length-1){const p=Lr.isFullBarJoin(r,i.beats[a+1],t);if(t===m-1&&p&&r.beamingMode===W.ForceSplitOnSecondaryToNext)n=o,h=n+u,l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),rh.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g),h=i.getBeatLineX(i.beats[a+1]),n=h-u,l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),rh.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g);else{if(p)n=o,h=i.getBeatLineX(i.beats[a+1]);else{if(0!==a&&Lr.isFullBarJoin(i.beats[a-1],r,t))continue;n=o,h=n+u}l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),rh.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g)}}else a>0&&!Lr.isFullBarJoin(r,i.beats[a-1],t)&&(n=o-u,h=o,l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),rh.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g))}}}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 nh extends rh{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.beatEffectsMinY=null,this.beatEffectsMaxY=null,this.accidentalHelper=new Er(this)}get lineSpacing(){return sn.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){let e=this.getScoreY(-2),t=this.getScoreY(10),s=this.simpleWhammyOverflow;const 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),n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);n.direction===We.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),h=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);h.direction===We.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),this.paintTuplets(e,t,s)}getSlashFlagY(e,t){let s=(this.heightLineCount-1)/2,i=0;switch(e){case g.QuadrupleWhole:case g.DoubleWhole:case g.Whole:i+=2;break;default:i+=1}t==We.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*=$a.GraceScale),s}getBarStemSize(e){let t=0;switch(e){case g.QuadrupleWhole:case g.Half:case g.Quarter:case g.Eighth:case g.Sixteenth:t=6;break;case g.ThirtySecond:t=8;break;case g.SixtyFourth:case g.OneHundredTwentyEighth:t=9;break;case g.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){let e=(this.heightLineCount-1)/2;return this.getLineY(e)}let s=super.getNoteY(e,t);if(isNaN(s)){const t=Er.computeLineWithoutAccidentals(this.bar,e);s=this.getScoreY(t)}return s}applyLayoutingInfo(){const e=super.applyLayoutingInfo();if(e&&this.bar.isMultiVoice){let 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){let i=this.getStemSize(e);if(!e.drawingInfos.has(s)){let t=new Dr;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===We.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===We.Up?this.getFlagTopY(a,s)-i:this.getFlagBottomY(a,s)+i,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?s===We.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===We.Up?this.getFlagTopY(r,s)-i:this.getFlagBottomY(r,s)+i;let o=10;if(s===We.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),s===We.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),s===We.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),s===We.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(s===We.Up){let s=this.getScoreY(this.accidentalHelper.getMinLine(e.beatOfHighestNote))-i;const 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=de.getIndex(e.shortestDuration)-2;let a=e.isGrace?$a.GraceScale:1,r=i*(sn.BeamSpacing+sn.BeamThickness)*a;if(r+=sn.BeamSpacing,s===We.Up&&null!==e.minRestLine){let s=this.getScoreY(e.minRestLine)-r;const i=t.calcY(e.getBeatLineX(e.beatOfMinRestLine))-s;i>0&&(t.startY-=i,t.endY-=i)}else if(s===We.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===We.Up?n-=i:s===We.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===We.Up?this.getScoreY(this.accidentalHelper.getMaxLine(e)):this.getScoreY(this.accidentalHelper.getMinLine(e))}createLinePreBeatGlyphs(){if(this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let e=0;switch(this.bar.clef){case n.Neutral:e=this.bar.staff.standardNotationLineCount-1;break;case n.F4:e=2;break;case n.C3:e=4;break;case n.C4:e=2;break;case n.G2:e=6}this.createStartSpacing(),this.addPreBeatGlyph(new ho(0,this.getScoreY(e)+.5*sn.StaffLineThickness,this.bar.clef,this.bar.clefOttava))}(0===this.index&&this.bar.masterBar.keySignature!==P.C||this.bar.previousBar&&this.bar.masterBar.keySignature!==this.bar.previousBar.masterBar.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,t=this.bar.masterBar.keySignature,s=this.bar.previousBar?this.bar.previousBar.masterBar.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}let i=new Map,a=[];if(de.keySignatureIsSharp(t))for(let s=0;s<Math.abs(t);s++){let t=nh.SharpKsSteps[s]+e;a.push(new oo(0,this.getScoreY(t),Je.Sharp,1)),i.set(t,!0)}else for(let s=0;s<Math.abs(t);s++){let t=nh.FlatKsSteps[s]+e;a.push(new oo(0,this.getScoreY(t),Je.Flat,1)),i.set(t,!0)}if(this.bar.masterBar.keySignature===P.C){let t=Math.abs(s),a=de.keySignatureIsSharp(s)?nh.SharpKsSteps:nh.FlatKsSteps;for(let s=0;s<t;s++){let t=a[s]+e;i.has(t)||this.addPreBeatGlyph(new oo(0,this.getScoreY(a[s]+e),Je.Natural,1))}}for(let e of a)this.addPreBeatGlyph(e)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Do(0,0,5));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new Yo(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){let s=new Zo(t,this.getVoiceContainer(e));s.preNotes=new zo,s.onNotes=new Vo,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,Us.Center),s=this.getNoteY(e.lowestNoteInHelper,Us.Center),i=this.getStemSize(e);e.hasTuplet&&(i+=2*this.resources.effectFont.size),e.direction==We.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){r.lineWidth=sn.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}}nh.StaffId="score",nh.SharpKsSteps=[-1,2,-2,1,4,0,3],nh.FlatKsSteps=[3,0,4,1,5,2,6];class oh extends Nr{get staffId(){return nh.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 nh(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showStandardNotation}constructor(){super()}}class hh extends ja{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){let i=this.renderer,a=0,r=0,n=0,o=0;switch(this._inType){case _.IntoFromBelow:n=e+i.x+i.getNoteX(this._startNote,Xs.Left)-2,o=t+i.y+i.getNoteY(this._startNote,Us.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,Us.Center)+3;break;case _.IntoFromAbove:n=e+i.x+i.getNoteX(this._startNote,Xs.Left)-2,o=t+i.y+i.getNoteY(this._startNote,Us.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,Us.Center)-3;break;default:return}this.paintSlideLine(s,!1,a,n,r,o)}paintSlideOut(e,t,s){let i=this.renderer,a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case w.Shift:case w.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,Ws.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,Us.Center),this._startNote.slideTarget){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,Ws.OnNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,Us.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 w.OutUp:a=e+i.x+i.getNoteX(this._startNote,Xs.Right)+2,r=t+i.y+i.getNoteY(this._startNote,Us.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,Us.Center)-3;break;case w.OutDown:a=e+i.x+i.getNoteX(this._startNote,Xs.Right)+2,r=t+i.y+i.getNoteY(this._startNote,Us.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,Us.Center)+3;break;case w.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,Xs.Right)+4,r=t+i.y+i.getNoteY(this._startNote,Us.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,Ws.PreNotes)),h=!0;break;case w.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,Xs.Right)+4,r=t+i.y+i.getNoteY(this._startNote,Us.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,Ws.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new Wn(0,0,B.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;let n=i-s,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;let 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 lh extends go{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?We.Up:lh.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?We.Up:We.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,Us.Center):this.tieDirection===We.Up?this.startNoteRenderer.getNoteY(this.startNote,Us.Top):this.startNoteRenderer.getNoteY(this.startNote,Us.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Xs.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,Xs.Left):this.endNoteRenderer.getNoteX(this.endNote,Xs.Center)}}class dh extends lh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=lh.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!==lh.getBeamDirectionForNote(e))return!1;switch(this._direction){case We.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 We.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){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,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 ch extends er{constructor(e,t){super(e,t),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;let t=this.renderer;if(e.isTieOrigin&&t.showTiedNotes&&e.tieDestination.isVisible){let t=new lh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){let t=new lh(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new lh(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(let s of this._effectSlurs)if(s.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){let t=new dh(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(let s of this._effectSlurs)if(s.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){let t=new dh(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==_.None||e.slideOutType!==w.None){let t=new hh(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new Co;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class uh extends ja{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(){let t=this._note,s=t.fret-t.beat.voice.bar.staff.transpositionPitch;if(t.harmonicType===b.Natural&&0!==t.harmonicValue&&(s=t.harmonicValue-t.beat.voice.bar.staff.transpositionPitch),t.isTieDestination)0===t.beat.index&&this.renderer.settings.notation.notationMode==e.NotationMode.GuitarPro||(t.bendType===c.Bend||t.bendType===c.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(e.NotationElement.TabNotesOnTiedBends)?this._noteString="("+(t.tieOrigin.fret-t.beat.voice.bar.staff.transpositionPitch).toString()+")":this._noteString="";else if(this._noteString=t.isDead?"x":s.toString(),t.isGhost)this._noteString="("+this._noteString+")";else if(t.harmonicType===b.Natural){let e=this._noteString.indexOf(String.fromCharCode(46));e>=0&&(this._noteString=this._noteString.substr(0,e+2)),this._noteString="<"+this._noteString+">"}if(t.isTrill)this._trillNoteString="("+(t.trillFret-t.beat.voice.bar.staff.transpositionPitch).toString()+")";else if(de.isAlmostEqualTo(t.harmonicValue,0))this._trillNoteString="";else switch(t.harmonicType){case b.Artificial:case b.Pinch:case b.Tap:case b.Semi:case b.Feedback:let e=(s+t.harmonicValue).toString(),i=e.indexOf(String.fromCharCode(46));i>=0&&(e=e.substr(0,i+2)),this._trillNoteString="<"+e+">";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;let i=this.noteStringWidth+this._trillNoteStringWidth,a=e+this.x+(this.width-i)/2,r=this.renderer.scoreRenderer.canvas.font;this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,s.fillText(this._trillNoteString,a+this.noteStringWidth+3,t+this.y),this.renderer.scoreRenderer.canvas.font=r,s.fillText(this._noteString,a,t+this.y)}buildBoundingsLookup(e,t,s){let i=new Ca;i.note=this._note,i.noteHeadBounds=new cs,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 ph extends ja{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)){let s=this.notesPerString.get(e.string),i=this.x+s.x;switch(t){case Xs.Left:break;case Xs.Center:i+=s.noteStringWidth/2;break;case Xs.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 Us.Top:case Us.TopWithStem:i-=s.height/2+2;break;case Us.Center:break;case Us.Bottom:case Us.BottomWithStem:i+=s.height/2}return i}return 0}doLayout(){let e=0;if(this.beat.deadSlapped)this._deadSlapped=new wo,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++){let 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;let s=this.renderer.resources.tablatureFont.size,i=this.getNoteY(this.minStringNote,Us.Center)+s/2,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{let i=this.renderer.resources,a=s.textBaseline;s.textBaseline=M.Middle,s.font=this._isGrace?i.graceFont:i.tablatureFont;let r=this._notes,n=this.width;for(let i of r)i.renderer=this.renderer,i.width=n,i.paint(e,t,s);s.textBaseline=a;for(const i of this.beatEffects.values())i.paint(e,t,s)}}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 gh extends Qa{constructor(e,t,s,i){super(e,t,1,To.getSymbol(i)),this._isVisibleRest=s,this._duration=i}doLayout(){this._isVisibleRest?this.width=To.getSize(this._duration):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){this._isVisibleRest&&super.paint(e,t,s)}}class mh extends ln{constructor(){super(...arguments),this.slash=null,this.noteNumbers=null,this.restGlyph=null}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(){let t=this.renderer;if(this.container.beat.isRest){let e=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),s=t.getTabY(e);const i=new gh(0,s,t.showRests,this.container.beat.duration);if(this.restGlyph=i,i.beat=this.container.beat,i.beamingHelper=this.beamingHelper,this.addGlyph(i),this.container.beat.dots>0&&t.showRests){this.addGlyph(new Do(0,0,5));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new co(0,s,1.5))}}else{let s,i=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==f.None;if(this.container.beat.slashed&&!this.container.beat.notes.some((e=>e.isTieDestination))){const e=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),a=t.getLineY(e),r=new Oo(0,a,this.container.beat.duration,i);this.slash=r,r.beat=this.container.beat,r.beamingHelper=this.beamingHelper,this.addGlyph(r),s=r.beatEffects}else{const e=new ph(0,0,i);this.noteNumbers=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;for(let e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);this.addGlyph(e),s=e.beatEffects}if(this.container.beat.hasWhammyBar){let e=new Eo(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,t=this.container.beat.tremoloSpeed,i=5;switch(t){case g.ThirtySecond:e=10;break;case g.Sixteenth:e=5;break;case g.Eighth:e=0}this.container.beat.duration<g.Half&&(i=0),s.set("tremolo",new _o(i,e,t))}if(this.container.beat.dots>0&&t.rhythmMode!==e.TabRhythmMode.Hidden){this.addGlyph(new Do(0,0,5));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new co(0,t.lineOffset*t.bar.staff.tuning.length+t.settings.notation.rhythmHeight,1.5))}}if(!this.glyphs)return;let s=0;for(let e=0,t=this.glyphs.length;e<t;e++){let t=this.glyphs[e];t.x=s,t.renderer=this.renderer,t.doLayout(),s+=t.width}this.width=s,this.computedWidth=s,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){let t=this.renderer,s=new uh(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);let a=s.y-s.height/2,r=a+s.height;this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,a,r)}}class fh extends ja{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10}paint(e,t,s){let i=this.renderer,a=t+this.x+i.getNoteY(this._beat.maxStringNote,Us.Top),r=t+this.y+i.getNoteY(this._beat.minStringNote,Us.Bottom),n=e+this.x+this.width/2|0;if(this._beat.brushType!==u.None){if(this._beat.brushType===u.BrushUp||this._beat.brushType===u.BrushDown)s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke();else if(this._beat.brushType===u.ArpeggioUp){let t=new Wn(0,0,B.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let 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===u.ArpeggioDown){let t=new Wn(0,0,B.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let 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===u.BrushUp||this._beat.brushType===u.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 yh extends hn{doLayout(){this.container.beat.brushType===u.None||this.container.beat.isRest||(this.addGlyph(new fh(this.container.beat)),this.addGlyph(new Do(0,0,4))),super.doLayout()}constructor(){super()}}class bh extends ja{constructor(e,t){super(e,t)}doLayout(){this.width=28}paint(e,t,s){let i=this.renderer.bar.staff.tuning.length,a=i<=4?D.FourStringTabClef:D.SixStringTabClef,r=i<=4?i/4.5:i/6.5;s.fillMusicFontSymbol(e+this.x+5,t+this.y,r,a,!1)}}class Sh extends Jo{get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?$a.GraceScale:1}}class _h extends rh{constructor(e,t){super(e,t),this._hasTuplets=!1,this.showTimeSignature=!1,this.showRests=!1,this.showTiedNotes=!1,t.staff.showStandardNotation||(this.showTimeSignature=!0,this.showRests=!0,this.showTiedNotes=!0)}get lineSpacing(){return _h.TabLineSpacing}get heightLineCount(){return this.bar.staff.tuning.length}get drawnLineCount(){return this.bar.staff.tuning.length}get rhythmMode(){let t=this.settings.notation.rhythmMode;return t===e.TabRhythmMode.Automatic&&(t=this.bar.staff.showStandardNotation?e.TabRhythmMode.Hidden:e.TabRhythmMode.ShowWithBars),t}getTabY(e){return super.getLineY(e)}getTabHeight(e){return super.getLineHeight(e)}collectSpaces(e){for(let t of this.bar.voices)if(this.hasVoiceContainer(t)){let s=this.getVoiceContainer(t);for(let t of s.beatGlyphs){let 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!==e.TabRhythmMode.Hidden&&(this.height+=this.settings.notation.rhythmHeight,this.bottomPadding+=this.settings.notation.rhythmHeight)}doLayout(){if(super.doLayout(),this.rhythmMode!==e.TabRhythmMode.Hidden){this._hasTuplets=!1;for(let 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){let e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new bh(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 Do(0,0,5));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new Sh(0,this.getTabY(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){let s=new ch(t,this.getVoiceContainer(e));s.preNotes=new yh,s.onNotes=new mh,this.addBeatGlyph(s)}}paint(t,s,i){super.paint(t,s,i),this.rhythmMode!==e.TabRhythmMode.Hidden&&(this.paintBeams(t,s,i),this.paintTuplets(t,s,i))}drawBeamHelperAsFlags(t){return super.drawBeamHelperAsFlags(t)||this.rhythmMode===e.TabRhythmMode.ShowWithBeams}getFlagTopY(e,t){const s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==g.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,Us.Bottom):this.height-this.settings.notation.rhythmHeight-this.tupletSize}getFlagBottomY(e,t){return this.getFlagAndBarPos()}getFlagStemSize(e,t=!1){return 0}getBarLineStart(e,t){let s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==g.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,Us.Bottom)+this.lineOffset/2:this.height-this.settings.notation.rhythmHeight-this.tupletSize}getBeamDirection(e){return We.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===f.None&&this.drawBeamHelperAsFlags(t))}paintBeamingStem(e,t,s,i,a,r){if(a<i){const e=a;a=i,i=e}r.lineWidth=sn.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}}_h.StaffId="tab",_h.TabLineSpacing=10;class wh extends Nr{get staffId(){return _h.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){let s=new _h(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 Bh extends Ka{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+Bh.Padding}paint(e,t,s){let i=this.renderer.resources;s.font=i.effectFont;let a=s.textAlign;s.textAlign=L.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+(Bh.Padding-1),s.font.size/1.6)}}Bh.Padding=4;class Th extends vn{get notationElement(){return e.NotationElement.EffectTap}get sizingMode(){return Js.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new Bh}}class kh{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"}(Jn||(Jn={}));class Nh extends kh{constructor(){super(...arguments),this.align=L.Left,this.frame=Jn.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class xh extends kh{constructor(){super(...arguments),this.chord=new Te}}class vh extends kh{}class Ph extends kh{}class Ch extends kh{constructor(){super(...arguments),this.number=0}}class Eh extends kh{constructor(){super(...arguments),this.decrescendo=!1}}class Fh extends kh{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class Dh extends kh{constructor(){super(...arguments),this.octave=1}}class Lh extends kh{}class Mh{constructor(){this.defaultClef=n.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class Ih{constructor(){this.from=0,this.to=0,this.curly=!1}}class Ah{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class Rh{constructor(){this._trackChannel=0,this._beamingMode=W.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new oe,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;let s=new ys;try{s.parse(e)}catch(e){throw new Q("Could not parse XML",e)}this.parseDom(s),this.consolidate(),this.score.finish(t)}consolidate(){for(const e of this.score.tracks){const t=this._voiceCounts.get(e.index);for(const s of e.staves){for(;s.bars.length<this.score.masterBars.length;)this.addNewBar(s);for(const e of s.bars){for(;e.voices.length<t;)e.addVoice(new Ie);for(const t of e.voices)if(0===t.beats.length){const e=new Be;e.isEmpty=!0,t.addBeat(e)}}}}Rh.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),Rh.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?p.Decrescendo:p.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){let t=e.firstElement;if(!t)throw new Q("No valid XML");if("score"!==t.localName)throw new Q('Root node of XML was not "score"');this.score=new ve,this.score.tempo=120;for(let e of t.childNodes)if(e.nodeType===rs.Element)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(let t of e.childNodes)if(t.nodeType===rs.Element)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 Me,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(let t of e.childNodes)if(t.nodeType===rs.Element&&"bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new Ih;t.from=parseInt(e.getAttribute("from")),t.to=parseInt(e.getAttribute("to")),e.attributes.has("curly")&&(t.curly="true"===e.attributes.get("curly")),this._brackets.push(t)}parseLayoutStaves(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new Mh;t.description=e.getAttribute("description");for(let s of e.childNodes)if(s.nodeType===rs.Element)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=parseInt(s.attributes.get("instr"))),s.attributes.has("volume")&&(t.volume=parseInt(s.attributes.get("volume"))),s.attributes.has("transpose")&&(t.transpose=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(let t of e.childNodes)if(t.nodeType===rs.Element&&"system"===t.localName)this.parseSystem(t)}parseSystem(e){e.attributes.has("tempo")&&0===this.score.masterBars.length&&(this.score.tempo=parseInt(e.attributes.get("tempo"))),"0"===e.getAttribute("beamGrouping")&&(this._beamingMode=W.ForceSplitToNext);for(let t of e.childNodes)if(t.nodeType===rs.Element&&"staves"===t.localName)this.parseStaves(e,t);this._isFirstSystem=!1}parseStaves(e,t){let s=this.score.masterBars.length;for(let i of t.childNodes)if(i.nodeType===rs.Element&&"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(let r of s.childNodes)if(r.nodeType===rs.Element&&"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=parseInt(t[0]),this._timeSignature.timeSignatureDenominator=parseInt(t[1]),this._timeSignature.timeSignatureCommon=!1}}}parseVoices(e,t,s,i,a){let r=0;for(let n of a.childNodes)if(n.nodeType===rs.Element&&"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){let t=new ee;if(e.bars.length>0?(t.clef=e.bars[e.bars.length-1].clef,t.clefOttava=e.bars[e.bars.length-1].clefOttava):t.clef=this._currentStaffLayout.defaultClef,e.addBar(t),e.bars.length>this.score.masterBars.length){let e=new oe;this.score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,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,n){const o=e+"_"+i;if(this._currentVoiceState&&!this._currentVoiceState.currentBarComplete&&(this._currentBar.masterBar.isAnacrusis=!0),this._voiceStates.has(o)?(this._currentVoiceState=this._voiceStates.get(o),this._currentBar=this.getOrCreateBar(t,this._currentVoiceState.currentBarIndex),this.ensureVoice(t,i)):(this._currentVoiceState=new Ah,this._currentVoiceState.currentBarIndex=a-1,this._voiceStates.set(o,this._currentVoiceState),this.newBar(t,i)),n.attributes.has("stemDir"))switch(n.attributes.get("stemDir")){case"up":this._currentVoiceState.voiceStemDir=We.Up;break;case"down":this._currentVoiceState.voiceStemDir=We.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const h=n.findChildElement("noteObjects");if(s.attributes.has("tempo")){const e=new $;e.isLinear=!0,e.type=r.Tempo,e.value=parseInt(s.attributes.get("tempo")),e.ratioPosition=this._currentVoiceState.currentPosition/this._currentVoiceState.currentBarDuration,this._currentBar.masterBar.tempoAutomations.push(e)}if(h)for(let e of h.childNodes)if(e.nodeType===rs.Element)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.masterBar.keySignature=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.masterBar.isDoubleBar=!0,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":let s=new Be;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){let 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 Ie);(!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 me;for(let i of t.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"stem":switch(i.getAttribute("dir")){case"up":e.preferredBeamDirection=We.Up;break;case"down":e.preferredBeamDirection=We.Down}break;case"articulation":switch(i.getAttribute("type")){case"staccato":s.isStaccato=!0;break;case"normalAccent":s.accentuated=a.Normal;break;case"strongAccent":s.accentuated=a.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=W.ForceMergeWithNext;break;case"divide":e.beamingMode=W.ForceSplitToNext}}}parseHeads(e,t,s){for(let i of s.childNodes)if(i.nodeType===rs.Element&&"head"===i.localName)this.parseHead(e,t,i)}parseHead(e,t,s){const i=new me,a=de.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(let e of s.childNodes)if(e.nodeType===rs.Element)switch(e.localName){case"alter":e.attributes.has("step")&&(i.tone+=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(let s of t.childNodes)if(s.nodeType===rs.Element&&"drawObj"===s.localName){const t=this.parseDrawObj(s);if(t)if(t instanceof Nh)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new et,e.fermata.type=Ge.Medium):"f"===t.text?e.dynamics=m.F:"j"===t.text&&(e.dynamics=m.MF):this._isFirstSystem&&""===this.score.title&&t.align===L.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===L.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===L.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof xh);else if(t instanceof Ph)e.vibrato=B.Slight;else if(t instanceof Eh)e.crescendo=t.decrescendo?p.Decrescendo:p.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof vh){const s=t;this._slurs.set(e,s)}else t instanceof Fh&&this.applyVolta(t)}}parseBarDrawObject(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof Fh&&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(let s of t.childNodes)if(s.nodeType===rs.Element&&"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("/")){let s=new Be;return s.beamingMode=this._beamingMode,this.parseDuration(e,s,t),s}if(1===parseInt(s)){let e=new Be;return e.beamingMode=this._beamingMode,e.duration=g.Whole,e}return ne.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return g.DoubleWhole;case"1/1":return g.Whole;case"1/2":return g.Half;case"1/4":return g.Quarter;case"1/8":return g.Eighth;case"1/16":return g.Sixteenth;case"1/32":return g.ThirtySecond;case"1/64":return g.SixtyFourth;case"1/128":return g.OneHundredTwentyEighth;default:return ne.warning("Importer","Unsupported duration"),g.Quarter}}parseDuration(e,t,s){const i=s.getAttribute("base");t.duration=this.parseDurationValue(i),s.attributes.has("dots")&&(t.dots=parseInt(s.attributes.get("dots")));const a=s.findChildElement("tuplet");if(a){t.tupletNumerator=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(let t of e.childNodes)if(t.nodeType===rs.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof Nh)switch(e.align){case L.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case L.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&this._galleryObjects.set(t.getAttribute("name"),e)}}parseDrawObj(e){let t=null,s=1;for(let i of e.childNodes)if(i.nodeType===rs.Element)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=parseInt(i.attributes.get("noteRange")))}return t&&(t.noteRange=s),t}parseTrill(e){return new Lh}parseOctaveClef(e){const t=new Dh;return e.attributes.has("octave")&&(t.octave=parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new Fh;return t.allNumbers="true"===e.attributes.get("allNumbers"),e.attributes.has("firstNumber")&&(t.firstNumber=parseInt(e.attributes.get("firstNumber"))),e.attributes.has("lastNumber")&&(t.lastNumber=parseInt(e.attributes.get("lastNumber"))),t}parseWedge(e){const t=new Eh;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new Ch;return e.attributes.has("number")&&(t.number=parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new Ph}parseSlur(e){return new vh}parseGuitar(e){const t=new xh,s=e.innerText.trim();for(let e=0;e<s.length;e++)"/"===s.charAt(e)?t.chord.strings.push(0):t.chord.strings.push(parseInt(s.charAt(e)));return t}parseText(e){const t=new Nh;switch(e.attributes.has("x")&&(t.x=parseFloat(e.attributes.get("x"))),e.attributes.has("x")&&(t.y=parseFloat(e.attributes.get("y"))),e.getAttribute("align")){case"left":t.align=L.Left;break;case"center":t.align=L.Center;break;case"right":t.align=L.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=Jn.Rectangle;break;case"ellipse":t.frame=Jn.Ellipse;break;case"circle":t.frame=Jn.Circle;break;case"none":t.frame=Jn.None}if(e.firstElement){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"font":t.fontFace=s.getAttribute("face"),s.attributes.has("weight")&&(t.weight=parseInt(s.attributes.get("weight"))),s.attributes.has("height")&&(t.height=parseInt(s.attributes.get("height")));break;case"content":t.text=s.innerText}}else t.text=e.innerText;return t}parseInfo(e){for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class Oh extends j{get name(){return"Capella"}constructor(){super()}readScore(){ne.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new Ks(this.data).read(),ne.debug(this.name,"Zip entries loaded"),e.length>0){for(let s of e)if("score.xml"===s.fileName)t=Re.toString(s.data,this.settings.importer.encoding)}else this.data.reset(),t=Re.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new Q("No valid capella file");ne.debug(this.name,"Start Parsing score.xml");try{let e=new Rh;return e.parseXml(t,this.settings),ne.debug(this.name,"score.xml parsed"),e.score}catch(e){throw new Q("Failed to parse CapXML",e)}}}class Vh{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 Hh{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=[];this._elements.forEach((t=>{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)}}function Gh(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}var Wh="function"==typeof SuppressedError?SuppressedError:function(e,t,s){var i=new Error(s);return i.name="SuppressedError",i.error=e,i.suppressed=t,i};function zh(e){function t(t){e.error=e.hasError?new Wh(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var s,i=0;return 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}()}class Uh{static enable(e,t){Uh.alphaSkia=t,Uh.initializeMusicFont(Uh.alphaSkia.AlphaSkiaTypeface.register(e))}static initializeMusicFont(e){Uh.musicFont=e}static registerFont(e,t){const s=Uh.alphaSkia.AlphaSkiaTypeface.register(e.buffer);t||(t=nt.withFamilyList([s.familyName],12,s.isItalic?Ye.Italic:Ye.Plain,s.isBold?qe.Bold:qe.Regular));for(const e of t.families)this.customTypeFaces.set(Uh.customTypefaceKey(e,t.isBold,t.isItalic),s);return t}static customTypefaceKey(e,t,s){return e.toLowerCase()+"_"+t+"_"+s}getTypeFace(){if(this._typeFaceCache!=this.font.toCssString(this._scale)){if(this._typeFaceIsSystem){const e={stack:[],error:void 0,hasError:!1};try{Gh(e,this._typeFace,!1)}catch(t){e.error=t,e.hasError=!0}finally{zh(e)}}for(const t of this.font.families){var e=Uh.customTypefaceKey(t,this.font.isBold,this.font.isItalic);Uh.customTypeFaces.has(e)?(this._typeFaceIsSystem=!1,this._typeFace=Uh.customTypeFaces.get(e)):(this._typeFaceIsSystem=!0,this._typeFace=Uh.alphaSkia.AlphaSkiaTypeface.create(t,this.font.isBold,this.font.isItalic))}this._typeFaceCache=this.font.toCssString(this._scale)}return this._typeFace}constructor(){this._color=new Ee(0,0,0,0),this._lineWidth=0,this._typeFaceCache="",this._typeFaceIsSystem=!1,this._typeFace=null,this._scale=1,this.font=new nt("Arial",10,Ye.Plain),this.textAlign=L.Left,this.textBaseline=M.Top,this._initialMeasure=!0,this._canvas=new Uh.alphaSkia.AlphaSkiaCanvas,this.color=new Ee(0,0,0,255)}destroy(){const e={stack:[],error:void 0,hasError:!1};try{Gh(e,this._canvas,!1)}catch(t){e.error=t,e.hasError=!0}finally{zh(e)}}onRenderFinished(){return null}beginRender(e,t){this._scale=this.settings.display.scale,this._canvas.beginRender(e,t,Nl.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=Uh.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=Uh.alphaSkia.AlphaSkiaTextAlign.Left;switch(this.textAlign){case L.Left:i=Uh.alphaSkia.AlphaSkiaTextAlign.Left;break;case L.Center:i=Uh.alphaSkia.AlphaSkiaTextAlign.Center;break;case L.Right:i=Uh.alphaSkia.AlphaSkiaTextAlign.Right}let a=Uh.alphaSkia.AlphaSkiaTextBaseline.Top;switch(this.textBaseline){case M.Top:a=Uh.alphaSkia.AlphaSkiaTextBaseline.Top;break;case M.Middle:a=Uh.alphaSkia.AlphaSkiaTextBaseline.Middle;break;case M.Bottom:a=Uh.alphaSkia.AlphaSkiaTextBaseline.Bottom}this._canvas.fillText(e,this.getTypeFace(),this.font.size*this._scale,t*this._scale,s*this._scale,i,a)}measureText(e){return this._initialMeasure&&(this._canvas.measureText(e,this.getTypeFace(),this.font.size*this._scale),this._initialMeasure=!1),new ce(this._canvas.measureText(e,this.getTypeFace(),this.font.size*this._scale),this.font.size*this._scale*Uh.FontSizeToLineHeight)}fillMusicFontSymbol(e,t,s,i,a){i!==D.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(let e of i)e!==D.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){this._canvas.fillText(i,Uh.musicFont,Nl.MusicFontSize*this._scale*s,e*this._scale,t*this._scale,a?Uh.alphaSkia.AlphaSkiaTextAlign.Center:Uh.alphaSkia.AlphaSkiaTextAlign.Left,Uh.alphaSkia.AlphaSkiaTextBaseline.Alphabetic)}beginRotate(e,t,s){this._canvas.beginRotate(e*this._scale,t*this._scale,s)}endRotate(){this._canvas.endRotate()}}Uh.musicFont=null,Uh.customTypeFaces=new Map,Uh.FontSizeToLineHeight=1.2;class Xh extends go{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 We.Down}static getBeamDirectionForNote(e){return We.Down}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,Us.Center)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Xs.Right)}getEndX(){return this.endNoteRenderer.getNoteX(this.endNote,Xs.Left)}}class Jh extends er{constructor(e,t){super(e,t),this._tiedNoteTie=null}createTies(e){if(e.isVisible){if(!this._tiedNoteTie&&e.isTieOrigin&&e.tieDestination.isVisible){let t=new Xh(e,e.tieDestination,!1);this._tiedNoteTie=t,this.addTie(t)}if(!this._tiedNoteTie&&e.isTieDestination){let t=new Xh(e.tieOrigin,e,!0);this._tiedNoteTie=t,this.addTie(t)}}}}class Yh extends To{constructor(e,t,s){super(e,t,s)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class qh extends ln{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.restGlyph=null}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 Xs.Left:break;case Xs.Center:e+=s.width/2;break;case Xs.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new Ca;i.note=this.container.beat.notes[0],i.noteHeadBounds=new cs,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 Us.Top:case Us.TopWithStem:e-=s.height/2+2;break;case Us.Center:break;case Us.Bottom:case Us.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(){let e=this.renderer;const t=e.getNoteLine(),s=e.getLineY(t);if(this.container.beat.deadSlapped){const e=new wo;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addGlyph(e)}else if(!this.container.beat.isEmpty)if(this.container.beat.isRest){const e=new Yh(0,s,this.container.beat.duration);this.restGlyph=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper,this.addGlyph(e),this.beamingHelper&&this.beamingHelper.applyRest(this.container.beat,0)}else{const e=this.container.beat.graceType!==f.None,t=new Oo(0,s,this.container.beat.duration,e);this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper,this.addGlyph(t)}if(this.container.beat.dots>0){this.addGlyph(new Do(0,0,5));for(let t=0;t<this.container.beat.dots;t++)this.addGlyph(new co(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 jh extends rh{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._isOnlySlash=!t.staff.showTablature&&!t.staff.showStandardNotation,this.helpers.preferredBeamDirection=We.Up}get lineSpacing(){return sn.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),this.paintTuplets(e,t,s)}doLayout(){super.doLayout();let e=!1;for(let 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){return this.getLineY(0)-Oo.NoteHeadHeight/2}getFlagBottomY(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}getBeamDirection(e){return We.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return isNaN(s)&&(s=this.getLineY(0)),s}calculateBeamYWithDirection(e,t,s){return this.getLineY(0)-this.getFlagStemSize(e.shortestDuration)}getBarLineStart(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/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 Do(0,0,5));const e=this.bar.masterBar;this.addPreBeatGlyph(new Yo(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime)))}createVoiceGlyphs(e){for(const t of e.beats){let s=new Jh(t,this.getVoiceContainer(e));s.preNotes=new hn,s.onNotes=0==e.index?new qh:new ln,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){r.lineWidth=sn.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}}jh.StaffId="slash";class Kh extends Nr{get staffId(){return jh.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 jh(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showSlash}constructor(){super()}}class Qh extends go{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 We.Up}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,Us.Top)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Xs.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,Xs.Left):this.endNoteRenderer.getNoteX(this.endNote,Xs.Center)}}class $h extends lh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=We.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 We.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 We.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){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,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 Zh extends er{constructor(e,t){super(e,t),this._effectSlurs=[]}createTies(e){if(e.isVisible){if(e.isTieOrigin&&e.tieDestination.isVisible){let t=new Qh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination){let t=new Qh(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new Qh(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(let s of this._effectSlurs)if(s.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){let t=new $h(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(let s of this._effectSlurs)if(s.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){let t=new $h(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}}}}class el extends ja{constructor(e,t,s,i){super(e,t),this._isGrace=i,this._number=s}paint(e,t,s){const i=this.renderer.resources;s.font=this._isGrace?i.numberedNotationGraceFont:i.numberedNotationFont,s.textBaseline=M.Middle,s.textAlign=L.Left,s.fillText(this._number.toString(),e+this.x,t+this.y)}doLayout(){const e=this._isGrace?$a.GraceScale:1;this.width=el.NoteHeadWidth*e,this.height=el.NoteHeadHeight*e}}el.NoteHeadHeight=17,el.NoteHeadWidth=12;class tl extends ja{doLayout(){this.width=14+tl.Padding,this.height=rl.BarSize}paint(e,t,s){const i=tl.Padding;s.fillRect(e+this.x,t+this.y,this.width-i,this.height)}}tl.Padding=3;class sl extends hn{constructor(){super(...arguments),this.isNaturalizeAccidental=!1,this.accidental=Je.None}doLayout(){if(!this.container.beat.isRest&&!this.container.beat.isEmpty){let e=new No;if(e.renderer=this.renderer,this.container.beat.notes.length>0){const t=this.container.beat.notes[0],s=t?t.accidentalMode:S.Default,i=Er.getNoteValue(t);let a=Er.computeAccidental(this.renderer.bar.masterBar.keySignature,s,i,t.hasQuarterToneOffset);if(a==Je.Natural){a=this.renderer.bar.masterBar.keySignature+7<7?Je.Sharp:Je.Flat,this.isNaturalizeAccidental=!0}if(a!==Je.None){this.accidental=a;let s=this.renderer,i=new oo(0,s.getLineY(0),a,t.beat.graceType!==f.None?$a.GraceScale*$a.GraceScale:$a.GraceScale);i.renderer=this.renderer,e.addGlyph(i),this.addGlyph(e),this.addGlyph(new Do(0,0,4))}}}super.doLayout()}}class il extends ln{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.octaveDots=0}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 Xs.Left:break;case Xs.Center:e+=s.width/2;break;case Xs.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new Ca;i.note=this.container.beat.notes[0],i.noteHeadBounds=new cs,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 Us.Top:case Us.TopWithStem:e-=s.height/2+2;break;case Us.Center:break;case Us.Bottom:case Us.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(){let 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.masterBar.keySignatureType,i=this.renderer.bar.masterBar.keySignature,a=i+7,r=(t===C.Minor?il.MinorKeySignatureOneValues:il.MajorKeySignatureOneValues)[a],n=this.container.beat.notes[0];if(n.isDead)s="X";else{let t=n.displayValue-r,o=t<0?(t%12+12)%12:t%12,h=t<0?(Math.abs(t)+12)/12|0:t/12|0;t<0&&(h*=-1),this.octaveDots=h,e.registerOctave(h);let l=(de.keySignatureIsSharp(i)||de.keySignatureIsNatural(i)?Er.FlatNoteSteps:Er.SharpNoteSteps)[o]+1;Er.AccidentalNotes[o]&&!this.container.preNotes.isNaturalizeAccidental&&(a<7?l++:l--),s=l.toString()}}if(this.container.beat.deadSlapped){const e=new wo;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addGlyph(e)}else{const e=this.container.beat.graceType!==f.None,i=new el(0,t,s,e);this.noteHeads=i,this.addGlyph(i)}if(this.container.beat.dots>0&&this.container.beat.duration>=g.Quarter){this.addGlyph(new Do(0,0,5));for(let t=0;t<this.container.beat.dots;t++){const t=new co(0,e.getLineY(0),1.5);t.renderer=this.renderer,this.addGlyph(t)}}let i=0;switch(this.container.beat.duration){case g.QuadrupleWhole:i=16;break;case g.DoubleWhole:i=8;break;case g.Whole:i=4;break;case g.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 tl(0,e.getLineY(0));t.renderer=this.renderer,this.addGlyph(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)}}il.MajorKeySignatureOneValues=[59,66,61,68,63,58,65,60,67,62,69,64,71,66,61],il.MinorKeySignatureOneValues=[71,66,73,68,63,70,65,72,67,74,69,64,71,66,73];class al extends ja{constructor(e,t,s,i){super(e,t),this._text="",this._accidental=Je.None,this._accidentalOffset=0,this._keySignature=s,this._keySignatureType=i}doLayout(){super.doLayout();const e="1 = ";let t="",s=Je.None;switch(this._keySignatureType){case C.Major:switch(this._keySignature){case P.Cb:t=" C",s=Je.Flat;break;case P.Gb:t=" G",s=Je.Flat;break;case P.Db:t=" D",s=Je.Flat;break;case P.Ab:t=" A",s=Je.Flat;break;case P.Eb:t=" E",s=Je.Flat;break;case P.Bb:t=" B",s=Je.Flat;break;case P.F:t="F";break;case P.C:t="C",s=Je.None;break;case P.G:t="G",s=Je.None;break;case P.D:t="D",s=Je.None;break;case P.A:t="A",s=Je.None;break;case P.E:t="E",s=Je.None;break;case P.B:t="B",s=Je.None;break;case P.FSharp:t=" F",s=Je.Sharp;break;case P.CSharp:t=" C",s=Je.Sharp}break;case C.Minor:switch(this._keySignature){case P.Cb:t=" a",s=Je.Flat;break;case P.Gb:t=" e",s=Je.Flat;break;case P.Db:t=" b",s=Je.Flat;break;case P.Ab:t="f",s=Je.None;break;case P.Eb:t="c",s=Je.None;break;case P.Bb:t="g",s=Je.None;break;case P.F:t="d";break;case P.C:t="a",s=Je.None;break;case P.G:t="e",s=Je.None;break;case P.D:t="b",s=Je.None;break;case P.A:t=" f",s=Je.Sharp;break;case P.E:t=" c",s=Je.Sharp;break;case P.B:t=" g",s=Je.Sharp;break;case P.FSharp:t=" d",s=Je.Sharp;break;case P.CSharp:t=" a",s=Je.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=this.renderer.resources;s.font=i.numberedNotationFont,s.textBaseline=M.Middle,s.fillText(this._text,e+this.x,t+this.y),this._accidental!=Je.None&&s.fillMusicFontSymbol(e+this.x+this._accidentalOffset,t+this.y,.7,oo.getMusicSymbol(this._accidental),!1)}}class rl extends rh{registerOctave(e){null===this.lowestOctave?(this.lowestOctave=e,this.highestOctave=e):(e<this.lowestOctave&&(this.lowestOctave=e),e>this.highestOctave&&(this.highestOctave=e))}constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.shortestDuration=g.QuadrupleWhole,this.lowestOctave=null,this.highestOctave=null,this._isOnlyNumbered=!t.staff.showSlash&&!t.staff.showTablature&&!t.staff.showStandardNotation}get lineSpacing(){return sn.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),this.paintTuplets(e,t,s,!0)}doLayout(){super.doLayout();let e=!1;for(let 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){let e=de.getIndex(this.shortestDuration)-2;if(e>0){let t=(e-1)*rl.BarSpacing+rl.BarSize,s=0;const i=this.lowestOctave;null!==i&&(s=Math.abs(i)*rl.DotSpacing+rl.DotSize),this.registerOverflowBottom(t+s)}const t=this.highestOctave;if(null!==t){const e=Math.abs(t)*rl.DotSpacing+rl.DotSize;this.registerOverflowTop(e)}}}paintFlag(e,t,s,i){this.paintBar(e,t,s,i)}paintBar(e,t,s,i){const a=this.resources;for(let n=0,o=i.beats.length;n<o;n++){let o=i.beats[n],h=rl.BarSpacing,l=rl.BarSize,d=de.getIndex(o.duration)-2,c=t+this.y,u=this.getBeatX(o,Ws.PreNotes)-this.beatGlyphsStart;var r=this.calculateBeamY(i,u);for(let t=0;t<d;t++){let a=0,d=0,p=0,g=c+t*h;n===i.beats.length-1?(a=u,d=this.getBeatX(o,Ws.PostNotes)-this.beatGlyphsStart):(a=u,d=this.getBeatX(i.beats[n+1],Ws.PreNotes)-this.beatGlyphsStart),p=g+r|0,rh.paintSingleBar(s,e+this.x+a,p,e+this.x+d,p,l)}let p=this.getBeatContainer(o).onNotes.octaveDots,g=0,m=0;p>0?(g=c+this.getLineY(0)-a.numberedNotationFont.size/1.5,m=-1*rl.DotSpacing):p<0&&(g=c+r+d*h,m=rl.DotSpacing);let f=this.getBeatX(o,Ws.OnNotes)+4-this.beatGlyphsStart;p=Math.abs(p);for(let t=0;t<p;t++)s.fillCircle(e+this.x+f,g,rl.DotSize),g+=m}}getNoteLine(){return 0}get tupletOffset(){return super.tupletOffset+this.resources.numberedNotationFont.size}getFlagTopY(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}getFlagBottomY(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}getBeamDirection(e){return We.Down}getTupletBeamDirection(e){return We.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return 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){return this.getLineY(0)-Oo.NoteHeadHeight/2}createLinePreBeatGlyphs(){this.bar.previousBar&&this.bar.masterBar.keySignature===this.bar.previousBar.masterBar.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 al(0,this.getLineY(0),this.bar.masterBar.keySignature,this.bar.masterBar.keySignatureType))}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Do(0,0,5));const e=this.bar.masterBar;this.addPreBeatGlyph(new Yo(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime)))}createPostBeatGlyphs(){this._isOnlyNumbered&&super.createPostBeatGlyphs()}createVoiceGlyphs(e){for(const t of e.beats){let s=new Zh(t,this.getVoiceContainer(e));s.preNotes=0==e.index?new sl:new hn,s.onNotes=0==e.index?new il:new ln,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){r.lineWidth=sn.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}}rl.StaffId="numbered",rl.BarSpacing=sn.BeamSpacing+sn.BeamThickness,rl.BarSize=2,rl.DotSpacing=5,rl.DotSize=2;class nl extends Nr{get staffId(){return jh.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 rl(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showNumbered}constructor(){super()}}class ol extends pn{get notationElement(){return e.NotationElement.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Js.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 Wr(0,0,"Free time",e.resources.effectFont,L.Left)}canExpand(e,t){return!0}}class hl extends Ka{constructor(){super(0,0)}doLayout(){super.doLayout(),this.height=hl.TextHeight}paint(e,t,s){const i=this.renderer,a=t+this.y,r=this.height;let n=i.bar.sustainPedals,o=0;for(;o<n.length;){let t=n[o];for(;null!=t;){const i=e+this.renderer.getRatioPositionX(t.ratioPosition);let h=0;if(t.pedalType===l.Down?(s.fillMusicFontSymbol(i,a+r,1,D.KeyboardPedalPed,!0),h=hl.TextWidth/2+hl.TextLinePadding):t.pedalType===l.Up&&(s.fillMusicFontSymbol(i,a+r,1,D.KeyboardPedalUp,!0),h=hl.StarSize/2+hl.StarLinePadding),t.nextPedalMarker)if(t.nextPedalMarker.bar===t.bar){let n=e+this.renderer.getRatioPositionX(t.nextPedalMarker.ratioPosition);switch(t.nextPedalMarker.pedalType){case l.Down:n-=hl.TextWidth/2;break;case l.Hold:break;case l.Up:n-=hl.StarSize/2}const o=i+h;n>o&&s.fillRect(o,a+r-1,n-o,1)}else{const t=e+this.x+this.width,n=i+h;s.fillRect(n,a+r-1,t-n,1)}if(0===o&&t.previousPedalMarker){const t=e+this.x,n=i-h;s.fillRect(t,a+r-1,n-t,1)}o++,null!=t.nextPedalMarker&&t.nextPedalMarker.bar!==t.bar?(t=null,o=n.length):t=t.nextPedalMarker}}}}hl.TextHeight=19,hl.TextWidth=35,hl.TextLinePadding=3,hl.StarSize=16,hl.StarLinePadding=3;class ll extends pn{get notationElement(){return e.NotationElement.EffectSustainPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Js.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&t.voice.bar.sustainPedals.length>0}createNewGlyph(e,t){return new hl}canExpand(e,t){return!0}}class dl extends pn{constructor(e,t){super(),this._type=e,this._shouldCreate=t}get notationElement(){return e.NotationElement.EffectGolpe}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Js.SingleOnBeat}shouldCreateGlyph(e,t){const s=this._shouldCreate;return t.golpe==this._type&&(!s||s(e,t))}createNewGlyph(e,t){return new Ao(0,0,!0)}canExpand(e,t){return!1}}class cl extends Qa{constructor(e){super(0,0,1,cl.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case V.Open:return D.GuitarOpenPedal;case V.Closed:return D.GuitarClosePedal}return D.None}doLayout(){this.width=11,this.height=11}paint(e,t,s){super.paint(e,t+this.height,s)}}class ul extends pn{get notationElement(){return e.NotationElement.EffectWahPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Js.SingleOnBeat}shouldCreateGlyph(e,t){return t.wahPedal!==V.None}createNewGlyph(e,t){return new cl(t.wahPedal)}canExpand(e,t){return!1}}class pl extends pn{get notationElement(){return e.NotationElement.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isBarre}get sizingMode(){return Js.GroupedOnBeat}createNewGlyph(e,t){let s="";switch(t.barreShape){case H.None:case H.Full:break;case H.Half:s+="1/2"}return s+="B "+pl.toRoman(t.barreFret),new Pn(s,!1)}static toRoman(e){let t="";if(e>0)for(var[s,i]of pl.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}}pl.RomanLetters=new Map([["L",50],["XL",40],["X",10],["IX",9],["V",5],["IV",4],["I",1]]);class gl extends Qa{constructor(e){super(0,0,1,gl.getSymbol(e)),this.center=!0}doLayout(){this.width=26,this.height=18}static getSymbol(e){switch(e){case I.InvertedTurn:return D.OrnamentTurnInverted;case I.Turn:return D.OrnamentTurn;case I.UpperMordent:return D.OrnamentShortTrill;case I.LowerMordent:return D.OrnamentMordent}return D.None}paint(e,t,s){super.paint(e,t+this.height-4,s)}}class ml extends pn{get notationElement(){return e.NotationElement.EffectNoteOrnament}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Js.SingleOnBeat}shouldCreateGlyph(e,t){return t.notes.some((e=>e.ornament!==I.None))}createNewGlyph(e,t){return new gl(t.notes.find((e=>e.ornament!=I.None)).ornament)}canExpand(e,t){return!1}}class fl extends pn{get notationElement(){return e.NotationElement.EffectRasgueado}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.hasRasgueado}get sizingMode(){return Js.GroupedOnBeat}createNewGlyph(e,t){return new Pn("rasg.")}canExpand(e,t){return!0}}class yl extends ja{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 bl extends ja{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=M.Middle,s.textAlign=L.Right,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=i,s.textBaseline=a,s.textAlign=r}}class Sl extends Ka{constructor(e,t,s){super(e,t),this._barBeginGlyphs=[],this._barEndGlyphs=[],this._directions=s}doLayout(){const e=this._directions;e.has(He.TargetSegnoSegno)&&this._barBeginGlyphs.push(new yl([D.Segno,D.Segno])),e.has(He.TargetSegno)&&this._barBeginGlyphs.push(new yl([D.Segno])),e.has(He.TargetDoubleCoda)&&this._barBeginGlyphs.push(new yl([D.Coda,D.Coda])),e.has(He.TargetCoda)&&this._barBeginGlyphs.push(new yl([D.Coda])),e.has(He.TargetFine)&&this._barEndGlyphs.push(new bl("Fine")),e.has(He.JumpDaDoubleCoda)&&this._barEndGlyphs.push(new bl("To Double Coda")),e.has(He.JumpDaCoda)&&this._barEndGlyphs.push(new bl("To Coda")),e.has(He.JumpDalSegnoSegno)&&this._barEndGlyphs.push(new bl("D.S.S.")),e.has(He.JumpDalSegnoSegnoAlCoda)&&this._barEndGlyphs.push(new bl("D.S.S. al Coda")),e.has(He.JumpDalSegnoSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new bl("D.S.S. al Double Coda")),e.has(He.JumpDalSegnoSegnoAlFine)&&this._barEndGlyphs.push(new bl("D.S.S. al Fine")),e.has(He.JumpDalSegno)&&this._barEndGlyphs.push(new bl("D.S.")),e.has(He.JumpDalSegnoAlCoda)&&this._barEndGlyphs.push(new bl("D.S. al Coda")),e.has(He.JumpDalSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new bl("D.S. al Double Coda")),e.has(He.JumpDalSegnoAlFine)&&this._barEndGlyphs.push(new bl("D.S. al Fine")),e.has(He.JumpDaCapo)&&this._barEndGlyphs.push(new bl("D.C.")),e.has(He.JumpDaCapoAlCoda)&&this._barEndGlyphs.push(new bl("D.C. al Coda")),e.has(He.JumpDaCapoAlDoubleCoda)&&this._barEndGlyphs.push(new bl("D.C. al Double Coda")),e.has(He.JumpDaCapoAlFine)&&this._barEndGlyphs.push(new bl("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 _l extends pn{get notationElement(){return e.NotationElement.EffectDirections}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Js.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 Sl(0,0,t.voice.bar.masterBar.directions)}canExpand(e,t){return!0}}class wl extends Ka{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*wl.PaddingY,this._textWidth=i.width+2*wl.PaddingX,this.height=this._textHeight+2*wl.MarginY}paint(e,t,s){const i=this._textWidth/2|0;s.strokeRect(e+this.x-i,t+this.y+wl.MarginY,this._textWidth,this._textHeight);const a=s.font,r=s.textBaseline,n=s.textAlign;s.font=this.renderer.resources.timerFont,s.textBaseline=M.Middle,s.textAlign=L.Center,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=a,s.textBaseline=r,s.textAlign=n}}wl.PaddingX=2,wl.PaddingY=2,wl.MarginY=2;class Bl extends pn{get notationElement(){return e.NotationElement.EffectBeatTimer}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return Js.SingleOnBeat}shouldCreateGlyph(e,t){return t.showTimer}createNewGlyph(e,t){return new wl(t.timer??0)}canExpand(e,t){return!0}}class Tl{constructor(e,t){this.vertical=e,this.createLayout=t}}class kl{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class Nl{static createStyleElement(e,t){let s=e.getElementById("alphaTabStyle");if(!s){if(!t)return void ne.error("AlphaTab","Font directory could not be detected, cannot create style element");s=e.createElement("style"),s.id="alphaTabStyle";let 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: ${Nl.MusicFontSize}px;\n overflow: visible !important;\n }`;s.innerHTML=i,e.getElementsByTagName("head").item(0).appendChild(s),Nl.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===Nl._globalThis){try{Nl._globalThis=globalThis}catch(e){}void 0===Nl._globalThis&&(Nl._globalThis=self),void 0===Nl._globalThis&&(Nl._globalThis=global),void 0===Nl._globalThis&&(Nl._globalThis=window),void 0===Nl._globalThis&&(Nl._globalThis=Function("return this")())}return this._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in Nl.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in Nl.globalThis}static throttle(e,t){let s=0;return()=>{Nl.globalThis.clearTimeout(s),s=Nl.globalThis.setTimeout(e,t)}}static detectScriptFile(){if(!Nl.isRunningInWorker&&Nl.globalThis.ALPHATAB_ROOT){let e=Nl.globalThis.ALPHATAB_ROOT;return e=Nl.ensureFullUrl(e),e=Nl.appendScriptName(e),e}try{const e={};if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in Nl.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="",s=Nl.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("/")){let 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(!Nl.isRunningInWorker&&Nl.globalThis.ALPHATAB_FONT)return Nl.ensureFullUrl(Nl.globalThis.ALPHATAB_FONT);const e=Nl.scriptFile;if(e){let t=e.lastIndexOf(String.fromCharCode(47));if(t>=0)return e.substr(0,t)+"/font/"}return null}static registerJQueryPlugin(){if(!Nl.isRunningInWorker&&Nl.globalThis&&"jQuery"in Nl.globalThis){let e=Nl.globalThis.jQuery,t=new Br;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:Br.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&Nl.renderEngines.has(e)?Nl.renderEngines.get(e):Nl.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&Nl.layoutEngines.has(t)?Nl.layoutEngines.get(t):Nl.layoutEngines.get(e.LayoutMode.Page)}static buildImporters(){return[new hs,new ri,new ei,new ni,new Oh,new st]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new kl(!0,(()=>new kr))),e.set("default",e.get("svg")),e.set("skia",new kl(!1,(()=>new Uh))),Nl.createPlatformSpecificRenderEngines(e),e}static enableAlphaSkia(e,t){Uh.enable(e,t)}static registerAlphaSkiaCustomFont(e,t){return Uh.registerFont(e,t)}static createPlatformSpecificRenderEngines(e){e.set("html5",new kl(!1,(()=>new Ma)))}static createDefaultRenderers(){return[new cn(Nl.StaffIdBeforeSlashAlways,[new jn,new eo,new Ln,new _l,new gn,new ol,new Kn,new Bl,new fn]),new Kh,new cn(Nl.StaffIdBeforeScoreAlways,[new Nn,new pl,new ml,new fl,new ul]),new cn(Nl.StaffIdBeforeScoreHideable,[new to,new $n,new In(!0),new so,new Gn,new io,new zn(!1),new Th,new dl(R.Finger)],((e,t)=>t.showStandardNotation)),new oh,new cn(Nl.StaffIdBeforeNumberedAlways,[new Sn,new In(!1),new wn,new dl(R.Thumb,((e,t)=>t.voice.bar.staff.showStandardNotation)),new ll]),new nl,new cn(Nl.StaffIdBeforeTabAlways,[new Dn]),new cn(Nl.StaffIdBeforeTabHideable,[new $n,new so,new Gn,new io,new zn(!0),new Un,new Tn,new Cn(b.Natural),new Cn(b.Artificial),new Cn(b.Pinch),new Cn(b.Tap),new Cn(b.Semi),new Cn(b.Feedback),new En,new mn,new xn,new An,new Vn,new Rn,new Th,new dl(R.Finger,((e,t)=>!t.voice.bar.staff.showStandardNotation))],((e,t)=>t.showTablature)),new wh,new cn(Nl.StaffIdBeforeEndAlways,[new dl(R.Thumb,((e,t)=>!t.voice.bar.staff.showStandardNotation))])]}static createDefaultStaveProfiles(){const t=new Map,s=Nl.createDefaultRenderers();t.set(e.StaveProfile.Default,s),t.set(e.StaveProfile.ScoreTab,s);const i=new Set([Nl.StaffIdBeforeSlashAlways,Nl.StaffIdBeforeScoreAlways,Nl.StaffIdBeforeNumberedAlways,Nl.StaffIdBeforeTabAlways,nh.StaffId,Nl.StaffIdBeforeEndAlways]);t.set(e.StaveProfile.Score,s.filter((e=>i.has(e.staffId))));const a=new Set([Nl.StaffIdBeforeSlashAlways,Nl.StaffIdBeforeScoreAlways,Nl.StaffIdBeforeNumberedAlways,Nl.StaffIdBeforeTabAlways,_h.StaffId,Nl.StaffIdBeforeEndAlways]);return t.set(e.StaveProfile.Tab,Nl.createDefaultRenderers().filter((e=>{if(e instanceof wh){const t=e;t.showTimeSignature=!0,t.showRests=!0,t.showTiedNotes=!0}return a.has(e.staffId)}))),t.set(e.StaveProfile.TabMixed,Nl.createDefaultRenderers().filter((e=>{if(e instanceof wh){const t=e;t.showTimeSignature=!1,t.showRests=!1,t.showTiedNotes=!1}return a.has(e.staffId)}))),t}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.LayoutMode.Page,new Tl(!0,(e=>new no(e)))),t.set(e.LayoutMode.Horizontal,new Tl(!1,(e=>new ro(e)))),t}static initializeMain(t,s){Nl.isRunningInWorker||Nl.isRunningInAudioWorklet||(Nl.webPlatform!==e.WebPlatform.Browser&&Nl.webPlatform!==e.WebPlatform.BrowserModule||(Nl.registerJQueryPlugin(),Nl.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in Nl.globalThis||(Nl.globalThis.ResizeObserver=Vh),"IntersectionObserver"in Nl.globalThis||(Nl.globalThis.IntersectionObserver=Hh),"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)})),Nl.createWebWorker=t,Nl.createAudioWorklet=s)}static get alphaTabWorker(){return this.globalThis.Worker}static get alphaTabUrl(){return this.globalThis.URL}static initializeWorker(){if(!Nl.isRunningInWorker)throw new K(e.AlphaTabErrorType.General,"Not running in worker, cannot run worker initialization");La.init(),Ba.init(),Nl.createWebWorker=t=>{throw new K(e.AlphaTabErrorType.General,"Nested workers are not supported")}}static initializeAudioWorklet(){if(!Nl.isRunningInAudioWorklet)throw new K(e.AlphaTabErrorType.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 e.WebPlatform.NodeJs}catch(e){}try{const t={};if(t&&"string"==typeof t&&!t.startsWith("file://"))return e.WebPlatform.BrowserModule}catch(e){}return e.WebPlatform.Browser}}Nl.StaffIdBeforeSlashAlways="before-slash-always",Nl.StaffIdBeforeScoreAlways="before-score-always",Nl.StaffIdBeforeScoreHideable="before-score-hideable",Nl.StaffIdBeforeNumberedAlways="before-numbered-always",Nl.StaffIdBeforeTabAlways="before-tab-always",Nl.StaffIdBeforeTabHideable="before-tab-hideable",Nl.StaffIdBeforeEndAlways="before-end-always",Nl.MusicFontSize=34,Nl.HighDpiFactor=1,Nl._globalThis=void 0,Nl.webPlatform=Nl.detectWebPlatform(),Nl.isWebPackBundled=Nl.detectWebPack(),Nl.isViteBundled=Nl.detectVite(),Nl.scriptFile=Nl.detectScriptFile(),Nl.fontDirectory=Nl.detectFontDirectory(),Nl.bravuraFontChecker=new lr(["alphaTab"]),Nl.renderEngines=Nl.createDefaultRenderEngines(),Nl.layoutEngines=Nl.createDefaultLayoutEngines(),Nl.staveProfiles=Nl.createDefaultStaveProfiles();class xl{constructor(){this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=e.LogLevel.Info,this.useWorkers=!0,this.includeNoteBounds=!1,this.scriptFile=Nl.scriptFile,this.fontDirectory=Nl.fontDirectory}}class vl{}vl.version="1.4.0",vl.date="2025-03-02T15:59:05.431Z";var Pl,Cl=Object.freeze({__proto__:null,ScoreImporter:j,ScoreLoader:nr,UnsupportedFormatError:Q});class El{init(e,t){this.data=e,this.settings=t}export(e,t=null){const s=Oe.withCapacity(1024);return this.init(s,t??new Ot),this.writeScore(e),s.toArray()}}!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"}(Pl||(Pl={}));class Fl{constructor(e,t,s=null){if(this.icon=Pl.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 Dl{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new ys;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 a.Normal:i|=8;break;case a.Heavy:i|=4;break;case a.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 B.Slight:s.addElement("Vibrato").innerText="Slight";break;case B.Wide:s.addElement("Vibrato").innerText="Wide"}if(t.isFingering){switch(t.leftHandFinger){case y.Thumb:s.addElement("LeftFingering").innerText="P";break;case y.IndexFinger:s.addElement("LeftFingering").innerText="I";break;case y.MiddleFinger:s.addElement("LeftFingering").innerText="M";break;case y.AnnularFinger:s.addElement("LeftFingering").innerText="A";break;case y.LittleFinger:s.addElement("LeftFingering").innerText="C"}switch(t.rightHandFinger){case y.Thumb:s.addElement("RightFingering").innerText="P";break;case y.IndexFinger:s.addElement("RightFingering").innerText="I";break;case y.MiddleFinger:s.addElement("RightFingering").innerText="M";break;case y.AnnularFinger:s.addElement("RightFingering").innerText="A";break;case y.LittleFinger:s.addElement("RightFingering").innerText="C"}}t.percussionArticulation>=0?s.addElement("InstrumentArticulation").innerText=t.percussionArticulation.toString():s.addElement("InstrumentArticulation").innerText="0",t.ornament!==I.None&&(s.addElement("Ornament").innerText=I[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!==b.None){switch(t.harmonicType){case b.Natural:this.writeSimplePropertyNode(s,"HarmonicType","HType","Natural");break;case b.Artificial:this.writeSimplePropertyNode(s,"HarmonicType","HType","Artificial");break;case b.Pinch:this.writeSimplePropertyNode(s,"HarmonicType","HType","Pinch");break;case b.Tap:this.writeSimplePropertyNode(s,"HarmonicType","HType","Tap");break;case b.Semi:this.writeSimplePropertyNode(s,"HarmonicType","HType","Semi");break;case b.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 _.IntoFromAbove:i|=32;break;case _.IntoFromBelow:i|=16}switch(t.slideOutType){case w.Shift:i|=1;break;case w.Legato:i|=2;break;case w.OutDown:i|=4;break;case w.OutUp:i|=8;break;case w.PickSlideDown:i|=64;break;case w.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=De.defaultSteps[a],o=De.defaultAccidentals[a]};switch(h(),i){case S.Default:break;case S.ForceNone:case S.ForceNatural:o="";break;case S.ForceSharp:o="#";break;case S.ForceDoubleSharp:"#"===o&&(s-=2,h()),o="x";break;case S.ForceFlat:"#"===o&&(s+=1,h()),o="b";break;case S.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);var s,i,a=t[0],r=t[t.length-1];switch(t.length){case 4:s=t[1],i=t[2];break;case 3:s=t[1],i=t[1];break;default:i=s=new se((a.offset+r.offset)/2,(a.value+r.value)/2)}this.writeSimplePropertyNode(e,"BendDestinationOffset","Float",this.toBendOffset(r.offset).toString()),this.writeSimplePropertyNode(e,"BendDestinationValue","Float",this.toBendValue(r.value).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset1","Float",this.toBendOffset(s.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset2","Float",this.toBendOffset(i.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleValue","Float",this.toBendValue(s.value).toString()),this.writeSimplePropertyNode(e,"BendOriginOffset","Float",this.toBendOffset(a.offset).toString()),this.writeSimplePropertyNode(e,"BendOriginValue","Float",this.toBendValue(a.value).toString())}toBendValue(e){return 25*e}toBendOffset(e){return e/se.MaxPosition*100}writeBeatNode(e,t,s){const i=e.addElement("Beat");if(i.attributes.set("id",t.id.toString()),i.addElement("Dynamic").innerText=m[t.dynamics],t.fade!==O.None&&(i.addElement("Fadding").innerText=O[t.fade]),t.isTremolo)switch(t.tremoloSpeed){case g.Eighth:i.addElement("Tremolo").innerText="1/2";break;case g.Sixteenth:i.addElement("Tremolo").innerText="1/4";break;case g.ThirtySecond:i.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&i.addElement("Chord").setCData(t.chordId),t.crescendo!==p.None&&(i.addElement("Hairpin").innerText=p[t.crescendo]),t.brushType){case u.ArpeggioUp:i.addElement("Arpeggio").innerText="Up";break;case u.ArpeggioDown:i.addElement("Arpeggio").innerText="Down"}switch(t.text&&i.addElement("FreeText").setCData(t.text),t.graceType){case f.OnBeat:case f.BeforeBeat:i.addElement("GraceNotes").innerText=f[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 We.Up:i.addElement("TransposedPitchStemOrientation").innerText="Upward",i.addElement("UserTransposedPitchStemOrientation").innerText="Upward";break;case We.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!==R.None&&(i.addElement("Golpe").innerText=R[t.golpe]),t.wahPedal!==V.None&&(i.addElement("Wah").innerText=V[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 W.ForceSplitToNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","2");break;case W.ForceMergeWithNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","1");break;case W.ForceSplitOnSecondaryToNext:this.writeSimpleXPropertyNode(s,"1124204552","Int","1")}}writeBeatProperties(e,t){const s=e.addElement("Properties");switch(t.brushType){case u.BrushUp:this.writeSimplePropertyNode(s,"Brush","Direction","Up");break;case u.BrushDown:this.writeSimplePropertyNode(s,"Brush","Direction","Down")}switch(t.pickStroke){case F.Up:this.writeSimplePropertyNode(s,"PickStroke","Direction","Up");break;case F.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 B.Wide:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Wide");break;case B.Slight:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Slight")}if(t.isBarre)switch(this.writeSimplePropertyNode(s,"BarreFret","Fret",t.barreFret.toString()),t.barreShape){case H.Full:this.writeSimplePropertyNode(s,"BarreString","String","0");break;case H.Half:this.writeSimplePropertyNode(s,"BarreString","String","1")}if(t.rasgueado!=G.None){let e="";switch(t.rasgueado){case G.Ii:e="ii_1";break;case G.Mi:e="mi_1";break;case G.MiiTriplet:e="mii_1";break;case G.MiiAnapaest:e="mii_2";break;case G.PmpTriplet:e="pmp_1";break;case G.PmpAnapaest:e="pmp_2";break;case G.PeiTriplet:e="pei_1";break;case G.PeiAnapaest:e="pei_2";break;case G.PaiTriplet:e="pai_1";break;case G.PaiAnapaest:e="pai_2";break;case G.AmiTriplet:e="ami_1";break;case G.AmiAnapaest:e="ami_2";break;case G.Ppp:e="ppp_1";break;case G.Amii:e="amii_1";break;case G.Amip:e="amip_1";break;case G.Eami:e="eami_1";break;case G.Eamii:e="eamii_1";break;case G.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 g.QuadrupleWhole:r="Long";break;case g.DoubleWhole:r="DoubleWhole";break;case g.Whole:r="Whole";break;case g.Half:r="Half";break;case g.Quarter:r="Quarter";break;case g.Eighth:r="Eighth";break;case g.Sixteenth:r="16th";break;case g.ThirtySecond:r="32nd";break;case g.SixtyFourth:r="64th";break;case g.OneHundredTwentyEighth:r="128th";break;case g.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");var i,a,r=t[0],n=t[t.length-1];switch(t.length){case 4:i=t[1],a=t[2];break;case 3:i=t[1],a=t[1];break;default:a=i=new se((r.offset+n.offset)/2,(r.value+n.value)/2)}s.attributes.set("destinationOffset",this.toBendOffset(n.offset).toString()),s.attributes.set("destinationValue",this.toBendValue(n.value).toString()),s.attributes.set("middleOffset1",this.toBendOffset(i.offset).toString()),s.attributes.set("middleOffset2",this.toBendOffset(a.offset).toString()),s.attributes.set("middleValue",this.toBendValue(i.value).toString()),s.attributes.set("originOffset",this.toBendOffset(r.offset).toString()),s.attributes.set("originValue",this.toBendValue(r.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=q.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",s.addElement("UseOneChannelPerString"),s.addElement("IconId").innerText=Dl.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?Dl.DrumKitProgramInfo.icon:Dl.MidiProgramInfoLookup.has(e.program)?Dl.MidiProgramInfoLookup.get(e.program).icon:Pl.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 d=t.addElement("Automation");d.addElement("Type").innerText="Sound",d.addElement("Linear").innerText="false",d.addElement("Bar").innerText=r.toString(),d.addElement("Position").innerText=o.toString(),d.addElement("Visible").innerText="true",d.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}`,n="Factory";let o=!1;for(const h of t.staves)for(const l of h.bars)for(const h of l.voices)for(const d of h.beats){const h=d.getAutomation(r.Instrument),c=0===l.index&&0===d.index;if(h){const r=c?e:`ProgramChange_${d.id}`,u=c?a:`Midi/${h.value}`,p=c?n:"User";c||o||(this.writeSoundAndAutomation(s,i,e,a,n,t.staves[0].bars[0].index,t.playbackInfo.program),o=!0),this.writeSoundAndAutomation(s,i,r,u,p,l.index,h.value,h.ratioPosition),c&&(o=!0)}}}for(const e of t.staves)for(const t of e.bars)for(const e of t.sustainPedals)if(e.pedalType!==l.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 l.Down:s.addElement("Value").innerText="0 1";break;case l.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++){let 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=[y.LittleFinger,y.AnnularFinger,y.MiddleFinger,y.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():y.IndexFinger;for(const e of i){const i=o.addElement("Position");switch(a){case y.LittleFinger:i.attributes.set("finger","Pinky");break;case y.AnnularFinger:i.attributes.set("finger","Ring");break;case y.MiddleFinger:i.attributes.set("finger","Middle");break;case y.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 d=i.addElement("Property");d.attributes.set("name","ShowFingering"),d.attributes.set("type","bool"),d.attributes.set("value",t.showFingering?"true":"false");const c=i.addElement("Chord"),u=c.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=c.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=c.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const m=c.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");let 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(pe.instrumentArticulations.values());s.addElement("Name").innerText=Dl.DrumKitProgramInfo.instrumentSetName,s.addElement("Type").innerText=Dl.DrumKitProgramInfo.instrumentSetType;let i="",r=new ps,n=new Map;const o=s.addElement("Elements");for(const t of e){{var a=o.addElement("Element");let e=t.elementType;if(n.has(e)){const t=n.get(e);e+=" "+t,n.set(e,t+1)}else n.set(e,1);i=e,a.addElement("Name").innerText=e,a.addElement("Type").innerText=t.elementType,r=a.addElement("Articulations")}const e=r.addElement("Articulation");switch(e.addElement("Name").innerText=i+" "+r.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 M.Top:e.addElement("TechniquePlacement").innerText="below";break;case M.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case M.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=Dl.MidiProgramInfoLookup.has(t.playbackInfo.program)?Dl.MidiProgramInfoLookup.get(t.playbackInfo.program):Dl.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===D.None)return"";let t=D[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");let 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!==E.NoTripletFeel&&(s.addElement("TripletFeel").innerText=E[t.tripletFeel]),t.directions&&t.directions.size>0){const e=s.addElement("Directions");for(const s of t.directions)switch(s){case He.TargetFine:e.addElement("Target").innerText="Fine";break;case He.TargetSegno:e.addElement("Target").innerText="Segno";break;case He.TargetSegnoSegno:e.addElement("Target").innerText="SegnoSegno";break;case He.TargetCoda:e.addElement("Target").innerText="Coda";break;case He.TargetDoubleCoda:e.addElement("Target").innerText="DoubleCoda";break;case He.JumpDaCapo:e.addElement("Jump").innerText="DaCapo";break;case He.JumpDaCapoAlCoda:e.addElement("Jump").innerText="DaCapoAlCoda";break;case He.JumpDaCapoAlDoubleCoda:e.addElement("Jump").innerText="DaCapoAlDoubleCoda";break;case He.JumpDaCapoAlFine:e.addElement("Jump").innerText="DaCapoAlFine";break;case He.JumpDalSegno:e.addElement("Jump").innerText="DaSegno";break;case He.JumpDalSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoAlCoda";break;case He.JumpDalSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoAlDoubleCoda";break;case He.JumpDalSegnoAlFine:e.addElement("Jump").innerText="DaSegnoAlFine";break;case He.JumpDalSegnoSegno:e.addElement("Jump").innerText="DaSegnoSegno";break;case He.JumpDalSegnoSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlCoda";break;case He.JumpDalSegnoSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlDoubleCoda";break;case He.JumpDalSegnoSegnoAlFine:e.addElement("Jump").innerText="DaSegnoSegnoAlFine";break;case He.JumpDaCoda:e.addElement("Jump").innerText="DaCoda";break;case He.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/te.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=Ge[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(" ")}}Dl.MidiProgramInfoLookup=new Map([[0,new Fl(Pl.Piano,"Acoustic Piano")],[1,new Fl(Pl.Piano,"Acoustic Piano")],[2,new Fl(Pl.Piano,"Electric Piano")],[3,new Fl(Pl.Piano,"Acoustic Piano")],[4,new Fl(Pl.Piano,"Electric Piano")],[5,new Fl(Pl.Piano,"Electric Piano")],[6,new Fl(Pl.Piano,"Harpsichord")],[7,new Fl(Pl.Piano,"Harpsichord")],[8,new Fl(Pl.PitchedIdiophone,"Celesta")],[9,new Fl(Pl.PitchedIdiophone,"Vibraphone")],[10,new Fl(Pl.PitchedIdiophone,"Vibraphone")],[11,new Fl(Pl.PitchedIdiophone,"Vibraphone")],[12,new Fl(Pl.PitchedIdiophone,"Xylophone")],[13,new Fl(Pl.PitchedIdiophone,"Xylophone")],[14,new Fl(Pl.PitchedIdiophone,"Vibraphone")],[15,new Fl(Pl.Banjo,"Banjo")],[16,new Fl(Pl.Piano,"Electric Organ")],[17,new Fl(Pl.Piano,"Electric Organ")],[18,new Fl(Pl.Piano,"Electric Organ")],[19,new Fl(Pl.Piano,"Electric Organ")],[20,new Fl(Pl.Piano,"Electric Organ")],[21,new Fl(Pl.Piano,"Electric Organ")],[22,new Fl(Pl.Woodwind,"Recorder")],[23,new Fl(Pl.Piano,"Electric Organ")],[24,new Fl(Pl.ClassicalGuitar,"Nylon Guitar")],[25,new Fl(Pl.SteelGuitar,"Steel Guitar")],[26,new Fl(Pl.SteelGuitar,"Electric Guitar")],[27,new Fl(Pl.ElectricGuitar,"Electric Guitar")],[28,new Fl(Pl.ElectricGuitar,"Electric Guitar")],[29,new Fl(Pl.ElectricGuitar,"Electric Guitar")],[30,new Fl(Pl.SteelGuitar,"Electric Guitar")],[31,new Fl(Pl.SteelGuitar,"Electric Guitar")],[32,new Fl(Pl.Bass,"Acoustic Bass")],[33,new Fl(Pl.Bass,"Electric Bass")],[34,new Fl(Pl.Bass,"Electric Bass")],[35,new Fl(Pl.Bass,"Acoustic Bass")],[36,new Fl(Pl.Bass,"Electric Bass")],[37,new Fl(Pl.Bass,"Electric Bass")],[38,new Fl(Pl.Synth,"Synth Bass")],[39,new Fl(Pl.Synth,"Synth Bass")],[40,new Fl(Pl.Strings,"Violin")],[41,new Fl(Pl.Strings,"Viola")],[42,new Fl(Pl.Strings,"Cello")],[43,new Fl(Pl.Strings,"Contrabass")],[44,new Fl(Pl.Strings,"Violin")],[45,new Fl(Pl.Strings,"Violin")],[46,new Fl(Pl.Piano,"Harp")],[47,new Fl(Pl.Membraphone,"Timpani")],[48,new Fl(Pl.Strings,"Violin")],[49,new Fl(Pl.Strings,"Violin")],[50,new Fl(Pl.Strings,"Violin")],[51,new Fl(Pl.Strings,"Violin")],[52,new Fl(Pl.Vocal,"Voice")],[53,new Fl(Pl.Vocal,"Voice")],[54,new Fl(Pl.Vocal,"Voice")],[55,new Fl(Pl.Synth,"Pad Synthesizer")],[56,new Fl(Pl.Brass,"Trumpet")],[57,new Fl(Pl.Brass,"Trombone")],[58,new Fl(Pl.Brass,"Tuba")],[59,new Fl(Pl.Brass,"Trumpet")],[60,new Fl(Pl.Brass,"French Horn")],[61,new Fl(Pl.Brass,"Trumpet")],[62,new Fl(Pl.Brass,"Trumpet")],[63,new Fl(Pl.Brass,"Trumpet")],[64,new Fl(Pl.Reed,"Saxophone")],[65,new Fl(Pl.Reed,"Saxophone")],[66,new Fl(Pl.Reed,"Saxophone")],[67,new Fl(Pl.Reed,"Saxophone")],[68,new Fl(Pl.Reed,"Oboe")],[69,new Fl(Pl.Reed,"English Horn")],[70,new Fl(Pl.Reed,"Bassoon")],[71,new Fl(Pl.Reed,"Clarinet")],[72,new Fl(Pl.Reed,"Piccolo")],[73,new Fl(Pl.Woodwind,"Flute")],[74,new Fl(Pl.Woodwind,"Recorder")],[75,new Fl(Pl.Woodwind,"Flute")],[76,new Fl(Pl.Woodwind,"Recorder")],[77,new Fl(Pl.Woodwind,"Flute")],[78,new Fl(Pl.Woodwind,"Recorder")],[79,new Fl(Pl.Woodwind,"Flute")],[80,new Fl(Pl.Synth,"Lead Synthesizer")],[81,new Fl(Pl.Synth,"Lead Synthesizer")],[82,new Fl(Pl.Synth,"Lead Synthesizer")],[83,new Fl(Pl.Synth,"Lead Synthesizer")],[84,new Fl(Pl.Synth,"Lead Synthesizer")],[85,new Fl(Pl.Synth,"Lead Synthesizer")],[86,new Fl(Pl.Synth,"Lead Synthesizer")],[87,new Fl(Pl.Synth,"Lead Synthesizer")],[88,new Fl(Pl.Synth,"Pad Synthesizer")],[89,new Fl(Pl.Synth,"Pad Synthesizer")],[90,new Fl(Pl.Synth,"Pad Synthesizer")],[91,new Fl(Pl.Synth,"Pad Synthesizer")],[92,new Fl(Pl.Synth,"Pad Synthesizer")],[93,new Fl(Pl.Synth,"Pad Synthesizer")],[94,new Fl(Pl.Synth,"Pad Synthesizer")],[95,new Fl(Pl.Synth,"Pad Synthesizer")],[96,new Fl(Pl.Fx,"Pad Synthesizer")],[97,new Fl(Pl.Fx,"Pad Synthesizer")],[98,new Fl(Pl.Fx,"Pad Synthesizer")],[99,new Fl(Pl.Fx,"Pad Synthesizer")],[100,new Fl(Pl.Fx,"Lead Synthesizer")],[101,new Fl(Pl.Fx,"Lead Synthesizer")],[102,new Fl(Pl.Fx,"Lead Synthesizer")],[103,new Fl(Pl.Fx,"Trumpet")],[104,new Fl(Pl.ElectricGuitar,"Banjo")],[105,new Fl(Pl.Banjo,"Banjo")],[106,new Fl(Pl.Ukulele,"Ukulele")],[107,new Fl(Pl.Banjo,"Banjo")],[108,new Fl(Pl.PitchedIdiophone,"Xylophone")],[109,new Fl(Pl.Reed,"Bassoon")],[110,new Fl(Pl.Strings,"Violin")],[111,new Fl(Pl.Woodwind,"Flute")],[112,new Fl(Pl.PitchedIdiophone,"Xylophone")],[113,new Fl(Pl.Idiophone,"Celesta")],[114,new Fl(Pl.PitchedIdiophone,"Vibraphone")],[115,new Fl(Pl.Idiophone,"Xylophone")],[116,new Fl(Pl.Membraphone,"Xylophone")],[117,new Fl(Pl.Membraphone,"Xylophone")],[118,new Fl(Pl.Membraphone,"Xylophone")],[119,new Fl(Pl.Idiophone,"Celesta")],[120,new Fl(Pl.Fx,"Steel Guitar")],[121,new Fl(Pl.Fx,"Recorder")],[122,new Fl(Pl.Fx,"Recorder")],[123,new Fl(Pl.Fx,"Recorder")],[124,new Fl(Pl.Fx,"Recorder")],[125,new Fl(Pl.Fx,"Recorder")],[126,new Fl(Pl.Fx,"Recorder")],[127,new Fl(Pl.Fx,"Timpani")]]),Dl.DrumKitProgramInfo=new Fl(Pl.PercussionKit,"Drums","drumKit");class Ll{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=Ll.CrcInit,this.reset()}update(e,t,s){for(let i=0;i<s;i++)this._checkValue=Ll.Crc32Lookup[255&(this._checkValue^e[t+i])]^this._checkValue>>>8}reset(){this._checkValue=Ll.CrcInit}}Ll.Crc32Lookup=Ll.buildCrc32Lookup(),Ll.CrcInit=4294967295;class Ml{}Ml.MAX_WBITS=15,Ml.WSIZE=1<<Ml.MAX_WBITS,Ml.WMASK=Ml.WSIZE-1,Ml.MIN_MATCH=3,Ml.MAX_MATCH=258,Ml.DEFAULT_MEM_LEVEL=8,Ml.PENDING_BUF_SIZE=1<<Ml.DEFAULT_MEM_LEVEL+8,Ml.HASH_BITS=Ml.DEFAULT_MEM_LEVEL+7,Ml.HASH_SIZE=1<<Ml.HASH_BITS,Ml.HASH_SHIFT=(Ml.HASH_BITS+Ml.MIN_MATCH-1)/Ml.MIN_MATCH,Ml.HASH_MASK=Ml.HASH_SIZE-1,Ml.MIN_LOOKAHEAD=Ml.MAX_MATCH+Ml.MIN_MATCH+1,Ml.MAX_DIST=Ml.WSIZE-Ml.MIN_LOOKAHEAD;class Il{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(){let e=this.freqs.length,t=new Int32Array(e),s=0,i=0;for(let a=0;a<e;a++){let e=this.freqs[a];if(0!==e){let r=s++;for(;r>0;){let 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;){let e=i<2?++i:0;t[s++]=e}this.numCodes=Math.max(i+1,this.minNumCodes);let a=s,r=new Int32Array(4*s-2),n=new Int32Array(2*s-1),o=a;for(let e=0;e<s;e++){let s=t[e];r[2*e]=s,r[2*e+1]=-1,n[e]=this.freqs[s]<<8,t[e]=e}do{let e=t[0],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;let d=t[0];i=o++,r[2*i]=e,r[2*i+1]=d;let c=Math.min(255&n[e],255&n[d]);for(l=n[e]+n[d]-c+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);let t=Math.floor(e.length/2),s=Math.floor((t+1)/2),i=0;for(let e=0;e<this.maxLength;e++)this.bitLengthCounts[e]=0;let 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{let 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;){let 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;let 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[Il.Repeat3To6]++:i<=10?e.freqs[Il.Repeat3To10]++:e.freqs[Il.Repeat11To138]++}}setStaticCodes(e,t){this.codes=e,this.length=t}buildCodes(){let e=new Int32Array(this.maxLength),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++){let s=this.length[t];s>0&&(this.codes[t]=Al.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;let 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(Il.Repeat3To6),this.huffman.pending.writeBits(i-3,2)):i<=10?(e.writeSymbol(Il.Repeat3To10),this.huffman.pending.writeBits(i-3,3)):(e.writeSymbol(Il.Repeat11To138),this.huffman.pending.writeBits(i-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}Il.Repeat3To6=16,Il.Repeat3To10=17,Il.Repeat11To138=18;class Al{static staticInit(){let e=0;for(;e<144;)Al.staticLCodes[e]=Al.bitReverse(48+e<<8),Al.staticLLength[e++]=8;for(;e<256;)Al.staticLCodes[e]=Al.bitReverse(256+e<<7),Al.staticLLength[e++]=9;for(;e<280;)Al.staticLCodes[e]=Al.bitReverse(-256+e<<9),Al.staticLLength[e++]=7;for(;e<Al.LITERAL_NUM;)Al.staticLCodes[e]=Al.bitReverse(-88+e<<8),Al.staticLLength[e++]=8;for(e=0;e<Al.DIST_NUM;e++)Al.staticDCodes[e]=Al.bitReverse(e<<11),Al.staticDLength[e]=5}static bitReverse(e){return Al.bit4Reverse[15&e]<<12|Al.bit4Reverse[e>>4&15]<<8|Al.bit4Reverse[e>>8&15]<<4|Al.bit4Reverse[e>>12]}constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new Il(this,Al.LITERAL_NUM,257,15),this.distTree=new Il(this,Al.DIST_NUM,1,15),this.blTree=new Il(this,Al.BITLEN_NUM,4,7),this.d_buf=new Int16Array(Al.BUFSIZE),this.l_buf=new Uint8Array(Al.BUFSIZE)}isFull(){return this.last_lit>=Al.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((Al.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[Al.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[Al.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<Al.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*Al.staticLLength[e];for(let e=0;e<Al.DIST_NUM;e++)n+=this.distTree.freqs[e]*Al.staticDLength[e];r>=n&&(r=n),t>=0&&s+4<r>>3?this.flushStoredBlock(e,t,s,i):r==n?(this.pending.writeBits((Al.STATIC_TREES<<1)+(i?1:0),3),this.literalTree.setStaticCodes(Al.staticLCodes,Al.staticLLength),this.distTree.setStaticCodes(Al.staticDCodes,Al.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((Al.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[Al.BL_ORDER[t]],3);this.literalTree.writeTree(this.blTree),this.distTree.writeTree(this.blTree)}compressBlock(){for(let e=0;e<this.last_lit;e++){let t=255&this.l_buf[e],s=this.d_buf[e];if(0!=s--){let e=Al.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);let a=Al.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(Al.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;let s=Al.Lcode(t-3);this.literalTree.freqs[s]++,s>=265&&s<285&&(this.extra_bits+=Math.floor((s-261)/4));let i=Al.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}}Al.BUFSIZE=1<<Ml.DEFAULT_MEM_LEVEL+6,Al.LITERAL_NUM=286,Al.STORED_BLOCK=0,Al.STATIC_TREES=1,Al.DYN_TREES=2,Al.DIST_NUM=30,Al.staticLCodes=new Int16Array(Al.LITERAL_NUM),Al.staticLLength=new Uint8Array(Al.LITERAL_NUM),Al.staticDCodes=new Int16Array(Al.DIST_NUM),Al.staticDLength=new Uint8Array(Al.DIST_NUM),Al.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Al.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),Al.BITLEN_NUM=19,Al.EOF_SYMBOL=256,Al.staticInit();class Rl{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 Al(e),this.inputCrc=new Ll,this.window=new Uint8Array(2*Ml.WSIZE),this.head=new Int16Array(Ml.HASH_SIZE),this.prev=new Int16Array(Ml.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=Ml.MIN_MATCH-1;for(let e=0;e<Ml.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<Ml.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<Ml.HASH_SHIFT^this.window[this.strstart+1]}needsInput(){return this.inputEnd==this.inputOff}setInput(e,t,s){let i=t+s;this.inputBuf=e,this.inputOff=t,this.inputEnd=i}deflate(e,t){let s;do{this.fillWindow();let i=e&&this.inputOff==this.inputEnd;s=this.deflateSlow(i,t)}while(this.pending.isFlushed&&s);return s}deflateSlow(e,t){if(this.lookahead<Ml.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=Ml.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*Ml.WSIZE-Ml.MIN_LOOKAHEAD&&this.slideWindow();let e=this.matchStart,s=this.matchLen;if(this.lookahead>=Ml.MIN_MATCH){let e=this.insertString();0!=e&&this.strstart-e<=Ml.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen==Ml.MIN_MATCH&&this.strstart-this.matchStart>Rl.TooFar&&(this.matchLen=Ml.MIN_MATCH-1)}if(s>=Ml.MIN_MATCH&&this.matchLen<=s){this.huffman.tallyDist(this.strstart-1-e,s),s-=2;do{this.strstart++,this.lookahead--,this.lookahead>=Ml.MIN_MATCH&&this.insertString()}while(--s>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=Ml.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--;let 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,i=s+Math.min(Ml.MAX_MATCH,this.lookahead)-1,a=Math.max(s-Ml.MAX_DIST,0),r=this.window,n=this.prev,o=this.maxChain,h=Math.min(this.niceLength,this.lookahead);if(this.matchLen=Math.max(this.matchLen,Ml.MIN_MATCH-1),s+this.matchLen>i)return!1;let l=r[s+this.matchLen-1],d=r[s+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,s=this.strstart,r[t+this.matchLen]==d&&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],d=r[s]}e=65535&n[e&Ml.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=Ml.MIN_MATCH}insertString(){let e,t=(this.insertHashIndex<<Ml.HASH_SHIFT^this.window[this.strstart+(Ml.MIN_MATCH-1)])&Ml.HASH_MASK;return e=this.head[t],this.prev[this.strstart&Ml.WMASK]=e,this.head[t]=this.strstart,this.insertHashIndex=t,65535&e}fillWindow(){if(this.strstart>=Ml.WSIZE+Ml.MAX_DIST&&this.slideWindow(),this.lookahead<Ml.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*Ml.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>=Ml.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(Ml.WSIZE,Ml.WSIZE+Ml.WSIZE),0),this.matchStart-=Ml.WSIZE,this.strstart-=Ml.WSIZE,this.blockStart-=Ml.WSIZE;for(let e=0;e<Ml.HASH_SIZE;++e){let t=65535&this.head[e];this.head[e]=t>=Ml.WSIZE?t-Ml.WSIZE:0}for(let e=0;e<Ml.WSIZE;e++){let t=65535&this.prev[e];this.prev[e]=t>=Ml.WSIZE?t-Ml.WSIZE:0}}}Rl.TooFar=4096;class Ol{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 Vl{get inputCrc(){return this._engine.inputCrc.value}constructor(){this._state=0,this._pending=new Ol(Ml.PENDING_BUF_SIZE),this._engine=new Rl(this._pending),this.reset()}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state==Vl.FinishedState&&this._pending.isFlushed}reset(){this._state=Vl.BusyState,this._pending.reset(),this._engine.reset()}setInput(e,t,s){this._engine.setInput(e,t,s)}deflate(e,t,s){let i=s;for(;;){let a=this._pending.flush(e,t,s);if(t+=a,0==(s-=a)||this._state==Vl.FinishedState)break;if(!this._engine.deflate(!!(this._state&Vl.IsFlushing),!!(this._state&Vl.IsFinishing)))switch(this._state){case Vl.BusyState:return i-s;case Vl.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=Vl.BusyState;break;case Vl.FinishingState:this._pending.alignToByte(),this._state=Vl.FinishedState}}return i-s}finish(){this._state|=Vl.IsFlushing|Vl.IsFinishing}}Vl.IsFlushing=4,Vl.IsFinishing=8,Vl.BusyState=16,Vl.FlushingState=20,Vl.FinishingState=28,Vl.FinishedState=30;class Hl{constructor(e,t,s,i,a){this.entry=e,this.crc32=t,this.localHeaderOffset=s,this.compressionMode=i,this.compressedSize=a}}class Gl{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new Vl,this._data=e}writeEntry(e){const t=js.CompressionMethodDeflate,s=Oe.empty(),i=this.compress(s,e.data,t),a=s.toArray(),r=new Hl(e,i,this._data.bytesWritten,t,s.length);this._centralDirectoryHeaders.push(r),Re.writeInt32LE(this._data,js.LocalFileHeaderSignature),Re.writeUInt16LE(this._data,10),Re.writeUInt16LE(this._data,2048),Re.writeUInt16LE(this._data,t),Re.writeInt16LE(this._data,0),Re.writeInt16LE(this._data,0),Re.writeInt32LE(this._data,i),Re.writeInt32LE(this._data,a.length),Re.writeInt32LE(this._data,e.data.length),Re.writeInt16LE(this._data,e.fullName.length),Re.writeInt16LE(this._data,0);const n=Re.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,s){if(s!=js.CompressionMethodDeflate){const s=new Ll;return s.update(t,0,t.length),e.write(t,0,t.length),s.value}{let s=new Uint8Array(512);for(this._deflater.reset(),this._deflater.setInput(t,0,t.length);!this._deflater.isNeedingInput;){const t=this._deflater.deflate(s,0,s.length);if(t<=0)break;e.write(s,0,t)}for(this._deflater.finish();!this._deflater.isFinished;){const t=this._deflater.deflate(s,0,s.length);if(t<=0)break;e.write(s,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){Re.writeInt32LE(this._data,js.EndOfCentralDirSignature),Re.writeInt16LE(this._data,0),Re.writeInt16LE(this._data,0),Re.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Re.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Re.writeInt32LE(this._data,t-e),Re.writeInt32LE(this._data,e),Re.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){Re.writeInt32LE(this._data,js.CentralFileHeaderSignature),Re.writeUInt16LE(this._data,10),Re.writeUInt16LE(this._data,10),Re.writeUInt16LE(this._data,2048),Re.writeUInt16LE(this._data,e.compressionMode),Re.writeInt16LE(this._data,0),Re.writeInt16LE(this._data,0),Re.writeInt32LE(this._data,e.crc32),Re.writeInt32LE(this._data,e.compressedSize),Re.writeInt32LE(this._data,e.entry.data.length),Re.writeInt16LE(this._data,e.entry.fullName.length),Re.writeInt16LE(this._data,0),Re.writeInt16LE(this._data,0),Re.writeInt16LE(this._data,0),Re.writeInt16LE(this._data,0),Re.writeInt32LE(this._data,0),Re.writeInt32LE(this._data,e.localHeaderOffset);const t=Re.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}var Wl=Object.freeze({__proto__:null,Gp7Exporter:class extends El{get name(){return"Guitar Pro 7"}constructor(){super()}writeScore(e){ne.debug(this.name,"Writing data entries");const t=(new Dl).writeXml(e),s=us.writeForScore(e),i=Ts.writeForScore(e),a=Zs.writeForScore(e);ne.debug(this.name,"Writing ZIP entries");let r=new Gl(this.data);r.writeEntry(new js("VERSION",Re.stringToBytes("7.0"))),r.writeEntry(new js("Content/",new Uint8Array(0))),r.writeEntry(new js("Content/BinaryStylesheet",s)),r.writeEntry(new js("Content/PartConfiguration",i)),r.writeEntry(new js("Content/LayoutConfiguration",a)),r.writeEntry(new js("Content/score.gpif",Re.stringToBytes(t))),r.end()}},ScoreExporter:El}),zl=Object.freeze({__proto__:null,AlphaSynthMidiFileHandler:Ia,AlphaTabMetronomeEvent:ut,AlphaTabRestEvent:pt,BeatTickLookup:Va,ControlChangeEvent:yt,get ControllerType(){return Os},EndOfTrackEvent:Bt,MasterBarTickLookup:Ga,MidiEvent:lt,get MidiEventType(){return Ke},MidiFile:ht,get MidiFileFormat(){return je},MidiFileGenerator:Ya,MidiTickLookup:za,MidiTickLookupFindBeatResult:Wa,NoteBendEvent:wt,NoteEvent:gt,NoteOffEvent:ft,NoteOnEvent:mt,PitchBendEvent:_t,ProgramChangeEvent:bt,TempoChangeEvent:St,TimeSignatureEvent:dt}),Ul=Object.freeze({__proto__:null,BarBounds:xa,BeatBounds:va,Bounds:cs,BoundsLookup:Fa,MasterBarBounds:Pa,NoteBounds:Ca,RenderFinishedEventArgs:Na,ScoreRenderer:Da,StaffSystemBounds:Ea}),Xl=Object.freeze({__proto__:null,ActiveBeatsChangedEventArgs:sr,AlphaSynth:_a,AlphaSynthAudioWorkletOutput:br,AlphaSynthScriptProcessorOutput:ur,AlphaSynthWebAudioOutputBase:cr,AlphaSynthWebWorkerApi:gr,CircularSampleBuffer:dr,MidiEventsPlayedEventArgs:ba,PlaybackRange:qa,PlaybackRangeChangedEventArgs:Sa,get PlayerState(){return Fs},PlayerStateChangedEventArgs:ci,PositionChangedEventArgs:ui}),Jl=Object.freeze({__proto__:null});Nl.isRunningInWorker?Nl.initializeWorker():Nl.isRunningInAudioWorklet?Nl.initializeAudioWorklet():Nl.initializeMain((t=>{if(Nl.webPlatform==e.WebPlatform.NodeJs)throw new K(e.AlphaTabErrorType.General,"Workers not yet supported in Node.js");if(Nl.webPlatform==e.WebPlatform.BrowserModule||Nl.isWebPackBundled||Nl.isViteBundled){ne.debug("AlphaTab","Creating webworker");try{return new Nl.alphaTabWorker(new URL("./alphaTab.worker",{}),{type:"module"})}catch(e){ne.debug("AlphaTab","ESM webworker construction with direct URL failed",e)}let e="";try{e=new Nl.alphaTabUrl("./alphaTab.worker",{});const t=`import ${JSON.stringify(e)}`,s=new Blob([t],{type:"application/javascript"});return new Worker(URL.createObjectURL(s),{type:"module"})}catch(t){ne.debug("AlphaTab","ESM webworker construction with blob import failed",e,t)}try{if(!t.core.scriptFile)throw new Error("Could not detect alphaTab script file");e=t.core.scriptFile;const s=`import ${JSON.stringify(t.core.scriptFile)}`,i=new Blob([s],{type:"application/javascript"});return new Worker(URL.createObjectURL(i),{type:"module"})}catch(e){ne.debug("AlphaTab","ESM webworker construction with blob import failed",t.core.scriptFile,e)}}if(!t.core.scriptFile)throw new K(e.AlphaTabErrorType.General,"Could not detect alphaTab script file, cannot initialize renderer");try{ne.debug("AlphaTab","Creating Blob worker");const e=`importScripts('${t.core.scriptFile}')`,s=new Blob([e],{type:"application/javascript"});return new Worker(URL.createObjectURL(s))}catch(e){return ne.warning("Rendering","Could not create inline worker, fallback to normal worker"),new Worker(t.core.scriptFile)}}),((t,s)=>{if(Nl.webPlatform==e.WebPlatform.NodeJs)throw new K(e.AlphaTabErrorType.General,"Audio Worklets not yet supported in Node.js");if(Nl.webPlatform==e.WebPlatform.BrowserModule||Nl.isWebPackBundled||Nl.isViteBundled){ne.debug("AlphaTab","Creating Module worklet");return t.audioWorklet.addModule(new URL("./alphaTab.worklet",{}))}return ne.debug("AlphaTab","Creating Script worklet"),t.audioWorklet.addModule(s.core.scriptFile)})),e.AlphaTabApi=wr,e.AlphaTabError=K,e.ConsoleLogger=re,e.CoreSettings=xl,e.DisplaySettings=kt,e.Environment=Nl,e.FileLoadError=rr,e.FormatError=Ce,e.ImporterSettings=Nt,e.LayoutEngineFactory=Tl,e.Logger=ne,e.NotationSettings=ie,e.PlayerSettings=Pt,e.ProgressEventArgs=pr,e.RenderEngineFactory=kl,e.RenderingResources=Tt,e.ResizeEventArgs=tr,e.Settings=Ot,e.VibratoPlaybackSettings=xt,e.exporter=Wl,e.importer=Cl,e.json=Jl,e.meta=vl,e.midi=zl,e.model=os,e.platform=Yn,e.rendering=Ul,e.synth=Xl}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).alphaTab={})}(this,(function(e){"use strict";var t,s,i,a,r,n,o,h,l,d,c,u,p,g,m,f,y,b,S,_,w,B,T,k,N,x,v,P,C,E,F,D,L,M,I,A,R,O,V,H,G,W,z,U,X,J,Y;e.LayoutMode=void 0,(t=e.LayoutMode||(e.LayoutMode={}))[t.Page=0]="Page",t[t.Horizontal=1]="Horizontal",e.StaveProfile=void 0,(s=e.StaveProfile||(e.StaveProfile={}))[s.Default=0]="Default",s[s.ScoreTab=1]="ScoreTab",s[s.Score=2]="Score",s[s.Tab=3]="Tab",s[s.TabMixed=4]="TabMixed";class q{static getValue(e){return q._values||(q._values=new Map),e=e.toLowerCase().replaceAll(" ",""),q._values.has(e)?q._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}}q._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]]);class j{init(e,t){this.data=e,this.settings=t}}e.AlphaTabErrorType=void 0,(i=e.AlphaTabErrorType||(e.AlphaTabErrorType={}))[i.General=0]="General",i[i.Format=1]="Format",i[i.AlphaTex=2]="AlphaTex";class K extends Error{constructor(e,t="",s){super(t??"",{cause:s}),this.type=e,Object.setPrototypeOf(this,K.prototype)}}class Q extends K{constructor(t=null,s){super(e.AlphaTabErrorType.Format,t??"Unsupported format",s),Object.setPrototypeOf(this,Q.prototype)}}!function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy",e[e.Tenuto=3]="Tenuto"}(a||(a={})),function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(r||(r={}));class ${constructor(){this.isLinear=!1,this.type=r.Tempo,this.value=0,this.ratioPosition=0,this.text=""}static buildTempoAutomation(e,t,s,i){(i<1||i>5)&&(i=2);let a=new Float32Array([1,.5,1,1.5,2,3]),n=new $;return n.type=r.Tempo,n.isLinear=e,n.ratioPosition=t,n.value=s*a[i],n}static buildInstrumentAutomation(e,t,s){let i=new $;return i.type=r.Instrument,i.isLinear=e,i.ratioPosition=t,i.value=s,i}}!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.Down=0]="Down",e[e.Hold=1]="Hold",e[e.Up=2]="Up"}(l||(l={}));class Z{constructor(){this.ratioPosition=0,this.pedalType=l.Down,this.nextPedalMarker=null,this.previousPedalMarker=null}}class ee{constructor(){this.id=ee._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=[]}get masterBar(){return this.staff.track.score.masterBars[this.index]}get isEmpty(){for(let e=0,t=this.voices.length;e<t;e++)if(!this.voices[e].isEmpty)return!1;return!0}addVoice(e){e.bar=this,e.index=this.voices.length,this.voices.push(e)}finish(e,t=null){this.isMultiVoice=!1;for(let s=0,i=this.voices.length;s<i;s++){let i=this.voices[s];i.finish(e,t),s>0&&!i.isEmpty&&(this.isMultiVoice=!0)}if(this.sustainPedals.length>0){let e=null;this.previousBar&&this.previousBar.sustainPedals.length>0&&(e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1]);for(const t of this.sustainPedals)e&&e.pedalType!==l.Up&&(e.nextPedalMarker=t,t.previousPedalMarker=e),t.bar=this,e=t}else if(this.previousBar&&this.previousBar.sustainPedals.length>0){const e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1];if(e.pedalType!==l.Up){const t=new Z;t.ratioPosition=0,t.bar=this,t.pedalType=l.Hold,this.sustainPedals.push(t),e.nextPedalMarker=t,t.previousPedalMarker=e}}}calculateDuration(){let e=0;for(let t of this.voices){let s=t.calculateDuration();s>e&&(e=s)}return e}}ee._globalBarId=0;class te{static ticksToMillis(e,t){return e*(6e4/(t*te.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*te.QuarterTime))|0}static toTicks(e){return te.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),te.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){return te.MinVelocity+e*te.VelocityIncrement}}te.QuarterTime=960,te.MinVelocity=15,te.VelocityIncrement=16;class se{constructor(e=0,t=0){this.offset=e,this.value=t}}se.MaxPosition=60,se.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(d||(d={})),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"}(c||(c={})),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"}(u||(u={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(p||(p={})),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"}(g||(g={})),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"}(m||(m={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(f||(f={})),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"}(y||(y={})),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"}(b||(b={})),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"}(S||(S={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(_||(_={})),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"}(w||(w={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(B||(B={})),e.TabRhythmMode=void 0,(T=e.TabRhythmMode||(e.TabRhythmMode={}))[T.Hidden=0]="Hidden",T[T.ShowWithBeams=1]="ShowWithBeams",T[T.ShowWithBars=2]="ShowWithBars",T[T.Automatic=3]="Automatic",e.FingeringMode=void 0,(k=e.FingeringMode||(e.FingeringMode={}))[k.ScoreDefault=0]="ScoreDefault",k[k.ScoreForcePiano=1]="ScoreForcePiano",k[k.SingleNoteEffectBand=2]="SingleNoteEffectBand",k[k.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano",e.NotationMode=void 0,(N=e.NotationMode||(e.NotationMode={}))[N.GuitarPro=0]="GuitarPro",N[N.SongBook=1]="SongBook",e.NotationElement=void 0,(x=e.NotationElement||(e.NotationElement={}))[x.ScoreTitle=0]="ScoreTitle",x[x.ScoreSubTitle=1]="ScoreSubTitle",x[x.ScoreArtist=2]="ScoreArtist",x[x.ScoreAlbum=3]="ScoreAlbum",x[x.ScoreWords=4]="ScoreWords",x[x.ScoreMusic=5]="ScoreMusic",x[x.ScoreWordsAndMusic=6]="ScoreWordsAndMusic",x[x.ScoreCopyright=7]="ScoreCopyright",x[x.GuitarTuning=8]="GuitarTuning",x[x.TrackNames=9]="TrackNames",x[x.ChordDiagrams=10]="ChordDiagrams",x[x.ParenthesisOnTiedBends=11]="ParenthesisOnTiedBends",x[x.TabNotesOnTiedBends=12]="TabNotesOnTiedBends",x[x.ZerosOnDiveWhammys=13]="ZerosOnDiveWhammys",x[x.EffectAlternateEndings=14]="EffectAlternateEndings",x[x.EffectCapo=15]="EffectCapo",x[x.EffectChordNames=16]="EffectChordNames",x[x.EffectCrescendo=17]="EffectCrescendo",x[x.EffectDynamics=18]="EffectDynamics",x[x.EffectFadeIn=19]="EffectFadeIn",x[x.EffectFermata=20]="EffectFermata",x[x.EffectFingering=21]="EffectFingering",x[x.EffectHarmonics=22]="EffectHarmonics",x[x.EffectLetRing=23]="EffectLetRing",x[x.EffectLyrics=24]="EffectLyrics",x[x.EffectMarker=25]="EffectMarker",x[x.EffectOttavia=26]="EffectOttavia",x[x.EffectPalmMute=27]="EffectPalmMute",x[x.EffectPickSlide=28]="EffectPickSlide",x[x.EffectPickStroke=29]="EffectPickStroke",x[x.EffectSlightBeatVibrato=30]="EffectSlightBeatVibrato",x[x.EffectSlightNoteVibrato=31]="EffectSlightNoteVibrato",x[x.EffectTap=32]="EffectTap",x[x.EffectTempo=33]="EffectTempo",x[x.EffectText=34]="EffectText",x[x.EffectTrill=35]="EffectTrill",x[x.EffectTripletFeel=36]="EffectTripletFeel",x[x.EffectWhammyBar=37]="EffectWhammyBar",x[x.EffectWideBeatVibrato=38]="EffectWideBeatVibrato",x[x.EffectWideNoteVibrato=39]="EffectWideNoteVibrato",x[x.EffectLeftHandTap=40]="EffectLeftHandTap",x[x.EffectFreeTime=41]="EffectFreeTime",x[x.EffectSustainPedal=42]="EffectSustainPedal",x[x.EffectGolpe=43]="EffectGolpe",x[x.EffectWahPedal=44]="EffectWahPedal",x[x.EffectBeatBarre=45]="EffectBeatBarre",x[x.EffectNoteOrnament=46]="EffectNoteOrnament",x[x.EffectRasgueado=47]="EffectRasgueado",x[x.EffectDirections=48]="EffectDirections",x[x.EffectBeatTimer=49]="EffectBeatTimer";class ie{constructor(){this.notationMode=e.NotationMode.GuitarPro,this.fingeringMode=e.FingeringMode.ScoreDefault,this.elements=new Map,this.rhythmMode=e.TabRhythmMode.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):!ie.defaultElements.has(e)||ie.defaultElements.get(e)}}ie.defaultElements=new Map([[e.NotationElement.ZerosOnDiveWhammys,!1]]);class ae{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}e.LogLevel=void 0,(v=e.LogLevel||(e.LogLevel={}))[v.None=0]="None",v[v.Debug=1]="Debug",v[v.Info=2]="Info",v[v.Warning=3]="Warning",v[v.Error=4]="Error";class re{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...s){console.debug(re.format(e,t),...s)}warning(e,t,...s){console.warn(re.format(e,t),...s)}info(e,t,...s){console.info(re.format(e,t),...s)}error(e,t,...s){console.error(re.format(e,t),...s)}}re.logLevel=e.LogLevel.Info;class ne{static shouldLog(t){return ne.logLevel!==e.LogLevel.None&&t>=ne.logLevel}static debug(t,s,...i){ne.shouldLog(e.LogLevel.Debug)&&ne.log.debug(t,s,...i)}static warning(t,s,...i){ne.shouldLog(e.LogLevel.Warning)&&ne.log.warning(t,s,...i)}static info(t,s,...i){ne.shouldLog(e.LogLevel.Info)&&ne.log.info(t,s,...i)}static error(t,s,...i){ne.shouldLog(e.LogLevel.Error)&&ne.log.error(t,s,...i)}}ne.logLevel=e.LogLevel.Info,ne.log=new re,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"}(P||(P={})),function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(C||(C={})),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"}(E||(E={}));class oe{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=P.C,this.keySignatureType=C.Major,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.isFreeTime=!1,this.tripletFeel=E.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 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(let t of this.score.tracks)for(let s of t.staves){let t=this.index<s.bars.length?s.bars[this.index].calculateDuration():0;t>e&&(e=t)}return e}return this.timeSignatureNumerator*te.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}}oe.MaxAlternateEndings=8;class he{constructor(){this.note=null,this.tone=new le,this.octave=0}get realValue(){return 12*this.octave+this.tone.noteValue}}class le{constructor(e=0,t=S.Default){this.noteValue=e,this.accidentalMode=t}}class de{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(let i of t.tracks[s].staves)i.displayTranspositionPitch=-e.notation.displayTranspositionPitches[s];if(s<e.notation.transpositionPitches.length)for(let i of t.tracks[s].staves)i.transpositionPitch=-e.notation.transpositionPitches[s]}}static fingerToString(t,s,i,a){if(t.notation.fingeringMode===e.FingeringMode.ScoreForcePiano||t.notation.fingeringMode===e.FingeringMode.SingleNoteEffectBandForcePiano||q.isPiano(s.voice.bar.staff.track.playbackInfo.program))switch(i){case y.Unknown:case y.NoOrDead:return null;case y.Thumb:return"1";case y.IndexFinger:return"2";case y.MiddleFinger:return"3";case y.AnnularFinger:return"4";case y.LittleFinger:return"5";default:return null}if(a)switch(i){case y.Unknown:return null;case y.NoOrDead:return"0";case y.Thumb:return"t";case y.IndexFinger:return"1";case y.MiddleFinger:return"2";case y.AnnularFinger:return"3";case y.LittleFinger:return"4";default:return null}switch(i){case y.Unknown:case y.NoOrDead:return null;case y.Thumb:return"p";case y.IndexFinger:return"i";case y.MiddleFinger:return"m";case y.AnnularFinger:return"a";case y.LittleFinger:return"c";default:return null}}static isTuning(e){return!!de.parseTuning(e)}static parseTuning(e){let t="",s="";for(let i=0;i<e.length;i++){let a=e.charCodeAt(i);if(a>=48&&a<=57){if(!t)return null;s+=String.fromCharCode(a)}else{if(!de.TuningLetters.has(a))return null;t+=String.fromCharCode(a)}}if(!s||!t)return null;let i=new he;return i.octave=parseInt(s)+1,i.note=t.toLowerCase(),i.tone=de.getToneForText(i.note),i.tone.noteValue<0&&(i.octave--,i.tone.noteValue+=12),i}static getTuningForText(e){let t=de.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=de.parseAccidentalMode(s),a){case S.Default:case S.ForceNone:case S.ForceNatural:break;case S.ForceSharp:i++;break;case S.ForceDoubleSharp:i+=2;break;case S.ForceFlat:i--;break;case S.ForceDoubleFlat:i-=2}return new le(i,a)}static parseAccidentalMode(e){const t=e.toLowerCase();return de.accidentalModeMapping.has(t)?de.accidentalModeMapping.get(t):S.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<oe.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}}de.TuningLetters=new Set([67,68,69,70,71,65,66,99,100,101,102,103,97,98,35]),de.accidentalModeMapping=new Map([["default",S.Default],["d",S.Default],["forcenone",S.ForceNone],["-",S.ForceNone],["forcenatural",S.ForceNatural],["n",S.ForceNatural],["forcesharp",S.ForceSharp],["#",S.ForceSharp],["forcedoublesharp",S.ForceDoubleSharp],["##",S.ForceDoubleSharp],["x",S.ForceDoubleSharp],["forceflat",S.ForceFlat],["b",S.ForceFlat],["forcedoubleflat",S.ForceDoubleFlat],["bb",S.ForceDoubleFlat]]),function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(F||(F={})),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.NoteheadTriangleUpWhole=57531]="NoteheadTriangleUpWhole",e[e.NoteheadTriangleUpHalf=57532]="NoteheadTriangleUpHalf",e[e.NoteheadTriangleUpBlack=57534]="NoteheadTriangleUpBlack",e[e.NoteheadDiamondBlackWide=57564]="NoteheadDiamondBlackWide",e[e.NoteheadDiamondWhite=57565]="NoteheadDiamondWhite",e[e.NoteheadDiamondWhiteWide=57566]="NoteheadDiamondWhiteWide",e[e.NoteheadCircleX=57523]="NoteheadCircleX",e[e.NoteheadXWhole=57511]="NoteheadXWhole",e[e.NoteheadXHalf=57512]="NoteheadXHalf",e[e.NoteheadXBlack=57513]="NoteheadXBlack",e[e.NoteheadParenthesis=57550]="NoteheadParenthesis",e[e.NoteheadSlashedBlack2=57552]="NoteheadSlashedBlack2",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.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.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.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.DynamicForte=58658]="DynamicForte",e[e.DynamicFF=58671]="DynamicFF",e[e.DynamicFFF=58672]="DynamicFFF",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"}(D||(D={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(L||(L={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(M||(M={}));class ce{constructor(e,t){this.width=e,this.height=t}}class ue{constructor(e="",t=0,s=0,i=D.None,a=D.None,r=D.None,n=D.None,o=M.Middle){this.elementType=e,this.outputMidiNumber=s,this.staffLine=t,this.noteHeadDefault=i,this.noteHeadHalf=a!==D.None?a:i,this.noteHeadWhole=r!==D.None?r:i,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case g.Whole:return this.noteHeadWhole;case g.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class pe{static articulationFromElementVariation(e,t){return e<pe.gp6ElementAndVariationToArticulation.length?(t>=pe.gp6ElementAndVariationToArticulation.length&&(t=0),pe.gp6ElementAndVariationToArticulation[e][t]):38}static getArticulation(e){const t=e.percussionArticulation,s=e.beat.voice.bar.staff.track.percussionArticulations;return t<s.length?s[t]:pe.getArticulationByValue(t)}static getElementAndVariation(e){const t=pe.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<pe.gp6ElementAndVariationToArticulation.length;e++){const s=pe.gp6ElementAndVariationToArticulation[e];for(let i=0;i<s.length;i++){const a=pe.getArticulationByValue(s[i]);if(a?.outputMidiNumber===t.outputMidiNumber)return[e,i]}}return[-1,-1]}static getArticulationByValue(e){return pe.instrumentArticulations.has(e)?pe.instrumentArticulations.get(e):null}}pe.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]],pe.instrumentArticulations=new Map([[38,new ue("snare",3,38,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[37,new ue("snare",3,37,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[91,new ue("snare",3,38,D.NoteheadDiamondWhite,D.NoteheadDiamondWhite,D.NoteheadDiamondWhite)],[42,new ue("hiHat",-1,42,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[92,new ue("hiHat",-1,46,D.NoteheadCircleSlash,D.NoteheadCircleSlash,D.NoteheadCircleSlash)],[46,new ue("hiHat",-1,46,D.NoteheadCircleX,D.NoteheadCircleX,D.NoteheadCircleX)],[44,new ue("hiHat",9,44,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[35,new ue("kickDrum",8,35,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[36,new ue("kickDrum",7,36,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[50,new ue("tom",1,50,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[48,new ue("tom",2,48,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[47,new ue("tom",4,47,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[45,new ue("tom",5,45,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[43,new ue("tom",6,43,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[93,new ue("ride",0,51,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack,D.PictEdgeOfCymbal,M.Bottom)],[51,new ue("ride",0,51,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[53,new ue("ride",0,53,D.NoteheadDiamondWhite,D.NoteheadDiamondWhite,D.NoteheadDiamondWhite)],[94,new ue("ride",0,51,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack,D.ArticStaccatoAbove,M.Top)],[55,new ue("splash",-2,55,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[95,new ue("splash",-2,55,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack,D.ArticStaccatoAbove,M.Bottom)],[52,new ue("china",-3,52,D.NoteheadHeavyXHat,D.NoteheadHeavyXHat,D.NoteheadHeavyXHat)],[96,new ue("china",-3,52,D.NoteheadHeavyXHat,D.NoteheadHeavyXHat,D.NoteheadHeavyXHat)],[49,new ue("crash",-2,49,D.NoteheadHeavyX,D.NoteheadHeavyX,D.NoteheadHeavyX)],[97,new ue("crash",-2,49,D.NoteheadHeavyX,D.NoteheadHeavyX,D.NoteheadHeavyX,D.ArticStaccatoAbove,M.Bottom)],[57,new ue("crash",-1,57,D.NoteheadHeavyX,D.NoteheadHeavyX,D.NoteheadHeavyX)],[98,new ue("crash",-1,57,D.NoteheadHeavyX,D.NoteheadHeavyX,D.NoteheadHeavyX,D.ArticStaccatoAbove,M.Bottom)],[99,new ue("cowbell",1,56,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpHalf,D.NoteheadTriangleUpWhole)],[100,new ue("cowbell",1,56,D.NoteheadXBlack,D.NoteheadXHalf,D.NoteheadXWhole)],[56,new ue("cowbell",0,56,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpHalf,D.NoteheadTriangleUpWhole)],[101,new ue("cowbell",0,56,D.NoteheadXBlack,D.NoteheadXHalf,D.NoteheadXWhole)],[102,new ue("cowbell",-1,56,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpHalf,D.NoteheadTriangleUpWhole)],[103,new ue("cowbell",-1,56,D.NoteheadXBlack,D.NoteheadXHalf,D.NoteheadXWhole)],[77,new ue("woodblock",-9,77,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack)],[76,new ue("woodblock",-10,76,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack)],[60,new ue("bongo",-4,60,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[104,new ue("bongo",-5,60,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.NoteheadParenthesis,M.Middle)],[105,new ue("bongo",-6,60,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[61,new ue("bongo",-7,61,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[106,new ue("bongo",-8,61,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.NoteheadParenthesis,M.Middle)],[107,new ue("bongo",-16,61,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[66,new ue("timbale",10,66,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[65,new ue("timbale",9,65,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[68,new ue("agogo",12,68,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[67,new ue("agogo",11,67,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[64,new ue("conga",17,64,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[108,new ue("conga",16,64,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[109,new ue("conga",15,64,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.NoteheadParenthesis,M.Middle)],[63,new ue("conga",14,63,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[110,new ue("conga",13,63,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[62,new ue("conga",19,62,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.NoteheadParenthesis,M.Middle)],[72,new ue("whistle",-11,72,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[71,new ue("whistle",-17,71,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[73,new ue("guiro",38,73,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[74,new ue("guiro",37,74,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[86,new ue("surdo",36,86,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[87,new ue("surdo",35,87,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadParenthesis,M.Middle)],[54,new ue("tambourine",3,54,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack)],[111,new ue("tambourine",2,54,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack,D.StringsUpBow,M.Bottom)],[112,new ue("tambourine",1,54,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack,D.NoteheadTriangleUpBlack,D.StringsDownBow,M.Bottom)],[113,new ue("tambourine",-7,54,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[79,new ue("cuica",30,79,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[78,new ue("cuica",29,78,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[58,new ue("vibraslap",28,58,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[81,new ue("triangle",27,81,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[80,new ue("triangle",26,80,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadParenthesis,M.Middle)],[114,new ue("grancassa",25,43,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[115,new ue("piatti",18,49,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[116,new ue("piatti",24,49,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[69,new ue("cabasa",23,69,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[117,new ue("cabasa",22,69,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.StringsUpBow,M.Bottom)],[85,new ue("castanets",21,85,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[75,new ue("claves",20,75,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[70,new ue("maraca",-12,70,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[118,new ue("maraca",-13,70,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.StringsUpBow,M.Bottom)],[119,new ue("maraca",-14,70,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[120,new ue("maraca",-15,70,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.StringsUpBow,M.Bottom)],[82,new ue("shaker",-23,54,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[122,new ue("shaker",-24,54,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.StringsUpBow,M.Bottom)],[84,new ue("bellTree",-18,53,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[123,new ue("bellTree",-19,53,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole,D.StringsUpBow,M.Bottom)],[83,new ue("jingleBell",-20,53,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[124,new ue("unpitched",-21,62,D.NoteheadNull,D.NoteheadNull,D.NoteheadNull,D.GuitarGolpe,M.Top)],[125,new ue("unpitched",-22,62,D.NoteheadNull,D.NoteheadNull,D.NoteheadNull,D.GuitarGolpe,M.Bottom)],[39,new ue("handClap",3,39,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[40,new ue("snare",3,40,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[31,new ue("snare",3,40,D.NoteheadSlashedBlack2,D.NoteheadSlashedBlack2,D.NoteheadSlashedBlack2)],[41,new ue("tom",5,41,D.NoteheadBlack,D.NoteheadHalf,D.NoteheadWhole)],[59,new ue("ride",2,59,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack,D.PictEdgeOfCymbal,M.Bottom)],[126,new ue("ride",2,59,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[127,new ue("ride",2,59,D.NoteheadDiamondWhite,D.NoteheadDiamondWhite,D.NoteheadDiamondWhite)],[29,new ue("ride",2,59,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack,D.ArticStaccatoAbove,M.Top)],[30,new ue("crash",-3,49,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[33,new ue("snare",3,37,D.NoteheadXBlack,D.NoteheadXBlack,D.NoteheadXBlack)],[34,new ue("snare",3,38,D.NoteheadBlack,D.NoteheadBlack,D.NoteheadBlack)]]),pe.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"}(I||(I={}));class ge{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1}}class me{constructor(){this.id=me.GlobalNoteId++,this.index=0,this.accentuated=a.None,this.bendType=c.None,this.bendStyle=d.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=b.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=_.None,this.slideOutType=w.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=B.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=y.Unknown,this.rightHandFinger=y.Unknown,this.trillValue=-1,this.trillSpeed=g.ThirtySecond,this.durationPercent=1,this.accidentalMode=S.Default,this.dynamics=m.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.ornament=I.None,this._noteIdBag=null}get hasBend(){return null!==this.bendPoints&&this.bendType!==c.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?pe.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?pe.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==b.None}get isTieOrigin(){return null!==this.tieDestination}get isFingering(){return this.leftHandFinger!==y.Unknown||this.rightHandFinger!==y.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+me.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===b.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===b.None||!this.isStringed)return 0;let e=this.harmonicValue;return de.isAlmostEqualTo(e,2.4)?36:de.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!==b.Natural&&this.harmonicType!==b.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===c.None&&(this.bendType=c.Custom)}finish(t,s=null){let i=new ae((()=>me.nextNoteOnSameLine(this))),a=t&&t.notation.notationMode===e.NotationMode.SongBook;if(this.isTieDestination&&(this.chain(s),a&&this.tieOrigin&&this.tieOrigin.isLetRing&&(this.isLetRing=!0)),this.isLetRing&&(i.value&&i.value.isLetRing?this.letRingDestination=i.value:this.letRingDestination=this,a&&this.isTieDestination&&!this.tieOrigin.hasBend&&(this.isVisible=!1)),this.isPalmMute&&(i.value&&i.value.isPalmMute?this.palmMuteDestination=i.value:this.palmMuteDestination=this),this.isHammerPullOrigin){let e=me.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case w.Shift:case w.Legato:this.slideTarget=i.value,this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=w.None}let r=null;this.isHammerPullOrigin&&this.hammerPullDestination?r=this.hammerPullDestination:this.slideOutType===w.Legato&&this.slideTarget&&(r=this.slideTarget),r&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===F.None?(this.effectSlurOrigin.effectSlurDestination=r,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=r,this.effectSlurDestination.effectSlurOrigin=this));const n=this.bendPoints,o=null!=n&&n.length>0;if(o){let e=this.isTieDestination&&this.tieOrigin.hasBend;this.isContinuedBend=e}else this.bendType=c.None;if(o&&this.bendType===c.Custom)if(4===n.length){let e=n[0],t=n[1],s=n[2],i=n[3];t.value===s.value?i.value>e.value?t.value>i.value?this.bendType=c.BendRelease:!this.isContinuedBend&&e.value>0?(this.bendType=c.PrebendBend,n.splice(2,1),n.splice(1,1)):(this.bendType=c.Bend,n.splice(2,1),n.splice(1,1)):i.value<e.value?this.isContinuedBend?(this.bendType=c.Release,n.splice(2,1),n.splice(1,1)):(this.bendType=c.PrebendRelease,n.splice(2,1),n.splice(1,1)):t.value>e.value?this.bendType=c.BendRelease:e.value>0&&!this.isContinuedBend?(this.bendType=c.Prebend,n.splice(2,1),n.splice(1,1)):(this.bendType=c.Hold,n.splice(2,1),n.splice(1,1)):ne.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===n.length){let e=n[0],t=n[1];t.value>e.value?!this.isContinuedBend&&e.value>0?this.bendType=c.PrebendBend:this.bendType=c.Bend:t.value<e.value?this.isContinuedBend?this.bendType=c.Release:this.bendType=c.PrebendRelease:e.value>0&&!this.isContinuedBend?this.bendType=c.Prebend:this.bendType=c.Hold}this.initialBendValue>0&&(this.accidentalMode=S.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+me.MaxOffsetForSameLineSearch;){let 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+me.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-me.MaxOffsetForSameLineSearch;){if(e.isStringed){let 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{let 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(me.NoteIdLookupKey)?t=e.get(me.NoteIdLookupKey):(t=new Map,e.set(me.NoteIdLookupKey,t)),-1===this._noteIdBag.hammerPullDestinationNoteId&&-1===this._noteIdBag.tieDestinationNoteId&&-1===this._noteIdBag.slurDestinationNoteId||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),this._noteIdBag=null}else{if(!this.isTieDestination&&null===this.tieOrigin)return;let e=this.tieOrigin??me.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)}setProperty(e,t){switch(e){case"tiedestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new ge),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new ge),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new ge),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new ge),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new ge),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new ge),this._noteIdBag.hammerPullDestinationNoteId=t,!0}return!1}}me.GlobalNoteId=0,me.MaxOffsetForSameLineSearch=3,me.NoteIdLookupKey="NoteIdLookup";class fe{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!==f.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{let e=this.beats[0].tupletNumerator/this.beats[0].tupletDenominator|0;for(let t of fe.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}fe.HalfTicks=1920,fe.QuarterTicks=960,fe.EighthTicks=480,fe.SixteenthTicks=240,fe.ThirtySecondTicks=120,fe.SixtyFourthTicks=60,fe.OneHundredTwentyEighthTicks=30,fe.TwoHundredFiftySixthTicks=15,fe.AllTicks=[fe.HalfTicks,fe.QuarterTicks,fe.EighthTicks,fe.SixteenthTicks,fe.ThirtySecondTicks,fe.SixtyFourthTicks,fe.OneHundredTwentyEighthTicks,fe.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"}(A||(A={}));class ye{static clone(e){const t=new se;return t.offset=e.offset,t.value=e.value,t}}class be{static clone(e){const t=new me;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(ye.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 Se{static clone(e){const t=new $;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class _e{static clone(e){const t=new Be;t.index=e.index,t.notes=[];for(const s of e.notes)t.addNote(be.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(Se.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(ye.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.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}}class we{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.None=0]="None",e[e.Thumb=1]="Thumb",e[e.Finger=2]="Finger"}(R||(R={})),function(e){e[e.None=0]="None",e[e.FadeIn=1]="FadeIn",e[e.FadeOut=2]="FadeOut",e[e.VolumeSwell=3]="VolumeSwell"}(O||(O={})),function(e){e[e.None=0]="None",e[e.Open=1]="Open",e[e.Closed=2]="Closed"}(V||(V={})),function(e){e[e.None=0]="None",e[e.Full=1]="Full",e[e.Half=2]="Half"}(H||(H={})),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"}(G||(G={})),function(e){e[e.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext",e[e.ForceSplitOnSecondaryToNext=3]="ForceSplitOnSecondaryToNext"}(W||(W={}));class Be{constructor(){this.id=Be._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=d.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=g.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fade=O.None,this.lyrics=null,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.slashed=!1,this.deadSlapped=!1,this.brushType=u.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=A.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=B.None,this.chordId=null,this.graceType=f.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=F.None,this.tremoloSpeed=null,this.crescendo=p.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.golpe=R.None,this.dynamics=m.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=W.Auto,this.wahPedal=V.None,this.barreFret=-1,this.barreShape=H.None,this.rasgueado=G.None,this.showTimer=!1,this.timer=null}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===g.Whole}get fadeIn(){return this.fade===O.FadeIn}set fadeIn(e){this.fade=e?O.FadeIn:O.None}get hasRasgueado(){return this.rasgueado!==G.None}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==A.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 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!==H.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===A.None&&(this.whammyBarType=A.Custom)}removeWhammyBarPoint(e){const t=this.whammyBarPoints;if(null===t||e<0||e>=t.length)return;t.splice(e,1);let s=t[e];if(s===this.maxWhammyPoint){this.maxWhammyPoint=null;for(let e of t)(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e)}if(s===this.minWhammyPoint){this.minWhammyPoint=null;for(let 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){let 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++){let 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(this.isFullBarRest)return this.voice.bar.masterBar.calculateDuration();let e=te.toTicks(this.duration);return 2===this.dots?e=te.applyDot(e,!0):1===this.dots&&(e=te.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=te.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){let e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case f.BeforeBeat:case f.OnBeat:switch(this.duration){case g.Sixteenth:this.playbackDuration=te.toTicks(g.SixtyFourth);break;case g.ThirtySecond:this.playbackDuration=te.toTicks(g.OneHundredTwentyEighth);break;default:this.playbackDuration=te.toTicks(g.ThirtySecond)}this.displayDuration=0;break;case f.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;let t=this.previousBeat;t&&t.graceType===f.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){let e=this.previousBeat,t=e?e.tupletGroup:null;if((this.hasTuplet||this.graceType!==f.None&&t)&&(e&&t&&t.check(this)||(t=new fe(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!==r.Volume&&t.push(s);this.automations=t}}finish(t,s=null){switch(null===this.getAutomation(r.Instrument)&&0===this.index&&0===this.voice.index&&0===this.voice.bar.index&&0===this.voice.bar.staff.index&&this.automations.push($.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case f.OnBeat:case f.BeforeBeat:let e=this.graceGroup.beats.length;this.duration=1===e?g.Eighth:2===e?g.Sixteenth:g.ThirtySecond}let i=t?t.notation.notationMode:e.NotationMode.GuitarPro,a="grad"===this.text||"grad."===this.text;a&&i===e.NotationMode.SongBook&&(this.text="");let n=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let o=0,h=!1;for(let r=0,l=this.notes.length;r<l;r++){let l=this.notes[r];if(l.dynamics=this.dynamics,l.finish(t,s),l.isLetRing&&(this.isLetRing=!0),l.isPalmMute&&(this.isPalmMute=!0),i===e.NotationMode.SongBook&&l.hasBend&&this.graceType!==f.BendGrace){if(!l.isTieOrigin)switch(l.bendType){case c.Bend:case c.PrebendRelease:case c.PrebendBend:n=!0}a||l.bendStyle===d.Gradual?(a=!0,l.bendStyle=d.Gradual,n=!1):l.bendStyle=d.Fast}l.isVisible&&(o++,(!this.minNote||l.realValue<this.minNote.realValue)&&(this.minNote=l),(!this.maxNote||l.realValue>this.maxNote.realValue)&&(this.maxNote=l),(!this.minStringNote||l.string<this.minStringNote.string)&&(this.minStringNote=l),(!this.maxStringNote||l.string>this.maxStringNote.string)&&(this.maxStringNote=l),l.hasEffectSlur&&(h=!0))}if(h&&(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===o&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&t&&t.notation.notationMode===e.NotationMode.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 l=this.whammyBarPoints,u=null!==l&&l.length>0;if(u){const e=!!this.previousBeat&&this.previousBeat.hasWhammyBar;this.isContinuedWhammy=e}else this.whammyBarType=A.None;if(u&&this.whammyBarType===A.Custom&&(i===e.NotationMode.SongBook&&(this.whammyStyle=a?d.Gradual:d.Fast),4===l.length)){let t=l[0],s=l[1],a=l[2],r=l[3];s.value===a.value&&(t.value<s.value&&s.value<r.value||t.value>s.value&&s.value>r.value?(0===t.value||this.isContinuedWhammy?this.whammyBarType=A.Dive:this.whammyBarType=A.PrediveDive,l.splice(2,1),l.splice(1,1)):t.value>s.value&&s.value<r.value||t.value<s.value&&s.value>r.value?(this.whammyBarType=A.Dip,s.offset!==a.offset&&i!==e.NotationMode.SongBook||l.splice(2,1)):t.value===s.value&&s.value===r.value&&(0===t.value||this.isContinuedWhammy?this.whammyBarType=A.Hold:this.whammyBarType=A.Predive,l.splice(2,1),l.splice(1,1)))}if(this.updateDurations(),n){let e=_e.clone(this);e.id=Be._globalBeatId++,e.pickStroke=F.None;for(let t=0,s=e.notes.length;t<s;t++){let s=e.notes[t],i=this.notes[t];if(s.bendType=c.None,s.maxBendPoint=null,s.bendPoints=null,s.bendStyle=d.Default,s.id=me.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){let e=me.findTieOrigin(i);if(e&&e.hasBend){s.bendType=c.Hold;let e=i.bendPoints[i.bendPoints.length-1];s.addBendPoint(new se(0,e.value)),s.addBendPoint(new se(se.MaxPosition,e.value))}}s.isTieDestination=!0}this.graceType=f.BendGrace,this.graceGroup=new we,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new we,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)}}Be._globalBeatId=0;class Te{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"}(z||(z={}));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=z.Begin,r=z.Begin,n=!1,o=0;for(;t<e.length;){let s=e.charCodeAt(t);switch(a){case z.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 z.Begin:if(s!==ke.CharCodeBrackedOpen){o=t,a=z.Text;continue}a=z.Comment;break;case z.Comment:if(s===ke.CharCodeBrackedClose)a=z.Begin;break;case z.Text:switch(s){case ke.CharCodeDash:a=z.Dash;break;case ke.CharCodeCR:case ke.CharCodeLF:case ke.CharCodeSpace:let s=e.substr(o,t-o);this.addChunk(s,i),a=z.IgnoreSpaces,r=z.Begin}break;case z.Dash:if(s!==ke.CharCodeDash){let s=e.substr(o,t-o);this.addChunk(s,i),n=!0,a=z.IgnoreSpaces,r=z.Begin;continue}}t+=1}a===z.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){let t=e.split("+").join(" "),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,function(e){e[e.NoBrackets=0]="NoBrackets",e[e.GroupStaves=1]="GroupStaves",e[e.GroupSimilarInstruments=2]="GroupSimilarInstruments"}(U||(U={})),function(e){e[e.Hidden=0]="Hidden",e[e.FirstSystem=1]="FirstSystem",e[e.AllSystems=2]="AllSystems"}(X||(X={})),function(e){e[e.FullName=0]="FullName",e[e.ShortName=1]="ShortName"}(J||(J={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical"}(Y||(Y={}));class Ne{constructor(){this.hideDynamics=!1,this.bracketExtendMode=U.GroupStaves,this.useSystemSignSeparator=!1,this.globalDisplayTuning=!0,this.perTrackDisplayTuning=null,this.globalDisplayChordDiagramsOnTop=!0,this.perTrackChordDiagramsOnTop=null,this.singleTrackTrackNamePolicy=X.FirstSystem,this.multiTrackTrackNamePolicy=X.FirstSystem,this.firstSystemTrackNameMode=J.ShortName,this.otherSystemsTrackNameMode=J.ShortName,this.firstSystemTrackNameOrientation=Y.Vertical,this.otherSystemsTrackNameOrientation=Y.Vertical}}class xe{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 ve{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 Ne}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 xe,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new xe,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 Pe{constructor(){this.marker="",this.text=""}}class Ce extends K{constructor(t){super(e.AlphaTabErrorType.Format,t),Object.setPrototypeOf(this,Ce.prototype)}}class Ee{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="#"+de.toHexString(this.r,2)+de.toHexString(this.g,2)+de.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 Ee(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){if(e instanceof Ee)return e;switch(typeof e){case"number":{const t=new Ee(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 Ee(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16));if(5===t.length)return new Ee(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16),17*parseInt(t[4],16));if(7===t.length)return new Ee(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16));if(9===t.length)return new Ee(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16),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 Ce("No values specified for rgb/rgba function");const i=t.substring(e+1,s).split(",");if(3===i.length)return new Ee(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]));if(4===i.length)return new Ee(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]),255*parseFloat(i[3]))}return null}}throw new Ce("Unsupported format for color")}static toJson(e){return e.raw}}Ee.BlackRgb="#000000";class Fe{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 De{static getTextForTuning(e,t){let s=De.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 De._defaultTunings.has(e)?De._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return De._sevenStrings;case 6:return De._sixStrings;case 5:return De._fiveStrings;case 4:return De._fourStrings}return[]}static initialize(){De._defaultTunings.set(7,new De("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),De._sevenStrings.push(De._defaultTunings.get(7)),De._defaultTunings.set(6,new De("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),De._sixStrings.push(De._defaultTunings.get(6)),De._sixStrings.push(new De("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),De._sixStrings.push(new De("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),De._sixStrings.push(new De("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),De._sixStrings.push(new De("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),De._sixStrings.push(new De("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),De._sixStrings.push(new De("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),De._sixStrings.push(new De("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),De._sixStrings.push(new De("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),De._sixStrings.push(new De("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),De._sixStrings.push(new De("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),De._sixStrings.push(new De("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),De._sixStrings.push(new De("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),De._sixStrings.push(new De("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),De._sixStrings.push(new De("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),De._sixStrings.push(new De("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),De._sixStrings.push(new De("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),De._sixStrings.push(new De("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),De._sixStrings.push(new De("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),De._sixStrings.push(new De("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),De._sixStrings.push(new De("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),De._sixStrings.push(new De("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),De._sixStrings.push(new De("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),De._sixStrings.push(new De("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),De._sixStrings.push(new De("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),De._sixStrings.push(new De("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),De._sixStrings.push(new De("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),De._sixStrings.push(new De("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),De._sixStrings.push(new De("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),De._sixStrings.push(new De("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),De._sixStrings.push(new De("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),De._defaultTunings.set(5,new De("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),De._fiveStrings.push(De._defaultTunings.get(5)),De._fiveStrings.push(new De("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),De._fiveStrings.push(new De("Banjo Open D Tuning",[62,57,54,50,69],!1)),De._fiveStrings.push(new De("Banjo Open G Tuning",[62,59,55,50,67],!1)),De._fiveStrings.push(new De("Banjo G Minor Tuning",[62,58,55,50,67],!1)),De._fiveStrings.push(new De("Banjo G Modal Tuning",[62,57,55,50,67],!1)),De._defaultTunings.set(4,new De("Bass Standard Tuning",[43,38,33,28],!0)),De._fourStrings.push(De._defaultTunings.get(4)),De._fourStrings.push(new De("Bass Tune down ½ step",[42,37,32,27],!1)),De._fourStrings.push(new De("Bass Tune down 1 step",[41,36,31,26],!1)),De._fourStrings.push(new De("Bass Tune down 2 step",[39,34,29,24],!1)),De._fourStrings.push(new De("Bass Dropped D Tuning",[43,38,33,26],!1)),De._fourStrings.push(new De("Ukulele C Tuning",[45,40,36,43],!1)),De._fourStrings.push(new De("Ukulele G Tuning",[52,47,43,38],!1)),De._fourStrings.push(new De("Mandolin Standard Tuning",[64,57,50,43],!1)),De._fourStrings.push(new De("Mandolin or Violin Tuning",[76,69,62,55],!1)),De._fourStrings.push(new De("Viola Tuning",[69,62,55,48],!1)),De._fourStrings.push(new De("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){let t=De.getPresetsFor(e.length);for(let s=0,i=t.length;s<i;s++){let i=t[s],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=De.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}De._sevenStrings=[],De._sixStrings=[],De._fiveStrings=[],De._fourStrings=[],De._defaultTunings=new Map,De.defaultAccidentals=["","#","","#","","","#","","#","","#",""],De.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],De.initialize();class Le{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new De("",[],!1),this.showSlash=!1,this.showNumbered=!1,this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=Le.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){let 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)}}Le.DefaultStandardNotationLineCount=5;class Me{constructor(){this.index=0,this.staves=[],this.playbackInfo=new Fe,this.color=new Ee(200,0,0,255),this.name="",this.isVisibleOnMultiTrack=!0,this.shortName="",this.defaultSystemsLayout=3,this.systemsLayout=[],this.percussionArticulations=[]}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new Le)}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>Me.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,Me.ShortNameMaxLength)));for(let s=0,i=this.staves.length;s<i;s++)this.staves[s].finish(e,t)}applyLyrics(e){for(let t of e)t.finish();let t=this.staves[0];for(let s=0;s<e.length;s++){let 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)}}}}}Me.ShortNameMaxLength=10;let Ie=class e{constructor(){this.id=e._globalBarId++,this.index=0,this.beats=[],this.isEmpty=!0}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)}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){let 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);let t=this.beats[this.beats.length-1];this.beats.splice(this.beats.length-1,1),this.addBeat(e),this.addBeat(t),this.isEmpty=!1}getBeatAtPlaybackStart(e){return this._beatLookup.has(e)?this._beatLookup.get(e):null}finish(e,t=null){this._beatLookup=new Map;let s=null;for(let e=0;e<this.beats.length;e++){let i=this.beats[e];i.index=e,this.chain(i,t),i.graceType===f.None?(i.graceGroup=s,s&&(s.isComplete=!0),s=null):(s||(s=new we),s.addBeat(i))}let i=0,a=0;for(let s=0;s<this.beats.length;s++){let r=this.beats[s];if(r.index=s,r.finish(e,t),r.graceType===f.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==f.BendGrace){let s=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case f.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 f.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;let e=this.beats[this.beats.length-1],t=this.beats[0];return e.playbackStart+e.playbackDuration-t.playbackStart}};Ie._globalBarId=0;class Ae{static float64ToBytes(e){return Ae._dataView.setFloat64(0,e,!0),this._conversionByteArray}static bytesToInt64LE(e){Ae._conversionByteArray.set(e,0);const t=Ae._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 Ae._conversionByteArray.set(e,0),Ae._dataView.getFloat64(0,!0)}static bytesToFloat32LE(e){return Ae._conversionByteArray.set(e,0),Ae._dataView.getFloat32(0,!0)}static float32BEToBytes(e){return Ae._dataView.setFloat32(0,e,!1),Ae._conversionByteArray.slice(0,4)}static uint16ToInt16(e){return Ae._dataView.setUint16(0,e,!0),Ae._dataView.getInt16(0,!0)}static int16ToUint32(e){return Ae._dataView.setInt16(0,e,!0),Ae._dataView.getUint32(0,!0)}static int32ToUint16(e){return Ae._dataView.setInt32(0,e,!0),Ae._dataView.getUint16(0,!0)}static int32ToInt16(e){return Ae._dataView.setInt32(0,e,!0),Ae._dataView.getInt16(0,!0)}static int32ToUint32(e){return Ae._dataView.setInt32(0,e,!0),Ae._dataView.getUint32(0,!0)}static uint8ToInt8(e){return Ae._dataView.setUint8(0,e),Ae._dataView.getInt8(0)}}Ae._conversionBuffer=new ArrayBuffer(8),Ae._conversionByteArray=new Uint8Array(Ae._conversionBuffer),Ae._dataView=new DataView(Ae._conversionBuffer);class Re{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(),Ae.bytesToFloat32LE(t)}static readFloat64BE(e){const t=new Uint8Array(8);return e.read(t,0,t.length),t.reverse(),Ae.bytesToFloat64LE(t)}static readInt32LE(e){let 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),Ae.bytesToInt64LE(t)}static readUInt32LE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static decodeUInt32LE(e,t){let s=e[t],i=e[t+1],a=e[t+2];return e[t+3]<<24|a<<16|i<<8|s}static readUInt16LE(e){let t=e.readByte(),s=e.readByte();return Ae.int32ToUint16(s<<8|t)}static readInt16LE(e){let t=e.readByte(),s=e.readByte();return Ae.int32ToInt16(s<<8|t)}static readUInt32BE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte(),a=e.readByte();return Ae.int32ToUint32(t<<24|s<<16|i<<8|a)}static readUInt16BE(e){let t=e.readByte(),s=e.readByte();return Ae.int32ToInt16(t<<8|s)}static readInt16BE(e){let t=e.readByte(),s=e.readByte();return Ae.int32ToInt16(t<<8|s)}static readByteArray(e,t){let s=new Uint8Array(t);return e.read(s,0,t),s}static read8BitChars(e,t){let s=new Uint8Array(t);return e.read(s,0,s.length),Re.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++){let t=e.readByte();0===t&&-1===i&&(i=a),s+=String.fromCharCode(t)}let a=s;return i>=0?a.substr(0,i):a}static readSInt8(e){let 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 Ae.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){let s=Re.detectEncoding(e);return s&&(t=s),t||(t="utf-8"),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=Ae.float32BEToBytes(t);e.write(s,0,s.length)}}class Oe{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return Oe.withCapacity(0)}static withCapacity(e){let t=new Oe;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){let t=new Oe;return t._buffer=e,t.length=e.length,t}static fromString(e){let t=Re.stringToBytes(e);return Oe.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){let 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){let i=this.position+s;this.ensureCapacity(i);let 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);let 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(){let 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)}}class Ve{}var He,Ge,We,ze,Ue,Xe,Je,Ye,qe,je,Ke,Qe,$e,Ze;Ve.DefaultChannelCount=17,Ve.MetronomeChannel=Ve.DefaultChannelCount-1,Ve.MetronomeKey=33,Ve.AudioChannels=2,Ve.MinVolume=0,Ve.MinProgram=0,Ve.MaxProgram=127,Ve.MinPlaybackSpeed=.125,Ve.MaxPlaybackSpeed=8,Ve.PercussionChannel=9,Ve.PercussionBank=128,Ve.MaxPitchWheel=16384,Ve.MaxPitchWheel20=4294967296,Ve.DefaultPitchWheel=Ve.MaxPitchWheel/2,Ve.MicroBufferCount=32,Ve.MicroBufferSize=64,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"}(He||(He={})),function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(Ge||(Ge={}));class et{constructor(){this.type=Ge.Short,this.length=0}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(We||(We={})),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"}(ze||(ze={})),function(e){e[e.KnownStaffMeta=0]="KnownStaffMeta",e[e.UnknownStaffMeta=1]="UnknownStaffMeta",e[e.EndOfMetaDetected=2]="EndOfMetaDetected"}(Ue||(Ue={}));class tt extends K{constructor(t,s,i,a,r,n,o,h=null){super(e.AlphaTabErrorType.AlphaTex,t),this.position=s,this.line=i,this.col=a,this.nonTerm=r??"",this.expected=n??ze.No,this.symbol=o??ze.No,this.symbolData=h,Object.setPrototypeOf(this,tt.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 ${ze[a]} found a ${ze[r]}`,null!==n&&(o+=`: '${n}'`)):o+=`, invalid value: '${n}'`,new tt(o,e,t,s,i,a,r,n)}static errorMessage(e,t,s,i){return new tt(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"}(Xe||(Xe={}));class st extends j{constructor(){super(),this._trackChannel=0,this._barIndex=0,this._voiceIndex=0,this._input="",this._ch=st.Eof,this._curChPos=0,this._line=1,this._col=0,this._lastValidSpot=[0,1,0],this._sy=ze.No,this._syData="",this._allowNegatives=!1,this._allowFloat=!1,this._allowTuning=!1,this._currentDuration=g.QuadrupleWhole,this._currentDynamics=m.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._accidentalMode=Xe.Explicit,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=Oe.empty(),this._input=e,this.settings=t}readScore(){try{if(this.data.length>0&&(this._input=Re.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=g.Quarter,this._currentDynamics=m.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===ze.LowerThan)throw new Q("Unknown start sign '<' (meant to import as XML?)");if(this._sy!==ze.Eof){const e=this.metaData(),t=this.bars();if(!e&&!t)throw new Q("No alphaTex data found")}this.consolidate(),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)if(0===e.ratioPosition){const s=t.voice.bar.masterBar.calculateDuration();e.ratioPosition=t.playbackStart/s}return this._score}catch(e){throw e instanceof tt?new Q(e.message,e):e}}consolidate(){if(0===this._score.masterBars.length){const e=new oe;this._score.addMasterBar(e);const t=new $;t.isLinear=!1,t.type=r.Tempo,t.value=this._score.tempo,e.tempoAutomations.push(t);const s=new ee;this._score.tracks[0].staves[0].addBar(s);const i=new Ie;s.addVoice(i);const a=new Be;return a.isEmpty=!0,void i.addBeat(a)}for(let e of this._score.tracks)for(let t of e.staves){for(const e of t.bars)for(const t of e.voices)if(t.isEmpty&&0==t.beats.length){const e=new Be;e.isEmpty=!0,t.addBeat(e)}const e=0===t.bars.length?1:t.bars[0].voices.length;for(;t.bars.length<this._score.masterBars.length;){const s=new ee;t.addBar(s);for(let t=0;t<e;t++){const e=new Ie;s.addVoice(e);const t=new Be;t.isEmpty=!0,e.addBeat(t)}}}}error(e,t,s=!0){let i,a=!1;s?(i=this._sy,i!==ze.String&&i!==ze.Number&&i!==ze.MetaCommand||(a=!0)):i=t;let r=tt.symbolError(this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2],e,t,i,a?this._syData:null);throw this.logErrors&&ne.error(this.name,r.message),r}errorMessage(e){let t=tt.errorMessage(e,this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2]);throw this.logErrors&&ne.error(this.name,t.message),t}createDefaultScore(){this._score=new ve,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new Me,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=De.getDefaultTuningFor(6).tunings,this.beginStaff(e),this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=m.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 E.NoTripletFeel;case"t16":case"triplet-16th":return E.Triplet16th;case"t8":case"triplet-8th":return E.Triplet8th;case"d16":case"dotted-16th":return E.Dotted16th;case"d8":case"dotted-8th":return E.Dotted8th;case"s16":case"scottish-16th":return E.Scottish16th;case"s8":case"scottish-8th":return E.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return E.NoTripletFeel;case 1:return E.Triplet16th;case 2:return E.Triplet8th;case 3:return E.Dotted16th;case 4:return E.Dotted8th;case 5:return E.Scottish16th;case 6:return E.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":case"abminor":return P.Cb;case"gb":case"gbmajor":case"ebminor":return P.Gb;case"db":case"dbmajor":case"bbminor":return P.Db;case"ab":case"abmajor":case"fminor":return P.Ab;case"eb":case"ebmajor":case"cminor":return P.Eb;case"bb":case"bbmajor":case"gminor":return P.Bb;case"f":case"fmajor":case"dminor":return P.F;case"c":case"cmajor":case"aminor":default:return P.C;case"g":case"gmajor":case"eminor":return P.G;case"d":case"dmajor":case"bminor":return P.D;case"a":case"amajor":case"f#minor":return P.A;case"e":case"emajor":case"c#minor":return P.E;case"b":case"bmajor":case"g#minor":return P.B;case"f#":case"f#major":case"d#minor":return P.FSharp;case"c#":case"c#major":case"a#minor":return P.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=st.Eof,this._ch}saveValidSpot(){this._lastValidSpot=[this._curChPos,this._line,this._col]}newSy(){for(this.saveValidSpot(),this._sy=ze.No;this._sy===ze.No;)if(this._ch===st.Eof)this._sy=ze.Eof;else if(st.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!==st.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;this._ch!==st.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",ze.String,!1);this.saveValidSpot()}else if(34===this._ch||39===this._ch){let e=this._ch;this._ch=this.nextChar();let t="";for(this._sy=ze.String;this._ch!==e&&this._ch!==st.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===st.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=ze.String,this._syData=this.readName());else if(46===this._ch)this._sy=ze.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=ze.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=ze.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=ze.MetaCommand,92===this._ch&&(this._ch=this.nextChar()),this._syData=this.readName();else if(41===this._ch)this._sy=ze.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=ze.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=ze.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=ze.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=ze.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=ze.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this.readNumberOrName();else if(st.isNameLetter(this._ch)){let e=this.readName(),t=this._allowTuning?de.parseTuning(e):null;t?(this._sy=ze.Tuning,this._syData=t):(this._sy=ze.String,this._syData=e)}else this.error("symbol",ze.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)||st.isNameLetter(this._ch));t?(this._sy=ze.Number,this._syData=this._allowFloat?parseFloat(e):parseInt(e)):(this._sy=ze.String,this._syData=e)}static isNameLetter(e){return!st.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(st.isNameLetter(this._ch)||this.isDigit(this._ch));return e}metaData(){let e=!1,t=!1,s=!0;for(;this._sy===ze.MetaCommand&&s;){let 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!==ze.String&&this.error(i,ze.String,!0);let a=this._syData;switch(i){case"title":this._score.title=a;break;case"subtitle":this._score.subTitle=a;break;case"artist":this._score.artist=a;break;case"album":this._score.album=a;break;case"words":this._score.words=a;break;case"music":this._score.music=a;break;case"copyright":this._score.copyright=a;break;case"instructions":this._score.instructions=a;break;case"notices":this._score.notices=a;break;case"tab":this._score.tab=a}this._sy=this.newSy(),e=!0;break;case"tempo":this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy===ze.Number?this._score.tempo=this._syData:this.error("tempo",ze.Number,!0),this._sy=this.newSy(),this._sy===ze.String&&(this._score.tempoLabel=this._syData,this._sy=this.newSy()),e=!0;break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===ze.Number?(this._score.defaultSystemsLayout=this._syData,this._sy=this.newSy(),e=!0):this.error("default-systems-layout",ze.Number,!0);break;case"systemslayout":for(this._sy=this.newSy(),e=!0;this._sy===ze.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!==ze.String&&this.error("bracketExtendMode",ze.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"singletracktracknamepolicy":this._sy=this.newSy(),this._sy!==ze.String&&this.error("singleTrackTrackNamePolicy",ze.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!==ze.String&&this.error("multiTrackTrackNamePolicy",ze.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!==ze.String&&this.error("firstSystemTrackNameMode",ze.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!==ze.String&&this.error("otherSystemsTrackNameMode",ze.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!==ze.String&&this.error("firstSystemTrackNameOrientation",ze.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!==ze.String&&this.error("otherSystemsTrackNameOrientation",ze.String,!0),this._score.stylesheet.otherSystemsTrackNameOrientation=this.parseTrackNameOrientation(this._syData),this._sy=this.newSy(),e=!0;break;default:switch(this.handleStaffMeta()){case Ue.KnownStaffMeta:t=!0;break;case Ue.UnknownStaffMeta:e||t?this.error("metaDataTags",ze.String,!1):s=!1;break;case Ue.EndOfMetaDetected:s=!1}}}return e?(this._sy!==ze.Dot&&this.error("song",ze.Dot,!0),this._sy=this.newSy()):this._sy===ze.Dot&&(this._sy=this.newSy(),e=!0),e||t}parseTrackNamePolicy(e){switch(e.toLowerCase()){case"hidden":return X.Hidden;case"allsystems":return X.AllSystems;default:return X.FirstSystem}}parseTrackNameMode(e){return"fullname"===e.toLowerCase()?J.FullName:J.ShortName}parseTrackNameOrientation(e){return"horizontal"===e.toLowerCase()?Y.Horizontal:Y.Vertical}handleStaffMeta(){switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===ze.Number?this._currentStaff.capo=this._syData:this.error("capo",ze.Number,!0),this._sy=this.newSy(),Ue.KnownStaffMeta;case"tuning":this._sy=this.newSy();let e=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case ze.String:let e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?this.makeCurrentStaffPitched():this.error("tuning",ze.Tuning,!0),this._sy=this.newSy();break;case ze.Tuning:let t=[];do{let e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===ze.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",ze.Tuning,!0)}return this._sy===ze.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"),Ue.KnownStaffMeta;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===ze.Number){let e=this._syData;e>=0&&e<=127?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",ze.Number,!1)}else if(this._sy===ze.String){let e=this._syData.toLowerCase();if("percussion"===e){for(const e of this._currentTrack.staves)this.applyPercussionStaff(e);this._currentTrack.playbackInfo.primaryChannel=Ve.PercussionChannel,this._currentTrack.playbackInfo.secondaryChannel=Ve.PercussionChannel}else this._currentTrack.playbackInfo.program=q.getValue(e)}else this.error("instrument",ze.Number,!0);return this._sy=this.newSy(),Ue.KnownStaffMeta;case"lyrics":this._sy=this.newSy();let t=new ke;return t.startBar=0,t.text="",this._sy===ze.Number&&(t.startBar=this._syData,this._sy=this.newSy()),this._sy===ze.String?(t.text=this._syData,this._sy=this.newSy()):this.error("lyrics",ze.String,!0),this._lyrics.get(this._currentTrack.index).push(t),Ue.KnownStaffMeta;case"chord":this._sy=this.newSy();let s=new Te;this.chordProperties(s),this._sy===ze.String?(s.name=this._syData,this._sy=this.newSy()):this.error("chord-name",ze.String,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===ze.Number?s.strings.push(this._syData):this._sy===ze.String&&"x"===this._syData.toLowerCase()&&s.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,s.name),s),Ue.KnownStaffMeta;case"articulation":this._sy=this.newSy();let i="";if(this._sy===ze.String?(i=this._syData,this._sy=this.newSy()):this.error("articulation-name",ze.String,!0),"defaults"===i){for(const[e,t]of pe.instrumentArticulationNames)this._percussionArticulationNames.set(e.toLowerCase(),t),this._percussionArticulationNames.set(st.toArticulationId(e),t);return Ue.KnownStaffMeta}let a=0;return this._sy===ze.Number?(a=this._syData,this._sy=this.newSy()):this.error("articulation-number",ze.Number,!0),pe.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),Ue.KnownStaffMeta;case"accidentals":return this.handleAccidentalMode(),Ue.KnownStaffMeta;case"displaytranspose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===ze.Number?(this._currentStaff.displayTranspositionPitch=-1*this._syData,this._staffHasExplicitDisplayTransposition=!0):this.error("displaytranspose",ze.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),Ue.KnownStaffMeta;case"transpose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===ze.Number?this._currentStaff.transpositionPitch=-1*this._syData:this.error("transpose",ze.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),Ue.KnownStaffMeta;case"track":case"staff":return Ue.EndOfMetaDetected;case"voice":return this._sy=this.newSy(),this.handleNewVoice()?Ue.EndOfMetaDetected:Ue.KnownStaffMeta;default:return Ue.UnknownStaffMeta}}handleAccidentalMode(){switch(this._sy=this.newSy(),this._sy!==ze.String&&this.error("accidental-mode",ze.String,!0),this._syData){case"auto":this._accidentalMode=Xe.Auto;break;case"explicit":this._accidentalMode=Xe.Explicit}this._sy=this.newSy()}makeCurrentStaffPitched(){this._currentStaff.stringTuning.tunings=[],this._staffHasExplicitDisplayTransposition||(this._currentStaff.displayTranspositionPitch=0)}static toArticulationId(e){return e.replace(new RegExp("[^a-zA-Z0-9]","g"),"").toLowerCase()}applyPercussionStaff(e){e.isPercussion=!0,e.showTablature=!1}chordProperties(e){if(this._sy===ze.LBrace){for(this._sy=this.newSy();this._sy===ze.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===ze.Number)e.firstFret=this._syData;else this.error("chord-firstfret",ze.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case ze.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case ze.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",ze.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case ze.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case ze.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",ze.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case ze.String:e.showName="false"!==this._syData.toLowerCase();break;case ze.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",ze.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===ze.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",ze.String,!1)}this._sy!==ze.RBrace&&this.error("chord-properties",ze.RBrace,!0),this._sy=this.newSy()}}bars(){let e=this.bar();for(;this._sy!==ze.Eof;)if(this._sy===ze.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==ze.MetaCommand)break;this.bar()}return e}trackStaffMeta(){if(this._sy!==ze.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===ze.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===ze.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy()),this.trackProperties()),this._sy===ze.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=m.F}this.staffProperties()}return this._sy===ze.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 Ie;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===ze.LBrace){for(this._sy=this.newSy();this._sy===ze.String;)switch(this._syData.toLowerCase()){case"color":this._sy=this.newSy(),this._sy!==ze.String&&this.error("track-color",ze.String,!0),this._currentTrack.color=Ee.fromJson(this._syData),this._sy=this.newSy();break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===ze.Number?(this._currentTrack.defaultSystemsLayout=this._syData,this._sy=this.newSy()):this.error("default-systems-layout",ze.Number,!0);break;case"systemslayout":for(this._sy=this.newSy();this._sy===ze.Number;)this._currentTrack.systemsLayout.push(this._syData),this._sy=this.newSy();break;case"volume":this._sy=this.newSy(),this._sy!==ze.Number&&this.error("track-volume",ze.Number,!0),this._currentTrack.playbackInfo.volume=de.clamp(this._syData,0,16),this._sy=this.newSy();break;case"balance":this._sy=this.newSy(),this._sy!==ze.Number&&this.error("track-balance",ze.Number,!0),this._currentTrack.playbackInfo.balance=de.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;default:this.error("track-properties",ze.String,!1)}this._sy!==ze.RBrace&&this.error("track-properties",ze.RBrace,!0),this._sy=this.newSy()}}staffProperties(){if(this._sy!==ze.LBrace)return;this._sy=this.newSy();let e=!1,t=!1,s=!1,i=!1;for(;this._sy===ze.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy(),this._sy===ze.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",ze.String,!1)}(e||t||s||i)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t,this._currentStaff.showSlash=s,this._currentStaff.showNumbered=i),this._sy!==ze.RBrace&&this.error("staff-properties",ze.RBrace,!0),this._sy=this.newSy()}bar(){const e=this.trackStaffMeta();let t=this.newBar(this._currentStaff);if(this._currentStaff.bars.length>this._score.masterBars.length){let e=new oe;this._score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,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=De.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,r=t.voices[this._voiceIndex];if(!(this._sy===ze.MetaCommand&&("track"===this._syData.toLowerCase()||"staff"===this._syData.toLowerCase())))for(;this._sy!==ze.Pipe&&this._sy!==ze.Eof&&this.beat(r);)a=!0;if(0===r.beats.length){let e=new Be;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 ee;e.addBar(s),s.previousBar&&(s.clef=s.previousBar.clef,s.clefOttava=s.previousBar.clefOttava),this._barIndex++;for(let e=0;e<t;e++){let e=new Ie;s.addVoice(e)}return s}beat(e){this.beatDuration();let t=new Be;if(e.addBeat(t),this._allowTuning=!this._currentStaff.isPercussion,this._sy===ze.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==ze.RParensis&&this._sy!==ze.Eof&&(this._allowTuning=!this._currentStaff.isPercussion,this.note(t)););this._sy!==ze.RParensis&&this.error("note-list",ze.RParensis,!0),this._sy=this.newSy()}else if(this._sy===ze.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===ze.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==ze.Number&&this.error("duration",ze.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||st.applyTuplet(t,this._currentTuplet);let s=1;this._sy===ze.Multiply&&(this._sy=this.newSy(),this._sy!==ze.Number?this.error("multiplier",ze.Number,!0):s=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let i=0;i<s-1;i++)e.addBeat(_e.clone(t));return!0}beatDuration(){if(this._sy===ze.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==ze.Number&&this.error("duration",ze.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===ze.LBrace)){for(this._sy=this.newSy();this._sy===ze.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==ze.Number&&this.error("duration-tuplet",ze.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",ze.String,!1)}this._sy!==ze.RBrace&&this.error("beat-duration",ze.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===ze.LBrace){for(this._sy=this.newSy();this._sy===ze.String;)this.applyBeatEffect(e)||this.error("beat-effects",ze.String,!1);this._sy!==ze.RBrace&&this.error("beat-effects",ze.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){let t=this._syData.toLowerCase();if("f"===t)e.fade=O.FadeIn;else if("fo"===t)e.fade=O.FadeOut;else if("vs"===t)e.fade=O.VolumeSwell;else if("v"===t)e.vibrato=B.Slight;else if("vw"===t)e.vibrato=B.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!==ze.String)return this.error("beat-text",ze.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=F.Up;else if("sd"===t)e.pickStroke=F.Down;else{if("tu"===t){if(this._sy=this.newSy(),this._sy!==ze.Number)return this.error("tuplet",ze.Number,!0),!1;const t=this._syData;if(this._sy=this.newSy(),this._sy===ze.Number){const s=this._syData;this._sy=this.newSy(),e.tupletNumerator=t,e.tupletDenominator=s}else st.applyTuplet(e,t);return!0}if("tb"===t||"tbe"===t){this._sy=this.newSy();let s="tbe"===t;for(this._sy===ze.String&&(e.whammyBarType=this.parseWhammyType(this._syData),this._sy=this.newSy()),this._sy===ze.String&&(e.whammyStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==ze.LParensis&&this.error("tremolobar-effect",ze.LParensis,!0),this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy();this._sy!==ze.RParensis&&this._sy!==ze.Eof;){let t=0,i=0;s?(this._sy!==ze.Number&&this.error("tremolobar-effect",ze.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==ze.Number&&this.error("tremolobar-effect",ze.Number,!0),i=this._syData):(this._sy!==ze.Number&&this.error("tremolobar-effect",ze.Number,!0),t=0,i=this._syData),e.addWhammyBarPoint(new se(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{let t=e.whammyBarPoints.length,s=60/t|0,i=0;for(;i<t;)e.whammyBarPoints[i].offset=Math.min(60,i*s),i++}}this._allowNegatives=!1,this._allowFloat=!1,this._sy!==ze.RParensis&&this.error("tremolobar-effect",ze.RParensis,!0)}else{if("bu"===t||"bd"===t||"au"===t||"ad"===t){switch(t){case"bu":e.brushType=u.BrushUp;break;case"bd":e.brushType=u.BrushDown;break;case"au":e.brushType=u.ArpeggioUp;break;case"ad":e.brushType=u.ArpeggioDown}return this._sy=this.newSy(),this._sy===ze.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();let t=this._syData,s=this.getChordId(this._currentStaff,t);if(!this._currentStaff.hasChord(s)){let e=new Te;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=f.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=f.BendGrace,this._sy=this.newSy()):e.graceType=f.BeforeBeat,!0;if("dy"===t){switch(this._sy=this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=m.PPP;break;case"pp":e.dynamics=m.PP;break;case"p":e.dynamics=m.P;break;case"mp":e.dynamics=m.MP;break;case"mf":e.dynamics=m.MF;break;case"f":e.dynamics=m.F;break;case"ff":e.dynamics=m.FF;break;case"fff":e.dynamics=m.FFF}this._currentDynamics=e.dynamics}else if("cre"===t)e.crescendo=p.Crescendo;else if("dec"===t)e.crescendo=p.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=g.Eighth,this._sy===ze.Number){switch(this._syData){case 8:default:e.tremoloSpeed=g.Eighth;break;case 16:e.tremoloSpeed=g.Sixteenth;break;case 32:e.tremoloSpeed=g.ThirtySecond}this._sy=this.newSy()}return!0}if("spd"===t){const t=new Z;return t.pedalType=l.Down,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spu"===t){const t=new Z;return t.pedalType=l.Up,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spe"===t){const t=new Z;return t.pedalType=l.Up,t.ratioPosition=1,this._sustainPedalToBeat.set(t,e),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=R.Finger,!0;if("glpt"===t)return this._sy=this.newSy(),e.golpe=R.Thumb,!0;if("waho"===t)return this._sy=this.newSy(),e.wahPedal=V.Open,!0;if("wahc"===t)return this._sy=this.newSy(),e.wahPedal=V.Closed,!0;if("barre"===t){if(this._sy=this.newSy(),this._sy!==ze.Number&&this.error("beat-barre",ze.Number,!0),e.barreFret=this._syData,e.barreShape=H.Full,this._sy=this.newSy(),this._sy===ze.String)switch(this._syData.toLowerCase()){case"full":e.barreShape=H.Full,this._sy=this.newSy();break;case"half":e.barreShape=H.Half,this._sy=this.newSy()}return!0}if("rasg"===t){switch(this._sy=this.newSy(),this._sy!==ze.String&&this.error("rasgueado",ze.String,!0),this._syData.toLowerCase()){case"ii":e.rasgueado=G.Ii;break;case"mi":e.rasgueado=G.Mi;break;case"miitriplet":e.rasgueado=G.MiiTriplet;break;case"miianapaest":e.rasgueado=G.MiiAnapaest;break;case"pmptriplet":e.rasgueado=G.PmpTriplet;break;case"pmpanapaest":e.rasgueado=G.PmpAnapaest;break;case"peitriplet":e.rasgueado=G.PeiTriplet;break;case"peianapaest":e.rasgueado=G.PeiAnapaest;break;case"paitriplet":e.rasgueado=G.PaiTriplet;break;case"paianapaest":e.rasgueado=G.PaiAnapaest;break;case"amitriplet":e.rasgueado=G.AmiTriplet;break;case"amianapaest":e.rasgueado=G.AmiAnapaest;break;case"ppp":e.rasgueado=G.Ppp;break;case"amii":e.rasgueado=G.Amii;break;case"amip":e.rasgueado=G.Amip;break;case"eami":e.rasgueado=G.Eami;break;case"eamii":e.rasgueado=G.Eamii;break;case"peami":e.rasgueado=G.Peami}return this._sy=this.newSy(),!0}if("ot"===t)this._sy=this.newSy(),this._sy!==ze.String&&this.error("beat-ottava",ze.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!==ze.String&&this.error("fermata",ze.Number,!0);const t=new et;return t.type=this.parseFermataFromString(this._syData),this._allowFloat=!0,this._sy=this.newSy(),this._sy===ze.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!==ze.String&&this.error("beam",ze.Number,!0),this._syData.toLowerCase()){case"invert":e.invertBeamDirection=!0;break;case"up":e.preferredBeamDirection=We.Up;break;case"down":e.preferredBeamDirection=We.Down;break;case"auto":e.beamingMode=W.Auto;break;case"split":e.beamingMode=W.ForceSplitToNext;break;case"merge":e.beamingMode=W.ForceMergeWithNext;break;case"splitsecondary":e.beamingMode=W.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===ze.Number?t=this._syData:this._sy===ze.String?t=q.getValue(this._syData):this.error("instrument-change",ze.Number,!0);const s=new $;s.isLinear=!1,s.type=r.Instrument,s.value=t,e.automations.push(s)}}}}}}return this._sy=this.newSy(),!0}parseBracketExtendMode(e){switch(e.toLowerCase()){case"nobrackets":return U.NoBrackets;case"groupstaves":default:return U.GroupStaves;case"groupsimilarinstruments":return U.GroupSimilarInstruments}}parseFermataFromString(e){switch(e.toLowerCase()){case"short":return Ge.Short;case"medium":default:return Ge.Medium;case"long":return Ge.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=S.Default;switch(this._sy){case ze.Number:i=this._syData,this._currentStaff.isPercussion&&!pe.instrumentArticulations.has(i)&&this.errorMessage(`Unknown percussion articulation ${i}`);break;case ze.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",ze.Number,!0);break;case ze.Tuning:0===e.index&&0===e.voice.index&&0===e.voice.bar.index&&this.makeCurrentStaffPitched();let o=this._syData;a=o.octave,r=o.tone.noteValue,this._accidentalMode==Xe.Explicit&&(n=o.tone.accidentalMode);break;default:return!1}this._sy=this.newSy();let o=-1===a&&this._currentStaff.tuning.length>0&&!this._currentStaff.isPercussion,h=-1;o&&(this._sy!==ze.Dot&&this.error("note",ze.Dot,!0),this._sy=this.newSy(),this._sy!==ze.Number&&this.error("note-string",ze.Number,!0),h=this._syData,(h<1||h>this._currentStaff.tuning.length)&&this.error("note-string",ze.Number,!1),this._sy=this.newSy());let l=new me;return o?(l.string=this._currentStaff.tuning.length-(h-1),l.isDead=t,l.isTieDestination=s,s||(l.fret=i)):this._currentStaff.isPercussion?l.percussionArticulation=i:(l.octave=a,l.tone=r,l.accidentalMode=n,l.isTieDestination=s),e.addNote(l),this.noteEffects(l),!0}noteEffects(e){if(this._sy===ze.LBrace){for(this._sy=this.newSy();this._sy===ze.String;){let t=this._syData.toLowerCase();if("b"===t||"be"===t){this._sy=this.newSy();let s="be"===t;for(this._sy===ze.String&&(e.bendType=this.parseBendType(this._syData),this._sy=this.newSy()),this._sy===ze.String&&(e.bendStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==ze.LParensis&&this.error("bend-effect",ze.LParensis,!0),this._sy=this.newSy();this._sy!==ze.RParensis&&this._sy!==ze.Eof;){let t=0,i=0;s?(this._sy!==ze.Number&&this.error("bend-effect-value",ze.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==ze.Number&&this.error("bend-effect-value",ze.Number,!0),i=this._syData):(this._sy!==ze.Number&&this.error("bend-effect-value",ze.Number,!0),i=this._syData),e.addBendPoint(new se(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{let e=i.length,t=60/(e-1)|0,s=0;for(;s<e;)i[s].offset=Math.min(60,s*t),s++}}this._sy!==ze.RParensis&&this.error("bend-effect",ze.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=b.Natural,e.harmonicValue=de.deltaFretToHarmonicValue(e.fret),this._sy=this.newSy();else if("ah"===t)e.harmonicType=b.Artificial,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("th"===t)e.harmonicType=b.Tap,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("ph"===t)e.harmonicType=b.Pinch,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("sh"===t)e.harmonicType=b.Semi,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("fh"===t)e.harmonicType=b.Feedback,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("tr"===t){this._sy=this.newSy(),this._sy!==ze.Number&&this.error("trill-effect",ze.Number,!0);let t=this._syData;this._sy=this.newSy();let s=g.Sixteenth;if(this._sy===ze.Number){switch(this._syData){case 16:default:s=g.Sixteenth;break;case 32:s=g.ThirtySecond;break;case 64:s=g.SixtyFourth}this._sy=this.newSy()}e.trillValue=t+e.stringTuning,e.trillSpeed=s}else if("v"===t)this._sy=this.newSy(),e.vibrato=B.Slight;else if("sl"===t)this._sy=this.newSy(),e.slideOutType=w.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=w.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=_.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=_.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=w.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=w.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=w.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=w.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=a.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=a.Heavy;else if("ten"===t)this._sy=this.newSy(),e.accentuated=a.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=y.Thumb;this._sy===ze.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.leftHandFinger=t}else if("rf"===t){this._sy=this.newSy();let t=y.Thumb;this._sy===ze.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else if("acc"===t)this._sy=this.newSy(),this._sy!==ze.String&&this.error("note-accidental",ze.String,!0),e.accidentalMode=de.parseAccidentalMode(this._syData),this._sy=this.newSy();else if("turn"===t)this._sy=this.newSy(),e.ornament=I.Turn;else if("iturn"===t)this._sy=this.newSy(),e.ornament=I.InvertedTurn;else if("umordent"===t)this._sy=this.newSy(),e.ornament=I.UpperMordent;else if("lmordent"===t)this._sy=this.newSy(),e.ornament=I.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!==ze.String&&this.error("slur",ze.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,ze.String,!1)}this._sy!==ze.RBrace&&this.error("note-effect",ze.RBrace,!1),this._sy=this.newSy()}}harmonicValue(e){return this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy(),this._sy===ze.Number&&(e=this._syData,this._sy=this.newSy()),this._allowNegatives=!1,this._allowFloat=!1,e}toFinger(e){switch(e){case 1:return y.Thumb;case 2:return y.IndexFinger;case 3:return y.MiddleFinger;case 4:return y.AnnularFinger;case 5:return y.LittleFinger}return y.Thumb}parseDuration(e){switch(e){case-4:return g.QuadrupleWhole;case-2:return g.DoubleWhole;case 1:return g.Whole;case 2:return g.Half;case 4:return g.Quarter;case 8:return g.Eighth;case 16:return g.Sixteenth;case 32:return g.ThirtySecond;case 64:return g.SixtyFourth;case 128:return g.OneHundredTwentyEighth;case 256:return g.TwoHundredFiftySixth;default:return g.Quarter}}parseBendStyle(e){switch(e.toLowerCase()){case"gradual":return d.Gradual;case"fast":return d.Fast;default:return d.Default}}parseBendType(e){switch(e.toLowerCase()){case"none":return c.None;case"custom":default:return c.Custom;case"bend":return c.Bend;case"release":return c.Release;case"bendrelease":return c.BendRelease;case"hold":return c.Hold;case"prebend":return c.Prebend;case"prebendbend":return c.PrebendBend;case"prebendrelease":return c.PrebendRelease}}barMeta(e){let t=!1,s=e.masterBar,i=!1;for(;!i&&this._sy===ze.MetaCommand;){t=!0;let a=this._syData.toLowerCase();if("ts"===a)this._sy=this.newSy(),this._sy===ze.String?"common"===this._syData.toLowerCase()?(s.timeSignatureCommon=!0,s.timeSignatureNumerator=4,s.timeSignatureDenominator=4,this._sy=this.newSy()):this.error("timesignature-numerator",ze.String,!0):(this._sy!==ze.Number&&this.error("timesignature-numerator",ze.Number,!0),s.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==ze.Number&&this.error("timesignature-denominator",ze.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!==ze.Number&&this.error("repeatclose",ze.Number,!0),this._syData>2048&&this.error("repeatclose",ze.Number,!1),s.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===a)if(this._sy=this.newSy(),this._sy===ze.LParensis){for(this._sy=this.newSy(),this._sy!==ze.Number&&this.error("alternateending",ze.Number,!0),this.applyAlternateEnding(s);this._sy===ze.Number;)this.applyAlternateEnding(s);this._sy!==ze.RParensis&&this.error("alternateending-list",ze.RParensis,!0),this._sy=this.newSy()}else this._sy!==ze.Number&&this.error("alternateending",ze.Number,!0),this.applyAlternateEnding(s);else if("ks"===a)this._sy=this.newSy(),this._sy!==ze.String&&this.error("keysignature",ze.String,!0),s.keySignature=this.parseKeySignature(this._syData),s.keySignatureType=this.parseKeySignatureType(this._syData),this._sy=this.newSy();else if("clef"===a){switch(this._sy=this.newSy(),this._sy){case ze.String:e.clef=this.parseClefFromString(this._syData);break;case ze.Number:e.clef=this.parseClefFromInt(this._syData);break;case ze.Tuning:let t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",ze.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!==ze.String&&this.error("section",ze.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==ze.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());let i=new Pe;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 ze.String:s.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case ze.Number:s.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",ze.String,!0)}this._sy=this.newSy()}else if("ac"===a)s.isAnacrusis=!0,this._sy=this.newSy();else if("db"===a)s.isDoubleBar=!0,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!==ze.String&&this.error("ottava",ze.String,!0),e.clefOttava=this.parseClefOttavaFromString(this._syData),this._sy=this.newSy();else if("simile"===a)this._sy=this.newSy(),this._sy!==ze.String&&this.error("simile",ze.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!==ze.Number&&this.error("scale",ze.Number,!0),s.displayScale=this._syData,e.displayScale=this._syData,this._sy=this.newSy();else if("width"===a)this._sy=this.newSy(),this._sy!==ze.Number&&this.error("width",ze.Number,!0),s.displayWidth=this._syData,e.displayWidth=this._syData,this._sy=this.newSy();else if(0===e.index)switch(this.handleStaffMeta()){case Ue.KnownStaffMeta:break;case Ue.UnknownStaffMeta:this.error("measure-effects",ze.String,!1);break;case Ue.EndOfMetaDetected:i=!0}else this.error("measure-effects",ze.String,!1)}if(0===s.index&&0===s.tempoAutomations.length){let e=new $;e.isLinear=!1,e.type=r.Tempo,e.value=this._score.tempo,e.text=this._score.tempoLabel,s.tempoAutomations.push(e)}return t}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!==ze.String&&this.error("direction",ze.String,!0),this._syData.toLowerCase()){case"fine":e.addDirection(He.TargetFine);break;case"segno":e.addDirection(He.TargetSegno);break;case"segnosegno":e.addDirection(He.TargetSegnoSegno);break;case"coda":e.addDirection(He.TargetCoda);break;case"doublecoda":e.addDirection(He.TargetDoubleCoda);break;case"dacapo":e.addDirection(He.JumpDaCapo);break;case"dacapoalcoda":e.addDirection(He.JumpDaCapoAlCoda);break;case"dacapoaldoublecoda":e.addDirection(He.JumpDaCapoAlDoubleCoda);break;case"dacapoalfine":e.addDirection(He.JumpDaCapoAlFine);break;case"dalsegno":e.addDirection(He.JumpDalSegno);break;case"dalsegnoalcoda":e.addDirection(He.JumpDalSegnoAlCoda);break;case"dalsegnoaldoublecoda":e.addDirection(He.JumpDalSegnoAlDoubleCoda);break;case"dalsegnoalfine":e.addDirection(He.JumpDalSegnoAlFine);break;case"dalsegnosegno":e.addDirection(He.JumpDalSegnoSegno);break;case"dalsegnosegnoalcoda":e.addDirection(He.JumpDalSegnoSegnoAlCoda);break;case"dalsegnosegnoaldoublecoda":e.addDirection(He.JumpDalSegnoSegnoAlDoubleCoda);break;case"dalsegnosegnoalfine":e.addDirection(He.JumpDalSegnoSegnoAlFine);break;case"dacoda":e.addDirection(He.JumpDaCoda);break;case"dadoublecoda":e.addDirection(He.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!==ze.Number&&this.error("tempo",ze.Number,!0);const e=new $;return e.isLinear=!1,e.type=r.Tempo,e.value=this._syData,this._sy=this.newSy(),this._sy===ze.String&&(e.text=this._syData,this._sy=this.newSy()),e}applyAlternateEnding(e){let t=this._syData;t<1&&this.error("alternateending",ze.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}parseWhammyType(e){switch(e.toLowerCase()){case"none":return A.None;case"custom":default:return A.Custom;case"dive":return A.Dive;case"dip":return A.Dip;case"hold":return A.Hold;case"predive":return A.Predive;case"predivedive":return A.PrediveDive}}}st.Eof=0,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"}(Je||(Je={}));class it{static parseEnum(t,s){switch(typeof t){case"string":const e=parseInt(t);return isNaN(e)?s[Object.keys(s).find((e=>e.toLowerCase()===t.toLowerCase()))]:e;case"number":return t;case"undefined":case"object":return null}throw new K(e.AlphaTabErrorType.Format,`Could not parse enum value '${t}'`)}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 at{constructor(e,t,s){this.text=e,this.startPos=t,this.endPos=s}}class rt{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 at(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 rt(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;){let 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,a=[];for(;;){if(!this._currentToken)return;let 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"}(Ye||(Ye={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(qe||(qe={}));class nt{reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=rt.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===qe.Bold}get isItalic(){return this.style===Ye.Italic}constructor(e,t,s=Ye.Plain,i=qe.Regular){this._cssScale=0,this._families=rt.parseFamilies(e),this._size=t,this._style=s,this._weight=i,this._css=this.toCssString()}withSize(e){return nt.withFamilyList(this._families,e,this._style,this._weight)}static withFamilyList(e,t,s=Ye.Plain,i=qe.Regular){const a=new nt("",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=>rt.quoteFont(e))).join(", "),this._css=t,this._cssScale=e}return this._css}static fromJson(e){if(e instanceof nt)return e;switch(typeof e){case"undefined":default:return null;case"object":{const t=e;let s=t.get("families"),i=t.get("size"),a=it.parseEnum(t.get("style"),Ye),r=it.parseEnum(t.get("weight"),qe);return nt.withFamilyList(s,i,a,r)}case"string":{const t=new rt(e);t.parse();let s=t.families,i=t.size.toLowerCase(),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*parseFloat(i.substr(0,i.length-2)):i.endsWith("pt")?16*parseFloat(i.substr(0,i.length-2))/12:i.endsWith("px")?parseFloat(i.substr(0,i.length-2)):12}catch(e){a=12}}let r=Ye.Plain;"italic"===t.style&&(r=Ye.Italic);let n=qe.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=qe.Bold}return nt.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}}!function(e){e[e.SingleTrackMultiChannel=0]="SingleTrackMultiChannel",e[e.MultiTrack=1]="MultiTrack"}(je||(je={}));class ot{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){let t=Oe.empty(),s=0;for(let e of this.events){let i=e.tick-s;ht.writeVariableInt(t,i),e.writeTo(t),s=e.tick}const i=new Uint8Array([77,84,114,107]);e.write(i,0,i.length);let a=t.toArray();Re.writeInt32BE(e,a.length),e.write(a,0,a.length)}}class ht{constructor(){this.format=je.SingleTrackMultiChannel,this.division=te.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 ot)}addEvent(e){this.format==je.SingleTrackMultiChannel?(this.ensureTracks(1),this.tracks[0].addEvent(e)):(this.ensureTracks(e.track+1),this.tracks[e.track].addEvent(e))}toBinary(){let e=Oe.empty();return this.writeTo(e),e.toArray()}writeTo(e){let t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),Re.writeInt32BE(e,6),Re.writeInt16BE(e,this.format),Re.writeInt16BE(e,this.tracks.length),Re.writeInt16BE(e,this.division);for(const t of this.tracks)t.writeTo(e)}static writeVariableInt(e,t){let s=new Uint8Array(4),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"}(Ke||(Ke={}));class lt{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 dt extends lt{constructor(e,t,s,i,a,r){super(e,t,Ke.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),ht.writeVariableInt(e,4),e.writeByte(255&this.numerator),e.writeByte(255&this.denominatorIndex),e.writeByte(255&this.midiClocksPerMetronomeClick),e.writeByte(255&this.thirtySecondNodesInQuarter)}}class ct extends lt{constructor(e,t,s){super(e,t,s)}writeTo(e){e.writeByte(240);const t=Oe.withCapacity(16);t.writeByte(ct.AlphaTabManufacturerId),this.writeEventData(t),t.writeByte(247),ht.writeVariableInt(e,t.length),t.copyTo(e)}}ct.AlphaTabManufacturerId=125,ct.MetronomeEventId=0,ct.RestEventId=1;class ut extends ct{constructor(e,t,s,i,a){super(e,t,Ke.AlphaTabMetronome),this.isMetronome=!0,this.metronomeNumerator=s,this.metronomeDurationInMilliseconds=a,this.metronomeDurationInTicks=i}writeEventData(e){e.writeByte(ct.MetronomeEventId),e.writeByte(this.metronomeNumerator),Re.writeInt32LE(e,this.metronomeDurationInTicks),Re.writeInt32LE(e,this.metronomeDurationInMilliseconds)}}class pt extends ct{constructor(e,t,s){super(e,t,Ke.AlphaTabRest),this.channel=s}writeEventData(e){e.writeByte(ct.RestEventId),e.writeByte(this.channel)}}class gt extends lt{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 mt extends gt{constructor(e,t,s,i,a){super(e,t,Ke.NoteOn,s,i,a)}writeTo(e){e.writeByte(15&this.channel|144),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class ft extends gt{constructor(e,t,s,i,a){super(e,t,Ke.NoteOff,s,i,a)}writeTo(e){e.writeByte(15&this.channel|128),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class yt extends lt{constructor(e,t,s,i,a){super(e,t,Ke.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 bt extends lt{constructor(e,t,s,i){super(e,t,Ke.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 St extends lt{constructor(e,t){super(0,e,Ke.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 _t extends lt{constructor(e,t,s,i){super(e,t,Ke.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 wt extends lt{constructor(e,t,s,i,a){super(e,t,Ke.PerNotePitchBend),this.channel=s,this.noteKey=i,this.value=a}writeTo(t){throw new K(e.AlphaTabErrorType.General,"Note Bend (Midi2.0) events cannot be exported to SMF1.0")}}class Bt extends lt{constructor(e,t){super(e,t,Ke.EndOfTrack)}writeTo(e){e.writeByte(255),e.writeByte(47),e.writeByte(0)}}class Tt{constructor(){this.copyrightFont=new nt(Tt.sansFont,12,Ye.Plain,qe.Bold),this.titleFont=new nt(Tt.serifFont,32,Ye.Plain),this.subTitleFont=new nt(Tt.serifFont,20,Ye.Plain),this.wordsFont=new nt(Tt.serifFont,15,Ye.Plain),this.effectFont=new nt(Tt.serifFont,12,Ye.Italic),this.timerFont=new nt(Tt.serifFont,12,Ye.Plain),this.directionsFont=new nt(Tt.serifFont,14,Ye.Plain),this.fretboardNumberFont=new nt(Tt.sansFont,11,Ye.Plain),this.numberedNotationFont=new nt(Tt.sansFont,16,Ye.Plain),this.numberedNotationGraceFont=new nt(Tt.sansFont,14,Ye.Plain),this.tablatureFont=new nt(Tt.sansFont,13,Ye.Plain),this.graceFont=new nt(Tt.sansFont,11,Ye.Plain),this.staffLineColor=new Ee(165,165,165,255),this.barSeparatorColor=new Ee(34,34,17,255),this.barNumberFont=new nt(Tt.sansFont,11,Ye.Plain),this.barNumberColor=new Ee(200,0,0,255),this.fingeringFont=new nt(Tt.serifFont,14,Ye.Plain),this.inlineFingeringFont=new nt(Tt.serifFont,12,Ye.Plain),this.markerFont=new nt(Tt.serifFont,14,Ye.Plain,qe.Bold),this.mainGlyphColor=new Ee(0,0,0,255),this.secondaryGlyphColor=new Ee(0,0,0,100),this.scoreInfoColor=new Ee(0,0,0,255)}}Tt.sansFont="Arial, sans-serif",Tt.serifFont="Georgia, serif",e.SystemsLayoutMode=void 0,(Qe=e.SystemsLayoutMode||(e.SystemsLayoutMode={}))[Qe.Automatic=0]="Automatic",Qe[Qe.UseModelLayout=1]="UseModelLayout";class kt{constructor(){this.scale=1,this.stretchForce=1,this.layoutMode=e.LayoutMode.Page,this.staveProfile=e.StaveProfile.Default,this.barsPerRow=-1,this.startBar=1,this.barCount=-1,this.barCountPerPartial=10,this.justifyLastSystem=!1,this.resources=new Tt,this.padding=[35,35],this.firstSystemPaddingTop=5,this.systemPaddingTop=10,this.systemPaddingBottom=20,this.lastSystemPaddingBottom=0,this.systemLabelPaddingLeft=0,this.systemLabelPaddingRight=5,this.accoladeBarPaddingRight=3,this.notationStaffPaddingTop=5,this.notationStaffPaddingBottom=5,this.effectStaffPaddingTop=0,this.effectStaffPaddingBottom=0,this.firstStaffPaddingLeft=6,this.staffPaddingLeft=2,this.systemsLayoutMode=e.SystemsLayoutMode.Automatic}}class Nt{constructor(){this.encoding="utf-8",this.mergePartGroupsInMusicXml=!1,this.beatTextAsLyrics=!1}}e.ScrollMode=void 0,($e=e.ScrollMode||(e.ScrollMode={}))[$e.Off=0]="Off",$e[$e.Continuous=1]="Continuous",$e[$e.OffScreen=2]="OffScreen";class xt{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 vt{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}e.PlayerOutputMode=void 0,(Ze=e.PlayerOutputMode||(e.PlayerOutputMode={}))[Ze.WebAudioAudioWorklets=0]="WebAudioAudioWorklets",Ze[Ze.WebAudioScriptProcessor=1]="WebAudioScriptProcessor";class Pt{constructor(){this.soundFont=null,this.scrollElement="html,body",this.outputMode=e.PlayerOutputMode.WebAudioAudioWorklets,this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=e.ScrollMode.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new xt,this.slide=new vt,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}class Ct{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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(t,s,i){switch(s){case"scriptfile":return t.scriptFile=i,!0;case"fontdirectory":return t.fontDirectory=i,!0;case"file":return t.file=i,!0;case"tex":return t.tex=i,!0;case"tracks":return t.tracks=i,!0;case"enablelazyloading":return t.enableLazyLoading=i,!0;case"engine":return t.engine=i,!0;case"loglevel":return t.logLevel=it.parseEnum(i,e.LogLevel),!0;case"useworkers":return t.useWorkers=i,!0;case"includenotebounds":return t.includeNoteBounds=i,!0}return!1}}class Et{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("copyrightfont",nt.toJson(e.copyrightFont)),t.set("titlefont",nt.toJson(e.titleFont)),t.set("subtitlefont",nt.toJson(e.subTitleFont)),t.set("wordsfont",nt.toJson(e.wordsFont)),t.set("effectfont",nt.toJson(e.effectFont)),t.set("timerfont",nt.toJson(e.timerFont)),t.set("directionsfont",nt.toJson(e.directionsFont)),t.set("fretboardnumberfont",nt.toJson(e.fretboardNumberFont)),t.set("numberednotationfont",nt.toJson(e.numberedNotationFont)),t.set("numberednotationgracefont",nt.toJson(e.numberedNotationGraceFont)),t.set("tablaturefont",nt.toJson(e.tablatureFont)),t.set("gracefont",nt.toJson(e.graceFont)),t.set("stafflinecolor",Ee.toJson(e.staffLineColor)),t.set("barseparatorcolor",Ee.toJson(e.barSeparatorColor)),t.set("barnumberfont",nt.toJson(e.barNumberFont)),t.set("barnumbercolor",Ee.toJson(e.barNumberColor)),t.set("fingeringfont",nt.toJson(e.fingeringFont)),t.set("inlinefingeringfont",nt.toJson(e.inlineFingeringFont)),t.set("markerfont",nt.toJson(e.markerFont)),t.set("mainglyphcolor",Ee.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",Ee.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",Ee.toJson(e.scoreInfoColor)),t}static setProperty(e,t,s){switch(t){case"copyrightfont":return e.copyrightFont=nt.fromJson(s),!0;case"titlefont":return e.titleFont=nt.fromJson(s),!0;case"subtitlefont":return e.subTitleFont=nt.fromJson(s),!0;case"wordsfont":return e.wordsFont=nt.fromJson(s),!0;case"effectfont":return e.effectFont=nt.fromJson(s),!0;case"timerfont":return e.timerFont=nt.fromJson(s),!0;case"directionsfont":return e.directionsFont=nt.fromJson(s),!0;case"fretboardnumberfont":return e.fretboardNumberFont=nt.fromJson(s),!0;case"numberednotationfont":return e.numberedNotationFont=nt.fromJson(s),!0;case"numberednotationgracefont":return e.numberedNotationGraceFont=nt.fromJson(s),!0;case"tablaturefont":return e.tablatureFont=nt.fromJson(s),!0;case"gracefont":return e.graceFont=nt.fromJson(s),!0;case"stafflinecolor":return e.staffLineColor=Ee.fromJson(s),!0;case"barseparatorcolor":return e.barSeparatorColor=Ee.fromJson(s),!0;case"barnumberfont":return e.barNumberFont=nt.fromJson(s),!0;case"barnumbercolor":return e.barNumberColor=Ee.fromJson(s),!0;case"fingeringfont":return e.fingeringFont=nt.fromJson(s),!0;case"inlinefingeringfont":return e.inlineFingeringFont=nt.fromJson(s),!0;case"markerfont":return e.markerFont=nt.fromJson(s),!0;case"mainglyphcolor":return e.mainGlyphColor=Ee.fromJson(s),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=Ee.fromJson(s),!0;case"scoreinfocolor":return e.scoreInfoColor=Ee.fromJson(s),!0}return!1}}class Ft{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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",Et.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(t,s,i){switch(s){case"scale":return t.scale=i,!0;case"stretchforce":return t.stretchForce=i,!0;case"layoutmode":return t.layoutMode=it.parseEnum(i,e.LayoutMode),!0;case"staveprofile":return t.staveProfile=it.parseEnum(i,e.StaveProfile),!0;case"barsperrow":return t.barsPerRow=i,!0;case"startbar":return t.startBar=i,!0;case"barcount":return t.barCount=i,!0;case"barcountperpartial":return t.barCountPerPartial=i,!0;case"justifylastsystem":return t.justifyLastSystem=i,!0;case"padding":return t.padding=i,!0;case"firstsystempaddingtop":return t.firstSystemPaddingTop=i,!0;case"systempaddingtop":return t.systemPaddingTop=i,!0;case"systempaddingbottom":return t.systemPaddingBottom=i,!0;case"lastsystempaddingbottom":return t.lastSystemPaddingBottom=i,!0;case"systemlabelpaddingleft":return t.systemLabelPaddingLeft=i,!0;case"systemlabelpaddingright":return t.systemLabelPaddingRight=i,!0;case"accoladebarpaddingright":return t.accoladeBarPaddingRight=i,!0;case"notationstaffpaddingtop":return t.notationStaffPaddingTop=i,!0;case"notationstaffpaddingbottom":return t.notationStaffPaddingBottom=i,!0;case"effectstaffpaddingtop":return t.effectStaffPaddingTop=i,!0;case"effectstaffpaddingbottom":return t.effectStaffPaddingBottom=i,!0;case"firststaffpaddingleft":return t.firstStaffPaddingLeft=i,!0;case"staffpaddingleft":return t.staffPaddingLeft=i,!0;case"systemslayoutmode":return t.systemsLayoutMode=it.parseEnum(i,e.SystemsLayoutMode),!0}if(["resources"].indexOf(s)>=0)return Et.fromJson(t.resources,i),!0;for(const e of["resources"])if(0===s.indexOf(e)&&Et.setProperty(t.resources,s.substring(e.length),i))return!0;return!1}}class Dt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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(t,s,i){switch(s){case"notationmode":return t.notationMode=it.parseEnum(i,e.NotationMode),!0;case"fingeringmode":return t.fingeringMode=it.parseEnum(i,e.FingeringMode),!0;case"elements":return t.elements=new Map,it.forEach(i,((s,i)=>{t.elements.set(it.parseEnum(i,e.NotationElement),s)})),!0;case"rhythmmode":return t.rhythmMode=it.parseEnum(i,e.TabRhythmMode),!0;case"rhythmheight":return t.rhythmHeight=i,!0;case"transpositionpitches":return t.transpositionPitches=i,!0;case"displaytranspositionpitches":return t.displayTranspositionPitches=i,!0;case"smallgracetabnotes":return t.smallGraceTabNotes=i,!0;case"extendbendarrowsontiednotes":return t.extendBendArrowsOnTiedNotes=i,!0;case"extendlineeffectstobeatend":return t.extendLineEffectsToBeatEnd=i,!0;case"slurheight":return t.slurHeight=i,!0}return!1}}class Lt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 Mt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 It{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 At{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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",Mt.toJson(e.vibrato)),t.set("slide",It.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t.set("buffertimeinmilliseconds",e.bufferTimeInMilliseconds),t}static setProperty(t,s,i){switch(s){case"soundfont":return t.soundFont=i,!0;case"scrollelement":return t.scrollElement=i,!0;case"outputmode":return t.outputMode=it.parseEnum(i,e.PlayerOutputMode),!0;case"enableplayer":return t.enablePlayer=i,!0;case"enablecursor":return t.enableCursor=i,!0;case"enableanimatedbeatcursor":return t.enableAnimatedBeatCursor=i,!0;case"enableelementhighlighting":return t.enableElementHighlighting=i,!0;case"enableuserinteraction":return t.enableUserInteraction=i,!0;case"scrolloffsetx":return t.scrollOffsetX=i,!0;case"scrolloffsety":return t.scrollOffsetY=i,!0;case"scrollmode":return t.scrollMode=it.parseEnum(i,e.ScrollMode),!0;case"scrollspeed":return t.scrollSpeed=i,!0;case"nativebrowsersmoothscroll":return t.nativeBrowserSmoothScroll=i,!0;case"songbookbendduration":return t.songBookBendDuration=i,!0;case"songbookdipduration":return t.songBookDipDuration=i,!0;case"playtripletfeel":return t.playTripletFeel=i,!0;case"buffertimeinmilliseconds":return t.bufferTimeInMilliseconds=i,!0}if(["vibrato"].indexOf(s)>=0)return Mt.fromJson(t.vibrato,i),!0;for(const e of["vibrato"])if(0===s.indexOf(e)&&Mt.setProperty(t.vibrato,s.substring(e.length),i))return!0;if(["slide"].indexOf(s)>=0)return It.fromJson(t.slide,i),!0;for(const e of["slide"])if(0===s.indexOf(e)&&It.setProperty(t.slide,s.substring(e.length),i))return!0;return!1}}class Rt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("core",Ct.toJson(e.core)),t.set("display",Ft.toJson(e.display)),t.set("notation",Dt.toJson(e.notation)),t.set("importer",Lt.toJson(e.importer)),t.set("player",At.toJson(e.player)),t}static setProperty(e,t,s){if(["core",""].indexOf(t)>=0)return Ct.fromJson(e.core,s),!0;for(const i of["core",""])if(0===t.indexOf(i)&&Ct.setProperty(e.core,t.substring(i.length),s))return!0;if(["display",""].indexOf(t)>=0)return Ft.fromJson(e.display,s),!0;for(const i of["display",""])if(0===t.indexOf(i)&&Ft.setProperty(e.display,t.substring(i.length),s))return!0;if(["notation"].indexOf(t)>=0)return Dt.fromJson(e.notation,s),!0;for(const i of["notation"])if(0===t.indexOf(i)&&Dt.setProperty(e.notation,t.substring(i.length),s))return!0;if(["importer"].indexOf(t)>=0)return Lt.fromJson(e.importer,s),!0;for(const i of["importer"])if(0===t.indexOf(i)&&Lt.setProperty(e.importer,t.substring(i.length),s))return!0;if(["player"].indexOf(t)>=0)return At.fromJson(e.player,s),!0;for(const i of["player"])if(0===t.indexOf(i)&&At.setProperty(e.player,t.substring(i.length),s))return!0;return!1}}class Ot{constructor(){this.core=new vl,this.display=new kt,this.notation=new ie,this.importer=new Nt,this.player=new Pt}setSongBookModeSettings(){this.notation.notationMode=e.NotationMode.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=e.FingeringMode.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(e.NotationElement.ParenthesisOnTiedBends,!1),this.notation.elements.set(e.NotationElement.TabNotesOnTiedBends,!1),this.notation.elements.set(e.NotationElement.ZerosOnDiveWhammys,!0)}static get songBook(){let e=new Ot;return e.setSongBookModeSettings(),e}fillFromJson(e){Rt.fromJson(this,e)}}class Vt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 Ht{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=it.parseEnum(s,r),!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 Gt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=it.parseEnum(s,Ge),!0;case"length":return e.length=s,!0}return!1}}class Wt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("alternateendings",e.alternateEndings),t.set("keysignature",e.keySignature),t.set("keysignaturetype",e.keySignatureType),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),t.set("section",Vt.toJson(e.section)),t.set("tempoautomations",e.tempoAutomations.map((e=>Ht.toJson(e)))),null!==e.fermata){const s=new Map;t.set("fermata",s);for(const[t,i]of e.fermata)s.set(t.toString(),Gt.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"keysignature":return e.keySignature=it.parseEnum(s,P),!0;case"keysignaturetype":return e.keySignatureType=it.parseEnum(s,C),!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=it.parseEnum(s,E),!0;case"tempoautomations":e.tempoAutomations=[];for(const t of s){const s=new $;Ht.fromJson(s,t),e.tempoAutomations.push(s)}return!0;case"fermata":return e.fermata=new Map,it.forEach(s,((t,s)=>{const i=new et;Gt.fromJson(i,t),e.addFermata(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(it.parseEnum(t,He));return!0}return["section"].indexOf(t)>=0&&(s?(e.section=new Pe,Vt.fromJson(e.section,s)):e.section=null,!0)}}class zt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 Ut{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=>zt.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.toJson(t),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"accentuated":return e.accentuated=it.parseEnum(s,a),!0;case"bendtype":return e.bendType=it.parseEnum(s,c),!0;case"bendstyle":return e.bendStyle=it.parseEnum(s,d),!0;case"iscontinuedbend":return e.isContinuedBend=s,!0;case"bendpoints":if(s){e.bendPoints=[];for(const t of s){const s=new se;zt.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=it.parseEnum(s,b),!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=it.parseEnum(s,_),!0;case"slideouttype":return e.slideOutType=it.parseEnum(s,w),!0;case"vibrato":return e.vibrato=it.parseEnum(s,B),!0;case"istiedestination":return e.isTieDestination=s,!0;case"lefthandfinger":return e.leftHandFinger=it.parseEnum(s,y),!0;case"righthandfinger":return e.rightHandFinger=it.parseEnum(s,y),!0;case"trillvalue":return e.trillValue=s,!0;case"trillspeed":return e.trillSpeed=it.parseEnum(s,g),!0;case"durationpercent":return e.durationPercent=s,!0;case"accidentalmode":return e.accidentalMode=it.parseEnum(s,S),!0;case"dynamics":return e.dynamics=it.parseEnum(s,m),!0;case"ornament":return e.ornament=it.parseEnum(s,I),!0}return e.setProperty(t,s)}}class Xt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=>Ut.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=>Ht.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=>zt.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("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),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 me;Ut.fromJson(s,t),e.addNote(s)}return!0;case"isempty":return e.isEmpty=s,!0;case"whammystyle":return e.whammyStyle=it.parseEnum(s,d),!0;case"ottava":return e.ottava=it.parseEnum(s,o),!0;case"islegatoorigin":return e.isLegatoOrigin=s,!0;case"duration":return e.duration=it.parseEnum(s,g),!0;case"automations":e.automations=[];for(const t of s){const s=new $;Ht.fromJson(s,t),e.automations.push(s)}return!0;case"dots":return e.dots=s,!0;case"fade":return e.fade=it.parseEnum(s,O),!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=it.parseEnum(s,u),!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=it.parseEnum(s,A),!0;case"whammybarpoints":if(s){e.whammyBarPoints=[];for(const t of s){const s=new se;zt.fromJson(s,t),e.addWhammyBarPoint(s)}}return!0;case"vibrato":return e.vibrato=it.parseEnum(s,B),!0;case"chordid":return e.chordId=s,!0;case"gracetype":return e.graceType=it.parseEnum(s,f),!0;case"pickstroke":return e.pickStroke=it.parseEnum(s,F),!0;case"tremolospeed":return e.tremoloSpeed=it.parseEnum(s,g),!0;case"crescendo":return e.crescendo=it.parseEnum(s,p),!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"golpe":return e.golpe=it.parseEnum(s,R),!0;case"dynamics":return e.dynamics=it.parseEnum(s,m),!0;case"invertbeamdirection":return e.invertBeamDirection=s,!0;case"preferredbeamdirection":return e.preferredBeamDirection=it.parseEnum(s,We),!0;case"beamingmode":return e.beamingMode=it.parseEnum(s,W),!0;case"wahpedal":return e.wahPedal=it.parseEnum(s,V),!0;case"barrefret":return e.barreFret=s,!0;case"barreshape":return e.barreShape=it.parseEnum(s,H),!0;case"rasgueado":return e.rasgueado=it.parseEnum(s,G),!0;case"showtimer":return e.showTimer=s,!0;case"timer":return e.timer=s,!0}return!1}}class Jt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=>Xt.toJson(e)))),t.set("isempty",e.isEmpty),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 Be;Xt.fromJson(s,t),e.addBeat(s)}return!0;case"isempty":return e.isEmpty=s,!0}return!1}}class Yt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=it.parseEnum(s,l),!0}return!1}}class qt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=>Jt.toJson(e)))),t.set("similemark",e.simileMark),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t.set("sustainpedals",e.sustainPedals.map((e=>Yt.toJson(e)))),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"clef":return e.clef=it.parseEnum(s,n),!0;case"clefottava":return e.clefOttava=it.parseEnum(s,o),!0;case"voices":e.voices=[];for(const t of s){const s=new Ie;Jt.fromJson(s,t),e.addVoice(s)}return!0;case"similemark":return e.simileMark=it.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 Z;Yt.fromJson(s,t),e.sustainPedals.push(s)}return!0}return!1}}class jt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 Kt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 Qt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("bars",e.bars.map((e=>qt.toJson(e)))),null!==e.chords){const s=new Map;t.set("chords",s);for(const[t,i]of e.chords)s.set(t.toString(),jt.toJson(i))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",Kt.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 ee;qt.fromJson(s,t),e.addBar(s)}return!0;case"chords":return e.chords=new Map,it.forEach(s,((t,s)=>{const i=new Te;jt.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"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["stringtuning"].indexOf(t)>=0&&(Kt.fromJson(e.stringTuning,s),!0)}}class $t{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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 Zt{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=it.parseEnum(s,D),!0;case"noteheadhalf":return e.noteHeadHalf=it.parseEnum(s,D),!0;case"noteheadwhole":return e.noteHeadWhole=it.parseEnum(s,D),!0;case"techniquesymbol":return e.techniqueSymbol=it.parseEnum(s,D),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=it.parseEnum(s,M),!0;case"outputmidinumber":return e.outputMidiNumber=s,!0}return!1}}class es{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("staves",e.staves.map((e=>Qt.toJson(e)))),t.set("playbackinfo",$t.toJson(e.playbackInfo)),t.set("color",Ee.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),t.set("percussionarticulations",e.percussionArticulations.map((e=>Zt.toJson(e)))),t}static setProperty(e,t,s){switch(t){case"staves":e.staves=[];for(const t of s){const s=new Le;Qt.fromJson(s,t),e.addStaff(s)}return!0;case"color":return e.color=Ee.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"percussionarticulations":e.percussionArticulations=[];for(const t of s){const s=new ue;Zt.fromJson(s,t),e.percussionArticulations.push(s)}return!0}return["playbackinfo"].indexOf(t)>=0&&($t.fromJson(e.playbackInfo,s),!0)}}class ts{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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)}return 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}static setProperty(e,t,s){switch(t){case"hidedynamics":return e.hideDynamics=s,!0;case"bracketextendmode":return e.bracketExtendMode=it.parseEnum(s,U),!0;case"usesystemsignseparator":return e.useSystemSignSeparator=s,!0;case"globaldisplaytuning":return e.globalDisplayTuning=s,!0;case"pertrackdisplaytuning":return e.perTrackDisplayTuning=new Map,it.forEach(s,((t,s)=>{e.perTrackDisplayTuning.set(parseInt(s),t)})),!0;case"globaldisplaychorddiagramsontop":return e.globalDisplayChordDiagramsOnTop=s,!0;case"pertrackchorddiagramsontop":return e.perTrackChordDiagramsOnTop=new Map,it.forEach(s,((t,s)=>{e.perTrackChordDiagramsOnTop.set(parseInt(s),t)})),!0;case"singletracktracknamepolicy":return e.singleTrackTrackNamePolicy=it.parseEnum(s,X),!0;case"multitracktracknamepolicy":return e.multiTrackTrackNamePolicy=it.parseEnum(s,X),!0;case"firstsystemtracknamemode":return e.firstSystemTrackNameMode=it.parseEnum(s,J),!0;case"othersystemstracknamemode":return e.otherSystemsTrackNameMode=it.parseEnum(s,J),!0;case"firstsystemtracknameorientation":return e.firstSystemTrackNameOrientation=it.parseEnum(s,Y),!0;case"othersystemstracknameorientation":return e.otherSystemsTrackNameOrientation=it.parseEnum(s,Y),!0}return!1}}class ss{static fromJson(e,t){t&&it.forEach(t,((t,s)=>this.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=>Wt.toJson(e)))),t.set("tracks",e.tracks.map((e=>es.toJson(e)))),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("stylesheet",ts.toJson(e.stylesheet)),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 oe;Wt.fromJson(s,t),e.addMasterBar(s)}return!0;case"tracks":e.tracks=[];for(const t of s){const s=new Me;es.fromJson(s,t),e.addTrack(s)}return!0;case"defaultsystemslayout":return e.defaultSystemsLayout=s,!0;case"systemslayout":return e.systemsLayout=s,!0}return["stylesheet"].indexOf(t)>=0&&(ts.fromJson(e.stylesheet,s),!0)}}class is{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){let t=is.scoreToJsObject(e);return JSON.stringify(t,is.jsonReplacer)}static jsonToScore(e,t){return is.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return ss.toJson(e)}static jsObjectToScore(e,t){let s=new ve;return ss.fromJson(s,e),s.finish(t??new Ot),s}static settingsToJson(e){let t=is.settingsToJsObject(e);return JSON.stringify(t,is.jsonReplacer)}static jsonToSettings(e){return is.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return Rt.toJson(e)}static jsObjectToSettings(e){let t=new Ot;return Rt.fromJson(t,e),t}static jsObjectToMidiFile(e){let t=new ht;return it.forEach(e,((e,s)=>{switch(s){case"division":t.division=e;break;case"tracks":for(let s of e){let e=is.jsObjectToMidiTrack(s);t.tracks.push(e)}}})),t}static jsObjectToMidiTrack(e){let t=new ot;return it.forEach(e,((e,s)=>{if("events"===s)for(let s of e){let e=is.jsObjectToMidiEvent(s);t.events.push(e)}})),t}static jsObjectToMidiEvent(t){let s=it.getValue(t,"track"),i=it.getValue(t,"tick"),a=it.getValue(t,"type");switch(a){case Ke.TimeSignature:return new dt(s,i,it.getValue(t,"numerator"),it.getValue(t,"denominatorIndex"),it.getValue(t,"midiClocksPerMetronomeClick"),it.getValue(t,"thirdySecondNodesInQuarter"));case Ke.AlphaTabRest:return new pt(s,i,it.getValue(t,"channel"));case Ke.AlphaTabMetronome:return new ut(s,i,it.getValue(t,"metronomeNumerator"),it.getValue(t,"metronomeDurationInTicks"),it.getValue(t,"metronomeDurationInMilliseconds"));case Ke.NoteOn:return new mt(s,i,it.getValue(t,"channel"),it.getValue(t,"noteKey"),it.getValue(t,"noteVelocity"));case Ke.NoteOff:return new ft(s,i,it.getValue(t,"channel"),it.getValue(t,"noteKey"),it.getValue(t,"noteVelocity"));case Ke.ControlChange:return new yt(s,i,it.getValue(t,"channel"),it.getValue(t,"controller"),it.getValue(t,"value"));case Ke.ProgramChange:return new bt(s,i,it.getValue(t,"channel"),it.getValue(t,"program"));case Ke.TempoChange:return new St(i,it.getValue(t,"microSecondsPerQuarterNote"));case Ke.PitchBend:return new _t(s,i,it.getValue(t,"channel"),it.getValue(t,"value"));case Ke.PerNotePitchBend:return new wt(s,i,it.getValue(t,"channel"),it.getValue(t,"noteKey"),it.getValue(t,"value"));case Ke.EndOfTrack:return new Bt(s,i)}throw new K(e.AlphaTabErrorType.Format,"Unknown Midi Event type: "+a)}static midiFileToJsObject(e){const t=new Map;t.set("division",e.division);const s=[];for(let t of e.tracks)s.push(is.midiTrackToJsObject(t));return t.set("tracks",s),t}static midiTrackToJsObject(e){const t=new Map,s=[];for(let t of e.events)s.push(is.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 Ke.TimeSignature:t.set("numerator",e.numerator),t.set("denominatorIndex",e.denominatorIndex),t.set("midiClocksPerMetronomeClick",e.midiClocksPerMetronomeClick),t.set("thirdySecondNodesInQuarter",e.thirtySecondNodesInQuarter);break;case Ke.AlphaTabRest:t.set("channel",e.channel);break;case Ke.AlphaTabMetronome:t.set("metronomeNumerator",e.metronomeNumerator),t.set("metronomeDurationInMilliseconds",e.metronomeDurationInMilliseconds),t.set("metronomeDurationInTicks",e.metronomeDurationInTicks);break;case Ke.NoteOn:case Ke.NoteOff:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("noteVelocity",e.noteVelocity);break;case Ke.ControlChange:t.set("channel",e.channel),t.set("controller",e.controller),t.set("value",e.value);break;case Ke.ProgramChange:t.set("channel",e.channel),t.set("program",e.program);break;case Ke.TempoChange:t.set("microSecondsPerQuarterNote",e.microSecondsPerQuarterNote);break;case Ke.PitchBend:t.set("channel",e.channel),t.set("value",e.value);break;case Ke.PerNotePitchBend:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("value",e.value);case Ke.EndOfTrack:}return t}}var as,rs,ns,os=Object.freeze({__proto__:null,get AccentuationType(){return a},get AccidentalType(){return Je},Automation:$,get AutomationType(){return r},Bar:ee,get BarreShape(){return H},Beat:Be,get BeatBeamingMode(){return W},BendPoint:se,get BendStyle(){return d},get BendType(){return c},get BracketExtendMode(){return U},get BrushType(){return u},Chord:Te,get Clef(){return n},Color:Ee,get CrescendoType(){return p},get Duration(){return g},get DynamicValue(){return m},get FadeType(){return O},Fermata:et,get FermataType(){return Ge},get Fingers(){return y},Font:nt,get FontStyle(){return Ye},get FontWeight(){return qe},get GraceType(){return f},get HarmonicType(){return b},InstrumentArticulation:ue,JsonConverter:is,get KeySignature(){return P},get KeySignatureType(){return C},Lyrics:ke,MasterBar:oe,get MusicFontSymbol(){return D},Note:me,get NoteAccidentalMode(){return S},get NoteOrnament(){return I},get Ottavia(){return o},get PickStroke(){return F},PlaybackInformation:Fe,get Rasgueado(){return G},RenderStylesheet:Ne,RepeatGroup:xe,Score:ve,Section:Pe,get SimileMark(){return h},get SlideInType(){return _},get SlideOutType(){return w},Staff:Le,SustainPedalMarker:Z,get SustainPedalMarkerType(){return l},Track:Me,get TrackNameMode(){return J},get TrackNameOrientation(){return Y},get TrackNamePolicy(){return X},get TripletFeel(){return E},Tuning:De,TupletGroup:fe,get VibratoType(){return B},Voice:Ie,get WahPedal(){return V},get WhammyType(){return A}});class hs extends j{get name(){return"Guitar Pro 3-5"}constructor(){super(),this._versionNumber=0,this._globalTripletFeel=E.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._beatTextChunksByTrack=new Map,this._directionLookup=new Map}readScore(){if(this._directionLookup.clear(),this.readVersion(),this._score=new ve,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=ls.gpReadBool(this.data)?E.Triplet8th:E.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=ls.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=Re.readInt32LE(this.data),this._versionNumber>=510&&ls.gpReadBool(this.data),Re.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.readDirection(He.TargetCoda),this.readDirection(He.TargetDoubleCoda),this.readDirection(He.TargetSegno),this.readDirection(He.TargetSegnoSegno),this.readDirection(He.TargetFine),this.readDirection(He.JumpDaCapo),this.readDirection(He.JumpDaCapoAlCoda),this.readDirection(He.JumpDaCapoAlDoubleCoda),this.readDirection(He.JumpDaCapoAlFine),this.readDirection(He.JumpDalSegno),this.readDirection(He.JumpDalSegnoAlCoda),this.readDirection(He.JumpDalSegnoAlDoubleCoda),this.readDirection(He.JumpDalSegnoAlFine),this.readDirection(He.JumpDalSegnoSegno),this.readDirection(He.JumpDalSegnoSegnoAlCoda),this.readDirection(He.JumpDalSegnoSegnoAlDoubleCoda),this.readDirection(He.JumpDalSegnoSegnoAlFine),this.readDirection(He.JumpDaCoda),this.readDirection(He.JumpDaDoubleCoda),this.data.skip(4)),this._barCount=Re.readInt32LE(this.data),this._trackCount=Re.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0){const e=$.buildTempoAutomation(!1,0,this._score.tempo,2);e.text=this._score.tempoLabel,this._score.masterBars[0].tempoAutomations.push(e)}return 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=Re.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=ls.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(hs.VersionString))throw new Q("Unsupported format");e=e.substr(hs.VersionString.length+1);let t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*parseInt(e.substr(0,t))+parseInt(e.substr(t+1)),ne.debug(this.name,"Guitar Pro version "+e+" detected")}readScoreInformation(){this._score.title=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding);let e=Re.readInt32LE(this.data),t="";for(let s=0;s<e;s++)s>0&&(t+="\r\n"),t+=ls.gpReadStringIntUnused(this.data,this.settings.importer.encoding)?.toString();this._score.notices=t}readLyrics(){this._lyrics=[],this._lyricsTrack=Re.readInt32LE(this.data)-1;for(let e=0;e<5;e++){let e=new ke;e.startBar=Re.readInt32LE(this.data)-1,e.text=ls.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(30);for(let e=0;e<10;e++)ls.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){let t=new Fe;t.primaryChannel=e,t.secondaryChannel=e,t.program=Re.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]);let t=new oe,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,r=this.data.readByte();for(let e=0;e<8;e++){let t=1<<e;r>e&&!(i&t)&&(a|=t)}t.alternateEndings=a}if(32&s){let e=new Pe;e.text=ls.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",ls.gpReadColor(this.data,!1),t.section=e}if(64&s?(t.keySignature=Re.readSInt8(this.data),t.keySignatureType=this.data.readByte()):e&&(t.keySignature=e.keySignature,t.keySignatureType=e.keySignatureType),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=E.Triplet8th;break;case 2:t.tripletFeel=E.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=!!(128&s);const i=this._score.masterBars.length;if(this._directionLookup.has(i))for(const e of this._directionLookup.get(i))t.addDirection(e);this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){let e=new Me;e.ensureStaveCount(1),this._score.addTrack(e);let t=e.staves[0],s=this.data.readByte();e.name=ls.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));let i=Re.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){let t=Re.readInt32LE(this.data);i>e&&a.push(t)}t.stringTuning.tunings=a;let r=Re.readInt32LE(this.data),n=Re.readInt32LE(this.data)-1,o=Re.readInt32LE(this.data)-1;if(this.data.skip(4),n>=0&&n<this._playbackInfos.length){let i=this._playbackInfos[n];i.port=r,i.isSolo=!!(16&s),i.isMute=!!(32&s),i.secondaryChannel=o,q.isGuitar(i.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=i}if(t.capo=Re.readInt32LE(this.data),e.color=ls.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),ls.gpReadStringIntByte(this.data,this.settings.importer.encoding),ls.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){let t=new ee,s=e.staves[0];s.isPercussion&&(t.clef=n.Neutral),s.addBar(t);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){let s=Re.readInt32LE(this.data);if(0===s)return;let i=new Ie;t.addVoice(i);for(let a=0;a<s;a++)this.readBeat(e,t,i)}readBeat(e,t,s){let i=new Be,a=this.data.readByte();if(1&a&&(i.dots=1),64&a){let e=this.data.readByte();i.isEmpty=!(2&e)}switch(s.addBeat(i),Re.readSInt8(this.data)){case-2:i.duration=g.Whole;break;case-1:i.duration=g.Half;break;case 0:i.duration=g.Quarter;break;case 1:i.duration=g.Eighth;break;case 2:i.duration=g.Sixteenth;break;case 3:i.duration=g.ThirtySecond;break;case 4:i.duration=g.SixtyFourth;break;default:i.duration=g.Quarter}if(32&a)switch(i.tupletNumerator=Re.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);let r=this.settings.importer.beatTextAsLyrics&&e.index!==this._lyricsTrack;if(4&a){const t=ls.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=b.None;8&a&&(n=this.readBeatEffects(i)),16&a&&this.readMixTableChange(i);let 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!==b.None&&(r.harmonicType=n,r.harmonicType===b.Natural&&(r.harmonicValue=de.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){const e=Re.readInt16LE(this.data);if(1&e&&i.index>0&&(s.beats[i.index-1].beamingMode=W.ForceSplitToNext),2&e&&(i.preferredBeamDirection=We.Down),4&e&&i.index>0&&(s.beats[i.index-1].beamingMode=W.ForceMergeWithNext),8&e&&(i.preferredBeamDirection=We.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=W.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){let t=new Te,s=de.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=ls.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Re.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Re.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}let 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=ls.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Re.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Re.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}let 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=ls.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=Re.readInt32LE(this.data);for(let s=0;s<6;s++){let i=Re.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}this.data.skip(36)}else{let s=this._versionNumber>=406?7:6;if(t.name=ls.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=Re.readInt32LE(this.data),t.firstFret>0)for(let i=0;i<s;i++){let s=Re.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){let t=this.data.readByte(),s=0;if(this._versionNumber>=400&&(s=this.data.readByte()),16&t&&(e.fade=O.FadeIn),(this._versionNumber<400&&1&t||2&t)&&(e.vibrato=B.Slight),1&s&&(e.rasgueado=G.Ii),32&t&&this._versionNumber>=400){switch(Re.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(Re.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=u.BrushUp,e.brushDuration=hs.toStrokeValue(t)):s>0&&(e.brushType=u.BrushDown,e.brushDuration=hs.toStrokeValue(s))}if(2&s)switch(Re.readSInt8(this.data)){case 0:e.pickStroke=F.None;break;case 1:e.pickStroke=F.Up;break;case 2:e.pickStroke=F.Down}if(this._versionNumber<400){if(4&t)return b.Natural;if(8&t)return b.Artificial}return b.None}readTremoloBarEffect(e){this.data.readByte(),Re.readInt32LE(this.data);let t=Re.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new se(0,0);t.offset=Re.readInt32LE(this.data),t.value=Re.readInt32LE(this.data)/hs.BendStep|0,ls.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){let t=new ds;t.instrument=Re.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=Re.readSInt8(this.data),t.balance=Re.readSInt8(this.data);let s=Re.readSInt8(this.data),i=Re.readSInt8(this.data),a=Re.readSInt8(this.data),n=Re.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=ls.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=Re.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(),n>=0&&this.data.readByte(),t.tempo>=0&&(t.duration=Re.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500){const t=Re.readSInt8(this.data);t>=100?e.wahPedal=V.Closed:t>=0&&(e.wahPedal=V.Open)}if(this._versionNumber>=510&&(ls.gpReadStringIntByte(this.data,this.settings.importer.encoding),ls.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){let s=new $;s.isLinear=!0,s.type=r.Volume,s.value=t.volume,e.automations.push(s)}if(t.balance>=0){let s=new $;s.isLinear=!0,s.type=r.Balance,s.value=t.balance,e.automations.push(s)}if(t.instrument>=0){let s=new $;s.isLinear=!0,s.type=r.Instrument,s.value=t.instrument,e.automations.push(s)}if(t.tempo>=0){let s=new $;s.isLinear=!0,s.type=r.Tempo,s.value=t.tempo,e.automations.push(s),e.voice.bar.masterBar.tempoAutomations.push(s)}}readNote(e,t,s,i,r){let n=new me;n.string=t.staff.tuning.length-r;let o=this.data.readByte();if(2&o?n.accentuated=a.Heavy:64&o&&(n.accentuated=a.Normal),n.isGhost=!!(4&o),32&o){let e=this.data.readByte();3===e?n.isDead=!0:2===e&&(n.isTieDestination=!0)}if(1&o&&this._versionNumber<500&&(this.data.readByte(),this.data.readByte()),16&o){let e=Re.readSInt8(this.data);n.dynamics=this.toDynamicValue(e),i.dynamics=n.dynamics}32&o&&(n.fret=Re.readSInt8(this.data)),128&o&&(n.leftHandFinger=Re.readSInt8(this.data),n.rightHandFinger=Re.readSInt8(this.data));let h=!1;if(this._versionNumber>=500){1&o&&(n.durationPercent=Re.readFloat64BE(this.data)),h=!!(2&this.data.readByte())}if(i.addNote(n),8&o&&this.readNoteEffects(e,s,i,n),t.staff.isPercussion&&(n.percussionArticulation=n.fret,n.string=-1,n.fret=-1),h){const e=De.defaultAccidentals[n.realValueWithoutHarmonic%12];"#"===e?n.accidentalMode=S.ForceFlat:"b"===e&&(n.accidentalMode=S.ForceSharp)}return n}toDynamicValue(e){switch(e){case 1:return m.PPP;case 2:return m.PP;case 3:return m.P;case 4:return m.MP;case 5:return m.MF;case 6:default:return m.F;case 7:return m.FF;case 8:return m.FFF}}readNoteEffects(e,t,s,i){let a=this.data.readByte(),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=w.Shift),16&r&&this.readArtificialHarmonic(i),32&r&&this.readTrill(i),i.isLetRing=!!(8&a),i.isHammerPullOrigin=!!(2&a),64&r&&(i.vibrato=B.Slight),i.isPalmMute=!!(2&r),i.isStaccato=!!(1&r)}readBend(e){this.data.readByte(),Re.readInt32LE(this.data);let t=Re.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new se(0,0);t.offset=Re.readInt32LE(this.data),t.value=Re.readInt32LE(this.data)/hs.BendStep|0,ls.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){let s=new Be,i=new me;switch(i.string=t.string,i.fret=Re.readSInt8(this.data),s.duration=g.ThirtySecond,s.dynamics=this.toDynamicValue(Re.readSInt8(this.data)),Re.readSInt8(this.data)){case 0:case 2:break;case 1:i.slideOutType=w.Legato,i.slideTarget=t;break;case 3:i.isHammerPullOrigin=!0}if(i.dynamics=s.dynamics,this.data.skip(1),this._versionNumber<500)s.graceType=f.BeforeBeat;else{let e=this.data.readByte();i.isDead=!!(1&e),s.graceType=2&e?f.OnBeat:f.BeforeBeat}e.addGraceBeat(s),s.addNote(i)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=g.Eighth;break;case 2:e.tremoloSpeed=g.Sixteenth;break;case 3:e.tremoloSpeed=g.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){let t=Re.readSInt8(this.data);1&t?e.slideOutType=w.Shift:2&t?e.slideOutType=w.Legato:4&t?e.slideOutType=w.OutDown:8&t&&(e.slideOutType=w.OutUp),16&t?e.slideInType=_.IntoFromBelow:32&t&&(e.slideInType=_.IntoFromAbove)}else{switch(Re.readSInt8(this.data)){case 1:e.slideOutType=w.Shift;break;case 2:e.slideOutType=w.Legato;break;case 3:e.slideOutType=w.OutDown;break;case 4:e.slideOutType=w.OutUp;break;case-1:e.slideInType=_.IntoFromBelow;break;case-2:e.slideInType=_.IntoFromAbove}}}readArtificialHarmonic(e){let t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=b.Natural,e.harmonicValue=de.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=b.Artificial;break;case 3:e.harmonicType=b.Tap,e.harmonicValue=de.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=b.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=b.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=b.Natural;break;case 3:e.harmonicType=b.Tap;break;case 4:e.harmonicType=b.Pinch;break;case 5:e.harmonicType=b.Semi;break;case 15:case 17:case 22:e.harmonicType=b.Artificial}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=g.Sixteenth;break;case 2:e.trillSpeed=g.ThirtySecond;break;case 3:e.trillSpeed=g.SixtyFourth}}}hs.VersionString="FICHIER GUITAR PRO ",hs.BendStep=25;class ls{static gpReadColor(e,t=!1){let s=e.readByte(),i=e.readByte(),a=e.readByte(),r=255;return t?r=e.readByte():e.skip(1),new Ee(s,i,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),ls.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return ls.gpReadString(e,Re.readInt32LE(e),t)}static gpReadStringIntByte(e,t){let s=Re.readInt32LE(e)-1;return e.readByte(),ls.gpReadString(e,s,t)}static gpReadString(e,t,s){let i=new Uint8Array(t);return e.read(i,0,i.length),Re.toString(i,s)}static gpWriteString(e,t){const s=Re.stringToBytes(t);e.writeByte(t.length),e.write(s,0,s.length)}static gpReadStringByteLength(e,t,s){let i=e.readByte(),a=ls.gpReadString(e,i,s);return i<t&&e.skip(t-i),a}}class ds{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class cs{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"}(as||(as={}));class us{constructor(e){this._types=new Map,this.raw=new Map,e&&this.read(e)}read(e){let t=Oe.fromBuffer(e),s=Re.readInt32BE(t);for(let e=0;e<s;e++){let e=ls.gpReadString(t,t.readByte(),"utf-8"),s=t.readByte();switch(this._types.set(e,s),s){case as.Boolean:let s=1===t.readByte();this.addValue(e,s);break;case as.Integer:let i=Re.readInt32BE(t);this.addValue(e,i);break;case as.Float:let a=Re.readFloat32BE(t);this.addValue(e,a);break;case as.String:let r=ls.gpReadString(t,Re.readInt16BE(t),"utf-8");this.addValue(e,r);break;case as.Point:let n=Re.readInt32BE(t),o=Re.readInt32BE(t);this.addValue(e,new se(n,o));break;case as.Size:let h=Re.readInt32BE(t),l=Re.readInt32BE(t);this.addValue(e,new se(h,l));break;case as.Rectangle:let d=new cs;d.x=Re.readInt32BE(t),d.y=Re.readInt32BE(t),d.w=Re.readInt32BE(t),d.h=Re.readInt32BE(t),this.addValue(e,d);break;case as.Color:let c=ls.gpReadColor(t,!0);this.addValue(e,c)}}}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=X.Hidden);break;case"System/showTrackNameMulti":s||(e.stylesheet.multiTrackTrackNamePolicy=X.Hidden);break;case"System/trackNameModeSingle":if(e.stylesheet.singleTrackTrackNamePolicy!==X.Hidden)switch(s){case 0:case 1:e.stylesheet.singleTrackTrackNamePolicy=X.FirstSystem;break;case 2:e.stylesheet.singleTrackTrackNamePolicy=X.AllSystems}break;case"System/trackNameModeMulti":if(e.stylesheet.multiTrackTrackNamePolicy!==X.Hidden)switch(s){case 0:case 1:e.stylesheet.multiTrackTrackNamePolicy=X.FirstSystem;break;case 2:e.stylesheet.multiTrackTrackNamePolicy=X.AllSystems}break;case"System/shortTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameMode=s?J.ShortName:J.FullName;break;case"System/shortTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameMode=s?J.ShortName:J.FullName;break;case"System/horizontalTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameOrientation=s?Y.Horizontal:Y.Vertical;break;case"System/horizontalTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameOrientation=s?Y.Horizontal:Y.Vertical}}addValue(e,t,s){this.raw.set(e,t),void 0!==s&&this._types.set(e,s)}writeTo(e){Re.writeInt32BE(e,this.raw.size);for(const[t,s]of this.raw){const i=this.getDataType(t,s);switch(ls.gpWriteString(e,t),e.writeByte(i),i){case as.Boolean:e.writeByte(s?1:0);break;case as.Integer:Re.writeInt32BE(e,s);break;case as.Float:Re.writeFloat32BE(e,s);break;case as.String:const t=Re.stringToBytes(s);Re.writeInt16BE(e,t.length),e.write(t,0,t.length);break;case as.Point:case as.Size:Re.writeInt32BE(e,s.offset),Re.writeInt32BE(e,s.value);break;case as.Rectangle:Re.writeInt32BE(e,s.x),Re.writeInt32BE(e,s.y),Re.writeInt32BE(e,s.w),Re.writeInt32BE(e,s.h);break;case as.Color:e.writeByte(s.r),e.writeByte(s.g),e.writeByte(s.b),e.writeByte(s.a)}}}getDataType(t,s){if(this._types.has(t))return this._types.get(t);const i=typeof s;switch(typeof s){case"string":return as.String;case"number":return s==(0|s)?as.Integer:as.Float;case"object":if(s instanceof se)return as.Point;if(s instanceof cs)return as.Rectangle;if(s instanceof Ee)return as.Color}throw new K(e.AlphaTabErrorType.General,`Unknown value type in BinaryStylesheet: ${i}`)}static writeForScore(e){const t=new us;switch(t.addValue("StandardNotation/hideDynamics",e.stylesheet.hideDynamics,as.Boolean),t.addValue("System/bracketExtendMode",e.stylesheet.bracketExtendMode,as.Integer),t.addValue("Global/useSystemSignSeparator",e.stylesheet.useSystemSignSeparator,as.Boolean),t.addValue("Global/DisplayTuning",e.stylesheet.globalDisplayTuning,as.Boolean),t.addValue("Global/DrawChords",e.stylesheet.globalDisplayChordDiagramsOnTop,as.Boolean),e.stylesheet.singleTrackTrackNamePolicy){case X.Hidden:t.addValue("System/showTrackNameSingle",!1,as.Boolean);break;case X.FirstSystem:t.addValue("System/trackNameModeSingle",0,as.Integer);break;case X.AllSystems:t.addValue("System/trackNameModeSingle",2,as.Integer)}switch(e.stylesheet.multiTrackTrackNamePolicy){case X.Hidden:t.addValue("System/trackNameModeMulti",!1,as.Boolean);break;case X.FirstSystem:t.addValue("System/trackNameModeMulti",0,as.Integer);break;case X.AllSystems:t.addValue("System/trackNameModeMulti",2,as.Integer)}switch(e.stylesheet.firstSystemTrackNameMode){case J.FullName:t.addValue("System/shortTrackNameOnFirstSystem",!1,as.Boolean);break;case J.ShortName:t.addValue("System/shortTrackNameOnFirstSystem",!0,as.Boolean)}switch(e.stylesheet.otherSystemsTrackNameMode){case J.FullName:t.addValue("System/shortTrackNameOnOtherSystems",!1,as.Boolean);break;case J.ShortName:t.addValue("System/shortTrackNameOnOtherSystems",!0,as.Boolean)}switch(e.stylesheet.firstSystemTrackNameOrientation){case Y.Horizontal:t.addValue("System/horizontalTrackNameOnFirstSystem",!0,as.Boolean);break;case Y.Vertical:t.addValue("System/horizontalTrackNameOnFirstSystem",!1,as.Boolean)}switch(e.stylesheet.otherSystemsTrackNameOrientation){case Y.Horizontal:t.addValue("System/horizontalTrackNameOnOtherSystems",!0,as.Boolean);break;case Y.Vertical:t.addValue("System/horizontalTrackNameOnOtherSystems",!1,as.Boolean)}const s=Oe.withCapacity(128);return t.writeTo(s),s.toArray()}}!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"}(rs||(rs={}));class ps{constructor(){this.nodeType=rs.None,this.localName=null,this.value=null,this.childNodes=[],this.attributes=new Map,this.firstChild=null,this.firstElement=null}addChild(e){this.childNodes.push(e),this.firstChild=e,e.nodeType!==rs.Element&&e.nodeType!==rs.CDATA||(this.firstElement=e)}getAttribute(e){return this.attributes.has(e)?this.attributes.get(e):""}getElementsByTagName(e,t=!1){let s=[];return this.searchElementsByTagName(this.childNodes,s,e,t),s}searchElementsByTagName(e,t,s,i=!1){for(let a of e)a&&a.nodeType===rs.Element&&a.localName===s&&t.push(a),i&&this.searchElementsByTagName(a.childNodes,t,s,!0)}findChildElement(e){for(let t of this.childNodes)if(t&&t.nodeType===rs.Element&&t.localName===e)return t;return null}addElement(e){const t=new ps;return t.nodeType=rs.Element,t.localName=e,this.addChild(t),t}get innerText(){if(this.nodeType===rs.Element||this.nodeType===rs.Document){if(this.firstElement&&this.firstElement.nodeType===rs.CDATA)return this.firstElement.innerText;let e="";for(let t of this.childNodes)e+=t.innerText?.toString();return e.trim()}return this.value??""}set innerText(e){const t=new ps;t.nodeType=rs.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new ps;t.nodeType=rs.CDATA,t.value=e,this.childNodes=[t]}}class gs extends K{constructor(t,s,i){super(e.AlphaTabErrorType.Format,t),this.pos=0,this.xml=s,this.pos=i,Object.setPrototypeOf(this,gs.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"}(ns||(ns={}));class ms{static parse(e,t,s){let i=e.charCodeAt(t),a=ns.Begin,r=ns.Begin,n=0,o="",h=ns.Begin,l=null,d=null,c=0,u=0;for(;t<e.length;){switch(i=e.charCodeAt(t),a){case ns.IgnoreSpaces:switch(i){case ms.CharCodeLF:case ms.CharCodeCR:case ms.CharCodeTab:case ms.CharCodeSpace:break;default:a=r;continue}break;case ns.Begin:if(i!==ms.CharCodeLowerThan){n=t,a=ns.Pcdata;continue}a=ns.IgnoreSpaces,r=ns.BeginNode;break;case ns.Pcdata:if(i===ms.CharCodeLowerThan){o+=e.substr(n,t-n);let i=new ps;i.nodeType=rs.Text,i.value=o,o="",s.addChild(i),a=ns.IgnoreSpaces,r=ns.BeginNode}else i===ms.CharCodeAmp&&(o+=e.substr(n,t-n),a=ns.Escape,h=ns.Pcdata,n=t+1);break;case ns.Cdata:if(i===ms.CharCodeBrackedClose&&e.charCodeAt(t+1)===ms.CharCodeBrackedClose&&e.charCodeAt(t+2)===ms.CharCodeGreaterThan){let i=new ps;i.nodeType=rs.CDATA,i.value=e.substr(n,t-n),s.addChild(i),t+=2,a=ns.Begin}break;case ns.BeginNode:switch(i){case ms.CharCodeExclamation:if(e.charCodeAt(t+1)===ms.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new gs("Expected <![CDATA[",e,t);t+=5,a=ns.Cdata,n=t+1}else if(e.charCodeAt(t+1)===ms.CharCodeUpperD||e.charCodeAt(t+1)===ms.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new gs("Expected <!DOCTYPE",e,t);t+=8,a=ns.Doctype,n=t+1}else{if(e.charCodeAt(t+1)!==ms.CharCodeMinus||e.charCodeAt(t+2)!==ms.CharCodeMinus)throw new gs("Expected \x3c!--",e,t);t+=2,a=ns.Comment,n=t+1}break;case ms.CharCodeQuestion:a=ns.Header,n=t;break;case ms.CharCodeSlash:if(!s)throw new gs("Expected node name",e,t);n=t+1,a=ns.IgnoreSpaces,r=ns.Close;break;default:a=ns.TagName,n=t;continue}break;case ns.TagName:if(!ms.isValidChar(i)){if(t===n)throw new gs("Expected node name",e,t);l=new ps,l.nodeType=rs.Element,l.localName=e.substr(n,t-n),s.addChild(l),a=ns.IgnoreSpaces,r=ns.Body;continue}break;case ns.Body:switch(i){case ms.CharCodeSlash:a=ns.WaitEnd;break;case ms.CharCodeGreaterThan:a=ns.Childs;break;default:a=ns.AttribName,n=t;continue}break;case ns.AttribName:if(!ms.isValidChar(i)){if(n===t)throw new gs("Expected attribute name",e,t);if(d=e.substr(n,t-n),l.attributes.has(d))throw new gs(`Duplicate attribute [${d}]`,e,t);a=ns.IgnoreSpaces,r=ns.Equals;continue}break;case ns.Equals:if(i!==ms.CharCodeEquals)throw new gs("Expected =",e,t);a=ns.IgnoreSpaces,r=ns.AttvalBegin;break;case ns.AttvalBegin:switch(i){case ms.CharCodeDoubleQuote:case ms.CharCodeSingleQuote:o="",a=ns.AttribVal,n=t+1,u=i}break;case ns.AttribVal:if(i===ms.CharCodeAmp)o+=e.substr(n,t-n),a=ns.Escape,h=ns.AttribVal,n=t+1;else if(i===u){o+=e.substr(n,t-n);let s=o;o="",l.attributes.set(d,s),a=ns.IgnoreSpaces,r=ns.Body}break;case ns.Childs:n=t=ms.parse(e,t,l),a=ns.Begin;break;case ns.WaitEnd:if(i!==ms.CharCodeGreaterThan)throw new gs("Expected >",e,t);a=ns.Begin;break;case ns.WaitEndRet:if(i===ms.CharCodeGreaterThan)return t;throw new gs("Expected >",e,t);case ns.Close:if(!ms.isValidChar(i)){if(n===t)throw new gs("Expected node name",e,t);if(e.substr(n,t-n)!==s.localName)throw new gs("Expected </"+s.localName+">",e,t);a=ns.IgnoreSpaces,r=ns.WaitEndRet;continue}break;case ns.Comment:i===ms.CharCodeMinus&&e.charCodeAt(t+1)===ms.CharCodeMinus&&e.charCodeAt(t+2)===ms.CharCodeGreaterThan&&(t+=2,a=ns.Begin);break;case ns.Doctype:if(i===ms.CharCodeBrackedOpen)c++;else if(i===ms.CharCodeBrackedClose)c--;else if(i===ms.CharCodeGreaterThan&&0===c){let i=new ps;i.nodeType=rs.DocumentType,i.value=e.substr(n,t-n),s.addChild(i),a=ns.Begin}break;case ns.Header:i===ms.CharCodeQuestion&&e.charCodeAt(t+1)===ms.CharCodeGreaterThan&&(t++,a=ns.Begin);break;case ns.Escape:if(i===ms.CharCodeSemi){let s=e.substr(n,t-n);if(s.charCodeAt(0)===ms.CharCodeSharp){let e=s.charCodeAt(1)===ms.CharCodeLowerX?parseInt("0"+s.substr(1,s.length-1)):parseInt(s.substr(1,s.length-1));o+=String.fromCharCode(e)}else ms.Escapes.has(s)?o+=ms.Escapes.get(s):o+=("&"+s+";")?.toString();n=t+1,a=h}else ms.isValidChar(i)||i===ms.CharCodeSharp||(o+="&",o+=e.substr(n,t-n),n=--t+1,a=h)}t++}if(a===ns.Begin&&(n=t,a=ns.Pcdata),a===ns.Pcdata){if(t!==n){o+=e.substr(n,t-n);let i=new ps;i.nodeType=rs.Text,i.value=o,s.addChild(i)}return t}if(a===ns.Escape&&h===ns.Pcdata){o+="&",o+=e.substr(n,t-n);let i=new ps;return i.nodeType=rs.Text,i.value=o,s.addChild(i),t}throw new gs("Unexpected end",e,t)}static isValidChar(e){return e>=ms.CharCodeLowerA&&e<=ms.CharCodeLowerZ||e>=ms.CharCodeUpperA&&e<=ms.CharCodeUpperZ||e>=ms.CharCode0&&e<=ms.CharCode9||e===ms.CharCodeColon||e===ms.CharCodeDot||e===ms.CharCodeUnderscore||e===ms.CharCodeMinus}}ms.CharCodeLF=10,ms.CharCodeTab=9,ms.CharCodeCR=13,ms.CharCodeSpace=32,ms.CharCodeLowerThan=60,ms.CharCodeAmp=38,ms.CharCodeBrackedClose=93,ms.CharCodeBrackedOpen=91,ms.CharCodeGreaterThan=62,ms.CharCodeExclamation=33,ms.CharCodeUpperD=68,ms.CharCodeLowerD=100,ms.CharCodeMinus=45,ms.CharCodeQuestion=63,ms.CharCodeSlash=47,ms.CharCodeEquals=61,ms.CharCodeDoubleQuote=34,ms.CharCodeSingleQuote=39,ms.CharCodeSharp=35,ms.CharCodeLowerX=120,ms.CharCodeLowerA=97,ms.CharCodeLowerZ=122,ms.CharCodeUpperA=65,ms.CharCodeUpperZ=90,ms.CharCode0=48,ms.CharCode9=57,ms.CharCodeColon=58,ms.CharCodeDot=46,ms.CharCodeUnderscore=95,ms.CharCodeSemi=59,ms.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class fs{static write(e,t,s){const i=new fs(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 rs.None:break;case rs.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===rs.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case rs.Text:e.value&&this.write(e.value);break;case rs.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case rs.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case rs.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("<");break;case">":this._result.push(">");break;case"&":this._result.push("&");break;case"'":this._result.push("'");break;case'"':this._result.push(""");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 ys extends ps{constructor(){super(),this.nodeType=rs.Document}parse(e){ms.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return fs.write(this,e,t)}}class bs{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=g.Quarter}}class Ss{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return this.path+";"+this.name+";"+this.role}}class _s{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1}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;let s=new ys;try{s.parse(e)}catch(e){throw new Q("Could not parse XML",e)}if(this.parseDom(s),this.buildModel(),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){let t=e.firstElement;if(t){if("GPIF"!==t.localName)throw new Q("Root node of XML was not GPIF");this.score=new ve;for(let e of t.childNodes)if(e.nodeType===rs.Element)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(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"Title":this.score.title=t.firstChild.innerText;break;case"SubTitle":this.score.subTitle=t.firstChild.innerText;break;case"Artist":this.score.artist=t.firstChild.innerText;break;case"Album":this.score.album=t.firstChild.innerText;break;case"Words":this.score.words=t.firstChild.innerText;break;case"Music":this.score.music=t.firstChild.innerText;break;case"WordsAndMusic":if(t.firstChild&&""!==t.firstChild.innerText){let e=t.firstChild.innerText;e&&!this.score.words&&(this.score.words=e),e&&!this.score.music&&(this.score.music=e)}break;case"Copyright":this.score.copyright=t.firstChild.innerText;break;case"Tabber":this.score.tab=t.firstChild.innerText;break;case"Instructions":this.score.instructions=t.firstChild.innerText;break;case"Notices":this.score.notices=t.firstChild.innerText;break;case"ScoreSystemsDefaultLayout":this.score.defaultSystemsLayout=parseInt(t.innerText);break;case"ScoreSystemsLayout":this.score.systemsLayout=t.innerText.split(" ").map((e=>parseInt(e)))}}parseMasterTrackNode(e){for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null,null);break;case"Tracks":this._tracksMapping=t.innerText.split(" ");break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,s,i){for(let a of e.childNodes)if(a.nodeType===rs.Element&&"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,d=null,c=0,u=null;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"Type":a=t.innerText;break;case"Linear":r="true"===t.innerText.toLowerCase();break;case"Bar":n=parseInt(t.innerText);break;case"Position":o=parseFloat(t.innerText);break;case"Value":if(t.firstElement&&t.firstElement.nodeType===rs.CDATA)d=t.innerText;else{let e=t.innerText.split(" ");1===e.length?(h=parseFloat(e[0]),c=1):(h=parseFloat(e[0]),c=parseInt(e[1]))}break;case"Text":u=t.innerText}if(!a)return;let p=null;switch(a){case"Tempo":p=$.buildTempoAutomation(r,o,h,c);break;case"Sound":d&&s&&s.has(d)&&(p=$.buildInstrumentAutomation(r,o,s.get(d).program));break;case"SustainPedal":if(i){let e;i.has(n)?e=i.get(n):(e=[],i.set(n,e));const t=new Z;switch(t.ratioPosition=o,c){case 1:t.pedalType=l.Down;break;case 3:t.pedalType=l.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(let t of e.childNodes)if(t.nodeType===rs.Element&&"Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;let t=new Me;t.ensureStaveCount(1),t.staves[0].showStandardNotation=!0;let s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"Name":t.name=i.innerText;break;case"Color":let e=i.innerText.split(" ");if(e.length>=3){let s=parseInt(e[0]),i=parseInt(e[1]),a=parseInt(e[2]);t.color=new Ee(s,i,a,255)}break;case"Instrument":let 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=parseInt(i.innerText);break;case"SystemsLayout":t.systemsLayout=i.innerText.split(" ").map((e=>parseInt(e)));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":let 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(let s of t.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"LineCount":const t=parseInt(s.innerText);for(let s of e.staves)s.standardNotationLineCount=t;break;case"Elements":this.parseElements(e,s)}}parseInstrumentSet(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"Type":if("drumKit"===s.innerText)for(let t of e.staves)t.isPercussion=!0;if("drumKit"===s.innerText)for(let t of e.staves)t.isPercussion=!0;break;case"Elements":this.parseElements(e,s);break;case"LineCount":const t=parseInt(s.innerText);for(let s of e.staves)s.standardNotationLineCount=t}}parseElements(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"Element"===s.localName)this.parseElement(e,s)}parseElement(e,t){const s=t.findChildElement("Type"),i=s?s.innerText:"";for(let s of t.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"Name":case"Articulations":this.parseArticulations(e,s,i)}}parseArticulations(e,t,s){for(let i of t.childNodes)if(i.nodeType===rs.Element&&"Articulation"===i.localName)this.parseArticulation(e,i,s)}parseArticulation(e,t,s){const i=new ue;i.outputMidiNumber=-1,i.elementType=s;let a="";for(let e of t.childNodes)if(e.nodeType===rs.Element){const t=e.innerText;switch(e.localName){case"Name":a=e.innerText;break;case"OutputMidiNumber":t.length>0&&(i.outputMidiNumber=parseInt(t));break;case"TechniqueSymbol":i.techniqueSymbol=this.parseTechniqueSymbol(t);break;case"TechniquePlacement":switch(t){case"outside":case"above":i.techniqueSymbolPlacement=M.Bottom;break;case"inside":i.techniqueSymbolPlacement=M.Middle;break;case"below":i.techniqueSymbolPlacement=M.Top}break;case"Noteheads":const s=t.split(" ");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==D.None&&(i.noteHeadHalf=i.noteHeadDefault),i.noteHeadWhole==D.None&&(i.noteHeadWhole=i.noteHeadDefault);break;case"StaffLine":t.length>0&&(i.staffLine=parseInt(t))}}-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 D.PictEdgeOfCymbal;case"articStaccatoAbove":return D.ArticStaccatoAbove;case"noteheadParenthesis":return D.NoteheadParenthesis;case"stringsUpBow":return D.StringsUpBow;case"stringsDownBow":return D.StringsDownBow;case"guitarGolpe":return D.GuitarGolpe;default:return D.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return D.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return D.NoteheadDoubleWhole;case"noteheadWhole":return D.NoteheadWhole;case"noteheadHalf":return D.NoteheadHalf;case"noteheadBlack":return D.NoteheadBlack;case"noteheadNull":return D.NoteheadNull;case"noteheadXOrnate":return D.NoteheadXOrnate;case"noteheadTriangleUpWhole":return D.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return D.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return D.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return D.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return D.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return D.NoteheadDiamondWhiteWide;case"noteheadCircleX":return D.NoteheadCircleX;case"noteheadXWhole":return D.NoteheadXWhole;case"noteheadXHalf":return D.NoteheadXHalf;case"noteheadXBlack":return D.NoteheadXBlack;case"noteheadParenthesis":return D.NoteheadParenthesis;case"noteheadSlashedBlack2":return D.NoteheadSlashedBlack2;case"noteheadCircleSlash":return D.NoteheadCircleSlash;case"noteheadHeavyX":return D.NoteheadHeavyX;case"noteheadHeavyXHat":return D.NoteheadHeavyXHat;default:return ne.warning("GPIF","Unknown notehead symbol",e),D.None}}parseStaves(e,t){let s=0;for(let i of t.childNodes)if(i.nodeType===rs.Element&&"Staff"===i.localName){e.ensureStaveCount(s+1);let t=e.staves[s];this.parseStaff(t,i),s++}}parseStaff(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"Properties"===s.localName)this.parseStaffProperties(e,s)}parseStaffProperties(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"Property"===s.localName)this.parseStaffProperty(e,s)}parseStaffProperty(e,t){switch(t.getAttribute("name")){case"Tuning":for(let s of t.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"Pitches":let i=t.findChildElement("Pitches").innerText.split(" "),a=new Array(i.length);for(let e=0;e<a.length;e++)a[a.length-1-e]=parseInt(i[e]);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":let s=parseInt(t.findChildElement("Fret").innerText);e.capo=s}}parseLyrics(e,t){let s=[];for(let e of t.childNodes)if(e.nodeType===rs.Element&&"Line"===e.localName)s.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,s)}parseLyricsLine(e){let t=new ke;for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"Offset":t.startBar=parseInt(s.innerText);break;case"Text":t.text=s.innerText}return t}parseDiagramCollectionForTrack(e,t){let s=t.findChildElement("Items");for(let t of s.childNodes)if(t.nodeType===rs.Element&&"Item"===t.localName)this.parseDiagramItemForTrack(e,t)}parseDiagramCollectionForStaff(e,t){let s=t.findChildElement("Items");for(let t of s.childNodes)if(t.nodeType===rs.Element&&"Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){let s=new Te,i=t.getAttribute("id");for(let t of e.staves)t.addChord(i,s);this.parseDiagramItemForChord(s,t)}parseDiagramItemForStaff(e,t){let s=new Te,i=t.getAttribute("id");e.addChord(i,s),this.parseDiagramItemForChord(s,t)}parseDiagramItemForChord(e,t){e.name=t.getAttribute("name");let s=t.findChildElement("Diagram");if(!s)return e.showDiagram=!1,void(e.showFingering=!1);let i=parseInt(s.getAttribute("stringCount")),a=s.attributes.has("baseFret")?parseInt(s.getAttribute("baseFret")):0;e.firstFret=a+1;for(let t=0;t<i;t++)e.strings.push(-1);for(let t of s.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"Fret":let s=parseInt(t.getAttribute("string"));e.strings[i-s-1]=a+parseInt(t.getAttribute("fret"));break;case"Fingering":let r=new Map;for(let s of t.childNodes)if(s.nodeType===rs.Element&&"Position"===s.localName){let t=y.Unknown,i=a+parseInt(s.getAttribute("fret"));switch(s.getAttribute("finger")){case"Index":t=y.IndexFinger;break;case"Middle":t=y.MiddleFinger;break;case"Rank":t=y.AnnularFinger;break;case"Pinky":t=y.LittleFinger;break;case"Thumb":t=y.Thumb}t!==y.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(let s of t.childNodes)if(s.nodeType===rs.Element&&"Property"===s.localName)this.parseTrackProperty(e,s)}parseTrackProperty(e,t){switch(t.getAttribute("name")){case"Tuning":let s=t.findChildElement("Pitches").innerText.split(" "),i=new Array(s.length);for(let e=0;e<i.length;e++)i[i.length-1-e]=parseInt(s[e]);for(let 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":let a=parseInt(t.findChildElement("Fret").innerText);for(let t of e.staves)t.capo=a}}parseGeneralMidi(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"Program":e.playbackInfo.program=parseInt(s.innerText);break;case"Port":e.playbackInfo.port=parseInt(s.innerText);break;case"PrimaryChannel":e.playbackInfo.primaryChannel=parseInt(s.innerText);break;case"SecondaryChannel":e.playbackInfo.secondaryChannel=parseInt(s.innerText)}if("Percussion"===t.getAttribute("table"))for(let t of e.staves)t.isPercussion=!0}parseSounds(e,t,s){for(let i of s.childNodes)if(i.nodeType===rs.Element&&"Sound"===i.localName)this.parseSound(e,t,i)}parseSound(e,t,s){const i=new Ss;for(let e of s.childNodes)if(e.nodeType===rs.Element)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(let s of t.childNodes)if(s.nodeType===rs.Element&&"Program"===s.localName)e.program=parseInt(s.innerText)}parsePartSounding(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"TranspositionPitch"===s.localName)for(let t of e.staves)t.displayTranspositionPitch=parseInt(s.innerText)}parseTranspose(e,t){let s=0,i=0;for(let e of t.childNodes)if(e.nodeType===rs.Element)switch(e.localName){case"Chromatic":i=parseInt(e.innerText);break;case"Octave":s=parseInt(e.innerText)}for(let t of e.staves)t.displayTranspositionPitch=12*s+i}parseRSE(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"ChannelStrip"===s.localName)this.parseChannelStrip(e,s)}parseChannelStrip(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"Parameters"===s.localName)this.parseChannelStripParameters(e,s)}parseChannelStripParameters(e,t){if(t.firstChild&&t.firstChild.value){let s=t.firstChild.value.split(" ");s.length>=12&&(e.playbackInfo.balance=Math.floor(16*parseFloat(s[11])),e.playbackInfo.volume=Math.floor(16*parseFloat(s[12])))}}parseMasterBarsNode(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){let t=new oe;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"Time":let e=s.innerText.split("/");t.timeSignatureNumerator=parseInt(e[0]),t.timeSignatureDenominator=parseInt(e[1]);break;case"FreeTime":t.isFreeTime=!0;break;case"DoubleBar":t.isDoubleBar=!0;break;case"Section":t.section=new Pe,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=parseInt(s.getAttribute("count")));break;case"AlternateEndings":let i=s.innerText.split(" "),a=0;for(let e=0;e<i.length;e++)a|=1<<-1+parseInt(i[e]);t.alternateEndings=a;break;case"Bars":this._barsOfMasterBar.push(s.innerText.split(" "));break;case"TripletFeel":switch(s.innerText){case"NoTripletFeel":t.tripletFeel=E.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=E.Triplet8th;break;case"Triplet16th":t.tripletFeel=E.Triplet16th;break;case"Dotted8th":t.tripletFeel=E.Dotted8th;break;case"Dotted16th":t.tripletFeel=E.Dotted16th;break;case"Scottish8th":t.tripletFeel=E.Scottish8th;break;case"Scottish16th":t.tripletFeel=E.Scottish16th}break;case"Key":t.keySignature=parseInt(s.findChildElement("AccidentalCount").innerText);let r=s.findChildElement("Mode");if(r)switch(r.innerText.toLowerCase()){case"major":t.keySignatureType=C.Major;break;case"minor":t.keySignatureType=C.Minor}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(let s of t.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"Target":switch(s.innerText){case"Coda":e.addDirection(He.TargetCoda);break;case"DoubleCoda":e.addDirection(He.TargetDoubleCoda);break;case"Segno":e.addDirection(He.TargetSegno);break;case"SegnoSegno":e.addDirection(He.TargetSegnoSegno);break;case"Fine":e.addDirection(He.TargetFine)}break;case"Jump":switch(s.innerText){case"DaCapo":e.addDirection(He.JumpDaCapo);break;case"DaCapoAlCoda":e.addDirection(He.JumpDaCapoAlCoda);break;case"DaCapoAlDoubleCoda":e.addDirection(He.JumpDaCapoAlDoubleCoda);break;case"DaCapoAlFine":e.addDirection(He.JumpDaCapoAlFine);break;case"DaSegno":e.addDirection(He.JumpDalSegno);break;case"DaSegnoAlCoda":e.addDirection(He.JumpDalSegnoAlCoda);break;case"DaSegnoAlDoubleCoda":e.addDirection(He.JumpDalSegnoAlDoubleCoda);break;case"DaSegnoAlFine":e.addDirection(He.JumpDalSegnoAlFine);break;case"DaSegnoSegno":e.addDirection(He.JumpDalSegnoSegno);break;case"DaSegnoSegnoAlCoda":e.addDirection(He.JumpDalSegnoSegnoAlCoda);break;case"DaSegnoSegnoAlDoubleCoda":e.addDirection(He.JumpDalSegnoSegnoAlDoubleCoda);break;case"DaSegnoSegnoAlFine":e.addDirection(He.JumpDalSegnoSegnoAlFine);break;case"DaCoda":e.addDirection(He.JumpDaCoda);break;case"DaDoubleCoda":e.addDirection(He.JumpDaDoubleCoda)}}}parseFermatas(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"Fermata"===s.localName)this.parseFermata(e,s)}parseFermata(e,t){let s=0,i=new et;for(let e of t.childNodes)if(e.nodeType===rs.Element)switch(e.localName){case"Type":switch(e.innerText){case"Short":i.type=Ge.Short;break;case"Medium":i.type=Ge.Medium;break;case"Long":i.type=Ge.Long}break;case"Length":i.length=parseFloat(e.innerText);break;case"Offset":let t=e.innerText.split("/");if(2===t.length){s=parseInt(t[0])/parseInt(t[1])*te.QuarterTime|0}}e.addFermata(s,i)}parseBars(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"Bar"===t.localName)this.parseBar(t)}parseBar(e){let t=new ee,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"Voices":this._voicesOfBar.set(s,i.innerText.split(" "));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(let t of e.childNodes)if(t.nodeType===rs.Element&&"Voice"===t.localName)this.parseVoice(t)}parseVoice(e){let t=new Ie,s=e.getAttribute("id");for(let t of e.childNodes)if(t.nodeType===rs.Element&&"Beats"===t.localName)this._beatsOfVoice.set(s,t.innerText.split(" "));this._voiceById.set(s,t)}parseBeats(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"Beat"===t.localName)this.parseBeat(t)}parseBeat(e){let t=new Be,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"Notes":this._notesOfBeat.set(s,i.innerText.split(" "));break;case"Rhythm":this._rhythmOfBeat.set(s,i.getAttribute("ref"));break;case"Fadding":switch(i.innerText){case"FadeIn":t.fade=O.FadeIn;break;case"FadeOut":t.fade=O.FadeOut;break;case"VolumeSwell":t.fade=O.VolumeSwell}break;case"Tremolo":switch(i.innerText){case"1/2":t.tremoloSpeed=g.Eighth;break;case"1/4":t.tremoloSpeed=g.Sixteenth;break;case"1/8":t.tremoloSpeed=g.ThirtySecond}break;case"Chord":t.chordId=i.innerText;break;case"Hairpin":switch(i.innerText){case"Crescendo":t.crescendo=p.Crescendo;break;case"Decrescendo":t.crescendo=p.Decrescendo}break;case"Arpeggio":"Up"===i.innerText?t.brushType=u.ArpeggioUp:t.brushType=u.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=We.Up;break;case"Downward":t.preferredBeamDirection=We.Down}break;case"Dynamic":switch(i.innerText){case"PPP":t.dynamics=m.PPP;break;case"PP":t.dynamics=m.PP;break;case"P":t.dynamics=m.P;break;case"MP":t.dynamics=m.MP;break;case"MF":t.dynamics=m.MF;break;case"F":t.dynamics=m.F;break;case"FF":t.dynamics=m.FF;break;case"FFF":t.dynamics=m.FFF}break;case"GraceNotes":switch(i.innerText){case"OnBeat":t.graceType=f.OnBeat;break;case"BeforeBeat":t.graceType=f.BeforeBeat}break;case"Legato":"true"===i.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":let e=new se(0,0);e.value=this.toBendValue(parseFloat(i.getAttribute("originValue"))),e.offset=this.toBendOffset(parseFloat(i.getAttribute("originOffset"))),t.addWhammyBarPoint(e);let a=new se(0,0);a.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),a.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);let r=new se(0,0);r.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),r.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);let n=new se(0,0);n.value=this.toBendValue(parseFloat(i.getAttribute("destinationValue"))),n.offset=this.toBendOffset(parseFloat(i.getAttribute("destinationOffset"))),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=R.Finger;break;case"Thumb":t.golpe=R.Thumb}break;case"Wah":switch(i.innerText){case"Open":t.wahPedal=V.Open;break;case"Closed":t.wahPedal=V.Closed}break;case"UserTransposedPitchStemOrientation":switch(i.innerText){case"Downward":t.preferredBeamDirection=We.Down;break;case"Upward":t.preferredBeamDirection=We.Up}break;case"Timer":t.showTimer=!0,i.innerText.length>0&&(t.timer=parseInt(i.innerText))}this._beatById.set(s,t)}parseBeatLyrics(e){const t=[];for(let s of e.childNodes)if(s.nodeType===rs.Element&&"Line"===s.localName)t.push(s.innerText);return t}parseBeatXProperties(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element&&"XProperty"===s.localName){let e=0;switch(s.getAttribute("id")){case"1124204546":switch(e=parseInt(s.findChildElement("Int").innerText),e){case 1:t.beamingMode=W.ForceMergeWithNext;break;case 2:t.beamingMode=W.ForceSplitToNext}break;case"1124204552":if(e=parseInt(s.findChildElement("Int").innerText),1===e)t.beamingMode!==W.ForceSplitToNext&&(t.beamingMode=W.ForceSplitOnSecondaryToNext);break;case"1124204545":e=parseInt(s.findChildElement("Int").innerText),t.invertBeamDirection=1===e;break;case"687935489":e=parseInt(s.findChildElement("Int").innerText),t.brushDuration=e}}}parseBarXProperties(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element&&"XProperty"===s.localName){if("1124139520"===s.getAttribute("id")){const e=s.findChildElement("Double")??s.findChildElement("Float");t.displayScale=parseFloat(e.innerText)}}}parseMasterBarXProperties(e,t){for(let s of t.childNodes)if(s.nodeType===rs.Element&&"XProperty"===s.localName){if("1124073984"===s.getAttribute("id"))e.displayScale=parseFloat(s.findChildElement("Double").innerText)}}parseBeatProperties(e,t){let s=!1,i=null,a=null,r=null,n=null,o=null;for(let h of e.childNodes)if(h.nodeType===rs.Element&&"Property"===h.localName){switch(h.getAttribute("name")){case"Brush":"Up"===h.findChildElement("Direction").innerText?t.brushType=u.BrushUp:t.brushType=u.BrushDown;break;case"PickStroke":"Up"===h.findChildElement("Direction").innerText?t.pickStroke=F.Up:t.pickStroke=F.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=B.Wide;break;case"Slight":t.vibrato=B.Slight}break;case"WhammyBar":s=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":i||(i=new se(0,0)),i.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":i||(i=new se(0,0)),i.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleValue":a=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleOffset1":r=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleOffset2":n=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationValue":o||(o=new se(se.MaxPosition,0)),o.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new se(0,0)),o.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"BarreFret":t.barreFret=parseInt(h.findChildElement("Fret").innerText);break;case"BarreString":switch(h.findChildElement("String").innerText){case"0":t.barreShape=H.Full;break;case"1":t.barreShape=H.Half}break;case"Rasgueado":switch(h.findChildElement("Rasgueado").innerText){case"ii_1":t.rasgueado=G.Ii;break;case"mi_1":t.rasgueado=G.Mi;break;case"mii_1":t.rasgueado=G.MiiTriplet;break;case"mii_2":t.rasgueado=G.MiiAnapaest;break;case"pmp_1":t.rasgueado=G.PmpTriplet;break;case"pmp_2":t.rasgueado=G.PmpAnapaest;break;case"pei_1":t.rasgueado=G.PeiTriplet;break;case"pei_2":t.rasgueado=G.PeiAnapaest;break;case"pai_1":t.rasgueado=G.PaiTriplet;break;case"pai_2":t.rasgueado=G.PaiAnapaest;break;case"ami_1":t.rasgueado=G.AmiTriplet;break;case"ami_2":t.rasgueado=G.AmiAnapaest;break;case"ppp_1":t.rasgueado=G.Ppp;break;case"amii_1":t.rasgueado=G.Amii;break;case"amip_1":t.rasgueado=G.Amip;break;case"eami_1":t.rasgueado=G.Eami;break;case"eamii_1":t.rasgueado=G.Eamii;break;case"peami_1":t.rasgueado=G.Peami}}}s&&(i||(i=new se(0,0)),o||(o=new se(se.MaxPosition,0)),t.addWhammyBarPoint(i),r&&a&&t.addWhammyBarPoint(new se(r,a)),n&&a&&t.addWhammyBarPoint(new se(n,a)),r||n||!a||t.addWhammyBarPoint(new se(se.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"Note"===t.localName)this.parseNote(t)}parseNote(e){let t=new me,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===rs.Element)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=parseInt(i.innerText),t.trillSpeed=g.Sixteenth;break;case"Accent":let e=parseInt(i.innerText);1&e&&(t.isStaccato=!0),4&e&&(t.accentuated=a.Heavy),8&e&&(t.accentuated=a.Normal),16&e&&(t.accentuated=a.Tenuto);break;case"Tie":"true"===i.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(i.innerText){case"Slight":t.vibrato=B.Slight;break;case"Wide":t.vibrato=B.Wide}break;case"LeftFingering":switch(i.innerText){case"P":t.leftHandFinger=y.Thumb;break;case"I":t.leftHandFinger=y.IndexFinger;break;case"M":t.leftHandFinger=y.MiddleFinger;break;case"A":t.leftHandFinger=y.AnnularFinger;break;case"C":t.leftHandFinger=y.LittleFinger}break;case"RightFingering":switch(i.innerText){case"P":t.rightHandFinger=y.Thumb;break;case"I":t.rightHandFinger=y.IndexFinger;break;case"M":t.rightHandFinger=y.MiddleFinger;break;case"A":t.rightHandFinger=y.AnnularFinger;break;case"C":t.rightHandFinger=y.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=parseInt(i.innerText);break;case"Ornament":switch(i.innerText){case"Turn":t.ornament=I.Turn;break;case"InvertedTurn":t.ornament=I.InvertedTurn;break;case"UpperMordent":t.ornament=I.UpperMordent;break;case"LowerMordent":t.ornament=I.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,d=-1;for(let c of e.childNodes)if(c.nodeType===rs.Element&&"Property"===c.localName){switch(c.getAttribute("name")){case"ShowStringNumber":c.findChildElement("Enable")&&(t.showStringNumber=!0);break;case"String":t.string=parseInt(c.findChildElement("String").innerText)+1;break;case"Fret":t.fret=parseInt(c.findChildElement("Fret").innerText);break;case"Element":l=parseInt(c.findChildElement("Element").innerText);break;case"Variation":d=parseInt(c.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(s,!0);break;case"HarmonicType":let e=c.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=b.None;break;case"Natural":t.harmonicType=b.Natural;break;case"Artificial":t.harmonicType=b.Artificial;break;case"Pinch":t.harmonicType=b.Pinch;break;case"Tap":t.harmonicType=b.Tap;break;case"Semi":t.harmonicType=b.Semi;break;case"Feedback":t.harmonicType=b.Feedback}break;case"HarmonicFret":let u=c.findChildElement("HFret");u&&(t.harmonicValue=parseFloat(u.innerText));break;case"Muted":c.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":c.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=parseInt(c.findChildElement("Number").innerText),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=parseInt(c.findChildElement("Step").innerText);break;case"ConcertPitch":this.parseConcertPitch(c,t);break;case"Bended":i=!0;break;case"BendOriginValue":a||(a=new se(0,0)),a.value=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new se(0,0)),a.offset=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleValue":r=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleOffset1":n=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleOffset2":o=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendDestinationValue":h||(h=new se(se.MaxPosition,0)),h.value=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new se(0,0)),h.offset=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"HopoOrigin":c.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":let p=parseInt(c.findChildElement("Flags").innerText);1&p?t.slideOutType=w.Shift:2&p?t.slideOutType=w.Legato:4&p?t.slideOutType=w.OutDown:8&p&&(t.slideOutType=w.OutUp),16&p?t.slideInType=_.IntoFromBelow:32&p&&(t.slideInType=_.IntoFromAbove),64&p?t.slideOutType=w.PickSlideDown:128&p&&(t.slideOutType=w.PickSlideUp)}}i&&(a||(a=new se(0,0)),h||(h=new se(se.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new se(n,r)),o&&r&&t.addBendPoint(new se(o,r)),n||o||!r||t.addBendPoint(new se(se.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==d&&(t.percussionArticulation=pe.articulationFromElementVariation(l,d))}parseConcertPitch(e,t){const s=e.findChildElement("Pitch");if(s)for(let e of s.childNodes)if(e.nodeType===rs.Element&&"Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=S.ForceDoubleSharp;break;case"#":t.accidentalMode=S.ForceSharp;break;case"b":t.accidentalMode=S.ForceFlat;break;case"bb":t.accidentalMode=S.ForceDoubleFlat}}toBendValue(e){return e*_s.BendPointValueFactor|0}toBendOffset(e){return e*_s.BendPointPositionFactor}parseRhythms(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){let t=new bs,s=e.getAttribute("id");t.id=s;for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"NoteValue":switch(s.innerText){case"Long":t.value=g.QuadrupleWhole;break;case"DoubleWhole":t.value=g.DoubleWhole;break;case"Whole":t.value=g.Whole;break;case"Half":t.value=g.Half;break;case"Quarter":t.value=g.Quarter;break;case"Eighth":t.value=g.Eighth;break;case"16th":t.value=g.Sixteenth;break;case"32nd":t.value=g.ThirtySecond;break;case"64th":t.value=g.SixtyFourth;break;case"128th":t.value=g.OneHundredTwentyEighth;break;case"256th":t.value=g.TwoHundredFiftySixth}break;case"PrimaryTuplet":t.tupletNumerator=parseInt(s.getAttribute("num")),t.tupletDenominator=parseInt(s.getAttribute("den"));break;case"AugmentationDot":t.dots=parseInt(s.getAttribute("count"))}this._rhythmById.set(s,t)}buildModel(){for(let e=0,t=this._masterBars.length;e<t;e++){let t=this._masterBars[e];this.score.addMasterBar(t)}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e);this.score.addTrack(t)}for(let e of this._barsOfMasterBar){let t=0;for(let s=0,i=0;s<e.length&&i<this.score.tracks.length;s++){let a=e[s];if(a!==_s.InvalidId){let e=this._barsById.get(a),s=this.score.tracks[i],r=s.staves[t];if(r.addBar(e),this._voicesOfBar.has(a))for(let t of this._voicesOfBar.get(a))if(t!==_s.InvalidId){let s=this._voiceById.get(t);if(e.addVoice(s),this._beatsOfVoice.has(t))for(let e of this._beatsOfVoice.get(t))if(e!==_s.InvalidId){let t=_e.clone(this._beatById.get(e));s.addBeat(t);let 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(let s of this._notesOfBeat.get(e))if(s!==_s.InvalidId){const e=be.clone(this._noteById.get(s));r.isPercussion?(e.fret=-1,e.string=-1):e.percussionArticulation=-1,t.addNote(e),this._tappedNotes.has(s)&&(t.tap=!0)}}}else{let t=new Ie;e.addVoice(t);let s=new Be;s.isEmpty=!0,s.duration=g.Quarter,t.addBeat(s)}t===s.staves.length-1?(i++,t=0):t++}else i++}}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e),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){let s=this.score.masterBars[e];for(let i=0,a=t.length;i<a;i++){let a=t[i];a.type===r.Tempo&&(0===e&&(this.score.tempo=0|a.value,a.text&&(this.score.tempoLabel=a.text)),s.tempoAutomations.push(a))}}}}_s.InvalidId="-1",_s.BendPointPositionFactor=se.MaxPosition/100,_s.BendPointValueFactor=.04;class ws{constructor(){this.isMultiRest=!1,this.trackViewGroups=[]}}class Bs{constructor(){this.showNumbered=!1,this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class Ts{apply(e){if(this.scoreViews.length>0){let t=0;for(let 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++}}}constructor(e){this.scoreViews=[];let t=Oe.fromBuffer(e);const s=Re.readInt32BE(t);for(let e=0;e<s;e++){const e=new ws;this.scoreViews.push(e),e.isMultiRest=ls.gpReadBool(t);const s=Re.readInt32BE(t);for(let i=0;i<s;i++){let s=t.readByte();0===s&&(s=1);let i=new Bs;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=Oe.withCapacity(128),s=[new ws];for(const t of e.tracks){const e=new Bs;e.showStandardNotation=t.staves[0].showStandardNotation,e.showTablature=t.staves[0].showTablature,e.showSlash=t.staves[0].showSlash,e.showNumbered=t.staves[0].showNumbered,s[0].trackViewGroups.push(e);const i=new ws;i.trackViewGroups.push(e),s.push(i)}Re.writeInt32BE(t,s.length);for(const e of s){t.writeByte(e.isMultiRest?1:0),Re.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 Re.writeInt32BE(t,1),t.toArray()}}let ks=class{};class Ns extends ks{constructor(e){super(),this.n=e}}class xs extends ks{constructor(e,t){super(),this.left=e,this.right=t}}class vs extends ks{constructor(e,t){super(),this.n=e,this.table=t}}class Ps{static make(e,t,s,i){let a=[],r=[];if(i>32)throw new Ce("Invalid huffman");for(let e=0;e<i;e++)a.push(0),r.push(0);for(let r=0;r<s;r++){let s=e[r+t];if(s>=i)throw new Ce("Invalid huffman");a[s]++}let n=0;for(let e=1;e<i-1;e++)n=n+a[e]<<1,r[e]=n;let o=new Map;for(let i=0;i<s;i++){let s=e[i+t];if(0!==s){let e=r[s-1];r[s-1]=e+1,o.set(e<<5|s,i)}}return Ps.treeCompress(new xs(Ps.treeMake(o,i,0,1),Ps.treeMake(o,i,1,1)))}static treeMake(e,t,s,i){if(i>t)throw new Ce("Invalid huffman");let a=s<<5|i;return e.has(a)?new Ns(e.get(a)):(s<<=1,i+=1,new xs(Ps.treeMake(e,t,s,i),Ps.treeMake(e,t,1|s,i)))}static treeCompress(e){let t=Ps.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof xs)return new xs(Ps.treeCompress(e.left),Ps.treeCompress(e.right));throw new Ce("assert")}let s=1<<t,i=[];for(let e=0;e<s;e++)i.push(new Ns(-1));return Ps.treeWalk(i,0,0,t,e),new vs(t,i)}static treeWalk(e,t,s,i,a){a instanceof xs&&i>0?(Ps.treeWalk(e,t,s+1,i-1,a.left),Ps.treeWalk(e,t|1<<s,s+1,i-1,a.right)):e[t]=Ps.treeCompress(a)}static treeDepth(e){if(e instanceof Ns)return 0;if(e instanceof vs)throw new Ce("assert");if(e instanceof xs){let t=Ps.treeDepth(e.left),s=Ps.treeDepth(e.right);return 1+(t<s?t:s)}return 0}}var Cs,Es,Fs,Ds,Ls,Ms,Is,As,Rs,Os,Vs,Hs,Gs,Ws,zs,Us,Xs,Js,Ys;!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"}(Cs||(Cs={}));class qs{constructor(){this.buffer=new Uint8Array(qs.BufferSize),this.pos=0}slide(){let e=new Uint8Array(qs.BufferSize);this.pos-=qs.Size,e.set(this.buffer.subarray(qs.Size,qs.Size+this.pos),0),this.buffer=e}addBytes(e,t,s){this.pos+s>qs.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+s),this.pos),this.pos+=s}addByte(e){this.pos===qs.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}qs.Size=32768,qs.BufferSize=65536;class js{static buildFixedHuffman(){let e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return Ps.make(e,0,288,10)}constructor(e){this._nbits=0,this._bits=0,this._state=Cs.Block,this._isFinal=!1,this._huffman=js._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new qs,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 Cs.Head:let e=this._input.readByte();if(8!==(15&e))throw new Ce("Invalid data");let t=this._input.readByte(),s=!!(32&t);if(((e<<8)+t)%31!=0)throw new Ce("Invalid data");if(s)throw new Ce("Unsupported dictionary");return this._state=Cs.Block,!0;case Cs.Crc:return this._state=Cs.Done,!0;case Cs.Done:return!1;case Cs.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:if(this._len=Re.readUInt16LE(this._input),Re.readUInt16LE(this._input)!==65535-this._len)throw new Ce("Invalid data");this._state=Cs.Flat;let e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=js._fixedHuffman,this._huffdist=null,this._state=Cs.CData,!0;case 2:let t=this.getBits(5)+257,s=this.getBits(5)+1,i=this.getBits(4)+4;for(let e=0;e<i;e++)this._lengths[js.CodeLengthsPos[e]]=this.getBits(3);for(let e=i;e<19;e++)this._lengths[js.CodeLengthsPos[e]]=0;this._huffman=Ps.make(this._lengths,0,19,8);let a=[];for(let e=0;e<t+s;e++)a.push(0);return this.inflateLengths(a,t+s),this._huffdist=Ps.make(a,t,s,16),this._huffman=Ps.make(a,0,t,16),this._state=Cs.CData,!0;default:throw new Ce("Invalid data")}case Cs.Flat:{let e=this._len<this._needed?this._len:this._needed,t=Re.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?Cs.Crc:Cs.Block),this._needed>0}case Cs.DistOne:{let e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=Cs.CData),this._needed>0}case Cs.Dist:for(;this._len>0&&this._needed>0;){let 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=Cs.CData),this._needed>0;case Cs.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?Cs.Crc:Cs.Block,!0;{i=i-257&255;let e=js.LenExtraBitsTbl[i];if(-1===e)throw new Ce("Invalid data");this._len=js.LenBaseValTbl[i]+this.getBits(e);let t=this._huffdist,s=t?this.applyHuffman(t):this.getRevBits(5);if(e=js.DistExtraBitsTbl[s],-1===e)throw new Ce("Invalid data");if(this._dist=js.DistBaseValTbl[s]+this.getBits(e),this._dist>this._window.available())throw new Ce("Invalid data");return this._state=1===this._dist?Cs.DistOne:Cs.Dist,!0}}return!1}addDistOne(e){let 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());let 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;let 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;){let 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:let r=s+3+this.getBits(2);if(r>t)throw new Ce("Invalid data");for(;s<r;)e[s]=i,s++;break;case 17:if(s+=3+this.getBits(3),s>t)throw new Ce("Invalid data");break;case 18:if(s+=11+this.getBits(7),s>t)throw new Ce("Invalid data");break;default:throw new Ce("Invalid data")}}}applyHuffman(e){if(e instanceof Ns)return e.n;if(e instanceof xs)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof vs)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new Ce("Invalid data")}}js.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],js.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],js.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],js.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],js.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],js._fixedHuffman=js.buildFixedHuffman();class Ks{constructor(e,t){this.fullName=e;let s=e.lastIndexOf("/");this.fileName=-1===s||s===e.length-1?this.fullName:e.substr(s+1),this.data=t}}Ks.OptionalDataDescriptorSignature=134695760,Ks.CompressionMethodDeflate=8,Ks.LocalFileHeaderSignature=67324752,Ks.CentralFileHeaderSignature=33639248,Ks.EndOfCentralDirSignature=101010256;class Qs{constructor(e){this._readable=e}read(){let e=[];for(;;){let t=this.readEntry();if(!t)break;e.push(t)}return e}readEntry(){let e=this._readable;if(Re.readInt32LE(e)!==Ks.LocalFileHeaderSignature)return null;Re.readUInt16LE(e);let t=Re.readUInt16LE(e),s=Re.readUInt16LE(e),i=0!==s;if(i&&s!==Ks.CompressionMethodDeflate)return null;Re.readInt16LE(this._readable),Re.readInt16LE(this._readable),Re.readInt32LE(e),Re.readInt32LE(e);let a,r=Re.readInt32LE(e),n=Re.readInt16LE(e),o=Re.readInt16LE(e),h=Re.toString(Re.readByteArray(e,n),"utf-8");if(e.skip(o),i){let e=Oe.empty(),t=new js(this._readable),s=new Uint8Array(65536);for(;;){let i=t.readBytes(s,0,s.length);if(e.write(s,0,i),i<s.length)break}a=e.toArray()}else a=Re.readByteArray(this._readable,r);if(8&t){Re.readInt32LE(this._readable)===Ks.OptionalDataDescriptorSignature&&Re.readInt32LE(this._readable),Re.readInt32LE(this._readable),Re.readInt32LE(this._readable)}return new Ks(h,a)}}class $s{constructor(){this.trackViewGroups=[]}}class Zs{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"}(Es||(Es={}));class ei{constructor(e,t){this.zoomLevel=4,this.view=Es.PageVertical,this.muiltiVoiceCursor=!1,this.scoreViews=[];const s=Oe.fromBuffer(t);this.zoomLevel=Re.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 $s;this.scoreViews.push(i);const a=e.scoreViews[t];for(let e=0;e<a.trackViewGroups.length;e++){const e=new Zs;e.isVisible=0!=s.readByte(),i.trackViewGroups.push(e)}}}apply(e){if(this.scoreViews.length>0){let t=0;for(let s of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){e.tracks[t].isVisibleOnMultiTrack=s.isVisible}t++}}}static writeForScore(e){const t=Oe.withCapacity(128);Re.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 ti extends j{get name(){return"Guitar Pro 7-8"}constructor(){super()}readScore(){ne.debug(this.name,"Loading ZIP entries");let e,t=new Qs(this.data);try{e=t.read()}catch(e){throw new Q("No Zip archive",e)}ne.debug(this.name,"Zip entries loaded");let s=null,i=null,a=null,r=null;for(let t of e)switch(t.fileName){case"score.gpif":s=Re.toString(t.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=t.data;break;case"PartConfiguration":a=t.data;break;case"LayoutConfiguration":r=t.data}if(!s)throw new Q("No score.gpif found in zip archive");ne.debug(this.name,"Start Parsing score.gpif");let n=new _s;n.parseXml(s,this.settings),ne.debug(this.name,"score.gpif parsed");let o=n.score;if(i){ne.debug(this.name,"Start Parsing BinaryStylesheet"),new us(i).apply(o),ne.debug(this.name,"BinaryStylesheet parsed")}let h=null;if(a&&(ne.debug(this.name,"Start Parsing Part Configuration"),h=new Ts(a),h.apply(o),ne.debug(this.name,"Part Configuration parsed")),r&&null!=h){ne.debug(this.name,"Start Parsing Layout Configuration"),new ei(h,r).apply(o),ne.debug(this.name,"Layout Configuration parsed")}return o}}class si extends K{constructor(){super(e.AlphaTabErrorType.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,si.prototype)}}class ii{constructor(e){this._currentByte=0,this._position=ii.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 si;this._position=0}const e=this._currentByte>>ii.ByteSize-this._position-1&1;return this._position++,e}readAll(){let e=Oe.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof si))throw e}return e.toArray()}}ii.ByteSize=8;class ai{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class ri{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){let t=new ii(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){let s,i=Oe.empty(),a=this.getInteger(e.readBytes(4),0);try{for(;i.length<a;){if(1===e.readBits(1)){let t=e.readBits(4),a=e.readBitsReversed(t),r=e.readBitsReversed(t),n=i.length-a,o=Math.min(a,r);s=i.getBuffer(),i.write(s,n,o)}else{let t=e.readBitsReversed(2);for(let s=0;s<t;s++)i.writeByte(e.readByte())}}}catch(e){if(!(e instanceof si))throw e}s=i.getBuffer();let r=t?4:0,n=i.length-r,o=new Uint8Array(n),h=n;return o.set(s.subarray(r,r+h),0),o}readBlock(e){let t=this.readHeader(e);if("BCFZ"===t)this.readUncompressedBlock(this.decompress(e,!0));else{if("BCFS"!==t)throw new Q("Unsupported format");this.readUncompressedBlock(e.readAll())}}readUncompressedBlock(e){let t=4096,s=t;for(;s+3<e.length;){if(2===this.getInteger(e,s)){let i=new ai;i.fileName=this.getString(e,s+4,127),i.fileSize=this.getInteger(e,s+140);let a=!this.fileFilter||this.fileFilter(i.fileName);a&&this.files.push(i);let r=s+148,n=0,o=0,h=a?Oe.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));let 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++){let 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]}}ri.HeaderBcFs="BCFS",ri.HeaderBcFz="BCFZ";class ni extends j{get name(){return"Guitar Pro 6"}constructor(){super()}readScore(){ne.debug(this.name,"Loading GPX filesystem");let e=new ri;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration")||e.endsWith("LayoutConfiguration"),e.load(this.data),ne.debug(this.name,"GPX filesystem loaded");let t=null,s=null,i=null,a=null;for(let r of e.files)switch(r.fileName){case"score.gpif":t=Re.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 Q("No score.gpif found in GPX");ne.debug(this.name,"Start Parsing score.gpif");let r=new _s;r.parseXml(t,this.settings),ne.debug(this.name,"score.gpif parsed");let n=r.score;if(s){ne.debug(this.name,"Start Parsing BinaryStylesheet"),new us(s).apply(n),ne.debug(this.name,"BinaryStylesheet parsed")}let o=null;if(i&&(ne.debug(this.name,"Start Parsing Part Configuration"),o=new Ts(i),o.apply(n),ne.debug(this.name,"Part Configuration parsed")),a&&null!=o){ne.debug(this.name,"Start Parsing Layout Configuration"),new ei(o,a).apply(n),ne.debug(this.name,"Layout Configuration parsed")}return n}}class oi extends j{get name(){return"MusicXML"}constructor(){super(),this._currentPartGroup=null,this._trackFirstMeasureNumber=0,this._maxVoices=0,this._currentDirection=null,this._currentChord=null,this._divisionsPerQuarterNote=0,this._voiceOfStaff=new Map,this._isBeamContinue=!1,this._previousBeatWasPulled=!1,this._previousBeat=null}readScore(){this._trackById=new Map,this._partGroups=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._slurStarts=new Map;let e=this.extractMusicXml(),t=new ys;try{t.parse(e)}catch(e){throw new Q("Unsupported format")}return this._score=new ve,this._score.tempo=120,this.parseDom(t),this.settings.importer.mergePartGroupsInMusicXml&&this.mergePartGroups(),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}extractMusicXml(){const e=new Qs(this.data);let t;try{t=e.read()}catch(e){t=[]}if(0===t.length)return this.data.reset(),Re.toString(this.data.readAll(),this.settings.importer.encoding);const s=t.find((e=>"META-INF/container.xml"===e.fullName));if(!s)throw new Q("No compressed MusicXML");const i=new ys;try{i.parse(Re.toString(s.data,this.settings.importer.encoding))}catch(e){throw new Q("Malformed container.xml, could not parse as XML",e)}let a=i.firstElement;if(!a||"container"!==a.localName)throw new Q("Malformed container.xml, root element not 'container'");const r=a.findChildElement("rootfiles");if(!r)throw new Q("Malformed container.xml, 'container/rootfiles' not found");let n="";for(const e of r.childNodes)if(e.nodeType==rs.Element&&"rootfile"===e.localName){n=e.getAttribute("full-path");break}if(!n)throw new Q("Unsupported compressed MusicXML, missing rootfile");const o=t.find((e=>e.fullName===n));if(!o)throw new Q(`Malformed container.xml, '${n}' not contained in zip`);return Re.toString(o.data,this.settings.importer.encoding)}mergePartGroups(){let e=!1;for(const t of this._partGroups.values())t.length>1&&(this.mergeGroup(t),e=!0);if(e)for(let e=0;e<this._score.tracks.length;e++)this._score.tracks[e].index=e}mergeGroup(e){let t=e[0];for(let s=1;s<e.length;s++){let i=e[s];for(let e of i.staves)t.addStaff(e);let a=this._score.tracks.indexOf(i);this._score.tracks.splice(a,1)}}parseDom(e){let t=e.firstElement;if(!t)throw new Q("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":break;default:throw new Q("Unsupported format")}}parsePartwise(e){for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"work":this.parseWork(t);break;case"movement-title":this._score.title=t.innerText;break;case"identification":this.parseIdentification(t);break;case"part-list":this.parsePartList(t);break;case"part":this.parsePart(t)}}parseWork(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"work-title"===t.localName)this._score.title=t.innerText}parsePart(e){let t=e.getAttribute("id");if(!this._trackById.has(t)){if(1!==this._trackById.size)return;for(const[e,s]of this._trackById)0!==s.staves.length&&0!==s.staves[0].bars.length||(t=e);if(!this._trackById.has(t))return}let s=this._trackById.get(t),i=!0;this._maxVoices=0;for(let t of e.childNodes)if(t.nodeType===rs.Element&&"measure"===t.localName)this.parseMeasure(t,s,i)&&(i=!1);for(let e of s.staves)for(let t of e.bars)this.ensureVoices(t)}parseMeasure(e,t,s){if("yes"===e.getAttribute("implicit")&&0===e.getElementsByTagName("note",!1).length)return!1;let i=0;if(s)this._divisionsPerQuarterNote=0,this._trackFirstMeasureNumber=parseInt(e.getAttribute("number")),this._trackFirstMeasureNumber||(this._trackFirstMeasureNumber=0),i=0;else{if(i=parseInt(e.getAttribute("number")),!i)return!1;i-=this._trackFirstMeasureNumber}if(s){let s=e.getElementsByTagName("attributes",!1);if(s.length>0){let e=s[0].getElementsByTagName("staves",!1);if(e.length>0){let s=parseInt(e[0].innerText);t.ensureStaveCount(s)}}}let a=new Array(t.staves.length),r=null;for(let e=t.staves[0].bars.length;e<=i;e++)for(let e=0;e<t.staves.length;e++){let s=new ee;if(a[e]=s,t.staves[e].bars.length>0){let i=t.staves[e].bars[t.staves[e].bars.length-1];s.clef=i.clef}r=this.getOrCreateMasterBar(i),t.staves[e].addBar(s),this.ensureVoices(s)}let n=new Map;if(r){let s=!1;for(let i of e.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"note":this.parseNoteBeat(i,a);break;case"forward":this.parseForward(i,a);break;case"direction":this.parseDirection(i,r);break;case"attributes":s||(this.parseAttributes(i,a,r,t),s=!0);break;case"harmony":this.parseHarmony(i,t,n);break;case"sound":break;case"barline":this.parseBarline(i,r)}}return!0}ensureVoices(e){for(;e.voices.length<this._maxVoices;){let t=new Ie;e.addVoice(t);let s=new Be;s.isEmpty=!0,s.chordId=this._currentChord,t.addBeat(s)}}getOrCreateBeat(e,t,s){let i=0,a=e.getElementsByTagName("voice",!1);a.length>0&&(i=parseInt(a[0].innerText)-1);let r=this._previousBeatWasPulled;this._previousBeatWasPulled=!1;let n,o,h=e.getElementsByTagName("staff",!1),l=1;if(h.length>0){l=parseInt(h[0].innerText),(this._isBeamContinue||r)&&this._previousBeat.voice.bar.staff.index!==l-1&&(l=this._previousBeat.voice.bar.staff.index+1,this._previousBeatWasPulled=!0);let e=t[0].staff.track.index+"-"+l;this._voiceOfStaff.has(e)||this._voiceOfStaff.set(e,i)}l--,n=l<0?t[0]:l>=t.length?t[t.length-1]:t[l];let d=this.getOrCreateVoice(n,i);return s&&d.beats.length>0||1===d.beats.length&&d.isEmpty?o=d.beats[d.beats.length-1]:(o=new Be,o.isEmpty=!1,d.addBeat(o)),this._isBeamContinue=!1,this._previousBeat=o,o}parseForward(e,t){let s=this.getOrCreateBeat(e,t,!1),i=parseInt(e.findChildElement("duration").innerText)*g.Quarter/this._divisionsPerQuarterNote,a=[g.SixtyFourth,g.ThirtySecond,g.Sixteenth,g.Eighth,g.Quarter,g.Half,g.Whole];for(let e of a)if(i>=e){s.duration=e,i-=e;break}s.isEmpty=!1}parseStaffDetails(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"staff-lines":for(let e of t.staves)e.stringTuning.tunings=new Array(parseInt(s.innerText)).fill(0);break;case"staff-tuning":this.parseStaffTuning(s,t)}for(let e of t.staves)this.isEmptyTuning(e.tuning)&&(e.stringTuning.tunings=[])}parseStaffTuning(e,t){let s=parseInt(e.getAttribute("line")),i="C",a="",r=0;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"tuning-step":i=t.innerText;break;case"tuning-alter":r=parseInt(t.innerText);break;case"tuning-octave":a=t.innerText}let n=de.getTuningForText(i+a)+r;for(let e of t.staves)e.tuning[e.tuning.length-s]=n}parseHarmony(e,t,s){let i=new Te;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"root":i.name=this.parseHarmonyRoot(t);break;case"kind":i.name=i.name+this.parseHarmonyKind(t);break;case"frame":this.parseHarmonyFrame(t,i)}this._currentChord=de.newGuid();const a=i.uniqueId;s.has(a)&&(i.showDiagram=!1);for(let e of t.staves)e.addChord(this._currentChord,i);s.set(a,i)}parseHarmonyRoot(e){let t="",s="";for(let i of e.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"root-step":t=i.innerText;break;case"root-alter":switch(parseInt(e.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{switch(e.innerText){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"}}return s}parseHarmonyFrame(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"frame-strings":const e=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=parseInt(s.innerText);break;case"frame-note":let i=null,a=null;for(let e of s.childNodes)switch(e.localName){case"string":i=parseInt(e.innerText);break;case"fret":a=parseInt(e.innerText),i&&a>=0&&(t.strings[i-1]=a);break;case"barre":i&&a&&"start"===e.getAttribute("type")&&t.barreFrets.push(a)}}}parseBarline(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"repeat":this.parseRepeat(s,t);break;case"ending":this.parseEnding(s,t)}}parseEnding(e,t){let s=parseInt(e.getAttribute("number"));s>0&&(--s,t.alternateEndings=t.alternateEndings|1<<s&255)}parseRepeat(e,t){let s=e.getAttribute("direction"),i=parseInt(e.getAttribute("times"));(i<0||isNaN(i))&&(i=2),"backward"===s?t.repeatCount=i:"forward"===s&&(t.isRepeatStart=!0)}parseNoteBeat(e,t){let s=e.getElementsByTagName("chord",!1).length>0,i=this.getOrCreateBeat(e,t,s);!i.chordId&&this._currentChord&&(i.chordId=this._currentChord,this._currentChord=null),this._currentDirection&&(i.text=this._currentDirection,this._currentDirection=null);let a=new me;i.voice.isEmpty=!1,i.isEmpty=!1,i.addNote(a),i.dots=0;let r=!1;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"grace":i.graceType=f.BeforeBeat,i.duration=g.ThirtySecond;break;case"duration":if(i.isRest&&!r){switch(parseInt(t.innerText)){case 1:i.duration=g.Whole;break;case 2:i.duration=g.Half;break;case 4:default:i.duration=g.Quarter;break;case 8:i.duration=g.Eighth;break;case 16:i.duration=g.Sixteenth;break;case 32:i.duration=g.ThirtySecond;break;case 64:i.duration=g.SixtyFourth}}break;case"tie":this.parseTied(t,a);break;case"cue":case"instrument":case"stem":break;case"type":i.duration=this.getDuration(t.innerText),i.graceType!==f.None&&i.duration<g.Sixteenth&&(i.duration=g.Eighth);break;case"dot":i.dots++;break;case"accidental":this.parseAccidental(t,a);break;case"time-modification":this.parseTimeModification(t,i);break;case"notehead":"yes"===t.getAttribute("parentheses")&&(a.isGhost=!0);break;case"beam":"continue"===t.innerText&&(this._isBeamContinue=!0);break;case"notations":this.parseNotations(t,i,a);break;case"lyric":this.parseLyric(t,i);break;case"pitch":this.parsePitch(t,a);break;case"unpitched":this.parseUnpitched(t,a);break;case"rest":r="yes"===t.getAttribute("measure"),i.isEmpty=!1,i.notes=[],i.duration=g.Whole}if(a.isStringed)for(let e=0;e<i.notes.length;e++)if(i.notes[e].string===a.string&&i.notes[e]!==a){i.removeNote(a);break}}getDuration(e){switch(e){case"256th":case"128th":case"64th":return g.SixtyFourth;case"32nd":return g.ThirtySecond;case"16th":return g.Sixteenth;case"eighth":return g.Eighth;case"quarter":return g.Quarter;case"half":return g.Half;case"long":case"breve":case"whole":return g.Whole}return g.Quarter}parseLyric(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element&&"text"===s.localName)t.text?t.text+=" "+s.innerText:t.text=s.innerText}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=S.ForceSharp;break;case"natural":t.accidentalMode=S.ForceNatural;break;case"flat":t.accidentalMode=S.ForceFlat}}parseTied(e,t){if("start"===e.getAttribute("type"))this._tieStartIds.has(t.id)||(this._tieStartIds.set(t.id,!0),this._tieStarts.push(t));else if("stop"===e.getAttribute("type")&&this._tieStarts.length>0&&!t.isTieDestination){const e=this._tieStarts[0];e.beat.voice.index===t.beat.voice.index&&e.beat.voice.bar.staff.index===t.beat.voice.bar.staff.index&&e.beat.voice.bar.staff.track.index===t.beat.voice.bar.staff.track.index&&(t.isTieDestination=!0,t.tieOrigin=this._tieStarts[0]),this._tieStarts.splice(0,1),this._tieStartIds.delete(t.id)}}parseNotations(e,t,s){for(let i of e.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"articulations":this.parseArticulations(i,s);break;case"tied":this.parseTied(i,s);break;case"slide":case"glissando":"start"===i.getAttribute("type")&&(s.slideOutType=w.Shift);break;case"dynamics":this.parseDynamics(i,t);break;case"technical":this.parseTechnical(i,s);break;case"ornaments":this.parseOrnaments(i,s);break;case"slur":let e=i.getAttribute("number");switch(e||(e="1"),e=t.voice.bar.staff.index+"_"+e,i.getAttribute("type")){case"start":this._slurStarts.set(e,s);break;case"stop":if(this._slurStarts.has(e)){s.isSlurDestination=!0;let t=this._slurStarts.get(e);t.slurDestination=s,s.slurOrigin=t}}}}parseOrnaments(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element&&"tremolo"===s.localName){switch(parseInt(s.innerText)){case 1:t.beat.tremoloSpeed=g.Eighth;break;case 2:t.beat.tremoloSpeed=g.Sixteenth;break;case 3:t.beat.tremoloSpeed=g.ThirtySecond}}}parseTechnical(e,t){let s=[];for(let i of e.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"string":t.string=parseInt(i.innerText),-2147483648!==t.string&&(t.string=t.beat.voice.bar.staff.tuning.length-t.string+1);break;case"fret":t.fret=parseInt(i.innerText);break;case"down-bow":t.beat.pickStroke=F.Down;break;case"up-bow":t.beat.pickStroke=F.Up;break;case"bend":s.push(i)}s.length>0&&this.parseBends(s,t),-2147483648!==t.string&&-2147483648!==t.fret||(t.string=-1,t.fret=-1)}parseBends(e,t){let s=se.MaxPosition/e.length,i=0,a=0,r=!0;for(let n of e){let e=n.findChildElement("bend-alter");if(e){let o=Math.round(2*Math.abs(parseFloat(e.innerText)));n.findChildElement("pre-bend")?r?(i+=o,t.addBendPoint(new se(a,i)),a+=s,t.addBendPoint(new se(a,i)),r=!1):a+=s:n.findChildElement("release")?(r&&(i+=o),t.addBendPoint(new se(a,i)),a+=s,i-=o,t.addBendPoint(new se(a,i)),r=!1):(t.addBendPoint(new se(a,i)),i+=o,a+=s,t.addBendPoint(new se(a,i)),r=!1)}}}parseArticulations(e,t){for(let s of e.childNodes)switch(s.localName){case"accent":t.accentuated=a.Normal;break;case"strong-accent":t.accentuated=a.Heavy;break;case"staccato":case"detached-legato":t.isStaccato=!0;break;case"tenuto":t.accentuated=a.Tenuto}}parseDynamics(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"p":t.dynamics=m.P;break;case"pp":t.dynamics=m.PP;break;case"ppp":t.dynamics=m.PPP;break;case"f":t.dynamics=m.F;break;case"ff":t.dynamics=m.FF;break;case"fff":t.dynamics=m.FFF;break;case"mp":t.dynamics=m.MP;break;case"mf":t.dynamics=m.MF}}parseTimeModification(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"actual-notes":t.tupletNumerator=parseInt(s.innerText);break;case"normal-notes":t.tupletDenominator=parseInt(s.innerText)}}parseUnpitched(e,t){let s="",i=0,a=0;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"display-step":s=t.innerText;break;case"display-alter":i=parseInt(t.innerText);break;case"display-octave":a=parseInt(t.innerText)}let r=12*a+de.getToneForText(s).noteValue+i;t.octave=r/12|0,t.tone=r-12*t.octave}parsePitch(e,t){let s="",i=0,a=0;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"step":s=t.innerText;break;case"alter":i=parseFloat(t.innerText),isNaN(i)&&(i=0);break;case"octave":a=parseInt(t.innerText)+1}let r=12*a+de.getToneForText(s).noteValue+(0|i);t.octave=r/12|0,t.tone=r-12*t.octave}getOrCreateVoice(e,t){if(t<e.voices.length)return e.voices[t];for(let s=e.voices.length;s<=t;s++)e.addVoice(new Ie);return this._maxVoices=Math.max(this._maxVoices,e.voices.length),e.voices[t]}parseDirection(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"sound":let e=s.getAttribute("tempo");if(e){let s=new $;s.isLinear=!0,s.type=r.Tempo,s.value=parseInt(e),t.tempoAutomations.push(s),0===t.index&&(t.score.tempo=s.value)}break;case"direction-type":let i=s.firstElement;switch(i.localName){case"words":this._currentDirection=i.innerText;break;case"metronome":this.parseMetronome(i,t)}}}parseMetronome(e,t){let s=g.Quarter,i=120;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"beat-unit":s=this.getDuration(t.innerText);break;case"per-minute":i=parseInt(t.innerText)}let a=new $;a.type=r.Tempo,a.value=i*(s/4)|0,this.hasSameTempo(t,a)||(t.tempoAutomations.push(a),0===t.index&&(t.score.tempo=a.value))}hasSameTempo(e,t){for(const s of e.tempoAutomations)if(t.ratioPosition===s.ratioPosition&&t.value==s.value)return!0;return!1}parseAttributes(e,t,s,i){let a=0,r=!1;for(let n of e.childNodes)if(n.nodeType===rs.Element)switch(n.localName){case"divisions":this._divisionsPerQuarterNote=parseInt(n.innerText);break;case"key":this.parseKey(n,s);break;case"time":this.parseTime(n,s),r=!0;break;case"clef":a=parseInt(n.getAttribute("number")),isNaN(a)&&(a=1),this.parseClef(n,t[a-1]);break;case"staff-details":this.parseStaffDetails(n,i);break;case"transpose":this.parseTranspose(n,i)}r||(s.timeSignatureCommon=!0)}parseTranspose(e,t){let s=0;for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"chromatic":s+=parseInt(t.innerText);break;case"octave-change":s+=12*parseInt(t.innerText)}for(let e of t.staves)e.transpositionPitch=s}parseClef(e,t){let s="s",i=0;for(let a of e.childNodes)if(a.nodeType===rs.Element)switch(a.localName){case"sign":s=a.innerText.toLowerCase();break;case"line":i=parseInt(a.innerText);break;case"clef-octave-change":switch(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){"common"===e.getAttribute("symbol")&&(t.timeSignatureCommon=!0);let s=!1,i=!1;for(let a of e.childNodes)if(a.nodeType===rs.Element){let e=a.innerText;switch(a.localName){case"beats":s||(-1===e.indexOf("+")?t.timeSignatureNumerator=parseInt(e):t.timeSignatureNumerator=4,s=!0);break;case"beat-type":i||(-1===e.indexOf("+")?t.timeSignatureDenominator=parseInt(e):t.timeSignatureDenominator=4,i=!0)}}}parseKey(e,t){let s=-2147483648,i="";for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"fifths":s=parseInt(t.innerText);break;case"key-step":case"key-alter":break;case"mode":i=t.innerText}t.keySignature=-7<=s&&s<=7?s:P.C,t.keySignatureType="minor"===i?C.Minor:C.Major}getOrCreateMasterBar(e){if(e<this._score.masterBars.length)return this._score.masterBars[e];for(let t=this._score.masterBars.length;t<=e;t++){let e=new oe;if(this._score.masterBars.length>0){let t=this._score.masterBars[this._score.masterBars.length-1];e.timeSignatureDenominator=t.timeSignatureDenominator,e.timeSignatureNumerator=t.timeSignatureNumerator,e.keySignature=t.keySignature,e.keySignatureType=t.keySignatureType}this._score.addMasterBar(e)}return this._score.masterBars[e]}parseIdentification(e){for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"creator":"composer"===t.getAttribute("type")&&(this._score.music=t.innerText);break;case"rights":this._score.copyright&&(this._score.copyright+="\n"),this._score.copyright+=t.innerText}}parsePartList(e){for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"part-group":this.parsePartGroup(t);break;case"score-part":this.parseScorePart(t)}}parsePartGroup(e){switch(e.getAttribute("type")){case"start":this._currentPartGroup=e.getAttribute("number"),this._partGroups.set(this._currentPartGroup,[]);break;case"stop":this._currentPartGroup=null}}parseScorePart(e){let t=e.getAttribute("id"),s=new Me;s.ensureStaveCount(1),s.staves[0].showStandardNotation=!0,this._trackById.set(t,s),this._score.addTrack(s),this._currentPartGroup&&this._partGroups.get(this._currentPartGroup).push(s);for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"part-name":s.name=t.innerText;break;case"part-abbreviation":s.shortName=t.innerText;break;case"midi-instrument":this.parseMidiInstrument(t,s)}this.isEmptyTuning(s.staves[0].tuning)&&(s.staves[0].stringTuning.tunings=[])}isEmptyTuning(e){if(!e)return!0;for(let t=0;t<e.length;t++)if(0!==e[t])return!1;return!0}parseMidiInstrument(e,t){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"midi-channel":t.playbackInfo.primaryChannel=parseInt(s.innerText);break;case"midi-program":t.playbackInfo.program=parseInt(s.innerText);break;case"volume":t.playbackInfo.volume=Math.floor(parseInt(s.innerText)/100*16);break;case"pan":t.playbackInfo.balance=Math.max(0,Math.min(16,Math.floor((parseInt(s.innerText)+90)/180*16)))}}}class hi{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event.type==Ke.AlphaTabMetronome}static newMetronomeEvent(e,t,s,i,a){const r=new ut(0,t,s,i,a);return new hi(e,r)}}class li{constructor(e,t,s){this.bpm=e,this.ticks=t,this.time=s}}class di{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=te.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class ci{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 di,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){let e=this._synthesizer.metronomeVolume;this._synthesizer.noteOffAll(!0),this._synthesizer.resetSoft(),this._synthesizer.setupMetronomeChannel(e)}this.mainSilentProcess(e)}}mainSilentProcess(e){if(e<=0)return;let 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(Ve.MicroBufferSize);this._mainState.currentTime=s;let i=Date.now()-t;ne.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 di;this.percussionKeys.add(Ve.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,d=0;for(let c of e.events){let u=new hi(t.synthData.length,c);t.synthData.push(u);let p=c.tick-d;if(i+=p,a+=p*(6e4/(s*e.division)),u.time=a,d=c.tick,n>0)for(;h<i;){let e=hi.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(c.type===Ke.TempoChange){s=6e7/c.microSecondsPerQuarterNote,t.tempoChanges.push(new li(s,i,a)),o=n*(6e4/(s*e.division))}else if(c.type===Ke.TimeSignature){let i=c,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(c.type===Ke.ProgramChange){const e=c;let s=e.channel;t.firstProgramEventPerChannel.has(s)||t.firstProgramEventPerChannel.set(s,u);s===Ve.PercussionChannel||this.instrumentPrograms.add(e.program)}else if(c.type==Ke.NoteOn){const e=c;e.channel===Ve.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=Ve.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 di;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 li(t,0,0));let a=e.division*(4/i)|0,r=a*(6e4/(t*this._mainState.division)),n=0,o=0;for(let t=0;t<s;t++){let s=hi.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"}(Fs||(Fs={}));class ui{constructor(e,t){this.state=e,this.stopped=t}}class pi{constructor(e,t,s,i,a){this.currentTime=e,this.endTime=t,this.currentTick=s,this.endTick=i,this.isSeek=a}}class gi{constructor(){this.id="",this.size=0}static load(e,t,s){if(e&&gi.HeaderSize>e.size)return!1;if(s.position+gi.HeaderSize>=s.length)return!1;if(t.id=Re.read8BitStringLength(s,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=Re.readUInt32LE(s),e&&gi.HeaderSize+t.size>e.size)return!1;e&&(e.size-=gi.HeaderSize+t.size);let i="RIFF"===t.id,a="LIST"===t.id;return(!i||!e)&&(!i&&!a||(t.id=Re.read8BitStringLength(s,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}gi.HeaderSize=8;class mi{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"}(Ds||(Ds={}));class fi{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==Re.readInt32LE(this._readable))return!0;this._readable.position-=3}return!1}readPage(t){const s=this._readable.readByte();if(-1===s||0!==s)return!1;const i=this._readable.readByte(),a=Re.readInt64LE(this._readable);this._readable.skip(4),this._readable.skip(4),this._readable.skip(4);const r=this._readable.readByte();if(-1==r)return!1;const n=[];let o=0;for(let e=0;e<r;e++){const e=this._readable.readByte();o==n.length&&n.push(0),n[o]+=e,e<255&&o++}for(let s=0;s<n.length;s++){const r=new Uint8Array(n[s]);if(this._readable.read(r,0,r.length)!=r.length)return!1;if(i&Ds.ContinuesPacket){if(0==t.length)throw new K(e.AlphaTabErrorType.Format,"OGG: Continuation page without any previous packets");t[t.length-1].addData(r)}else{const e=new mi(r,!!(i&Ds.BeginningOfStream)&&0==s,!!(i&Ds.EndOfStream)&&s==n.length-1,a);t.push(e)}}return!0}}class yi{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 bi{constructor(){this.value=0,this.bitsRead=0}}class Si{constructor(e){this._bitBucket=0n,this._bitCount=0n,this._overflowBits=0n,this._source=e}readByte(){return this.readBits(Si.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(t){if(t<0||t>32)throw new K(e.AlphaTabErrorType.General,"IO: Cannot read more than 32 bits in one go");if(0==t)return new bi;const s=new bi;for(;this._bitCount<t;){const e=BigInt(this._source.readByte());if(-1n==e)return s.bitsRead=Number(this._bitCount),s.value=Number(this._bitBucket),this._bitBucket=0n,this._bitCount=0n,s;this._bitBucket=(0xffn&e)<<this._bitCount|this._bitBucket,this._bitCount+=8n,this._bitCount>32&&(this._overflowBits=e>>40n-this._bitCount&0xffn)}let i=this._bitBucket;return t<64&&(i&=(1n<<BigInt(t))-1n),s.value=Number(i),s.bitsRead=t,s}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)}}}}Si.ByteSize=8;class _i{constructor(){this.codebooks=[],this.timeDomainTransforms=[],this.floors=[],this.residues=[],this.mappings=[],this.modes=[]}}class wi{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 Bi{constructor(e){this._data=e}get(e){return this._data[e]}}class Ti{get(e){return e}}Ti.instance=new Ti;class ki{constructor(t,s){this._maxBits=0,this._overflowList=null,this._prefixList=null,this._prefixBitLength=0,this.dimensions=0,this.entries=0,this.mapType=0;if(5653314!=t.readBits(24))throw new K(e.AlphaTabErrorType.Format,"Vorbis: Book header had invalid signature!");this.dimensions=t.readBits(16),this.entries=t.readBits(24),this._lengths=new Int32Array(this.entries),this.initTree(t,s),this.initLookupTable(t)}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(t,s){let i,a,r=0;if(t.readBit()){let e=t.readBits(5)+1;for(let s=0;s<this.entries;){let i=t.readBits(wi.ilog(this.entries-s));for(;--i>=0;)this._lengths[s++]=e;++e}r=0,i=!1,a=e}else{a=-1,i=t.readBit();for(let e=0;e<this.entries;e++)!i||t.readBit()?(this._lengths[e]=t.readBits(5)+1,++r):this._lengths[e]=-1,this._lengths[e]>a&&(a=this._lengths[e])}if(this._maxBits=a,a>-1){let t,a=null;i&&r>=this.entries>>2&&(a=new Int32Array(this.entries),a.set(this._lengths.subarray(0,this.entries),0),i=!1),t=i?r:0;let n=null,o=null;if(i?0!=t&&(a=new Int32Array(t),o=new Int32Array(t),n=new Int32Array(t)):o=new Int32Array(this.entries),!this.computeCodewords(i,o,a,this._lengths,this.entries,n))throw new K(e.AlphaTabErrorType.Format,"Vorbis: Failed to compute codewords");const h=null==n?Ti.instance:new Bi(n);s.generateTable(h,a??this._lengths,o),this._prefixList=s.prefixTree,this._prefixBitLength=s.tableBits,this._overflowList=s.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;let o=n[a];if(n[a]=0,this.addEntry(e,t,s,wi.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=wi.convertFromVorbisFloat32(e.readBits(32)),s=wi.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 d=o[e/h%r|0]*s+t+i;n[e*this.dimensions+l]=d,a&&(i=d),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 xi{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>xi.MAX_TABLE_BITS?xi.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}}xi.MAX_TABLE_BITS=10;class vi{constructor(e){e.readBits(16)}}class Pi{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(t,s,i,a){if(this._order=t.readBits(8),this._rate=t.readBits(16),this._bark_map_size=t.readBits(16),this._ampBits=t.readBits(6),this._ampOfs=t.readBits(8),this._books=new Array(t.readBits(4)+1),this._order<1||this._rate<1||this._bark_map_size<1||0==this._books.length)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Floor0 Data");this._ampDiv=(1<<this._ampBits)-1;for(let s=0;s<this._books.length;s++){const i=t.readBits(8);if(i<0||i>=a.length)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Floor0 Data");const r=a[i];if(0==r.mapType||r.dimensions<1)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Floor0 Data");this._books[s]=r}this._bookBits=wi.ilog(this._books.length),this._barkMaps=new Map([[s,this.synthesizeBarkCurve(s/2)],[i,this.synthesizeBarkCurve(i/2)]]),this._wMap=new Map([[s,this.synthesizeWDelMap(s/2)],[i,this.synthesizeWDelMap(i/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){var i=new Pi(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;var 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,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 Ei{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 Fi{constructor(t,s){let i=-1;this._partitionClass=new Int32Array(t.readBits(5));for(let e=0;e<this._partitionClass.length;e++)this._partitionClass[e]=t.readBits(4),this._partitionClass[e]>i&&(i=this._partitionClass[e]);++i,this._classDimensions=new Int32Array(i),this._classSubclasses=new Int32Array(i),this._classMasterbooks=new Array(i),this._classMasterBookIndex=new Int32Array(i),this._subclassBooks=new Array(i),this._subclassBookIndex=new Array(i);for(let e=0;e<i;e++){this._classDimensions[e]=t.readBits(3)+1,this._classSubclasses[e]=t.readBits(2),this._classSubclasses[e]>0&&(this._classMasterBookIndex[e]=t.readBits(8),this._classMasterbooks[e]=s[this._classMasterBookIndex[e]]),this._subclassBooks[e]=new Array(1<<this._classSubclasses[e]),this._subclassBookIndex[e]=new Int32Array(this._subclassBooks[e].length);for(let i=0;i<this._subclassBooks[e].length;i++){const a=t.readBits(8)-1;a>=0&&(this._subclassBooks[e][i]=s[a]),this._subclassBookIndex[e][i]=a}}this._multiplier=t.readBits(2),this._range=Fi._rangeLookup[this._multiplier],this._yBits=Fi._yBitsLookup[this._multiplier],++this._multiplier;const a=t.readBits(4),r=[];r.push(0),r.push(1<<a);for(let e=0;e<this._partitionClass.length;e++){const s=this._partitionClass[e];for(let e=0;e<this._classDimensions[s];e++)r.push(t.readBits(a))}this._xList=new Int32Array(r),this._lNeigh=new Int32Array(r.length),this._hNeigh=new Int32Array(r.length),this._sortIdx=new Int32Array(r.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 t=0;t<this._sortIdx.length-1;t++)for(let s=t+1;s<this._sortIdx.length;s++){if(this._xList[t]==this._xList[s])throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Floor1 Data");if(this._xList[this._sortIdx[t]]>this._xList[this._sortIdx[s]]){const e=this._sortIdx[t];this._sortIdx[t]=this._sortIdx[s],this._sortIdx[s]=e}}}unpack(e,t,s){var i=new Ei;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,h=i.posts[0]*this._multiplier;for(let l=1;l<i.postCount;l++){var r=this._sortIdx[l];if(e[r]){var n=this._xList[r],o=i.posts[r]*this._multiplier;t<a&&this.renderLineMulti(t,h,Math.min(n,a),o,s),t=n,h=o}if(t>=a)break}t<a&&this.renderLineMulti(t,h,a,h,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 d;d=h<l?2*h:2*l,0!=o?(t[a]=!0,t[r]=!0,t[i]=!0,s[i]=o>=d?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){var 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 d=e,c=t,u=-n;for(a[e]*=Fi.inverse_dB_table[t],o-=Math.abs(l)*n;++d<s;)c+=l,u+=o,u>=0&&(u-=n,c+=h),a[d]*=Fi.inverse_dB_table[c]}}Fi._rangeLookup=[256,128,86,64],Fi._yBitsLookup=[8,7,7,6],Fi.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 Di{constructor(t,s,i,a){const r=t.readBits(16);switch(r){case 0:this.floor=new Ci(t,s,i,a);break;case 1:this.floor=new Fi(t,a);break;default:throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Floor type: "+r)}}apply(e,t,s){this.floor.apply(e,t,s)}unpack(e,t,s){return this.floor.unpack(e,t,s)}}class Li{constructor(t,s,i){this._begin=t.readBits(24),this._end=t.readBits(24),this._partitionSize=t.readBits(24)+1,this._classifications=t.readBits(6)+1,this._classBook=i[t.readBits(8)],this._cascade=new Int32Array(this._classifications);let a=0;for(let e=0;e<this._classifications;e++){const s=t.readBits(3);t.readBit()?this._cascade[e]=t.readBits(5)<<3|s:this._cascade[e]=s,a+=Li.icount(this._cascade[e])}const r=new Int32Array(a);for(let s=0;s<a;s++)if(r[s]=t.readBits(8),0==i[r[s]].mapType)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Residue 0");const n=this._classBook.entries;let o=this._classBook.dimensions,h=1;for(;o>0;){if(h*=this._classifications,h>n)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Residue 0");--o}this._books=new Array(this._classifications),a=0;let l,d=0;for(let e=0;e<this._classifications;e++)if(l=wi.ilog(this._cascade[e]),this._books[e]=new Array(l),l>0){d=Math.max(d,l);for(let t=0;t<l;t++)(this._cascade[e]&1<<t)>0&&(this._books[e][t]=i[r[a++]])}this._maxStages=d,this._decodeMap=new Array(h);for(let e=0;e<h;e++){let t=e,s=h/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=s}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 d=r[l][n][o];if(this._cascade[d]&1<<s){const r=this._books[d][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 Li{constructor(e,t,s){super(e,t,s)}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 Ii extends Li{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 Ai{constructor(t,s,i){const a=t.readBits(16);switch(a){case 0:this.residue=new Li(t,s,i);break;case 1:this.residue=new Mi(t,s,i);break;case 2:this.residue=new Ii(t,s,i);break;default:throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid Residue type: "+a)}}decode(e,t,s,i){this.residue.decode(e,t,s,i)}}class Ri{constructor(t,s,i,a,r){if(0!==t.readBits(16))throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid mapping type!");let n=1;t.readBit()&&(n+=t.readBits(4));let o=0;t.readBit()&&(o=t.readBits(8)+1);const h=wi.ilog(s-1);this._couplingAngle=new Int32Array(o),this._couplingMangitude=new Int32Array(o);for(let i=0;i<o;i++){const a=t.readBits(h),r=t.readBits(h);if(a==r||a>s-1||r>s-1)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid magnitude or angle in mapping header!");this._couplingAngle[i]=r,this._couplingMangitude[i]=a}if(0!=t.readBits(2))throw new K(e.AlphaTabErrorType.Format,"Vorbis: Reserved bits not 0 in mapping header.");const l=new Int32Array(s);if(n>1)for(let i=0;i<s;i++)if(l[i]=t.readBits(4),l[i]>n)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid channel mux submap index in mapping header!");this._submapFloor=new Array(n),this._submapResidue=new Array(n);for(let s=0;s<n;s++){t.skipBits(8);const r=t.readBits(8);if(r>=i.length)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid floor number in mapping header!");const n=t.readBits(8);if(n>=a.length)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Invalid residue number in mapping header!");this._submapFloor[s]=i[r],this._submapResidue[s]=a[n]}this._channelFloor=new Array(s),this._channelResidue=new Array(s);for(let e=0;e<s;e++)this._channelFloor[e]=this._submapFloor[l[e]],this._channelResidue[e]=this._submapResidue[l[e]];this._mdct=r}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(var n=0;n<i;n++){let e,s;const i=t[n],r=a[n];i>0?r>0?(e=i,s=i-r):(s=i,e=i+r):r>0?(e=i,s=i+r):(s=i,e=i-r),t[n]=e,a[n]=s}}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 Oi{constructor(){this.packetStartIndex=0,this.packetTotalLength=0,this.packetValidLength=0}}class Vi{constructor(){this.overlapInfo=new Oi,this.windowIndex=0}}class Hi{constructor(e=null){this.samplePosition=null,this.samplePosition=e}}class Gi{constructor(t,s,i,a,r){if(this._overlapInfo=null,this._channels=s,this._blockFlag=t.readBit(),0!=t.readBits(32))throw new K(e.AlphaTabErrorType.Format,"Vorbis: Mode header had invalid window or transform type!");const n=t.readBits(8);if(n>=r.length)throw new K(e.AlphaTabErrorType.Format,"Vorbis: Mode header had invalid mapping index!");this._mapping=r[n],this._blockFlag?(this._blockSize=a,this._windows=[Gi.calcWindow(i,a,i),Gi.calcWindow(a,a,i),Gi.calcWindow(i,a,a),Gi.calcWindow(a,a,a)],this._overlapInfo=[Gi.calcOverlap(i,a,i),Gi.calcOverlap(a,a,i),Gi.calcOverlap(i,a,a),Gi.calcOverlap(a,a,a)]):(this._blockSize=i,this._windows=[Gi.calcWindow(i,i,i)])}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 Vi;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*Gi.M_PI2);t*=t,i[n+e]=Math.sin(t*Gi.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*Gi.M_PI2);t*=t,i[o+e]=Math.sin(t*Gi.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 Oi;return o.packetStartIndex=a,o.packetValidLength=n,o.packetTotalLength=r,o}}Gi.M_PI2=1.57079632695;class Wi{constructor(e){this._n=e,this._n2=e>>1,this._n4=this._n2>>1,this._n8=this._n4>>1,this._ld=wi.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*Wi.M_PI/e),this._a[s+1]=-Math.sin(4*t*Wi.M_PI/e),this._b[s]=.5*Math.cos((s+1)*Wi.M_PI/e/2),this._b[s+1]=.5*Math.sin((s+1)*Wi.M_PI/e/2);for(t=0,s=0;t<this._n8;++t,s+=2)this._c[s]=Math.cos(2*(s+1)*Wi.M_PI/e),this._c[s+1]=-Math.sin(2*(s+1)*Wi.M_PI/e);this._bitrev=new Uint16Array(this._n8);for(let e=0;e<this._n8;++e)this._bitrev[e]=Ae.int32ToUint16(wi.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,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}}for(var r=0,n=0,o=this._n2-4;n<o;){let e,t,i,a,h,l;e=s[n]-s[o+2],t=s[n+1]+s[o+3],i=this._c[r+1]*e+this._c[r]*t,a=this._c[r+1]*t-this._c[r]*e,h=s[n]+s[o+2],l=s[n+1]-s[o+3],s[n]=h+i,s[n+1]=l+a,s[o+2]=h-i,s[o+3]=a-l,e=s[n+2]-s[o],t=s[n+3]+s[o+1],i=this._c[r+3]*e+this._c[r+2]*t,a=this._c[r+3]*t-this._c[r+2]*e,h=s[n+2]+s[o],l=s[n+3]-s[o+1],s[n+2]=h+i,s[n+3]=l+a,s[o]=h-i,s[o+1]=a-l,r+=4,n+=4,o-=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,d,c;c=i[s+6]*this._b[t+7]-i[s+7]*this._b[t+6],d=-i[s+6]*this._b[t+6]-i[s+7]*this._b[t+7],e[a]=c,e[r+3]=-c,e[n]=d,e[o+3]=d,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,c=i[s+2]*this._b[t+3]-i[s+3]*this._b[t+2],d=-i[s+2]*this._b[t+2]-i[s+3]*this._b[t+3],e[a+2]=c,e[r+1]=-c,e[n+2]=d,e[o+1]=d,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){var 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){var o=this._a[a],h=this._a[a+1],l=this._a[a+r],d=this._a[a+r+1],c=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*d,t[b-3]=f*l+m*d,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*c-f*u,t[b-5]=f*c+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){let s,i,a,r,n,o,h,l;s=e[t]-e[t-4],n=e[t]+e[t-4],h=e[t-2]+e[t-6],a=e[t-2]-e[t-6],e[t]=n+h,e[t-2]=n-h,r=e[t-3]-e[t-7],e[t-4]=s+r,e[t-6]=s-r,i=e[t-1]-e[t-5],o=e[t-1]+e[t-5],l=e[t-3]+e[t-7],e[t-1]=o+l,e[t-3]=o-l,e[t-5]=i-a,e[t-7]=i+a}}Wi.M_PI=3.141592653589793;class zi{constructor(){this._setupCache=new Map}reverse(e,t){let s;this._setupCache.has(t)?s=this._setupCache.get(t):(s=new Wi(t),this._setupCache.set(t,s)),s.calcReverse(e)}}class Ui{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=wi.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?(Ui.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 Hi(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 Si(Oe.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"}(Ls||(Ls={}));class Ji{constructor(e){this._packetIndex=-1,this._packets=e}read(){let e;for(;;){if(e=this.nextPacket(),null==e)return null;if(e.isBeginningOfStream){var 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 yi;if(!this.readIdentificationHeader(t,e))return null;if(!this.readComments(this.nextPacket()))return null;const s=new _i;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 Ui(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<Ji.VorbisHeaderMarker.length;e++)if(s[1+e]!==Ji.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<Ji.VorbisHeaderMarker.length;e++)if(s[1+e]!==Ji.VorbisHeaderMarker[e])return!1;return!0}readIdentificationHeader(e,t){const s=Oe.fromBuffer(t.packetData);if(!this.comonHeaderDecode(Ls.IdentificationHeader,s))return!1;if(0!=Re.readUInt32LE(s))return!1;if(e.audioChannels=s.readByte(),e.audioSampleRate=Re.readUInt32LE(s),e.audioChannels<=0||e.audioSampleRate<=0)return!1;e.bitrateMaximum=Re.readInt32LE(s),e.bitrateNominal=Re.readInt32LE(s),e.bitrateMinimum=Re.readInt32LE(s);var i=s.readByte();if(e.blocksize0=1<<(15&i),e.blocksize1=1<<(i>>4),e.blocksize0>e.blocksize1||!Ji.isAllowedBlockSize(e.blocksize0)||!Ji.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;var t=Oe.fromBuffer(e.packetData);if(!this.comonHeaderDecode(Ls.Comment,t))return!1;const s=Re.readUInt32LE(t);t.skip(s);var i=Re.readUInt32LE(t);for(let e=0;e<i;e++){const e=Re.readUInt32LE(t);t.skip(e)}return 0!=t.readByte()}readSetupHeader(e,t,s){if(null==s)return!1;const i=new Si(Oe.fromBuffer(s.packetData)),a=new zi,r=new xi;if(!this.comonHeaderDecodeBit(Ls.SetupHeader,i))return!1;let n=i.readByte()+1;for(let e=0;e<n;e++)t.codebooks.push(new ki(i,r));n=i.readBits(6)+1;for(let e=0;e<n;e++)t.timeDomainTransforms.push(new vi(i));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.floors.push(new Di(i,e.blocksize0,e.blocksize1,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.residues.push(new Ai(i,e.audioChannels,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.mappings.push(new Ri(i,e.audioChannels,t.floors,t.residues,a));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.modes.push(new Gi(i,e.audioChannels,e.blocksize0,e.blocksize1,t.mappings));return!!i.readBit()}}Ji.VorbisHeaderMarker=new Uint8Array(["v".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"b".charCodeAt(0),"i".charCodeAt(0),"s".charCodeAt(0)]);class Yi{constructor(e){this.streams=[];for(var t=new fi(e).read(),s=new Ji(t);;){let e=s.read();if(null==e)break;this.streams.push(e)}}}class qi{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 Yi(Oe.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 gi,s=new gi;if(!gi.load(null,t,e)||"sfbk"!==t.id)throw new Ce("Soundfont is not a valid Soundfont2 file");for(;gi.load(t,s,e);){let t=new gi;if("pdta"===s.id)for(;gi.load(s,t,e);)switch(t.id){case"phdr":for(let s=0,i=t.size/ta.SizeInFile|0;s<i;s++)this.phdrs.push(new ta(e));break;case"pbag":for(let s=0,i=t.size/Zi.SizeInFile|0;s<i;s++)this.pbags.push(new Zi(e));break;case"pmod":for(let s=0,i=t.size/sa.SizeInFile|0;s<i;s++)this.pmods.push(new sa(e));break;case"pgen":for(let s=0,i=t.size/ea.SizeInFile|0;s<i;s++)this.pgens.push(new ea(e));break;case"inst":for(let s=0,i=t.size/$i.SizeInFile|0;s<i;s++)this.insts.push(new $i(e));break;case"ibag":for(let s=0,i=t.size/ji.SizeInFile|0;s<i;s++)this.ibags.push(new ji(e));break;case"imod":for(let s=0,i=t.size/Ki.SizeInFile|0;s<i;s++)this.imods.push(new Ki(e));break;case"igen":for(let s=0,i=t.size/Qi.SizeInFile|0;s<i;s++)this.igens.push(new Qi(e));break;case"shdr":for(let s=0,i=t.size/ia.SizeInFile|0;s<i;s++)this.sHdrs.push(new ia(e));break;default:e.position+=t.size}else if("sdta"===s.id)for(;gi.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 ji{constructor(e){this.instGenNdx=Re.readUInt16LE(e),this.instModNdx=Re.readUInt16LE(e)}}ji.SizeInFile=4;class Ki{constructor(e){this.modSrcOper=Re.readUInt16LE(e),this.modDestOper=Re.readUInt16LE(e),this.modAmount=Re.readInt16LE(e),this.modAmtSrcOper=Re.readUInt16LE(e),this.modTransOper=Re.readUInt16LE(e)}}Ki.SizeInFile=10;class Qi{constructor(e){this.genOper=Re.readUInt16LE(e),this.genAmount=new aa(e)}}Qi.SizeInFile=4;class $i{constructor(e){this.instName=Re.read8BitStringLength(e,20),this.instBagNdx=Re.readUInt16LE(e)}}$i.SizeInFile=22;class Zi{constructor(e){this.genNdx=Re.readUInt16LE(e),this.modNdx=Re.readUInt16LE(e)}}Zi.SizeInFile=4;class ea{constructor(e){this.genOper=Re.readUInt16LE(e),this.genAmount=new aa(e)}}ea.SizeInFile=4,ea.GenInstrument=41,ea.GenKeyRange=43,ea.GenVelRange=44,ea.GenSampleId=53;class ta{constructor(e){this.presetName=Re.read8BitStringLength(e,20),this.preset=Re.readUInt16LE(e),this.bank=Re.readUInt16LE(e),this.presetBagNdx=Re.readUInt16LE(e),this.library=Re.readUInt32LE(e),this.genre=Re.readUInt32LE(e),this.morphology=Re.readUInt32LE(e)}}ta.SizeInFile=38;class sa{constructor(e){this.modSrcOper=Re.readUInt16LE(e),this.modDestOper=Re.readUInt16LE(e),this.modAmount=Re.readUInt16LE(e),this.modAmtSrcOper=Re.readUInt16LE(e),this.modTransOper=Re.readUInt16LE(e)}}sa.SizeInFile=10;class ia{constructor(e){this.sampleName=Re.read8BitStringLength(e,20),this.start=Re.readUInt32LE(e),this.end=Re.readUInt32LE(e),this.startLoop=Re.readUInt32LE(e),this.endLoop=Re.readUInt32LE(e),this.sampleRate=Re.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=Re.readSInt8(e),this.sampleLink=Re.readUInt16LE(e),this.sampleType=Re.readUInt16LE(e)}}ia.SizeInFile=46;class aa{get shortAmount(){return Ae.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}constructor(e){this.wordAmount=Re.readUInt16LE(e)}}class ra{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 na{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"}(Ms||(Ms={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(Is||(Is={}));class oa{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null}}class ha{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 la{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:ha.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:ha.timecents2Secs(this.attack),this.release=this.release<-11950?0:ha.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:ha.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:ha.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?ha.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"}(As||(As={}));class da{constructor(e){this.loopMode=Ms.None,this.samples=da.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 la,this.modEnv=new la,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 la(e.ampEnv),this.modEnv=new la(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=Ms.None,this.samples=da.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 As.StartAddrsOffset:this.offset+=Ae.int16ToUint32(t.shortAmount);break;case As.EndAddrsOffset:this.end+=Ae.int16ToUint32(t.shortAmount);break;case As.StartloopAddrsOffset:this.loopStart+=Ae.int16ToUint32(t.shortAmount);break;case As.EndloopAddrsOffset:this.loopEnd+=Ae.int16ToUint32(t.shortAmount);break;case As.StartAddrsCoarseOffset:this.offset+=32768*Ae.int16ToUint32(t.shortAmount);break;case As.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case As.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case As.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case As.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case As.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case As.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case As.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case As.EndAddrsCoarseOffset:this.end+=32768*Ae.int16ToUint32(t.shortAmount);break;case As.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case As.Pan:this.pan=t.shortAmount/1e3;break;case As.DelayModLFO:this.delayModLFO=t.shortAmount;break;case As.FreqModLFO:this.freqModLFO=t.shortAmount;break;case As.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case As.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case As.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case As.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case As.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case As.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case As.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case As.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case As.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case As.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case As.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case As.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case As.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case As.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case As.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case As.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case As.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case As.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case As.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case As.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case As.StartloopAddrsCoarseOffset:this.loopStart+=32768*Ae.int16ToUint32(t.shortAmount);break;case As.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case As.EndloopAddrsCoarseOffset:this.loopEnd+=32768*Ae.int16ToUint32(t.shortAmount);break;case As.CoarseTune:this.transpose+=t.shortAmount;break;case As.FineTune:this.tune+=t.shortAmount;break;case As.SampleModes:this.loopMode=3&~t.wordAmount?1==(3&t.wordAmount)?Ms.Continuous:Ms.None:Ms.Sustain;break;case As.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case As.ExclusiveClass:this.group=t.wordAmount;break;case As.OverridingRootKey:this.pitchKeyCenter=t.shortAmount}}}da.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"}(Rs||(Rs={}));class ca{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=Rs.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case Rs.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=Rs.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=Rs.Delay;break;case Rs.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=Rs.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=Rs.Attack;break;case Rs.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=Rs.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=Rs.Hold;break;case Rs.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=Rs.Decay,this.level=1,this.isAmpEnv){let 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=Rs.Decay;break;case Rs.Decay:return this.segment=Rs.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case Rs.Sustain:if(this.segment=Rs.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?ca.FastReleaseTime:this.parameters.release)*t|0,this.isAmpEnv){let 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=Rs.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,s,i,a){this.parameters=new la(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:ha.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:ha.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|s,this.isAmpEnv=i,this.nextSegment(Rs.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)}}ca.FastReleaseTime=.01;class ua{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,s){this.samplesUntil=e*s|0,this.delta=4*ha.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 pa{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){let 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){let 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 ga{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 ca,this.modEnv=new ca,this.lowPass=new pa,this.modLfo=new ua,this.vibLfo=new ua,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/(ha.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(Rs.Sustain,e),this.modEnv.nextSegment(Rs.Sustain,e),this.region.loopMode===Ms.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(Rs.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(Rs.Sustain,e)}render(e,t,s,i,a){if(!this.region)return;let r=this.region,n=r.samples,o=0,h=e.outputMode===Is.StereoUnweaved?i:-1,l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,d=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),c=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,m=r.end,f=g+1,y=this.sourceSamplePosition,b=new pa(this.lowPass),S=0!==r.modLfoToFilterFc||0!==r.modEnvToFilterFc,_=0,w=0,B=0,T=0,k=0!==r.modLfoToPitch||0!==r.modEnvToPitch||0!==r.vibLfoToPitch,N=0,x=0,v=0,P=0,C=0!==r.modLfoToVolume,E=0,F=0;for(S?(_=e.outSampleRate,w=r.initialFilterFc,B=r.modLfoToFilterFc,T=r.modEnvToFilterFc):(_=0,w=0,B=0,T=0),k?(N=0,x=r.modLfoToPitch,v=r.vibLfoToPitch,P=r.modEnvToPitch):(N=ha.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,x=0,v=0,P=0),C?F=.1*r.modLfoToVolume:(E=ha.decibelsToGain(this.noteGainDb),F=0);i>0;){let r,D,L=0,M=i>ga.RenderEffectSampleBlock?ga.RenderEffectSampleBlock:i;if(i-=M,S){let e=w+this.modLfo.level*B+this.modEnv.level*T;b.active=e<=13500,b.active&&b.setup(ha.cents2Hertz(e)/_)}switch(k&&(N=ha.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*x+this.vibLfo.level*v+this.modEnv.level*P))*this.pitchOutputFactor),C&&(E=ha.decibelsToGain(this.noteGainDb+this.modLfo.level*F)),r=E*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(M,e.outSampleRate),l&&this.modEnv.process(M,e.outSampleRate),d&&this.modLfo.process(M),c&&this.vibLfo.process(M),e.outputMode){case Is.StereoInterleaved:for(D=r*this.panFactorLeft,L=r*this.panFactorRight;M-- >0&&y<m;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*D,o++,t[s+o]+=r*L,o++,y+=N,y>=f&&u&&(y-=g-p+1)}break;case Is.StereoUnweaved:for(D=r*this.panFactorLeft,L=r*this.panFactorRight;M-- >0&&y<m;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*D,o++,t[s+h]+=r*L,h++,y+=N,y>=f&&u&&(y-=g-p+1)}break;case Is.Mono:for(;M-- >0&&y<m;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,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===Rs.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}ga.RenderEffectSampleBlock=Ve.MicroBufferSize;class ma{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"}(Os||(Os={}));class fa{constructor(e){this._midiEventQueue=new ma,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=Is.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){let s=this.channelInit(e);for(let 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;){let e=this._midiEventQueue.dequeue();e.isMetronome&&this.metronomeVolume>0?(this.channelNoteOff(Ve.MetronomeChannel,Ve.MetronomeKey),this.channelNoteOn(Ve.MetronomeChannel,Ve.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!=Ve.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,s,n):a.kill()}return a}processMidiMessage(e){ne.debug("Midi","Processing Midi message "+Ke[e.type]+"/"+e.tick);switch(e.type){case Ke.TimeSignature:const t=e;this.timeSignatureNumerator=t.numerator,this.timeSignatureDenominator=Math.pow(2,t.denominatorIndex);break;case Ke.NoteOn:const s=e;this.channelNoteOn(s.channel,s.noteKey,s.noteVelocity/127);break;case Ke.NoteOff:const i=e;this.channelNoteOff(i.channel,i.noteKey);break;case Ke.ControlChange:const a=e;this.channelMidiControl(a.channel,a.controller,a.value);break;case Ke.ProgramChange:const r=e;this.channelSetPresetNumber(r.channel,r.program,9===r.channel);break;case Ke.TempoChange:const n=e;this.currentTempo=6e7/n.microSecondsPerQuarterNote;break;case Ke.PitchBend:const o=e;this.channelSetPitchWheel(o.channel,o.value);break;case Ke.PerNotePitchBend:const h=e;let l=h.value;l=l*Ve.MaxPitchWheel/Ve.MaxPitchWheel20,this.channelSetPerNotePitchWheel(h.channel,h.noteKey,l)}}get metronomeVolume(){return this.channelGetMixVolume(Ve.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Ve.MetronomeChannel,e),e>0&&(this.channelSetVolume(Ve.MetronomeChannel,1),this.channelSetPresetNumber(Ve.MetronomeChannel,0,!0))}get masterVolume(){return ha.decibelsToGain(this.globalGainDb)}set masterVolume(e){var t=ha.gainToDecibels(e);const 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<Rs.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(let e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<Rs.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(let e of this._voices)-1===e.playingPreset&&(n=e);if(!n){for(let e=0;e<4;e++){const e=new ga;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-ha.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!==Ms.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(ha.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){let a=this.getPresetIndex(e,t);return-1!==a&&(this.noteOn(a,s,i),!0)}noteOff(e,t){let s=null,i=null,a=[];for(let r of this._voices)r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=Rs.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>=Rs.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<Rs.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 na);for(let t=this._channels.channelList.length;t<=e;t++){let e=new ra;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--){let 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>=Rs.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>=Rs.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<Rs.Release&&t.end(this.outSampleRate)}channelSoundsOffAll(e){this.channelInit(e).perNotePitchWheel.clear();for(let t of this._voices)-1!==t.playingPreset&&t.playingChannel===e&&(t.ampEnv.segment<Rs.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=Ae.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=Ae.int32ToUint16(t)}channelSetBankPreset(e,t,s){const i=this.channelInit(e),a=this.getPresetIndex(t,s);return-1!==a&&(i.presetIndex=Ae.int32ToUint16(a),i.bank=Ae.int32ToUint16(t),!0)}channelSetPan(e,t){for(const s of this._voices)if(s.playingChannel===e&&-1!==s.playingPreset){let 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=ha.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=Ae.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){let i=this.channelInit(e);switch(t){case Os.DataEntryFine:return i.midiData=Ae.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 Os.VolumeCoarse:return i.midiVolume=Ae.int32ToUint16(127&i.midiVolume|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.VolumeFine:return i.midiVolume=Ae.int32ToUint16(16256&i.midiVolume|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.ExpressionControllerCoarse:return i.midiExpression=Ae.int32ToUint16(127&i.midiExpression|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.ExpressionControllerFine:return i.midiExpression=Ae.int32ToUint16(16256&i.midiExpression|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.PanCoarse:return i.midiPan=Ae.int32ToUint16(127&i.midiPan|s<<7),void this.channelSetPan(e,i.midiPan/16383);case Os.PanFine:return i.midiPan=Ae.int32ToUint16(16256&i.midiPan|s),void this.channelSetPan(e,i.midiPan/16383);case Os.DataEntryCoarse:return i.midiData=Ae.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===Os.DataEntryCoarse&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Os.BankSelectCoarse:return void(i.bank=Ae.int32ToUint16(32768|s));case Os.BankSelectFine:return void(i.bank=Ae.int32ToUint16((32768&i.bank?(127&i.bank)<<7:0)|s));case Os.RegisteredParameterCourse:return void(i.midiRpn=Ae.int32ToUint16(127&(65535===i.midiRpn?0:i.midiRpn)|s<<7));case Os.RegisteredParameterFine:return void(i.midiRpn=Ae.int32ToUint16(16256&(65535===i.midiRpn?0:i.midiRpn)|s));case Os.NonRegisteredParameterFine:case Os.NonRegisteredParameterCourse:return void(i.midiRpn=65535);case Os.AllSoundOff:return void this.channelSoundsOffAll(e);case Os.AllNotesOff:return void this.channelNoteOffAll(e);case Os.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?ha.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 oa;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++){let t=e.pgens[n];if(t.genOper!==ea.GenKeyRange)if(t.genOper!==ea.GenVelRange){if(t.genOper===ea.GenInstrument&&!(t.genAmount.wordAmount>=e.insts.length))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,d=127;for(let c=e.ibags[n].instGenNdx;c<e.ibags[n+1].instGenNdx;c++){let n=e.igens[c];n.genOper!==ea.GenKeyRange?n.genOper!==ea.GenVelRange?53===n.genOper&&o>=s&&t<=i&&d>=a&&l<=r&&h++:(l=n.genAmount.lowByteAmount,d=n.genAmount.highByteAmount):(t=n.genAmount.lowByteAmount,o=n.genAmount.highByteAmount)}}}else a=t.genAmount.lowByteAmount,r=t.genAmount.highByteAmount;else s=t.genAmount.lowByteAmount,i=t.genAmount.highByteAmount}}o.regions=new Array(h);let l=new da;l.clear(!0);for(let a=r.presetBagNdx;a<e.phdrs[i+1].presetBagNdx;a++){const i=e.pbags[a],h=new da(l);let d=!1;for(let l=i.genNdx;l<e.pbags[a+1].genNdx;l++){const i=e.pgens[l];if(i.genOper===ea.GenInstrument){let a=i.genAmount.wordAmount;if(a>=e.insts.length)continue;let l=new da;l.clear(!1);let c=e.insts[a];for(let i=c.instBagNdx;i<e.insts[a+1].instBagNdx;i++){let a=e.ibags[i],d=new da(l),u=!1;for(let l=a.instGenNdx;l<e.ibags[i+1].instGenNdx;l++){let i=e.igens[l];if(i.genOper===ea.GenSampleId){if(d.hiKey<h.loKey||d.loKey>h.hiKey)continue;if(d.hiVel<h.loVel||d.loVel>h.hiVel)continue;h.loKey>d.loKey&&(d.loKey=h.loKey),h.hiKey<d.hiKey&&(d.hiKey=h.hiKey),h.loVel>d.loVel&&(d.loVel=h.loVel),h.hiVel<d.hiVel&&(d.hiVel=h.hiVel),d.offset+=h.offset,d.end+=h.end,d.loopStart+=h.loopStart,d.loopEnd+=h.loopEnd,d.transpose+=h.transpose,d.tune+=h.tune,d.pitchKeyTrack+=h.pitchKeyTrack,d.attenuation+=h.attenuation,d.pan+=h.pan,d.ampEnv.delay+=h.ampEnv.delay,d.ampEnv.attack+=h.ampEnv.attack,d.ampEnv.hold+=h.ampEnv.hold,d.ampEnv.decay+=h.ampEnv.decay,d.ampEnv.sustain+=h.ampEnv.sustain,d.ampEnv.release+=h.ampEnv.release,d.modEnv.delay+=h.modEnv.delay,d.modEnv.attack+=h.modEnv.attack,d.modEnv.hold+=h.modEnv.hold,d.modEnv.decay+=h.modEnv.decay,d.modEnv.sustain+=h.modEnv.sustain,d.modEnv.release+=h.modEnv.release,d.initialFilterQ+=h.initialFilterQ,d.initialFilterFc+=h.initialFilterFc,d.modEnvToPitch+=h.modEnvToPitch,d.modEnvToFilterFc+=h.modEnvToFilterFc,d.delayModLFO+=h.delayModLFO,d.freqModLFO+=h.freqModLFO,d.modLfoToPitch+=h.modLfoToPitch,d.modLfoToFilterFc+=h.modLfoToFilterFc,d.modLfoToVolume+=h.modLfoToVolume,d.delayVibLFO+=h.delayVibLFO,d.freqVibLFO+=h.freqVibLFO,d.vibLfoToPitch+=h.vibLfoToPitch,d.ampEnv.envToSecs(!0),d.modEnv.envToSecs(!1),d.delayModLFO=d.delayModLFO<-11950?0:ha.timecents2Secs(d.delayModLFO),d.delayVibLFO=d.delayVibLFO<-11950?0:ha.timecents2Secs(d.delayVibLFO),d.pan<-.5?d.pan=-.5:d.pan>.5&&(d.pan=.5),(d.initialFilterQ<1500||d.initialFilterQ>13500)&&(d.initialFilterQ=0);let a=e.sHdrs[i.genAmount.wordAmount];d.offset+=a.start,d.end+=a.end,d.loopStart+=a.startLoop,d.loopEnd+=a.endLoop,a.endLoop>0&&(d.loopEnd-=1),-1===d.pitchKeyCenter&&(d.pitchKeyCenter=a.originalPitch),d.tune+=a.pitchCorrection,d.sampleRate=a.sampleRate;const l=r.bank==Ve.PercussionBank;if(l&&fa.setContainsRange(s,d.loKey,d.hiKey)||!l&&t.has(r.preset))if(1&a.sampleType){ne.debug("AlphaSynth",`Loading of used sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`);!!(16&a.sampleType)?d.samples=e.decodeSamples(a.start,a.end,!0):(d.samples=e.decodeSamples(2*d.offset,2*d.end,!1),d.loopStart>0&&(d.loopStart-=d.offset),d.loopEnd>0&&(d.loopEnd-=d.offset)),d.offset=0,d.end=d.samples.length-1}else ne.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})`),d.samples=new Float32Array(0);else ne.debug("AlphaSynth",`Skipping load of unused sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`),d.samples=new Float32Array(0);o.regions[n]=new da(d),n++,u=!0}else d.operator(i.genOper,i.genAmount)}a!==e.ibags[c.instBagNdx]||u||(l=new da(d))}d=!0}else h.operator(i.genOper,i.genAmount)}i!==e.pbags[r.presetBagNdx]||d||(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==Ve.PercussionBank)for(const t of s.regions)if(t.loKey>=e&&t.hiKey<=e&&t.samples.length>0)return!0;return!1}}class ya{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 ba{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 Sa{constructor(e){this.events=e}}class _a{constructor(e){this.playbackRange=e}}class wa{get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return ne.logLevel}set logLevel(e){ne.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Ve.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Ve.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Ve.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=de.clamp(e,Ve.MinPlaybackSpeed,Ve.MaxPlaybackSpeed);let 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){ne.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 _a(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){ne.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 ma,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this._synthStopping=!1,this.isReady=!1,this.state=Fs.Paused,this._loadedSoundFonts=[],this.ready=new ya,this.readyForPlayback=new ya,this.finished=new ya,this.soundFontLoaded=new ya,this.soundFontLoadFailed=new ba,this.midiLoaded=new ba,this.midiLoadFailed=new ba,this.stateChanged=new ba,this.positionChanged=new ba,this.midiEventsPlayed=new ba,this.playbackRangeChanged=new ba,ne.debug("AlphaSynth","Initializing player"),this.state=Fs.Paused,ne.debug("AlphaSynth","Creating output"),this.output=e,ne.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new fa(this.output.sampleRate),this._sequencer=new ci(this._synthesizer),ne.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this.state==Fs.Playing&&(!this._sequencer.isFinished||this._synthesizer.activeVoiceCount>0)){let e=new Float32Array(Ve.MicroBufferSize*Ve.MicroBufferCount*Ve.AudioChannels),t=0;for(let s=0;s<Ve.MicroBufferCount;s++){this._sequencer.fillMidiEventQueue();const s=this._synthesizer.synthesize(e,t,Ve.MicroBufferSize);t+=Ve.MicroBufferSize*Ve.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{let e=new Float32Array(0);this.output.addSamples(e)}})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open(t)}play(){return!(this.state!==Fs.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(ne.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(ne.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),ne.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this._synthStopping=!1,this.state=Fs.Playing,this.stateChanged.trigger(new ui(this.state,!1))}pause(){this.state!==Fs.Paused&&this._isMidiLoaded&&(ne.debug("AlphaSynth","Pausing playback"),this.state=Fs.Paused,this.stateChanged.trigger(new ui(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===Fs.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(ne.debug("AlphaSynth","Stopping playback"),this.state=Fs.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 ui(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();let s=Oe.fromBuffer(e);try{ne.debug("AlphaSynth","Loading soundfont from bytes");let e=new qi;e.load(s),t||(this._loadedSoundFonts=[]),this._loadedSoundFonts.push(e),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),ne.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){ne.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{ne.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new pi(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),ne.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){ne.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,Ve.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;let t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*Ve.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?(ne.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(ne.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=Fs.Paused,this.stopOneTimeMidi()):this.isLooping?(ne.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,ne.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(ne.debug("AlphaSynth",`Position changed: (time: ${s}/${a}, tick: ${i}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new pi(s,a,i,r,t)),t)this._playedEventsQueue.clear();else{const e=new ma;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<s;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new Sa(e.toArray()))}}hasSamplesForProgram(e){return this._synthesizer.hasSamplesForProgram(e)}hasSamplesForPercussion(e){return this._synthesizer.hasSamplesForPercussion(e)}}class Ba{constructor(){this.ready=new ya,this.samplesPlayed=new ba,this.sampleRequest=new ya}get sampleRate(){return Ba.preferredSampleRate}open(){ne.debug("AlphaSynth","Initializing synth worker"),this._worker=xl.globalThis,this._worker.addEventListener("message",this.handleMessage.bind(this)),this.ready.trigger()}destroy(){this._worker.postMessage({cmd:"alphaSynth.output.destroy"})}handleMessage(e){let t=e.data;switch(t.cmd){case Ba.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case Ba.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(){}}Ba.CmdOutputPrefix="alphaSynth.output.",Ba.CmdOutputAddSamples=Ba.CmdOutputPrefix+"addSamples",Ba.CmdOutputPlay=Ba.CmdOutputPrefix+"play",Ba.CmdOutputPause=Ba.CmdOutputPrefix+"pause",Ba.CmdOutputResetSamples=Ba.CmdOutputPrefix+"resetSamples",Ba.CmdOutputStop=Ba.CmdOutputPrefix+"stop",Ba.CmdOutputSampleRequest=Ba.CmdOutputPrefix+"sampleRequest",Ba.CmdOutputSamplesPlayed=Ba.CmdOutputPrefix+"samplesPlayed",Ba.preferredSampleRate=0;class Ta{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new wa(new Ba,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(){let e=xl.globalThis;e.addEventListener("message",(t=>{let s=t.data;if("alphaSynth.initialize"===s.cmd)Ba.preferredSampleRate=s.sampleRate,ne.logLevel=s.logLevel,xl.globalThis.alphaSynthWebWorker=new Ta(e,s.bufferTimeInMilliseconds)}))}handleMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":ne.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(is.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(is.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){let 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(is.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}e.WebPlatform=void 0,(Vs=e.WebPlatform||(e.WebPlatform={}))[Vs.Browser=0]="Browser",Vs[Vs.NodeJs=1]="NodeJs",Vs[Vs.BrowserModule=2]="BrowserModule";class ka{constructor(e,t){this.characterWidths=e,this.fontSizeToHeight=t}}class Na{static generateFontLookup(t){if(!Na.FontSizeLookupTables.has(t))if(xl.isRunningInWorker||xl.webPlatform==e.WebPlatform.NodeJs){const e=new ka(new Uint8Array([8]),1.2);Na.FontSizeLookupTables.set(t,e)}else{let e=document.createElement("canvas").getContext("2d");const s=11;e.font=`${s}px ${t}`;const i=[];let a="";for(let t=Na.ControlChars;t<255;t++){let s=String.fromCharCode(t);a+=s;const r=e.measureText(s);i.push(r.width)}const r=e.measureText(a+"ÄÖÜÁÈ"),n=0-Math.abs(r.fontBoundingBoxAscent),o=0+Math.abs(r.fontBoundingBoxDescent)-n,h=new ka(new Uint8Array(i),o/s);Na.FontSizeLookupTables.set(t,h)}}static measureString(e,t,s,i,a){let r,n=t[0];for(let e=0;e<t.length;e++)if(Na.FontSizeLookupTables.has(t[e])){n=t[e];break}Na.FontSizeLookupTables.has(n)||Na.generateFontLookup(n),r=Na.FontSizeLookupTables.get(n);let o=1;i===Ye.Italic&&(o*=1.1),a===qe.Bold&&(o*=1.1);let h=0;for(let t=0;t<e.length;t++){let i=Math.min(r.characterWidths.length-1,e.charCodeAt(t)-Na.ControlChars);i>=0&&(h+=r.characterWidths[i]*s/11)}return o*=1.07,new ce(h*o,s*r.fontSizeToHeight)}}Na.FontSizeLookupTables=new Map,Na.ControlChars=32;class xa{constructor(){this.id=de.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 va{constructor(){this.beats=[]}addBeat(e){e.barBounds=this,this.beats.push(e),this.masterBarBounds.addBeat(e)}findBeatAtPos(e){let t=null;for(let 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 Pa{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(let i of s){let 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 Ca{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(let t of this.bars){let 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 Ea{finish(e=1){this.noteHeadBounds.scaleWith(e)}}class Fa{constructor(){this.index=0,this.bars=[]}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e);for(let 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(let 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 Da{constructor(){this._beatLookup=new Map,this._masterBarLookup=new Map,this._currentStaffSystem=null,this.staffSystems=[],this.isFinished=!1}toJson(){let e={},t=[];e.staffSystems=t;for(let e of this.staffSystems){let s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.bars=[];for(let t of e.bars){let 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(let s of t.bars){let t={};t.visualBounds=this.boundsToJson(s.visualBounds),t.realBounds=this.boundsToJson(s.realBounds),t.beats=[];for(let e of s.beats){let s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.onNotesX=e.onNotesX;let 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){let t=s.notes=[];for(let s of e.notes){let 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){let s=new Da,i=e.staffSystems;for(let e of i){let i=new Fa;i.visualBounds=Da.boundsFromJson(e.visualBounds),i.realBounds=Da.boundsFromJson(e.realBounds),s.addStaffSystem(i);for(let s of e.bars){let e=new Ca;e.index=s.index,e.isFirstOfLine=s.isFirstOfLine,e.lineAlignedBounds=Da.boundsFromJson(s.lineAlignedBounds),e.visualBounds=Da.boundsFromJson(s.visualBounds),e.realBounds=Da.boundsFromJson(s.realBounds),i.addBar(e);for(let i of s.bars){let s=new va;s.visualBounds=Da.boundsFromJson(i.visualBounds),s.realBounds=Da.boundsFromJson(i.realBounds),e.addBar(s);for(let e of i.beats){let i=new Pa;i.visualBounds=Da.boundsFromJson(e.visualBounds),i.realBounds=Da.boundsFromJson(e.realBounds),i.onNotesX=e.onNotesX;let 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(let t of e.notes){let e=new Ea,s=t;e.note=i.beat.notes[s.index],e.noteHeadBounds=Da.boundsFromJson(t.noteHeadBounds),i.addNote(e)}}s.addBeat(i)}}}}return s}static boundsFromJson(e){const t=new cs;return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}boundsToJson(e){let t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(e=1){for(let 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){let 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){let 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;){let 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;let 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 La{constructor(t){this._currentLayoutMode=e.LayoutMode.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 ba,this.renderFinished=new ba,this.partialRenderFinished=new ba,this.partialLayoutFinished=new ba,this.postRenderFinished=new ya,this.error=new ba,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=xl.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=xl.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(let 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?(ne.debug("Rendering","Request render of lazy partial "+e),t.renderLazyPartial(e)):ne.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 Da,this.recreateCanvas(),this.canvas.lineWidth=1,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){ne.debug("Rendering","Rendering "+this.tracks.length+" tracks");for(let e=0;e<this.tracks.length;e++){let t=this.tracks[e];ne.debug("Rendering","Track "+e+": "+t.name)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),ne.debug("Rendering","Rendering finished")}else ne.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),ne.debug("Rendering","Clearing finished");else ne.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(ne.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(ne.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new Da,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):ne.debug("Rendering","Current layout does not support dynamic resizing, nothing was done",null),ne.debug("Rendering","Resize finished")}layoutAndRender(){ne.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 xa;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}class Ma{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){xl.globalThis.alphaTabWebWorker=new Ma(xl.globalThis)}handleMessage(e){let t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":let e=is.jsObjectToSettings(t.settings);ne.logLevel=e.core.logLevel,this._renderer=new La(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);let s=null==t.score?null:is.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){Na.FontSizeLookupTables||(Na.FontSizeLookupTables=new Map);for(let[t,s]of e)Na.FontSizeLookupTables.set(t,s)}}updateSettings(e){Rt.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){ne.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class Ia{constructor(){this._canvas=null,this._color=new Ee(0,0,0,255),this._font=new nt("Arial",10,Ye.Plain),this._lineWidth=0;let e=document.createElement("span");e.classList.add("at"),document.body.appendChild(e);let t=window.getComputedStyle(e),s=t.fontFamily;(s.startsWith('"')||s.startsWith("'"))&&(s=s.substr(1,s.length-2)),this._musicFont=new nt(s,parseFloat(t.fontSize),Ye.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*xl.HighDpiFactor|0,this._canvas.height=t*xl.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(xl.HighDpiFactor*s,xl.HighDpiFactor*s),this._context.lineWidth=this._lineWidth}endRender(){let 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 L.Left;case"center":return L.Center;case"right":return L.Right}}set textAlign(e){switch(e){case L.Left:this._context.textAlign="left";break;case L.Center:this._context.textAlign="center";break;case L.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return M.Top;case"middle":return M.Middle;case"bottom":return M.Bottom}}set textBaseline(e){switch(e){case M.Top:this._context.textBaseline="hanging";break;case M.Middle:this._context.textBaseline="middle";break;case M.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 ce(t.width,t.actualBoundingBoxDescent-t.actualBoundingBoxAscent)}fillMusicFontSymbol(e,t,s,i,a=!1){i!==D.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a=!1){let r="";for(let e of i)e!==D.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){let 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 Aa{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 dt(0,e,t,i,48,8))}addRest(e,t,s){this._smf1Mode||this._midiFile.addEvent(new pt(e,t,s))}addNote(e,t,s,i,a,r){this._midiFile.addEvent(new mt(e,t,r,Aa.fixValue(i),Aa.fixValue(a))),this._midiFile.addEvent(new ft(e,t+s,r,Aa.fixValue(i),Aa.fixValue(a)))}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,s,i,a){this._midiFile.addEvent(new yt(e,t,s,i,Aa.fixValue(a)))}addProgramChange(e,t,s,i){this._midiFile.addEvent(new bt(e,t,s,i))}addTempo(e,t){const s=6e7/t|0;this._midiFile.addEvent(new St(e,s))}addBend(e,t,s,i){i=i>=Ve.MaxPitchWheel?Ve.MaxPitchWheel:Math.floor(i),this._midiFile.addEvent(new _t(e,t,s,i))}addNoteBend(e,t,s,i,a){this._smf1Mode?this.addBend(e,t,s,a):(a=a*Ve.MaxPitchWheel20/Ve.MaxPitchWheel,this._midiFile.addEvent(new wt(e,t,s,i,a)))}finishTrack(e,t){this._midiFile.format!=je.MultiTrack&&0!=e||this._midiFile.addEvent(new Bt(e,t))}}class Ra{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"}(Hs||(Hs={}));class Oa{get finished(){return this.index>=this._score.masterBars.length}constructor(e){this._repeatStack=[],this._groupsOnStack=new Set,this._previousAlternateEndings=0,this._state=Hs.PlayingNormally,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}processCurrent(){const e=this._score.masterBars[this.index];if(this._state===Hs.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 Ra(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=Hs.PlayingNormally,!0)}return!1}moveNextWithDirections(){const e=this._score.masterBars[this.index],t=null!==e.directions&&e.directions.size>0;if(this._state===Hs.PlayingNormally&&!t)return!1;if(!t)return this.index++,!0;switch(this._state){case Hs.PlayingNormally:return!!(this.handleDaCapo(e.directions,He.JumpDaCapo,Hs.DirectionJumped)||this.handleDaCapo(e.directions,He.JumpDaCapoAlCoda,Hs.DirectionJumpedAlCoda)||this.handleDaCapo(e.directions,He.JumpDaCapoAlDoubleCoda,Hs.DirectionJumpedAlDoubleCoda)||this.handleDaCapo(e.directions,He.JumpDaCapoAlFine,Hs.DirectionJumpedAlFine))||(!!(this.handleDalSegno(e.directions,He.JumpDalSegno,Hs.DirectionJumped,He.TargetSegno)||this.handleDalSegno(e.directions,He.JumpDalSegnoAlCoda,Hs.DirectionJumpedAlCoda,He.TargetSegno)||this.handleDalSegno(e.directions,He.JumpDalSegnoAlDoubleCoda,Hs.DirectionJumpedAlDoubleCoda,He.TargetSegno)||this.handleDalSegno(e.directions,He.JumpDalSegnoAlFine,Hs.DirectionJumpedAlFine,He.TargetSegno))||!!(this.handleDalSegno(e.directions,He.JumpDalSegnoSegno,Hs.DirectionJumped,He.TargetSegnoSegno)||this.handleDalSegno(e.directions,He.JumpDalSegnoSegnoAlCoda,Hs.DirectionJumpedAlCoda,He.TargetSegnoSegno)||this.handleDalSegno(e.directions,He.JumpDalSegnoSegnoAlDoubleCoda,Hs.DirectionJumpedAlDoubleCoda,He.TargetSegnoSegno)||this.handleDalSegno(e.directions,He.JumpDalSegnoSegnoAlFine,Hs.DirectionJumpedAlFine,He.TargetSegnoSegno)));case Hs.DirectionJumped:return this.index++,!0;case Hs.DirectionJumpedAlCoda:return this.handleDaCoda(e.directions,He.JumpDaCoda,He.TargetCoda)||this.index++,!0;case Hs.DirectionJumpedAlDoubleCoda:return this.handleDaCoda(e.directions,He.JumpDaDoubleCoda,He.TargetDoubleCoda)||this.index++,!0;case Hs.DirectionJumpedAlFine:return e.directions.has(He.TargetFine)?(this.index=this._score.masterBars.length,!0):(this.index++,!0)}return!0}findJumpTarget(e,t,s){if(s){let s=this.findJumpTargetBackwards(e,t);return-1===s&&(s=this.findJumpTargetForwards(e,t)),s}{let s=this.findJumpTargetForwards(e,t);return-1===s&&(s=this.findJumpTargetBackwards(e,t)),s}}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 Va{constructor(e,t){this.beat=e,this.playbackStart=t}}class Ha{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 Va(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 Ga{constructor(e,t){this.tick=e,this.tempo=t}}class Wa{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(t,s,i,a){const r=i+a;if(null==this.firstBeat){const e=new Ha(i,r);e.highlightBeat(t,s),this.insertAfter(this.firstBeat,e)}else if(i>=this.lastBeat.end){const e=new Ha(this.lastBeat.end,r);e.highlightBeat(t,s),this.insertAfter(this.lastBeat,e)}else{let a=null;if(i<this.firstBeat.start)a=this.firstBeat;else{let t=this.firstBeat;for(;null!=t;){if(i>=t.start&&i<t.end){a=t;break}t=t.nextBeat}if(null===a)throw new K(e.AlphaTabErrorType.General,"Error on building lookup, unknown variant")}if(i<a.start)if(r==a.start){const e=new Ha(i,a.start);e.highlightBeat(t,s),this.insertBefore(this.firstBeat,e)}else if(r<a.end){const e=new Ha(i,a.start);e.highlightBeat(t,s),this.insertBefore(a,e);const n=new Ha(a.start,r);for(const e of a.highlightedBeats)n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(t,s),this.insertBefore(a,n),a.start=r}else if(r==a.end){const e=new Ha(i,a.start);e.highlightBeat(t,s),a.highlightBeat(t,s),this.insertBefore(a,e)}else{const e=new Ha(i,a.start);e.highlightBeat(t,s),a.highlightBeat(t,s),this.insertBefore(a,e),this.addBeat(t,s,a.end,r-a.end)}else if(i>a.start)if(r==a.end){const e=new Ha(a.start,i);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart);a.start=i,a.highlightBeat(t,s),this.insertBefore(a,e)}else if(r<a.end){const e=new Ha(a.start,i);this.insertBefore(a,e);const n=new Ha(i,r);this.insertBefore(a,n);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart),n.highlightBeat(t.beat,t.playbackStart);n.highlightBeat(t,s),a.start=r}else{const e=new Ha(a.start,i);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart);a.start=i,a.highlightBeat(t,s),this.insertBefore(a,e),this.addBeat(t,s,a.end,r-a.end)}else if(r===a.end)a.highlightBeat(t,s);else if(r<a.end){const e=new Ha(a.start,r);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart);e.highlightBeat(t,s),a.start=r,this.insertBefore(a,e)}else a.highlightBeat(t,s),this.addBeat(t,s,a.end,r-a.end)}}}!function(e){e[e.Unknown=0]="Unknown",e[e.ToNextBext=1]="ToNextBext",e[e.ToEndOfBar=2]="ToEndOfBar"}(Gs||(Gs={}));class za{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=Gs.Unknown,this.masterBar=e}calculateDuration(){if(1===this.masterBar.tempoChanges.length)this.duration=te.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+=te.ticksToMillis(a.tick-t,s),s=a.tempo,t=a.tick}i>t&&(e+=te.ticksToMillis(i-t,s)),this.duration=e}}}class Ua{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[]}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}fillNextBeat(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=Gs.ToNextBext,e.calculateDuration()),e.nextBeat||(e.tickDuration=e.masterBar.end-e.start,e.cursorMode=Gs.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=Gs.ToEndOfBar)}findBeatSlow(e,t,s,i){let a=null;if(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)return null;for(;a;){if(a.firstBeat){let 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&&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 za(e);return r.beat=s,r.beatLookup=t,r.tickDuration=t.end-t.start,i||this.fillNextBeat(r,a),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 Wa;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 Xa{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Ja{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class Ya{constructor(){this.durations=[],this.brushInfos=[]}}class qa{constructor(e,t,s){this._programsPerChannel=new Map,this._currentTime=0,this._calculatedBeatTimers=new Set,this.tickLookup=new Ua,this.applyTranspositionPitches=!0,this.transpositionPitches=new Map,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new Ot,this._handler=s}generate(){this.transpositionPitches.clear(),this._calculatedBeatTimers.clear(),this._currentTime=0;for(const e of this._score.tracks)this.generateTrack(e);ne.debug("Midi","Begin midi generation");const e=new Oa(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);ne.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);let a=qa.toChannelShort(s.volume),r=qa.toChannelShort(s.balance);this._handler.addControlChange(e.index,0,t,Os.VolumeCoarse,a),this._handler.addControlChange(e.index,0,t,Os.PanCoarse,r),this._handler.addControlChange(e.index,0,t,Os.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,Os.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,Os.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,Os.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,Os.DataEntryCoarse,qa.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 Wa;if(e.tempoAutomations.length>0){e.tempoAutomations[0].ratioPosition>0&&r.tempoChanges.push(new Ga(s,i));for(const t of e.tempoAutomations){const e=s+a*t.ratioPosition;this._handler.addTempo(e,t.value),r.tempoChanges.push(new Ga(e,t.value))}}else t?r.tempoChanges.push(new Ga(s,i)):(this._handler.addTempo(s,e.score.tempo),r.tempoChanges.push(new Ga(s,e.score.tempo)));r.masterBar=e,r.start=s,r.end=r.start+a,this.tickLookup.addMasterBar(r)}generateBar(e,t,s){let i=this.getPlaybackBar(e);const 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+te.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+=te.ticksToMillis(s,i)),i=t.value,e+=s}const h=r-e;h>0&&(this._currentTime+=te.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!==E.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(a-=this._currentTripletFeel.secondBeatStartOffset,r=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=qa.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+=te.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{let 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!==O.None&&this.generateFade(e,t+a,r),e.vibrato!==B.None){let s=240,i=3;switch(e.vibrato){case B.Slight:s=this._settings.player.vibrato.beatSlightLength,i=this._settings.player.vibrato.beatSlightAmplitude;break;case B.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 E.Triplet8th:case E.Dotted8th:case E.Scottish8th:i=g.Eighth;break;case E.Triplet16th:case E.Dotted16th:case E.Scottish16th:i=g.Sixteenth;break;default:return null}const a=te.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 Ja;switch(s.voice.bar.masterBar.tripletFeel){case E.Triplet8th:r.firstBeatDuration=te.applyTuplet(te.toTicks(g.Quarter),3,2),r.secondBeatDuration=te.applyTuplet(te.toTicks(g.Eighth),3,2);break;case E.Dotted8th:r.firstBeatDuration=te.applyDot(te.toTicks(g.Eighth),!1),r.secondBeatDuration=te.toTicks(g.Sixteenth);break;case E.Scottish8th:r.firstBeatDuration=te.toTicks(g.Sixteenth),r.secondBeatDuration=te.applyDot(te.toTicks(g.Eighth),!1);break;case E.Triplet16th:r.firstBeatDuration=te.applyTuplet(te.toTicks(g.Eighth),3,2),r.secondBeatDuration=te.applyTuplet(te.toTicks(g.Sixteenth),3,2);break;case E.Dotted16th:r.firstBeatDuration=te.applyDot(te.toTicks(g.Sixteenth),!1),r.secondBeatDuration=te.toTicks(g.ThirtySecond);break;case E.Scottish16th:r.firstBeatDuration=te.toTicks(g.ThirtySecond),r.secondBeatDuration=te.applyDot(te.toTicks(g.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateDeadSlap(e,t){const s=te.toTicks(g.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,te.dynamicToVelocity(m.F),i.track.playbackInfo.primaryChannel)}needsSecondaryChannel(e){return e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==B.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=pe.getArticulation(e);t&&(h=t.outputMidiNumber)}const l=null==r&&e.isStringed&&e.string<=a.length?a[e.string-1]:0,d=t+l,c=this.getNoteDuration(e,s,i);c.untilTieOrSlideEnd-=l,c.noteOnly-=l,c.letRingEnd-=l;const u=qa.getNoteVelocity(e),p=this.determineChannel(n,e);let g=0,m=Math.max(c.untilTieOrSlideEnd,c.letRingEnd);g=e.hasBend?qa.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?qa.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===w.Legato?-1:qa.getPitchWheel(0),g>=0&&this._handler.addNoteBend(n.index,d,p,h,g),e.beat.hasRasgueado?this.generateRasgueado(n,e,d,h,u,p,r):e.ornament===I.None?!e.isTrill||o.isPercussion?e.beat.isTremolo?this.generateTremoloPicking(e,d,c,h,u,p):(e.hasBend?this.generateBend(e,d,c,h,p,i):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,d,c,p,i):e.slideInType!==_.None||e.slideOutType!==w.None?this.generateSlide(e,d,c,h,p,i):(e.vibrato!==B.None||e.isTieDestination&&e.tieOrigin.vibrato!==B.None)&&this.generateVibrato(e,d,c,h,p),e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===w.Legato||this._handler.addNote(n.index,d,m,h,u,p)):this.generateTrill(e,d,c,h,u,p):this.generateOrnament(n,e,d,m,h,u,p)}generateOrnament(e,t,s,i,a,r,n){let o,h;const l=a%12,d=1/3;switch(t.ornament){case I.Turn:o=[a+qa.OrnamentKeysUp[l],a,a+qa.OrnamentKeysDown[l]],h=[te.toTicks(g.Sixteenth)*d,te.toTicks(g.Sixteenth)*d,te.toTicks(g.Sixteenth)*d];break;case I.InvertedTurn:o=[a+qa.OrnamentKeysDown[l],a,a+qa.OrnamentKeysUp[l]],h=[te.toTicks(g.Sixteenth)*d,te.toTicks(g.Sixteenth)*d,te.toTicks(g.Sixteenth)*d];break;case I.UpperMordent:o=[a,a+qa.OrnamentKeysUp[l]],h=[te.toTicks(g.ThirtySecond),te.toTicks(g.ThirtySecond)];break;case I.LowerMordent:o=[a,a+qa.OrnamentKeysDown[l]],h=[te.toTicks(g.ThirtySecond),te.toTicks(g.ThirtySecond)];break;default:return}let c=1;i<te.QuarterTime&&(c=i/te.QuarterTime),r-=te.VelocityIncrement;let u=0;for(let t=0;t<o.length;t++){const i=h[t]*c;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(t,s,i){const a=new Xa;if(a.noteOnly=s,a.untilTieOrSlideEnd=s,a.letRingEnd=s,t.isDead)return a.noteOnly=this.applyStaticDuration(qa.DefaultDurationDead,s,i),a.untilTieOrSlideEnd=a.noteOnly,a.letRingEnd=a.noteOnly,a;if(t.isPalmMute)return a.noteOnly=this.applyStaticDuration(qa.DefaultDurationPalmMute,s,i),a.untilTieOrSlideEnd=a.noteOnly,a.letRingEnd=a.noteOnly,a;if(t.isStaccato)return a.noteOnly=s/2|0,a.untilTieOrSlideEnd=a.noteOnly,a.letRingEnd=a.noteOnly,a;if(t.isTieOrigin){const e=t.tieDestination;if(e)if(t.isTieDestination){const t=this.getNoteDuration(e,e.beat.playbackDuration,i);a.untilTieOrSlideEnd=s+t.untilTieOrSlideEnd}else{const s=t.beat.absolutePlaybackStart,r=this.getNoteDuration(e,e.beat.playbackDuration,i),n=e.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;a.untilTieOrSlideEnd=n-s}}else if(t.slideOutType===w.Legato){const e=t.slideTarget;if(e){const s=t.beat.absolutePlaybackStart,r=this.getNoteDuration(e,e.beat.playbackDuration,i),n=e.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;a.untilTieOrSlideEnd=n-s}}if(t.isLetRing&&this._settings.notation.notationMode===e.NotationMode.GuitarPro){let e=t.beat,i=0;const r=t.beat.voice.bar.masterBar.calculateDuration();for(;e.nextBeat;){let s=e.nextBeat;if(s.isRest)break;if(t.isStringed&&s.hasNoteOnString(t.string))break;if(e=e.nextBeat,i=e.absolutePlaybackStart-t.beat.absolutePlaybackStart+e.playbackDuration,i>r){i=r;break}}e===t.beat?a.letRingEnd=s:a.letRingEnd=i}else a.letRingEnd=a.untilTieOrSlideEnd;return a}applyStaticDuration(e,t,s){const i=s*e/se.MaxPosition|0;return Math.min(i,t)}static getNoteVelocity(e){let t=e.dynamics;switch(!e.beat.voice.bar.staff.isPercussion&&e.hammerPullOrigin&&t--,e.isGhost&&t--,e.accentuated){case a.Normal:t++;break;case a.Heavy:t+=2}return te.dynamicToVelocity(t)}generateFade(e,t,s){const i=e.voice.bar.staff.track;switch(e.fade){case O.FadeIn:this.generateFadeSteps(i,t,s,0,qa.toChannelShort(i.playbackInfo.volume));break;case O.FadeOut:this.generateFadeSteps(i,t,s,qa.toChannelShort(i.playbackInfo.volume),0);break;case O.VolumeSwell:const e=s/2|0;this.generateFadeSteps(i,t,e,0,qa.toChannelShort(i.playbackInfo.volume)),this.generateFadeSteps(i,t+e,e,qa.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,d=h?a:Math.round(i+(l-t)*r);this._handler.addControlChange(e.index,l,e.playbackInfo.primaryChannel,Os.VolumeCoarse,d),this._handler.addControlChange(e.index,l,e.playbackInfo.secondaryChannel,Os.VolumeCoarse,d)}}generateVibrato(e,t,s,i,a){let r=0,n=0;switch(e.vibrato!==B.None?e.vibrato:e.isTieDestination?e.tieOrigin.vibrato:B.Slight){case B.Slight:r=this._settings.player.vibrato.noteSlightLength,n=this._settings.player.vibrato.noteSlightAmplitude;break;case B.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;){let s=i+a*Math.sin(t*Math.PI/o);r(e+t|0,qa.getPitchWheel(s)),t+=n}e+=s}r(0|h,qa.getPitchWheel(i))}static getPitchWheel(e){return Ve.DefaultPitchWheel+e/2*qa.PitchValuePerSemitone}generateSlide(e,t,s,i,a,r){let n=e.slideOutType===w.Legato?s.noteOnly:s.untilTieOrSlideEnd,o=[],h=e.beat.voice.bar.staff.track;const l=this._settings.player.slide.simpleSlidePitchOffset,d=Math.floor(se.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),c=Math.floor(se.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case _.IntoFromAbove:o.push(new se(0,l)),o.push(new se(d,0));break;case _.IntoFromBelow:o.push(new se(0,-l)),o.push(new se(d,0))}switch(e.slideOutType){case w.Legato:case w.Shift:o.push(new se(c,0));const t=2*(e.slideTarget.calculateRealValue(this.applyTranspositionPitches,!0)-e.calculateRealValue(this.applyTranspositionPitches,!0));o.push(new se(se.MaxPosition,t));break;case w.OutDown:o.push(new se(se.MaxPosition-d,0)),o.push(new se(se.MaxPosition,-l));break;case w.OutUp:o.push(new se(se.MaxPosition-d,0)),o.push(new se(se.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){let n=e.bendPoints,o=e.beat.voice.bar.staff.track;const h=(e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)};let l,u=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend&&t.tieDestination.vibrato==B.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!==f.None){switch(e.tieDestination.bendType){case c.Bend:case c.BendRelease:case c.PrebendBend:u=e.tieDestination.bendPoints[1].value;break;case c.Prebend:case c.PrebendRelease:u=e.tieDestination.bendPoints[0].value}l=Math.max(s.noteOnly,te.millisToTicks(this._settings.player.songBookBendDuration,r))}else l=s.noteOnly;n[0].value>0&&!e.isContinuedBend&&t>0&&t--;const p=Math.min(l,te.millisToTicks(this._settings.player.songBookBendDuration,r));let g=[];switch(e.bendType){case c.Custom:g=n;break;case c.Bend:case c.Release:switch(e.bendStyle){case d.Default:g=n;break;case d.Gradual:g.push(new se(0,e.bendPoints[0].value)),(!u||u<e.bendPoints[1].value)&&(u=e.bendPoints[1].value),g.push(new se(se.MaxPosition,u));break;case d.Fast:return(!u||u<e.bendPoints[1].value)&&(u=e.bendPoints[1].value),void(e.beat.graceType===f.BendGrace?this.generateSongBookWhammyOrBend(t,l,!0,[e.bendPoints[0].value,u],p,r,h):this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,u],p,r,h))}break;case c.BendRelease:switch(e.bendStyle){case d.Default:g=n;break;case d.Gradual:g.push(new se(0,e.bendPoints[0].value)),g.push(new se(se.MaxPosition/2|0,e.bendPoints[1].value)),g.push(new se(se.MaxPosition,e.bendPoints[2].value));break;case d.Fast:return void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],p,r,h)}break;case c.Hold:case c.Prebend:g=n;break;case c.PrebendBend:switch(e.bendStyle){case d.Default:g=n;break;case d.Gradual:g.push(new se(0,e.bendPoints[0].value)),g.push(new se(se.MaxPosition,e.bendPoints[1].value));break;case d.Fast:return h(t,0|qa.getPitchWheel(e.bendPoints[0].value)),(!u||u<e.bendPoints[1].value)&&(u=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,u],p,r,h)}break;case c.PrebendRelease:switch(e.bendStyle){case d.Default:g=n;break;case d.Gradual:g.push(new se(0,e.bendPoints[0].value)),g.push(new se(se.MaxPosition,e.bendPoints[1].value));break;case d.Fast:return h(t,0|qa.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,e.bendPoints[1].value],p,r,h)}}this.generateWhammyOrBend(t,l,g,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=qa.getPitchWheel(i[e]),s=qa.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 A.Custom:l=r;break;case A.Dive:switch(e.whammyStyle){case d.Default:l=r;break;case d.Gradual:l.push(new se(0,r[0].value)),l.push(new se(se.MaxPosition,r[1].value));break;case d.Fast:const e=Math.min(o,te.millisToTicks(this._settings.player.songBookBendDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!1,[r[0].value,r[1].value],e,a,h)}break;case A.Dip:switch(e.whammyStyle){case d.Default:l=r;break;case d.Gradual:l.push(new se(0,r[0].value)),l.push(new se(se.MaxPosition/2|0,r[1].value)),l.push(new se(se.MaxPosition,r[2].value));break;case d.Fast:const e=Math.min(o,te.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 A.Hold:case A.Predive:l=r;break;case A.PrediveDive:switch(e.whammyStyle){case d.Default:l=r;break;case d.Gradual:l.push(new se(0,r[0].value)),l.push(new se(se.MaxPosition/2|0,r[0].value)),l.push(new se(se.MaxPosition,r[1].value));break;case d.Fast:const e=qa.getPitchWheel(r[0].value);this._handler.addBend(n.index,t,i,0|e);const s=Math.min(o,te.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/se.MaxPosition;for(let t=0;t<s.length-1;t++){const n=s[t],o=s[t+1],h=qa.getPitchWheel(n.value),l=qa.getPitchWheel(o.value),d=r*(o.offset-n.offset),c=e+r*n.offset;this.generateBendValues(c,d,h,l,i,a)}}generateBendValues(e,t,s,i,a,r){const n=te.ticksToMillis(t,a),o=Math.abs(i-s)/qa.PitchValuePerSemitone,h=Math.max(qa.MinBreakpointsPerSemitone*o,n/qa.MillisecondsPerBreakpoint),l=t/h,d=(i-s)/h,c=e+t;for(let t=0;t<h;t++)r(0|e,Math.round(s)),s+=d,e+=l;r(0|c,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,d=n.durations[s];this._handler.addNote(e.index,o+l,d-l,i,a,r),o+=d}}generateTrill(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=te.toTicks(e.trillSpeed),l=!0,d=t,c=t+s.untilTieOrSlideEnd;for(;d+10<c;)d+h>=c&&(h=c-d),this._handler.addNote(n.index,d,h,l?o:i,a,r),l=!l,d+=h}generateTremoloPicking(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track;let o=te.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 Ya,i=qa.RasgueadoDurations.get(e.rasgueado).reduce(((e,t)=>e+t),0);s.durations=qa.RasgueadoDurations.get(e.rasgueado).map((e=>t*e/i)),s.brushInfos=new Array(s.durations.length);const a=te.toTicks(g.Sixteenth);let r=0,n=0;for(const t of e.notes)t.isTieDestination||(r|=1<<t.string-1,n++);const o=qa.RasgueadoDirections.get(e.rasgueado);for(let t=0;t<s.durations.length;t++){const i=s.durations[t]*a/te.QuarterTime,h=new Int32Array(e.voice.bar.staff.tuning.length);s.brushInfos[t]=h;const l=o[t];l!==u.None&&this.fillBrushInfo(e,h,l===u.ArpeggioDown||l===u.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===u.ArpeggioDown||e.brushType===u.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++){let 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 r.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 r.Balance:let i=qa.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Os.PanCoarse,i),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Os.PanCoarse,i);break;case r.Volume:let a=qa.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Os.VolumeCoarse,a),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Os.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 r.Instrument:s=i.value;break;case r.Tempo:t=i.value}i=i.previousBeat}const a=e.voice.bar.staff.track,n=e.voice.bar.masterBar;-1===t&&(t=n.score.tempo);const o=e.playbackStart/n.calculateDuration();for(const e of n.tempoAutomations){if(!(e.ratioPosition<=o))break;t=e.value}-1===s&&(s=a.playbackInfo.program);const h=a.playbackInfo.volume;this.generateTrack(a),this._handler.addTimeSignature(0,n.timeSignatureNumerator,n.timeSignatureDenominator),this._handler.addTempo(0,t);let l=qa.toChannelShort(h);return this._handler.addControlChange(0,0,a.playbackInfo.primaryChannel,Os.VolumeCoarse,l),this._handler.addControlChange(0,0,a.playbackInfo.secondaryChannel,Os.VolumeCoarse,l),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)}}qa.DefaultDurationDead=30,qa.DefaultDurationPalmMute=80,qa.OrnamentKeysUp=[2,2,2,1,1,2,2,2,2,2,1,1],qa.OrnamentKeysDown=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],qa.PitchBendRangeInSemitones=16,qa.PitchValuePerSemitone=Ve.DefaultPitchWheel/qa.PitchBendRangeInSemitones,qa.MinBreakpointsPerSemitone=6,qa.MillisecondsPerBreakpoint=150,qa.RasgueadoDirections=new Map([[G.Ii,[u.BrushDown,u.BrushUp]],[G.Mi,[u.BrushDown,u.BrushDown]],[G.MiiTriplet,[u.BrushDown,u.BrushDown,u.BrushUp]],[G.MiiAnapaest,[u.BrushDown,u.BrushDown,u.BrushUp]],[G.PmpTriplet,[u.BrushUp,u.BrushDown,u.BrushDown]],[G.PmpAnapaest,[u.BrushUp,u.BrushDown,u.BrushDown]],[G.PeiTriplet,[u.BrushUp,u.BrushDown,u.BrushDown]],[G.PeiAnapaest,[u.BrushUp,u.BrushDown,u.BrushDown]],[G.PaiTriplet,[u.BrushUp,u.BrushDown,u.BrushDown]],[G.PaiAnapaest,[u.BrushUp,u.BrushDown,u.BrushDown]],[G.AmiTriplet,[u.BrushDown,u.BrushDown,u.BrushDown]],[G.AmiAnapaest,[u.BrushDown,u.BrushDown,u.BrushDown]],[G.Ppp,[u.None,u.BrushDown,u.BrushUp]],[G.Amii,[u.BrushDown,u.BrushDown,u.BrushDown,u.BrushUp]],[G.Amip,[u.BrushDown,u.BrushDown,u.BrushDown,u.BrushUp]],[G.Eami,[u.BrushDown,u.BrushDown,u.BrushDown,u.BrushDown]],[G.Eamii,[u.BrushDown,u.BrushDown,u.BrushDown,u.BrushDown,u.BrushUp]],[G.Peami,[u.BrushDown,u.BrushDown,u.BrushDown,u.BrushDown,u.BrushUp]]]),qa.RasgueadoDurations=new Map([[G.Ii,[te.toTicks(g.Eighth),te.toTicks(g.Eighth)]],[G.Mi,[te.toTicks(g.Eighth),te.toTicks(g.Eighth)]],[G.MiiTriplet,[te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3]],[G.MiiAnapaest,[te.toTicks(g.Sixteenth),te.toTicks(g.Sixteenth),te.toTicks(g.Eighth)]],[G.PmpTriplet,[te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3]],[G.PmpAnapaest,[te.toTicks(g.Sixteenth)/3,te.toTicks(g.Sixteenth)/3,te.toTicks(g.Eighth)/3]],[G.PeiTriplet,[te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3]],[G.PeiAnapaest,[te.toTicks(g.Sixteenth),te.toTicks(g.Sixteenth),te.toTicks(g.Eighth)]],[G.PaiTriplet,[te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3]],[G.PaiAnapaest,[te.toTicks(g.Sixteenth),te.toTicks(g.Sixteenth),te.toTicks(g.Eighth)]],[G.AmiTriplet,[te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3,te.toTicks(g.Eighth)/3]],[G.AmiAnapaest,[te.toTicks(g.Sixteenth)/3,te.toTicks(g.Sixteenth)/3,te.toTicks(g.Eighth)/3]],[G.Ppp,[te.toTicks(g.Sixteenth)/3,te.toTicks(g.Sixteenth)/3,te.toTicks(g.Eighth)/3]],[G.Amii,[te.toTicks(g.Sixteenth)/3,te.toTicks(g.Sixteenth)/3,te.toTicks(g.Sixteenth)/3,te.toTicks(g.Eighth)]],[G.Amip,[te.toTicks(g.Sixteenth)/3,te.toTicks(g.Sixteenth)/3,te.toTicks(g.Sixteenth)/3,te.toTicks(g.Eighth)]],[G.Eami,[te.toTicks(g.Sixteenth),te.toTicks(g.Sixteenth),te.toTicks(g.Sixteenth),te.toTicks(g.Sixteenth)]],[G.Eamii,[te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5]],[G.Peami,[te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5,te.toTicks(g.Sixteenth)/5]]]);class ja{constructor(){this.startTick=0,this.endTick=0}}class Ka{constructor(e,t){this.width=0,this.height=0,this.x=e,this.y=t}doLayout(){}paint(e,t,s){}}class Qa extends Ka{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class $a extends Qa{constructor(e,t,s,i){super(e,t),this.glyphScale=0,this.center=!1,this.glyphScale=s,this.symbol=i}paint(e,t,s){s.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale,this.symbol,this.center)}}class Za extends $a{constructor(e,t,s,i){super(e,t,i?Za.GraceScale:1,Za.getSymbol(s)),this._isGrace=i,this._duration=s}paint(e,t,s){let i=this._isGrace?1:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale,this.symbol,!1)}doLayout(){let e=this._isGrace?Za.GraceScale:1;switch(this._duration){case g.QuadrupleWhole:this.width=14*e;break;case g.DoubleWhole:case g.Whole:this.width=14*(this._isGrace?Za.GraceScale:1);break;default:this.width=Za.QuarterNoteHeadWidth*(this._isGrace?Za.GraceScale:1)}this.height=Za.NoteHeadHeight*e}static getSymbol(e){switch(e){case g.QuadrupleWhole:return D.NoteheadDoubleWholeSquare;case g.DoubleWhole:return D.NoteheadDoubleWhole;case g.Whole:return D.NoteheadWhole;case g.Half:return D.NoteheadHalf;default:return D.NoteheadBlack}}}Za.GraceScale=.75,Za.NoteHeadHeight=8,Za.QuarterNoteHeadWidth=9;class er extends $a{constructor(e,t,s,i,a){super(e,t,a?Za.GraceScale:1,er.getSymbol(s,i,a))}doLayout(){this.width=0}static getSymbol(e,t,s){if(s&&(e=g.Eighth),t===We.Up)switch(e){case g.Eighth:return D.FlagEighthUp;case g.Sixteenth:return D.FlagSixteenthUp;case g.ThirtySecond:return D.FlagThirtySecondUp;case g.SixtyFourth:return D.FlagSixtyFourthUp;case g.OneHundredTwentyEighth:return D.FlagOneHundredTwentyEighthUp;case g.TwoHundredFiftySixth:return D.FlagTwoHundredFiftySixthUp;default:return D.FlagEighthUp}switch(e){case g.Eighth:return D.FlagEighthDown;case g.Sixteenth:return D.FlagSixteenthDown;case g.ThirtySecond:return D.FlagThirtySecondDown;case g.SixtyFourth:return D.FlagSixtyFourthDown;case g.OneHundredTwentyEighth:case g.TwoHundredFiftySixth:return D.FlagOneHundredTwentyEighthDown;default:return D.FlagEighthDown}}}er.FlagWidth=11;class tr extends Ka{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){let t=this.preNotes.computedWidth+this.onNotes.centerX,s=this.onNotes.computedWidth-this.onNotes.centerX;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);this.beat.graceType!==f.None?1===this.beat.graceGroup.beats.length?s+=er.FlagWidth*Za.GraceScale:this.beat.graceIndex<this.beat.graceGroup.beats.length-1?s+=7:s+=tr.GraceBeatPadding:i&&this.drawBeamHelperAsFlags(i)&&(s+=er.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>=g.Eighth&&(this.minWidth+=20);else switch(this.beat.duration){case g.OneHundredTwentyEighth:case g.TwoHundredFiftySixth:this.minWidth+=10}let e=0;for(let 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.beat.voice.isEmpty)return;if(this.preNotes.isEmpty&&this.onNotes.isEmpty&&0===this.ties.length)return;s.beginGroup(tr.getGroupId(this.beat)),this.preNotes.paint(e+this.x,t+this.y,s),this.onNotes.paint(e+this.x,t+this.y,s);let 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++){let t=this.ties[e];t.renderer=this.renderer,t.paint(i,a,s)}s.endGroup()}buildBoundingsLookup(e,t,s,i){let a=new Pa;if(a.beat=this.beat,this.beat.isEmpty)a.visualBounds=new cs,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 cs,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 cs,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!==f.None)&&(a.visualBounds.w+=er.FlagWidth*(this.beat.graceType!==f.None?Za.GraceScale:1)),a.visualBounds.y=e.visualBounds.y,a.visualBounds.h=e.visualBounds.h,a.realBounds=new cs,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)}}tr.GraceBeatPadding=3;class sr{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new vl}causeIssue(){return this.settings=null,!0}}class ir{constructor(e){this.activeBeats=e}}class ar{constructor(e){this.bounds=null,this.beat=e}}class rr{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=Fs.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=Fs.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new ba,this.activeBeatsChanged=new ba,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new ba,this.beatMouseMove=new ba,this.beatMouseUp=new ba,this.noteMouseDown=new ba,this.noteMouseMove=new ba,this.noteMouseUp=new ba,this.scoreLoaded=new ba,this.resize=new ba,this.renderStarted=new ba,this.renderFinished=new ba,this.postRenderFinished=new ya,this.error=new ba,this.playerReady=new ya,this.playerFinished=new ya,this.soundFontLoaded=new ya,this.midiLoad=new ba,this.midiLoaded=new ba,this.playerStateChanged=new ba,this.playerPositionChanged=new ba,this.midiEventsPlayed=new ba,this.playbackRangeChanged=new ba,this.settingsUpdated=new ya,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),ne.logLevel=this.settings.core.logLevel,this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&xl.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new La(this.settings),this.container.resize.on(xl.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));let s=new sr;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((()=>{let e=Date.now()-this._startTime;ne.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&&de.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?(this.setupPlayer(),e&&this.player?.applyTranspositionPitches(qa.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){let 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(let t of e.tracks)s.push(t);else for(let 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(t){if(t.length>0){let s=t[0].score;for(let i of t)if(i.score!==s)return void this.onError(new K(e.AlphaTabErrorType.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(s,t)}}internalRenderTracks(e,t){if(de.applyPitchOffsets(this.settings,e),e!==this.score){this.score=e,this.tracks=t,this._trackIndexes=[];for(let 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,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this._trackIndexLookup=new Set(this._trackIndexes),this.render()}}triggerResize(){if(this.container.isVisible){let e=new sr;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 ne.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{ne.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{let s=new st;s.logErrors=!0,s.initFromString(e,this.settings);let 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 isReadyForPlayback(){return!!this.player&&this.player.isReadyForPlayback}get playerState(){return this.player?this.player.state:Fs.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=Fs.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(let e of this.tracks){let 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;ne.debug("AlphaTab","Generating Midi");let e=new ht,t=new Aa(e),s=new qa(this.score,this.settings,t);s.applyTranspositionPitches=!1,s.generate(),this._tickCache=s.tickLookup,this.onMidiLoad(e);const i=this.player;i&&(i.loadMidiFile(e),i.applyTranspositionPitches(s.transpositionPitches))}changeTrackVolume(e,t){if(this.player)for(let s of e)this.player.setChannelVolume(s.playbackInfo.primaryChannel,t),this.player.setChannelVolume(s.playbackInfo.secondaryChannel,t)}changeTrackSolo(e,t){if(this.player)for(let s of e)this.player.setChannelSolo(s.playbackInfo.primaryChannel,t),this.player.setChannelSolo(s.playbackInfo.secondaryChannel,t)}changeTrackMute(e,t){if(this.player)for(let s of e)this.player.setChannelMute(s.playbackInfo.primaryChannel,t),this.player.setChannelMute(s.playbackInfo.secondaryChannel,t)}changeTrackTranspositionPitch(e,t){if(this.player)for(let 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;let t=new ht,s=new Aa(t);new qa(e.voice.bar.staff.track.score,this.settings,s).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;let t=new ht,s=new Aa(t);new qa(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){let 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=Fs.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===Fs.Paused){let e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getBeatStart(e.beat))}})))}cursorUpdateTick(e,t,s=!1,i=!1){let a=this._tickCache;if(a){let r=this._trackIndexLookup;if(null!=r&&r.size>0){let n=a.findBeat(r,e,this._currentBeat);n&&this.cursorUpdateBeat(n,t,s,i||this.playerState===Fs.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;let h=this.renderer.boundsLookup;if(!h)return;let l=this._currentBeat,d=this._previousCursorCache,c=this._previousStateForCursor;if(!i&&a===l?.beat&&h===d&&c===this._playerState&&l?.start===e.start)return;let 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(t){let s=this.uiFacade.getScrollContainer(),i=xl.getLayoutEngineFactory(this.settings.display.layoutMode).vertical,a=this.settings.player.scrollMode;if(i){let i=t.realBounds.y+this.settings.player.scrollOffsetY;if(i!==this._lastScroll)switch(this._lastScroll=i,a){case e.ScrollMode.Continuous:let a=this.uiFacade.getOffset(s,this.container);this.uiFacade.scrollToY(s,a.y+i,this.settings.player.scrollSpeed);break;case e.ScrollMode.OffScreen:let r=s.scrollTop+this.uiFacade.getOffset(null,s).h;if(t.visualBounds.y+t.visualBounds.h>=r||t.visualBounds.y<s.scrollTop){let e=t.realBounds.y+this.settings.player.scrollOffsetY;this.uiFacade.scrollToY(s,e,this.settings.player.scrollSpeed)}}}else{let i=t.visualBounds.x;if(i!==this._lastScroll)switch(this._lastScroll=i,a){case e.ScrollMode.Continuous:let i=t.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=t.visualBounds.x,this.uiFacade.scrollToX(s,i,this.settings.player.scrollSpeed);break;case e.ScrollMode.OffScreen:let a=s.scrollLeft+this.uiFacade.getOffset(null,s).w;if(t.visualBounds.x+t.visualBounds.w>=a||t.visualBounds.x<s.scrollLeft){let e=t.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=t.visualBounds.x,this.uiFacade.scrollToX(s,e,this.settings.player.scrollSpeed)}}}}internalCursorUpdateBeat(t,s,i,a,r,n,o,h,l){const d=this._barCursor,c=this._beatCursor;let u=o.barBounds.masterBarBounds,p=u.visualBounds;this._currentBarBounds=u,d&&d.setBounds(p.x,p.y,p.w,p.h),c&&(this.settings.player.enableAnimatedBeatCursor&&c.stopAnimation(),c.setBounds(o.onNotesX,p.y,1,p.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let g=!1;if(this._playerState===Fs.Playing&&!a){if(this.settings.player.enableElementHighlighting)for(let e of r){let s=tr.getGroupId(e.beat);this.uiFacade.highlightElements(s,t.voice.bar.index)}if(this.settings.player.enableAnimatedBeatCursor){let e=u.visualBounds.x+u.visualBounds.w;if(s&&l==Gs.ToNextBext){let t=n.findBeat(s);t&&t.barBounds.masterBarBounds.staffSystemBounds===u.staffSystemBounds&&(e=t.onNotesX)}this.uiFacade.beginInvoke((()=>{c&&c.transitionToX(i/this.playbackSpeed,e)}))}h=!a,g=!0}h&&!this._beatMouseDown&&this.settings.player.scrollMode!==e.ScrollMode.Off&&this.internalScrollToCursor(u),g&&(this.onPlayedBeatChanged(t),this.onActiveBeatsChanged(new ir(r.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 ar(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 ar(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){let e=this._tickCache?.getBeatStart(this._selectionStart.beat)??this._selectionStart.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(this._selectionEnd.beat)??this._selectionEnd.beat.absolutePlaybackStart)<e){let e=this._selectionStart;this._selectionStart=this._selectionEnd,this._selectionEnd=e}}if(this._selectionStart&&this._tickCache){let e=this._tickCache,t=e.getMasterBarStart(this._selectionStart.beat.voice.bar.masterBar);if(this._currentBeat=null,this._playerState===Fs.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){let s=e.getMasterBarStart(this._selectionEnd.beat.voice.bar.masterBar),i=new ja;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 ar(t.beat),i=new ar(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();let 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;let 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();let 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){let s=this.renderer.boundsLookup;if(!s)return;let 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));let a=this._tickCache?.getBeatStart(e.beat)??e.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(t.beat)??t.beat.absolutePlaybackStart)<a){let s=e;e=t,t=s}let r=e.bounds.realBounds.x,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){let 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);let l=e.bounds.barBounds.masterBarBounds.staffSystemBounds.index+1,d=t.bounds.barBounds.masterBarBounds.staffSystemBounds.index;for(let e=l;e<d;e++){let t=s.staffSystems[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),i.appendChild(r)}let c=this.uiFacade.createSelectionElement();c.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(c)}else{let 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||(ne.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))}}class nr extends K{constructor(t,s){super(e.AlphaTabErrorType.General,t),this.xhr=s,Object.setPrototypeOf(this,nr.prototype)}}class or{static loadScoreAsync(e,t,s,i){let a=new XMLHttpRequest;a.open("GET",e,!0,null,null),a.responseType="arraybuffer",a.onreadystatechange=()=>{if(a.readyState===XMLHttpRequest.DONE){let e=a.response;if(200===a.status||0===a.status&&e)try{let e=a.response,s=new Uint8Array(e),r=or.loadScoreFromBytes(s,i);t(r)}catch(e){s(e)}else 0===a.status?s(new nr("You are offline!!\n Please Check Your Network.",a)):404===a.status?s(new nr("Requested URL not found.",a)):500===a.status?s(new nr("Internel Server Error.",a)):"parsererror"===a.statusText?s(new nr("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?s(new nr("Request Time out.",a)):s(new nr("Unknow Error: "+a.responseText,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Ot);let s=xl.buildImporters();ne.debug("ScoreLoader",`Loading score from ${e.length} bytes using ${s.length} importers`);let i=null,a=Oe.fromBuffer(e);for(let e of s){a.reset();try{ne.debug("ScoreLoader","Importing using importer "+e.name),e.init(a,t),i=e.readScore(),ne.debug("ScoreLoader","Score imported using "+e.name);break}catch(t){if(!(t instanceof Q))throw ne.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;ne.debug("ScoreLoader",e.name+" does not support the file")}}if(i)return i;throw new Q("No compatible importer found for file")}}class hr{get isLeftMouseButton(){return 0===this.mouseEvent.button}getX(e){let t=e.element,s=t.getBoundingClientRect().left+t.ownerDocument.defaultView.pageXOffset;return this.mouseEvent.pageX-s}getY(e){let 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 lr{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 cs,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new hr(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new hr(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new hr(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&lr.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,lr.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,NaN,NaN,NaN)}setBounds(e,t,s,i){isNaN(e)&&(e=this.lastBounds.x),isNaN(t)&&(t=this.lastBounds.y),isNaN(s)&&(s=this.lastBounds.w),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=""}}lr.resizeObserver=new ae((()=>new ResizeObserver((e=>{for(const t of e){let e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class dr{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new ba,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(xl.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0,t=window.setInterval((()=>{ne.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);ne.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);let s=e=>{this._families.length>1?(ne.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(ne.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},i=e=>{ne.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 ne.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){ne.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 cr{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 ur{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new ya,this.samplesPlayed=new ba,this.sampleRequest=new ya}get sampleRate(){return this._context?this._context.sampleRate:ur.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(ne.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{ne.debug("WebAudio",`Audio Context resume success: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}`),e&&e()}),(e=>{ne.warning("WebAudio",`Audio Context resume failed: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}, reason=${e}`)})))}patchIosSampleRate(){let e=navigator.userAgent;if(-1!==e.indexOf("iPhone")||-1!==e.indexOf("iPad")){let e=this.createAudioContext(),t=e.createBuffer(1,1,ur.PreferredSampleRate),s=e.createBufferSource();s.buffer=t,s.connect(e.destination),s.start(0),s.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in xl.globalThis)return new AudioContext;if("webkitAudioContext"in xl.globalThis)return new webkitAudioContext;throw new K(e.AlphaTabErrorType.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(){let e=this._context;this.activate(),this._buffer=e.createBuffer(2,ur.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()}}ur.BufferSize=4096,ur.PreferredSampleRate=44100;class pr extends ur{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/ur.BufferSize),this._circularBuffer=new cr(ur.BufferSize*this._bufferCount),this.onReady()}play(){super.play();let 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;let t=e*ur.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*ur.BufferSize<t){for(let t=0;t<e;t++)this.onSampleRequest();this._requestedBufferCount+=e}}generateSound(e){let t=e.outputBuffer.getChannelData(0),s=e.outputBuffer.getChannelData(1),i=t.length+s.length,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/Ve.AudioChannels),this.requestBuffers()}}class gr{constructor(e,t){this.loaded=e,this.total=t}}class mr{get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return ne.logLevel}set logLevel(e){ne.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Ve.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Ve.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Ve.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=de.clamp(e,Ve.MinPlaybackSpeed,Ve.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=Fs.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 ya,this.readyForPlayback=new ya,this.finished=new ya,this.soundFontLoaded=new ya,this.soundFontLoadFailed=new ba,this.midiLoaded=new ba,this.midiLoadFailed=new ba,this.stateChanged=new ba,this.positionChanged=new ba,this.midiEventsPlayed=new ba,this.playbackRangeChanged=new ba,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Fs.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=xl.createWebWorker(t)}catch(e){ne.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:is.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,s){ne.debug("AlphaSynth",`Start loading Soundfont from url ${e}`);let i=new XMLHttpRequest;i.open("GET",e,!0,null,null),i.responseType="arraybuffer",i.onload=e=>{let s=new Uint8Array(i.response);this.loadSoundFont(s,t)},i.onerror=e=>{ne.error("AlphaSynth","Loading failed: "+e.message),this.soundFontLoadFailed.trigger(new nr(e.message,i))},i.onprogress=e=>{ne.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),s(new gr(e.loaded,e.total))},i.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:is.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,Ve.MinVolume),this._synth.postMessage({cmd:"alphaSynth.setChannelVolume",channel:e,volume:t})}handleWorkerMessage(e){let 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 pi(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new Sa(t.events.map(is.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new ui(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new _a(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 pi(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 fr{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new ba,this.partialRenderFinished=new ba,this.partialLayoutFinished=new ba,this.renderFinished=new ba,this.postRenderFinished=new ya,this.error=new ba,this._api=e;try{this._worker=xl.createWebWorker(t)}catch(e){return void ne.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=is.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){let 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=Da.fromJson(t.boundsLookup,this._api.score),this.boundsLookup.finish(),this.postRenderFinished.trigger();break;case"alphaTab.error":this.error.trigger(t.error)}}renderScore(e,t){let s=null==e?null:is.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:s,trackIndexes:t,fontSizes:Na.FontSizeLookupTables})}}class yr{constructor(e,t,s,i){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=s,this.selectionWrapper=i}}class br{static init(){var e;br._isRegistered||(br._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,ne.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new cr(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){let t=e.data;switch(t.cmd){case Ba.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case Ba.CmdOutputResetSamples:this._circularBuffer.clear();break;case Ba.CmdOutputStop:this._isStopped=!0}}process(e,t,s){if(1!==t.length&&2!==t[0].length)return!1;let i=t[0][0],a=t[0][1];if(!i||!a)return!0;let r=i.length+a.length,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:Ba.CmdOutputSamplesPlayed,samples:o/Ve.AudioChannels}),this.requestBuffers(),this._circularBuffer.count>0||!this._isStopped}requestBuffers(){const t=this._bufferCount/2|0;let s=t*e.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*e.BufferSize<s){for(let e=0;e<t;e++)this.port.postMessage({cmd:Ba.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}br._isRegistered=!1;class Sr extends ur{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();let e=this._context;xl.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=>{ne.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){let t=e.data;switch(t.cmd){case Ba.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case Ba.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.postMessage({cmd:Ba.CmdOutputStop}),this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){this._worklet?.port.postMessage({cmd:Ba.CmdOutputAddSamples,samples:e})}resetSamples(){this._worklet?.port.postMessage({cmd:Ba.CmdOutputResetSamples})}}class _r extends lr{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){isNaN(e)&&(e=this.lastBounds.x),isNaN(t)&&(t=this.lastBounds.y),isNaN(s)?s=this.lastBounds.w:s/=this._xscale,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"}(Ws||(Ws={}));class wr{get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(xl.bravuraFontChecker.checkForFontAvailability(),!xl.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(ne.debug("Font","All fonts loaded: "+this._fontCheckers.size),!0)}onFontLoaded(e){Na.generateFontLookup(e),this.areAllFontsLoaded()&&this.canRenderChanged.trigger()}constructor(t){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 ya,this.canRenderChanged=new ya,this._highlightedElements=[],this._scrollContainer=null,xl.webPlatform!==e.WebPlatform.Browser&&xl.webPlatform!==e.WebPlatform.BrowserModule)throw new K(e.AlphaTabErrorType.General,"Usage of AlphaTabApi is only possible in browser environments. For usage in node use the Low Level APIs");t.classList.add("alphaTab"),this.rootContainer=new lr(t),this.areWorkersSupported="Worker"in window,xl.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(t)}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!==Ws.RenderRequested&&(s.resultState=Ws.RenderRequested,this._api.renderer.renderResult(s.layoutResultId)):e.replaceChildren():s.resultState===Ws.Detached&&(e.replaceChildren(...s.renderedResult),s.resultState=Ws.RenderDone):s.resultState===Ws.RenderDone&&(s.resultState=Ws.Detached,s.replaceChildren())}}}createWorkerRenderer(){return new fr(this._api,this._api.settings)}initialize(t,s){let i;this._api=t,i=s instanceof Ot?s:is.jsObjectToSettings(s);let a=this.getDataAttributes();Rt.fromJson(i,a),i.notation.notationMode===e.NotationMode.SongBook&&i.setSongBookModeSettings(),t.settings=i,this.setupFontCheckers(i),this._initialTrackIndexes=this.parseTracks(i.core.tracks),this._contents="";let r=t.container;i.core.tex&&(this._contents=r.element.innerHTML,r.element.innerHTML=""),this.createStyleElement(i),this._file=i.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(", "))){let t=new dr(e.families);this._fontCheckers.set(e.families.join(", "),t),t.fontLoaded.on(this.onFontLoaded.bind(this)),t.checkForFontAvailability()}}destroy(){this.rootContainer.element.innerHTML=""}createCanvasElement(){let 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 lr(e)}triggerEvent(e,t,s=null,i){let a=e.element;t="alphaTab."+t;let 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){let e=window.jQuery,i=[];i.push(s),n&&i.push(n),e(a).trigger(t,i)}}load(e,t,s){if(e instanceof ve)return t(e),!0;if(e instanceof ArrayBuffer){let s=new Uint8Array(e);return t(or.loadScoreFromBytes(s,this._api.settings)),!0}return e instanceof Uint8Array?(t(or.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(or.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&&or.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){let t=this._api.container.element.ownerDocument;xl.createStyleElement(t,e.core.fontDirectory)}parseTracks(e){if(!e)return[];let 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){let s=e.length,i=e;for(let e=0;e<s;e++){let s=i[e],a=0;a="number"==typeof s?s:"index"in s?s.index:parseInt(s.toString()),(a>=0||-1===a)&&t.push(a)}}else"index"in e&&t.push(e.index);return t}getDataAttributes(){let e=new Map,t=this._api.container.element;if(t.dataset)for(let s of Object.keys(t.dataset)){let i=t.dataset[s];try{let 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++){let i=t.attributes.item(s),a=i.nodeName;if(a.startsWith("data-")){let t=a.substr(5).split("-"),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=Ws.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=Ws.LayoutDone,delete s.renderedResultId,delete s.renderedResult,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 t=null,s="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window&&this._api.settings.player.outputMode===e.PlayerOutputMode.WebAudioAudioWorklets?(ne.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),t=new mr(new Sr(this._api.settings),this._api.settings)):s&&(ne.debug("Player","Will use webworkers for synthesizing and web audio api with ScriptProcessor for playback"),t=new mr(new pr,this._api.settings)),t?t.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):ne.error("Player","Player requires webworkers and web audio api, browser unsupported",null),t}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const s=this._barToElementLookup.get(t);if(s){let 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(){let e=this._api.container.element,t=e.querySelector(".at-cursors");e.removeChild(t)}createCursors(){let e=this._api.container.element,t=document.createElement("div");t.classList.add("at-cursors");let s=document.createElement("div");s.classList.add("at-selection");const i=this.createScalingElement(),a=this.createScalingElement();let r=i.element;r.classList.add("at-cursor-bar");let 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 yr(new lr(t),i,a,new lr(s))}getOffset(e,t){let s=t.element,i=s.getBoundingClientRect(),a=i.top+s.ownerDocument.defaultView.pageYOffset,r=i.left+s.ownerDocument.defaultView.pageXOffset;if(e){let t=e.element,s=t.nodeName.toLowerCase();if("html"!==s&&"body"!==s){let s=this.getOffset(null,e);a=a+t.scrollTop-s.y,r=r+t.scrollLeft-s.x}}let n=new cs;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,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 lr(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new _r(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{let i=e.scrollTop,a=t-i,r=0,n=t=>{0===r&&(r=t);let 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{let i=e.scrollLeft,a=t-i,r=0,n=t=>{0===r&&(r=t);let o=t-r,h=Math.min(o/s,1);e.scrollLeft=i+a*h|0,o<s&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}}class Br extends rr{constructor(e,t){super(new wr(e),t),this.soundFontLoad=new ba}tex(e,t){let s=this.uiFacade;super.tex(e,s.parseTracks(t))}print(t,s=null){let i=window.open("","","width=0,height=0"),a=i.document.createElement("div");t?a.style.width=t:this.settings.display.layoutMode===e.LayoutMode.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);let 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,d=a.offsetWidth+50,c=window.innerHeight,u=(h/2|0)-(d/2|0)+n,p=(l/2|0)-(c/2|0)+o;i.resizeTo(d,c),i.moveTo(u,p),i.focus();let g=is.jsObjectToSettings(is.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,Rt.fromJson(g,s);let m=new Br(a,g);i.onunload=()=>{m.destroy()},m.renderer.postRenderFinished.on((()=>{i.print()})),m.renderTracks(this.tracks)}downloadMidi(e=je.SingleTrackMultiChannel){if(!this.score)return;let t=new ht;t.format=e;let s=new Aa(t,!0);new qa(this.score,this.settings,s).generate();let i=t.toBinary(),a=this.score.title?`${this.score.title}.mid`:"File.mid",r=document.createElement("a");r.download=a;let 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){let s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackMute(s,t)}changeTrackSolo(e,t){let s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackSolo(s,t)}changeTrackVolume(e,t){let s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackVolume(s,t)}trackIndexesToTracks(e){if(!this.score)return[];let t=[];if(1===e.length&&-1===e[0])for(let e of this.score.tracks)t.push(e);else for(let 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 Tr{constructor(){this._initListeners=[]}exec(e,t,s){if("string"!=typeof t&&(s=[t],t="init"),95===t.charCodeAt(0)||"exec"===t)return null;let i=new jQuery(e),a=i.data("alphaTab");if("destroy"===t&&!a)return null;if("init"!==t&&!a)throw new Error("alphaTab not initialized");let r=this[t];if(r){let e=[i,a].concat(s);return r.apply(this,e)}return ne.error("Api","Method '"+t+"' does not exist on jQuery.alphaTab"),null}init(e,t,s){if(!t){t=new Br(e[0],s),e.data("alphaTab",t);for(let 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 kr{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.scale=1,this.color=new Ee(255,255,255,255),this.lineWidth=1,this.font=new nt("Arial",10,Ye.Plain),this.textAlign=L.Left,this.textBaseline=M.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=M.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!==L.Left&&(i+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),i+=`>${kr.escapeText(e)}</text>`,this.buffer+=i}static escapeText(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}getSvgTextAlignment(e){switch(e){case L.Left:return"start";case L.Center:return"middle";case L.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case M.Top:return"dominant-baseline: hanging";case M.Bottom:return"dominant-baseline: ideographic";default:return""}}measureText(e){return e?Na.measureString(e,this.font.families,this.font.size*this.scale,this.font.style,this.font.weight):new ce(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 Nr extends kr{constructor(){super()}fillMusicFontSymbol(e,t,s,i,a){i!==D.None&&this.fillMusicFontSymbolText(e,t,s,`&#${i};`,a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(let e of i)e!==D.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(L.Center)+'"'),this.buffer+=`>${i}</text></g>`}}class xr{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"}(zs||(zs={}));class vr extends Ka{get isEmpty(){return!this.glyphs||0===this.glyphs.length}constructor(e,t){super(e,t),this.glyphs=null}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++){let 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){let i=this.glyphs;if(i&&0!==i.length)for(let a of i)a.paint(e+this.x,t+this.y,s)}}class Pr extends vr{constructor(){super(0,0),this.glyphs=[]}addGlyph(e){e.x=0===this.glyphs.length?0:this.glyphs[this.glyphs.length-1].x+this.glyphs[this.glyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.width=e.x+e.width,super.addGlyph(e)}}class Cr extends vr{constructor(e,t,s){super(e,t),this.voice=s,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){let t=this.renderer.layoutingInfo.spaceToForce(e);this.scaleToForce(t)}scaleToForce(e){this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e);let t=this.renderer.layoutingInfo.buildOnTimePositions(e),s=this.beatGlyphs;for(let e=0,i=s.length;e<i;e++){let a=s[e];if(a.beat.graceType===f.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;let e=this.renderer.layoutingInfo.allGraceRods.get(r);const s=a.beat.graceGroup.beats[a.beat.graceGroup.beats.length-1].nextBeat,n=s?this.renderer.layoutingInfo.getPreBeatSize(s)+tr.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{let t=this.renderer.layoutingInfo.incompleteGraceRods.get(r);const 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){let t=a.x-s[e-1].x;s[e-1].scaleToWidth(t)}if(e===i-1){let e=this.width-s[s.length-1].x;a.scaleToWidth(e)}}}registerLayoutingInfo(e){let t=this.beatGlyphs;for(let s of t)s.registerLayoutingInfo(e)}applyLayoutingInfo(e){let t=this.beatGlyphs;for(let s of t)s.applyLayoutingInfo(e);this.scaleToForce(Math.max(this.renderer.settings.display.stretchForce,e.minStretchForce))}addGlyph(e){let 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){s.color=0===this.voice.index?this.renderer.resources.mainGlyphColor:this.renderer.resources.secondaryGlyphColor;for(let i=0,a=this.beatGlyphs.length;i<a;i++)this.beatGlyphs[i].paint(e+this.x,t+this.y,s)}}Cr.KeySizeBeat="Beat";class Er{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class Fr{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:pe.getArticulationByValue(t)?.staffLine??0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case S.ForceDoubleFlat:t+=2;break;case S.ForceDoubleSharp:t-=2;break;case S.ForceFlat:t+=1;break;case S.ForceSharp:t-=1}return t}applyAccidental(e){const t=Fr.getNoteValue(e);let 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=Fr.getNoteValue(t);return s=e.staff.isPercussion?Fr.getPercussionLine(e,i):Fr.calculateNoteLine(e,i),s}static computeAccidental(e,t,s,i,a=null){let r=e+7,n=s%12,o=r<7?Je.Flat:Je.Sharp,h=Fr.KeySignatureLookup[r][n],l=Fr.AccidentalNotes[n],d=Je.None;if(i)switch(d=l?o:Je.Natural,d){case Je.Natural:d=Je.NaturalQuarterNoteUp;break;case Je.Sharp:d=Je.SharpQuarterNoteUp;break;case Je.Flat:d=Je.FlatQuarterNoteUp}else{switch(t){case S.ForceSharp:d=Je.Sharp;break;case S.ForceDoubleSharp:d=Je.DoubleSharp;break;case S.ForceFlat:d=Je.Flat;break;case S.ForceDoubleFlat:d=Je.DoubleFlat;break;default:l?d=o:h&&(d=Je.Natural)}d!==Je.None?null!=a?a===d&&(d=Je.None):h&&d===o&&(d=Je.None):null!==a&&(d=a===Je.Natural?Je.None:Je.Natural)}return d}getAccidental(e,t,s,i,a=null){let r=0,n=Je.None;if(this._bar.staff.isPercussion)r=Fr.getPercussionLine(this._bar,e);else{const s=a?a.accidentalMode:S.Default;r=Fr.calculateNoteLine(this._bar,e);const i=this._registeredAccidentals.has(r)?this._registeredAccidentals.get(r):null;n=Fr.computeAccidental(this._bar.masterBar.keySignature,s,e,t,i);let o=!1;switch(n){case Je.NaturalQuarterNoteUp:case Je.SharpQuarterNoteUp:case Je.FlatQuarterNoteUp:break;default:if(a&&a.isTieDestination&&0===a.beat.index){const e=this._barRenderer.previousRenderer;if(e){e.accidentalHelper.getNoteLine(a.tieOrigin)===r&&(o=!0)}}o?n=Je.None:n!==Je.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 Er,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 calculateNoteLine(e,t){let s=t,i=e.masterBar.keySignature,a=e.clef,r=s%12,n=(s/12|0)-1,o=Fr.OctaveSteps[a];return o-=n*Fr.StepsPerOctave,o-=(de.keySignatureIsSharp(i)||de.keySignatureIsNatural(i)?Fr.SharpNoteSteps:Fr.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}}Fr.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]],Fr.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],Fr.StepsPerOctave=7,Fr.OctaveSteps=[38,32,30,26,38],Fr.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],Fr.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class Dr{constructor(){this.staffId="",this.up=0,this.down=0}}class Lr{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 Mr{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>g.Whole}hasFlag(e,t){return e&&this.beatHasFlag(t)||!e&&1===this.beats.length&&this.beatHasFlag(this.beats[0])}beatHasFlag(e){return!e.isRest&&(e.duration>g.Quarter||e.graceType!==f.None)}constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=g.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=We.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===We.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){let 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 Dr),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(We.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==f.None)&&(e=this.invert(We.Up)):e=We.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){let t=this._renderer.getNoteY(this.highestNoteInHelper,Xs.Center),s=this._renderer.getNoteY(this.lowestNoteInHelper,Xs.Center);if(null===e){const i=(t+s)/2;e=this.invert(this._renderer.middleYPosition<i?We.Up:We.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(We.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case g.QuadrupleWhole:case g.DoubleWhole:return[2,2];case g.Whole:return[0,1];case g.Half:return[1,0];case g.Quarter:return[3,3];case g.Eighth:return[2,2];case g.Sixteenth:return[2,4];case g.ThirtySecond:return[4,4];case g.SixtyFourth:return[4,6];case g.OneHundredTwentyEighth:return[6,6];case g.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=Mr.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===We.Down?We.Up:We.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 W.Auto:case W.ForceSplitOnSecondaryToNext:t=Mr.canJoin(this.beats[this.beats.length-1],e);break;case W.ForceSplitToNext:t=!1;break;case W.ForceMergeWithNext:t=!0}return t&&(null==this.preferredBeamDirection&&null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.hasTuplet&&(this.hasTuplet=!0),e.graceType!==f.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=-Fr.getPercussionLine(this.voice.bar,Fr.getNoteValue(e)),s=t):(t=Fr.getNoteValue(e),s=t,e.harmonicType!==b.None&&e.harmonicType!==b.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===f.BendGrace||t.graceType===f.BendGrace)return!1;if(e.graceType!==f.None&&t.graceType!==f.None)return!0;let s=e.voice.bar;if(s!==t.voice.bar)return!1;let i=e.playbackStart,a=t.playbackStart;if(!Mr.canJoinDuration(e.duration)||!Mr.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=te.QuarterTime;if(8===s.masterBar.timeSignatureDenominator)s.masterBar.timeSignatureNumerator%3==0&&(r+=te.QuarterTime/2|0);return((r+i)/r|0)===((r+a)/r|0)}static canJoinDuration(e){switch(e){case g.Whole:case g.Half:case g.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,s){return de.getIndex(e.duration)-2-s>0&&de.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 Ir{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class Ar{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new Ir(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 Rr{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 Ar(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=Mr.computeLineHeightsForRest(e.duration).map((e=>e*s));let a=t-i[0],r=t+i[1],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;let t=n+i[0]+i[1];const r=2*s;let h=Math.ceil(Math.abs(n-a)/r);return o.addSlot(n,t),n<a?h*-r:h*r}}return 0}}class Or{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this.preferredBeamDirection=null,this._renderer=e,this.collisionHelper=new Rr}initialize(){var e=this._renderer,t=this._renderer.bar;let s=null,i=null;for(let a=0,r=t.voices.length;a<r;a++){let r=t.voices[a];this.beamHelpers.push([]),this.beamHelperLookup.push(new Map);for(let a=0,n=r.beats.length;a<n;a++){let n,o=r.beats[a];o.graceType!==f.None?n=i:(n=s,i=null),n&&n.checkBeat(o)||(n&&n.finish(),n=new Mr(t.staff,e),n.preferredBeamDirection=this.preferredBeamDirection,n.checkBeat(o),o.graceType!==f.None?i=n:s=n,this.beamHelpers[r.index].push(n)),this.beamHelperLookup[r.index].set(o.index,n)}s&&s.finish(),i&&i.finish(),s=null,i=null}}getBeamingHelperForBeat(e){return this.beamHelperLookup[e.voice.index].get(e.index)}}class Vr extends Qa{constructor(e,t,s){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=s}doLayout(){super.doLayout();let e=this.renderer.resources;this._textRow=1.5*e.effectFont.size,this._fretRow=1.5*e.effectFont.size,this._chord.firstFret>1?this._firstFretSpacing=Vr.FretSpacing:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+Vr.Frets*Vr.FretSpacing+2*Vr.Padding[1],this.width=this._firstFretSpacing+(this._chord.staff.tuning.length-1)*Vr.StringSpacing+2*Vr.Padding[0]}paint(e,t,s){e+=this.x+Vr.Padding[0]+this._firstFretSpacing,t+=this.y;let i=Vr.StringSpacing,a=Vr.FretSpacing,r=this.renderer.resources,n=Vr.CircleRadius,o=this.width-2*Vr.Padding[0]-this._firstFretSpacing,h=s.textAlign,l=s.textBaseline;s.font=r.effectFont,s.textAlign=L.Center,s.textBaseline=M.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=M.Middle;for(let a=0;a<this._chord.staff.tuning.length;a++){let r=e+a*i,n=t+this._fretRow/2,o=this._chord.strings[this._chord.staff.tuning.length-a-1];o<0?s.fillMusicFontSymbol(r,n,1,D.FretboardX,!0):0===o?s.fillMusicFontSymbol(r,n,1,D.FretboardO,!0):(o-=this._chord.firstFret-1,s.fillText(o.toString(),r,n))}t+=this._fretRow;for(let r=0;r<this._chord.staff.tuning.length;r++){let n=e+r*i;s.fillRect(n,t,1,a*Vr.Frets+1)}this._chord.firstFret>1&&(s.textAlign=L.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<=Vr.Frets;i++){let r=t+i*a;s.fillRect(e,r,o,1)}let d=new Map;for(let e of this._chord.barreFrets){let t=[-1,-1];d.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,d.has(o)){let e=d.get(o);(-1===e[0]||r<e[0])&&(e[0]=r),(-1===e[1]||r>e[1])&&(e[1]=r)}let 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 d){let h=t+r*a+a/2+.5,l=e+(this._chord.strings.length-o[1]-1)*i,d=e+(this._chord.strings.length-o[0]-1)*i;s.fillRect(l,h-n,d-l,2*n)}s.textAlign=h,s.textBaseline=l}}Vr.Padding=[5,2],Vr.Frets=5,Vr.CircleRadius=2.5,Vr.StringSpacing=10,Vr.FretSpacing=12;class Hr extends vr{constructor(e,t,s=L.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=s}doLayout(){let e=0;switch(this._align){case L.Left:e=0;break;case L.Center:e=(this.width-this._glyphWidth)/2;break;case L.Right:e=this.width-this._glyphWidth}for(let 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 Gr extends vr{constructor(e,t,s=L.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=s}doLayout(){let e=0,t=0,s=Gr.Padding;this._rows=[];let i=new Hr(e,t,this._align);i.width=this.width;for(let 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 Hr(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(let i of this._rows)i.paint(e+this.x,t+this.y,s)}}Gr.Padding=3;class Wr extends Gr{constructor(e,t){super(e,t)}addChord(e){if(e.strings.length>0){let t=new Vr(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}}class zr extends Qa{constructor(e,t,s,i,a=L.Left,r=null){super(e,t),this._lineHeights=null,this._lines=s.split("\n"),this.font=i,this.textAlign=a,this.textBaseline=r}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){let i=s.color;s.color=i,s.font=this.font;let 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}}class Ur{get staveId(){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.staveId,e)}addBar(e,t){let s;s=e?this._factory.create(this.system.layout.renderer,e):new an(this.system.layout.renderer,e),s.staff=this,s.index=this.barRenderers.length,s.layoutingInfo=t,s.doLayout(),s.registerLayoutingInfo();const i=s.barDisplayWidth;i>0&&this.system.layout.systemsLayoutMode==Us.FromModelWithWidths&&(s.width=i),this.barRenderers.push(s),e&&this.system.layout.registerBarRenderer(this.staveId,s)}revertLastBar(){let e=this.barRenderers[this.barRenderers.length-1];this.barRenderers.splice(this.barRenderers.length-1,1),this.system.layout.unregisterBarRenderer(this.staveId,e);for(const e of this.barRenderers)e.applyLayoutingInfo();return e}scaleToWidth(e){this._sharedLayoutData=new Map;let t=this.topOverflow,s=0;switch(this.system.layout.systemsLayoutMode){case Us.Automatic:let i=(e-this.system.computedWidth)/this.barRenderers.length;for(const e of this.barRenderers){e.x=s,e.y=this.topSpacing+t;let a=e.computedWidth+i;e.scaleToWidth(a),s+=e.width}break;case Us.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 Us.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++){let 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++){let 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,this.height=Math.max(this.height,this.barRenderers[e].height),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 Xr{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 Jr{constructor(){this._timeSortedSprings=[],this._xMin=0,this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,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!==f.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!==f.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 Xr,r.timePosition=e,r.allDurations.add(t),this._timeSortedSprings.length>0){let e=this._timeSortedSprings[this._timeSortedSprings.length-1];for(const t of e.allDurations)e.timePosition}r.longestDuration=t,r.postSpringWidth=a,r.graceBeatWidth=s,r.preBeatWidth=i,this.springs.set(e,r);let n=this._timeSortedSprings,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){let i=e.absoluteDisplayStart;if(e.graceType!==f.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));let 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 Xr;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(){this._xMin=0;let e=this.springs;for(const t of e.values())t.springWidth<this._xMin&&(this._xMin=t.springWidth);let t=0,s=this._timeSortedSprings;if(0===s.length)return this.totalSpringConstant=-1,void(this.minStretchForce=-1);for(let e=0;e<s.length;e++){let i=s[e],a=0;if(e===s.length-1)a=i.longestDuration;else{let t=s[e+1];a=Math.abs(t.timePosition-i.timePosition)}i.springConstant=this.calculateSpringConstant(i,a),t+=1/i.springConstant}this.totalSpringConstant=1/t,this.minStretchForce=0;for(let e=0;e<s.length;e++){let t=s[e],i=0;if(e===s.length-1)i=t.postSpringWidth;else{let a=s[e+1];i=t.postSpringWidth+a.preSpringWidth}0===e&&(i+=t.preSpringWidth);let a=i*t.springConstant;this.updateMinStretchForce(a)}}paint(e,t,s){}calculateSpringConstant(e,t){return t<=0&&(t=te.toTicks(g.SixtyFourth)),0===e.smallestDuration&&(e.smallestDuration=t),e.smallestDuration/t*(1/((1+.85*Math.log2(t/Jr.MinDuration))*Jr.MinDurationWidth))}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(de.isAlmostEqualTo(this._onTimePositionsForce,e)&&this._onTimePositions)return this._onTimePositions;this._onTimePositionsForce=e;let t=new Map;this._onTimePositions=t;let 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}}Jr.MinDuration=30,Jr.MinDurationWidth=7;class Yr{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.renderers=[]}}class qr{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 jr{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);if(this.width=3,!this.drawAsBrace||!this.firstStaffInBracket||!this.lastStaffInBracket)return;const e=this.firstStaffInBracket.contentTop,t=(this.lastStaffInBracket.contentBottom-e)/xl.MusicFontSize;this.braceScale=t,this.width=3*this.braceScale}}class Kr extends jr{constructor(e){super(),this.track=e,this.drawAsBrace=Kr.isTrackDrawAsBrace(e)}includesStaff(e){return e.modelStaff.track===this.track}static isTrackDrawAsBrace(e){return e.staves.filter((e=>e.showStandardNotation)).length>1}}class Qr extends Kr{constructor(e){super(e)}includesStaff(e){return e.modelStaff.track===this.track||!this.drawAsBrace&&this.track.playbackInfo.program==e.modelStaff.track.playbackInfo.program}}class $r{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++){let i=this.staves[e];for(let e=0,a=i.staves.length;e<a;e++){let a=i.staves[e],r=t.renderers[s++];a.addBarRenderer(r)}}return this.calculateAccoladeSpacing(e),this.updateWidthFromLastBar(),t}addBars(e,t){if(0===e.length)return null;let s=new Yr;s.layoutingInfo=new Jr,s.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(s);let i=s.layoutingInfo;for(let e of this.staves)for(let a of e.staves){let r=e.track.staves[a.modelStaff.index].bars[t];a.addBar(r,i);let n=a.barRenderers[a.barRenderers.length-1];s.renderers.push(n),n.isLinkedToPrevious&&(s.isLinkedToPrevious=!0),n.canWrap||(s.canWrap=!1)}return this.calculateAccoladeSpacing(e),i.finish(),s.width=this.updateWidthFromLastBar(),s}revertLastBar(){if(this.masterBarsRenderers.length>1){let 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++){let i=this._allStaves[e].revertLastBar();const 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++){let i=this._allStaves[s];const 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(t){const s=this.layout.renderer.settings;if(!this._accoladeSpacingCalculated){this._accoladeSpacingCalculated=!0,this.accoladeWidth=0;const i=this.layout.renderer.score.stylesheet;if(this.layout.renderer.settings.notation.isNotationElementVisible(e.NotationElement.TrackNames)){const e=1===this.layout.renderer.tracks.length?i.singleTrackTrackNamePolicy:i.multiTrackTrackNamePolicy,a=0===this.index?i.firstSystemTrackNameMode:i.otherSystemsTrackNameMode,r=0===this.index?i.firstSystemTrackNameOrientation:i.otherSystemsTrackNameOrientation;let n=!1;switch(e){case X.Hidden:break;case X.FirstSystem:n=0===this.index;break;case X.AllSystems:n=!0}let o=!1;if(n){let e=this.layout.renderer.canvas,i=s.display.resources.effectFont;e.font=i;for(let s of t){let t="";switch(a){case J.FullName:t=s.name;break;case J.ShortName:t=s.shortName}if(t.length>0){o=!0;const s=e.measureText(t);switch(r){case Y.Horizontal:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,s.width));break;case Y.Vertical:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,s.height))}}}o&&(this.accoladeWidth+=s.display.systemLabelPaddingLeft,this.accoladeWidth+=s.display.systemLabelPaddingRight)}}let a=0;for(let e of this._allStaves)e.y=a,e.calculateHeightForAccolade(),a+=e.height;let r=0;for(const e of this._brackets)e.finalizeBracket(),r=Math.max(r,e.width);this.accoladeWidth+=r,this.width+=this.accoladeWidth,this.computedWidth+=this.accoladeWidth}}getStaffTrackGroup(e){for(let t=0,s=this.staves.length;t<s;t++){let s=this.staves[t];if(s.track===e)return s}return null}addStaff(e,t){let s=this.getStaffTrackGroup(e);if(s||(s=new qr(this,e),this.staves.push(s)),t.staffTrackGroup=s,t.system=this,t.index=this._allStaves.length,this._allStaves.push(t),s.addStaff(t),t.isInsideBracket){this._firstStaffInBrackets||(this._firstStaffInBrackets=t,t.isFirstInSystem=!0),s.firstStaffInBracket||(s.firstStaffInBracket=t),this._lastStaffInBrackets=t,s.lastStaffInBracket=t;let i=this._brackets.find((e=>e.includesStaff(t)));if(!i)switch(e.score.stylesheet.bracketExtendMode){case U.NoBrackets:break;case U.GroupStaves:i=new Kr(e),i.index=this._brackets.length,this._brackets.push(i);break;case U.GroupSimilarInstruments:i=new Qr(e),i.index=this._brackets.length,this._brackets.push(i)}i&&(i.firstStaffInBracket||(i.firstStaffInBracket=t),i.lastStaffInBracket=t,s.bracket=i)}}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){t+=this.topPadding,this.paintPartial(e+this.x,t+this.y,s,0,this.masterBarsRenderers.length),this._hasSystemSeparator&&(s.fillMusicFontSymbol(e+this.x,t+this.y+this.height-10,1,D.SystemDivider,!1),s.fillMusicFontSymbol(e+this.x+this.width-$r.SystemSignSeparatorWidth,t+this.y+this.height-$r.SystemSignSeparatorPadding,1,D.SystemDivider,!1))}paintPartial(t,s,i,a,r){for(let e=0,n=this._allStaves.length;e<n;e++)this._allStaves[e].paint(t,s,i,a,r);let n=this.layout.renderer.settings.display.resources;if(this.staves.length>0&&0===a){i.color=n.barSeparatorColor;const a=this._firstStaffInBrackets,r=this._lastStaffInBrackets;if(a&&r){let e=s+a.contentTop,n=s+r.contentBottom,o=t+a.x;i.beginPath(),i.moveTo(o,e),i.lineTo(o,n),i.stroke()}const o=this.layout.renderer.settings,h=this.layout.renderer.settings.notation.isNotationElementVisible(e.NotationElement.TrackNames);if(i.font=n.effectFont,h){const e=this.layout.renderer.score.stylesheet,a=1===this.layout.renderer.tracks.length?e.singleTrackTrackNamePolicy:e.multiTrackTrackNamePolicy,r=0===this.index?e.firstSystemTrackNameMode:e.otherSystemsTrackNameMode,n=0===this.index?e.firstSystemTrackNameOrientation:e.otherSystemsTrackNameOrientation;let h=!1;switch(a){case X.Hidden:break;case X.FirstSystem:h=0===this.index;break;case X.AllSystems:h=!0}if(h){const e=i.textBaseline,a=i.textAlign;for(const e of this.staves)if(e.firstStaffInBracket&&e.lastStaffInBracket){let a=s+e.firstStaffInBracket.contentTop,h=s+e.lastStaffInBracket.contentBottom,l="";switch(r){case J.FullName:l=e.track.name;break;case J.ShortName:l=e.track.shortName}if(l.length>0){const s=t+e.firstStaffInBracket.x-o.display.accoladeBarPaddingRight-(e.bracket?.width??0)-o.display.systemLabelPaddingRight;switch(n){case Y.Horizontal:i.textBaseline=M.Middle,i.textAlign=L.Right,i.fillText(l,s,(a+h)/2);break;case Y.Vertical:i.textBaseline=M.Bottom,i.textAlign=L.Center;const e=.1;i.beginRotate(s,(a+h)/2,-90-e),i.fillText(l,0,0),i.endRotate()}}}i.textBaseline=e,i.textAlign=a}}for(const e of this._brackets)if(e.firstStaffInBracket&&e.lastStaffInBracket){const a=t+e.firstStaffInBracket.x,r=e.width,n=o.display.accoladeBarPaddingRight;let h=s+e.firstStaffInBracket.contentTop,l=s+e.lastStaffInBracket.contentBottom;if(e.drawAsBrace)i.fillMusicFontSymbol(a-n-r,l,e.braceScale,D.Brace);else if(e.firstStaffInBracket!==e.lastStaffInBracket){const e=r/2;h-=e,l+=2*e,i.fillRect(a-n-r,h,r,Math.ceil(l-h));let t=a-n-r-.5;i.fillMusicFontSymbol(t,h,1,D.BracketTop),i.fillMusicFontSymbol(t,Math.floor(l),1,D.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+=$r.SystemSignSeparatorHeight,this._hasSystemSeparator=!0);let t=0;for(let 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;let 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),d=n-r,c=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 Fa;g.visualBounds=new cs,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 cs,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);let m=new Map;for(let e=0;e<this.staves.length;e++)for(let s of this.staves[e].stavesRelevantForBoundsLookup)for(let e of s.barRenderers){let i;m.has(e.bar.masterBar.index)?i=m.get(e.bar.masterBar.index):(i=new Ca,i.index=e.bar.masterBar.index,i.isFirstOfLine=e.isFirstOfLine,i.realBounds=new cs,i.realBounds.x=p+e.x,i.realBounds.y=o,i.realBounds.w=e.width,i.realBounds.h=u,i.visualBounds=new cs,i.visualBounds.x=p+e.x,i.visualBounds.y=r,i.visualBounds.w=e.width,i.visualBounds.h=d,i.lineAlignedBounds=new cs,i.lineAlignedBounds.x=p+e.x,i.lineAlignedBounds.y=l,i.lineAlignedBounds.w=e.width,i.lineAlignedBounds.h=c,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;let t=this.layout.renderer.tracks[0].staves[0].bars[e];return this.layout.getRendererForBar(this._firstStaffInBrackets.staveId,t).x}}$r.SystemSignSeparatorHeight=40,$r.SystemSignSeparatorPadding=10,$r.SystemSignSeparatorWidth=36;class Zr extends vr{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=M.Middle,super.paint(e,t,s)}createGlyphs(e){const t=this.renderer.resources;this.height=0;if(this._trackLabel.length>0){const e=new zr(0,this.height,this._trackLabel,t.effectFont,L.Left);e.renderer=this.renderer,e.doLayout(),this.height+=e.height,e.y+=e.height/2,this.addGlyph(e)}const s=new zr(0,this.height,e.name,t.effectFont,L.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=Zr.CircleNumberScale,i=Zr.CircleNumberHeight*s;let a=0|Math.ceil(e.tunings.length/2),r=0,n=this.height;for(let o=0,h=e.tunings.length;o<h;o++){const h=D.GuitarString0+(o+1);this.addGlyph(new $a(r,n+i/2.5,s,h));const l="= "+De.getTextForTuning(e.tunings[o],!1);this.addGlyph(new zr(r+i+1,n,l,t.effectFont,L.Left)),n+=15,o===a-1&&(n=this.height,r+=64)}this.height+=15*a}this.width+=15}}Zr.CircleNumberHeight=20,Zr.CircleNumberScale=.7;class en extends Gr{constructor(e,t){super(e,t,L.Left)}addTuning(e,t){if(e.tunings.length>0){let s=new Zr(0,0,e,t);s.renderer=this.renderer,s.doLayout(),this.glyphs.push(s)}}}class tn{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"}(Us||(Us={}));class sn{get scaledWidth(){return this.width/this.renderer.settings.display.scale}constructor(e){this._barRendererLookup=new Map,this.width=0,this.height=0,this.scoreInfoGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this.systemsLayoutMode=Us.Automatic,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t)),this.firstBarIndex=t;let s=this.renderer.settings.display.barCount;s<0&&(s=e.masterBars.length),s=t+s-1,s=Math.min(e.masterBars.length-1,Math.max(0,s)),this.lastBarIndex=s,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 tn(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)}}createScoreInfoGlyphs(){ne.debug("ScoreLayout","Creating score info glyphs");let t=this.renderer.settings.notation,s=this.renderer.score,i=this.renderer.settings.display.resources;this.scoreInfoGlyphs=new Map,s.title&&t.isNotationElementVisible(e.NotationElement.ScoreTitle)&&this.scoreInfoGlyphs.set(e.NotationElement.ScoreTitle,new zr(0,0,s.title,i.titleFont,L.Center)),s.subTitle&&t.isNotationElementVisible(e.NotationElement.ScoreSubTitle)&&this.scoreInfoGlyphs.set(e.NotationElement.ScoreSubTitle,new zr(0,0,s.subTitle,i.subTitleFont,L.Center)),s.artist&&t.isNotationElementVisible(e.NotationElement.ScoreArtist)&&this.scoreInfoGlyphs.set(e.NotationElement.ScoreArtist,new zr(0,0,s.artist,i.subTitleFont,L.Center)),s.album&&t.isNotationElementVisible(e.NotationElement.ScoreAlbum)&&this.scoreInfoGlyphs.set(e.NotationElement.ScoreAlbum,new zr(0,0,s.album,i.subTitleFont,L.Center)),s.music&&s.music===s.words&&t.isNotationElementVisible(e.NotationElement.ScoreWordsAndMusic)?this.scoreInfoGlyphs.set(e.NotationElement.ScoreWordsAndMusic,new zr(0,0,"Music and Words by "+s.words,i.wordsFont,L.Center)):(s.music&&t.isNotationElementVisible(e.NotationElement.ScoreMusic)&&this.scoreInfoGlyphs.set(e.NotationElement.ScoreMusic,new zr(0,0,"Music by "+s.music,i.wordsFont,L.Right)),s.words&&t.isNotationElementVisible(e.NotationElement.ScoreWords)&&this.scoreInfoGlyphs.set(e.NotationElement.ScoreWords,new zr(0,0,"Words by "+s.words,i.wordsFont,L.Left)));const a=new an(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);for(const[e,t]of this.scoreInfoGlyphs)t.renderer=a,t.doLayout();if(t.isNotationElementVisible(e.NotationElement.GuitarTuning)){let e=[];for(let t of this.renderer.tracks)for(let i of t.staves){let a=!i.isPercussion&&i.isStringed&&i.tuning.length>0&&i.showTablature;if(s.stylesheet.perTrackDisplayTuning&&s.stylesheet.perTrackDisplayTuning.has(t.index)&&!1===s.stylesheet.perTrackDisplayTuning.get(t.index)&&(a=!1),a){e.push(i);break}}if(e.length>0&&s.stylesheet.globalDisplayTuning){this.tuningGlyph=new en(0,0),this.tuningGlyph.renderer=a;for(const t of e)this.tuningGlyph.addTuning(t.stringTuning,e.length>1?t.track.name:"")}}if(t.isNotationElementVisible(e.NotationElement.ChordDiagrams)){this.chordDiagrams=new Wr(0,0),this.chordDiagrams.renderer=a;let e=new Set;for(let t of this.renderer.tracks){if(s.stylesheet.globalDisplayChordDiagramsOnTop&&(null==s.stylesheet.perTrackChordDiagramsOnTop||!s.stylesheet.perTrackChordDiagramsOnTop.has(t.index)||s.stylesheet.perTrackChordDiagramsOnTop.get(t.index)))for(let s of t.staves){const t=s.chords;if(t)for(const[,s]of t)e.has(s.uniqueId)||s.showDiagram&&(e.add(s.uniqueId),this.chordDiagrams.addChord(s))}}}}createEmptyStaffSystem(){let e=new $r(this);for(let t=0;t<this.renderer.tracks.length;t++){let s=this.renderer.tracks[t];for(let i=0;i<s.staves.length;i++){let a=s.staves[i],r=xl.staveProfiles.get(this.renderer.settings.display.staveProfile);for(let i of r)i.canCreate(s,a)&&e.addStaff(s,new Ur(t,a,i))}}return e}registerBarRenderer(e,t){this._barRendererLookup.has(e)||this._barRendererLookup.set(e,new Map),this._barRendererLookup.get(e).set(t.bar.id,t)}unregisterBarRenderer(e,t){if(this._barRendererLookup.has(e)){this._barRendererLookup.get(e).delete(t.bar.id)}}getRendererForBar(e,t){let s=t.id;return this._barRendererLookup.has(e)&&this._barRendererLookup.get(e).has(s)?this._barRendererLookup.get(e).get(s):null}layoutAndRenderAnnotation(e){let t="rendered by alphaTab",s=this.renderer.settings.display.resources,i=Math.floor(12);const a=new xa,r=nt.withFamilyList(s.copyrightFont.families,12,Ye.Plain,qe.Bold);this.renderer.canvas.font=r;const n=xl.getLayoutEngineFactory(this.renderer.settings.display.layoutMode).vertical;return a.width=this.renderer.canvas.measureText(t).width/this.renderer.settings.display.scale,a.height=i,a.x=n?(this.scaledWidth-a.width)/2:this.firstBarX,a.y=e,a.totalWidth=this.scaledWidth,a.totalHeight=e+i,a.firstMasterBarIndex=-1,a.lastMasterBarIndex=-1,this.registerPartial(a,(e=>{e.color=s.mainGlyphColor,e.font=r,e.textAlign=L.Left,e.textBaseline=M.Top,e.fillText(t,0,0)})),e+i}}!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"}(Xs||(Xs={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Js||(Js={}));class an{get nextRenderer(){return this.bar&&this.bar.nextBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.nextBar):null}get previousRenderer(){return this.bar&&this.bar.previousBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.previousBar):null}constructor(e,t){this._preBeatGlyphs=new Pr,this._voiceContainers=new Map,this._postBeatGlyphs=new Pr,this._ties=[],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 Or(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){let 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(){let 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;let 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);let 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==Us.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 Pr,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new Pr,this._postBeatGlyphs.renderer=this;for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];if(this.hasVoiceContainer(t)){let s=new Cr(0,0,t);s.renderer=this,this._voiceContainers.set(this.bar.voices[e].index,s)}}this.bar.simileMark===h.SecondOfDouble&&(this.canWrap=!1),this.createPreBeatGlyphs(),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!e.isEmpty||0===e.index}updateSizes(){this.staff.registerStaffTop(this.topPadding),this.staff.registerStaffBottom(this.height-this.bottomPadding);let e=this._voiceContainers,t=this.beatGlyphsStart,s=t;for(const i of e.values()){i.x=t,i.doLayout();let 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())s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,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){let i=new va;i.bar=this.bar,i.visualBounds=new cs,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 cs,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){let 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=zs.PreNotes){let s=this.getBeatContainer(e);if(s)switch(t){case zs.PreNotes:return s.voiceContainer.x+s.x;case zs.OnNotes:return s.voiceContainer.x+s.x+s.onNotes.x;case zs.MiddleNotes:return s.voiceContainer.x+s.x+s.onTimeX;case zs.Stem:const t=s.onNotes.beamingHelper?s.onNotes.beamingHelper.getBeatLineX(e):s.onNotes.x+s.onNotes.width/2;return s.voiceContainer.x+t;case zs.PostNotes:return s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.width;case zs.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],zs.OnNotes);return t+(this.postBeatGlyphsStart-t)*e}getNoteX(e,t){let s=this.getBeatContainer(e.beat);return s?s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.getNoteX(e,t):0}getNoteY(e,t){let s=this.getOnNotesGlyphForBeat(e.beat);return s?s.getNoteY(e,t):NaN}reLayout(){(this._wasFirstOfLine&&!this.isFirstOfLine||!this._wasFirstOfLine&&this.isFirstOfLine)&&this.recreatePreBeatGlyphs(),this.updateSizes(),this.registerLayoutingInfo()}recreatePreBeatGlyphs(){this._preBeatGlyphs=new Pr,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()}paintSimileMark(e,t,s){switch(this.bar.simileMark){case h.Simple:s.fillMusicFontSymbol(e+this.x+(this.width-20)/2,t+this.y+this.height/2,1,D.Repeat1Bar,!1);break;case h.SecondOfDouble:s.fillMusicFontSymbol(e+this.x-14,t+this.y+this.height/2,1,D.Repeat2Bars,!1)}}completeBeamingHelper(e){}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}}an.RawLineSpacing=8,an.StemWidth=.12*an.RawLineSpacing,an.StaffLineThickness=.13*an.RawLineSpacing,an.BeamThickness=.5*an.RawLineSpacing,an.BeamSpacing=.25*an.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"}(Ys||(Ys={}));class rn extends Ka{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 Ys.SingleOnBeatToEnd:case Ys.GroupedOnBeatToEnd:this.lastBeat.nextBeat&&(this.lastBeat=this.lastBeat.nextBeat)}let 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 Ys.FullBar:case Ys.SinglePreBeat:case Ys.SingleOnBeat:case Ys.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 Ys.GroupedOnBeat:case Ys.GroupedOnBeatToEnd:let i=e===Ys.GroupedOnBeat?Ys.SingleOnBeat:Ys.SingleOnBeatToEnd;if(t.index>0||this.renderer.index>0){let 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){let t=this.renderer.previousRenderer.getBand(e.voice,this.info.effectId);if(t){let i=t._effectGlyphs[e.voice.index];i.has(e.index)&&(s=i.get(e.index))}}let 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(Ys.SingleOnBeat,t)}}paint(e,t,s){super.paint(e,t,s);for(let i=0,a=this._uniqueEffectGlyphs.length;i<a;i++){let a=this._uniqueEffectGlyphs[i];for(let i=0,r=a.length;i<r;i++){a[i].paint(e+this.x,t+this.y,s)}}}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){let s=this._effectGlyphs[t.voice.index].get(t.index),i=this.renderer.getBeatContainer(t);switch(e){case Ys.SinglePreBeat:const e=this.renderer.layoutingInfo.getPreBeatSize(t);s.x=this.renderer.beatGlyphsStart+i.x-e;break;case Ys.SingleOnBeat:case Ys.GroupedOnBeat:s.x=this.renderer.beatGlyphsStart+i.x;break;case Ys.SingleOnBeatToEnd:case Ys.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 Ys.FullBar:s.width=this.renderer.width}}}class nn{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class on{constructor(){this.bands=[],this.shared=new nn}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 hn{constructor(){this.slots=[],this._effectSlot=new Map}getOrCreateSlot(e){if(this._effectSlot.has(e.info.effectId)){let t=this._effectSlot.get(e.info.effectId);if(t.canBeUsed(e))return t}for(let t of this.slots)if(t.canBeUsed(e))return t;let t=new on;return this.slots.push(t),t}register(e){let t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class ln extends vr{constructor(){super(0,0),this.computedWidth=0}doLayout(){let e=0;if(this.glyphs)for(let t=0,s=this.glyphs.length;t<s;t++){let 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])}}class dn extends ln{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,s){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class cn extends an{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(let t of this.sizingInfo.slots){t.shared.y=e;for(let 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){let e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new hn;for(let e of this._bands)e.resetHeight(),e.alignGlyphs(),e.isEmpty||this.sizingInfo.register(e);return this.updateHeight(),e}scaleToWidth(e){super.scaleToWidth(e);for(let e of this._bands)e.alignGlyphs()}createBeatGlyphs(){this._bands=[],this._bandLookup=new Map;for(let e of this.bar.voices)if(this.hasVoiceContainer(e))for(let t of this._infos){let s=new rn(e,t);s.renderer=this,s.doLayout(),this._bands.push(s),this._bandLookup.set(e.index+"."+t.effectId,s)}for(let e of this.bar.voices)this.hasVoiceContainer(e)&&this.createVoiceGlyphs(e);for(let e of this._bands)e.isLinkedToPrevious&&(this.isLinkedToPrevious=!0)}createVoiceGlyphs(e){for(let t of e.beats){let s=new tr(t,this.getVoiceContainer(e));s.preNotes=new ln,s.onNotes=new dn,this.addBeatGlyph(s);for(let e of this._bands)e.createGlyph(t)}}paint(e,t,s){this.paintBackground(e,t,s);for(let 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){let s=e.index+"."+t;return this._bandLookup.has(s)?this._bandLookup.get(s):null}}class un extends xr{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 cn(e,t,this.infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class pn extends Qa{constructor(e,t,s){super(e,t),this._endingsString="",this._endings=de.getAlternateEndingsList(s)}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(pn.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){super.paint(e,t,s);let i=s.textBaseline;if(s.textBaseline=M.Top,this._endings.length>0){let i=this.renderer.resources;s.font=i.wordsFont,s.moveTo(e+this.x,t+this.y+this.height),s.lineTo(e+this.x,t+this.y),s.lineTo(e+this.x+this.width,t+this.y),s.stroke(),s.fillText(this._endingsString,e+this.x+pn.Padding,t+this.y)}s.textBaseline=i}}pn.Padding=3;class gn{get effectId(){return this.notationElement.toString()}}class mn extends gn{get notationElement(){return e.NotationElement.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Ys.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){return new pn(0,0,t.voice.bar.masterBar.alternateEndings)}canExpand(e,t){return!0}}class fn extends gn{get notationElement(){return e.NotationElement.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ys.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new zr(0,0,"Capo. fret "+t.voice.bar.staff.capo,e.resources.effectFont,L.Left)}canExpand(e,t){return!1}}class yn extends gn{get notationElement(){return e.NotationElement.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ys.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new zr(0,0,t.chord.name,e.resources.effectFont,L.Center)}canExpand(e,t){return!1}}class bn extends Qa{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;let 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){let i=e-this.renderer.x,a=this.calculateEndX(this.renderer,this.beat,i,this.endPosition);this.paintGrouped(e,t,a,s)}}class Sn extends bn{constructor(e,t,s){super(zs.EndBeat),this._crescendo=p.None,this._crescendo=s,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17}paintGrouped(e,t,s,i){let a=e+this.x,r=this.height;i.beginPath(),this._crescendo===p.Crescendo?(s-=Sn.Padding,i.moveTo(s,t+this.y),i.lineTo(a,t+this.y+r/2),i.lineTo(s,t+this.y+r)):(s-=Sn.Padding,i.moveTo(a,t+this.y),i.lineTo(s,t+this.y+r/2),i.lineTo(a,t+this.y+r)),i.stroke()}}Sn.Padding=Za.QuarterNoteHeadWidth/2|0;class _n extends gn{get notationElement(){return e.NotationElement.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ys.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==p.None}createNewGlyph(e,t){return new Sn(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class wn extends $a{constructor(e,t,s){super(e,t,.6,wn.getSymbol(s))}doLayout(){super.doLayout(),this.height=17,this.y+=this.height/2}static getSymbol(e){switch(e){case m.PPP:return D.DynamicPPP;case m.PP:return D.DynamicPP;case m.P:return D.DynamicPiano;case m.MP:return D.DynamicMP;case m.MF:return D.DynamicMF;case m.F:return D.DynamicForte;case m.FF:return D.DynamicFF;case m.FFF:return D.DynamicFFF;default:return D.None}}}class Bn extends gn{get notationElement(){return e.NotationElement.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ys.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||e.graceType!==f.None)return!1;let t=this.getPreviousDynamicsBeat(e),s=0===e.voice.index&&!t||e.dynamics!==t?.dynamics;if(s&&e.voice.index>0)for(let t of e.voice.bar.voices)if(t.index<e.voice.index){let 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&&t.graceType===f.None)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new wn(0,0,t.dynamics)}canExpand(e,t){return!0}}class Tn extends $a{constructor(e){super(0,0,1,Tn.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case O.FadeIn:return D.GuitarFadeIn;case O.FadeOut:return D.GuitarFadeOut;case O.VolumeSwell:return D.GuitarVolumeSwell}return D.None}doLayout(){this.width=13,this.symbol==D.GuitarVolumeSwell&&(this.width*=2),this.height=13}paint(e,t,s){super.paint(e,t+this.height,s)}}class kn extends gn{get notationElement(){return e.NotationElement.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ys.SingleOnBeat}shouldCreateGlyph(e,t){return t.fade!=O.None}createNewGlyph(e,t){return new Tn(t.fade)}canExpand(e,t){return!0}}class Nn extends $a{constructor(e,t,s){super(e,t,1,Nn.getSymbol(s))}static getSymbol(e){switch(e){case Ge.Short:return D.FermataShortAbove;case Ge.Medium:return D.FermataAbove;case Ge.Long:return D.FermataLongAbove;default:return D.None}}doLayout(){this.width=23,this.height=12}paint(e,t,s){super.paint(e-this.width/2,t+this.height,s)}}class xn extends gn{get notationElement(){return e.NotationElement.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ys.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new Nn(0,0,t.fermata.type)}canExpand(e,t){return!0}}class vn extends gn{get notationElement(){return e.NotationElement.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ys.SingleOnBeat}shouldCreateGlyph(t,s){return!(0!==s.voice.index||s.isRest||t.notation.fingeringMode!==e.FingeringMode.SingleNoteEffectBand&&t.notation.fingeringMode!==e.FingeringMode.SingleNoteEffectBandForcePiano)&&(1===s.notes.length&&s.notes[0].isFingering)}createNewGlyph(e,t){let s=y.Unknown,i=!1,a=t.notes[0];a.leftHandFinger!==y.Unknown?(s=a.leftHandFinger,i=!0):a.rightHandFinger!==y.Unknown&&(s=a.rightHandFinger);let r=de.fingerToString(e.settings,t,s,i)??"";return new zr(0,0,r,e.resources.fingeringFont,L.Left)}canExpand(e,t){return!0}}class Pn extends gn{constructor(){super(...arguments),this.lastCreateInfo=null}shouldCreateGlyph(e,t){this.lastCreateInfo=[];for(let e=0,s=t.notes.length;e<s;e++){let 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 Cn extends bn{constructor(e,t=!0){super(zs.OnNotes),this._label=e,this._dashed=t}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=zs.EndBeat,this.forceGroupedRendering=!0),super.doLayout(),this.height=this.renderer.resources.effectFont.size}paintNonGrouped(e,t,s){let i=this.renderer.resources;s.font=i.effectFont;let a=s.textAlign;s.textAlign=L.Center,s.fillText(this._label,e+this.x,t+this.y),s.textAlign=a}paintGrouped(e,t,s,i){this.paintNonGrouped(e,t,i);let 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()}}Cn.LineSpacing=3,Cn.LineTopPadding=4,Cn.LineTopOffset=5,Cn.LineSize=8;class En extends Pn{get effectId(){return this._effectId}get notationElement(){return e.NotationElement.EffectHarmonics}constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case b.None:this._effectId="harmonics-none";break;case b.Natural:this._effectId="harmonics-natural";break;case b.Artificial:this._effectId="harmonics-artificial";break;case b.Pinch:this._effectId="harmonics-pinch";break;case b.Tap:this._effectId="harmonics-tap";break;case b.Semi:this._effectId="harmonics-semi";break;case b.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 Ys.GroupedOnBeat}createNewGlyph(e,t){return new Cn(En.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case b.Natural:return"N.H.";case b.Artificial:return"A.H.";case b.Pinch:return"P.H.";case b.Tap:return"T.H.";case b.Semi:return"S.H.";case b.Feedback:return"Fdbk."}return""}}class Fn extends gn{get notationElement(){return e.NotationElement.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return Ys.GroupedOnBeat}createNewGlyph(e,t){return new Cn("LetRing")}canExpand(e,t){return!0}}class Dn extends Qa{constructor(e,t,s,i,a=L.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;let 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 Ln extends gn{get notationElement(){return e.NotationElement.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ys.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new Dn(0,0,t.lyrics,e.resources.effectFont,L.Center)}canExpand(e,t){return!0}}class Mn extends gn{get notationElement(){return e.NotationElement.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return Ys.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 zr(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,L.Left)}canExpand(e,t){return!0}}class In extends bn{constructor(e,t){super(zs.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=13}paintNonGrouped(e,t,s){this.paintOttava(e,t,s)}paintOttava(e,t,s){let i=0;switch(this._ottava){case o._15ma:i=37,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,D.QuindicesimaAlta,!1);break;case o._8va:i=26,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,D.OttavaAlta,!1);break;case o._8vb:i=23,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,D.OttavaBassaVb,!1);break;case o._15mb:i=36,s.fillMusicFontSymbols(e+this.x-i/2,t+this.y+this.height,.8,[D.Quindicesima,D.OctaveBaselineM,D.OctaveBaselineB],!1)}return i/2}paintGrouped(e,t,s,i){let a=this.paintOttava(e,t,i),r=e+this.x+a+3,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 An extends gn{get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return e.NotationElement.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ys.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 In(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class Rn extends Pn{get notationElement(){return e.NotationElement.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return Ys.GroupedOnBeat}createNewGlyph(e,t){return new Cn("P.M.")}constructor(){super()}}class On extends Pn{get notationElement(){return e.NotationElement.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===w.PickSlideDown||e.slideOutType===w.PickSlideUp}get sizingMode(){return Ys.GroupedOnBeat}createNewGlyph(e,t){return new Cn("P.S.")}constructor(){super()}}class Vn extends $a{constructor(e,t,s){super(e,t,Za.GraceScale,Vn.getSymbol(s))}doLayout(){this.width=9,this.height=13}paint(e,t,s){super.paint(e,t+this.height,s)}static getSymbol(e){switch(e){case F.Up:return D.StringsUpBow;case F.Down:return D.StringsDownBow;default:return D.None}}}class Hn extends gn{get notationElement(){return e.NotationElement.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ys.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==F.None}createNewGlyph(e,t){return new Vn(0,0,t.pickStroke)}canExpand(e,t){return!0}}class Gn extends bn{constructor(e){super(zs.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case B.Slight:this._stepSize=12;break;case B.Wide:this._stepSize=23}this.height=18}paintGrouped(e,t,s,i){let a=e+this.x,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 Wn extends gn{get notationElement(){return e.NotationElement.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ys.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===B.Slight}createNewGlyph(e,t){return new Gn(B.Slight)}canExpand(e,t){return!0}}class zn extends bn{constructor(e,t,s,i=1.2,a=!1){super(zs.EndBeat),this._scale=0,this._symbol=D.None,this._symbolSize=0,this._type=s,this._scale=i,this.x=e,this.y=t,this._partialWaves=a}doLayout(){super.doLayout();let e=0;switch(this._type){case B.Slight:this._symbol=D.WiggleTrill,this._symbolSize=9*this._scale,e=6*this._scale;break;case B.Wide:this._symbol=D.WiggleVibratoMediumFast,this._symbolSize=10*this._scale,e=10*this._scale}this.height=e}paintGrouped(e,t,s,i){let a=s-(e+this.x),r=this._symbolSize,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 Un extends Pn{get notationElement(){return e.NotationElement.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){let t=e.vibrato===B.Slight||e.isTieDestination&&e.tieOrigin.vibrato===B.Slight;return this._hideOnTiedBend&&t&&e.isTieDestination&&e.tieOrigin.hasBend&&(t=!1),t}get sizingMode(){return Ys.GroupedOnBeatToEnd}createNewGlyph(e,t){return new zn(0,0,B.Slight,1.2)}constructor(e){super(),this._hideOnTiedBend=e}}class Xn extends gn{get notationElement(){return e.NotationElement.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ys.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){let s=e.resources;return t.slap?new zr(0,0,"S",s.effectFont,L.Left):t.pop?new zr(0,0,"P",s.effectFont,L.Left):new zr(0,0,"T",s.effectFont,L.Left)}canExpand(e,t){return!0}}var Jn,Yn,qn=Object.freeze({__proto__:null,CssFontSvgCanvas:Nr,Cursors:yr,FontSizes:Na,SvgCanvas:kr,get TextAlign(){return L},get TextBaseline(){return M}});class jn extends Qa{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=M.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,D.NoteQuarterUp,!0),s.fillText("= "+i.value.toString(),a+8,t+this.y+s.font.size/2)}}}class Kn extends gn{get notationElement(){return e.NotationElement.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Ys.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 jn(t.voice.bar.masterBar.tempoAutomations)}canExpand(e,t){return!0}}class Qn extends gn{get notationElement(){return e.NotationElement.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ys.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new zr(0,0,t.text,e.resources.effectFont,L.Left)}canExpand(e,t){return!0}}class $n extends Qa{constructor(e,t){super(e,t)}doLayout(){super.doLayout(),this.height=this.renderer.resources.markerFont.size}paint(e,t,s){let i=this.renderer.resources;s.font=i.markerFont;let a=s.measureText("tr").width;s.fillText("tr",e+this.x,t+this.y);let r=a+3,n=this.width-r,o=Math.max(1,(n-r)/13.2),h=r,l=t+this.y+1.2*this.height;for(let t=0;t<o;t++)s.fillMusicFontSymbol(e+this.x+h,l,1.2,D.WiggleTrill,!1),h+=13.2}}class Zn extends Pn{get notationElement(){return e.NotationElement.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return Ys.SingleOnBeat}createNewGlyph(e,t){return new $n(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(Jn||(Jn={}));class eo extends Qa{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25}paint(e,t,s){e+=this.x;let i=(t+=this.y)+this.height*Za.GraceScale,a=i+8;s.font=this.renderer.resources.effectFont,s.fillText("(",e,t+.3*this.height);let r=e+10,n=e+40,o=[],h=[],l=[],d=[];switch(this._tripletFeel){case E.NoTripletFeel:o=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac8thLongStem],l=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac8thLongStem];break;case E.Triplet8th:o=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac8thLongStem],l=[D.TextBlackNoteLongStem,D.Space,D.NoteEighthUp],d=[D.TextTupletBracketStartLongStem,D.TextTuplet3LongStem,D.TextTupletBracketEndLongStem];break;case E.Triplet16th:o=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac8thLongStem],l=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac16thLongStem],d=[D.TextTupletBracketStartLongStem,D.TextTuplet3LongStem,D.TextTupletBracketEndLongStem];break;case E.Dotted8th:o=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac8thLongStem],h=[D.TextAugmentationDot],l=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac16thLongStem];break;case E.Dotted16th:o=[D.TextBlackNoteLongStem,D.TextCont16thBeamLongStem,D.TextBlackNoteFrac16thLongStem],h=[D.TextAugmentationDot],l=[D.TextBlackNoteLongStem,D.TextCont16thBeamLongStem,D.TextBlackNoteFrac32ndLongStem],s.fillCircle(n+9,i,1);break;case E.Scottish8th:o=[D.TextBlackNoteLongStem,D.TextCont8thBeamLongStem,D.TextBlackNoteFrac8thLongStem],l=[D.TextBlackNoteLongStem,D.TextCont16thBeamLongStem,D.TextBlackNoteFrac8thLongStem,D.TextAugmentationDot];break;case E.Scottish16th:o=[D.TextBlackNoteLongStem,D.TextCont16thBeamLongStem,D.TextBlackNoteFrac16thLongStem],l=[D.TextBlackNoteLongStem,D.TextCont32ndBeamLongStem,D.TextBlackNoteFrac16thLongStem,D.TextAugmentationDot]}s.fillMusicFontSymbols(r,i,eo.NoteScale,o,!1),s.fillText("=",e+32,t+5),s.fillMusicFontSymbols(n,i,eo.NoteScale,l,!1),h.length>0&&s.fillMusicFontSymbols(n+7,i,eo.NoteScale,h,!1),d.length>0&&s.fillMusicFontSymbols(n,a,eo.TupletScale,d,!1),s.fillText(")",e+65,t+.3*this.height)}}eo.NoteScale=.5,eo.TupletScale=.7;class to extends gn{get notationElement(){return e.NotationElement.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Ys.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==E.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new eo(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class so extends gn{get notationElement(){return e.NotationElement.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ys.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new Cn("w/bar")}canExpand(e,t){return!0}}class io extends gn{get notationElement(){return e.NotationElement.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ys.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===B.Wide}createNewGlyph(e,t){return new Gn(B.Wide)}canExpand(e,t){return!0}}class ao extends Pn{get notationElement(){return e.NotationElement.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===B.Wide||e.isTieDestination&&e.tieOrigin.vibrato===B.Wide}get sizingMode(){return Ys.GroupedOnBeatToEnd}createNewGlyph(e,t){return new zn(0,0,B.Wide,1.2)}}class ro{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class no extends sn{get name(){return"HorizontalScreen"}constructor(e){super(e),this._system=null,this._pagePadding=null}get supportsResize(){return!1}get firstBarX(){let e=this._pagePadding[0];return this._system&&(e+=this._system.accoladeWidth),e}doResize(){}doLayoutAndRender(){switch(this._pagePadding=this.renderer.settings.display.padding,this.renderer.settings.display.systemsLayoutMode){case e.SystemsLayoutMode.Automatic:this.systemsLayoutMode=Us.Automatic;break;case e.SystemsLayoutMode.UseModelLayout:this.systemsLayoutMode=Us.FromModelWithWidths}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]]);let t=this.renderer.score,s=this.renderer.settings.display.startBar;s--,s=Math.min(t.masterBars.length-1,Math.max(0,s));let i=s,a=this.renderer.settings.display.barCount;a<=0&&(a=t.masterBars.length),a=s+a-1,a=Math.min(t.masterBars.length-1,Math.max(0,a)),this._system=this.createEmptyStaffSystem(),this._system.isLast=!0,this._system.x=this._pagePadding[0],this._system.y=this._pagePadding[1];let r=this.renderer.settings.display.barCountPerPartial,n=[],o=new ro,h=0;for(;i<=a;){let e=this._system.addBars(this.renderer.tracks,i);if(e)if(0===o.masterBars.length&&e.isLinkedToPrevious&&n.length>0){let s=n[n.length-1];s.masterBars.push(t.masterBars[i]),s.width+=e.width,h+=e.width,o.x+=h}else o.masterBars.push(t.masterBars[i]),o.width+=e.width,o.masterBars.length>=r&&(0===n.length&&(o.width+=this._system.accoladeWidth+this._pagePadding[0]),h+=o.width,n.push(o),ne.debug(this.name,"Finished partial from bar "+o.masterBars[0].index+" to "+o.masterBars[o.masterBars.length-1].index,null),o=new ro,o.x=h);i++}o.masterBars.length>0&&(0===n.length&&(o.width+=this._system.accoladeWidth+this._pagePadding[0]),n.push(o),ne.debug(this.name,"Finished partial from bar "+o.masterBars[0].index+" to "+o.masterBars[o.masterBars.length-1].index,null)),this.finalizeStaffSystem();const l=this.renderer.settings.display.scale;this.height=Math.floor(this._system.y+this._system.height)*l,this.width=(this._system.x+this._system.width+this._pagePadding[2])*l,i=0;let d=0;for(let e=0;e<n.length;e++){const t=n[e],s=new xa;s.x=d,s.y=0,s.totalWidth=this.width/l,s.totalHeight=this.height/l,s.width=t.width,s.height=this.height/l,s.firstMasterBarIndex=t.masterBars[0].index,s.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,d+=t.width;const a=i,r=e;this._system.buildBoundingsLookup(0,0),this.registerPartial(s,(e=>{let s=this._system.getBarX(t.masterBars[0].index)+this._system.accoladeWidth;0===r&&(s-=this._system.x+this._system.accoladeWidth),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=L.Left,ne.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)})),i+=t.masterBars.length}this.height=this.layoutAndRenderAnnotation(this.height)+this._pagePadding[3]}finalizeStaffSystem(){this._system.scaleToWidth(this._system.width),this._system.finalizeSystem()}}class oo extends sn{get name(){return"PageView"}constructor(e){super(e),this._systems=[],this._allMasterBarRenderers=[],this._barsFromPreviousSystem=[],this._pagePadding=null}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case e.SystemsLayoutMode.Automatic:this.systemsLayoutMode=Us.Automatic;break;case e.SystemsLayoutMode.UseModelLayout:this.systemsLayoutMode=Us.FromModelWithScale}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]]);let t=this._pagePadding[1];this.width=this.renderer.width,this._allMasterBarRenderers=[],t=this.layoutAndRenderScoreInfo(t,-1),t=this.layoutAndRenderTunings(t,-1),t=this.layoutAndRenderChordDiagrams(t,-1),t=this.layoutAndRenderScore(t),t=this.layoutAndRenderAnnotation(t),this.height=(t+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;let 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.layoutAndRenderAnnotation(e),this.height=(e+this._pagePadding[3])*this.renderer.settings.display.scale}layoutAndRenderTunings(e,t=-1){if(!this.tuningGlyph)return e;let s=this.renderer.settings.display.resources;this.tuningGlyph.x=this._pagePadding[0],this.tuningGlyph.width=this.scaledWidth,this.tuningGlyph.doLayout();let i=this.tuningGlyph.height;const a=new xa;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=L.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.floor(this.chordDiagrams.height),a=new xa;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=L.Center,this.chordDiagrams.paint(0,0,e)})),e+i}layoutAndRenderScoreInfo(t,s=-1){ne.debug(this.name,"Layouting score info");const i=new xa;i.x=0,i.y=t;let a=0,r=this.renderer.settings.display.resources,n=[e.NotationElement.ScoreTitle,e.NotationElement.ScoreSubTitle,e.NotationElement.ScoreArtist,e.NotationElement.ScoreAlbum,e.NotationElement.ScoreWordsAndMusic];for(let e=0;e<n.length;e++)if(this.scoreInfoGlyphs.has(n[e])){let t=this.scoreInfoGlyphs.get(n[e]);t.x=this.scaledWidth/2,t.y=a,t.textAlign=L.Center,a+=t.font.size}let o=!1,h=0;if(this.scoreInfoGlyphs.has(e.NotationElement.ScoreMusic)){let t=this.scoreInfoGlyphs.get(e.NotationElement.ScoreMusic);t.x=this.scaledWidth-this._pagePadding[2],t.y=a,t.textAlign=L.Right,o=!0,h=t.font.size}if(this.scoreInfoGlyphs.has(e.NotationElement.ScoreWords)){let t=this.scoreInfoGlyphs.get(e.NotationElement.ScoreWords);t.x=this._pagePadding[0],t.y=a,t.textAlign=L.Left,o=!0,h=t.font.size}return o&&(a+=h),this.scoreInfoGlyphs.size>0&&(a=Math.floor(a+17),i.width=this.scaledWidth,i.height=a,i.totalWidth=this.scaledWidth,i.totalHeight=s<0?t+i.height:s,this.registerPartial(i,(e=>{e.color=r.scoreInfoColor,e.textAlign=L.Center;for(const t of this.scoreInfoGlyphs.values())t.paint(0,0,e)}))),t+a}resizeAndRenderScore(e,t){if(this.renderer.settings.display.barsPerRow>0||this.systemsLayoutMode==Us.FromModelWithScale)for(let s=0;s<this._systems.length;s++){let i=this._systems[s];this.fitSystem(i),e+=this.paintSystem(i,t)}else{this._systems=[];let s=0,i=this.maxWidth,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,s=this.lastBarIndex;for(this._systems=[];t<=s;){let i=this.createStaffSystem(t,s);this._systems.push(i),i.x=this._pagePadding[0],i.y=e,t=i.lastBarIndex+1,this.fitSystem(i),ne.debug(this.name,"Rendering partial from bar "+i.firstBarIndex+" to "+i.lastBarIndex,null),e+=this.paintSystem(i,e)}return e}paintSystem(e,t){let s=Math.floor(e.height);const i=new xa;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=L.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==Us.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){let s=this.createEmptyStaffSystem();s.index=this._systems.length;let i=this.getBarsPerSystem(s.index),a=this.maxWidth,r=t+1,n=e;for(;n<r;){if(this._barsFromPreviousSystem.length>0)for(let e of this._barsFromPreviousSystem)s.addMasterBarRenderers(this.renderer.tracks,e),n=e.masterBar.index;else{let e=s.addBars(this.renderer.tracks,n);e&&this._allMasterBarRenderers.push(e)}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}s.x=0,n++}return s.isLast=t===s.lastBarIndex,s}get maxWidth(){return this.scaledWidth-this._pagePadding[0]-this._pagePadding[2]}}class ho extends $a{constructor(e,t,s,i){super(e,t,i,ho.getMusicSymbol(s)),this._accidentalType=s}static getMusicSymbol(e){switch(e){case Je.Natural:return D.AccidentalNatural;case Je.Sharp:return D.AccidentalSharp;case Je.Flat:return D.AccidentalFlat;case Je.NaturalQuarterNoteUp:return D.AccidentalQuarterToneNaturalArrowUp;case Je.SharpQuarterNoteUp:return D.AccidentalQuarterToneSharpArrowUp;case Je.FlatQuarterNoteUp:return D.AccidentalQuarterToneFlatArrowUp;case Je.DoubleSharp:return D.AccidentalDoubleSharp;case Je.DoubleFlat:return D.AccidentalDoubleFlat}return D.None}doLayout(){if(this._accidentalType===Je.DoubleFlat)this.width=18;else this.width=8;this.width=this.width*this.glyphScale}}class lo extends $a{constructor(e,t,s,i){super(e,t,1,lo.getSymbol(s)),this._clef=s,this._clefOttava=i}doLayout(){switch(this._clef){case n.Neutral:this.width=15;break;case n.C3:case n.C4:case n.F4:case n.G2:this.width=28}}static getSymbol(e){switch(e){case n.Neutral:return D.UnpitchedPercussionClef1;case n.C3:case n.C4:return D.CClef;case n.F4:return D.FClef;case n.G2:return D.GClef;default:return D.None}}paint(e,t,s){let i;super.paint(e,t,s);let a=!1;switch(this._clefOttava){case o._15ma:i=new $a(-4,0,.5,D.Quindicesima),a=!0;break;case o._8va:i=new $a(-2,0,.5,D.Ottava),a=!0;break;case o._8vb:i=new $a(-6,0,.5,D.Ottava);break;case o._15mb:i=new $a(-8,0,.5,D.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();let l=this.width/2;i.paint(e+this.x+l+h,t+this.y+r,s)}}class co extends Qa{constructor(e,t,s){super(e,t),this._note=s}static getSymbol(e,t){switch(e){case a.None:return D.None;case a.Normal:return t?D.ArticAccentAbove:D.ArticAccentBelow;case a.Heavy:return t?D.ArticMarcatoAbove:D.ArticMarcatoBelow;case a.Tenuto:return t?D.ArticTenutoAbove:D.ArticTenutoBelow;default:return D.None}}doLayout(){this.width=9,this.height=9}paint(e,t,s){const i=this.renderer.getBeatDirection(this._note.beat),a=co.getSymbol(this._note.accentuated,i==We.Down),r=i==We.Up?t+this.y:t+this.y+this.height-2;s.fillMusicFontSymbol(e+this.x-2,r,1,a,!1)}}class uo extends Ka{constructor(e,t,s){super(e,t),this._size=0,this._size=s}doLayout(){this.width=this._size+3}paint(e,t,s){s.fillCircle(e+this.x,t+this.y,this._size)}}class po extends $a{constructor(e,t,s){super(e,t,s?Za.GraceScale:1,D.NoteheadXOrnate),this._isGrace=s}doLayout(){this.width=9*(this._isGrace?Za.GraceScale:1),this.height=Za.NoteHeadHeight}}class go extends $a{constructor(e,t,s,i){super(e,t,i?Za.GraceScale:1,go.getSymbol(s)),this._isGrace=i}static getSymbol(e){switch(e){case g.QuadrupleWhole:case g.DoubleWhole:case g.Whole:case g.Half:return D.NoteheadDiamondWhiteWide;default:return D.NoteheadDiamondBlackWide}}doLayout(){this.width=9*(this._isGrace?Za.GraceScale:1),this.height=Za.NoteHeadHeight}}class mo extends Ka{constructor(e,t,s){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=We.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);let e=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar);this.startNoteRenderer=e;let t=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.endBeat.voice.bar);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&&(this.y=Math.min(this._startY,this._endY),this.shouldDrawBendSlur()?this._tieHeight=0:(this._tieHeight=this.getTieHeight(this._startX,this._startY,this._endX,this._endY),this.height=mo.calculateActualTieHeight(1,this._startX,this._startY,this._endX,this._endY,this.tieDirection===We.Down,this._tieHeight,4).h),this.tieDirection===We.Up&&(this.y-=this.height))}paint(e,t,s){this._shouldDraw&&(this.shouldDrawBendSlur()?mo.drawBendSlur(s,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===We.Down,1):mo.paintTie(s,1,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===We.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,s,i){return 22}getBeamDirection(e,t){return We.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=mo.computeBezierControlPoints(e,t,s,i,a,r,n,o);t=h[0],s=h[1];const l=h[2],d=h[3];i=h[6],a=h[7];const c=(t-l)/(t-2*l+i),u=mo.calculateExtrema(t,s,l,d,i,a,c),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-d)/(s-2*d+a),f=mo.calculateExtrema(t,s,l,d,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 cs;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,d=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=d,l/=d;let c=(i+t)/2,u=(a+s)/2;return[t,s,c+n*h,u+n*l,c+(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=mo.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,d=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=d,l/=d;let c=(i+t)/2,u=(a+s)/2,p=mo.BendSlurHeight*n;i-t<20&&(p/=2);let g=c+p*h,m=u+p*l;if(e.beginPath(),e.moveTo(t,s),e.lineTo(g,m),e.lineTo(i,a),e.stroke(),o){let t=e.measureText(o).width,s=r?0:-e.font.size;e.fillText(o,g-t/2,m+s)}}}mo.BendSlurHeight=11;class fo extends Ka{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=fo.Size}paint(e,t,s){this._isOpen?mo.paintTie(s,1,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):mo.paintTie(s,1,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3)}}fo.Size=6;class yo{constructor(e,t){this.line=0,this.line=e,this.isGhost=t}}class bo extends Ka{constructor(e){super(0,0),this._infos=[],this._glyphs=[],this.isEmpty=!0,this._isOpen=e}addParenthesis(t){let s=this.renderer,i=s.getNoteLine(t),a=t.isGhost||this.isTiedBend(t)&&s.settings.notation.isNotationElementVisible(e.NotationElement.ParenthesisOnTiedBends);this.addParenthesisOnLine(i,a)}addParenthesisOnLine(e,t){let s=new yo(e,t);this._infos.push(s),t&&(this.isEmpty=!1)}isTiedBend(e){return!!e.isTieDestination&&(!!e.tieOrigin.hasBend||this.isTiedBend(e.tieOrigin))}doLayout(){let e=this.renderer;this._infos.sort(((e,t)=>e.line-t.line));let t=null,s=e.getScoreHeight(1);for(let i=0,a=this._infos.length;i<a;i++){let a;if(this._infos[i].isGhost)if(t){let a=e.getScoreY(this._infos[i].line)+s;t.height=a-t.y}else a=new fo(this._isOpen),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(let i of this._glyphs)i.paint(e+this.x,t+this.y,s)}}class So{constructor(e,t){this.line=0,this.glyph=e,this.line=t}}class _o extends Ka{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new ya,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){let s=new So(e,t);this._infos.push(s),(!this.minNote||this.minNote.line>s.line)&&(this.minNote=s),(!this.maxNote||this.maxNote.line<s.line)&&(this.maxNote=s)}get hasTopOverflow(){return!!this.minNote&&this.minNote.line<=0}get hasBottomOverflow(){return!!this.maxNote&&this.maxNote.line>8}doLayout(){this._infos.sort(((e,t)=>t.line-e.line));let e=0,t=!1,s=0,i=!1,a=this.direction,r=0;for(let n=0,o=this._infos.length;n<o;n++){let 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].line)<=1?t?t=!1:(h=!0,o.x=e,i=!0,t=!0):t=!1,a===We.Down?o.x=h?0:e:o.x=h?e:0,o.x+=this.noteStartX,s=this._infos[n].line,r=Math.max(r,o.x+o.width)}i?(this._noteHeadPadding=0,this.upLineX=e,this.downLineX=e):(this._noteHeadPadding=a===We.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;let i=this.renderer,a=this.width-this.noteStartX+6;if(this.hasTopOverflow){let r=s.color;s.color=i.resources.staffLineColor;let n=-2;for(;n>=this.minNote.line;){let r=t+i.getScoreY(n);s.fillRect(e-3+this.noteStartX,r,a,1),n-=2}s.color=r}if(this.hasBottomOverflow){let r=s.color;s.color=i.resources.staffLineColor;let n=10;for(;n<=this.maxNote.line;){let r=t+i.getScoreY(n);s.fillRect(e-3+this.noteStartX,r,a,1),n+=2}s.color=r}let r=this._infos,n=e+this._noteHeadPadding;for(let e of r)e.glyph.renderer=this.renderer,e.glyph.paint(n,t,s)}}class wo extends $a{constructor(e,t,s){super(e,t,1,wo.getSymbol(s))}doLayout(){this.width=12}static getSymbol(e){switch(e){case g.ThirtySecond:return D.Tremolo3;case g.Sixteenth:return D.Tremolo2;case g.Eighth:return D.Tremolo1;default:return D.None}}}class Bo extends Ka{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 To extends _o{constructor(){super(),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)){let s=this._noteGlyphLookup.get(e.id),i=this.x+s.x+this._noteHeadPadding;switch(t){case Js.Left:break;case Js.Center:i+=s.width/2;break;case Js.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 Xs.TopWithStem:i-=this.renderer.getStemSize(this.beamingHelper);break;case Xs.Top:i-=s.height/2;break;case Xs.Center:break;case Xs.Bottom:i+=s.height/2;break;case Xs.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();let e=this.renderer;this.beat.deadSlapped&&(this._deadSlapped=new Bo,this._deadSlapped.renderer=this.renderer,this._deadSlapped.doLayout(),this.width=this._deadSlapped.width);let t=this.direction,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===We.Up?(n=!1,o=!0,i=e.getScoreY(this.maxNote.line+2),s=e.getScoreY(this.minNote.line)-e.getStemSize(this.beamingHelper,!0)):(n=!0,o=!1,i=e.getScoreY(this.minNote.line-1),a*=-1,r*=-1,s=e.getScoreY(this.maxNote.line)+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,s=t===We.Up?this.minNote:this.maxNote,i=t===We.Up?this.displacedX:0,a=this.beat.tremoloSpeed;switch(a){case g.ThirtySecond:e=t===We.Up?-15:15;break;case g.Sixteenth:e=t===We.Up?-12:15;break;case g.Eighth:e=t===We.Up?-10:10;break;default:e=t===We.Up?-10:15}this.beat.duration<g.Half&&(i=this.width/2),this._tremoloPicking=new wo(i,s.glyph.y+e,a),this._tremoloPicking.renderer=this.renderer,this._tremoloPicking.doLayout()}}buildBoundingsLookup(e,t,s){for(let i of this._notes)if(this._noteGlyphLookup.has(i.id)){let a=this._noteGlyphLookup.get(i.id),r=new Ea;r.note=i,r.noteHeadBounds=new cs,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){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);super.paint(e,t,s),this._tremoloPicking&&this._tremoloPicking.paint(e,t,s),this._deadSlapped&&this._deadSlapped.paint(e,t,s)}}class ko extends $a{constructor(e,t,s){super(e,t,1,ko.getSymbol(s)),this._duration=s}static getSymbol(e){switch(e){case g.QuadrupleWhole:return D.RestLonga;case g.DoubleWhole:return D.RestDoubleWhole;case g.Whole:return D.RestWhole;case g.Half:return D.RestHalf;case g.Quarter:return D.RestQuarter;case g.Eighth:return D.RestEighth;case g.Sixteenth:return D.RestSixteenth;case g.ThirtySecond:return D.RestThirtySecond;case g.SixtyFourth:return D.RestSixtyFourth;case g.OneHundredTwentyEighth:return D.RestOneHundredTwentyEighth;case g.TwoHundredFiftySixth:return D.RestTwoHundredFiftySixth;default:return D.None}}static getSize(e){switch(e){case g.QuadrupleWhole:case g.DoubleWhole:case g.Whole:case g.Half:case g.Quarter:case g.Eighth:case g.Sixteenth:return 9;case g.ThirtySecond:return 12;case g.SixtyFourth:return 14;case g.OneHundredTwentyEighth:case g.TwoHundredFiftySixth:return 20}return 10}doLayout(){this.width=ko.getSize(this._duration)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class No{constructor(){this.x=0,this.y=-3e3,this.width=0}}class xo extends vr{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));let e=[];e.push(new No);for(let t=0,s=this.glyphs.length;t<s;t++){let 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 No);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++){let s=this.glyphs[t];const i=e[s.x];s.x=this.width-i.x}}}class vo extends _o{get direction(){return We.Up}constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new xo,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new bo(!0),this._postNoteParenthesis=new bo(!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=!1){let s=this.renderer,i=new Za(0,0,g.Quarter,!0),a=s.accidentalHelper.applyAccidentalForValue(this._beat,e,t,!0),r=s.accidentalHelper.getNoteLineForValue(e,!1);if(i.y=s.getScoreY(r),this._showParenthesis&&(this._preNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.addParenthesisOnLine(r,!0),this._postNoteParenthesis.addParenthesisOnLine(r,!0)),a!==Je.None){let e=new ho(0,i.y,a,Za.GraceScale);e.renderer=this.renderer,this._accidentals.renderer=this.renderer,this._accidentals.addGlyph(e)}this._noteValueLookup.set(e,i),this.add(i,r),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+vo.ElementPadding),this._accidentals.isEmpty||(e+=this._accidentals.width+vo.ElementPadding,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+vo.ElementPadding),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+vo.ElementPadding,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+vo.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)}}vo.ElementPadding=2;class Po extends Ka{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,s,i,a,r,n,o){mo.drawBendSlur(e,t,s,i,a,r,n,o)}doLayout(){super.doLayout(),this.width=0;for(let e of this.BendNoteHeads)e.doLayout(),this.width+=e.width+10}getTieDirection(e,t){return t.getBeatDirection(e)===We.Up?We.Down:We.Up}}Po.EndPadding=8;class Co extends se{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class Eo extends Ka{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);let 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 c.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 c.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 c.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 c.Prebend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s);break;case c.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 c.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();let e=this._maxBendValue*Eo.BendValueHeight;this.renderer.registerOverflowTop(e);let t=0;for(let e of this._notes){let s=this._renderPoints.get(e.id);switch(e.bendType){case c.Bend:s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case c.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t);break;case c.BendRelease:s[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[2].lineValue=t);break;case c.Prebend:s[0].lineValue=this._preBendMinValue;break;case c.PrebendBend:s[0].lineValue=this._preBendMinValue,s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case c.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){let t=[];switch(e.bendType){case c.Custom:for(let s of e.bendPoints)t.push(new Co(s.offset,s.value));break;case c.BendRelease:t.push(new Co(0,e.bendPoints[0].value)),t.push(new Co(se.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new Co(se.MaxPosition,e.bendPoints[3].value));break;case c.Bend:case c.Hold:case c.Prebend:case c.PrebendBend:case c.PrebendRelease:case c.Release:t.push(new Co(0,e.bendPoints[0].value)),t.push(new Co(se.MaxPosition,e.bendPoints[1].value))}return t}paint(e,t,s){let i=s.color;this._notes.length>1&&(s.color=this.renderer.resources.secondaryGlyphColor);for(let a of this._notes){let r=this._renderPoints.get(a.id),n=this.renderer,o=a,h=!1,l=null,u=!1,p=a.bendStyle===d.Gradual?"grad.":"",g=null;for(;o.isTieOrigin;){let e=o.tieDestination;if(l=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,e.beat.voice.bar),!l||n.staff!==l.staff)break;if(o=e,h=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes||o.vibrato!=B.None){u=!0;break}}g=o.beat,l=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,g.voice.bar),g.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(g=null);let m=0,f=0,y=t+n.y;m=e+n.x,r[0].value>0||a.isContinuedBend?m+=n.getBeatX(a.beat,zs.MiddleNotes):m+=n.getNoteX(a,Js.Right),f=!g||g.isLastOfVoice&&!u?e+l.x+l.postBeatGlyphsStart:u||!g.nextBeat?e+l.x+l.getBeatX(g,zs.MiddleNotes):a.bendType===c.Hold?e+l.x+l.getBeatX(g.nextBeat,zs.OnNotes):e+l.x+l.getBeatX(g.nextBeat,zs.PreNotes),h||(f-=Eo.ArrowSize);let b=(f-m)/se.MaxPosition;s.beginPath();for(let e=0,t=r.length-1;e<t;e++){let t=r[e],i=r[e+1];0!==e||0===t.value||a.isTieDestination||this.paintBend(a,new Co(0,0),t,m,y,b,p,s),a.bendType!==c.Prebend?(0===e&&(m+=2),this.paintBend(a,t,i,m,y,b,p,s)):a.isTieOrigin&&a.tieDestination.hasBend&&(i=new Co(se.MaxPosition,t.value),i.lineValue=t.lineValue,this.paintBend(a,t,i,m,y,b,p,s))}if(o.vibrato!==B.None){const i=f-e+Eo.ArrowSize-l.x,a=y-t-Eo.BendValueHeight*r[r.length-1].lineValue,n=new zn(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){let h=this.renderer,l=this.renderer.resources,d=h.lineOffset/2,c=i+r*t.offset,u=Eo.BendValueHeight,p=a-u*t.lineValue;0===t.value?s.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,Xs.Top):p+=h.getNoteY(e,Xs.Center):p+=d;let g=i+r*s.offset,m=a-u*s.lineValue;0===s.lineValue?m+=h.getNoteY(e,Xs.Center):m+=d;let f=0,y=Eo.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,t=Eo.DashSize,s=c+t;if((e-c)/(2*t)<1)o.moveTo(e,p),o.lineTo(c,p);else for(;e>s;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>c?(o.moveTo(c,p),o.bezierCurveTo((c+g)/2,p,g,p,g,m+f),o.stroke()):(o.moveTo(c,p),o.lineTo(g,m),o.stroke());if(n&&t.offset<s.offset){o.font=l.graceFont;let e=o.measureText(n).width,t=0,s=0;if(p>m){let i=Math.abs(p-m);t=i>1.3*o.font.size?p-i/2:p,s=(c+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,i=s.value>t.value;e=Math.abs(e);let r="";if(4===e)r="full",e-=4;else if(e>=4||e<=-4){let t=e/4|0;r+=t,e-=4*t}if(e>0&&(r+=Eo.getFractionSign(e)),""!==r){m=a-u*s.value;let e=m;i||(e=p+1*Math.abs(m-p)/3),o.font=l.tablatureFont;let 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"}}}Eo.ArrowSize=6,Eo.DashSize=3,Eo.BendValueHeight=6;class Fo extends Ka{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===A.Custom)return e.whammyBarPoints;let t=[];switch(e.whammyBarType){case A.Dive:case A.Hold:case A.PrediveDive:case A.Predive:t.push(new se(0,e.whammyBarPoints[0].value)),t.push(new se(se.MaxPosition,e.whammyBarPoints[1].value));break;case A.Dip:t.push(new se(0,e.whammyBarPoints[0].value)),t.push(new se(se.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new se(se.MaxPosition,e.whammyBarPoints[e.whammyBarPoints.length-1].value))}return t}doLayout(){super.doLayout(),this._isSimpleDip=this.renderer.settings.notation.notationMode===e.NotationMode.SongBook&&this._beat.whammyBarType===A.Dip;let t=null,s=null,i=this._beat;for(;i&&i.hasWhammyBar;)(!t||t.value>i.minWhammyPoint.value)&&(t=i.minWhammyPoint),(!s||s.value<i.maxWhammyPoint.value)&&(s=i.maxWhammyPoint),i=i.nextBeat;let a=s.value>0?Math.abs(this.getOffset(s.value)):0;(a>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(e.NotationElement.ZerosOnDiveWhammys))&&(a+=2*this.renderer.resources.tablatureFont.size);let r=t.value<0?Math.abs(this.getOffset(t.value)):0;this.renderer.registerOverflowTop(a+r),a>this.renderer.staff.getSharedLayoutData(Fo.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(Fo.TopOffsetSharedDataKey,a)}getOffset(e){if(0===e)return 0;let t=Fo.PerHalfSize+Math.log2(Math.abs(e)/2)*Fo.PerHalfSize;return e<0&&(t=-t),t}paint(t,s,i){let a=this.renderer,r=this._beat.nextBeat,n=null,o=zs.PreNotes;r&&(n=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.voice.bar),n&&n.staff===a.staff&&(n===a||r.hasWhammyBar)?o=!r.hasWhammyBar||a.settings.notation.notationMode===e.NotationMode.SongBook&&r.whammyBarType===A.Dip?zs.PreNotes:zs.MiddleNotes:(r=null,n=null));let h=0,l=0;this._isSimpleDip?(h=t+a.x+a.getBeatX(this._beat,zs.OnNotes)-2,l=t+a.x+a.getBeatX(this._beat,zs.PostNotes)+2):(h=t+a.x+a.getBeatX(this._beat,zs.MiddleNotes),l=n?t+n.x+n.getBeatX(r,o):t+a.x+a.width-2);let c=i.textAlign;if(i.textAlign=L.Center,this._renderPoints.length>=2){let e=(l-h)/se.MaxPosition;i.beginPath();let t=s+this.renderer.staff.getSharedLayoutData(Fo.TopOffsetSharedDataKey,0),a=this._beat.whammyStyle===d.Gradual?"grad.":"";for(let s=0,r=this._renderPoints.length-1;s<r;s++){let n=this._renderPoints[s],o=this._renderPoints[s+1],l=s<r-2?this._renderPoints[s+2]:null,d=0===s;0!==s||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new se(0,0),n,o,h,t,e,i),d=!1),this.paintWhammy(d,n,o,l,h,t,e,i,a),a=""}i.stroke()}i.textAlign=c}paintWhammy(t,s,i,a,r,n,o,h,l){let d=r+o*s.offset,c=r+o*i.offset,u=n-this.getOffset(s.value),p=n-this.getOffset(i.value);if(s.offset===i.offset){let e=Fo.DashSize;if(Math.abs(p-u)/(2*e)<1)h.moveTo(d,u),h.lineTo(c,p);else{let t=Math.max(u,p),s=Math.min(u,p);for(;t>s;)h.moveTo(d,s),h.lineTo(d,s+e),s+=2*e}h.stroke()}else if(s.value===i.value){let e=Fo.DashSize;if(Math.abs(c-d)/(2*e)<1)h.moveTo(d,u),h.lineTo(c,p);else{let t=Math.max(d,c),s=Math.min(d,c);for(;t>s;)h.moveTo(t,u),h.lineTo(t-e,u),t-=2*e}h.stroke()}else h.moveTo(d,u),h.lineTo(c,p);let g=this.renderer.resources;if(t&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let t=u;t-=g.tablatureFont.size+2,this.renderer.settings.notation.isNotationElementVisible(e.NotationElement.ZerosOnDiveWhammys)&&h.fillText("0",d,t),l&&(t-=g.tablatureFont.size+2,h.fillText(l,d,t))}let m=Math.abs(i.value);if((0!==m||this.renderer.settings.notation.isNotationElementVisible(e.NotationElement.ZerosOnDiveWhammys)&&!this._isSimpleDip)&&s.value!==i.value){let e="";if(i.value<0&&(e+="-"),m>=4){let t=m/4|0;e+=t,m-=4*t}else 0===m&&(e+="0");m>0&&(e+=Eo.getFractionSign(m));let t=0;this._isSimpleDip?t=Math.min(u,p)-g.tablatureFont.size-2:(t=s.offset===i.offset?Math.min(u,p):p,t-=g.tablatureFont.size+2,a&&a.value>i.value&&(t-=2));let r=c;h.fillText(e,r,t)}}}Fo.TopOffsetSharedDataKey="tab.whammy.topoffset",Fo.PerHalfSize=6,Fo.DashSize=3;class Do extends Po{constructor(e){super(0,0),this._beat=e}doLayout(){let t=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case A.None:case A.Custom:case A.Hold:return;case A.Dive:case A.PrediveDive:{let e=new vo(this._beat,!1);e.renderer=this.renderer;let t=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let s of this._beat.notes)s.isTieOrigin||e.addGlyph(this.getBendNoteValue(s,t),t.value%2!=0);e.doLayout(),this.BendNoteHeads.push(e)}break;case A.Dip:if(t===e.NotationMode.SongBook){let e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+Do.SimpleDipHeight+Do.SimpleDipPadding}else{let t=new vo(this._beat,!1);if(t.renderer=this.renderer,this.renderer.settings.notation.notationMode===e.NotationMode.GuitarPro){let e=this._beat.whammyBarPoints[1];for(let s of this._beat.notes)t.addGlyph(this.getBendNoteValue(s,this._beat.whammyBarPoints[1]),e.value%2!=0)}t.doLayout(),this.BendNoteHeads.push(t);let s=new vo(this._beat,!1);if(s.renderer=this.renderer,this.renderer.settings.notation.notationMode===e.NotationMode.GuitarPro){let e=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let t of this._beat.notes)s.addGlyph(this.getBendNoteValue(t,e),e.value%2!=0)}s.doLayout(),this.BendNoteHeads.push(s)}case A.Predive:}super.doLayout()}paint(t,s,i){let a=this._beat;switch(a.whammyBarType){case A.None:case A.Custom:return}let r=this.renderer.settings.notation.notationMode,n=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,a.voice.bar),o=t+n.x+n.getBeatX(a,zs.MiddleNotes),h=this.getTieDirection(a,n),l=1===this._beat.notes.length?h:We.Up,c=i.textAlign;for(let c=0;c<a.notes.length;c++){let u=a.notes[c],p=s+n.y;c>0&&c>=(this._beat.notes.length/2|0)&&(l=We.Down),l===We.Down?p+=n.getNoteY(u,Xs.Bottom):p+=n.getNoteY(u,Xs.Top);let g=t+n.x;a.isLastOfVoice?g+=n.width:g+=n.getBeatX(a,zs.EndBeat),g-=8;let m=a.whammyStyle===d.Gradual&&0===c?"grad.":"",f=null;u.isTieOrigin&&(f=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,u.tieDestination.beat.voice.bar),f&&f.staff===n.staff?g=t+f.x+f.getBeatX(u.tieDestination.beat,zs.MiddleNotes):f=null);let y=Za.NoteHeadHeight*Za.GraceScale*.5;l===We.Up&&(y=-y);let b=a.whammyBarPoints.length>0?this.getBendNoteValue(u,a.whammyBarPoints[a.whammyBarPoints.length-1]):0,S=0,_=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(b)?(S=this.BendNoteHeads[0].getNoteValueY(b)+y,_=!0):f&&(u.isTieOrigin&&u.tieDestination.beat.hasWhammyBar||u.beat.isContinuedWhammy)?(S=s+f.y+f.getNoteY(u.tieDestination,Xs.Top),_=!0,l===We.Down&&(S+=Za.NoteHeadHeight)):u.isTieOrigin&&(S=f?s+f.y+f.getNoteY(u.tieDestination,Xs.Top):p,l===We.Down&&(S+=Za.NoteHeadHeight)),a.whammyBarType){case A.Hold:u.isTieOrigin&&mo.paintTie(i,1,o,p,g,S,h===We.Down,22,4);break;case A.Dive:0===c&&(this.BendNoteHeads[0].x=g-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=s+n.y,this.BendNoteHeads[0].paint(0,0,i),this.BendNoteHeads[0].containsNoteValue(b)&&(S+=this.BendNoteHeads[0].y)),_?this.drawBendSlur(i,o,p,g,S,l===We.Down,1,m):u.isTieOrigin&&mo.paintTie(i,1,o,p,g,S,h===We.Down,22,4);break;case A.Dip:if(r===e.NotationMode.SongBook){if(0===c){let e=t+n.x+n.getBeatX(this._beat,zs.OnNotes)-2,a=t+n.x+n.getBeatX(this._beat,zs.PostNotes)+2,r=(e+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();i.font=this.renderer.resources.tablatureFont,i.fillText(o,r,s+this.y);let h=s+this.y+i.font.size+2,l=h+Do.SimpleDipHeight;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(i.moveTo(e,l),i.lineTo(r,h),i.lineTo(a,l)):(i.moveTo(e,h),i.lineTo(r,l),i.lineTo(a,h)),i.stroke()}u.isTieOrigin&&mo.paintTie(i,1,o,p,g,S,h===We.Down,22,4)}else{let e=(o+g)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=s+n.y,this.BendNoteHeads[0].paint(0,0,i);let t=this.getBendNoteValue(u,a.whammyBarPoints[1]),r=this.BendNoteHeads[0].getNoteValueY(t)+y;this.drawBendSlur(i,o,p,e,r,l===We.Down,1,m),this.BendNoteHeads[1].x=g-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=s+n.y,this.BendNoteHeads[1].paint(0,0,i),S=this.BendNoteHeads[1].getNoteValueY(b)+y,this.drawBendSlur(i,e,r,g,S,l===We.Down,1,m)}break;case A.PrediveDive:case A.Predive:let d=t+n.x+n.getBeatX(u.beat,zs.PreNotes);d+=n.getPreNotesGlyphForBeat(u.beat).prebendNoteHeadOffset;let f=s+n.y+n.getScoreY(n.accidentalHelper.getNoteLineForValue(u.displayValue-(u.beat.whammyBarPoints[0].value/2|0),!1))+y;this.drawBendSlur(i,d,f,o,p,l===We.Down,1,m),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=g-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=s+n.y,this.BendNoteHeads[0].paint(0,0,i),this.drawBendSlur(i,o,p,g,S,l===We.Down,1,m))}}i.textAlign=c}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}Do.SimpleDipHeight=2*Fo.PerHalfSize,Do.SimpleDipPadding=2;class Lo extends Ka{constructor(e,t,s){super(e,t),this.width=s}}class Mo extends $a{constructor(e,t,s,i,a){super(e,t,a?Za.GraceScale:1,s.getSymbol(i)),this._isGrace=a,this._articulation=s}paint(e,t,s){let i=this._isGrace?1:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale,this.symbol,!1),this._articulation.techniqueSymbol!==D.None&&this._articulation.techniqueSymbolPlacement===M.Middle&&s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale,this._articulation.techniqueSymbol,!1)}doLayout(){const e=this._isGrace?Za.GraceScale:1;switch(this.symbol){case D.NoteheadWhole:this.width=14;break;case D.NoteheadCircleX:case D.NoteheadDiamondWhite:this.width=9;break;case D.NoteheadHeavyXHat:case D.NoteheadHeavyX:this.width=13;break;default:this.width=10}this.width=this.width*e,this.height=Za.NoteHeadHeight*e}}class Io extends $a{constructor(e,t){super(e,t,Za.GraceScale,D.ArticStaccatoAbove)}doLayout(){this.width=Za.QuarterNoteHeadWidth,this.height=7}paint(e,t,s){super.paint(e+3,t+5,s)}}class Ao extends $a{constructor(e,t){super(e,t,.5,D.PictEdgeOfCymbal)}doLayout(){this.width=22,this.height=15}paint(e,t,s){super.paint(e-3,t+this.height,s)}}class Ro extends Qa{constructor(e,t,s=!1){super(e,t),this._center=s}doLayout(){this.width=9,this.height=10}paint(e,t,s){s.fillMusicFontSymbol(e+this.x,t+this.y+this.height,Za.GraceScale,D.GuitarGolpe,this._center)}}class Oo extends Qa{constructor(){super(...arguments),this._strings=new Set}addString(e){this._strings.add(e)}doLayout(){const e=Zr.CircleNumberHeight*Zr.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=Zr.CircleNumberHeight*Zr.CircleNumberScale;for(const n of this._strings){const o=i-n,h=D.GuitarString1+o;s.fillMusicFontSymbol(e+this.x+Za.NoteHeadHeight/2,t+this.y+r+a,Zr.CircleNumberScale,h,!0),a+=r+3}}}class Vo extends Qa{constructor(e,t,s,i){super(e,t),this.beatEffects=new Map,this._isGrace=i,this._duration=s,this._symbol=Vo.getSymbol(s)}paint(e,t,s){let i=this._isGrace?1:0;const a=this._isGrace?Za.GraceScale:1;s.fillMusicFontSymbol(e+this.x,t+this.y+i,a,this._symbol,!1);for(const i of this.beatEffects.values())i.paint(e+this.x,t+this.y,s)}doLayout(){const e=this._isGrace?Za.GraceScale:1;switch(this._duration){case g.QuadrupleWhole:case g.DoubleWhole:case g.Whole:this.width=Vo.WholeNoteHeadWidth*e;break;case g.Half:this.width=Vo.HalfNoteHeadWidth*e;break;default:this.width=Vo.QuarterNoteHeadWidth*e}this.height=Vo.NoteHeadHeight*e;let t=Vo.NoteHeadHeight;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 g.QuadrupleWhole:case g.DoubleWhole:case g.Whole:return D.NoteheadSlashWhiteWhole;case g.Half:return D.NoteheadSlashWhiteHalf;default:return D.NoteheadSlashVerticalEnds}}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width,e+this.x)}}Vo.NoteHeadHeight=17,Vo.QuarterNoteHeadWidth=12,Vo.HalfNoteHeadWidth=25,Vo.WholeNoteHeadWidth=32;class Ho extends dn{constructor(){super(...arguments),this._collisionOffset=-1e3,this._skipPaint=!1,this.slash=null,this.noteHeads=null,this.restGlyph=null}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(){let 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===g.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const s=new ko(0,e.getScoreY(t),this.container.beat.duration);if(this.restGlyph=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper,this.addGlyph(s),this.renderer.bar.isMultiVoice)if(0===this.container.beat.voice.index){const t=Mr.computeLineHeightsForRest(this.container.beat.duration);let 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.addGlyph(new Lo(0,0,5));for(let e=0;e<this.container.beat.dots;e++){let e=new vr(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addGlyph(e)}}}else{if(this.container.beat.slashed){const t=this.container.beat.graceType!==f.None,s=(e.heightLineCount-1)/2,i=e.getLineY(s),a=new Vo(0,i,this.container.beat.duration,t);this.slash=a,a.beat=this.container.beat,a.beamingHelper=this.beamingHelper,this.addGlyph(a)}else{const e=new To;this.noteHeads=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;let t=new bo(!1);t.renderer=this.renderer;for(let e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),t.addParenthesis(e));this.addGlyph(e),t.isEmpty||(this.addGlyph(new Lo(0,0,4*(this.container.beat.graceType!==f.None?Za.GraceScale:1))),this.addGlyph(t))}if(this.container.beat.hasWhammyBar){let e=new Do(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addGlyph(new Lo(0,0,5));for(let t=0;t<this.container.beat.dots;t++){let t=new vr(0,0);t.renderer=this.renderer;for(let s of this.container.beat.notes)this.createBeatDot(e.getNoteLine(s),t);this.addGlyph(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){let s=this.renderer;t.addGlyph(new uo(0,s.getScoreY(e),1.5))}createNoteHeadGlyph(e){let t=this.container.beat.graceType!==f.None;if(e.beat.voice.bar.staff.isPercussion){const s=pe.getArticulation(e);if(s)return new Mo(0,0,s,e.beat.duration,t);ne.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new po(0,0,t):e.beat.graceType===f.BendGrace?new Za(0,0,g.Quarter,!0):e.harmonicType===b.Natural?new go(0,0,e.beat.duration,t):new Za(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===f.BendGrace&&!e.hasBend)return;let t=this.renderer,s=this.createNoteHeadGlyph(e),i=t.getNoteLine(e);if(s.y=t.getScoreY(i),this.noteHeads.addNoteGlyph(s,e,i),e.harmonicType!==b.None&&e.harmonicType!==b.Natural){let a=e.displayValue+e.harmonicPitch;s=new go(0,0,e.beat.duration,this.container.beat.graceType!==f.None),i=t.accidentalHelper.getNoteLineForValue(a,!1),s.y=t.getScoreY(i),this.noteHeads.addNoteGlyph(s,e,i)}const r=this.noteHeads.belowBeatEffects,n=this.noteHeads.aboveBeatEffects;if(e.isStaccato&&!r.has("Staccato")&&r.set("Staccato",new Io(0,0)),e.accentuated!==a.Normal||r.has("Accent")||r.set("Accent",new co(0,0,e)),e.accentuated!==a.Heavy||r.has("HAccent")||r.set("HAccent",new co(0,0,e)),e.accentuated!==a.Tenuto||r.has("Tenuto")||r.set("Tenuto",new co(0,0,e)),e.showStringNumber&&e.isStringed){let t;n.has("StringNumber")?t=n.get("StringNumber"):(t=new Oo(0,0),n.set("StringNumber",t)),t.addString(e.string)}if(e.isPercussion){const t=pe.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==M.Middle){const e=t.techniqueSymbolPlacement===M.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case D.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new Ao(0,0));break;case D.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new Io(0,0));break;case D.StringsUpBow:e.set("StringsUpBow",new Vn(0,0,F.Up));break;case D.StringsDownBow:e.set("StringsDownBow",new Vn(0,0,F.Down));break;case D.GuitarGolpe:e.set("GuitarGolpe",new Ro(0,0))}}}}}class Go extends Ka{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=this._beat.brushType===u.ArpeggioUp||this._beat.brushType===u.ArpeggioDown?10:0}paint(e,t,s){if(this._beat.brushType===u.ArpeggioUp||this._beat.brushType===u.ArpeggioDown){let i=this.renderer,a=i.lineOffset,r=t+this.y+(i.getNoteY(this._beat.maxNote,Xs.Bottom)-a),n=t+this.y+i.getNoteY(this._beat.minNote,Xs.Top)+a,o=e+this.x+this.width/2,h=8,l=new zn(0,0,B.Slight,1.2,!0);l.renderer=this.renderer,l.doLayout();let d=-l.height/2;if(this._beat.brushType===u.ArpeggioUp){let t=r+h,i=n-h;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5,i,-90),l.paint(0,d,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===u.ArpeggioDown){let t=r+h,i=n;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5,t,90),l.paint(0,d,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 Wo{constructor(e,t){this.line=0,this.line=e,this.text=t}}class zo extends vr{constructor(){super(0,0),this._infos=new Map}get isEmpty(){return 0===this._infos.size}addFingers(t){const s=this.renderer.settings;if(s.notation.fingeringMode!==e.FingeringMode.ScoreDefault&&s.notation.fingeringMode!==e.FingeringMode.ScoreForcePiano)return;const i=de.fingerToString(this.renderer.settings,t.beat,t.leftHandFinger,!0);i&&this.addFinger(t,i);const a=de.fingerToString(this.renderer.settings,t.beat,t.rightHandFinger,!1);a&&this.addFinger(t,a)}addFinger(e,t){let s=this.renderer.getNoteLine(e);if(this._infos.has(s)){this._infos.get(s).text+=t}else{const e=new Wo(s,t);this._infos.set(s,e)}}doLayout(){let e=this.renderer;for(const[t,s]of this._infos){const t=new zr(0,0,s.text,e.resources.inlineFingeringFont,L.Left,M.Middle);t.renderer=e,t.y=e.getScoreY(s.line),t.doLayout(),this.addGlyph(t),this.width=Math.max(this.width,t.width)}}}class Uo extends ln{get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}doLayout(){if(!this.container.beat.isRest){let e=new xo;e.renderer=this.renderer;let t=new zo;t.renderer=this.renderer;let s=new bo(!0);s.renderer=this.renderer;const i=new vo(this.container.beat,!0);this._prebends=i,i.renderer=this.renderer;for(let a of this.container.beat.notes)if(a.isVisible){if(a.hasBend)switch(a.bendType){case c.PrebendBend:case c.Prebend:case c.PrebendRelease:i.addGlyph(a.displayValue-(a.bendPoints[0].value/2|0),!1)}else if(a.beat.hasWhammyBar)switch(a.beat.whammyBarType){case A.PrediveDive:case A.Predive:this._prebends.addGlyph(a.displayValue-(a.beat.whammyBarPoints[0].value/2|0),!1)}this.createAccidentalGlyph(a,e),s.addParenthesis(a),t.addFingers(a)}i.isEmpty||(this.addGlyph(i),this.addGlyph(new Lo(0,0,4*(this.container.beat.graceType!==f.None?Za.GraceScale:1)))),this.container.beat.brushType!==u.None&&(this.addGlyph(new Go(this.container.beat)),this.addGlyph(new Lo(0,0,4))),t.isEmpty||(this.isEmpty||this.addGlyph(new Lo(0,0,2*(this.container.beat.graceType!==f.None?Za.GraceScale:1))),this.addGlyph(t),this.addGlyph(new Lo(0,0,2*(this.container.beat.graceType!==f.None?Za.GraceScale:1)))),s.isEmpty||(this.addGlyph(s),this.addGlyph(new Lo(0,0,4*(this.container.beat.graceType!==f.None?Za.GraceScale:1)))),e.isEmpty||(this.accidentals=e,this.isEmpty||this.addGlyph(new Lo(0,0,2*(this.container.beat.graceType!==f.None?Za.GraceScale:1))),this.addGlyph(e),this.addGlyph(new Lo(0,0,2*(this.container.beat.graceType!==f.None?Za.GraceScale:1))))}super.doLayout()}createAccidentalGlyph(e,t){let s=this.renderer,i=s.accidentalHelper.applyAccidental(e),a=s.getNoteLine(e),r=this.container.beat.graceType!==f.None;const n=r?Za.GraceScale:1;if(i!==Je.None){let e=new ho(0,s.getScoreY(a),i,n);e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==b.None&&e.harmonicType!==b.Natural){let o=e.displayValue+e.harmonicPitch;i=s.accidentalHelper.applyAccidentalForValue(e.beat,o,r,!1),a=s.accidentalHelper.getNoteLineForValue(o,!1);let h=new ho(0,s.getScoreY(a),i,n);h.renderer=this.renderer,t.addGlyph(h)}}constructor(){super(),this._prebends=null,this.accidentals=null}}class Xo extends $a{constructor(e,t,s,i){super(e,t,i,Xo.getSymbol(s)),this._digit=0,this._scale=0,this._digit=s,this._scale=i}doLayout(){this.width=this.getDigitWidth(this._digit)*this._scale}getDigitWidth(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:return 14;case 1:return 10;default:return 0}}static getSymbol(e){switch(e){case 0:return D.TimeSig0;case 1:return D.TimeSig1;case 2:return D.TimeSig2;case 3:return D.TimeSig3;case 4:return D.TimeSig4;case 5:return D.TimeSig5;case 6:return D.TimeSig6;case 7:return D.TimeSig7;case 8:return D.TimeSig8;case 9:return D.TimeSig9;default:return D.None}}}class Jo extends vr{constructor(e,t,s,i=1){super(e,t),this._number=0,this._scale=0,this._number=s,this._scale=i}doLayout(){let e=this._number;for(;e>0;){let t=new Xo(0,0,e%10,this._scale);this.addGlyph(t),e=e/10|0}if(this.glyphs){this.glyphs.reverse();let e=0;for(let t=0,s=this.glyphs.length;t<s;t++){let s=this.glyphs[t];s.x=e,s.y=0,s.renderer=this.renderer,s.doLayout(),e+=s.width}this.width=e}}}Jo.numberHeight=18;class Yo extends vr{constructor(e,t,s,i,a,r){super(e,t),this._numerator=0,this._denominator=0,this._numerator=s,this._denominator=i,this._isCommon=a,this._isFreeTime=r}doLayout(){let e=0;const t=Jo.numberHeight;if(this._isFreeTime){const s=new fo(!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){let t=new $a(e,0,this.commonScale,D.TimeSigCutCommon);t.width=14,this.addGlyph(t),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){let t=new $a(e,0,this.commonScale,D.TimeSigCommon);t.width=14,this.addGlyph(t),super.doLayout()}else{let s=new Jo(e,-t/2,this._numerator,this.numberScale),i=new Jo(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 fo(!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 qo extends Yo{get commonScale(){return 1}get numberScale(){return 1}}class jo extends Po{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)switch(e.bendType){case c.Bend:case c.PrebendRelease:case c.PrebendBend:{let t=this._endNoteGlyph;t||(t=new vo(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let s=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,s),s.value%2!=0)}break;case c.Release:if(!e.isTieOrigin){let t=this._endNoteGlyph;t||(t=new vo(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let s=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,s),s.value%2!=0)}break;case c.BendRelease:{let t=this._middleNoteGlyph;t||(t=new vo(e.beat,!1),this._middleNoteGlyph=t,t.renderer=this.renderer,this.BendNoteHeads.push(t));let s=e.bendPoints[1];t.addGlyph(this.getBendNoteValue(e,e.bendPoints[1]),s.value%2!=0);let i=this._endNoteGlyph;i||(i=new vo(e.beat,!1),i.renderer=this.renderer,this._endNoteGlyph=i,this.BendNoteHeads.push(i));let a=e.bendPoints[e.bendPoints.length-1];i.addGlyph(this.getBendNoteValue(e,a),a.value%2!=0)}}}paint(e,t,s){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._beat.voice.bar),a=e+i.x+i.getBeatX(this._beat,zs.MiddleNotes),r=e+i.x;this._beat.isLastOfVoice?r+=i.postBeatGlyphsStart:r+=i.getBeatX(this._beat.nextBeat,zs.PreNotes),r-=8;let 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));let o=this._beat.graceType===f.BendGrace?this._beat.nextBeat:this._beat,h=1===this._notes.length?this.getTieDirection(o,i):We.Up;for(let o=0;o<this._notes.length;o++){let l=this._notes[o];o>0&&o>=(this._notes.length/2|0)&&(h=We.Down);let u=t+i.y+i.getNoteY(l,Xs.Top),p=Za.NoteHeadHeight*Za.GraceScale*.5;h===We.Down&&(u+=Za.NoteHeadHeight);let g=l.bendStyle===d.Gradual?"grad.":"";if(l.isTieOrigin){let r=l.tieDestination,n=r?this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.beat.voice.bar):null;if(n&&n.staff===i.staff){let i=e+n.x+n.getBeatX(r.beat,zs.MiddleNotes),o=t+n.y+n.getNoteY(r,Xs.Top);h===We.Down&&(o+=Za.NoteHeadHeight),l.bendType===c.Hold||l.bendType===c.Prebend?mo.paintTie(s,1,a,u,i,o,h===We.Down,22,4):this.drawBendSlur(s,a,u,i,o,h===We.Down,1,g)}else{let r=e+i.x+i.width,n=l.tieDestination.realValue;i.accidentalHelper.applyAccidentalForValue(l.beat,n,!1,!0);let o=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(n,!1));l.bendType===c.Hold||l.bendType===c.Prebend?mo.paintTie(s,1,a,u,r,o,h===We.Down,22,4):this.drawBendSlur(s,a,u,r,o,h===We.Down,1,g)}switch(l.bendType){case c.Prebend:case c.PrebendBend:case c.PrebendRelease:let r=e+i.x+i.getBeatX(l.beat,zs.PreNotes);r+=i.getPreNotesGlyphForBeat(l.beat).prebendNoteHeadOffset;let n=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(l.displayValue-(l.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,r,n,a,u,h===We.Down,1)}}else{h===We.Up&&(p=-p);let o=0,d=0;switch(l.bendType){case c.Bend:o=this.getBendNoteValue(l,l.bendPoints[l.bendPoints.length-1]),d=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,d,h===We.Down,1,g);break;case c.BendRelease:let m=this.getBendNoteValue(l,l.bendPoints[1]),f=this._middleNoteGlyph.getNoteValueY(m)+p;this.drawBendSlur(s,a,u,n,f,h===We.Down,1,g),o=this.getBendNoteValue(l,l.bendPoints[l.bendPoints.length-1]),d=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,n,f,r,d,h===We.Down,1,g);break;case c.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(l,l.bendPoints[l.bendPoints.length-1]),d=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,d,h===We.Down,1,g));break;case c.Prebend:case c.PrebendBend:case c.PrebendRelease:let y=e+i.x+i.getBeatX(l.beat,zs.PreNotes);y+=i.getPreNotesGlyphForBeat(l.beat).prebendNoteHeadOffset;let b=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(l.displayValue-(l.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,y,b,a,u,h===We.Down,1),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(l,l.bendPoints[l.bendPoints.length-1]),d=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,d,h===We.Down,1,g))}}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class Ko extends mo{constructor(e,t,s=!1){super(e,t,s)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?We.Up:t.getBeatDirection(e)===We.Up?We.Down:We.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===We.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,Xs.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,Xs.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===We.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===f.None?s===this.tieDirection?this.tieDirection===We.Up?e.getNoteY(this.endBeat.maxNote,Xs.TopWithStem):e.getNoteY(this.endBeat.minNote,Xs.BottomWithStem):this.tieDirection===We.Up?e.getNoteY(this.endBeat.maxNote,Xs.BottomWithStem):e.getNoteY(this.endBeat.minNote,Xs.TopWithStem):this.tieDirection===We.Up?e.getNoteY(this.endBeat.maxNote,Xs.Top):e.getNoteY(this.endBeat.minNote,Xs.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,zs.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>g.Whole&&e===this.tieDirection?zs.Stem:zs.MiddleNotes)}}class Qo extends Ka{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){let i=this.renderer,a=e+i.x+i.getNoteX(this._startNote,Js.Left)-2,r=t+i.y+i.getNoteY(this._startNote,Xs.Center),n=a-12,o=t+i.y;switch(this._inType){case _.IntoFromBelow:o+=i.getNoteY(this._startNote,Xs.Bottom);break;case _.IntoFromAbove:o+=i.getNoteY(this._startNote,Xs.Top);break;default:return}let h=this.getAccidentalsWidth(i,this._startNote.beat);n-=h,a-=h,this.paintSlideLine(s,!1,n,a,o,r)}getAccidentalsWidth(e,t){let s=e.getPreNotesGlyphForBeat(t);return s&&s.accidentals?s.accidentals.width:0}drawSlideOut(e,t,s){let i=this.renderer,a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case w.Shift:case w.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,zs.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,Xs.Center),this._startNote.slideTarget){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,zs.PreNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,Xs.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 w.OutUp:a=e+i.x+i.getNoteX(this._startNote,Js.Right)+2,r=t+i.y+i.getNoteY(this._startNote,Xs.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,Xs.Top);break;case w.OutDown:a=e+i.x+i.getNoteX(this._startNote,Js.Right)+2,r=t+i.y+i.getNoteY(this._startNote,Xs.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,Xs.Bottom);break;case w.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,Js.Right)+4,r=t+i.y+i.getNoteY(this._startNote,Xs.Center),o=t+i.y+i.getNoteY(this._startNote,Xs.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,zs.PreNotes)),h=!0;break;case w.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,Js.Right)+4,r=t+i.y+i.getNoteY(this._startNote,Xs.Center),o=t+i.y+i.getNoteY(this._startNote,Xs.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,zs.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new zn(0,0,B.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;let n=i-s,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;let 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 $o extends Ko{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===We.Up?this.startNoteRenderer.getNoteY(this._startNote,Xs.Top):this.startNoteRenderer.getNoteY(this._startNote,Xs.Bottom):this.startNoteRenderer.getNoteY(this._startNote,Xs.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===We.Up?this.endNoteRenderer.getNoteY(this._endNote,Xs.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,Xs.BottomWithStem):this.tieDirection===We.Up?this.endNoteRenderer.getNoteY(this._endNote,Xs.Top):this.endNoteRenderer.getNoteY(this._endNote,Xs.Bottom):this.endNoteRenderer.getNoteY(this._endNote,Xs.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===We.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===We.Down}isEndCentered(){return this._startNote.beat.graceType===f.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===We.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===We.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===f.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,zs.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,Js.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,zs.Stem):this.endNoteRenderer.getNoteX(this._endNote,Js.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,zs.PreNotes)}}class Zo extends mo{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)===We.Up?We.Down:We.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===We.Up?this.startNoteRenderer.getNoteY(this.startNote,Xs.Top):this.startNoteRenderer.getNoteY(this.startNote,Xs.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===We.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===We.Up?e.getNoteY(this.endNote,Xs.Top):e.getNoteY(this.endNote,Xs.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,zs.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,zs.PreNotes)}}class eh extends tr{constructor(e,t){super(e,t),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!==f.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){let t=new Zo(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){let t=new Zo(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==_.None||e.slideOutType!==w.None){let t=new Qo(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){let t=new $o(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){let t=new $o(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new $o(e,e.effectSlurDestination,!1);this._effectSlur=t,this.addTie(t)}if(!this._effectEndSlur&&e.beat.isEffectSlurDestination&&e.beat.effectSlurOrigin){let t=this.onNotes.beamingHelper.direction,s=t===We.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,i=t===We.Up?e.beat.minNote:e.beat.maxNote;const a=new $o(s,i,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new jo(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 Ko(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 Ko(e,this.beat,!0))}}}}class th extends Ka{constructor(e,t,s,i){super(e,t),this._dotOffset=0,this._circleSize=0,this._dotOffset=0,this._circleSize=0,this._dotOffset=i,this._circleSize=s}doLayout(){this.width=13}paint(e,t,s){let i=t+this.y+this.renderer.topPadding,a=t+this.y+this.renderer.height-this.renderer.bottomPadding,r=e+this.x+.5,n=a-i;s.fillRect(r,i,4,n),r+=7.5,s.beginPath(),s.moveTo(r,i),s.lineTo(r,a),s.stroke(),r+=3;let o=this._circleSize,h=(i+a)/2;s.fillCircle(r,h-o*this._dotOffset,o),s.fillCircle(r,h+o*this._dotOffset,o)}}class sh extends Ka{constructor(e,t){super(e,t)}doLayout(){this.renderer.isLast?this.width=15:this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart?this.width=2:(this.width=2,this.renderer.bar.masterBar.isDoubleBar&&(this.width+=2))}paint(e,t,s){let i=t+this.y+this.renderer.topPadding,a=t+this.y+this.renderer.height-this.renderer.bottomPadding,r=e+this.x,n=a-i;if(this.renderer.isLast)s.fillRect(r+this.width-4-4,i,1,n),s.fillRect(r+this.width-4,i,4,n);else if(!this.renderer.nextRenderer||this.renderer.nextRenderer.staff!==this.renderer.staff||!this.renderer.nextRenderer.bar.masterBar.isRepeatStart)if(this.renderer.bar.masterBar.isFreeTime){const e=sh.DashSize,t=.5+(r+this.width-1|0),o=Math.ceil(n/2/e);if(s.beginPath(),o<1)s.moveTo(t,i),s.lineTo(t,a);else{let r=i;const h=(n-o*e)/(o-1);for(;r<a;)s.moveTo(t,r),s.lineTo(t,r+e),r+=e+h}s.stroke()}else s.fillRect(r+this.width-1,i,1,n),this.renderer.bar.masterBar.isDoubleBar&&s.fillRect(r+this.width-5,i,1,n)}}sh.DashSize=4;class ih extends Ka{constructor(e,t){super(e,t)}doLayout(){this.width=11}paint(e,t,s){let i=t+this.y+this.renderer.topPadding,a=t+this.y+this.renderer.height-this.renderer.bottomPadding,r=e+this.x,n=a-i,o=1.5,h=(i+a)/2;s.fillCircle(r,h-4.5,o),s.fillCircle(r,h+4.5,o),r+=4,s.beginPath(),s.moveTo(r,i),s.lineTo(r,a),s.stroke(),r+=3.5,s.fillRect(r,i,4,n)}}class ah extends Ka{constructor(e,t,s){super(e,t),this._count=0,this._count=0,this._count=s}doLayout(){this.width=0}paint(e,t,s){let i=this.renderer.resources,a=s.textAlign;s.font=i.barNumberFont,s.textAlign=L.Right;let r="x"+this._count,n=s.measureText(r).width/1.5;s.fillText(r,e+this.x-n,t+this.y),s.textAlign=a}}class rh extends Ka{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;let i=this.renderer.resources,a=s.color;const r=s.textBaseline;s.textBaseline=M.Top,s.color=i.barNumberColor,s.font=i.barNumberFont,s.fillText(this._number.toString(),e+this.x,t+this.y),s.color=a,s.textBaseline=r}}class nh extends an{constructor(e,t){super(e,t),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(){let 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);const i=this.resources;s.color=i.staffLineColor;const a=[];for(let e=0,t=this.drawnLineCount;e<t;e++)a.push([]);this.collectSpaces(a);for(const e of a)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));for(let i=0;i<this.drawnLineCount;i++){const r=this.getLineY(i);let n=0;for(let o of a[i])s.fillRect(e+this.x+n,t+this.y+r|0,o[0]-n,an.StaffLineThickness),n=o[0]+o[1];s.fillRect(e+this.x+n,t+this.y+r|0,this.width-n,an.StaffLineThickness)}s.color=i.mainGlyphColor,this.paintSimileMark(e,t,s)}collectSpaces(e){}createStartSpacing(){if(this._startSpacing)return;const e=0===this.index?this.settings.display.firstStaffPaddingLeft:this.settings.display.staffPaddingLeft;this.addPreBeatGlyph(new Lo(0,0,e)),this._startSpacing=!0}paintTuplets(e,t,s,i=!1){for(const a of this.bar.voices)if(this.hasVoiceContainer(a)){const r=this.getVoiceContainer(a);for(const a of r.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,a,i)}}getTupletBeamDirection(e){return this.getBeamDirection(e)}paintTupletHelper(e,t,s,i,a){const r=this.resources;let n,o=s.textAlign,h=s.textBaseline;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=L.Center,s.textBaseline=M.Middle;let l=i.beats[0].tupletNumerator,d=i.beats[0].tupletDenominator;n=2===l&&3===d?"2":3===l&&2===d?"3":4===l&&6===d?"4":5===l&&4===d?"5":6===l&&4===d?"6":7===l&&4===d?"7":9===l&&8===d?"9":10===l&&8===d?"10":11===l&&8===d?"11":12===l&&8===d?"12":13===l&&8===d?"13":l+":"+d;let c=this.tupletOffset,u=5;if(1!==i.beats.length&&i.isFull){let o=i.beats[0],h=i.beats[i.beats.length-1],l=null,d=null;for(let e=0;e<i.beats.length;e++)if(!i.beats[e].isRest){l=i.beats[e];break}for(let e=i.beats.length-1;e>=0;e--)if(!i.beats[e].isRest){d=i.beats[e];break}let p=!1;l||(l=o,p=!0),d||(d=h);let g=this.helpers.beamHelperLookup[i.voice.index].get(o.index),m=this.helpers.beamHelperLookup[i.voice.index].get(h.index),f=g.getBeatLineX(o),y=m.getBeatLineX(h),b=this.helpers.beamHelperLookup[i.voice.index].get(l.index),S=this.helpers.beamHelperLookup[i.voice.index].get(d.index),_=this.getTupletBeamDirection(g),w=this.calculateBeamYWithDirection(b,f,_),B=this.calculateBeamYWithDirection(S,y,_);p&&(w=Math.max(w,B),B=w),s.font=r.effectFont;let T=s.measureText(n).width,k=3,N=(f+y)/2,x=N-T/2-k,v=N+T/2+k,P=(B-w)/(y-f),C=w-P*f,E=P*x+C,F=P*N+C,D=P*v+C;_===We.Down&&(c*=-1,u*=-1),s.beginPath(),s.moveTo(e+this.x+f,t+this.y+w-c|0),a?s.quadraticCurveTo(e+this.x+(x+f)/2,t+this.y+E-c-u|0,e+this.x+x,t+this.y+E-c-u|0):(s.lineTo(e+this.x+f,t+this.y+w-c-u|0),s.lineTo(e+this.x+x,t+this.y+E-c-u|0)),s.stroke(),s.beginPath(),s.moveTo(e+this.x+v,t+this.y+D-c-u|0),a?s.quadraticCurveTo(e+this.x+(y+v)/2,t+this.y+D-c-u|0,e+this.x+y,t+this.y+B-c|0):(s.lineTo(e+this.x+y,t+this.y+B-c-u|0),s.lineTo(e+this.x+y,t+this.y+B-c|0)),s.stroke(),s.fillText(n,e+this.x+N,t+this.y+F-c-u)}else for(const a of i.beats){let o=this.helpers.beamHelperLookup[i.voice.index].get(a.index);if(!o)continue;let h=this.getTupletBeamDirection(o),l=o.getBeatLineX(a),d=this.calculateBeamYWithDirection(o,l,h);h===We.Down?d+=c+u:d-=c+u,s.font=r.effectFont,s.fillText(n,e+this.x+l,t+this.y+d)}s.textAlign=o,s.textBaseline=h}paintBeams(e,t,s){for(const i of this.helpers.beamHelpers)for(const a of i)this.paintBeamHelper(e+this.beatGlyphsStart,t,s,a)}drawBeamHelperAsFlags(e){return 1===e.beats.length}paintBeamHelper(e,t,s,i){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(this.drawBeamHelperAsFlags(i)?this.paintFlag(e,t,s,i):this.paintBar(e,t,s,i))}shouldPaintFlag(t,s){return t.graceType!==f.BendGrace&&(!t.deadSlapped&&(!!s.hasBeatLineX(t)&&((t.graceType===f.None||this.settings.notation.notationMode!==e.NotationMode.SongBook)&&(t.duration!==g.Whole&&t.duration!==g.DoubleWhole&&t.duration!==g.QuadrupleWhole))))}paintFlag(e,t,s,i){for(const a of i.beats){if(!this.shouldPaintFlag(a,i))continue;let r=a.graceType!==f.None,n=r?Za.GraceScale:1,o=this.getFlagStemSize(i.shortestDuration),h=i.getBeatLineX(a),l=this.getBeamDirection(i),d=this.getFlagTopY(a,l),c=this.getFlagBottomY(a,l),u=0;if(l===We.Down?(c+=o*n,u=c):(d-=o*n,u=d),i.hasLine(!0,a)){if(this.paintBeamingStem(a,t+this.y,e+this.x+h,t+this.y+d,t+this.y+c,s),a.graceType===f.BeforeBeat){let i=15,a=12;s.beginPath(),l===We.Down?(s.moveTo(e+this.x+h-a/2,t+this.y+c-i),s.lineTo(e+this.x+h+a/2,t+this.y+c)):(s.moveTo(e+this.x+h-a/2,t+this.y+d+i),s.lineTo(e+this.x+h+a/2,t+this.y+d)),s.stroke()}if(i.hasFlag(!0,a)){let i=new er(h-.5,u,a.duration,l,r);i.renderer=this,i.doLayout(),i.paint(e+this.x,t+this.y,s)}}}}getFlagStemSize(e,t=!1){let s=0;switch(e){case g.QuadrupleWhole:case g.Half:case g.Quarter:case g.Eighth:case g.Sixteenth:case g.ThirtySecond:case g.SixtyFourth:case g.OneHundredTwentyEighth:case g.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.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new th(0,0,1.5,3)),this.createLinePreBeatGlyphs(),this.addPreBeatGlyph(new rh(0,this.getLineHeight(-.25),this.bar.index+1))}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new ih(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new ah(0,this.getLineHeight(-.25),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new sh(0,0))}paintBar(e,t,s,i){for(let a=0,r=i.beats.length;a<r;a++){let r=i.beats[a];if(!i.hasBeatLineX(r)||r.deadSlapped)continue;let n=r.graceType!==f.None?Za.GraceScale:1,o=i.getBeatLineX(r),h=this.getBeamDirection(i),l=t+this.y+this.getBarLineStart(r,h),d=t+this.y+this.calculateBeamY(i,o);this.paintBeamingStem(r,t+this.y,e+this.x+o,l,d,s);let c=d;h===We.Down?c+=2*s.font.size:0!==a&&(c-=1.5*s.font.size);let u=6*n,p=(an.BeamSpacing+an.BeamThickness)*n,g=an.BeamThickness*n,m=de.getIndex(r.duration)-2,y=t+this.y;h===We.Down&&(p=-p,g=-g);for(let t=0;t<m;t++){let n=0,h=0,l=0,d=0,c=y+t*p;if(a<i.beats.length-1){const p=Mr.isFullBarJoin(r,i.beats[a+1],t);if(t===m-1&&p&&r.beamingMode===W.ForceSplitOnSecondaryToNext)n=o,h=n+u,l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),nh.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g),h=i.getBeatLineX(i.beats[a+1]),n=h-u,l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),nh.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g);else{if(p)n=o,h=i.getBeatLineX(i.beats[a+1]);else{if(0!==a&&Mr.isFullBarJoin(i.beats[a-1],r,t))continue;n=o,h=n+u}l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),nh.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g)}}else a>0&&!Mr.isFullBarJoin(r,i.beats[a-1],t)&&(n=o-u,h=o,l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),nh.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g))}}}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 oh extends nh{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.beatEffectsMinY=null,this.beatEffectsMaxY=null,this.accidentalHelper=new Fr(this)}get lineSpacing(){return an.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){let e=this.getScoreY(-2),t=this.getScoreY(10),s=this.simpleWhammyOverflow;const 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),n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);n.direction===We.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),h=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);h.direction===We.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),this.paintTuplets(e,t,s)}getSlashFlagY(e,t){let s=(this.heightLineCount-1)/2,i=0;switch(e){case g.QuadrupleWhole:case g.DoubleWhole:case g.Whole:i+=2;break;default:i+=1}t==We.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*=Za.GraceScale),s}getBarStemSize(e){let t=0;switch(e){case g.QuadrupleWhole:case g.Half:case g.Quarter:case g.Eighth:case g.Sixteenth:t=6;break;case g.ThirtySecond:t=8;break;case g.SixtyFourth:case g.OneHundredTwentyEighth:t=9;break;case g.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){let e=(this.heightLineCount-1)/2;return this.getLineY(e)}let s=super.getNoteY(e,t);if(isNaN(s)){const t=Fr.computeLineWithoutAccidentals(this.bar,e);s=this.getScoreY(t)}return s}applyLayoutingInfo(){const e=super.applyLayoutingInfo();if(e&&this.bar.isMultiVoice){let 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){let i=this.getStemSize(e);if(!e.drawingInfos.has(s)){let t=new Lr;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===We.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===We.Up?this.getFlagTopY(a,s)-i:this.getFlagBottomY(a,s)+i,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?s===We.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===We.Up?this.getFlagTopY(r,s)-i:this.getFlagBottomY(r,s)+i;let o=10;if(s===We.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),s===We.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),s===We.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),s===We.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(s===We.Up){let s=this.getScoreY(this.accidentalHelper.getMinLine(e.beatOfHighestNote))-i;const 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=de.getIndex(e.shortestDuration)-2;let a=e.isGrace?Za.GraceScale:1,r=i*(an.BeamSpacing+an.BeamThickness)*a;if(r+=an.BeamSpacing,s===We.Up&&null!==e.minRestLine){let s=this.getScoreY(e.minRestLine)-r;const i=t.calcY(e.getBeatLineX(e.beatOfMinRestLine))-s;i>0&&(t.startY-=i,t.endY-=i)}else if(s===We.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===We.Up?n-=i:s===We.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===We.Up?this.getScoreY(this.accidentalHelper.getMaxLine(e)):this.getScoreY(this.accidentalHelper.getMinLine(e))}createLinePreBeatGlyphs(){if(this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let e=0;switch(this.bar.clef){case n.Neutral:e=this.bar.staff.standardNotationLineCount-1;break;case n.F4:e=2;break;case n.C3:e=4;break;case n.C4:e=2;break;case n.G2:e=6}this.createStartSpacing(),this.addPreBeatGlyph(new lo(0,this.getScoreY(e)+.5*an.StaffLineThickness,this.bar.clef,this.bar.clefOttava))}(0===this.index&&this.bar.masterBar.keySignature!==P.C||this.bar.previousBar&&this.bar.masterBar.keySignature!==this.bar.previousBar.masterBar.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,t=this.bar.masterBar.keySignature,s=this.bar.previousBar?this.bar.previousBar.masterBar.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}let i=new Map,a=[];if(de.keySignatureIsSharp(t))for(let s=0;s<Math.abs(t);s++){let t=oh.SharpKsSteps[s]+e;a.push(new ho(0,this.getScoreY(t),Je.Sharp,1)),i.set(t,!0)}else for(let s=0;s<Math.abs(t);s++){let t=oh.FlatKsSteps[s]+e;a.push(new ho(0,this.getScoreY(t),Je.Flat,1)),i.set(t,!0)}if(this.bar.masterBar.keySignature===P.C){let t=Math.abs(s),a=de.keySignatureIsSharp(s)?oh.SharpKsSteps:oh.FlatKsSteps;for(let s=0;s<t;s++){let t=a[s]+e;i.has(t)||this.addPreBeatGlyph(new ho(0,this.getScoreY(a[s]+e),Je.Natural,1))}}for(let e of a)this.addPreBeatGlyph(e)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Lo(0,0,5));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new qo(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){let s=new eh(t,this.getVoiceContainer(e));s.preNotes=new Uo,s.onNotes=new Ho,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,Xs.Center),s=this.getNoteY(e.lowestNoteInHelper,Xs.Center),i=this.getStemSize(e);e.hasTuplet&&(i+=2*this.resources.effectFont.size),e.direction==We.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){r.lineWidth=an.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}}oh.StaffId="score",oh.SharpKsSteps=[-1,2,-2,1,4,0,3],oh.FlatKsSteps=[3,0,4,1,5,2,6];class hh extends xr{get staffId(){return oh.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 oh(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showStandardNotation}constructor(){super()}}class lh extends Ka{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){let i=this.renderer,a=0,r=0,n=0,o=0;switch(this._inType){case _.IntoFromBelow:n=e+i.x+i.getNoteX(this._startNote,Js.Left)-2,o=t+i.y+i.getNoteY(this._startNote,Xs.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,Xs.Center)+3;break;case _.IntoFromAbove:n=e+i.x+i.getNoteX(this._startNote,Js.Left)-2,o=t+i.y+i.getNoteY(this._startNote,Xs.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,Xs.Center)-3;break;default:return}this.paintSlideLine(s,!1,a,n,r,o)}paintSlideOut(e,t,s){let i=this.renderer,a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case w.Shift:case w.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,zs.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,Xs.Center),this._startNote.slideTarget){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,zs.OnNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,Xs.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 w.OutUp:a=e+i.x+i.getNoteX(this._startNote,Js.Right)+2,r=t+i.y+i.getNoteY(this._startNote,Xs.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,Xs.Center)-3;break;case w.OutDown:a=e+i.x+i.getNoteX(this._startNote,Js.Right)+2,r=t+i.y+i.getNoteY(this._startNote,Xs.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,Xs.Center)+3;break;case w.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,Js.Right)+4,r=t+i.y+i.getNoteY(this._startNote,Xs.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,zs.PreNotes)),h=!0;break;case w.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,Js.Right)+4,r=t+i.y+i.getNoteY(this._startNote,Xs.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,zs.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new zn(0,0,B.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;let n=i-s,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;let 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 dh extends mo{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?We.Up:dh.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?We.Up:We.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,Xs.Center):this.tieDirection===We.Up?this.startNoteRenderer.getNoteY(this.startNote,Xs.Top):this.startNoteRenderer.getNoteY(this.startNote,Xs.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Js.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,Js.Left):this.endNoteRenderer.getNoteX(this.endNote,Js.Center)}}class ch extends dh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=dh.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!==dh.getBeamDirectionForNote(e))return!1;switch(this._direction){case We.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 We.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){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,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 uh extends tr{constructor(e,t){super(e,t),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;let t=this.renderer;if(e.isTieOrigin&&t.showTiedNotes&&e.tieDestination.isVisible){let t=new dh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){let t=new dh(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new dh(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(let s of this._effectSlurs)if(s.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){let t=new ch(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(let s of this._effectSlurs)if(s.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){let t=new ch(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==_.None||e.slideOutType!==w.None){let t=new lh(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new Eo;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class ph extends Ka{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(){let t=this._note,s=t.fret-t.beat.voice.bar.staff.transpositionPitch;if(t.harmonicType===b.Natural&&0!==t.harmonicValue&&(s=t.harmonicValue-t.beat.voice.bar.staff.transpositionPitch),t.isTieDestination)0===t.beat.index&&this.renderer.settings.notation.notationMode==e.NotationMode.GuitarPro||(t.bendType===c.Bend||t.bendType===c.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(e.NotationElement.TabNotesOnTiedBends)?this._noteString="("+(t.tieOrigin.fret-t.beat.voice.bar.staff.transpositionPitch).toString()+")":this._noteString="";else if(this._noteString=t.isDead?"x":s.toString(),t.isGhost)this._noteString="("+this._noteString+")";else if(t.harmonicType===b.Natural){let e=this._noteString.indexOf(String.fromCharCode(46));e>=0&&(this._noteString=this._noteString.substr(0,e+2)),this._noteString="<"+this._noteString+">"}if(t.isTrill)this._trillNoteString="("+(t.trillFret-t.beat.voice.bar.staff.transpositionPitch).toString()+")";else if(de.isAlmostEqualTo(t.harmonicValue,0))this._trillNoteString="";else switch(t.harmonicType){case b.Artificial:case b.Pinch:case b.Tap:case b.Semi:case b.Feedback:let e=(s+t.harmonicValue).toString(),i=e.indexOf(String.fromCharCode(46));i>=0&&(e=e.substr(0,i+2)),this._trillNoteString="<"+e+">";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;let i=this.noteStringWidth+this._trillNoteStringWidth,a=e+this.x+(this.width-i)/2,r=this.renderer.scoreRenderer.canvas.font;this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,s.fillText(this._trillNoteString,a+this.noteStringWidth+3,t+this.y),this.renderer.scoreRenderer.canvas.font=r,s.fillText(this._noteString,a,t+this.y)}buildBoundingsLookup(e,t,s){let i=new Ea;i.note=this._note,i.noteHeadBounds=new cs,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 gh extends Ka{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)){let s=this.notesPerString.get(e.string),i=this.x+s.x;switch(t){case Js.Left:break;case Js.Center:i+=s.noteStringWidth/2;break;case Js.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 Xs.Top:case Xs.TopWithStem:i-=s.height/2+2;break;case Xs.Center:break;case Xs.Bottom:case Xs.BottomWithStem:i+=s.height/2}return i}return 0}doLayout(){let e=0;if(this.beat.deadSlapped)this._deadSlapped=new Bo,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++){let 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;let s=this.renderer.resources.tablatureFont.size,i=this.getNoteY(this.minStringNote,Xs.Center)+s/2,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{let i=this.renderer.resources,a=s.textBaseline;s.textBaseline=M.Middle,s.font=this._isGrace?i.graceFont:i.tablatureFont;let r=this._notes,n=this.width;for(let i of r)i.renderer=this.renderer,i.width=n,i.paint(e,t,s);s.textBaseline=a;for(const i of this.beatEffects.values())i.paint(e,t,s)}}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 mh extends $a{constructor(e,t,s,i){super(e,t,1,ko.getSymbol(i)),this._isVisibleRest=s,this._duration=i}doLayout(){this._isVisibleRest?this.width=ko.getSize(this._duration):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){this._isVisibleRest&&super.paint(e,t,s)}}class fh extends dn{constructor(){super(...arguments),this.slash=null,this.noteNumbers=null,this.restGlyph=null}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(){let t=this.renderer;if(this.container.beat.isRest){let e=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),s=t.getTabY(e);const i=new mh(0,s,t.showRests,this.container.beat.duration);if(this.restGlyph=i,i.beat=this.container.beat,i.beamingHelper=this.beamingHelper,this.addGlyph(i),this.container.beat.dots>0&&t.showRests){this.addGlyph(new Lo(0,0,5));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new uo(0,s,1.5))}}else{let s,i=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==f.None;if(this.container.beat.slashed&&!this.container.beat.notes.some((e=>e.isTieDestination))){const e=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),a=t.getLineY(e),r=new Vo(0,a,this.container.beat.duration,i);this.slash=r,r.beat=this.container.beat,r.beamingHelper=this.beamingHelper,this.addGlyph(r),s=r.beatEffects}else{const e=new gh(0,0,i);this.noteNumbers=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;for(let e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);this.addGlyph(e),s=e.beatEffects}if(this.container.beat.hasWhammyBar){let e=new Fo(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,t=this.container.beat.tremoloSpeed,i=5;switch(t){case g.ThirtySecond:e=10;break;case g.Sixteenth:e=5;break;case g.Eighth:e=0}this.container.beat.duration<g.Half&&(i=0),s.set("tremolo",new wo(i,e,t))}if(this.container.beat.dots>0&&t.rhythmMode!==e.TabRhythmMode.Hidden){this.addGlyph(new Lo(0,0,5));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new uo(0,t.lineOffset*t.bar.staff.tuning.length+t.settings.notation.rhythmHeight,1.5))}}if(!this.glyphs)return;let s=0;for(let e=0,t=this.glyphs.length;e<t;e++){let t=this.glyphs[e];t.x=s,t.renderer=this.renderer,t.doLayout(),s+=t.width}this.width=s,this.computedWidth=s,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){let t=this.renderer,s=new ph(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);let a=s.y-s.height/2,r=a+s.height;this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,a,r)}}class yh extends Ka{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10}paint(e,t,s){let i=this.renderer,a=t+this.x+i.getNoteY(this._beat.maxStringNote,Xs.Top),r=t+this.y+i.getNoteY(this._beat.minStringNote,Xs.Bottom),n=e+this.x+this.width/2|0;if(this._beat.brushType!==u.None){if(this._beat.brushType===u.BrushUp||this._beat.brushType===u.BrushDown)s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke();else if(this._beat.brushType===u.ArpeggioUp){let t=new zn(0,0,B.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let 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===u.ArpeggioDown){let t=new zn(0,0,B.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let 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===u.BrushUp||this._beat.brushType===u.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 bh extends ln{doLayout(){this.container.beat.brushType===u.None||this.container.beat.isRest||(this.addGlyph(new yh(this.container.beat)),this.addGlyph(new Lo(0,0,4))),super.doLayout()}constructor(){super()}}class Sh extends Ka{constructor(e,t){super(e,t)}doLayout(){this.width=28}paint(e,t,s){let i=this.renderer.bar.staff.tuning.length,a=i<=4?D.FourStringTabClef:D.SixStringTabClef,r=i<=4?i/4.5:i/6.5;s.fillMusicFontSymbol(e+this.x+5,t+this.y,r,a,!1)}}class _h extends Yo{get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?Za.GraceScale:1}}class wh extends nh{constructor(e,t){super(e,t),this._hasTuplets=!1,this.showTimeSignature=!1,this.showRests=!1,this.showTiedNotes=!1,t.staff.showStandardNotation||(this.showTimeSignature=!0,this.showRests=!0,this.showTiedNotes=!0)}get lineSpacing(){return wh.TabLineSpacing}get heightLineCount(){return this.bar.staff.tuning.length}get drawnLineCount(){return this.bar.staff.tuning.length}get rhythmMode(){let t=this.settings.notation.rhythmMode;return t===e.TabRhythmMode.Automatic&&(t=this.bar.staff.showStandardNotation?e.TabRhythmMode.Hidden:e.TabRhythmMode.ShowWithBars),t}getTabY(e){return super.getLineY(e)}getTabHeight(e){return super.getLineHeight(e)}collectSpaces(e){for(let t of this.bar.voices)if(this.hasVoiceContainer(t)){let s=this.getVoiceContainer(t);for(let t of s.beatGlyphs){let 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!==e.TabRhythmMode.Hidden&&(this.height+=this.settings.notation.rhythmHeight,this.bottomPadding+=this.settings.notation.rhythmHeight)}doLayout(){if(super.doLayout(),this.rhythmMode!==e.TabRhythmMode.Hidden){this._hasTuplets=!1;for(let 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){let e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new Sh(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 Lo(0,0,5));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new _h(0,this.getTabY(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){let s=new uh(t,this.getVoiceContainer(e));s.preNotes=new bh,s.onNotes=new fh,this.addBeatGlyph(s)}}paint(t,s,i){super.paint(t,s,i),this.rhythmMode!==e.TabRhythmMode.Hidden&&(this.paintBeams(t,s,i),this.paintTuplets(t,s,i))}drawBeamHelperAsFlags(t){return super.drawBeamHelperAsFlags(t)||this.rhythmMode===e.TabRhythmMode.ShowWithBeams}getFlagTopY(e,t){const s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==g.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,Xs.Bottom):this.height-this.settings.notation.rhythmHeight-this.tupletSize}getFlagBottomY(e,t){return this.getFlagAndBarPos()}getFlagStemSize(e,t=!1){return 0}getBarLineStart(e,t){let s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==g.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,Xs.Bottom)+this.lineOffset/2:this.height-this.settings.notation.rhythmHeight-this.tupletSize}getBeamDirection(e){return We.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===f.None&&this.drawBeamHelperAsFlags(t))}paintBeamingStem(e,t,s,i,a,r){if(a<i){const e=a;a=i,i=e}r.lineWidth=an.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}}wh.StaffId="tab",wh.TabLineSpacing=10;class Bh extends xr{get staffId(){return wh.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){let s=new wh(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 Th extends Qa{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+Th.Padding}paint(e,t,s){let i=this.renderer.resources;s.font=i.effectFont;let a=s.textAlign;s.textAlign=L.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+(Th.Padding-1),s.font.size/1.6)}}Th.Padding=4;class kh extends Pn{get notationElement(){return e.NotationElement.EffectTap}get sizingMode(){return Ys.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new Th}}class Nh{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"}(Yn||(Yn={}));class xh extends Nh{constructor(){super(...arguments),this.align=L.Left,this.frame=Yn.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class vh extends Nh{constructor(){super(...arguments),this.chord=new Te}}class Ph extends Nh{}class Ch extends Nh{}class Eh extends Nh{constructor(){super(...arguments),this.number=0}}class Fh extends Nh{constructor(){super(...arguments),this.decrescendo=!1}}class Dh extends Nh{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class Lh extends Nh{constructor(){super(...arguments),this.octave=1}}class Mh extends Nh{}class Ih{constructor(){this.defaultClef=n.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class Ah{constructor(){this.from=0,this.to=0,this.curly=!1}}class Rh{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class Oh{constructor(){this._trackChannel=0,this._beamingMode=W.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new oe,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;let s=new ys;try{s.parse(e)}catch(e){throw new Q("Could not parse XML",e)}this.parseDom(s),this.consolidate(),this.score.finish(t)}consolidate(){for(const e of this.score.tracks){const t=this._voiceCounts.get(e.index);for(const s of e.staves){for(;s.bars.length<this.score.masterBars.length;)this.addNewBar(s);for(const e of s.bars){for(;e.voices.length<t;)e.addVoice(new Ie);for(const t of e.voices)if(0===t.beats.length){const e=new Be;e.isEmpty=!0,t.addBeat(e)}}}}Oh.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),Oh.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?p.Decrescendo:p.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){let t=e.firstElement;if(!t)throw new Q("No valid XML");if("score"!==t.localName)throw new Q('Root node of XML was not "score"');this.score=new ve,this.score.tempo=120;for(let e of t.childNodes)if(e.nodeType===rs.Element)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(let t of e.childNodes)if(t.nodeType===rs.Element)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 Me,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(let t of e.childNodes)if(t.nodeType===rs.Element&&"bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new Ah;t.from=parseInt(e.getAttribute("from")),t.to=parseInt(e.getAttribute("to")),e.attributes.has("curly")&&(t.curly="true"===e.attributes.get("curly")),this._brackets.push(t)}parseLayoutStaves(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new Ih;t.description=e.getAttribute("description");for(let s of e.childNodes)if(s.nodeType===rs.Element)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=parseInt(s.attributes.get("instr"))),s.attributes.has("volume")&&(t.volume=parseInt(s.attributes.get("volume"))),s.attributes.has("transpose")&&(t.transpose=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(let t of e.childNodes)if(t.nodeType===rs.Element&&"system"===t.localName)this.parseSystem(t)}parseSystem(e){e.attributes.has("tempo")&&0===this.score.masterBars.length&&(this.score.tempo=parseInt(e.attributes.get("tempo"))),"0"===e.getAttribute("beamGrouping")&&(this._beamingMode=W.ForceSplitToNext);for(let t of e.childNodes)if(t.nodeType===rs.Element&&"staves"===t.localName)this.parseStaves(e,t);this._isFirstSystem=!1}parseStaves(e,t){let s=this.score.masterBars.length;for(let i of t.childNodes)if(i.nodeType===rs.Element&&"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(let r of s.childNodes)if(r.nodeType===rs.Element&&"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=parseInt(t[0]),this._timeSignature.timeSignatureDenominator=parseInt(t[1]),this._timeSignature.timeSignatureCommon=!1}}}parseVoices(e,t,s,i,a){let r=0;for(let n of a.childNodes)if(n.nodeType===rs.Element&&"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){let t=new ee;if(e.bars.length>0?(t.clef=e.bars[e.bars.length-1].clef,t.clefOttava=e.bars[e.bars.length-1].clefOttava):t.clef=this._currentStaffLayout.defaultClef,e.addBar(t),e.bars.length>this.score.masterBars.length){let e=new oe;this.score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,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,n){const o=e+"_"+i;if(this._currentVoiceState&&!this._currentVoiceState.currentBarComplete&&(this._currentBar.masterBar.isAnacrusis=!0),this._voiceStates.has(o)?(this._currentVoiceState=this._voiceStates.get(o),this._currentBar=this.getOrCreateBar(t,this._currentVoiceState.currentBarIndex),this.ensureVoice(t,i)):(this._currentVoiceState=new Rh,this._currentVoiceState.currentBarIndex=a-1,this._voiceStates.set(o,this._currentVoiceState),this.newBar(t,i)),n.attributes.has("stemDir"))switch(n.attributes.get("stemDir")){case"up":this._currentVoiceState.voiceStemDir=We.Up;break;case"down":this._currentVoiceState.voiceStemDir=We.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const h=n.findChildElement("noteObjects");if(s.attributes.has("tempo")){const e=new $;e.isLinear=!0,e.type=r.Tempo,e.value=parseInt(s.attributes.get("tempo")),e.ratioPosition=this._currentVoiceState.currentPosition/this._currentVoiceState.currentBarDuration,this._currentBar.masterBar.tempoAutomations.push(e)}if(h)for(let e of h.childNodes)if(e.nodeType===rs.Element)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.masterBar.keySignature=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.masterBar.isDoubleBar=!0,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":let s=new Be;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){let 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 Ie);(!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 me;for(let i of t.childNodes)if(i.nodeType===rs.Element)switch(i.localName){case"stem":switch(i.getAttribute("dir")){case"up":e.preferredBeamDirection=We.Up;break;case"down":e.preferredBeamDirection=We.Down}break;case"articulation":switch(i.getAttribute("type")){case"staccato":s.isStaccato=!0;break;case"normalAccent":s.accentuated=a.Normal;break;case"strongAccent":s.accentuated=a.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=W.ForceMergeWithNext;break;case"divide":e.beamingMode=W.ForceSplitToNext}}}parseHeads(e,t,s){for(let i of s.childNodes)if(i.nodeType===rs.Element&&"head"===i.localName)this.parseHead(e,t,i)}parseHead(e,t,s){const i=new me,a=de.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(let e of s.childNodes)if(e.nodeType===rs.Element)switch(e.localName){case"alter":e.attributes.has("step")&&(i.tone+=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(let s of t.childNodes)if(s.nodeType===rs.Element&&"drawObj"===s.localName){const t=this.parseDrawObj(s);if(t)if(t instanceof xh)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new et,e.fermata.type=Ge.Medium):"f"===t.text?e.dynamics=m.F:"j"===t.text&&(e.dynamics=m.MF):this._isFirstSystem&&""===this.score.title&&t.align===L.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===L.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===L.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof vh);else if(t instanceof Ch)e.vibrato=B.Slight;else if(t instanceof Fh)e.crescendo=t.decrescendo?p.Decrescendo:p.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof Ph){const s=t;this._slurs.set(e,s)}else t instanceof Dh&&this.applyVolta(t)}}parseBarDrawObject(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof Dh&&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(let s of t.childNodes)if(s.nodeType===rs.Element&&"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("/")){let s=new Be;return s.beamingMode=this._beamingMode,this.parseDuration(e,s,t),s}if(1===parseInt(s)){let e=new Be;return e.beamingMode=this._beamingMode,e.duration=g.Whole,e}return ne.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return g.DoubleWhole;case"1/1":return g.Whole;case"1/2":return g.Half;case"1/4":return g.Quarter;case"1/8":return g.Eighth;case"1/16":return g.Sixteenth;case"1/32":return g.ThirtySecond;case"1/64":return g.SixtyFourth;case"1/128":return g.OneHundredTwentyEighth;default:return ne.warning("Importer","Unsupported duration"),g.Quarter}}parseDuration(e,t,s){const i=s.getAttribute("base");t.duration=this.parseDurationValue(i),s.attributes.has("dots")&&(t.dots=parseInt(s.attributes.get("dots")));const a=s.findChildElement("tuplet");if(a){t.tupletNumerator=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(let t of e.childNodes)if(t.nodeType===rs.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof xh)switch(e.align){case L.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case L.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(let t of e.childNodes)if(t.nodeType===rs.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&this._galleryObjects.set(t.getAttribute("name"),e)}}parseDrawObj(e){let t=null,s=1;for(let i of e.childNodes)if(i.nodeType===rs.Element)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=parseInt(i.attributes.get("noteRange")))}return t&&(t.noteRange=s),t}parseTrill(e){return new Mh}parseOctaveClef(e){const t=new Lh;return e.attributes.has("octave")&&(t.octave=parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new Dh;return t.allNumbers="true"===e.attributes.get("allNumbers"),e.attributes.has("firstNumber")&&(t.firstNumber=parseInt(e.attributes.get("firstNumber"))),e.attributes.has("lastNumber")&&(t.lastNumber=parseInt(e.attributes.get("lastNumber"))),t}parseWedge(e){const t=new Fh;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new Eh;return e.attributes.has("number")&&(t.number=parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new Ch}parseSlur(e){return new Ph}parseGuitar(e){const t=new vh,s=e.innerText.trim();for(let e=0;e<s.length;e++)"/"===s.charAt(e)?t.chord.strings.push(0):t.chord.strings.push(parseInt(s.charAt(e)));return t}parseText(e){const t=new xh;switch(e.attributes.has("x")&&(t.x=parseFloat(e.attributes.get("x"))),e.attributes.has("x")&&(t.y=parseFloat(e.attributes.get("y"))),e.getAttribute("align")){case"left":t.align=L.Left;break;case"center":t.align=L.Center;break;case"right":t.align=L.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=Yn.Rectangle;break;case"ellipse":t.frame=Yn.Ellipse;break;case"circle":t.frame=Yn.Circle;break;case"none":t.frame=Yn.None}if(e.firstElement){for(let s of e.childNodes)if(s.nodeType===rs.Element)switch(s.localName){case"font":t.fontFace=s.getAttribute("face"),s.attributes.has("weight")&&(t.weight=parseInt(s.attributes.get("weight"))),s.attributes.has("height")&&(t.height=parseInt(s.attributes.get("height")));break;case"content":t.text=s.innerText}}else t.text=e.innerText;return t}parseInfo(e){for(let t of e.childNodes)if(t.nodeType===rs.Element)switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class Vh extends j{get name(){return"Capella"}constructor(){super()}readScore(){ne.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new Qs(this.data).read(),ne.debug(this.name,"Zip entries loaded"),e.length>0){for(let s of e)if("score.xml"===s.fileName)t=Re.toString(s.data,this.settings.importer.encoding)}else this.data.reset(),t=Re.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new Q("No valid capella file");ne.debug(this.name,"Start Parsing score.xml");try{let e=new Oh;return e.parseXml(t,this.settings),ne.debug(this.name,"score.xml parsed"),e.score}catch(e){throw new Q("Failed to parse CapXML",e)}}}class Hh{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 Gh{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=[];this._elements.forEach((t=>{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)}}function Wh(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}var zh="function"==typeof SuppressedError?SuppressedError:function(e,t,s){var i=new Error(s);return i.name="SuppressedError",i.error=e,i.suppressed=t,i};function Uh(e){function t(t){e.error=e.hasError?new zh(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var s,i=0;return 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}()}class Xh{static enable(e,t){Xh.alphaSkia=t,Xh.initializeMusicFont(Xh.alphaSkia.AlphaSkiaTypeface.register(e))}static initializeMusicFont(e){Xh.musicFont=e}static registerFont(e,t){const s=Xh.alphaSkia.AlphaSkiaTypeface.register(e.buffer);t||(t=nt.withFamilyList([s.familyName],12,s.isItalic?Ye.Italic:Ye.Plain,s.isBold?qe.Bold:qe.Regular));for(const e of t.families)this.customTypeFaces.set(Xh.customTypefaceKey(e,t.isBold,t.isItalic),s);return t}static customTypefaceKey(e,t,s){return e.toLowerCase()+"_"+t+"_"+s}getTypeFace(){if(this._typeFaceCache!=this.font.toCssString(this._scale)){if(this._typeFaceIsSystem){const e={stack:[],error:void 0,hasError:!1};try{Wh(e,this._typeFace,!1)}catch(t){e.error=t,e.hasError=!0}finally{Uh(e)}}for(const t of this.font.families){var e=Xh.customTypefaceKey(t,this.font.isBold,this.font.isItalic);Xh.customTypeFaces.has(e)?(this._typeFaceIsSystem=!1,this._typeFace=Xh.customTypeFaces.get(e)):(this._typeFaceIsSystem=!0,this._typeFace=Xh.alphaSkia.AlphaSkiaTypeface.create(t,this.font.isBold,this.font.isItalic))}this._typeFaceCache=this.font.toCssString(this._scale)}return this._typeFace}constructor(){this._color=new Ee(0,0,0,0),this._lineWidth=0,this._typeFaceCache="",this._typeFaceIsSystem=!1,this._typeFace=null,this._scale=1,this.font=new nt("Arial",10,Ye.Plain),this.textAlign=L.Left,this.textBaseline=M.Top,this._initialMeasure=!0,this._canvas=new Xh.alphaSkia.AlphaSkiaCanvas,this.color=new Ee(0,0,0,255)}destroy(){const e={stack:[],error:void 0,hasError:!1};try{Wh(e,this._canvas,!1)}catch(t){e.error=t,e.hasError=!0}finally{Uh(e)}}onRenderFinished(){return null}beginRender(e,t){this._scale=this.settings.display.scale,this._canvas.beginRender(e,t,xl.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=Xh.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=Xh.alphaSkia.AlphaSkiaTextAlign.Left;switch(this.textAlign){case L.Left:i=Xh.alphaSkia.AlphaSkiaTextAlign.Left;break;case L.Center:i=Xh.alphaSkia.AlphaSkiaTextAlign.Center;break;case L.Right:i=Xh.alphaSkia.AlphaSkiaTextAlign.Right}let a=Xh.alphaSkia.AlphaSkiaTextBaseline.Top;switch(this.textBaseline){case M.Top:a=Xh.alphaSkia.AlphaSkiaTextBaseline.Top;break;case M.Middle:a=Xh.alphaSkia.AlphaSkiaTextBaseline.Middle;break;case M.Bottom:a=Xh.alphaSkia.AlphaSkiaTextBaseline.Bottom}this._canvas.fillText(e,this.getTypeFace(),this.font.size*this._scale,t*this._scale,s*this._scale,i,a)}measureText(e){return this._initialMeasure&&(this._canvas.measureText(e,this.getTypeFace(),this.font.size*this._scale),this._initialMeasure=!1),new ce(this._canvas.measureText(e,this.getTypeFace(),this.font.size*this._scale),this.font.size*this._scale*Xh.FontSizeToLineHeight)}fillMusicFontSymbol(e,t,s,i,a){i!==D.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(let e of i)e!==D.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){this._canvas.fillText(i,Xh.musicFont,xl.MusicFontSize*this._scale*s,e*this._scale,t*this._scale,a?Xh.alphaSkia.AlphaSkiaTextAlign.Center:Xh.alphaSkia.AlphaSkiaTextAlign.Left,Xh.alphaSkia.AlphaSkiaTextBaseline.Alphabetic)}beginRotate(e,t,s){this._canvas.beginRotate(e*this._scale,t*this._scale,s)}endRotate(){this._canvas.endRotate()}}Xh.musicFont=null,Xh.customTypeFaces=new Map,Xh.FontSizeToLineHeight=1.2;class Jh extends mo{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 We.Down}static getBeamDirectionForNote(e){return We.Down}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,Xs.Center)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Js.Right)}getEndX(){return this.endNoteRenderer.getNoteX(this.endNote,Js.Left)}}class Yh extends tr{constructor(e,t){super(e,t),this._tiedNoteTie=null}createTies(e){if(e.isVisible){if(!this._tiedNoteTie&&e.isTieOrigin&&e.tieDestination.isVisible){let t=new Jh(e,e.tieDestination,!1);this._tiedNoteTie=t,this.addTie(t)}if(!this._tiedNoteTie&&e.isTieDestination){let t=new Jh(e.tieOrigin,e,!0);this._tiedNoteTie=t,this.addTie(t)}}}}class qh extends ko{constructor(e,t,s){super(e,t,s)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class jh extends dn{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.restGlyph=null}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 Js.Left:break;case Js.Center:e+=s.width/2;break;case Js.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new Ea;i.note=this.container.beat.notes[0],i.noteHeadBounds=new cs,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 Xs.Top:case Xs.TopWithStem:e-=s.height/2+2;break;case Xs.Center:break;case Xs.Bottom:case Xs.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(){let e=this.renderer;const t=e.getNoteLine(),s=e.getLineY(t);if(this.container.beat.deadSlapped){const e=new Bo;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addGlyph(e)}else if(!this.container.beat.isEmpty)if(this.container.beat.isRest){const e=new qh(0,s,this.container.beat.duration);this.restGlyph=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper,this.addGlyph(e),this.beamingHelper&&this.beamingHelper.applyRest(this.container.beat,0)}else{const e=this.container.beat.graceType!==f.None,t=new Vo(0,s,this.container.beat.duration,e);this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper,this.addGlyph(t)}if(this.container.beat.dots>0){this.addGlyph(new Lo(0,0,5));for(let t=0;t<this.container.beat.dots;t++)this.addGlyph(new uo(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 Kh extends nh{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._isOnlySlash=!t.staff.showTablature&&!t.staff.showStandardNotation,this.helpers.preferredBeamDirection=We.Up}get lineSpacing(){return an.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),this.paintTuplets(e,t,s)}doLayout(){super.doLayout();let e=!1;for(let 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){return this.getLineY(0)-Vo.NoteHeadHeight/2}getFlagBottomY(e,t){return this.getLineY(0)-Vo.NoteHeadHeight/2}getBeamDirection(e){return We.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return isNaN(s)&&(s=this.getLineY(0)),s}calculateBeamYWithDirection(e,t,s){return this.getLineY(0)-this.getFlagStemSize(e.shortestDuration)}getBarLineStart(e,t){return this.getLineY(0)-Vo.NoteHeadHeight/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 Lo(0,0,5));const e=this.bar.masterBar;this.addPreBeatGlyph(new qo(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime)))}createVoiceGlyphs(e){for(const t of e.beats){let s=new Yh(t,this.getVoiceContainer(e));s.preNotes=new ln,s.onNotes=0==e.index?new jh:new dn,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){r.lineWidth=an.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}}Kh.StaffId="slash";class Qh extends xr{get staffId(){return Kh.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 Kh(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showSlash}constructor(){super()}}class $h extends mo{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 We.Up}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,Xs.Top)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Js.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,Js.Left):this.endNoteRenderer.getNoteX(this.endNote,Js.Center)}}class Zh extends dh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=We.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 We.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 We.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){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,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 tr{constructor(e,t){super(e,t),this._effectSlurs=[]}createTies(e){if(e.isVisible){if(e.isTieOrigin&&e.tieDestination.isVisible){let t=new $h(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination){let t=new $h(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new $h(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(let s of this._effectSlurs)if(s.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){let t=new Zh(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(let s of this._effectSlurs)if(s.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){let t=new Zh(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}}}}class tl extends Ka{constructor(e,t,s,i){super(e,t),this._isGrace=i,this._number=s}paint(e,t,s){const i=this.renderer.resources;s.font=this._isGrace?i.numberedNotationGraceFont:i.numberedNotationFont,s.textBaseline=M.Middle,s.textAlign=L.Left,s.fillText(this._number.toString(),e+this.x,t+this.y)}doLayout(){const e=this._isGrace?Za.GraceScale:1;this.width=tl.NoteHeadWidth*e,this.height=tl.NoteHeadHeight*e}}tl.NoteHeadHeight=17,tl.NoteHeadWidth=12;class sl extends Ka{doLayout(){this.width=14+sl.Padding,this.height=nl.BarSize}paint(e,t,s){const i=sl.Padding;s.fillRect(e+this.x,t+this.y,this.width-i,this.height)}}sl.Padding=3;class il extends ln{constructor(){super(...arguments),this.isNaturalizeAccidental=!1,this.accidental=Je.None}doLayout(){if(!this.container.beat.isRest&&!this.container.beat.isEmpty){let e=new xo;if(e.renderer=this.renderer,this.container.beat.notes.length>0){const t=this.container.beat.notes[0],s=t?t.accidentalMode:S.Default,i=Fr.getNoteValue(t);let a=Fr.computeAccidental(this.renderer.bar.masterBar.keySignature,s,i,t.hasQuarterToneOffset);if(a==Je.Natural){a=this.renderer.bar.masterBar.keySignature+7<7?Je.Sharp:Je.Flat,this.isNaturalizeAccidental=!0}if(a!==Je.None){this.accidental=a;let s=this.renderer,i=new ho(0,s.getLineY(0),a,t.beat.graceType!==f.None?Za.GraceScale*Za.GraceScale:Za.GraceScale);i.renderer=this.renderer,e.addGlyph(i),this.addGlyph(e),this.addGlyph(new Lo(0,0,4))}}}super.doLayout()}}class al extends dn{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.octaveDots=0}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 Js.Left:break;case Js.Center:e+=s.width/2;break;case Js.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new Ea;i.note=this.container.beat.notes[0],i.noteHeadBounds=new cs,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 Xs.Top:case Xs.TopWithStem:e-=s.height/2+2;break;case Xs.Center:break;case Xs.Bottom:case Xs.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(){let 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.masterBar.keySignatureType,i=this.renderer.bar.masterBar.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{let t=n.displayValue-r,o=t<0?(t%12+12)%12:t%12,h=t<0?(Math.abs(t)+12)/12|0:t/12|0;t<0&&(h*=-1),this.octaveDots=h,e.registerOctave(h);let l=(de.keySignatureIsSharp(i)||de.keySignatureIsNatural(i)?Fr.FlatNoteSteps:Fr.SharpNoteSteps)[o]+1;Fr.AccidentalNotes[o]&&!this.container.preNotes.isNaturalizeAccidental&&(a<7?l++:l--),s=l.toString()}}if(this.container.beat.deadSlapped){const e=new Bo;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addGlyph(e)}else{const e=this.container.beat.graceType!==f.None,i=new tl(0,t,s,e);this.noteHeads=i,this.addGlyph(i)}if(this.container.beat.dots>0&&this.container.beat.duration>=g.Quarter){this.addGlyph(new Lo(0,0,5));for(let t=0;t<this.container.beat.dots;t++){const t=new uo(0,e.getLineY(0),1.5);t.renderer=this.renderer,this.addGlyph(t)}}let i=0;switch(this.container.beat.duration){case g.QuadrupleWhole:i=16;break;case g.DoubleWhole:i=8;break;case g.Whole:i=4;break;case g.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 sl(0,e.getLineY(0));t.renderer=this.renderer,this.addGlyph(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 Ka{constructor(e,t,s,i){super(e,t),this._text="",this._accidental=Je.None,this._accidentalOffset=0,this._keySignature=s,this._keySignatureType=i}doLayout(){super.doLayout();const e="1 = ";let t="",s=Je.None;switch(this._keySignatureType){case C.Major:switch(this._keySignature){case P.Cb:t=" C",s=Je.Flat;break;case P.Gb:t=" G",s=Je.Flat;break;case P.Db:t=" D",s=Je.Flat;break;case P.Ab:t=" A",s=Je.Flat;break;case P.Eb:t=" E",s=Je.Flat;break;case P.Bb:t=" B",s=Je.Flat;break;case P.F:t="F";break;case P.C:t="C",s=Je.None;break;case P.G:t="G",s=Je.None;break;case P.D:t="D",s=Je.None;break;case P.A:t="A",s=Je.None;break;case P.E:t="E",s=Je.None;break;case P.B:t="B",s=Je.None;break;case P.FSharp:t=" F",s=Je.Sharp;break;case P.CSharp:t=" C",s=Je.Sharp}break;case C.Minor:switch(this._keySignature){case P.Cb:t=" a",s=Je.Flat;break;case P.Gb:t=" e",s=Je.Flat;break;case P.Db:t=" b",s=Je.Flat;break;case P.Ab:t="f",s=Je.None;break;case P.Eb:t="c",s=Je.None;break;case P.Bb:t="g",s=Je.None;break;case P.F:t="d";break;case P.C:t="a",s=Je.None;break;case P.G:t="e",s=Je.None;break;case P.D:t="b",s=Je.None;break;case P.A:t=" f",s=Je.Sharp;break;case P.E:t=" c",s=Je.Sharp;break;case P.B:t=" g",s=Je.Sharp;break;case P.FSharp:t=" d",s=Je.Sharp;break;case P.CSharp:t=" a",s=Je.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=this.renderer.resources;s.font=i.numberedNotationFont,s.textBaseline=M.Middle,s.fillText(this._text,e+this.x,t+this.y),this._accidental!=Je.None&&s.fillMusicFontSymbol(e+this.x+this._accidentalOffset,t+this.y,.7,ho.getMusicSymbol(this._accidental),!1)}}class nl extends nh{registerOctave(e){null===this.lowestOctave?(this.lowestOctave=e,this.highestOctave=e):(e<this.lowestOctave&&(this.lowestOctave=e),e>this.highestOctave&&(this.highestOctave=e))}constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.shortestDuration=g.QuadrupleWhole,this.lowestOctave=null,this.highestOctave=null,this._isOnlyNumbered=!t.staff.showSlash&&!t.staff.showTablature&&!t.staff.showStandardNotation}get lineSpacing(){return an.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),this.paintTuplets(e,t,s,!0)}doLayout(){super.doLayout();let e=!1;for(let 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){let e=de.getIndex(this.shortestDuration)-2;if(e>0){let t=(e-1)*nl.BarSpacing+nl.BarSize,s=0;const i=this.lowestOctave;null!==i&&(s=Math.abs(i)*nl.DotSpacing+nl.DotSize),this.registerOverflowBottom(t+s)}const t=this.highestOctave;if(null!==t){const e=Math.abs(t)*nl.DotSpacing+nl.DotSize;this.registerOverflowTop(e)}}}paintFlag(e,t,s,i){this.paintBar(e,t,s,i)}paintBar(e,t,s,i){const a=this.resources;for(let n=0,o=i.beats.length;n<o;n++){let o=i.beats[n],h=nl.BarSpacing,l=nl.BarSize,d=de.getIndex(o.duration)-2,c=t+this.y,u=this.getBeatX(o,zs.PreNotes)-this.beatGlyphsStart;var r=this.calculateBeamY(i,u);for(let t=0;t<d;t++){let a=0,d=0,p=0,g=c+t*h;n===i.beats.length-1?(a=u,d=this.getBeatX(o,zs.PostNotes)-this.beatGlyphsStart):(a=u,d=this.getBeatX(i.beats[n+1],zs.PreNotes)-this.beatGlyphsStart),p=g+r|0,nh.paintSingleBar(s,e+this.x+a,p,e+this.x+d,p,l)}let p=this.getBeatContainer(o).onNotes.octaveDots,g=0,m=0;p>0?(g=c+this.getLineY(0)-a.numberedNotationFont.size/1.5,m=-1*nl.DotSpacing):p<0&&(g=c+r+d*h,m=nl.DotSpacing);let f=this.getBeatX(o,zs.OnNotes)+4-this.beatGlyphsStart;p=Math.abs(p);for(let t=0;t<p;t++)s.fillCircle(e+this.x+f,g,nl.DotSize),g+=m}}getNoteLine(){return 0}get tupletOffset(){return super.tupletOffset+this.resources.numberedNotationFont.size}getFlagTopY(e,t){return this.getLineY(0)-Vo.NoteHeadHeight/2}getFlagBottomY(e,t){return this.getLineY(0)-Vo.NoteHeadHeight/2}getBeamDirection(e){return We.Down}getTupletBeamDirection(e){return We.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return 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){return this.getLineY(0)-Vo.NoteHeadHeight/2}createLinePreBeatGlyphs(){this.bar.previousBar&&this.bar.masterBar.keySignature===this.bar.previousBar.masterBar.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.masterBar.keySignature,this.bar.masterBar.keySignatureType))}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Lo(0,0,5));const e=this.bar.masterBar;this.addPreBeatGlyph(new qo(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime)))}createPostBeatGlyphs(){this._isOnlyNumbered&&super.createPostBeatGlyphs()}createVoiceGlyphs(e){for(const t of e.beats){let s=new el(t,this.getVoiceContainer(e));s.preNotes=0==e.index?new il:new ln,s.onNotes=0==e.index?new al:new dn,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){r.lineWidth=an.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}}nl.StaffId="numbered",nl.BarSpacing=an.BeamSpacing+an.BeamThickness,nl.BarSize=2,nl.DotSpacing=5,nl.DotSize=2;class ol extends xr{get staffId(){return Kh.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 nl(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showNumbered}constructor(){super()}}class hl extends gn{get notationElement(){return e.NotationElement.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ys.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 zr(0,0,"Free time",e.resources.effectFont,L.Left)}canExpand(e,t){return!0}}class ll extends Qa{constructor(){super(0,0)}doLayout(){super.doLayout(),this.height=ll.TextHeight}paint(e,t,s){const i=this.renderer,a=t+this.y,r=this.height;let n=i.bar.sustainPedals,o=0;for(;o<n.length;){let t=n[o];for(;null!=t;){const i=e+this.renderer.getRatioPositionX(t.ratioPosition);let h=0;if(t.pedalType===l.Down?(s.fillMusicFontSymbol(i,a+r,1,D.KeyboardPedalPed,!0),h=ll.TextWidth/2+ll.TextLinePadding):t.pedalType===l.Up&&(s.fillMusicFontSymbol(i,a+r,1,D.KeyboardPedalUp,!0),h=ll.StarSize/2+ll.StarLinePadding),t.nextPedalMarker)if(t.nextPedalMarker.bar===t.bar){let n=e+this.renderer.getRatioPositionX(t.nextPedalMarker.ratioPosition);switch(t.nextPedalMarker.pedalType){case l.Down:n-=ll.TextWidth/2;break;case l.Hold:break;case l.Up:n-=ll.StarSize/2}const o=i+h;n>o&&s.fillRect(o,a+r-1,n-o,1)}else{const t=e+this.x+this.width,n=i+h;s.fillRect(n,a+r-1,t-n,1)}if(0===o&&t.previousPedalMarker){const t=e+this.x,n=i-h;s.fillRect(t,a+r-1,n-t,1)}o++,null!=t.nextPedalMarker&&t.nextPedalMarker.bar!==t.bar?(t=null,o=n.length):t=t.nextPedalMarker}}}}ll.TextHeight=19,ll.TextWidth=35,ll.TextLinePadding=3,ll.StarSize=16,ll.StarLinePadding=3;class dl extends gn{get notationElement(){return e.NotationElement.EffectSustainPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ys.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&t.voice.bar.sustainPedals.length>0}createNewGlyph(e,t){return new ll}canExpand(e,t){return!0}}class cl extends gn{constructor(e,t){super(),this._type=e,this._shouldCreate=t}get notationElement(){return e.NotationElement.EffectGolpe}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ys.SingleOnBeat}shouldCreateGlyph(e,t){const s=this._shouldCreate;return t.golpe==this._type&&(!s||s(e,t))}createNewGlyph(e,t){return new Ro(0,0,!0)}canExpand(e,t){return!1}}class ul extends $a{constructor(e){super(0,0,1,ul.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case V.Open:return D.GuitarOpenPedal;case V.Closed:return D.GuitarClosePedal}return D.None}doLayout(){this.width=11,this.height=11}paint(e,t,s){super.paint(e,t+this.height,s)}}class pl extends gn{get notationElement(){return e.NotationElement.EffectWahPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ys.SingleOnBeat}shouldCreateGlyph(e,t){return t.wahPedal!==V.None}createNewGlyph(e,t){return new ul(t.wahPedal)}canExpand(e,t){return!1}}class gl extends gn{get notationElement(){return e.NotationElement.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isBarre}get sizingMode(){return Ys.GroupedOnBeat}createNewGlyph(e,t){let s="";switch(t.barreShape){case H.None:case H.Full:break;case H.Half:s+="1/2"}return s+="B "+gl.toRoman(t.barreFret),new Cn(s,!1)}static toRoman(e){let t="";if(e>0)for(var[s,i]of gl.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}}gl.RomanLetters=new Map([["L",50],["XL",40],["X",10],["IX",9],["V",5],["IV",4],["I",1]]);class ml extends $a{constructor(e){super(0,0,1,ml.getSymbol(e)),this.center=!0}doLayout(){this.width=26,this.height=18}static getSymbol(e){switch(e){case I.InvertedTurn:return D.OrnamentTurnInverted;case I.Turn:return D.OrnamentTurn;case I.UpperMordent:return D.OrnamentShortTrill;case I.LowerMordent:return D.OrnamentMordent}return D.None}paint(e,t,s){super.paint(e,t+this.height-4,s)}}class fl extends gn{get notationElement(){return e.NotationElement.EffectNoteOrnament}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ys.SingleOnBeat}shouldCreateGlyph(e,t){return t.notes.some((e=>e.ornament!==I.None))}createNewGlyph(e,t){return new ml(t.notes.find((e=>e.ornament!=I.None)).ornament)}canExpand(e,t){return!1}}class yl extends gn{get notationElement(){return e.NotationElement.EffectRasgueado}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.hasRasgueado}get sizingMode(){return Ys.GroupedOnBeat}createNewGlyph(e,t){return new Cn("rasg.")}canExpand(e,t){return!0}}class bl extends Ka{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 Sl extends Ka{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=M.Middle,s.textAlign=L.Right,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=i,s.textBaseline=a,s.textAlign=r}}class _l extends Qa{constructor(e,t,s){super(e,t),this._barBeginGlyphs=[],this._barEndGlyphs=[],this._directions=s}doLayout(){const e=this._directions;e.has(He.TargetSegnoSegno)&&this._barBeginGlyphs.push(new bl([D.Segno,D.Segno])),e.has(He.TargetSegno)&&this._barBeginGlyphs.push(new bl([D.Segno])),e.has(He.TargetDoubleCoda)&&this._barBeginGlyphs.push(new bl([D.Coda,D.Coda])),e.has(He.TargetCoda)&&this._barBeginGlyphs.push(new bl([D.Coda])),e.has(He.TargetFine)&&this._barEndGlyphs.push(new Sl("Fine")),e.has(He.JumpDaDoubleCoda)&&this._barEndGlyphs.push(new Sl("To Double Coda")),e.has(He.JumpDaCoda)&&this._barEndGlyphs.push(new Sl("To Coda")),e.has(He.JumpDalSegnoSegno)&&this._barEndGlyphs.push(new Sl("D.S.S.")),e.has(He.JumpDalSegnoSegnoAlCoda)&&this._barEndGlyphs.push(new Sl("D.S.S. al Coda")),e.has(He.JumpDalSegnoSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new Sl("D.S.S. al Double Coda")),e.has(He.JumpDalSegnoSegnoAlFine)&&this._barEndGlyphs.push(new Sl("D.S.S. al Fine")),e.has(He.JumpDalSegno)&&this._barEndGlyphs.push(new Sl("D.S.")),e.has(He.JumpDalSegnoAlCoda)&&this._barEndGlyphs.push(new Sl("D.S. al Coda")),e.has(He.JumpDalSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new Sl("D.S. al Double Coda")),e.has(He.JumpDalSegnoAlFine)&&this._barEndGlyphs.push(new Sl("D.S. al Fine")),e.has(He.JumpDaCapo)&&this._barEndGlyphs.push(new Sl("D.C.")),e.has(He.JumpDaCapoAlCoda)&&this._barEndGlyphs.push(new Sl("D.C. al Coda")),e.has(He.JumpDaCapoAlDoubleCoda)&&this._barEndGlyphs.push(new Sl("D.C. al Double Coda")),e.has(He.JumpDaCapoAlFine)&&this._barEndGlyphs.push(new Sl("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 wl extends gn{get notationElement(){return e.NotationElement.EffectDirections}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Ys.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 _l(0,0,t.voice.bar.masterBar.directions)}canExpand(e,t){return!0}}class Bl extends Qa{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*Bl.PaddingY,this._textWidth=i.width+2*Bl.PaddingX,this.height=this._textHeight+2*Bl.MarginY}paint(e,t,s){const i=this._textWidth/2|0;s.strokeRect(e+this.x-i,t+this.y+Bl.MarginY,this._textWidth,this._textHeight);const a=s.font,r=s.textBaseline,n=s.textAlign;s.font=this.renderer.resources.timerFont,s.textBaseline=M.Middle,s.textAlign=L.Center,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=a,s.textBaseline=r,s.textAlign=n}}Bl.PaddingX=2,Bl.PaddingY=2,Bl.MarginY=2;class Tl extends gn{get notationElement(){return e.NotationElement.EffectBeatTimer}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return Ys.SingleOnBeat}shouldCreateGlyph(e,t){return t.showTimer}createNewGlyph(e,t){return new Bl(t.timer??0)}canExpand(e,t){return!0}}class kl{constructor(e,t){this.vertical=e,this.createLayout=t}}class Nl{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class xl{static createStyleElement(e,t){let s=e.getElementById("alphaTabStyle");if(!s){if(!t)return void ne.error("AlphaTab","Font directory could not be detected, cannot create style element");s=e.createElement("style"),s.id="alphaTabStyle";let 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: ${xl.MusicFontSize}px;\n overflow: visible !important;\n }`;s.innerHTML=i,e.getElementsByTagName("head").item(0).appendChild(s),xl.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===xl._globalThis){try{xl._globalThis=globalThis}catch(e){}void 0===xl._globalThis&&(xl._globalThis=self),void 0===xl._globalThis&&(xl._globalThis=global),void 0===xl._globalThis&&(xl._globalThis=window),void 0===xl._globalThis&&(xl._globalThis=Function("return this")())}return this._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in xl.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in xl.globalThis}static throttle(e,t){let s=0;return()=>{xl.globalThis.clearTimeout(s),s=xl.globalThis.setTimeout(e,t)}}static detectScriptFile(){if(!xl.isRunningInWorker&&xl.globalThis.ALPHATAB_ROOT){let e=xl.globalThis.ALPHATAB_ROOT;return e=xl.ensureFullUrl(e),e=xl.appendScriptName(e),e}try{const e={};if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in xl.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="",s=xl.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("/")){let 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(!xl.isRunningInWorker&&xl.globalThis.ALPHATAB_FONT)return xl.ensureFullUrl(xl.globalThis.ALPHATAB_FONT);const e=xl.scriptFile;if(e){let t=e.lastIndexOf(String.fromCharCode(47));if(t>=0)return e.substr(0,t)+"/font/"}return null}static registerJQueryPlugin(){if(!xl.isRunningInWorker&&xl.globalThis&&"jQuery"in xl.globalThis){let e=xl.globalThis.jQuery,t=new Tr;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:Tr.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&xl.renderEngines.has(e)?xl.renderEngines.get(e):xl.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&xl.layoutEngines.has(t)?xl.layoutEngines.get(t):xl.layoutEngines.get(e.LayoutMode.Page)}static buildImporters(){return[new hs,new ni,new ti,new oi,new Vh,new st]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new Nl(!0,(()=>new Nr))),e.set("default",e.get("svg")),e.set("skia",new Nl(!1,(()=>new Xh))),xl.createPlatformSpecificRenderEngines(e),e}static enableAlphaSkia(e,t){Xh.enable(e,t)}static registerAlphaSkiaCustomFont(e,t){return Xh.registerFont(e,t)}static createPlatformSpecificRenderEngines(e){e.set("html5",new Nl(!1,(()=>new Ia)))}static createDefaultRenderers(){return[new un(xl.StaffIdBeforeSlashAlways,[new Kn,new to,new Mn,new wl,new mn,new hl,new Qn,new Tl,new yn]),new Qh,new un(xl.StaffIdBeforeScoreAlways,[new xn,new gl,new fl,new yl,new pl]),new un(xl.StaffIdBeforeScoreHideable,[new so,new Zn,new An(!0),new io,new Wn,new ao,new Un(!1),new kh,new cl(R.Finger)],((e,t)=>t.showStandardNotation)),new hh,new un(xl.StaffIdBeforeNumberedAlways,[new _n,new An(!1),new Bn,new cl(R.Thumb,((e,t)=>t.voice.bar.staff.showStandardNotation)),new dl]),new ol,new un(xl.StaffIdBeforeTabAlways,[new Ln]),new un(xl.StaffIdBeforeTabHideable,[new Zn,new io,new Wn,new ao,new Un(!0),new Xn,new kn,new En(b.Natural),new En(b.Artificial),new En(b.Pinch),new En(b.Tap),new En(b.Semi),new En(b.Feedback),new Fn,new fn,new vn,new Rn,new Hn,new On,new kh,new cl(R.Finger,((e,t)=>!t.voice.bar.staff.showStandardNotation))],((e,t)=>t.showTablature)),new Bh,new un(xl.StaffIdBeforeEndAlways,[new cl(R.Thumb,((e,t)=>!t.voice.bar.staff.showStandardNotation))])]}static createDefaultStaveProfiles(){const t=new Map,s=xl.createDefaultRenderers();t.set(e.StaveProfile.Default,s),t.set(e.StaveProfile.ScoreTab,s);const i=new Set([xl.StaffIdBeforeSlashAlways,xl.StaffIdBeforeScoreAlways,xl.StaffIdBeforeNumberedAlways,xl.StaffIdBeforeTabAlways,oh.StaffId,xl.StaffIdBeforeEndAlways]);t.set(e.StaveProfile.Score,s.filter((e=>i.has(e.staffId))));const a=new Set([xl.StaffIdBeforeSlashAlways,xl.StaffIdBeforeScoreAlways,xl.StaffIdBeforeNumberedAlways,xl.StaffIdBeforeTabAlways,wh.StaffId,xl.StaffIdBeforeEndAlways]);return t.set(e.StaveProfile.Tab,xl.createDefaultRenderers().filter((e=>{if(e instanceof Bh){const t=e;t.showTimeSignature=!0,t.showRests=!0,t.showTiedNotes=!0}return a.has(e.staffId)}))),t.set(e.StaveProfile.TabMixed,xl.createDefaultRenderers().filter((e=>{if(e instanceof Bh){const t=e;t.showTimeSignature=!1,t.showRests=!1,t.showTiedNotes=!1}return a.has(e.staffId)}))),t}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.LayoutMode.Page,new kl(!0,(e=>new oo(e)))),t.set(e.LayoutMode.Horizontal,new kl(!1,(e=>new no(e)))),t}static initializeMain(t,s){xl.isRunningInWorker||xl.isRunningInAudioWorklet||(xl.webPlatform!==e.WebPlatform.Browser&&xl.webPlatform!==e.WebPlatform.BrowserModule||(xl.registerJQueryPlugin(),xl.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in xl.globalThis||(xl.globalThis.ResizeObserver=Hh),"IntersectionObserver"in xl.globalThis||(xl.globalThis.IntersectionObserver=Gh),"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)})),xl.createWebWorker=t,xl.createAudioWorklet=s)}static get alphaTabWorker(){return this.globalThis.Worker}static get alphaTabUrl(){return this.globalThis.URL}static initializeWorker(){if(!xl.isRunningInWorker)throw new K(e.AlphaTabErrorType.General,"Not running in worker, cannot run worker initialization");Ma.init(),Ta.init(),xl.createWebWorker=t=>{throw new K(e.AlphaTabErrorType.General,"Nested workers are not supported")}}static initializeAudioWorklet(){if(!xl.isRunningInAudioWorklet)throw new K(e.AlphaTabErrorType.General,"Not running in audio worklet, cannot run worklet initialization");br.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 e.WebPlatform.NodeJs}catch(e){}try{const t={};if(t&&"string"==typeof t&&!t.startsWith("file://"))return e.WebPlatform.BrowserModule}catch(e){}return e.WebPlatform.Browser}}xl.StaffIdBeforeSlashAlways="before-slash-always",xl.StaffIdBeforeScoreAlways="before-score-always",xl.StaffIdBeforeScoreHideable="before-score-hideable",xl.StaffIdBeforeNumberedAlways="before-numbered-always",xl.StaffIdBeforeTabAlways="before-tab-always",xl.StaffIdBeforeTabHideable="before-tab-hideable",xl.StaffIdBeforeEndAlways="before-end-always",xl.MusicFontSize=34,xl.HighDpiFactor=1,xl._globalThis=void 0,xl.webPlatform=xl.detectWebPlatform(),xl.isWebPackBundled=xl.detectWebPack(),xl.isViteBundled=xl.detectVite(),xl.scriptFile=xl.detectScriptFile(),xl.fontDirectory=xl.detectFontDirectory(),xl.bravuraFontChecker=new dr(["alphaTab"]),xl.renderEngines=xl.createDefaultRenderEngines(),xl.layoutEngines=xl.createDefaultLayoutEngines(),xl.staveProfiles=xl.createDefaultStaveProfiles();class vl{constructor(){this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=e.LogLevel.Info,this.useWorkers=!0,this.includeNoteBounds=!1,this.scriptFile=xl.scriptFile,this.fontDirectory=xl.fontDirectory}}class Pl{}Pl.version="1.4.3",Pl.date="2025-04-13T21:11:16.350Z";var Cl,El=Object.freeze({__proto__:null,ScoreImporter:j,ScoreLoader:or,UnsupportedFormatError:Q});class Fl{init(e,t){this.data=e,this.settings=t}export(e,t=null){const s=Oe.withCapacity(1024);return this.init(s,t??new Ot),this.writeScore(e),s.toArray()}}!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"}(Cl||(Cl={}));class Dl{constructor(e,t,s=null){if(this.icon=Cl.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 Ll{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new ys;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 a.Normal:i|=8;break;case a.Heavy:i|=4;break;case a.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 B.Slight:s.addElement("Vibrato").innerText="Slight";break;case B.Wide:s.addElement("Vibrato").innerText="Wide"}if(t.isFingering){switch(t.leftHandFinger){case y.Thumb:s.addElement("LeftFingering").innerText="P";break;case y.IndexFinger:s.addElement("LeftFingering").innerText="I";break;case y.MiddleFinger:s.addElement("LeftFingering").innerText="M";break;case y.AnnularFinger:s.addElement("LeftFingering").innerText="A";break;case y.LittleFinger:s.addElement("LeftFingering").innerText="C"}switch(t.rightHandFinger){case y.Thumb:s.addElement("RightFingering").innerText="P";break;case y.IndexFinger:s.addElement("RightFingering").innerText="I";break;case y.MiddleFinger:s.addElement("RightFingering").innerText="M";break;case y.AnnularFinger:s.addElement("RightFingering").innerText="A";break;case y.LittleFinger:s.addElement("RightFingering").innerText="C"}}t.percussionArticulation>=0?s.addElement("InstrumentArticulation").innerText=t.percussionArticulation.toString():s.addElement("InstrumentArticulation").innerText="0",t.ornament!==I.None&&(s.addElement("Ornament").innerText=I[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!==b.None){switch(t.harmonicType){case b.Natural:this.writeSimplePropertyNode(s,"HarmonicType","HType","Natural");break;case b.Artificial:this.writeSimplePropertyNode(s,"HarmonicType","HType","Artificial");break;case b.Pinch:this.writeSimplePropertyNode(s,"HarmonicType","HType","Pinch");break;case b.Tap:this.writeSimplePropertyNode(s,"HarmonicType","HType","Tap");break;case b.Semi:this.writeSimplePropertyNode(s,"HarmonicType","HType","Semi");break;case b.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 _.IntoFromAbove:i|=32;break;case _.IntoFromBelow:i|=16}switch(t.slideOutType){case w.Shift:i|=1;break;case w.Legato:i|=2;break;case w.OutDown:i|=4;break;case w.OutUp:i|=8;break;case w.PickSlideDown:i|=64;break;case w.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=De.defaultSteps[a],o=De.defaultAccidentals[a]};switch(h(),i){case S.Default:break;case S.ForceNone:case S.ForceNatural:o="";break;case S.ForceSharp:o="#";break;case S.ForceDoubleSharp:"#"===o&&(s-=2,h()),o="x";break;case S.ForceFlat:"#"===o&&(s+=1,h()),o="b";break;case S.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);var s,i,a=t[0],r=t[t.length-1];switch(t.length){case 4:s=t[1],i=t[2];break;case 3:s=t[1],i=t[1];break;default:i=s=new se((a.offset+r.offset)/2,(a.value+r.value)/2)}this.writeSimplePropertyNode(e,"BendDestinationOffset","Float",this.toBendOffset(r.offset).toString()),this.writeSimplePropertyNode(e,"BendDestinationValue","Float",this.toBendValue(r.value).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset1","Float",this.toBendOffset(s.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset2","Float",this.toBendOffset(i.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleValue","Float",this.toBendValue(s.value).toString()),this.writeSimplePropertyNode(e,"BendOriginOffset","Float",this.toBendOffset(a.offset).toString()),this.writeSimplePropertyNode(e,"BendOriginValue","Float",this.toBendValue(a.value).toString())}toBendValue(e){return 25*e}toBendOffset(e){return e/se.MaxPosition*100}writeBeatNode(e,t,s){const i=e.addElement("Beat");if(i.attributes.set("id",t.id.toString()),i.addElement("Dynamic").innerText=m[t.dynamics],t.fade!==O.None&&(i.addElement("Fadding").innerText=O[t.fade]),t.isTremolo)switch(t.tremoloSpeed){case g.Eighth:i.addElement("Tremolo").innerText="1/2";break;case g.Sixteenth:i.addElement("Tremolo").innerText="1/4";break;case g.ThirtySecond:i.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&i.addElement("Chord").setCData(t.chordId),t.crescendo!==p.None&&(i.addElement("Hairpin").innerText=p[t.crescendo]),t.brushType){case u.ArpeggioUp:i.addElement("Arpeggio").innerText="Up";break;case u.ArpeggioDown:i.addElement("Arpeggio").innerText="Down"}switch(t.text&&i.addElement("FreeText").setCData(t.text),t.graceType){case f.OnBeat:case f.BeforeBeat:i.addElement("GraceNotes").innerText=f[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 We.Up:i.addElement("TransposedPitchStemOrientation").innerText="Upward",i.addElement("UserTransposedPitchStemOrientation").innerText="Upward";break;case We.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!==R.None&&(i.addElement("Golpe").innerText=R[t.golpe]),t.wahPedal!==V.None&&(i.addElement("Wah").innerText=V[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 W.ForceSplitToNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","2");break;case W.ForceMergeWithNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","1");break;case W.ForceSplitOnSecondaryToNext:this.writeSimpleXPropertyNode(s,"1124204552","Int","1")}}writeBeatProperties(e,t){const s=e.addElement("Properties");switch(t.brushType){case u.BrushUp:this.writeSimplePropertyNode(s,"Brush","Direction","Up");break;case u.BrushDown:this.writeSimplePropertyNode(s,"Brush","Direction","Down")}switch(t.pickStroke){case F.Up:this.writeSimplePropertyNode(s,"PickStroke","Direction","Up");break;case F.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 B.Wide:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Wide");break;case B.Slight:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Slight")}if(t.isBarre)switch(this.writeSimplePropertyNode(s,"BarreFret","Fret",t.barreFret.toString()),t.barreShape){case H.Full:this.writeSimplePropertyNode(s,"BarreString","String","0");break;case H.Half:this.writeSimplePropertyNode(s,"BarreString","String","1")}if(t.rasgueado!=G.None){let e="";switch(t.rasgueado){case G.Ii:e="ii_1";break;case G.Mi:e="mi_1";break;case G.MiiTriplet:e="mii_1";break;case G.MiiAnapaest:e="mii_2";break;case G.PmpTriplet:e="pmp_1";break;case G.PmpAnapaest:e="pmp_2";break;case G.PeiTriplet:e="pei_1";break;case G.PeiAnapaest:e="pei_2";break;case G.PaiTriplet:e="pai_1";break;case G.PaiAnapaest:e="pai_2";break;case G.AmiTriplet:e="ami_1";break;case G.AmiAnapaest:e="ami_2";break;case G.Ppp:e="ppp_1";break;case G.Amii:e="amii_1";break;case G.Amip:e="amip_1";break;case G.Eami:e="eami_1";break;case G.Eamii:e="eamii_1";break;case G.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 g.QuadrupleWhole:r="Long";break;case g.DoubleWhole:r="DoubleWhole";break;case g.Whole:r="Whole";break;case g.Half:r="Half";break;case g.Quarter:r="Quarter";break;case g.Eighth:r="Eighth";break;case g.Sixteenth:r="16th";break;case g.ThirtySecond:r="32nd";break;case g.SixtyFourth:r="64th";break;case g.OneHundredTwentyEighth:r="128th";break;case g.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");var i,a,r=t[0],n=t[t.length-1];switch(t.length){case 4:i=t[1],a=t[2];break;case 3:i=t[1],a=t[1];break;default:a=i=new se((r.offset+n.offset)/2,(r.value+n.value)/2)}s.attributes.set("destinationOffset",this.toBendOffset(n.offset).toString()),s.attributes.set("destinationValue",this.toBendValue(n.value).toString()),s.attributes.set("middleOffset1",this.toBendOffset(i.offset).toString()),s.attributes.set("middleOffset2",this.toBendOffset(a.offset).toString()),s.attributes.set("middleValue",this.toBendValue(i.value).toString()),s.attributes.set("originOffset",this.toBendOffset(r.offset).toString()),s.attributes.set("originValue",this.toBendValue(r.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=q.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",s.addElement("UseOneChannelPerString"),s.addElement("IconId").innerText=Ll.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?Ll.DrumKitProgramInfo.icon:Ll.MidiProgramInfoLookup.has(e.program)?Ll.MidiProgramInfoLookup.get(e.program).icon:Cl.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 d=t.addElement("Automation");d.addElement("Type").innerText="Sound",d.addElement("Linear").innerText="false",d.addElement("Bar").innerText=r.toString(),d.addElement("Position").innerText=o.toString(),d.addElement("Visible").innerText="true",d.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}`,n="Factory";let o=!1;for(const h of t.staves)for(const l of h.bars)for(const h of l.voices)for(const d of h.beats){const h=d.getAutomation(r.Instrument),c=0===l.index&&0===d.index;if(h){const r=c?e:`ProgramChange_${d.id}`,u=c?a:`Midi/${h.value}`,p=c?n:"User";c||o||(this.writeSoundAndAutomation(s,i,e,a,n,t.staves[0].bars[0].index,t.playbackInfo.program),o=!0),this.writeSoundAndAutomation(s,i,r,u,p,l.index,h.value,h.ratioPosition),c&&(o=!0)}}}for(const e of t.staves)for(const t of e.bars)for(const e of t.sustainPedals)if(e.pedalType!==l.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 l.Down:s.addElement("Value").innerText="0 1";break;case l.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++){let 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=[y.LittleFinger,y.AnnularFinger,y.MiddleFinger,y.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():y.IndexFinger;for(const e of i){const i=o.addElement("Position");switch(a){case y.LittleFinger:i.attributes.set("finger","Pinky");break;case y.AnnularFinger:i.attributes.set("finger","Ring");break;case y.MiddleFinger:i.attributes.set("finger","Middle");break;case y.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 d=i.addElement("Property");d.attributes.set("name","ShowFingering"),d.attributes.set("type","bool"),d.attributes.set("value",t.showFingering?"true":"false");const c=i.addElement("Chord"),u=c.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=c.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=c.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const m=c.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");let 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(pe.instrumentArticulations.values());s.addElement("Name").innerText=Ll.DrumKitProgramInfo.instrumentSetName,s.addElement("Type").innerText=Ll.DrumKitProgramInfo.instrumentSetType;let i="",r=new ps,n=new Map;const o=s.addElement("Elements");for(const t of e){{var a=o.addElement("Element");let e=t.elementType;if(n.has(e)){const t=n.get(e);e+=" "+t,n.set(e,t+1)}else n.set(e,1);i=e,a.addElement("Name").innerText=e,a.addElement("Type").innerText=t.elementType,r=a.addElement("Articulations")}const e=r.addElement("Articulation");switch(e.addElement("Name").innerText=i+" "+r.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 M.Top:e.addElement("TechniquePlacement").innerText="below";break;case M.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case M.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=Ll.MidiProgramInfoLookup.has(t.playbackInfo.program)?Ll.MidiProgramInfoLookup.get(t.playbackInfo.program):Ll.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===D.None)return"";let t=D[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");let 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!==E.NoTripletFeel&&(s.addElement("TripletFeel").innerText=E[t.tripletFeel]),t.directions&&t.directions.size>0){const e=s.addElement("Directions");for(const s of t.directions)switch(s){case He.TargetFine:e.addElement("Target").innerText="Fine";break;case He.TargetSegno:e.addElement("Target").innerText="Segno";break;case He.TargetSegnoSegno:e.addElement("Target").innerText="SegnoSegno";break;case He.TargetCoda:e.addElement("Target").innerText="Coda";break;case He.TargetDoubleCoda:e.addElement("Target").innerText="DoubleCoda";break;case He.JumpDaCapo:e.addElement("Jump").innerText="DaCapo";break;case He.JumpDaCapoAlCoda:e.addElement("Jump").innerText="DaCapoAlCoda";break;case He.JumpDaCapoAlDoubleCoda:e.addElement("Jump").innerText="DaCapoAlDoubleCoda";break;case He.JumpDaCapoAlFine:e.addElement("Jump").innerText="DaCapoAlFine";break;case He.JumpDalSegno:e.addElement("Jump").innerText="DaSegno";break;case He.JumpDalSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoAlCoda";break;case He.JumpDalSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoAlDoubleCoda";break;case He.JumpDalSegnoAlFine:e.addElement("Jump").innerText="DaSegnoAlFine";break;case He.JumpDalSegnoSegno:e.addElement("Jump").innerText="DaSegnoSegno";break;case He.JumpDalSegnoSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlCoda";break;case He.JumpDalSegnoSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlDoubleCoda";break;case He.JumpDalSegnoSegnoAlFine:e.addElement("Jump").innerText="DaSegnoSegnoAlFine";break;case He.JumpDaCoda:e.addElement("Jump").innerText="DaCoda";break;case He.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/te.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=Ge[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(" ")}}Ll.MidiProgramInfoLookup=new Map([[0,new Dl(Cl.Piano,"Acoustic Piano")],[1,new Dl(Cl.Piano,"Acoustic Piano")],[2,new Dl(Cl.Piano,"Electric Piano")],[3,new Dl(Cl.Piano,"Acoustic Piano")],[4,new Dl(Cl.Piano,"Electric Piano")],[5,new Dl(Cl.Piano,"Electric Piano")],[6,new Dl(Cl.Piano,"Harpsichord")],[7,new Dl(Cl.Piano,"Harpsichord")],[8,new Dl(Cl.PitchedIdiophone,"Celesta")],[9,new Dl(Cl.PitchedIdiophone,"Vibraphone")],[10,new Dl(Cl.PitchedIdiophone,"Vibraphone")],[11,new Dl(Cl.PitchedIdiophone,"Vibraphone")],[12,new Dl(Cl.PitchedIdiophone,"Xylophone")],[13,new Dl(Cl.PitchedIdiophone,"Xylophone")],[14,new Dl(Cl.PitchedIdiophone,"Vibraphone")],[15,new Dl(Cl.Banjo,"Banjo")],[16,new Dl(Cl.Piano,"Electric Organ")],[17,new Dl(Cl.Piano,"Electric Organ")],[18,new Dl(Cl.Piano,"Electric Organ")],[19,new Dl(Cl.Piano,"Electric Organ")],[20,new Dl(Cl.Piano,"Electric Organ")],[21,new Dl(Cl.Piano,"Electric Organ")],[22,new Dl(Cl.Woodwind,"Recorder")],[23,new Dl(Cl.Piano,"Electric Organ")],[24,new Dl(Cl.ClassicalGuitar,"Nylon Guitar")],[25,new Dl(Cl.SteelGuitar,"Steel Guitar")],[26,new Dl(Cl.SteelGuitar,"Electric Guitar")],[27,new Dl(Cl.ElectricGuitar,"Electric Guitar")],[28,new Dl(Cl.ElectricGuitar,"Electric Guitar")],[29,new Dl(Cl.ElectricGuitar,"Electric Guitar")],[30,new Dl(Cl.SteelGuitar,"Electric Guitar")],[31,new Dl(Cl.SteelGuitar,"Electric Guitar")],[32,new Dl(Cl.Bass,"Acoustic Bass")],[33,new Dl(Cl.Bass,"Electric Bass")],[34,new Dl(Cl.Bass,"Electric Bass")],[35,new Dl(Cl.Bass,"Acoustic Bass")],[36,new Dl(Cl.Bass,"Electric Bass")],[37,new Dl(Cl.Bass,"Electric Bass")],[38,new Dl(Cl.Synth,"Synth Bass")],[39,new Dl(Cl.Synth,"Synth Bass")],[40,new Dl(Cl.Strings,"Violin")],[41,new Dl(Cl.Strings,"Viola")],[42,new Dl(Cl.Strings,"Cello")],[43,new Dl(Cl.Strings,"Contrabass")],[44,new Dl(Cl.Strings,"Violin")],[45,new Dl(Cl.Strings,"Violin")],[46,new Dl(Cl.Piano,"Harp")],[47,new Dl(Cl.Membraphone,"Timpani")],[48,new Dl(Cl.Strings,"Violin")],[49,new Dl(Cl.Strings,"Violin")],[50,new Dl(Cl.Strings,"Violin")],[51,new Dl(Cl.Strings,"Violin")],[52,new Dl(Cl.Vocal,"Voice")],[53,new Dl(Cl.Vocal,"Voice")],[54,new Dl(Cl.Vocal,"Voice")],[55,new Dl(Cl.Synth,"Pad Synthesizer")],[56,new Dl(Cl.Brass,"Trumpet")],[57,new Dl(Cl.Brass,"Trombone")],[58,new Dl(Cl.Brass,"Tuba")],[59,new Dl(Cl.Brass,"Trumpet")],[60,new Dl(Cl.Brass,"French Horn")],[61,new Dl(Cl.Brass,"Trumpet")],[62,new Dl(Cl.Brass,"Trumpet")],[63,new Dl(Cl.Brass,"Trumpet")],[64,new Dl(Cl.Reed,"Saxophone")],[65,new Dl(Cl.Reed,"Saxophone")],[66,new Dl(Cl.Reed,"Saxophone")],[67,new Dl(Cl.Reed,"Saxophone")],[68,new Dl(Cl.Reed,"Oboe")],[69,new Dl(Cl.Reed,"English Horn")],[70,new Dl(Cl.Reed,"Bassoon")],[71,new Dl(Cl.Reed,"Clarinet")],[72,new Dl(Cl.Reed,"Piccolo")],[73,new Dl(Cl.Woodwind,"Flute")],[74,new Dl(Cl.Woodwind,"Recorder")],[75,new Dl(Cl.Woodwind,"Flute")],[76,new Dl(Cl.Woodwind,"Recorder")],[77,new Dl(Cl.Woodwind,"Flute")],[78,new Dl(Cl.Woodwind,"Recorder")],[79,new Dl(Cl.Woodwind,"Flute")],[80,new Dl(Cl.Synth,"Lead Synthesizer")],[81,new Dl(Cl.Synth,"Lead Synthesizer")],[82,new Dl(Cl.Synth,"Lead Synthesizer")],[83,new Dl(Cl.Synth,"Lead Synthesizer")],[84,new Dl(Cl.Synth,"Lead Synthesizer")],[85,new Dl(Cl.Synth,"Lead Synthesizer")],[86,new Dl(Cl.Synth,"Lead Synthesizer")],[87,new Dl(Cl.Synth,"Lead Synthesizer")],[88,new Dl(Cl.Synth,"Pad Synthesizer")],[89,new Dl(Cl.Synth,"Pad Synthesizer")],[90,new Dl(Cl.Synth,"Pad Synthesizer")],[91,new Dl(Cl.Synth,"Pad Synthesizer")],[92,new Dl(Cl.Synth,"Pad Synthesizer")],[93,new Dl(Cl.Synth,"Pad Synthesizer")],[94,new Dl(Cl.Synth,"Pad Synthesizer")],[95,new Dl(Cl.Synth,"Pad Synthesizer")],[96,new Dl(Cl.Fx,"Pad Synthesizer")],[97,new Dl(Cl.Fx,"Pad Synthesizer")],[98,new Dl(Cl.Fx,"Pad Synthesizer")],[99,new Dl(Cl.Fx,"Pad Synthesizer")],[100,new Dl(Cl.Fx,"Lead Synthesizer")],[101,new Dl(Cl.Fx,"Lead Synthesizer")],[102,new Dl(Cl.Fx,"Lead Synthesizer")],[103,new Dl(Cl.Fx,"Trumpet")],[104,new Dl(Cl.ElectricGuitar,"Banjo")],[105,new Dl(Cl.Banjo,"Banjo")],[106,new Dl(Cl.Ukulele,"Ukulele")],[107,new Dl(Cl.Banjo,"Banjo")],[108,new Dl(Cl.PitchedIdiophone,"Xylophone")],[109,new Dl(Cl.Reed,"Bassoon")],[110,new Dl(Cl.Strings,"Violin")],[111,new Dl(Cl.Woodwind,"Flute")],[112,new Dl(Cl.PitchedIdiophone,"Xylophone")],[113,new Dl(Cl.Idiophone,"Celesta")],[114,new Dl(Cl.PitchedIdiophone,"Vibraphone")],[115,new Dl(Cl.Idiophone,"Xylophone")],[116,new Dl(Cl.Membraphone,"Xylophone")],[117,new Dl(Cl.Membraphone,"Xylophone")],[118,new Dl(Cl.Membraphone,"Xylophone")],[119,new Dl(Cl.Idiophone,"Celesta")],[120,new Dl(Cl.Fx,"Steel Guitar")],[121,new Dl(Cl.Fx,"Recorder")],[122,new Dl(Cl.Fx,"Recorder")],[123,new Dl(Cl.Fx,"Recorder")],[124,new Dl(Cl.Fx,"Recorder")],[125,new Dl(Cl.Fx,"Recorder")],[126,new Dl(Cl.Fx,"Recorder")],[127,new Dl(Cl.Fx,"Timpani")]]),Ll.DrumKitProgramInfo=new Dl(Cl.PercussionKit,"Drums","drumKit");class Ml{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=Ml.CrcInit,this.reset()}update(e,t,s){for(let i=0;i<s;i++)this._checkValue=Ml.Crc32Lookup[255&(this._checkValue^e[t+i])]^this._checkValue>>>8}reset(){this._checkValue=Ml.CrcInit}}Ml.Crc32Lookup=Ml.buildCrc32Lookup(),Ml.CrcInit=4294967295;class Il{}Il.MAX_WBITS=15,Il.WSIZE=1<<Il.MAX_WBITS,Il.WMASK=Il.WSIZE-1,Il.MIN_MATCH=3,Il.MAX_MATCH=258,Il.DEFAULT_MEM_LEVEL=8,Il.PENDING_BUF_SIZE=1<<Il.DEFAULT_MEM_LEVEL+8,Il.HASH_BITS=Il.DEFAULT_MEM_LEVEL+7,Il.HASH_SIZE=1<<Il.HASH_BITS,Il.HASH_SHIFT=(Il.HASH_BITS+Il.MIN_MATCH-1)/Il.MIN_MATCH,Il.HASH_MASK=Il.HASH_SIZE-1,Il.MIN_LOOKAHEAD=Il.MAX_MATCH+Il.MIN_MATCH+1,Il.MAX_DIST=Il.WSIZE-Il.MIN_LOOKAHEAD;class Al{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(){let e=this.freqs.length,t=new Int32Array(e),s=0,i=0;for(let a=0;a<e;a++){let e=this.freqs[a];if(0!==e){let r=s++;for(;r>0;){let 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;){let e=i<2?++i:0;t[s++]=e}this.numCodes=Math.max(i+1,this.minNumCodes);let a=s,r=new Int32Array(4*s-2),n=new Int32Array(2*s-1),o=a;for(let e=0;e<s;e++){let s=t[e];r[2*e]=s,r[2*e+1]=-1,n[e]=this.freqs[s]<<8,t[e]=e}do{let e=t[0],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;let d=t[0];i=o++,r[2*i]=e,r[2*i+1]=d;let c=Math.min(255&n[e],255&n[d]);for(l=n[e]+n[d]-c+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);let t=Math.floor(e.length/2),s=Math.floor((t+1)/2),i=0;for(let e=0;e<this.maxLength;e++)this.bitLengthCounts[e]=0;let 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{let 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;){let 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;let 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[Al.Repeat3To6]++:i<=10?e.freqs[Al.Repeat3To10]++:e.freqs[Al.Repeat11To138]++}}setStaticCodes(e,t){this.codes=e,this.length=t}buildCodes(){let e=new Int32Array(this.maxLength),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++){let s=this.length[t];s>0&&(this.codes[t]=Rl.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;let 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(Al.Repeat3To6),this.huffman.pending.writeBits(i-3,2)):i<=10?(e.writeSymbol(Al.Repeat3To10),this.huffman.pending.writeBits(i-3,3)):(e.writeSymbol(Al.Repeat11To138),this.huffman.pending.writeBits(i-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}Al.Repeat3To6=16,Al.Repeat3To10=17,Al.Repeat11To138=18;class Rl{static staticInit(){let e=0;for(;e<144;)Rl.staticLCodes[e]=Rl.bitReverse(48+e<<8),Rl.staticLLength[e++]=8;for(;e<256;)Rl.staticLCodes[e]=Rl.bitReverse(256+e<<7),Rl.staticLLength[e++]=9;for(;e<280;)Rl.staticLCodes[e]=Rl.bitReverse(-256+e<<9),Rl.staticLLength[e++]=7;for(;e<Rl.LITERAL_NUM;)Rl.staticLCodes[e]=Rl.bitReverse(-88+e<<8),Rl.staticLLength[e++]=8;for(e=0;e<Rl.DIST_NUM;e++)Rl.staticDCodes[e]=Rl.bitReverse(e<<11),Rl.staticDLength[e]=5}static bitReverse(e){return Rl.bit4Reverse[15&e]<<12|Rl.bit4Reverse[e>>4&15]<<8|Rl.bit4Reverse[e>>8&15]<<4|Rl.bit4Reverse[e>>12]}constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new Al(this,Rl.LITERAL_NUM,257,15),this.distTree=new Al(this,Rl.DIST_NUM,1,15),this.blTree=new Al(this,Rl.BITLEN_NUM,4,7),this.d_buf=new Int16Array(Rl.BUFSIZE),this.l_buf=new Uint8Array(Rl.BUFSIZE)}isFull(){return this.last_lit>=Rl.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((Rl.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[Rl.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[Rl.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<Rl.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*Rl.staticLLength[e];for(let e=0;e<Rl.DIST_NUM;e++)n+=this.distTree.freqs[e]*Rl.staticDLength[e];r>=n&&(r=n),t>=0&&s+4<r>>3?this.flushStoredBlock(e,t,s,i):r==n?(this.pending.writeBits((Rl.STATIC_TREES<<1)+(i?1:0),3),this.literalTree.setStaticCodes(Rl.staticLCodes,Rl.staticLLength),this.distTree.setStaticCodes(Rl.staticDCodes,Rl.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((Rl.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[Rl.BL_ORDER[t]],3);this.literalTree.writeTree(this.blTree),this.distTree.writeTree(this.blTree)}compressBlock(){for(let e=0;e<this.last_lit;e++){let t=255&this.l_buf[e],s=this.d_buf[e];if(0!=s--){let e=Rl.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);let a=Rl.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(Rl.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;let s=Rl.Lcode(t-3);this.literalTree.freqs[s]++,s>=265&&s<285&&(this.extra_bits+=Math.floor((s-261)/4));let i=Rl.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}}Rl.BUFSIZE=1<<Il.DEFAULT_MEM_LEVEL+6,Rl.LITERAL_NUM=286,Rl.STORED_BLOCK=0,Rl.STATIC_TREES=1,Rl.DYN_TREES=2,Rl.DIST_NUM=30,Rl.staticLCodes=new Int16Array(Rl.LITERAL_NUM),Rl.staticLLength=new Uint8Array(Rl.LITERAL_NUM),Rl.staticDCodes=new Int16Array(Rl.DIST_NUM),Rl.staticDLength=new Uint8Array(Rl.DIST_NUM),Rl.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Rl.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),Rl.BITLEN_NUM=19,Rl.EOF_SYMBOL=256,Rl.staticInit();class Ol{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 Rl(e),this.inputCrc=new Ml,this.window=new Uint8Array(2*Il.WSIZE),this.head=new Int16Array(Il.HASH_SIZE),this.prev=new Int16Array(Il.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=Il.MIN_MATCH-1;for(let e=0;e<Il.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<Il.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<Il.HASH_SHIFT^this.window[this.strstart+1]}needsInput(){return this.inputEnd==this.inputOff}setInput(e,t,s){let i=t+s;this.inputBuf=e,this.inputOff=t,this.inputEnd=i}deflate(e,t){let s;do{this.fillWindow();let i=e&&this.inputOff==this.inputEnd;s=this.deflateSlow(i,t)}while(this.pending.isFlushed&&s);return s}deflateSlow(e,t){if(this.lookahead<Il.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=Il.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*Il.WSIZE-Il.MIN_LOOKAHEAD&&this.slideWindow();let e=this.matchStart,s=this.matchLen;if(this.lookahead>=Il.MIN_MATCH){let e=this.insertString();0!=e&&this.strstart-e<=Il.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen==Il.MIN_MATCH&&this.strstart-this.matchStart>Ol.TooFar&&(this.matchLen=Il.MIN_MATCH-1)}if(s>=Il.MIN_MATCH&&this.matchLen<=s){this.huffman.tallyDist(this.strstart-1-e,s),s-=2;do{this.strstart++,this.lookahead--,this.lookahead>=Il.MIN_MATCH&&this.insertString()}while(--s>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=Il.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--;let 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,i=s+Math.min(Il.MAX_MATCH,this.lookahead)-1,a=Math.max(s-Il.MAX_DIST,0),r=this.window,n=this.prev,o=this.maxChain,h=Math.min(this.niceLength,this.lookahead);if(this.matchLen=Math.max(this.matchLen,Il.MIN_MATCH-1),s+this.matchLen>i)return!1;let l=r[s+this.matchLen-1],d=r[s+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,s=this.strstart,r[t+this.matchLen]==d&&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],d=r[s]}e=65535&n[e&Il.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=Il.MIN_MATCH}insertString(){let e,t=(this.insertHashIndex<<Il.HASH_SHIFT^this.window[this.strstart+(Il.MIN_MATCH-1)])&Il.HASH_MASK;return e=this.head[t],this.prev[this.strstart&Il.WMASK]=e,this.head[t]=this.strstart,this.insertHashIndex=t,65535&e}fillWindow(){if(this.strstart>=Il.WSIZE+Il.MAX_DIST&&this.slideWindow(),this.lookahead<Il.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*Il.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>=Il.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(Il.WSIZE,Il.WSIZE+Il.WSIZE),0),this.matchStart-=Il.WSIZE,this.strstart-=Il.WSIZE,this.blockStart-=Il.WSIZE;for(let e=0;e<Il.HASH_SIZE;++e){let t=65535&this.head[e];this.head[e]=t>=Il.WSIZE?t-Il.WSIZE:0}for(let e=0;e<Il.WSIZE;e++){let t=65535&this.prev[e];this.prev[e]=t>=Il.WSIZE?t-Il.WSIZE:0}}}Ol.TooFar=4096;class Vl{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 Hl{get inputCrc(){return this._engine.inputCrc.value}constructor(){this._state=0,this._pending=new Vl(Il.PENDING_BUF_SIZE),this._engine=new Ol(this._pending),this.reset()}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state==Hl.FinishedState&&this._pending.isFlushed}reset(){this._state=Hl.BusyState,this._pending.reset(),this._engine.reset()}setInput(e,t,s){this._engine.setInput(e,t,s)}deflate(e,t,s){let i=s;for(;;){let a=this._pending.flush(e,t,s);if(t+=a,0==(s-=a)||this._state==Hl.FinishedState)break;if(!this._engine.deflate(!!(this._state&Hl.IsFlushing),!!(this._state&Hl.IsFinishing)))switch(this._state){case Hl.BusyState:return i-s;case Hl.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=Hl.BusyState;break;case Hl.FinishingState:this._pending.alignToByte(),this._state=Hl.FinishedState}}return i-s}finish(){this._state|=Hl.IsFlushing|Hl.IsFinishing}}Hl.IsFlushing=4,Hl.IsFinishing=8,Hl.BusyState=16,Hl.FlushingState=20,Hl.FinishingState=28,Hl.FinishedState=30;class Gl{constructor(e,t,s,i,a){this.entry=e,this.crc32=t,this.localHeaderOffset=s,this.compressionMode=i,this.compressedSize=a}}class Wl{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new Hl,this._data=e}writeEntry(e){const t=Ks.CompressionMethodDeflate,s=Oe.empty(),i=this.compress(s,e.data,t),a=s.toArray(),r=new Gl(e,i,this._data.bytesWritten,t,s.length);this._centralDirectoryHeaders.push(r),Re.writeInt32LE(this._data,Ks.LocalFileHeaderSignature),Re.writeUInt16LE(this._data,10),Re.writeUInt16LE(this._data,2048),Re.writeUInt16LE(this._data,t),Re.writeInt16LE(this._data,0),Re.writeInt16LE(this._data,0),Re.writeInt32LE(this._data,i),Re.writeInt32LE(this._data,a.length),Re.writeInt32LE(this._data,e.data.length),Re.writeInt16LE(this._data,e.fullName.length),Re.writeInt16LE(this._data,0);const n=Re.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,s){if(s!=Ks.CompressionMethodDeflate){const s=new Ml;return s.update(t,0,t.length),e.write(t,0,t.length),s.value}{let s=new Uint8Array(512);for(this._deflater.reset(),this._deflater.setInput(t,0,t.length);!this._deflater.isNeedingInput;){const t=this._deflater.deflate(s,0,s.length);if(t<=0)break;e.write(s,0,t)}for(this._deflater.finish();!this._deflater.isFinished;){const t=this._deflater.deflate(s,0,s.length);if(t<=0)break;e.write(s,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){Re.writeInt32LE(this._data,Ks.EndOfCentralDirSignature),Re.writeInt16LE(this._data,0),Re.writeInt16LE(this._data,0),Re.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Re.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Re.writeInt32LE(this._data,t-e),Re.writeInt32LE(this._data,e),Re.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){Re.writeInt32LE(this._data,Ks.CentralFileHeaderSignature),Re.writeUInt16LE(this._data,10),Re.writeUInt16LE(this._data,10),Re.writeUInt16LE(this._data,2048),Re.writeUInt16LE(this._data,e.compressionMode),Re.writeInt16LE(this._data,0),Re.writeInt16LE(this._data,0),Re.writeInt32LE(this._data,e.crc32),Re.writeInt32LE(this._data,e.compressedSize),Re.writeInt32LE(this._data,e.entry.data.length),Re.writeInt16LE(this._data,e.entry.fullName.length),Re.writeInt16LE(this._data,0),Re.writeInt16LE(this._data,0),Re.writeInt16LE(this._data,0),Re.writeInt16LE(this._data,0),Re.writeInt32LE(this._data,0),Re.writeInt32LE(this._data,e.localHeaderOffset);const t=Re.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}var zl=Object.freeze({__proto__:null,Gp7Exporter:class extends Fl{get name(){return"Guitar Pro 7"}constructor(){super()}writeScore(e){ne.debug(this.name,"Writing data entries");const t=(new Ll).writeXml(e),s=us.writeForScore(e),i=Ts.writeForScore(e),a=ei.writeForScore(e);ne.debug(this.name,"Writing ZIP entries");let r=new Wl(this.data);r.writeEntry(new Ks("VERSION",Re.stringToBytes("7.0"))),r.writeEntry(new Ks("Content/",new Uint8Array(0))),r.writeEntry(new Ks("Content/BinaryStylesheet",s)),r.writeEntry(new Ks("Content/PartConfiguration",i)),r.writeEntry(new Ks("Content/LayoutConfiguration",a)),r.writeEntry(new Ks("Content/score.gpif",Re.stringToBytes(t))),r.end()}},ScoreExporter:Fl}),Ul=Object.freeze({__proto__:null,AlphaSynthMidiFileHandler:Aa,AlphaTabMetronomeEvent:ut,AlphaTabRestEvent:pt,BeatTickLookup:Ha,ControlChangeEvent:yt,get ControllerType(){return Os},EndOfTrackEvent:Bt,MasterBarTickLookup:Wa,MidiEvent:lt,get MidiEventType(){return Ke},MidiFile:ht,get MidiFileFormat(){return je},MidiFileGenerator:qa,MidiTickLookup:Ua,MidiTickLookupFindBeatResult:za,NoteBendEvent:wt,NoteEvent:gt,NoteOffEvent:ft,NoteOnEvent:mt,PitchBendEvent:_t,ProgramChangeEvent:bt,TempoChangeEvent:St,TimeSignatureEvent:dt}),Xl=Object.freeze({__proto__:null,BarBounds:va,BeatBounds:Pa,Bounds:cs,BoundsLookup:Da,MasterBarBounds:Ca,NoteBounds:Ea,RenderFinishedEventArgs:xa,ScoreRenderer:La,StaffSystemBounds:Fa}),Jl=Object.freeze({__proto__:null,ActiveBeatsChangedEventArgs:ir,AlphaSynth:wa,AlphaSynthAudioWorkletOutput:Sr,AlphaSynthScriptProcessorOutput:pr,AlphaSynthWebAudioOutputBase:ur,AlphaSynthWebWorkerApi:mr,CircularSampleBuffer:cr,MidiEventsPlayedEventArgs:Sa,PlaybackRange:ja,PlaybackRangeChangedEventArgs:_a,get PlayerState(){return Fs},PlayerStateChangedEventArgs:ui,PositionChangedEventArgs:pi}),Yl=Object.freeze({__proto__:null});xl.isRunningInWorker?xl.initializeWorker():xl.isRunningInAudioWorklet?xl.initializeAudioWorklet():xl.initializeMain((t=>{if(xl.webPlatform==e.WebPlatform.NodeJs)throw new K(e.AlphaTabErrorType.General,"Workers not yet supported in Node.js");if(xl.webPlatform==e.WebPlatform.BrowserModule||xl.isWebPackBundled||xl.isViteBundled){ne.debug("AlphaTab","Creating webworker");try{return new xl.alphaTabWorker(new URL("./alphaTab.worker",{}),{type:"module"})}catch(e){ne.debug("AlphaTab","ESM webworker construction with direct URL failed",e)}let e="";try{e=new xl.alphaTabUrl("./alphaTab.worker",{});const t=`import ${JSON.stringify(e)}`,s=new Blob([t],{type:"application/javascript"});return new Worker(URL.createObjectURL(s),{type:"module"})}catch(t){ne.debug("AlphaTab","ESM webworker construction with blob import failed",e,t)}try{if(!t.core.scriptFile)throw new Error("Could not detect alphaTab script file");e=t.core.scriptFile;const s=`import ${JSON.stringify(t.core.scriptFile)}`,i=new Blob([s],{type:"application/javascript"});return new Worker(URL.createObjectURL(i),{type:"module"})}catch(e){ne.debug("AlphaTab","ESM webworker construction with blob import failed",t.core.scriptFile,e)}}if(!t.core.scriptFile)throw new K(e.AlphaTabErrorType.General,"Could not detect alphaTab script file, cannot initialize renderer");try{ne.debug("AlphaTab","Creating Blob worker");const e=`importScripts('${t.core.scriptFile}')`,s=new Blob([e],{type:"application/javascript"});return new Worker(URL.createObjectURL(s))}catch(e){return ne.warning("Rendering","Could not create inline worker, fallback to normal worker"),new Worker(t.core.scriptFile)}}),((t,s)=>{if(xl.webPlatform==e.WebPlatform.NodeJs)throw new K(e.AlphaTabErrorType.General,"Audio Worklets not yet supported in Node.js");if(xl.webPlatform==e.WebPlatform.BrowserModule||xl.isWebPackBundled||xl.isViteBundled){ne.debug("AlphaTab","Creating Module worklet");return t.audioWorklet.addModule(new URL("./alphaTab.worklet",{}))}return ne.debug("AlphaTab","Creating Script worklet"),t.audioWorklet.addModule(s.core.scriptFile)})),e.AlphaTabApi=Br,e.AlphaTabError=K,e.ConsoleLogger=re,e.CoreSettings=vl,e.DisplaySettings=kt,e.Environment=xl,e.FileLoadError=nr,e.FormatError=Ce,e.ImporterSettings=Nt,e.LayoutEngineFactory=kl,e.Logger=ne,e.NotationSettings=ie,e.PlayerSettings=Pt,e.ProgressEventArgs=gr,e.RenderEngineFactory=Nl,e.RenderingResources=Tt,e.ResizeEventArgs=sr,e.Settings=Ot,e.VibratoPlaybackSettings=xt,e.exporter=zl,e.importer=El,e.json=Yl,e.meta=Pl,e.midi=Ul,e.model=os,e.platform=qn,e.rendering=Xl,e.synth=Jl}));
|
|
2
2
|
//# sourceMappingURL=alphaTab.min.js.map
|