@coderline/alphatab 1.3.0 → 1.3.1
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 +3 -3
- package/dist/alphaTab.js +3 -3
- 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.d.ts +24 -5
- package/dist/alphaTab.webpack.js +424 -225
- package/dist/alphaTab.webpack.mjs +423 -224
- package/dist/alphaTab.worker.mjs +1 -1
- package/dist/alphaTab.worklet.mjs +1 -1
- package/package.json +4 -2
- package/dist/alphaTab.core.min.mjs.map +0 -1
- package/dist/alphaTab.core.mjs.map +0 -1
- package/dist/alphaTab.js.map +0 -1
- package/dist/alphaTab.min.js.map +0 -1
- package/dist/alphaTab.min.mjs.map +0 -1
- package/dist/alphaTab.mjs.map +0 -1
- package/dist/alphaTab.vite.js.map +0 -1
- package/dist/alphaTab.vite.mjs.map +0 -1
- package/dist/alphaTab.webpack.js.map +0 -1
- package/dist/alphaTab.webpack.mjs.map +0 -1
- package/dist/alphaTab.worker.min.mjs.map +0 -1
- package/dist/alphaTab.worker.mjs.map +0 -1
- package/dist/alphaTab.worklet.min.mjs.map +0 -1
- package/dist/alphaTab.worklet.mjs.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e,t,s,i,a,r,n,o,h,l,c,d,u,p,g,f,m,y,b,S,_,w,B,T,k,v,x,N,P,C,E,F,L,M,I,D;!function(e){e[e.Page=0]="Page",e[e.Horizontal=1]="Horizontal"}(e||(e={})),function(e){e[e.Default=0]="Default",e[e.ScoreTab=1]="ScoreTab",e[e.Score=2]="Score",e[e.Tab=3]="Tab",e[e.TabMixed=4]="TabMixed"}(t||(t={}));class A{static getValue(e){return A._values||(A._values=new Map),e=e.toLowerCase().replaceAll(" ",""),A._values.has(e)?A._values.get(e):0}static isPiano(e){return e<=7||e>=16&&e<=23}static isGuitar(e){return e>=24&&e<=39||105===e||43===e}}A._values=new Map([["acousticgrandpiano",0],["brightacousticpiano",1],["electricgrandpiano",2],["honkytonkpiano",3],["electricpiano1",4],["electricpiano2",5],["harpsichord",6],["clavinet",7],["celesta",8],["glockenspiel",9],["musicbox",10],["vibraphone",11],["marimba",12],["xylophone",13],["tubularbells",14],["dulcimer",15],["drawbarorgan",16],["percussiveorgan",17],["rockorgan",18],["churchorgan",19],["reedorgan",20],["accordion",21],["harmonica",22],["tangoaccordion",23],["acousticguitarnylon",24],["acousticguitarsteel",25],["electricguitarjazz",26],["electricguitarclean",27],["electricguitarmuted",28],["overdrivenguitar",29],["distortionguitar",30],["guitarharmonics",31],["acousticbass",32],["electricbassfinger",33],["electricbasspick",34],["fretlessbass",35],["slapbass1",36],["slapbass2",37],["synthbass1",38],["synthbass2",39],["violin",40],["viola",41],["cello",42],["contrabass",43],["tremolostrings",44],["pizzicatostrings",45],["orchestralharp",46],["timpani",47],["stringensemble1",48],["stringensemble2",49],["synthstrings1",50],["synthstrings2",51],["choiraahs",52],["voiceoohs",53],["synthvoice",54],["orchestrahit",55],["trumpet",56],["trombone",57],["tuba",58],["mutedtrumpet",59],["frenchhorn",60],["brasssection",61],["synthbrass1",62],["synthbrass2",63],["sopranosax",64],["altosax",65],["tenorsax",66],["baritonesax",67],["oboe",68],["englishhorn",69],["bassoon",70],["clarinet",71],["piccolo",72],["flute",73],["recorder",74],["panflute",75],["blownbottle",76],["shakuhachi",77],["whistle",78],["ocarina",79],["lead1square",80],["lead2sawtooth",81],["lead3calliope",82],["lead4chiff",83],["lead5charang",84],["lead6voice",85],["lead7fifths",86],["lead8bassandlead",87],["pad1newage",88],["pad2warm",89],["pad3polysynth",90],["pad4choir",91],["pad5bowed",92],["pad6metallic",93],["pad7halo",94],["pad8sweep",95],["fx1rain",96],["fx2soundtrack",97],["fx3crystal",98],["fx4atmosphere",99],["fx5brightness",100],["fx6goblins",101],["fx7echoes",102],["fx8scifi",103],["sitar",104],["banjo",105],["shamisen",106],["koto",107],["kalimba",108],["bagpipe",109],["fiddle",110],["shanai",111],["tinklebell",112],["agogo",113],["steeldrums",114],["woodblock",115],["taikodrum",116],["melodictom",117],["synthdrum",118],["reversecymbal",119],["guitarfretnoise",120],["breathnoise",121],["seashore",122],["birdtweet",123],["telephonering",124],["helicopter",125],["applause",126],["gunshot",127]]);class R{init(e,t){this.data=e,this.settings=t}}!function(e){e[e.General=0]="General",e[e.Format=1]="Format",e[e.AlphaTex=2]="AlphaTex"}(s||(s={}));class O extends Error{constructor(e,t="",s){super(t??"",{cause:s}),this.type=e,this.inner=s??null,Object.setPrototypeOf(this,O.prototype)}}class G extends O{constructor(e=null,t=null){super(s.Format,e??"Unsupported format"),this.inner=t,Object.setPrototypeOf(this,G.prototype)}}!function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy"}(i||(i={})),function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(a||(a={}));class V{constructor(){this.isLinear=!1,this.type=a.Tempo,this.value=0,this.ratioPosition=0,this.text=""}static buildTempoAutomation(e,t,s,i){(i<1||i>5)&&(i=2);let r=new Float32Array([1,.5,1,1.5,2,3]),n=new V;return n.type=a.Tempo,n.isLinear=e,n.ratioPosition=t,n.value=s*r[i],n}static buildInstrumentAutomation(e,t,s){let i=new V;return i.type=a.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"}(r||(r={})),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"}(n||(n={})),function(e){e[e.None=0]="None",e[e.Simple=1]="Simple",e[e.FirstOfDouble=2]="FirstOfDouble",e[e.SecondOfDouble=3]="SecondOfDouble"}(o||(o={}));class H{constructor(){this.id=H._globalBarId++,this.index=0,this.nextBar=null,this.previousBar=null,this.clef=r.G2,this.clefOttava=n.Regular,this.voices=[],this.simileMark=o.None,this.isMultiVoice=!1,this.displayScale=1,this.displayWidth=-1}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)}}calculateDuration(){let e=0;for(let t of this.voices){let s=t.calculateDuration();s>e&&(e=s)}return e}}H._globalBarId=0;class W{static ticksToMillis(e,t){return e*(6e4/(t*W.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*W.QuarterTime))|0}static toTicks(e){return W.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),W.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 W.MinVelocity+e*W.VelocityIncrement}}W.QuarterTime=960,W.MinVelocity=15,W.VelocityIncrement=16;class z{constructor(e=0,t=0){this.offset=e,this.value=t}}z.MaxPosition=60,z.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(h||(h={})),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"}(l||(l={})),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"}(c||(c={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(d||(d={})),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"}(u||(u={})),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"}(p||(p={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(g||(g={})),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"}(f||(f={})),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"}(m||(m={})),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"}(y||(y={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(b||(b={})),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"}(S||(S={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(_||(_={})),function(e){e[e.Hidden=0]="Hidden",e[e.ShowWithBeams=1]="ShowWithBeams",e[e.ShowWithBars=2]="ShowWithBars"}(w||(w={})),function(e){e[e.ScoreDefault=0]="ScoreDefault",e[e.ScoreForcePiano=1]="ScoreForcePiano",e[e.SingleNoteEffectBand=2]="SingleNoteEffectBand",e[e.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano"}(B||(B={})),function(e){e[e.GuitarPro=0]="GuitarPro",e[e.SongBook=1]="SongBook"}(T||(T={})),function(e){e[e.ScoreTitle=0]="ScoreTitle",e[e.ScoreSubTitle=1]="ScoreSubTitle",e[e.ScoreArtist=2]="ScoreArtist",e[e.ScoreAlbum=3]="ScoreAlbum",e[e.ScoreWords=4]="ScoreWords",e[e.ScoreMusic=5]="ScoreMusic",e[e.ScoreWordsAndMusic=6]="ScoreWordsAndMusic",e[e.ScoreCopyright=7]="ScoreCopyright",e[e.GuitarTuning=8]="GuitarTuning",e[e.TrackNames=9]="TrackNames",e[e.ChordDiagrams=10]="ChordDiagrams",e[e.ParenthesisOnTiedBends=11]="ParenthesisOnTiedBends",e[e.TabNotesOnTiedBends=12]="TabNotesOnTiedBends",e[e.ZerosOnDiveWhammys=13]="ZerosOnDiveWhammys",e[e.EffectAlternateEndings=14]="EffectAlternateEndings",e[e.EffectCapo=15]="EffectCapo",e[e.EffectChordNames=16]="EffectChordNames",e[e.EffectCrescendo=17]="EffectCrescendo",e[e.EffectDynamics=18]="EffectDynamics",e[e.EffectFadeIn=19]="EffectFadeIn",e[e.EffectFermata=20]="EffectFermata",e[e.EffectFingering=21]="EffectFingering",e[e.EffectHarmonics=22]="EffectHarmonics",e[e.EffectLetRing=23]="EffectLetRing",e[e.EffectLyrics=24]="EffectLyrics",e[e.EffectMarker=25]="EffectMarker",e[e.EffectOttavia=26]="EffectOttavia",e[e.EffectPalmMute=27]="EffectPalmMute",e[e.EffectPickSlide=28]="EffectPickSlide",e[e.EffectPickStroke=29]="EffectPickStroke",e[e.EffectSlightBeatVibrato=30]="EffectSlightBeatVibrato",e[e.EffectSlightNoteVibrato=31]="EffectSlightNoteVibrato",e[e.EffectTap=32]="EffectTap",e[e.EffectTempo=33]="EffectTempo",e[e.EffectText=34]="EffectText",e[e.EffectTrill=35]="EffectTrill",e[e.EffectTripletFeel=36]="EffectTripletFeel",e[e.EffectWhammyBar=37]="EffectWhammyBar",e[e.EffectWideBeatVibrato=38]="EffectWideBeatVibrato",e[e.EffectWideNoteVibrato=39]="EffectWideNoteVibrato",e[e.EffectLeftHandTap=40]="EffectLeftHandTap"}(k||(k={}));class U{constructor(){this.notationMode=T.GuitarPro,this.fingeringMode=B.ScoreDefault,this.elements=new Map,this.rhythmMode=w.Hidden,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):!U.defaultElements.has(e)||U.defaultElements.get(e)}}U.defaultElements=new Map([[k.ZerosOnDiveWhammys,!1]]);class X{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}!function(e){e[e.None=0]="None",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warning=3]="Warning",e[e.Error=4]="Error"}(v||(v={}));class Y{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...s){console.debug(Y.format(e,t),...s)}warning(e,t,...s){console.warn(Y.format(e,t),...s)}info(e,t,...s){console.info(Y.format(e,t),...s)}error(e,t,...s){console.error(Y.format(e,t),...s)}}Y.logLevel=v.Info;class q{static shouldLog(e){return q.logLevel!==v.None&&e>=q.logLevel}static debug(e,t,...s){q.shouldLog(v.Debug)&&q.log.debug(e,t,...s)}static warning(e,t,...s){q.shouldLog(v.Warning)&&q.log.warning(e,t,...s)}static info(e,t,...s){q.shouldLog(v.Info)&&q.log.info(e,t,...s)}static error(e,t,...s){q.shouldLog(v.Error)&&q.log.error(e,t,...s)}}q.logLevel=v.Info,q.log=new Y;class J{constructor(){this.note=null,this.noteValue=0,this.octave=0}get realValue(){return 12*this.octave+this.noteValue}}class j{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(e,t,s,i){if(e.notation.fingeringMode===B.ScoreForcePiano||e.notation.fingeringMode===B.SingleNoteEffectBandForcePiano||A.isPiano(t.voice.bar.staff.track.playbackInfo.program))switch(s){case f.Unknown:case f.NoOrDead:return null;case f.Thumb:return"1";case f.IndexFinger:return"2";case f.MiddleFinger:return"3";case f.AnnularFinger:return"4";case f.LittleFinger:return"5";default:return null}if(i)switch(s){case f.Unknown:case f.NoOrDead:return"0";case f.Thumb:return"T";case f.IndexFinger:return"1";case f.MiddleFinger:return"2";case f.AnnularFinger:return"3";case f.LittleFinger:return"4";default:return null}switch(s){case f.Unknown:case f.NoOrDead:return null;case f.Thumb:return"p";case f.IndexFinger:return"i";case f.MiddleFinger:return"m";case f.AnnularFinger:return"a";case f.LittleFinger:return"c";default:return null}}static isTuning(e){return!!j.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(!(a>=65&&a<=90||a>=97&&a<=122||35===a))return null;t+=String.fromCharCode(a)}}if(!s||!t)return null;let i=new J;return i.octave=parseInt(s)+1,i.note=t.toLowerCase(),i.noteValue=j.getToneForText(i.note),i}static getTuningForText(e){let t=j.parseTuning(e);return t?t.realValue:-1}static getToneForText(e){switch(e.toLowerCase()){case"c":default:return 0;case"c#":case"db":return 1;case"d":return 2;case"d#":case"eb":return 3;case"e":return 4;case"f":return 5;case"f#":case"gb":return 6;case"g":return 7;case"g#":case"ab":return 8;case"a":return 9;case"a#":case"bb":return 10;case"b":return 11}}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}}!function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(x||(x={})),function(e){e[e.None=-1]="None",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.NoteQuarterUp=57813]="NoteQuarterUp",e[e.NoteEighthUp=57815]="NoteEighthUp",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.ArticAccentAbove=58528]="ArticAccentAbove",e[e.ArticStaccatoAbove=58530]="ArticStaccatoAbove",e[e.ArticMarcatoAbove=58540]="ArticMarcatoAbove",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.StringsDownBow=58896]="StringsDownBow",e[e.StringsUpBow=58898]="StringsUpBow",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.GuitarGolpe=59458]="GuitarGolpe",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"}(N||(N={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(P||(P={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(C||(C={}));class Q{constructor(e="",t=0,s=0,i=N.None,a=N.None,r=N.None,n=N.None,o=C.Middle){this.elementType=e,this.outputMidiNumber=s,this.staffLine=t,this.noteHeadDefault=i,this.noteHeadHalf=a!==N.None?a:i,this.noteHeadWhole=r!==N.None?r:i,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case u.Whole:return this.noteHeadWhole;case u.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class ${static articulationFromElementVariation(e,t){return e<$.gp6ElementAndVariationToArticulation.length?(t>=$.gp6ElementAndVariationToArticulation.length&&(t=0),$.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]:$.getArticulationByValue(t)}static getElementAndVariation(e){const t=$.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<$.gp6ElementAndVariationToArticulation.length;e++){const s=$.gp6ElementAndVariationToArticulation[e];for(let i=0;i<s.length;i++){const a=$.getArticulationByValue(s[i]);if(a?.outputMidiNumber===t.outputMidiNumber)return[e,i]}}return[-1,-1]}static getArticulationByValue(e){return $.instrumentArticulations.has(e)?$.instrumentArticulations.get(e):null}}$.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]],$.instrumentArticulations=new Map([[38,new Q("snare",3,38,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[37,new Q("snare",3,37,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[91,new Q("snare",3,38,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite)],[42,new Q("hiHat",-1,42,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[92,new Q("hiHat",-1,46,N.NoteheadCircleSlash,N.NoteheadCircleSlash,N.NoteheadCircleSlash)],[46,new Q("hiHat",-1,46,N.NoteheadCircleX,N.NoteheadCircleX,N.NoteheadCircleX)],[44,new Q("hiHat",9,44,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[35,new Q("kickDrum",8,35,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[36,new Q("kickDrum",7,36,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[50,new Q("tom",1,50,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[48,new Q("tom",2,48,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[47,new Q("tom",4,47,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[45,new Q("tom",5,45,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[43,new Q("tom",6,43,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[93,new Q("ride",0,51,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.PictEdgeOfCymbal,C.Bottom)],[51,new Q("ride",0,51,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[53,new Q("ride",0,53,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite)],[94,new Q("ride",0,51,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.ArticStaccatoAbove,C.Top)],[55,new Q("splash",-2,55,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[95,new Q("splash",-2,55,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.ArticStaccatoAbove,C.Bottom)],[52,new Q("china",-3,52,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat)],[96,new Q("china",-3,52,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat)],[49,new Q("crash",-2,49,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX)],[97,new Q("crash",-2,49,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX,N.ArticStaccatoAbove,C.Bottom)],[57,new Q("crash",-1,57,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX)],[98,new Q("crash",-1,57,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX,N.ArticStaccatoAbove,C.Bottom)],[99,new Q("cowbell",1,56,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpHalf,N.NoteheadTriangleUpWhole)],[100,new Q("cowbell",1,56,N.NoteheadXBlack,N.NoteheadXHalf,N.NoteheadXWhole)],[56,new Q("cowbell",0,56,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpHalf,N.NoteheadTriangleUpWhole)],[101,new Q("cowbell",0,56,N.NoteheadXBlack,N.NoteheadXHalf,N.NoteheadXWhole)],[102,new Q("cowbell",-1,56,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpHalf,N.NoteheadTriangleUpWhole)],[103,new Q("cowbell",-1,56,N.NoteheadXBlack,N.NoteheadXHalf,N.NoteheadXWhole)],[77,new Q("woodblock",-9,77,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack)],[76,new Q("woodblock",-10,76,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack)],[60,new Q("bongo",-4,60,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[104,new Q("bongo",-5,60,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,C.Middle)],[105,new Q("bongo",-6,60,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[61,new Q("bongo",-7,61,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[106,new Q("bongo",-8,61,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,C.Middle)],[107,new Q("bongo",-16,61,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[66,new Q("timbale",10,66,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[65,new Q("timbale",9,65,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[68,new Q("agogo",12,68,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[67,new Q("agogo",11,67,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[64,new Q("conga",17,64,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[108,new Q("conga",16,64,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[109,new Q("conga",15,64,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,C.Middle)],[63,new Q("conga",14,63,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[110,new Q("conga",13,63,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[62,new Q("conga",19,62,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,C.Middle)],[72,new Q("whistle",-11,72,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[71,new Q("whistle",-17,71,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[73,new Q("guiro",38,73,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[74,new Q("guiro",37,74,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[86,new Q("surdo",36,86,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[87,new Q("surdo",35,87,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadParenthesis,C.Middle)],[54,new Q("tambourine",3,54,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack)],[111,new Q("tambourine",2,54,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.StringsUpBow,C.Bottom)],[112,new Q("tambourine",1,54,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.StringsDownBow,C.Bottom)],[113,new Q("tambourine",-7,54,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[79,new Q("cuica",30,79,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[78,new Q("cuica",29,78,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[58,new Q("vibraslap",28,58,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[81,new Q("triangle",27,81,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[80,new Q("triangle",26,80,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadParenthesis,C.Middle)],[114,new Q("grancassa",25,43,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[115,new Q("piatti",18,49,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[116,new Q("piatti",24,49,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[69,new Q("cabasa",23,69,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[117,new Q("cabasa",22,69,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,C.Bottom)],[85,new Q("castanets",21,85,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[75,new Q("claves",20,75,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[70,new Q("maraca",-12,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[118,new Q("maraca",-13,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,C.Bottom)],[119,new Q("maraca",-14,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[120,new Q("maraca",-15,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,C.Bottom)],[82,new Q("shaker",-23,54,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[122,new Q("shaker",-24,54,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,C.Bottom)],[84,new Q("bellTree",-18,53,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[123,new Q("bellTree",-19,53,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,C.Bottom)],[83,new Q("jingleBell",-20,53,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[124,new Q("unpitched",-21,62,N.NoteheadNull,N.NoteheadNull,N.NoteheadNull,N.GuitarGolpe,C.Top)],[125,new Q("unpitched",-22,62,N.NoteheadNull,N.NoteheadNull,N.NoteheadNull,N.GuitarGolpe,C.Bottom)],[39,new Q("handClap",3,39,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[40,new Q("snare",3,40,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[31,new Q("snare",3,40,N.NoteheadSlashedBlack2,N.NoteheadSlashedBlack2,N.NoteheadSlashedBlack2)],[41,new Q("tom",5,41,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[59,new Q("ride",2,59,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.PictEdgeOfCymbal,C.Bottom)],[126,new Q("ride",2,59,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[127,new Q("ride",2,59,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite)],[29,new Q("ride",2,59,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.ArticStaccatoAbove,C.Top)],[30,new Q("crash",-3,49,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[33,new Q("snare",3,37,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[34,new Q("snare",3,38,N.NoteheadBlack,N.NoteheadBlack,N.NoteheadBlack)]]);class K{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1}}class Z{constructor(){this.id=Z.GlobalNoteId++,this.index=0,this.accentuated=i.None,this.bendType=l.None,this.bendStyle=h.Default,this.bendOrigin=null,this.isContinuedBend=!1,this.bendPoints=null,this.maxBendPoint=null,this.fret=-1,this.string=-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=m.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=b.None,this.slideOutType=S.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=_.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=f.Unknown,this.rightHandFinger=f.Unknown,this.isFingering=!1,this.trillValue=-1,this.trillSpeed=u.ThirtySecond,this.durationPercent=1,this.accidentalMode=y.Default,this.dynamics=p.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this._noteIdBag=null}get hasBend(){return null!==this.bendPoints&&this.bendType!==l.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?$.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?$.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==m.None}get isTieOrigin(){return null!==this.tieDestination}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+Z.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===m.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===m.None||!this.isStringed)return 0;let e=this.harmonicValue;return j.isAlmostEqualTo(e,2.4)?36:j.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!==m.Natural&&this.harmonicType!==m.None&&(e-=this.harmonicPitch),this.beat.ottava){case n._15ma:e-=24;break;case n._8va:e-=12;break;case n.Regular:break;case n._8vb:e+=12;break;case n._15mb:e+=24}switch(this.beat.voice.bar.clefOttava){case n._15ma:e-=24;break;case n._8va:e-=12;break;case n.Regular:break;case n._8vb:e+=12;break;case n._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===l.None&&(this.bendType=l.Custom)}finish(e,t=null){let s=new X((()=>Z.nextNoteOnSameLine(this))),i=e&&e.notation.notationMode===T.SongBook;if(this.isTieDestination&&(this.chain(t),i&&this.tieOrigin&&this.tieOrigin.isLetRing&&(this.isLetRing=!0)),this.isLetRing&&(s.value&&s.value.isLetRing?this.letRingDestination=s.value:this.letRingDestination=this,i&&this.isTieDestination&&!this.tieOrigin.hasBend&&(this.isVisible=!1)),this.isPalmMute&&(s.value&&s.value.isPalmMute?this.palmMuteDestination=s.value:this.palmMuteDestination=this),this.isHammerPullOrigin){let e=Z.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case S.Shift:case S.Legato:this.slideTarget=s.value,this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=S.None}let a=null;this.isHammerPullOrigin&&this.hammerPullDestination?a=this.hammerPullDestination:this.slideOutType===S.Legato&&this.slideTarget&&(a=this.slideTarget),a&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===x.None?(this.effectSlurOrigin.effectSlurDestination=a,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=a,this.effectSlurDestination.effectSlurOrigin=this));const r=this.bendPoints;if(null!=r&&r.length>0&&this.bendType===l.Custom){let e=this.isTieDestination&&this.tieOrigin.hasBend;if(this.isContinuedBend=e,4===r.length){let t=r[0],s=r[1],i=r[2],a=r[3];s.value===i.value?a.value>t.value?s.value>a.value?this.bendType=l.BendRelease:!e&&t.value>0?(this.bendType=l.PrebendBend,r.splice(2,1),r.splice(1,1)):(this.bendType=l.Bend,r.splice(2,1),r.splice(1,1)):a.value<t.value?e?(this.bendType=l.Release,r.splice(2,1),r.splice(1,1)):(this.bendType=l.PrebendRelease,r.splice(2,1),r.splice(1,1)):s.value>t.value?this.bendType=l.BendRelease:t.value>0&&!e?(this.bendType=l.Prebend,r.splice(2,1),r.splice(1,1)):(this.bendType=l.Hold,r.splice(2,1),r.splice(1,1)):q.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===r.length){let t=r[0],s=r[1];s.value>t.value?!e&&t.value>0?this.bendType=l.PrebendBend:this.bendType=l.Bend:s.value<t.value?this.bendType=e?l.Release:l.PrebendRelease:this.bendType=l.Hold}}else null!==r&&0!==r.length||(this.bendType=l.None);this.initialBendValue>0&&(this.accidentalMode=y.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+Z.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+Z.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-Z.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(Z.NoteIdLookupKey)?t=e.get(Z.NoteIdLookupKey):(t=new Map,e.set(Z.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??Z.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 K),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new K),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new K),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new K),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new K),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new K),this._noteIdBag.hammerPullDestinationNoteId=t,!0}return!1}}Z.GlobalNoteId=0,Z.MaxOffsetForSameLineSearch=3,Z.NoteIdLookupKey="NoteIdLookup";class ee{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!==g.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 ee.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}ee.HalfTicks=1920,ee.QuarterTicks=960,ee.EighthTicks=480,ee.SixteenthTicks=240,ee.ThirtySecondTicks=120,ee.SixtyFourthTicks=60,ee.OneHundredTwentyEighthTicks=30,ee.TwoHundredFiftySixthTicks=15,ee.AllTicks=[ee.HalfTicks,ee.QuarterTicks,ee.EighthTicks,ee.SixteenthTicks,ee.ThirtySecondTicks,ee.SixtyFourthTicks,ee.OneHundredTwentyEighthTicks,ee.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"}(E||(E={}));class te{static clone(e){const t=new z;return t.offset=e.offset,t.value=e.value,t}}class se{static clone(e){const t=new Z;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(te.clone(s))}return t.fret=e.fret,t.string=e.string,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.isFingering=e.isFingering,t.trillValue=e.trillValue,t.trillSpeed=e.trillSpeed,t.durationPercent=e.durationPercent,t.accidentalMode=e.accidentalMode,t.dynamics=e.dynamics,t}}class ie{static clone(e){const t=new V;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class ae{static clone(e){const t=new ne;t.index=e.index,t.notes=[];for(const s of e.notes)t.addNote(se.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(ie.clone(s));if(t.dots=e.dots,t.fadeIn=e.fadeIn,t.lyrics=e.lyrics?e.lyrics.slice():null,t.hasRasgueado=e.hasRasgueado,t.pop=e.pop,t.slap=e.slap,t.tap=e.tap,t.text=e.text,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(te.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.dynamics=e.dynamics,t.invertBeamDirection=e.invertBeamDirection,t.preferredBeamDirection=e.preferredBeamDirection,t.isEffectSlurOrigin=e.isEffectSlurOrigin,t.beamingMode=e.beamingMode,t}}class re{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.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext"}(F||(F={}));class ne{constructor(){this.id=ne._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=h.Default,this.ottava=n.Regular,this.fermata=null,this.isLegatoOrigin=!1,this.minNote=null,this.maxNote=null,this.maxStringNote=null,this.minStringNote=null,this.duration=u.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fadeIn=!1,this.lyrics=null,this.hasRasgueado=!1,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.brushType=c.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=E.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=_.None,this.chordId=null,this.graceType=g.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=x.None,this.tremoloSpeed=null,this.crescendo=d.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.dynamics=p.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=F.Auto}get isLastOfVoice(){return this.index===this.voice.beats.length-1}get isLegatoDestination(){return!!this.previousBeat&&this.previousBeat.isLegatoOrigin}get isRest(){return this.isEmpty||0===this.notes.length}get isFullBarRest(){return this.isRest&&1===this.voice.beats.length&&this.duration===u.Whole}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==E.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}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===E.None&&(this.whammyBarType=E.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=W.toTicks(this.duration);return 2===this.dots?e=W.applyDot(e,!0):1===this.dots&&(e=W.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=W.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){let e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case g.BeforeBeat:case g.OnBeat:switch(this.duration){case u.Sixteenth:this.playbackDuration=W.toTicks(u.SixtyFourth);break;case u.ThirtySecond:this.playbackDuration=W.toTicks(u.OneHundredTwentyEighth);break;default:this.playbackDuration=W.toTicks(u.ThirtySecond)}this.displayDuration=0;break;case g.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;let t=this.previousBeat;t&&t.graceType===g.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){let e=this.previousBeat,t=e?e.tupletGroup:null;(this.hasTuplet||this.graceType!==g.None&&t)&&(e&&t&&t.check(this)||(t=new ee(this.voice),t.check(this)),this.tupletGroup=t)}finish(e,t=null){switch(null===this.getAutomation(a.Instrument)&&0===this.index&&0===this.voice.index&&0===this.voice.bar.index&&0===this.voice.bar.staff.index&&this.automations.push(V.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case g.OnBeat:case g.BeforeBeat:let e=this.graceGroup.beats.length;this.duration=1===e?u.Eighth:2===e?u.Sixteenth:u.ThirtySecond}let s=e?e.notation.notationMode:T.GuitarPro,i="grad"===this.text||"grad."===this.text;i&&s===T.SongBook&&(this.text="");let r=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let n=0,o=!1;for(let a=0,c=this.notes.length;a<c;a++){let c=this.notes[a];if(c.dynamics=this.dynamics,c.finish(e,t),c.isLetRing&&(this.isLetRing=!0),c.isPalmMute&&(this.isPalmMute=!0),s===T.SongBook&&c.hasBend&&this.graceType!==g.BendGrace){if(!c.isTieOrigin)switch(c.bendType){case l.Bend:case l.PrebendRelease:case l.PrebendBend:r=!0}i||c.bendStyle===h.Gradual?(i=!0,c.bendStyle=h.Gradual,r=!1):c.bendStyle=h.Fast}c.isVisible&&(n++,(!this.minNote||c.realValue<this.minNote.realValue)&&(this.minNote=c),(!this.maxNote||c.realValue>this.maxNote.realValue)&&(this.maxNote=c),(!this.minStringNote||c.string<this.minStringNote.string)&&(this.minStringNote=c),(!this.maxStringNote||c.string>this.maxStringNote.string)&&(this.maxStringNote=c),c.hasEffectSlur&&(o=!0))}if(o&&(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===n&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&e&&e.notation.notationMode===T.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 c=this.whammyBarPoints;if(null!==c&&c.length>0&&this.whammyBarType===E.Custom){s===T.SongBook&&(this.whammyStyle=i?h.Gradual:h.Fast);let e=!!this.previousBeat&&this.previousBeat.hasWhammyBar;if(this.isContinuedWhammy=e,4===c.length){let t=c[0],i=c[1],a=c[2],r=c[3];i.value===a.value&&(t.value<i.value&&i.value<r.value||t.value>i.value&&i.value>r.value?(0===t.value||e?this.whammyBarType=E.Dive:this.whammyBarType=E.PrediveDive,c.splice(2,1),c.splice(1,1)):t.value>i.value&&i.value<r.value||t.value<i.value&&i.value>r.value?(this.whammyBarType=E.Dip,i.offset!==a.offset&&s!==T.SongBook||c.splice(2,1)):t.value===i.value&&i.value===r.value&&(0===t.value||e?this.whammyBarType=E.Hold:this.whammyBarType=E.Predive,c.splice(2,1),c.splice(1,1)))}}if(this.updateDurations(),r){let e=ae.clone(this);e.id=ne._globalBeatId++,e.pickStroke=x.None;for(let t=0,s=e.notes.length;t<s;t++){let s=e.notes[t],i=this.notes[t];if(s.bendType=l.None,s.maxBendPoint=null,s.bendPoints=null,s.bendStyle=h.Default,s.id=Z.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=Z.findTieOrigin(i);if(e&&e.hasBend){s.bendType=l.Hold;let e=i.bendPoints[i.bendPoints.length-1];s.addBendPoint(new z(0,e.value)),s.addBendPoint(new z(z.MaxPosition,e.value))}}s.isTieDestination=!0}this.graceType=g.BendGrace,this.graceGroup=new re,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new re,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)}}ne._globalBeatId=0;class oe{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.Cb=-7]="Cb",e[e.Gb=-6]="Gb",e[e.Db=-5]="Db",e[e.Ab=-4]="Ab",e[e.Eb=-3]="Eb",e[e.Bb=-2]="Bb",e[e.F=-1]="F",e[e.C=0]="C",e[e.G=1]="G",e[e.D=2]="D",e[e.A=3]="A",e[e.E=4]="E",e[e.B=5]="B",e[e.FSharp=6]="FSharp",e[e.CSharp=7]="CSharp"}(L||(L={})),function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.Text=2]="Text",e[e.Comment=3]="Comment",e[e.Dash=4]="Dash"}(M||(M={}));class he{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=M.Begin,r=M.Begin,n=!1,o=0;for(;t<e.length;){let s=e.charCodeAt(t);switch(a){case M.IgnoreSpaces:switch(s){case he.CharCodeLF:case he.CharCodeCR:case he.CharCodeTab:break;case he.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case M.Begin:if(s!==he.CharCodeBrackedOpen){o=t,a=M.Text;continue}a=M.Comment;break;case M.Comment:if(s===he.CharCodeBrackedClose)a=M.Begin;break;case M.Text:switch(s){case he.CharCodeDash:a=M.Dash;break;case he.CharCodeCR:case he.CharCodeLF:case he.CharCodeSpace:let s=e.substr(o,t-o);this.addChunk(s,i),a=M.IgnoreSpaces,r=M.Begin}break;case M.Dash:if(s!==he.CharCodeDash){let s=e.substr(o,t-o);this.addChunk(s,i),n=!0,a=M.IgnoreSpaces,r=M.Begin;continue}}t+=1}a===M.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}}he.CharCodeLF=10,he.CharCodeTab=9,he.CharCodeCR=13,he.CharCodeSpace=32,he.CharCodeBrackedClose=93,he.CharCodeBrackedOpen=91,he.CharCodeDash=45,function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(I||(I={})),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"}(D||(D={}));class le{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=L.C,this.keySignatureType=I.Major,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.tripletFeel=D.NoTripletFeel,this.section=null,this.tempoAutomation=null,this.fermata=null,this.start=0,this.isAnacrusis=!1,this.displayScale=1,this.displayWidth=-1}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}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*W.valueToTicks(this.timeSignatureDenominator)}addFermata(e,t){let s=this.fermata;null===s&&(s=new Map,this.fermata=s),s.set(e,t)}getFermata(e){const t=this.fermata;return null===t?null:t.has(e.playbackStart)?t.get(e.playbackStart):null}}le.MaxAlternateEndings=8;class ce{constructor(){this.hideDynamics=!1}}class de{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 ue{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 ce}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 de,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new de,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 ge extends O{constructor(e){super(s.Format,e),Object.setPrototypeOf(this,ge.prototype)}}class fe{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="#"+j.toHexString(this.r,2)+j.toHexString(this.g,2)+j.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 fe(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){switch(typeof e){case"number":{const t=new fe(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 fe(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16));if(5===t.length)return new fe(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 fe(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16));if(9===t.length)return new fe(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 ge("No values specified for rgb/rgba function");const i=t.substring(e+1,s).split(",");if(3===i.length)return new fe(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]));if(4===i.length)return new fe(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]),255*parseFloat(i[3]))}return null}}throw new ge("Unsupported format for color")}static toJson(e){return e.raw}}fe.BlackRgb="#000000";class me{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 ye{static getTextForTuning(e,t){let s=ye.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 ye._defaultTunings.has(e)?ye._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return ye._sevenStrings;case 6:return ye._sixStrings;case 5:return ye._fiveStrings;case 4:return ye._fourStrings}return[]}static initialize(){ye._defaultTunings.set(7,new ye("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),ye._sevenStrings.push(ye._defaultTunings.get(7)),ye._defaultTunings.set(6,new ye("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),ye._sixStrings.push(ye._defaultTunings.get(6)),ye._sixStrings.push(new ye("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),ye._sixStrings.push(new ye("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),ye._sixStrings.push(new ye("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),ye._sixStrings.push(new ye("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),ye._sixStrings.push(new ye("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),ye._sixStrings.push(new ye("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),ye._sixStrings.push(new ye("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),ye._sixStrings.push(new ye("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),ye._sixStrings.push(new ye("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),ye._sixStrings.push(new ye("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),ye._sixStrings.push(new ye("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),ye._sixStrings.push(new ye("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),ye._sixStrings.push(new ye("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),ye._sixStrings.push(new ye("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),ye._sixStrings.push(new ye("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),ye._sixStrings.push(new ye("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),ye._sixStrings.push(new ye("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),ye._sixStrings.push(new ye("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),ye._sixStrings.push(new ye("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),ye._sixStrings.push(new ye("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),ye._sixStrings.push(new ye("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),ye._sixStrings.push(new ye("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),ye._defaultTunings.set(5,new ye("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),ye._fiveStrings.push(ye._defaultTunings.get(5)),ye._fiveStrings.push(new ye("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),ye._fiveStrings.push(new ye("Banjo Open D Tuning",[62,57,54,50,69],!1)),ye._fiveStrings.push(new ye("Banjo Open G Tuning",[62,59,55,50,67],!1)),ye._fiveStrings.push(new ye("Banjo G Minor Tuning",[62,58,55,50,67],!1)),ye._fiveStrings.push(new ye("Banjo G Modal Tuning",[62,57,55,50,67],!1)),ye._defaultTunings.set(4,new ye("Bass Standard Tuning",[43,38,33,28],!0)),ye._fourStrings.push(ye._defaultTunings.get(4)),ye._fourStrings.push(new ye("Bass Tune down ½ step",[42,37,32,27],!1)),ye._fourStrings.push(new ye("Bass Tune down 1 step",[41,36,31,26],!1)),ye._fourStrings.push(new ye("Bass Tune down 2 step",[39,34,29,24],!1)),ye._fourStrings.push(new ye("Bass Dropped D Tuning",[43,38,33,26],!1)),ye._fourStrings.push(new ye("Ukulele C Tuning",[45,40,36,43],!1)),ye._fourStrings.push(new ye("Ukulele G Tuning",[52,47,43,38],!1)),ye._fourStrings.push(new ye("Mandolin Standard Tuning",[64,57,50,43],!1)),ye._fourStrings.push(new ye("Mandolin or Violin Tuning",[76,69,62,55],!1)),ye._fourStrings.push(new ye("Viola Tuning",[69,62,55,48],!1)),ye._fourStrings.push(new ye("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){let t=ye.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=ye.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}ye._sevenStrings=[],ye._sixStrings=[],ye._fiveStrings=[],ye._fourStrings=[],ye._defaultTunings=new Map,ye.defaultAccidentals=["","#","","#","","","#","","#","","#",""],ye.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],ye.initialize();class be{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new ye("",[],!1),this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=5}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)}}class Se{constructor(){this.index=0,this.staves=[],this.playbackInfo=new me,this.color=new fe(200,0,0,255),this.name="",this.shortName="",this.defaultSystemsLayout=3,this.systemsLayout=[],this.percussionArticulations=[]}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new be)}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>Se.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,Se.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)}}}}}Se.ShortNameMaxLength=10;let _e=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===g.None?(i.graceGroup=s,s&&(s.isComplete=!0),s=null):(s||(s=new re),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===g.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==g.BendGrace){let s=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case g.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 g.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}};_e._globalBarId=0;class we{static float64ToBytes(e){return we._dataView.setFloat64(0,e,!0),this._conversionByteArray}static bytesToFloat64(e){throw we._conversionByteArray.set(e,0),we._dataView.getFloat64(0,!0)}static uint16ToInt16(e){return we._dataView.setUint16(0,e,!0),we._dataView.getInt16(0,!0)}static int16ToUint32(e){return we._dataView.setInt16(0,e,!0),we._dataView.getUint32(0,!0)}static int32ToUint16(e){return we._dataView.setInt32(0,e,!0),we._dataView.getUint16(0,!0)}static int32ToInt16(e){return we._dataView.setInt32(0,e,!0),we._dataView.getInt16(0,!0)}static int32ToUint32(e){return we._dataView.setInt32(0,e,!0),we._dataView.getUint32(0,!0)}static uint8ToInt8(e){return we._dataView.setUint8(0,e),we._dataView.getInt8(0)}}we._conversionBuffer=new ArrayBuffer(8),we._conversionByteArray=new Uint8Array(we._conversionBuffer),we._dataView=new DataView(we._conversionBuffer);class Be{static readInt32BE(e){return e.readByte()<<24|e.readByte()<<16|e.readByte()<<8|e.readByte()}static readInt32LE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|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 we.int32ToUint16(s<<8|t)}static readInt16LE(e){let t=e.readByte(),s=e.readByte();return we.int32ToInt16(s<<8|t)}static readUInt32BE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte(),a=e.readByte();return we.int32ToUint32(t<<24|s<<16|i<<8|a)}static readUInt16BE(e){let t=e.readByte(),s=e.readByte();return we.int32ToInt16(t<<8|s)}static readInt16BE(e){let t=e.readByte(),s=e.readByte();return we.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),Be.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 we.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){let s=Be.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)}}class Te{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return Te.withCapacity(0)}static withCapacity(e){let t=new Te;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){let t=new Te;return t._buffer=e,t.length=e.length,t}static fromString(e){let t=Be.stringToBytes(e);return Te.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)}}var ke,ve,xe,Ne,Pe,Ce,Ee,Fe,Le,Me,Ie,De,Ae,Re,Oe,Ge,Ve,He,We,ze,Ue,Xe,Ye,qe,Je,je,Qe,$e,Ke,Ze;!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"}(ke||(ke={}));class et extends O{constructor(e,t,i,a,r,n,o,h=null){super(s.AlphaTex,e),this.position=t,this.line=i,this.col=a,this.nonTerm=r??"",this.expected=n??ke.No,this.symbol=o??ke.No,this.symbolData=h,Object.setPrototypeOf(this,et.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 ${ke[a]} found a ${ke[r]}`,null!==n&&(o+=`: '${n}'`)):o+=`, invalid value: '${n}'`,new et(o,e,t,s,i,a,r,n)}static errorMessage(e,t,s,i){return new et(e=`MalFormed AlphaTex: @${t} (line ${s}, col ${i}): ${e}`,t,s,i,null,null,null,null)}}class tt extends R{constructor(){super(),this._trackChannel=0,this._input="",this._ch=tt.Eof,this._curChPos=0,this._line=1,this._col=0,this._lastValidSpot=[0,1,0],this._sy=ke.No,this._syData="",this._allowNegatives=!1,this._allowFloat=!1,this._allowTuning=!1,this._currentDuration=u.QuadrupleWhole,this._currentDynamics=p.PPP,this._currentTuplet=0,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=Te.empty(),this._input=e,this.settings=t}readScore(){try{if(this.data.length>0&&(this._input=Be.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this.createDefaultScore(),this._curChPos=0,this._line=1,this._col=0,this.saveValidSpot(),this._currentDuration=u.Quarter,this._currentDynamics=p.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===ke.LowerThan)throw new G("Unknown start sign '<' (meant to import as XML?)");if(this._sy===ke.Eof)throw new G("Unexpected end of file");const e=this.metaData(),t=this.bars();if(!e&&!t)throw new G("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);return this._score}catch(e){throw e instanceof et?new G(e.message,e):e}}consolidate(){for(let e of this._score.tracks)for(let t of e.staves)for(;t.bars.length<this._score.masterBars.length;){let e=this.newBar(t),s=new ne;s.isEmpty=!0,e.voices[0].addBeat(s)}}error(e,t,s=!0){let i,a=!1;s?(i=this._sy,i!==ke.String&&i!==ke.Number&&i!==ke.MetaCommand||(a=!0)):i=t;let r=et.symbolError(this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2],e,t,i,a?this._syData:null);throw this.logErrors&&q.error(this.name,r.message),r}errorMessage(e){let t=et.errorMessage(e,this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2]);throw this.logErrors&&q.error(this.name,t.message),t}createDefaultScore(){this._score=new ue,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new Se,this._currentTrack.ensureStaveCount(1),this._currentTrack.playbackInfo.program=25,this._currentTrack.playbackInfo.primaryChannel=this._trackChannel++,this._currentTrack.playbackInfo.secondaryChannel=this._trackChannel++,this._currentStaff=this._currentTrack.staves[0],this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=ye.getDefaultTuningFor(6).tunings,this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=p.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":default:return r.G2;case"f4":case"bass":return r.F4;case"c3":case"tenor":return r.C3;case"c4":case"alto":return r.C4;case"n":case"neutral":return r.Neutral}}parseClefFromInt(e){switch(e){case 43:default:return r.G2;case 65:return r.F4;case 48:return r.C3;case 60:return r.C4}}parseTripletFeelFromString(e){switch(e.toLowerCase()){case"no":case"none":default:return D.NoTripletFeel;case"t16":case"triplet-16th":return D.Triplet16th;case"t8":case"triplet-8th":return D.Triplet8th;case"d16":case"dotted-16th":return D.Dotted16th;case"d8":case"dotted-8th":return D.Dotted8th;case"s16":case"scottish-16th":return D.Scottish16th;case"s8":case"scottish-8th":return D.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return D.NoTripletFeel;case 1:return D.Triplet16th;case 2:return D.Triplet8th;case 3:return D.Dotted16th;case 4:return D.Dotted8th;case 5:return D.Scottish16th;case 6:return D.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":return L.Cb;case"gb":case"gbmajor":case"d#minor":return L.Gb;case"db":case"dbmajor":case"bbminor":return L.Db;case"ab":case"abmajor":case"fminor":return L.Ab;case"eb":case"ebmajor":case"cminor":return L.Eb;case"bb":case"bbmajor":case"gminor":return L.Bb;case"f":case"fmajor":case"dminor":return L.F;case"c":case"cmajor":case"aminor":default:return L.C;case"g":case"gmajor":case"eminor":return L.G;case"d":case"dmajor":case"bminor":return L.D;case"a":case"amajor":case"f#minor":return L.A;case"e":case"emajor":case"c#minor":return L.E;case"b":case"bmajor":case"g#minor":return L.B;case"f#":case"f#major":case"ebminor":return L.FSharp;case"c#":case"c#major":return L.CSharp}}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=tt.Eof,this._ch}saveValidSpot(){this._lastValidSpot=[this._curChPos,this._line,this._col]}newSy(){for(this.saveValidSpot(),this._sy=ke.No;this._sy===ke.No;)if(this._ch===tt.Eof)this._sy=ke.Eof;else if(tt.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!==tt.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;this._ch!==tt.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",ke.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=ke.String;this._ch!==e&&this._ch!==tt.Eof;)t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._ch===tt.Eof&&this.errorMessage("String opened but never closed"),this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)this._allowNegatives?(this._sy=ke.Number,this._syData=this.readNumber()):(this._sy=ke.String,this._syData=this.readName());else if(46===this._ch)this._sy=ke.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=ke.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=ke.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=ke.MetaCommand,this._syData=this.readName();else if(41===this._ch)this._sy=ke.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=ke.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=ke.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=ke.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=ke.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=ke.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this._sy=ke.Number,this._syData=this.readNumber();else if(tt.isNameLetter(this._ch)){let e=this.readName(),t=this._allowTuning?j.parseTuning(e):null;t?(this._sy=ke.Tuning,this._syData=t):(this._sy=ke.String,this._syData=e)}else this.error("symbol",ke.String,!1);return this._sy}static isNameLetter(e){return!tt.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||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(tt.isNameLetter(this._ch)||this.isDigit(this._ch));return e}readNumber(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(this.isDigit(this._ch));return this._allowFloat?parseFloat(e):parseInt(e)}metaData(){let e=!1,t=!0;for(;this._sy===ke.MetaCommand&&t;){let s=this._syData.toLowerCase();switch(s){case"title":case"subtitle":case"artist":case"album":case"words":case"music":case"copyright":this._sy=this.newSy(),this._sy!==ke.String&&this.error(s,ke.String,!0);let i=this._syData;switch(s){case"title":this._score.title=i;break;case"subtitle":this._score.subTitle=i;break;case"artist":this._score.artist=i;break;case"album":this._score.album=i;break;case"words":this._score.words=i;break;case"music":this._score.music=i;break;case"copyright":this._score.copyright=i}this._sy=this.newSy(),e=!0;break;case"tempo":this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy===ke.Number?this._score.tempo=this._syData:this.error("tempo",ke.Number,!0),this._sy=this.newSy(),e=!0;break;default:this.handleStaffMeta()?e=!0:e?this.error("metaDataTags",ke.String,!1):t=!1}}return e?(this._sy!==ke.Dot&&this.error("song",ke.Dot,!0),this._sy=this.newSy()):this._sy===ke.Dot&&(this._sy=this.newSy()),e}handleStaffMeta(){switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===ke.Number?this._currentStaff.capo=this._syData:this.error("capo",ke.Number,!0),this._sy=this.newSy(),!0;case"tuning":this._sy=this.newSy();let e=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case ke.String:let e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?(this._currentStaff.stringTuning.tunings=[],this._currentStaff.displayTranspositionPitch=0):this.error("tuning",ke.Tuning,!0),this._sy=this.newSy();break;case ke.Tuning:let t=[];do{let e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===ke.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",ke.Tuning,!0)}return e!==this._currentStaff.tuning.length&&(this._currentStaff.chords?.size??0)>0&&this.errorMessage("Tuning must be defined before any chord"),!0;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===ke.Number){let e=this._syData;e>=0&&e<=127?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",ke.Number,!1)}else if(this._sy===ke.String){let e=this._syData.toLowerCase();this._currentTrack.playbackInfo.program=A.getValue(e)}else this.error("instrument",ke.Number,!0);return this._sy=this.newSy(),!0;case"lyrics":this._sy=this.newSy();let t=new he;return t.startBar=0,t.text="",this._sy===ke.Number&&(t.startBar=this._syData,this._sy=this.newSy()),this._sy===ke.String?(t.text=this._syData,this._sy=this.newSy()):this.error("lyrics",ke.String,!0),this._lyrics.get(this._currentTrack.index).push(t),!0;case"chord":this._sy=this.newSy();let s=new oe;this.chordProperties(s),this._sy===ke.String?(s.name=this._syData,this._sy=this.newSy()):this.error("chord-name",ke.Number,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===ke.Number?s.strings.push(this._syData):this._sy===ke.String&&"x"===this._syData.toLowerCase()&&s.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,s.name),s),!0;default:return!1}}chordProperties(e){if(this._sy===ke.LBrace){for(this._sy=this.newSy();this._sy===ke.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===ke.Number)e.firstFret=this._syData;else this.error("chord-firstfret",ke.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case ke.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case ke.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",ke.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case ke.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case ke.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",ke.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case ke.String:e.showName="false"!==this._syData.toLowerCase();break;case ke.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",ke.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===ke.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",ke.String,!1)}this._sy!==ke.RBrace&&this.error("chord-properties",ke.RBrace,!0),this._sy=this.newSy()}}bars(){let e=this.bar();for(;this._sy!==ke.Eof;)if(this._sy===ke.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==ke.MetaCommand)break;this.bar()}return e}trackStaffMeta(){return this._sy===ke.MetaCommand&&("track"===this._syData.toLowerCase()&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===ke.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===ke.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy())),this._sy===ke.MetaCommand&&"staff"===this._syData.toLowerCase()&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0&&(this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this._currentStaff=this._currentTrack.staves[this._currentTrack.staves.length-1],this._currentDynamics=p.F),this.staffProperties()),!0)}staffProperties(){if(this._sy!==ke.LBrace)return;this._sy=this.newSy();let e=!1,t=!1;for(;this._sy===ke.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy();break;case"tabs":t=!0,this._sy=this.newSy();break;default:this.error("staff-properties",ke.String,!1)}(e||t)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t),this._sy!==ke.RBrace&&this.error("staff-properties",ke.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 le;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);if(!this._staffTuningApplied&&!this._staffHasExplicitTuning){const e=this._currentTrack.playbackInfo.program;this._currentStaff.displayTranspositionPitch=0,this._currentStaff.stringTuning.tunings=[],15==e||e>=24&&e<=31?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=ye.getDefaultTuningFor(6).tunings):e>=32&&e<=39?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):40==e||44==e||45==e||48==e||49==e||50==e||51==e?this._currentStaff.stringTuning.tunings=[52,57,50,43]:41==e?this._currentStaff.stringTuning.tunings=[57,50,43,36]:42==e?this._currentStaff.stringTuning.tunings=[45,38,31,24]:43==e?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):105==e?this._currentStaff.stringTuning.tunings=[50,47,43,38,55]:106==e?this._currentStaff.stringTuning.tunings=[57,52,45]:107==e?this._currentStaff.stringTuning.tunings=[52,45,38,31]:110==e&&(this._currentStaff.stringTuning.tunings=[64,57,50,43]),this._staffTuningApplied=!0}let i=!1,a=t.voices[0];for(;this._sy!==ke.Pipe&&this._sy!==ke.Eof&&this.beat(a);)i=!0;if(0===a.beats.length){let e=new ne;e.isEmpty=!0,a.addBeat(e)}return e||s||i}newBar(e){let t=new H;e.addBar(t),t.index>0&&(t.clef=t.previousBar.clef);let s=new _e;return t.addVoice(s),t}beat(e){this.beatDuration();let t=new ne;if(e.addBeat(t),this._sy===ke.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==ke.RParensis&&this._sy!==ke.Eof&&this.note(t););this._sy!==ke.RParensis&&this.error("note-list",ke.RParensis,!0),this._sy=this.newSy()}else if(this._sy===ke.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===ke.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==ke.Number&&this.error("duration",ke.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||tt.applyTuplet(t,this._currentTuplet);let s=1;this._sy===ke.Multiply&&(this._sy=this.newSy(),this._sy!==ke.Number?this.error("multiplier",ke.Number,!0):s=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let i=0;i<s-1;i++)e.addBeat(ae.clone(t));return!0}beatDuration(){if(this._sy===ke.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==ke.Number&&this.error("duration",ke.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===ke.LBrace)){for(this._sy=this.newSy();this._sy===ke.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==ke.Number&&this.error("duration-tuplet",ke.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",ke.String,!1)}this._sy!==ke.RBrace&&this.error("beat-duration",ke.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===ke.LBrace){for(this._sy=this.newSy();this._sy===ke.String;)this.applyBeatEffect(e)||this.error("beat-effects",ke.String,!1);this._sy!==ke.RBrace&&this.error("beat-effects",ke.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){let t=this._syData.toLowerCase();if("f"===t)e.fadeIn=!0;else if("v"===t)e.vibrato=_.Slight;else if("s"===t)e.slap=!0;else if("p"===t)e.pop=!0;else if("tt"===t)e.tap=!0;else if("dd"===t)e.dots=2;else if("d"===t)e.dots=1;else if("su"===t)e.pickStroke=x.Up;else if("sd"===t)e.pickStroke=x.Down;else if("tu"===t){if(this._sy=this.newSy(),this._sy!==ke.Number)return this.error("tuplet",ke.Number,!0),!1;tt.applyTuplet(e,this._syData)}else if("tb"===t||"tbe"===t){let s="tbe"===t;for(this._sy=this.newSy(),this._sy!==ke.LParensis&&this.error("tremolobar-effect",ke.LParensis,!0),this._allowNegatives=!0,this._sy=this.newSy();this._sy!==ke.RParensis&&this._sy!==ke.Eof;){let t=0,i=0;s?(this._sy!==ke.Number&&this.error("tremolobar-effect",ke.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==ke.Number&&this.error("tremolobar-effect",ke.Number,!0),i=this._syData):(this._sy!==ke.Number&&this.error("tremolobar-effect",ke.Number,!0),t=0,i=this._syData),e.addWhammyBarPoint(new z(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._sy!==ke.RParensis&&this.error("tremolobar-effect",ke.RParensis,!0)}else{if("bu"===t||"bd"===t||"au"===t||"ad"===t){switch(t){case"bu":e.brushType=c.BrushUp;break;case"bd":e.brushType=c.BrushDown;break;case"au":e.brushType=c.ArpeggioUp;break;case"ad":e.brushType=c.ArpeggioDown}return this._sy=this.newSy(),this._sy===ke.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 oe;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=g.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=g.BendGrace,this._sy=this.newSy()):e.graceType=g.BeforeBeat,!0;if("dy"===t){switch(this._sy=this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=p.PPP;break;case"pp":e.dynamics=p.PP;break;case"p":e.dynamics=p.P;break;case"mp":e.dynamics=p.MP;break;case"mf":e.dynamics=p.MF;break;case"f":e.dynamics=p.F;break;case"ff":e.dynamics=p.FF;break;case"fff":e.dynamics=p.FFF}this._currentDynamics=e.dynamics}else if("cre"===t)e.crescendo=d.Crescendo;else{if("dec"!==t){if("tp"===t){if(this._sy=this.newSy(),e.tremoloSpeed=u.Eighth,this._sy===ke.Number){switch(this._syData){case 8:default:e.tremoloSpeed=u.Eighth;break;case 16:e.tremoloSpeed=u.Sixteenth;break;case 32:e.tremoloSpeed=u.ThirtySecond}this._sy=this.newSy()}return!0}return!1}e.crescendo=d.Decrescendo}}}return this._sy=this.newSy(),!0}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;switch(this._sy){case ke.Number:i=this._syData;break;case ke.String:t="x"===this._syData,s="-"===this._syData,s||t?i=0:this.error("note-fret",ke.Number,!0);break;case ke.Tuning:let e=this._syData;a=e.octave,r=e.noteValue;break;default:return!1}this._sy=this.newSy();let n=-1===a&&this._currentStaff.tuning.length>0,o=-1;n&&(this._sy!==ke.Dot&&this.error("note",ke.Dot,!0),this._sy=this.newSy(),this._sy!==ke.Number&&this.error("note-string",ke.Number,!0),o=this._syData,(o<1||o>this._currentStaff.tuning.length)&&this.error("note-string",ke.Number,!1),this._sy=this.newSy());let h=new Z;return n?(h.string=this._currentStaff.tuning.length-(o-1),h.isDead=t,h.isTieDestination=s,s||(h.fret=i)):(h.octave=a,h.tone=r,h.isTieDestination=s),e.addNote(h),this.noteEffects(h),!0}noteEffects(e){if(this._sy===ke.LBrace){for(this._sy=this.newSy();this._sy===ke.String;){let t=this._syData.toLowerCase();if("b"===t||"be"===t){let s="be"===t;for(this._sy=this.newSy(),this._sy!==ke.LParensis&&this.error("bend-effect",ke.LParensis,!0),this._sy=this.newSy();this._sy!==ke.RParensis&&this._sy!==ke.Eof;){let t=0,i=0;s?(this._sy!==ke.Number&&this.error("bend-effect-value",ke.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==ke.Number&&this.error("bend-effect-value",ke.Number,!0),i=this._syData):(this._sy!==ke.Number&&this.error("bend-effect-value",ke.Number,!0),i=this._syData),e.addBendPoint(new z(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!==ke.RParensis&&this.error("bend-effect",ke.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=m.Natural,this._sy=this.newSy();else if("ah"===t)e.harmonicType=m.Artificial,this._sy=this.newSy();else if("th"===t)e.harmonicType=m.Tap,this._sy=this.newSy();else if("ph"===t)e.harmonicType=m.Pinch,this._sy=this.newSy();else if("sh"===t)e.harmonicType=m.Semi,this._sy=this.newSy();else if("tr"===t){this._sy=this.newSy(),this._sy!==ke.Number&&this.error("trill-effect",ke.Number,!0);let t=this._syData;this._sy=this.newSy();let s=u.Sixteenth;if(this._sy===ke.Number){switch(this._syData){case 16:default:s=u.Sixteenth;break;case 32:s=u.ThirtySecond;break;case 64:s=u.SixtyFourth}this._sy=this.newSy()}e.trillValue=t+e.stringTuning,e.trillSpeed=s}else if("v"===t)this._sy=this.newSy(),e.vibrato=_.Slight;else if("sl"===t)this._sy=this.newSy(),e.slideOutType=S.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=S.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=b.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=b.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=S.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=S.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=S.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=S.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=i.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=i.Heavy;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=f.Thumb;this._sy===ke.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.leftHandFinger=t}else if("rf"===t){this._sy=this.newSy();let t=f.Thumb;this._sy===ke.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else this.applyBeatEffect(e.beat)||this.error(t,ke.String,!1)}this._sy!==ke.RBrace&&this.error("note-effect",ke.RBrace,!1),this._sy=this.newSy()}}toFinger(e){switch(e){case 1:return f.Thumb;case 2:return f.IndexFinger;case 3:return f.MiddleFinger;case 4:return f.AnnularFinger;case 5:return f.LittleFinger}return f.Thumb}parseDuration(e){switch(e){case-4:return u.QuadrupleWhole;case-2:return u.DoubleWhole;case 1:return u.Whole;case 2:return u.Half;case 4:return u.Quarter;case 8:return u.Eighth;case 16:return u.Sixteenth;case 32:return u.ThirtySecond;case 64:return u.SixtyFourth;case 128:return u.OneHundredTwentyEighth;case 256:return u.TwoHundredFiftySixth;default:return u.Quarter}}barMeta(e){let t=!1,s=e.masterBar;for(;this._sy===ke.MetaCommand;){t=!0;let i=this._syData.toLowerCase();if("ts"===i)this._sy=this.newSy(),this._sy!==ke.Number&&this.error("timesignature-numerator",ke.Number,!0),s.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==ke.Number&&this.error("timesignature-denominator",ke.Number,!0),s.timeSignatureDenominator=this._syData,this._sy=this.newSy();else if("ro"===i)s.isRepeatStart=!0,this._sy=this.newSy();else if("rc"===i)this._sy=this.newSy(),this._sy!==ke.Number&&this.error("repeatclose",ke.Number,!0),this._syData>2048&&this.error("repeatclose",ke.Number,!1),s.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===i)if(this._sy=this.newSy(),this._sy===ke.LParensis){for(this._sy=this.newSy(),this._sy!==ke.Number&&this.error("alternateending",ke.Number,!0),this.applyAlternateEnding(s);this._sy===ke.Number;)this.applyAlternateEnding(s);this._sy!==ke.RParensis&&this.error("alternateending-list",ke.RParensis,!0),this._sy=this.newSy()}else this._sy!==ke.Number&&this.error("alternateending",ke.Number,!0),this.applyAlternateEnding(s);else if("ks"===i)this._sy=this.newSy(),this._sy!==ke.String&&this.error("keysignature",ke.String,!0),s.keySignature=this.parseKeySignature(this._syData),this._sy=this.newSy();else if("clef"===i){switch(this._sy=this.newSy(),this._sy){case ke.String:e.clef=this.parseClefFromString(this._syData);break;case ke.Number:e.clef=this.parseClefFromInt(this._syData);break;case ke.Tuning:let t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",ke.String,!0)}this._sy=this.newSy()}else if("tempo"===i){this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==ke.Number&&this.error("tempo",ke.Number,!0);let e=new V;e.isLinear=!1,e.type=a.Tempo,e.value=this._syData,s.tempoAutomation=e,this._sy=this.newSy()}else if("section"===i){this._sy=this.newSy(),this._sy!==ke.String&&this.error("section",ke.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==ke.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"===i){switch(this._allowTuning=!1,this._sy=this.newSy(),this._allowTuning=!0,this._sy){case ke.String:s.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case ke.Number:s.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",ke.String,!0)}this._sy=this.newSy()}else"ac"===i?(s.isAnacrusis=!0,this._sy=this.newSy()):0===e.index&&this.handleStaffMeta()||this.error("measure-effects",ke.String,!1)}if(0===s.index&&!s.tempoAutomation){let e=new V;e.isLinear=!1,e.type=a.Tempo,e.value=this._score.tempo,s.tempoAutomation=e}return t}applyAlternateEnding(e){let t=this._syData;t<1&&this.error("alternateending",ke.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}}tt.Eof=0;class st extends R{get name(){return"Guitar Pro 3-5"}constructor(){super(),this._versionNumber=0,this._globalTripletFeel=D.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._beatTextChunksByTrack=new Map}readScore(){return this.readVersion(),this._score=new ue,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=it.gpReadBool(this.data)?D.Triplet8th:D.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=it.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=Be.readInt32LE(this.data),this._versionNumber>=510&&it.gpReadBool(this.data),Be.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.data.skip(38),this.data.skip(4)),this._barCount=Be.readInt32LE(this.data),this._trackCount=Be.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0&&(this._score.masterBars[0].tempoAutomation=V.buildTempoAutomation(!1,0,this._score.tempo,2),this._score.masterBars[0].tempoAutomation.text=this._score.tempoLabel),this._score.finish(this.settings),this._lyrics&&this._lyricsTrack>=0&&this._score.tracks[this._lyricsTrack].applyLyrics(this._lyrics),this._score}readVersion(){let e=it.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(st.VersionString))throw new G("Unsupported format");e=e.substr(st.VersionString.length+1);let t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*parseInt(e.substr(0,t))+parseInt(e.substr(t+1)),q.debug(this.name,"Guitar Pro version "+e+" detected")}readScoreInformation(){this._score.title=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?it.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding);let e=Be.readInt32LE(this.data),t="";for(let s=0;s<e;s++)s>0&&(t+="\r\n"),t+=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding)?.toString();this._score.notices=t}readLyrics(){this._lyrics=[],this._lyricsTrack=Be.readInt32LE(this.data)-1;for(let e=0;e<5;e++){let e=new he;e.startBar=Be.readInt32LE(this.data)-1,e.text=it.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(30);for(let e=0;e<10;e++)it.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){let t=new me;t.primaryChannel=e,t.secondaryChannel=e,t.program=Be.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 le,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=it.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",it.gpReadColor(this.data,!1),t.section=e}if(64&s?(t.keySignature=Be.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=D.Triplet8th;break;case 2:t.tripletFeel=D.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=!!(128&s),this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){let e=new Se;e.ensureStaveCount(1),this._score.addTrack(e);let t=e.staves[0],s=this.data.readByte();e.name=it.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),1&s&&(t.isPercussion=!0);let i=Be.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){let t=Be.readInt32LE(this.data);i>e&&a.push(t)}t.stringTuning.tunings=a;let r=Be.readInt32LE(this.data),n=Be.readInt32LE(this.data)-1,o=Be.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,A.isGuitar(i.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=i}t.capo=Be.readInt32LE(this.data),e.color=it.gpReadColor(this.data,!1),this._versionNumber>=500&&(this.data.readByte(),this.data.readByte(),this.data.skip(43)),this._versionNumber>=510&&(this.data.skip(4),it.gpReadStringIntByte(this.data,this.settings.importer.encoding),it.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 H,s=e.staves[0];s.isPercussion&&(t.clef=r.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=Be.readInt32LE(this.data);if(0===s)return;let i=new _e;t.addVoice(i);for(let a=0;a<s;a++)this.readBeat(e,t,i)}readBeat(e,t,s){let i=new ne,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),Be.readSInt8(this.data)){case-2:i.duration=u.Whole;break;case-1:i.duration=u.Half;break;case 0:i.duration=u.Quarter;break;case 1:i.duration=u.Eighth;break;case 2:i.duration=u.Sixteenth;break;case 3:i.duration=u.ThirtySecond;break;case 4:i.duration=u.SixtyFourth;break;default:i.duration=u.Quarter}if(32&a)switch(i.tupletNumerator=Be.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=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const s=new he;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=m.None;8&a&&(n=this.readBeatEffects(i)),16&a&&this.readMixTableChange(i);let o=this.data.readByte();for(let a=6;a>=0;a--)if(o&1<<a&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,s,i,6-a);n!==m.None&&(r.harmonicType=n,r.harmonicType===m.Natural&&(r.harmonicValue=this.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){this.data.readByte(),8&this.data.readByte()&&this.data.readByte()}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 oe,s=j.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=it.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Be.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Be.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=it.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Be.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Be.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=it.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=Be.readInt32LE(this.data);for(let s=0;s<6;s++){let i=Be.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=it.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=Be.readInt32LE(this.data),t.firstFret>0)for(let i=0;i<s;i++){let s=Be.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()),e.fadeIn=!!(16&t),(this._versionNumber<400&&1&t||2&t)&&(e.vibrato=_.Slight),e.hasRasgueado=!!(1&s),32&t&&this._versionNumber>=400){switch(Be.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(Be.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=c.BrushUp,e.brushDuration=st.toStrokeValue(t)):s>0&&(e.brushType=c.BrushDown,e.brushDuration=st.toStrokeValue(s))}if(2&s)switch(Be.readSInt8(this.data)){case 0:e.pickStroke=x.None;break;case 1:e.pickStroke=x.Up;break;case 2:e.pickStroke=x.Down}if(this._versionNumber<400){if(4&t)return m.Natural;if(8&t)return m.Artificial}return m.None}readTremoloBarEffect(e){this.data.readByte(),Be.readInt32LE(this.data);let t=Be.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new z(0,0);t.offset=Be.readInt32LE(this.data),t.value=Be.readInt32LE(this.data)/st.BendStep|0,it.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 at;t.instrument=Be.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=Be.readSInt8(this.data),t.balance=Be.readSInt8(this.data);let s=Be.readSInt8(this.data),i=Be.readSInt8(this.data),r=Be.readSInt8(this.data),n=Be.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=it.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=Be.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(),r>=0&&this.data.readByte(),n>=0&&this.data.readByte(),t.tempo>=0&&(t.duration=Be.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500&&this.data.readByte(),this._versionNumber>=510&&(it.gpReadStringIntByte(this.data,this.settings.importer.encoding),it.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){let s=new V;s.isLinear=!0,s.type=a.Volume,s.value=t.volume,e.automations.push(s)}if(t.balance>=0){let s=new V;s.isLinear=!0,s.type=a.Balance,s.value=t.balance,e.automations.push(s)}if(t.instrument>=0){let s=new V;s.isLinear=!0,s.type=a.Instrument,s.value=t.instrument,e.automations.push(s)}if(t.tempo>=0){let s=new V;s.isLinear=!0,s.type=a.Tempo,s.value=t.tempo,e.automations.push(s),e.voice.bar.masterBar.tempoAutomation=s}}readNote(e,t,s,a,r){let n=new Z;n.string=t.staff.tuning.length-r;let o=this.data.readByte();if(2&o?n.accentuated=i.Heavy:64&o&&(n.accentuated=i.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=Be.readSInt8(this.data);n.dynamics=this.toDynamicValue(e),a.dynamics=n.dynamics}32&o&&(n.fret=Be.readSInt8(this.data)),128&o&&(n.leftHandFinger=Be.readSInt8(this.data),n.rightHandFinger=Be.readSInt8(this.data),n.isFingering=!0);let h=!1;if(this._versionNumber>=500){1&o&&(n.durationPercent=it.gpReadDouble(this.data)),h=!!(2&this.data.readByte())}if(a.addNote(n),8&o&&this.readNoteEffects(e,s,a,n),t.staff.isPercussion&&(n.percussionArticulation=n.fret,n.string=-1,n.fret=-1),h){const e=ye.defaultAccidentals[n.realValueWithoutHarmonic%12];"#"===e?n.accidentalMode=y.ForceFlat:"b"===e&&(n.accidentalMode=y.ForceSharp)}return n}toDynamicValue(e){switch(e){case 1:return p.PPP;case 2:return p.PP;case 3:return p.P;case 4:return p.MP;case 5:return p.MF;case 6:default:return p.F;case 7:return p.FF;case 8:return p.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=S.Shift),16&r&&this.readArtificialHarmonic(i),32&r&&this.readTrill(i),i.isLetRing=!!(8&a),i.isHammerPullOrigin=!!(2&a),64&r&&(i.vibrato=_.Slight),i.isPalmMute=!!(2&r),i.isStaccato=!!(1&r)}readBend(e){this.data.readByte(),Be.readInt32LE(this.data);let t=Be.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new z(0,0);t.offset=Be.readInt32LE(this.data),t.value=Be.readInt32LE(this.data)/st.BendStep|0,it.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){let s=new ne,i=new Z;switch(i.string=t.string,i.fret=Be.readSInt8(this.data),s.duration=u.ThirtySecond,s.dynamics=this.toDynamicValue(Be.readSInt8(this.data)),Be.readSInt8(this.data)){case 0:case 2:break;case 1:i.slideOutType=S.Legato,i.slideTarget=t;break;case 3:i.isHammerPullOrigin=!0}if(i.dynamics=s.dynamics,this.data.skip(1),this._versionNumber<500)s.graceType=g.BeforeBeat;else{let e=this.data.readByte();i.isDead=!!(1&e),s.graceType=2&e?g.OnBeat:g.BeforeBeat}e.addGraceBeat(s),s.addNote(i)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=u.Eighth;break;case 2:e.tremoloSpeed=u.Sixteenth;break;case 3:e.tremoloSpeed=u.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){let t=Be.readSInt8(this.data);1&t?e.slideOutType=S.Shift:2&t?e.slideOutType=S.Legato:4&t?e.slideOutType=S.OutDown:8&t&&(e.slideOutType=S.OutUp),16&t?e.slideInType=b.IntoFromBelow:32&t&&(e.slideInType=b.IntoFromAbove)}else{switch(Be.readSInt8(this.data)){case 1:e.slideOutType=S.Shift;break;case 2:e.slideOutType=S.Legato;break;case 3:e.slideOutType=S.OutDown;break;case 4:e.slideOutType=S.OutUp;break;case-1:e.slideInType=b.IntoFromBelow;break;case-2:e.slideInType=b.IntoFromAbove}}}readArtificialHarmonic(e){let t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=m.Natural,e.harmonicValue=this.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=m.Artificial;break;case 3:e.harmonicType=m.Tap,e.harmonicValue=this.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=m.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=m.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=m.Natural;break;case 3:e.harmonicType=m.Tap;break;case 4:e.harmonicType=m.Pinch;break;case 5:e.harmonicType=m.Semi;break;case 15:case 17:case 22:e.harmonicType=m.Artificial}}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}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=u.Sixteenth;break;case 2:e.trillSpeed=u.ThirtySecond;break;case 3:e.trillSpeed=u.SixtyFourth}}}st.VersionString="FICHIER GUITAR PRO ",st.BendStep=25;class it{static gpReadDouble(e){let t=new Uint8Array(8);return e.read(t,0,t.length),new Float64Array(t.buffer)[0]}static gpReadFloat(e){let t=new Uint8Array(4);return t[3]=e.readByte(),t[2]=e.readByte(),t[2]=e.readByte(),t[1]=e.readByte(),new Float32Array(t.buffer)[0]}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 fe(s,i,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),it.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return it.gpReadString(e,Be.readInt32LE(e),t)}static gpReadStringIntByte(e,t){let s=Be.readInt32LE(e)-1;return e.readByte(),it.gpReadString(e,s,t)}static gpReadString(e,t,s){let i=new Uint8Array(t);return e.read(i,0,i.length),Be.toString(i,s)}static gpWriteString(e,t){const s=Be.stringToBytes(t);e.writeByte(t.length),e.write(s,0,s.length)}static gpReadStringByteLength(e,t,s){let i=e.readByte(),a=it.gpReadString(e,i,s);return i<t&&e.skip(t-i),a}}class at{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class rt{constructor(){this.x=0,this.y=0,this.w=0,this.h=0}}!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"}(ve||(ve={}));class nt{constructor(e){this.raw=new Map;let t=Te.fromBuffer(e),s=Be.readInt32BE(t);for(let e=0;e<s;e++){let e=it.gpReadString(t,t.readByte(),"utf-8");switch(t.readByte()){case ve.Boolean:let s=1===t.readByte();this.addValue(e,s);break;case ve.Integer:let i=Be.readInt32BE(t);this.addValue(e,i);break;case ve.Float:let a=it.gpReadFloat(t);this.addValue(e,a);break;case ve.String:let r=it.gpReadString(t,Be.readInt16BE(t),"utf-8");this.addValue(e,r);break;case ve.Point:let n=Be.readInt32BE(t),o=Be.readInt32BE(t);this.addValue(e,new z(n,o));break;case ve.Size:let h=Be.readInt32BE(t),l=Be.readInt32BE(t);this.addValue(e,new z(h,l));break;case ve.Rectangle:let c=new rt;c.x=Be.readInt32BE(t),c.y=Be.readInt32BE(t),c.w=Be.readInt32BE(t),c.h=Be.readInt32BE(t),this.addValue(e,c);break;case ve.Color:let d=it.gpReadColor(t,!0);this.addValue(e,d)}}}apply(e){for(const[t,s]of this.raw)if("StandardNotation/hideDynamics"===t)e.stylesheet.hideDynamics=s}addValue(e,t){this.raw.set(e,t)}static writeForScore(e){const t=Te.withCapacity(128);return Be.writeInt32BE(t,1),nt.writeBooleanEntry(t,"StandardNotation/hideDynamics",e.stylesheet.hideDynamics),t.toArray()}static writeBooleanEntry(e,t,s){it.gpWriteString(e,t),e.writeByte(ve.Boolean),e.writeByte(s?1:0)}}!function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(xe||(xe={}));class ot{constructor(){this.type=xe.Short,this.length=0}}!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"}(Ne||(Ne={}));class ht{constructor(){this.nodeType=Ne.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!==Ne.Element&&e.nodeType!==Ne.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===Ne.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===Ne.Element&&t.localName===e)return t;return null}addElement(e){const t=new ht;return t.nodeType=Ne.Element,t.localName=e,this.addChild(t),t}get innerText(){if(this.nodeType===Ne.Element||this.nodeType===Ne.Document){if(this.firstElement&&this.firstElement.nodeType===Ne.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 ht;t.nodeType=Ne.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new ht;t.nodeType=Ne.CDATA,t.value=e,this.childNodes=[t]}}class lt extends O{constructor(e,t,i){super(s.Format,e),this.pos=0,this.xml=t,this.pos=i,Object.setPrototypeOf(this,lt.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"}(Pe||(Pe={}));class ct{static parse(e,t,s){let i=e.charCodeAt(t),a=Pe.Begin,r=Pe.Begin,n=0,o="",h=Pe.Begin,l=null,c=null,d=0,u=0;for(;t<e.length;){switch(i=e.charCodeAt(t),a){case Pe.IgnoreSpaces:switch(i){case ct.CharCodeLF:case ct.CharCodeCR:case ct.CharCodeTab:case ct.CharCodeSpace:break;default:a=r;continue}break;case Pe.Begin:if(i!==ct.CharCodeLowerThan){n=t,a=Pe.Pcdata;continue}a=Pe.IgnoreSpaces,r=Pe.BeginNode;break;case Pe.Pcdata:if(i===ct.CharCodeLowerThan){o+=e.substr(n,t-n);let i=new ht;i.nodeType=Ne.Text,i.value=o,o="",s.addChild(i),a=Pe.IgnoreSpaces,r=Pe.BeginNode}else i===ct.CharCodeAmp&&(o+=e.substr(n,t-n),a=Pe.Escape,h=Pe.Pcdata,n=t+1);break;case Pe.Cdata:if(i===ct.CharCodeBrackedClose&&e.charCodeAt(t+1)===ct.CharCodeBrackedClose&&e.charCodeAt(t+2)===ct.CharCodeGreaterThan){let i=new ht;i.nodeType=Ne.CDATA,i.value=e.substr(n,t-n),s.addChild(i),t+=2,a=Pe.Begin}break;case Pe.BeginNode:switch(i){case ct.CharCodeExclamation:if(e.charCodeAt(t+1)===ct.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new lt("Expected <![CDATA[",e,t);t+=5,a=Pe.Cdata,n=t+1}else if(e.charCodeAt(t+1)===ct.CharCodeUpperD||e.charCodeAt(t+1)===ct.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new lt("Expected <!DOCTYPE",e,t);t+=8,a=Pe.Doctype,n=t+1}else{if(e.charCodeAt(t+1)!==ct.CharCodeMinus||e.charCodeAt(t+2)!==ct.CharCodeMinus)throw new lt("Expected \x3c!--",e,t);t+=2,a=Pe.Comment,n=t+1}break;case ct.CharCodeQuestion:a=Pe.Header,n=t;break;case ct.CharCodeSlash:if(!s)throw new lt("Expected node name",e,t);n=t+1,a=Pe.IgnoreSpaces,r=Pe.Close;break;default:a=Pe.TagName,n=t;continue}break;case Pe.TagName:if(!ct.isValidChar(i)){if(t===n)throw new lt("Expected node name",e,t);l=new ht,l.nodeType=Ne.Element,l.localName=e.substr(n,t-n),s.addChild(l),a=Pe.IgnoreSpaces,r=Pe.Body;continue}break;case Pe.Body:switch(i){case ct.CharCodeSlash:a=Pe.WaitEnd;break;case ct.CharCodeGreaterThan:a=Pe.Childs;break;default:a=Pe.AttribName,n=t;continue}break;case Pe.AttribName:if(!ct.isValidChar(i)){if(n===t)throw new lt("Expected attribute name",e,t);if(c=e.substr(n,t-n),l.attributes.has(c))throw new lt(`Duplicate attribute [${c}]`,e,t);a=Pe.IgnoreSpaces,r=Pe.Equals;continue}break;case Pe.Equals:if(i!==ct.CharCodeEquals)throw new lt("Expected =",e,t);a=Pe.IgnoreSpaces,r=Pe.AttvalBegin;break;case Pe.AttvalBegin:switch(i){case ct.CharCodeDoubleQuote:case ct.CharCodeSingleQuote:o="",a=Pe.AttribVal,n=t+1,u=i}break;case Pe.AttribVal:if(i===ct.CharCodeAmp)o+=e.substr(n,t-n),a=Pe.Escape,h=Pe.AttribVal,n=t+1;else if(i===u){o+=e.substr(n,t-n);let s=o;o="",l.attributes.set(c,s),a=Pe.IgnoreSpaces,r=Pe.Body}break;case Pe.Childs:n=t=ct.parse(e,t,l),a=Pe.Begin;break;case Pe.WaitEnd:if(i!==ct.CharCodeGreaterThan)throw new lt("Expected >",e,t);a=Pe.Begin;break;case Pe.WaitEndRet:if(i===ct.CharCodeGreaterThan)return t;throw new lt("Expected >",e,t);case Pe.Close:if(!ct.isValidChar(i)){if(n===t)throw new lt("Expected node name",e,t);if(e.substr(n,t-n)!==s.localName)throw new lt("Expected </"+s.localName+">",e,t);a=Pe.IgnoreSpaces,r=Pe.WaitEndRet;continue}break;case Pe.Comment:i===ct.CharCodeMinus&&e.charCodeAt(t+1)===ct.CharCodeMinus&&e.charCodeAt(t+2)===ct.CharCodeGreaterThan&&(t+=2,a=Pe.Begin);break;case Pe.Doctype:if(i===ct.CharCodeBrackedOpen)d++;else if(i===ct.CharCodeBrackedClose)d--;else if(i===ct.CharCodeGreaterThan&&0===d){let i=new ht;i.nodeType=Ne.DocumentType,i.value=e.substr(n,t-n),s.addChild(i),a=Pe.Begin}break;case Pe.Header:i===ct.CharCodeQuestion&&e.charCodeAt(t+1)===ct.CharCodeGreaterThan&&(t++,a=Pe.Begin);break;case Pe.Escape:if(i===ct.CharCodeSemi){let s=e.substr(n,t-n);if(s.charCodeAt(0)===ct.CharCodeSharp){let e=s.charCodeAt(1)===ct.CharCodeLowerX?parseInt("0"+s.substr(1,s.length-1)):parseInt(s.substr(1,s.length-1));o+=String.fromCharCode(e)}else ct.Escapes.has(s)?o+=ct.Escapes.get(s):o+=("&"+s+";")?.toString();n=t+1,a=h}else ct.isValidChar(i)||i===ct.CharCodeSharp||(o+="&",o+=e.substr(n,t-n),n=--t+1,a=h)}t++}if(a===Pe.Begin&&(n=t,a=Pe.Pcdata),a===Pe.Pcdata){if(t!==n){o+=e.substr(n,t-n);let i=new ht;i.nodeType=Ne.Text,i.value=o,s.addChild(i)}return t}if(a===Pe.Escape&&h===Pe.Pcdata){o+="&",o+=e.substr(n,t-n);let i=new ht;return i.nodeType=Ne.Text,i.value=o,s.addChild(i),t}throw new lt("Unexpected end",e,t)}static isValidChar(e){return e>=ct.CharCodeLowerA&&e<=ct.CharCodeLowerZ||e>=ct.CharCodeUpperA&&e<=ct.CharCodeUpperZ||e>=ct.CharCode0&&e<=ct.CharCode9||e===ct.CharCodeColon||e===ct.CharCodeDot||e===ct.CharCodeUnderscore||e===ct.CharCodeMinus}}ct.CharCodeLF=10,ct.CharCodeTab=9,ct.CharCodeCR=13,ct.CharCodeSpace=32,ct.CharCodeLowerThan=60,ct.CharCodeAmp=38,ct.CharCodeBrackedClose=93,ct.CharCodeBrackedOpen=91,ct.CharCodeGreaterThan=62,ct.CharCodeExclamation=33,ct.CharCodeUpperD=68,ct.CharCodeLowerD=100,ct.CharCodeMinus=45,ct.CharCodeQuestion=63,ct.CharCodeSlash=47,ct.CharCodeEquals=61,ct.CharCodeDoubleQuote=34,ct.CharCodeSingleQuote=39,ct.CharCodeSharp=35,ct.CharCodeLowerX=120,ct.CharCodeLowerA=97,ct.CharCodeLowerZ=122,ct.CharCodeUpperA=65,ct.CharCodeUpperZ=90,ct.CharCode0=48,ct.CharCode9=57,ct.CharCodeColon=58,ct.CharCodeDot=46,ct.CharCodeUnderscore=95,ct.CharCodeSemi=59,ct.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class dt{static write(e,t,s){const i=new dt(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 Ne.None:break;case Ne.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===Ne.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case Ne.Text:e.value&&this.write(e.value);break;case Ne.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case Ne.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case Ne.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 ut extends ht{constructor(){super(),this.nodeType=Ne.Document}parse(e){ct.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return dt.write(this,e,t)}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(Ce||(Ce={}));class pt{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=u.Quarter}}class gt{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return this.path+";"+this.name+";"+this.role}}class ft{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1}parseXml(e,t){this._masterTrackAutomations=new Map,this._automationsPerTrackIdAndBarIndex=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 ut;try{s.parse(e)}catch(e){throw new G("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 G("Root node of XML was not GPIF");this.score=new ue;for(let e of t.childNodes)if(e.nodeType===Ne.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===Ne.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===Ne.Element)switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null);break;case"Tracks":this._tracksMapping=t.innerText.split(" ");break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,s){for(let i of e.childNodes)if(i.nodeType===Ne.Element&&"Automation"===i.localName)this.parseAutomation(i,t,s)}parseAutomation(e,t,s){let i=null,a=!1,r=-1,n=0,o=0,h=null,l=0,c=null;for(let t of e.childNodes)if(t.nodeType===Ne.Element)switch(t.localName){case"Type":i=t.innerText;break;case"Linear":a="true"===t.innerText.toLowerCase();break;case"Bar":r=parseInt(t.innerText);break;case"Position":n=parseFloat(t.innerText);break;case"Value":if(t.firstElement&&t.firstElement.nodeType===Ne.CDATA)h=t.innerText;else{let e=t.innerText.split(" ");1===e.length?(o=parseFloat(e[0]),l=1):(o=parseFloat(e[0]),l=parseInt(e[1]))}break;case"Text":c=t.innerText}if(!i)return;let d=null;switch(i){case"Tempo":d=V.buildTempoAutomation(a,n,o,l);break;case"Sound":h&&s&&s.has(h)&&(d=V.buildInstrumentAutomation(a,n,s.get(h).program))}d&&(c&&(d.text=c),r>=0&&(t.has(r)||t.set(r,[]),t.get(r).push(d)))}parseTracksNode(e){for(let t of e.childNodes)if(t.nodeType===Ne.Element&&"Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;let t=new Se;t.ensureStaveCount(1),t.staves[0].showStandardNotation=!0;let s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===Ne.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 fe(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),this.parseAutomations(t,s,this._soundsByTrack.get(e))}parseNotationPatch(e,t){for(let s of t.childNodes)if(s.nodeType===Ne.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===Ne.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===Ne.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===Ne.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===Ne.Element&&"Articulation"===i.localName)this.parseArticulation(e,i,s)}parseArticulation(e,t,s){const i=new Q;i.outputMidiNumber=-1,i.elementType=s;let a="";for(let e of t.childNodes)if(e.nodeType===Ne.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=C.Bottom;break;case"inside":i.techniqueSymbolPlacement=C.Middle;break;case"below":i.techniqueSymbolPlacement=C.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==N.None&&(i.noteHeadHalf=i.noteHeadDefault),i.noteHeadWhole==N.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 N.PictEdgeOfCymbal;case"articStaccatoAbove":return N.ArticStaccatoAbove;case"noteheadParenthesis":return N.NoteheadParenthesis;case"stringsUpBow":return N.StringsUpBow;case"stringsDownBow":return N.StringsDownBow;case"guitarGolpe":return N.GuitarGolpe;default:return N.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return N.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return N.NoteheadDoubleWhole;case"noteheadWhole":return N.NoteheadWhole;case"noteheadHalf":return N.NoteheadHalf;case"noteheadBlack":return N.NoteheadBlack;case"noteheadNull":return N.NoteheadNull;case"noteheadXOrnate":return N.NoteheadXOrnate;case"noteheadTriangleUpWhole":return N.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return N.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return N.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return N.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return N.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return N.NoteheadDiamondWhiteWide;case"noteheadCircleX":return N.NoteheadCircleX;case"noteheadXWhole":return N.NoteheadXWhole;case"noteheadXHalf":return N.NoteheadXHalf;case"noteheadXBlack":return N.NoteheadXBlack;case"noteheadParenthesis":return N.NoteheadParenthesis;case"noteheadSlashedBlack2":return N.NoteheadSlashedBlack2;case"noteheadCircleSlash":return N.NoteheadCircleSlash;case"noteheadHeavyX":return N.NoteheadHeavyX;case"noteheadHeavyXHat":return N.NoteheadHeavyXHat;default:return q.warning("GPIF","Unknown notehead symbol",e),N.None}}parseStaves(e,t){let s=0;for(let i of t.childNodes)if(i.nodeType===Ne.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===Ne.Element&&"Properties"===s.localName)this.parseStaffProperties(e,s)}parseStaffProperties(e,t){for(let s of t.childNodes)if(s.nodeType===Ne.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===Ne.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===Ne.Element&&"Line"===e.localName)s.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,s)}parseLyricsLine(e){let t=new he;for(let s of e.childNodes)if(s.nodeType===Ne.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===Ne.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===Ne.Element&&"Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){let s=new oe,i=t.getAttribute("id");for(let t of e.staves)t.addChord(i,s);this.parseDiagramItemForChord(s,t)}parseDiagramItemForStaff(e,t){let s=new oe,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=parseInt(s.getAttribute("baseFret"));e.firstFret=a+1;for(let t=0;t<i;t++)e.strings.push(-1);for(let t of s.childNodes)if(t.nodeType===Ne.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===Ne.Element&&"Position"===s.localName){let t=f.Unknown,i=a+parseInt(s.getAttribute("fret"));switch(s.getAttribute("finger")){case"Index":t=f.IndexFinger;break;case"Middle":t=f.MiddleFinger;break;case"Rank":t=f.AnnularFinger;break;case"Pinky":t=f.LittleFinger;break;case"Thumb":t=f.Thumb}t!==f.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===Ne.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===Ne.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===Ne.Element&&"Sound"===i.localName)this.parseSound(e,t,i)}parseSound(e,t,s){const i=new gt;for(let e of s.childNodes)if(e.nodeType===Ne.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===Ne.Element&&"Program"===s.localName)e.program=parseInt(s.innerText)}parsePartSounding(e,t){for(let s of t.childNodes)if(s.nodeType===Ne.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===Ne.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===Ne.Element&&"ChannelStrip"===s.localName)this.parseChannelStrip(e,s)}parseChannelStrip(e,t){for(let s of t.childNodes)if(s.nodeType===Ne.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===Ne.Element&&"MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){let t=new le;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(let s of e.childNodes)if(s.nodeType===Ne.Element)switch(s.localName){case"Time":let e=s.innerText.split("/");t.timeSignatureNumerator=parseInt(e[0]),t.timeSignatureDenominator=parseInt(e[1]);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=D.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=D.Triplet8th;break;case"Triplet16th":t.tripletFeel=D.Triplet16th;break;case"Dotted8th":t.tripletFeel=D.Dotted8th;break;case"Dotted16th":t.tripletFeel=D.Dotted16th;break;case"Scottish8th":t.tripletFeel=D.Scottish8th;break;case"Scottish16th":t.tripletFeel=D.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=I.Major;break;case"minor":t.keySignatureType=I.Minor}break;case"Fermatas":this.parseFermatas(t,s);break;case"XProperties":this.parseMasterBarXProperties(s,t)}this._masterBars.push(t)}parseFermatas(e,t){for(let s of t.childNodes)if(s.nodeType===Ne.Element&&"Fermata"===s.localName)this.parseFermata(e,s)}parseFermata(e,t){let s=0,i=new ot;for(let e of t.childNodes)if(e.nodeType===Ne.Element)switch(e.localName){case"Type":switch(e.innerText){case"Short":i.type=xe.Short;break;case"Medium":i.type=xe.Medium;break;case"Long":i.type=xe.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])*W.QuarterTime|0}}e.addFermata(s,i)}parseBars(e){for(let t of e.childNodes)if(t.nodeType===Ne.Element&&"Bar"===t.localName)this.parseBar(t)}parseBar(e){let t=new H,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===Ne.Element)switch(i.localName){case"Voices":this._voicesOfBar.set(s,i.innerText.split(" "));break;case"Clef":switch(i.innerText){case"Neutral":t.clef=r.Neutral;break;case"G2":t.clef=r.G2;break;case"F4":t.clef=r.F4;break;case"C4":t.clef=r.C4;break;case"C3":t.clef=r.C3}break;case"Ottavia":switch(i.innerText){case"8va":t.clefOttava=n._8va;break;case"15ma":t.clefOttava=n._15ma;break;case"8vb":t.clefOttava=n._8vb;break;case"15mb":t.clefOttava=n._15mb}break;case"SimileMark":switch(i.innerText){case"Simple":t.simileMark=o.Simple;break;case"FirstOfDouble":t.simileMark=o.FirstOfDouble;break;case"SecondOfDouble":t.simileMark=o.SecondOfDouble}break;case"XProperties":this.parseBarXProperties(i,t)}this._barsById.set(s,t)}parseVoices(e){for(let t of e.childNodes)if(t.nodeType===Ne.Element&&"Voice"===t.localName)this.parseVoice(t)}parseVoice(e){let t=new _e,s=e.getAttribute("id");for(let t of e.childNodes)if(t.nodeType===Ne.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===Ne.Element&&"Beat"===t.localName)this.parseBeat(t)}parseBeat(e){let t=new ne,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===Ne.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":"FadeIn"===i.innerText&&(t.fadeIn=!0);break;case"Tremolo":switch(i.innerText){case"1/2":t.tremoloSpeed=u.Eighth;break;case"1/4":t.tremoloSpeed=u.Sixteenth;break;case"1/8":t.tremoloSpeed=u.ThirtySecond}break;case"Chord":t.chordId=i.innerText;break;case"Hairpin":switch(i.innerText){case"Crescendo":t.crescendo=d.Crescendo;break;case"Decrescendo":t.crescendo=d.Decrescendo}break;case"Arpeggio":"Up"===i.innerText?t.brushType=c.ArpeggioUp:t.brushType=c.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=Ce.Up;break;case"Downward":t.preferredBeamDirection=Ce.Down}break;case"Dynamic":switch(i.innerText){case"PPP":t.dynamics=p.PPP;break;case"PP":t.dynamics=p.PP;break;case"P":t.dynamics=p.P;break;case"MP":t.dynamics=p.MP;break;case"MF":t.dynamics=p.MF;break;case"F":t.dynamics=p.F;break;case"FF":t.dynamics=p.FF;break;case"FFF":t.dynamics=p.FFF}break;case"GraceNotes":switch(i.innerText){case"OnBeat":t.graceType=g.OnBeat;break;case"BeforeBeat":t.graceType=g.BeforeBeat}break;case"Legato":"true"===i.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":let e=new z(0,0);e.value=this.toBendValue(parseFloat(i.getAttribute("originValue"))),e.offset=this.toBendOffset(parseFloat(i.getAttribute("originOffset"))),t.addWhammyBarPoint(e);let a=new z(0,0);a.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),a.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);let r=new z(0,0);r.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),r.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);let o=new z(0,0);o.value=this.toBendValue(parseFloat(i.getAttribute("destinationValue"))),o.offset=this.toBendOffset(parseFloat(i.getAttribute("destinationOffset"))),t.addWhammyBarPoint(o);break;case"Ottavia":switch(i.innerText){case"8va":t.ottava=n._8va;break;case"8vb":t.ottava=n._8vb;break;case"15ma":t.ottava=n._15ma;break;case"15mb":t.ottava=n._15mb}break;case"Lyrics":t.lyrics=this.parseBeatLyrics(i),this._skipApplyLyrics=!0}this._beatById.set(s,t)}parseBeatLyrics(e){const t=[];for(let s of e.childNodes)if(s.nodeType===Ne.Element&&"Line"===s.localName)t.push(s.innerText);return t}parseBeatXProperties(e,t){for(let s of e.childNodes)if(s.nodeType===Ne.Element&&"XProperty"===s.localName){let e=0;switch(s.getAttribute("id")){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===Ne.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 e.childNodes)if(s.nodeType===Ne.Element&&"XProperty"===s.localName){if("1124073984"===s.getAttribute("id"))t.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===Ne.Element&&"Property"===h.localName){switch(h.getAttribute("name")){case"Brush":"Up"===h.findChildElement("Direction").innerText?t.brushType=c.BrushUp:t.brushType=c.BrushDown;break;case"PickStroke":"Up"===h.findChildElement("Direction").innerText?t.pickStroke=x.Up:t.pickStroke=x.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=_.Wide;break;case"Slight":t.vibrato=_.Slight}break;case"WhammyBar":s=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":i||(i=new z(0,0)),i.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":i||(i=new z(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 z(z.MaxPosition,0)),o.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new z(0,0)),o.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText))}}s&&(i||(i=new z(0,0)),o||(o=new z(z.MaxPosition,0)),t.addWhammyBarPoint(i),r&&a&&t.addWhammyBarPoint(new z(r,a)),n&&a&&t.addWhammyBarPoint(new z(n,a)),r||n||!a||t.addWhammyBarPoint(new z(z.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(let t of e.childNodes)if(t.nodeType===Ne.Element&&"Note"===t.localName)this.parseNote(t)}parseNote(e){let t=new Z,s=e.getAttribute("id");for(let a of e.childNodes)if(a.nodeType===Ne.Element)switch(a.localName){case"Properties":this.parseNoteProperties(a,t,s);break;case"AntiAccent":"normal"===a.innerText.toLowerCase()&&(t.isGhost=!0);break;case"LetRing":t.isLetRing=!0;break;case"Trill":t.trillValue=parseInt(a.innerText),t.trillSpeed=u.Sixteenth;break;case"Accent":let e=parseInt(a.innerText);1&e&&(t.isStaccato=!0),4&e&&(t.accentuated=i.Heavy),8&e&&(t.accentuated=i.Normal);break;case"Tie":"true"===a.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(a.innerText){case"Slight":t.vibrato=_.Slight;break;case"Wide":t.vibrato=_.Wide}break;case"LeftFingering":switch(t.isFingering=!0,a.innerText){case"P":t.leftHandFinger=f.Thumb;break;case"I":t.leftHandFinger=f.IndexFinger;break;case"M":t.leftHandFinger=f.MiddleFinger;break;case"A":t.leftHandFinger=f.AnnularFinger;break;case"C":t.leftHandFinger=f.LittleFinger}break;case"RightFingering":switch(t.isFingering=!0,a.innerText){case"P":t.rightHandFinger=f.Thumb;break;case"I":t.rightHandFinger=f.IndexFinger;break;case"M":t.rightHandFinger=f.MiddleFinger;break;case"A":t.rightHandFinger=f.AnnularFinger;break;case"C":t.rightHandFinger=f.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=parseInt(a.innerText)}this._noteById.set(s,t)}parseNoteProperties(e,t,s){let i=!1,a=null,r=null,n=null,o=null,h=null,l=-1,c=-1;for(let d of e.childNodes)if(d.nodeType===Ne.Element&&"Property"===d.localName){switch(d.getAttribute("name")){case"String":t.string=parseInt(d.findChildElement("String").innerText)+1;break;case"Fret":t.fret=parseInt(d.findChildElement("Fret").innerText);break;case"Element":l=parseInt(d.findChildElement("Element").innerText);break;case"Variation":c=parseInt(d.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(s,!0);break;case"HarmonicType":let e=d.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=m.None;break;case"Natural":t.harmonicType=m.Natural;break;case"Artificial":t.harmonicType=m.Artificial;break;case"Pinch":t.harmonicType=m.Pinch;break;case"Tap":t.harmonicType=m.Tap;break;case"Semi":t.harmonicType=m.Semi;break;case"Feedback":t.harmonicType=m.Feedback}break;case"HarmonicFret":let u=d.findChildElement("HFret");u&&(t.harmonicValue=parseFloat(u.innerText));break;case"Muted":d.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":d.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=parseInt(d.findChildElement("Number").innerText),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=parseInt(d.findChildElement("Step").innerText);break;case"ConcertPitch":this.parseConcertPitch(d,t);break;case"Bended":i=!0;break;case"BendOriginValue":a||(a=new z(0,0)),a.value=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new z(0,0)),a.offset=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleValue":r=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleOffset1":n=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleOffset2":o=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationValue":h||(h=new z(z.MaxPosition,0)),h.value=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new z(0,0)),h.offset=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"HopoOrigin":d.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":let p=parseInt(d.findChildElement("Flags").innerText);1&p?t.slideOutType=S.Shift:2&p?t.slideOutType=S.Legato:4&p?t.slideOutType=S.OutDown:8&p&&(t.slideOutType=S.OutUp),16&p?t.slideInType=b.IntoFromBelow:32&p&&(t.slideInType=b.IntoFromAbove),64&p?t.slideOutType=S.PickSlideDown:128&p&&(t.slideOutType=S.PickSlideUp)}}i&&(a||(a=new z(0,0)),h||(h=new z(z.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new z(n,r)),o&&r&&t.addBendPoint(new z(o,r)),n||o||!r||t.addBendPoint(new z(z.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==c&&(t.percussionArticulation=$.articulationFromElementVariation(l,c))}parseConcertPitch(e,t){const s=e.findChildElement("Pitch");if(s)for(let e of s.childNodes)if(e.nodeType===Ne.Element&&"Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=y.ForceDoubleSharp;break;case"#":t.accidentalMode=y.ForceSharp;break;case"b":t.accidentalMode=y.ForceFlat;break;case"bb":t.accidentalMode=y.ForceDoubleFlat}}toBendValue(e){return e*ft.BendPointValueFactor|0}toBendOffset(e){return e*ft.BendPointPositionFactor}parseRhythms(e){for(let t of e.childNodes)if(t.nodeType===Ne.Element&&"Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){let t=new pt,s=e.getAttribute("id");t.id=s;for(let s of e.childNodes)if(s.nodeType===Ne.Element)switch(s.localName){case"NoteValue":switch(s.innerText){case"Long":t.value=u.QuadrupleWhole;break;case"DoubleWhole":t.value=u.DoubleWhole;break;case"Whole":t.value=u.Whole;break;case"Half":t.value=u.Half;break;case"Quarter":t.value=u.Quarter;break;case"Eighth":t.value=u.Eighth;break;case"16th":t.value=u.Sixteenth;break;case"32nd":t.value=u.ThirtySecond;break;case"64th":t.value=u.SixtyFourth;break;case"128th":t.value=u.OneHundredTwentyEighth;break;case"256th":t.value=u.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!==ft.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!==ft.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!==ft.InvalidId){let t=ae.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!==ft.InvalidId){const e=se.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 _e;e.addVoice(t);let s=new ne;s.isEmpty=!0,s.duration=u.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)}}}}for(const[e,t]of this._masterTrackAutomations){let s=this.score.masterBars[e];for(let i=0,r=t.length;i<r;i++){let r=t[i];r.type===a.Tempo&&(0===e&&(this.score.tempo=0|r.value,r.text&&(this.score.tempoLabel=r.text)),s.tempoAutomation=r)}}}}ft.InvalidId="-1",ft.BendPointPositionFactor=z.MaxPosition/100,ft.BendPointValueFactor=.04;class mt{constructor(){this.isMultiRest=!1,this.trackViewGroups=[]}}class yt{constructor(){this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class bt{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}t++}}}constructor(e){this.scoreViews=[];let t=Te.fromBuffer(e);const s=Be.readInt32BE(t);for(let e=0;e<s;e++){const e=new mt;this.scoreViews.push(e),e.isMultiRest=it.gpReadBool(t);const s=Be.readInt32BE(t);for(let i=0;i<s;i++){let s=t.readByte();0===s&&(s=1);let i=new yt;i.showStandardNotation=!!(1&s),i.showTablature=!!(2&s),i.showSlash=!!(4&s),e.trackViewGroups.push(i)}}}static writeForScore(e){const t=Te.withCapacity(128),s=[new mt];for(const t of e.tracks){const e=new yt;e.showStandardNotation=t.staves[0].showStandardNotation,e.showTablature=t.staves[0].showTablature,s[0].trackViewGroups.push(e);const i=new mt;i.trackViewGroups.push(e),s.push(i)}Be.writeInt32BE(t,s.length);for(const e of s){t.writeByte(e.isMultiRest?1:0),Be.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),t.writeByte(e)}}return Be.writeInt32BE(t,1),t.toArray()}}class St{}class _t extends St{constructor(e){super(),this.n=e}}class wt extends St{constructor(e,t){super(),this.left=e,this.right=t}}class Bt extends St{constructor(e,t){super(),this.n=e,this.table=t}}class Tt{static make(e,t,s,i){let a=[],r=[];if(i>32)throw new ge("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 ge("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 Tt.treeCompress(new wt(Tt.treeMake(o,i,0,1),Tt.treeMake(o,i,1,1)))}static treeMake(e,t,s,i){if(i>t)throw new ge("Invalid huffman");let a=s<<5|i;return e.has(a)?new _t(e.get(a)):(s<<=1,i+=1,new wt(Tt.treeMake(e,t,s,i),Tt.treeMake(e,t,1|s,i)))}static treeCompress(e){let t=Tt.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof wt)return new wt(Tt.treeCompress(e.left),Tt.treeCompress(e.right));throw new ge("assert")}let s=1<<t,i=[];for(let e=0;e<s;e++)i.push(new _t(-1));return Tt.treeWalk(i,0,0,t,e),new Bt(t,i)}static treeWalk(e,t,s,i,a){a instanceof wt&&i>0?(Tt.treeWalk(e,t,s+1,i-1,a.left),Tt.treeWalk(e,t|1<<s,s+1,i-1,a.right)):e[t]=Tt.treeCompress(a)}static treeDepth(e){if(e instanceof _t)return 0;if(e instanceof Bt)throw new ge("assert");if(e instanceof wt){let t=Tt.treeDepth(e.left),s=Tt.treeDepth(e.right);return 1+(t<s?t:s)}return 0}}!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"}(Ee||(Ee={}));class kt{constructor(){this.buffer=new Uint8Array(kt.BufferSize),this.pos=0}slide(){let e=new Uint8Array(kt.BufferSize);this.pos-=kt.Size,e.set(this.buffer.subarray(kt.Size,kt.Size+this.pos),0),this.buffer=e}addBytes(e,t,s){this.pos+s>kt.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+s),this.pos),this.pos+=s}addByte(e){this.pos===kt.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}kt.Size=32768,kt.BufferSize=65536;class vt{static buildFixedHuffman(){let e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return Tt.make(e,0,288,10)}constructor(e){this._nbits=0,this._bits=0,this._state=Ee.Block,this._isFinal=!1,this._huffman=vt._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new kt,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 Ee.Head:let e=this._input.readByte();if(8!==(15&e))throw new ge("Invalid data");let t=this._input.readByte(),s=!!(32&t);if(((e<<8)+t)%31!=0)throw new ge("Invalid data");if(s)throw new ge("Unsupported dictionary");return this._state=Ee.Block,!0;case Ee.Crc:return this._state=Ee.Done,!0;case Ee.Done:return!1;case Ee.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:if(this._len=Be.readUInt16LE(this._input),Be.readUInt16LE(this._input)!==65535-this._len)throw new ge("Invalid data");this._state=Ee.Flat;let e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=vt._fixedHuffman,this._huffdist=null,this._state=Ee.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[vt.CodeLengthsPos[e]]=this.getBits(3);for(let e=i;e<19;e++)this._lengths[vt.CodeLengthsPos[e]]=0;this._huffman=Tt.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=Tt.make(a,t,s,16),this._huffman=Tt.make(a,0,t,16),this._state=Ee.CData,!0;default:throw new ge("Invalid data")}case Ee.Flat:{let e=this._len<this._needed?this._len:this._needed,t=Be.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?Ee.Crc:Ee.Block),this._needed>0}case Ee.DistOne:{let e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=Ee.CData),this._needed>0}case Ee.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=Ee.CData),this._needed>0;case Ee.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?Ee.Crc:Ee.Block,!0;{i=i-257&255;let e=vt.LenExtraBitsTbl[i];if(-1===e)throw new ge("Invalid data");this._len=vt.LenBaseValTbl[i]+this.getBits(e);let t=this._huffdist,s=t?this.applyHuffman(t):this.getRevBits(5);if(e=vt.DistExtraBitsTbl[s],-1===e)throw new ge("Invalid data");if(this._dist=vt.DistBaseValTbl[s]+this.getBits(e),this._dist>this._window.available())throw new ge("Invalid data");return this._state=1===this._dist?Ee.DistOne:Ee.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 ge("Invalid data");for(;s<r;)e[s]=i,s++;break;case 17:if(s+=3+this.getBits(3),s>t)throw new ge("Invalid data");break;case 18:if(s+=11+this.getBits(7),s>t)throw new ge("Invalid data");break;default:throw new ge("Invalid data")}}}applyHuffman(e){if(e instanceof _t)return e.n;if(e instanceof wt)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof Bt)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new ge("Invalid data")}}vt.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],vt.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],vt.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],vt.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],vt.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],vt._fixedHuffman=vt.buildFixedHuffman();class xt{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}}xt.OptionalDataDescriptorSignature=134695760,xt.CompressionMethodDeflate=8,xt.LocalFileHeaderSignature=67324752,xt.CentralFileHeaderSignature=33639248,xt.EndOfCentralDirSignature=101010256;class Nt{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(Be.readInt32LE(e)!==xt.LocalFileHeaderSignature)return null;Be.readUInt16LE(e);let t=Be.readUInt16LE(e),s=Be.readUInt16LE(e),i=0!==s;if(i&&s!==xt.CompressionMethodDeflate)return null;Be.readInt16LE(this._readable),Be.readInt16LE(this._readable),Be.readInt32LE(e),Be.readInt32LE(e);let a,r=Be.readInt32LE(e),n=Be.readInt16LE(e),o=Be.readInt16LE(e),h=Be.toString(Be.readByteArray(e,n),"utf-8");if(e.skip(o),i){let e=Te.empty(),t=new vt(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=Be.readByteArray(this._readable,r);if(8&t){Be.readInt32LE(this._readable)===xt.OptionalDataDescriptorSignature&&Be.readInt32LE(this._readable),Be.readInt32LE(this._readable),Be.readInt32LE(this._readable)}return new xt(h,a)}}class Pt extends R{get name(){return"Guitar Pro 7"}constructor(){super()}readScore(){q.debug(this.name,"Loading ZIP entries");let e,t=new Nt(this.data);try{e=t.read()}catch(e){throw new G("No Zip archive",e)}q.debug(this.name,"Zip entries loaded");let s=null,i=null,a=null;for(let t of e)switch(t.fileName){case"score.gpif":s=Be.toString(t.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=t.data;break;case"PartConfiguration":a=t.data}if(!s)throw new G("No score.gpif found in zip archive");q.debug(this.name,"Start Parsing score.gpif");let r=new ft;r.parseXml(s,this.settings),q.debug(this.name,"score.gpif parsed");let n=r.score;if(i){q.debug(this.name,"Start Parsing BinaryStylesheet"),new nt(i).apply(n),q.debug(this.name,"BinaryStylesheet parsed")}if(a){q.debug(this.name,"Start Parsing Part Configuration"),new bt(a).apply(n),q.debug(this.name,"Part Configuration parsed")}return n}}class Ct extends O{constructor(){super(s.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,Ct.prototype)}}class Et{constructor(e){this._currentByte=0,this._position=Et.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 Ct;this._position=0}const e=this._currentByte>>Et.ByteSize-this._position-1&1;return this._position++,e}readAll(){let e=Te.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof Ct))throw e}return e.toArray()}}Et.ByteSize=8;class Ft{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class Lt{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){let t=new Et(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){let s,i=Te.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 Ct))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 G("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 Ft;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?Te.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]}}Lt.HeaderBcFs="BCFS",Lt.HeaderBcFz="BCFZ",Lt.ScoreGpif="score.gpif",Lt.BinaryStylesheet="BinaryStylesheet",Lt.PartConfiguration="PartConfiguration";class Mt extends R{get name(){return"Guitar Pro 6"}constructor(){super()}readScore(){q.debug(this.name,"Loading GPX filesystem");let e=new Lt;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration"),e.load(this.data),q.debug(this.name,"GPX filesystem loaded");let t=null,s=null,i=null;for(let a of e.files)switch(a.fileName){case"score.gpif":t=Be.toString(a.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=a.data;break;case"PartConfiguration":i=a.data}if(!t)throw new G("No score.gpif found in GPX");q.debug(this.name,"Start Parsing score.gpif");let a=new ft;a.parseXml(t,this.settings),q.debug(this.name,"score.gpif parsed");let r=a.score;if(s){q.debug(this.name,"Start Parsing BinaryStylesheet"),new nt(s).apply(r),q.debug(this.name,"BinaryStylesheet parsed")}if(i){q.debug(this.name,"Start Parsing Part Configuration"),new bt(i).apply(r),q.debug(this.name,"Part Configuration parsed")}return r}}class It extends R{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=Be.toString(this.data.readAll(),this.settings.importer.encoding),t=new ut;try{t.parse(e)}catch(e){throw new G("Unsupported format")}return this._score=new ue,this._score.tempo=120,this.parseDom(t),this.settings.importer.mergePartGroupsInMusicXml&&this.mergePartGroups(),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}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 G("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":break;default:throw new G("Unsupported format")}}parsePartwise(e){for(let t of e.childNodes)if(t.nodeType===Ne.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===Ne.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===Ne.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 H;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===Ne.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 _e;e.addVoice(t);let s=new ne;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 c=this.getOrCreateVoice(n,i);return s&&c.beats.length>0||1===c.beats.length&&c.isEmpty?o=c.beats[c.beats.length-1]:(o=new ne,o.isEmpty=!1,c.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)*u.Quarter/this._divisionsPerQuarterNote,a=[u.SixtyFourth,u.ThirtySecond,u.Sixteenth,u.Eighth,u.Quarter,u.Half,u.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===Ne.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===Ne.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=j.getTuningForText(i+a)+r;for(let e of t.staves)e.tuning[e.tuning.length-s]=n}parseHarmony(e,t,s){let i=new oe;for(let t of e.childNodes)if(t.nodeType===Ne.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=j.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===Ne.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===Ne.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===Ne.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 Z;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===Ne.Element)switch(t.localName){case"grace":i.graceType=g.BeforeBeat,i.duration=u.ThirtySecond;break;case"duration":if(i.isRest&&!r){switch(parseInt(t.innerText)){case 1:i.duration=u.Whole;break;case 2:i.duration=u.Half;break;case 4:default:i.duration=u.Quarter;break;case 8:i.duration=u.Eighth;break;case 16:i.duration=u.Sixteenth;break;case 32:i.duration=u.ThirtySecond;break;case 64:i.duration=u.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!==g.None&&i.duration<u.Sixteenth&&(i.duration=u.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=u.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 u.SixtyFourth;case"32nd":return u.ThirtySecond;case"16th":return u.Sixteenth;case"eighth":return u.Eighth;case"quarter":return u.Quarter;case"half":return u.Half;case"long":case"breve":case"whole":return u.Whole}return u.Quarter}parseLyric(e,t){for(let s of e.childNodes)if(s.nodeType===Ne.Element&&"text"===s.localName)t.text?t.text+=" "+s.innerText:t.text=s.innerText}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=y.ForceSharp;break;case"natural":t.accidentalMode=y.ForceNatural;break;case"flat":t.accidentalMode=y.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===Ne.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=S.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===Ne.Element&&"tremolo"===s.localName){switch(parseInt(s.innerText)){case 1:t.beat.tremoloSpeed=u.Eighth;break;case 2:t.beat.tremoloSpeed=u.Sixteenth;break;case 3:t.beat.tremoloSpeed=u.ThirtySecond}}}parseTechnical(e,t){for(let s of e.childNodes)if(s.nodeType===Ne.Element)switch(s.localName){case"string":t.string=parseInt(s.innerText),-2147483648!==t.string&&(t.string=t.beat.voice.bar.staff.tuning.length-t.string+1);break;case"fret":t.fret=parseInt(s.innerText);break;case"down-bow":t.beat.pickStroke=x.Down;break;case"up-bow":t.beat.pickStroke=x.Up}-2147483648!==t.string&&-2147483648!==t.fret||(t.string=-1,t.fret=-1)}parseArticulations(e,t){for(let s of e.childNodes)switch(s.localName){case"accent":t.accentuated=i.Normal;break;case"strong-accent":t.accentuated=i.Heavy;break;case"staccato":case"detached-legato":t.isStaccato=!0}}parseDynamics(e,t){for(let s of e.childNodes)if(s.nodeType===Ne.Element)switch(s.localName){case"p":t.dynamics=p.P;break;case"pp":t.dynamics=p.PP;break;case"ppp":t.dynamics=p.PPP;break;case"f":t.dynamics=p.F;break;case"ff":t.dynamics=p.FF;break;case"fff":t.dynamics=p.FFF;break;case"mp":t.dynamics=p.MP;break;case"mf":t.dynamics=p.MF}}parseTimeModification(e,t){for(let s of e.childNodes)if(s.nodeType===Ne.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===Ne.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+j.getToneForText(s)+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===Ne.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+j.getToneForText(s)+(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 _e);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===Ne.Element)switch(s.localName){case"sound":let e=s.getAttribute("tempo");if(e){let s=new V;s.isLinear=!0,s.type=a.Tempo,s.value=parseInt(e),t.tempoAutomation=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=u.Quarter,i=120;for(let t of e.childNodes)if(t.nodeType===Ne.Element)switch(t.localName){case"beat-unit":s=this.getDuration(t.innerText);break;case"per-minute":i=parseInt(t.innerText)}let r=new V;r.type=a.Tempo,r.value=i*(s/4|0),t.tempoAutomation=r,0===t.index&&(t.score.tempo=r.value)}parseAttributes(e,t,s,i){let a=0,r=!1;for(let n of e.childNodes)if(n.nodeType===Ne.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===Ne.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===Ne.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=n._15mb;break;case-1:t.clefOttava=n._8vb;break;case 1:t.clefOttava=n._8va;break;case 2:t.clefOttava=n._15mb}}switch(s){case"g":default:t.clef=r.G2;break;case"f":t.clef=r.F4;break;case"c":t.clef=3===i?r.C3:r.C4;break;case"percussion":t.clef=r.Neutral,t.staff.isPercussion=!0;break;case"tab":t.clef=r.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===Ne.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===Ne.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:L.C,t.keySignatureType="minor"===i?I.Minor:I.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 le;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===Ne.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===Ne.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 Se;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===Ne.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===Ne.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)))}}}!function(e){e[e.SingleTrackMultiChannel=0]="SingleTrackMultiChannel",e[e.MultiTrack=1]="MultiTrack"}(Fe||(Fe={}));class Dt{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=Te.empty(),s=0;for(let e of this.events){let i=e.tick-s;At.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();Be.writeInt32BE(e,a.length),e.write(a,0,a.length)}}class At{constructor(){this.format=Fe.SingleTrackMultiChannel,this.division=W.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 Dt)}addEvent(e){this.format==Fe.SingleTrackMultiChannel?(this.ensureTracks(1),this.tracks[0].addEvent(e)):(this.ensureTracks(e.track+1),this.tracks[e.track].addEvent(e))}toBinary(){let e=Te.empty();return this.writeTo(e),e.toArray()}writeTo(e){let t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),Be.writeInt32BE(e,6),Be.writeInt16BE(e,this.format),Be.writeInt16BE(e,this.tracks.length),Be.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"}(Le||(Le={}));class Rt{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 Ot extends Rt{constructor(e,t,s,i,a,r){super(e,t,Le.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),At.writeVariableInt(e,4),e.writeByte(255&this.numerator),e.writeByte(255&this.denominatorIndex),e.writeByte(255&this.midiClocksPerMetronomeClick),e.writeByte(255&this.thirtySecondNodesInQuarter)}}class Gt extends Rt{constructor(e,t,s){super(e,t,s)}writeTo(e){e.writeByte(240);const t=Te.withCapacity(16);t.writeByte(Gt.AlphaTabManufacturerId),this.writeEventData(t),t.writeByte(247),At.writeVariableInt(e,t.length),t.copyTo(e)}}Gt.AlphaTabManufacturerId=125,Gt.MetronomeEventId=0,Gt.RestEventId=1;class Vt extends Gt{constructor(e,t,s,i,a){super(e,t,Le.AlphaTabMetronome),this.isMetronome=!0,this.metronomeNumerator=s,this.metronomeDurationInMilliseconds=a,this.metronomeDurationInTicks=i}writeEventData(e){e.writeByte(Gt.MetronomeEventId),e.writeByte(this.metronomeNumerator),Be.writeInt32LE(e,this.metronomeDurationInTicks),Be.writeInt32LE(e,this.metronomeDurationInMilliseconds)}}class Ht extends Gt{constructor(e,t,s){super(e,t,Le.AlphaTabRest),this.channel=s}writeEventData(e){e.writeByte(Gt.RestEventId),e.writeByte(this.channel)}}class Wt extends Rt{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 zt extends Wt{constructor(e,t,s,i,a){super(e,t,Le.NoteOn,s,i,a)}writeTo(e){e.writeByte(15&this.channel|144),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class Ut extends Wt{constructor(e,t,s,i,a){super(e,t,Le.NoteOff,s,i,a)}writeTo(e){e.writeByte(15&this.channel|128),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class Xt extends Rt{constructor(e,t,s,i,a){super(e,t,Le.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 Yt extends Rt{constructor(e,t,s,i){super(e,t,Le.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 qt extends Rt{constructor(e,t){super(0,e,Le.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 Jt extends Rt{constructor(e,t,s,i){super(e,t,Le.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 jt extends Rt{constructor(e,t,s,i,a){super(e,t,Le.PerNotePitchBend),this.channel=s,this.noteKey=i,this.value=a}writeTo(e){throw new O(s.General,"Note Bend (Midi2.0) events cannot be exported to SMF1.0")}}class Qt extends Rt{constructor(e,t){super(e,t,Le.EndOfTrack)}writeTo(e){e.writeByte(255),e.writeByte(47),e.writeByte(0)}}class $t{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event.type==Le.AlphaTabMetronome}static newMetronomeEvent(e,t,s,i,a){const r=new Vt(0,t,s,i,a);return new $t(e,r)}}class Kt{}Kt.DefaultChannelCount=17,Kt.MetronomeChannel=Kt.DefaultChannelCount-1,Kt.AudioChannels=2,Kt.MinVolume=0,Kt.MinProgram=0,Kt.MaxProgram=127,Kt.MinPlaybackSpeed=.125,Kt.MaxPlaybackSpeed=8,Kt.MaxPitchWheel=16384,Kt.MaxPitchWheel20=4294967296,Kt.DefaultPitchWheel=Kt.MaxPitchWheel/2,Kt.MicroBufferCount=32,Kt.MicroBufferSize=64;class Zt{constructor(e,t,s){this.bpm=e,this.ticks=t,this.time=s}}class es{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=W.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class ts{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._synthesizer=e,this._mainState=new es,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(Kt.MicroBufferSize);this._mainState.currentTime=s;let i=Date.now()-t;q.debug("Sequencer","Silent seek finished in "+i+"ms (main)")}loadOneTimeMidi(e){this._oneTimeState=this.createStateFromFile(e),this._currentState=this._oneTimeState}loadMidi(e){this._mainState=this.createStateFromFile(e),this._currentState=this._mainState}createStateFromFile(e){const t=new es;t.tempoChanges=[],t.division=e.division,t.eventIndex=0,t.currentTime=0,t.synthData=[];let s=120,i=0,a=0,r=0,n=0,o=0,h=0,l=0,c=0;for(let d of e.events){let u=new $t(t.synthData.length,d);t.synthData.push(u);let p=d.tick-c;if(i+=p,a+=p*(6e4/(s*e.division)),u.time=a,c=d.tick,n>0)for(;h<i;){let e=$t.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(d.type===Le.TempoChange){s=6e7/d.microSecondsPerQuarterNote,t.tempoChanges.push(new Zt(s,i,a)),o=n*(6e4/(s*e.division))}else if(d.type===Le.TimeSignature){let i=d,a=Math.pow(2,i.denominatorIndex);r=i.numerator,n=t.division*(4/a)|0,o=n*(6e4/(s*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=i.numerator,t.firstTimeSignatureDenominator=a)}else if(d.type===Le.ProgramChange){let e=d.channel;t.firstProgramEventPerChannel.has(e)||t.firstProgramEventPerChannel.set(e,u)}}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=Kt.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 es;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 Zt(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=$t.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"}(Me||(Me={}));class ss{constructor(e,t){this.state=e,this.stopped=t}}class is{constructor(e,t,s,i,a){this.currentTime=e,this.endTime=t,this.currentTick=s,this.endTick=i,this.isSeek=a}}class as{constructor(){this.id="",this.size=0}static load(e,t,s){if(e&&as.HeaderSize>e.size)return!1;if(s.position+as.HeaderSize>=s.length)return!1;if(t.id=Be.read8BitStringLength(s,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=Be.readUInt32LE(s),e&&as.HeaderSize+t.size>e.size)return!1;e&&(e.size-=as.HeaderSize+t.size);let i="RIFF"===t.id,a="LIST"===t.id;return(!i||!e)&&(!i&&!a||(t.id=Be.read8BitStringLength(s,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}as.HeaderSize=8;class rs{constructor(){this.phdrs=[],this.pbags=[],this.pmods=[],this.pgens=[],this.insts=[],this.ibags=[],this.imods=[],this.igens=[],this.sHdrs=[],this.fontSamples=new Float32Array(0)}load(e){const t=new as,s=new as;if(!as.load(null,t,e)||"sfbk"!==t.id)throw new ge("Soundfont is not a valid Soundfont2 file");for(;as.load(t,s,e);){let t=new as;if("pdta"===s.id)for(;as.load(s,t,e);)switch(t.id){case"phdr":for(let s=0,i=t.size/us.SizeInFile|0;s<i;s++)this.phdrs.push(new us(e));break;case"pbag":for(let s=0,i=t.size/cs.SizeInFile|0;s<i;s++)this.pbags.push(new cs(e));break;case"pmod":for(let s=0,i=t.size/ps.SizeInFile|0;s<i;s++)this.pmods.push(new ps(e));break;case"pgen":for(let s=0,i=t.size/ds.SizeInFile|0;s<i;s++)this.pgens.push(new ds(e));break;case"inst":for(let s=0,i=t.size/ls.SizeInFile|0;s<i;s++)this.insts.push(new ls(e));break;case"ibag":for(let s=0,i=t.size/ns.SizeInFile|0;s<i;s++)this.ibags.push(new ns(e));break;case"imod":for(let s=0,i=t.size/os.SizeInFile|0;s<i;s++)this.imods.push(new os(e));break;case"igen":for(let s=0,i=t.size/hs.SizeInFile|0;s<i;s++)this.igens.push(new hs(e));break;case"shdr":for(let s=0,i=t.size/gs.SizeInFile|0;s<i;s++)this.sHdrs.push(new gs(e));break;default:e.position+=t.size}else if("sdta"===s.id)for(;as.load(s,t,e);)if("smpl"===t.id)this.fontSamples=rs.loadSamples(t,e);else e.position+=t.size;else e.position+=s.size}}static loadSamples(e,t){let s=e.size/2|0;const i=new Float32Array(s);let a=0;const r=new Uint8Array(16384);for(;s>0;){let e=Math.min(s,r.length/2|0);t.read(r,0,2*e);for(let t=0;t<e;t++){const e=we.int32ToInt16(r[2*t+1]<<8|r[2*t]);i[a+t]=e/32767}s-=e,a+=e}return i}}class ns{constructor(e){this.instGenNdx=Be.readUInt16LE(e),this.instModNdx=Be.readUInt16LE(e)}}ns.SizeInFile=4;class os{constructor(e){this.modSrcOper=Be.readUInt16LE(e),this.modDestOper=Be.readUInt16LE(e),this.modAmount=Be.readInt16LE(e),this.modAmtSrcOper=Be.readUInt16LE(e),this.modTransOper=Be.readUInt16LE(e)}}os.SizeInFile=10;class hs{constructor(e){this.genOper=Be.readUInt16LE(e),this.genAmount=new fs(e)}}hs.SizeInFile=4;class ls{constructor(e){this.instName=Be.read8BitStringLength(e,20),this.instBagNdx=Be.readUInt16LE(e)}}ls.SizeInFile=22;class cs{constructor(e){this.genNdx=Be.readUInt16LE(e),this.modNdx=Be.readUInt16LE(e)}}cs.SizeInFile=4;class ds{constructor(e){this.genOper=Be.readUInt16LE(e),this.genAmount=new fs(e)}}ds.SizeInFile=4,ds.GenInstrument=41,ds.GenKeyRange=43,ds.GenVelRange=44,ds.GenSampleId=53;class us{constructor(e){this.presetName=Be.read8BitStringLength(e,20),this.preset=Be.readUInt16LE(e),this.bank=Be.readUInt16LE(e),this.presetBagNdx=Be.readUInt16LE(e),this.library=Be.readUInt32LE(e),this.genre=Be.readUInt32LE(e),this.morphology=Be.readUInt32LE(e)}}us.SizeInFile=38;class ps{constructor(e){this.modSrcOper=Be.readUInt16LE(e),this.modDestOper=Be.readUInt16LE(e),this.modAmount=Be.readUInt16LE(e),this.modAmtSrcOper=Be.readUInt16LE(e),this.modTransOper=Be.readUInt16LE(e)}}ps.SizeInFile=10;class gs{constructor(e){this.sampleName=Be.read8BitStringLength(e,20),this.start=Be.readUInt32LE(e),this.end=Be.readUInt32LE(e),this.startLoop=Be.readUInt32LE(e),this.endLoop=Be.readUInt32LE(e),this.sampleRate=Be.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=Be.readSInt8(e),this.sampleLink=Be.readUInt16LE(e),this.sampleType=Be.readUInt16LE(e)}}gs.SizeInFile=46;class fs{get shortAmount(){return we.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}constructor(e){this.wordAmount=Be.readUInt16LE(e)}}class ms{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 ys{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"}(Ie||(Ie={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(De||(De={}));class bs{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null,this.fontSamples=null}}class Ss{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)}static clamp(e,t,s){return e<=t?t:e>=s?s:e}}class _s{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:Ss.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:Ss.timecents2Secs(this.attack),this.release=this.release<-11950?0:Ss.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:Ss.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:Ss.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?Ss.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"}(Ae||(Ae={}));class ws{constructor(e){this.loopMode=Ie.None,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 _s,this.modEnv=new _s,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.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 _s(e.ampEnv),this.modEnv=new _s(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=Ie.None,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 Ae.StartAddrsOffset:this.offset+=we.int16ToUint32(t.shortAmount);break;case Ae.EndAddrsOffset:this.end+=we.int16ToUint32(t.shortAmount);break;case Ae.StartloopAddrsOffset:this.loopStart+=we.int16ToUint32(t.shortAmount);break;case Ae.EndloopAddrsOffset:this.loopEnd+=we.int16ToUint32(t.shortAmount);break;case Ae.StartAddrsCoarseOffset:this.offset+=32768*we.int16ToUint32(t.shortAmount);break;case Ae.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case Ae.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case Ae.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case Ae.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case Ae.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case Ae.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case Ae.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case Ae.EndAddrsCoarseOffset:this.end+=32768*we.int16ToUint32(t.shortAmount);break;case Ae.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case Ae.Pan:this.pan=t.shortAmount/1e3;break;case Ae.DelayModLFO:this.delayModLFO=t.shortAmount;break;case Ae.FreqModLFO:this.freqModLFO=t.shortAmount;break;case Ae.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case Ae.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case Ae.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case Ae.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case Ae.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case Ae.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case Ae.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case Ae.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case Ae.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case Ae.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case Ae.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case Ae.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case Ae.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case Ae.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case Ae.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case Ae.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case Ae.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case Ae.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case Ae.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case Ae.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case Ae.StartloopAddrsCoarseOffset:this.loopStart+=32768*we.int16ToUint32(t.shortAmount);break;case Ae.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case Ae.EndloopAddrsCoarseOffset:this.loopEnd+=32768*we.int16ToUint32(t.shortAmount);break;case Ae.CoarseTune:this.transpose+=t.shortAmount;break;case Ae.FineTune:this.tune+=t.shortAmount;break;case Ae.SampleModes:this.loopMode=3&~t.wordAmount?1==(3&t.wordAmount)?Ie.Continuous:Ie.None:Ie.Sustain;break;case Ae.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case Ae.ExclusiveClass:this.group=t.wordAmount;break;case Ae.OverridingRootKey:this.pitchKeyCenter=t.shortAmount}}}!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"}(Re||(Re={}));class Bs{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=Re.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case Re.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=Re.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=Re.Delay;break;case Re.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=Re.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=Re.Attack;break;case Re.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=Re.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=Re.Hold;break;case Re.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=Re.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=Re.Decay;break;case Re.Decay:return this.segment=Re.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case Re.Sustain:if(this.segment=Re.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?Bs.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=Re.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,s,i,a){this.parameters=new _s(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:Ss.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:Ss.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|s,this.isAmpEnv=i,this.nextSegment(Re.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)}}Bs.FastReleaseTime=.01;class Ts{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,s){this.samplesUntil=e*s|0,this.delta=4*Ss.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 ks{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 vs{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 Bs,this.modEnv=new Bs,this.lowPass=new ks,this.modLfo=new Ts,this.vibLfo=new Ts,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/(Ss.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(Re.Sustain,e),this.modEnv.nextSegment(Re.Sustain,e),this.region.loopMode===Ie.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(Re.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(Re.Sustain,e)}render(e,t,s,i,a){if(!this.region)return;let r=this.region;let n=e.presets[this.playingPreset].fontSamples,o=0,h=e.outputMode===De.StereoUnweaved?i:-1,l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,c=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),d=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,f=r.end,m=g+1,y=this.sourceSamplePosition,b=new ks(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,v=0,x=0,N=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?(v=0,x=r.modLfoToPitch,N=r.vibLfoToPitch,P=r.modEnvToPitch):(v=Ss.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,x=0,N=0,P=0),C?F=.1*r.modLfoToVolume:(E=Ss.decibelsToGain(this.noteGainDb),F=0);i>0;){let r,L,M=0,I=i>vs.RenderEffectSampleBlock?vs.RenderEffectSampleBlock:i;if(i-=I,S){let e=w+this.modLfo.level*B+this.modEnv.level*T;b.active=e<=13500,b.active&&b.setup(Ss.cents2Hertz(e)/_)}switch(k&&(v=Ss.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*x+this.vibLfo.level*N+this.modEnv.level*P))*this.pitchOutputFactor),C&&(E=Ss.decibelsToGain(this.noteGainDb+this.modLfo.level*F)),r=E*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(I,e.outSampleRate),l&&this.modEnv.process(I,e.outSampleRate),c&&this.modLfo.process(I),d&&this.vibLfo.process(I),e.outputMode){case De.StereoInterleaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;I-- >0&&y<f;){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*L,o++,t[s+o]+=r*M,o++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case De.StereoUnweaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;I-- >0&&y<f;){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*L,o++,t[s+h]+=r*M,h++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case De.Mono:for(;I-- >0&&y<f;){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+=v,y>=m&&u&&(y-=g-p+1)}}if(y>=f||this.ampEnv.segment===Re.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}vs.RenderEffectSampleBlock=Kt.MicroBufferSize;class xs{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"}(Oe||(Oe={}));class Ns{constructor(e){this._midiEventQueue=new xs,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this._transpositionPitches=new Map,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=De.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.applyTranspositionPitches(new Map),this._isAnySolo=!1}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(Kt.MetronomeChannel,33),this.channelNoteOn(Kt.MetronomeChannel,33,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!=Kt.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,s,n):a.kill()}return a}processMidiMessage(e){q.debug("MIdi","Processing Midi message "+Le[e.type]+"/"+e.tick);switch(e.type){case Le.TimeSignature:const t=e;this.timeSignatureNumerator=t.numerator,this.timeSignatureDenominator=Math.pow(2,t.denominatorIndex);break;case Le.NoteOn:const s=e;this.channelNoteOn(s.channel,s.noteKey,s.noteVelocity/127);break;case Le.NoteOff:const i=e;this.channelNoteOff(i.channel,i.noteKey);break;case Le.ControlChange:const a=e;this.channelMidiControl(a.channel,a.controller,a.value);break;case Le.ProgramChange:const r=e;this.channelSetPresetNumber(r.channel,r.program,9===r.channel);break;case Le.TempoChange:const n=e;this.currentTempo=6e7/n.microSecondsPerQuarterNote;break;case Le.PitchBend:const o=e;this.channelSetPitchWheel(o.channel,o.value);break;case Le.PerNotePitchBend:const h=e;let l=h.value;l=l*Kt.MaxPitchWheel/Kt.MaxPitchWheel20,this.channelSetPerNotePitchWheel(h.channel,h.noteKey,l)}}get metronomeVolume(){return this.channelGetMixVolume(Kt.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Kt.MetronomeChannel,e),e>0&&(this.channelSetVolume(Kt.MetronomeChannel,1),this.channelSetPresetNumber(Kt.MetronomeChannel,0,!0))}get masterVolume(){return Ss.decibelsToGain(this.globalGainDb)}set masterVolume(e){var t=Ss.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<Re.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<Re.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 vs;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-Ss.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!==Ie.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(Ss.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>=Re.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>=Re.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&&t.ampEnv.segment<Re.Release&&(e?t.endQuick(this.outSampleRate):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 ys);for(let t=this._channels.channelList.length;t<=e;t++){let e=new ms;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._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,s))}channelNoteOff(e,t){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.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>=Re.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>=Re.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<Re.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<Re.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=we.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=we.int32ToUint16(t)}channelSetBankPreset(e,t,s){const i=this.channelInit(e),a=this.getPresetIndex(t,s);return-1!==a&&(i.presetIndex=we.int32ToUint16(a),i.bank=we.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=Ss.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=we.int32ToUint16(t),this.channelApplyPitch(e,s))}channelSetPerNotePitchWheel(e,t,s){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.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 Oe.DataEntryFine:return i.midiData=we.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 Oe.VolumeCoarse:return i.midiVolume=we.int32ToUint16(127&i.midiVolume|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Oe.VolumeFine:return i.midiVolume=we.int32ToUint16(16256&i.midiVolume|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Oe.ExpressionControllerCoarse:return i.midiExpression=we.int32ToUint16(127&i.midiExpression|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Oe.ExpressionControllerFine:return i.midiExpression=we.int32ToUint16(16256&i.midiExpression|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Oe.PanCoarse:return i.midiPan=we.int32ToUint16(127&i.midiPan|s<<7),void this.channelSetPan(e,i.midiPan/16383);case Oe.PanFine:return i.midiPan=we.int32ToUint16(16256&i.midiPan|s),void this.channelSetPan(e,i.midiPan/16383);case Oe.DataEntryCoarse:return i.midiData=we.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===Oe.DataEntryCoarse&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Oe.BankSelectCoarse:return void(i.bank=we.int32ToUint16(32768|s));case Oe.BankSelectFine:return void(i.bank=we.int32ToUint16((32768&i.bank?(127&i.bank)<<7:0)|s));case Oe.RegisteredParameterCourse:return void(i.midiRpn=we.int32ToUint16(127&(65535===i.midiRpn?0:i.midiRpn)|s<<7));case Oe.RegisteredParameterFine:return void(i.midiRpn=we.int32ToUint16(16256&(65535===i.midiRpn?0:i.midiRpn)|s));case Oe.NonRegisteredParameterFine:case Oe.NonRegisteredParameterCourse:return void(i.midiRpn=65535);case Oe.AllSoundOff:return void this.channelSoundsOffAll(e);case Oe.AllNotesOff:return void this.channelNoteOffAll(e);case Oe.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?Ss.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){const s=[];for(let t=0;t<e.phdrs.length-1;t++){const i=e.phdrs[t];let a=0;const r=new bs;s.push(r),r.name=i.presetName,r.bank=i.bank,r.presetNumber=i.preset,r.fontSamples=e.fontSamples;let n=0;for(let s=i.presetBagNdx;s<e.phdrs[t+1].presetBagNdx;s++){let t=0,i=127,a=0,r=127;for(let o=e.pbags[s].genNdx;o<e.pbags[s+1].genNdx;o++){let s=e.pgens[o];if(s.genOper!==ds.GenKeyRange)if(s.genOper!==ds.GenVelRange){if(s.genOper===ds.GenInstrument&&!(s.genAmount.wordAmount>=e.insts.length))for(let o=e.insts[s.genAmount.wordAmount].instBagNdx;o<e.insts[s.genAmount.wordAmount+1].instBagNdx;o++){let s=0,h=127,l=0,c=127;for(let d=e.ibags[o].instGenNdx;d<e.ibags[o+1].instGenNdx;d++){let o=e.igens[d];o.genOper!==ds.GenKeyRange?o.genOper!==ds.GenVelRange?53===o.genOper&&h>=t&&s<=i&&c>=a&&l<=r&&n++:(l=o.genAmount.lowByteAmount,c=o.genAmount.highByteAmount):(s=o.genAmount.lowByteAmount,h=o.genAmount.highByteAmount)}}}else a=s.genAmount.lowByteAmount,r=s.genAmount.highByteAmount;else t=s.genAmount.lowByteAmount,i=s.genAmount.highByteAmount}}r.regions=new Array(n);let o=new ws;o.clear(!0);for(let s=i.presetBagNdx;s<e.phdrs[t+1].presetBagNdx;s++){const t=e.pbags[s],n=new ws(o);let h=!1;for(let i=t.genNdx;i<e.pbags[s+1].genNdx;i++){const t=e.pgens[i];if(t.genOper===ds.GenInstrument){let s=t.genAmount.wordAmount;if(s>=e.insts.length)continue;let i=new ws;i.clear(!1);let o=e.insts[s];for(let t=o.instBagNdx;t<e.insts[s+1].instBagNdx;t++){let s=e.ibags[t],h=new ws(i),l=!1;for(let i=s.instGenNdx;i<e.ibags[t+1].instGenNdx;i++){let t=e.igens[i];if(t.genOper===ds.GenSampleId){if(h.hiKey<n.loKey||h.loKey>n.hiKey)continue;if(h.hiVel<n.loVel||h.loVel>n.hiVel)continue;n.loKey>h.loKey&&(h.loKey=n.loKey),n.hiKey<h.hiKey&&(h.hiKey=n.hiKey),n.loVel>h.loVel&&(h.loVel=n.loVel),n.hiVel<h.hiVel&&(h.hiVel=n.hiVel),h.offset+=n.offset,h.end+=n.end,h.loopStart+=n.loopStart,h.loopEnd+=n.loopEnd,h.transpose+=n.transpose,h.tune+=n.tune,h.pitchKeyTrack+=n.pitchKeyTrack,h.attenuation+=n.attenuation,h.pan+=n.pan,h.ampEnv.delay+=n.ampEnv.delay,h.ampEnv.attack+=n.ampEnv.attack,h.ampEnv.hold+=n.ampEnv.hold,h.ampEnv.decay+=n.ampEnv.decay,h.ampEnv.sustain+=n.ampEnv.sustain,h.ampEnv.release+=n.ampEnv.release,h.modEnv.delay+=n.modEnv.delay,h.modEnv.attack+=n.modEnv.attack,h.modEnv.hold+=n.modEnv.hold,h.modEnv.decay+=n.modEnv.decay,h.modEnv.sustain+=n.modEnv.sustain,h.modEnv.release+=n.modEnv.release,h.initialFilterQ+=n.initialFilterQ,h.initialFilterFc+=n.initialFilterFc,h.modEnvToPitch+=n.modEnvToPitch,h.modEnvToFilterFc+=n.modEnvToFilterFc,h.delayModLFO+=n.delayModLFO,h.freqModLFO+=n.freqModLFO,h.modLfoToPitch+=n.modLfoToPitch,h.modLfoToFilterFc+=n.modLfoToFilterFc,h.modLfoToVolume+=n.modLfoToVolume,h.delayVibLFO+=n.delayVibLFO,h.freqVibLFO+=n.freqVibLFO,h.vibLfoToPitch+=n.vibLfoToPitch,h.ampEnv.envToSecs(!0),h.modEnv.envToSecs(!1),h.delayModLFO=h.delayModLFO<-11950?0:Ss.timecents2Secs(h.delayModLFO),h.delayVibLFO=h.delayVibLFO<-11950?0:Ss.timecents2Secs(h.delayVibLFO),h.pan<-.5?h.pan=-.5:h.pan>.5&&(h.pan=.5),(h.initialFilterQ<1500||h.initialFilterQ>13500)&&(h.initialFilterQ=0);let s=e.sHdrs[t.genAmount.wordAmount];h.offset+=s.start,h.end+=s.end,h.loopStart+=s.startLoop,h.loopEnd+=s.endLoop,s.endLoop>0&&(h.loopEnd-=1),-1===h.pitchKeyCenter&&(h.pitchKeyCenter=s.originalPitch),h.tune+=s.pitchCorrection,h.sampleRate=s.sampleRate,0!==h.end&&h.end<r.fontSamples.length?h.end++:h.end=r.fontSamples.length,r.regions[a]=new ws(h),a++,l=!0}else h.operator(t.genOper,t.genAmount)}s!==e.ibags[o.instBagNdx]||l||(i=new ws(h))}h=!0}else n.operator(t.genOper,t.genAmount)}t!==e.pbags[i.presetBagNdx]||h||(o=n)}}if(t&&this.presets)for(const e of s)this.presets.push(e);else this.presets=s}}class Ps{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 Cs{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 Es{constructor(e){this.events=e}}class Fs{constructor(e){this.playbackRange=e}}class Ls{get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return q.logLevel}set logLevel(e){q.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Kt.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Kt.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Kt.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=Ss.clamp(e,Kt.MinPlaybackSpeed,Kt.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){q.debug("AlphaSynth",`Seeking to position ${e}ms (main)`),this._sequencer.mainSeek(e),this.updateTimePosition(e,!0),this._sequencer.isPlayingMain&&(this._notPlayedSamples=0,this.output.resetSamples())}get playbackRange(){return this._sequencer.mainPlaybackRange}set playbackRange(e){this._sequencer.mainPlaybackRange=e,e&&(this.tickPosition=e.startTick),this.playbackRangeChanged.trigger(new Fs(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){q.debug("AlphaSynth","Destroying player"),this.stop(),this.output.destroy()}constructor(e,t){this._isSoundFontLoaded=!1,this._isMidiLoaded=!1,this._tickPosition=0,this._timePosition=0,this._metronomeVolume=0,this._countInVolume=0,this._playedEventsQueue=new xs,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this.isReady=!1,this.state=Me.Paused,this.ready=new Ps,this.readyForPlayback=new Ps,this.finished=new Ps,this.soundFontLoaded=new Ps,this.soundFontLoadFailed=new Cs,this.midiLoaded=new Cs,this.midiLoadFailed=new Cs,this.stateChanged=new Cs,this.positionChanged=new Cs,this.midiEventsPlayed=new Cs,this.playbackRangeChanged=new Cs,q.debug("AlphaSynth","Initializing player"),this.state=Me.Paused,q.debug("AlphaSynth","Creating output"),this.output=e,q.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new Ns(this.output.sampleRate),this._sequencer=new ts(this._synthesizer),q.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this.state!=Me.Playing||this._sequencer.isFinished){let e=new Float32Array(0);this.output.addSamples(e)}else{let e=new Float32Array(Kt.MicroBufferSize*Kt.MicroBufferCount*Kt.AudioChannels),t=0;for(let s=0;s<Kt.MicroBufferCount;s++){this._sequencer.fillMidiEventQueue();const s=this._synthesizer.synthesize(e,t,Kt.MicroBufferSize);t+=Kt.MicroBufferSize*Kt.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)}})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open(t)}play(){return!(this.state!==Me.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(q.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(q.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),q.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.state=Me.Playing,this.stateChanged.trigger(new ss(this.state,!1))}pause(){this.state!==Me.Paused&&this._isMidiLoaded&&(q.debug("AlphaSynth","Pausing playback"),this.state=Me.Paused,this.stateChanged.trigger(new ss(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===Me.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(q.debug("AlphaSynth","Stopping playback"),this.state=Me.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 ss(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._isSoundFontLoaded=!1,this.soundFontLoaded.trigger()}loadSoundFont(e,t){this.pause();let s=Te.fromBuffer(e);try{q.debug("AlphaSynth","Loading soundfont from bytes");let e=new rs;e.load(s),this._synthesizer.loadPresets(e,t),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),q.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){q.error("AlphaSynth","Could not load soundfont from bytes "+e),this.soundFontLoadFailed.trigger(e)}}checkReadyForPlayback(){this.isReadyForPlayback&&(this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.readyForPlayback.trigger())}loadMidiFile(e){this.stop();try{q.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new is(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),q.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){q.error("AlphaSynth","Could not load midi from model "+e),this.midiLoadFailed.trigger(e)}}applyTranspositionPitches(e){this._synthesizer.applyTranspositionPitches(e)}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,Kt.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;let t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*Kt.AudioChannels,this.updateTimePosition(this._timePosition+t,!1),this.checkForFinish()}checkForFinish(){let e=0,t=0;this.playbackRange&&this._sequencer.isPlayingMain?(e=this.playbackRange.startTick,t=this.playbackRange.endTick):t=this._sequencer.currentEndTick,this._tickPosition>=t&&this._notPlayedSamples<=0&&(this._notPlayedSamples=0,this._sequencer.isPlayingCountIn?(q.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(q.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=Me.Paused,this.stopOneTimeMidi()):(q.debug("AlphaSynth","Finished playback (main)"),this.finished.trigger(),this.isLooping?this.tickPosition=e:this.stop()))}stopOneTimeMidi(){this.output.pause(),this._synthesizer.noteOffAll(!0),this._sequencer.resetOneTimeMidi(),this.timePosition=this._sequencer.currentTime}updateTimePosition(e,t){const s=e;this._timePosition=s;const i=this._sequencer.currentTimePositionToTickPosition(s);this._tickPosition=i;const a=this._sequencer.currentEndTime,r=this._sequencer.currentEndTick,n=this._sequencer.isPlayingMain?"main":this._sequencer.isPlayingCountIn?"count-in":"one-time";if(q.debug("AlphaSynth",`Position changed: (time: ${s}/${a}, tick: ${i}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new is(s,a,i,r,t)),t)this._playedEventsQueue.clear();else{const e=new xs;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<s;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new Es(e.toArray()))}}}class Ms{static parseEnum(e,t){switch(typeof e){case"string":const s=parseInt(e);return isNaN(s)?t[Object.keys(t).find((t=>t.toLowerCase()===e.toLowerCase()))]:s;case"number":return e;case"undefined":case"object":return null}throw new O(s.Format,`Could not parse enum value '${e}'`)}static forEach(e,t){if(e instanceof Map)e.forEach(t);else if("object"==typeof e)for(const s in e)t(e[s],s)}static getValue(e,t){return e instanceof Map?e.get(t):"object"==typeof e?e[t]:null}}class Is{constructor(e,t,s){this.text=e,this.startPos=t,this.endPos=s}}class Ds{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 Is(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 Ds(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"}(Ge||(Ge={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(Ve||(Ve={}));class As{reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=Ds.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===Ve.Bold}get isItalic(){return this.style===Ge.Italic}constructor(e,t,s=Ge.Plain,i=Ve.Regular){this._cssScale=0,this._families=Ds.parseFamilies(e),this._size=t,this._style=s,this._weight=i,this._css=this.toCssString()}static withFamilyList(e,t,s=Ge.Plain,i=Ve.Regular){const a=new As("",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=>Ds.quoteFont(e))).join(", "),this._css=t,this._cssScale=e}return this._css}static fromJson(e){switch(typeof e){case"undefined":default:return null;case"object":{const t=e;let s=t.get("families"),i=t.get("size"),a=Ms.parseEnum(t.get("style"),Ge),r=Ms.parseEnum(t.get("weight"),Ve);return As.withFamilyList(s,i,a,r)}case"string":{const t=new Ds(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=Ge.Plain;"italic"===t.style&&(r=Ge.Italic);let n=Ve.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=Ve.Bold}return As.withFamilyList(s,a,r,n)}}}static toJson(e){const t=new Map;return t.set("families",e.families),t.set("size",e.size),t.set("style",e.style),t.set("weight",e.weight),t}}class Rs{constructor(){this.copyrightFont=new As(Rs.sansFont,12,Ge.Plain,Ve.Bold),this.titleFont=new As(Rs.serifFont,32,Ge.Plain),this.subTitleFont=new As(Rs.serifFont,20,Ge.Plain),this.wordsFont=new As(Rs.serifFont,15,Ge.Plain),this.effectFont=new As(Rs.serifFont,12,Ge.Italic),this.fretboardNumberFont=new As(Rs.sansFont,11,Ge.Plain),this.tablatureFont=new As(Rs.sansFont,13,Ge.Plain),this.graceFont=new As(Rs.sansFont,11,Ge.Plain),this.staffLineColor=new fe(165,165,165,255),this.barSeparatorColor=new fe(34,34,17,255),this.barNumberFont=new As(Rs.sansFont,11,Ge.Plain),this.barNumberColor=new fe(200,0,0,255),this.fingeringFont=new As(Rs.serifFont,14,Ge.Plain),this.markerFont=new As(Rs.serifFont,14,Ge.Plain,Ve.Bold),this.mainGlyphColor=new fe(0,0,0,255),this.secondaryGlyphColor=new fe(0,0,0,100),this.scoreInfoColor=new fe(0,0,0,255)}}Rs.sansFont="Arial, sans-serif",Rs.serifFont="Georgia, serif",function(e){e[e.Automatic=0]="Automatic",e[e.UseModelLayout=1]="UseModelLayout"}(He||(He={}));class Os{constructor(){this.scale=1,this.stretchForce=1,this.layoutMode=e.Page,this.staveProfile=t.Default,this.barsPerRow=-1,this.startBar=1,this.barCount=-1,this.barCountPerPartial=10,this.justifyLastSystem=!1,this.resources=new Rs,this.padding=null,this.systemsLayoutMode=He.Automatic}}class Gs{constructor(){this.encoding="utf-8",this.mergePartGroupsInMusicXml=!1,this.beatTextAsLyrics=!1}}!function(e){e[e.Off=0]="Off",e[e.Continuous=1]="Continuous",e[e.OffScreen=2]="OffScreen"}(We||(We={}));class Vs{constructor(){this.noteWideLength=480,this.noteWideAmplitude=2,this.noteSlightLength=480,this.noteSlightAmplitude=2,this.beatWideLength=240,this.beatWideAmplitude=3,this.beatSlightLength=240,this.beatSlightAmplitude=3}}class Hs{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}!function(e){e[e.WebAudioAudioWorklets=0]="WebAudioAudioWorklets",e[e.WebAudioScriptProcessor=1]="WebAudioScriptProcessor"}(ze||(ze={}));class Ws{constructor(){this.soundFont=null,this.scrollElement="html,body",this.outputMode=ze.WebAudioAudioWorklets,this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=We.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new Vs,this.slide=new Hs,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}class zs{static fromJson(e,t){t&&Ms.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(e,t,s){switch(t){case"scriptfile":return e.scriptFile=s,!0;case"fontdirectory":return e.fontDirectory=s,!0;case"file":return e.file=s,!0;case"tex":return e.tex=s,!0;case"tracks":return e.tracks=s,!0;case"enablelazyloading":return e.enableLazyLoading=s,!0;case"engine":return e.engine=s,!0;case"loglevel":return e.logLevel=Ms.parseEnum(s,v),!0;case"useworkers":return e.useWorkers=s,!0;case"includenotebounds":return e.includeNoteBounds=s,!0}return!1}}class Us{static fromJson(e,t){t&&Ms.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",As.toJson(e.copyrightFont)),t.set("titlefont",As.toJson(e.titleFont)),t.set("subtitlefont",As.toJson(e.subTitleFont)),t.set("wordsfont",As.toJson(e.wordsFont)),t.set("effectfont",As.toJson(e.effectFont)),t.set("fretboardnumberfont",As.toJson(e.fretboardNumberFont)),t.set("tablaturefont",As.toJson(e.tablatureFont)),t.set("gracefont",As.toJson(e.graceFont)),t.set("stafflinecolor",fe.toJson(e.staffLineColor)),t.set("barseparatorcolor",fe.toJson(e.barSeparatorColor)),t.set("barnumberfont",As.toJson(e.barNumberFont)),t.set("barnumbercolor",fe.toJson(e.barNumberColor)),t.set("fingeringfont",As.toJson(e.fingeringFont)),t.set("markerfont",As.toJson(e.markerFont)),t.set("mainglyphcolor",fe.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",fe.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",fe.toJson(e.scoreInfoColor)),t}static setProperty(e,t,s){switch(t){case"copyrightfont":return e.copyrightFont=As.fromJson(s),!0;case"titlefont":return e.titleFont=As.fromJson(s),!0;case"subtitlefont":return e.subTitleFont=As.fromJson(s),!0;case"wordsfont":return e.wordsFont=As.fromJson(s),!0;case"effectfont":return e.effectFont=As.fromJson(s),!0;case"fretboardnumberfont":return e.fretboardNumberFont=As.fromJson(s),!0;case"tablaturefont":return e.tablatureFont=As.fromJson(s),!0;case"gracefont":return e.graceFont=As.fromJson(s),!0;case"stafflinecolor":return e.staffLineColor=fe.fromJson(s),!0;case"barseparatorcolor":return e.barSeparatorColor=fe.fromJson(s),!0;case"barnumberfont":return e.barNumberFont=As.fromJson(s),!0;case"barnumbercolor":return e.barNumberColor=fe.fromJson(s),!0;case"fingeringfont":return e.fingeringFont=As.fromJson(s),!0;case"markerfont":return e.markerFont=As.fromJson(s),!0;case"mainglyphcolor":return e.mainGlyphColor=fe.fromJson(s),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=fe.fromJson(s),!0;case"scoreinfocolor":return e.scoreInfoColor=fe.fromJson(s),!0}return!1}}class Xs{static fromJson(e,t){t&&Ms.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",Us.toJson(e.resources)),t.set("padding",e.padding),t.set("systemslayoutmode",e.systemsLayoutMode),t}static setProperty(s,i,a){switch(i){case"scale":return s.scale=a,!0;case"stretchforce":return s.stretchForce=a,!0;case"layoutmode":return s.layoutMode=Ms.parseEnum(a,e),!0;case"staveprofile":return s.staveProfile=Ms.parseEnum(a,t),!0;case"barsperrow":return s.barsPerRow=a,!0;case"startbar":return s.startBar=a,!0;case"barcount":return s.barCount=a,!0;case"barcountperpartial":return s.barCountPerPartial=a,!0;case"justifylastsystem":return s.justifyLastSystem=a,!0;case"padding":return s.padding=a,!0;case"systemslayoutmode":return s.systemsLayoutMode=Ms.parseEnum(a,He),!0}if(["resources"].indexOf(i)>=0)return Us.fromJson(s.resources,a),!0;for(const e of["resources"])if(0===i.indexOf(e)&&Us.setProperty(s.resources,i.substring(e.length),a))return!0;return!1}}class Ys{static fromJson(e,t){t&&Ms.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(e,t,s){switch(t){case"notationmode":return e.notationMode=Ms.parseEnum(s,T),!0;case"fingeringmode":return e.fingeringMode=Ms.parseEnum(s,B),!0;case"elements":return e.elements=new Map,Ms.forEach(s,((t,s)=>{e.elements.set(Ms.parseEnum(s,k),t)})),!0;case"rhythmmode":return e.rhythmMode=Ms.parseEnum(s,w),!0;case"rhythmheight":return e.rhythmHeight=s,!0;case"transpositionpitches":return e.transpositionPitches=s,!0;case"displaytranspositionpitches":return e.displayTranspositionPitches=s,!0;case"smallgracetabnotes":return e.smallGraceTabNotes=s,!0;case"extendbendarrowsontiednotes":return e.extendBendArrowsOnTiedNotes=s,!0;case"extendlineeffectstobeatend":return e.extendLineEffectsToBeatEnd=s,!0;case"slurheight":return e.slurHeight=s,!0}return!1}}class qs{static fromJson(e,t){t&&Ms.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 Js{static fromJson(e,t){t&&Ms.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 js{static fromJson(e,t){t&&Ms.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 Qs{static fromJson(e,t){t&&Ms.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",Js.toJson(e.vibrato)),t.set("slide",js.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t.set("buffertimeinmilliseconds",e.bufferTimeInMilliseconds),t}static setProperty(e,t,s){switch(t){case"soundfont":return e.soundFont=s,!0;case"scrollelement":return e.scrollElement=s,!0;case"outputmode":return e.outputMode=Ms.parseEnum(s,ze),!0;case"enableplayer":return e.enablePlayer=s,!0;case"enablecursor":return e.enableCursor=s,!0;case"enableanimatedbeatcursor":return e.enableAnimatedBeatCursor=s,!0;case"enableelementhighlighting":return e.enableElementHighlighting=s,!0;case"enableuserinteraction":return e.enableUserInteraction=s,!0;case"scrolloffsetx":return e.scrollOffsetX=s,!0;case"scrolloffsety":return e.scrollOffsetY=s,!0;case"scrollmode":return e.scrollMode=Ms.parseEnum(s,We),!0;case"scrollspeed":return e.scrollSpeed=s,!0;case"nativebrowsersmoothscroll":return e.nativeBrowserSmoothScroll=s,!0;case"songbookbendduration":return e.songBookBendDuration=s,!0;case"songbookdipduration":return e.songBookDipDuration=s,!0;case"playtripletfeel":return e.playTripletFeel=s,!0;case"buffertimeinmilliseconds":return e.bufferTimeInMilliseconds=s,!0}if(["vibrato"].indexOf(t)>=0)return Js.fromJson(e.vibrato,s),!0;for(const i of["vibrato"])if(0===t.indexOf(i)&&Js.setProperty(e.vibrato,t.substring(i.length),s))return!0;if(["slide"].indexOf(t)>=0)return js.fromJson(e.slide,s),!0;for(const i of["slide"])if(0===t.indexOf(i)&&js.setProperty(e.slide,t.substring(i.length),s))return!0;return!1}}class $s{static fromJson(e,t){t&&Ms.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",zs.toJson(e.core)),t.set("display",Xs.toJson(e.display)),t.set("notation",Ys.toJson(e.notation)),t.set("importer",qs.toJson(e.importer)),t.set("player",Qs.toJson(e.player)),t}static setProperty(e,t,s){if(["core",""].indexOf(t)>=0)return zs.fromJson(e.core,s),!0;for(const i of["core",""])if(0===t.indexOf(i)&&zs.setProperty(e.core,t.substring(i.length),s))return!0;if(["display",""].indexOf(t)>=0)return Xs.fromJson(e.display,s),!0;for(const i of["display",""])if(0===t.indexOf(i)&&Xs.setProperty(e.display,t.substring(i.length),s))return!0;if(["notation"].indexOf(t)>=0)return Ys.fromJson(e.notation,s),!0;for(const i of["notation"])if(0===t.indexOf(i)&&Ys.setProperty(e.notation,t.substring(i.length),s))return!0;if(["importer"].indexOf(t)>=0)return qs.fromJson(e.importer,s),!0;for(const i of["importer"])if(0===t.indexOf(i)&&qs.setProperty(e.importer,t.substring(i.length),s))return!0;if(["player"].indexOf(t)>=0)return Qs.fromJson(e.player,s),!0;for(const i of["player"])if(0===t.indexOf(i)&&Qs.setProperty(e.player,t.substring(i.length),s))return!0;return!1}}class Ks{constructor(){this.core=new Co,this.display=new Os,this.notation=new U,this.importer=new Gs,this.player=new Ws}setSongBookModeSettings(){this.notation.notationMode=T.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=B.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(k.ParenthesisOnTiedBends,!1),this.notation.elements.set(k.TabNotesOnTiedBends,!1),this.notation.elements.set(k.ZerosOnDiveWhammys,!0)}static get songBook(){let e=new Ks;return e.setSongBookModeSettings(),e}fillFromJson(e){$s.fromJson(this,e)}}class Zs{static fromJson(e,t){t&&Ms.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 ei{static fromJson(e,t){t&&Ms.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=Ms.parseEnum(s,a),!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 ti{static fromJson(e,t){t&&Ms.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=Ms.parseEnum(s,xe),!0;case"length":return e.length=s,!0}return!1}}class si{static fromJson(e,t){t&&Ms.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("tripletfeel",e.tripletFeel),t.set("section",Zs.toJson(e.section)),t.set("tempoautomation",ei.toJson(e.tempoAutomation)),null!==e.fermata){const s=new Map;t.set("fermata",s);for(const[t,i]of e.fermata)s.set(t.toString(),ti.toJson(i))}return t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t}static setProperty(e,t,s){switch(t){case"alternateendings":return e.alternateEndings=s,!0;case"keysignature":return e.keySignature=Ms.parseEnum(s,L),!0;case"keysignaturetype":return e.keySignatureType=Ms.parseEnum(s,I),!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"tripletfeel":return e.tripletFeel=Ms.parseEnum(s,D),!0;case"fermata":return e.fermata=new Map,Ms.forEach(s,((t,s)=>{const i=new ot;ti.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}return["section"].indexOf(t)>=0?(s?(e.section=new pe,Zs.fromJson(e.section,s)):e.section=null,!0):["tempoautomation"].indexOf(t)>=0&&(s?(e.tempoAutomation=new V,ei.fromJson(e.tempoAutomation,s)):e.tempoAutomation=null,!0)}}class ii{static fromJson(e,t){t&&Ms.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 ai{static fromJson(e,t){t&&Ms.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=>ii.toJson(e)))),t.set("fret",e.fret),t.set("string",e.string),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("isfingering",e.isFingering),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),e.toJson(t),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"accentuated":return e.accentuated=Ms.parseEnum(s,i),!0;case"bendtype":return e.bendType=Ms.parseEnum(s,l),!0;case"bendstyle":return e.bendStyle=Ms.parseEnum(s,h),!0;case"iscontinuedbend":return e.isContinuedBend=s,!0;case"bendpoints":if(s){e.bendPoints=[];for(const t of s){const s=new z;ii.fromJson(s,t),e.addBendPoint(s)}}return!0;case"fret":return e.fret=s,!0;case"string":return e.string=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=Ms.parseEnum(s,m),!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=Ms.parseEnum(s,b),!0;case"slideouttype":return e.slideOutType=Ms.parseEnum(s,S),!0;case"vibrato":return e.vibrato=Ms.parseEnum(s,_),!0;case"istiedestination":return e.isTieDestination=s,!0;case"lefthandfinger":return e.leftHandFinger=Ms.parseEnum(s,f),!0;case"righthandfinger":return e.rightHandFinger=Ms.parseEnum(s,f),!0;case"isfingering":return e.isFingering=s,!0;case"trillvalue":return e.trillValue=s,!0;case"trillspeed":return e.trillSpeed=Ms.parseEnum(s,u),!0;case"durationpercent":return e.durationPercent=s,!0;case"accidentalmode":return e.accidentalMode=Ms.parseEnum(s,y),!0;case"dynamics":return e.dynamics=Ms.parseEnum(s,p),!0}return e.setProperty(t,s)}}class ri{static fromJson(e,t){t&&Ms.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=>ai.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=>ei.toJson(e)))),t.set("dots",e.dots),t.set("fadein",e.fadeIn),t.set("lyrics",e.lyrics),t.set("hasrasgueado",e.hasRasgueado),t.set("pop",e.pop),t.set("slap",e.slap),t.set("tap",e.tap),t.set("text",e.text),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=>ii.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("dynamics",e.dynamics),t.set("invertbeamdirection",e.invertBeamDirection),t.set("preferredbeamdirection",e.preferredBeamDirection),t.set("beamingmode",e.beamingMode),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 Z;ai.fromJson(s,t),e.addNote(s)}return!0;case"isempty":return e.isEmpty=s,!0;case"whammystyle":return e.whammyStyle=Ms.parseEnum(s,h),!0;case"ottava":return e.ottava=Ms.parseEnum(s,n),!0;case"islegatoorigin":return e.isLegatoOrigin=s,!0;case"duration":return e.duration=Ms.parseEnum(s,u),!0;case"automations":e.automations=[];for(const t of s){const s=new V;ei.fromJson(s,t),e.automations.push(s)}return!0;case"dots":return e.dots=s,!0;case"fadein":return e.fadeIn=s,!0;case"lyrics":return e.lyrics=s,!0;case"hasrasgueado":return e.hasRasgueado=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"brushtype":return e.brushType=Ms.parseEnum(s,c),!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=Ms.parseEnum(s,E),!0;case"whammybarpoints":if(s){e.whammyBarPoints=[];for(const t of s){const s=new z;ii.fromJson(s,t),e.addWhammyBarPoint(s)}}return!0;case"vibrato":return e.vibrato=Ms.parseEnum(s,_),!0;case"chordid":return e.chordId=s,!0;case"gracetype":return e.graceType=Ms.parseEnum(s,g),!0;case"pickstroke":return e.pickStroke=Ms.parseEnum(s,x),!0;case"tremolospeed":return e.tremoloSpeed=Ms.parseEnum(s,u),!0;case"crescendo":return e.crescendo=Ms.parseEnum(s,d),!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"dynamics":return e.dynamics=Ms.parseEnum(s,p),!0;case"invertbeamdirection":return e.invertBeamDirection=s,!0;case"preferredbeamdirection":return e.preferredBeamDirection=Ms.parseEnum(s,Ce),!0;case"beamingmode":return e.beamingMode=Ms.parseEnum(s,F),!0}return!1}}class ni{static fromJson(e,t){t&&Ms.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=>ri.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 ne;ri.fromJson(s,t),e.addBeat(s)}return!0;case"isempty":return e.isEmpty=s,!0}return!1}}class oi{static fromJson(e,t){t&&Ms.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=>ni.toJson(e)))),t.set("similemark",e.simileMark),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"clef":return e.clef=Ms.parseEnum(s,r),!0;case"clefottava":return e.clefOttava=Ms.parseEnum(s,n),!0;case"voices":e.voices=[];for(const t of s){const s=new _e;ni.fromJson(s,t),e.addVoice(s)}return!0;case"similemark":return e.simileMark=Ms.parseEnum(s,o),!0;case"displayscale":return e.displayScale=s,!0;case"displaywidth":return e.displayWidth=s,!0}return!1}}class hi{static fromJson(e,t){t&&Ms.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 li{static fromJson(e,t){t&&Ms.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 ci{static fromJson(e,t){t&&Ms.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=>oi.toJson(e)))),null!==e.chords){const s=new Map;t.set("chords",s);for(const[t,i]of e.chords)s.set(t.toString(),hi.toJson(i))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",li.toJson(e.stringTuning)),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 H;oi.fromJson(s,t),e.addBar(s)}return!0;case"chords":return e.chords=new Map,Ms.forEach(s,((t,s)=>{const i=new oe;hi.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"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&&(li.fromJson(e.stringTuning,s),!0)}}class di{static fromJson(e,t){t&&Ms.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 ui{static fromJson(e,t){t&&Ms.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=Ms.parseEnum(s,N),!0;case"noteheadhalf":return e.noteHeadHalf=Ms.parseEnum(s,N),!0;case"noteheadwhole":return e.noteHeadWhole=Ms.parseEnum(s,N),!0;case"techniquesymbol":return e.techniqueSymbol=Ms.parseEnum(s,N),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=Ms.parseEnum(s,C),!0;case"outputmidinumber":return e.outputMidiNumber=s,!0}return!1}}class pi{static fromJson(e,t){t&&Ms.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=>ci.toJson(e)))),t.set("playbackinfo",di.toJson(e.playbackInfo)),t.set("color",fe.toJson(e.color)),t.set("name",e.name),t.set("shortname",e.shortName),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("percussionarticulations",e.percussionArticulations.map((e=>ui.toJson(e)))),t}static setProperty(e,t,s){switch(t){case"staves":e.staves=[];for(const t of s){const s=new be;ci.fromJson(s,t),e.addStaff(s)}return!0;case"color":return e.color=fe.fromJson(s),!0;case"name":return e.name=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 Q;ui.fromJson(s,t),e.percussionArticulations.push(s)}return!0}return["playbackinfo"].indexOf(t)>=0&&(di.fromJson(e.playbackInfo,s),!0)}}class gi{static fromJson(e,t){t&&Ms.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("hidedynamics",e.hideDynamics),t}static setProperty(e,t,s){return"hidedynamics"===t&&(e.hideDynamics=s,!0)}}class fi{static fromJson(e,t){t&&Ms.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=>si.toJson(e)))),t.set("tracks",e.tracks.map((e=>pi.toJson(e)))),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("stylesheet",gi.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 le;si.fromJson(s,t),e.addMasterBar(s)}return!0;case"tracks":e.tracks=[];for(const t of s){const s=new Se;pi.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&&(gi.fromJson(e.stylesheet,s),!0)}}class mi{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=mi.scoreToJsObject(e);return JSON.stringify(t,mi.jsonReplacer)}static jsonToScore(e,t){return mi.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return fi.toJson(e)}static jsObjectToScore(e,t){let s=new ue;return fi.fromJson(s,e),s.finish(t??new Ks),s}static settingsToJson(e){let t=mi.settingsToJsObject(e);return JSON.stringify(t,mi.jsonReplacer)}static jsonToSettings(e){return mi.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return $s.toJson(e)}static jsObjectToSettings(e){let t=new Ks;return $s.fromJson(t,e),t}static jsObjectToMidiFile(e){let t=new At;return Ms.forEach(e,((e,s)=>{switch(s){case"division":t.division=e;break;case"tracks":for(let s of e){let e=mi.jsObjectToMidiTrack(s);t.tracks.push(e)}}})),t}static jsObjectToMidiTrack(e){let t=new Dt;return Ms.forEach(e,((e,s)=>{if("events"===s)for(let s of e){let e=mi.jsObjectToMidiEvent(s);t.events.push(e)}})),t}static jsObjectToMidiEvent(e){let t=Ms.getValue(e,"track"),i=Ms.getValue(e,"tick"),a=Ms.getValue(e,"type");switch(a){case Le.TimeSignature:return new Ot(t,i,Ms.getValue(e,"numerator"),Ms.getValue(e,"denominatorIndex"),Ms.getValue(e,"midiClocksPerMetronomeClick"),Ms.getValue(e,"thirdySecondNodesInQuarter"));case Le.AlphaTabRest:return new Ht(t,i,Ms.getValue(e,"channel"));case Le.AlphaTabMetronome:return new Vt(t,i,Ms.getValue(e,"metronomeNumerator"),Ms.getValue(e,"metronomeDurationInTicks"),Ms.getValue(e,"metronomeDurationInMilliseconds"));case Le.NoteOn:return new zt(t,i,Ms.getValue(e,"channel"),Ms.getValue(e,"noteKey"),Ms.getValue(e,"noteVelocity"));case Le.NoteOff:return new Ut(t,i,Ms.getValue(e,"channel"),Ms.getValue(e,"noteKey"),Ms.getValue(e,"noteVelocity"));case Le.ControlChange:return new Xt(t,i,Ms.getValue(e,"channel"),Ms.getValue(e,"controller"),Ms.getValue(e,"value"));case Le.ProgramChange:return new Yt(t,i,Ms.getValue(e,"channel"),Ms.getValue(e,"program"));case Le.TempoChange:return new qt(i,Ms.getValue(e,"microSecondsPerQuarterNote"));case Le.PitchBend:return new Jt(t,i,Ms.getValue(e,"channel"),Ms.getValue(e,"value"));case Le.PerNotePitchBend:return new jt(t,i,Ms.getValue(e,"channel"),Ms.getValue(e,"noteKey"),Ms.getValue(e,"value"));case Le.EndOfTrack:return new Qt(t,i)}throw new O(s.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(mi.midiTrackToJsObject(t));return t.set("tracks",s),t}static midiTrackToJsObject(e){const t=new Map,s=[];for(let t of e.events)s.push(mi.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 Le.TimeSignature:t.set("numerator",e.numerator),t.set("denominatorIndex",e.denominatorIndex),t.set("midiClocksPerMetronomeClick",e.midiClocksPerMetronomeClick),t.set("thirdySecondNodesInQuarter",e.thirtySecondNodesInQuarter);break;case Le.AlphaTabRest:t.set("channel",e.channel);break;case Le.AlphaTabMetronome:t.set("metronomeNumerator",e.metronomeNumerator),t.set("metronomeDurationInMilliseconds",e.metronomeDurationInMilliseconds),t.set("metronomeDurationInTicks",e.metronomeDurationInTicks);break;case Le.NoteOn:case Le.NoteOff:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("noteVelocity",e.noteVelocity);break;case Le.ControlChange:t.set("channel",e.channel),t.set("controller",e.controller),t.set("value",e.value);break;case Le.ProgramChange:t.set("channel",e.channel),t.set("program",e.program);break;case Le.TempoChange:t.set("microSecondsPerQuarterNote",e.microSecondsPerQuarterNote);break;case Le.PitchBend:t.set("channel",e.channel),t.set("value",e.value);break;case Le.PerNotePitchBend:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("value",e.value);case Le.EndOfTrack:}return t}}class yi{constructor(){this.ready=new Ps,this.samplesPlayed=new Cs,this.sampleRequest=new Ps}get sampleRate(){return yi.preferredSampleRate}open(){q.debug("AlphaSynth","Initializing synth worker"),this._worker=Po.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 yi.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case yi.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(){}}yi.CmdOutputPrefix="alphaSynth.output.",yi.CmdOutputAddSamples=yi.CmdOutputPrefix+"addSamples",yi.CmdOutputPlay=yi.CmdOutputPrefix+"play",yi.CmdOutputPause=yi.CmdOutputPrefix+"pause",yi.CmdOutputResetSamples=yi.CmdOutputPrefix+"resetSamples",yi.CmdOutputSampleRequest=yi.CmdOutputPrefix+"sampleRequest",yi.CmdOutputSamplesPlayed=yi.CmdOutputPrefix+"samplesPlayed",yi.preferredSampleRate=0;class bi{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new Ls(new yi,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=Po.globalThis;e.addEventListener("message",(t=>{let s=t.data;if("alphaSynth.initialize"===s.cmd)yi.preferredSampleRate=s.sampleRate,q.logLevel=s.logLevel,Po.globalThis.alphaSynthWebWorker=new bi(e,s.bufferTimeInMilliseconds)}))}handleMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":q.logLevel=t.value;break;case"alphaSynth.setMasterVolume":this._player.masterVolume=t.value;break;case"alphaSynth.setMetronomeVolume":this._player.metronomeVolume=t.value;break;case"alphaSynth.setPlaybackSpeed":this._player.playbackSpeed=t.value;break;case"alphaSynth.setTickPosition":this._player.tickPosition=t.value;break;case"alphaSynth.setTimePosition":this._player.timePosition=t.value;break;case"alphaSynth.setPlaybackRange":this._player.playbackRange=t.value;break;case"alphaSynth.setIsLooping":this._player.isLooping=t.value;break;case"alphaSynth.setCountInVolume":this._player.countInVolume=t.value;break;case"alphaSynth.setMidiEventsPlayedFilter":this._player.midiEventsPlayedFilter=t.value;break;case"alphaSynth.play":this._player.play();break;case"alphaSynth.pause":this._player.pause();break;case"alphaSynth.playPause":this._player.playPause();break;case"alphaSynth.stop":this._player.stop();break;case"alphaSynth.playOneTimeMidiFile":this._player.playOneTimeMidiFile(mi.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(mi.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);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(mi.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}class Si{static generateFontLookup(e){if(!Si.FontSizeLookupTables.has(e))if(Po.isRunningInWorker)Si.FontSizeLookupTables.set(e,new Uint8Array([8]));else{let t=document.createElement("canvas").getContext("2d");t.font=`11px ${e}`;let s=[];for(let e=32;e<255;e++){let i=String.fromCharCode(e);s.push(t.measureText(i).width)}let i=new Uint8Array(s);Si.FontSizeLookupTables.set(e,i)}}static measureString(e,t,s,i,a){let r,n=t[0];for(let e=0;e<t.length;e++)if(Si.FontSizeLookupTables.has(t[e])){n=t[e];break}Si.FontSizeLookupTables.has(n)||Si.generateFontLookup(n),r=Si.FontSizeLookupTables.get(n);let o=1;i===Ge.Italic&&(o*=1.2),a===Ve.Bold&&(o*=1.2);let h=0;for(let t=0;t<e.length;t++){let i=Math.min(r.length-1,e.charCodeAt(t)-32);i>=0&&(h+=r[i]*s/11)}return h*o}}Si.Georgia=new Uint8Array([3,4,5,7,7,9,8,2,4,4,5,7,3,4,3,5,7,5,6,6,6,6,6,6,7,6,3,3,7,7,7,5,10,7,7,7,8,7,7,8,9,4,6,8,7,10,8,8,7,8,8,6,7,8,7,11,8,7,7,4,5,4,7,7,6,6,6,5,6,5,4,6,6,3,3,6,3,10,6,6,6,6,5,5,4,6,5,8,6,5,5,5,4,5,7,6,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,3,4,6,7,6,7,4,6,6,10,6,6,7,0,10,7,5,7,6,6,6,6,6,3,6,6,6,6,12,12,12,5,7,7,7,7,7,7,11,7,7,7,7,7,4,4,4,4,8,8,8,8,8,8,8,7,8,8,8,8,8,7,7,6,6,6,6,6,6,6,8,5,5,5,5,5,3,3,3,3,6,6,6,6,6,6,6,7,6,6,6,6,6,5,6]),Si.Arial=new Uint8Array([3,3,4,6,6,10,7,2,4,4,4,6,3,4,3,3,6,6,6,6,6,6,6,6,6,6,3,3,6,6,6,6,11,7,7,8,8,7,7,9,8,3,6,7,6,9,8,9,7,9,8,7,7,8,7,10,7,7,7,3,3,3,5,6,4,6,6,6,6,6,3,6,6,2,2,6,2,9,6,6,6,6,4,6,3,6,6,8,6,6,6,4,3,4,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,4,6,6,6,6,3,6,4,8,4,6,6,0,8,6,4,6,4,4,4,6,6,4,4,4,4,6,9,9,9,7,7,7,7,7,7,7,11,8,7,7,7,7,3,3,3,3,8,8,9,9,9,9,9,6,9,8,8,8,8,7,7,7,6,6,6,6,6,6,10,6,6,6,6,6,3,3,3,3,6,6,6,6,6,6,6,6,7,6,6,6,6,6,6]),Si.FontSizeLookupTables=new Map([["Arial",Si.Arial],["'Arial'",Si.Arial],['"Arial"',Si.Arial],["Georgia",Si.Georgia],["'Georgia'",Si.Georgia],['"Georgia"',Si.Georgia]]),Si.ControlChars=32;class _i{constructor(){this.id=j.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 wi{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(){this.beats.sort(((e,t)=>e.realBounds.x-t.realBounds.x))}}class Bi{constructor(){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}}class Ti{constructor(){this.index=0,this.isFirstOfLine=!1,this.bars=[],this.staveGroupBounds=null}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(){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 e of this.bars)e.finish()}addBeat(e){this.staveGroupBounds.boundsLookup.addBeat(e)}}class ki{}class vi{constructor(){this.index=0,this.bars=[]}finish(){for(let e of this.bars)e.finish()}addBar(e){this.boundsLookup.addMasterBar(e),e.staveGroupBounds=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 xi{constructor(){this._beatLookup=new Map,this._masterBarLookup=new Map,this._currentStaveGroup=null,this.staveGroups=[],this.isFinished=!1}toJson(){let e={},t=[];e.staveGroups=t;for(let e of this.staveGroups){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);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 xi,i=e.staveGroups;for(let e of i){let i=new vi;i.visualBounds=e.visualBounds,i.realBounds=e.realBounds,s.addStaveGroup(i);for(let s of e.bars){let e=new Ti;e.index=s.index,e.isFirstOfLine=s.isFirstOfLine,e.lineAlignedBounds=s.lineAlignedBounds,e.visualBounds=s.visualBounds,e.realBounds=s.realBounds,i.addBar(e);for(let i of s.bars){let s=new wi;s.visualBounds=i.visualBounds,s.realBounds=i.realBounds,e.addBar(s);for(let e of i.beats){let i=new Bi;i.visualBounds=e.visualBounds,i.realBounds=e.realBounds;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 ki,s=t;e.note=i.beat.notes[s.index],e.noteHeadBounds=t.noteHeadBounds,i.addNote(e)}}s.addBeat(i)}}}}return s}boundsToJson(e){let t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(){for(let e of this.staveGroups)e.finish();this.isFinished=!0}addStaveGroup(e){e.index=this.staveGroups.length,e.boundsLookup=this,this.staveGroups.push(e),this._currentStaveGroup=e}addMasterBar(e){e.staveGroupBounds?this._masterBarLookup.set(e.index,e):(e.staveGroupBounds=this._currentStaveGroup,this._masterBarLookup.set(e.index,e),this._currentStaveGroup.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.staveGroups.length-1,a=-1;for(;s<=i;){let e=(i+s)/2|0,r=this.staveGroups[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.staveGroups[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 Ni{constructor(t){this._currentLayoutMode=e.Page,this._currentRenderEngine=null,this._renderedTracks=null,this.canvas=null,this.score=null,this.tracks=null,this.layout=null,this.boundsLookup=null,this.width=0,this.preRender=new Cs,this.renderFinished=new Cs,this.partialRenderFinished=new Cs,this.partialLayoutFinished=new Cs,this.postRenderFinished=new Ps,this.error=new Cs,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=Po.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=Po.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?(q.debug("Rendering","Request render of lazy partial "+e),t.renderLazyPartial(e)):q.warning("Rendering","Request render of lazy partial "+e+" ignored, no layout exists")}catch(e){this.error.trigger(e)}}render(){if(0!==this.width)if(this.boundsLookup=new xi,this.recreateCanvas(),this.canvas.lineWidth=this.settings.display.scale,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){q.debug("Rendering","Rendering "+this.tracks.length+" tracks");for(let e=0;e<this.tracks.length;e++){let t=this.tracks[e];q.debug("Rendering","Track "+e+": "+t.name)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),q.debug("Rendering","Rendering finished")}else q.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),q.debug("Rendering","Clearing finished");else q.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(q.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(q.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new xi,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):q.debug("Rendering","Current layout does not support dynamic resizing, nothing was done",null),q.debug("Rendering","Resize finished")}layoutAndRender(){q.debug("Rendering","Rendering at scale "+this.settings.display.scale+" with layout "+this.layout.name,null),this.layout.layoutAndRender(),this._renderedTracks=this.tracks,this.onRenderFinished(),this.postRenderFinished.trigger()}onRenderFinished(){this.boundsLookup?.finish();const e=new _i;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}class Pi{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){Po.globalThis.alphaTabWebWorker=new Pi(Po.globalThis)}handleMessage(e){let t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":let e=mi.jsObjectToSettings(t.settings);q.logLevel=e.core.logLevel,this._renderer=new Ni(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:mi.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(s,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(e){Si.FontSizeLookupTables||(Si.FontSizeLookupTables=new Map);for(let t in e)Si.FontSizeLookupTables.set(t,e[t])}}updateSettings(e){$s.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){q.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class Ci{constructor(){this._canvas=null,this._color=new fe(0,0,0,255),this._font=new As("Arial",10,Ge.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 As(s,parseFloat(t.fontSize),Ge.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){this._canvas=document.createElement("canvas"),this._canvas.width=e*Po.HighDpiFactor|0,this._canvas.height=t*Po.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(Po.HighDpiFactor,Po.HighDpiFactor),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){this._context.strokeRect(0|e,0|t,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(this.settings.display.scale)),this._measureContext.font=e.toCssString(this.settings.display.scale)}get textAlign(){switch(this._context.textAlign){case"left":default:return P.Left;case"center":return P.Center;case"right":return P.Right}}set textAlign(e){switch(e){case P.Left:this._context.textAlign="left";break;case P.Center:this._context.textAlign="center";break;case P.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return C.Top;case"middle":return C.Middle;case"bottom":return C.Bottom}}set textBaseline(e){switch(e){case C.Top:this._context.textBaseline="hanging";break;case C.Middle:this._context.textBaseline="middle";break;case C.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,s){this._context.fillText(e,t,s)}measureText(e){return this._measureContext.measureText(e).width}fillMusicFontSymbol(e,t,s,i,a=!1){i!==N.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!==N.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a=!1){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 Ei{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 Ot(0,e,t,i,48,8))}addRest(e,t,s){this._smf1Mode||this._midiFile.addEvent(new Ht(e,t,s))}addNote(e,t,s,i,a,r){this._midiFile.addEvent(new zt(e,t,r,Ei.fixValue(i),Ei.fixValue(a))),this._midiFile.addEvent(new Ut(e,t+s,r,Ei.fixValue(i),Ei.fixValue(a)))}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,s,i,a){this._midiFile.addEvent(new Xt(e,t,s,i,Ei.fixValue(a)))}addProgramChange(e,t,s,i){this._midiFile.addEvent(new Yt(e,t,s,i))}addTempo(e,t){const s=6e7/t|0;this._midiFile.addEvent(new qt(e,s))}addBend(e,t,s,i){i=i>=Kt.MaxPitchWheel?Kt.MaxPitchWheel:Math.floor(i),this._midiFile.addEvent(new Jt(e,t,s,i))}addNoteBend(e,t,s,i,a){this._smf1Mode?this.addBend(e,t,s,a):(a=a*Kt.MaxPitchWheel20/Kt.MaxPitchWheel,this._midiFile.addEvent(new jt(e,t,s,i,a)))}finishTrack(e,t){this._midiFile.format!=Fe.MultiTrack&&0!=e||this._midiFile.addEvent(new Qt(e,t))}}class Fi{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))}}class Li{get finished(){return this.index>=this._score.masterBars.length}constructor(e){this._repeatStack=[],this._groupsOnStack=new Set,this._previousAlternateEndings=0,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}processCurrent(){const e=this._score.masterBars[this.index];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 Fi(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)}this.shouldPlay&&(this.currentTick+=e.calculateDuration())}moveNext(){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 Mi{constructor(e,t){this.beat=e,this.playbackStart=t}}class Ii{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 Mi(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 Di{constructor(){this.start=0,this.end=0,this.tempo=0,this.firstBeat=null,this.lastBeat=null,this.nextMasterBar=null,this.previousMasterBar=null}insertAfter(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.nextBeat=e.nextBeat,t.previousBeat=e,e.nextBeat&&(e.nextBeat.previousBeat=t),e.nextBeat=t,e==this.lastBeat&&(this.lastBeat=t))}insertBefore(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.previousBeat=e.previousBeat,t.nextBeat=e,e.previousBeat&&(e.previousBeat.nextBeat=t),e.previousBeat=t,e==this.firstBeat&&(this.firstBeat=t))}addBeat(e,t,i,a){const r=i+a;if(null==this.firstBeat){const s=new Ii(i,r);s.highlightBeat(e,t),this.insertAfter(this.firstBeat,s)}else if(i>=this.lastBeat.end){const s=new Ii(this.lastBeat.end,r);s.highlightBeat(e,t),this.insertAfter(this.lastBeat,s)}else{let a=null;if(i<this.firstBeat.start)a=this.firstBeat;else{let e=this.firstBeat;for(;null!=e;){if(i>=e.start&&i<e.end){a=e;break}e=e.nextBeat}if(null===a)throw new O(s.General,"Error on building lookup, unknown variant")}if(i<a.start)if(r==a.start){const s=new Ii(i,a.start);s.highlightBeat(e,t),this.insertBefore(this.firstBeat,s)}else if(r<a.end){const s=new Ii(i,a.start);s.highlightBeat(e,t),this.insertBefore(a,s);const n=new Ii(a.start,r);for(const e of a.highlightedBeats)n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(e,t),this.insertBefore(a,n),a.start=r}else if(r==a.end){const s=new Ii(i,a.start);s.highlightBeat(e,t),a.highlightBeat(e,t),this.insertBefore(a,s)}else{const s=new Ii(i,a.start);s.highlightBeat(e,t),a.highlightBeat(e,t),this.insertBefore(a,s),this.addBeat(e,t,a.end,r-a.end)}else if(i>a.start)if(r==a.end){const s=new Ii(a.start,i);for(const e of a.highlightedBeats)s.highlightBeat(e.beat,e.playbackStart);a.start=i,a.highlightBeat(e,t),this.insertBefore(a,s)}else if(r<a.end){const s=new Ii(a.start,i);this.insertBefore(a,s);const n=new Ii(i,r);this.insertBefore(a,n);for(const e of a.highlightedBeats)s.highlightBeat(e.beat,e.playbackStart),n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(e,t),a.start=r}else{const s=new Ii(a.start,i);for(const e of a.highlightedBeats)s.highlightBeat(e.beat,e.playbackStart);a.start=i,a.highlightBeat(e,t),this.insertBefore(a,s),this.addBeat(e,t,a.end,r-a.end)}else if(r===a.end)a.highlightBeat(e,t);else if(r<a.end){const s=new Ii(a.start,r);for(const e of a.highlightedBeats)s.highlightBeat(e.beat,e.playbackStart);s.highlightBeat(e,t),a.start=r,this.insertBefore(a,s)}else a.highlightBeat(e,t),this.addBeat(e,t,a.end,r-a.end)}}}class Ai{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}}class Ri{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.duration=W.ticksToMillis(e.tickDuration,e.masterBar.tempo)),e.nextBeat||(e.tickDuration=e.masterBar.end-e.start,e.duration=W.ticksToMillis(e.tickDuration,e.masterBar.tempo))}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 Ai(e);return r.beat=s,r.beatLookup=t,r.tickDuration=t.end-t.start,i&&this.fillNextBeat(r,a),r.duration=W.ticksToMillis(r.tickDuration,e.tempo),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 Di;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 Oi{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Gi{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class Vi{constructor(e,t,s){this._currentTempo=0,this._programsPerChannel=new Map,this.tickLookup=new Ri,this.applyTranspositionPitches=!0,this.transpositionPitches=new Map,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new Ks,this._currentTempo=this._score.tempo,this._handler=s}generate(){this.transpositionPitches.clear();for(const e of this._score.tracks)this.generateTrack(e);q.debug("Midi","Begin midi generation");const e=new Li(this._score);let t=null;for(;!e.finished;){const s=e.index,i=this._score.masterBars[s],a=e.currentTick;if(e.processCurrent(),e.shouldPlay){this.generateMasterBar(i,t,a);for(const e of this._score.tracks)for(const t of e.staves)s<t.bars.length&&this.generateBar(t.bars[s],a)}e.moveNext(),t=i}for(const t of this._score.tracks)this._handler.finishTrack(t.index,e.currentTick);q.debug("Midi","Midi generation done")}generateTrack(e){this.generateChannel(e,e.playbackInfo.primaryChannel,e.playbackInfo),e.playbackInfo.primaryChannel!==e.playbackInfo.secondaryChannel&&this.generateChannel(e,e.playbackInfo.secondaryChannel,e.playbackInfo)}addProgramChange(e,t,s,i){this._programsPerChannel.has(s)&&this._programsPerChannel.get(s)===i||(this._handler.addProgramChange(e.index,t,s,i),this._programsPerChannel.set(s,i))}static buildTranspositionPitches(e,t){const s=new Map;for(const i of e.tracks){const e=i.index<t.notation.transpositionPitches.length?t.notation.transpositionPitches[i.index]:0;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]:0;this.transpositionPitches.set(t,i);let a=Vi.toChannelShort(s.volume),r=Vi.toChannelShort(s.balance);this._handler.addControlChange(e.index,0,t,Oe.VolumeCoarse,a),this._handler.addControlChange(e.index,0,t,Oe.PanCoarse,r),this._handler.addControlChange(e.index,0,t,Oe.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,Oe.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,Oe.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,Oe.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,Oe.DataEntryCoarse,Vi.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){t&&t.timeSignatureDenominator===e.timeSignatureDenominator&&t.timeSignatureNumerator===e.timeSignatureNumerator||this._handler.addTimeSignature(s,e.timeSignatureNumerator,e.timeSignatureDenominator),e.tempoAutomation?(this._handler.addTempo(s,e.tempoAutomation.value),this._currentTempo=e.tempoAutomation.value):t||(this._handler.addTempo(s,e.score.tempo),this._currentTempo=e.score.tempo);const i=new Di;i.masterBar=e,i.start=s,i.tempo=this._currentTempo,i.end=i.start+e.calculateDuration(),this.tickLookup.addMasterBar(i)}generateBar(e,t){let s=this.getPlaybackBar(e);for(const i of s.voices)this.generateVoice(i,t,e)}getPlaybackBar(e){switch(e.simileMark){case o.Simple:e.previousBar&&(e=this.getPlaybackBar(e.previousBar));break;case o.FirstOfDouble:case o.SecondOfDouble:e.previousBar&&e.previousBar.previousBar&&(e=this.getPlaybackBar(e.previousBar.previousBar))}return e}generateVoice(e,t,s){if(!e.isEmpty||e.bar.isEmpty&&0===e.index)for(const i of e.beats)this.generateBeat(i,t,s)}generateBeat(e,t,s){let i=e.playbackStart,a=e.playbackDuration;e.voice.bar.isEmpty?a=e.voice.bar.masterBar.calculateDuration():e.voice.bar.masterBar.tripletFeel!==D.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(i-=this._currentTripletFeel.secondBeatStartOffset,a=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=Vi.calculateTripletFeelInfo(i,a,e),this._currentTripletFeel&&(a=this._currentTripletFeel.firstBeatDuration))),s===e.voice.bar?this.tickLookup.addBeat(e,i,a):this.tickLookup.addBeat(e,0,a);const r=e.voice.bar.staff.track;for(const s of e.automations)this.generateAutomation(e,s,t);if(e.isRest)this._handler.addRest(r.index,t+i,r.playbackInfo.primaryChannel);else{let s=this.getBrushInfo(e);for(const r of e.notes)this.generateNote(r,t+i,a,s)}if(e.vibrato!==_.None){let s=240,a=3;switch(e.vibrato){case _.Slight:s=this._settings.player.vibrato.beatSlightLength,a=this._settings.player.vibrato.beatSlightAmplitude;break;case _.Wide:s=this._settings.player.vibrato.beatWideLength,a=this._settings.player.vibrato.beatWideAmplitude}this.generateVibratorWithParams(t+i,e.playbackDuration,s,a,((t,s)=>{this._handler.addBend(e.voice.bar.staff.track.index,t,r.playbackInfo.secondaryChannel,s)}))}}static calculateTripletFeelInfo(e,t,s){let i;switch(s.voice.bar.masterBar.tripletFeel){case D.Triplet8th:case D.Dotted8th:case D.Scottish8th:i=u.Eighth;break;case D.Triplet16th:case D.Dotted16th:case D.Scottish16th:i=u.Sixteenth;break;default:return null}const a=W.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 Gi;switch(s.voice.bar.masterBar.tripletFeel){case D.Triplet8th:r.firstBeatDuration=W.applyTuplet(W.toTicks(u.Quarter),3,2),r.secondBeatDuration=W.applyTuplet(W.toTicks(u.Eighth),3,2);break;case D.Dotted8th:r.firstBeatDuration=W.applyDot(W.toTicks(u.Eighth),!1),r.secondBeatDuration=W.toTicks(u.Sixteenth);break;case D.Scottish8th:r.firstBeatDuration=W.toTicks(u.Sixteenth),r.secondBeatDuration=W.applyDot(W.toTicks(u.Eighth),!1);break;case D.Triplet16th:r.firstBeatDuration=W.applyTuplet(W.toTicks(u.Eighth),3,2),r.secondBeatDuration=W.applyTuplet(W.toTicks(u.Sixteenth),3,2);break;case D.Dotted16th:r.firstBeatDuration=W.applyDot(W.toTicks(u.Sixteenth),!1),r.secondBeatDuration=W.toTicks(u.ThirtySecond);break;case D.Scottish16th:r.firstBeatDuration=W.toTicks(u.ThirtySecond),r.secondBeatDuration=W.applyDot(W.toTicks(u.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateNote(e,t,s,i){const a=e.beat.voice.bar.staff.track,r=e.beat.voice.bar.staff;let n=e.calculateRealValue(this.applyTranspositionPitches,!0);if(e.isPercussion){const t=$.getArticulation(e);t&&(n=t.outputMidiNumber)}const o=e.isStringed&&e.string<=i.length?i[e.string-1]:0,h=t+o,l=this.getNoteDuration(e,s);l.untilTieOrSlideEnd-=o,l.noteOnly-=o,l.letRingEnd-=o;const c=Vi.getNoteVelocity(e),d=e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==_.None?a.playbackInfo.secondaryChannel:a.playbackInfo.primaryChannel;let u=0;if(u=e.hasBend?Vi.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?Vi.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===S.Legato?-1:Vi.getPitchWheel(0),u>=0&&this._handler.addNoteBend(a.index,h,d,n,u),e.beat.fadeIn&&this.generateFadeIn(e,h,l),!e.isTrill||r.isPercussion){if(e.beat.isTremolo)this.generateTremoloPicking(e,h,l,n,c,d);else if(e.hasBend?this.generateBend(e,h,l,n,d):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,h,l,d):e.slideInType!==b.None||e.slideOutType!==S.None?this.generateSlide(e,h,l,n,d):(e.vibrato!==_.None||e.isTieDestination&&e.tieOrigin.vibrato!==_.None)&&this.generateVibrato(e,h,l,n,d),!(e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===S.Legato)){let e=Math.max(l.untilTieOrSlideEnd,l.letRingEnd);this._handler.addNote(a.index,h,e,n,c,d)}}else this.generateTrill(e,h,l,n,c,d)}getNoteDuration(e,t){const s=new Oi;if(s.noteOnly=t,s.untilTieOrSlideEnd=t,s.letRingEnd=t,e.isDead)return s.noteOnly=this.applyStaticDuration(Vi.DefaultDurationDead,t),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(e.isPalmMute)return s.noteOnly=this.applyStaticDuration(Vi.DefaultDurationPalmMute,t),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(e.isStaccato)return s.noteOnly=t/2|0,s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(e.isTieOrigin){const i=e.tieDestination;if(i)if(e.isTieDestination){const e=this.getNoteDuration(i,i.beat.playbackDuration);s.untilTieOrSlideEnd=t+e.untilTieOrSlideEnd}else{const t=e.beat.absolutePlaybackStart,a=this.getNoteDuration(i,i.beat.playbackDuration),r=i.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-t}}else if(e.slideOutType===S.Legato){const t=e.slideTarget;if(t){const i=e.beat.absolutePlaybackStart,a=this.getNoteDuration(t,t.beat.playbackDuration),r=t.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-i}}if(e.isLetRing&&this._settings.notation.notationMode===T.GuitarPro){let i=e.beat,a=0;const r=e.beat.voice.bar.masterBar.calculateDuration();for(;i.nextBeat;){let t=i.nextBeat;if(t.isRest)break;if(e.isStringed&&t.hasNoteOnString(e.string))break;if(i=i.nextBeat,a=i.absolutePlaybackStart-e.beat.absolutePlaybackStart+i.playbackDuration,a>r){a=r;break}}i===e.beat?s.letRingEnd=t:s.letRingEnd=a}else s.letRingEnd=s.untilTieOrSlideEnd;return s}applyStaticDuration(e,t){const s=this._currentTempo*e/z.MaxPosition|0;return Math.min(s,t)}static getNoteVelocity(e){let t=e.dynamics;switch(!e.beat.voice.bar.staff.isPercussion&&e.hammerPullOrigin&&t--,e.isGhost&&t--,e.accentuated){case i.Normal:t++;break;case i.Heavy:t+=2}return W.dynamicToVelocity(t)}generateFadeIn(e,t,s){const i=e.beat.voice.bar.staff.track,a=Vi.toChannelShort(i.playbackInfo.volume)/s.noteOnly,r=s.noteOnly/120|0,n=t+s.noteOnly;for(let e=r-1;e>=0;e--){const s=n-120*e,o=(s-t)*a;e===r-1&&(this._handler.addControlChange(i.index,t,i.playbackInfo.primaryChannel,Oe.VolumeCoarse,o),this._handler.addControlChange(i.index,t,i.playbackInfo.secondaryChannel,Oe.VolumeCoarse,o)),this._handler.addControlChange(i.index,s,i.playbackInfo.primaryChannel,Oe.VolumeCoarse,o),this._handler.addControlChange(i.index,s,i.playbackInfo.secondaryChannel,Oe.VolumeCoarse,o)}}generateVibrato(e,t,s,i,a){let r=0,n=0;switch(e.vibrato!==_.None?e.vibrato:e.isTieDestination?e.tieOrigin.vibrato:_.Slight){case _.Slight:r=this._settings.player.vibrato.noteSlightLength,n=this._settings.player.vibrato.noteSlightAmplitude;break;case _.Wide:r=this._settings.player.vibrato.noteWideLength,n=this._settings.player.vibrato.noteWideAmplitude;break;default:return}const o=e.beat.voice.bar.staff.track;this.generateVibratorWithParams(t,s.noteOnly,r,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)}))}generateVibratorWithParams(e,t,s,i,a){const r=this.vibratoResolution,n=s/2|0,o=(e+=s)+t;for(;e<o;){let t=0;const h=e+s<o?s:o-e;for(;t<h;){let s=i*Math.sin(t*Math.PI/n);a(e+t|0,Vi.getPitchWheel(s)),t+=r}e+=s}}static getPitchWheel(e){return Kt.DefaultPitchWheel+e/2*Vi.PitchValuePerSemitone}generateSlide(e,t,s,i,a){let r=e.slideOutType===S.Legato?s.noteOnly:s.untilTieOrSlideEnd,n=[],o=e.beat.voice.bar.staff.track;const h=this._settings.player.slide.simpleSlidePitchOffset,l=Math.floor(z.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),c=Math.floor(z.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case b.IntoFromAbove:n.push(new z(0,h)),n.push(new z(l,0));break;case b.IntoFromBelow:n.push(new z(0,-h)),n.push(new z(l,0))}switch(e.slideOutType){case S.Legato:case S.Shift:n.push(new z(c,0));const t=2*(e.slideTarget.calculateRealValue(this.applyTranspositionPitches,!0)-e.calculateRealValue(this.applyTranspositionPitches,!0));n.push(new z(z.MaxPosition,t));break;case S.OutDown:n.push(new z(z.MaxPosition-l,0)),n.push(new z(z.MaxPosition,-h));break;case S.OutUp:n.push(new z(z.MaxPosition-l,0)),n.push(new z(z.MaxPosition,h))}this.generateWhammyOrBend(t,r,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)}))}generateBend(e,t,s,i,a){let r=e.bendPoints,n=e.beat.voice.bar.staff.track;const o=(e,t)=>{this._handler.addNoteBend(n.index,e,a,i,t)};let c,d=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend;)t=t.tieDestination;c=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==g.None){switch(e.tieDestination.bendType){case l.Bend:case l.BendRelease:case l.PrebendBend:d=e.tieDestination.bendPoints[1].value;break;case l.Prebend:case l.PrebendRelease:d=e.tieDestination.bendPoints[0].value}c=Math.max(s.noteOnly,W.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo))}else c=s.noteOnly;r[0].value>0&&!e.isContinuedBend&&t>0&&t--;const u=Math.min(c,W.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));let p=[];switch(e.bendType){case l.Custom:p=r;break;case l.Bend:case l.Release:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new z(0,e.bendPoints[0].value)),(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),p.push(new z(z.MaxPosition,d));break;case h.Fast:return(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),void(e.beat.graceType===g.BendGrace?this.generateSongBookWhammyOrBend(t,c,!0,[e.bendPoints[0].value,d],u,o):this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,d],u,o))}break;case l.BendRelease:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new z(0,e.bendPoints[0].value)),p.push(new z(z.MaxPosition/2|0,e.bendPoints[1].value)),p.push(new z(z.MaxPosition,e.bendPoints[2].value));break;case h.Fast:return void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],u,o)}break;case l.Hold:case l.Prebend:p=r;break;case l.PrebendBend:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new z(0,e.bendPoints[0].value)),p.push(new z(z.MaxPosition,e.bendPoints[1].value));break;case h.Fast:return o(t,0|Vi.getPitchWheel(e.bendPoints[0].value)),(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,d],u,o)}break;case l.PrebendRelease:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new z(0,e.bendPoints[0].value)),p.push(new z(z.MaxPosition,e.bendPoints[1].value));break;case h.Fast:return o(t,0|Vi.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,e.bendPoints[1].value],u,o)}}this.generateWhammyOrBend(t,c,p,o)}generateSongBookWhammyOrBend(e,t,s,i,a,r){const n=s?e:e+t-a,o=a/(i.length-1);for(let e=0;e<i.length-1;e++){const t=Vi.getPitchWheel(i[e]),s=Vi.getPitchWheel(i[e+1]),a=n+o*e;this.generateBendValues(a,o,t,s,r)}}generateWhammy(e,t,s,i){const a=e.whammyBarPoints,r=e.voice.bar.staff.track,n=s.noteOnly;a[0].value>0&&!e.isContinuedWhammy&&t--;const o=(e,t)=>{this._handler.addBend(r.index,e,i,t)};let l=[];switch(e.whammyBarType){case E.Custom:l=a;break;case E.Dive:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new z(0,a[0].value)),l.push(new z(z.MaxPosition,a[1].value));break;case h.Fast:const e=Math.min(n,W.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],e,o)}break;case E.Dip:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new z(0,a[0].value)),l.push(new z(z.MaxPosition/2|0,a[1].value)),l.push(new z(z.MaxPosition,a[2].value));break;case h.Fast:const e=Math.min(n,W.millisToTicks(this._settings.player.songBookDipDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!0,[a[0].value,a[1].value,a[2].value],e,o)}break;case E.Hold:case E.Predive:l=a;break;case E.PrediveDive:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new z(0,a[0].value)),l.push(new z(z.MaxPosition/2|0,a[0].value)),l.push(new z(z.MaxPosition,a[1].value));break;case h.Fast:const e=Vi.getPitchWheel(a[0].value);this._handler.addBend(r.index,t,i,0|e);const s=Math.min(n,W.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],s,o)}}this.generateWhammyOrBend(t,n,l,o)}generateWhammyOrBend(e,t,s,i){const a=t/z.MaxPosition;for(let t=0;t<s.length-1;t++){const r=s[t],n=s[t+1],o=Vi.getPitchWheel(r.value),h=Vi.getPitchWheel(n.value),l=a*(n.offset-r.offset),c=e+a*r.offset;this.generateBendValues(c,l,o,h,i)}}generateBendValues(e,t,s,i,a){const r=W.ticksToMillis(t,this._currentTempo),n=Math.abs(i-s)/Vi.PitchValuePerSemitone,o=Math.max(Vi.MinBreakpointsPerSemitone*n,r/Vi.MillisecondsPerBreakpoint),h=t/o,l=(i-s)/o;for(let t=0;t<o;t++)a(0|e,Math.round(s)),s+=l,e+=h;s<i&&a(0|e,i)}generateTrill(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=W.toTicks(e.trillSpeed),l=!0,c=t,d=t+s.untilTieOrSlideEnd;for(;c+10<d;)c+h>=d&&(h=d-c),this._handler.addNote(n.index,c,h,l?o:i,a,r),l=!l,c+=h}generateTremoloPicking(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track;let o=W.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}getBrushInfo(e){const t=new Int32Array(e.voice.bar.staff.tuning.length);if(e.brushType!==c.None){let s=0,i=0;for(const t of e.notes)t.isTieDestination||(s|=1<<t.string-1,i++);if(e.notes.length>0){let a=0;const r=e.brushDuration/(i-1)|0;for(let i=0;i<e.voice.bar.staff.tuning.length;i++){let n=e.brushType===c.ArpeggioDown||e.brushType===c.BrushDown?i:t.length-1-i;s&1<<n&&(t[n]=a,a+=r)}}}return t}generateAutomation(e,t,s){switch(t.type){case a.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 a.Balance:let i=Vi.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Oe.PanCoarse,i),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Oe.PanCoarse,i);break;case a.Volume:let r=Vi.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Oe.VolumeCoarse,r),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Oe.VolumeCoarse,r)}}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 a.Instrument:s=i.value;break;case a.Tempo:t=i.value}i=i.previousBeat}const r=e.voice.bar.staff.track,n=e.voice.bar.masterBar;-1===t&&(t=n.score.tempo),-1===s&&(s=r.playbackInfo.program);const o=r.playbackInfo.volume;this.generateTrack(r),this._handler.addTimeSignature(0,n.timeSignatureNumerator,n.timeSignatureDenominator),this._handler.addTempo(0,t);let h=Vi.toChannelShort(o);this._handler.addControlChange(0,0,r.playbackInfo.primaryChannel,Oe.VolumeCoarse,h),this._handler.addControlChange(0,0,r.playbackInfo.secondaryChannel,Oe.VolumeCoarse,h)}generateSingleBeat(e){this.prepareSingleBeat(e),this.generateBeat(e,-e.playbackStart,e.voice.bar)}generateSingleNote(e){this.prepareSingleBeat(e.beat),this.generateNote(e,0,e.beat.playbackDuration,new Int32Array(e.beat.voice.bar.staff.tuning.length))}}Vi.DefaultDurationDead=30,Vi.DefaultDurationPalmMute=80,Vi.PitchBendRangeInSemitones=16,Vi.PitchValuePerSemitone=Kt.DefaultPitchWheel/Vi.PitchBendRangeInSemitones,Vi.MinBreakpointsPerSemitone=6,Vi.MillisecondsPerBreakpoint=150;class Hi{constructor(){this.startTick=0,this.endTick=0}}class Wi{constructor(e,t){this.width=0,this.height=0,this.x=e,this.y=t}get scale(){return this.renderer.scale}doLayout(){}paint(e,t,s){}}class zi extends Wi{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Ui extends zi{constructor(e,t,s,i){super(e,t),this.glyphScale=0,this.glyphScale=s,this.symbol=i}paint(e,t,s){s.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale*this.scale,this.symbol,!1)}}class Xi extends Ui{constructor(e,t,s,i){super(e,t,i?Xi.GraceScale:1,Xi.getSymbol(s)),this._isGrace=i,this._duration=s}paint(e,t,s){let i=this._isGrace?this.scale:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale*this.scale,this.symbol,!1)}doLayout(){let e=(this._isGrace?Xi.GraceScale:1)*this.scale;switch(this._duration){case u.QuadrupleWhole:this.width=14*e;break;case u.DoubleWhole:case u.Whole:this.width=14*(this._isGrace?Xi.GraceScale:1)*this.scale;break;default:this.width=Xi.QuarterNoteHeadWidth*(this._isGrace?Xi.GraceScale:1)*this.scale}this.height=Xi.NoteHeadHeight*e}static getSymbol(e){switch(e){case u.QuadrupleWhole:return N.NoteheadDoubleWholeSquare;case u.DoubleWhole:return N.NoteheadDoubleWhole;case u.Whole:return N.NoteheadWhole;case u.Half:return N.NoteheadHalf;default:return N.NoteheadBlack}}}Xi.GraceScale=.75,Xi.NoteHeadHeight=8,Xi.QuarterNoteHeadWidth=9;class Yi extends Ui{constructor(e,t,s,i,a){super(e,t,a?Xi.GraceScale:1,Yi.getSymbol(s,i,a))}doLayout(){this.width=0}static getSymbol(e,t,s){if(s&&(e=u.Eighth),t===Ce.Up)switch(e){case u.Eighth:return N.FlagEighthUp;case u.Sixteenth:return N.FlagSixteenthUp;case u.ThirtySecond:return N.FlagThirtySecondUp;case u.SixtyFourth:return N.FlagSixtyFourthUp;case u.OneHundredTwentyEighth:return N.FlagOneHundredTwentyEighthUp;case u.TwoHundredFiftySixth:return N.FlagTwoHundredFiftySixthUp;default:return N.FlagEighthUp}switch(e){case u.Eighth:return N.FlagEighthDown;case u.Sixteenth:return N.FlagSixteenthDown;case u.ThirtySecond:return N.FlagThirtySecondDown;case u.SixtyFourth:return N.FlagSixtyFourthDown;case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:return N.FlagOneHundredTwentyEighthDown;default:return N.FlagEighthDown}}}Yi.FlagWidth=11;class qi extends Wi{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)}registerLayoutingInfo(e){let t=this.preNotes.computedWidth+this.onNotes.centerX;this.beat.graceGroup&&!this.beat.graceGroup.isComplete&&(t+=qi.GraceBeatPadding*this.renderer.scale);let s=this.onNotes.computedWidth-this.onNotes.centerX;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);(i&&i.hasFlag||this.beat.graceType!==g.None)&&(s+=Yi.FlagWidth*this.scale*(this.beat.graceType!==g.None?Xi.GraceScale:1));for(const e of this.ties)s+=e.width;this.beat.graceType!==g.None&&(s+=qi.GraceBeatPadding*this.renderer.scale),e.addBeatSpring(this.beat,t,s),e.setPreBeatSize(this.beat,this.preNotes.computedWidth),e.setOnBeatSize(this.beat,this.onNotes.computedWidth),e.setBeatCenterX(this.beat,this.onNotes.centerX)}applyLayoutingInfo(e){let t=e.getBeatCenterX(this.beat)-this.onNotes.centerX;this.beat.graceGroup&&!this.beat.graceGroup.isComplete&&(t+=qi.GraceBeatPadding*this.renderer.scale),this.preNotes.x=t,this.preNotes.width=e.getPreBeatSize(this.beat),this.onNotes.width=e.getOnBeatSize(this.beat),this.onNotes.x=this.preNotes.x+this.preNotes.width,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>=u.Eighth&&(this.minWidth+=20*this.scale);else switch(this.beat.duration){case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:this.minWidth+=10*this.scale}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(qi.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 Bi;a.beat=this.beat,a.visualBounds=new rt,a.visualBounds.x=t+this.x+this.onNotes.x,a.visualBounds.y=e.visualBounds.y,a.visualBounds.w=this.onNotes.width,a.visualBounds.h=e.visualBounds.h,a.realBounds=new rt,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,i&&(a.visualBounds.x=t+this.x,a.realBounds.x=a.visualBounds.x),e.addBeat(a),this.renderer.settings.core.includeNoteBounds&&this.onNotes.buildBoundingsLookup(a,t+this.x,s+this.y)}}qi.GraceBeatPadding=3;class Ji{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new Co}causeIssue(){return this.settings=null,!0}}class ji{constructor(e){this.activeBeats=e}}class Qi{constructor(e){this.bounds=null,this.beat=e}}class $i{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=Me.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=Me.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new Cs,this.activeBeatsChanged=new Cs,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new Cs,this.beatMouseMove=new Cs,this.beatMouseUp=new Cs,this.noteMouseDown=new Cs,this.noteMouseMove=new Cs,this.noteMouseUp=new Cs,this.scoreLoaded=new Cs,this.resize=new Cs,this.renderStarted=new Cs,this.renderFinished=new Cs,this.postRenderFinished=new Ps,this.error=new Cs,this.playerReady=new Ps,this.playerFinished=new Ps,this.soundFontLoaded=new Ps,this.midiLoad=new Cs,this.midiLoaded=new Cs,this.playerStateChanged=new Cs,this.playerPositionChanged=new Cs,this.midiEventsPlayed=new Cs,this.playbackRangeChanged=new Cs,this.settingsUpdated=new Ps,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),q.logLevel=this.settings.core.logLevel,this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&Po.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new Ni(this.settings),this.container.resize.on(Po.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));let s=new Ji;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;q.debug("rendering","Rendering completed in "+e+"ms"),this.onPostRenderFinished()})),this.renderer.preRender.on((e=>{this._startTime=Date.now()})),this.renderer.partialLayoutFinished.on(this.appendRenderResult.bind(this)),this.renderer.partialRenderFinished.on(this.updateRenderResult.bind(this)),this.renderer.renderFinished.on((e=>{this.appendRenderResult(e),this.appendRenderResult(null)})),this.renderer.error.on(this.onError.bind(this)),this.settings.player.enablePlayer&&this.setupPlayer(),this.setupClickHandling(),this.uiFacade.beginInvoke((()=>{this.uiFacade.initialRender()}))}destroy(){this._isDestroyed=!0,this.player&&this.player.destroy(),this.uiFacade.destroy(),this.renderer.destroy()}updateSettings(){const e=this.score;e&&j.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?(this.setupPlayer(),e&&this.player?.applyTranspositionPitches(Vi.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(e){if(e.length>0){let t=e[0].score;for(let i of e)if(i.score!==t)return void this.onError(new O(s.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(t,e)}}internalRenderTracks(e,t){if(j.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 Ji;e.oldWidth=this.renderer.width,e.newWidth=this.container.width,e.settings=this.settings,this.onResize(e),this.renderer.updateSettings(this.settings),this.renderer.width=this.container.width,this.renderer.resizeRender()}else q.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{q.debug("Rendering","AlphaTab container became visible, doing autosizing",null),this.triggerResize()}))}appendRenderResult(e){e?(this.canvasElement.width=e.totalWidth,this.canvasElement.height=e.totalHeight,this._cursorWrapper&&(this._cursorWrapper.width=e.totalWidth,this._cursorWrapper.height=e.totalHeight),(e.width>0||e.height>0)&&this.uiFacade.beginAppendRenderResults(e)):this.uiFacade.beginAppendRenderResults(e)}updateRenderResult(e){e&&e.renderResult&&this.uiFacade.beginUpdateRenderResults(e)}tex(e,t){try{let s=new tt;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:Me.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=Me.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.player||!this.score||!this.player.isReady)return;q.debug("AlphaTab","Generating Midi");let e=new At,t=new Ei(e),s=new Vi(this.score,this.settings,t);s.applyTranspositionPitches=!1,s.generate(),this._tickCache=s.tickLookup,this.onMidiLoad(e),this.player.loadMidiFile(e),this.player.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)}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 At,s=new Ei(t);new Vi(e.voice.bar.staff.track.score,this.settings,s).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;let t=new At,s=new Ei(t);new Vi(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=Me.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===Me.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,c=this._previousCursorCache,d=this._previousStateForCursor;if(!i&&a===l?.beat&&h===c&&d===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(e){let t=this.uiFacade.getScrollContainer(),s=Po.getLayoutEngineFactory(this.settings.display.layoutMode).vertical,i=this.settings.player.scrollMode;if(s){let s=e.realBounds.y+this.settings.player.scrollOffsetY;if(s!==this._lastScroll)switch(this._lastScroll=s,i){case We.Continuous:let i=this.uiFacade.getOffset(t,this.container);this.uiFacade.scrollToY(t,i.y+s,this.settings.player.scrollSpeed);break;case We.OffScreen:let a=t.scrollTop+this.uiFacade.getOffset(null,t).h;if(e.visualBounds.y+e.visualBounds.h>=a||e.visualBounds.y<t.scrollTop){let s=e.realBounds.y+this.settings.player.scrollOffsetY;this.uiFacade.scrollToY(t,s,this.settings.player.scrollSpeed)}}}else{let s=e.visualBounds.x;if(s!==this._lastScroll)switch(this._lastScroll=s,i){case We.Continuous:let s=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,s,this.settings.player.scrollSpeed);break;case We.OffScreen:let i=t.scrollLeft+this.uiFacade.getOffset(null,t).w;if(e.visualBounds.x+e.visualBounds.w>=i||e.visualBounds.x<t.scrollLeft){let s=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,s,this.settings.player.scrollSpeed)}}}}internalCursorUpdateBeat(e,t,s,i,a,r,n,o){const h=this._barCursor,l=this._beatCursor;let c=n.barBounds.masterBarBounds,d=c.visualBounds;this._currentBarBounds=c,h&&h.setBounds(d.x,d.y,d.w,d.h),l&&(this.settings.player.enableAnimatedBeatCursor&&l.stopAnimation(),l.setBounds(n.visualBounds.x,d.y,1,d.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let u=!1;if(this._playerState===Me.Playing&&!i){if(this.settings.player.enableElementHighlighting)for(let t of a){let s=qi.getGroupId(t.beat);this.uiFacade.highlightElements(s,e.voice.bar.index)}if(this.settings.player.enableAnimatedBeatCursor){let e=c.visualBounds.x+c.visualBounds.w;if(t){let s=r.findBeat(t);s&&s.barBounds.masterBarBounds.staveGroupBounds===c.staveGroupBounds&&(e=s.visualBounds.x)}this.uiFacade.beginInvoke((()=>{l&&l.transitionToX(s/this.playbackSpeed,e)}))}o=!i,u=!0}o&&!this._beatMouseDown&&this.settings.player.scrollMode!==We.Off&&this.internalScrollToCursor(c),u&&(this.onPlayedBeatChanged(e),this.onActiveBeatsChanged(new ji(a.map((e=>e.beat)))))}onPlayedBeatChanged(e){this._isDestroyed||(this.playedBeatChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playedBeatChanged",e))}onActiveBeatsChanged(e){this._isDestroyed||(this.activeBeatsChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"activeBeatsChanged",e))}onBeatMouseDown(e,t){this._isDestroyed||(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&(this._selectionStart=new Qi(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 Qi(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===Me.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 Hi;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 Qi(t.beat),i=new Qi(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.staveGroupBounds!==t.bounds.barBounds.masterBarBounds.staveGroupBounds){let a=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x,o=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x+e.bounds.barBounds.masterBarBounds.staveGroupBounds.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.staveGroupBounds.index+1,c=t.bounds.barBounds.masterBarBounds.staveGroupBounds.index;for(let e=l;e<c;e++){let t=s.staveGroups[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),i.appendChild(r)}let d=this.uiFacade.createSelectionElement();d.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(d)}else{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||(q.error("API","An unexpected error occurred",e),this.error.trigger(e),this.uiFacade.triggerEvent(this.container,"error",e))}onPlayerReady(){this._isDestroyed||(this.playerReady.trigger(),this.uiFacade.triggerEvent(this.container,"playerReady",null))}onPlayerFinished(){this._isDestroyed||(this.playerFinished.trigger(),this.uiFacade.triggerEvent(this.container,"playerFinished",null))}onSoundFontLoaded(){this._isDestroyed||(this.soundFontLoaded.trigger(),this.uiFacade.triggerEvent(this.container,"soundFontLoaded",null))}onMidiLoad(e){this._isDestroyed||(this.midiLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"midiLoad",e))}onMidiLoaded(e){this._isDestroyed||(this.midiLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"midiFileLoaded",e))}onPlayerStateChanged(e){this._isDestroyed||(this.playerStateChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerStateChanged",e))}onPlayerPositionChanged(e){this._isDestroyed||null!==this.score&&this.tracks.length>0&&(this.playerPositionChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerPositionChanged",e))}onMidiEventsPlayed(e){this._isDestroyed||(this.midiEventsPlayed.trigger(e),this.uiFacade.triggerEvent(this.container,"midiEventsPlayed",e))}onPlaybackRangeChanged(e){this._isDestroyed||(this.playbackRangeChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playbackRangeChanged",e))}onSettingsUpdated(){this._isDestroyed||(this.settingsUpdated.trigger(),this.uiFacade.triggerEvent(this.container,"settingsUpdated",null))}}class Ki extends O{constructor(e,t){super(s.General,e),this.xhr=t,Object.setPrototypeOf(this,Ki.prototype)}}class Zi{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=Zi.loadScoreFromBytes(s,i);t(r)}catch(e){s(e)}else 0===a.status?s(new Ki("You are offline!!\n Please Check Your Network.",a)):404===a.status?s(new Ki("Requested URL not found.",a)):500===a.status?s(new Ki("Internel Server Error.",a)):"parsererror"===a.statusText?s(new Ki("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?s(new Ki("Request Time out.",a)):s(new Ki("Unknow Error: "+a.responseText,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Ks);let s=Po.buildImporters();q.debug("ScoreLoader",`Loading score from ${e.length} bytes using ${s.length} importers`);let i=null,a=Te.fromBuffer(e);for(let e of s){a.reset();try{q.debug("ScoreLoader","Importing using importer "+e.name),e.init(a,t),i=e.readScore(),q.debug("ScoreLoader","Score imported using "+e.name);break}catch(t){if(!(t instanceof G))throw q.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;q.debug("ScoreLoader",e.name+" does not support the file")}}if(i)return i;throw new G("No compatible importer found for file")}}class ea{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 ta{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.scrollTop=e}get scrollTop(){return this.element.scrollLeft}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 rt,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new ea(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new ea(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new ea(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&ta.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,ta.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=""}}ta.resizeObserver=new X((()=>new ResizeObserver((e=>{for(const t of e){let e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class sa{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new Cs,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(Po.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0,t=window.setInterval((()=>{q.warning("Rendering",`Could not load font '${this._families[0]}' within ${5*(e+1)} seconds`,null),this._families.length>1?(this._families.shift(),e=0):e++}),5e3);q.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);let s=e=>{this._families.length>1?(q.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(q.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},i=e=>{q.debug("Font",`[${e}] Font API signaled available`),this.isFontLoaded=!0,window.clearInterval(t),this.fontLoaded.trigger(this._families[0])},a=async()=>{for(const e of this._families)if(await this.isFontAvailable(e,!1))return void i(e);try{await document.fonts.load(`1em ${this._families[0]}`)}catch(e){s(e)}return q.debug("Font",`[${this._families[0]}] Font API signaled loaded`),await this.isFontAvailable(this._families[0],!0)?i(this._families[0]):s("Font not available"),!0};document.fonts.ready.then((()=>{a()}))}isFontAvailable(e,t){return new Promise((s=>{const i="1em "+e;if(document.fonts.check(i))s(!0);else if(t){q.debug("Font",`Font ${e} not available, creating test element to trigger load`);const t=document.createElement("div");t.style.font=i,t.style.opacity="0",t.style.position="absolute",t.style.top="0",t.style.left="0",t.innerText=`Trigger ${e} load`,document.body.appendChild(t),setTimeout((()=>{document.body.removeChild(t),document.fonts.check(i)?s(!0):s(!1)}),200)}else s(!1)}))}}class ia{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 aa{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new Ps,this.samplesPlayed=new Cs,this.sampleRequest=new Ps}get sampleRate(){return this._context?this._context.sampleRate:aa.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(q.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{q.debug("WebAudio",`Audio Context resume success: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}`),e&&e()}),(e=>{q.warning("WebAudio",`Audio Context resume failed: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}, reason=${e}`)})))}patchIosSampleRate(){let e=navigator.userAgent;if(-1!==e.indexOf("iPhone")||-1!==e.indexOf("iPad")){let e=this.createAudioContext(),t=e.createBuffer(1,1,aa.PreferredSampleRate),s=e.createBufferSource();s.buffer=t,s.connect(e.destination),s.start(0),s.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in Po.globalThis)return new AudioContext;if("webkitAudioContext"in Po.globalThis)return new webkitAudioContext;throw new O(s.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,aa.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()}}aa.BufferSize=4096,aa.PreferredSampleRate=44100;class ra extends aa{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/aa.BufferSize),this._circularBuffer=new ia(aa.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*aa.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*aa.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;for(let e=0;e<t.length;e++)t[e]=a[n++],s[e]=a[n++];this.onSamplesPlayed(r/Kt.AudioChannels),this.requestBuffers()}}class na{constructor(e,t){this.loaded=e,this.total=t}}class oa{get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return q.logLevel}set logLevel(e){q.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Kt.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Kt.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Kt.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=Ss.clamp(e,Kt.MinPlaybackSpeed,Kt.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=Me.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 Ps,this.readyForPlayback=new Ps,this.finished=new Ps,this.soundFontLoaded=new Ps,this.soundFontLoadFailed=new Cs,this.midiLoaded=new Cs,this.midiLoadFailed=new Cs,this.stateChanged=new Cs,this.positionChanged=new Cs,this.midiEventsPlayed=new Cs,this.playbackRangeChanged=new Cs,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Me.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=Po.createWebWorker(t)}catch(e){q.error("AlphaSynth","Failed to create WebWorker: "+e)}this._synth.addEventListener("message",this.handleWorkerMessage.bind(this),!1),this._synth.postMessage({cmd:"alphaSynth.initialize",sampleRate:this._output.sampleRate,logLevel:t.core.logLevel,bufferTimeInMilliseconds:t.player.bufferTimeInMilliseconds}),this.masterVolume=1,this.playbackSpeed=1,this.metronomeVolume=0}destroy(){this._synth.postMessage({cmd:"alphaSynth.destroy"})}play(){return this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.play"}),!0}pause(){this._synth.postMessage({cmd:"alphaSynth.pause"})}playPause(){this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.playPause"})}stop(){this._synth.postMessage({cmd:"alphaSynth.stop"})}playOneTimeMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.playOneTimeMidiFile",midi:mi.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,s){q.debug("AlphaSynth",`Start loading Soundfont from url ${e}`);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=>{q.error("AlphaSynth","Loading failed: "+e.message),this.soundFontLoadFailed.trigger(new Ki(e.message,i))},i.onprogress=e=>{q.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),s(new na(e.loaded,e.total))},i.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:mi.midiFileToJsObject(e)})}applyTranspositionPitches(e){this._synth.postMessage({cmd:"alphaSynth.applyTranspositionPitches",transpositionPitches:JSON.stringify(Array.from(e.entries()))})}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,Kt.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 is(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new Es(t.events.map(mi.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new ss(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new Fs(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 is(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 ha{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new Cs,this.partialRenderFinished=new Cs,this.partialLayoutFinished=new Cs,this.renderFinished=new Cs,this.postRenderFinished=new Ps,this.error=new Cs,this._api=e;try{this._worker=Po.createWebWorker(t)}catch(e){return void q.error("Rendering",`Failed to create WebWorker: ${e}`)}this._worker.postMessage({cmd:"alphaTab.initialize",settings:this.serializeSettingsForWorker(t)}),this._worker.addEventListener("message",this.handleWorkerMessage.bind(this))}destroy(){this._worker.terminate()}updateSettings(e){this._worker.postMessage({cmd:"alphaTab.updateSettings",settings:this.serializeSettingsForWorker(e)})}serializeSettingsForWorker(e){const t=mi.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=xi.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:mi.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:s,trackIndexes:t,fontSizes:Si.FontSizeLookupTables})}}class la{constructor(e,t,s,i){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=s,this.selectionWrapper=i}}!function(e){e[e.Browser=0]="Browser",e[e.NodeJs=1]="NodeJs",e[e.BrowserModule=2]="BrowserModule"}(Ue||(Ue={}));class ca{static init(){var e;ca._isRegistered||(ca._isRegistered=!0,registerProcessor("alphatab",((e=class extends AudioWorkletProcessor{constructor(t){super(t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,q.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new ia(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){let t=e.data;switch(t.cmd){case yi.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case yi.CmdOutputResetSamples:this._circularBuffer.clear()}}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;for(let e=0;e<i.length;e++)i[e]=n[h++],a[e]=n[h++];return this.port.postMessage({cmd:yi.CmdOutputSamplesPlayed,samples:o/Kt.AudioChannels}),this.requestBuffers(),!0}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:yi.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}ca._isRegistered=!1;class da extends aa{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;Po.createAudioWorklet(e,this._settings).then((()=>{this._worklet=new AudioWorkletNode(e,"alphatab",{numberOfOutputs:1,outputChannelCount:[2],processorOptions:{bufferTimeInMilliseconds:this._bufferTimeInMilliseconds}}),this._worklet.port.onmessage=this.handleMessage.bind(this),this._source.connect(this._worklet),this._source.start(0),this._worklet.connect(e.destination)}),(e=>{q.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){let t=e.data;switch(t.cmd){case yi.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case yi.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){this._worklet?.port.postMessage({cmd:yi.CmdOutputAddSamples,samples:e})}resetSamples(){this._worklet?.port.postMessage({cmd:yi.CmdOutputResetSamples})}}class ua extends ta{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"}(Xe||(Xe={}));class pa{get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(Po.bravuraFontChecker.checkForFontAvailability(),!Po.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(q.debug("Font","All fonts loaded: "+this._fontCheckers.size),!0)}onFontLoaded(e){Si.generateFontLookup(e),this.areAllFontsLoaded()&&this.canRenderChanged.trigger()}constructor(e){if(this._fontCheckers=new Map,this._contents=null,this._file=null,this._totalResultCount=0,this._initialTrackIndexes=null,this._barToElementLookup=new Map,this._resultIdToElementLookup=new Map,this.rootContainerBecameVisible=new Ps,this.canRenderChanged=new Ps,this._highlightedElements=[],this._scrollContainer=null,Po.webPlatform!==Ue.Browser&&Po.webPlatform!==Ue.BrowserModule)throw new O(s.General,"Usage of AlphaTabApi is only possible in browser environments. For usage in node use the Low Level APIs");e.classList.add("alphaTab"),this.rootContainer=new ta(e),this.areWorkersSupported="Worker"in window,Po.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(e)}onElementVisibilityChanged(e){for(const t of e){const e=t.target;if(e===this.rootContainer.element)t.isIntersecting&&(this.rootContainerBecameVisible.trigger(),this._intersectionObserver.unobserve(this.rootContainer.element));else if("layoutResultId"in e&&this._api.settings.core.enableLazyLoading){const s=e;t.isIntersecting?s.renderedResultId!==s.layoutResultId?this._resultIdToElementLookup.has(s.layoutResultId)?s.resultState!==Xe.RenderRequested&&(s.resultState=Xe.RenderRequested,this._api.renderer.renderResult(s.layoutResultId)):e.replaceChildren():s.resultState===Xe.Detached&&(e.replaceChildren(...s.renderedResult),s.resultState=Xe.RenderDone):s.resultState===Xe.RenderDone&&(s.resultState=Xe.Detached,s.replaceChildren())}}}createWorkerRenderer(){return new ha(this._api,this._api.settings)}initialize(e,t){let s;this._api=e,s=t instanceof Ks?t:mi.jsObjectToSettings(t);let i=this.getDataAttributes();$s.fromJson(s,i),s.notation.notationMode===T.SongBook&&s.setSongBookModeSettings(),e.settings=s,this.setupFontCheckers(s),this._initialTrackIndexes=this.parseTracks(s.core.tracks),this._contents="";let a=e.container;s.core.tex&&(this._contents=a.element.innerHTML,a.element.innerHTML=""),this.createStyleElement(s),this._file=s.core.file}setupFontCheckers(e){this.registerFontChecker(e.display.resources.copyrightFont),this.registerFontChecker(e.display.resources.effectFont),this.registerFontChecker(e.display.resources.fingeringFont),this.registerFontChecker(e.display.resources.graceFont),this.registerFontChecker(e.display.resources.markerFont),this.registerFontChecker(e.display.resources.tablatureFont),this.registerFontChecker(e.display.resources.titleFont),this.registerFontChecker(e.display.resources.wordsFont),this.registerFontChecker(e.display.resources.barNumberFont),this.registerFontChecker(e.display.resources.fretboardNumberFont),this.registerFontChecker(e.display.resources.subTitleFont)}registerFontChecker(e){if(!this._fontCheckers.has(e.families.join(", "))){let t=new sa(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 ta(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 ue)return t(e),!0;if(e instanceof ArrayBuffer){let s=new Uint8Array(e);return t(Zi.loadScoreFromBytes(s,this._api.settings)),!0}return e instanceof Uint8Array?(t(Zi.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(Zi.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&&Zi.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;Po.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=Xe.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=Xe.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 e=null,t="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window&&this._api.settings.player.outputMode===ze.WebAudioAudioWorklets?(q.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),e=new oa(new da(this._api.settings),this._api.settings)):t&&(q.debug("Player","Will use webworkers for synthesizing and web audio api with ScriptProcessor for playback"),e=new oa(new ra,this._api.settings)),e?e.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):q.error("Player","Player requires webworkers and web audio api, browser unsupported",null),e}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const s=this._barToElementLookup.get(t);if(s){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 la(new ta(t),i,a,new ta(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 rt;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 ta(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new ua(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 ga extends $i{constructor(e,t){super(new pa(e),t),this.soundFontLoad=new Cs}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.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,c=a.offsetWidth+50,d=window.innerHeight,u=(h/2|0)-(c/2|0)+n,p=(l/2|0)-(d/2|0)+o;i.resizeTo(c,d),i.moveTo(u,p),i.focus();let g=mi.jsObjectToSettings(mi.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,$s.fromJson(g,s);let f=new ga(a,g);i.onunload=()=>{f.destroy()},f.renderer.postRenderFinished.on((()=>{i.print()})),f.renderTracks(this.tracks)}downloadMidi(e=Fe.SingleTrackMultiChannel){if(!this.score)return;let t=new At;t.format=e;let s=new Ei(t,!0);new Vi(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 fa{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 q.error("Api","Method '"+t+"' does not exist on jQuery.alphaTab"),null}init(e,t,s){if(!t){t=new ga(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 ma{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.color=new fe(255,255,255,255),this.lineWidth=1,this.font=new As("Arial",10,Ge.Plain),this.textAlign=P.Left,this.textBaseline=C.Top}destroy(){}beginRender(e,t){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=C.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="${0|e}" y="${0|t}" width="${s}" height="${i}" fill="${this.color.rgba}" />\n`)}strokeRect(e,t,s,i){this.buffer+=`<rect x="${0|e}" y="${0|t}" width="${s}" height="${i}" stroke="${this.color.rgba}"`,1!==this.lineWidth&&(this.buffer+=` stroke-width="${this.lineWidth}"`),this.buffer+=' fill="transparent" />\n'}beginPath(){}closePath(){this._currentPath+=" z"}moveTo(e,t){this._currentPath+=` M${e},${t}`}lineTo(e,t){this._currentPathIsEmpty=!1,this._currentPath+=` L${e},${t}`}quadraticCurveTo(e,t,s,i){this._currentPathIsEmpty=!1,this._currentPath+=` Q${e},${t},${s},${i}`}bezierCurveTo(e,t,s,i,a,r){this._currentPathIsEmpty=!1,this._currentPath+=` C${e},${t},${s},${i},${a},${r}`}fillCircle(e,t,s){this._currentPathIsEmpty=!1,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,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&&(e+=` stroke-width="${this.lineWidth}"`),e+=' style="fill: none" />',this.buffer+=e}this._currentPath="",this._currentPathIsEmpty=!0}fillText(e,t,s){if(""===e)return;let i=`<text x="${0|t}" y="${0|s}" style="stroke: none; font:${this.font.toCssString(this.settings.display.scale)}" ${this.getSvgBaseLine()}`;"#000000"!==this.color.rgba&&(i+=` fill="${this.color.rgba}"`),this.textAlign!==P.Left&&(i+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),i+=`>${ma.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 P.Left:return"start";case P.Center:return"middle";case P.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case C.Top:return'dominant-baseline="hanging"';case C.Bottom:return'dominant-baseline="bottom"';default:return""}}measureText(e){return e?Si.measureString(e,this.font.families,this.font.size,this.font.style,this.font.weight):0}onRenderFinished(){return null}beginRotate(e,t,s){this.buffer+='<g transform="translate('+e+" ,"+t+") rotate( "+s+')">'}endRotate(){this.buffer+="</g>"}}class ya extends ma{constructor(){super()}fillMusicFontSymbol(e,t,s,i,a){i!==N.None&&this.fillMusicFontSymbolText(e,t,s,`&#${i};`,a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(let e of i)e!==N.None&&(r+=`&#${e};`);this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){this.buffer+=`<g transform="translate(${e} ${t})" class="at" ><text`,this.buffer+=1!==s?` style="font-size: ${100*s}%; stroke:none"`:' style="stroke:none"',"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),a&&(this.buffer+=' text-anchor="'+this.getSvgTextAlignment(P.Center)+'"'),this.buffer+=`>${i}</text></g>`}}class ba{constructor(){this.isInAccolade=!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"}(Ye||(Ye={}));class Sa extends Wi{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 _a extends Sa{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 wa extends Sa{constructor(e,t,s){super(e,t),this.voice=s,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){const t=this.renderer.scale;let s=this.renderer.layoutingInfo.spaceToForce(e/t);this.scaleToForce(s)}scaleToForce(e){const t=this.renderer.scale;this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e)*t;let s=this.renderer.layoutingInfo.buildOnTimePositions(e),i=this.beatGlyphs;for(let e=0,a=i.length;e<a;e++){let r=i[e];if(r.beat.graceType===g.None)r.x=s.get(r.beat.absoluteDisplayStart)*t-r.onTimeX;else{const a=r.beat.graceGroup.beats[0].absoluteDisplayStart,n=r.beat.graceGroup.id;if(r.beat.graceGroup.isComplete&&s.has(a)){r.x=s.get(a)*t-r.onTimeX;let e=this.renderer.layoutingInfo.allGraceRods.get(n);const i=r.beat.graceGroup.beats[r.beat.graceGroup.beats.length-1].nextBeat,o=i?this.renderer.layoutingInfo.getPreBeatSize(i)+qi.GraceBeatPadding*this.renderer.scale:0;r.x-=o,r.x-=e[r.beat.graceIndex].postSpringWidth,r.x+=e[r.beat.graceIndex].graceBeatWidth;const h=e[r.beat.graceGroup.beats.length-1];r.x-=h.graceBeatWidth}else{let t=this.renderer.layoutingInfo.incompleteGraceRods.get(n);const s=t[r.beat.graceIndex].postSpringWidth-t[r.beat.graceIndex].preSpringWidth;e>0?0===r.beat.graceIndex?r.x=i[e-1].x+i[e-1].width:r.x=i[e-1].x+t[r.beat.graceIndex-1].postSpringWidth-t[r.beat.graceIndex-1].preSpringWidth-s:r.x=-s}}if(e>0){let t=r.x-i[e-1].x;i[e-1].scaleToWidth(t)}if(e===a-1){let e=this.width-i[i.length-1].x;r.scaleToWidth(e)}}}registerLayoutingInfo(e){e.updateVoiceSize(this.width);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)}}wa.KeySizeBeat="Beat",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"}(qe||(qe={}));class Ba{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class Ta{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:$.getArticulationByValue(t)?.staffLine??0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case y.ForceDoubleFlat:t+=2;break;case y.ForceDoubleSharp:t-=2;break;case y.ForceFlat:t+=1;break;case y.ForceSharp:t-=1}return t}applyAccidental(e){const t=Ta.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=Ta.getNoteValue(t);if(e.staff.isPercussion)s=Ta.getPercussionLine(e,i);else{const a=t?t.accidentalMode:y.Default;s=Ta.calculateNoteLine(e,i,a)}return s}getAccidental(e,t,s,i,a=null){let r=qe.None,n=0;if(this._bar.staff.isPercussion)n=Ta.getPercussionLine(this._bar,e);else{const s=a?a.accidentalMode:y.Default;n=Ta.calculateNoteLine(this._bar,e,s);let i=this._bar.masterBar.keySignature+7,o=e%12,h=i<7?qe.Flat:qe.Sharp,l=Ta.KeySignatureLookup[i][o],c=Ta.AccidentalNotes[o];if(t)switch(r=c?h:qe.Natural,r){case qe.Natural:r=qe.NaturalQuarterNoteUp;break;case qe.Sharp:r=qe.SharpQuarterNoteUp;break;case qe.Flat:r=qe.FlatQuarterNoteUp}else{switch(s){case y.ForceSharp:r=qe.Sharp;break;case y.ForceDoubleSharp:r=qe.DoubleSharp;break;case y.ForceFlat:r=qe.Flat;break;case y.ForceDoubleFlat:r=qe.DoubleFlat;break;default:c?r=h:l&&(r=qe.Natural)}let e=!1;if(a&&a.isTieDestination&&0===a.beat.index){const t=this._barRenderer.previousRenderer;if(t){t.accidentalHelper.getNoteLine(a.tieOrigin)===n&&(e=!0)}}e?r=qe.None:r!==qe.None?(this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===r&&(r=qe.None):l&&r===h&&(r=qe.None),r!==qe.None&&this._registeredAccidentals.set(n,r)):this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===qe.Natural?r=qe.None:(r=qe.Natural,this._registeredAccidentals.set(n,r)):this._registeredAccidentals.delete(n)}}return a?(this._appliedScoreLines.set(a.id,n),this._notesByValue.set(e,a)):this._appliedScoreLinesByValue.set(e,n),(-1e3===this.minLine||this.minLine<n)&&(this.minLine=n,this.minLineBeat=s),(-1e3===this.maxLine||this.maxLine>n)&&(this.maxLine=n,this.maxLineBeat=s),i||this.registerLine(s,n),r}registerLine(e,t){let s;this._beatLines.has(e.id)?s=this._beatLines.get(e.id):(s=new Ba,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,s){let i=t,a=e.masterBar.keySignature,r=e.clef,n=i%12,o=(i/12|0)-1,h=Ta.OctaveSteps[r];return h-=o*Ta.StepsPerOctave,h-=(j.keySignatureIsSharp(a)||j.keySignatureIsNatural(a)?Ta.SharpNoteSteps:Ta.FlatNoteSteps)[n],h}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}}Ta.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]],Ta.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],Ta.StepsPerOctave=7,Ta.OctaveSteps=[38,32,30,26,38],Ta.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],Ta.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class ka{constructor(){this.staffId="",this.up=0,this.down=0}}class va{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 xa{get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}get hasLine(){return 1===this.beats.length&&this.beats[0].duration>u.Whole}get hasFlag(){return 1===this.beats.length&&!this.beats[0].isRest&&(this.beats[0].duration>u.Quarter||this.beats[0].graceType!==g.None)}constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=u.QuadrupleWhole,this.fingeringCount=0,this.hasTuplet=!1,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=Ce.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}getBeatLineX(e){return this.hasBeatLineX(e)?this.direction===Ce.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 ka),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(Ce.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==g.None)&&(e=this.invert(Ce.Up)):e=Ce.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){let t=this._renderer.getNoteY(this.highestNoteInHelper,je.Center),s=this._renderer.getNoteY(this.lowestNoteInHelper,je.Center);if(null===e){const i=(t+s)/2;e=this.invert(this._renderer.middleYPosition<i?Ce.Up:Ce.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(Ce.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:return[2,2];case u.Whole:return[0,1];case u.Half:return[1,0];case u.Quarter:return[3,3];case u.Eighth:return[2,2];case u.Sixteenth:return[2,4];case u.ThirtySecond:return[4,4];case u.SixtyFourth:return[4,6];case u.OneHundredTwentyEighth:return[6,6];case u.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=xa.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===Ce.Down?Ce.Up:Ce.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 F.Auto:t=xa.canJoin(this.beats[this.beats.length-1],e);break;case F.ForceSplitToNext:t=!1;break;case F.ForceMergeWithNext:t=!0}if(t){if(null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.isRest)0===this.beats.length&&this.beats.push(e);else{this.isRestBeamHelper&&(this.beats=[]),this.beats.push(e),e.graceType!==g.None&&(this.isGrace=!0),e.hasTuplet&&(this.hasTuplet=!0);let t=0;for(let s=0;s<e.notes.length;s++){let i=e.notes[s];i.leftHandFinger===f.Unknown&&i.rightHandFinger===f.Unknown||t++}t>this.fingeringCount&&(this.fingeringCount=t),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.hasTuplet&&(this.hasTuplet=!0)}return t}checkNote(e){if(!e)return;let t,s;this.voice&&e.isPercussion?(t=-Ta.getPercussionLine(this.voice.bar,Ta.getNoteValue(e)),s=t):(t=Ta.getNoteValue(e),s=t,e.harmonicType!==m.None&&e.harmonicType!==m.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===g.BendGrace||t.graceType===g.BendGrace)return!1;if(e.graceType!==g.None&&t.graceType!==g.None)return!0;let s=e.voice.bar;if(s!==t.voice.bar)return!1;let i=e.playbackStart,a=t.playbackStart;if(!xa.canJoinDuration(e.duration)||!xa.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=W.QuarterTime;if(8===s.masterBar.timeSignatureDenominator)s.masterBar.timeSignatureNumerator%3==0&&(r+=W.QuarterTime/2|0);return((r+i)/r|0)===((r+a)/r|0)}static canJoinDuration(e){switch(e){case u.Whole:case u.Half:case u.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,s){return j.getIndex(e.duration)-2-s>0&&j.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 Na{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class Pa{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new Na(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 Ca{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 Pa(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=xa.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 Ea{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this._renderer=e,this.collisionHelper=new Ca}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!==g.None?n=i:(n=s,i=null),n&&n.checkBeat(o)||(n&&n.finish(),n=new xa(t.staff,e),n.checkBeat(o),o.graceType!==g.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 Fa extends zi{constructor(e,t,s){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=s}doLayout(){super.doLayout();const e=this.scale;let t=this.renderer.resources;this._textRow=1.5*t.effectFont.size*e,this._fretRow=1.5*t.effectFont.size*e,this._chord.firstFret>1?this._firstFretSpacing=Fa.FretSpacing*e:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+(Fa.Frets-1)*Fa.FretSpacing*e+2*Fa.Padding*e,this.width=this._firstFretSpacing+(this._chord.staff.tuning.length-1)*Fa.StringSpacing*e+2*Fa.Padding*e}paint(e,t,s){e+=this.x+Fa.Padding*this.scale+this._firstFretSpacing,t+=this.y;let i=this.width-2*Fa.Padding*this.scale+this.scale-this._firstFretSpacing,a=Fa.StringSpacing*this.scale,r=Fa.FretSpacing*this.scale,n=this.renderer.resources,o=Fa.CircleRadius*this.scale,h=s.textAlign,l=s.textBaseline;s.font=n.effectFont,s.textAlign=P.Center,s.textBaseline=C.Top,this._chord.showName&&s.fillText(this._chord.name,e+this.width/2,t+n.effectFont.size/2),t+=this._textRow,e+=a/2,s.font=n.fretboardNumberFont,s.textBaseline=C.Middle;for(let i=0;i<this._chord.staff.tuning.length;i++){let r=e+i*a,n=t+this._fretRow/2,o=this._chord.strings[this._chord.staff.tuning.length-i-1];o<0?s.fillMusicFontSymbol(r,n,this.scale,N.FretboardX,!0):0===o?s.fillMusicFontSymbol(r,n,this.scale,N.FretboardO,!0):(o-=this._chord.firstFret-1,s.fillText(o.toString(),r,n))}t+=this._fretRow;for(let i=0;i<this._chord.staff.tuning.length;i++){let n=e+i*a;s.fillRect(n,t,1,r*Fa.Frets+this.scale)}this._chord.firstFret>1&&(s.textAlign=P.Left,s.fillText(this._chord.firstFret.toString(),e-this._firstFretSpacing,t+r/2)),s.fillRect(e,t-this.scale,i,2*this.scale);for(let a=0;a<=Fa.Frets;a++){let n=t+a*r;s.fillRect(e,n,i,this.scale)}let c=new Map;for(let e of this._chord.barreFrets){let t=[-1,-1];c.set(e-this._chord.firstFret,t)}for(let i=0;i<this._chord.strings.length;i++){let n=this._chord.strings[i];if(n>0){if(n-=this._chord.firstFret,c.has(n)){let e=c.get(n);(-1===e[0]||i<e[0])&&(e[0]=i),(-1===e[1]||i>e[1])&&(e[1]=i)}let h=t+n*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-i-1)*a;s.fillCircle(l,h,o)}}for(const[i,n]of c){let h=t+i*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-n[1]-1)*a,c=e+(this._chord.strings.length-n[0]-1)*a;s.fillRect(l,h-o,c-l,2*o)}s.textAlign=h,s.textBaseline=l}}Fa.Padding=5,Fa.Frets=5,Fa.CircleRadius=2.5,Fa.StringSpacing=10,Fa.FretSpacing=12;class La extends Sa{constructor(e,t,s=P.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=s}doLayout(){let e=0;switch(this._align){case P.Left:e=0;break;case P.Center:e=(this.width-this._glyphWidth)/2;break;case P.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 Ma extends Sa{constructor(e,t,s=P.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=s}doLayout(){let e=0,t=0,s=2*Ma.Padding*this.scale;this._rows=[];let i=new La(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 La(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+s}paint(e,t,s){for(let i of this._rows)i.paint(e+this.x,t+this.y+Ma.Padding*this.scale,s)}}Ma.Padding=3;class Ia extends Ma{constructor(e,t){super(e,t)}addChord(e){if(e.strings.length>0){let t=new Fa(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}}class Da extends zi{constructor(e,t,s,i,a=P.Left){super(e,t),this._lines=s.split("\n"),this.font=i,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,s){let i=s.color;s.color=i,s.font=this.font;let a=s.textAlign;s.textAlign=this.textAlign;let r=t+this.y;for(let t of this._lines)s.fillText(t,e+this.x,r),r+=this.font.size;s.textAlign=a}}class Aa{get staveId(){return this._factory.staffId}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.trackIndex=0,this.staveTop=0,this.topSpacing=20,this.bottomSpacing=5,this.staveBottom=0,this.isFirstInAccolade=!1,this.isLastInAccolade=!1,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 isInAccolade(){return this._factory.isInAccolade}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.staveGroup.layout.registerBarRenderer(this.staveId,e)}addBar(e,t){let s;s=e?this._factory.create(this.staveGroup.layout.renderer,e):new Ya(this.staveGroup.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.staveGroup.layout.systemsLayoutMode==Je.FromModelWithWidths&&(s.width=i),this.barRenderers.push(s),e&&this.staveGroup.layout.registerBarRenderer(this.staveId,s)}revertLastBar(){let e=this.barRenderers[this.barRenderers.length-1];return this.barRenderers.splice(this.barRenderers.length-1,1),this.staveGroup.layout.unregisterBarRenderer(this.staveId,e),e}scaleToWidth(e){this._sharedLayoutData=new Map;let t=this.topOverflow,s=0;switch(this.staveGroup.layout.systemsLayoutMode){case Je.Automatic:let i=(e-this.staveGroup.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 Je.FromModelWithScale:e-=this.staveGroup.accoladeSpacing;const a=this.staveGroup.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 Je.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}finalizeStaff(){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 Ra{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 Oa{constructor(){this._timeSortedSprings=[],this._xMin=0,this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,this.version=0,this.preBeatSizes=new Map,this.onBeatSizes=new Map,this.onBeatCenterX=new Map,this.preBeatSize=0,this.postBeatSize=0,this.voiceSize=0,this.minStretchForce=0,this.totalSpringConstant=0,this.incompleteGraceRods=new Map,this.allGraceRods=new Map,this.springs=new Map,this.height=0}updateVoiceSize(e){e>this.voiceSize&&(this.voiceSize=e,this.version++)}setPreBeatSize(e,t){(!this.preBeatSizes.has(e.id)||this.preBeatSizes.get(e.id)<t)&&(this.preBeatSizes.set(e.id,t),this.version++)}getPreBeatSize(e){return this.preBeatSizes.has(e.id)?this.preBeatSizes.get(e.id):0}setOnBeatSize(e,t){(!this.onBeatSizes.has(e.id)||this.onBeatSizes.get(e.id)<t)&&(this.onBeatSizes.set(e.id,t),this.version++)}getOnBeatSize(e){return this.onBeatSizes.has(e.id)?this.onBeatSizes.get(e.id):0}getBeatCenterX(e){return this.onBeatCenterX.has(e.id)?this.onBeatCenterX.get(e.id):0}setBeatCenterX(e,t){(!this.onBeatCenterX.has(e.id)||this.onBeatCenterX.get(e.id)<t)&&(this.onBeatCenterX.set(e.id,t),this.version++)}updateMinStretchForce(e){this.minStretchForce<e&&(this.minStretchForce=e)}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 Ra,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!==g.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 Ra;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 s=0;if(this.incompleteGraceRods.has(e))for(const e of t)s+=e.preBeatWidth,e.graceBeatWidth=s,s+=e.postSpringWidth;else for(let e=t.length-1;e>=0;e--)t[e].graceBeatWidth=s,s-=t[e].preBeatWidth+t[e].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=W.toTicks(u.SixtyFourth)),0===e.smallestDuration&&(e.smallestDuration=t),e.smallestDuration/t*(1/((1+.85*Math.log2(t/Oa.MinDuration))*Oa.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(j.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}}Oa.MinDuration=30,Oa.MinDurationWidth=7;class Ga{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.renderers=[]}}class Va{constructor(e,t){this.staves=[],this.stavesRelevantForBoundsLookup=[],this.firstStaffInAccolade=null,this.lastStaffInAccolade=null,this.staveGroup=e,this.track=t}addStaff(e){this.staves.push(e),e.isRelevantForBoundsLookup&&this.stavesRelevantForBoundsLookup.push(e)}}class Ha{constructor(){this._allStaves=[],this._firstStaffInAccolade=null,this._lastStaffInAccolade=null,this._accoladeSpacingCalculated=!1,this.x=0,this.y=0,this.index=0,this.accoladeSpacing=0,this.isFull=!1,this.width=0,this.computedWidth=0,this.totalBarDisplayScale=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[]}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),this.calculateAccoladeSpacing(e),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.updateWidthFromLastBar(),t}addBars(e,t){if(0===e.length)return null;let s=new Ga;s.layoutingInfo=new Oa,s.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(s),this.calculateAccoladeSpacing(e);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 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(e){if(!this._accoladeSpacingCalculated&&0===this.index)if(this._accoladeSpacingCalculated=!0,this.layout.renderer.settings.notation.isNotationElementVisible(k.TrackNames)){let t=this.layout.renderer.canvas,s=this.layout.renderer.settings.display.resources.effectFont;t.font=s;for(let s of e)this.accoladeSpacing=Math.ceil(Math.max(this.accoladeSpacing,t.measureText(s.shortName)));this.accoladeSpacing*=this.layout.scale,this.accoladeSpacing+=2*Ha.AccoladeLabelSpacing*this.layout.scale,this.width+=this.accoladeSpacing,this.computedWidth+=this.accoladeSpacing}else this.accoladeSpacing=0}getStaveTrackGroup(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.getStaveTrackGroup(e);s||(s=new Va(this,e),this.staves.push(s)),t.staveTrackGroup=s,t.staveGroup=this,t.index=this._allStaves.length,this._allStaves.push(t),s.addStaff(t),t.isInAccolade&&(this._firstStaffInAccolade||(this._firstStaffInAccolade=t,t.isFirstInAccolade=!0),s.firstStaffInAccolade||(s.firstStaffInAccolade=t),this._lastStaffInAccolade||(this._lastStaffInAccolade=t,t.isLastInAccolade=!0),this._lastStaffInAccolade&&(this._lastStaffInAccolade.isLastInAccolade=!1),this._lastStaffInAccolade=t,this._lastStaffInAccolade.isLastInAccolade=!0,s.lastStaffInAccolade=t)}get height(){return this._allStaves[this._allStaves.length-1].y+this._allStaves[this._allStaves.length-1].height}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){this.paintPartial(e+this.x,t+this.y,s,0,this.masterBarsRenderers.length)}paintPartial(e,t,s,i,a){for(let r=0,n=this._allStaves.length;r<n;r++)this._allStaves[r].paint(e,t,s,i,a);let r=this.layout.renderer.settings.display.resources;if(this.staves.length>0&&0===i){if(s.color=r.barSeparatorColor,this._firstStaffInAccolade&&this._lastStaffInAccolade){let i=t+this._firstStaffInAccolade.y+this._firstStaffInAccolade.staveTop+this._firstStaffInAccolade.topSpacing+this._firstStaffInAccolade.topOverflow,a=t+this._lastStaffInAccolade.y+this._lastStaffInAccolade.topSpacing+this._lastStaffInAccolade.topOverflow+this._lastStaffInAccolade.staveBottom,r=e+this._firstStaffInAccolade.x;s.beginPath(),s.moveTo(r,i),s.lineTo(r,a),s.stroke()}s.font=r.effectFont;for(let i=0,a=this.staves.length;i<a;i++){let a=this.staves[i];if(a.firstStaffInAccolade&&a.lastStaffInAccolade){let i=t+a.firstStaffInAccolade.y+a.firstStaffInAccolade.staveTop+a.firstStaffInAccolade.topSpacing+a.firstStaffInAccolade.topOverflow,r=t+a.lastStaffInAccolade.y+a.lastStaffInAccolade.topSpacing+a.lastStaffInAccolade.topOverflow+a.lastStaffInAccolade.staveBottom,n=e+a.firstStaffInAccolade.x,o=3*this.layout.renderer.settings.display.scale,h=o,l=i-4*o,c=r+4*o;0===this.index&&this.layout.renderer.settings.notation.isNotationElementVisible(k.TrackNames)&&s.fillText(a.track.shortName,e+Ha.AccoladeLabelSpacing*this.layout.scale,i),s.fillRect(n-h-o,l,o,c-l);let d=n-h-o,u=n+2*o;s.beginPath(),s.moveTo(d,l),s.bezierCurveTo(d,l,d,l,u,l-o),s.bezierCurveTo(n,l+o,d,l+o,d,l+o),s.closePath(),s.fill(),s.beginPath(),s.moveTo(d,c),s.bezierCurveTo(d,c,n,c,u,c+o),s.bezierCurveTo(n,c-o,d,c-o,d,c-o),s.closePath(),s.fill()}}}}finalizeGroup(){let e=0;for(let t of this._allStaves)t.x=this.accoladeSpacing,t.y=e,t.finalizeStaff(),e+=t.height}buildBoundingsLookup(e,t){if(this.layout.renderer.boundsLookup.isFinished)return;if(!this._firstStaffInAccolade||!this._lastStaffInAccolade)return;let s=this._allStaves[this._allStaves.length-1],i=t+this.y+this._firstStaffInAccolade.y,a=t+this.y+this._lastStaffInAccolade.y+this._lastStaffInAccolade.height,r=t+this.y+this._allStaves[0].y,n=t+this.y+s.y+s.height,o=t+this.y+this._firstStaffInAccolade.y+this._firstStaffInAccolade.topSpacing+this._firstStaffInAccolade.topOverflow+(this._firstStaffInAccolade.barRenderers.length>0?this._firstStaffInAccolade.barRenderers[0].topPadding:0),h=a-i,l=t+this.y+s.y+s.height-s.bottomSpacing-s.bottomOverflow-(s.barRenderers.length>0?s.barRenderers[0].bottomPadding:0)-o,c=n-r,d=this.x+this._firstStaffInAccolade.x,u=new vi;u.visualBounds=new rt,u.visualBounds.x=e,u.visualBounds.y=t+this.y,u.visualBounds.w=this.width,u.visualBounds.h=this.height,u.realBounds=new rt,u.realBounds.x=e,u.realBounds.y=t+this.y,u.realBounds.w=this.width,u.realBounds.h=this.height,this.layout.renderer.boundsLookup.addStaveGroup(u);let p=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 a;p.has(e.bar.masterBar.index)?a=p.get(e.bar.masterBar.index):(a=new Ti,a.index=e.bar.masterBar.index,a.isFirstOfLine=e.isFirstOfLine,a.realBounds=new rt,a.realBounds.x=d+e.x,a.realBounds.y=r,a.realBounds.w=e.width,a.realBounds.h=c,a.visualBounds=new rt,a.visualBounds.x=d+e.x,a.visualBounds.y=i,a.visualBounds.w=e.width,a.visualBounds.h=h,a.lineAlignedBounds=new rt,a.lineAlignedBounds.x=d+e.x,a.lineAlignedBounds.y=o,a.lineAlignedBounds.w=e.width,a.lineAlignedBounds.h=l,this.layout.renderer.boundsLookup.addMasterBar(a),p.set(a.index,a)),e.buildBoundingsLookup(a,d,t+this.y+s.y)}}getBarX(e){if(!this._firstStaffInAccolade||0===this.layout.renderer.tracks.length)return 0;let t=this.layout.renderer.tracks[0].staves[0].bars[e];return this.layout.getRendererForBar(this._firstStaffInAccolade.staveId,t).x}}Ha.AccoladeLabelSpacing=10;class Wa extends Sa{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()}}createGlyphs(e){const t=this.renderer.scale,s=this.renderer.resources;this.height=0;const i=15*t;this._trackLabel.length>0&&(this.addGlyph(new Da(0,this.height,this._trackLabel,s.effectFont,P.Left)),this.height+=i),this.addGlyph(new Da(0,this.height,e.name,s.effectFont,P.Left));const a=64*t;if(this.renderer.scoreRenderer.canvas.font=s.effectFont,this.width=Math.max(this.renderer.scoreRenderer.canvas.measureText(this._trackLabel)*t,Math.max(this.renderer.scoreRenderer.canvas.measureText(e.name)*t,2*a)),this.height+=i,!e.isStandard){const r=.7,n=Wa.CircleNumberHeight*r*t;let o=0|Math.ceil(e.tunings.length/2),h=0,l=this.height;for(let c=0,d=e.tunings.length;c<d;c++){const d=N.GuitarString0+(c+1);this.addGlyph(new Ui(h,l+n/1.2,r,d));const u="= "+ye.getTextForTuning(e.tunings[c],!1);this.addGlyph(new Da(h+n+1*t,l,u,s.effectFont,P.Left)),l+=i,c===o-1&&(l=this.height,h+=a)}this.height+=o*i}this.width+=15*t}}Wa.CircleNumberHeight=20;class za extends Ma{constructor(e,t){super(e,t,P.Left)}addTuning(e,t){if(e.tunings.length>0){let s=new Wa(0,0,e,t);s.renderer=this.renderer,s.doLayout(),this.glyphs.push(s)}}}class Ua{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"}(Je||(Je={}));class Xa{constructor(e){this._barRendererLookup=new Map,this.width=0,this.height=0,this.scoreInfoGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this.systemsLayoutMode=Je.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){this.renderer.settings.core.enableLazyLoading?(this._lazyPartials.set(e.id,new Ua(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(){q.debug("ScoreLayout","Creating score info glyphs");let e=this.renderer.settings.notation,t=this.renderer.score,s=this.renderer.settings.display.resources;this.scoreInfoGlyphs=new Map,t.title&&e.isNotationElementVisible(k.ScoreTitle)&&this.scoreInfoGlyphs.set(k.ScoreTitle,new Da(0,0,t.title,s.titleFont,P.Center)),t.subTitle&&e.isNotationElementVisible(k.ScoreSubTitle)&&this.scoreInfoGlyphs.set(k.ScoreSubTitle,new Da(0,0,t.subTitle,s.subTitleFont,P.Center)),t.artist&&e.isNotationElementVisible(k.ScoreArtist)&&this.scoreInfoGlyphs.set(k.ScoreArtist,new Da(0,0,t.artist,s.subTitleFont,P.Center)),t.album&&e.isNotationElementVisible(k.ScoreAlbum)&&this.scoreInfoGlyphs.set(k.ScoreAlbum,new Da(0,0,t.album,s.subTitleFont,P.Center)),t.music&&t.music===t.words&&e.isNotationElementVisible(k.ScoreWordsAndMusic)?this.scoreInfoGlyphs.set(k.ScoreWordsAndMusic,new Da(0,0,"Music and Words by "+t.words,s.wordsFont,P.Center)):(t.music&&e.isNotationElementVisible(k.ScoreMusic)&&this.scoreInfoGlyphs.set(k.ScoreMusic,new Da(0,0,"Music by "+t.music,s.wordsFont,P.Right)),t.words&&e.isNotationElementVisible(k.ScoreWords)&&this.scoreInfoGlyphs.set(k.ScoreWords,new Da(0,0,"Words by "+t.words,s.wordsFont,P.Left)));const i=new Ya(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);if(e.isNotationElementVisible(k.GuitarTuning)){let e=[];for(let t of this.renderer.tracks)for(let s of t.staves)if(!s.isPercussion&&s.isStringed&&s.tuning.length>0&&s.showTablature){e.push(s);break}if(e.length>0){this.tuningGlyph=new za(0,0),this.tuningGlyph.renderer=i;for(const t of e)this.tuningGlyph.addTuning(t.stringTuning,e.length>1?t.track.name:"")}}if(e.isNotationElementVisible(k.ChordDiagrams)){this.chordDiagrams=new Ia(0,0),this.chordDiagrams.renderer=i;let e=new Set;for(let t of this.renderer.tracks)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))}}}get scale(){return this.renderer.settings.display.scale}createEmptyStaveGroup(){let e=new Ha;e.layout=this;for(let s=0;s<this.renderer.tracks.length;s++){let i=this.renderer.tracks[s],a=!1;for(let e of i.staves)if(e.showStandardNotation){a=!0;break}for(let r=0;r<i.staves.length;r++){let n,o=i.staves[r];if(o.isPercussion)n=t.Score;else if(this.renderer.settings.display.staveProfile!==t.Default)n=this.renderer.settings.display.staveProfile;else if(o.showTablature&&o.showStandardNotation)n=t.ScoreTab;else if(o.showTablature)n=a?t.TabMixed:t.Tab;else{if(!o.showStandardNotation)continue;n=t.Score}let h=Po.staveProfiles.get(n);for(let t of h)t.canCreate(i,o)&&e.addStaff(i,new Aa(s,o,t))}}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=12*this.renderer.settings.display.scale,a=Math.floor(2*i);const r=new _i,n=As.withFamilyList(s.copyrightFont.families,i,Ge.Plain,Ve.Bold);this.renderer.canvas.font=n;const o=Po.getLayoutEngineFactory(this.renderer.settings.display.layoutMode).vertical;return r.width=this.renderer.canvas.measureText(t),r.height=a,r.x=o?(this.width-r.width)/2:this.firstBarX,r.y=e,r.totalWidth=this.width,r.totalHeight=e+a,r.firstMasterBarIndex=-1,r.lastMasterBarIndex=-1,this.registerPartial(r,(e=>{e.color=s.mainGlyphColor,e.font=n,e.textAlign=P.Left,e.fillText(t,0,i)})),e+a}}!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"}(je||(je={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Qe||(Qe={}));class Ya{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 _a,this._voiceContainers=new Map,this._postBeatGlyphs=new _a,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 Ea(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 scale(){return this.settings.display.scale}get barDisplayScale(){return this.staff.staveGroup.staves.length>1?this.bar.masterBar.displayScale:this.bar.displayScale}get barDisplayWidth(){return this.staff.staveGroup.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==Je.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 _a,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new _a,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 wa(0,0,t);s.renderer=this,this._voiceContainers.set(this.bar.voices[e].index,s)}}this.bar.simileMark===o.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*this.scale}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 wi;i.bar=this.bar,i.visualBounds=new rt,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 rt,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(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];this.hasVoiceContainer(t)&&this.createVoiceGlyphs(this.bar.voices[e])}}createVoiceGlyphs(e){}createPostBeatGlyphs(){}get beatGlyphsStart(){return this._preBeatGlyphs.x+this._preBeatGlyphs.width}get postBeatGlyphsStart(){return this._postBeatGlyphs.x}getBeatX(e,t=Ye.PreNotes){let s=this.getBeatContainer(e);if(s)switch(t){case Ye.PreNotes:return s.voiceContainer.x+s.x;case Ye.OnNotes:return s.voiceContainer.x+s.x+s.onNotes.x;case Ye.MiddleNotes:return s.voiceContainer.x+s.x+s.onTimeX;case Ye.Stem:const t=s.onNotes.beamingHelper?s.onNotes.beamingHelper.getBeatLineX(e):s.onNotes.x+s.onNotes.width/2;return s.voiceContainer.x+t;case Ye.PostNotes:return s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.width;case Ye.EndBeat:return s.voiceContainer.x+s.x+s.width}return 0}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._preBeatGlyphs=new _a,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()),this.updateSizes(),this.registerLayoutingInfo()}paintSimileMark(e,t,s){switch(this.bar.simileMark){case o.Simple:s.fillMusicFontSymbol(e+this.x+(this.width-20*this.scale)/2,t+this.y+this.height/2,1,N.Repeat1Bar,!1);break;case o.SecondOfDouble:s.fillMusicFontSymbol(e+this.x-28*this.scale/2,t+this.y+this.height/2,1,N.Repeat2Bars,!1)}}completeBeamingHelper(e){}}Ya.LineSpacing=8,Ya.StemWidth=.12*Ya.LineSpacing,Ya.StaffLineThickness=.13*Ya.LineSpacing,Ya.BeamThickness=.5*Ya.LineSpacing,Ya.BeamSpacing=.25*Ya.LineSpacing,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"}($e||($e={}));class qa extends Wi{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.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 $e.SingleOnBeatToEnd:case $e.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)}}createOrResizeGlyph(e,t){let s;switch(e){case $e.FullBar:case $e.SinglePreBeat:case $e.SingleOnBeat:case $e.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 $e.GroupedOnBeat:case $e.GroupedOnBeatToEnd:let i=e===$e.GroupedOnBeat?$e.SingleOnBeat:$e.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($e.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,i=this._effectGlyphs[t.voice.index].get(t.index),a=this.renderer.getBeatContainer(t);switch(e){case $e.SinglePreBeat:s=a.preNotes,i.x=this.renderer.beatGlyphsStart+s.x+a.x,i.width=s.width;break;case $e.SingleOnBeat:case $e.GroupedOnBeat:s=a.onNotes,i.x=this.renderer.beatGlyphsStart+s.x+a.x,i.width=s.width;break;case $e.SingleOnBeatToEnd:case $e.GroupedOnBeatToEnd:s=a.onNotes,i.x=this.renderer.beatGlyphsStart+s.x+a.x,a.beat.isLastOfVoice?i.width=this.renderer.width-i.x:i.width=a.width-a.preNotes.width-a.preNotes.x;break;case $e.FullBar:i.width=this.renderer.width}}}class Ja{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class ja{constructor(){this.bands=[],this.shared=new Ja}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 Qa{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 ja;return this.slots.push(t),t}register(e){let t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class $a extends Sa{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 Ka extends $a{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,s){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class Za extends Ya{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(){if(!super.applyLayoutingInfo())return!1;if(this.index>0){let e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new Qa;for(let e of this._bands)e.alignGlyphs(),e.isEmpty||this.sizingInfo.register(e);return this.updateHeight(),!0}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 qa(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 qi(t,this.getVoiceContainer(e));s.preNotes=new $a,s.onNotes=new Ka,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 er extends ba{get staffId(){return this._staffId}constructor(e,t){super(),this._infos=t,this._staffId=e,this.isInAccolade=!1,this.isRelevantForBoundsLookup=!1}create(e,t){return new Za(e,t,this._infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class tr extends zi{constructor(e,t,s){super(e,t),this._endingsString="",this._endings=[];for(let e=0;e<le.MaxAlternateEndings;e++)s&1<<e&&this._endings.push(e)}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(tr.Padding*this.scale+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=C.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+tr.Padding*this.scale,t+this.y*this.scale)}s.textBaseline=i}}tr.Padding=3;class sr{get effectId(){return this.notationElement.toString()}}class ir extends sr{get notationElement(){return k.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return $e.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){return new tr(0,0,t.voice.bar.masterBar.alternateEndings)}canExpand(e,t){return!0}}class ar extends sr{get notationElement(){return k.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Da(0,0,"Capo. fret "+t.voice.bar.staff.capo,e.resources.effectFont,P.Left)}canExpand(e,t){return!1}}class rr extends sr{get notationElement(){return k.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Da(0,0,t.chord.name,e.resources.effectFont,P.Center)}canExpand(e,t){return!1}}class nr extends zi{constructor(e){super(),this.forceGroupedRendering=!1,this.endOnBarLine=!1,this.endPosition=e}get isLinkedWithPrevious(){return!!this.previousGlyph&&this.previousGlyph.renderer.staff.staveGroup===this.renderer.staff.staveGroup}get isLinkedWithNext(){return!!this.nextGlyph&&this.nextGlyph.renderer.isFinalized&&this.nextGlyph.renderer.staff.staveGroup===this.renderer.staff.staveGroup}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 or extends nr{constructor(e,t,s){super(Ye.EndBeat),this._crescendo=d.None,this._crescendo=s,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17*this.scale}paintGrouped(e,t,s,i){let a=e+this.x,r=this.height*this.scale;i.beginPath(),this._crescendo===d.Crescendo?(s-=or.Padding*this.scale,i.moveTo(s,t+this.y),i.lineTo(a,t+this.y+r/2),i.lineTo(s,t+this.y+r)):(s-=or.Padding*this.scale,i.moveTo(a,t+this.y),i.lineTo(s,t+this.y+r/2),i.lineTo(a,t+this.y+r)),i.stroke()}}or.Padding=Xi.QuarterNoteHeadWidth/2|0;class hr extends sr{get notationElement(){return k.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==d.None}createNewGlyph(e,t){return new or(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class lr extends Ui{constructor(e,t,s){super(e,t,.6,lr.getSymbol(s))}doLayout(){super.doLayout(),this.height=17*this.scale,this.y+=this.height/2}static getSymbol(e){switch(e){case p.PPP:return N.DynamicPPP;case p.PP:return N.DynamicPP;case p.P:return N.DynamicPiano;case p.MP:return N.DynamicMP;case p.MF:return N.DynamicMF;case p.F:return N.DynamicForte;case p.FF:return N.DynamicFF;case p.FFF:return N.DynamicFFF;default:return N.None}}}class cr extends sr{get notationElement(){return k.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return $e.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!==g.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===g.None)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new lr(0,0,t.dynamics)}canExpand(e,t){return!0}}class dr extends zi{doLayout(){super.doLayout(),this.height=17*this.scale}paint(e,t,s){let i=6*this.scale,a=Math.max(this.width,14*this.scale),r=this.height/2;s.beginPath(),s.moveTo(e+this.x,t+this.y+r),s.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r-i),s.moveTo(e+this.x,t+this.y+r),s.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r+i),s.stroke()}}class ur extends sr{get notationElement(){return k.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return t.fadeIn}createNewGlyph(e,t){return new dr}canExpand(e,t){return!0}}class pr extends Ui{constructor(e,t,s){super(e,t,1,pr.getSymbol(s))}static getSymbol(e){switch(e){case xe.Short:return N.FermataShortAbove;case xe.Medium:return N.FermataAbove;case xe.Long:return N.FermataLongAbove;default:return N.None}}doLayout(){this.width=23*this.scale,this.height=12*this.scale}paint(e,t,s){super.paint(e-this.width/2,t+this.height,s)}}class gr extends sr{get notationElement(){return k.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new pr(0,0,t.fermata.type)}canExpand(e,t){return!0}}class fr extends sr{get notationElement(){return k.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return!(0!==t.voice.index||t.isRest||e.notation.fingeringMode!==B.SingleNoteEffectBand&&e.notation.fingeringMode!==B.SingleNoteEffectBandForcePiano)&&(1===t.notes.length&&t.notes[0].isFingering)}createNewGlyph(e,t){let s=f.Unknown,i=!1,a=t.notes[0];a.leftHandFinger!==f.Unknown?(s=a.leftHandFinger,i=!0):a.rightHandFinger!==f.Unknown&&(s=a.rightHandFinger);let r=j.fingerToString(e.settings,t,s,i)??"";return new Da(0,0,r,e.resources.fingeringFont,P.Left)}canExpand(e,t){return!0}}class mr extends sr{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 yr extends nr{constructor(e){super(Ye.OnNotes),this._label=e}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=Ye.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=P.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=3*this.scale,r=i.measureText(this._label),n=e+this.x+r/2+a,o=t+this.y+4*this.scale,h=8*this.scale;if(s>n){let e=n;for(;e<s;)i.beginPath(),i.moveTo(e,0|o),i.lineTo(Math.min(e+h,s),0|o),e+=h+a,i.stroke();i.beginPath(),i.moveTo(s,o-5*this.scale|0),i.lineTo(s,o+5*this.scale|0),i.stroke()}}}yr.LineSpacing=3,yr.LineTopPadding=4,yr.LineTopOffset=5,yr.LineSize=8;class br extends mr{get effectId(){return this._effectId}get notationElement(){return k.EffectHarmonics}constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case m.None:this._effectId="harmonics-none";break;case m.Natural:this._effectId="harmonics-natural";break;case m.Artificial:this._effectId="harmonics-artificial";break;case m.Pinch:this._effectId="harmonics-pinch";break;case m.Tap:this._effectId="harmonics-tap";break;case m.Semi:this._effectId="harmonics-semi";break;case m.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 $e.GroupedOnBeat}createNewGlyph(e,t){return new yr(br.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case m.Natural:return"N.H.";case m.Artificial:return"A.H.";case m.Pinch:return"P.H.";case m.Tap:return"T.H.";case m.Semi:return"S.H.";case m.Feedback:return"Fdbk."}return""}}class Sr extends sr{get notationElement(){return k.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return $e.GroupedOnBeat}createNewGlyph(e,t){return new yr("LetRing")}canExpand(e,t){return!0}}class _r extends zi{constructor(e,t,s,i,a=P.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 wr extends sr{get notationElement(){return k.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new _r(0,0,t.lyrics,e.resources.effectFont,P.Center)}canExpand(e,t){return!0}}class Br extends sr{get notationElement(){return k.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return $e.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 Da(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,P.Left)}canExpand(e,t){return!0}}class Tr extends nr{constructor(e,t){super(Ye.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=13*this.scale}paintNonGrouped(e,t,s){this.paintOttava(e,t,s)}paintOttava(e,t,s){let i=0;switch(this._ottava){case n._15ma:i=37*this.scale,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,N.QuindicesimaAlta,!1);break;case n._8va:i=26*this.scale,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,N.OttavaAlta,!1);break;case n._8vb:i=23*this.scale,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,N.OttavaBassaVb,!1);break;case n._15mb:i=36*this.scale,s.fillMusicFontSymbols(e+this.x-i/2,t+this.y+this.height,.8,[N.Quindicesima,N.OctaveBaselineM,N.OctaveBaselineB],!1)}return i/2}paintGrouped(e,t,s,i){let a=this.paintOttava(e,t,i),r=3*this.scale,n=e+this.x+a+r,o=t+this.y;o+=this._aboveStaff?2*this.scale:this.height-2*this.scale;let h=8*this.scale;if(s>n){let e=n;for(;e<s;)i.beginPath(),i.moveTo(e,0|o),i.lineTo(Math.min(e+h,s),0|o),e+=h+r,i.stroke();i.beginPath(),this._aboveStaff?(i.moveTo(s,o),i.lineTo(s,t+this.y+this.height)):(i.moveTo(s,o),i.lineTo(s,t+this.y)),i.stroke()}}}class kr extends sr{get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return k.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.GroupedOnBeat}constructor(e){super(),this._aboveStaff=e}shouldCreateGlyph(e,t){switch(t.ottava){case n._15ma:case n._8va:return this._aboveStaff;case n._8vb:case n._15mb:return!this._aboveStaff}return!1}createNewGlyph(e,t){return new Tr(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class vr extends mr{get notationElement(){return k.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return $e.GroupedOnBeat}createNewGlyph(e,t){return new yr("P.M.")}constructor(){super()}}class xr extends mr{get notationElement(){return k.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===S.PickSlideDown||e.slideOutType===S.PickSlideUp}get sizingMode(){return $e.GroupedOnBeat}createNewGlyph(e,t){return new yr("P.S.")}constructor(){super()}}class Nr extends Ui{constructor(e,t,s){super(e,t,Xi.GraceScale,Nr.getSymbol(s))}doLayout(){this.width=9*this.scale,this.height=13*this.scale}paint(e,t,s){super.paint(e,t+this.height,s)}static getSymbol(e){switch(e){case x.Up:return N.StringsUpBow;case x.Down:return N.StringsDownBow;default:return N.None}}}class Pr extends sr{get notationElement(){return k.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==x.None}createNewGlyph(e,t){return new Nr(0,0,t.pickStroke)}canExpand(e,t){return!0}}class Cr extends nr{constructor(e){super(Ye.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case _.Slight:this._stepSize=12*this.scale;break;case _.Wide:this._stepSize=23*this.scale}this.height=18*this.scale}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 Er extends sr{get notationElement(){return k.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===_.Slight}createNewGlyph(e,t){return new Cr(_.Slight)}canExpand(e,t){return!0}}class Fr extends nr{constructor(e,t,s,i=1.2,a=!1){super(Ye.EndBeat),this._scale=0,this._symbol=N.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 _.Slight:this._symbol=N.WiggleTrill,this._symbolSize=9*this._scale,e=6*this._scale;break;case _.Wide:this._symbol=N.WiggleVibratoMediumFast,this._symbolSize=10*this._scale,e=10*this._scale}this.height=e*this.scale}paintGrouped(e,t,s,i){let a=s-(e+this.x),r=this._symbolSize*this.scale,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.scale,this._symbol,!1),o+=r}}class Lr extends mr{get notationElement(){return k.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===_.Slight||e.isTieDestination&&e.tieOrigin.vibrato===_.Slight}get sizingMode(){return $e.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Fr(0,0,_.Slight,1.2)}constructor(){super()}}class Mr extends sr{get notationElement(){return k.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){let s=e.resources;return t.slap?new Da(0,0,"S",s.effectFont,P.Left):t.pop?new Da(0,0,"P",s.effectFont,P.Left):new Da(0,0,"T",s.effectFont,P.Left)}canExpand(e,t){return!0}}class Ir extends zi{constructor(e,t,s){super(e,t),this._tempo=0,this._tempo=s}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,s){let i=this.renderer.resources;s.font=i.markerFont,s.fillMusicFontSymbol(e+this.x,t+this.y+.8*this.height,this.scale*Xi.GraceScale,N.NoteQuarterUp,!1),s.fillText("= "+this._tempo.toString(),e+this.x+this.height/2,t+this.y+s.font.size/2)}}class Dr extends sr{get notationElement(){return k.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return $e.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&(!!t.voice.bar.masterBar.tempoAutomation||0===t.voice.bar.index)}createNewGlyph(e,t){let s=0;return s=t.voice.bar.masterBar.tempoAutomation?t.voice.bar.masterBar.tempoAutomation.value:t.voice.bar.staff.track.score.tempo,new Ir(0,0,s)}canExpand(e,t){return!0}}class Ar extends sr{get notationElement(){return k.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Da(0,0,t.text,e.resources.effectFont,P.Left)}canExpand(e,t){return!0}}class Rr extends zi{constructor(e,t){super(e,t)}doLayout(){super.doLayout(),this.height=this.renderer.resources.markerFont.size*this.scale}paint(e,t,s){let i=this.renderer.resources;s.font=i.markerFont;let a=s.measureText("tr");s.fillText("tr",e+this.x,t+this.y);let r=a+3*this.scale,n=this.width-r,o=11*this.scale*1.2,h=Math.max(1,(n-r)/o),l=r,c=t+this.y+1.2*this.height;for(let t=0;t<h;t++)s.fillMusicFontSymbol(e+this.x+l,c,1.2,N.WiggleTrill,!1),l+=o}}class Or extends mr{get notationElement(){return k.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return $e.SingleOnBeat}createNewGlyph(e,t){return new Rr(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(Ke||(Ke={}));class Gr extends zi{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,s){e+=this.x;let i=(t+=this.y)+this.height*Xi.GraceScale;s.font=this.renderer.resources.effectFont,s.fillText("(",e,t+.3*this.height);let a=e+10*this.scale,r=e+40*this.scale;switch(this._tripletFeel){case D.NoTripletFeel:this.renderBarNote(a,i,Gr.NoteScale,s,[Ke.Full]),this.renderBarNote(r,i,Gr.NoteScale,s,[Ke.Full]);break;case D.Triplet8th:this.renderBarNote(a,i,Gr.NoteScale,s,[Ke.Full]),s.fillMusicFontSymbol(r,i,Gr.NoteScale,N.NoteQuarterUp,!1),s.fillMusicFontSymbol(r+Gr.NoteSeparation*this.scale,i,Gr.NoteScale,N.NoteEighthUp,!1),this.renderTriplet(r,t,s);break;case D.Triplet16th:this.renderBarNote(a,i,Gr.NoteScale,s,[Ke.Full,Ke.Full]),this.renderBarNote(r,i,Gr.NoteScale,s,[Ke.Full,Ke.PartialRight]),this.renderTriplet(r,t,s);break;case D.Dotted8th:this.renderBarNote(a,i,Gr.NoteScale,s,[Ke.Full]),this.renderBarNote(r,i,Gr.NoteScale,s,[Ke.Full,Ke.PartialRight]),s.fillCircle(r+9*this.scale,i,this.scale);break;case D.Dotted16th:this.renderBarNote(a,i,Gr.NoteScale,s,[Ke.Full,Ke.Full]),this.renderBarNote(r,i,Gr.NoteScale,s,[Ke.Full,Ke.Full,Ke.PartialRight]),s.fillCircle(r+9*this.scale,i,this.scale);break;case D.Scottish8th:this.renderBarNote(a,i,Gr.NoteScale,s,[Ke.Full]),this.renderBarNote(r,i,Gr.NoteScale,s,[Ke.Full,Ke.PartialLeft]),s.fillCircle(r+Gr.NoteSeparation*this.scale+8*this.scale,i,this.scale);break;case D.Scottish16th:this.renderBarNote(a,i,Gr.NoteScale,s,[Ke.Full,Ke.Full]),this.renderBarNote(r,i,Gr.NoteScale,s,[Ke.Full,Ke.Full,Ke.PartialLeft]),s.fillCircle(r+Gr.NoteSeparation*this.scale+8*this.scale,i,this.scale)}s.fillText("=",e+30*this.scale,t+5*this.scale),s.fillText(")",e+65*this.scale,t+.3*this.height)}renderBarNote(e,t,s,i,a){i.fillMusicFontSymbol(e,t,s,N.NoteQuarterUp,!1);let r=Gr.NoteSeparation/2*this.scale;for(let s=0;s<a.length;s++)switch(a[s]){case Ke.Full:i.fillRect(e+4*this.scale,t-Gr.NoteHeight*this.scale+Gr.BarSeparation*this.scale*s,Gr.NoteSeparation*this.scale,Gr.BarHeight*this.scale);break;case Ke.PartialLeft:i.fillRect(e+4*this.scale,t-Gr.NoteHeight*this.scale+Gr.BarSeparation*this.scale*s,r,Gr.BarHeight*this.scale);break;case Ke.PartialRight:i.fillRect(e+4*this.scale+r,t-Gr.NoteHeight*this.scale+Gr.BarSeparation*this.scale*s,r,Gr.BarHeight*this.scale)}i.fillMusicFontSymbol(e+Gr.NoteSeparation*this.scale,t,s,N.NoteQuarterUp,!1)}renderTriplet(e,t,s){t+=2*this.scale;let i=this.renderer.resources.effectFont;s.font=As.withFamilyList(i.families,.8*i.size,i.style);let a=e+Gr.NoteSeparation*this.scale+3*this.scale;s.beginPath(),s.moveTo(e,t+3*this.scale),s.lineTo(e,t),s.lineTo(e+5*this.scale,t),s.moveTo(a+5*this.scale,t+3*this.scale),s.lineTo(a+5*this.scale,t),s.lineTo(a,t),s.stroke(),s.fillText("3",e+7*this.scale,t-10*this.scale),s.font=i}}Gr.NoteScale=.4,Gr.NoteHeight=12,Gr.NoteSeparation=12,Gr.BarHeight=2,Gr.BarSeparation=3;class Vr extends sr{get notationElement(){return k.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return $e.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==D.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new Gr(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class Hr extends sr{get notationElement(){return k.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return $e.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new yr("w/bar")}canExpand(e,t){return!0}}class Wr extends sr{get notationElement(){return k.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===_.Wide}createNewGlyph(e,t){return new Cr(_.Wide)}canExpand(e,t){return!0}}class zr extends mr{get notationElement(){return k.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===_.Wide||e.isTieDestination&&e.tieOrigin.vibrato===_.Wide}get sizingMode(){return $e.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Fr(0,0,_.Wide,1.2)}}class Ur{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class Xr extends Xa{get name(){return"HorizontalScreen"}constructor(e){super(e),this._group=null,this._pagePadding=null}get supportsResize(){return!1}get firstBarX(){let e=this._pagePadding[0];return this._group&&(e+=this._group.accoladeSpacing),e}doResize(){}doLayoutAndRender(){switch(this._pagePadding=this.renderer.settings.display.padding,this.renderer.settings.display.systemsLayoutMode){case He.Automatic:this.systemsLayoutMode=Je.Automatic;break;case He.UseModelLayout:this.systemsLayoutMode=Je.FromModelWithWidths}this._pagePadding||(this._pagePadding=Xr.PagePadding),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 e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t));let s=t,i=this.renderer.settings.display.barCount;i<=0&&(i=e.masterBars.length),i=t+i-1,i=Math.min(e.masterBars.length-1,Math.max(0,i)),this._group=this.createEmptyStaveGroup(),this._group.isLast=!0,this._group.x=this._pagePadding[0],this._group.y=this._pagePadding[1];let a=this.renderer.settings.display.barCountPerPartial,r=[],n=new Ur,o=0;for(;s<=i;){let t=this._group.addBars(this.renderer.tracks,s);if(t)if(0===n.masterBars.length&&t.isLinkedToPrevious&&r.length>0){let i=r[r.length-1];i.masterBars.push(e.masterBars[s]),i.width+=t.width,o+=t.width,n.x+=o}else n.masterBars.push(e.masterBars[s]),n.width+=t.width,n.masterBars.length>=a&&(0===r.length&&(n.width+=this._group.accoladeSpacing+this._pagePadding[0]),o+=n.width,r.push(n),q.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null),n=new Ur,n.x=o);s++}n.masterBars.length>0&&(0===r.length&&(n.width+=this._group.accoladeSpacing+this._pagePadding[0]),r.push(n),q.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null)),this.finalizeGroup(),this.height=Math.floor(this._group.y+this._group.height),this.width=this._group.x+this._group.width+this._pagePadding[2],s=0;let h=0;for(let e=0;e<r.length;e++){const t=r[e],i=new _i;i.x=h,i.y=0,i.totalWidth=this.width,i.totalHeight=this.height,i.width=t.width,i.height=this.height,i.firstMasterBarIndex=t.masterBars[0].index,i.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,h+=t.width;const a=s,n=e;this._group.buildBoundingsLookup(this._group.x,this._group.y),this.registerPartial(i,(e=>{let s=this._group.getBarX(t.masterBars[0].index)+this._group.accoladeSpacing;0===n&&(s-=this._group.x+this._group.accoladeSpacing),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=P.Left,q.debug(this.name,"Rendering partial from bar "+t.masterBars[0].index+" to "+t.masterBars[t.masterBars.length-1].index,null),this._group.paintPartial(-s,this._group.y,e,a,t.masterBars.length)})),s+=t.masterBars.length}this.height=this.layoutAndRenderAnnotation(this.height)+this._pagePadding[3]}finalizeGroup(){this._group.scaleToWidth(this._group.width),this._group.finalizeGroup()}}Xr.PagePadding=[20,20,20,20],Xr.GroupSpacing=20;class Yr extends Xa{get name(){return"PageView"}constructor(e){super(e),this._groups=[],this._allMasterBarRenderers=[],this._barsFromPreviousGroup=[],this._pagePadding=null}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case He.Automatic:this.systemsLayoutMode=Je.Automatic;break;case He.UseModelLayout:this.systemsLayoutMode=Je.FromModelWithScale}this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=Yr.PagePadding),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 e=0;this.width=this.renderer.width,this._allMasterBarRenderers=[],e=this.layoutAndRenderScoreInfo(e,-1),e=this.layoutAndRenderTunings(e,-1),e=this.layoutAndRenderChordDiagrams(e,-1),e=this.layoutAndRenderScore(e),e=this.layoutAndRenderAnnotation(e),this.height=e+this._pagePadding[3]}get supportsResize(){return!0}get firstBarX(){let e=this._pagePadding[0];return this._groups.length>0&&(e+=this._groups[0].accoladeSpacing),e}doResize(){let e=0;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]}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.width,this.tuningGlyph.doLayout();let i=this.tuningGlyph.height+11*this.scale;const a=new _i;return a.x=0,a.y=e,a.width=this.width,a.height=i,a.totalWidth=this.width,a.totalHeight=t<0?e+a.height:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=P.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.width,this.chordDiagrams.doLayout();const i=Math.floor(this.chordDiagrams.height),a=new _i;return a.x=0,a.y=e,a.width=this.width,a.height=i,a.totalWidth=this.width,a.totalHeight=t<0?e+i:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=P.Center,this.chordDiagrams.paint(0,0,e)})),e+i}layoutAndRenderScoreInfo(e,t=-1){q.debug(this.name,"Layouting score info");const s=new _i;s.x=0,s.y=e;let i=this._pagePadding[1],a=this.scale,r=this.renderer.settings.display.resources,n=[k.ScoreTitle,k.ScoreSubTitle,k.ScoreArtist,k.ScoreAlbum,k.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.width/2,t.y=i,t.textAlign=P.Center,i+=t.font.size*a}let o=!1,h=0;if(this.scoreInfoGlyphs.has(k.ScoreMusic)){let e=this.scoreInfoGlyphs.get(k.ScoreMusic);e.x=this.width-this._pagePadding[2],e.y=i,e.textAlign=P.Right,o=!0,h=e.font.size*a}if(this.scoreInfoGlyphs.has(k.ScoreWords)){let e=this.scoreInfoGlyphs.get(k.ScoreWords);e.x=this._pagePadding[0],e.y=i,e.textAlign=P.Left,o=!0,h=e.font.size*a}return o&&(i+=h),i=Math.floor(i+17*this.scale),s.width=this.width,s.height=i,s.totalWidth=this.width,s.totalHeight=t<0?e+s.height:t,this.registerPartial(s,(e=>{e.color=r.scoreInfoColor,e.textAlign=P.Center;for(const t of this.scoreInfoGlyphs.values())t.paint(0,0,e)})),e+i}resizeAndRenderScore(e,t){if(this.renderer.settings.display.barsPerRow>0||this.systemsLayoutMode==Je.FromModelWithScale)for(let s=0;s<this._groups.length;s++){let i=this._groups[s];this.fitGroup(i),e+=this.paintGroup(i,t)}else{this._groups=[];let s=0,i=this.maxWidth,a=this.createEmptyStaveGroup();for(a.index=this._groups.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._groups.push(a),this.fitGroup(a),e+=this.paintGroup(a,t),a=this.createEmptyStaveGroup(),a.index=this._groups.length,a.x=this._pagePadding[0],a.y=e}}a.isLast=this.lastBarIndex===a.lastBarIndex,this.fitGroup(a),e+=this.paintGroup(a,t)}return e}layoutAndRenderScore(e){let t=this.firstBarIndex,s=this.lastBarIndex;for(this._groups=[];t<=s;){let i=this.createStaveGroup(t,s);this._groups.push(i),i.x=this._pagePadding[0],i.y=e,t=i.lastBarIndex+1,this.fitGroup(i),q.debug(this.name,"Rendering partial from bar "+i.firstBarIndex+" to "+i.lastBarIndex,null),e+=this.paintGroup(i,e)}return e}paintGroup(e,t){let s=Math.floor(e.height+20*this.scale);const i=new _i;return i.x=0,i.y=e.y,i.totalWidth=this.width,i.totalHeight=t,i.width=this.width,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=P.Left,e.paint(0,-i.y,t)})),t+=s,s}fitGroup(e){e.isFull||e.width>this.maxWidth||this.renderer.settings.display.justifyLastSystem?e.scaleToWidth(this.maxWidth):e.scaleToWidth(e.width),e.finalizeGroup()}getBarsPerRow(e){let t=this.renderer.settings.display.barsPerRow;if(this.systemsLayoutMode==Je.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}createStaveGroup(e,t){let s=this.createEmptyStaveGroup();s.index=this._groups.length;let i=this.getBarsPerRow(s.index),a=this.maxWidth,r=t+1,n=e;for(;n<r;){if(this._barsFromPreviousGroup.length>0)for(let e of this._barsFromPreviousGroup)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._barsFromPreviousGroup=[];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._barsFromPreviousGroup.push(e);e&&!e.canWrap&&s.masterBarsRenderers.length>1;)e=s.revertLastBar(),e&&this._barsFromPreviousGroup.push(e);return s.isFull=!0,s.isLast=!1,this._barsFromPreviousGroup.reverse(),s}s.x=0,n++}return s.isLast=t===s.lastBarIndex,s}get maxWidth(){return this.renderer.width-this._pagePadding[0]-this._pagePadding[2]}}Yr.PagePadding=[40,40,40,40],Yr.GroupSpacing=20;class qr extends Ui{constructor(e,t,s,i=!1){super(e,t,i?Xi.GraceScale:1,qr.getMusicSymbol(s)),this._isGrace=i,this._accidentalType=s}static getMusicSymbol(e){switch(e){case qe.Natural:return N.AccidentalNatural;case qe.Sharp:return N.AccidentalSharp;case qe.Flat:return N.AccidentalFlat;case qe.NaturalQuarterNoteUp:return N.AccidentalQuarterToneNaturalArrowUp;case qe.SharpQuarterNoteUp:return N.AccidentalQuarterToneSharpArrowUp;case qe.FlatQuarterNoteUp:return N.AccidentalQuarterToneFlatArrowUp;case qe.DoubleSharp:return N.AccidentalDoubleSharp;case qe.DoubleFlat:return N.AccidentalDoubleFlat}return N.None}doLayout(){if(this._accidentalType===qe.DoubleFlat)this.width=18;else this.width=8;this.width=this.width*(this._isGrace?Xi.GraceScale:1)*this.scale}}class Jr extends Wi{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())+5*this.scale}paint(e,t,s){if(!this.renderer.staff.isFirstInAccolade)return;let i=this.renderer.resources,a=s.color;s.color=i.barNumberColor,s.font=i.barNumberFont,s.fillText(this._number.toString(),e+this.x,t+this.y),s.color=a}}class jr extends Wi{constructor(e,t){super(e,t)}doLayout(){this.renderer.isLast?this.width=15*this.scale:this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart?this.width=2*this.scale:(this.width=2*this.scale,this.renderer.bar.masterBar.isDoubleBar&&(this.width+=2*this.scale))}paint(e,t,s){let i=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x,o=r-a;this.renderer.isLast?(s.fillRect(n+this.width-i-i,a,this.scale,o),s.fillRect(n+this.width-i,a,i,o)):this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart||(s.fillRect(n+this.width-this.scale,a,this.scale,o),this.renderer.bar.masterBar.isDoubleBar&&s.fillRect(n+this.width-5*this.scale,a,this.scale,o))}}class Qr extends Ui{constructor(e,t,s,i){super(e,t,1,Qr.getSymbol(s)),this._clef=s,this._clefOttava=i}doLayout(){switch(this._clef){case r.Neutral:this.width=15*this.scale;break;case r.C3:case r.C4:case r.F4:case r.G2:this.width=28*this.scale}}static getSymbol(e){switch(e){case r.Neutral:return N.UnpitchedPercussionClef1;case r.C3:case r.C4:return N.CClef;case r.F4:return N.FClef;case r.G2:return N.GClef;default:return N.None}}paint(e,t,s){let i;super.paint(e,t,s);let a=!1;switch(this._clefOttava){case n._15ma:i=new Ui(-4*this.scale,0,.5,N.Quindicesima),a=!0;break;case n._8va:i=new Ui(-2*this.scale,0,.5,N.Ottava),a=!0;break;case n._8vb:i=new Ui(-6*this.scale,0,.5,N.Ottava);break;case n._15mb:i=new Ui(-8*this.scale,0,.5,N.Quindicesima);break;default:return}let o=0,h=0;switch(this._clef){case r.Neutral:o=a?-12:15,h=0;break;case r.C3:case r.C4:o=a?-19:27,h=0;break;case r.F4:o=a?-9:27,h=-4;break;case r.G2:o=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*this.scale,t+this.y+o*this.scale,s)}}class $r extends Wi{constructor(e,t){super(e,t)}doLayout(){this.width=11*this.scale}paint(e,t,s){let i=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x,o=r-a,h=1.5*this.scale,l=(a+r)/2;s.fillCircle(n,l-3*h,h),s.fillCircle(n,l+3*h,h),n+=4*this.scale,s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke(),n+=3*this.scale+.5,s.fillRect(n,a,i,o)}}class Kr extends Wi{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=P.Right;let r="x"+this._count,n=s.measureText(r)/1.5;s.fillText(r,e+this.x-n,t+this.y),s.textAlign=a}}class Zr extends Wi{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*this.scale}paint(e,t,s){let i=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x+.5,o=r-a;s.fillRect(n,a,i,o),n+=2*i-.5,s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke(),n+=3*this.scale;let h=this._circleSize*this.scale,l=(a+r)/2;s.fillCircle(n,l-h*this._dotOffset,h),s.fillCircle(n,l+h*this._dotOffset,h)}}class en extends Ui{constructor(e,t,s){super(e,t,1,en.getSymbol(s))}static getSymbol(e){switch(e){case i.None:return N.None;case i.Normal:return N.ArticAccentAbove;case i.Heavy:return N.ArticMarcatoAbove;default:return N.None}}doLayout(){this.width=9*this.scale,this.height=9*this.scale}paint(e,t,s){super.paint(e-2*this.scale,t+this.height,s)}}class tn extends Wi{constructor(e,t,s){super(e,t),this._size=0,this._size=s}doLayout(){this.width=this._size+3*this.scale}paint(e,t,s){s.fillCircle(e+this.x,t+this.y,this._size)}}class sn extends Ui{constructor(e,t,s){super(e,t,s?Xi.GraceScale:1,N.NoteheadXOrnate),this._isGrace=s}doLayout(){this.width=9*(this._isGrace?Xi.GraceScale:1)*this.scale,this.height=Xi.NoteHeadHeight*this.scale}}class an extends Ui{constructor(e,t,s,i){super(e,t,i?Xi.GraceScale:1,an.getSymbol(s)),this._isGrace=i}static getSymbol(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:case u.Whole:case u.Half:return N.NoteheadDiamondWhiteWide;default:return N.NoteheadDiamondBlackWide}}doLayout(){this.width=9*(this._isGrace?Xi.GraceScale:1)*this.scale,this.height=Xi.NoteHeadHeight*this.scale}}class rn extends Wi{constructor(e,t,s){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=Ce.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=rn.calculateActualTieHeight(this.renderer.scale,this._startX,this._startY,this._endX,this._endY,this.tieDirection===Ce.Down,this._tieHeight,4).h),this.tieDirection===Ce.Up&&(this.y-=this.height))}paint(e,t,s){this._shouldDraw&&(this.shouldDrawBendSlur()?rn.drawBendSlur(s,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Ce.Down,this.scale):rn.paintTie(s,this.scale,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Ce.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,s,i){return 22}getBeamDirection(e,t){return Ce.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=rn.computeBezierControlPoints(e,t,s,i,a,r,n,o);t=h[0],s=h[1];const l=h[2],c=h[3];i=h[6],a=h[7];const d=(t-l)/(t-2*l+i),u=rn.calculateExtrema(t,s,l,c,i,a,d),p=u.length>0?Math.min(t,i,u[0]):Math.min(t,i),g=u.length>0?Math.max(t,i,u[0]):Math.max(t,i),f=(s-c)/(s-2*c+a),m=rn.calculateExtrema(t,s,l,c,i,a,f),y=m.length>0?Math.min(s,a,m[1]):Math.min(s,a),b=m.length>0?Math.max(s,a,m[1]):Math.max(s,a),S=new rt;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,c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;let d=(i+t)/2,u=(a+s)/2;return[t,s,d+n*h,u+n*l,d+(n-o)*h,u+(n-o)*l,i,a]}static paintTie(e,t,s,i,a,r,n=!1,o=22,h=4){const l=rn.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,c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;let d=(i+t)/2,u=(a+s)/2,p=rn.BendSlurHeight*n;i-t<20&&(p/=2);let g=d+p*h,f=u+p*l;if(e.beginPath(),e.moveTo(t,s),e.lineTo(g,f),e.lineTo(i,a),e.stroke(),o){let t=e.measureText(o),s=r?0:-e.font.size;e.fillText(o,g-t/2,f+s)}}}rn.BendSlurHeight=11;class nn extends Wi{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=nn.Size*this.scale}paint(e,t,s){this._isOpen?rn.paintTie(s,this.scale,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):rn.paintTie(s,this.scale,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3)}}nn.Size=6;class on{constructor(e,t){this.line=0,this.line=e,this.isGhost=t}}class hn extends Wi{constructor(e){super(0,0),this._infos=[],this._glyphs=[],this.isEmpty=!0,this._isOpen=e}addParenthesis(e){let t=this.renderer,s=t.getNoteLine(e),i=e.isGhost||this.isTiedBend(e)&&t.settings.notation.isNotationElementVisible(k.ParenthesisOnTiedBends);this.addParenthesisOnLine(s,i)}addParenthesisOnLine(e,t){let s=new on(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 nn(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 ln{constructor(e,t){this.line=0,this.glyph=e,this.line=t}}class cn extends Wi{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new Ps,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){let s=new ln(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===Ce.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===Ce.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=3*this.scale,r=this.width-this.noteStartX+2*a;if(this.hasTopOverflow){let n=s.color;s.color=i.resources.staffLineColor;let o=-2;for(;o>=this.minNote.line;){let n=t+i.getScoreY(o);s.fillRect(e-a+this.noteStartX,n,r,this.scale),o-=2}s.color=n}if(this.hasBottomOverflow){let n=s.color;s.color=i.resources.staffLineColor;let o=10;for(;o<=this.maxNote.line;){let n=t+i.getScoreY(o);s.fillRect(e-a+this.noteStartX,n,r,this.scale),o+=2}s.color=n}let n=this._infos,o=e+this._noteHeadPadding;for(let e of n)e.glyph.renderer=this.renderer,e.glyph.paint(o,t,s)}}class dn extends Ui{constructor(e,t,s){super(e,t,1,dn.getSymbol(s))}doLayout(){this.width=12*this.scale}static getSymbol(e){switch(e){case u.ThirtySecond:return N.Tremolo3;case u.Sixteenth:return N.Tremolo2;case u.Eighth:return N.Tremolo1;default:return N.None}}}class un extends cn{constructor(){super(),this._noteGlyphLookup=new Map,this._notes=[],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 Qe.Left:break;case Qe.Center:i+=s.width/2;break;case Qe.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 je.TopWithStem:i-=this.renderer.getStemSize(this.beamingHelper);break;case je.Top:i-=s.height/2;break;case je.Center:break;case je.Bottom:i+=s.height/2;break;case je.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.direction;for(const e of this.aboveBeatEffects.values())e.renderer=this.renderer,e.doLayout();for(const e of this.belowBeatEffects.values())e.renderer=this.renderer,e.doLayout();if(this.beat.isTremolo){let t=0,s=e===Ce.Up?this.minNote:this.maxNote,i=e===Ce.Up?this.displacedX:0,a=this.beat.tremoloSpeed;switch(a){case u.ThirtySecond:t=e===Ce.Up?-15:15;break;case u.Sixteenth:t=e===Ce.Up?-12:15;break;case u.Eighth:t=e===Ce.Up?-10:10;break;default:t=e===Ce.Up?-10:15}this._tremoloPicking=new dn(i,s.glyph.y+t*this.scale,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 ki;r.note=i,r.noteHeadBounds=new rt,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){let i=this.renderer,a=0,r=0,n=1,o=-n;this.beamingHelper.direction===Ce.Up?(r=i.getScoreY(this.minNote.line),a=i.getScoreY(this.maxNote.line-2)):(r=i.getScoreY(this.maxNote.line-1),a=i.getScoreY(this.minNote.line+1),o*=-1,n*=-1);for(const i of this.aboveBeatEffects.values())a+=o*i.height,i.paint(e+this.x+2*this.scale,t+this.y+a,s);for(const i of this.belowBeatEffects.values())r+=n*i.height,i.paint(e+this.x+2*this.scale,t+this.y+r,s);super.paint(e,t,s),this._tremoloPicking&&this._tremoloPicking.paint(e,t,s)}}class pn extends Ui{constructor(e,t,s){super(e,t,1,pn.getSymbol(s)),this._duration=s}static getSymbol(e){switch(e){case u.QuadrupleWhole:return N.RestLonga;case u.DoubleWhole:return N.RestDoubleWhole;case u.Whole:return N.RestWhole;case u.Half:return N.RestHalf;case u.Quarter:return N.RestQuarter;case u.Eighth:return N.RestEighth;case u.Sixteenth:return N.RestSixteenth;case u.ThirtySecond:return N.RestThirtySecond;case u.SixtyFourth:return N.RestSixtyFourth;case u.OneHundredTwentyEighth:return N.RestOneHundredTwentyEighth;case u.TwoHundredFiftySixth:return N.RestTwoHundredFiftySixth;default:return N.None}}static getSize(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:case u.Whole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:return 9;case u.ThirtySecond:return 12;case u.SixtyFourth:return 14;case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:return 20}return 10}doLayout(){this.width=pn.getSize(this._duration)*this.scale}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class gn{constructor(){this.x=0,this.y=-3e3,this.width=0}}class fn extends Sa{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 gn);let t=21*this.scale;for(let s=0,i=this.glyphs.length;s<i;s++){let i=this.glyphs[s];i.renderer=this.renderer,i.doLayout();let a=0;for(;e[a].y>i.y;)a++,a===e.length&&e.push(new gn);i.x=a,e[a].y=i.y+t,e[a].width<i.width&&(e[a].width=i.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 mn extends cn{get direction(){return Ce.Up}constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new fn,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new hn(!0),this._postNoteParenthesis=new hn(!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 Xi(0,0,u.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!==qe.None){let e=new qr(0,i.y,a,!0);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+mn.ElementPadding*this.scale),this._accidentals.isEmpty||(e+=this._accidentals.width+mn.ElementPadding*this.scale,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+mn.ElementPadding*this.scale),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+mn.ElementPadding*this.scale,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+mn.ElementPadding*this.scale)}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)}}mn.ElementPadding=2;class yn extends Wi{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,s,i,a,r,n,o){rn.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*this.scale}getTieDirection(e,t){return t.getBeatDirection(e)===Ce.Up?Ce.Down:Ce.Up}}yn.EndPadding=8;class bn extends z{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class Sn extends Wi{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 l.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 l.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 l.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 l.Prebend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s);break;case l.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 l.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*Sn.BendValueHeight*this.scale;this.renderer.registerOverflowTop(e);let t=0;for(let e of this._notes){let s=this._renderPoints.get(e.id);switch(e.bendType){case l.Bend:s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case l.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t);break;case l.BendRelease:s[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[2].lineValue=t);break;case l.Prebend:s[0].lineValue=this._preBendMinValue;break;case l.PrebendBend:s[0].lineValue=this._preBendMinValue,s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case l.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 l.Custom:for(let s of e.bendPoints)t.push(new bn(s.offset,s.value));break;case l.BendRelease:t.push(new bn(0,e.bendPoints[0].value)),t.push(new bn(z.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new bn(z.MaxPosition,e.bendPoints[3].value));break;case l.Bend:case l.Hold:case l.Prebend:case l.PrebendBend:case l.PrebendRelease:case l.Release:t.push(new bn(0,e.bendPoints[0].value)),t.push(new bn(z.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,c=!1,d=null,u=!1,p=a.bendStyle===h.Gradual?"grad.":"",g=null;for(;o.isTieOrigin;){let e=o.tieDestination;if(d=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,e.beat.voice.bar),!d||n.staff!==d.staff)break;if(o=e,c=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes){u=!0;break}}g=o.beat,d=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,g.voice.bar),g.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(g=null);let f=0,m=0,y=t+n.y;f=e+n.x,r[0].value>0||a.isContinuedBend?f+=n.getBeatX(a.beat,Ye.MiddleNotes):f+=n.getNoteX(a,Qe.Right),m=!g||g.isLastOfVoice&&!u?e+d.x+d.postBeatGlyphsStart:u||!g.nextBeat?e+d.x+d.getBeatX(g,Ye.MiddleNotes):a.bendType===l.Hold?e+d.x+d.getBeatX(g.nextBeat,Ye.OnNotes):e+d.x+d.getBeatX(g.nextBeat,Ye.PreNotes),c||(m-=Sn.ArrowSize*this.scale);let b=(m-f)/z.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 bn(0,0),t,f,y,b,p,s),a.bendType!==l.Prebend?(0===e&&(f+=2*this.scale),this.paintBend(a,t,i,f,y,b,p,s)):a.isTieOrigin&&a.tieDestination.hasBend&&(i=new bn(z.MaxPosition,t.value),i.lineValue=t.lineValue,this.paintBend(a,t,i,f,y,b,p,s))}s.color=i}}paintBend(e,t,s,i,a,r,n,o){let h=this.renderer,l=this.renderer.resources,c=h.lineOffset/2,d=i+r*t.offset,u=Sn.BendValueHeight*this.scale,p=a-u*t.lineValue;0===t.value?s.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,je.Top):p+=h.getNoteY(e,je.Center):p+=c;let g=i+r*s.offset,f=a-u*s.lineValue;0===s.lineValue?f+=h.getNoteY(e,je.Center):f+=c;let m=0,y=Sn.ArrowSize*this.scale;if(s.value>t.value?(f+y>p&&(f=p-y),o.beginPath(),o.moveTo(g,f),o.lineTo(g-.5*y,f+y),o.lineTo(g+.5*y,f+y),o.closePath(),o.fill(),m=y):s.value!==t.value&&(f<p&&(f=p+y),o.beginPath(),o.moveTo(g,f),o.lineTo(g-.5*y,f-y),o.lineTo(g+.5*y,f-y),o.closePath(),o.fill(),m=-y),o.stroke(),t.value===s.value){if(t.lineValue>0){let e=g,t=Sn.DashSize*this.scale,s=d+t;if((e-d)/(2*t)<1)o.moveTo(e,p),o.lineTo(d,p);else for(;e>s;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>d?(o.moveTo(d,p),o.bezierCurveTo((d+g)/2,p,g,p,g,f+m),o.stroke()):(o.moveTo(d,p),o.lineTo(g,f),o.stroke());if(n&&t.offset<s.offset){o.font=l.graceFont;let e=o.measureText(n),t=0,s=0;if(p>f){let i=Math.abs(p-f);t=i>1.3*o.font.size?p-i/2:p,s=(d+g-e)/2}else t=p,s=g-e;o.fillText(n,s,t)}if(0!==s.value&&t.value!==s.value){let e=s.value,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+=Sn.getFractionSign(e)),""!==r){f=a-u*s.value;let e=f;i||(e=p+1*Math.abs(f-p)/3),o.font=l.tablatureFont;let t=o.measureText(r),n=e-.5*l.tablatureFont.size-2*this.scale,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"}}}Sn.ArrowSize=6,Sn.DashSize=3,Sn.BendValueHeight=6;class _n extends Wi{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===E.Custom)return e.whammyBarPoints;let t=[];switch(e.whammyBarType){case E.Dive:case E.Hold:case E.PrediveDive:case E.Predive:t.push(new z(0,e.whammyBarPoints[0].value)),t.push(new z(z.MaxPosition,e.whammyBarPoints[1].value));break;case E.Dip:t.push(new z(0,e.whammyBarPoints[0].value)),t.push(new z(z.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new z(z.MaxPosition,e.whammyBarPoints[e.whammyBarPoints.length-1].value))}return t}doLayout(){super.doLayout(),this._isSimpleDip=this.renderer.settings.notation.notationMode===T.SongBook&&this._beat.whammyBarType===E.Dip;let e=null,t=null,s=this._beat;for(;s&&s.hasWhammyBar;)(!e||e.value>s.minWhammyPoint.value)&&(e=s.minWhammyPoint),(!t||t.value<s.maxWhammyPoint.value)&&(t=s.maxWhammyPoint),s=s.nextBeat;let i=t.value>0?Math.abs(this.getOffset(t.value)):0;(i>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys))&&(i+=2*this.renderer.resources.tablatureFont.size);let a=e.value<0?Math.abs(this.getOffset(e.value)):0;this.renderer.registerOverflowTop(i+a),i>this.renderer.staff.getSharedLayoutData(_n.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(_n.TopOffsetSharedDataKey,i)}getOffset(e){if(0===e)return 0;let t=_n.PerHalfSize*this.scale+Math.log2(Math.abs(e)/2)*_n.PerHalfSize*this.scale;return e<0&&(t=-t),t}paint(e,t,s){let i=this.renderer,a=this._beat.nextBeat,r=null,n=Ye.PreNotes;a&&(r=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,a.voice.bar),r&&r.staff===i.staff&&(r===i||a.hasWhammyBar)?n=!a.hasWhammyBar||i.settings.notation.notationMode===T.SongBook&&a.whammyBarType===E.Dip?Ye.PreNotes:Ye.MiddleNotes:(a=null,r=null));let o=0,l=0;this._isSimpleDip?(o=e+i.x+i.getBeatX(this._beat,Ye.OnNotes)-2*this.scale,l=e+i.x+i.getBeatX(this._beat,Ye.PostNotes)+2*this.scale):(o=e+i.x+i.getBeatX(this._beat,Ye.MiddleNotes),l=r?e+r.x+r.getBeatX(a,n):e+i.x+i.width-2*this.scale);let c=s.textAlign;if(s.textAlign=P.Center,this._renderPoints.length>=2){let e=(l-o)/z.MaxPosition;s.beginPath();let i=t+this.renderer.staff.getSharedLayoutData(_n.TopOffsetSharedDataKey,0),a=this._beat.whammyStyle===h.Gradual?"grad.":"";for(let t=0,r=this._renderPoints.length-1;t<r;t++){let n=this._renderPoints[t],h=this._renderPoints[t+1],l=t<r-2?this._renderPoints[t+2]:null,c=0===t;0!==t||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new z(0,0),n,h,o,i,e,s),c=!1),this.paintWhammy(c,n,h,l,o,i,e,s,a),a=""}s.stroke()}s.textAlign=c}paintWhammy(e,t,s,i,a,r,n,o,h){let l=a+n*t.offset,c=a+n*s.offset,d=r-this.getOffset(t.value),u=r-this.getOffset(s.value);if(t.offset===s.offset){let e=_n.DashSize*this.scale;if(Math.abs(u-d)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(d,u),s=Math.min(d,u);for(;t>s;)o.moveTo(l,s),o.lineTo(l,s+e),s+=2*e}o.stroke()}else if(t.value===s.value){let e=_n.DashSize*this.scale;if(Math.abs(c-l)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(l,c),s=Math.min(l,c);for(;t>s;)o.moveTo(t,d),o.lineTo(t-e,d),t-=2*e}o.stroke()}else o.moveTo(l,d),o.lineTo(c,u);let p=this.renderer.resources;if(e&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let e=d;e-=p.tablatureFont.size+2*this.scale,this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2*this.scale,o.fillText(h,l,e))}let g=Math.abs(s.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys)&&!this._isSimpleDip)&&t.value!==s.value){let e="";if(s.value<0&&(e+="-"),g>=4){let t=g/4|0;e+=t,g-=4*t}else 0===g&&(e+="0");g>0&&(e+=Sn.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(d,u)-p.tablatureFont.size-2*this.scale:(a=t.offset===s.offset?Math.min(d,u):u,a-=p.tablatureFont.size+2*this.scale,i&&i.value>s.value&&(a-=2*this.scale));let r=c;o.fillText(e,r,a)}}}_n.TopOffsetSharedDataKey="tab.whammy.topoffset",_n.PerHalfSize=6,_n.DashSize=3;class wn extends yn{constructor(e){super(0,0),this._beat=e}doLayout(){let e=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case E.None:case E.Custom:case E.Hold:return;case E.Dive:case E.PrediveDive:{let e=new mn(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 E.Dip:if(e===T.SongBook){let e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+wn.SimpleDipHeight*this.scale+wn.SimpleDipPadding*this.scale}else{let e=new mn(this._beat,!1);if(e.renderer=this.renderer,this.renderer.settings.notation.notationMode===T.GuitarPro){let t=this._beat.whammyBarPoints[1];for(let s of this._beat.notes)e.addGlyph(this.getBendNoteValue(s,this._beat.whammyBarPoints[1]),t.value%2!=0)}e.doLayout(),this.BendNoteHeads.push(e);let t=new mn(this._beat,!1);if(t.renderer=this.renderer,this.renderer.settings.notation.notationMode===T.GuitarPro){let e=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let s of this._beat.notes)t.addGlyph(this.getBendNoteValue(s,e),e.value%2!=0)}t.doLayout(),this.BendNoteHeads.push(t)}case E.Predive:}super.doLayout()}paint(e,t,s){let i=this._beat;switch(i.whammyBarType){case E.None:case E.Custom:return}let a=this.renderer.settings.notation.notationMode,r=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,i.voice.bar),n=e+r.x+r.getBeatX(i,Ye.MiddleNotes),o=this.getTieDirection(i,r),l=1===this._beat.notes.length?o:Ce.Up,c=s.textAlign;for(let c=0;c<i.notes.length;c++){let d=i.notes[c],u=t+r.y;c>0&&c>=(this._beat.notes.length/2|0)&&(l=Ce.Down),l===Ce.Down?u+=r.getNoteY(d,je.Bottom):u+=r.getNoteY(d,je.Top);let p=e+r.x;i.isLastOfVoice?p+=r.width:p+=r.getBeatX(i,Ye.EndBeat),p-=8*this.scale;let g=i.whammyStyle===h.Gradual&&0===c?"grad.":"",f=null;d.isTieOrigin&&(f=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,d.tieDestination.beat.voice.bar),f&&f.staff===r.staff?p=e+f.x+f.getBeatX(d.tieDestination.beat,Ye.MiddleNotes):f=null);let m=Xi.NoteHeadHeight*this.scale*Xi.GraceScale*.5;l===Ce.Up&&(m=-m);let y=i.whammyBarPoints.length>0?this.getBendNoteValue(d,i.whammyBarPoints[i.whammyBarPoints.length-1]):0,b=0,S=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(y)?(b=this.BendNoteHeads[0].getNoteValueY(y)+m,S=!0):f&&(d.isTieOrigin&&d.tieDestination.beat.hasWhammyBar||d.beat.isContinuedWhammy)?(b=t+f.y+f.getNoteY(d.tieDestination,je.Top),S=!0,l===Ce.Down&&(b+=Xi.NoteHeadHeight*this.scale)):d.isTieOrigin&&(b=f?t+f.y+f.getNoteY(d.tieDestination,je.Top):u,l===Ce.Down&&(b+=Xi.NoteHeadHeight*this.scale)),i.whammyBarType){case E.Hold:d.isTieOrigin&&rn.paintTie(s,this.scale,n,u,p,b,o===Ce.Down,22,4);break;case E.Dive:0===c&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.BendNoteHeads[0].containsNoteValue(y)&&(b+=this.BendNoteHeads[0].y)),S?this.drawBendSlur(s,n,u,p,b,l===Ce.Down,this.scale,g):d.isTieOrigin&&rn.paintTie(s,this.scale,n,u,p,b,o===Ce.Down,22,4);break;case E.Dip:if(a===T.SongBook){if(0===c){let i=e+r.x+r.getBeatX(this._beat,Ye.OnNotes)-2*this.scale,a=e+r.x+r.getBeatX(this._beat,Ye.PostNotes)+2*this.scale,n=(i+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();s.font=this.renderer.resources.tablatureFont,s.fillText(o,n,t+this.y);let h=t+this.y+s.font.size+2*this.scale,l=h+wn.SimpleDipHeight*this.scale;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(s.moveTo(i,l),s.lineTo(n,h),s.lineTo(a,l)):(s.moveTo(i,h),s.lineTo(n,l),s.lineTo(a,h)),s.stroke()}d.isTieOrigin&&rn.paintTie(s,this.scale,n,u,p,b,o===Ce.Down,22,4)}else{let e=(n+p)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s);let a=this.getBendNoteValue(d,i.whammyBarPoints[1]),o=this.BendNoteHeads[0].getNoteValueY(a)+m;this.drawBendSlur(s,n,u,e,o,l===Ce.Down,this.scale,g),this.BendNoteHeads[1].x=p-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=t+r.y,this.BendNoteHeads[1].paint(0,0,s),b=this.BendNoteHeads[1].getNoteValueY(y)+m,this.drawBendSlur(s,e,o,p,b,l===Ce.Down,this.scale,g)}break;case E.PrediveDive:case E.Predive:let h=e+r.x+r.getBeatX(d.beat,Ye.PreNotes);h+=r.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let f=t+r.y+r.getScoreY(r.accidentalHelper.getNoteLineForValue(d.displayValue-(d.beat.whammyBarPoints[0].value/2|0),!1))+m;this.drawBendSlur(s,h,f,n,u,l===Ce.Down,this.scale,g),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.drawBendSlur(s,n,u,p,b,l===Ce.Down,this.scale,g))}}s.textAlign=c}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}wn.SimpleDipHeight=2*_n.PerHalfSize,wn.SimpleDipPadding=2;class Bn extends Wi{constructor(e,t,s){super(e,t),this.width=s}}class Tn extends Ui{constructor(e,t,s,i,a){super(e,t,a?Xi.GraceScale:1,s.getSymbol(i)),this._isGrace=a,this._articulation=s}paint(e,t,s){let i=this._isGrace?this.scale:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale*this.scale,this.symbol,!1),this._articulation.techniqueSymbol!==N.None&&this._articulation.techniqueSymbolPlacement===C.Middle&&s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale*this.scale,this._articulation.techniqueSymbol,!1)}doLayout(){let e=(this._isGrace?Xi.GraceScale:1)*this.scale;switch(this.symbol){case N.NoteheadWhole:this.width=14;break;case N.NoteheadCircleX:case N.NoteheadDiamondWhite:this.width=9;break;case N.NoteheadHeavyXHat:case N.NoteheadHeavyX:this.width=13;break;default:this.width=10}this.width=this.width*(this._isGrace?Xi.GraceScale:1)*this.scale,this.height=Xi.NoteHeadHeight*e}}class kn extends Ui{constructor(e,t){super(e,t,Xi.GraceScale,N.ArticStaccatoAbove)}doLayout(){this.width=Xi.QuarterNoteHeadWidth*this.scale,this.height=7*this.scale}paint(e,t,s){super.paint(e+3*this.scale,t+5*this.scale,s)}}class vn extends Ui{constructor(e,t){super(e,t,.5,N.PictEdgeOfCymbal)}doLayout(){this.width=22*this.scale,this.height=15*this.scale}paint(e,t,s){super.paint(e-3*this.scale,t+this.height,s)}}class xn extends Ui{constructor(e,t){super(e,t,Xi.GraceScale,N.GuitarGolpe)}doLayout(){this.width=9*this.scale,this.height=10*this.scale}paint(e,t,s){super.paint(e,t+this.height,s)}}class Nn extends Ka{constructor(){super(...arguments),this._collisionOffset=-1e3,this._skipPaint=!1,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&&(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)}}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===u.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const s=new pn(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=xa.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 Bn(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++){let e=new Sa(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addGlyph(e)}}}else{const t=new un;this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper;let s=new hn(!1);s.renderer=this.renderer;for(let e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),s.addParenthesis(e));if(this.addGlyph(t),s.isEmpty||(this.addGlyph(new Bn(0,0,4*(this.container.beat.graceType!==g.None?Xi.GraceScale:1)*this.scale)),this.addGlyph(s)),this.container.beat.hasWhammyBar){let e=new wn(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addGlyph(new Bn(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++){let t=new Sa(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.container.beat.isRest?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.centerX=this.noteHeads.x+this.noteHeads.width/2}createBeatDot(e,t){let s=this.renderer;t.addGlyph(new tn(0,s.getScoreY(e),1.5*this.scale))}createNoteHeadGlyph(e){let t=this.container.beat.graceType!==g.None;if(e.beat.voice.bar.staff.isPercussion){const s=$.getArticulation(e);if(s)return new Tn(0,0,s,e.beat.duration,t);q.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new sn(0,0,t):e.beat.graceType===g.BendGrace?new Xi(0,0,u.Quarter,!0):e.harmonicType===m.Natural?new an(0,0,e.beat.duration,t):new Xi(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===g.BendGrace&&!e.hasBend)return;let t=this.renderer,s=this.createNoteHeadGlyph(e),a=t.getNoteLine(e);if(s.y=t.getScoreY(a),this.noteHeads.addNoteGlyph(s,e,a),e.harmonicType!==m.None&&e.harmonicType!==m.Natural){let i=e.displayValue+e.harmonicPitch;s=new an(0,0,e.beat.duration,this.container.beat.graceType!==g.None),a=t.accidentalHelper.getNoteLineForValue(i,!1),s.y=t.getScoreY(a),this.noteHeads.addNoteGlyph(s,e,a)}if(e.isStaccato&&!this.noteHeads.aboveBeatEffects.has("Staccato")&&this.noteHeads.belowBeatEffects.set("Staccato",new kn(0,0)),e.accentuated!==i.Normal||this.noteHeads.aboveBeatEffects.has("Accent")||this.noteHeads.belowBeatEffects.set("Accent",new en(0,0,i.Normal)),e.accentuated!==i.Heavy||this.noteHeads.aboveBeatEffects.has("HAccent")||this.noteHeads.belowBeatEffects.set("HAccent",new en(0,0,i.Heavy)),e.isPercussion){const t=$.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==C.Middle){const e=t.techniqueSymbolPlacement===C.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case N.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new vn(0,0));break;case N.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new kn(0,0));break;case N.StringsUpBow:e.set("StringsUpBow",new Nr(0,0,x.Up));break;case N.StringsDownBow:e.set("StringsDownBow",new Nr(0,0,x.Down));break;case N.GuitarGolpe:e.set("GuitarGolpe",new xn(0,0))}}}}}class Pn extends Wi{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=this._beat.brushType===c.ArpeggioUp||this._beat.brushType===c.ArpeggioDown?10*this.scale:0}paint(e,t,s){if(this._beat.brushType===c.ArpeggioUp||this._beat.brushType===c.ArpeggioDown){let i=this.renderer,a=i.lineOffset,r=t+this.y+(i.getNoteY(this._beat.maxNote,je.Bottom)-a),n=t+this.y+i.getNoteY(this._beat.minNote,je.Top)+a,o=e+this.x+this.width/2,h=8*this.scale,l=new Fr(0,0,_.Slight,1.2,!0);l.renderer=this.renderer,l.doLayout();let d=-l.height/2;if(this._beat.brushType===c.ArpeggioUp){let t=r+h,i=n-h;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5*this.scale,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===c.ArpeggioDown){let t=r+h,i=n;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5*this.scale,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 Cn extends $a{get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}doLayout(){if(!this.container.beat.isRest){let e=new fn;e.renderer=this.renderer;let t=new hn(!0);t.renderer=this.renderer;const s=new mn(this.container.beat,!0);this._prebends=s,s.renderer=this.renderer;for(let i of this.container.beat.notes)if(i.isVisible){if(i.hasBend)switch(i.bendType){case l.PrebendBend:case l.Prebend:case l.PrebendRelease:s.addGlyph(i.displayValue-(i.bendPoints[0].value/2|0),!1)}else if(i.beat.hasWhammyBar)switch(i.beat.whammyBarType){case E.PrediveDive:case E.Predive:this._prebends.addGlyph(i.displayValue-(i.beat.whammyBarPoints[0].value/2|0),!1)}this.createAccidentalGlyph(i,e),t.addParenthesis(i)}s.isEmpty||(this.addGlyph(s),this.addGlyph(new Bn(0,0,4*(this.container.beat.graceType!==g.None?Xi.GraceScale:1)*this.scale))),this.container.beat.brushType!==c.None&&(this.addGlyph(new Pn(this.container.beat)),this.addGlyph(new Bn(0,0,4*this.scale))),t.isEmpty||(this.addGlyph(t),this.addGlyph(new Bn(0,0,4*(this.container.beat.graceType!==g.None?Xi.GraceScale:1)*this.scale))),e.isEmpty||(this.accidentals=e,this.addGlyph(new Bn(0,0,2*(this.container.beat.graceType!==g.None?Xi.GraceScale:1)*this.scale)),this.addGlyph(e),this.addGlyph(new Bn(0,0,2*(this.container.beat.graceType!==g.None?Xi.GraceScale:1)*this.scale)))}super.doLayout()}createAccidentalGlyph(e,t){let s=this.renderer,i=s.accidentalHelper.applyAccidental(e),a=s.getNoteLine(e),r=this.container.beat.graceType!==g.None;if(i!==qe.None){let e=new qr(0,s.getScoreY(a),i,r);e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==m.None&&e.harmonicType!==m.Natural){let n=e.displayValue+e.harmonicPitch;i=s.accidentalHelper.applyAccidentalForValue(e.beat,n,r,!1),a=s.accidentalHelper.getNoteLineForValue(n,!1);let o=new qr(0,s.getScoreY(a),i,r);o.renderer=this.renderer,t.addGlyph(o)}}constructor(){super(),this._prebends=null,this.accidentals=null}}class En extends Ui{constructor(e,t,s,i){super(e,t,i,En.getSymbol(s)),this._digit=0,this._scale=0,this._digit=s,this._scale=i}doLayout(){this.width=this.getDigitWidth(this._digit)*this.scale*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 N.TimeSig0;case 1:return N.TimeSig1;case 2:return N.TimeSig2;case 3:return N.TimeSig3;case 4:return N.TimeSig4;case 5:return N.TimeSig5;case 6:return N.TimeSig6;case 7:return N.TimeSig7;case 8:return N.TimeSig8;case 9:return N.TimeSig9;default:return N.None}}}class Fn extends Sa{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 En(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}}}Fn.numberHeight=18;class Ln extends Sa{constructor(e,t,s,i,a){super(e,t),this._numerator=0,this._denominator=0,this._numerator=s,this._denominator=i,this._isCommon=a}doLayout(){if(this._isCommon&&2===this._numerator&&2===this._denominator){let e=new Ui(0,0,this.commonScale,N.TimeSigCutCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){let e=new Ui(0,0,this.commonScale,N.TimeSigCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else{const e=Fn.numberHeight*this.scale;let t=new Fn(0,-e/2,this._numerator,this.numberScale),s=new Fn(0,e/2,this._denominator,this.numberScale);this.addGlyph(t),this.addGlyph(s),super.doLayout();for(let e=0,t=this.glyphs.length;e<t;e++){let t=this.glyphs[e];t.x=(this.width-t.width)/2}}}}class Mn extends Ln{get commonScale(){return 1}get numberScale(){return 1}}class In extends yn{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 l.Bend:case l.PrebendRelease:case l.PrebendBend:{let t=this._endNoteGlyph;t||(t=new mn(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 l.Release:if(!e.isTieOrigin){let t=this._endNoteGlyph;t||(t=new mn(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 l.BendRelease:{let t=this._middleNoteGlyph;t||(t=new mn(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 mn(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,Ye.MiddleNotes),r=e+i.x;this._beat.isLastOfVoice?r+=i.postBeatGlyphsStart:r+=i.getBeatX(this._beat.nextBeat,Ye.PreNotes),r-=8*this.scale;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===g.BendGrace?this._beat.nextBeat:this._beat,c=1===this._notes.length?this.getTieDirection(o,i):Ce.Up;for(let o=0;o<this._notes.length;o++){let d=this._notes[o];o>0&&o>=(this._notes.length/2|0)&&(c=Ce.Down);let u=t+i.y+i.getNoteY(d,je.Top),p=Xi.NoteHeadHeight*this.scale*Xi.GraceScale*.5;c===Ce.Down&&(u+=Xi.NoteHeadHeight*this.scale);let g=d.bendStyle===h.Gradual?"grad.":"";if(d.isTieOrigin){let r=d.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,Ye.MiddleNotes),o=t+n.y+n.getNoteY(r,je.Top);c===Ce.Down&&(o+=Xi.NoteHeadHeight*this.scale),d.bendType===l.Hold||d.bendType===l.Prebend?rn.paintTie(s,this.scale,a,u,i,o,c===Ce.Down,22,4):this.drawBendSlur(s,a,u,i,o,c===Ce.Down,this.scale,g)}else{let r=e+i.x+i.width,n=d.tieDestination.realValue;i.accidentalHelper.applyAccidentalForValue(d.beat,n,!1,!0);let o=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(n,!1));d.bendType===l.Hold||d.bendType===l.Prebend?rn.paintTie(s,this.scale,a,u,r,o,c===Ce.Down,22,4):this.drawBendSlur(s,a,u,r,o,c===Ce.Down,this.scale,g)}switch(d.bendType){case l.Prebend:case l.PrebendBend:case l.PrebendRelease:let r=e+i.x+i.getBeatX(d.beat,Ye.PreNotes);r+=i.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let n=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(d.displayValue-(d.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,r,n,a,u,c===Ce.Down,this.scale)}}else{c===Ce.Up&&(p=-p);let o=0,h=0;switch(d.bendType){case l.Bend:o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,h,c===Ce.Down,this.scale,g);break;case l.BendRelease:let f=this.getBendNoteValue(d,d.bendPoints[1]),m=this._middleNoteGlyph.getNoteValueY(f)+p;this.drawBendSlur(s,a,u,n,m,c===Ce.Down,this.scale,g),o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,n,m,r,h,c===Ce.Down,this.scale,g);break;case l.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,h,c===Ce.Down,this.scale,g));break;case l.Prebend:case l.PrebendBend:case l.PrebendRelease:let y=e+i.x+i.getBeatX(d.beat,Ye.PreNotes);y+=i.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let b=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(d.displayValue-(d.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,y,b,a,u,c===Ce.Down,this.scale),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,h,c===Ce.Down,this.scale,g))}}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class Dn extends rn{constructor(e,t,s=!1){super(e,t,s)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?Ce.Up:t.getBeatDirection(e)===Ce.Up?Ce.Down:Ce.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Ce.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,je.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,je.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===Ce.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===g.None?s===this.tieDirection?this.tieDirection===Ce.Up?e.getNoteY(this.endBeat.maxNote,je.TopWithStem):e.getNoteY(this.endBeat.minNote,je.BottomWithStem):this.tieDirection===Ce.Up?e.getNoteY(this.endBeat.maxNote,je.BottomWithStem):e.getNoteY(this.endBeat.minNote,je.TopWithStem):this.tieDirection===Ce.Up?e.getNoteY(this.endBeat.maxNote,je.Top):e.getNoteY(this.endBeat.minNote,je.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,Ye.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>u.Whole&&e===this.tieDirection?Ye.Stem:Ye.MiddleNotes)}}class An extends Wi{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=12*this.scale,r=e+i.x+i.getNoteX(this._startNote,Qe.Left)-2*this.scale,n=t+i.y+i.getNoteY(this._startNote,je.Center),o=r-a,h=t+i.y;switch(this._inType){case b.IntoFromBelow:h+=i.getNoteY(this._startNote,je.Bottom);break;case b.IntoFromAbove:h+=i.getNoteY(this._startNote,je.Top);break;default:return}let l=this.getAccidentalsWidth(i,this._startNote.beat);o-=l,r-=l,this.paintSlideLine(s,!1,o,r,h,n)}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=12*this.scale,r=1*this.scale,n=2*this.scale,o=0,h=0,l=0,c=0,d=!1;switch(this._outType){case S.Shift:case S.Legato:if(o=e+i.x+i.getBeatX(this._startNote.beat,Ye.PostNotes),h=t+i.y+i.getNoteY(this._startNote,je.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?(l=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,Ye.PreNotes)-r,c=t+s.y+s.getNoteY(this._startNote.slideTarget,je.Center)):(l=e+i.x+i.width,c=h),this._startNote.slideTarget.realValue>this._startNote.realValue?(h+=n,c-=n):(h-=n,c+=n)}else l=e+i.x+this._parent.x,c=h;break;case S.OutUp:o=e+i.x+i.getNoteX(this._startNote,Qe.Right),h=t+i.y+i.getNoteY(this._startNote,je.Center),l=o+a,c=t+i.y+i.getNoteY(this._startNote,je.Top);break;case S.OutDown:o=e+i.x+i.getNoteX(this._startNote,Qe.Right),h=t+i.y+i.getNoteY(this._startNote,je.Center),l=o+a,c=t+i.y+i.getNoteY(this._startNote,je.Bottom);break;case S.PickSlideUp:o=e+i.x+i.getNoteX(this._startNote,Qe.Right),h=t+i.y+i.getNoteY(this._startNote,je.Center),c=t+i.y+i.getNoteY(this._startNote,je.Top),l=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(l=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Ye.PreNotes)),d=!0;break;case S.PickSlideDown:o=e+i.x+i.getNoteX(this._startNote,Qe.Right),h=t+i.y+i.getNoteY(this._startNote,je.Center),c=t+i.y+i.getNoteY(this._startNote,je.Bottom),l=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(l=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Ye.PreNotes)),d=!0;break;default:return}this.paintSlideLine(s,d,o,l,h,c)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new Fr(0,0,_.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 Rn extends Dn{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===Ce.Up?this.startNoteRenderer.getNoteY(this._startNote,je.Top):this.startNoteRenderer.getNoteY(this._startNote,je.Bottom):this.startNoteRenderer.getNoteY(this._startNote,je.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===Ce.Up?this.endNoteRenderer.getNoteY(this._endNote,je.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,je.BottomWithStem):this.tieDirection===Ce.Up?this.endNoteRenderer.getNoteY(this._endNote,je.Top):this.endNoteRenderer.getNoteY(this._endNote,je.Bottom):this.endNoteRenderer.getNoteY(this._endNote,je.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===Ce.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===Ce.Down}isEndCentered(){return this._startNote.beat.graceType===g.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===Ce.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===Ce.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===g.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,Ye.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,Qe.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,Ye.Stem):this.endNoteRenderer.getNoteX(this._endNote,Qe.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,Ye.PreNotes)}}class On extends rn{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)===Ce.Up?Ce.Down:Ce.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Ce.Up?this.startNoteRenderer.getNoteY(this.startNote,je.Top):this.startNoteRenderer.getNoteY(this.startNote,je.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===Ce.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===Ce.Up?e.getNoteY(this.endNote,je.Top):e.getNoteY(this.endNote,je.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,Ye.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,Ye.PreNotes)}}class Gn extends qi{constructor(e,t){super(e,t),this._bend=null,this._effectSlur=null,this._effectEndSlur=null}doLayout(){if(this._effectSlur=null,this._effectEndSlur=null,super.doLayout(),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 Dn(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 Dn(e,this.beat,!0))}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!==g.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){let t=new On(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){let t=new On(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==b.None||e.slideOutType!==S.None){let t=new An(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){let t=new Rn(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){let t=new Rn(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new Rn(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===Ce.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,i=t===Ce.Up?e.beat.minNote:e.beat.maxNote;const a=new Rn(s,i,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new In(e.beat);this._bend=t,t.renderer=this.renderer,this.addTie(t)}this._bend.addBends(e)}}}}class Vn extends Ya{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._firstLineY=0,this._startSpacing=!1,this.accidentalHelper=new Ta(this)}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}get lineOffset(){return(Ya.LineSpacing+1)*this.scale}updateSizes(){let e=this.resources,t=e.tablatureFont.size/2+.2*e.tablatureFont.size;this.topPadding=t*this.scale,this.bottomPadding=t*this.scale,this.height=4*this.lineOffset+this.topPadding+this.bottomPadding,this.updateFirstLineY(),super.updateSizes()}updateFirstLineY(){let e=4*this.lineOffset,t=(this.bar.staff.standardNotationLineCount-1)*this.lineOffset;this._firstLineY=(e-t)/2}doLayout(){if(this.updateFirstLineY(),super.doLayout(),!this.bar.isEmpty&&this.accidentalHelper.maxLineBeat){let e=this.getScoreY(-2),t=this.getScoreY(6),s=this.simpleWhammyOverflow;this.registerOverflowTop(s);let i=this.getScoreY(this.accidentalHelper.maxLine),a=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);a.direction===Ce.Up&&(i-=this.getStemSize(a),i-=a.fingeringCount*this.resources.graceFont.size,a.hasTuplet&&(i-=2*this.resources.effectFont.size)),a.hasTuplet&&(i-=1.5*this.resources.effectFont.size),i<e&&this.registerOverflowTop(Math.abs(i)+s);let r=this.getScoreY(this.accidentalHelper.minLine),n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);n.direction===Ce.Down&&(r+=this.getStemSize(n),r+=n.fingeringCount*this.resources.graceFont.size),r>t&&this.registerOverflowBottom(Math.abs(r)-t)}}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s),this.paintTuplets(e,t,s)}paintTuplets(e,t,s){for(let i of this.bar.voices)if(this.hasVoiceContainer(i)){let a=this.getVoiceContainer(i);for(let i of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,i)}}paintBeams(e,t,s){for(let i=0,a=this.helpers.beamHelpers.length;i<a;i++){let a=this.helpers.beamHelpers[i];for(let i=0,r=a.length;i<r;i++){let r=a[i];this.paintBeamHelper(e+this.beatGlyphsStart,t,s,r)}}}paintBeamHelper(e,t,s,i){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(1===i.beats.length?this.paintFlag(e,t,s,i):this.paintBar(e,t,s,i))}paintTupletHelper(e,t,s,i){let a,r=this.resources,n=s.textAlign,o=s.textBaseline;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=P.Center,s.textBaseline=C.Middle;let h=i.beats[0].tupletNumerator,l=i.beats[0].tupletDenominator;a=2===h&&3===l?"2":3===h&&2===l?"3":4===h&&6===l?"4":5===h&&4===l?"5":6===h&&4===l?"6":7===h&&4===l?"7":9===h&&8===l?"9":10===h&&8===l?"10":11===h&&8===l?"11":12===h&&8===l?"12":13===h&&8===l?"13":h+":"+l;let c=10*this.scale,d=5*this.scale;if(1!==i.beats.length&&i.isFull){let n=i.beats[0],o=i.beats[i.beats.length-1],h=null,l=null;for(let e=0;e<i.beats.length;e++)if(!i.beats[e].isRest){h=i.beats[e];break}for(let e=i.beats.length-1;e>=0;e--)if(!i.beats[e].isRest){l=i.beats[e];break}let u=!1;h||(h=n,u=!0),l||(l=o);let p=this.helpers.beamHelperLookup[i.voice.index].get(n.index),g=this.helpers.beamHelperLookup[i.voice.index].get(o.index),f=p.getBeatLineX(n),m=g.getBeatLineX(o),y=this.helpers.beamHelperLookup[i.voice.index].get(h.index),b=this.helpers.beamHelperLookup[i.voice.index].get(l.index),S=p.direction,_=this.calculateBeamYWithDirection(y,f,S),w=this.calculateBeamYWithDirection(b,m,S);u&&(_=Math.max(_,w),w=_),s.font=r.effectFont;let B=s.measureText(a),T=3*this.scale,k=(f+m)/2,v=k-B/2-T,x=k+B/2+T,N=(w-_)/(m-f),P=_-N*f,C=N*v+P,E=N*k+P,F=N*x+P;S===Ce.Down&&(c*=-1,d*=-1),s.beginPath(),s.moveTo(e+this.x+f,t+this.y+_-c|0),s.lineTo(e+this.x+f,t+this.y+_-c-d|0),s.lineTo(e+this.x+v,t+this.y+C-c-d|0),s.stroke(),s.beginPath(),s.moveTo(e+this.x+x,t+this.y+F-c-d|0),s.lineTo(e+this.x+m,t+this.y+w-c-d|0),s.lineTo(e+this.x+m,t+this.y+w-c|0),s.stroke(),s.fillText(a,e+this.x+k,t+this.y+E-c-d)}else for(let n=0,o=i.beats.length;n<o;n++){let o=i.beats[n],h=this.helpers.beamHelperLookup[i.voice.index].get(o.index);if(!h)continue;let l=h.direction,u=h.getBeatLineX(o),p=this.calculateBeamYWithDirection(h,u,l);l===Ce.Down&&(c*=-1,d*=-1),s.font=r.effectFont,s.fillText(a,e+this.x+u,t+this.y+p-c-d)}s.textAlign=n,s.textBaseline=o}getStemSize(e){let t=1===e.beats.length?this.getFlagStemSize(e.shortestDuration):this.getBarStemSize(e.shortestDuration);return e.isGrace&&(t*=Xi.GraceScale),t}getBarStemSize(e){let t=0;switch(e){case u.QuadrupleWhole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:t=6;break;case u.ThirtySecond:t=8;break;case u.SixtyFourth:case u.OneHundredTwentyEighth:t=9;break;case u.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}getFlagStemSize(e){let t=0;switch(e){case u.QuadrupleWhole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:case u.ThirtySecond:case u.SixtyFourth:case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:t=6;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){let s=super.getNoteY(e,t);if(isNaN(s)){const t=Ta.computeLineWithoutAccidentals(this.bar,e);s=this.getScoreY(t)}return s}calculateBeamY(e,t){return this.calculateBeamYWithDirection(e,t,e.direction)}applyLayoutingInfo(){const e=super.applyLayoutingInfo();if(e&&this.bar.isMultiVoice){let e=this.getScoreY(-2),t=this.getScoreY(6),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 va;e.drawingInfos.set(s,t);const a=e.beats[0],r=e.beats[e.beats.length-1];let n=e.isRestBeamHelper;t.startBeat=a,t.startX=e.getBeatLineX(a),t.startY=n?s===Ce.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===Ce.Up?this.getScoreY(this.accidentalHelper.getMinLine(a))-i:this.getScoreY(this.accidentalHelper.getMaxLine(a))+i,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?s===Ce.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===Ce.Up?this.getScoreY(this.accidentalHelper.getMinLine(r))-i:this.getScoreY(this.accidentalHelper.getMaxLine(r))+i;let o=10*this.scale;if(s===Ce.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),s===Ce.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),s===Ce.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),s===Ce.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(s===Ce.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=j.getIndex(e.shortestDuration)-2;let a=e.isGrace?Xi.GraceScale:1,r=i*(Ya.BeamSpacing+Ya.BeamThickness)*this.scale*a;if(r+=Ya.BeamSpacing,s===Ce.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===Ce.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)}}}}return e.drawingInfos.get(s).calcY(t)}paintBar(e,t,s,i){for(let a=0,r=i.beats.length;a<r;a++){let r=i.beats[a],n=r.graceType!==g.None?Xi.GraceScale:1,o=i.getBeatLineX(r),h=i.direction,l=t+this.y;l+=h===Ce.Up?this.getScoreY(this.accidentalHelper.getMaxLine(r)):this.getScoreY(this.accidentalHelper.getMinLine(r));let c=t+this.y;c+=this.calculateBeamY(i,o),s.lineWidth=Ya.StemWidth*this.scale,s.beginPath(),s.moveTo(e+this.x+o,l),s.lineTo(e+this.x+o,c),s.stroke(),s.lineWidth=this.scale;let d=c;h===Ce.Down?d+=2*s.font.size:0!==a&&(d-=1.5*s.font.size),this.paintFingering(s,r,e+this.x+o,h,d);let u=6*this.scale*n,p=(Ya.BeamSpacing+Ya.BeamThickness)*this.scale*n,f=Ya.BeamThickness*this.scale*n,m=j.getIndex(r.duration)-2,y=t+this.y;h===Ce.Down&&(p=-p,f=-f);for(let t=0;t<m;t++){let n=0,h=0,l=0,c=0,d=y+t*p;if(a<i.beats.length-1){if(xa.isFullBarJoin(r,i.beats[a+1],t))n=o,h=i.getBeatLineX(i.beats[a+1]);else{if(0!==a&&xa.isFullBarJoin(i.beats[a-1],r,t))continue;n=o,h=n+u}l=d+this.calculateBeamY(i,n),c=d+this.calculateBeamY(i,h),Vn.paintSingleBar(s,e+this.x+n,l,e+this.x+h,c,f)}else a>0&&!xa.isFullBarJoin(r,i.beats[a-1],t)&&(n=o-u,h=o,l=d+this.calculateBeamY(i,n),c=d+this.calculateBeamY(i,h),Vn.paintSingleBar(s,e+this.x+n,l,e+this.x+h,c,f))}}}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()}paintFlag(e,t,s,i){let a=i.beats[0];if(a.graceType===g.BendGrace||a.graceType!==g.None&&this.settings.notation.notationMode===T.SongBook)return;let r=a.graceType!==g.None,n=r?Xi.GraceScale:1,o=this.getFlagStemSize(i.shortestDuration),h=i.getBeatLineX(a),l=i.direction,c=this.getScoreY(this.accidentalHelper.getMinLine(a)),d=this.getScoreY(this.accidentalHelper.getMaxLine(a)),u=0,p=0;if(l===Ce.Down?(d+=o*n,u=d,p=t+this.y+d):(c-=o*n,u=c,p=t+this.y+c),this.paintFingering(s,a,e+this.x+h,l,p),i.hasLine){if(s.lineWidth=Ya.StemWidth*this.scale,s.beginPath(),s.moveTo(e+this.x+h,t+this.y+c),s.lineTo(e+this.x+h,t+this.y+d),s.stroke(),s.lineWidth=this.scale,a.graceType===g.BeforeBeat){let i=15*this.scale,a=12*this.scale;s.beginPath(),l===Ce.Down?(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.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.stroke()}if(i.hasFlag){let i=new Yi(h-this.scale/2,u,a.duration,l,r);i.renderer=this,i.doLayout(),i.paint(e+this.x,t+this.y,s)}}}paintFingering(e,t,s,i,a){let r=this.settings;if(r.notation.fingeringMode!==B.ScoreDefault&&r.notation.fingeringMode!==B.ScoreForcePiano)return;i===Ce.Up?s-=10*this.scale:s+=3*this.scale;let n=t.notes.slice(0);n.sort(((e,t)=>e.realValue-t.realValue));for(let i=0;i<n.length;i++){let o=n[i],h=null;o.leftHandFinger!==f.Unknown?h=j.fingerToString(r,t,o.leftHandFinger,!0):o.rightHandFinger!==f.Unknown&&(h=j.fingerToString(r,t,o.rightHandFinger,!1)),h&&(e.fillText(h,s,a),a-=0|e.font.size)}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Zr(0,0,1.5,3)),this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let e=0;switch(this.bar.clef){case r.Neutral:e=this.bar.staff.standardNotationLineCount-1;break;case r.F4:e=2;break;case r.C3:e=4;break;case r.C4:e=2;break;case r.G2:e=6}this.createStartSpacing(),this.addPreBeatGlyph(new Qr(0,this.getScoreY(e)+.5*Ya.StaffLineThickness,this.bar.clef,this.bar.clefOttava))}(0===this.index&&this.bar.masterBar.keySignature!==L.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.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new Jr(0,this.getScoreHeight(-.5),this.bar.index+1))}createBeatGlyphs(){for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];this.hasVoiceContainer(t)&&this.createVoiceGlyphs(t)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new $r(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Kr(0,this.getScoreHeight(-.5),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new jr(0,0))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new Bn(0,0,2*this.scale)),this._startSpacing=!0)}createKeySignatureGlyphs(){let e=0,t=this.bar.masterBar.keySignature,s=this.bar.previousBar?this.bar.previousBar.masterBar.keySignature:0;switch(this.bar.clef){case r.Neutral:e=0;break;case r.G2:e=1;break;case r.F4:e=3;break;case r.C3:e=2;break;case r.C4:e=0}let i=new Map,a=[];if(j.keySignatureIsSharp(t))for(let s=0;s<Math.abs(t);s++){let t=Vn.SharpKsSteps[s]+e;a.push(new qr(0,this.getScoreY(t),qe.Sharp,!1)),i.set(t,!0)}else for(let s=0;s<Math.abs(t);s++){let t=Vn.FlatKsSteps[s]+e;a.push(new qr(0,this.getScoreY(t),qe.Flat,!1)),i.set(t,!0)}let n=Math.abs(s),o=j.keySignatureIsSharp(s)?Vn.SharpKsSteps:Vn.FlatKsSteps;for(let t=0;t<n;t++){let s=o[t]+e;i.has(s)||this.addPreBeatGlyph(new qr(0,this.getScoreY(o[t]+e),qe.Natural,!1))}for(let e of a)this.addPreBeatGlyph(e)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Bn(0,0,5*this.scale));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new Mn(0,this.getScoreY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,s=e.beats.length;t<s;t++){let s=e.beats[t],i=new Gn(s,this.getVoiceContainer(e));i.preNotes=new Cn,i.onNotes=new Nn,this.addBeatGlyph(i)}}getNoteLine(e){return this.accidentalHelper.getNoteLine(e)}getScoreY(e){return this._firstLineY+this.lineOffset+this.getScoreHeight(e)}getScoreHeight(e){return this.lineOffset/2*e}paintBackground(e,t,s){super.paintBackground(e,t,s);let i=this.resources;s.color=i.staffLineColor;for(let i=0;i<this.bar.staff.standardNotationLineCount;i++){const a=t+this.y+this.getScoreY(2*i);s.fillRect(e+this.x,0|a,this.width,this.scale*Ya.StaffLineThickness)}s.color=i.mainGlyphColor,this.paintSimileMark(e,t,s)}completeBeamingHelper(e){if(this.bar.isMultiVoice&&e.highestNoteInHelper&&e.lowestNoteInHelper){let t=this.getNoteY(e.highestNoteInHelper,je.Center),s=this.getNoteY(e.lowestNoteInHelper,je.Center),i=this.getStemSize(e);e.hasTuplet&&(i+=2*this.resources.effectFont.size),e.direction==Ce.Up?t-=i:s+=i;for(const i of e.beats)this.helpers.collisionHelper.reserveBeatSlot(i,t,s)}}}Vn.StaffId="score",Vn.SharpKsSteps=[-1,2,-2,1,4,0,3],Vn.FlatKsSteps=[3,0,4,1,5,2,6];class Hn extends ba{get staffId(){return Vn.StaffId}create(e,t){return new Vn(e,t)}constructor(){super()}}class Wn extends Wi{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=12*this.scale,r=3*this.scale,n=0,o=0,h=0,l=0;switch(this._inType){case b.IntoFromBelow:h=e+i.x+i.getNoteX(this._startNote,Qe.Left),l=t+i.y+i.getNoteY(this._startNote,je.Center),n=h-a,o=t+i.y+i.getNoteY(this._startNote,je.Center)+r;break;case b.IntoFromAbove:h=e+i.x+i.getNoteX(this._startNote,Qe.Left),l=t+i.y+i.getNoteY(this._startNote,je.Center),n=h-a,o=t+i.y+i.getNoteY(this._startNote,je.Center)-r;break;default:return}this.paintSlideLine(s,!1,n,h,o,l)}paintSlideOut(e,t,s){let i=this.renderer,a=12*this.scale,r=3*this.scale,n=0,o=0,h=0,l=0,c=!1;const d=2*this.scale;switch(this._outType){case S.Shift:case S.Legato:if(n=e+i.x+i.getBeatX(this._startNote.beat,Ye.PostNotes),o=t+i.y+i.getNoteY(this._startNote,je.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?(h=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,Ye.OnNotes)-d,l=t+s.y+s.getNoteY(this._startNote.slideTarget,je.Center)):(h=e+i.x+i.width,l=o),this._startNote.slideTarget.fret>this._startNote.fret?(o+=r,l-=r):(o-=r,l+=r)}else h=e+i.x+this._parent.x,l=o;break;case S.OutUp:n=e+i.x+i.getNoteX(this._startNote,Qe.Right),o=t+i.y+i.getNoteY(this._startNote,je.Center),h=n+a-d,l=t+i.y+i.getNoteY(this._startNote,je.Center)-r;break;case S.OutDown:n=e+i.x+i.getNoteX(this._startNote,Qe.Right),o=t+i.y+i.getNoteY(this._startNote,je.Center),h=n+a-d,l=t+i.y+i.getNoteY(this._startNote,je.Center)+r;break;case S.PickSlideDown:n=e+i.x+i.getNoteX(this._startNote,Qe.Right),o=t+i.y+i.getNoteY(this._startNote,je.Center),h=e+i.x+i.getBeatX(this._startNote.beat,Ye.EndBeat),l=o+3*r,c=!0;break;case S.PickSlideUp:n=e+i.x+i.getNoteX(this._startNote,Qe.Right),o=t+i.y+i.getNoteY(this._startNote,je.Center),h=e+i.x+i.getBeatX(this._startNote.beat,Ye.EndBeat),l=o-3*r,c=!0;break;default:return}this.paintSlideLine(s,c,n,h,o,l)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new Fr(0,0,_.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 zn extends rn{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?Ce.Up:zn.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?Ce.Up:Ce.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,je.Center):this.tieDirection===Ce.Up?this.startNoteRenderer.getNoteY(this.startNote,je.Top):this.startNoteRenderer.getNoteY(this.startNote,je.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20*this.scale:this.startNoteRenderer.getNoteX(this.startNote,Qe.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,Qe.Left):this.endNoteRenderer.getNoteX(this.endNote,Qe.Center)}}class Un extends zn{constructor(e,t,s,i=!1){super(e,t,i),this._direction=zn.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!==zn.getBeamDirectionForNote(e))return!1;switch(this._direction){case Ce.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 Ce.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 Xn extends qi{constructor(e,t){super(e,t),this._bend=null,this._effectSlurs=[]}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 zn(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){let t=new zn(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new zn(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 Un(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 Un(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==b.None||e.slideOutType!==S.None){let t=new Wn(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new Sn;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class Yn extends Wi{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 e=this._note,t=e.fret-e.beat.voice.bar.staff.transpositionPitch;if(e.harmonicType===m.Natural&&0!==e.harmonicValue&&(t=e.harmonicValue-e.beat.voice.bar.staff.transpositionPitch),e.isTieDestination)0===e.beat.index&&this.renderer.settings.notation.notationMode==T.GuitarPro||(e.bendType===l.Bend||e.bendType===l.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(k.TabNotesOnTiedBends)?this._noteString="("+(e.tieOrigin.fret-e.beat.voice.bar.staff.transpositionPitch).toString()+")":this._noteString="";else if(this._noteString=e.isDead?"x":t.toString(),e.isGhost)this._noteString="("+this._noteString+")";else if(e.harmonicType===m.Natural){let e=this._noteString.indexOf(String.fromCharCode(46));e>=0&&(this._noteString=this._noteString.substr(0,e+2)),this._noteString="<"+this._noteString+">"}if(e.isTrill)this._trillNoteString="("+(e.trillFret-e.beat.voice.bar.staff.transpositionPitch).toString()+")";else if(j.isAlmostEqualTo(e.harmonicValue,0))this._trillNoteString="";else switch(e.harmonicType){case m.Artificial:case m.Pinch:case m.Tap:case m.Semi:case m.Feedback:let s=(t+e.harmonicValue).toString(),i=s.indexOf(String.fromCharCode(46));i>=0&&(s=s.substr(0,i+2)),this._trillNoteString="<"+s+">";break;default:this._trillNoteString=""}if(this.isEmpty=!this._noteString,!this.isEmpty){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.tablatureFont,this.noteStringWidth=this.renderer.scoreRenderer.canvas.measureText(this._noteString)*this.scale,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.scale+this.renderer.scoreRenderer.canvas.measureText(this._trillNoteString),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*this.scale,t+this.y),this.renderer.scoreRenderer.canvas.font=r,s.fillText(this._noteString,a,t+this.y)}buildBoundingsLookup(e,t,s){let i=new ki;i.note=this._note,i.noteHeadBounds=new rt,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 qn extends Wi{constructor(e,t,s){super(e,t),this._notes=[],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 Qe.Left:break;case Qe.Center:i+=s.noteStringWidth/2;break;case Qe.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 je.Top:case je.TopWithStem:i-=s.height/2+2*this.scale;break;case je.Center:break;case je.Bottom:case je.BottomWithStem:i+=s.height/2}return i}return 0}doLayout(){let e=0,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,je.Center)+s/2,a=7*this.scale;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){e+=this.x,t+=this.y;let i=this.renderer.resources,a=s.textBaseline;s.textBaseline=C.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 Jn extends Ui{constructor(e,t,s,i){super(e,t,1,pn.getSymbol(i)),this._isVisibleRest=s,this._duration=i}doLayout(){this._isVisibleRest?this.width=pn.getSize(this._duration)*this.scale:this.width=10*this.scale}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 jn extends Ka{constructor(){super(...arguments),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 e=this.renderer;if(this.container.beat.isRest){let t=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),s=e.getTabY(t);const i=new Jn(0,s,e.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&&e.showRests){this.addGlyph(new Bn(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new tn(0,s,1.5*this.scale))}}else{let t=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==g.None;const s=new qn(0,0,t);this.noteNumbers=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper;for(let e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);if(this.addGlyph(s),this.container.beat.hasWhammyBar){let e=new _n(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!this.noteNumbers.beatEffects.has("tremolo")){let e=0,t=this.container.beat.tremoloSpeed;switch(t){case u.ThirtySecond:e=10;break;case u.Sixteenth:e=5;break;case u.Eighth:e=0}this.noteNumbers.beatEffects.set("tremolo",new dn(5*this.scale,e*this.scale,t))}if(this.container.beat.dots>0&&e.settings.notation.rhythmMode!==w.Hidden){this.addGlyph(new Bn(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++)this.addGlyph(new tn(0,e.lineOffset*e.bar.staff.tuning.length+e.settings.notation.rhythmHeight*e.scale,1.5*this.scale))}}if(!this.glyphs)return;let t=0;for(let e=0,s=this.glyphs.length;e<s;e++){let s=this.glyphs[e];s.x=t,s.renderer=this.renderer,s.doLayout(),t+=s.width}this.width=t,this.computedWidth=t,this.container.beat.isEmpty?this.centerX=this.width/2:this.container.beat.isRest?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.centerX=this.noteNumbers.x+this.noteNumbers.noteStringWidth/2}updateBeamingHelper(){this.container.beat.isRest?this.restGlyph.updateBeamingHelper(this.container.x+this.x):this.noteNumbers.updateBeamingHelper(this.container.x+this.x)}createNoteGlyph(e){let t=this.renderer,s=new Yn(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 Qn extends Wi{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10*this.scale}paint(e,t,s){let i=this.renderer,a=t+this.x+i.getNoteY(this._beat.maxStringNote,je.Top),r=t+this.y+i.getNoteY(this._beat.minStringNote,je.Bottom),n=e+this.x+this.width/2|0,o=8*this.scale;if(this._beat.brushType!==c.None){if(this._beat.brushType===c.BrushUp||this._beat.brushType===c.BrushDown)s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke();else if(this._beat.brushType===c.ArpeggioUp){let t=new Fr(0,0,_.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let i=a,n=r-o;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4*this.scale,n,-90),t.paint(0,-t.height/2,s),s.endRotate()}else if(this._beat.brushType===c.ArpeggioDown){let t=new Fr(0,0,_.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let i=a+o,n=r;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4*this.scale,i,90),t.paint(0,-t.height/2,s),s.endRotate()}this._beat.brushType===c.BrushUp||this._beat.brushType===c.ArpeggioUp?(s.beginPath(),s.moveTo(n,r),s.lineTo(n+o/2,r-o),s.lineTo(n-o/2,r-o),s.closePath(),s.fill()):(s.beginPath(),s.moveTo(n,a),s.lineTo(n+o/2,a+o),s.lineTo(n-o/2,a+o),s.closePath(),s.fill())}}}class $n extends $a{doLayout(){this.container.beat.brushType===c.None||this.container.beat.isRest||(this.addGlyph(new Qn(this.container.beat)),this.addGlyph(new Bn(0,0,4*this.scale))),super.doLayout()}constructor(){super()}}class Kn extends Wi{constructor(e,t){super(e,t)}doLayout(){this.width=28*this.scale}paint(e,t,s){let i=this.renderer.bar.staff.tuning.length,a=i<=4?N.FourStringTabClef:N.SixStringTabClef,r=i<=4?i/4.5:i/6.5;s.fillMusicFontSymbol(e+this.x+5*this.scale,t+this.y,r*this.scale,a,!1)}}class Zn extends Ln{get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?Xi.GraceScale:1}}class eo extends Ya{constructor(e,t){super(e,t),this._firstLineY=0,this._tupletSize=0,this.showTimeSignature=!1,this.showRests=!1,this.showTiedNotes=!1,this._startSpacing=!1}get lineOffset(){return(eo.TabLineSpacing+1)*this.scale}updateSizes(){let e=this.resources,t=(e.tablatureFont.size/2+.2*e.tablatureFont.size)*this.scale;this.topPadding=t,this.bottomPadding=t,this.height=this.lineOffset*(this.bar.staff.tuning.length-1)+2*t,this.settings.notation.rhythmMode!==w.Hidden&&(this.height+=this.settings.notation.rhythmHeight*this.settings.display.scale,this.bottomPadding+=this.settings.notation.rhythmHeight*this.settings.display.scale),this.updateFirstLineY(),super.updateSizes()}updateFirstLineY(){let e=this.resources;this._firstLineY=(e.tablatureFont.size/2+.2*e.tablatureFont.size)*this.scale}doLayout(){if(this.updateFirstLineY(),super.doLayout(),this.settings.notation.rhythmMode!==w.Hidden){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._tupletSize=.8*this.resources.effectFont.size,this.registerOverflowBottom(this._tupletSize))}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Zr(0,0,1.5,3)),this.isFirstOfLine){let e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new Kn(5*this.scale,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.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new Jr(0,this.getTabHeight(-.5),this.bar.index+1))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new Bn(0,0,2*this.scale)),this._startSpacing=!0)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Bn(0,0,5*this.scale));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new Zn(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,s=e.beats.length;t<s;t++){let s=e.beats[t],i=new Xn(s,this.getVoiceContainer(e));i.preNotes=new $n,i.onNotes=new jn,this.addBeatGlyph(i)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new $r(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Kr(0,this.getTabY(-1),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new jr(0,0))}getTabY(e){return this._firstLineY+this.getTabHeight(e)}getTabHeight(e){return this.lineOffset*e}get middleYPosition(){return this.getTabY(this.bar.staff.tuning.length-1)}paintBackground(e,t,s){super.paintBackground(e,t,s);let i=this.resources;s.color=i.staffLineColor;let a=this.scale,r=[];for(let e=0,t=this.bar.staff.tuning.length;e<t;e++)r.push([]);for(let e of this.bar.voices)if(this.hasVoiceContainer(e)){let t=this.getVoiceContainer(e);for(let e of t.beatGlyphs){let s=e.onNotes,i=s.noteNumbers;if(i)for(const[n,o]of i.notesPerString)o.isEmpty||r[this.bar.staff.tuning.length-n].push(new Float32Array([t.x+e.x+s.x+i.x,i.width+a]))}}for(let e of r)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));for(let i=0,a=this.bar.staff.tuning.length;i<a;i++){const a=this.getTabY(i);let n=0;for(let o of r[i])s.fillRect(e+this.x+n,t+this.y+a|0,o[0]-n,this.scale*Ya.StaffLineThickness),n=o[0]+o[1];s.fillRect(e+this.x+n,t+this.y+a|0,this.width-n,this.scale*Ya.StaffLineThickness)}s.color=i.mainGlyphColor,this.paintSimileMark(e,t,s)}paint(e,t,s){super.paint(e,t,s),this.settings.notation.rhythmMode!==w.Hidden&&(this.paintBeams(e,t,s),this.paintTuplets(e,t,s))}paintBeams(e,t,s){for(let i=0,a=this.helpers.beamHelpers.length;i<a;i++){let a=this.helpers.beamHelpers[i];for(let i=0,r=a.length;i<r;i++){let r=a[i];this.paintBeamHelper(e+this.beatGlyphsStart,t,s,r)}}}paintTuplets(e,t,s){for(let i of this.bar.voices)if(this.hasVoiceContainer(i)){let a=this.getVoiceContainer(i);for(let i of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,i)}}paintBeamHelper(e,t,s,i){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(1===i.beats.length||this.settings.notation.rhythmMode===w.ShowWithBeams?this.paintFooter(e,t,s,i):this.paintBar(e,t,s,i))}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)){let n=i.getBeatLineX(r),o=t+this.y,h=t+this.y+this.height-this._tupletSize,l=this.getOnNotesGlyphForBeat(r);l.noteNumbers&&r.duration!==u.Half?o+=l.noteNumbers.getNoteY(l.noteNumbers.minStringNote,je.Bottom)+this.lineOffset/2:o+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(r,t+this.y,e+this.x+n,o,h,s);let c=6*this.scale,d=-6*this.scale,p=3*this.scale,g=j.getIndex(r.duration)-2,f=h;for(let t=0;t<g;t++){let o=0,h=0,l=0,u=0,g=f+t*d;if(1===i.beats.length)o=n,h=n+c,l=g,u=g,eo.paintSingleBar(s,e+this.x+o,l,e+this.x+h,u,p);else if(a<i.beats.length-1){if(xa.isFullBarJoin(r,i.beats[a+1],t))o=n,h=i.getBeatLineX(i.beats[a+1]);else{if(0!==a&&xa.isFullBarJoin(i.beats[a-1],r,t))continue;o=n,h=o+c}l=g,u=g,eo.paintSingleBar(s,e+this.x+o,l,e+this.x+h,u,p)}else a>0&&!xa.isFullBarJoin(r,i.beats[a-1],t)&&(o=n-c,h=n,l=g,u=g,eo.paintSingleBar(s,e+this.x+o,l,e+this.x+h,u,p))}}}}paintTupletHelper(e,t,s,i){let a,r=this.resources,n=s.textAlign,o=s.textBaseline;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=P.Center,s.textBaseline=C.Middle;let h=i.beats[0].tupletNumerator,l=i.beats[0].tupletDenominator;if(a=2===h&&3===l?"2":3===h&&2===l?"3":4===h&&6===l?"4":5===h&&4===l?"5":6===h&&4===l?"6":7===h&&4===l?"7":9===h&&8===l?"9":10===h&&8===l?"10":11===h&&8===l?"11":12===h&&8===l?"12":13===h&&8===l?"13":h+":"+l,1!==i.beats.length&&i.isFull){let n=i.beats[0],o=i.beats[i.beats.length-1],h=this.helpers.beamHelperLookup[i.voice.index].get(n.index),l=this.helpers.beamHelperLookup[i.voice.index].get(o.index);if(h&&l){let i=h.getBeatLineX(n),c=l.getBeatLineX(o);s.font=r.effectFont;let d=s.measureText(a),u=3*this.scale,p=(i+c)/2,g=p-d/2-u,f=p+d/2+u,m=t+this.y+this.height-this._tupletSize+.5*r.effectFont.size,y=.25*-r.effectFont.size,b=-5*this.scale;s.beginPath(),s.moveTo(e+this.x+i,m-y|0),s.lineTo(e+this.x+i,m-y-b|0),s.lineTo(e+this.x+g,m-y-b|0),s.stroke(),s.beginPath(),s.moveTo(e+this.x+f,m-y-b|0),s.lineTo(e+this.x+c,m-y-b|0),s.lineTo(e+this.x+c,m-y|0),s.stroke(),s.fillText(a,e+this.x+p,m-y-b)}}else for(let n=0,o=i.beats.length;n<o;n++){let o=i.beats[n],h=this.helpers.beamHelperLookup[i.voice.index].get(o.index);if(!h)continue;let l=h.getBeatLineX(o),c=t+this.y+this.height-this._tupletSize+.5*r.effectFont.size;s.font=r.effectFont,s.fillText(a,e+this.x+l,c)}s.textAlign=n,s.textBaseline=o}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()}paintBeamingStem(e,t,s,i,a,r){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()}paintFooter(e,t,s,i){for(let a of i.beats){if(a.graceType!==g.None||a.duration===u.Whole||a.duration===u.DoubleWhole||a.duration===u.QuadrupleWhole)return;let r=i.getBeatLineX(a),n=t+this.y,o=t+this.y+this.height-this._tupletSize,h=this.getOnNotesGlyphForBeat(a);if(h.noteNumbers&&a.duration!==u.Half?n+=h.noteNumbers.getNoteY(h.noteNumbers.minStringNote,je.Bottom):n+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(a,t+this.y,e+this.x+r,n,o,s),a.duration>u.Quarter){let t=new Yi(0,0,a.duration,Ce.Down,!1);t.renderer=this,t.doLayout(),t.paint(e+this.x+r,o,s)}}}}eo.StaffId="tab",eo.TabLineSpacing=10;class to extends ba{get staffId(){return eo.StaffId}constructor(e,t,s){super(),this._showTimeSignature=e,this._showRests=t,this._showTiedNotes=s,this.hideOnPercussionTrack=!0}canCreate(e,t){return t.tuning.length>0&&super.canCreate(e,t)}create(e,t){let s=new eo(e,t);return s.showRests=this._showRests,s.showTimeSignature=this._showTimeSignature,s.showTiedNotes=this._showTiedNotes,s}}class so extends zi{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+so.Padding*this.scale}paint(e,t,s){let i=this.renderer.resources;s.font=i.effectFont;let a=s.textAlign;s.textAlign=P.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+(so.Padding-1)*this.scale,s.font.size/1.6)}}so.Padding=4;class io extends mr{get notationElement(){return k.EffectTap}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new so}}class ao{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"}(Ze||(Ze={}));class ro extends ao{constructor(){super(...arguments),this.align=P.Left,this.frame=Ze.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class no extends ao{constructor(){super(...arguments),this.chord=new oe}}class oo extends ao{}class ho extends ao{}class lo extends ao{constructor(){super(...arguments),this.number=0}}class co extends ao{constructor(){super(...arguments),this.decrescendo=!1}}class uo extends ao{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class po extends ao{constructor(){super(...arguments),this.octave=1}}class go extends ao{}class fo{constructor(){this.defaultClef=r.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class mo{constructor(){this.from=0,this.to=0,this.curly=!1}}class yo{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class bo{constructor(){this._trackChannel=0,this._beamingMode=F.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new le,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 ut;try{s.parse(e)}catch(e){throw new G("Could not parse XML",e)}this.parseDom(s),this.consolidate(),this.score.finish(t)}consolidate(){let e=this.score.tempo;for(const t of this.score.tracks){const s=this._voiceCounts.get(t.index);for(const i of t.staves){for(;i.bars.length<this.score.masterBars.length;)this.addNewBar(i);for(const t of i.bars){for(;t.voices.length<s;)t.addVoice(new _e);for(const e of t.voices)if(0===e.beats.length){const t=new ne;t.isEmpty=!0,e.addBeat(t)}const i=t.masterBar;i.tempoAutomation&&(i.tempoAutomation.value!==e?e=i.tempoAutomation.value:i.tempoAutomation=null)}}}bo.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),bo.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?d.Decrescendo:d.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 G("No valid XML");if("score"!==t.localName)throw new G('Root node of XML was not "score"');this.score=new ue,this.score.tempo=120;for(let e of t.childNodes)if(e.nodeType===Ne.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===Ne.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 Se,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===Ne.Element&&"bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new mo;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===Ne.Element&&"staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new fo;t.description=e.getAttribute("description");for(let s of e.childNodes)if(s.nodeType===Ne.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 r.G2;case"bass":return r.F4;case"alto":case"tenor":return r.C4}return r.G2}parseClefOttava(e){return e.endsWith("-")?n._8vb:e.endsWith("+")?n._8va:n.Regular}parseSystems(e){for(let t of e.childNodes)if(t.nodeType===Ne.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=F.ForceSplitToNext);for(let t of e.childNodes)if(t.nodeType===Ne.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===Ne.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===Ne.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===Ne.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 H;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 le;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,r,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 yo,this._currentVoiceState.currentBarIndex=r-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=Ce.Up;break;case"down":this._currentVoiceState.voiceStemDir=Ce.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const h=n.findChildElement("noteObjects");if(s.attributes.has("tempo")&&(this._currentBar.masterBar.tempoAutomation=new V,this._currentBar.masterBar.tempoAutomation.isLinear=!0,this._currentBar.masterBar.tempoAutomation.type=a.Tempo,this._currentBar.masterBar.tempoAutomation.value=parseInt(s.attributes.get("tempo"))),h)for(let e of h.childNodes)if(e.nodeType===Ne.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 ne;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 _e);(!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 Z;for(let a of t.childNodes)if(a.nodeType===Ne.Element)switch(a.localName){case"stem":switch(a.getAttribute("dir")){case"up":e.preferredBeamDirection=Ce.Up;break;case"down":e.preferredBeamDirection=Ce.Down}break;case"articulation":switch(a.getAttribute("type")){case"staccato":s.isStaccato=!0;break;case"normalAccent":s.accentuated=i.Normal;break;case"strongAccent":s.accentuated=i.Heavy}break;case"lyric":this.parseLyric(e,a);break;case"drawObjects":this.parseBeatDrawObject(e,a);break;case"heads":this.parseHeads(e,s,a);break;case"beam":switch(a.getAttribute("group")){case"force":e.beamingMode=F.ForceMergeWithNext;break;case"divide":e.beamingMode=F.ForceSplitToNext}}}parseHeads(e,t,s){for(let i of s.childNodes)if(i.nodeType===Ne.Element&&"head"===i.localName)this.parseHead(e,t,i)}parseHead(e,t,s){const i=new Z,a=j.parseTuning(s.getAttribute("pitch"));i.octave=a.octave-1,i.tone=a.noteValue,i.isStaccato=t.isStaccato,i.accentuated=t.accentuated,e.addNote(i);for(let e of s.childNodes)if(e.nodeType===Ne.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===Ne.Element&&"drawObj"===s.localName){const t=this.parseDrawObj(s);if(t)if(t instanceof ro)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new ot,e.fermata.type=xe.Medium):"f"===t.text?e.dynamics=p.F:"j"===t.text&&(e.dynamics=p.MF):this._isFirstSystem&&""===this.score.title&&t.align===P.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===P.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===P.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof no);else if(t instanceof ho)e.vibrato=_.Slight;else if(t instanceof co)e.crescendo=t.decrescendo?d.Decrescendo:d.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof oo){const s=t;this._slurs.set(e,s)}else t instanceof uo&&this.applyVolta(t)}}parseBarDrawObject(e){for(let t of e.childNodes)if(t.nodeType===Ne.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof uo&&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===Ne.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 ne;return s.beamingMode=this._beamingMode,this.parseDuration(e,s,t),s}if(1===parseInt(s)){let e=new ne;return e.beamingMode=this._beamingMode,e.duration=u.Whole,e}return q.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return u.DoubleWhole;case"1/1":return u.Whole;case"1/2":return u.Half;case"1/4":return u.Quarter;case"1/8":return u.Eighth;case"1/16":return u.Sixteenth;case"1/32":return u.ThirtySecond;case"1/64":return u.SixtyFourth;case"1/128":return u.OneHundredTwentyEighth;default:return q.warning("Importer","Unsupported duration"),u.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===Ne.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof ro)switch(e.align){case P.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case P.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(let t of e.childNodes)if(t.nodeType===Ne.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===Ne.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 go}parseOctaveClef(e){const t=new po;return e.attributes.has("octave")&&(t.octave=parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new uo;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 co;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new lo;return e.attributes.has("number")&&(t.number=parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new ho}parseSlur(e){return new oo}parseGuitar(e){const t=new no,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 ro;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=P.Left;break;case"center":t.align=P.Center;break;case"right":t.align=P.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=Ze.Rectangle;break;case"ellipse":t.frame=Ze.Ellipse;break;case"circle":t.frame=Ze.Circle;break;case"none":t.frame=Ze.None}if(e.firstElement){for(let s of e.childNodes)if(s.nodeType===Ne.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===Ne.Element)switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class So extends R{get name(){return"Capella"}constructor(){super()}readScore(){q.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new Nt(this.data).read(),q.debug(this.name,"Zip entries loaded"),e.length>0){for(let s of e)if("score.xml"===s.fileName)t=Be.toString(s.data,this.settings.importer.encoding)}else this.data.reset(),t=Be.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new G("No valid capella file");q.debug(this.name,"Start Parsing score.xml");try{let e=new bo;return e.parseXml(t,this.settings),q.debug(this.name,"score.xml parsed"),e.score}catch(e){throw new G("Failed to parse CapXML",e)}}}class _o{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 wo{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 Bo(e,t,s){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var i;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]}if("function"!=typeof i)throw new TypeError("Object not disposable.");e.stack.push({value:t,dispose:i,async:s})}else s&&e.stack.push({async:!0});return t}var To="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 ko(e){function t(t){e.error=e.hasError?new To(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}return function s(){for(;e.stack.length;){var i=e.stack.pop();try{var a=i.dispose&&i.dispose.call(i.value);if(i.async)return Promise.resolve(a).then(s,(function(e){return t(e),s()}))}catch(e){t(e)}}if(e.hasError)throw e.error}()}class vo{static enable(e,t){vo.alphaSkia=t,vo.initializeMusicFont(vo.alphaSkia.AlphaSkiaTypeface.register(e))}static initializeMusicFont(e){vo.musicFont=e}static registerFont(e,t){const s=vo.alphaSkia.AlphaSkiaTypeface.register(e.buffer);t||(t=As.withFamilyList([s.familyName],12,s.isItalic?Ge.Italic:Ge.Plain,s.isBold?Ve.Bold:Ve.Regular));for(const e of t.families)this.customTypeFaces.set(vo.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.settings.display.scale)){if(this._typeFaceIsSystem){const e={stack:[],error:void 0,hasError:!1};try{Bo(e,this._typeFace,!1)}catch(t){e.error=t,e.hasError=!0}finally{ko(e)}}for(const t of this.font.families){var e=vo.customTypefaceKey(t,this.font.isBold,this.font.isItalic);vo.customTypeFaces.has(e)?(this._typeFaceIsSystem=!1,this._typeFace=vo.customTypeFaces.get(e)):(this._typeFaceIsSystem=!0,this._typeFace=vo.alphaSkia.AlphaSkiaTypeface.create(t,this.font.isBold,this.font.isItalic))}this._typeFaceCache=this.font.toCssString(this.settings.display.scale)}return this._typeFace}constructor(){this._color=new fe(0,0,0,0),this._lineWidth=0,this._typeFaceCache="",this._typeFaceIsSystem=!1,this._typeFace=null,this.font=new As("Arial",10,Ge.Plain),this.textAlign=P.Left,this.textBaseline=C.Top,this._canvas=new vo.alphaSkia.AlphaSkiaCanvas,this.color=new fe(0,0,0,255)}destroy(){const e={stack:[],error:void 0,hasError:!1};try{Bo(e,this._canvas,!1)}catch(t){e.error=t,e.hasError=!0}finally{ko(e)}}onRenderFinished(){return null}beginRender(e,t){this._canvas.beginRender(e,t,Po.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=vo.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(0|e,0|t,s,i)}strokeRect(e,t,s,i){this._canvas.strokeRect(0|e,0|t,s,i)}beginPath(){this._canvas.beginPath()}closePath(){this._canvas.closePath()}moveTo(e,t){this._canvas.moveTo(e,t)}lineTo(e,t){this._canvas.lineTo(e,t)}quadraticCurveTo(e,t,s,i){this._canvas.quadraticCurveTo(e,t,s,i)}bezierCurveTo(e,t,s,i,a,r){this._canvas.bezierCurveTo(e,t,s,i,a,r)}fillCircle(e,t,s){this._canvas.fillCircle(e,t,s)}strokeCircle(e,t,s){this._canvas.strokeCircle(e,t,s)}fill(){this._canvas.fill()}stroke(){this._canvas.stroke()}beginGroup(e){}endGroup(){}fillText(e,t,s){if(0==e.length)return;let i=vo.alphaSkia.AlphaSkiaTextAlign.Left;switch(this.textAlign){case P.Left:i=vo.alphaSkia.AlphaSkiaTextAlign.Left;break;case P.Center:i=vo.alphaSkia.AlphaSkiaTextAlign.Center;break;case P.Right:i=vo.alphaSkia.AlphaSkiaTextAlign.Right}let a=vo.alphaSkia.AlphaSkiaTextBaseline.Top;switch(this.textBaseline){case C.Top:a=vo.alphaSkia.AlphaSkiaTextBaseline.Top;break;case C.Middle:a=vo.alphaSkia.AlphaSkiaTextBaseline.Middle;break;case C.Bottom:a=vo.alphaSkia.AlphaSkiaTextBaseline.Bottom}this._canvas.fillText(e,this.getTypeFace(),this.font.size*this.settings.display.scale,t,s,i,a)}measureText(e){return this._canvas.measureText(e,this.getTypeFace(),this.font.size*this.settings.display.scale)}fillMusicFontSymbol(e,t,s,i,a){i!==N.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(let e of i)e!==N.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){this._canvas.fillText(i,vo.musicFont,Po.MusicFontSize*this.settings.display.scale*s,e,t,a?vo.alphaSkia.AlphaSkiaTextAlign.Center:vo.alphaSkia.AlphaSkiaTextAlign.Left,vo.alphaSkia.AlphaSkiaTextBaseline.Alphabetic)}beginRotate(e,t,s){this._canvas.beginRotate(e,t,s)}endRotate(){this._canvas.endRotate()}}vo.musicFont=null,vo.customTypeFaces=new Map;class xo{constructor(e,t){this.vertical=e,this.createLayout=t}}class No{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class Po{static createStyleElement(e,t){let s=e.getElementById("alphaTabStyle");if(!s){if(!t)return void q.error("AlphaTab","Font directory could not be detected, cannot create style element");s=e.createElement("style"),s.id="alphaTabStyle";let i=`\n @font-face {\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 } \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: ${Po.MusicFontSize}px;\n overflow: visible !important;\n }`;s.innerHTML=i,e.getElementsByTagName("head").item(0).appendChild(s),Po.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===Po._globalThis){try{Po._globalThis=globalThis}catch(e){}void 0===Po._globalThis&&(Po._globalThis=self),void 0===Po._globalThis&&(Po._globalThis=global),void 0===Po._globalThis&&(Po._globalThis=window),void 0===Po._globalThis&&(Po._globalThis=Function("return this")())}return this._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in Po.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in Po.globalThis}static throttle(e,t){let s=0;return()=>{Po.globalThis.clearTimeout(s),s=Po.globalThis.setTimeout(e,t)}}static detectScriptFile(){if(!Po.isRunningInWorker&&Po.globalThis.ALPHATAB_ROOT){let e=Po.globalThis.ALPHATAB_ROOT;return e=Po.ensureFullUrl(e),e=Po.appendScriptName(e),e}try{const e=import.meta.url;if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in Po.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=Po.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(!Po.isRunningInWorker&&Po.globalThis.ALPHATAB_FONT)return Po.ensureFullUrl(Po.globalThis.ALPHATAB_FONT);const e=Po.scriptFile;if(e){let t=e.lastIndexOf(String.fromCharCode(47));if(t>=0)return e.substr(0,t)+"/font/"}return null}static registerJQueryPlugin(){if(!Po.isRunningInWorker&&Po.globalThis&&"jQuery"in Po.globalThis){let e=Po.globalThis.jQuery,t=new fa;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:fa.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&Po.renderEngines.has(e)?Po.renderEngines.get(e):Po.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&Po.layoutEngines.has(t)?Po.layoutEngines.get(t):Po.layoutEngines.get(e.Page)}static buildImporters(){return[new st,new Mt,new Pt,new It,new So,new tt]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new No(!0,(()=>new ya))),e.set("default",e.get("svg")),e.set("skia",new No(!1,(()=>new vo))),Po.createPlatformSpecificRenderEngines(e),e}static enableAlphaSkia(e,t){vo.enable(e,t)}static registerAlphaSkiaCustomFont(e,t){return vo.registerFont(e,t)}static createPlatformSpecificRenderEngines(e){e.set("html5",new No(!1,(()=>new Ci)))}static createDefaultStaveProfiles(){const e=new Map;e.set(t.ScoreTab,[new er("score-effects",[new Dr,new Vr,new Br,new Ar,new rr,new gr,new Hr,new Or,new kr(!0),new Wr,new Er,new zr,new Lr,new io,new ir]),new Hn,new er("tab-effects",[new hr,new kr(!1),new cr,new wr,new Or,new Wr,new Er,new zr,new Lr,new Mr,new ur,new br(m.Natural),new br(m.Artificial),new br(m.Pinch),new br(m.Tap),new br(m.Semi),new br(m.Feedback),new Sr,new ar,new fr,new vr,new Pr,new xr,new io]),new to(!1,!1,!1)]),e.set(t.Score,[new er("score-effects",[new Dr,new Vr,new Br,new Ar,new rr,new gr,new Hr,new Or,new kr(!0),new Wr,new Er,new zr,new Lr,new ur,new Sr,new vr,new Pr,new xr,new io,new ir]),new Hn,new er("score-bottom-effects",[new hr,new kr(!1),new cr,new wr])]);let s=[new Dr,new Vr,new Br,new Ar,new rr,new gr,new Or,new Wr,new Er,new zr,new Lr,new Mr,new ur,new br(m.Artificial),new br(m.Pinch),new br(m.Tap),new br(m.Semi),new br(m.Feedback),new Sr,new ar,new fr,new vr,new Pr,new xr,new io,new ir];return e.set(t.Tab,[new er("tab-effects",s),new to(!0,!0,!0),new er("tab-bottom-effects",[new wr])]),e.set(t.TabMixed,[new er("tab-effects",s),new to(!1,!1,!1),new er("tab-bottom-effects",[new wr])]),e}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.Page,new xo(!0,(e=>new Yr(e)))),t.set(e.Horizontal,new xo(!1,(e=>new Xr(e)))),t}static initializeMain(e,t){Po.isRunningInWorker||Po.isRunningInAudioWorklet||(Po.webPlatform!==Ue.Browser&&Po.webPlatform!==Ue.BrowserModule||(Po.registerJQueryPlugin(),Po.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in Po.globalThis||(Po.globalThis.ResizeObserver=_o),"IntersectionObserver"in Po.globalThis||(Po.globalThis.IntersectionObserver=wo),"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)})),Po.createWebWorker=e,Po.createAudioWorklet=t)}static get alphaTabWorker(){return this.globalThis.Worker}static initializeWorker(){if(!Po.isRunningInWorker)throw new O(s.General,"Not running in worker, cannot run worker initialization");Pi.init(),bi.init(),Po.createWebWorker=e=>{throw new O(s.General,"Nested workers are not supported")}}static initializeAudioWorklet(){if(!Po.isRunningInAudioWorklet)throw new O(s.General,"Not running in audio worklet, cannot run worklet initialization");ca.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 Ue.NodeJs}catch(e){}try{const e=import.meta.url;if(e&&"string"==typeof e&&!e.startsWith("file://"))return Ue.BrowserModule}catch(e){}return Ue.Browser}}Po.MusicFontSize=34,Po.HighDpiFactor=1,Po._globalThis=void 0,Po.webPlatform=Po.detectWebPlatform(),Po.isWebPackBundled=Po.detectWebPack(),Po.isViteBundled=Po.detectVite(),Po.scriptFile=Po.detectScriptFile(),Po.fontDirectory=Po.detectFontDirectory(),Po.bravuraFontChecker=new sa(["alphaTab"]),Po.renderEngines=Po.createDefaultRenderEngines(),Po.layoutEngines=Po.createDefaultLayoutEngines(),Po.staveProfiles=Po.createDefaultStaveProfiles();class Co{constructor(){this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=v.Info,this.useWorkers=!0,this.includeNoteBounds=!1,this.scriptFile=Po.scriptFile,this.fontDirectory=Po.fontDirectory}}class Eo{}Eo.version="1.3.0",Eo.date="2024-05-15T11:07:17.263Z";var Fo,Lo=Object.freeze({__proto__:null,ScoreImporter:R,ScoreLoader:Zi,UnsupportedFormatError:G});class Mo{init(e,t){this.data=e,this.settings=t}export(e,t=null){const s=Te.withCapacity(1024);return this.init(s,t??new Ks),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"}(Fo||(Fo={}));class Io{constructor(e,t,s=null){if(this.icon=Fo.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 Do{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new ut;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 a=0;switch(t.isStaccato&&(a|=1),t.accentuated){case i.Normal:a|=8;break;case i.Heavy:a|=4}if(a>0&&(s.addElement("Accent").innerText=a.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 _.Slight:s.addElement("Vibrato").innerText="Slight";break;case _.Wide:s.addElement("Vibrato").innerText="Wide"}if(t.isFingering){switch(t.leftHandFinger){case f.Thumb:s.addElement("LeftFingering").innerText="P";break;case f.IndexFinger:s.addElement("LeftFingering").innerText="I";break;case f.MiddleFinger:s.addElement("LeftFingering").innerText="M";break;case f.AnnularFinger:s.addElement("LeftFingering").innerText="A";break;case f.LittleFinger:s.addElement("LeftFingering").innerText="C"}switch(t.rightHandFinger){case f.Thumb:s.addElement("RightFingering").innerText="P";break;case f.IndexFinger:s.addElement("RightFingering").innerText="I";break;case f.MiddleFinger:s.addElement("RightFingering").innerText="M";break;case f.AnnularFinger:s.addElement("RightFingering").innerText="A";break;case f.LittleFinger:s.addElement("RightFingering").innerText="C"}}t.percussionArticulation>=0?s.addElement("InstrumentArticulation").innerText=t.percussionArticulation.toString():s.addElement("InstrumentArticulation").innerText="0"}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.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!==m.None){switch(t.harmonicType){case m.Natural:this.writeSimplePropertyNode(s,"HarmonicType","HType","Natural");break;case m.Artificial:this.writeSimplePropertyNode(s,"HarmonicType","HType","Artificial");break;case m.Pinch:this.writeSimplePropertyNode(s,"HarmonicType","HType","Pinch");break;case m.Tap:this.writeSimplePropertyNode(s,"HarmonicType","HType","Tap");break;case m.Semi:this.writeSimplePropertyNode(s,"HarmonicType","HType","Semi");break;case m.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 b.IntoFromAbove:i|=32;break;case b.IntoFromBelow:i|=16}switch(t.slideOutType){case S.Shift:i|=1;break;case S.Legato:i|=2;break;case S.OutDown:i|=4;break;case S.OutUp:i|=8;break;case S.PickSlideDown:i|=64;break;case S.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=ye.defaultSteps[a],o=ye.defaultAccidentals[a]};switch(h(),i){case y.Default:break;case y.ForceNone:case y.ForceNatural:o="";break;case y.ForceSharp:o="#";break;case y.ForceDoubleSharp:"#"===o&&(s-=2,h()),o="x";break;case y.ForceFlat:"#"===o&&(s+=1,h()),o="b";break;case y.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 z((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/z.MaxPosition*100}writeBeatNode(e,t,s){const i=e.addElement("Beat");if(i.attributes.set("id",t.id.toString()),i.addElement("Dynamic").innerText=p[t.dynamics],t.fadeIn&&(i.addElement("Fadding").innerText="FadeIn"),t.isTremolo)switch(t.tremoloSpeed){case u.Eighth:i.addElement("Tremolo").innerText="1/2";break;case u.Sixteenth:i.addElement("Tremolo").innerText="1/4";break;case u.ThirtySecond:i.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&i.addElement("Chord").setCData(t.chordId),t.crescendo!==d.None&&(i.addElement("Hairpin").innerText=d[t.crescendo]),t.brushType){case c.ArpeggioUp:i.addElement("Arpeggio").innerText="Up";break;case c.ArpeggioDown:i.addElement("Arpeggio").innerText="Down"}switch(t.text&&i.addElement("FreeText").setCData(t.text),t.graceType){case g.OnBeat:case g.BeforeBeat:i.addElement("GraceNotes").innerText=g[t.graceType]}if(t.ottava!==n.Regular&&(i.addElement("Ottavia").innerText=n[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 Ce.Up:i.addElement("TransposedPitchStemOrientation").innerText="Upward";break;case Ce.Down:i.addElement("TransposedPitchStemOrientation").innerText="Downward"}i.addElement("ConcertPitchStemOrientation").innerText="Undefined",t.isRest||(i.addElement("Notes").innerText=t.notes.map((e=>e.id)).join(" ")),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");t.brushDuration>0&&this.writeSimpleXPropertyNode(s,"687935489","Int",t.brushDuration.toString())}writeBeatProperties(e,t){const s=e.addElement("Properties");switch(t.brushType){case c.BrushUp:this.writeSimplePropertyNode(s,"Brush","Direction","Up");break;case c.BrushDown:this.writeSimplePropertyNode(s,"Brush","Direction","Down")}switch(t.pickStroke){case x.Up:this.writeSimplePropertyNode(s,"PickStroke","Direction","Up");break;case x.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 _.Wide:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Wide");break;case _.Slight:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Slight")}}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 u.QuadrupleWhole:r="Long";break;case u.DoubleWhole:r="DoubleWhole";break;case u.Whole:r="Whole";break;case u.Half:r="Half";break;case u.Quarter:r="Quarter";break;case u.Eighth:r="Eighth";break;case u.Sixteenth:r="16th";break;case u.ThirtySecond:r="32nd";break;case u.SixtyFourth:r="64th";break;case u.OneHundredTwentyEighth:r="128th";break;case u.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 z((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");t.masterBars.length>0&&t.masterBars[0].isAnacrusis&&s.addElement("Anacrusis");const a=i.addElement("Automation");a.addElement("Type").innerText="Tempo",a.addElement("Linear").innerText="false",a.addElement("Bar").innerText="0",a.addElement("Position").innerText="0",a.addElement("Visible").innerText="true",a.addElement("Value").innerText=`${t.tempo} 2`,t.tempoLabel&&(a.addElement("Text").innerText=t.tempoLabel);for(const e of t.masterBars)if(e.index>0&&e.tempoAutomation){const t=i.addElement("Automation");t.addElement("Type").innerText="Tempo",t.addElement("Linear").innerText=e.tempoAutomation.isLinear?"true":"false",t.addElement("Bar").innerText=e.index.toString(),t.addElement("Position").innerText=e.tempoAutomation.ratioPosition.toString(),t.addElement("Visible").innerText="true",t.addElement("Value").innerText=`${e.tempoAutomation.value} 2`,e.tempoAutomation.text&&(t.addElement("Text").innerText=e.tempoAutomation.text)}}writeAudioTracksNode(e,t){e.addElement("AudioTracks")}writeTracksNode(e,t){const s=e.addElement("Tracks");for(const e of t.tracks)this.writeTrackNode(s,e)}writeTrackNode(e,t){const s=e.addElement("Track");s.attributes.set("id",t.index.toString()),s.addElement("Name").setCData(t.name),s.addElement("ShortName").setCData(t.shortName),s.addElement("Color").innerText=`${t.color.r} ${t.color.g} ${t.color.b}`,s.addElement("SystemsDefautLayout").innerText=t.defaultSystemsLayout.toString(),s.addElement("SystemsLayout").innerText=t.systemsLayout.join(" "),s.addElement("AutoBrush"),s.addElement("PalmMute").innerText="0",s.addElement("PlayingStyle").innerText=A.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",s.addElement("UseOneChannelPerString"),s.addElement("IconId").innerText=Do.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?Do.DrumKitProgramInfo.icon:Do.MidiProgramInfoLookup.has(e.program)?Do.MidiProgramInfoLookup.get(e.program).icon:Fo.SteelGuitar}writeSoundAndAutomation(e,t,s,i,a,r,n,o=0){const h=e.addElement("Sound");h.addElement("Name").setCData(s),h.addElement("Label").setCData(s),h.addElement("Path").setCData(i),h.addElement("Role").setCData(a);const l=h.addElement("MIDI");l.addElement("LSB").innerText="0",l.addElement("MSB").innerText="0",l.addElement("Program").innerText=n.toString();const c=t.addElement("Automation");c.addElement("Type").innerText="Sound",c.addElement("Linear").innerText="false",c.addElement("Bar").innerText=r.toString(),c.addElement("Position").innerText=o.toString(),c.addElement("Visible").innerText="true",c.addElement("Value").setCData(`${i};${s};${a}`)}writeSoundsAndAutomations(e,t){const s=e.addElement("Sounds"),i=e.addElement("Automations");if(t.staves.length>0&&t.staves[0].bars.length>0){const e=`Track_${t.index}_Initial`,r=`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 c of h.beats){const h=c.getAutomation(a.Instrument),d=0===l.index&&0===c.index;if(h){const a=d?e:`ProgramChange_${c.id}`,u=d?r:`Midi/${h.value}`,p=d?n:"User";d||o||(this.writeSoundAndAutomation(s,i,e,r,n,t.staves[0].bars[0].index,t.playbackInfo.program),o=!0),this.writeSoundAndAutomation(s,i,a,u,p,l.index,h.value,h.ratioPosition),d&&(o=!0)}}}}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=[f.LittleFinger,f.AnnularFinger,f.MiddleFinger,f.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():f.IndexFinger;for(const e of i){const i=o.addElement("Position");switch(a){case f.LittleFinger:i.attributes.set("finger","Pinky");break;case f.AnnularFinger:i.attributes.set("finger","Ring");break;case f.MiddleFinger:i.attributes.set("finger","Middle");break;case f.IndexFinger:i.attributes.set("finger","Index")}i.attributes.set("fret",(s-t.firstFret+1).toString()),i.attributes.set("string",e.toString())}}}}const h=i.addElement("Property");h.attributes.set("name","ShowName"),h.attributes.set("type","bool"),h.attributes.set("value",t.showName?"true":"false");const l=i.addElement("Property");l.attributes.set("name","ShowDiagram"),l.attributes.set("type","bool"),l.attributes.set("value",t.showDiagram?"true":"false");const c=i.addElement("Property");c.attributes.set("name","ShowFingering"),c.attributes.set("type","bool"),c.attributes.set("value",t.showFingering?"true":"false");const d=i.addElement("Chord"),u=d.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=d.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=d.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const m=d.addElement("Degree");m.attributes.set("interval","Fifth"),m.attributes.set("alteration","Perfect"),m.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,s,i){const a=e.addElement("Property");a.attributes.set("name",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeSimpleXPropertyNode(e,t,s,i){const a=e.addElement("XProperty");a.attributes.set("id",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeLyricsNode(e,t){const s=e.addElement("Lyrics");s.attributes.set("dispatched","true");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 he;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($.instrumentArticulations.values());s.addElement("Name").innerText=Do.DrumKitProgramInfo.instrumentSetName,s.addElement("Type").innerText=Do.DrumKitProgramInfo.instrumentSetType;let i="",r=new ht,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 C.Top:e.addElement("TechniquePlacement").innerText="below";break;case C.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case C.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=Do.MidiProgramInfoLookup.has(t.playbackInfo.program)?Do.MidiProgramInfoLookup.get(t.playbackInfo.program):Do.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===N.None)return"";let t=N[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=I[t.keySignatureType],i.addElement("Sharps").innerText="Sharps",s.addElement("Time").innerText=`${t.timeSignatureNumerator}/${t.timeSignatureDenominator}`;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(" ")}t.tripletFeel!==D.NoTripletFeel&&(s.addElement("TripletFeel").innerText=D[t.tripletFeel]),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/W.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=xe[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=r[t.clef],t.clefOttava!==n.Regular&&(s.addElement("Ottavia").innerText=n[t.clefOttava].substr(1)),t.simileMark!==o.None&&(s.addElement("SimileMark").innerText=o[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(" ")}}Do.MidiProgramInfoLookup=new Map([[0,new Io(Fo.Piano,"Acoustic Piano")],[1,new Io(Fo.Piano,"Acoustic Piano")],[2,new Io(Fo.Piano,"Electric Piano")],[3,new Io(Fo.Piano,"Acoustic Piano")],[4,new Io(Fo.Piano,"Electric Piano")],[5,new Io(Fo.Piano,"Electric Piano")],[6,new Io(Fo.Piano,"Harpsichord")],[7,new Io(Fo.Piano,"Harpsichord")],[8,new Io(Fo.PitchedIdiophone,"Celesta")],[9,new Io(Fo.PitchedIdiophone,"Vibraphone")],[10,new Io(Fo.PitchedIdiophone,"Vibraphone")],[11,new Io(Fo.PitchedIdiophone,"Vibraphone")],[12,new Io(Fo.PitchedIdiophone,"Xylophone")],[13,new Io(Fo.PitchedIdiophone,"Xylophone")],[14,new Io(Fo.PitchedIdiophone,"Vibraphone")],[15,new Io(Fo.Banjo,"Banjo")],[16,new Io(Fo.Piano,"Electric Organ")],[17,new Io(Fo.Piano,"Electric Organ")],[18,new Io(Fo.Piano,"Electric Organ")],[19,new Io(Fo.Piano,"Electric Organ")],[20,new Io(Fo.Piano,"Electric Organ")],[21,new Io(Fo.Piano,"Electric Organ")],[22,new Io(Fo.Woodwind,"Recorder")],[23,new Io(Fo.Piano,"Electric Organ")],[24,new Io(Fo.ClassicalGuitar,"Nylon Guitar")],[25,new Io(Fo.SteelGuitar,"Steel Guitar")],[26,new Io(Fo.SteelGuitar,"Electric Guitar")],[27,new Io(Fo.ElectricGuitar,"Electric Guitar")],[28,new Io(Fo.ElectricGuitar,"Electric Guitar")],[29,new Io(Fo.ElectricGuitar,"Electric Guitar")],[30,new Io(Fo.SteelGuitar,"Electric Guitar")],[31,new Io(Fo.SteelGuitar,"Electric Guitar")],[32,new Io(Fo.Bass,"Acoustic Bass")],[33,new Io(Fo.Bass,"Electric Bass")],[34,new Io(Fo.Bass,"Electric Bass")],[35,new Io(Fo.Bass,"Acoustic Bass")],[36,new Io(Fo.Bass,"Electric Bass")],[37,new Io(Fo.Bass,"Electric Bass")],[38,new Io(Fo.Synth,"Synth Bass")],[39,new Io(Fo.Synth,"Synth Bass")],[40,new Io(Fo.Strings,"Violin")],[41,new Io(Fo.Strings,"Viola")],[42,new Io(Fo.Strings,"Cello")],[43,new Io(Fo.Strings,"Contrabass")],[44,new Io(Fo.Strings,"Violin")],[45,new Io(Fo.Strings,"Violin")],[46,new Io(Fo.Piano,"Harp")],[47,new Io(Fo.Membraphone,"Timpani")],[48,new Io(Fo.Strings,"Violin")],[49,new Io(Fo.Strings,"Violin")],[50,new Io(Fo.Strings,"Violin")],[51,new Io(Fo.Strings,"Violin")],[52,new Io(Fo.Vocal,"Voice")],[53,new Io(Fo.Vocal,"Voice")],[54,new Io(Fo.Vocal,"Voice")],[55,new Io(Fo.Synth,"Pad Synthesizer")],[56,new Io(Fo.Brass,"Trumpet")],[57,new Io(Fo.Brass,"Trombone")],[58,new Io(Fo.Brass,"Tuba")],[59,new Io(Fo.Brass,"Trumpet")],[60,new Io(Fo.Brass,"French Horn")],[61,new Io(Fo.Brass,"Trumpet")],[62,new Io(Fo.Brass,"Trumpet")],[63,new Io(Fo.Brass,"Trumpet")],[64,new Io(Fo.Reed,"Saxophone")],[65,new Io(Fo.Reed,"Saxophone")],[66,new Io(Fo.Reed,"Saxophone")],[67,new Io(Fo.Reed,"Saxophone")],[68,new Io(Fo.Reed,"Oboe")],[69,new Io(Fo.Reed,"English Horn")],[70,new Io(Fo.Reed,"Bassoon")],[71,new Io(Fo.Reed,"Clarinet")],[72,new Io(Fo.Reed,"Piccolo")],[73,new Io(Fo.Woodwind,"Flute")],[74,new Io(Fo.Woodwind,"Recorder")],[75,new Io(Fo.Woodwind,"Flute")],[76,new Io(Fo.Woodwind,"Recorder")],[77,new Io(Fo.Woodwind,"Flute")],[78,new Io(Fo.Woodwind,"Recorder")],[79,new Io(Fo.Woodwind,"Flute")],[80,new Io(Fo.Synth,"Lead Synthesizer")],[81,new Io(Fo.Synth,"Lead Synthesizer")],[82,new Io(Fo.Synth,"Lead Synthesizer")],[83,new Io(Fo.Synth,"Lead Synthesizer")],[84,new Io(Fo.Synth,"Lead Synthesizer")],[85,new Io(Fo.Synth,"Lead Synthesizer")],[86,new Io(Fo.Synth,"Lead Synthesizer")],[87,new Io(Fo.Synth,"Lead Synthesizer")],[88,new Io(Fo.Synth,"Pad Synthesizer")],[89,new Io(Fo.Synth,"Pad Synthesizer")],[90,new Io(Fo.Synth,"Pad Synthesizer")],[91,new Io(Fo.Synth,"Pad Synthesizer")],[92,new Io(Fo.Synth,"Pad Synthesizer")],[93,new Io(Fo.Synth,"Pad Synthesizer")],[94,new Io(Fo.Synth,"Pad Synthesizer")],[95,new Io(Fo.Synth,"Pad Synthesizer")],[96,new Io(Fo.Fx,"Pad Synthesizer")],[97,new Io(Fo.Fx,"Pad Synthesizer")],[98,new Io(Fo.Fx,"Pad Synthesizer")],[99,new Io(Fo.Fx,"Pad Synthesizer")],[100,new Io(Fo.Fx,"Lead Synthesizer")],[101,new Io(Fo.Fx,"Lead Synthesizer")],[102,new Io(Fo.Fx,"Lead Synthesizer")],[103,new Io(Fo.Fx,"Trumpet")],[104,new Io(Fo.ElectricGuitar,"Banjo")],[105,new Io(Fo.Banjo,"Banjo")],[106,new Io(Fo.Ukulele,"Ukulele")],[107,new Io(Fo.Banjo,"Banjo")],[108,new Io(Fo.PitchedIdiophone,"Xylophone")],[109,new Io(Fo.Reed,"Bassoon")],[110,new Io(Fo.Strings,"Violin")],[111,new Io(Fo.Woodwind,"Flute")],[112,new Io(Fo.PitchedIdiophone,"Xylophone")],[113,new Io(Fo.Idiophone,"Celesta")],[114,new Io(Fo.PitchedIdiophone,"Vibraphone")],[115,new Io(Fo.Idiophone,"Xylophone")],[116,new Io(Fo.Membraphone,"Xylophone")],[117,new Io(Fo.Membraphone,"Xylophone")],[118,new Io(Fo.Membraphone,"Xylophone")],[119,new Io(Fo.Idiophone,"Celesta")],[120,new Io(Fo.Fx,"Steel Guitar")],[121,new Io(Fo.Fx,"Recorder")],[122,new Io(Fo.Fx,"Recorder")],[123,new Io(Fo.Fx,"Recorder")],[124,new Io(Fo.Fx,"Recorder")],[125,new Io(Fo.Fx,"Recorder")],[126,new Io(Fo.Fx,"Recorder")],[127,new Io(Fo.Fx,"Timpani")]]),Do.DrumKitProgramInfo=new Io(Fo.PercussionKit,"Drums","drumKit");class Ao{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=Ao.CrcInit,this.reset()}update(e,t,s){for(let i=0;i<s;i++)this._checkValue=Ao.Crc32Lookup[255&(this._checkValue^e[t+i])]^this._checkValue>>>8}reset(){this._checkValue=Ao.CrcInit}}Ao.Crc32Lookup=Ao.buildCrc32Lookup(),Ao.CrcInit=4294967295;class Ro{}Ro.MAX_WBITS=15,Ro.WSIZE=1<<Ro.MAX_WBITS,Ro.WMASK=Ro.WSIZE-1,Ro.MIN_MATCH=3,Ro.MAX_MATCH=258,Ro.DEFAULT_MEM_LEVEL=8,Ro.PENDING_BUF_SIZE=1<<Ro.DEFAULT_MEM_LEVEL+8,Ro.HASH_BITS=Ro.DEFAULT_MEM_LEVEL+7,Ro.HASH_SIZE=1<<Ro.HASH_BITS,Ro.HASH_SHIFT=(Ro.HASH_BITS+Ro.MIN_MATCH-1)/Ro.MIN_MATCH,Ro.HASH_MASK=Ro.HASH_SIZE-1,Ro.MIN_LOOKAHEAD=Ro.MAX_MATCH+Ro.MIN_MATCH+1,Ro.MAX_DIST=Ro.WSIZE-Ro.MIN_LOOKAHEAD;class Oo{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 c=t[0];i=o++,r[2*i]=e,r[2*i+1]=c;let d=Math.min(255&n[e],255&n[c]);for(l=n[e]+n[c]-d+1,n[i]=l,a=0,h=1;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*a+1;for(;h=a,h>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i}while(s>1);this.buildLength(r)}buildLength(e){this.length=new Uint8Array(this.freqs.length);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[Oo.Repeat3To6]++:i<=10?e.freqs[Oo.Repeat3To10]++:e.freqs[Oo.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]=Go.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(Oo.Repeat3To6),this.huffman.pending.writeBits(i-3,2)):i<=10?(e.writeSymbol(Oo.Repeat3To10),this.huffman.pending.writeBits(i-3,3)):(e.writeSymbol(Oo.Repeat11To138),this.huffman.pending.writeBits(i-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}Oo.Repeat3To6=16,Oo.Repeat3To10=17,Oo.Repeat11To138=18;class Go{static staticInit(){let e=0;for(;e<144;)Go.staticLCodes[e]=Go.bitReverse(48+e<<8),Go.staticLLength[e++]=8;for(;e<256;)Go.staticLCodes[e]=Go.bitReverse(256+e<<7),Go.staticLLength[e++]=9;for(;e<280;)Go.staticLCodes[e]=Go.bitReverse(-256+e<<9),Go.staticLLength[e++]=7;for(;e<Go.LITERAL_NUM;)Go.staticLCodes[e]=Go.bitReverse(-88+e<<8),Go.staticLLength[e++]=8;for(e=0;e<Go.DIST_NUM;e++)Go.staticDCodes[e]=Go.bitReverse(e<<11),Go.staticDLength[e]=5}static bitReverse(e){return Go.bit4Reverse[15&e]<<12|Go.bit4Reverse[e>>4&15]<<8|Go.bit4Reverse[e>>8&15]<<4|Go.bit4Reverse[e>>12]}constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new Oo(this,Go.LITERAL_NUM,257,15),this.distTree=new Oo(this,Go.DIST_NUM,1,15),this.blTree=new Oo(this,Go.BITLEN_NUM,4,7),this.d_buf=new Int16Array(Go.BUFSIZE),this.l_buf=new Uint8Array(Go.BUFSIZE)}isFull(){return this.last_lit>=Go.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((Go.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[Go.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[Go.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<Go.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*Go.staticLLength[e];for(let e=0;e<Go.DIST_NUM;e++)n+=this.distTree.freqs[e]*Go.staticDLength[e];r>=n&&(r=n),t>=0&&s+4<r>>3?this.flushStoredBlock(e,t,s,i):r==n?(this.pending.writeBits((Go.STATIC_TREES<<1)+(i?1:0),3),this.literalTree.setStaticCodes(Go.staticLCodes,Go.staticLLength),this.distTree.setStaticCodes(Go.staticDCodes,Go.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((Go.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[Go.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=Go.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=Go.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(Go.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;let s=Go.Lcode(t-3);this.literalTree.freqs[s]++,s>=265&&s<285&&(this.extra_bits+=Math.floor((s-261)/4));let i=Go.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}}Go.BUFSIZE=1<<Ro.DEFAULT_MEM_LEVEL+6,Go.LITERAL_NUM=286,Go.STORED_BLOCK=0,Go.STATIC_TREES=1,Go.DYN_TREES=2,Go.DIST_NUM=30,Go.staticLCodes=new Int16Array(Go.LITERAL_NUM),Go.staticLLength=new Uint8Array(Go.LITERAL_NUM),Go.staticDCodes=new Int16Array(Go.DIST_NUM),Go.staticDLength=new Uint8Array(Go.DIST_NUM),Go.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Go.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),Go.BITLEN_NUM=19,Go.EOF_SYMBOL=256,Go.staticInit();class Vo{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 Go(e),this.inputCrc=new Ao,this.window=new Uint8Array(2*Ro.WSIZE),this.head=new Int16Array(Ro.HASH_SIZE),this.prev=new Int16Array(Ro.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=Ro.MIN_MATCH-1;for(let e=0;e<Ro.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<Ro.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<Ro.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<Ro.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=Ro.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*Ro.WSIZE-Ro.MIN_LOOKAHEAD&&this.slideWindow();let e=this.matchStart,s=this.matchLen;if(this.lookahead>=Ro.MIN_MATCH){let e=this.insertString();0!=e&&this.strstart-e<=Ro.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen==Ro.MIN_MATCH&&this.strstart-this.matchStart>Vo.TooFar&&(this.matchLen=Ro.MIN_MATCH-1)}if(s>=Ro.MIN_MATCH&&this.matchLen<=s){this.huffman.tallyDist(this.strstart-1-e,s),s-=2;do{this.strstart++,this.lookahead--,this.lookahead>=Ro.MIN_MATCH&&this.insertString()}while(--s>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=Ro.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(Ro.MAX_MATCH,this.lookahead)-1,a=Math.max(s-Ro.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,Ro.MIN_MATCH-1),s+this.matchLen>i)return!1;let l=r[s+this.matchLen-1],c=r[s+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,s=this.strstart,r[t+this.matchLen]==c&&r[t+this.matchLen-1]==l&&r[t]==r[s]&&r[++t]==r[++s]){switch((i-s)%8){case 1:if(r[++s]==r[++t])break;break;case 2:if(r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 3:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 4:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 5:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 6:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 7:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break}if(r[s]==r[t])do{if(s==i){++s,++t;break}}while(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]);if(s-this.strstart>this.matchLen){if(this.matchStart=e,this.matchLen=s-this.strstart,this.matchLen>=h)break;l=r[s-1],c=r[s]}e=65535&n[e&Ro.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=Ro.MIN_MATCH}insertString(){let e,t=(this.insertHashIndex<<Ro.HASH_SHIFT^this.window[this.strstart+(Ro.MIN_MATCH-1)])&Ro.HASH_MASK;return e=this.head[t],this.prev[this.strstart&Ro.WMASK]=e,this.head[t]=this.strstart,this.insertHashIndex=t,65535&e}fillWindow(){if(this.strstart>=Ro.WSIZE+Ro.MAX_DIST&&this.slideWindow(),this.lookahead<Ro.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*Ro.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>=Ro.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(Ro.WSIZE,Ro.WSIZE+Ro.WSIZE),0),this.matchStart-=Ro.WSIZE,this.strstart-=Ro.WSIZE,this.blockStart-=Ro.WSIZE;for(let e=0;e<Ro.HASH_SIZE;++e){let t=65535&this.head[e];this.head[e]=t>=Ro.WSIZE?t-Ro.WSIZE:0}for(let e=0;e<Ro.WSIZE;e++){let t=65535&this.prev[e];this.prev[e]=t>=Ro.WSIZE?t-Ro.WSIZE:0}}}Vo.TooFar=4096;class Ho{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 Wo{get inputCrc(){return this._engine.inputCrc.value}constructor(){this._state=0,this._pending=new Ho(Ro.PENDING_BUF_SIZE),this._engine=new Vo(this._pending),this.reset()}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state==Wo.FinishedState&&this._pending.isFlushed}reset(){this._state=Wo.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==Wo.FinishedState)break;if(!this._engine.deflate(!!(this._state&Wo.IsFlushing),!!(this._state&Wo.IsFinishing)))switch(this._state){case Wo.BusyState:return i-s;case Wo.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=Wo.BusyState;break;case Wo.FinishingState:this._pending.alignToByte(),this._state=Wo.FinishedState}}return i-s}finish(){this._state|=Wo.IsFlushing|Wo.IsFinishing}}Wo.IsFlushing=4,Wo.IsFinishing=8,Wo.BusyState=16,Wo.FlushingState=20,Wo.FinishingState=28,Wo.FinishedState=30;class zo{constructor(e,t,s,i,a){this.entry=e,this.crc32=t,this.localHeaderOffset=s,this.compressionMode=i,this.compressedSize=a}}class Uo{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new Wo,this._data=e}writeEntry(e){const t=xt.CompressionMethodDeflate,s=Te.empty(),i=this.compress(s,e.data,t),a=s.toArray(),r=new zo(e,i,this._data.bytesWritten,t,s.length);this._centralDirectoryHeaders.push(r),Be.writeInt32LE(this._data,xt.LocalFileHeaderSignature),Be.writeUInt16LE(this._data,10),Be.writeUInt16LE(this._data,2048),Be.writeUInt16LE(this._data,t),Be.writeInt16LE(this._data,0),Be.writeInt16LE(this._data,0),Be.writeInt32LE(this._data,i),Be.writeInt32LE(this._data,a.length),Be.writeInt32LE(this._data,e.data.length),Be.writeInt16LE(this._data,e.fullName.length),Be.writeInt16LE(this._data,0);const n=Be.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,s){if(s!=xt.CompressionMethodDeflate){const s=new Ao;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){Be.writeInt32LE(this._data,xt.EndOfCentralDirSignature),Be.writeInt16LE(this._data,0),Be.writeInt16LE(this._data,0),Be.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Be.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Be.writeInt32LE(this._data,t-e),Be.writeInt32LE(this._data,e),Be.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){Be.writeInt32LE(this._data,xt.CentralFileHeaderSignature),Be.writeUInt16LE(this._data,10),Be.writeUInt16LE(this._data,10),Be.writeUInt16LE(this._data,2048),Be.writeUInt16LE(this._data,e.compressionMode),Be.writeInt16LE(this._data,0),Be.writeInt16LE(this._data,0),Be.writeInt32LE(this._data,e.crc32),Be.writeInt32LE(this._data,e.compressedSize),Be.writeInt32LE(this._data,e.entry.data.length),Be.writeInt16LE(this._data,e.entry.fullName.length),Be.writeInt16LE(this._data,0),Be.writeInt16LE(this._data,0),Be.writeInt16LE(this._data,0),Be.writeInt16LE(this._data,0),Be.writeInt32LE(this._data,0),Be.writeInt32LE(this._data,e.localHeaderOffset);const t=Be.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}var Xo=Object.freeze({__proto__:null,Gp7Exporter:class extends Mo{get name(){return"Guitar Pro 7"}constructor(){super()}writeScore(e){q.debug(this.name,"Writing data entries");const t=(new Do).writeXml(e),s=nt.writeForScore(e),i=bt.writeForScore(e);q.debug(this.name,"Writing ZIP entries");let a=new Uo(this.data);a.writeEntry(new xt("VERSION",Be.stringToBytes("7.0"))),a.writeEntry(new xt("Content/",new Uint8Array(0))),a.writeEntry(new xt("Content/BinaryStylesheet",s)),a.writeEntry(new xt("Content/PartConfiguration",i)),a.writeEntry(new xt("Content/score.gpif",Be.stringToBytes(t))),a.end()}},ScoreExporter:Mo}),Yo=Object.freeze({__proto__:null,AlphaSynthMidiFileHandler:Ei,AlphaTabMetronomeEvent:Vt,AlphaTabRestEvent:Ht,BeatTickLookup:Ii,ControlChangeEvent:Xt,get ControllerType(){return Oe},EndOfTrackEvent:Qt,MasterBarTickLookup:Di,MidiEvent:Rt,get MidiEventType(){return Le},MidiFile:At,get MidiFileFormat(){return Fe},MidiFileGenerator:Vi,MidiTickLookup:Ri,MidiTickLookupFindBeatResult:Ai,NoteBendEvent:jt,NoteEvent:Wt,NoteOffEvent:Ut,NoteOnEvent:zt,PitchBendEvent:Jt,ProgramChangeEvent:Yt,TempoChangeEvent:qt,TimeSignatureEvent:Ot}),qo=Object.freeze({__proto__:null,get AccentuationType(){return i},get AccidentalType(){return qe},Automation:V,get AutomationType(){return a},Bar:H,Beat:ne,BendPoint:z,get BendStyle(){return h},get BendType(){return l},get BrushType(){return c},Chord:oe,get Clef(){return r},Color:fe,get CrescendoType(){return d},get Duration(){return u},get DynamicValue(){return p},Fermata:ot,get FermataType(){return xe},get Fingers(){return f},Font:As,get FontStyle(){return Ge},get GraceType(){return g},get HarmonicType(){return m},InstrumentArticulation:Q,JsonConverter:mi,get KeySignature(){return L},get KeySignatureType(){return I},Lyrics:he,MasterBar:le,get MusicFontSymbol(){return N},Note:Z,get NoteAccidentalMode(){return y},get Ottavia(){return n},get PickStroke(){return x},PlaybackInformation:me,RenderStylesheet:ce,RepeatGroup:de,Score:ue,Section:pe,get SimileMark(){return o},get SlideInType(){return b},get SlideOutType(){return S},Staff:be,Track:Se,get TripletFeel(){return D},Tuning:ye,TupletGroup:ee,get VibratoType(){return _},Voice:_e,get WhammyType(){return E}}),Jo=Object.freeze({__proto__:null,BarBounds:wi,BeatBounds:Bi,Bounds:rt,BoundsLookup:xi,MasterBarBounds:Ti,NoteBounds:ki,RenderFinishedEventArgs:_i,ScoreRenderer:Ni,StaveGroupBounds:vi}),jo=Object.freeze({__proto__:null,CssFontSvgCanvas:ya,Cursors:la,FontSizes:Si,SvgCanvas:ma,get TextAlign(){return P},get TextBaseline(){return C}}),Qo=Object.freeze({__proto__:null,ActiveBeatsChangedEventArgs:ji,AlphaSynth:Ls,AlphaSynthAudioWorkletOutput:da,AlphaSynthScriptProcessorOutput:ra,AlphaSynthWebAudioOutputBase:aa,AlphaSynthWebWorkerApi:oa,CircularSampleBuffer:ia,MidiEventsPlayedEventArgs:Es,PlaybackRange:Hi,PlaybackRangeChangedEventArgs:Fs,get PlayerState(){return Me},PlayerStateChangedEventArgs:ss,PositionChangedEventArgs:is});export{ga as AlphaTabApi,O as AlphaTabError,s as AlphaTabErrorType,Co as CoreSettings,Os as DisplaySettings,Po as Environment,Ki as FileLoadError,B as FingeringMode,ge as FormatError,Gs as ImporterSettings,e as LayoutMode,v as LogLevel,q as Logger,T as NotationMode,U as NotationSettings,ze as PlayerOutputMode,Ws as PlayerSettings,na as ProgressEventArgs,Rs as RenderingResources,Ji as ResizeEventArgs,We as ScrollMode,Ks as Settings,t as StaveProfile,He as SystemsLayoutMode,w as TabRhythmMode,Vs as VibratoPlaybackSettings,Ue as WebPlatform,Xo as exporter,Lo as importer,Eo as meta,Yo as midi,qo as model,jo as platform,Jo as rendering,Qo as synth};
|
|
1
|
+
var e,t,s,i,a,r,n,o,h,l,c,d,u,p,g,f,m,y,b,S,_,w,B,T,k,v,x,N,P,C,E,F,L,M,I,D;!function(e){e[e.Page=0]="Page",e[e.Horizontal=1]="Horizontal"}(e||(e={})),function(e){e[e.Default=0]="Default",e[e.ScoreTab=1]="ScoreTab",e[e.Score=2]="Score",e[e.Tab=3]="Tab",e[e.TabMixed=4]="TabMixed"}(t||(t={}));class A{static getValue(e){return A._values||(A._values=new Map),e=e.toLowerCase().replaceAll(" ",""),A._values.has(e)?A._values.get(e):0}static isPiano(e){return e<=7||e>=16&&e<=23}static isGuitar(e){return e>=24&&e<=39||105===e||43===e}}A._values=new Map([["acousticgrandpiano",0],["brightacousticpiano",1],["electricgrandpiano",2],["honkytonkpiano",3],["electricpiano1",4],["electricpiano2",5],["harpsichord",6],["clavinet",7],["celesta",8],["glockenspiel",9],["musicbox",10],["vibraphone",11],["marimba",12],["xylophone",13],["tubularbells",14],["dulcimer",15],["drawbarorgan",16],["percussiveorgan",17],["rockorgan",18],["churchorgan",19],["reedorgan",20],["accordion",21],["harmonica",22],["tangoaccordion",23],["acousticguitarnylon",24],["acousticguitarsteel",25],["electricguitarjazz",26],["electricguitarclean",27],["electricguitarmuted",28],["overdrivenguitar",29],["distortionguitar",30],["guitarharmonics",31],["acousticbass",32],["electricbassfinger",33],["electricbasspick",34],["fretlessbass",35],["slapbass1",36],["slapbass2",37],["synthbass1",38],["synthbass2",39],["violin",40],["viola",41],["cello",42],["contrabass",43],["tremolostrings",44],["pizzicatostrings",45],["orchestralharp",46],["timpani",47],["stringensemble1",48],["stringensemble2",49],["synthstrings1",50],["synthstrings2",51],["choiraahs",52],["voiceoohs",53],["synthvoice",54],["orchestrahit",55],["trumpet",56],["trombone",57],["tuba",58],["mutedtrumpet",59],["frenchhorn",60],["brasssection",61],["synthbrass1",62],["synthbrass2",63],["sopranosax",64],["altosax",65],["tenorsax",66],["baritonesax",67],["oboe",68],["englishhorn",69],["bassoon",70],["clarinet",71],["piccolo",72],["flute",73],["recorder",74],["panflute",75],["blownbottle",76],["shakuhachi",77],["whistle",78],["ocarina",79],["lead1square",80],["lead2sawtooth",81],["lead3calliope",82],["lead4chiff",83],["lead5charang",84],["lead6voice",85],["lead7fifths",86],["lead8bassandlead",87],["pad1newage",88],["pad2warm",89],["pad3polysynth",90],["pad4choir",91],["pad5bowed",92],["pad6metallic",93],["pad7halo",94],["pad8sweep",95],["fx1rain",96],["fx2soundtrack",97],["fx3crystal",98],["fx4atmosphere",99],["fx5brightness",100],["fx6goblins",101],["fx7echoes",102],["fx8scifi",103],["sitar",104],["banjo",105],["shamisen",106],["koto",107],["kalimba",108],["bagpipe",109],["fiddle",110],["shanai",111],["tinklebell",112],["agogo",113],["steeldrums",114],["woodblock",115],["taikodrum",116],["melodictom",117],["synthdrum",118],["reversecymbal",119],["guitarfretnoise",120],["breathnoise",121],["seashore",122],["birdtweet",123],["telephonering",124],["helicopter",125],["applause",126],["gunshot",127]]);class R{init(e,t){this.data=e,this.settings=t}}!function(e){e[e.General=0]="General",e[e.Format=1]="Format",e[e.AlphaTex=2]="AlphaTex"}(s||(s={}));class O extends Error{constructor(e,t="",s){super(t??"",{cause:s}),this.type=e,this.inner=s??null,Object.setPrototypeOf(this,O.prototype)}}class G extends O{constructor(e=null,t=null){super(s.Format,e??"Unsupported format"),this.inner=t,Object.setPrototypeOf(this,G.prototype)}}!function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy"}(i||(i={})),function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(a||(a={}));class V{constructor(){this.isLinear=!1,this.type=a.Tempo,this.value=0,this.ratioPosition=0,this.text=""}static buildTempoAutomation(e,t,s,i){(i<1||i>5)&&(i=2);let r=new Float32Array([1,.5,1,1.5,2,3]),n=new V;return n.type=a.Tempo,n.isLinear=e,n.ratioPosition=t,n.value=s*r[i],n}static buildInstrumentAutomation(e,t,s){let i=new V;return i.type=a.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"}(r||(r={})),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"}(n||(n={})),function(e){e[e.None=0]="None",e[e.Simple=1]="Simple",e[e.FirstOfDouble=2]="FirstOfDouble",e[e.SecondOfDouble=3]="SecondOfDouble"}(o||(o={}));class H{constructor(){this.id=H._globalBarId++,this.index=0,this.nextBar=null,this.previousBar=null,this.clef=r.G2,this.clefOttava=n.Regular,this.voices=[],this.simileMark=o.None,this.isMultiVoice=!1,this.displayScale=1,this.displayWidth=-1}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)}}calculateDuration(){let e=0;for(let t of this.voices){let s=t.calculateDuration();s>e&&(e=s)}return e}}H._globalBarId=0;class W{static ticksToMillis(e,t){return e*(6e4/(t*W.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*W.QuarterTime))|0}static toTicks(e){return W.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),W.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 W.MinVelocity+e*W.VelocityIncrement}}W.QuarterTime=960,W.MinVelocity=15,W.VelocityIncrement=16;class z{constructor(e=0,t=0){this.offset=e,this.value=t}}z.MaxPosition=60,z.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(h||(h={})),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"}(l||(l={})),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"}(c||(c={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(d||(d={})),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"}(u||(u={})),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"}(p||(p={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(g||(g={})),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"}(f||(f={})),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"}(m||(m={})),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"}(y||(y={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(b||(b={})),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"}(S||(S={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(_||(_={})),function(e){e[e.Hidden=0]="Hidden",e[e.ShowWithBeams=1]="ShowWithBeams",e[e.ShowWithBars=2]="ShowWithBars"}(w||(w={})),function(e){e[e.ScoreDefault=0]="ScoreDefault",e[e.ScoreForcePiano=1]="ScoreForcePiano",e[e.SingleNoteEffectBand=2]="SingleNoteEffectBand",e[e.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano"}(B||(B={})),function(e){e[e.GuitarPro=0]="GuitarPro",e[e.SongBook=1]="SongBook"}(T||(T={})),function(e){e[e.ScoreTitle=0]="ScoreTitle",e[e.ScoreSubTitle=1]="ScoreSubTitle",e[e.ScoreArtist=2]="ScoreArtist",e[e.ScoreAlbum=3]="ScoreAlbum",e[e.ScoreWords=4]="ScoreWords",e[e.ScoreMusic=5]="ScoreMusic",e[e.ScoreWordsAndMusic=6]="ScoreWordsAndMusic",e[e.ScoreCopyright=7]="ScoreCopyright",e[e.GuitarTuning=8]="GuitarTuning",e[e.TrackNames=9]="TrackNames",e[e.ChordDiagrams=10]="ChordDiagrams",e[e.ParenthesisOnTiedBends=11]="ParenthesisOnTiedBends",e[e.TabNotesOnTiedBends=12]="TabNotesOnTiedBends",e[e.ZerosOnDiveWhammys=13]="ZerosOnDiveWhammys",e[e.EffectAlternateEndings=14]="EffectAlternateEndings",e[e.EffectCapo=15]="EffectCapo",e[e.EffectChordNames=16]="EffectChordNames",e[e.EffectCrescendo=17]="EffectCrescendo",e[e.EffectDynamics=18]="EffectDynamics",e[e.EffectFadeIn=19]="EffectFadeIn",e[e.EffectFermata=20]="EffectFermata",e[e.EffectFingering=21]="EffectFingering",e[e.EffectHarmonics=22]="EffectHarmonics",e[e.EffectLetRing=23]="EffectLetRing",e[e.EffectLyrics=24]="EffectLyrics",e[e.EffectMarker=25]="EffectMarker",e[e.EffectOttavia=26]="EffectOttavia",e[e.EffectPalmMute=27]="EffectPalmMute",e[e.EffectPickSlide=28]="EffectPickSlide",e[e.EffectPickStroke=29]="EffectPickStroke",e[e.EffectSlightBeatVibrato=30]="EffectSlightBeatVibrato",e[e.EffectSlightNoteVibrato=31]="EffectSlightNoteVibrato",e[e.EffectTap=32]="EffectTap",e[e.EffectTempo=33]="EffectTempo",e[e.EffectText=34]="EffectText",e[e.EffectTrill=35]="EffectTrill",e[e.EffectTripletFeel=36]="EffectTripletFeel",e[e.EffectWhammyBar=37]="EffectWhammyBar",e[e.EffectWideBeatVibrato=38]="EffectWideBeatVibrato",e[e.EffectWideNoteVibrato=39]="EffectWideNoteVibrato",e[e.EffectLeftHandTap=40]="EffectLeftHandTap"}(k||(k={}));class U{constructor(){this.notationMode=T.GuitarPro,this.fingeringMode=B.ScoreDefault,this.elements=new Map,this.rhythmMode=w.Hidden,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):!U.defaultElements.has(e)||U.defaultElements.get(e)}}U.defaultElements=new Map([[k.ZerosOnDiveWhammys,!1]]);class X{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}!function(e){e[e.None=0]="None",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warning=3]="Warning",e[e.Error=4]="Error"}(v||(v={}));class Y{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...s){console.debug(Y.format(e,t),...s)}warning(e,t,...s){console.warn(Y.format(e,t),...s)}info(e,t,...s){console.info(Y.format(e,t),...s)}error(e,t,...s){console.error(Y.format(e,t),...s)}}Y.logLevel=v.Info;class q{static shouldLog(e){return q.logLevel!==v.None&&e>=q.logLevel}static debug(e,t,...s){q.shouldLog(v.Debug)&&q.log.debug(e,t,...s)}static warning(e,t,...s){q.shouldLog(v.Warning)&&q.log.warning(e,t,...s)}static info(e,t,...s){q.shouldLog(v.Info)&&q.log.info(e,t,...s)}static error(e,t,...s){q.shouldLog(v.Error)&&q.log.error(e,t,...s)}}q.logLevel=v.Info,q.log=new Y;class J{constructor(){this.note=null,this.noteValue=0,this.octave=0}get realValue(){return 12*this.octave+this.noteValue}}class j{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(e,t,s,i){if(e.notation.fingeringMode===B.ScoreForcePiano||e.notation.fingeringMode===B.SingleNoteEffectBandForcePiano||A.isPiano(t.voice.bar.staff.track.playbackInfo.program))switch(s){case f.Unknown:case f.NoOrDead:return null;case f.Thumb:return"1";case f.IndexFinger:return"2";case f.MiddleFinger:return"3";case f.AnnularFinger:return"4";case f.LittleFinger:return"5";default:return null}if(i)switch(s){case f.Unknown:case f.NoOrDead:return"0";case f.Thumb:return"T";case f.IndexFinger:return"1";case f.MiddleFinger:return"2";case f.AnnularFinger:return"3";case f.LittleFinger:return"4";default:return null}switch(s){case f.Unknown:case f.NoOrDead:return null;case f.Thumb:return"p";case f.IndexFinger:return"i";case f.MiddleFinger:return"m";case f.AnnularFinger:return"a";case f.LittleFinger:return"c";default:return null}}static isTuning(e){return!!j.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(!(a>=65&&a<=90||a>=97&&a<=122||35===a))return null;t+=String.fromCharCode(a)}}if(!s||!t)return null;let i=new J;return i.octave=parseInt(s)+1,i.note=t.toLowerCase(),i.noteValue=j.getToneForText(i.note),i}static getTuningForText(e){let t=j.parseTuning(e);return t?t.realValue:-1}static getToneForText(e){switch(e.toLowerCase()){case"c":default:return 0;case"c#":case"db":return 1;case"d":return 2;case"d#":case"eb":return 3;case"e":return 4;case"f":return 5;case"f#":case"gb":return 6;case"g":return 7;case"g#":case"ab":return 8;case"a":return 9;case"a#":case"bb":return 10;case"b":return 11}}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}}!function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(x||(x={})),function(e){e[e.None=-1]="None",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.NoteQuarterUp=57813]="NoteQuarterUp",e[e.NoteEighthUp=57815]="NoteEighthUp",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.ArticAccentAbove=58528]="ArticAccentAbove",e[e.ArticStaccatoAbove=58530]="ArticStaccatoAbove",e[e.ArticMarcatoAbove=58540]="ArticMarcatoAbove",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.StringsDownBow=58896]="StringsDownBow",e[e.StringsUpBow=58898]="StringsUpBow",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.GuitarGolpe=59458]="GuitarGolpe",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"}(N||(N={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(P||(P={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(C||(C={}));class Q{constructor(e="",t=0,s=0,i=N.None,a=N.None,r=N.None,n=N.None,o=C.Middle){this.elementType=e,this.outputMidiNumber=s,this.staffLine=t,this.noteHeadDefault=i,this.noteHeadHalf=a!==N.None?a:i,this.noteHeadWhole=r!==N.None?r:i,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case u.Whole:return this.noteHeadWhole;case u.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class ${static articulationFromElementVariation(e,t){return e<$.gp6ElementAndVariationToArticulation.length?(t>=$.gp6ElementAndVariationToArticulation.length&&(t=0),$.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]:$.getArticulationByValue(t)}static getElementAndVariation(e){const t=$.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<$.gp6ElementAndVariationToArticulation.length;e++){const s=$.gp6ElementAndVariationToArticulation[e];for(let i=0;i<s.length;i++){const a=$.getArticulationByValue(s[i]);if(a?.outputMidiNumber===t.outputMidiNumber)return[e,i]}}return[-1,-1]}static getArticulationByValue(e){return $.instrumentArticulations.has(e)?$.instrumentArticulations.get(e):null}}$.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]],$.instrumentArticulations=new Map([[38,new Q("snare",3,38,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[37,new Q("snare",3,37,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[91,new Q("snare",3,38,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite)],[42,new Q("hiHat",-1,42,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[92,new Q("hiHat",-1,46,N.NoteheadCircleSlash,N.NoteheadCircleSlash,N.NoteheadCircleSlash)],[46,new Q("hiHat",-1,46,N.NoteheadCircleX,N.NoteheadCircleX,N.NoteheadCircleX)],[44,new Q("hiHat",9,44,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[35,new Q("kickDrum",8,35,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[36,new Q("kickDrum",7,36,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[50,new Q("tom",1,50,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[48,new Q("tom",2,48,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[47,new Q("tom",4,47,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[45,new Q("tom",5,45,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[43,new Q("tom",6,43,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[93,new Q("ride",0,51,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.PictEdgeOfCymbal,C.Bottom)],[51,new Q("ride",0,51,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[53,new Q("ride",0,53,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite)],[94,new Q("ride",0,51,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.ArticStaccatoAbove,C.Top)],[55,new Q("splash",-2,55,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[95,new Q("splash",-2,55,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.ArticStaccatoAbove,C.Bottom)],[52,new Q("china",-3,52,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat)],[96,new Q("china",-3,52,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat)],[49,new Q("crash",-2,49,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX)],[97,new Q("crash",-2,49,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX,N.ArticStaccatoAbove,C.Bottom)],[57,new Q("crash",-1,57,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX)],[98,new Q("crash",-1,57,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX,N.ArticStaccatoAbove,C.Bottom)],[99,new Q("cowbell",1,56,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpHalf,N.NoteheadTriangleUpWhole)],[100,new Q("cowbell",1,56,N.NoteheadXBlack,N.NoteheadXHalf,N.NoteheadXWhole)],[56,new Q("cowbell",0,56,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpHalf,N.NoteheadTriangleUpWhole)],[101,new Q("cowbell",0,56,N.NoteheadXBlack,N.NoteheadXHalf,N.NoteheadXWhole)],[102,new Q("cowbell",-1,56,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpHalf,N.NoteheadTriangleUpWhole)],[103,new Q("cowbell",-1,56,N.NoteheadXBlack,N.NoteheadXHalf,N.NoteheadXWhole)],[77,new Q("woodblock",-9,77,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack)],[76,new Q("woodblock",-10,76,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack)],[60,new Q("bongo",-4,60,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[104,new Q("bongo",-5,60,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,C.Middle)],[105,new Q("bongo",-6,60,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[61,new Q("bongo",-7,61,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[106,new Q("bongo",-8,61,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,C.Middle)],[107,new Q("bongo",-16,61,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[66,new Q("timbale",10,66,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[65,new Q("timbale",9,65,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[68,new Q("agogo",12,68,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[67,new Q("agogo",11,67,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[64,new Q("conga",17,64,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[108,new Q("conga",16,64,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[109,new Q("conga",15,64,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,C.Middle)],[63,new Q("conga",14,63,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[110,new Q("conga",13,63,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[62,new Q("conga",19,62,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,C.Middle)],[72,new Q("whistle",-11,72,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[71,new Q("whistle",-17,71,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[73,new Q("guiro",38,73,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[74,new Q("guiro",37,74,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[86,new Q("surdo",36,86,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[87,new Q("surdo",35,87,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadParenthesis,C.Middle)],[54,new Q("tambourine",3,54,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack)],[111,new Q("tambourine",2,54,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.StringsUpBow,C.Bottom)],[112,new Q("tambourine",1,54,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.StringsDownBow,C.Bottom)],[113,new Q("tambourine",-7,54,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[79,new Q("cuica",30,79,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[78,new Q("cuica",29,78,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[58,new Q("vibraslap",28,58,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[81,new Q("triangle",27,81,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[80,new Q("triangle",26,80,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadParenthesis,C.Middle)],[114,new Q("grancassa",25,43,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[115,new Q("piatti",18,49,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[116,new Q("piatti",24,49,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[69,new Q("cabasa",23,69,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[117,new Q("cabasa",22,69,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,C.Bottom)],[85,new Q("castanets",21,85,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[75,new Q("claves",20,75,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[70,new Q("maraca",-12,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[118,new Q("maraca",-13,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,C.Bottom)],[119,new Q("maraca",-14,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[120,new Q("maraca",-15,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,C.Bottom)],[82,new Q("shaker",-23,54,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[122,new Q("shaker",-24,54,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,C.Bottom)],[84,new Q("bellTree",-18,53,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[123,new Q("bellTree",-19,53,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,C.Bottom)],[83,new Q("jingleBell",-20,53,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[124,new Q("unpitched",-21,62,N.NoteheadNull,N.NoteheadNull,N.NoteheadNull,N.GuitarGolpe,C.Top)],[125,new Q("unpitched",-22,62,N.NoteheadNull,N.NoteheadNull,N.NoteheadNull,N.GuitarGolpe,C.Bottom)],[39,new Q("handClap",3,39,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[40,new Q("snare",3,40,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[31,new Q("snare",3,40,N.NoteheadSlashedBlack2,N.NoteheadSlashedBlack2,N.NoteheadSlashedBlack2)],[41,new Q("tom",5,41,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[59,new Q("ride",2,59,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.PictEdgeOfCymbal,C.Bottom)],[126,new Q("ride",2,59,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[127,new Q("ride",2,59,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite)],[29,new Q("ride",2,59,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.ArticStaccatoAbove,C.Top)],[30,new Q("crash",-3,49,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[33,new Q("snare",3,37,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[34,new Q("snare",3,38,N.NoteheadBlack,N.NoteheadBlack,N.NoteheadBlack)]]);class K{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1}}class Z{constructor(){this.id=Z.GlobalNoteId++,this.index=0,this.accentuated=i.None,this.bendType=l.None,this.bendStyle=h.Default,this.bendOrigin=null,this.isContinuedBend=!1,this.bendPoints=null,this.maxBendPoint=null,this.fret=-1,this.string=-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=m.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=b.None,this.slideOutType=S.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=_.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=f.Unknown,this.rightHandFinger=f.Unknown,this.isFingering=!1,this.trillValue=-1,this.trillSpeed=u.ThirtySecond,this.durationPercent=1,this.accidentalMode=y.Default,this.dynamics=p.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this._noteIdBag=null}get hasBend(){return null!==this.bendPoints&&this.bendType!==l.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?$.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?$.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==m.None}get isTieOrigin(){return null!==this.tieDestination}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+Z.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===m.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===m.None||!this.isStringed)return 0;let e=this.harmonicValue;return j.isAlmostEqualTo(e,2.4)?36:j.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!==m.Natural&&this.harmonicType!==m.None&&(e-=this.harmonicPitch),this.beat.ottava){case n._15ma:e-=24;break;case n._8va:e-=12;break;case n.Regular:break;case n._8vb:e+=12;break;case n._15mb:e+=24}switch(this.beat.voice.bar.clefOttava){case n._15ma:e-=24;break;case n._8va:e-=12;break;case n.Regular:break;case n._8vb:e+=12;break;case n._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===l.None&&(this.bendType=l.Custom)}finish(e,t=null){let s=new X((()=>Z.nextNoteOnSameLine(this))),i=e&&e.notation.notationMode===T.SongBook;if(this.isTieDestination&&(this.chain(t),i&&this.tieOrigin&&this.tieOrigin.isLetRing&&(this.isLetRing=!0)),this.isLetRing&&(s.value&&s.value.isLetRing?this.letRingDestination=s.value:this.letRingDestination=this,i&&this.isTieDestination&&!this.tieOrigin.hasBend&&(this.isVisible=!1)),this.isPalmMute&&(s.value&&s.value.isPalmMute?this.palmMuteDestination=s.value:this.palmMuteDestination=this),this.isHammerPullOrigin){let e=Z.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case S.Shift:case S.Legato:this.slideTarget=s.value,this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=S.None}let a=null;this.isHammerPullOrigin&&this.hammerPullDestination?a=this.hammerPullDestination:this.slideOutType===S.Legato&&this.slideTarget&&(a=this.slideTarget),a&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===x.None?(this.effectSlurOrigin.effectSlurDestination=a,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=a,this.effectSlurDestination.effectSlurOrigin=this));const r=this.bendPoints;if(null!=r&&r.length>0&&this.bendType===l.Custom){let e=this.isTieDestination&&this.tieOrigin.hasBend;if(this.isContinuedBend=e,4===r.length){let t=r[0],s=r[1],i=r[2],a=r[3];s.value===i.value?a.value>t.value?s.value>a.value?this.bendType=l.BendRelease:!e&&t.value>0?(this.bendType=l.PrebendBend,r.splice(2,1),r.splice(1,1)):(this.bendType=l.Bend,r.splice(2,1),r.splice(1,1)):a.value<t.value?e?(this.bendType=l.Release,r.splice(2,1),r.splice(1,1)):(this.bendType=l.PrebendRelease,r.splice(2,1),r.splice(1,1)):s.value>t.value?this.bendType=l.BendRelease:t.value>0&&!e?(this.bendType=l.Prebend,r.splice(2,1),r.splice(1,1)):(this.bendType=l.Hold,r.splice(2,1),r.splice(1,1)):q.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===r.length){let t=r[0],s=r[1];s.value>t.value?!e&&t.value>0?this.bendType=l.PrebendBend:this.bendType=l.Bend:s.value<t.value?this.bendType=e?l.Release:l.PrebendRelease:this.bendType=l.Hold}}else null!==r&&0!==r.length||(this.bendType=l.None);this.initialBendValue>0&&(this.accidentalMode=y.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+Z.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+Z.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-Z.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(Z.NoteIdLookupKey)?t=e.get(Z.NoteIdLookupKey):(t=new Map,e.set(Z.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??Z.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 K),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new K),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new K),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new K),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new K),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new K),this._noteIdBag.hammerPullDestinationNoteId=t,!0}return!1}}Z.GlobalNoteId=0,Z.MaxOffsetForSameLineSearch=3,Z.NoteIdLookupKey="NoteIdLookup";class ee{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!==g.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 ee.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}ee.HalfTicks=1920,ee.QuarterTicks=960,ee.EighthTicks=480,ee.SixteenthTicks=240,ee.ThirtySecondTicks=120,ee.SixtyFourthTicks=60,ee.OneHundredTwentyEighthTicks=30,ee.TwoHundredFiftySixthTicks=15,ee.AllTicks=[ee.HalfTicks,ee.QuarterTicks,ee.EighthTicks,ee.SixteenthTicks,ee.ThirtySecondTicks,ee.SixtyFourthTicks,ee.OneHundredTwentyEighthTicks,ee.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"}(E||(E={}));class te{static clone(e){const t=new z;return t.offset=e.offset,t.value=e.value,t}}class se{static clone(e){const t=new Z;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(te.clone(s))}return t.fret=e.fret,t.string=e.string,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.isFingering=e.isFingering,t.trillValue=e.trillValue,t.trillSpeed=e.trillSpeed,t.durationPercent=e.durationPercent,t.accidentalMode=e.accidentalMode,t.dynamics=e.dynamics,t}}class ie{static clone(e){const t=new V;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class ae{static clone(e){const t=new ne;t.index=e.index,t.notes=[];for(const s of e.notes)t.addNote(se.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(ie.clone(s));if(t.dots=e.dots,t.fadeIn=e.fadeIn,t.lyrics=e.lyrics?e.lyrics.slice():null,t.hasRasgueado=e.hasRasgueado,t.pop=e.pop,t.slap=e.slap,t.tap=e.tap,t.text=e.text,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(te.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.dynamics=e.dynamics,t.invertBeamDirection=e.invertBeamDirection,t.preferredBeamDirection=e.preferredBeamDirection,t.isEffectSlurOrigin=e.isEffectSlurOrigin,t.beamingMode=e.beamingMode,t}}class re{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.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext"}(F||(F={}));class ne{constructor(){this.id=ne._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=h.Default,this.ottava=n.Regular,this.fermata=null,this.isLegatoOrigin=!1,this.minNote=null,this.maxNote=null,this.maxStringNote=null,this.minStringNote=null,this.duration=u.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fadeIn=!1,this.lyrics=null,this.hasRasgueado=!1,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.brushType=c.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=E.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=_.None,this.chordId=null,this.graceType=g.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=x.None,this.tremoloSpeed=null,this.crescendo=d.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.dynamics=p.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=F.Auto}get isLastOfVoice(){return this.index===this.voice.beats.length-1}get isLegatoDestination(){return!!this.previousBeat&&this.previousBeat.isLegatoOrigin}get isRest(){return this.isEmpty||0===this.notes.length}get isFullBarRest(){return this.isRest&&1===this.voice.beats.length&&this.duration===u.Whole}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==E.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}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===E.None&&(this.whammyBarType=E.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=W.toTicks(this.duration);return 2===this.dots?e=W.applyDot(e,!0):1===this.dots&&(e=W.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=W.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){let e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case g.BeforeBeat:case g.OnBeat:switch(this.duration){case u.Sixteenth:this.playbackDuration=W.toTicks(u.SixtyFourth);break;case u.ThirtySecond:this.playbackDuration=W.toTicks(u.OneHundredTwentyEighth);break;default:this.playbackDuration=W.toTicks(u.ThirtySecond)}this.displayDuration=0;break;case g.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;let t=this.previousBeat;t&&t.graceType===g.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){let e=this.previousBeat,t=e?e.tupletGroup:null;(this.hasTuplet||this.graceType!==g.None&&t)&&(e&&t&&t.check(this)||(t=new ee(this.voice),t.check(this)),this.tupletGroup=t)}finish(e,t=null){switch(null===this.getAutomation(a.Instrument)&&0===this.index&&0===this.voice.index&&0===this.voice.bar.index&&0===this.voice.bar.staff.index&&this.automations.push(V.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case g.OnBeat:case g.BeforeBeat:let e=this.graceGroup.beats.length;this.duration=1===e?u.Eighth:2===e?u.Sixteenth:u.ThirtySecond}let s=e?e.notation.notationMode:T.GuitarPro,i="grad"===this.text||"grad."===this.text;i&&s===T.SongBook&&(this.text="");let r=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let n=0,o=!1;for(let a=0,c=this.notes.length;a<c;a++){let c=this.notes[a];if(c.dynamics=this.dynamics,c.finish(e,t),c.isLetRing&&(this.isLetRing=!0),c.isPalmMute&&(this.isPalmMute=!0),s===T.SongBook&&c.hasBend&&this.graceType!==g.BendGrace){if(!c.isTieOrigin)switch(c.bendType){case l.Bend:case l.PrebendRelease:case l.PrebendBend:r=!0}i||c.bendStyle===h.Gradual?(i=!0,c.bendStyle=h.Gradual,r=!1):c.bendStyle=h.Fast}c.isVisible&&(n++,(!this.minNote||c.realValue<this.minNote.realValue)&&(this.minNote=c),(!this.maxNote||c.realValue>this.maxNote.realValue)&&(this.maxNote=c),(!this.minStringNote||c.string<this.minStringNote.string)&&(this.minStringNote=c),(!this.maxStringNote||c.string>this.maxStringNote.string)&&(this.maxStringNote=c),c.hasEffectSlur&&(o=!0))}if(o&&(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===n&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&e&&e.notation.notationMode===T.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 c=this.whammyBarPoints;if(null!==c&&c.length>0&&this.whammyBarType===E.Custom){s===T.SongBook&&(this.whammyStyle=i?h.Gradual:h.Fast);let e=!!this.previousBeat&&this.previousBeat.hasWhammyBar;if(this.isContinuedWhammy=e,4===c.length){let t=c[0],i=c[1],a=c[2],r=c[3];i.value===a.value&&(t.value<i.value&&i.value<r.value||t.value>i.value&&i.value>r.value?(0===t.value||e?this.whammyBarType=E.Dive:this.whammyBarType=E.PrediveDive,c.splice(2,1),c.splice(1,1)):t.value>i.value&&i.value<r.value||t.value<i.value&&i.value>r.value?(this.whammyBarType=E.Dip,i.offset!==a.offset&&s!==T.SongBook||c.splice(2,1)):t.value===i.value&&i.value===r.value&&(0===t.value||e?this.whammyBarType=E.Hold:this.whammyBarType=E.Predive,c.splice(2,1),c.splice(1,1)))}}if(this.updateDurations(),r){let e=ae.clone(this);e.id=ne._globalBeatId++,e.pickStroke=x.None;for(let t=0,s=e.notes.length;t<s;t++){let s=e.notes[t],i=this.notes[t];if(s.bendType=l.None,s.maxBendPoint=null,s.bendPoints=null,s.bendStyle=h.Default,s.id=Z.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=Z.findTieOrigin(i);if(e&&e.hasBend){s.bendType=l.Hold;let e=i.bendPoints[i.bendPoints.length-1];s.addBendPoint(new z(0,e.value)),s.addBendPoint(new z(z.MaxPosition,e.value))}}s.isTieDestination=!0}this.graceType=g.BendGrace,this.graceGroup=new re,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new re,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)}}ne._globalBeatId=0;class oe{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.Cb=-7]="Cb",e[e.Gb=-6]="Gb",e[e.Db=-5]="Db",e[e.Ab=-4]="Ab",e[e.Eb=-3]="Eb",e[e.Bb=-2]="Bb",e[e.F=-1]="F",e[e.C=0]="C",e[e.G=1]="G",e[e.D=2]="D",e[e.A=3]="A",e[e.E=4]="E",e[e.B=5]="B",e[e.FSharp=6]="FSharp",e[e.CSharp=7]="CSharp"}(L||(L={})),function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.Text=2]="Text",e[e.Comment=3]="Comment",e[e.Dash=4]="Dash"}(M||(M={}));class he{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=M.Begin,r=M.Begin,n=!1,o=0;for(;t<e.length;){let s=e.charCodeAt(t);switch(a){case M.IgnoreSpaces:switch(s){case he.CharCodeLF:case he.CharCodeCR:case he.CharCodeTab:break;case he.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case M.Begin:if(s!==he.CharCodeBrackedOpen){o=t,a=M.Text;continue}a=M.Comment;break;case M.Comment:if(s===he.CharCodeBrackedClose)a=M.Begin;break;case M.Text:switch(s){case he.CharCodeDash:a=M.Dash;break;case he.CharCodeCR:case he.CharCodeLF:case he.CharCodeSpace:let s=e.substr(o,t-o);this.addChunk(s,i),a=M.IgnoreSpaces,r=M.Begin}break;case M.Dash:if(s!==he.CharCodeDash){let s=e.substr(o,t-o);this.addChunk(s,i),n=!0,a=M.IgnoreSpaces,r=M.Begin;continue}}t+=1}a===M.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}}he.CharCodeLF=10,he.CharCodeTab=9,he.CharCodeCR=13,he.CharCodeSpace=32,he.CharCodeBrackedClose=93,he.CharCodeBrackedOpen=91,he.CharCodeDash=45,function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(I||(I={})),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"}(D||(D={}));class le{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=L.C,this.keySignatureType=I.Major,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.tripletFeel=D.NoTripletFeel,this.section=null,this.tempoAutomation=null,this.fermata=null,this.start=0,this.isAnacrusis=!1,this.displayScale=1,this.displayWidth=-1}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}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*W.valueToTicks(this.timeSignatureDenominator)}addFermata(e,t){let s=this.fermata;null===s&&(s=new Map,this.fermata=s),s.set(e,t)}getFermata(e){const t=this.fermata;return null===t?null:t.has(e.playbackStart)?t.get(e.playbackStart):null}}le.MaxAlternateEndings=8;class ce{constructor(){this.hideDynamics=!1}}class de{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 ue{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 ce}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 de,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new de,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 ge extends O{constructor(e){super(s.Format,e),Object.setPrototypeOf(this,ge.prototype)}}class fe{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="#"+j.toHexString(this.r,2)+j.toHexString(this.g,2)+j.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 fe(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){switch(typeof e){case"number":{const t=new fe(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 fe(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16));if(5===t.length)return new fe(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 fe(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16));if(9===t.length)return new fe(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 ge("No values specified for rgb/rgba function");const i=t.substring(e+1,s).split(",");if(3===i.length)return new fe(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]));if(4===i.length)return new fe(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]),255*parseFloat(i[3]))}return null}}throw new ge("Unsupported format for color")}static toJson(e){return e.raw}}fe.BlackRgb="#000000";class me{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 ye{static getTextForTuning(e,t){let s=ye.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 ye._defaultTunings.has(e)?ye._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return ye._sevenStrings;case 6:return ye._sixStrings;case 5:return ye._fiveStrings;case 4:return ye._fourStrings}return[]}static initialize(){ye._defaultTunings.set(7,new ye("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),ye._sevenStrings.push(ye._defaultTunings.get(7)),ye._defaultTunings.set(6,new ye("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),ye._sixStrings.push(ye._defaultTunings.get(6)),ye._sixStrings.push(new ye("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),ye._sixStrings.push(new ye("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),ye._sixStrings.push(new ye("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),ye._sixStrings.push(new ye("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),ye._sixStrings.push(new ye("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),ye._sixStrings.push(new ye("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),ye._sixStrings.push(new ye("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),ye._sixStrings.push(new ye("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),ye._sixStrings.push(new ye("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),ye._sixStrings.push(new ye("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),ye._sixStrings.push(new ye("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),ye._sixStrings.push(new ye("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),ye._sixStrings.push(new ye("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),ye._sixStrings.push(new ye("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),ye._sixStrings.push(new ye("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),ye._sixStrings.push(new ye("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),ye._sixStrings.push(new ye("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),ye._sixStrings.push(new ye("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),ye._sixStrings.push(new ye("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),ye._sixStrings.push(new ye("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),ye._sixStrings.push(new ye("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),ye._sixStrings.push(new ye("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),ye._sixStrings.push(new ye("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),ye._defaultTunings.set(5,new ye("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),ye._fiveStrings.push(ye._defaultTunings.get(5)),ye._fiveStrings.push(new ye("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),ye._fiveStrings.push(new ye("Banjo Open D Tuning",[62,57,54,50,69],!1)),ye._fiveStrings.push(new ye("Banjo Open G Tuning",[62,59,55,50,67],!1)),ye._fiveStrings.push(new ye("Banjo G Minor Tuning",[62,58,55,50,67],!1)),ye._fiveStrings.push(new ye("Banjo G Modal Tuning",[62,57,55,50,67],!1)),ye._defaultTunings.set(4,new ye("Bass Standard Tuning",[43,38,33,28],!0)),ye._fourStrings.push(ye._defaultTunings.get(4)),ye._fourStrings.push(new ye("Bass Tune down ½ step",[42,37,32,27],!1)),ye._fourStrings.push(new ye("Bass Tune down 1 step",[41,36,31,26],!1)),ye._fourStrings.push(new ye("Bass Tune down 2 step",[39,34,29,24],!1)),ye._fourStrings.push(new ye("Bass Dropped D Tuning",[43,38,33,26],!1)),ye._fourStrings.push(new ye("Ukulele C Tuning",[45,40,36,43],!1)),ye._fourStrings.push(new ye("Ukulele G Tuning",[52,47,43,38],!1)),ye._fourStrings.push(new ye("Mandolin Standard Tuning",[64,57,50,43],!1)),ye._fourStrings.push(new ye("Mandolin or Violin Tuning",[76,69,62,55],!1)),ye._fourStrings.push(new ye("Viola Tuning",[69,62,55,48],!1)),ye._fourStrings.push(new ye("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){let t=ye.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=ye.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}ye._sevenStrings=[],ye._sixStrings=[],ye._fiveStrings=[],ye._fourStrings=[],ye._defaultTunings=new Map,ye.defaultAccidentals=["","#","","#","","","#","","#","","#",""],ye.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],ye.initialize();class be{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new ye("",[],!1),this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=5}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)}}class Se{constructor(){this.index=0,this.staves=[],this.playbackInfo=new me,this.color=new fe(200,0,0,255),this.name="",this.shortName="",this.defaultSystemsLayout=3,this.systemsLayout=[],this.percussionArticulations=[]}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new be)}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>Se.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,Se.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)}}}}}Se.ShortNameMaxLength=10;let _e=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===g.None?(i.graceGroup=s,s&&(s.isComplete=!0),s=null):(s||(s=new re),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===g.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==g.BendGrace){let s=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case g.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 g.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}};_e._globalBarId=0;class we{static float64ToBytes(e){return we._dataView.setFloat64(0,e,!0),this._conversionByteArray}static bytesToFloat64(e){throw we._conversionByteArray.set(e,0),we._dataView.getFloat64(0,!0)}static uint16ToInt16(e){return we._dataView.setUint16(0,e,!0),we._dataView.getInt16(0,!0)}static int16ToUint32(e){return we._dataView.setInt16(0,e,!0),we._dataView.getUint32(0,!0)}static int32ToUint16(e){return we._dataView.setInt32(0,e,!0),we._dataView.getUint16(0,!0)}static int32ToInt16(e){return we._dataView.setInt32(0,e,!0),we._dataView.getInt16(0,!0)}static int32ToUint32(e){return we._dataView.setInt32(0,e,!0),we._dataView.getUint32(0,!0)}static uint8ToInt8(e){return we._dataView.setUint8(0,e),we._dataView.getInt8(0)}}we._conversionBuffer=new ArrayBuffer(8),we._conversionByteArray=new Uint8Array(we._conversionBuffer),we._dataView=new DataView(we._conversionBuffer);class Be{static readInt32BE(e){return e.readByte()<<24|e.readByte()<<16|e.readByte()<<8|e.readByte()}static readInt32LE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|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 we.int32ToUint16(s<<8|t)}static readInt16LE(e){let t=e.readByte(),s=e.readByte();return we.int32ToInt16(s<<8|t)}static readUInt32BE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte(),a=e.readByte();return we.int32ToUint32(t<<24|s<<16|i<<8|a)}static readUInt16BE(e){let t=e.readByte(),s=e.readByte();return we.int32ToInt16(t<<8|s)}static readInt16BE(e){let t=e.readByte(),s=e.readByte();return we.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),Be.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 we.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){let s=Be.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)}}class Te{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return Te.withCapacity(0)}static withCapacity(e){let t=new Te;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){let t=new Te;return t._buffer=e,t.length=e.length,t}static fromString(e){let t=Be.stringToBytes(e);return Te.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)}}var ke,ve,xe,Ne,Pe,Ce,Ee,Fe,Le,Me,Ie,De,Ae,Re,Oe,Ge,Ve,He,We,ze,Ue,Xe,Ye,qe,Je,je,Qe,$e,Ke,Ze;!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"}(ke||(ke={}));class et extends O{constructor(e,t,i,a,r,n,o,h=null){super(s.AlphaTex,e),this.position=t,this.line=i,this.col=a,this.nonTerm=r??"",this.expected=n??ke.No,this.symbol=o??ke.No,this.symbolData=h,Object.setPrototypeOf(this,et.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 ${ke[a]} found a ${ke[r]}`,null!==n&&(o+=`: '${n}'`)):o+=`, invalid value: '${n}'`,new et(o,e,t,s,i,a,r,n)}static errorMessage(e,t,s,i){return new et(e=`MalFormed AlphaTex: @${t} (line ${s}, col ${i}): ${e}`,t,s,i,null,null,null,null)}}class tt extends R{constructor(){super(),this._trackChannel=0,this._input="",this._ch=tt.Eof,this._curChPos=0,this._line=1,this._col=0,this._lastValidSpot=[0,1,0],this._sy=ke.No,this._syData="",this._allowNegatives=!1,this._allowFloat=!1,this._allowTuning=!1,this._currentDuration=u.QuadrupleWhole,this._currentDynamics=p.PPP,this._currentTuplet=0,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=Te.empty(),this._input=e,this.settings=t}readScore(){try{if(this.data.length>0&&(this._input=Be.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this.createDefaultScore(),this._curChPos=0,this._line=1,this._col=0,this.saveValidSpot(),this._currentDuration=u.Quarter,this._currentDynamics=p.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===ke.LowerThan)throw new G("Unknown start sign '<' (meant to import as XML?)");if(this._sy===ke.Eof)throw new G("Unexpected end of file");const e=this.metaData(),t=this.bars();if(!e&&!t)throw new G("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);return this._score}catch(e){throw e instanceof et?new G(e.message,e):e}}consolidate(){for(let e of this._score.tracks)for(let t of e.staves)for(;t.bars.length<this._score.masterBars.length;){let e=this.newBar(t),s=new ne;s.isEmpty=!0,e.voices[0].addBeat(s)}}error(e,t,s=!0){let i,a=!1;s?(i=this._sy,i!==ke.String&&i!==ke.Number&&i!==ke.MetaCommand||(a=!0)):i=t;let r=et.symbolError(this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2],e,t,i,a?this._syData:null);throw this.logErrors&&q.error(this.name,r.message),r}errorMessage(e){let t=et.errorMessage(e,this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2]);throw this.logErrors&&q.error(this.name,t.message),t}createDefaultScore(){this._score=new ue,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new Se,this._currentTrack.ensureStaveCount(1),this._currentTrack.playbackInfo.program=25,this._currentTrack.playbackInfo.primaryChannel=this._trackChannel++,this._currentTrack.playbackInfo.secondaryChannel=this._trackChannel++,this._currentStaff=this._currentTrack.staves[0],this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=ye.getDefaultTuningFor(6).tunings,this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=p.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":default:return r.G2;case"f4":case"bass":return r.F4;case"c3":case"tenor":return r.C3;case"c4":case"alto":return r.C4;case"n":case"neutral":return r.Neutral}}parseClefFromInt(e){switch(e){case 43:default:return r.G2;case 65:return r.F4;case 48:return r.C3;case 60:return r.C4}}parseTripletFeelFromString(e){switch(e.toLowerCase()){case"no":case"none":default:return D.NoTripletFeel;case"t16":case"triplet-16th":return D.Triplet16th;case"t8":case"triplet-8th":return D.Triplet8th;case"d16":case"dotted-16th":return D.Dotted16th;case"d8":case"dotted-8th":return D.Dotted8th;case"s16":case"scottish-16th":return D.Scottish16th;case"s8":case"scottish-8th":return D.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return D.NoTripletFeel;case 1:return D.Triplet16th;case 2:return D.Triplet8th;case 3:return D.Dotted16th;case 4:return D.Dotted8th;case 5:return D.Scottish16th;case 6:return D.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":return L.Cb;case"gb":case"gbmajor":case"d#minor":return L.Gb;case"db":case"dbmajor":case"bbminor":return L.Db;case"ab":case"abmajor":case"fminor":return L.Ab;case"eb":case"ebmajor":case"cminor":return L.Eb;case"bb":case"bbmajor":case"gminor":return L.Bb;case"f":case"fmajor":case"dminor":return L.F;case"c":case"cmajor":case"aminor":default:return L.C;case"g":case"gmajor":case"eminor":return L.G;case"d":case"dmajor":case"bminor":return L.D;case"a":case"amajor":case"f#minor":return L.A;case"e":case"emajor":case"c#minor":return L.E;case"b":case"bmajor":case"g#minor":return L.B;case"f#":case"f#major":case"ebminor":return L.FSharp;case"c#":case"c#major":return L.CSharp}}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=tt.Eof,this._ch}saveValidSpot(){this._lastValidSpot=[this._curChPos,this._line,this._col]}newSy(){for(this.saveValidSpot(),this._sy=ke.No;this._sy===ke.No;)if(this._ch===tt.Eof)this._sy=ke.Eof;else if(tt.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!==tt.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;this._ch!==tt.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",ke.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=ke.String;this._ch!==e&&this._ch!==tt.Eof;)t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._ch===tt.Eof&&this.errorMessage("String opened but never closed"),this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)this._allowNegatives?(this._sy=ke.Number,this._syData=this.readNumber()):(this._sy=ke.String,this._syData=this.readName());else if(46===this._ch)this._sy=ke.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=ke.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=ke.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=ke.MetaCommand,this._syData=this.readName();else if(41===this._ch)this._sy=ke.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=ke.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=ke.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=ke.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=ke.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=ke.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this._sy=ke.Number,this._syData=this.readNumber();else if(tt.isNameLetter(this._ch)){let e=this.readName(),t=this._allowTuning?j.parseTuning(e):null;t?(this._sy=ke.Tuning,this._syData=t):(this._sy=ke.String,this._syData=e)}else this.error("symbol",ke.String,!1);return this._sy}static isNameLetter(e){return!tt.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||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(tt.isNameLetter(this._ch)||this.isDigit(this._ch));return e}readNumber(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(this.isDigit(this._ch));return this._allowFloat?parseFloat(e):parseInt(e)}metaData(){let e=!1,t=!0;for(;this._sy===ke.MetaCommand&&t;){let s=this._syData.toLowerCase();switch(s){case"title":case"subtitle":case"artist":case"album":case"words":case"music":case"copyright":this._sy=this.newSy(),this._sy!==ke.String&&this.error(s,ke.String,!0);let i=this._syData;switch(s){case"title":this._score.title=i;break;case"subtitle":this._score.subTitle=i;break;case"artist":this._score.artist=i;break;case"album":this._score.album=i;break;case"words":this._score.words=i;break;case"music":this._score.music=i;break;case"copyright":this._score.copyright=i}this._sy=this.newSy(),e=!0;break;case"tempo":this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy===ke.Number?this._score.tempo=this._syData:this.error("tempo",ke.Number,!0),this._sy=this.newSy(),e=!0;break;default:this.handleStaffMeta()?e=!0:e?this.error("metaDataTags",ke.String,!1):t=!1}}return e?(this._sy!==ke.Dot&&this.error("song",ke.Dot,!0),this._sy=this.newSy()):this._sy===ke.Dot&&(this._sy=this.newSy()),e}handleStaffMeta(){switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===ke.Number?this._currentStaff.capo=this._syData:this.error("capo",ke.Number,!0),this._sy=this.newSy(),!0;case"tuning":this._sy=this.newSy();let e=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case ke.String:let e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?(this._currentStaff.stringTuning.tunings=[],this._currentStaff.displayTranspositionPitch=0):this.error("tuning",ke.Tuning,!0),this._sy=this.newSy();break;case ke.Tuning:let t=[];do{let e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===ke.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",ke.Tuning,!0)}return e!==this._currentStaff.tuning.length&&(this._currentStaff.chords?.size??0)>0&&this.errorMessage("Tuning must be defined before any chord"),!0;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===ke.Number){let e=this._syData;e>=0&&e<=127?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",ke.Number,!1)}else if(this._sy===ke.String){let e=this._syData.toLowerCase();this._currentTrack.playbackInfo.program=A.getValue(e)}else this.error("instrument",ke.Number,!0);return this._sy=this.newSy(),!0;case"lyrics":this._sy=this.newSy();let t=new he;return t.startBar=0,t.text="",this._sy===ke.Number&&(t.startBar=this._syData,this._sy=this.newSy()),this._sy===ke.String?(t.text=this._syData,this._sy=this.newSy()):this.error("lyrics",ke.String,!0),this._lyrics.get(this._currentTrack.index).push(t),!0;case"chord":this._sy=this.newSy();let s=new oe;this.chordProperties(s),this._sy===ke.String?(s.name=this._syData,this._sy=this.newSy()):this.error("chord-name",ke.Number,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===ke.Number?s.strings.push(this._syData):this._sy===ke.String&&"x"===this._syData.toLowerCase()&&s.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,s.name),s),!0;default:return!1}}chordProperties(e){if(this._sy===ke.LBrace){for(this._sy=this.newSy();this._sy===ke.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===ke.Number)e.firstFret=this._syData;else this.error("chord-firstfret",ke.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case ke.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case ke.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",ke.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case ke.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case ke.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",ke.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case ke.String:e.showName="false"!==this._syData.toLowerCase();break;case ke.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",ke.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===ke.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",ke.String,!1)}this._sy!==ke.RBrace&&this.error("chord-properties",ke.RBrace,!0),this._sy=this.newSy()}}bars(){let e=this.bar();for(;this._sy!==ke.Eof;)if(this._sy===ke.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==ke.MetaCommand)break;this.bar()}return e}trackStaffMeta(){return this._sy===ke.MetaCommand&&("track"===this._syData.toLowerCase()&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===ke.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===ke.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy())),this._sy===ke.MetaCommand&&"staff"===this._syData.toLowerCase()&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0&&(this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this._currentStaff=this._currentTrack.staves[this._currentTrack.staves.length-1],this._currentDynamics=p.F),this.staffProperties()),!0)}staffProperties(){if(this._sy!==ke.LBrace)return;this._sy=this.newSy();let e=!1,t=!1;for(;this._sy===ke.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy();break;case"tabs":t=!0,this._sy=this.newSy();break;default:this.error("staff-properties",ke.String,!1)}(e||t)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t),this._sy!==ke.RBrace&&this.error("staff-properties",ke.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 le;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);if(!this._staffTuningApplied&&!this._staffHasExplicitTuning){const e=this._currentTrack.playbackInfo.program;this._currentStaff.displayTranspositionPitch=0,this._currentStaff.stringTuning.tunings=[],15==e||e>=24&&e<=31?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=ye.getDefaultTuningFor(6).tunings):e>=32&&e<=39?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):40==e||44==e||45==e||48==e||49==e||50==e||51==e?this._currentStaff.stringTuning.tunings=[52,57,50,43]:41==e?this._currentStaff.stringTuning.tunings=[57,50,43,36]:42==e?this._currentStaff.stringTuning.tunings=[45,38,31,24]:43==e?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):105==e?this._currentStaff.stringTuning.tunings=[50,47,43,38,55]:106==e?this._currentStaff.stringTuning.tunings=[57,52,45]:107==e?this._currentStaff.stringTuning.tunings=[52,45,38,31]:110==e&&(this._currentStaff.stringTuning.tunings=[64,57,50,43]),this._staffTuningApplied=!0}let i=!1,a=t.voices[0];for(;this._sy!==ke.Pipe&&this._sy!==ke.Eof&&this.beat(a);)i=!0;if(0===a.beats.length){let e=new ne;e.isEmpty=!0,a.addBeat(e)}return e||s||i}newBar(e){let t=new H;e.addBar(t),t.index>0&&(t.clef=t.previousBar.clef);let s=new _e;return t.addVoice(s),t}beat(e){this.beatDuration();let t=new ne;if(e.addBeat(t),this._sy===ke.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==ke.RParensis&&this._sy!==ke.Eof&&this.note(t););this._sy!==ke.RParensis&&this.error("note-list",ke.RParensis,!0),this._sy=this.newSy()}else if(this._sy===ke.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===ke.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==ke.Number&&this.error("duration",ke.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||tt.applyTuplet(t,this._currentTuplet);let s=1;this._sy===ke.Multiply&&(this._sy=this.newSy(),this._sy!==ke.Number?this.error("multiplier",ke.Number,!0):s=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let i=0;i<s-1;i++)e.addBeat(ae.clone(t));return!0}beatDuration(){if(this._sy===ke.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==ke.Number&&this.error("duration",ke.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===ke.LBrace)){for(this._sy=this.newSy();this._sy===ke.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==ke.Number&&this.error("duration-tuplet",ke.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",ke.String,!1)}this._sy!==ke.RBrace&&this.error("beat-duration",ke.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===ke.LBrace){for(this._sy=this.newSy();this._sy===ke.String;)this.applyBeatEffect(e)||this.error("beat-effects",ke.String,!1);this._sy!==ke.RBrace&&this.error("beat-effects",ke.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){let t=this._syData.toLowerCase();if("f"===t)e.fadeIn=!0;else if("v"===t)e.vibrato=_.Slight;else if("s"===t)e.slap=!0;else if("p"===t)e.pop=!0;else if("tt"===t)e.tap=!0;else if("dd"===t)e.dots=2;else if("d"===t)e.dots=1;else if("su"===t)e.pickStroke=x.Up;else if("sd"===t)e.pickStroke=x.Down;else if("tu"===t){if(this._sy=this.newSy(),this._sy!==ke.Number)return this.error("tuplet",ke.Number,!0),!1;tt.applyTuplet(e,this._syData)}else if("tb"===t||"tbe"===t){let s="tbe"===t;for(this._sy=this.newSy(),this._sy!==ke.LParensis&&this.error("tremolobar-effect",ke.LParensis,!0),this._allowNegatives=!0,this._sy=this.newSy();this._sy!==ke.RParensis&&this._sy!==ke.Eof;){let t=0,i=0;s?(this._sy!==ke.Number&&this.error("tremolobar-effect",ke.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==ke.Number&&this.error("tremolobar-effect",ke.Number,!0),i=this._syData):(this._sy!==ke.Number&&this.error("tremolobar-effect",ke.Number,!0),t=0,i=this._syData),e.addWhammyBarPoint(new z(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._sy!==ke.RParensis&&this.error("tremolobar-effect",ke.RParensis,!0)}else{if("bu"===t||"bd"===t||"au"===t||"ad"===t){switch(t){case"bu":e.brushType=c.BrushUp;break;case"bd":e.brushType=c.BrushDown;break;case"au":e.brushType=c.ArpeggioUp;break;case"ad":e.brushType=c.ArpeggioDown}return this._sy=this.newSy(),this._sy===ke.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 oe;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=g.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=g.BendGrace,this._sy=this.newSy()):e.graceType=g.BeforeBeat,!0;if("dy"===t){switch(this._sy=this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=p.PPP;break;case"pp":e.dynamics=p.PP;break;case"p":e.dynamics=p.P;break;case"mp":e.dynamics=p.MP;break;case"mf":e.dynamics=p.MF;break;case"f":e.dynamics=p.F;break;case"ff":e.dynamics=p.FF;break;case"fff":e.dynamics=p.FFF}this._currentDynamics=e.dynamics}else if("cre"===t)e.crescendo=d.Crescendo;else{if("dec"!==t){if("tp"===t){if(this._sy=this.newSy(),e.tremoloSpeed=u.Eighth,this._sy===ke.Number){switch(this._syData){case 8:default:e.tremoloSpeed=u.Eighth;break;case 16:e.tremoloSpeed=u.Sixteenth;break;case 32:e.tremoloSpeed=u.ThirtySecond}this._sy=this.newSy()}return!0}return!1}e.crescendo=d.Decrescendo}}}return this._sy=this.newSy(),!0}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;switch(this._sy){case ke.Number:i=this._syData;break;case ke.String:t="x"===this._syData,s="-"===this._syData,s||t?i=0:this.error("note-fret",ke.Number,!0);break;case ke.Tuning:let e=this._syData;a=e.octave,r=e.noteValue;break;default:return!1}this._sy=this.newSy();let n=-1===a&&this._currentStaff.tuning.length>0,o=-1;n&&(this._sy!==ke.Dot&&this.error("note",ke.Dot,!0),this._sy=this.newSy(),this._sy!==ke.Number&&this.error("note-string",ke.Number,!0),o=this._syData,(o<1||o>this._currentStaff.tuning.length)&&this.error("note-string",ke.Number,!1),this._sy=this.newSy());let h=new Z;return n?(h.string=this._currentStaff.tuning.length-(o-1),h.isDead=t,h.isTieDestination=s,s||(h.fret=i)):(h.octave=a,h.tone=r,h.isTieDestination=s),e.addNote(h),this.noteEffects(h),!0}noteEffects(e){if(this._sy===ke.LBrace){for(this._sy=this.newSy();this._sy===ke.String;){let t=this._syData.toLowerCase();if("b"===t||"be"===t){let s="be"===t;for(this._sy=this.newSy(),this._sy!==ke.LParensis&&this.error("bend-effect",ke.LParensis,!0),this._sy=this.newSy();this._sy!==ke.RParensis&&this._sy!==ke.Eof;){let t=0,i=0;s?(this._sy!==ke.Number&&this.error("bend-effect-value",ke.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==ke.Number&&this.error("bend-effect-value",ke.Number,!0),i=this._syData):(this._sy!==ke.Number&&this.error("bend-effect-value",ke.Number,!0),i=this._syData),e.addBendPoint(new z(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!==ke.RParensis&&this.error("bend-effect",ke.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=m.Natural,this._sy=this.newSy();else if("ah"===t)e.harmonicType=m.Artificial,this._sy=this.newSy();else if("th"===t)e.harmonicType=m.Tap,this._sy=this.newSy();else if("ph"===t)e.harmonicType=m.Pinch,this._sy=this.newSy();else if("sh"===t)e.harmonicType=m.Semi,this._sy=this.newSy();else if("tr"===t){this._sy=this.newSy(),this._sy!==ke.Number&&this.error("trill-effect",ke.Number,!0);let t=this._syData;this._sy=this.newSy();let s=u.Sixteenth;if(this._sy===ke.Number){switch(this._syData){case 16:default:s=u.Sixteenth;break;case 32:s=u.ThirtySecond;break;case 64:s=u.SixtyFourth}this._sy=this.newSy()}e.trillValue=t+e.stringTuning,e.trillSpeed=s}else if("v"===t)this._sy=this.newSy(),e.vibrato=_.Slight;else if("sl"===t)this._sy=this.newSy(),e.slideOutType=S.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=S.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=b.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=b.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=S.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=S.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=S.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=S.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=i.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=i.Heavy;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=f.Thumb;this._sy===ke.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.leftHandFinger=t}else if("rf"===t){this._sy=this.newSy();let t=f.Thumb;this._sy===ke.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else this.applyBeatEffect(e.beat)||this.error(t,ke.String,!1)}this._sy!==ke.RBrace&&this.error("note-effect",ke.RBrace,!1),this._sy=this.newSy()}}toFinger(e){switch(e){case 1:return f.Thumb;case 2:return f.IndexFinger;case 3:return f.MiddleFinger;case 4:return f.AnnularFinger;case 5:return f.LittleFinger}return f.Thumb}parseDuration(e){switch(e){case-4:return u.QuadrupleWhole;case-2:return u.DoubleWhole;case 1:return u.Whole;case 2:return u.Half;case 4:return u.Quarter;case 8:return u.Eighth;case 16:return u.Sixteenth;case 32:return u.ThirtySecond;case 64:return u.SixtyFourth;case 128:return u.OneHundredTwentyEighth;case 256:return u.TwoHundredFiftySixth;default:return u.Quarter}}barMeta(e){let t=!1,s=e.masterBar;for(;this._sy===ke.MetaCommand;){t=!0;let i=this._syData.toLowerCase();if("ts"===i)this._sy=this.newSy(),this._sy!==ke.Number&&this.error("timesignature-numerator",ke.Number,!0),s.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==ke.Number&&this.error("timesignature-denominator",ke.Number,!0),s.timeSignatureDenominator=this._syData,this._sy=this.newSy();else if("ro"===i)s.isRepeatStart=!0,this._sy=this.newSy();else if("rc"===i)this._sy=this.newSy(),this._sy!==ke.Number&&this.error("repeatclose",ke.Number,!0),this._syData>2048&&this.error("repeatclose",ke.Number,!1),s.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===i)if(this._sy=this.newSy(),this._sy===ke.LParensis){for(this._sy=this.newSy(),this._sy!==ke.Number&&this.error("alternateending",ke.Number,!0),this.applyAlternateEnding(s);this._sy===ke.Number;)this.applyAlternateEnding(s);this._sy!==ke.RParensis&&this.error("alternateending-list",ke.RParensis,!0),this._sy=this.newSy()}else this._sy!==ke.Number&&this.error("alternateending",ke.Number,!0),this.applyAlternateEnding(s);else if("ks"===i)this._sy=this.newSy(),this._sy!==ke.String&&this.error("keysignature",ke.String,!0),s.keySignature=this.parseKeySignature(this._syData),this._sy=this.newSy();else if("clef"===i){switch(this._sy=this.newSy(),this._sy){case ke.String:e.clef=this.parseClefFromString(this._syData);break;case ke.Number:e.clef=this.parseClefFromInt(this._syData);break;case ke.Tuning:let t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",ke.String,!0)}this._sy=this.newSy()}else if("tempo"===i){this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==ke.Number&&this.error("tempo",ke.Number,!0);let e=new V;e.isLinear=!1,e.type=a.Tempo,e.value=this._syData,s.tempoAutomation=e,this._sy=this.newSy()}else if("section"===i){this._sy=this.newSy(),this._sy!==ke.String&&this.error("section",ke.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==ke.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"===i){switch(this._allowTuning=!1,this._sy=this.newSy(),this._allowTuning=!0,this._sy){case ke.String:s.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case ke.Number:s.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",ke.String,!0)}this._sy=this.newSy()}else"ac"===i?(s.isAnacrusis=!0,this._sy=this.newSy()):0===e.index&&this.handleStaffMeta()||this.error("measure-effects",ke.String,!1)}if(0===s.index&&!s.tempoAutomation){let e=new V;e.isLinear=!1,e.type=a.Tempo,e.value=this._score.tempo,s.tempoAutomation=e}return t}applyAlternateEnding(e){let t=this._syData;t<1&&this.error("alternateending",ke.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}}tt.Eof=0;class st extends R{get name(){return"Guitar Pro 3-5"}constructor(){super(),this._versionNumber=0,this._globalTripletFeel=D.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._beatTextChunksByTrack=new Map}readScore(){return this.readVersion(),this._score=new ue,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=it.gpReadBool(this.data)?D.Triplet8th:D.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=it.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=Be.readInt32LE(this.data),this._versionNumber>=510&&it.gpReadBool(this.data),Be.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.data.skip(38),this.data.skip(4)),this._barCount=Be.readInt32LE(this.data),this._trackCount=Be.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0&&(this._score.masterBars[0].tempoAutomation=V.buildTempoAutomation(!1,0,this._score.tempo,2),this._score.masterBars[0].tempoAutomation.text=this._score.tempoLabel),this._score.finish(this.settings),this._lyrics&&this._lyricsTrack>=0&&this._score.tracks[this._lyricsTrack].applyLyrics(this._lyrics),this._score}readVersion(){let e=it.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(st.VersionString))throw new G("Unsupported format");e=e.substr(st.VersionString.length+1);let t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*parseInt(e.substr(0,t))+parseInt(e.substr(t+1)),q.debug(this.name,"Guitar Pro version "+e+" detected")}readScoreInformation(){this._score.title=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?it.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding);let e=Be.readInt32LE(this.data),t="";for(let s=0;s<e;s++)s>0&&(t+="\r\n"),t+=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding)?.toString();this._score.notices=t}readLyrics(){this._lyrics=[],this._lyricsTrack=Be.readInt32LE(this.data)-1;for(let e=0;e<5;e++){let e=new he;e.startBar=Be.readInt32LE(this.data)-1,e.text=it.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(30);for(let e=0;e<10;e++)it.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){let t=new me;t.primaryChannel=e,t.secondaryChannel=e,t.program=Be.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 le,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=it.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",it.gpReadColor(this.data,!1),t.section=e}if(64&s?(t.keySignature=Be.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=D.Triplet8th;break;case 2:t.tripletFeel=D.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=!!(128&s),this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){let e=new Se;e.ensureStaveCount(1),this._score.addTrack(e);let t=e.staves[0],s=this.data.readByte();e.name=it.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),1&s&&(t.isPercussion=!0);let i=Be.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){let t=Be.readInt32LE(this.data);i>e&&a.push(t)}t.stringTuning.tunings=a;let r=Be.readInt32LE(this.data),n=Be.readInt32LE(this.data)-1,o=Be.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,A.isGuitar(i.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=i}t.capo=Be.readInt32LE(this.data),e.color=it.gpReadColor(this.data,!1),this._versionNumber>=500&&(this.data.readByte(),this.data.readByte(),this.data.skip(43)),this._versionNumber>=510&&(this.data.skip(4),it.gpReadStringIntByte(this.data,this.settings.importer.encoding),it.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 H,s=e.staves[0];s.isPercussion&&(t.clef=r.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=Be.readInt32LE(this.data);if(0===s)return;let i=new _e;t.addVoice(i);for(let a=0;a<s;a++)this.readBeat(e,t,i)}readBeat(e,t,s){let i=new ne,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),Be.readSInt8(this.data)){case-2:i.duration=u.Whole;break;case-1:i.duration=u.Half;break;case 0:i.duration=u.Quarter;break;case 1:i.duration=u.Eighth;break;case 2:i.duration=u.Sixteenth;break;case 3:i.duration=u.ThirtySecond;break;case 4:i.duration=u.SixtyFourth;break;default:i.duration=u.Quarter}if(32&a)switch(i.tupletNumerator=Be.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=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const s=new he;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=m.None;8&a&&(n=this.readBeatEffects(i)),16&a&&this.readMixTableChange(i);let o=this.data.readByte();for(let a=6;a>=0;a--)if(o&1<<a&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,s,i,6-a);n!==m.None&&(r.harmonicType=n,r.harmonicType===m.Natural&&(r.harmonicValue=this.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){this.data.readByte(),8&this.data.readByte()&&this.data.readByte()}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 oe,s=j.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=it.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Be.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Be.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=it.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Be.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Be.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=it.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=Be.readInt32LE(this.data);for(let s=0;s<6;s++){let i=Be.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=it.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=Be.readInt32LE(this.data),t.firstFret>0)for(let i=0;i<s;i++){let s=Be.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()),e.fadeIn=!!(16&t),(this._versionNumber<400&&1&t||2&t)&&(e.vibrato=_.Slight),e.hasRasgueado=!!(1&s),32&t&&this._versionNumber>=400){switch(Be.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(Be.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=c.BrushUp,e.brushDuration=st.toStrokeValue(t)):s>0&&(e.brushType=c.BrushDown,e.brushDuration=st.toStrokeValue(s))}if(2&s)switch(Be.readSInt8(this.data)){case 0:e.pickStroke=x.None;break;case 1:e.pickStroke=x.Up;break;case 2:e.pickStroke=x.Down}if(this._versionNumber<400){if(4&t)return m.Natural;if(8&t)return m.Artificial}return m.None}readTremoloBarEffect(e){this.data.readByte(),Be.readInt32LE(this.data);let t=Be.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new z(0,0);t.offset=Be.readInt32LE(this.data),t.value=Be.readInt32LE(this.data)/st.BendStep|0,it.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 at;t.instrument=Be.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=Be.readSInt8(this.data),t.balance=Be.readSInt8(this.data);let s=Be.readSInt8(this.data),i=Be.readSInt8(this.data),r=Be.readSInt8(this.data),n=Be.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=it.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=Be.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(),r>=0&&this.data.readByte(),n>=0&&this.data.readByte(),t.tempo>=0&&(t.duration=Be.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500&&this.data.readByte(),this._versionNumber>=510&&(it.gpReadStringIntByte(this.data,this.settings.importer.encoding),it.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){let s=new V;s.isLinear=!0,s.type=a.Volume,s.value=t.volume,e.automations.push(s)}if(t.balance>=0){let s=new V;s.isLinear=!0,s.type=a.Balance,s.value=t.balance,e.automations.push(s)}if(t.instrument>=0){let s=new V;s.isLinear=!0,s.type=a.Instrument,s.value=t.instrument,e.automations.push(s)}if(t.tempo>=0){let s=new V;s.isLinear=!0,s.type=a.Tempo,s.value=t.tempo,e.automations.push(s),e.voice.bar.masterBar.tempoAutomation=s}}readNote(e,t,s,a,r){let n=new Z;n.string=t.staff.tuning.length-r;let o=this.data.readByte();if(2&o?n.accentuated=i.Heavy:64&o&&(n.accentuated=i.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=Be.readSInt8(this.data);n.dynamics=this.toDynamicValue(e),a.dynamics=n.dynamics}32&o&&(n.fret=Be.readSInt8(this.data)),128&o&&(n.leftHandFinger=Be.readSInt8(this.data),n.rightHandFinger=Be.readSInt8(this.data),n.isFingering=!0);let h=!1;if(this._versionNumber>=500){1&o&&(n.durationPercent=it.gpReadDouble(this.data)),h=!!(2&this.data.readByte())}if(a.addNote(n),8&o&&this.readNoteEffects(e,s,a,n),t.staff.isPercussion&&(n.percussionArticulation=n.fret,n.string=-1,n.fret=-1),h){const e=ye.defaultAccidentals[n.realValueWithoutHarmonic%12];"#"===e?n.accidentalMode=y.ForceFlat:"b"===e&&(n.accidentalMode=y.ForceSharp)}return n}toDynamicValue(e){switch(e){case 1:return p.PPP;case 2:return p.PP;case 3:return p.P;case 4:return p.MP;case 5:return p.MF;case 6:default:return p.F;case 7:return p.FF;case 8:return p.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=S.Shift),16&r&&this.readArtificialHarmonic(i),32&r&&this.readTrill(i),i.isLetRing=!!(8&a),i.isHammerPullOrigin=!!(2&a),64&r&&(i.vibrato=_.Slight),i.isPalmMute=!!(2&r),i.isStaccato=!!(1&r)}readBend(e){this.data.readByte(),Be.readInt32LE(this.data);let t=Be.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new z(0,0);t.offset=Be.readInt32LE(this.data),t.value=Be.readInt32LE(this.data)/st.BendStep|0,it.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){let s=new ne,i=new Z;switch(i.string=t.string,i.fret=Be.readSInt8(this.data),s.duration=u.ThirtySecond,s.dynamics=this.toDynamicValue(Be.readSInt8(this.data)),Be.readSInt8(this.data)){case 0:case 2:break;case 1:i.slideOutType=S.Legato,i.slideTarget=t;break;case 3:i.isHammerPullOrigin=!0}if(i.dynamics=s.dynamics,this.data.skip(1),this._versionNumber<500)s.graceType=g.BeforeBeat;else{let e=this.data.readByte();i.isDead=!!(1&e),s.graceType=2&e?g.OnBeat:g.BeforeBeat}e.addGraceBeat(s),s.addNote(i)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=u.Eighth;break;case 2:e.tremoloSpeed=u.Sixteenth;break;case 3:e.tremoloSpeed=u.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){let t=Be.readSInt8(this.data);1&t?e.slideOutType=S.Shift:2&t?e.slideOutType=S.Legato:4&t?e.slideOutType=S.OutDown:8&t&&(e.slideOutType=S.OutUp),16&t?e.slideInType=b.IntoFromBelow:32&t&&(e.slideInType=b.IntoFromAbove)}else{switch(Be.readSInt8(this.data)){case 1:e.slideOutType=S.Shift;break;case 2:e.slideOutType=S.Legato;break;case 3:e.slideOutType=S.OutDown;break;case 4:e.slideOutType=S.OutUp;break;case-1:e.slideInType=b.IntoFromBelow;break;case-2:e.slideInType=b.IntoFromAbove}}}readArtificialHarmonic(e){let t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=m.Natural,e.harmonicValue=this.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=m.Artificial;break;case 3:e.harmonicType=m.Tap,e.harmonicValue=this.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=m.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=m.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=m.Natural;break;case 3:e.harmonicType=m.Tap;break;case 4:e.harmonicType=m.Pinch;break;case 5:e.harmonicType=m.Semi;break;case 15:case 17:case 22:e.harmonicType=m.Artificial}}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}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=u.Sixteenth;break;case 2:e.trillSpeed=u.ThirtySecond;break;case 3:e.trillSpeed=u.SixtyFourth}}}st.VersionString="FICHIER GUITAR PRO ",st.BendStep=25;class it{static gpReadDouble(e){let t=new Uint8Array(8);return e.read(t,0,t.length),new Float64Array(t.buffer)[0]}static gpReadFloat(e){let t=new Uint8Array(4);return t[3]=e.readByte(),t[2]=e.readByte(),t[2]=e.readByte(),t[1]=e.readByte(),new Float32Array(t.buffer)[0]}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 fe(s,i,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),it.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return it.gpReadString(e,Be.readInt32LE(e),t)}static gpReadStringIntByte(e,t){let s=Be.readInt32LE(e)-1;return e.readByte(),it.gpReadString(e,s,t)}static gpReadString(e,t,s){let i=new Uint8Array(t);return e.read(i,0,i.length),Be.toString(i,s)}static gpWriteString(e,t){const s=Be.stringToBytes(t);e.writeByte(t.length),e.write(s,0,s.length)}static gpReadStringByteLength(e,t,s){let i=e.readByte(),a=it.gpReadString(e,i,s);return i<t&&e.skip(t-i),a}}class at{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class rt{constructor(){this.x=0,this.y=0,this.w=0,this.h=0}}!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"}(ve||(ve={}));class nt{constructor(e){this.raw=new Map;let t=Te.fromBuffer(e),s=Be.readInt32BE(t);for(let e=0;e<s;e++){let e=it.gpReadString(t,t.readByte(),"utf-8");switch(t.readByte()){case ve.Boolean:let s=1===t.readByte();this.addValue(e,s);break;case ve.Integer:let i=Be.readInt32BE(t);this.addValue(e,i);break;case ve.Float:let a=it.gpReadFloat(t);this.addValue(e,a);break;case ve.String:let r=it.gpReadString(t,Be.readInt16BE(t),"utf-8");this.addValue(e,r);break;case ve.Point:let n=Be.readInt32BE(t),o=Be.readInt32BE(t);this.addValue(e,new z(n,o));break;case ve.Size:let h=Be.readInt32BE(t),l=Be.readInt32BE(t);this.addValue(e,new z(h,l));break;case ve.Rectangle:let c=new rt;c.x=Be.readInt32BE(t),c.y=Be.readInt32BE(t),c.w=Be.readInt32BE(t),c.h=Be.readInt32BE(t),this.addValue(e,c);break;case ve.Color:let d=it.gpReadColor(t,!0);this.addValue(e,d)}}}apply(e){for(const[t,s]of this.raw)if("StandardNotation/hideDynamics"===t)e.stylesheet.hideDynamics=s}addValue(e,t){this.raw.set(e,t)}static writeForScore(e){const t=Te.withCapacity(128);return Be.writeInt32BE(t,1),nt.writeBooleanEntry(t,"StandardNotation/hideDynamics",e.stylesheet.hideDynamics),t.toArray()}static writeBooleanEntry(e,t,s){it.gpWriteString(e,t),e.writeByte(ve.Boolean),e.writeByte(s?1:0)}}!function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(xe||(xe={}));class ot{constructor(){this.type=xe.Short,this.length=0}}!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"}(Ne||(Ne={}));class ht{constructor(){this.nodeType=Ne.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!==Ne.Element&&e.nodeType!==Ne.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===Ne.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===Ne.Element&&t.localName===e)return t;return null}addElement(e){const t=new ht;return t.nodeType=Ne.Element,t.localName=e,this.addChild(t),t}get innerText(){if(this.nodeType===Ne.Element||this.nodeType===Ne.Document){if(this.firstElement&&this.firstElement.nodeType===Ne.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 ht;t.nodeType=Ne.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new ht;t.nodeType=Ne.CDATA,t.value=e,this.childNodes=[t]}}class lt extends O{constructor(e,t,i){super(s.Format,e),this.pos=0,this.xml=t,this.pos=i,Object.setPrototypeOf(this,lt.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"}(Pe||(Pe={}));class ct{static parse(e,t,s){let i=e.charCodeAt(t),a=Pe.Begin,r=Pe.Begin,n=0,o="",h=Pe.Begin,l=null,c=null,d=0,u=0;for(;t<e.length;){switch(i=e.charCodeAt(t),a){case Pe.IgnoreSpaces:switch(i){case ct.CharCodeLF:case ct.CharCodeCR:case ct.CharCodeTab:case ct.CharCodeSpace:break;default:a=r;continue}break;case Pe.Begin:if(i!==ct.CharCodeLowerThan){n=t,a=Pe.Pcdata;continue}a=Pe.IgnoreSpaces,r=Pe.BeginNode;break;case Pe.Pcdata:if(i===ct.CharCodeLowerThan){o+=e.substr(n,t-n);let i=new ht;i.nodeType=Ne.Text,i.value=o,o="",s.addChild(i),a=Pe.IgnoreSpaces,r=Pe.BeginNode}else i===ct.CharCodeAmp&&(o+=e.substr(n,t-n),a=Pe.Escape,h=Pe.Pcdata,n=t+1);break;case Pe.Cdata:if(i===ct.CharCodeBrackedClose&&e.charCodeAt(t+1)===ct.CharCodeBrackedClose&&e.charCodeAt(t+2)===ct.CharCodeGreaterThan){let i=new ht;i.nodeType=Ne.CDATA,i.value=e.substr(n,t-n),s.addChild(i),t+=2,a=Pe.Begin}break;case Pe.BeginNode:switch(i){case ct.CharCodeExclamation:if(e.charCodeAt(t+1)===ct.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new lt("Expected <![CDATA[",e,t);t+=5,a=Pe.Cdata,n=t+1}else if(e.charCodeAt(t+1)===ct.CharCodeUpperD||e.charCodeAt(t+1)===ct.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new lt("Expected <!DOCTYPE",e,t);t+=8,a=Pe.Doctype,n=t+1}else{if(e.charCodeAt(t+1)!==ct.CharCodeMinus||e.charCodeAt(t+2)!==ct.CharCodeMinus)throw new lt("Expected \x3c!--",e,t);t+=2,a=Pe.Comment,n=t+1}break;case ct.CharCodeQuestion:a=Pe.Header,n=t;break;case ct.CharCodeSlash:if(!s)throw new lt("Expected node name",e,t);n=t+1,a=Pe.IgnoreSpaces,r=Pe.Close;break;default:a=Pe.TagName,n=t;continue}break;case Pe.TagName:if(!ct.isValidChar(i)){if(t===n)throw new lt("Expected node name",e,t);l=new ht,l.nodeType=Ne.Element,l.localName=e.substr(n,t-n),s.addChild(l),a=Pe.IgnoreSpaces,r=Pe.Body;continue}break;case Pe.Body:switch(i){case ct.CharCodeSlash:a=Pe.WaitEnd;break;case ct.CharCodeGreaterThan:a=Pe.Childs;break;default:a=Pe.AttribName,n=t;continue}break;case Pe.AttribName:if(!ct.isValidChar(i)){if(n===t)throw new lt("Expected attribute name",e,t);if(c=e.substr(n,t-n),l.attributes.has(c))throw new lt(`Duplicate attribute [${c}]`,e,t);a=Pe.IgnoreSpaces,r=Pe.Equals;continue}break;case Pe.Equals:if(i!==ct.CharCodeEquals)throw new lt("Expected =",e,t);a=Pe.IgnoreSpaces,r=Pe.AttvalBegin;break;case Pe.AttvalBegin:switch(i){case ct.CharCodeDoubleQuote:case ct.CharCodeSingleQuote:o="",a=Pe.AttribVal,n=t+1,u=i}break;case Pe.AttribVal:if(i===ct.CharCodeAmp)o+=e.substr(n,t-n),a=Pe.Escape,h=Pe.AttribVal,n=t+1;else if(i===u){o+=e.substr(n,t-n);let s=o;o="",l.attributes.set(c,s),a=Pe.IgnoreSpaces,r=Pe.Body}break;case Pe.Childs:n=t=ct.parse(e,t,l),a=Pe.Begin;break;case Pe.WaitEnd:if(i!==ct.CharCodeGreaterThan)throw new lt("Expected >",e,t);a=Pe.Begin;break;case Pe.WaitEndRet:if(i===ct.CharCodeGreaterThan)return t;throw new lt("Expected >",e,t);case Pe.Close:if(!ct.isValidChar(i)){if(n===t)throw new lt("Expected node name",e,t);if(e.substr(n,t-n)!==s.localName)throw new lt("Expected </"+s.localName+">",e,t);a=Pe.IgnoreSpaces,r=Pe.WaitEndRet;continue}break;case Pe.Comment:i===ct.CharCodeMinus&&e.charCodeAt(t+1)===ct.CharCodeMinus&&e.charCodeAt(t+2)===ct.CharCodeGreaterThan&&(t+=2,a=Pe.Begin);break;case Pe.Doctype:if(i===ct.CharCodeBrackedOpen)d++;else if(i===ct.CharCodeBrackedClose)d--;else if(i===ct.CharCodeGreaterThan&&0===d){let i=new ht;i.nodeType=Ne.DocumentType,i.value=e.substr(n,t-n),s.addChild(i),a=Pe.Begin}break;case Pe.Header:i===ct.CharCodeQuestion&&e.charCodeAt(t+1)===ct.CharCodeGreaterThan&&(t++,a=Pe.Begin);break;case Pe.Escape:if(i===ct.CharCodeSemi){let s=e.substr(n,t-n);if(s.charCodeAt(0)===ct.CharCodeSharp){let e=s.charCodeAt(1)===ct.CharCodeLowerX?parseInt("0"+s.substr(1,s.length-1)):parseInt(s.substr(1,s.length-1));o+=String.fromCharCode(e)}else ct.Escapes.has(s)?o+=ct.Escapes.get(s):o+=("&"+s+";")?.toString();n=t+1,a=h}else ct.isValidChar(i)||i===ct.CharCodeSharp||(o+="&",o+=e.substr(n,t-n),n=--t+1,a=h)}t++}if(a===Pe.Begin&&(n=t,a=Pe.Pcdata),a===Pe.Pcdata){if(t!==n){o+=e.substr(n,t-n);let i=new ht;i.nodeType=Ne.Text,i.value=o,s.addChild(i)}return t}if(a===Pe.Escape&&h===Pe.Pcdata){o+="&",o+=e.substr(n,t-n);let i=new ht;return i.nodeType=Ne.Text,i.value=o,s.addChild(i),t}throw new lt("Unexpected end",e,t)}static isValidChar(e){return e>=ct.CharCodeLowerA&&e<=ct.CharCodeLowerZ||e>=ct.CharCodeUpperA&&e<=ct.CharCodeUpperZ||e>=ct.CharCode0&&e<=ct.CharCode9||e===ct.CharCodeColon||e===ct.CharCodeDot||e===ct.CharCodeUnderscore||e===ct.CharCodeMinus}}ct.CharCodeLF=10,ct.CharCodeTab=9,ct.CharCodeCR=13,ct.CharCodeSpace=32,ct.CharCodeLowerThan=60,ct.CharCodeAmp=38,ct.CharCodeBrackedClose=93,ct.CharCodeBrackedOpen=91,ct.CharCodeGreaterThan=62,ct.CharCodeExclamation=33,ct.CharCodeUpperD=68,ct.CharCodeLowerD=100,ct.CharCodeMinus=45,ct.CharCodeQuestion=63,ct.CharCodeSlash=47,ct.CharCodeEquals=61,ct.CharCodeDoubleQuote=34,ct.CharCodeSingleQuote=39,ct.CharCodeSharp=35,ct.CharCodeLowerX=120,ct.CharCodeLowerA=97,ct.CharCodeLowerZ=122,ct.CharCodeUpperA=65,ct.CharCodeUpperZ=90,ct.CharCode0=48,ct.CharCode9=57,ct.CharCodeColon=58,ct.CharCodeDot=46,ct.CharCodeUnderscore=95,ct.CharCodeSemi=59,ct.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class dt{static write(e,t,s){const i=new dt(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 Ne.None:break;case Ne.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===Ne.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case Ne.Text:e.value&&this.write(e.value);break;case Ne.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case Ne.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case Ne.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 ut extends ht{constructor(){super(),this.nodeType=Ne.Document}parse(e){ct.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return dt.write(this,e,t)}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(Ce||(Ce={}));class pt{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=u.Quarter}}class gt{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return this.path+";"+this.name+";"+this.role}}class ft{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1}parseXml(e,t){this._masterTrackAutomations=new Map,this._automationsPerTrackIdAndBarIndex=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 ut;try{s.parse(e)}catch(e){throw new G("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 G("Root node of XML was not GPIF");this.score=new ue;for(let e of t.childNodes)if(e.nodeType===Ne.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===Ne.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===Ne.Element)switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null);break;case"Tracks":this._tracksMapping=t.innerText.split(" ");break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,s){for(let i of e.childNodes)if(i.nodeType===Ne.Element&&"Automation"===i.localName)this.parseAutomation(i,t,s)}parseAutomation(e,t,s){let i=null,a=!1,r=-1,n=0,o=0,h=null,l=0,c=null;for(let t of e.childNodes)if(t.nodeType===Ne.Element)switch(t.localName){case"Type":i=t.innerText;break;case"Linear":a="true"===t.innerText.toLowerCase();break;case"Bar":r=parseInt(t.innerText);break;case"Position":n=parseFloat(t.innerText);break;case"Value":if(t.firstElement&&t.firstElement.nodeType===Ne.CDATA)h=t.innerText;else{let e=t.innerText.split(" ");1===e.length?(o=parseFloat(e[0]),l=1):(o=parseFloat(e[0]),l=parseInt(e[1]))}break;case"Text":c=t.innerText}if(!i)return;let d=null;switch(i){case"Tempo":d=V.buildTempoAutomation(a,n,o,l);break;case"Sound":h&&s&&s.has(h)&&(d=V.buildInstrumentAutomation(a,n,s.get(h).program))}d&&(c&&(d.text=c),r>=0&&(t.has(r)||t.set(r,[]),t.get(r).push(d)))}parseTracksNode(e){for(let t of e.childNodes)if(t.nodeType===Ne.Element&&"Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;let t=new Se;t.ensureStaveCount(1),t.staves[0].showStandardNotation=!0;let s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===Ne.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 fe(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),this.parseAutomations(t,s,this._soundsByTrack.get(e))}parseNotationPatch(e,t){for(let s of t.childNodes)if(s.nodeType===Ne.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===Ne.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===Ne.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===Ne.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===Ne.Element&&"Articulation"===i.localName)this.parseArticulation(e,i,s)}parseArticulation(e,t,s){const i=new Q;i.outputMidiNumber=-1,i.elementType=s;let a="";for(let e of t.childNodes)if(e.nodeType===Ne.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=C.Bottom;break;case"inside":i.techniqueSymbolPlacement=C.Middle;break;case"below":i.techniqueSymbolPlacement=C.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==N.None&&(i.noteHeadHalf=i.noteHeadDefault),i.noteHeadWhole==N.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 N.PictEdgeOfCymbal;case"articStaccatoAbove":return N.ArticStaccatoAbove;case"noteheadParenthesis":return N.NoteheadParenthesis;case"stringsUpBow":return N.StringsUpBow;case"stringsDownBow":return N.StringsDownBow;case"guitarGolpe":return N.GuitarGolpe;default:return N.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return N.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return N.NoteheadDoubleWhole;case"noteheadWhole":return N.NoteheadWhole;case"noteheadHalf":return N.NoteheadHalf;case"noteheadBlack":return N.NoteheadBlack;case"noteheadNull":return N.NoteheadNull;case"noteheadXOrnate":return N.NoteheadXOrnate;case"noteheadTriangleUpWhole":return N.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return N.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return N.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return N.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return N.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return N.NoteheadDiamondWhiteWide;case"noteheadCircleX":return N.NoteheadCircleX;case"noteheadXWhole":return N.NoteheadXWhole;case"noteheadXHalf":return N.NoteheadXHalf;case"noteheadXBlack":return N.NoteheadXBlack;case"noteheadParenthesis":return N.NoteheadParenthesis;case"noteheadSlashedBlack2":return N.NoteheadSlashedBlack2;case"noteheadCircleSlash":return N.NoteheadCircleSlash;case"noteheadHeavyX":return N.NoteheadHeavyX;case"noteheadHeavyXHat":return N.NoteheadHeavyXHat;default:return q.warning("GPIF","Unknown notehead symbol",e),N.None}}parseStaves(e,t){let s=0;for(let i of t.childNodes)if(i.nodeType===Ne.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===Ne.Element&&"Properties"===s.localName)this.parseStaffProperties(e,s)}parseStaffProperties(e,t){for(let s of t.childNodes)if(s.nodeType===Ne.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===Ne.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===Ne.Element&&"Line"===e.localName)s.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,s)}parseLyricsLine(e){let t=new he;for(let s of e.childNodes)if(s.nodeType===Ne.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===Ne.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===Ne.Element&&"Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){let s=new oe,i=t.getAttribute("id");for(let t of e.staves)t.addChord(i,s);this.parseDiagramItemForChord(s,t)}parseDiagramItemForStaff(e,t){let s=new oe,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=parseInt(s.getAttribute("baseFret"));e.firstFret=a+1;for(let t=0;t<i;t++)e.strings.push(-1);for(let t of s.childNodes)if(t.nodeType===Ne.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===Ne.Element&&"Position"===s.localName){let t=f.Unknown,i=a+parseInt(s.getAttribute("fret"));switch(s.getAttribute("finger")){case"Index":t=f.IndexFinger;break;case"Middle":t=f.MiddleFinger;break;case"Rank":t=f.AnnularFinger;break;case"Pinky":t=f.LittleFinger;break;case"Thumb":t=f.Thumb}t!==f.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===Ne.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===Ne.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===Ne.Element&&"Sound"===i.localName)this.parseSound(e,t,i)}parseSound(e,t,s){const i=new gt;for(let e of s.childNodes)if(e.nodeType===Ne.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===Ne.Element&&"Program"===s.localName)e.program=parseInt(s.innerText)}parsePartSounding(e,t){for(let s of t.childNodes)if(s.nodeType===Ne.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===Ne.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===Ne.Element&&"ChannelStrip"===s.localName)this.parseChannelStrip(e,s)}parseChannelStrip(e,t){for(let s of t.childNodes)if(s.nodeType===Ne.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===Ne.Element&&"MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){let t=new le;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(let s of e.childNodes)if(s.nodeType===Ne.Element)switch(s.localName){case"Time":let e=s.innerText.split("/");t.timeSignatureNumerator=parseInt(e[0]),t.timeSignatureDenominator=parseInt(e[1]);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=D.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=D.Triplet8th;break;case"Triplet16th":t.tripletFeel=D.Triplet16th;break;case"Dotted8th":t.tripletFeel=D.Dotted8th;break;case"Dotted16th":t.tripletFeel=D.Dotted16th;break;case"Scottish8th":t.tripletFeel=D.Scottish8th;break;case"Scottish16th":t.tripletFeel=D.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=I.Major;break;case"minor":t.keySignatureType=I.Minor}break;case"Fermatas":this.parseFermatas(t,s);break;case"XProperties":this.parseMasterBarXProperties(s,t)}this._masterBars.push(t)}parseFermatas(e,t){for(let s of t.childNodes)if(s.nodeType===Ne.Element&&"Fermata"===s.localName)this.parseFermata(e,s)}parseFermata(e,t){let s=0,i=new ot;for(let e of t.childNodes)if(e.nodeType===Ne.Element)switch(e.localName){case"Type":switch(e.innerText){case"Short":i.type=xe.Short;break;case"Medium":i.type=xe.Medium;break;case"Long":i.type=xe.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])*W.QuarterTime|0}}e.addFermata(s,i)}parseBars(e){for(let t of e.childNodes)if(t.nodeType===Ne.Element&&"Bar"===t.localName)this.parseBar(t)}parseBar(e){let t=new H,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===Ne.Element)switch(i.localName){case"Voices":this._voicesOfBar.set(s,i.innerText.split(" "));break;case"Clef":switch(i.innerText){case"Neutral":t.clef=r.Neutral;break;case"G2":t.clef=r.G2;break;case"F4":t.clef=r.F4;break;case"C4":t.clef=r.C4;break;case"C3":t.clef=r.C3}break;case"Ottavia":switch(i.innerText){case"8va":t.clefOttava=n._8va;break;case"15ma":t.clefOttava=n._15ma;break;case"8vb":t.clefOttava=n._8vb;break;case"15mb":t.clefOttava=n._15mb}break;case"SimileMark":switch(i.innerText){case"Simple":t.simileMark=o.Simple;break;case"FirstOfDouble":t.simileMark=o.FirstOfDouble;break;case"SecondOfDouble":t.simileMark=o.SecondOfDouble}break;case"XProperties":this.parseBarXProperties(i,t)}this._barsById.set(s,t)}parseVoices(e){for(let t of e.childNodes)if(t.nodeType===Ne.Element&&"Voice"===t.localName)this.parseVoice(t)}parseVoice(e){let t=new _e,s=e.getAttribute("id");for(let t of e.childNodes)if(t.nodeType===Ne.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===Ne.Element&&"Beat"===t.localName)this.parseBeat(t)}parseBeat(e){let t=new ne,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===Ne.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":"FadeIn"===i.innerText&&(t.fadeIn=!0);break;case"Tremolo":switch(i.innerText){case"1/2":t.tremoloSpeed=u.Eighth;break;case"1/4":t.tremoloSpeed=u.Sixteenth;break;case"1/8":t.tremoloSpeed=u.ThirtySecond}break;case"Chord":t.chordId=i.innerText;break;case"Hairpin":switch(i.innerText){case"Crescendo":t.crescendo=d.Crescendo;break;case"Decrescendo":t.crescendo=d.Decrescendo}break;case"Arpeggio":"Up"===i.innerText?t.brushType=c.ArpeggioUp:t.brushType=c.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=Ce.Up;break;case"Downward":t.preferredBeamDirection=Ce.Down}break;case"Dynamic":switch(i.innerText){case"PPP":t.dynamics=p.PPP;break;case"PP":t.dynamics=p.PP;break;case"P":t.dynamics=p.P;break;case"MP":t.dynamics=p.MP;break;case"MF":t.dynamics=p.MF;break;case"F":t.dynamics=p.F;break;case"FF":t.dynamics=p.FF;break;case"FFF":t.dynamics=p.FFF}break;case"GraceNotes":switch(i.innerText){case"OnBeat":t.graceType=g.OnBeat;break;case"BeforeBeat":t.graceType=g.BeforeBeat}break;case"Legato":"true"===i.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":let e=new z(0,0);e.value=this.toBendValue(parseFloat(i.getAttribute("originValue"))),e.offset=this.toBendOffset(parseFloat(i.getAttribute("originOffset"))),t.addWhammyBarPoint(e);let a=new z(0,0);a.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),a.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);let r=new z(0,0);r.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),r.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);let o=new z(0,0);o.value=this.toBendValue(parseFloat(i.getAttribute("destinationValue"))),o.offset=this.toBendOffset(parseFloat(i.getAttribute("destinationOffset"))),t.addWhammyBarPoint(o);break;case"Ottavia":switch(i.innerText){case"8va":t.ottava=n._8va;break;case"8vb":t.ottava=n._8vb;break;case"15ma":t.ottava=n._15ma;break;case"15mb":t.ottava=n._15mb}break;case"Lyrics":t.lyrics=this.parseBeatLyrics(i),this._skipApplyLyrics=!0}this._beatById.set(s,t)}parseBeatLyrics(e){const t=[];for(let s of e.childNodes)if(s.nodeType===Ne.Element&&"Line"===s.localName)t.push(s.innerText);return t}parseBeatXProperties(e,t){for(let s of e.childNodes)if(s.nodeType===Ne.Element&&"XProperty"===s.localName){let e=0;switch(s.getAttribute("id")){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===Ne.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 e.childNodes)if(s.nodeType===Ne.Element&&"XProperty"===s.localName){if("1124073984"===s.getAttribute("id"))t.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===Ne.Element&&"Property"===h.localName){switch(h.getAttribute("name")){case"Brush":"Up"===h.findChildElement("Direction").innerText?t.brushType=c.BrushUp:t.brushType=c.BrushDown;break;case"PickStroke":"Up"===h.findChildElement("Direction").innerText?t.pickStroke=x.Up:t.pickStroke=x.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=_.Wide;break;case"Slight":t.vibrato=_.Slight}break;case"WhammyBar":s=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":i||(i=new z(0,0)),i.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":i||(i=new z(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 z(z.MaxPosition,0)),o.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new z(0,0)),o.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText))}}s&&(i||(i=new z(0,0)),o||(o=new z(z.MaxPosition,0)),t.addWhammyBarPoint(i),r&&a&&t.addWhammyBarPoint(new z(r,a)),n&&a&&t.addWhammyBarPoint(new z(n,a)),r||n||!a||t.addWhammyBarPoint(new z(z.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(let t of e.childNodes)if(t.nodeType===Ne.Element&&"Note"===t.localName)this.parseNote(t)}parseNote(e){let t=new Z,s=e.getAttribute("id");for(let a of e.childNodes)if(a.nodeType===Ne.Element)switch(a.localName){case"Properties":this.parseNoteProperties(a,t,s);break;case"AntiAccent":"normal"===a.innerText.toLowerCase()&&(t.isGhost=!0);break;case"LetRing":t.isLetRing=!0;break;case"Trill":t.trillValue=parseInt(a.innerText),t.trillSpeed=u.Sixteenth;break;case"Accent":let e=parseInt(a.innerText);1&e&&(t.isStaccato=!0),4&e&&(t.accentuated=i.Heavy),8&e&&(t.accentuated=i.Normal);break;case"Tie":"true"===a.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(a.innerText){case"Slight":t.vibrato=_.Slight;break;case"Wide":t.vibrato=_.Wide}break;case"LeftFingering":switch(t.isFingering=!0,a.innerText){case"P":t.leftHandFinger=f.Thumb;break;case"I":t.leftHandFinger=f.IndexFinger;break;case"M":t.leftHandFinger=f.MiddleFinger;break;case"A":t.leftHandFinger=f.AnnularFinger;break;case"C":t.leftHandFinger=f.LittleFinger}break;case"RightFingering":switch(t.isFingering=!0,a.innerText){case"P":t.rightHandFinger=f.Thumb;break;case"I":t.rightHandFinger=f.IndexFinger;break;case"M":t.rightHandFinger=f.MiddleFinger;break;case"A":t.rightHandFinger=f.AnnularFinger;break;case"C":t.rightHandFinger=f.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=parseInt(a.innerText)}this._noteById.set(s,t)}parseNoteProperties(e,t,s){let i=!1,a=null,r=null,n=null,o=null,h=null,l=-1,c=-1;for(let d of e.childNodes)if(d.nodeType===Ne.Element&&"Property"===d.localName){switch(d.getAttribute("name")){case"String":t.string=parseInt(d.findChildElement("String").innerText)+1;break;case"Fret":t.fret=parseInt(d.findChildElement("Fret").innerText);break;case"Element":l=parseInt(d.findChildElement("Element").innerText);break;case"Variation":c=parseInt(d.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(s,!0);break;case"HarmonicType":let e=d.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=m.None;break;case"Natural":t.harmonicType=m.Natural;break;case"Artificial":t.harmonicType=m.Artificial;break;case"Pinch":t.harmonicType=m.Pinch;break;case"Tap":t.harmonicType=m.Tap;break;case"Semi":t.harmonicType=m.Semi;break;case"Feedback":t.harmonicType=m.Feedback}break;case"HarmonicFret":let u=d.findChildElement("HFret");u&&(t.harmonicValue=parseFloat(u.innerText));break;case"Muted":d.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":d.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=parseInt(d.findChildElement("Number").innerText),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=parseInt(d.findChildElement("Step").innerText);break;case"ConcertPitch":this.parseConcertPitch(d,t);break;case"Bended":i=!0;break;case"BendOriginValue":a||(a=new z(0,0)),a.value=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new z(0,0)),a.offset=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleValue":r=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleOffset1":n=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleOffset2":o=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationValue":h||(h=new z(z.MaxPosition,0)),h.value=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new z(0,0)),h.offset=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"HopoOrigin":d.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":let p=parseInt(d.findChildElement("Flags").innerText);1&p?t.slideOutType=S.Shift:2&p?t.slideOutType=S.Legato:4&p?t.slideOutType=S.OutDown:8&p&&(t.slideOutType=S.OutUp),16&p?t.slideInType=b.IntoFromBelow:32&p&&(t.slideInType=b.IntoFromAbove),64&p?t.slideOutType=S.PickSlideDown:128&p&&(t.slideOutType=S.PickSlideUp)}}i&&(a||(a=new z(0,0)),h||(h=new z(z.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new z(n,r)),o&&r&&t.addBendPoint(new z(o,r)),n||o||!r||t.addBendPoint(new z(z.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==c&&(t.percussionArticulation=$.articulationFromElementVariation(l,c))}parseConcertPitch(e,t){const s=e.findChildElement("Pitch");if(s)for(let e of s.childNodes)if(e.nodeType===Ne.Element&&"Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=y.ForceDoubleSharp;break;case"#":t.accidentalMode=y.ForceSharp;break;case"b":t.accidentalMode=y.ForceFlat;break;case"bb":t.accidentalMode=y.ForceDoubleFlat}}toBendValue(e){return e*ft.BendPointValueFactor|0}toBendOffset(e){return e*ft.BendPointPositionFactor}parseRhythms(e){for(let t of e.childNodes)if(t.nodeType===Ne.Element&&"Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){let t=new pt,s=e.getAttribute("id");t.id=s;for(let s of e.childNodes)if(s.nodeType===Ne.Element)switch(s.localName){case"NoteValue":switch(s.innerText){case"Long":t.value=u.QuadrupleWhole;break;case"DoubleWhole":t.value=u.DoubleWhole;break;case"Whole":t.value=u.Whole;break;case"Half":t.value=u.Half;break;case"Quarter":t.value=u.Quarter;break;case"Eighth":t.value=u.Eighth;break;case"16th":t.value=u.Sixteenth;break;case"32nd":t.value=u.ThirtySecond;break;case"64th":t.value=u.SixtyFourth;break;case"128th":t.value=u.OneHundredTwentyEighth;break;case"256th":t.value=u.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!==ft.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!==ft.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!==ft.InvalidId){let t=ae.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!==ft.InvalidId){const e=se.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 _e;e.addVoice(t);let s=new ne;s.isEmpty=!0,s.duration=u.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)}}}}for(const[e,t]of this._masterTrackAutomations){let s=this.score.masterBars[e];for(let i=0,r=t.length;i<r;i++){let r=t[i];r.type===a.Tempo&&(0===e&&(this.score.tempo=0|r.value,r.text&&(this.score.tempoLabel=r.text)),s.tempoAutomation=r)}}}}ft.InvalidId="-1",ft.BendPointPositionFactor=z.MaxPosition/100,ft.BendPointValueFactor=.04;class mt{constructor(){this.isMultiRest=!1,this.trackViewGroups=[]}}class yt{constructor(){this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class bt{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}t++}}}constructor(e){this.scoreViews=[];let t=Te.fromBuffer(e);const s=Be.readInt32BE(t);for(let e=0;e<s;e++){const e=new mt;this.scoreViews.push(e),e.isMultiRest=it.gpReadBool(t);const s=Be.readInt32BE(t);for(let i=0;i<s;i++){let s=t.readByte();0===s&&(s=1);let i=new yt;i.showStandardNotation=!!(1&s),i.showTablature=!!(2&s),i.showSlash=!!(4&s),e.trackViewGroups.push(i)}}}static writeForScore(e){const t=Te.withCapacity(128),s=[new mt];for(const t of e.tracks){const e=new yt;e.showStandardNotation=t.staves[0].showStandardNotation,e.showTablature=t.staves[0].showTablature,s[0].trackViewGroups.push(e);const i=new mt;i.trackViewGroups.push(e),s.push(i)}Be.writeInt32BE(t,s.length);for(const e of s){t.writeByte(e.isMultiRest?1:0),Be.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),t.writeByte(e)}}return Be.writeInt32BE(t,1),t.toArray()}}class St{}class _t extends St{constructor(e){super(),this.n=e}}class wt extends St{constructor(e,t){super(),this.left=e,this.right=t}}class Bt extends St{constructor(e,t){super(),this.n=e,this.table=t}}class Tt{static make(e,t,s,i){let a=[],r=[];if(i>32)throw new ge("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 ge("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 Tt.treeCompress(new wt(Tt.treeMake(o,i,0,1),Tt.treeMake(o,i,1,1)))}static treeMake(e,t,s,i){if(i>t)throw new ge("Invalid huffman");let a=s<<5|i;return e.has(a)?new _t(e.get(a)):(s<<=1,i+=1,new wt(Tt.treeMake(e,t,s,i),Tt.treeMake(e,t,1|s,i)))}static treeCompress(e){let t=Tt.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof wt)return new wt(Tt.treeCompress(e.left),Tt.treeCompress(e.right));throw new ge("assert")}let s=1<<t,i=[];for(let e=0;e<s;e++)i.push(new _t(-1));return Tt.treeWalk(i,0,0,t,e),new Bt(t,i)}static treeWalk(e,t,s,i,a){a instanceof wt&&i>0?(Tt.treeWalk(e,t,s+1,i-1,a.left),Tt.treeWalk(e,t|1<<s,s+1,i-1,a.right)):e[t]=Tt.treeCompress(a)}static treeDepth(e){if(e instanceof _t)return 0;if(e instanceof Bt)throw new ge("assert");if(e instanceof wt){let t=Tt.treeDepth(e.left),s=Tt.treeDepth(e.right);return 1+(t<s?t:s)}return 0}}!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"}(Ee||(Ee={}));class kt{constructor(){this.buffer=new Uint8Array(kt.BufferSize),this.pos=0}slide(){let e=new Uint8Array(kt.BufferSize);this.pos-=kt.Size,e.set(this.buffer.subarray(kt.Size,kt.Size+this.pos),0),this.buffer=e}addBytes(e,t,s){this.pos+s>kt.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+s),this.pos),this.pos+=s}addByte(e){this.pos===kt.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}kt.Size=32768,kt.BufferSize=65536;class vt{static buildFixedHuffman(){let e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return Tt.make(e,0,288,10)}constructor(e){this._nbits=0,this._bits=0,this._state=Ee.Block,this._isFinal=!1,this._huffman=vt._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new kt,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 Ee.Head:let e=this._input.readByte();if(8!==(15&e))throw new ge("Invalid data");let t=this._input.readByte(),s=!!(32&t);if(((e<<8)+t)%31!=0)throw new ge("Invalid data");if(s)throw new ge("Unsupported dictionary");return this._state=Ee.Block,!0;case Ee.Crc:return this._state=Ee.Done,!0;case Ee.Done:return!1;case Ee.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:if(this._len=Be.readUInt16LE(this._input),Be.readUInt16LE(this._input)!==65535-this._len)throw new ge("Invalid data");this._state=Ee.Flat;let e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=vt._fixedHuffman,this._huffdist=null,this._state=Ee.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[vt.CodeLengthsPos[e]]=this.getBits(3);for(let e=i;e<19;e++)this._lengths[vt.CodeLengthsPos[e]]=0;this._huffman=Tt.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=Tt.make(a,t,s,16),this._huffman=Tt.make(a,0,t,16),this._state=Ee.CData,!0;default:throw new ge("Invalid data")}case Ee.Flat:{let e=this._len<this._needed?this._len:this._needed,t=Be.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?Ee.Crc:Ee.Block),this._needed>0}case Ee.DistOne:{let e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=Ee.CData),this._needed>0}case Ee.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=Ee.CData),this._needed>0;case Ee.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?Ee.Crc:Ee.Block,!0;{i=i-257&255;let e=vt.LenExtraBitsTbl[i];if(-1===e)throw new ge("Invalid data");this._len=vt.LenBaseValTbl[i]+this.getBits(e);let t=this._huffdist,s=t?this.applyHuffman(t):this.getRevBits(5);if(e=vt.DistExtraBitsTbl[s],-1===e)throw new ge("Invalid data");if(this._dist=vt.DistBaseValTbl[s]+this.getBits(e),this._dist>this._window.available())throw new ge("Invalid data");return this._state=1===this._dist?Ee.DistOne:Ee.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 ge("Invalid data");for(;s<r;)e[s]=i,s++;break;case 17:if(s+=3+this.getBits(3),s>t)throw new ge("Invalid data");break;case 18:if(s+=11+this.getBits(7),s>t)throw new ge("Invalid data");break;default:throw new ge("Invalid data")}}}applyHuffman(e){if(e instanceof _t)return e.n;if(e instanceof wt)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof Bt)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new ge("Invalid data")}}vt.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],vt.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],vt.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],vt.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],vt.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],vt._fixedHuffman=vt.buildFixedHuffman();class xt{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}}xt.OptionalDataDescriptorSignature=134695760,xt.CompressionMethodDeflate=8,xt.LocalFileHeaderSignature=67324752,xt.CentralFileHeaderSignature=33639248,xt.EndOfCentralDirSignature=101010256;class Nt{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(Be.readInt32LE(e)!==xt.LocalFileHeaderSignature)return null;Be.readUInt16LE(e);let t=Be.readUInt16LE(e),s=Be.readUInt16LE(e),i=0!==s;if(i&&s!==xt.CompressionMethodDeflate)return null;Be.readInt16LE(this._readable),Be.readInt16LE(this._readable),Be.readInt32LE(e),Be.readInt32LE(e);let a,r=Be.readInt32LE(e),n=Be.readInt16LE(e),o=Be.readInt16LE(e),h=Be.toString(Be.readByteArray(e,n),"utf-8");if(e.skip(o),i){let e=Te.empty(),t=new vt(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=Be.readByteArray(this._readable,r);if(8&t){Be.readInt32LE(this._readable)===xt.OptionalDataDescriptorSignature&&Be.readInt32LE(this._readable),Be.readInt32LE(this._readable),Be.readInt32LE(this._readable)}return new xt(h,a)}}class Pt extends R{get name(){return"Guitar Pro 7"}constructor(){super()}readScore(){q.debug(this.name,"Loading ZIP entries");let e,t=new Nt(this.data);try{e=t.read()}catch(e){throw new G("No Zip archive",e)}q.debug(this.name,"Zip entries loaded");let s=null,i=null,a=null;for(let t of e)switch(t.fileName){case"score.gpif":s=Be.toString(t.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=t.data;break;case"PartConfiguration":a=t.data}if(!s)throw new G("No score.gpif found in zip archive");q.debug(this.name,"Start Parsing score.gpif");let r=new ft;r.parseXml(s,this.settings),q.debug(this.name,"score.gpif parsed");let n=r.score;if(i){q.debug(this.name,"Start Parsing BinaryStylesheet"),new nt(i).apply(n),q.debug(this.name,"BinaryStylesheet parsed")}if(a){q.debug(this.name,"Start Parsing Part Configuration"),new bt(a).apply(n),q.debug(this.name,"Part Configuration parsed")}return n}}class Ct extends O{constructor(){super(s.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,Ct.prototype)}}class Et{constructor(e){this._currentByte=0,this._position=Et.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 Ct;this._position=0}const e=this._currentByte>>Et.ByteSize-this._position-1&1;return this._position++,e}readAll(){let e=Te.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof Ct))throw e}return e.toArray()}}Et.ByteSize=8;class Ft{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class Lt{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){let t=new Et(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){let s,i=Te.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 Ct))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 G("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 Ft;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?Te.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]}}Lt.HeaderBcFs="BCFS",Lt.HeaderBcFz="BCFZ",Lt.ScoreGpif="score.gpif",Lt.BinaryStylesheet="BinaryStylesheet",Lt.PartConfiguration="PartConfiguration";class Mt extends R{get name(){return"Guitar Pro 6"}constructor(){super()}readScore(){q.debug(this.name,"Loading GPX filesystem");let e=new Lt;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration"),e.load(this.data),q.debug(this.name,"GPX filesystem loaded");let t=null,s=null,i=null;for(let a of e.files)switch(a.fileName){case"score.gpif":t=Be.toString(a.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=a.data;break;case"PartConfiguration":i=a.data}if(!t)throw new G("No score.gpif found in GPX");q.debug(this.name,"Start Parsing score.gpif");let a=new ft;a.parseXml(t,this.settings),q.debug(this.name,"score.gpif parsed");let r=a.score;if(s){q.debug(this.name,"Start Parsing BinaryStylesheet"),new nt(s).apply(r),q.debug(this.name,"BinaryStylesheet parsed")}if(i){q.debug(this.name,"Start Parsing Part Configuration"),new bt(i).apply(r),q.debug(this.name,"Part Configuration parsed")}return r}}class It extends R{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=Be.toString(this.data.readAll(),this.settings.importer.encoding),t=new ut;try{t.parse(e)}catch(e){throw new G("Unsupported format")}return this._score=new ue,this._score.tempo=120,this.parseDom(t),this.settings.importer.mergePartGroupsInMusicXml&&this.mergePartGroups(),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}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 G("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":break;default:throw new G("Unsupported format")}}parsePartwise(e){for(let t of e.childNodes)if(t.nodeType===Ne.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===Ne.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===Ne.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 H;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===Ne.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 _e;e.addVoice(t);let s=new ne;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 c=this.getOrCreateVoice(n,i);return s&&c.beats.length>0||1===c.beats.length&&c.isEmpty?o=c.beats[c.beats.length-1]:(o=new ne,o.isEmpty=!1,c.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)*u.Quarter/this._divisionsPerQuarterNote,a=[u.SixtyFourth,u.ThirtySecond,u.Sixteenth,u.Eighth,u.Quarter,u.Half,u.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===Ne.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===Ne.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=j.getTuningForText(i+a)+r;for(let e of t.staves)e.tuning[e.tuning.length-s]=n}parseHarmony(e,t,s){let i=new oe;for(let t of e.childNodes)if(t.nodeType===Ne.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=j.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===Ne.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===Ne.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===Ne.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 Z;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===Ne.Element)switch(t.localName){case"grace":i.graceType=g.BeforeBeat,i.duration=u.ThirtySecond;break;case"duration":if(i.isRest&&!r){switch(parseInt(t.innerText)){case 1:i.duration=u.Whole;break;case 2:i.duration=u.Half;break;case 4:default:i.duration=u.Quarter;break;case 8:i.duration=u.Eighth;break;case 16:i.duration=u.Sixteenth;break;case 32:i.duration=u.ThirtySecond;break;case 64:i.duration=u.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!==g.None&&i.duration<u.Sixteenth&&(i.duration=u.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=u.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 u.SixtyFourth;case"32nd":return u.ThirtySecond;case"16th":return u.Sixteenth;case"eighth":return u.Eighth;case"quarter":return u.Quarter;case"half":return u.Half;case"long":case"breve":case"whole":return u.Whole}return u.Quarter}parseLyric(e,t){for(let s of e.childNodes)if(s.nodeType===Ne.Element&&"text"===s.localName)t.text?t.text+=" "+s.innerText:t.text=s.innerText}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=y.ForceSharp;break;case"natural":t.accidentalMode=y.ForceNatural;break;case"flat":t.accidentalMode=y.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===Ne.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=S.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===Ne.Element&&"tremolo"===s.localName){switch(parseInt(s.innerText)){case 1:t.beat.tremoloSpeed=u.Eighth;break;case 2:t.beat.tremoloSpeed=u.Sixteenth;break;case 3:t.beat.tremoloSpeed=u.ThirtySecond}}}parseTechnical(e,t){for(let s of e.childNodes)if(s.nodeType===Ne.Element)switch(s.localName){case"string":t.string=parseInt(s.innerText),-2147483648!==t.string&&(t.string=t.beat.voice.bar.staff.tuning.length-t.string+1);break;case"fret":t.fret=parseInt(s.innerText);break;case"down-bow":t.beat.pickStroke=x.Down;break;case"up-bow":t.beat.pickStroke=x.Up}-2147483648!==t.string&&-2147483648!==t.fret||(t.string=-1,t.fret=-1)}parseArticulations(e,t){for(let s of e.childNodes)switch(s.localName){case"accent":t.accentuated=i.Normal;break;case"strong-accent":t.accentuated=i.Heavy;break;case"staccato":case"detached-legato":t.isStaccato=!0}}parseDynamics(e,t){for(let s of e.childNodes)if(s.nodeType===Ne.Element)switch(s.localName){case"p":t.dynamics=p.P;break;case"pp":t.dynamics=p.PP;break;case"ppp":t.dynamics=p.PPP;break;case"f":t.dynamics=p.F;break;case"ff":t.dynamics=p.FF;break;case"fff":t.dynamics=p.FFF;break;case"mp":t.dynamics=p.MP;break;case"mf":t.dynamics=p.MF}}parseTimeModification(e,t){for(let s of e.childNodes)if(s.nodeType===Ne.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===Ne.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+j.getToneForText(s)+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===Ne.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+j.getToneForText(s)+(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 _e);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===Ne.Element)switch(s.localName){case"sound":let e=s.getAttribute("tempo");if(e){let s=new V;s.isLinear=!0,s.type=a.Tempo,s.value=parseInt(e),t.tempoAutomation=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=u.Quarter,i=120;for(let t of e.childNodes)if(t.nodeType===Ne.Element)switch(t.localName){case"beat-unit":s=this.getDuration(t.innerText);break;case"per-minute":i=parseInt(t.innerText)}let r=new V;r.type=a.Tempo,r.value=i*(s/4|0),t.tempoAutomation=r,0===t.index&&(t.score.tempo=r.value)}parseAttributes(e,t,s,i){let a=0,r=!1;for(let n of e.childNodes)if(n.nodeType===Ne.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===Ne.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===Ne.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=n._15mb;break;case-1:t.clefOttava=n._8vb;break;case 1:t.clefOttava=n._8va;break;case 2:t.clefOttava=n._15mb}}switch(s){case"g":default:t.clef=r.G2;break;case"f":t.clef=r.F4;break;case"c":t.clef=3===i?r.C3:r.C4;break;case"percussion":t.clef=r.Neutral,t.staff.isPercussion=!0;break;case"tab":t.clef=r.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===Ne.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===Ne.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:L.C,t.keySignatureType="minor"===i?I.Minor:I.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 le;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===Ne.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===Ne.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 Se;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===Ne.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===Ne.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)))}}}!function(e){e[e.SingleTrackMultiChannel=0]="SingleTrackMultiChannel",e[e.MultiTrack=1]="MultiTrack"}(Fe||(Fe={}));class Dt{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=Te.empty(),s=0;for(let e of this.events){let i=e.tick-s;At.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();Be.writeInt32BE(e,a.length),e.write(a,0,a.length)}}class At{constructor(){this.format=Fe.SingleTrackMultiChannel,this.division=W.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 Dt)}addEvent(e){this.format==Fe.SingleTrackMultiChannel?(this.ensureTracks(1),this.tracks[0].addEvent(e)):(this.ensureTracks(e.track+1),this.tracks[e.track].addEvent(e))}toBinary(){let e=Te.empty();return this.writeTo(e),e.toArray()}writeTo(e){let t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),Be.writeInt32BE(e,6),Be.writeInt16BE(e,this.format),Be.writeInt16BE(e,this.tracks.length),Be.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"}(Le||(Le={}));class Rt{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 Ot extends Rt{constructor(e,t,s,i,a,r){super(e,t,Le.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),At.writeVariableInt(e,4),e.writeByte(255&this.numerator),e.writeByte(255&this.denominatorIndex),e.writeByte(255&this.midiClocksPerMetronomeClick),e.writeByte(255&this.thirtySecondNodesInQuarter)}}class Gt extends Rt{constructor(e,t,s){super(e,t,s)}writeTo(e){e.writeByte(240);const t=Te.withCapacity(16);t.writeByte(Gt.AlphaTabManufacturerId),this.writeEventData(t),t.writeByte(247),At.writeVariableInt(e,t.length),t.copyTo(e)}}Gt.AlphaTabManufacturerId=125,Gt.MetronomeEventId=0,Gt.RestEventId=1;class Vt extends Gt{constructor(e,t,s,i,a){super(e,t,Le.AlphaTabMetronome),this.isMetronome=!0,this.metronomeNumerator=s,this.metronomeDurationInMilliseconds=a,this.metronomeDurationInTicks=i}writeEventData(e){e.writeByte(Gt.MetronomeEventId),e.writeByte(this.metronomeNumerator),Be.writeInt32LE(e,this.metronomeDurationInTicks),Be.writeInt32LE(e,this.metronomeDurationInMilliseconds)}}class Ht extends Gt{constructor(e,t,s){super(e,t,Le.AlphaTabRest),this.channel=s}writeEventData(e){e.writeByte(Gt.RestEventId),e.writeByte(this.channel)}}class Wt extends Rt{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 zt extends Wt{constructor(e,t,s,i,a){super(e,t,Le.NoteOn,s,i,a)}writeTo(e){e.writeByte(15&this.channel|144),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class Ut extends Wt{constructor(e,t,s,i,a){super(e,t,Le.NoteOff,s,i,a)}writeTo(e){e.writeByte(15&this.channel|128),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class Xt extends Rt{constructor(e,t,s,i,a){super(e,t,Le.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 Yt extends Rt{constructor(e,t,s,i){super(e,t,Le.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 qt extends Rt{constructor(e,t){super(0,e,Le.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 Jt extends Rt{constructor(e,t,s,i){super(e,t,Le.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 jt extends Rt{constructor(e,t,s,i,a){super(e,t,Le.PerNotePitchBend),this.channel=s,this.noteKey=i,this.value=a}writeTo(e){throw new O(s.General,"Note Bend (Midi2.0) events cannot be exported to SMF1.0")}}class Qt extends Rt{constructor(e,t){super(e,t,Le.EndOfTrack)}writeTo(e){e.writeByte(255),e.writeByte(47),e.writeByte(0)}}class $t{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event.type==Le.AlphaTabMetronome}static newMetronomeEvent(e,t,s,i,a){const r=new Vt(0,t,s,i,a);return new $t(e,r)}}class Kt{}Kt.DefaultChannelCount=17,Kt.MetronomeChannel=Kt.DefaultChannelCount-1,Kt.AudioChannels=2,Kt.MinVolume=0,Kt.MinProgram=0,Kt.MaxProgram=127,Kt.MinPlaybackSpeed=.125,Kt.MaxPlaybackSpeed=8,Kt.MaxPitchWheel=16384,Kt.MaxPitchWheel20=4294967296,Kt.DefaultPitchWheel=Kt.MaxPitchWheel/2,Kt.MicroBufferCount=32,Kt.MicroBufferSize=64;class Zt{constructor(e,t,s){this.bpm=e,this.ticks=t,this.time=s}}class es{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=W.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class ts{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._synthesizer=e,this._mainState=new es,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(Kt.MicroBufferSize);this._mainState.currentTime=s;let i=Date.now()-t;q.debug("Sequencer","Silent seek finished in "+i+"ms (main)")}loadOneTimeMidi(e){this._oneTimeState=this.createStateFromFile(e),this._currentState=this._oneTimeState}loadMidi(e){this._mainState=this.createStateFromFile(e),this._currentState=this._mainState}createStateFromFile(e){const t=new es;t.tempoChanges=[],t.division=e.division,t.eventIndex=0,t.currentTime=0,t.synthData=[];let s=120,i=0,a=0,r=0,n=0,o=0,h=0,l=0,c=0;for(let d of e.events){let u=new $t(t.synthData.length,d);t.synthData.push(u);let p=d.tick-c;if(i+=p,a+=p*(6e4/(s*e.division)),u.time=a,c=d.tick,n>0)for(;h<i;){let e=$t.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(d.type===Le.TempoChange){s=6e7/d.microSecondsPerQuarterNote,t.tempoChanges.push(new Zt(s,i,a)),o=n*(6e4/(s*e.division))}else if(d.type===Le.TimeSignature){let i=d,a=Math.pow(2,i.denominatorIndex);r=i.numerator,n=t.division*(4/a)|0,o=n*(6e4/(s*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=i.numerator,t.firstTimeSignatureDenominator=a)}else if(d.type===Le.ProgramChange){let e=d.channel;t.firstProgramEventPerChannel.has(e)||t.firstProgramEventPerChannel.set(e,u)}}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=Kt.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 es;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 Zt(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=$t.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"}(Me||(Me={}));class ss{constructor(e,t){this.state=e,this.stopped=t}}class is{constructor(e,t,s,i,a){this.currentTime=e,this.endTime=t,this.currentTick=s,this.endTick=i,this.isSeek=a}}class as{constructor(){this.id="",this.size=0}static load(e,t,s){if(e&&as.HeaderSize>e.size)return!1;if(s.position+as.HeaderSize>=s.length)return!1;if(t.id=Be.read8BitStringLength(s,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=Be.readUInt32LE(s),e&&as.HeaderSize+t.size>e.size)return!1;e&&(e.size-=as.HeaderSize+t.size);let i="RIFF"===t.id,a="LIST"===t.id;return(!i||!e)&&(!i&&!a||(t.id=Be.read8BitStringLength(s,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}as.HeaderSize=8;class rs{constructor(){this.phdrs=[],this.pbags=[],this.pmods=[],this.pgens=[],this.insts=[],this.ibags=[],this.imods=[],this.igens=[],this.sHdrs=[],this.fontSamples=new Float32Array(0)}load(e){const t=new as,s=new as;if(!as.load(null,t,e)||"sfbk"!==t.id)throw new ge("Soundfont is not a valid Soundfont2 file");for(;as.load(t,s,e);){let t=new as;if("pdta"===s.id)for(;as.load(s,t,e);)switch(t.id){case"phdr":for(let s=0,i=t.size/us.SizeInFile|0;s<i;s++)this.phdrs.push(new us(e));break;case"pbag":for(let s=0,i=t.size/cs.SizeInFile|0;s<i;s++)this.pbags.push(new cs(e));break;case"pmod":for(let s=0,i=t.size/ps.SizeInFile|0;s<i;s++)this.pmods.push(new ps(e));break;case"pgen":for(let s=0,i=t.size/ds.SizeInFile|0;s<i;s++)this.pgens.push(new ds(e));break;case"inst":for(let s=0,i=t.size/ls.SizeInFile|0;s<i;s++)this.insts.push(new ls(e));break;case"ibag":for(let s=0,i=t.size/ns.SizeInFile|0;s<i;s++)this.ibags.push(new ns(e));break;case"imod":for(let s=0,i=t.size/os.SizeInFile|0;s<i;s++)this.imods.push(new os(e));break;case"igen":for(let s=0,i=t.size/hs.SizeInFile|0;s<i;s++)this.igens.push(new hs(e));break;case"shdr":for(let s=0,i=t.size/gs.SizeInFile|0;s<i;s++)this.sHdrs.push(new gs(e));break;default:e.position+=t.size}else if("sdta"===s.id)for(;as.load(s,t,e);)if("smpl"===t.id)this.fontSamples=rs.loadSamples(t,e);else e.position+=t.size;else e.position+=s.size}}static loadSamples(e,t){let s=e.size/2|0;const i=new Float32Array(s);let a=0;const r=new Uint8Array(16384);for(;s>0;){let e=Math.min(s,r.length/2|0);t.read(r,0,2*e);for(let t=0;t<e;t++){const e=we.int32ToInt16(r[2*t+1]<<8|r[2*t]);i[a+t]=e/32767}s-=e,a+=e}return i}}class ns{constructor(e){this.instGenNdx=Be.readUInt16LE(e),this.instModNdx=Be.readUInt16LE(e)}}ns.SizeInFile=4;class os{constructor(e){this.modSrcOper=Be.readUInt16LE(e),this.modDestOper=Be.readUInt16LE(e),this.modAmount=Be.readInt16LE(e),this.modAmtSrcOper=Be.readUInt16LE(e),this.modTransOper=Be.readUInt16LE(e)}}os.SizeInFile=10;class hs{constructor(e){this.genOper=Be.readUInt16LE(e),this.genAmount=new fs(e)}}hs.SizeInFile=4;class ls{constructor(e){this.instName=Be.read8BitStringLength(e,20),this.instBagNdx=Be.readUInt16LE(e)}}ls.SizeInFile=22;class cs{constructor(e){this.genNdx=Be.readUInt16LE(e),this.modNdx=Be.readUInt16LE(e)}}cs.SizeInFile=4;class ds{constructor(e){this.genOper=Be.readUInt16LE(e),this.genAmount=new fs(e)}}ds.SizeInFile=4,ds.GenInstrument=41,ds.GenKeyRange=43,ds.GenVelRange=44,ds.GenSampleId=53;class us{constructor(e){this.presetName=Be.read8BitStringLength(e,20),this.preset=Be.readUInt16LE(e),this.bank=Be.readUInt16LE(e),this.presetBagNdx=Be.readUInt16LE(e),this.library=Be.readUInt32LE(e),this.genre=Be.readUInt32LE(e),this.morphology=Be.readUInt32LE(e)}}us.SizeInFile=38;class ps{constructor(e){this.modSrcOper=Be.readUInt16LE(e),this.modDestOper=Be.readUInt16LE(e),this.modAmount=Be.readUInt16LE(e),this.modAmtSrcOper=Be.readUInt16LE(e),this.modTransOper=Be.readUInt16LE(e)}}ps.SizeInFile=10;class gs{constructor(e){this.sampleName=Be.read8BitStringLength(e,20),this.start=Be.readUInt32LE(e),this.end=Be.readUInt32LE(e),this.startLoop=Be.readUInt32LE(e),this.endLoop=Be.readUInt32LE(e),this.sampleRate=Be.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=Be.readSInt8(e),this.sampleLink=Be.readUInt16LE(e),this.sampleType=Be.readUInt16LE(e)}}gs.SizeInFile=46;class fs{get shortAmount(){return we.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}constructor(e){this.wordAmount=Be.readUInt16LE(e)}}class ms{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 ys{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"}(Ie||(Ie={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(De||(De={}));class bs{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null,this.fontSamples=null}}class Ss{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)}static clamp(e,t,s){return e<=t?t:e>=s?s:e}}class _s{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:Ss.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:Ss.timecents2Secs(this.attack),this.release=this.release<-11950?0:Ss.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:Ss.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:Ss.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?Ss.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"}(Ae||(Ae={}));class ws{constructor(e){this.loopMode=Ie.None,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 _s,this.modEnv=new _s,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.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 _s(e.ampEnv),this.modEnv=new _s(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=Ie.None,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 Ae.StartAddrsOffset:this.offset+=we.int16ToUint32(t.shortAmount);break;case Ae.EndAddrsOffset:this.end+=we.int16ToUint32(t.shortAmount);break;case Ae.StartloopAddrsOffset:this.loopStart+=we.int16ToUint32(t.shortAmount);break;case Ae.EndloopAddrsOffset:this.loopEnd+=we.int16ToUint32(t.shortAmount);break;case Ae.StartAddrsCoarseOffset:this.offset+=32768*we.int16ToUint32(t.shortAmount);break;case Ae.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case Ae.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case Ae.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case Ae.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case Ae.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case Ae.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case Ae.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case Ae.EndAddrsCoarseOffset:this.end+=32768*we.int16ToUint32(t.shortAmount);break;case Ae.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case Ae.Pan:this.pan=t.shortAmount/1e3;break;case Ae.DelayModLFO:this.delayModLFO=t.shortAmount;break;case Ae.FreqModLFO:this.freqModLFO=t.shortAmount;break;case Ae.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case Ae.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case Ae.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case Ae.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case Ae.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case Ae.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case Ae.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case Ae.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case Ae.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case Ae.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case Ae.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case Ae.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case Ae.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case Ae.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case Ae.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case Ae.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case Ae.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case Ae.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case Ae.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case Ae.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case Ae.StartloopAddrsCoarseOffset:this.loopStart+=32768*we.int16ToUint32(t.shortAmount);break;case Ae.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case Ae.EndloopAddrsCoarseOffset:this.loopEnd+=32768*we.int16ToUint32(t.shortAmount);break;case Ae.CoarseTune:this.transpose+=t.shortAmount;break;case Ae.FineTune:this.tune+=t.shortAmount;break;case Ae.SampleModes:this.loopMode=3&~t.wordAmount?1==(3&t.wordAmount)?Ie.Continuous:Ie.None:Ie.Sustain;break;case Ae.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case Ae.ExclusiveClass:this.group=t.wordAmount;break;case Ae.OverridingRootKey:this.pitchKeyCenter=t.shortAmount}}}!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"}(Re||(Re={}));class Bs{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=Re.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case Re.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=Re.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=Re.Delay;break;case Re.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=Re.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=Re.Attack;break;case Re.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=Re.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=Re.Hold;break;case Re.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=Re.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=Re.Decay;break;case Re.Decay:return this.segment=Re.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case Re.Sustain:if(this.segment=Re.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?Bs.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=Re.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,s,i,a){this.parameters=new _s(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:Ss.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:Ss.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|s,this.isAmpEnv=i,this.nextSegment(Re.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)}}Bs.FastReleaseTime=.01;class Ts{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,s){this.samplesUntil=e*s|0,this.delta=4*Ss.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 ks{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 vs{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 Bs,this.modEnv=new Bs,this.lowPass=new ks,this.modLfo=new Ts,this.vibLfo=new Ts,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/(Ss.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(Re.Sustain,e),this.modEnv.nextSegment(Re.Sustain,e),this.region.loopMode===Ie.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(Re.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(Re.Sustain,e)}render(e,t,s,i,a){if(!this.region)return;let r=this.region;let n=e.presets[this.playingPreset].fontSamples,o=0,h=e.outputMode===De.StereoUnweaved?i:-1,l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,c=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),d=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,f=r.end,m=g+1,y=this.sourceSamplePosition,b=new ks(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,v=0,x=0,N=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?(v=0,x=r.modLfoToPitch,N=r.vibLfoToPitch,P=r.modEnvToPitch):(v=Ss.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,x=0,N=0,P=0),C?F=.1*r.modLfoToVolume:(E=Ss.decibelsToGain(this.noteGainDb),F=0);i>0;){let r,L,M=0,I=i>vs.RenderEffectSampleBlock?vs.RenderEffectSampleBlock:i;if(i-=I,S){let e=w+this.modLfo.level*B+this.modEnv.level*T;b.active=e<=13500,b.active&&b.setup(Ss.cents2Hertz(e)/_)}switch(k&&(v=Ss.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*x+this.vibLfo.level*N+this.modEnv.level*P))*this.pitchOutputFactor),C&&(E=Ss.decibelsToGain(this.noteGainDb+this.modLfo.level*F)),r=E*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(I,e.outSampleRate),l&&this.modEnv.process(I,e.outSampleRate),c&&this.modLfo.process(I),d&&this.vibLfo.process(I),e.outputMode){case De.StereoInterleaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;I-- >0&&y<f;){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*L,o++,t[s+o]+=r*M,o++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case De.StereoUnweaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;I-- >0&&y<f;){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*L,o++,t[s+h]+=r*M,h++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case De.Mono:for(;I-- >0&&y<f;){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+=v,y>=m&&u&&(y-=g-p+1)}}if(y>=f||this.ampEnv.segment===Re.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}vs.RenderEffectSampleBlock=Kt.MicroBufferSize;class xs{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"}(Oe||(Oe={}));class Ns{constructor(e){this._midiEventQueue=new xs,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this._transpositionPitches=new Map,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=De.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.applyTranspositionPitches(new Map),this._isAnySolo=!1}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(Kt.MetronomeChannel,33),this.channelNoteOn(Kt.MetronomeChannel,33,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!=Kt.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,s,n):a.kill()}return a}processMidiMessage(e){q.debug("MIdi","Processing Midi message "+Le[e.type]+"/"+e.tick);switch(e.type){case Le.TimeSignature:const t=e;this.timeSignatureNumerator=t.numerator,this.timeSignatureDenominator=Math.pow(2,t.denominatorIndex);break;case Le.NoteOn:const s=e;this.channelNoteOn(s.channel,s.noteKey,s.noteVelocity/127);break;case Le.NoteOff:const i=e;this.channelNoteOff(i.channel,i.noteKey);break;case Le.ControlChange:const a=e;this.channelMidiControl(a.channel,a.controller,a.value);break;case Le.ProgramChange:const r=e;this.channelSetPresetNumber(r.channel,r.program,9===r.channel);break;case Le.TempoChange:const n=e;this.currentTempo=6e7/n.microSecondsPerQuarterNote;break;case Le.PitchBend:const o=e;this.channelSetPitchWheel(o.channel,o.value);break;case Le.PerNotePitchBend:const h=e;let l=h.value;l=l*Kt.MaxPitchWheel/Kt.MaxPitchWheel20,this.channelSetPerNotePitchWheel(h.channel,h.noteKey,l)}}get metronomeVolume(){return this.channelGetMixVolume(Kt.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Kt.MetronomeChannel,e),e>0&&(this.channelSetVolume(Kt.MetronomeChannel,1),this.channelSetPresetNumber(Kt.MetronomeChannel,0,!0))}get masterVolume(){return Ss.decibelsToGain(this.globalGainDb)}set masterVolume(e){var t=Ss.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<Re.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<Re.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 vs;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-Ss.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!==Ie.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(Ss.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>=Re.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>=Re.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&&t.ampEnv.segment<Re.Release&&(e?t.endQuick(this.outSampleRate):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 ys);for(let t=this._channels.channelList.length;t<=e;t++){let e=new ms;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._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,s))}channelNoteOff(e,t){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.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>=Re.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>=Re.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<Re.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<Re.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=we.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=we.int32ToUint16(t)}channelSetBankPreset(e,t,s){const i=this.channelInit(e),a=this.getPresetIndex(t,s);return-1!==a&&(i.presetIndex=we.int32ToUint16(a),i.bank=we.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=Ss.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=we.int32ToUint16(t),this.channelApplyPitch(e,s))}channelSetPerNotePitchWheel(e,t,s){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.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 Oe.DataEntryFine:return i.midiData=we.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 Oe.VolumeCoarse:return i.midiVolume=we.int32ToUint16(127&i.midiVolume|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Oe.VolumeFine:return i.midiVolume=we.int32ToUint16(16256&i.midiVolume|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Oe.ExpressionControllerCoarse:return i.midiExpression=we.int32ToUint16(127&i.midiExpression|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Oe.ExpressionControllerFine:return i.midiExpression=we.int32ToUint16(16256&i.midiExpression|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Oe.PanCoarse:return i.midiPan=we.int32ToUint16(127&i.midiPan|s<<7),void this.channelSetPan(e,i.midiPan/16383);case Oe.PanFine:return i.midiPan=we.int32ToUint16(16256&i.midiPan|s),void this.channelSetPan(e,i.midiPan/16383);case Oe.DataEntryCoarse:return i.midiData=we.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===Oe.DataEntryCoarse&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Oe.BankSelectCoarse:return void(i.bank=we.int32ToUint16(32768|s));case Oe.BankSelectFine:return void(i.bank=we.int32ToUint16((32768&i.bank?(127&i.bank)<<7:0)|s));case Oe.RegisteredParameterCourse:return void(i.midiRpn=we.int32ToUint16(127&(65535===i.midiRpn?0:i.midiRpn)|s<<7));case Oe.RegisteredParameterFine:return void(i.midiRpn=we.int32ToUint16(16256&(65535===i.midiRpn?0:i.midiRpn)|s));case Oe.NonRegisteredParameterFine:case Oe.NonRegisteredParameterCourse:return void(i.midiRpn=65535);case Oe.AllSoundOff:return void this.channelSoundsOffAll(e);case Oe.AllNotesOff:return void this.channelNoteOffAll(e);case Oe.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?Ss.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){const s=[];for(let t=0;t<e.phdrs.length-1;t++){const i=e.phdrs[t];let a=0;const r=new bs;s.push(r),r.name=i.presetName,r.bank=i.bank,r.presetNumber=i.preset,r.fontSamples=e.fontSamples;let n=0;for(let s=i.presetBagNdx;s<e.phdrs[t+1].presetBagNdx;s++){let t=0,i=127,a=0,r=127;for(let o=e.pbags[s].genNdx;o<e.pbags[s+1].genNdx;o++){let s=e.pgens[o];if(s.genOper!==ds.GenKeyRange)if(s.genOper!==ds.GenVelRange){if(s.genOper===ds.GenInstrument&&!(s.genAmount.wordAmount>=e.insts.length))for(let o=e.insts[s.genAmount.wordAmount].instBagNdx;o<e.insts[s.genAmount.wordAmount+1].instBagNdx;o++){let s=0,h=127,l=0,c=127;for(let d=e.ibags[o].instGenNdx;d<e.ibags[o+1].instGenNdx;d++){let o=e.igens[d];o.genOper!==ds.GenKeyRange?o.genOper!==ds.GenVelRange?53===o.genOper&&h>=t&&s<=i&&c>=a&&l<=r&&n++:(l=o.genAmount.lowByteAmount,c=o.genAmount.highByteAmount):(s=o.genAmount.lowByteAmount,h=o.genAmount.highByteAmount)}}}else a=s.genAmount.lowByteAmount,r=s.genAmount.highByteAmount;else t=s.genAmount.lowByteAmount,i=s.genAmount.highByteAmount}}r.regions=new Array(n);let o=new ws;o.clear(!0);for(let s=i.presetBagNdx;s<e.phdrs[t+1].presetBagNdx;s++){const t=e.pbags[s],n=new ws(o);let h=!1;for(let i=t.genNdx;i<e.pbags[s+1].genNdx;i++){const t=e.pgens[i];if(t.genOper===ds.GenInstrument){let s=t.genAmount.wordAmount;if(s>=e.insts.length)continue;let i=new ws;i.clear(!1);let o=e.insts[s];for(let t=o.instBagNdx;t<e.insts[s+1].instBagNdx;t++){let s=e.ibags[t],h=new ws(i),l=!1;for(let i=s.instGenNdx;i<e.ibags[t+1].instGenNdx;i++){let t=e.igens[i];if(t.genOper===ds.GenSampleId){if(h.hiKey<n.loKey||h.loKey>n.hiKey)continue;if(h.hiVel<n.loVel||h.loVel>n.hiVel)continue;n.loKey>h.loKey&&(h.loKey=n.loKey),n.hiKey<h.hiKey&&(h.hiKey=n.hiKey),n.loVel>h.loVel&&(h.loVel=n.loVel),n.hiVel<h.hiVel&&(h.hiVel=n.hiVel),h.offset+=n.offset,h.end+=n.end,h.loopStart+=n.loopStart,h.loopEnd+=n.loopEnd,h.transpose+=n.transpose,h.tune+=n.tune,h.pitchKeyTrack+=n.pitchKeyTrack,h.attenuation+=n.attenuation,h.pan+=n.pan,h.ampEnv.delay+=n.ampEnv.delay,h.ampEnv.attack+=n.ampEnv.attack,h.ampEnv.hold+=n.ampEnv.hold,h.ampEnv.decay+=n.ampEnv.decay,h.ampEnv.sustain+=n.ampEnv.sustain,h.ampEnv.release+=n.ampEnv.release,h.modEnv.delay+=n.modEnv.delay,h.modEnv.attack+=n.modEnv.attack,h.modEnv.hold+=n.modEnv.hold,h.modEnv.decay+=n.modEnv.decay,h.modEnv.sustain+=n.modEnv.sustain,h.modEnv.release+=n.modEnv.release,h.initialFilterQ+=n.initialFilterQ,h.initialFilterFc+=n.initialFilterFc,h.modEnvToPitch+=n.modEnvToPitch,h.modEnvToFilterFc+=n.modEnvToFilterFc,h.delayModLFO+=n.delayModLFO,h.freqModLFO+=n.freqModLFO,h.modLfoToPitch+=n.modLfoToPitch,h.modLfoToFilterFc+=n.modLfoToFilterFc,h.modLfoToVolume+=n.modLfoToVolume,h.delayVibLFO+=n.delayVibLFO,h.freqVibLFO+=n.freqVibLFO,h.vibLfoToPitch+=n.vibLfoToPitch,h.ampEnv.envToSecs(!0),h.modEnv.envToSecs(!1),h.delayModLFO=h.delayModLFO<-11950?0:Ss.timecents2Secs(h.delayModLFO),h.delayVibLFO=h.delayVibLFO<-11950?0:Ss.timecents2Secs(h.delayVibLFO),h.pan<-.5?h.pan=-.5:h.pan>.5&&(h.pan=.5),(h.initialFilterQ<1500||h.initialFilterQ>13500)&&(h.initialFilterQ=0);let s=e.sHdrs[t.genAmount.wordAmount];h.offset+=s.start,h.end+=s.end,h.loopStart+=s.startLoop,h.loopEnd+=s.endLoop,s.endLoop>0&&(h.loopEnd-=1),-1===h.pitchKeyCenter&&(h.pitchKeyCenter=s.originalPitch),h.tune+=s.pitchCorrection,h.sampleRate=s.sampleRate,0!==h.end&&h.end<r.fontSamples.length?h.end++:h.end=r.fontSamples.length,r.regions[a]=new ws(h),a++,l=!0}else h.operator(t.genOper,t.genAmount)}s!==e.ibags[o.instBagNdx]||l||(i=new ws(h))}h=!0}else n.operator(t.genOper,t.genAmount)}t!==e.pbags[i.presetBagNdx]||h||(o=n)}}if(t&&this.presets)for(const e of s)this.presets.push(e);else this.presets=s}}class Ps{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 Cs{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 Es{constructor(e){this.events=e}}class Fs{constructor(e){this.playbackRange=e}}class Ls{get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return q.logLevel}set logLevel(e){q.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Kt.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Kt.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Kt.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=Ss.clamp(e,Kt.MinPlaybackSpeed,Kt.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){q.debug("AlphaSynth",`Seeking to position ${e}ms (main)`),this._sequencer.mainSeek(e),this.updateTimePosition(e,!0),this._sequencer.isPlayingMain&&(this._notPlayedSamples=0,this.output.resetSamples())}get playbackRange(){return this._sequencer.mainPlaybackRange}set playbackRange(e){this._sequencer.mainPlaybackRange=e,e&&(this.tickPosition=e.startTick),this.playbackRangeChanged.trigger(new Fs(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){q.debug("AlphaSynth","Destroying player"),this.stop(),this.output.destroy()}constructor(e,t){this._isSoundFontLoaded=!1,this._isMidiLoaded=!1,this._tickPosition=0,this._timePosition=0,this._metronomeVolume=0,this._countInVolume=0,this._playedEventsQueue=new xs,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this.isReady=!1,this.state=Me.Paused,this.ready=new Ps,this.readyForPlayback=new Ps,this.finished=new Ps,this.soundFontLoaded=new Ps,this.soundFontLoadFailed=new Cs,this.midiLoaded=new Cs,this.midiLoadFailed=new Cs,this.stateChanged=new Cs,this.positionChanged=new Cs,this.midiEventsPlayed=new Cs,this.playbackRangeChanged=new Cs,q.debug("AlphaSynth","Initializing player"),this.state=Me.Paused,q.debug("AlphaSynth","Creating output"),this.output=e,q.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new Ns(this.output.sampleRate),this._sequencer=new ts(this._synthesizer),q.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this.state!=Me.Playing||this._sequencer.isFinished){let e=new Float32Array(0);this.output.addSamples(e)}else{let e=new Float32Array(Kt.MicroBufferSize*Kt.MicroBufferCount*Kt.AudioChannels),t=0;for(let s=0;s<Kt.MicroBufferCount;s++){this._sequencer.fillMidiEventQueue();const s=this._synthesizer.synthesize(e,t,Kt.MicroBufferSize);t+=Kt.MicroBufferSize*Kt.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)}})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open(t)}play(){return!(this.state!==Me.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(q.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(q.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),q.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.state=Me.Playing,this.stateChanged.trigger(new ss(this.state,!1))}pause(){this.state!==Me.Paused&&this._isMidiLoaded&&(q.debug("AlphaSynth","Pausing playback"),this.state=Me.Paused,this.stateChanged.trigger(new ss(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===Me.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(q.debug("AlphaSynth","Stopping playback"),this.state=Me.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 ss(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._isSoundFontLoaded=!1,this.soundFontLoaded.trigger()}loadSoundFont(e,t){this.pause();let s=Te.fromBuffer(e);try{q.debug("AlphaSynth","Loading soundfont from bytes");let e=new rs;e.load(s),this._synthesizer.loadPresets(e,t),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),q.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){q.error("AlphaSynth","Could not load soundfont from bytes "+e),this.soundFontLoadFailed.trigger(e)}}checkReadyForPlayback(){this.isReadyForPlayback&&(this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.readyForPlayback.trigger())}loadMidiFile(e){this.stop();try{q.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new is(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),q.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){q.error("AlphaSynth","Could not load midi from model "+e),this.midiLoadFailed.trigger(e)}}applyTranspositionPitches(e){this._synthesizer.applyTranspositionPitches(e)}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,Kt.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;let t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*Kt.AudioChannels,this.updateTimePosition(this._timePosition+t,!1),this.checkForFinish()}checkForFinish(){let e=0,t=0;this.playbackRange&&this._sequencer.isPlayingMain?(e=this.playbackRange.startTick,t=this.playbackRange.endTick):t=this._sequencer.currentEndTick,this._tickPosition>=t&&this._notPlayedSamples<=0&&(this._notPlayedSamples=0,this._sequencer.isPlayingCountIn?(q.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(q.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=Me.Paused,this.stopOneTimeMidi()):(q.debug("AlphaSynth","Finished playback (main)"),this.finished.trigger(),this.isLooping?this.tickPosition=e:this.stop()))}stopOneTimeMidi(){this.output.pause(),this._synthesizer.noteOffAll(!0),this._sequencer.resetOneTimeMidi(),this.timePosition=this._sequencer.currentTime}updateTimePosition(e,t){const s=e;this._timePosition=s;const i=this._sequencer.currentTimePositionToTickPosition(s);this._tickPosition=i;const a=this._sequencer.currentEndTime,r=this._sequencer.currentEndTick,n=this._sequencer.isPlayingMain?"main":this._sequencer.isPlayingCountIn?"count-in":"one-time";if(q.debug("AlphaSynth",`Position changed: (time: ${s}/${a}, tick: ${i}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new is(s,a,i,r,t)),t)this._playedEventsQueue.clear();else{const e=new xs;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<s;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new Es(e.toArray()))}}}class Ms{static parseEnum(e,t){switch(typeof e){case"string":const s=parseInt(e);return isNaN(s)?t[Object.keys(t).find((t=>t.toLowerCase()===e.toLowerCase()))]:s;case"number":return e;case"undefined":case"object":return null}throw new O(s.Format,`Could not parse enum value '${e}'`)}static forEach(e,t){if(e instanceof Map)e.forEach(t);else if("object"==typeof e)for(const s in e)t(e[s],s)}static getValue(e,t){return e instanceof Map?e.get(t):"object"==typeof e?e[t]:null}}class Is{constructor(e,t,s){this.text=e,this.startPos=t,this.endPos=s}}class Ds{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 Is(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 Ds(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"}(Ge||(Ge={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(Ve||(Ve={}));class As{reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=Ds.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===Ve.Bold}get isItalic(){return this.style===Ge.Italic}constructor(e,t,s=Ge.Plain,i=Ve.Regular){this._cssScale=0,this._families=Ds.parseFamilies(e),this._size=t,this._style=s,this._weight=i,this._css=this.toCssString()}static withFamilyList(e,t,s=Ge.Plain,i=Ve.Regular){const a=new As("",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=>Ds.quoteFont(e))).join(", "),this._css=t,this._cssScale=e}return this._css}static fromJson(e){switch(typeof e){case"undefined":default:return null;case"object":{const t=e;let s=t.get("families"),i=t.get("size"),a=Ms.parseEnum(t.get("style"),Ge),r=Ms.parseEnum(t.get("weight"),Ve);return As.withFamilyList(s,i,a,r)}case"string":{const t=new Ds(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=Ge.Plain;"italic"===t.style&&(r=Ge.Italic);let n=Ve.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=Ve.Bold}return As.withFamilyList(s,a,r,n)}}}static toJson(e){const t=new Map;return t.set("families",e.families),t.set("size",e.size),t.set("style",e.style),t.set("weight",e.weight),t}}class Rs{constructor(){this.copyrightFont=new As(Rs.sansFont,12,Ge.Plain,Ve.Bold),this.titleFont=new As(Rs.serifFont,32,Ge.Plain),this.subTitleFont=new As(Rs.serifFont,20,Ge.Plain),this.wordsFont=new As(Rs.serifFont,15,Ge.Plain),this.effectFont=new As(Rs.serifFont,12,Ge.Italic),this.fretboardNumberFont=new As(Rs.sansFont,11,Ge.Plain),this.tablatureFont=new As(Rs.sansFont,13,Ge.Plain),this.graceFont=new As(Rs.sansFont,11,Ge.Plain),this.staffLineColor=new fe(165,165,165,255),this.barSeparatorColor=new fe(34,34,17,255),this.barNumberFont=new As(Rs.sansFont,11,Ge.Plain),this.barNumberColor=new fe(200,0,0,255),this.fingeringFont=new As(Rs.serifFont,14,Ge.Plain),this.markerFont=new As(Rs.serifFont,14,Ge.Plain,Ve.Bold),this.mainGlyphColor=new fe(0,0,0,255),this.secondaryGlyphColor=new fe(0,0,0,100),this.scoreInfoColor=new fe(0,0,0,255)}}Rs.sansFont="Arial, sans-serif",Rs.serifFont="Georgia, serif",function(e){e[e.Automatic=0]="Automatic",e[e.UseModelLayout=1]="UseModelLayout"}(He||(He={}));class Os{constructor(){this.scale=1,this.stretchForce=1,this.layoutMode=e.Page,this.staveProfile=t.Default,this.barsPerRow=-1,this.startBar=1,this.barCount=-1,this.barCountPerPartial=10,this.justifyLastSystem=!1,this.resources=new Rs,this.padding=null,this.systemsLayoutMode=He.Automatic}}class Gs{constructor(){this.encoding="utf-8",this.mergePartGroupsInMusicXml=!1,this.beatTextAsLyrics=!1}}!function(e){e[e.Off=0]="Off",e[e.Continuous=1]="Continuous",e[e.OffScreen=2]="OffScreen"}(We||(We={}));class Vs{constructor(){this.noteWideLength=480,this.noteWideAmplitude=2,this.noteSlightLength=480,this.noteSlightAmplitude=2,this.beatWideLength=240,this.beatWideAmplitude=3,this.beatSlightLength=240,this.beatSlightAmplitude=3}}class Hs{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}!function(e){e[e.WebAudioAudioWorklets=0]="WebAudioAudioWorklets",e[e.WebAudioScriptProcessor=1]="WebAudioScriptProcessor"}(ze||(ze={}));class Ws{constructor(){this.soundFont=null,this.scrollElement="html,body",this.outputMode=ze.WebAudioAudioWorklets,this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=We.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new Vs,this.slide=new Hs,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}class zs{static fromJson(e,t){t&&Ms.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(e,t,s){switch(t){case"scriptfile":return e.scriptFile=s,!0;case"fontdirectory":return e.fontDirectory=s,!0;case"file":return e.file=s,!0;case"tex":return e.tex=s,!0;case"tracks":return e.tracks=s,!0;case"enablelazyloading":return e.enableLazyLoading=s,!0;case"engine":return e.engine=s,!0;case"loglevel":return e.logLevel=Ms.parseEnum(s,v),!0;case"useworkers":return e.useWorkers=s,!0;case"includenotebounds":return e.includeNoteBounds=s,!0}return!1}}class Us{static fromJson(e,t){t&&Ms.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",As.toJson(e.copyrightFont)),t.set("titlefont",As.toJson(e.titleFont)),t.set("subtitlefont",As.toJson(e.subTitleFont)),t.set("wordsfont",As.toJson(e.wordsFont)),t.set("effectfont",As.toJson(e.effectFont)),t.set("fretboardnumberfont",As.toJson(e.fretboardNumberFont)),t.set("tablaturefont",As.toJson(e.tablatureFont)),t.set("gracefont",As.toJson(e.graceFont)),t.set("stafflinecolor",fe.toJson(e.staffLineColor)),t.set("barseparatorcolor",fe.toJson(e.barSeparatorColor)),t.set("barnumberfont",As.toJson(e.barNumberFont)),t.set("barnumbercolor",fe.toJson(e.barNumberColor)),t.set("fingeringfont",As.toJson(e.fingeringFont)),t.set("markerfont",As.toJson(e.markerFont)),t.set("mainglyphcolor",fe.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",fe.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",fe.toJson(e.scoreInfoColor)),t}static setProperty(e,t,s){switch(t){case"copyrightfont":return e.copyrightFont=As.fromJson(s),!0;case"titlefont":return e.titleFont=As.fromJson(s),!0;case"subtitlefont":return e.subTitleFont=As.fromJson(s),!0;case"wordsfont":return e.wordsFont=As.fromJson(s),!0;case"effectfont":return e.effectFont=As.fromJson(s),!0;case"fretboardnumberfont":return e.fretboardNumberFont=As.fromJson(s),!0;case"tablaturefont":return e.tablatureFont=As.fromJson(s),!0;case"gracefont":return e.graceFont=As.fromJson(s),!0;case"stafflinecolor":return e.staffLineColor=fe.fromJson(s),!0;case"barseparatorcolor":return e.barSeparatorColor=fe.fromJson(s),!0;case"barnumberfont":return e.barNumberFont=As.fromJson(s),!0;case"barnumbercolor":return e.barNumberColor=fe.fromJson(s),!0;case"fingeringfont":return e.fingeringFont=As.fromJson(s),!0;case"markerfont":return e.markerFont=As.fromJson(s),!0;case"mainglyphcolor":return e.mainGlyphColor=fe.fromJson(s),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=fe.fromJson(s),!0;case"scoreinfocolor":return e.scoreInfoColor=fe.fromJson(s),!0}return!1}}class Xs{static fromJson(e,t){t&&Ms.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",Us.toJson(e.resources)),t.set("padding",e.padding),t.set("systemslayoutmode",e.systemsLayoutMode),t}static setProperty(s,i,a){switch(i){case"scale":return s.scale=a,!0;case"stretchforce":return s.stretchForce=a,!0;case"layoutmode":return s.layoutMode=Ms.parseEnum(a,e),!0;case"staveprofile":return s.staveProfile=Ms.parseEnum(a,t),!0;case"barsperrow":return s.barsPerRow=a,!0;case"startbar":return s.startBar=a,!0;case"barcount":return s.barCount=a,!0;case"barcountperpartial":return s.barCountPerPartial=a,!0;case"justifylastsystem":return s.justifyLastSystem=a,!0;case"padding":return s.padding=a,!0;case"systemslayoutmode":return s.systemsLayoutMode=Ms.parseEnum(a,He),!0}if(["resources"].indexOf(i)>=0)return Us.fromJson(s.resources,a),!0;for(const e of["resources"])if(0===i.indexOf(e)&&Us.setProperty(s.resources,i.substring(e.length),a))return!0;return!1}}class Ys{static fromJson(e,t){t&&Ms.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(e,t,s){switch(t){case"notationmode":return e.notationMode=Ms.parseEnum(s,T),!0;case"fingeringmode":return e.fingeringMode=Ms.parseEnum(s,B),!0;case"elements":return e.elements=new Map,Ms.forEach(s,((t,s)=>{e.elements.set(Ms.parseEnum(s,k),t)})),!0;case"rhythmmode":return e.rhythmMode=Ms.parseEnum(s,w),!0;case"rhythmheight":return e.rhythmHeight=s,!0;case"transpositionpitches":return e.transpositionPitches=s,!0;case"displaytranspositionpitches":return e.displayTranspositionPitches=s,!0;case"smallgracetabnotes":return e.smallGraceTabNotes=s,!0;case"extendbendarrowsontiednotes":return e.extendBendArrowsOnTiedNotes=s,!0;case"extendlineeffectstobeatend":return e.extendLineEffectsToBeatEnd=s,!0;case"slurheight":return e.slurHeight=s,!0}return!1}}class qs{static fromJson(e,t){t&&Ms.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 Js{static fromJson(e,t){t&&Ms.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 js{static fromJson(e,t){t&&Ms.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 Qs{static fromJson(e,t){t&&Ms.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",Js.toJson(e.vibrato)),t.set("slide",js.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t.set("buffertimeinmilliseconds",e.bufferTimeInMilliseconds),t}static setProperty(e,t,s){switch(t){case"soundfont":return e.soundFont=s,!0;case"scrollelement":return e.scrollElement=s,!0;case"outputmode":return e.outputMode=Ms.parseEnum(s,ze),!0;case"enableplayer":return e.enablePlayer=s,!0;case"enablecursor":return e.enableCursor=s,!0;case"enableanimatedbeatcursor":return e.enableAnimatedBeatCursor=s,!0;case"enableelementhighlighting":return e.enableElementHighlighting=s,!0;case"enableuserinteraction":return e.enableUserInteraction=s,!0;case"scrolloffsetx":return e.scrollOffsetX=s,!0;case"scrolloffsety":return e.scrollOffsetY=s,!0;case"scrollmode":return e.scrollMode=Ms.parseEnum(s,We),!0;case"scrollspeed":return e.scrollSpeed=s,!0;case"nativebrowsersmoothscroll":return e.nativeBrowserSmoothScroll=s,!0;case"songbookbendduration":return e.songBookBendDuration=s,!0;case"songbookdipduration":return e.songBookDipDuration=s,!0;case"playtripletfeel":return e.playTripletFeel=s,!0;case"buffertimeinmilliseconds":return e.bufferTimeInMilliseconds=s,!0}if(["vibrato"].indexOf(t)>=0)return Js.fromJson(e.vibrato,s),!0;for(const i of["vibrato"])if(0===t.indexOf(i)&&Js.setProperty(e.vibrato,t.substring(i.length),s))return!0;if(["slide"].indexOf(t)>=0)return js.fromJson(e.slide,s),!0;for(const i of["slide"])if(0===t.indexOf(i)&&js.setProperty(e.slide,t.substring(i.length),s))return!0;return!1}}class $s{static fromJson(e,t){t&&Ms.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",zs.toJson(e.core)),t.set("display",Xs.toJson(e.display)),t.set("notation",Ys.toJson(e.notation)),t.set("importer",qs.toJson(e.importer)),t.set("player",Qs.toJson(e.player)),t}static setProperty(e,t,s){if(["core",""].indexOf(t)>=0)return zs.fromJson(e.core,s),!0;for(const i of["core",""])if(0===t.indexOf(i)&&zs.setProperty(e.core,t.substring(i.length),s))return!0;if(["display",""].indexOf(t)>=0)return Xs.fromJson(e.display,s),!0;for(const i of["display",""])if(0===t.indexOf(i)&&Xs.setProperty(e.display,t.substring(i.length),s))return!0;if(["notation"].indexOf(t)>=0)return Ys.fromJson(e.notation,s),!0;for(const i of["notation"])if(0===t.indexOf(i)&&Ys.setProperty(e.notation,t.substring(i.length),s))return!0;if(["importer"].indexOf(t)>=0)return qs.fromJson(e.importer,s),!0;for(const i of["importer"])if(0===t.indexOf(i)&&qs.setProperty(e.importer,t.substring(i.length),s))return!0;if(["player"].indexOf(t)>=0)return Qs.fromJson(e.player,s),!0;for(const i of["player"])if(0===t.indexOf(i)&&Qs.setProperty(e.player,t.substring(i.length),s))return!0;return!1}}class Ks{constructor(){this.core=new Co,this.display=new Os,this.notation=new U,this.importer=new Gs,this.player=new Ws}setSongBookModeSettings(){this.notation.notationMode=T.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=B.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(k.ParenthesisOnTiedBends,!1),this.notation.elements.set(k.TabNotesOnTiedBends,!1),this.notation.elements.set(k.ZerosOnDiveWhammys,!0)}static get songBook(){let e=new Ks;return e.setSongBookModeSettings(),e}fillFromJson(e){$s.fromJson(this,e)}}class Zs{static fromJson(e,t){t&&Ms.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 ei{static fromJson(e,t){t&&Ms.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=Ms.parseEnum(s,a),!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 ti{static fromJson(e,t){t&&Ms.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=Ms.parseEnum(s,xe),!0;case"length":return e.length=s,!0}return!1}}class si{static fromJson(e,t){t&&Ms.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("tripletfeel",e.tripletFeel),t.set("section",Zs.toJson(e.section)),t.set("tempoautomation",ei.toJson(e.tempoAutomation)),null!==e.fermata){const s=new Map;t.set("fermata",s);for(const[t,i]of e.fermata)s.set(t.toString(),ti.toJson(i))}return t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t}static setProperty(e,t,s){switch(t){case"alternateendings":return e.alternateEndings=s,!0;case"keysignature":return e.keySignature=Ms.parseEnum(s,L),!0;case"keysignaturetype":return e.keySignatureType=Ms.parseEnum(s,I),!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"tripletfeel":return e.tripletFeel=Ms.parseEnum(s,D),!0;case"fermata":return e.fermata=new Map,Ms.forEach(s,((t,s)=>{const i=new ot;ti.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}return["section"].indexOf(t)>=0?(s?(e.section=new pe,Zs.fromJson(e.section,s)):e.section=null,!0):["tempoautomation"].indexOf(t)>=0&&(s?(e.tempoAutomation=new V,ei.fromJson(e.tempoAutomation,s)):e.tempoAutomation=null,!0)}}class ii{static fromJson(e,t){t&&Ms.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 ai{static fromJson(e,t){t&&Ms.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=>ii.toJson(e)))),t.set("fret",e.fret),t.set("string",e.string),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("isfingering",e.isFingering),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),e.toJson(t),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"accentuated":return e.accentuated=Ms.parseEnum(s,i),!0;case"bendtype":return e.bendType=Ms.parseEnum(s,l),!0;case"bendstyle":return e.bendStyle=Ms.parseEnum(s,h),!0;case"iscontinuedbend":return e.isContinuedBend=s,!0;case"bendpoints":if(s){e.bendPoints=[];for(const t of s){const s=new z;ii.fromJson(s,t),e.addBendPoint(s)}}return!0;case"fret":return e.fret=s,!0;case"string":return e.string=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=Ms.parseEnum(s,m),!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=Ms.parseEnum(s,b),!0;case"slideouttype":return e.slideOutType=Ms.parseEnum(s,S),!0;case"vibrato":return e.vibrato=Ms.parseEnum(s,_),!0;case"istiedestination":return e.isTieDestination=s,!0;case"lefthandfinger":return e.leftHandFinger=Ms.parseEnum(s,f),!0;case"righthandfinger":return e.rightHandFinger=Ms.parseEnum(s,f),!0;case"isfingering":return e.isFingering=s,!0;case"trillvalue":return e.trillValue=s,!0;case"trillspeed":return e.trillSpeed=Ms.parseEnum(s,u),!0;case"durationpercent":return e.durationPercent=s,!0;case"accidentalmode":return e.accidentalMode=Ms.parseEnum(s,y),!0;case"dynamics":return e.dynamics=Ms.parseEnum(s,p),!0}return e.setProperty(t,s)}}class ri{static fromJson(e,t){t&&Ms.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=>ai.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=>ei.toJson(e)))),t.set("dots",e.dots),t.set("fadein",e.fadeIn),t.set("lyrics",e.lyrics),t.set("hasrasgueado",e.hasRasgueado),t.set("pop",e.pop),t.set("slap",e.slap),t.set("tap",e.tap),t.set("text",e.text),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=>ii.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("dynamics",e.dynamics),t.set("invertbeamdirection",e.invertBeamDirection),t.set("preferredbeamdirection",e.preferredBeamDirection),t.set("beamingmode",e.beamingMode),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 Z;ai.fromJson(s,t),e.addNote(s)}return!0;case"isempty":return e.isEmpty=s,!0;case"whammystyle":return e.whammyStyle=Ms.parseEnum(s,h),!0;case"ottava":return e.ottava=Ms.parseEnum(s,n),!0;case"islegatoorigin":return e.isLegatoOrigin=s,!0;case"duration":return e.duration=Ms.parseEnum(s,u),!0;case"automations":e.automations=[];for(const t of s){const s=new V;ei.fromJson(s,t),e.automations.push(s)}return!0;case"dots":return e.dots=s,!0;case"fadein":return e.fadeIn=s,!0;case"lyrics":return e.lyrics=s,!0;case"hasrasgueado":return e.hasRasgueado=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"brushtype":return e.brushType=Ms.parseEnum(s,c),!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=Ms.parseEnum(s,E),!0;case"whammybarpoints":if(s){e.whammyBarPoints=[];for(const t of s){const s=new z;ii.fromJson(s,t),e.addWhammyBarPoint(s)}}return!0;case"vibrato":return e.vibrato=Ms.parseEnum(s,_),!0;case"chordid":return e.chordId=s,!0;case"gracetype":return e.graceType=Ms.parseEnum(s,g),!0;case"pickstroke":return e.pickStroke=Ms.parseEnum(s,x),!0;case"tremolospeed":return e.tremoloSpeed=Ms.parseEnum(s,u),!0;case"crescendo":return e.crescendo=Ms.parseEnum(s,d),!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"dynamics":return e.dynamics=Ms.parseEnum(s,p),!0;case"invertbeamdirection":return e.invertBeamDirection=s,!0;case"preferredbeamdirection":return e.preferredBeamDirection=Ms.parseEnum(s,Ce),!0;case"beamingmode":return e.beamingMode=Ms.parseEnum(s,F),!0}return!1}}class ni{static fromJson(e,t){t&&Ms.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=>ri.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 ne;ri.fromJson(s,t),e.addBeat(s)}return!0;case"isempty":return e.isEmpty=s,!0}return!1}}class oi{static fromJson(e,t){t&&Ms.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=>ni.toJson(e)))),t.set("similemark",e.simileMark),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"clef":return e.clef=Ms.parseEnum(s,r),!0;case"clefottava":return e.clefOttava=Ms.parseEnum(s,n),!0;case"voices":e.voices=[];for(const t of s){const s=new _e;ni.fromJson(s,t),e.addVoice(s)}return!0;case"similemark":return e.simileMark=Ms.parseEnum(s,o),!0;case"displayscale":return e.displayScale=s,!0;case"displaywidth":return e.displayWidth=s,!0}return!1}}class hi{static fromJson(e,t){t&&Ms.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 li{static fromJson(e,t){t&&Ms.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 ci{static fromJson(e,t){t&&Ms.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=>oi.toJson(e)))),null!==e.chords){const s=new Map;t.set("chords",s);for(const[t,i]of e.chords)s.set(t.toString(),hi.toJson(i))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",li.toJson(e.stringTuning)),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 H;oi.fromJson(s,t),e.addBar(s)}return!0;case"chords":return e.chords=new Map,Ms.forEach(s,((t,s)=>{const i=new oe;hi.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"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&&(li.fromJson(e.stringTuning,s),!0)}}class di{static fromJson(e,t){t&&Ms.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 ui{static fromJson(e,t){t&&Ms.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=Ms.parseEnum(s,N),!0;case"noteheadhalf":return e.noteHeadHalf=Ms.parseEnum(s,N),!0;case"noteheadwhole":return e.noteHeadWhole=Ms.parseEnum(s,N),!0;case"techniquesymbol":return e.techniqueSymbol=Ms.parseEnum(s,N),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=Ms.parseEnum(s,C),!0;case"outputmidinumber":return e.outputMidiNumber=s,!0}return!1}}class pi{static fromJson(e,t){t&&Ms.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=>ci.toJson(e)))),t.set("playbackinfo",di.toJson(e.playbackInfo)),t.set("color",fe.toJson(e.color)),t.set("name",e.name),t.set("shortname",e.shortName),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("percussionarticulations",e.percussionArticulations.map((e=>ui.toJson(e)))),t}static setProperty(e,t,s){switch(t){case"staves":e.staves=[];for(const t of s){const s=new be;ci.fromJson(s,t),e.addStaff(s)}return!0;case"color":return e.color=fe.fromJson(s),!0;case"name":return e.name=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 Q;ui.fromJson(s,t),e.percussionArticulations.push(s)}return!0}return["playbackinfo"].indexOf(t)>=0&&(di.fromJson(e.playbackInfo,s),!0)}}class gi{static fromJson(e,t){t&&Ms.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("hidedynamics",e.hideDynamics),t}static setProperty(e,t,s){return"hidedynamics"===t&&(e.hideDynamics=s,!0)}}class fi{static fromJson(e,t){t&&Ms.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=>si.toJson(e)))),t.set("tracks",e.tracks.map((e=>pi.toJson(e)))),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("stylesheet",gi.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 le;si.fromJson(s,t),e.addMasterBar(s)}return!0;case"tracks":e.tracks=[];for(const t of s){const s=new Se;pi.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&&(gi.fromJson(e.stylesheet,s),!0)}}class mi{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=mi.scoreToJsObject(e);return JSON.stringify(t,mi.jsonReplacer)}static jsonToScore(e,t){return mi.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return fi.toJson(e)}static jsObjectToScore(e,t){let s=new ue;return fi.fromJson(s,e),s.finish(t??new Ks),s}static settingsToJson(e){let t=mi.settingsToJsObject(e);return JSON.stringify(t,mi.jsonReplacer)}static jsonToSettings(e){return mi.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return $s.toJson(e)}static jsObjectToSettings(e){let t=new Ks;return $s.fromJson(t,e),t}static jsObjectToMidiFile(e){let t=new At;return Ms.forEach(e,((e,s)=>{switch(s){case"division":t.division=e;break;case"tracks":for(let s of e){let e=mi.jsObjectToMidiTrack(s);t.tracks.push(e)}}})),t}static jsObjectToMidiTrack(e){let t=new Dt;return Ms.forEach(e,((e,s)=>{if("events"===s)for(let s of e){let e=mi.jsObjectToMidiEvent(s);t.events.push(e)}})),t}static jsObjectToMidiEvent(e){let t=Ms.getValue(e,"track"),i=Ms.getValue(e,"tick"),a=Ms.getValue(e,"type");switch(a){case Le.TimeSignature:return new Ot(t,i,Ms.getValue(e,"numerator"),Ms.getValue(e,"denominatorIndex"),Ms.getValue(e,"midiClocksPerMetronomeClick"),Ms.getValue(e,"thirdySecondNodesInQuarter"));case Le.AlphaTabRest:return new Ht(t,i,Ms.getValue(e,"channel"));case Le.AlphaTabMetronome:return new Vt(t,i,Ms.getValue(e,"metronomeNumerator"),Ms.getValue(e,"metronomeDurationInTicks"),Ms.getValue(e,"metronomeDurationInMilliseconds"));case Le.NoteOn:return new zt(t,i,Ms.getValue(e,"channel"),Ms.getValue(e,"noteKey"),Ms.getValue(e,"noteVelocity"));case Le.NoteOff:return new Ut(t,i,Ms.getValue(e,"channel"),Ms.getValue(e,"noteKey"),Ms.getValue(e,"noteVelocity"));case Le.ControlChange:return new Xt(t,i,Ms.getValue(e,"channel"),Ms.getValue(e,"controller"),Ms.getValue(e,"value"));case Le.ProgramChange:return new Yt(t,i,Ms.getValue(e,"channel"),Ms.getValue(e,"program"));case Le.TempoChange:return new qt(i,Ms.getValue(e,"microSecondsPerQuarterNote"));case Le.PitchBend:return new Jt(t,i,Ms.getValue(e,"channel"),Ms.getValue(e,"value"));case Le.PerNotePitchBend:return new jt(t,i,Ms.getValue(e,"channel"),Ms.getValue(e,"noteKey"),Ms.getValue(e,"value"));case Le.EndOfTrack:return new Qt(t,i)}throw new O(s.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(mi.midiTrackToJsObject(t));return t.set("tracks",s),t}static midiTrackToJsObject(e){const t=new Map,s=[];for(let t of e.events)s.push(mi.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 Le.TimeSignature:t.set("numerator",e.numerator),t.set("denominatorIndex",e.denominatorIndex),t.set("midiClocksPerMetronomeClick",e.midiClocksPerMetronomeClick),t.set("thirdySecondNodesInQuarter",e.thirtySecondNodesInQuarter);break;case Le.AlphaTabRest:t.set("channel",e.channel);break;case Le.AlphaTabMetronome:t.set("metronomeNumerator",e.metronomeNumerator),t.set("metronomeDurationInMilliseconds",e.metronomeDurationInMilliseconds),t.set("metronomeDurationInTicks",e.metronomeDurationInTicks);break;case Le.NoteOn:case Le.NoteOff:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("noteVelocity",e.noteVelocity);break;case Le.ControlChange:t.set("channel",e.channel),t.set("controller",e.controller),t.set("value",e.value);break;case Le.ProgramChange:t.set("channel",e.channel),t.set("program",e.program);break;case Le.TempoChange:t.set("microSecondsPerQuarterNote",e.microSecondsPerQuarterNote);break;case Le.PitchBend:t.set("channel",e.channel),t.set("value",e.value);break;case Le.PerNotePitchBend:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("value",e.value);case Le.EndOfTrack:}return t}}class yi{constructor(){this.ready=new Ps,this.samplesPlayed=new Cs,this.sampleRequest=new Ps}get sampleRate(){return yi.preferredSampleRate}open(){q.debug("AlphaSynth","Initializing synth worker"),this._worker=Po.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 yi.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case yi.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(){}}yi.CmdOutputPrefix="alphaSynth.output.",yi.CmdOutputAddSamples=yi.CmdOutputPrefix+"addSamples",yi.CmdOutputPlay=yi.CmdOutputPrefix+"play",yi.CmdOutputPause=yi.CmdOutputPrefix+"pause",yi.CmdOutputResetSamples=yi.CmdOutputPrefix+"resetSamples",yi.CmdOutputSampleRequest=yi.CmdOutputPrefix+"sampleRequest",yi.CmdOutputSamplesPlayed=yi.CmdOutputPrefix+"samplesPlayed",yi.preferredSampleRate=0;class bi{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new Ls(new yi,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=Po.globalThis;e.addEventListener("message",(t=>{let s=t.data;if("alphaSynth.initialize"===s.cmd)yi.preferredSampleRate=s.sampleRate,q.logLevel=s.logLevel,Po.globalThis.alphaSynthWebWorker=new bi(e,s.bufferTimeInMilliseconds)}))}handleMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":q.logLevel=t.value;break;case"alphaSynth.setMasterVolume":this._player.masterVolume=t.value;break;case"alphaSynth.setMetronomeVolume":this._player.metronomeVolume=t.value;break;case"alphaSynth.setPlaybackSpeed":this._player.playbackSpeed=t.value;break;case"alphaSynth.setTickPosition":this._player.tickPosition=t.value;break;case"alphaSynth.setTimePosition":this._player.timePosition=t.value;break;case"alphaSynth.setPlaybackRange":this._player.playbackRange=t.value;break;case"alphaSynth.setIsLooping":this._player.isLooping=t.value;break;case"alphaSynth.setCountInVolume":this._player.countInVolume=t.value;break;case"alphaSynth.setMidiEventsPlayedFilter":this._player.midiEventsPlayedFilter=t.value;break;case"alphaSynth.play":this._player.play();break;case"alphaSynth.pause":this._player.pause();break;case"alphaSynth.playPause":this._player.playPause();break;case"alphaSynth.stop":this._player.stop();break;case"alphaSynth.playOneTimeMidiFile":this._player.playOneTimeMidiFile(mi.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(mi.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);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(mi.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}class Si{static generateFontLookup(e){if(!Si.FontSizeLookupTables.has(e))if(Po.isRunningInWorker)Si.FontSizeLookupTables.set(e,new Uint8Array([8]));else{let t=document.createElement("canvas").getContext("2d");t.font=`11px ${e}`;let s=[];for(let e=32;e<255;e++){let i=String.fromCharCode(e);s.push(t.measureText(i).width)}let i=new Uint8Array(s);Si.FontSizeLookupTables.set(e,i)}}static measureString(e,t,s,i,a){let r,n=t[0];for(let e=0;e<t.length;e++)if(Si.FontSizeLookupTables.has(t[e])){n=t[e];break}Si.FontSizeLookupTables.has(n)||Si.generateFontLookup(n),r=Si.FontSizeLookupTables.get(n);let o=1;i===Ge.Italic&&(o*=1.2),a===Ve.Bold&&(o*=1.2);let h=0;for(let t=0;t<e.length;t++){let i=Math.min(r.length-1,e.charCodeAt(t)-32);i>=0&&(h+=r[i]*s/11)}return h*o}}Si.Georgia=new Uint8Array([3,4,5,7,7,9,8,2,4,4,5,7,3,4,3,5,7,5,6,6,6,6,6,6,7,6,3,3,7,7,7,5,10,7,7,7,8,7,7,8,9,4,6,8,7,10,8,8,7,8,8,6,7,8,7,11,8,7,7,4,5,4,7,7,6,6,6,5,6,5,4,6,6,3,3,6,3,10,6,6,6,6,5,5,4,6,5,8,6,5,5,5,4,5,7,6,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,3,4,6,7,6,7,4,6,6,10,6,6,7,0,10,7,5,7,6,6,6,6,6,3,6,6,6,6,12,12,12,5,7,7,7,7,7,7,11,7,7,7,7,7,4,4,4,4,8,8,8,8,8,8,8,7,8,8,8,8,8,7,7,6,6,6,6,6,6,6,8,5,5,5,5,5,3,3,3,3,6,6,6,6,6,6,6,7,6,6,6,6,6,5,6]),Si.Arial=new Uint8Array([3,3,4,6,6,10,7,2,4,4,4,6,3,4,3,3,6,6,6,6,6,6,6,6,6,6,3,3,6,6,6,6,11,7,7,8,8,7,7,9,8,3,6,7,6,9,8,9,7,9,8,7,7,8,7,10,7,7,7,3,3,3,5,6,4,6,6,6,6,6,3,6,6,2,2,6,2,9,6,6,6,6,4,6,3,6,6,8,6,6,6,4,3,4,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,4,6,6,6,6,3,6,4,8,4,6,6,0,8,6,4,6,4,4,4,6,6,4,4,4,4,6,9,9,9,7,7,7,7,7,7,7,11,8,7,7,7,7,3,3,3,3,8,8,9,9,9,9,9,6,9,8,8,8,8,7,7,7,6,6,6,6,6,6,10,6,6,6,6,6,3,3,3,3,6,6,6,6,6,6,6,6,7,6,6,6,6,6,6]),Si.FontSizeLookupTables=new Map([["Arial",Si.Arial],["'Arial'",Si.Arial],['"Arial"',Si.Arial],["Georgia",Si.Georgia],["'Georgia'",Si.Georgia],['"Georgia"',Si.Georgia]]),Si.ControlChars=32;class _i{constructor(){this.id=j.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 wi{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(){this.beats.sort(((e,t)=>e.realBounds.x-t.realBounds.x))}}class Bi{constructor(){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}}class Ti{constructor(){this.index=0,this.isFirstOfLine=!1,this.bars=[],this.staveGroupBounds=null}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(){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 e of this.bars)e.finish()}addBeat(e){this.staveGroupBounds.boundsLookup.addBeat(e)}}class ki{}class vi{constructor(){this.index=0,this.bars=[]}finish(){for(let e of this.bars)e.finish()}addBar(e){this.boundsLookup.addMasterBar(e),e.staveGroupBounds=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 xi{constructor(){this._beatLookup=new Map,this._masterBarLookup=new Map,this._currentStaveGroup=null,this.staveGroups=[],this.isFinished=!1}toJson(){let e={},t=[];e.staveGroups=t;for(let e of this.staveGroups){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);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 xi,i=e.staveGroups;for(let e of i){let i=new vi;i.visualBounds=e.visualBounds,i.realBounds=e.realBounds,s.addStaveGroup(i);for(let s of e.bars){let e=new Ti;e.index=s.index,e.isFirstOfLine=s.isFirstOfLine,e.lineAlignedBounds=s.lineAlignedBounds,e.visualBounds=s.visualBounds,e.realBounds=s.realBounds,i.addBar(e);for(let i of s.bars){let s=new wi;s.visualBounds=i.visualBounds,s.realBounds=i.realBounds,e.addBar(s);for(let e of i.beats){let i=new Bi;i.visualBounds=e.visualBounds,i.realBounds=e.realBounds;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 ki,s=t;e.note=i.beat.notes[s.index],e.noteHeadBounds=t.noteHeadBounds,i.addNote(e)}}s.addBeat(i)}}}}return s}boundsToJson(e){let t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(){for(let e of this.staveGroups)e.finish();this.isFinished=!0}addStaveGroup(e){e.index=this.staveGroups.length,e.boundsLookup=this,this.staveGroups.push(e),this._currentStaveGroup=e}addMasterBar(e){e.staveGroupBounds?this._masterBarLookup.set(e.index,e):(e.staveGroupBounds=this._currentStaveGroup,this._masterBarLookup.set(e.index,e),this._currentStaveGroup.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.staveGroups.length-1,a=-1;for(;s<=i;){let e=(i+s)/2|0,r=this.staveGroups[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.staveGroups[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 Ni{constructor(t){this._currentLayoutMode=e.Page,this._currentRenderEngine=null,this._renderedTracks=null,this.canvas=null,this.score=null,this.tracks=null,this.layout=null,this.boundsLookup=null,this.width=0,this.preRender=new Cs,this.renderFinished=new Cs,this.partialRenderFinished=new Cs,this.partialLayoutFinished=new Cs,this.postRenderFinished=new Ps,this.error=new Cs,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=Po.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=Po.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?(q.debug("Rendering","Request render of lazy partial "+e),t.renderLazyPartial(e)):q.warning("Rendering","Request render of lazy partial "+e+" ignored, no layout exists")}catch(e){this.error.trigger(e)}}render(){if(0!==this.width)if(this.boundsLookup=new xi,this.recreateCanvas(),this.canvas.lineWidth=this.settings.display.scale,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){q.debug("Rendering","Rendering "+this.tracks.length+" tracks");for(let e=0;e<this.tracks.length;e++){let t=this.tracks[e];q.debug("Rendering","Track "+e+": "+t.name)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),q.debug("Rendering","Rendering finished")}else q.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),q.debug("Rendering","Clearing finished");else q.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(q.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(q.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new xi,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):q.debug("Rendering","Current layout does not support dynamic resizing, nothing was done",null),q.debug("Rendering","Resize finished")}layoutAndRender(){q.debug("Rendering","Rendering at scale "+this.settings.display.scale+" with layout "+this.layout.name,null),this.layout.layoutAndRender(),this._renderedTracks=this.tracks,this.onRenderFinished(),this.postRenderFinished.trigger()}onRenderFinished(){this.boundsLookup?.finish();const e=new _i;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}class Pi{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){Po.globalThis.alphaTabWebWorker=new Pi(Po.globalThis)}handleMessage(e){let t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":let e=mi.jsObjectToSettings(t.settings);q.logLevel=e.core.logLevel,this._renderer=new Ni(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:mi.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(s,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(e){Si.FontSizeLookupTables||(Si.FontSizeLookupTables=new Map);for(let t in e)Si.FontSizeLookupTables.set(t,e[t])}}updateSettings(e){$s.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){q.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class Ci{constructor(){this._canvas=null,this._color=new fe(0,0,0,255),this._font=new As("Arial",10,Ge.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 As(s,parseFloat(t.fontSize),Ge.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){this._canvas=document.createElement("canvas"),this._canvas.width=e*Po.HighDpiFactor|0,this._canvas.height=t*Po.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(Po.HighDpiFactor,Po.HighDpiFactor),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){this._context.strokeRect(0|e,0|t,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(this.settings.display.scale)),this._measureContext.font=e.toCssString(this.settings.display.scale)}get textAlign(){switch(this._context.textAlign){case"left":default:return P.Left;case"center":return P.Center;case"right":return P.Right}}set textAlign(e){switch(e){case P.Left:this._context.textAlign="left";break;case P.Center:this._context.textAlign="center";break;case P.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return C.Top;case"middle":return C.Middle;case"bottom":return C.Bottom}}set textBaseline(e){switch(e){case C.Top:this._context.textBaseline="hanging";break;case C.Middle:this._context.textBaseline="middle";break;case C.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,s){this._context.fillText(e,t,s)}measureText(e){return this._measureContext.measureText(e).width}fillMusicFontSymbol(e,t,s,i,a=!1){i!==N.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!==N.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a=!1){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 Ei{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 Ot(0,e,t,i,48,8))}addRest(e,t,s){this._smf1Mode||this._midiFile.addEvent(new Ht(e,t,s))}addNote(e,t,s,i,a,r){this._midiFile.addEvent(new zt(e,t,r,Ei.fixValue(i),Ei.fixValue(a))),this._midiFile.addEvent(new Ut(e,t+s,r,Ei.fixValue(i),Ei.fixValue(a)))}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,s,i,a){this._midiFile.addEvent(new Xt(e,t,s,i,Ei.fixValue(a)))}addProgramChange(e,t,s,i){this._midiFile.addEvent(new Yt(e,t,s,i))}addTempo(e,t){const s=6e7/t|0;this._midiFile.addEvent(new qt(e,s))}addBend(e,t,s,i){i=i>=Kt.MaxPitchWheel?Kt.MaxPitchWheel:Math.floor(i),this._midiFile.addEvent(new Jt(e,t,s,i))}addNoteBend(e,t,s,i,a){this._smf1Mode?this.addBend(e,t,s,a):(a=a*Kt.MaxPitchWheel20/Kt.MaxPitchWheel,this._midiFile.addEvent(new jt(e,t,s,i,a)))}finishTrack(e,t){this._midiFile.format!=Fe.MultiTrack&&0!=e||this._midiFile.addEvent(new Qt(e,t))}}class Fi{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))}}class Li{get finished(){return this.index>=this._score.masterBars.length}constructor(e){this._repeatStack=[],this._groupsOnStack=new Set,this._previousAlternateEndings=0,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}processCurrent(){const e=this._score.masterBars[this.index];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 Fi(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)}this.shouldPlay&&(this.currentTick+=e.calculateDuration())}moveNext(){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 Mi{constructor(e,t){this.beat=e,this.playbackStart=t}}class Ii{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 Mi(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 Di{constructor(){this.start=0,this.end=0,this.tempo=0,this.firstBeat=null,this.lastBeat=null,this.nextMasterBar=null,this.previousMasterBar=null}insertAfter(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.nextBeat=e.nextBeat,t.previousBeat=e,e.nextBeat&&(e.nextBeat.previousBeat=t),e.nextBeat=t,e==this.lastBeat&&(this.lastBeat=t))}insertBefore(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.previousBeat=e.previousBeat,t.nextBeat=e,e.previousBeat&&(e.previousBeat.nextBeat=t),e.previousBeat=t,e==this.firstBeat&&(this.firstBeat=t))}addBeat(e,t,i,a){const r=i+a;if(null==this.firstBeat){const s=new Ii(i,r);s.highlightBeat(e,t),this.insertAfter(this.firstBeat,s)}else if(i>=this.lastBeat.end){const s=new Ii(this.lastBeat.end,r);s.highlightBeat(e,t),this.insertAfter(this.lastBeat,s)}else{let a=null;if(i<this.firstBeat.start)a=this.firstBeat;else{let e=this.firstBeat;for(;null!=e;){if(i>=e.start&&i<e.end){a=e;break}e=e.nextBeat}if(null===a)throw new O(s.General,"Error on building lookup, unknown variant")}if(i<a.start)if(r==a.start){const s=new Ii(i,a.start);s.highlightBeat(e,t),this.insertBefore(this.firstBeat,s)}else if(r<a.end){const s=new Ii(i,a.start);s.highlightBeat(e,t),this.insertBefore(a,s);const n=new Ii(a.start,r);for(const e of a.highlightedBeats)n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(e,t),this.insertBefore(a,n),a.start=r}else if(r==a.end){const s=new Ii(i,a.start);s.highlightBeat(e,t),a.highlightBeat(e,t),this.insertBefore(a,s)}else{const s=new Ii(i,a.start);s.highlightBeat(e,t),a.highlightBeat(e,t),this.insertBefore(a,s),this.addBeat(e,t,a.end,r-a.end)}else if(i>a.start)if(r==a.end){const s=new Ii(a.start,i);for(const e of a.highlightedBeats)s.highlightBeat(e.beat,e.playbackStart);a.start=i,a.highlightBeat(e,t),this.insertBefore(a,s)}else if(r<a.end){const s=new Ii(a.start,i);this.insertBefore(a,s);const n=new Ii(i,r);this.insertBefore(a,n);for(const e of a.highlightedBeats)s.highlightBeat(e.beat,e.playbackStart),n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(e,t),a.start=r}else{const s=new Ii(a.start,i);for(const e of a.highlightedBeats)s.highlightBeat(e.beat,e.playbackStart);a.start=i,a.highlightBeat(e,t),this.insertBefore(a,s),this.addBeat(e,t,a.end,r-a.end)}else if(r===a.end)a.highlightBeat(e,t);else if(r<a.end){const s=new Ii(a.start,r);for(const e of a.highlightedBeats)s.highlightBeat(e.beat,e.playbackStart);s.highlightBeat(e,t),a.start=r,this.insertBefore(a,s)}else a.highlightBeat(e,t),this.addBeat(e,t,a.end,r-a.end)}}}class Ai{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}}class Ri{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.duration=W.ticksToMillis(e.tickDuration,e.masterBar.tempo)),e.nextBeat||(e.tickDuration=e.masterBar.end-e.start,e.duration=W.ticksToMillis(e.tickDuration,e.masterBar.tempo))}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 Ai(e);return r.beat=s,r.beatLookup=t,r.tickDuration=t.end-t.start,i&&this.fillNextBeat(r,a),r.duration=W.ticksToMillis(r.tickDuration,e.tempo),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 Di;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 Oi{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Gi{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class Vi{constructor(e,t,s){this._currentTempo=0,this._programsPerChannel=new Map,this.tickLookup=new Ri,this.applyTranspositionPitches=!0,this.transpositionPitches=new Map,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new Ks,this._currentTempo=this._score.tempo,this._handler=s}generate(){this.transpositionPitches.clear();for(const e of this._score.tracks)this.generateTrack(e);q.debug("Midi","Begin midi generation");const e=new Li(this._score);let t=null;for(;!e.finished;){const s=e.index,i=this._score.masterBars[s],a=e.currentTick;if(e.processCurrent(),e.shouldPlay){this.generateMasterBar(i,t,a);for(const e of this._score.tracks)for(const t of e.staves)s<t.bars.length&&this.generateBar(t.bars[s],a)}e.moveNext(),t=i}for(const t of this._score.tracks)this._handler.finishTrack(t.index,e.currentTick);q.debug("Midi","Midi generation done")}generateTrack(e){this.generateChannel(e,e.playbackInfo.primaryChannel,e.playbackInfo),e.playbackInfo.primaryChannel!==e.playbackInfo.secondaryChannel&&this.generateChannel(e,e.playbackInfo.secondaryChannel,e.playbackInfo)}addProgramChange(e,t,s,i){this._programsPerChannel.has(s)&&this._programsPerChannel.get(s)===i||(this._handler.addProgramChange(e.index,t,s,i),this._programsPerChannel.set(s,i))}static buildTranspositionPitches(e,t){const s=new Map;for(const i of e.tracks){const e=i.index<t.notation.transpositionPitches.length?t.notation.transpositionPitches[i.index]:0;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]:0;this.transpositionPitches.set(t,i);let a=Vi.toChannelShort(s.volume),r=Vi.toChannelShort(s.balance);this._handler.addControlChange(e.index,0,t,Oe.VolumeCoarse,a),this._handler.addControlChange(e.index,0,t,Oe.PanCoarse,r),this._handler.addControlChange(e.index,0,t,Oe.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,Oe.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,Oe.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,Oe.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,Oe.DataEntryCoarse,Vi.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){t&&t.timeSignatureDenominator===e.timeSignatureDenominator&&t.timeSignatureNumerator===e.timeSignatureNumerator||this._handler.addTimeSignature(s,e.timeSignatureNumerator,e.timeSignatureDenominator),e.tempoAutomation?(this._handler.addTempo(s,e.tempoAutomation.value),this._currentTempo=e.tempoAutomation.value):t||(this._handler.addTempo(s,e.score.tempo),this._currentTempo=e.score.tempo);const i=new Di;i.masterBar=e,i.start=s,i.tempo=this._currentTempo,i.end=i.start+e.calculateDuration(),this.tickLookup.addMasterBar(i)}generateBar(e,t){let s=this.getPlaybackBar(e);for(const i of s.voices)this.generateVoice(i,t,e)}getPlaybackBar(e){switch(e.simileMark){case o.Simple:e.previousBar&&(e=this.getPlaybackBar(e.previousBar));break;case o.FirstOfDouble:case o.SecondOfDouble:e.previousBar&&e.previousBar.previousBar&&(e=this.getPlaybackBar(e.previousBar.previousBar))}return e}generateVoice(e,t,s){if(!e.isEmpty||e.bar.isEmpty&&0===e.index)for(const i of e.beats)this.generateBeat(i,t,s)}generateBeat(e,t,s){let i=e.playbackStart,a=e.playbackDuration;e.voice.bar.isEmpty?a=e.voice.bar.masterBar.calculateDuration():e.voice.bar.masterBar.tripletFeel!==D.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(i-=this._currentTripletFeel.secondBeatStartOffset,a=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=Vi.calculateTripletFeelInfo(i,a,e),this._currentTripletFeel&&(a=this._currentTripletFeel.firstBeatDuration))),s===e.voice.bar?this.tickLookup.addBeat(e,i,a):this.tickLookup.addBeat(e,0,a);const r=e.voice.bar.staff.track;for(const s of e.automations)this.generateAutomation(e,s,t);if(e.isRest)this._handler.addRest(r.index,t+i,r.playbackInfo.primaryChannel);else{let s=this.getBrushInfo(e);for(const r of e.notes)this.generateNote(r,t+i,a,s)}if(e.vibrato!==_.None){let s=240,a=3;switch(e.vibrato){case _.Slight:s=this._settings.player.vibrato.beatSlightLength,a=this._settings.player.vibrato.beatSlightAmplitude;break;case _.Wide:s=this._settings.player.vibrato.beatWideLength,a=this._settings.player.vibrato.beatWideAmplitude}this.generateVibratorWithParams(t+i,e.playbackDuration,s,a,((t,s)=>{this._handler.addBend(e.voice.bar.staff.track.index,t,r.playbackInfo.secondaryChannel,s)}))}}static calculateTripletFeelInfo(e,t,s){let i;switch(s.voice.bar.masterBar.tripletFeel){case D.Triplet8th:case D.Dotted8th:case D.Scottish8th:i=u.Eighth;break;case D.Triplet16th:case D.Dotted16th:case D.Scottish16th:i=u.Sixteenth;break;default:return null}const a=W.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 Gi;switch(s.voice.bar.masterBar.tripletFeel){case D.Triplet8th:r.firstBeatDuration=W.applyTuplet(W.toTicks(u.Quarter),3,2),r.secondBeatDuration=W.applyTuplet(W.toTicks(u.Eighth),3,2);break;case D.Dotted8th:r.firstBeatDuration=W.applyDot(W.toTicks(u.Eighth),!1),r.secondBeatDuration=W.toTicks(u.Sixteenth);break;case D.Scottish8th:r.firstBeatDuration=W.toTicks(u.Sixteenth),r.secondBeatDuration=W.applyDot(W.toTicks(u.Eighth),!1);break;case D.Triplet16th:r.firstBeatDuration=W.applyTuplet(W.toTicks(u.Eighth),3,2),r.secondBeatDuration=W.applyTuplet(W.toTicks(u.Sixteenth),3,2);break;case D.Dotted16th:r.firstBeatDuration=W.applyDot(W.toTicks(u.Sixteenth),!1),r.secondBeatDuration=W.toTicks(u.ThirtySecond);break;case D.Scottish16th:r.firstBeatDuration=W.toTicks(u.ThirtySecond),r.secondBeatDuration=W.applyDot(W.toTicks(u.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateNote(e,t,s,i){const a=e.beat.voice.bar.staff.track,r=e.beat.voice.bar.staff;let n=e.calculateRealValue(this.applyTranspositionPitches,!0);if(e.isPercussion){const t=$.getArticulation(e);t&&(n=t.outputMidiNumber)}const o=e.isStringed&&e.string<=i.length?i[e.string-1]:0,h=t+o,l=this.getNoteDuration(e,s);l.untilTieOrSlideEnd-=o,l.noteOnly-=o,l.letRingEnd-=o;const c=Vi.getNoteVelocity(e),d=e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==_.None?a.playbackInfo.secondaryChannel:a.playbackInfo.primaryChannel;let u=0;if(u=e.hasBend?Vi.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?Vi.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===S.Legato?-1:Vi.getPitchWheel(0),u>=0&&this._handler.addNoteBend(a.index,h,d,n,u),e.beat.fadeIn&&this.generateFadeIn(e,h,l),!e.isTrill||r.isPercussion){if(e.beat.isTremolo)this.generateTremoloPicking(e,h,l,n,c,d);else if(e.hasBend?this.generateBend(e,h,l,n,d):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,h,l,d):e.slideInType!==b.None||e.slideOutType!==S.None?this.generateSlide(e,h,l,n,d):(e.vibrato!==_.None||e.isTieDestination&&e.tieOrigin.vibrato!==_.None)&&this.generateVibrato(e,h,l,n,d),!(e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===S.Legato)){let e=Math.max(l.untilTieOrSlideEnd,l.letRingEnd);this._handler.addNote(a.index,h,e,n,c,d)}}else this.generateTrill(e,h,l,n,c,d)}getNoteDuration(e,t){const s=new Oi;if(s.noteOnly=t,s.untilTieOrSlideEnd=t,s.letRingEnd=t,e.isDead)return s.noteOnly=this.applyStaticDuration(Vi.DefaultDurationDead,t),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(e.isPalmMute)return s.noteOnly=this.applyStaticDuration(Vi.DefaultDurationPalmMute,t),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(e.isStaccato)return s.noteOnly=t/2|0,s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(e.isTieOrigin){const i=e.tieDestination;if(i)if(e.isTieDestination){const e=this.getNoteDuration(i,i.beat.playbackDuration);s.untilTieOrSlideEnd=t+e.untilTieOrSlideEnd}else{const t=e.beat.absolutePlaybackStart,a=this.getNoteDuration(i,i.beat.playbackDuration),r=i.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-t}}else if(e.slideOutType===S.Legato){const t=e.slideTarget;if(t){const i=e.beat.absolutePlaybackStart,a=this.getNoteDuration(t,t.beat.playbackDuration),r=t.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-i}}if(e.isLetRing&&this._settings.notation.notationMode===T.GuitarPro){let i=e.beat,a=0;const r=e.beat.voice.bar.masterBar.calculateDuration();for(;i.nextBeat;){let t=i.nextBeat;if(t.isRest)break;if(e.isStringed&&t.hasNoteOnString(e.string))break;if(i=i.nextBeat,a=i.absolutePlaybackStart-e.beat.absolutePlaybackStart+i.playbackDuration,a>r){a=r;break}}i===e.beat?s.letRingEnd=t:s.letRingEnd=a}else s.letRingEnd=s.untilTieOrSlideEnd;return s}applyStaticDuration(e,t){const s=this._currentTempo*e/z.MaxPosition|0;return Math.min(s,t)}static getNoteVelocity(e){let t=e.dynamics;switch(!e.beat.voice.bar.staff.isPercussion&&e.hammerPullOrigin&&t--,e.isGhost&&t--,e.accentuated){case i.Normal:t++;break;case i.Heavy:t+=2}return W.dynamicToVelocity(t)}generateFadeIn(e,t,s){const i=e.beat.voice.bar.staff.track,a=Vi.toChannelShort(i.playbackInfo.volume)/s.noteOnly,r=s.noteOnly/120|0,n=t+s.noteOnly;for(let e=r-1;e>=0;e--){const s=n-120*e,o=(s-t)*a;e===r-1&&(this._handler.addControlChange(i.index,t,i.playbackInfo.primaryChannel,Oe.VolumeCoarse,o),this._handler.addControlChange(i.index,t,i.playbackInfo.secondaryChannel,Oe.VolumeCoarse,o)),this._handler.addControlChange(i.index,s,i.playbackInfo.primaryChannel,Oe.VolumeCoarse,o),this._handler.addControlChange(i.index,s,i.playbackInfo.secondaryChannel,Oe.VolumeCoarse,o)}}generateVibrato(e,t,s,i,a){let r=0,n=0;switch(e.vibrato!==_.None?e.vibrato:e.isTieDestination?e.tieOrigin.vibrato:_.Slight){case _.Slight:r=this._settings.player.vibrato.noteSlightLength,n=this._settings.player.vibrato.noteSlightAmplitude;break;case _.Wide:r=this._settings.player.vibrato.noteWideLength,n=this._settings.player.vibrato.noteWideAmplitude;break;default:return}const o=e.beat.voice.bar.staff.track;this.generateVibratorWithParams(t,s.noteOnly,r,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)}))}generateVibratorWithParams(e,t,s,i,a){const r=this.vibratoResolution,n=s/2|0,o=(e+=s)+t;for(;e<o;){let t=0;const h=e+s<o?s:o-e;for(;t<h;){let s=i*Math.sin(t*Math.PI/n);a(e+t|0,Vi.getPitchWheel(s)),t+=r}e+=s}}static getPitchWheel(e){return Kt.DefaultPitchWheel+e/2*Vi.PitchValuePerSemitone}generateSlide(e,t,s,i,a){let r=e.slideOutType===S.Legato?s.noteOnly:s.untilTieOrSlideEnd,n=[],o=e.beat.voice.bar.staff.track;const h=this._settings.player.slide.simpleSlidePitchOffset,l=Math.floor(z.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),c=Math.floor(z.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case b.IntoFromAbove:n.push(new z(0,h)),n.push(new z(l,0));break;case b.IntoFromBelow:n.push(new z(0,-h)),n.push(new z(l,0))}switch(e.slideOutType){case S.Legato:case S.Shift:n.push(new z(c,0));const t=2*(e.slideTarget.calculateRealValue(this.applyTranspositionPitches,!0)-e.calculateRealValue(this.applyTranspositionPitches,!0));n.push(new z(z.MaxPosition,t));break;case S.OutDown:n.push(new z(z.MaxPosition-l,0)),n.push(new z(z.MaxPosition,-h));break;case S.OutUp:n.push(new z(z.MaxPosition-l,0)),n.push(new z(z.MaxPosition,h))}this.generateWhammyOrBend(t,r,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)}))}generateBend(e,t,s,i,a){let r=e.bendPoints,n=e.beat.voice.bar.staff.track;const o=(e,t)=>{this._handler.addNoteBend(n.index,e,a,i,t)};let c,d=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend;)t=t.tieDestination;c=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==g.None){switch(e.tieDestination.bendType){case l.Bend:case l.BendRelease:case l.PrebendBend:d=e.tieDestination.bendPoints[1].value;break;case l.Prebend:case l.PrebendRelease:d=e.tieDestination.bendPoints[0].value}c=Math.max(s.noteOnly,W.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo))}else c=s.noteOnly;r[0].value>0&&!e.isContinuedBend&&t>0&&t--;const u=Math.min(c,W.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));let p=[];switch(e.bendType){case l.Custom:p=r;break;case l.Bend:case l.Release:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new z(0,e.bendPoints[0].value)),(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),p.push(new z(z.MaxPosition,d));break;case h.Fast:return(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),void(e.beat.graceType===g.BendGrace?this.generateSongBookWhammyOrBend(t,c,!0,[e.bendPoints[0].value,d],u,o):this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,d],u,o))}break;case l.BendRelease:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new z(0,e.bendPoints[0].value)),p.push(new z(z.MaxPosition/2|0,e.bendPoints[1].value)),p.push(new z(z.MaxPosition,e.bendPoints[2].value));break;case h.Fast:return void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],u,o)}break;case l.Hold:case l.Prebend:p=r;break;case l.PrebendBend:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new z(0,e.bendPoints[0].value)),p.push(new z(z.MaxPosition,e.bendPoints[1].value));break;case h.Fast:return o(t,0|Vi.getPitchWheel(e.bendPoints[0].value)),(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,d],u,o)}break;case l.PrebendRelease:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new z(0,e.bendPoints[0].value)),p.push(new z(z.MaxPosition,e.bendPoints[1].value));break;case h.Fast:return o(t,0|Vi.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,e.bendPoints[1].value],u,o)}}this.generateWhammyOrBend(t,c,p,o)}generateSongBookWhammyOrBend(e,t,s,i,a,r){const n=s?e:e+t-a,o=a/(i.length-1);for(let e=0;e<i.length-1;e++){const t=Vi.getPitchWheel(i[e]),s=Vi.getPitchWheel(i[e+1]),a=n+o*e;this.generateBendValues(a,o,t,s,r)}}generateWhammy(e,t,s,i){const a=e.whammyBarPoints,r=e.voice.bar.staff.track,n=s.noteOnly;a[0].value>0&&!e.isContinuedWhammy&&t--;const o=(e,t)=>{this._handler.addBend(r.index,e,i,t)};let l=[];switch(e.whammyBarType){case E.Custom:l=a;break;case E.Dive:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new z(0,a[0].value)),l.push(new z(z.MaxPosition,a[1].value));break;case h.Fast:const e=Math.min(n,W.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],e,o)}break;case E.Dip:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new z(0,a[0].value)),l.push(new z(z.MaxPosition/2|0,a[1].value)),l.push(new z(z.MaxPosition,a[2].value));break;case h.Fast:const e=Math.min(n,W.millisToTicks(this._settings.player.songBookDipDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!0,[a[0].value,a[1].value,a[2].value],e,o)}break;case E.Hold:case E.Predive:l=a;break;case E.PrediveDive:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new z(0,a[0].value)),l.push(new z(z.MaxPosition/2|0,a[0].value)),l.push(new z(z.MaxPosition,a[1].value));break;case h.Fast:const e=Vi.getPitchWheel(a[0].value);this._handler.addBend(r.index,t,i,0|e);const s=Math.min(n,W.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],s,o)}}this.generateWhammyOrBend(t,n,l,o)}generateWhammyOrBend(e,t,s,i){const a=t/z.MaxPosition;for(let t=0;t<s.length-1;t++){const r=s[t],n=s[t+1],o=Vi.getPitchWheel(r.value),h=Vi.getPitchWheel(n.value),l=a*(n.offset-r.offset),c=e+a*r.offset;this.generateBendValues(c,l,o,h,i)}}generateBendValues(e,t,s,i,a){const r=W.ticksToMillis(t,this._currentTempo),n=Math.abs(i-s)/Vi.PitchValuePerSemitone,o=Math.max(Vi.MinBreakpointsPerSemitone*n,r/Vi.MillisecondsPerBreakpoint),h=t/o,l=(i-s)/o;for(let t=0;t<o;t++)a(0|e,Math.round(s)),s+=l,e+=h;s<i&&a(0|e,i)}generateTrill(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=W.toTicks(e.trillSpeed),l=!0,c=t,d=t+s.untilTieOrSlideEnd;for(;c+10<d;)c+h>=d&&(h=d-c),this._handler.addNote(n.index,c,h,l?o:i,a,r),l=!l,c+=h}generateTremoloPicking(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track;let o=W.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}getBrushInfo(e){const t=new Int32Array(e.voice.bar.staff.tuning.length);if(e.brushType!==c.None){let s=0,i=0;for(const t of e.notes)t.isTieDestination||(s|=1<<t.string-1,i++);if(e.notes.length>0){let a=0;const r=e.brushDuration/(i-1)|0;for(let i=0;i<e.voice.bar.staff.tuning.length;i++){let n=e.brushType===c.ArpeggioDown||e.brushType===c.BrushDown?i:t.length-1-i;s&1<<n&&(t[n]=a,a+=r)}}}return t}generateAutomation(e,t,s){switch(t.type){case a.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 a.Balance:let i=Vi.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Oe.PanCoarse,i),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Oe.PanCoarse,i);break;case a.Volume:let r=Vi.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Oe.VolumeCoarse,r),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Oe.VolumeCoarse,r)}}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 a.Instrument:s=i.value;break;case a.Tempo:t=i.value}i=i.previousBeat}const r=e.voice.bar.staff.track,n=e.voice.bar.masterBar;-1===t&&(t=n.score.tempo),-1===s&&(s=r.playbackInfo.program);const o=r.playbackInfo.volume;this.generateTrack(r),this._handler.addTimeSignature(0,n.timeSignatureNumerator,n.timeSignatureDenominator),this._handler.addTempo(0,t);let h=Vi.toChannelShort(o);this._handler.addControlChange(0,0,r.playbackInfo.primaryChannel,Oe.VolumeCoarse,h),this._handler.addControlChange(0,0,r.playbackInfo.secondaryChannel,Oe.VolumeCoarse,h)}generateSingleBeat(e){this.prepareSingleBeat(e),this.generateBeat(e,-e.playbackStart,e.voice.bar)}generateSingleNote(e){this.prepareSingleBeat(e.beat),this.generateNote(e,0,e.beat.playbackDuration,new Int32Array(e.beat.voice.bar.staff.tuning.length))}}Vi.DefaultDurationDead=30,Vi.DefaultDurationPalmMute=80,Vi.PitchBendRangeInSemitones=16,Vi.PitchValuePerSemitone=Kt.DefaultPitchWheel/Vi.PitchBendRangeInSemitones,Vi.MinBreakpointsPerSemitone=6,Vi.MillisecondsPerBreakpoint=150;class Hi{constructor(){this.startTick=0,this.endTick=0}}class Wi{constructor(e,t){this.width=0,this.height=0,this.x=e,this.y=t}get scale(){return this.renderer.scale}doLayout(){}paint(e,t,s){}}class zi extends Wi{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Ui extends zi{constructor(e,t,s,i){super(e,t),this.glyphScale=0,this.glyphScale=s,this.symbol=i}paint(e,t,s){s.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale*this.scale,this.symbol,!1)}}class Xi extends Ui{constructor(e,t,s,i){super(e,t,i?Xi.GraceScale:1,Xi.getSymbol(s)),this._isGrace=i,this._duration=s}paint(e,t,s){let i=this._isGrace?this.scale:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale*this.scale,this.symbol,!1)}doLayout(){let e=(this._isGrace?Xi.GraceScale:1)*this.scale;switch(this._duration){case u.QuadrupleWhole:this.width=14*e;break;case u.DoubleWhole:case u.Whole:this.width=14*(this._isGrace?Xi.GraceScale:1)*this.scale;break;default:this.width=Xi.QuarterNoteHeadWidth*(this._isGrace?Xi.GraceScale:1)*this.scale}this.height=Xi.NoteHeadHeight*e}static getSymbol(e){switch(e){case u.QuadrupleWhole:return N.NoteheadDoubleWholeSquare;case u.DoubleWhole:return N.NoteheadDoubleWhole;case u.Whole:return N.NoteheadWhole;case u.Half:return N.NoteheadHalf;default:return N.NoteheadBlack}}}Xi.GraceScale=.75,Xi.NoteHeadHeight=8,Xi.QuarterNoteHeadWidth=9;class Yi extends Ui{constructor(e,t,s,i,a){super(e,t,a?Xi.GraceScale:1,Yi.getSymbol(s,i,a))}doLayout(){this.width=0}static getSymbol(e,t,s){if(s&&(e=u.Eighth),t===Ce.Up)switch(e){case u.Eighth:return N.FlagEighthUp;case u.Sixteenth:return N.FlagSixteenthUp;case u.ThirtySecond:return N.FlagThirtySecondUp;case u.SixtyFourth:return N.FlagSixtyFourthUp;case u.OneHundredTwentyEighth:return N.FlagOneHundredTwentyEighthUp;case u.TwoHundredFiftySixth:return N.FlagTwoHundredFiftySixthUp;default:return N.FlagEighthUp}switch(e){case u.Eighth:return N.FlagEighthDown;case u.Sixteenth:return N.FlagSixteenthDown;case u.ThirtySecond:return N.FlagThirtySecondDown;case u.SixtyFourth:return N.FlagSixtyFourthDown;case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:return N.FlagOneHundredTwentyEighthDown;default:return N.FlagEighthDown}}}Yi.FlagWidth=11;class qi extends Wi{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)}registerLayoutingInfo(e){let t=this.preNotes.computedWidth+this.onNotes.centerX;this.beat.graceGroup&&!this.beat.graceGroup.isComplete&&(t+=qi.GraceBeatPadding*this.renderer.scale);let s=this.onNotes.computedWidth-this.onNotes.centerX;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);(i&&i.hasFlag||this.beat.graceType!==g.None)&&(s+=Yi.FlagWidth*this.scale*(this.beat.graceType!==g.None?Xi.GraceScale:1));for(const e of this.ties)s+=e.width;this.beat.graceType!==g.None&&(s+=qi.GraceBeatPadding*this.renderer.scale),e.addBeatSpring(this.beat,t,s),e.setPreBeatSize(this.beat,this.preNotes.computedWidth),e.setOnBeatSize(this.beat,this.onNotes.computedWidth),e.setBeatCenterX(this.beat,this.onNotes.centerX)}applyLayoutingInfo(e){let t=e.getBeatCenterX(this.beat)-this.onNotes.centerX;this.beat.graceGroup&&!this.beat.graceGroup.isComplete&&(t+=qi.GraceBeatPadding*this.renderer.scale),this.preNotes.x=t,this.preNotes.width=e.getPreBeatSize(this.beat),this.onNotes.width=e.getOnBeatSize(this.beat),this.onNotes.x=this.preNotes.x+this.preNotes.width,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>=u.Eighth&&(this.minWidth+=20*this.scale);else switch(this.beat.duration){case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:this.minWidth+=10*this.scale}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(qi.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 Bi;a.beat=this.beat,a.visualBounds=new rt,a.visualBounds.x=t+this.x+this.onNotes.x,a.visualBounds.y=e.visualBounds.y,a.visualBounds.w=this.onNotes.width,a.visualBounds.h=e.visualBounds.h,a.realBounds=new rt,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,i&&(a.visualBounds.x=t+this.x,a.realBounds.x=a.visualBounds.x),e.addBeat(a),this.renderer.settings.core.includeNoteBounds&&this.onNotes.buildBoundingsLookup(a,t+this.x,s+this.y)}}qi.GraceBeatPadding=3;class Ji{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new Co}causeIssue(){return this.settings=null,!0}}class ji{constructor(e){this.activeBeats=e}}class Qi{constructor(e){this.bounds=null,this.beat=e}}class $i{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=Me.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=Me.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new Cs,this.activeBeatsChanged=new Cs,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new Cs,this.beatMouseMove=new Cs,this.beatMouseUp=new Cs,this.noteMouseDown=new Cs,this.noteMouseMove=new Cs,this.noteMouseUp=new Cs,this.scoreLoaded=new Cs,this.resize=new Cs,this.renderStarted=new Cs,this.renderFinished=new Cs,this.postRenderFinished=new Ps,this.error=new Cs,this.playerReady=new Ps,this.playerFinished=new Ps,this.soundFontLoaded=new Ps,this.midiLoad=new Cs,this.midiLoaded=new Cs,this.playerStateChanged=new Cs,this.playerPositionChanged=new Cs,this.midiEventsPlayed=new Cs,this.playbackRangeChanged=new Cs,this.settingsUpdated=new Ps,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),q.logLevel=this.settings.core.logLevel,this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&Po.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new Ni(this.settings),this.container.resize.on(Po.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));let s=new Ji;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;q.debug("rendering","Rendering completed in "+e+"ms"),this.onPostRenderFinished()})),this.renderer.preRender.on((e=>{this._startTime=Date.now()})),this.renderer.partialLayoutFinished.on(this.appendRenderResult.bind(this)),this.renderer.partialRenderFinished.on(this.updateRenderResult.bind(this)),this.renderer.renderFinished.on((e=>{this.appendRenderResult(e),this.appendRenderResult(null)})),this.renderer.error.on(this.onError.bind(this)),this.settings.player.enablePlayer&&this.setupPlayer(),this.setupClickHandling(),this.uiFacade.beginInvoke((()=>{this.uiFacade.initialRender()}))}destroy(){this._isDestroyed=!0,this.player&&this.player.destroy(),this.uiFacade.destroy(),this.renderer.destroy()}updateSettings(){const e=this.score;e&&j.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?(this.setupPlayer(),e&&this.player?.applyTranspositionPitches(Vi.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(e){if(e.length>0){let t=e[0].score;for(let i of e)if(i.score!==t)return void this.onError(new O(s.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(t,e)}}internalRenderTracks(e,t){if(j.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 Ji;e.oldWidth=this.renderer.width,e.newWidth=this.container.width,e.settings=this.settings,this.onResize(e),this.renderer.updateSettings(this.settings),this.renderer.width=this.container.width,this.renderer.resizeRender()}else q.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{q.debug("Rendering","AlphaTab container became visible, doing autosizing",null),this.triggerResize()}))}appendRenderResult(e){e?(this.canvasElement.width=e.totalWidth,this.canvasElement.height=e.totalHeight,this._cursorWrapper&&(this._cursorWrapper.width=e.totalWidth,this._cursorWrapper.height=e.totalHeight),(e.width>0||e.height>0)&&this.uiFacade.beginAppendRenderResults(e)):this.uiFacade.beginAppendRenderResults(e)}updateRenderResult(e){e&&e.renderResult&&this.uiFacade.beginUpdateRenderResults(e)}tex(e,t){try{let s=new tt;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:Me.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=Me.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.player||!this.score||!this.player.isReady)return;q.debug("AlphaTab","Generating Midi");let e=new At,t=new Ei(e),s=new Vi(this.score,this.settings,t);s.applyTranspositionPitches=!1,s.generate(),this._tickCache=s.tickLookup,this.onMidiLoad(e),this.player.loadMidiFile(e),this.player.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)}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 At,s=new Ei(t);new Vi(e.voice.bar.staff.track.score,this.settings,s).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;let t=new At,s=new Ei(t);new Vi(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=Me.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===Me.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,c=this._previousCursorCache,d=this._previousStateForCursor;if(!i&&a===l?.beat&&h===c&&d===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(e){let t=this.uiFacade.getScrollContainer(),s=Po.getLayoutEngineFactory(this.settings.display.layoutMode).vertical,i=this.settings.player.scrollMode;if(s){let s=e.realBounds.y+this.settings.player.scrollOffsetY;if(s!==this._lastScroll)switch(this._lastScroll=s,i){case We.Continuous:let i=this.uiFacade.getOffset(t,this.container);this.uiFacade.scrollToY(t,i.y+s,this.settings.player.scrollSpeed);break;case We.OffScreen:let a=t.scrollTop+this.uiFacade.getOffset(null,t).h;if(e.visualBounds.y+e.visualBounds.h>=a||e.visualBounds.y<t.scrollTop){let s=e.realBounds.y+this.settings.player.scrollOffsetY;this.uiFacade.scrollToY(t,s,this.settings.player.scrollSpeed)}}}else{let s=e.visualBounds.x;if(s!==this._lastScroll)switch(this._lastScroll=s,i){case We.Continuous:let s=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,s,this.settings.player.scrollSpeed);break;case We.OffScreen:let i=t.scrollLeft+this.uiFacade.getOffset(null,t).w;if(e.visualBounds.x+e.visualBounds.w>=i||e.visualBounds.x<t.scrollLeft){let s=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,s,this.settings.player.scrollSpeed)}}}}internalCursorUpdateBeat(e,t,s,i,a,r,n,o){const h=this._barCursor,l=this._beatCursor;let c=n.barBounds.masterBarBounds,d=c.visualBounds;this._currentBarBounds=c,h&&h.setBounds(d.x,d.y,d.w,d.h),l&&(this.settings.player.enableAnimatedBeatCursor&&l.stopAnimation(),l.setBounds(n.visualBounds.x,d.y,1,d.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let u=!1;if(this._playerState===Me.Playing&&!i){if(this.settings.player.enableElementHighlighting)for(let t of a){let s=qi.getGroupId(t.beat);this.uiFacade.highlightElements(s,e.voice.bar.index)}if(this.settings.player.enableAnimatedBeatCursor){let e=c.visualBounds.x+c.visualBounds.w;if(t){let s=r.findBeat(t);s&&s.barBounds.masterBarBounds.staveGroupBounds===c.staveGroupBounds&&(e=s.visualBounds.x)}this.uiFacade.beginInvoke((()=>{l&&l.transitionToX(s/this.playbackSpeed,e)}))}o=!i,u=!0}o&&!this._beatMouseDown&&this.settings.player.scrollMode!==We.Off&&this.internalScrollToCursor(c),u&&(this.onPlayedBeatChanged(e),this.onActiveBeatsChanged(new ji(a.map((e=>e.beat)))))}onPlayedBeatChanged(e){this._isDestroyed||(this.playedBeatChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playedBeatChanged",e))}onActiveBeatsChanged(e){this._isDestroyed||(this.activeBeatsChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"activeBeatsChanged",e))}onBeatMouseDown(e,t){this._isDestroyed||(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&(this._selectionStart=new Qi(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 Qi(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===Me.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 Hi;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 Qi(t.beat),i=new Qi(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.staveGroupBounds!==t.bounds.barBounds.masterBarBounds.staveGroupBounds){let a=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x,o=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x+e.bounds.barBounds.masterBarBounds.staveGroupBounds.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.staveGroupBounds.index+1,c=t.bounds.barBounds.masterBarBounds.staveGroupBounds.index;for(let e=l;e<c;e++){let t=s.staveGroups[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),i.appendChild(r)}let d=this.uiFacade.createSelectionElement();d.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(d)}else{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||(q.error("API","An unexpected error occurred",e),this.error.trigger(e),this.uiFacade.triggerEvent(this.container,"error",e))}onPlayerReady(){this._isDestroyed||(this.playerReady.trigger(),this.uiFacade.triggerEvent(this.container,"playerReady",null))}onPlayerFinished(){this._isDestroyed||(this.playerFinished.trigger(),this.uiFacade.triggerEvent(this.container,"playerFinished",null))}onSoundFontLoaded(){this._isDestroyed||(this.soundFontLoaded.trigger(),this.uiFacade.triggerEvent(this.container,"soundFontLoaded",null))}onMidiLoad(e){this._isDestroyed||(this.midiLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"midiLoad",e))}onMidiLoaded(e){this._isDestroyed||(this.midiLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"midiFileLoaded",e))}onPlayerStateChanged(e){this._isDestroyed||(this.playerStateChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerStateChanged",e))}onPlayerPositionChanged(e){this._isDestroyed||null!==this.score&&this.tracks.length>0&&(this.playerPositionChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerPositionChanged",e))}onMidiEventsPlayed(e){this._isDestroyed||(this.midiEventsPlayed.trigger(e),this.uiFacade.triggerEvent(this.container,"midiEventsPlayed",e))}onPlaybackRangeChanged(e){this._isDestroyed||(this.playbackRangeChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playbackRangeChanged",e))}onSettingsUpdated(){this._isDestroyed||(this.settingsUpdated.trigger(),this.uiFacade.triggerEvent(this.container,"settingsUpdated",null))}}class Ki extends O{constructor(e,t){super(s.General,e),this.xhr=t,Object.setPrototypeOf(this,Ki.prototype)}}class Zi{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=Zi.loadScoreFromBytes(s,i);t(r)}catch(e){s(e)}else 0===a.status?s(new Ki("You are offline!!\n Please Check Your Network.",a)):404===a.status?s(new Ki("Requested URL not found.",a)):500===a.status?s(new Ki("Internel Server Error.",a)):"parsererror"===a.statusText?s(new Ki("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?s(new Ki("Request Time out.",a)):s(new Ki("Unknow Error: "+a.responseText,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Ks);let s=Po.buildImporters();q.debug("ScoreLoader",`Loading score from ${e.length} bytes using ${s.length} importers`);let i=null,a=Te.fromBuffer(e);for(let e of s){a.reset();try{q.debug("ScoreLoader","Importing using importer "+e.name),e.init(a,t),i=e.readScore(),q.debug("ScoreLoader","Score imported using "+e.name);break}catch(t){if(!(t instanceof G))throw q.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;q.debug("ScoreLoader",e.name+" does not support the file")}}if(i)return i;throw new G("No compatible importer found for file")}}class ea{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 ta{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.scrollTop=e}get scrollTop(){return this.element.scrollLeft}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 rt,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new ea(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new ea(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new ea(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&ta.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,ta.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=""}}ta.resizeObserver=new X((()=>new ResizeObserver((e=>{for(const t of e){let e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class sa{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new Cs,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(Po.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0,t=window.setInterval((()=>{q.warning("Rendering",`Could not load font '${this._families[0]}' within ${5*(e+1)} seconds`,null),this._families.length>1?(this._families.shift(),e=0):e++}),5e3);q.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);let s=e=>{this._families.length>1?(q.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(q.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},i=e=>{q.debug("Font",`[${e}] Font API signaled available`),this.isFontLoaded=!0,window.clearInterval(t),this.fontLoaded.trigger(this._families[0])},a=async()=>{for(const e of this._families)if(await this.isFontAvailable(e,!1))return void i(e);try{await document.fonts.load(`1em ${this._families[0]}`)}catch(e){s(e)}return q.debug("Font",`[${this._families[0]}] Font API signaled loaded`),await this.isFontAvailable(this._families[0],!0)?i(this._families[0]):s("Font not available"),!0};document.fonts.ready.then((()=>{a()}))}isFontAvailable(e,t){return new Promise((s=>{const i="1em "+e;if(document.fonts.check(i))s(!0);else if(t){q.debug("Font",`Font ${e} not available, creating test element to trigger load`);const t=document.createElement("div");t.style.font=i,t.style.opacity="0",t.style.position="absolute",t.style.top="0",t.style.left="0",t.innerText=`Trigger ${e} load`,document.body.appendChild(t),setTimeout((()=>{document.body.removeChild(t),document.fonts.check(i)?s(!0):s(!1)}),200)}else s(!1)}))}}class ia{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 aa{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new Ps,this.samplesPlayed=new Cs,this.sampleRequest=new Ps}get sampleRate(){return this._context?this._context.sampleRate:aa.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(q.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{q.debug("WebAudio",`Audio Context resume success: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}`),e&&e()}),(e=>{q.warning("WebAudio",`Audio Context resume failed: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}, reason=${e}`)})))}patchIosSampleRate(){let e=navigator.userAgent;if(-1!==e.indexOf("iPhone")||-1!==e.indexOf("iPad")){let e=this.createAudioContext(),t=e.createBuffer(1,1,aa.PreferredSampleRate),s=e.createBufferSource();s.buffer=t,s.connect(e.destination),s.start(0),s.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in Po.globalThis)return new AudioContext;if("webkitAudioContext"in Po.globalThis)return new webkitAudioContext;throw new O(s.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,aa.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()}}aa.BufferSize=4096,aa.PreferredSampleRate=44100;class ra extends aa{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/aa.BufferSize),this._circularBuffer=new ia(aa.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*aa.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*aa.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;for(let e=0;e<t.length;e++)t[e]=a[n++],s[e]=a[n++];this.onSamplesPlayed(r/Kt.AudioChannels),this.requestBuffers()}}class na{constructor(e,t){this.loaded=e,this.total=t}}class oa{get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return q.logLevel}set logLevel(e){q.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Kt.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Kt.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Kt.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=Ss.clamp(e,Kt.MinPlaybackSpeed,Kt.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=Me.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 Ps,this.readyForPlayback=new Ps,this.finished=new Ps,this.soundFontLoaded=new Ps,this.soundFontLoadFailed=new Cs,this.midiLoaded=new Cs,this.midiLoadFailed=new Cs,this.stateChanged=new Cs,this.positionChanged=new Cs,this.midiEventsPlayed=new Cs,this.playbackRangeChanged=new Cs,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Me.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=Po.createWebWorker(t)}catch(e){q.error("AlphaSynth","Failed to create WebWorker: "+e)}this._synth.addEventListener("message",this.handleWorkerMessage.bind(this),!1),this._synth.postMessage({cmd:"alphaSynth.initialize",sampleRate:this._output.sampleRate,logLevel:t.core.logLevel,bufferTimeInMilliseconds:t.player.bufferTimeInMilliseconds}),this.masterVolume=1,this.playbackSpeed=1,this.metronomeVolume=0}destroy(){this._synth.postMessage({cmd:"alphaSynth.destroy"})}play(){return this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.play"}),!0}pause(){this._synth.postMessage({cmd:"alphaSynth.pause"})}playPause(){this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.playPause"})}stop(){this._synth.postMessage({cmd:"alphaSynth.stop"})}playOneTimeMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.playOneTimeMidiFile",midi:mi.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,s){q.debug("AlphaSynth",`Start loading Soundfont from url ${e}`);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=>{q.error("AlphaSynth","Loading failed: "+e.message),this.soundFontLoadFailed.trigger(new Ki(e.message,i))},i.onprogress=e=>{q.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),s(new na(e.loaded,e.total))},i.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:mi.midiFileToJsObject(e)})}applyTranspositionPitches(e){this._synth.postMessage({cmd:"alphaSynth.applyTranspositionPitches",transpositionPitches:JSON.stringify(Array.from(e.entries()))})}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,Kt.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 is(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new Es(t.events.map(mi.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new ss(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new Fs(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 is(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 ha{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new Cs,this.partialRenderFinished=new Cs,this.partialLayoutFinished=new Cs,this.renderFinished=new Cs,this.postRenderFinished=new Ps,this.error=new Cs,this._api=e;try{this._worker=Po.createWebWorker(t)}catch(e){return void q.error("Rendering",`Failed to create WebWorker: ${e}`)}this._worker.postMessage({cmd:"alphaTab.initialize",settings:this.serializeSettingsForWorker(t)}),this._worker.addEventListener("message",this.handleWorkerMessage.bind(this))}destroy(){this._worker.terminate()}updateSettings(e){this._worker.postMessage({cmd:"alphaTab.updateSettings",settings:this.serializeSettingsForWorker(e)})}serializeSettingsForWorker(e){const t=mi.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=xi.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:mi.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:s,trackIndexes:t,fontSizes:Si.FontSizeLookupTables})}}class la{constructor(e,t,s,i){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=s,this.selectionWrapper=i}}!function(e){e[e.Browser=0]="Browser",e[e.NodeJs=1]="NodeJs",e[e.BrowserModule=2]="BrowserModule"}(Ue||(Ue={}));class ca{static init(){var e;ca._isRegistered||(ca._isRegistered=!0,registerProcessor("alphatab",((e=class extends AudioWorkletProcessor{constructor(t){super(t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,q.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new ia(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){let t=e.data;switch(t.cmd){case yi.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case yi.CmdOutputResetSamples:this._circularBuffer.clear()}}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;for(let e=0;e<i.length;e++)i[e]=n[h++],a[e]=n[h++];return this.port.postMessage({cmd:yi.CmdOutputSamplesPlayed,samples:o/Kt.AudioChannels}),this.requestBuffers(),!0}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:yi.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}ca._isRegistered=!1;class da extends aa{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;Po.createAudioWorklet(e,this._settings).then((()=>{this._worklet=new AudioWorkletNode(e,"alphatab",{numberOfOutputs:1,outputChannelCount:[2],processorOptions:{bufferTimeInMilliseconds:this._bufferTimeInMilliseconds}}),this._worklet.port.onmessage=this.handleMessage.bind(this),this._source.connect(this._worklet),this._source.start(0),this._worklet.connect(e.destination)}),(e=>{q.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){let t=e.data;switch(t.cmd){case yi.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case yi.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){this._worklet?.port.postMessage({cmd:yi.CmdOutputAddSamples,samples:e})}resetSamples(){this._worklet?.port.postMessage({cmd:yi.CmdOutputResetSamples})}}class ua extends ta{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"}(Xe||(Xe={}));class pa{get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(Po.bravuraFontChecker.checkForFontAvailability(),!Po.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(q.debug("Font","All fonts loaded: "+this._fontCheckers.size),!0)}onFontLoaded(e){Si.generateFontLookup(e),this.areAllFontsLoaded()&&this.canRenderChanged.trigger()}constructor(e){if(this._fontCheckers=new Map,this._contents=null,this._file=null,this._totalResultCount=0,this._initialTrackIndexes=null,this._barToElementLookup=new Map,this._resultIdToElementLookup=new Map,this.rootContainerBecameVisible=new Ps,this.canRenderChanged=new Ps,this._highlightedElements=[],this._scrollContainer=null,Po.webPlatform!==Ue.Browser&&Po.webPlatform!==Ue.BrowserModule)throw new O(s.General,"Usage of AlphaTabApi is only possible in browser environments. For usage in node use the Low Level APIs");e.classList.add("alphaTab"),this.rootContainer=new ta(e),this.areWorkersSupported="Worker"in window,Po.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(e)}onElementVisibilityChanged(e){for(const t of e){const e=t.target;if(e===this.rootContainer.element)t.isIntersecting&&(this.rootContainerBecameVisible.trigger(),this._intersectionObserver.unobserve(this.rootContainer.element));else if("layoutResultId"in e&&this._api.settings.core.enableLazyLoading){const s=e;t.isIntersecting?s.renderedResultId!==s.layoutResultId?this._resultIdToElementLookup.has(s.layoutResultId)?s.resultState!==Xe.RenderRequested&&(s.resultState=Xe.RenderRequested,this._api.renderer.renderResult(s.layoutResultId)):e.replaceChildren():s.resultState===Xe.Detached&&(e.replaceChildren(...s.renderedResult),s.resultState=Xe.RenderDone):s.resultState===Xe.RenderDone&&(s.resultState=Xe.Detached,s.replaceChildren())}}}createWorkerRenderer(){return new ha(this._api,this._api.settings)}initialize(e,t){let s;this._api=e,s=t instanceof Ks?t:mi.jsObjectToSettings(t);let i=this.getDataAttributes();$s.fromJson(s,i),s.notation.notationMode===T.SongBook&&s.setSongBookModeSettings(),e.settings=s,this.setupFontCheckers(s),this._initialTrackIndexes=this.parseTracks(s.core.tracks),this._contents="";let a=e.container;s.core.tex&&(this._contents=a.element.innerHTML,a.element.innerHTML=""),this.createStyleElement(s),this._file=s.core.file}setupFontCheckers(e){this.registerFontChecker(e.display.resources.copyrightFont),this.registerFontChecker(e.display.resources.effectFont),this.registerFontChecker(e.display.resources.fingeringFont),this.registerFontChecker(e.display.resources.graceFont),this.registerFontChecker(e.display.resources.markerFont),this.registerFontChecker(e.display.resources.tablatureFont),this.registerFontChecker(e.display.resources.titleFont),this.registerFontChecker(e.display.resources.wordsFont),this.registerFontChecker(e.display.resources.barNumberFont),this.registerFontChecker(e.display.resources.fretboardNumberFont),this.registerFontChecker(e.display.resources.subTitleFont)}registerFontChecker(e){if(!this._fontCheckers.has(e.families.join(", "))){let t=new sa(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 ta(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 ue)return t(e),!0;if(e instanceof ArrayBuffer){let s=new Uint8Array(e);return t(Zi.loadScoreFromBytes(s,this._api.settings)),!0}return e instanceof Uint8Array?(t(Zi.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(Zi.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&&Zi.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;Po.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=Xe.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=Xe.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 e=null,t="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window&&this._api.settings.player.outputMode===ze.WebAudioAudioWorklets?(q.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),e=new oa(new da(this._api.settings),this._api.settings)):t&&(q.debug("Player","Will use webworkers for synthesizing and web audio api with ScriptProcessor for playback"),e=new oa(new ra,this._api.settings)),e?e.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):q.error("Player","Player requires webworkers and web audio api, browser unsupported",null),e}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const s=this._barToElementLookup.get(t);if(s){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 la(new ta(t),i,a,new ta(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 rt;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 ta(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new ua(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 ga extends $i{constructor(e,t){super(new pa(e),t),this.soundFontLoad=new Cs}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.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,c=a.offsetWidth+50,d=window.innerHeight,u=(h/2|0)-(c/2|0)+n,p=(l/2|0)-(d/2|0)+o;i.resizeTo(c,d),i.moveTo(u,p),i.focus();let g=mi.jsObjectToSettings(mi.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,$s.fromJson(g,s);let f=new ga(a,g);i.onunload=()=>{f.destroy()},f.renderer.postRenderFinished.on((()=>{i.print()})),f.renderTracks(this.tracks)}downloadMidi(e=Fe.SingleTrackMultiChannel){if(!this.score)return;let t=new At;t.format=e;let s=new Ei(t,!0);new Vi(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 fa{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 q.error("Api","Method '"+t+"' does not exist on jQuery.alphaTab"),null}init(e,t,s){if(!t){t=new ga(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 ma{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.color=new fe(255,255,255,255),this.lineWidth=1,this.font=new As("Arial",10,Ge.Plain),this.textAlign=P.Left,this.textBaseline=C.Top}destroy(){}beginRender(e,t){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=C.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="${0|e}" y="${0|t}" width="${s}" height="${i}" fill="${this.color.rgba}" />\n`)}strokeRect(e,t,s,i){this.buffer+=`<rect x="${0|e}" y="${0|t}" width="${s}" height="${i}" stroke="${this.color.rgba}"`,1!==this.lineWidth&&(this.buffer+=` stroke-width="${this.lineWidth}"`),this.buffer+=' fill="transparent" />\n'}beginPath(){}closePath(){this._currentPath+=" z"}moveTo(e,t){this._currentPath+=` M${e},${t}`}lineTo(e,t){this._currentPathIsEmpty=!1,this._currentPath+=` L${e},${t}`}quadraticCurveTo(e,t,s,i){this._currentPathIsEmpty=!1,this._currentPath+=` Q${e},${t},${s},${i}`}bezierCurveTo(e,t,s,i,a,r){this._currentPathIsEmpty=!1,this._currentPath+=` C${e},${t},${s},${i},${a},${r}`}fillCircle(e,t,s){this._currentPathIsEmpty=!1,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,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&&(e+=` stroke-width="${this.lineWidth}"`),e+=' style="fill: none" />',this.buffer+=e}this._currentPath="",this._currentPathIsEmpty=!0}fillText(e,t,s){if(""===e)return;let i=`<text x="${0|t}" y="${0|s}" style="stroke: none; font:${this.font.toCssString(this.settings.display.scale)}" ${this.getSvgBaseLine()}`;"#000000"!==this.color.rgba&&(i+=` fill="${this.color.rgba}"`),this.textAlign!==P.Left&&(i+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),i+=`>${ma.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 P.Left:return"start";case P.Center:return"middle";case P.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case C.Top:return'dominant-baseline="hanging"';case C.Bottom:return'dominant-baseline="bottom"';default:return""}}measureText(e){return e?Si.measureString(e,this.font.families,this.font.size,this.font.style,this.font.weight):0}onRenderFinished(){return null}beginRotate(e,t,s){this.buffer+='<g transform="translate('+e+" ,"+t+") rotate( "+s+')">'}endRotate(){this.buffer+="</g>"}}class ya extends ma{constructor(){super()}fillMusicFontSymbol(e,t,s,i,a){i!==N.None&&this.fillMusicFontSymbolText(e,t,s,`&#${i};`,a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(let e of i)e!==N.None&&(r+=`&#${e};`);this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){this.buffer+=`<g transform="translate(${e} ${t})" class="at" ><text`,this.buffer+=1!==s?` style="font-size: ${100*s}%; stroke:none"`:' style="stroke:none"',"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),a&&(this.buffer+=' text-anchor="'+this.getSvgTextAlignment(P.Center)+'"'),this.buffer+=`>${i}</text></g>`}}class ba{constructor(){this.isInAccolade=!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"}(Ye||(Ye={}));class Sa extends Wi{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 _a extends Sa{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 wa extends Sa{constructor(e,t,s){super(e,t),this.voice=s,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){const t=this.renderer.scale;let s=this.renderer.layoutingInfo.spaceToForce(e/t);this.scaleToForce(s)}scaleToForce(e){const t=this.renderer.scale;this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e)*t;let s=this.renderer.layoutingInfo.buildOnTimePositions(e),i=this.beatGlyphs;for(let e=0,a=i.length;e<a;e++){let r=i[e];if(r.beat.graceType===g.None)r.x=s.get(r.beat.absoluteDisplayStart)*t-r.onTimeX;else{const a=r.beat.graceGroup.beats[0].absoluteDisplayStart,n=r.beat.graceGroup.id;if(r.beat.graceGroup.isComplete&&s.has(a)){r.x=s.get(a)*t-r.onTimeX;let e=this.renderer.layoutingInfo.allGraceRods.get(n);const i=r.beat.graceGroup.beats[r.beat.graceGroup.beats.length-1].nextBeat,o=i?this.renderer.layoutingInfo.getPreBeatSize(i)+qi.GraceBeatPadding*this.renderer.scale:0;r.x-=o,r.x-=e[r.beat.graceIndex].postSpringWidth,r.x+=e[r.beat.graceIndex].graceBeatWidth;const h=e[r.beat.graceGroup.beats.length-1];r.x-=h.graceBeatWidth}else{let t=this.renderer.layoutingInfo.incompleteGraceRods.get(n);const s=t[r.beat.graceIndex].postSpringWidth-t[r.beat.graceIndex].preSpringWidth;e>0?0===r.beat.graceIndex?r.x=i[e-1].x+i[e-1].width:r.x=i[e-1].x+t[r.beat.graceIndex-1].postSpringWidth-t[r.beat.graceIndex-1].preSpringWidth-s:r.x=-s}}if(e>0){let t=r.x-i[e-1].x;i[e-1].scaleToWidth(t)}if(e===a-1){let e=this.width-i[i.length-1].x;r.scaleToWidth(e)}}}registerLayoutingInfo(e){e.updateVoiceSize(this.width);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)}}wa.KeySizeBeat="Beat",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"}(qe||(qe={}));class Ba{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class Ta{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:$.getArticulationByValue(t)?.staffLine??0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case y.ForceDoubleFlat:t+=2;break;case y.ForceDoubleSharp:t-=2;break;case y.ForceFlat:t+=1;break;case y.ForceSharp:t-=1}return t}applyAccidental(e){const t=Ta.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=Ta.getNoteValue(t);if(e.staff.isPercussion)s=Ta.getPercussionLine(e,i);else{const a=t?t.accidentalMode:y.Default;s=Ta.calculateNoteLine(e,i,a)}return s}getAccidental(e,t,s,i,a=null){let r=qe.None,n=0;if(this._bar.staff.isPercussion)n=Ta.getPercussionLine(this._bar,e);else{const s=a?a.accidentalMode:y.Default;n=Ta.calculateNoteLine(this._bar,e,s);let i=this._bar.masterBar.keySignature+7,o=e%12,h=i<7?qe.Flat:qe.Sharp,l=Ta.KeySignatureLookup[i][o],c=Ta.AccidentalNotes[o];if(t)switch(r=c?h:qe.Natural,r){case qe.Natural:r=qe.NaturalQuarterNoteUp;break;case qe.Sharp:r=qe.SharpQuarterNoteUp;break;case qe.Flat:r=qe.FlatQuarterNoteUp}else{switch(s){case y.ForceSharp:r=qe.Sharp;break;case y.ForceDoubleSharp:r=qe.DoubleSharp;break;case y.ForceFlat:r=qe.Flat;break;case y.ForceDoubleFlat:r=qe.DoubleFlat;break;default:c?r=h:l&&(r=qe.Natural)}let e=!1;if(a&&a.isTieDestination&&0===a.beat.index){const t=this._barRenderer.previousRenderer;if(t){t.accidentalHelper.getNoteLine(a.tieOrigin)===n&&(e=!0)}}e?r=qe.None:r!==qe.None?(this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===r&&(r=qe.None):l&&r===h&&(r=qe.None),r!==qe.None&&this._registeredAccidentals.set(n,r)):this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===qe.Natural?r=qe.None:(r=qe.Natural,this._registeredAccidentals.set(n,r)):this._registeredAccidentals.delete(n)}}return a?(this._appliedScoreLines.set(a.id,n),this._notesByValue.set(e,a)):this._appliedScoreLinesByValue.set(e,n),(-1e3===this.minLine||this.minLine<n)&&(this.minLine=n,this.minLineBeat=s),(-1e3===this.maxLine||this.maxLine>n)&&(this.maxLine=n,this.maxLineBeat=s),i||this.registerLine(s,n),r}registerLine(e,t){let s;this._beatLines.has(e.id)?s=this._beatLines.get(e.id):(s=new Ba,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,s){let i=t,a=e.masterBar.keySignature,r=e.clef,n=i%12,o=(i/12|0)-1,h=Ta.OctaveSteps[r];return h-=o*Ta.StepsPerOctave,h-=(j.keySignatureIsSharp(a)||j.keySignatureIsNatural(a)?Ta.SharpNoteSteps:Ta.FlatNoteSteps)[n],h}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}}Ta.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]],Ta.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],Ta.StepsPerOctave=7,Ta.OctaveSteps=[38,32,30,26,38],Ta.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],Ta.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class ka{constructor(){this.staffId="",this.up=0,this.down=0}}class va{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 xa{get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}get hasLine(){return 1===this.beats.length&&this.beats[0].duration>u.Whole}get hasFlag(){return 1===this.beats.length&&!this.beats[0].isRest&&(this.beats[0].duration>u.Quarter||this.beats[0].graceType!==g.None)}constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=u.QuadrupleWhole,this.fingeringCount=0,this.hasTuplet=!1,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=Ce.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}getBeatLineX(e){return this.hasBeatLineX(e)?this.direction===Ce.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 ka),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(Ce.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==g.None)&&(e=this.invert(Ce.Up)):e=Ce.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){let t=this._renderer.getNoteY(this.highestNoteInHelper,je.Center),s=this._renderer.getNoteY(this.lowestNoteInHelper,je.Center);if(null===e){const i=(t+s)/2;e=this.invert(this._renderer.middleYPosition<i?Ce.Up:Ce.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(Ce.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:return[2,2];case u.Whole:return[0,1];case u.Half:return[1,0];case u.Quarter:return[3,3];case u.Eighth:return[2,2];case u.Sixteenth:return[2,4];case u.ThirtySecond:return[4,4];case u.SixtyFourth:return[4,6];case u.OneHundredTwentyEighth:return[6,6];case u.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=xa.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===Ce.Down?Ce.Up:Ce.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 F.Auto:t=xa.canJoin(this.beats[this.beats.length-1],e);break;case F.ForceSplitToNext:t=!1;break;case F.ForceMergeWithNext:t=!0}if(t){if(null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.isRest)0===this.beats.length&&this.beats.push(e);else{this.isRestBeamHelper&&(this.beats=[]),this.beats.push(e),e.graceType!==g.None&&(this.isGrace=!0),e.hasTuplet&&(this.hasTuplet=!0);let t=0;for(let s=0;s<e.notes.length;s++){let i=e.notes[s];i.leftHandFinger===f.Unknown&&i.rightHandFinger===f.Unknown||t++}t>this.fingeringCount&&(this.fingeringCount=t),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.hasTuplet&&(this.hasTuplet=!0)}return t}checkNote(e){if(!e)return;let t,s;this.voice&&e.isPercussion?(t=-Ta.getPercussionLine(this.voice.bar,Ta.getNoteValue(e)),s=t):(t=Ta.getNoteValue(e),s=t,e.harmonicType!==m.None&&e.harmonicType!==m.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===g.BendGrace||t.graceType===g.BendGrace)return!1;if(e.graceType!==g.None&&t.graceType!==g.None)return!0;let s=e.voice.bar;if(s!==t.voice.bar)return!1;let i=e.playbackStart,a=t.playbackStart;if(!xa.canJoinDuration(e.duration)||!xa.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=W.QuarterTime;if(8===s.masterBar.timeSignatureDenominator)s.masterBar.timeSignatureNumerator%3==0&&(r+=W.QuarterTime/2|0);return((r+i)/r|0)===((r+a)/r|0)}static canJoinDuration(e){switch(e){case u.Whole:case u.Half:case u.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,s){return j.getIndex(e.duration)-2-s>0&&j.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 Na{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class Pa{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new Na(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 Ca{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 Pa(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=xa.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 Ea{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this._renderer=e,this.collisionHelper=new Ca}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!==g.None?n=i:(n=s,i=null),n&&n.checkBeat(o)||(n&&n.finish(),n=new xa(t.staff,e),n.checkBeat(o),o.graceType!==g.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 Fa extends zi{constructor(e,t,s){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=s}doLayout(){super.doLayout();const e=this.scale;let t=this.renderer.resources;this._textRow=1.5*t.effectFont.size*e,this._fretRow=1.5*t.effectFont.size*e,this._chord.firstFret>1?this._firstFretSpacing=Fa.FretSpacing*e:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+(Fa.Frets-1)*Fa.FretSpacing*e+2*Fa.Padding*e,this.width=this._firstFretSpacing+(this._chord.staff.tuning.length-1)*Fa.StringSpacing*e+2*Fa.Padding*e}paint(e,t,s){e+=this.x+Fa.Padding*this.scale+this._firstFretSpacing,t+=this.y;let i=this.width-2*Fa.Padding*this.scale+this.scale-this._firstFretSpacing,a=Fa.StringSpacing*this.scale,r=Fa.FretSpacing*this.scale,n=this.renderer.resources,o=Fa.CircleRadius*this.scale,h=s.textAlign,l=s.textBaseline;s.font=n.effectFont,s.textAlign=P.Center,s.textBaseline=C.Top,this._chord.showName&&s.fillText(this._chord.name,e+this.width/2,t+n.effectFont.size/2),t+=this._textRow,e+=a/2,s.font=n.fretboardNumberFont,s.textBaseline=C.Middle;for(let i=0;i<this._chord.staff.tuning.length;i++){let r=e+i*a,n=t+this._fretRow/2,o=this._chord.strings[this._chord.staff.tuning.length-i-1];o<0?s.fillMusicFontSymbol(r,n,this.scale,N.FretboardX,!0):0===o?s.fillMusicFontSymbol(r,n,this.scale,N.FretboardO,!0):(o-=this._chord.firstFret-1,s.fillText(o.toString(),r,n))}t+=this._fretRow;for(let i=0;i<this._chord.staff.tuning.length;i++){let n=e+i*a;s.fillRect(n,t,1,r*Fa.Frets+this.scale)}this._chord.firstFret>1&&(s.textAlign=P.Left,s.fillText(this._chord.firstFret.toString(),e-this._firstFretSpacing,t+r/2)),s.fillRect(e,t-this.scale,i,2*this.scale);for(let a=0;a<=Fa.Frets;a++){let n=t+a*r;s.fillRect(e,n,i,this.scale)}let c=new Map;for(let e of this._chord.barreFrets){let t=[-1,-1];c.set(e-this._chord.firstFret,t)}for(let i=0;i<this._chord.strings.length;i++){let n=this._chord.strings[i];if(n>0){if(n-=this._chord.firstFret,c.has(n)){let e=c.get(n);(-1===e[0]||i<e[0])&&(e[0]=i),(-1===e[1]||i>e[1])&&(e[1]=i)}let h=t+n*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-i-1)*a;s.fillCircle(l,h,o)}}for(const[i,n]of c){let h=t+i*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-n[1]-1)*a,c=e+(this._chord.strings.length-n[0]-1)*a;s.fillRect(l,h-o,c-l,2*o)}s.textAlign=h,s.textBaseline=l}}Fa.Padding=5,Fa.Frets=5,Fa.CircleRadius=2.5,Fa.StringSpacing=10,Fa.FretSpacing=12;class La extends Sa{constructor(e,t,s=P.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=s}doLayout(){let e=0;switch(this._align){case P.Left:e=0;break;case P.Center:e=(this.width-this._glyphWidth)/2;break;case P.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 Ma extends Sa{constructor(e,t,s=P.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=s}doLayout(){let e=0,t=0,s=2*Ma.Padding*this.scale;this._rows=[];let i=new La(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 La(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+s}paint(e,t,s){for(let i of this._rows)i.paint(e+this.x,t+this.y+Ma.Padding*this.scale,s)}}Ma.Padding=3;class Ia extends Ma{constructor(e,t){super(e,t)}addChord(e){if(e.strings.length>0){let t=new Fa(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}}class Da extends zi{constructor(e,t,s,i,a=P.Left){super(e,t),this._lines=s.split("\n"),this.font=i,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,s){let i=s.color;s.color=i,s.font=this.font;let a=s.textAlign;s.textAlign=this.textAlign;let r=t+this.y;for(let t of this._lines)s.fillText(t,e+this.x,r),r+=this.font.size;s.textAlign=a}}class Aa{get staveId(){return this._factory.staffId}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.trackIndex=0,this.staveTop=0,this.topSpacing=20,this.bottomSpacing=5,this.staveBottom=0,this.isFirstInAccolade=!1,this.isLastInAccolade=!1,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 isInAccolade(){return this._factory.isInAccolade}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.staveGroup.layout.registerBarRenderer(this.staveId,e)}addBar(e,t){let s;s=e?this._factory.create(this.staveGroup.layout.renderer,e):new Ya(this.staveGroup.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.staveGroup.layout.systemsLayoutMode==Je.FromModelWithWidths&&(s.width=i),this.barRenderers.push(s),e&&this.staveGroup.layout.registerBarRenderer(this.staveId,s)}revertLastBar(){let e=this.barRenderers[this.barRenderers.length-1];return this.barRenderers.splice(this.barRenderers.length-1,1),this.staveGroup.layout.unregisterBarRenderer(this.staveId,e),e}scaleToWidth(e){this._sharedLayoutData=new Map;let t=this.topOverflow,s=0;switch(this.staveGroup.layout.systemsLayoutMode){case Je.Automatic:let i=(e-this.staveGroup.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 Je.FromModelWithScale:e-=this.staveGroup.accoladeSpacing;const a=this.staveGroup.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 Je.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}finalizeStaff(){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 Ra{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 Oa{constructor(){this._timeSortedSprings=[],this._xMin=0,this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,this.version=0,this.preBeatSizes=new Map,this.onBeatSizes=new Map,this.onBeatCenterX=new Map,this.preBeatSize=0,this.postBeatSize=0,this.voiceSize=0,this.minStretchForce=0,this.totalSpringConstant=0,this.incompleteGraceRods=new Map,this.allGraceRods=new Map,this.springs=new Map,this.height=0}updateVoiceSize(e){e>this.voiceSize&&(this.voiceSize=e,this.version++)}setPreBeatSize(e,t){(!this.preBeatSizes.has(e.id)||this.preBeatSizes.get(e.id)<t)&&(this.preBeatSizes.set(e.id,t),this.version++)}getPreBeatSize(e){return this.preBeatSizes.has(e.id)?this.preBeatSizes.get(e.id):0}setOnBeatSize(e,t){(!this.onBeatSizes.has(e.id)||this.onBeatSizes.get(e.id)<t)&&(this.onBeatSizes.set(e.id,t),this.version++)}getOnBeatSize(e){return this.onBeatSizes.has(e.id)?this.onBeatSizes.get(e.id):0}getBeatCenterX(e){return this.onBeatCenterX.has(e.id)?this.onBeatCenterX.get(e.id):0}setBeatCenterX(e,t){(!this.onBeatCenterX.has(e.id)||this.onBeatCenterX.get(e.id)<t)&&(this.onBeatCenterX.set(e.id,t),this.version++)}updateMinStretchForce(e){this.minStretchForce<e&&(this.minStretchForce=e)}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 Ra,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!==g.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 Ra;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 s=0;if(this.incompleteGraceRods.has(e))for(const e of t)s+=e.preBeatWidth,e.graceBeatWidth=s,s+=e.postSpringWidth;else for(let e=t.length-1;e>=0;e--)t[e].graceBeatWidth=s,s-=t[e].preBeatWidth+t[e].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=W.toTicks(u.SixtyFourth)),0===e.smallestDuration&&(e.smallestDuration=t),e.smallestDuration/t*(1/((1+.85*Math.log2(t/Oa.MinDuration))*Oa.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(j.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}}Oa.MinDuration=30,Oa.MinDurationWidth=7;class Ga{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.renderers=[]}}class Va{constructor(e,t){this.staves=[],this.stavesRelevantForBoundsLookup=[],this.firstStaffInAccolade=null,this.lastStaffInAccolade=null,this.staveGroup=e,this.track=t}addStaff(e){this.staves.push(e),e.isRelevantForBoundsLookup&&this.stavesRelevantForBoundsLookup.push(e)}}class Ha{constructor(){this._allStaves=[],this._firstStaffInAccolade=null,this._lastStaffInAccolade=null,this._accoladeSpacingCalculated=!1,this.x=0,this.y=0,this.index=0,this.accoladeSpacing=0,this.isFull=!1,this.width=0,this.computedWidth=0,this.totalBarDisplayScale=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[]}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),this.calculateAccoladeSpacing(e),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.updateWidthFromLastBar(),t}addBars(e,t){if(0===e.length)return null;let s=new Ga;s.layoutingInfo=new Oa,s.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(s),this.calculateAccoladeSpacing(e);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 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(e){if(!this._accoladeSpacingCalculated&&0===this.index)if(this._accoladeSpacingCalculated=!0,this.layout.renderer.settings.notation.isNotationElementVisible(k.TrackNames)){let t=this.layout.renderer.canvas,s=this.layout.renderer.settings.display.resources.effectFont;t.font=s;for(let s of e)this.accoladeSpacing=Math.ceil(Math.max(this.accoladeSpacing,t.measureText(s.shortName)));this.accoladeSpacing*=this.layout.scale,this.accoladeSpacing+=2*Ha.AccoladeLabelSpacing*this.layout.scale,this.width+=this.accoladeSpacing,this.computedWidth+=this.accoladeSpacing}else this.accoladeSpacing=0}getStaveTrackGroup(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.getStaveTrackGroup(e);s||(s=new Va(this,e),this.staves.push(s)),t.staveTrackGroup=s,t.staveGroup=this,t.index=this._allStaves.length,this._allStaves.push(t),s.addStaff(t),t.isInAccolade&&(this._firstStaffInAccolade||(this._firstStaffInAccolade=t,t.isFirstInAccolade=!0),s.firstStaffInAccolade||(s.firstStaffInAccolade=t),this._lastStaffInAccolade||(this._lastStaffInAccolade=t,t.isLastInAccolade=!0),this._lastStaffInAccolade&&(this._lastStaffInAccolade.isLastInAccolade=!1),this._lastStaffInAccolade=t,this._lastStaffInAccolade.isLastInAccolade=!0,s.lastStaffInAccolade=t)}get height(){return this._allStaves[this._allStaves.length-1].y+this._allStaves[this._allStaves.length-1].height}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){this.paintPartial(e+this.x,t+this.y,s,0,this.masterBarsRenderers.length)}paintPartial(e,t,s,i,a){for(let r=0,n=this._allStaves.length;r<n;r++)this._allStaves[r].paint(e,t,s,i,a);let r=this.layout.renderer.settings.display.resources;if(this.staves.length>0&&0===i){if(s.color=r.barSeparatorColor,this._firstStaffInAccolade&&this._lastStaffInAccolade){let i=t+this._firstStaffInAccolade.y+this._firstStaffInAccolade.staveTop+this._firstStaffInAccolade.topSpacing+this._firstStaffInAccolade.topOverflow,a=t+this._lastStaffInAccolade.y+this._lastStaffInAccolade.topSpacing+this._lastStaffInAccolade.topOverflow+this._lastStaffInAccolade.staveBottom,r=e+this._firstStaffInAccolade.x;s.beginPath(),s.moveTo(r,i),s.lineTo(r,a),s.stroke()}s.font=r.effectFont;for(let i=0,a=this.staves.length;i<a;i++){let a=this.staves[i];if(a.firstStaffInAccolade&&a.lastStaffInAccolade){let i=t+a.firstStaffInAccolade.y+a.firstStaffInAccolade.staveTop+a.firstStaffInAccolade.topSpacing+a.firstStaffInAccolade.topOverflow,r=t+a.lastStaffInAccolade.y+a.lastStaffInAccolade.topSpacing+a.lastStaffInAccolade.topOverflow+a.lastStaffInAccolade.staveBottom,n=e+a.firstStaffInAccolade.x,o=3*this.layout.renderer.settings.display.scale,h=o,l=i-4*o,c=r+4*o;0===this.index&&this.layout.renderer.settings.notation.isNotationElementVisible(k.TrackNames)&&s.fillText(a.track.shortName,e+Ha.AccoladeLabelSpacing*this.layout.scale,i),s.fillRect(n-h-o,l,o,c-l);let d=n-h-o,u=n+2*o;s.beginPath(),s.moveTo(d,l),s.bezierCurveTo(d,l,d,l,u,l-o),s.bezierCurveTo(n,l+o,d,l+o,d,l+o),s.closePath(),s.fill(),s.beginPath(),s.moveTo(d,c),s.bezierCurveTo(d,c,n,c,u,c+o),s.bezierCurveTo(n,c-o,d,c-o,d,c-o),s.closePath(),s.fill()}}}}finalizeGroup(){let e=0;for(let t of this._allStaves)t.x=this.accoladeSpacing,t.y=e,t.finalizeStaff(),e+=t.height}buildBoundingsLookup(e,t){if(this.layout.renderer.boundsLookup.isFinished)return;if(!this._firstStaffInAccolade||!this._lastStaffInAccolade)return;let s=this._allStaves[this._allStaves.length-1],i=t+this.y+this._firstStaffInAccolade.y,a=t+this.y+this._lastStaffInAccolade.y+this._lastStaffInAccolade.height,r=t+this.y+this._allStaves[0].y,n=t+this.y+s.y+s.height,o=t+this.y+this._firstStaffInAccolade.y+this._firstStaffInAccolade.topSpacing+this._firstStaffInAccolade.topOverflow+(this._firstStaffInAccolade.barRenderers.length>0?this._firstStaffInAccolade.barRenderers[0].topPadding:0),h=a-i,l=t+this.y+s.y+s.height-s.bottomSpacing-s.bottomOverflow-(s.barRenderers.length>0?s.barRenderers[0].bottomPadding:0)-o,c=n-r,d=this.x+this._firstStaffInAccolade.x,u=new vi;u.visualBounds=new rt,u.visualBounds.x=e,u.visualBounds.y=t+this.y,u.visualBounds.w=this.width,u.visualBounds.h=this.height,u.realBounds=new rt,u.realBounds.x=e,u.realBounds.y=t+this.y,u.realBounds.w=this.width,u.realBounds.h=this.height,this.layout.renderer.boundsLookup.addStaveGroup(u);let p=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 a;p.has(e.bar.masterBar.index)?a=p.get(e.bar.masterBar.index):(a=new Ti,a.index=e.bar.masterBar.index,a.isFirstOfLine=e.isFirstOfLine,a.realBounds=new rt,a.realBounds.x=d+e.x,a.realBounds.y=r,a.realBounds.w=e.width,a.realBounds.h=c,a.visualBounds=new rt,a.visualBounds.x=d+e.x,a.visualBounds.y=i,a.visualBounds.w=e.width,a.visualBounds.h=h,a.lineAlignedBounds=new rt,a.lineAlignedBounds.x=d+e.x,a.lineAlignedBounds.y=o,a.lineAlignedBounds.w=e.width,a.lineAlignedBounds.h=l,this.layout.renderer.boundsLookup.addMasterBar(a),p.set(a.index,a)),e.buildBoundingsLookup(a,d,t+this.y+s.y)}}getBarX(e){if(!this._firstStaffInAccolade||0===this.layout.renderer.tracks.length)return 0;let t=this.layout.renderer.tracks[0].staves[0].bars[e];return this.layout.getRendererForBar(this._firstStaffInAccolade.staveId,t).x}}Ha.AccoladeLabelSpacing=10;class Wa extends Sa{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()}}createGlyphs(e){const t=this.renderer.scale,s=this.renderer.resources;this.height=0;const i=15*t;this._trackLabel.length>0&&(this.addGlyph(new Da(0,this.height,this._trackLabel,s.effectFont,P.Left)),this.height+=i),this.addGlyph(new Da(0,this.height,e.name,s.effectFont,P.Left));const a=64*t;if(this.renderer.scoreRenderer.canvas.font=s.effectFont,this.width=Math.max(this.renderer.scoreRenderer.canvas.measureText(this._trackLabel)*t,Math.max(this.renderer.scoreRenderer.canvas.measureText(e.name)*t,2*a)),this.height+=i,!e.isStandard){const r=.7,n=Wa.CircleNumberHeight*r*t;let o=0|Math.ceil(e.tunings.length/2),h=0,l=this.height;for(let c=0,d=e.tunings.length;c<d;c++){const d=N.GuitarString0+(c+1);this.addGlyph(new Ui(h,l+n/1.2,r,d));const u="= "+ye.getTextForTuning(e.tunings[c],!1);this.addGlyph(new Da(h+n+1*t,l,u,s.effectFont,P.Left)),l+=i,c===o-1&&(l=this.height,h+=a)}this.height+=o*i}this.width+=15*t}}Wa.CircleNumberHeight=20;class za extends Ma{constructor(e,t){super(e,t,P.Left)}addTuning(e,t){if(e.tunings.length>0){let s=new Wa(0,0,e,t);s.renderer=this.renderer,s.doLayout(),this.glyphs.push(s)}}}class Ua{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"}(Je||(Je={}));class Xa{constructor(e){this._barRendererLookup=new Map,this.width=0,this.height=0,this.scoreInfoGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this.systemsLayoutMode=Je.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){this.renderer.settings.core.enableLazyLoading?(this._lazyPartials.set(e.id,new Ua(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(){q.debug("ScoreLayout","Creating score info glyphs");let e=this.renderer.settings.notation,t=this.renderer.score,s=this.renderer.settings.display.resources;this.scoreInfoGlyphs=new Map,t.title&&e.isNotationElementVisible(k.ScoreTitle)&&this.scoreInfoGlyphs.set(k.ScoreTitle,new Da(0,0,t.title,s.titleFont,P.Center)),t.subTitle&&e.isNotationElementVisible(k.ScoreSubTitle)&&this.scoreInfoGlyphs.set(k.ScoreSubTitle,new Da(0,0,t.subTitle,s.subTitleFont,P.Center)),t.artist&&e.isNotationElementVisible(k.ScoreArtist)&&this.scoreInfoGlyphs.set(k.ScoreArtist,new Da(0,0,t.artist,s.subTitleFont,P.Center)),t.album&&e.isNotationElementVisible(k.ScoreAlbum)&&this.scoreInfoGlyphs.set(k.ScoreAlbum,new Da(0,0,t.album,s.subTitleFont,P.Center)),t.music&&t.music===t.words&&e.isNotationElementVisible(k.ScoreWordsAndMusic)?this.scoreInfoGlyphs.set(k.ScoreWordsAndMusic,new Da(0,0,"Music and Words by "+t.words,s.wordsFont,P.Center)):(t.music&&e.isNotationElementVisible(k.ScoreMusic)&&this.scoreInfoGlyphs.set(k.ScoreMusic,new Da(0,0,"Music by "+t.music,s.wordsFont,P.Right)),t.words&&e.isNotationElementVisible(k.ScoreWords)&&this.scoreInfoGlyphs.set(k.ScoreWords,new Da(0,0,"Words by "+t.words,s.wordsFont,P.Left)));const i=new Ya(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);if(e.isNotationElementVisible(k.GuitarTuning)){let e=[];for(let t of this.renderer.tracks)for(let s of t.staves)if(!s.isPercussion&&s.isStringed&&s.tuning.length>0&&s.showTablature){e.push(s);break}if(e.length>0){this.tuningGlyph=new za(0,0),this.tuningGlyph.renderer=i;for(const t of e)this.tuningGlyph.addTuning(t.stringTuning,e.length>1?t.track.name:"")}}if(e.isNotationElementVisible(k.ChordDiagrams)){this.chordDiagrams=new Ia(0,0),this.chordDiagrams.renderer=i;let e=new Set;for(let t of this.renderer.tracks)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))}}}get scale(){return this.renderer.settings.display.scale}createEmptyStaveGroup(){let e=new Ha;e.layout=this;for(let s=0;s<this.renderer.tracks.length;s++){let i=this.renderer.tracks[s],a=!1;for(let e of i.staves)if(e.showStandardNotation){a=!0;break}for(let r=0;r<i.staves.length;r++){let n,o=i.staves[r];if(o.isPercussion)n=t.Score;else if(this.renderer.settings.display.staveProfile!==t.Default)n=this.renderer.settings.display.staveProfile;else if(o.showTablature&&o.showStandardNotation)n=t.ScoreTab;else if(o.showTablature)n=a?t.TabMixed:t.Tab;else{if(!o.showStandardNotation)continue;n=t.Score}let h=Po.staveProfiles.get(n);for(let t of h)t.canCreate(i,o)&&e.addStaff(i,new Aa(s,o,t))}}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=12*this.renderer.settings.display.scale,a=Math.floor(2*i);const r=new _i,n=As.withFamilyList(s.copyrightFont.families,i,Ge.Plain,Ve.Bold);this.renderer.canvas.font=n;const o=Po.getLayoutEngineFactory(this.renderer.settings.display.layoutMode).vertical;return r.width=this.renderer.canvas.measureText(t),r.height=a,r.x=o?(this.width-r.width)/2:this.firstBarX,r.y=e,r.totalWidth=this.width,r.totalHeight=e+a,r.firstMasterBarIndex=-1,r.lastMasterBarIndex=-1,this.registerPartial(r,(e=>{e.color=s.mainGlyphColor,e.font=n,e.textAlign=P.Left,e.fillText(t,0,i)})),e+a}}!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"}(je||(je={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Qe||(Qe={}));class Ya{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 _a,this._voiceContainers=new Map,this._postBeatGlyphs=new _a,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 Ea(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 scale(){return this.settings.display.scale}get barDisplayScale(){return this.staff.staveGroup.staves.length>1?this.bar.masterBar.displayScale:this.bar.displayScale}get barDisplayWidth(){return this.staff.staveGroup.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==Je.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 _a,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new _a,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 wa(0,0,t);s.renderer=this,this._voiceContainers.set(this.bar.voices[e].index,s)}}this.bar.simileMark===o.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*this.scale}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 wi;i.bar=this.bar,i.visualBounds=new rt,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 rt,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(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];this.hasVoiceContainer(t)&&this.createVoiceGlyphs(this.bar.voices[e])}}createVoiceGlyphs(e){}createPostBeatGlyphs(){}get beatGlyphsStart(){return this._preBeatGlyphs.x+this._preBeatGlyphs.width}get postBeatGlyphsStart(){return this._postBeatGlyphs.x}getBeatX(e,t=Ye.PreNotes){let s=this.getBeatContainer(e);if(s)switch(t){case Ye.PreNotes:return s.voiceContainer.x+s.x;case Ye.OnNotes:return s.voiceContainer.x+s.x+s.onNotes.x;case Ye.MiddleNotes:return s.voiceContainer.x+s.x+s.onTimeX;case Ye.Stem:const t=s.onNotes.beamingHelper?s.onNotes.beamingHelper.getBeatLineX(e):s.onNotes.x+s.onNotes.width/2;return s.voiceContainer.x+t;case Ye.PostNotes:return s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.width;case Ye.EndBeat:return s.voiceContainer.x+s.x+s.width}return 0}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._preBeatGlyphs=new _a,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()),this.updateSizes(),this.registerLayoutingInfo()}paintSimileMark(e,t,s){switch(this.bar.simileMark){case o.Simple:s.fillMusicFontSymbol(e+this.x+(this.width-20*this.scale)/2,t+this.y+this.height/2,1,N.Repeat1Bar,!1);break;case o.SecondOfDouble:s.fillMusicFontSymbol(e+this.x-28*this.scale/2,t+this.y+this.height/2,1,N.Repeat2Bars,!1)}}completeBeamingHelper(e){}}Ya.LineSpacing=8,Ya.StemWidth=.12*Ya.LineSpacing,Ya.StaffLineThickness=.13*Ya.LineSpacing,Ya.BeamThickness=.5*Ya.LineSpacing,Ya.BeamSpacing=.25*Ya.LineSpacing,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"}($e||($e={}));class qa extends Wi{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.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 $e.SingleOnBeatToEnd:case $e.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)}}createOrResizeGlyph(e,t){let s;switch(e){case $e.FullBar:case $e.SinglePreBeat:case $e.SingleOnBeat:case $e.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 $e.GroupedOnBeat:case $e.GroupedOnBeatToEnd:let i=e===$e.GroupedOnBeat?$e.SingleOnBeat:$e.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($e.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,i=this._effectGlyphs[t.voice.index].get(t.index),a=this.renderer.getBeatContainer(t);switch(e){case $e.SinglePreBeat:s=a.preNotes,i.x=this.renderer.beatGlyphsStart+s.x+a.x,i.width=s.width;break;case $e.SingleOnBeat:case $e.GroupedOnBeat:s=a.onNotes,i.x=this.renderer.beatGlyphsStart+s.x+a.x,i.width=s.width;break;case $e.SingleOnBeatToEnd:case $e.GroupedOnBeatToEnd:s=a.onNotes,i.x=this.renderer.beatGlyphsStart+s.x+a.x,a.beat.isLastOfVoice?i.width=this.renderer.width-i.x:i.width=a.width-a.preNotes.width-a.preNotes.x;break;case $e.FullBar:i.width=this.renderer.width}}}class Ja{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class ja{constructor(){this.bands=[],this.shared=new Ja}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 Qa{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 ja;return this.slots.push(t),t}register(e){let t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class $a extends Sa{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 Ka extends $a{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,s){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class Za extends Ya{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(){if(!super.applyLayoutingInfo())return!1;if(this.index>0){let e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new Qa;for(let e of this._bands)e.alignGlyphs(),e.isEmpty||this.sizingInfo.register(e);return this.updateHeight(),!0}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 qa(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 qi(t,this.getVoiceContainer(e));s.preNotes=new $a,s.onNotes=new Ka,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 er extends ba{get staffId(){return this._staffId}constructor(e,t){super(),this._infos=t,this._staffId=e,this.isInAccolade=!1,this.isRelevantForBoundsLookup=!1}create(e,t){return new Za(e,t,this._infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class tr extends zi{constructor(e,t,s){super(e,t),this._endingsString="",this._endings=[];for(let e=0;e<le.MaxAlternateEndings;e++)s&1<<e&&this._endings.push(e)}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(tr.Padding*this.scale+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=C.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+tr.Padding*this.scale,t+this.y*this.scale)}s.textBaseline=i}}tr.Padding=3;class sr{get effectId(){return this.notationElement.toString()}}class ir extends sr{get notationElement(){return k.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return $e.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){return new tr(0,0,t.voice.bar.masterBar.alternateEndings)}canExpand(e,t){return!0}}class ar extends sr{get notationElement(){return k.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Da(0,0,"Capo. fret "+t.voice.bar.staff.capo,e.resources.effectFont,P.Left)}canExpand(e,t){return!1}}class rr extends sr{get notationElement(){return k.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Da(0,0,t.chord.name,e.resources.effectFont,P.Center)}canExpand(e,t){return!1}}class nr extends zi{constructor(e){super(),this.forceGroupedRendering=!1,this.endOnBarLine=!1,this.endPosition=e}get isLinkedWithPrevious(){return!!this.previousGlyph&&this.previousGlyph.renderer.staff.staveGroup===this.renderer.staff.staveGroup}get isLinkedWithNext(){return!!this.nextGlyph&&this.nextGlyph.renderer.isFinalized&&this.nextGlyph.renderer.staff.staveGroup===this.renderer.staff.staveGroup}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 or extends nr{constructor(e,t,s){super(Ye.EndBeat),this._crescendo=d.None,this._crescendo=s,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17*this.scale}paintGrouped(e,t,s,i){let a=e+this.x,r=this.height*this.scale;i.beginPath(),this._crescendo===d.Crescendo?(s-=or.Padding*this.scale,i.moveTo(s,t+this.y),i.lineTo(a,t+this.y+r/2),i.lineTo(s,t+this.y+r)):(s-=or.Padding*this.scale,i.moveTo(a,t+this.y),i.lineTo(s,t+this.y+r/2),i.lineTo(a,t+this.y+r)),i.stroke()}}or.Padding=Xi.QuarterNoteHeadWidth/2|0;class hr extends sr{get notationElement(){return k.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==d.None}createNewGlyph(e,t){return new or(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class lr extends Ui{constructor(e,t,s){super(e,t,.6,lr.getSymbol(s))}doLayout(){super.doLayout(),this.height=17*this.scale,this.y+=this.height/2}static getSymbol(e){switch(e){case p.PPP:return N.DynamicPPP;case p.PP:return N.DynamicPP;case p.P:return N.DynamicPiano;case p.MP:return N.DynamicMP;case p.MF:return N.DynamicMF;case p.F:return N.DynamicForte;case p.FF:return N.DynamicFF;case p.FFF:return N.DynamicFFF;default:return N.None}}}class cr extends sr{get notationElement(){return k.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return $e.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!==g.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===g.None)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new lr(0,0,t.dynamics)}canExpand(e,t){return!0}}class dr extends zi{doLayout(){super.doLayout(),this.height=17*this.scale}paint(e,t,s){let i=6*this.scale,a=Math.max(this.width,14*this.scale),r=this.height/2;s.beginPath(),s.moveTo(e+this.x,t+this.y+r),s.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r-i),s.moveTo(e+this.x,t+this.y+r),s.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r+i),s.stroke()}}class ur extends sr{get notationElement(){return k.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return t.fadeIn}createNewGlyph(e,t){return new dr}canExpand(e,t){return!0}}class pr extends Ui{constructor(e,t,s){super(e,t,1,pr.getSymbol(s))}static getSymbol(e){switch(e){case xe.Short:return N.FermataShortAbove;case xe.Medium:return N.FermataAbove;case xe.Long:return N.FermataLongAbove;default:return N.None}}doLayout(){this.width=23*this.scale,this.height=12*this.scale}paint(e,t,s){super.paint(e-this.width/2,t+this.height,s)}}class gr extends sr{get notationElement(){return k.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new pr(0,0,t.fermata.type)}canExpand(e,t){return!0}}class fr extends sr{get notationElement(){return k.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return!(0!==t.voice.index||t.isRest||e.notation.fingeringMode!==B.SingleNoteEffectBand&&e.notation.fingeringMode!==B.SingleNoteEffectBandForcePiano)&&(1===t.notes.length&&t.notes[0].isFingering)}createNewGlyph(e,t){let s=f.Unknown,i=!1,a=t.notes[0];a.leftHandFinger!==f.Unknown?(s=a.leftHandFinger,i=!0):a.rightHandFinger!==f.Unknown&&(s=a.rightHandFinger);let r=j.fingerToString(e.settings,t,s,i)??"";return new Da(0,0,r,e.resources.fingeringFont,P.Left)}canExpand(e,t){return!0}}class mr extends sr{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 yr extends nr{constructor(e){super(Ye.OnNotes),this._label=e}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=Ye.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=P.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=3*this.scale,r=i.measureText(this._label),n=e+this.x+r/2+a,o=t+this.y+4*this.scale,h=8*this.scale;if(s>n){let e=n;for(;e<s;)i.beginPath(),i.moveTo(e,0|o),i.lineTo(Math.min(e+h,s),0|o),e+=h+a,i.stroke();i.beginPath(),i.moveTo(s,o-5*this.scale|0),i.lineTo(s,o+5*this.scale|0),i.stroke()}}}yr.LineSpacing=3,yr.LineTopPadding=4,yr.LineTopOffset=5,yr.LineSize=8;class br extends mr{get effectId(){return this._effectId}get notationElement(){return k.EffectHarmonics}constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case m.None:this._effectId="harmonics-none";break;case m.Natural:this._effectId="harmonics-natural";break;case m.Artificial:this._effectId="harmonics-artificial";break;case m.Pinch:this._effectId="harmonics-pinch";break;case m.Tap:this._effectId="harmonics-tap";break;case m.Semi:this._effectId="harmonics-semi";break;case m.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 $e.GroupedOnBeat}createNewGlyph(e,t){return new yr(br.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case m.Natural:return"N.H.";case m.Artificial:return"A.H.";case m.Pinch:return"P.H.";case m.Tap:return"T.H.";case m.Semi:return"S.H.";case m.Feedback:return"Fdbk."}return""}}class Sr extends sr{get notationElement(){return k.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return $e.GroupedOnBeat}createNewGlyph(e,t){return new yr("LetRing")}canExpand(e,t){return!0}}class _r extends zi{constructor(e,t,s,i,a=P.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 wr extends sr{get notationElement(){return k.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new _r(0,0,t.lyrics,e.resources.effectFont,P.Center)}canExpand(e,t){return!0}}class Br extends sr{get notationElement(){return k.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return $e.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 Da(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,P.Left)}canExpand(e,t){return!0}}class Tr extends nr{constructor(e,t){super(Ye.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=13*this.scale}paintNonGrouped(e,t,s){this.paintOttava(e,t,s)}paintOttava(e,t,s){let i=0;switch(this._ottava){case n._15ma:i=37*this.scale,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,N.QuindicesimaAlta,!1);break;case n._8va:i=26*this.scale,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,N.OttavaAlta,!1);break;case n._8vb:i=23*this.scale,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,N.OttavaBassaVb,!1);break;case n._15mb:i=36*this.scale,s.fillMusicFontSymbols(e+this.x-i/2,t+this.y+this.height,.8,[N.Quindicesima,N.OctaveBaselineM,N.OctaveBaselineB],!1)}return i/2}paintGrouped(e,t,s,i){let a=this.paintOttava(e,t,i),r=3*this.scale,n=e+this.x+a+r,o=t+this.y;o+=this._aboveStaff?2*this.scale:this.height-2*this.scale;let h=8*this.scale;if(s>n){let e=n;for(;e<s;)i.beginPath(),i.moveTo(e,0|o),i.lineTo(Math.min(e+h,s),0|o),e+=h+r,i.stroke();i.beginPath(),this._aboveStaff?(i.moveTo(s,o),i.lineTo(s,t+this.y+this.height)):(i.moveTo(s,o),i.lineTo(s,t+this.y)),i.stroke()}}}class kr extends sr{get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return k.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.GroupedOnBeat}constructor(e){super(),this._aboveStaff=e}shouldCreateGlyph(e,t){switch(t.ottava){case n._15ma:case n._8va:return this._aboveStaff;case n._8vb:case n._15mb:return!this._aboveStaff}return!1}createNewGlyph(e,t){return new Tr(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class vr extends mr{get notationElement(){return k.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return $e.GroupedOnBeat}createNewGlyph(e,t){return new yr("P.M.")}constructor(){super()}}class xr extends mr{get notationElement(){return k.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===S.PickSlideDown||e.slideOutType===S.PickSlideUp}get sizingMode(){return $e.GroupedOnBeat}createNewGlyph(e,t){return new yr("P.S.")}constructor(){super()}}class Nr extends Ui{constructor(e,t,s){super(e,t,Xi.GraceScale,Nr.getSymbol(s))}doLayout(){this.width=9*this.scale,this.height=13*this.scale}paint(e,t,s){super.paint(e,t+this.height,s)}static getSymbol(e){switch(e){case x.Up:return N.StringsUpBow;case x.Down:return N.StringsDownBow;default:return N.None}}}class Pr extends sr{get notationElement(){return k.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==x.None}createNewGlyph(e,t){return new Nr(0,0,t.pickStroke)}canExpand(e,t){return!0}}class Cr extends nr{constructor(e){super(Ye.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case _.Slight:this._stepSize=12*this.scale;break;case _.Wide:this._stepSize=23*this.scale}this.height=18*this.scale}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 Er extends sr{get notationElement(){return k.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===_.Slight}createNewGlyph(e,t){return new Cr(_.Slight)}canExpand(e,t){return!0}}class Fr extends nr{constructor(e,t,s,i=1.2,a=!1){super(Ye.EndBeat),this._scale=0,this._symbol=N.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 _.Slight:this._symbol=N.WiggleTrill,this._symbolSize=9*this._scale,e=6*this._scale;break;case _.Wide:this._symbol=N.WiggleVibratoMediumFast,this._symbolSize=10*this._scale,e=10*this._scale}this.height=e*this.scale}paintGrouped(e,t,s,i){let a=s-(e+this.x),r=this._symbolSize*this.scale,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.scale,this._symbol,!1),o+=r}}class Lr extends mr{get notationElement(){return k.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===_.Slight||e.isTieDestination&&e.tieOrigin.vibrato===_.Slight}get sizingMode(){return $e.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Fr(0,0,_.Slight,1.2)}constructor(){super()}}class Mr extends sr{get notationElement(){return k.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){let s=e.resources;return t.slap?new Da(0,0,"S",s.effectFont,P.Left):t.pop?new Da(0,0,"P",s.effectFont,P.Left):new Da(0,0,"T",s.effectFont,P.Left)}canExpand(e,t){return!0}}class Ir extends zi{constructor(e,t,s){super(e,t),this._tempo=0,this._tempo=s}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,s){let i=this.renderer.resources;s.font=i.markerFont,s.fillMusicFontSymbol(e+this.x,t+this.y+.8*this.height,this.scale*Xi.GraceScale,N.NoteQuarterUp,!1),s.fillText("= "+this._tempo.toString(),e+this.x+this.height/2,t+this.y+s.font.size/2)}}class Dr extends sr{get notationElement(){return k.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return $e.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&(!!t.voice.bar.masterBar.tempoAutomation||0===t.voice.bar.index)}createNewGlyph(e,t){let s=0;return s=t.voice.bar.masterBar.tempoAutomation?t.voice.bar.masterBar.tempoAutomation.value:t.voice.bar.staff.track.score.tempo,new Ir(0,0,s)}canExpand(e,t){return!0}}class Ar extends sr{get notationElement(){return k.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Da(0,0,t.text,e.resources.effectFont,P.Left)}canExpand(e,t){return!0}}class Rr extends zi{constructor(e,t){super(e,t)}doLayout(){super.doLayout(),this.height=this.renderer.resources.markerFont.size*this.scale}paint(e,t,s){let i=this.renderer.resources;s.font=i.markerFont;let a=s.measureText("tr");s.fillText("tr",e+this.x,t+this.y);let r=a+3*this.scale,n=this.width-r,o=11*this.scale*1.2,h=Math.max(1,(n-r)/o),l=r,c=t+this.y+1.2*this.height;for(let t=0;t<h;t++)s.fillMusicFontSymbol(e+this.x+l,c,1.2,N.WiggleTrill,!1),l+=o}}class Or extends mr{get notationElement(){return k.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return $e.SingleOnBeat}createNewGlyph(e,t){return new Rr(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(Ke||(Ke={}));class Gr extends zi{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,s){e+=this.x;let i=(t+=this.y)+this.height*Xi.GraceScale;s.font=this.renderer.resources.effectFont,s.fillText("(",e,t+.3*this.height);let a=e+10*this.scale,r=e+40*this.scale;switch(this._tripletFeel){case D.NoTripletFeel:this.renderBarNote(a,i,Gr.NoteScale,s,[Ke.Full]),this.renderBarNote(r,i,Gr.NoteScale,s,[Ke.Full]);break;case D.Triplet8th:this.renderBarNote(a,i,Gr.NoteScale,s,[Ke.Full]),s.fillMusicFontSymbol(r,i,Gr.NoteScale,N.NoteQuarterUp,!1),s.fillMusicFontSymbol(r+Gr.NoteSeparation*this.scale,i,Gr.NoteScale,N.NoteEighthUp,!1),this.renderTriplet(r,t,s);break;case D.Triplet16th:this.renderBarNote(a,i,Gr.NoteScale,s,[Ke.Full,Ke.Full]),this.renderBarNote(r,i,Gr.NoteScale,s,[Ke.Full,Ke.PartialRight]),this.renderTriplet(r,t,s);break;case D.Dotted8th:this.renderBarNote(a,i,Gr.NoteScale,s,[Ke.Full]),this.renderBarNote(r,i,Gr.NoteScale,s,[Ke.Full,Ke.PartialRight]),s.fillCircle(r+9*this.scale,i,this.scale);break;case D.Dotted16th:this.renderBarNote(a,i,Gr.NoteScale,s,[Ke.Full,Ke.Full]),this.renderBarNote(r,i,Gr.NoteScale,s,[Ke.Full,Ke.Full,Ke.PartialRight]),s.fillCircle(r+9*this.scale,i,this.scale);break;case D.Scottish8th:this.renderBarNote(a,i,Gr.NoteScale,s,[Ke.Full]),this.renderBarNote(r,i,Gr.NoteScale,s,[Ke.Full,Ke.PartialLeft]),s.fillCircle(r+Gr.NoteSeparation*this.scale+8*this.scale,i,this.scale);break;case D.Scottish16th:this.renderBarNote(a,i,Gr.NoteScale,s,[Ke.Full,Ke.Full]),this.renderBarNote(r,i,Gr.NoteScale,s,[Ke.Full,Ke.Full,Ke.PartialLeft]),s.fillCircle(r+Gr.NoteSeparation*this.scale+8*this.scale,i,this.scale)}s.fillText("=",e+30*this.scale,t+5*this.scale),s.fillText(")",e+65*this.scale,t+.3*this.height)}renderBarNote(e,t,s,i,a){i.fillMusicFontSymbol(e,t,s,N.NoteQuarterUp,!1);let r=Gr.NoteSeparation/2*this.scale;for(let s=0;s<a.length;s++)switch(a[s]){case Ke.Full:i.fillRect(e+4*this.scale,t-Gr.NoteHeight*this.scale+Gr.BarSeparation*this.scale*s,Gr.NoteSeparation*this.scale,Gr.BarHeight*this.scale);break;case Ke.PartialLeft:i.fillRect(e+4*this.scale,t-Gr.NoteHeight*this.scale+Gr.BarSeparation*this.scale*s,r,Gr.BarHeight*this.scale);break;case Ke.PartialRight:i.fillRect(e+4*this.scale+r,t-Gr.NoteHeight*this.scale+Gr.BarSeparation*this.scale*s,r,Gr.BarHeight*this.scale)}i.fillMusicFontSymbol(e+Gr.NoteSeparation*this.scale,t,s,N.NoteQuarterUp,!1)}renderTriplet(e,t,s){t+=2*this.scale;let i=this.renderer.resources.effectFont;s.font=As.withFamilyList(i.families,.8*i.size,i.style);let a=e+Gr.NoteSeparation*this.scale+3*this.scale;s.beginPath(),s.moveTo(e,t+3*this.scale),s.lineTo(e,t),s.lineTo(e+5*this.scale,t),s.moveTo(a+5*this.scale,t+3*this.scale),s.lineTo(a+5*this.scale,t),s.lineTo(a,t),s.stroke(),s.fillText("3",e+7*this.scale,t-10*this.scale),s.font=i}}Gr.NoteScale=.4,Gr.NoteHeight=12,Gr.NoteSeparation=12,Gr.BarHeight=2,Gr.BarSeparation=3;class Vr extends sr{get notationElement(){return k.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return $e.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==D.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new Gr(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class Hr extends sr{get notationElement(){return k.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return $e.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new yr("w/bar")}canExpand(e,t){return!0}}class Wr extends sr{get notationElement(){return k.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return $e.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===_.Wide}createNewGlyph(e,t){return new Cr(_.Wide)}canExpand(e,t){return!0}}class zr extends mr{get notationElement(){return k.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===_.Wide||e.isTieDestination&&e.tieOrigin.vibrato===_.Wide}get sizingMode(){return $e.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Fr(0,0,_.Wide,1.2)}}class Ur{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class Xr extends Xa{get name(){return"HorizontalScreen"}constructor(e){super(e),this._group=null,this._pagePadding=null}get supportsResize(){return!1}get firstBarX(){let e=this._pagePadding[0];return this._group&&(e+=this._group.accoladeSpacing),e}doResize(){}doLayoutAndRender(){switch(this._pagePadding=this.renderer.settings.display.padding,this.renderer.settings.display.systemsLayoutMode){case He.Automatic:this.systemsLayoutMode=Je.Automatic;break;case He.UseModelLayout:this.systemsLayoutMode=Je.FromModelWithWidths}this._pagePadding||(this._pagePadding=Xr.PagePadding),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 e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t));let s=t,i=this.renderer.settings.display.barCount;i<=0&&(i=e.masterBars.length),i=t+i-1,i=Math.min(e.masterBars.length-1,Math.max(0,i)),this._group=this.createEmptyStaveGroup(),this._group.isLast=!0,this._group.x=this._pagePadding[0],this._group.y=this._pagePadding[1];let a=this.renderer.settings.display.barCountPerPartial,r=[],n=new Ur,o=0;for(;s<=i;){let t=this._group.addBars(this.renderer.tracks,s);if(t)if(0===n.masterBars.length&&t.isLinkedToPrevious&&r.length>0){let i=r[r.length-1];i.masterBars.push(e.masterBars[s]),i.width+=t.width,o+=t.width,n.x+=o}else n.masterBars.push(e.masterBars[s]),n.width+=t.width,n.masterBars.length>=a&&(0===r.length&&(n.width+=this._group.accoladeSpacing+this._pagePadding[0]),o+=n.width,r.push(n),q.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null),n=new Ur,n.x=o);s++}n.masterBars.length>0&&(0===r.length&&(n.width+=this._group.accoladeSpacing+this._pagePadding[0]),r.push(n),q.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null)),this.finalizeGroup(),this.height=Math.floor(this._group.y+this._group.height),this.width=this._group.x+this._group.width+this._pagePadding[2],s=0;let h=0;for(let e=0;e<r.length;e++){const t=r[e],i=new _i;i.x=h,i.y=0,i.totalWidth=this.width,i.totalHeight=this.height,i.width=t.width,i.height=this.height,i.firstMasterBarIndex=t.masterBars[0].index,i.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,h+=t.width;const a=s,n=e;this._group.buildBoundingsLookup(this._group.x,this._group.y),this.registerPartial(i,(e=>{let s=this._group.getBarX(t.masterBars[0].index)+this._group.accoladeSpacing;0===n&&(s-=this._group.x+this._group.accoladeSpacing),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=P.Left,q.debug(this.name,"Rendering partial from bar "+t.masterBars[0].index+" to "+t.masterBars[t.masterBars.length-1].index,null),this._group.paintPartial(-s,this._group.y,e,a,t.masterBars.length)})),s+=t.masterBars.length}this.height=this.layoutAndRenderAnnotation(this.height)+this._pagePadding[3]}finalizeGroup(){this._group.scaleToWidth(this._group.width),this._group.finalizeGroup()}}Xr.PagePadding=[20,20,20,20],Xr.GroupSpacing=20;class Yr extends Xa{get name(){return"PageView"}constructor(e){super(e),this._groups=[],this._allMasterBarRenderers=[],this._barsFromPreviousGroup=[],this._pagePadding=null}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case He.Automatic:this.systemsLayoutMode=Je.Automatic;break;case He.UseModelLayout:this.systemsLayoutMode=Je.FromModelWithScale}this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=Yr.PagePadding),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 e=0;this.width=this.renderer.width,this._allMasterBarRenderers=[],e=this.layoutAndRenderScoreInfo(e,-1),e=this.layoutAndRenderTunings(e,-1),e=this.layoutAndRenderChordDiagrams(e,-1),e=this.layoutAndRenderScore(e),e=this.layoutAndRenderAnnotation(e),this.height=e+this._pagePadding[3]}get supportsResize(){return!0}get firstBarX(){let e=this._pagePadding[0];return this._groups.length>0&&(e+=this._groups[0].accoladeSpacing),e}doResize(){let e=0;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]}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.width,this.tuningGlyph.doLayout();let i=this.tuningGlyph.height+11*this.scale;const a=new _i;return a.x=0,a.y=e,a.width=this.width,a.height=i,a.totalWidth=this.width,a.totalHeight=t<0?e+a.height:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=P.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.width,this.chordDiagrams.doLayout();const i=Math.floor(this.chordDiagrams.height),a=new _i;return a.x=0,a.y=e,a.width=this.width,a.height=i,a.totalWidth=this.width,a.totalHeight=t<0?e+i:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=P.Center,this.chordDiagrams.paint(0,0,e)})),e+i}layoutAndRenderScoreInfo(e,t=-1){q.debug(this.name,"Layouting score info");const s=new _i;s.x=0,s.y=e;let i=this._pagePadding[1],a=this.scale,r=this.renderer.settings.display.resources,n=[k.ScoreTitle,k.ScoreSubTitle,k.ScoreArtist,k.ScoreAlbum,k.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.width/2,t.y=i,t.textAlign=P.Center,i+=t.font.size*a}let o=!1,h=0;if(this.scoreInfoGlyphs.has(k.ScoreMusic)){let e=this.scoreInfoGlyphs.get(k.ScoreMusic);e.x=this.width-this._pagePadding[2],e.y=i,e.textAlign=P.Right,o=!0,h=e.font.size*a}if(this.scoreInfoGlyphs.has(k.ScoreWords)){let e=this.scoreInfoGlyphs.get(k.ScoreWords);e.x=this._pagePadding[0],e.y=i,e.textAlign=P.Left,o=!0,h=e.font.size*a}return o&&(i+=h),i=Math.floor(i+17*this.scale),s.width=this.width,s.height=i,s.totalWidth=this.width,s.totalHeight=t<0?e+s.height:t,this.registerPartial(s,(e=>{e.color=r.scoreInfoColor,e.textAlign=P.Center;for(const t of this.scoreInfoGlyphs.values())t.paint(0,0,e)})),e+i}resizeAndRenderScore(e,t){if(this.renderer.settings.display.barsPerRow>0||this.systemsLayoutMode==Je.FromModelWithScale)for(let s=0;s<this._groups.length;s++){let i=this._groups[s];this.fitGroup(i),e+=this.paintGroup(i,t)}else{this._groups=[];let s=0,i=this.maxWidth,a=this.createEmptyStaveGroup();for(a.index=this._groups.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._groups.push(a),this.fitGroup(a),e+=this.paintGroup(a,t),a=this.createEmptyStaveGroup(),a.index=this._groups.length,a.x=this._pagePadding[0],a.y=e}}a.isLast=this.lastBarIndex===a.lastBarIndex,this.fitGroup(a),e+=this.paintGroup(a,t)}return e}layoutAndRenderScore(e){let t=this.firstBarIndex,s=this.lastBarIndex;for(this._groups=[];t<=s;){let i=this.createStaveGroup(t,s);this._groups.push(i),i.x=this._pagePadding[0],i.y=e,t=i.lastBarIndex+1,this.fitGroup(i),q.debug(this.name,"Rendering partial from bar "+i.firstBarIndex+" to "+i.lastBarIndex,null),e+=this.paintGroup(i,e)}return e}paintGroup(e,t){let s=Math.floor(e.height+20*this.scale);const i=new _i;return i.x=0,i.y=e.y,i.totalWidth=this.width,i.totalHeight=t,i.width=this.width,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=P.Left,e.paint(0,-i.y,t)})),t+=s,s}fitGroup(e){e.isFull||e.width>this.maxWidth||this.renderer.settings.display.justifyLastSystem?e.scaleToWidth(this.maxWidth):e.scaleToWidth(e.width),e.finalizeGroup()}getBarsPerRow(e){let t=this.renderer.settings.display.barsPerRow;if(this.systemsLayoutMode==Je.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}createStaveGroup(e,t){let s=this.createEmptyStaveGroup();s.index=this._groups.length;let i=this.getBarsPerRow(s.index),a=this.maxWidth,r=t+1,n=e;for(;n<r;){if(this._barsFromPreviousGroup.length>0)for(let e of this._barsFromPreviousGroup)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._barsFromPreviousGroup=[];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._barsFromPreviousGroup.push(e);e&&!e.canWrap&&s.masterBarsRenderers.length>1;)e=s.revertLastBar(),e&&this._barsFromPreviousGroup.push(e);return s.isFull=!0,s.isLast=!1,this._barsFromPreviousGroup.reverse(),s}s.x=0,n++}return s.isLast=t===s.lastBarIndex,s}get maxWidth(){return this.renderer.width-this._pagePadding[0]-this._pagePadding[2]}}Yr.PagePadding=[40,40,40,40],Yr.GroupSpacing=20;class qr extends Ui{constructor(e,t,s,i=!1){super(e,t,i?Xi.GraceScale:1,qr.getMusicSymbol(s)),this._isGrace=i,this._accidentalType=s}static getMusicSymbol(e){switch(e){case qe.Natural:return N.AccidentalNatural;case qe.Sharp:return N.AccidentalSharp;case qe.Flat:return N.AccidentalFlat;case qe.NaturalQuarterNoteUp:return N.AccidentalQuarterToneNaturalArrowUp;case qe.SharpQuarterNoteUp:return N.AccidentalQuarterToneSharpArrowUp;case qe.FlatQuarterNoteUp:return N.AccidentalQuarterToneFlatArrowUp;case qe.DoubleSharp:return N.AccidentalDoubleSharp;case qe.DoubleFlat:return N.AccidentalDoubleFlat}return N.None}doLayout(){if(this._accidentalType===qe.DoubleFlat)this.width=18;else this.width=8;this.width=this.width*(this._isGrace?Xi.GraceScale:1)*this.scale}}class Jr extends Wi{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())+5*this.scale}paint(e,t,s){if(!this.renderer.staff.isFirstInAccolade)return;let i=this.renderer.resources,a=s.color;s.color=i.barNumberColor,s.font=i.barNumberFont,s.fillText(this._number.toString(),e+this.x,t+this.y),s.color=a}}class jr extends Wi{constructor(e,t){super(e,t)}doLayout(){this.renderer.isLast?this.width=15*this.scale:this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart?this.width=2*this.scale:(this.width=2*this.scale,this.renderer.bar.masterBar.isDoubleBar&&(this.width+=2*this.scale))}paint(e,t,s){let i=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x,o=r-a;this.renderer.isLast?(s.fillRect(n+this.width-i-i,a,this.scale,o),s.fillRect(n+this.width-i,a,i,o)):this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart||(s.fillRect(n+this.width-this.scale,a,this.scale,o),this.renderer.bar.masterBar.isDoubleBar&&s.fillRect(n+this.width-5*this.scale,a,this.scale,o))}}class Qr extends Ui{constructor(e,t,s,i){super(e,t,1,Qr.getSymbol(s)),this._clef=s,this._clefOttava=i}doLayout(){switch(this._clef){case r.Neutral:this.width=15*this.scale;break;case r.C3:case r.C4:case r.F4:case r.G2:this.width=28*this.scale}}static getSymbol(e){switch(e){case r.Neutral:return N.UnpitchedPercussionClef1;case r.C3:case r.C4:return N.CClef;case r.F4:return N.FClef;case r.G2:return N.GClef;default:return N.None}}paint(e,t,s){let i;super.paint(e,t,s);let a=!1;switch(this._clefOttava){case n._15ma:i=new Ui(-4*this.scale,0,.5,N.Quindicesima),a=!0;break;case n._8va:i=new Ui(-2*this.scale,0,.5,N.Ottava),a=!0;break;case n._8vb:i=new Ui(-6*this.scale,0,.5,N.Ottava);break;case n._15mb:i=new Ui(-8*this.scale,0,.5,N.Quindicesima);break;default:return}let o=0,h=0;switch(this._clef){case r.Neutral:o=a?-12:15,h=0;break;case r.C3:case r.C4:o=a?-19:27,h=0;break;case r.F4:o=a?-9:27,h=-4;break;case r.G2:o=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*this.scale,t+this.y+o*this.scale,s)}}class $r extends Wi{constructor(e,t){super(e,t)}doLayout(){this.width=11*this.scale}paint(e,t,s){let i=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x,o=r-a,h=1.5*this.scale,l=(a+r)/2;s.fillCircle(n,l-3*h,h),s.fillCircle(n,l+3*h,h),n+=4*this.scale,s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke(),n+=3*this.scale+.5,s.fillRect(n,a,i,o)}}class Kr extends Wi{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=P.Right;let r="x"+this._count,n=s.measureText(r)/1.5;s.fillText(r,e+this.x-n,t+this.y),s.textAlign=a}}class Zr extends Wi{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*this.scale}paint(e,t,s){let i=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x+.5,o=r-a;s.fillRect(n,a,i,o),n+=2*i-.5,s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke(),n+=3*this.scale;let h=this._circleSize*this.scale,l=(a+r)/2;s.fillCircle(n,l-h*this._dotOffset,h),s.fillCircle(n,l+h*this._dotOffset,h)}}class en extends Ui{constructor(e,t,s){super(e,t,1,en.getSymbol(s))}static getSymbol(e){switch(e){case i.None:return N.None;case i.Normal:return N.ArticAccentAbove;case i.Heavy:return N.ArticMarcatoAbove;default:return N.None}}doLayout(){this.width=9*this.scale,this.height=9*this.scale}paint(e,t,s){super.paint(e-2*this.scale,t+this.height,s)}}class tn extends Wi{constructor(e,t,s){super(e,t),this._size=0,this._size=s}doLayout(){this.width=this._size+3*this.scale}paint(e,t,s){s.fillCircle(e+this.x,t+this.y,this._size)}}class sn extends Ui{constructor(e,t,s){super(e,t,s?Xi.GraceScale:1,N.NoteheadXOrnate),this._isGrace=s}doLayout(){this.width=9*(this._isGrace?Xi.GraceScale:1)*this.scale,this.height=Xi.NoteHeadHeight*this.scale}}class an extends Ui{constructor(e,t,s,i){super(e,t,i?Xi.GraceScale:1,an.getSymbol(s)),this._isGrace=i}static getSymbol(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:case u.Whole:case u.Half:return N.NoteheadDiamondWhiteWide;default:return N.NoteheadDiamondBlackWide}}doLayout(){this.width=9*(this._isGrace?Xi.GraceScale:1)*this.scale,this.height=Xi.NoteHeadHeight*this.scale}}class rn extends Wi{constructor(e,t,s){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=Ce.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=rn.calculateActualTieHeight(this.renderer.scale,this._startX,this._startY,this._endX,this._endY,this.tieDirection===Ce.Down,this._tieHeight,4).h),this.tieDirection===Ce.Up&&(this.y-=this.height))}paint(e,t,s){this._shouldDraw&&(this.shouldDrawBendSlur()?rn.drawBendSlur(s,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Ce.Down,this.scale):rn.paintTie(s,this.scale,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Ce.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,s,i){return 22}getBeamDirection(e,t){return Ce.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=rn.computeBezierControlPoints(e,t,s,i,a,r,n,o);t=h[0],s=h[1];const l=h[2],c=h[3];i=h[6],a=h[7];const d=(t-l)/(t-2*l+i),u=rn.calculateExtrema(t,s,l,c,i,a,d),p=u.length>0?Math.min(t,i,u[0]):Math.min(t,i),g=u.length>0?Math.max(t,i,u[0]):Math.max(t,i),f=(s-c)/(s-2*c+a),m=rn.calculateExtrema(t,s,l,c,i,a,f),y=m.length>0?Math.min(s,a,m[1]):Math.min(s,a),b=m.length>0?Math.max(s,a,m[1]):Math.max(s,a),S=new rt;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,c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;let d=(i+t)/2,u=(a+s)/2;return[t,s,d+n*h,u+n*l,d+(n-o)*h,u+(n-o)*l,i,a]}static paintTie(e,t,s,i,a,r,n=!1,o=22,h=4){const l=rn.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,c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;let d=(i+t)/2,u=(a+s)/2,p=rn.BendSlurHeight*n;i-t<20&&(p/=2);let g=d+p*h,f=u+p*l;if(e.beginPath(),e.moveTo(t,s),e.lineTo(g,f),e.lineTo(i,a),e.stroke(),o){let t=e.measureText(o),s=r?0:-e.font.size;e.fillText(o,g-t/2,f+s)}}}rn.BendSlurHeight=11;class nn extends Wi{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=nn.Size*this.scale}paint(e,t,s){this._isOpen?rn.paintTie(s,this.scale,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):rn.paintTie(s,this.scale,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3)}}nn.Size=6;class on{constructor(e,t){this.line=0,this.line=e,this.isGhost=t}}class hn extends Wi{constructor(e){super(0,0),this._infos=[],this._glyphs=[],this.isEmpty=!0,this._isOpen=e}addParenthesis(e){let t=this.renderer,s=t.getNoteLine(e),i=e.isGhost||this.isTiedBend(e)&&t.settings.notation.isNotationElementVisible(k.ParenthesisOnTiedBends);this.addParenthesisOnLine(s,i)}addParenthesisOnLine(e,t){let s=new on(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 nn(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 ln{constructor(e,t){this.line=0,this.glyph=e,this.line=t}}class cn extends Wi{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new Ps,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){let s=new ln(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===Ce.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===Ce.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=3*this.scale,r=this.width-this.noteStartX+2*a;if(this.hasTopOverflow){let n=s.color;s.color=i.resources.staffLineColor;let o=-2;for(;o>=this.minNote.line;){let n=t+i.getScoreY(o);s.fillRect(e-a+this.noteStartX,n,r,this.scale),o-=2}s.color=n}if(this.hasBottomOverflow){let n=s.color;s.color=i.resources.staffLineColor;let o=10;for(;o<=this.maxNote.line;){let n=t+i.getScoreY(o);s.fillRect(e-a+this.noteStartX,n,r,this.scale),o+=2}s.color=n}let n=this._infos,o=e+this._noteHeadPadding;for(let e of n)e.glyph.renderer=this.renderer,e.glyph.paint(o,t,s)}}class dn extends Ui{constructor(e,t,s){super(e,t,1,dn.getSymbol(s))}doLayout(){this.width=12*this.scale}static getSymbol(e){switch(e){case u.ThirtySecond:return N.Tremolo3;case u.Sixteenth:return N.Tremolo2;case u.Eighth:return N.Tremolo1;default:return N.None}}}class un extends cn{constructor(){super(),this._noteGlyphLookup=new Map,this._notes=[],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 Qe.Left:break;case Qe.Center:i+=s.width/2;break;case Qe.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 je.TopWithStem:i-=this.renderer.getStemSize(this.beamingHelper);break;case je.Top:i-=s.height/2;break;case je.Center:break;case je.Bottom:i+=s.height/2;break;case je.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.direction;for(const e of this.aboveBeatEffects.values())e.renderer=this.renderer,e.doLayout();for(const e of this.belowBeatEffects.values())e.renderer=this.renderer,e.doLayout();if(this.beat.isTremolo){let t=0,s=e===Ce.Up?this.minNote:this.maxNote,i=e===Ce.Up?this.displacedX:0,a=this.beat.tremoloSpeed;switch(a){case u.ThirtySecond:t=e===Ce.Up?-15:15;break;case u.Sixteenth:t=e===Ce.Up?-12:15;break;case u.Eighth:t=e===Ce.Up?-10:10;break;default:t=e===Ce.Up?-10:15}this._tremoloPicking=new dn(i,s.glyph.y+t*this.scale,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 ki;r.note=i,r.noteHeadBounds=new rt,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){let i=this.renderer,a=0,r=0,n=1,o=-n;this.beamingHelper.direction===Ce.Up?(r=i.getScoreY(this.minNote.line),a=i.getScoreY(this.maxNote.line-2)):(r=i.getScoreY(this.maxNote.line-1),a=i.getScoreY(this.minNote.line+1),o*=-1,n*=-1);for(const i of this.aboveBeatEffects.values())a+=o*i.height,i.paint(e+this.x+2*this.scale,t+this.y+a,s);for(const i of this.belowBeatEffects.values())r+=n*i.height,i.paint(e+this.x+2*this.scale,t+this.y+r,s);super.paint(e,t,s),this._tremoloPicking&&this._tremoloPicking.paint(e,t,s)}}class pn extends Ui{constructor(e,t,s){super(e,t,1,pn.getSymbol(s)),this._duration=s}static getSymbol(e){switch(e){case u.QuadrupleWhole:return N.RestLonga;case u.DoubleWhole:return N.RestDoubleWhole;case u.Whole:return N.RestWhole;case u.Half:return N.RestHalf;case u.Quarter:return N.RestQuarter;case u.Eighth:return N.RestEighth;case u.Sixteenth:return N.RestSixteenth;case u.ThirtySecond:return N.RestThirtySecond;case u.SixtyFourth:return N.RestSixtyFourth;case u.OneHundredTwentyEighth:return N.RestOneHundredTwentyEighth;case u.TwoHundredFiftySixth:return N.RestTwoHundredFiftySixth;default:return N.None}}static getSize(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:case u.Whole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:return 9;case u.ThirtySecond:return 12;case u.SixtyFourth:return 14;case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:return 20}return 10}doLayout(){this.width=pn.getSize(this._duration)*this.scale}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class gn{constructor(){this.x=0,this.y=-3e3,this.width=0}}class fn extends Sa{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 gn);let t=21*this.scale;for(let s=0,i=this.glyphs.length;s<i;s++){let i=this.glyphs[s];i.renderer=this.renderer,i.doLayout();let a=0;for(;e[a].y>i.y;)a++,a===e.length&&e.push(new gn);i.x=a,e[a].y=i.y+t,e[a].width<i.width&&(e[a].width=i.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 mn extends cn{get direction(){return Ce.Up}constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new fn,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new hn(!0),this._postNoteParenthesis=new hn(!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 Xi(0,0,u.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!==qe.None){let e=new qr(0,i.y,a,!0);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+mn.ElementPadding*this.scale),this._accidentals.isEmpty||(e+=this._accidentals.width+mn.ElementPadding*this.scale,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+mn.ElementPadding*this.scale),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+mn.ElementPadding*this.scale,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+mn.ElementPadding*this.scale)}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)}}mn.ElementPadding=2;class yn extends Wi{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,s,i,a,r,n,o){rn.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*this.scale}getTieDirection(e,t){return t.getBeatDirection(e)===Ce.Up?Ce.Down:Ce.Up}}yn.EndPadding=8;class bn extends z{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class Sn extends Wi{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 l.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 l.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 l.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 l.Prebend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s);break;case l.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 l.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*Sn.BendValueHeight*this.scale;this.renderer.registerOverflowTop(e);let t=0;for(let e of this._notes){let s=this._renderPoints.get(e.id);switch(e.bendType){case l.Bend:s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case l.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t);break;case l.BendRelease:s[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[2].lineValue=t);break;case l.Prebend:s[0].lineValue=this._preBendMinValue;break;case l.PrebendBend:s[0].lineValue=this._preBendMinValue,s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case l.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 l.Custom:for(let s of e.bendPoints)t.push(new bn(s.offset,s.value));break;case l.BendRelease:t.push(new bn(0,e.bendPoints[0].value)),t.push(new bn(z.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new bn(z.MaxPosition,e.bendPoints[3].value));break;case l.Bend:case l.Hold:case l.Prebend:case l.PrebendBend:case l.PrebendRelease:case l.Release:t.push(new bn(0,e.bendPoints[0].value)),t.push(new bn(z.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,c=!1,d=null,u=!1,p=a.bendStyle===h.Gradual?"grad.":"",g=null;for(;o.isTieOrigin;){let e=o.tieDestination;if(d=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,e.beat.voice.bar),!d||n.staff!==d.staff)break;if(o=e,c=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes){u=!0;break}}g=o.beat,d=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,g.voice.bar),g.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(g=null);let f=0,m=0,y=t+n.y;f=e+n.x,r[0].value>0||a.isContinuedBend?f+=n.getBeatX(a.beat,Ye.MiddleNotes):f+=n.getNoteX(a,Qe.Right),m=!g||g.isLastOfVoice&&!u?e+d.x+d.postBeatGlyphsStart:u||!g.nextBeat?e+d.x+d.getBeatX(g,Ye.MiddleNotes):a.bendType===l.Hold?e+d.x+d.getBeatX(g.nextBeat,Ye.OnNotes):e+d.x+d.getBeatX(g.nextBeat,Ye.PreNotes),c||(m-=Sn.ArrowSize*this.scale);let b=(m-f)/z.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 bn(0,0),t,f,y,b,p,s),a.bendType!==l.Prebend?(0===e&&(f+=2*this.scale),this.paintBend(a,t,i,f,y,b,p,s)):a.isTieOrigin&&a.tieDestination.hasBend&&(i=new bn(z.MaxPosition,t.value),i.lineValue=t.lineValue,this.paintBend(a,t,i,f,y,b,p,s))}s.color=i}}paintBend(e,t,s,i,a,r,n,o){let h=this.renderer,l=this.renderer.resources,c=h.lineOffset/2,d=i+r*t.offset,u=Sn.BendValueHeight*this.scale,p=a-u*t.lineValue;0===t.value?s.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,je.Top):p+=h.getNoteY(e,je.Center):p+=c;let g=i+r*s.offset,f=a-u*s.lineValue;0===s.lineValue?f+=h.getNoteY(e,je.Center):f+=c;let m=0,y=Sn.ArrowSize*this.scale;if(s.value>t.value?(f+y>p&&(f=p-y),o.beginPath(),o.moveTo(g,f),o.lineTo(g-.5*y,f+y),o.lineTo(g+.5*y,f+y),o.closePath(),o.fill(),m=y):s.value!==t.value&&(f<p&&(f=p+y),o.beginPath(),o.moveTo(g,f),o.lineTo(g-.5*y,f-y),o.lineTo(g+.5*y,f-y),o.closePath(),o.fill(),m=-y),o.stroke(),t.value===s.value){if(t.lineValue>0){let e=g,t=Sn.DashSize*this.scale,s=d+t;if((e-d)/(2*t)<1)o.moveTo(e,p),o.lineTo(d,p);else for(;e>s;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>d?(o.moveTo(d,p),o.bezierCurveTo((d+g)/2,p,g,p,g,f+m),o.stroke()):(o.moveTo(d,p),o.lineTo(g,f),o.stroke());if(n&&t.offset<s.offset){o.font=l.graceFont;let e=o.measureText(n),t=0,s=0;if(p>f){let i=Math.abs(p-f);t=i>1.3*o.font.size?p-i/2:p,s=(d+g-e)/2}else t=p,s=g-e;o.fillText(n,s,t)}if(0!==s.value&&t.value!==s.value){let e=s.value,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+=Sn.getFractionSign(e)),""!==r){f=a-u*s.value;let e=f;i||(e=p+1*Math.abs(f-p)/3),o.font=l.tablatureFont;let t=o.measureText(r),n=e-.5*l.tablatureFont.size-2*this.scale,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"}}}Sn.ArrowSize=6,Sn.DashSize=3,Sn.BendValueHeight=6;class _n extends Wi{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===E.Custom)return e.whammyBarPoints;let t=[];switch(e.whammyBarType){case E.Dive:case E.Hold:case E.PrediveDive:case E.Predive:t.push(new z(0,e.whammyBarPoints[0].value)),t.push(new z(z.MaxPosition,e.whammyBarPoints[1].value));break;case E.Dip:t.push(new z(0,e.whammyBarPoints[0].value)),t.push(new z(z.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new z(z.MaxPosition,e.whammyBarPoints[e.whammyBarPoints.length-1].value))}return t}doLayout(){super.doLayout(),this._isSimpleDip=this.renderer.settings.notation.notationMode===T.SongBook&&this._beat.whammyBarType===E.Dip;let e=null,t=null,s=this._beat;for(;s&&s.hasWhammyBar;)(!e||e.value>s.minWhammyPoint.value)&&(e=s.minWhammyPoint),(!t||t.value<s.maxWhammyPoint.value)&&(t=s.maxWhammyPoint),s=s.nextBeat;let i=t.value>0?Math.abs(this.getOffset(t.value)):0;(i>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys))&&(i+=2*this.renderer.resources.tablatureFont.size);let a=e.value<0?Math.abs(this.getOffset(e.value)):0;this.renderer.registerOverflowTop(i+a),i>this.renderer.staff.getSharedLayoutData(_n.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(_n.TopOffsetSharedDataKey,i)}getOffset(e){if(0===e)return 0;let t=_n.PerHalfSize*this.scale+Math.log2(Math.abs(e)/2)*_n.PerHalfSize*this.scale;return e<0&&(t=-t),t}paint(e,t,s){let i=this.renderer,a=this._beat.nextBeat,r=null,n=Ye.PreNotes;a&&(r=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,a.voice.bar),r&&r.staff===i.staff&&(r===i||a.hasWhammyBar)?n=!a.hasWhammyBar||i.settings.notation.notationMode===T.SongBook&&a.whammyBarType===E.Dip?Ye.PreNotes:Ye.MiddleNotes:(a=null,r=null));let o=0,l=0;this._isSimpleDip?(o=e+i.x+i.getBeatX(this._beat,Ye.OnNotes)-2*this.scale,l=e+i.x+i.getBeatX(this._beat,Ye.PostNotes)+2*this.scale):(o=e+i.x+i.getBeatX(this._beat,Ye.MiddleNotes),l=r?e+r.x+r.getBeatX(a,n):e+i.x+i.width-2*this.scale);let c=s.textAlign;if(s.textAlign=P.Center,this._renderPoints.length>=2){let e=(l-o)/z.MaxPosition;s.beginPath();let i=t+this.renderer.staff.getSharedLayoutData(_n.TopOffsetSharedDataKey,0),a=this._beat.whammyStyle===h.Gradual?"grad.":"";for(let t=0,r=this._renderPoints.length-1;t<r;t++){let n=this._renderPoints[t],h=this._renderPoints[t+1],l=t<r-2?this._renderPoints[t+2]:null,c=0===t;0!==t||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new z(0,0),n,h,o,i,e,s),c=!1),this.paintWhammy(c,n,h,l,o,i,e,s,a),a=""}s.stroke()}s.textAlign=c}paintWhammy(e,t,s,i,a,r,n,o,h){let l=a+n*t.offset,c=a+n*s.offset,d=r-this.getOffset(t.value),u=r-this.getOffset(s.value);if(t.offset===s.offset){let e=_n.DashSize*this.scale;if(Math.abs(u-d)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(d,u),s=Math.min(d,u);for(;t>s;)o.moveTo(l,s),o.lineTo(l,s+e),s+=2*e}o.stroke()}else if(t.value===s.value){let e=_n.DashSize*this.scale;if(Math.abs(c-l)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(l,c),s=Math.min(l,c);for(;t>s;)o.moveTo(t,d),o.lineTo(t-e,d),t-=2*e}o.stroke()}else o.moveTo(l,d),o.lineTo(c,u);let p=this.renderer.resources;if(e&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let e=d;e-=p.tablatureFont.size+2*this.scale,this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2*this.scale,o.fillText(h,l,e))}let g=Math.abs(s.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys)&&!this._isSimpleDip)&&t.value!==s.value){let e="";if(s.value<0&&(e+="-"),g>=4){let t=g/4|0;e+=t,g-=4*t}else 0===g&&(e+="0");g>0&&(e+=Sn.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(d,u)-p.tablatureFont.size-2*this.scale:(a=t.offset===s.offset?Math.min(d,u):u,a-=p.tablatureFont.size+2*this.scale,i&&i.value>s.value&&(a-=2*this.scale));let r=c;o.fillText(e,r,a)}}}_n.TopOffsetSharedDataKey="tab.whammy.topoffset",_n.PerHalfSize=6,_n.DashSize=3;class wn extends yn{constructor(e){super(0,0),this._beat=e}doLayout(){let e=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case E.None:case E.Custom:case E.Hold:return;case E.Dive:case E.PrediveDive:{let e=new mn(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 E.Dip:if(e===T.SongBook){let e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+wn.SimpleDipHeight*this.scale+wn.SimpleDipPadding*this.scale}else{let e=new mn(this._beat,!1);if(e.renderer=this.renderer,this.renderer.settings.notation.notationMode===T.GuitarPro){let t=this._beat.whammyBarPoints[1];for(let s of this._beat.notes)e.addGlyph(this.getBendNoteValue(s,this._beat.whammyBarPoints[1]),t.value%2!=0)}e.doLayout(),this.BendNoteHeads.push(e);let t=new mn(this._beat,!1);if(t.renderer=this.renderer,this.renderer.settings.notation.notationMode===T.GuitarPro){let e=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let s of this._beat.notes)t.addGlyph(this.getBendNoteValue(s,e),e.value%2!=0)}t.doLayout(),this.BendNoteHeads.push(t)}case E.Predive:}super.doLayout()}paint(e,t,s){let i=this._beat;switch(i.whammyBarType){case E.None:case E.Custom:return}let a=this.renderer.settings.notation.notationMode,r=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,i.voice.bar),n=e+r.x+r.getBeatX(i,Ye.MiddleNotes),o=this.getTieDirection(i,r),l=1===this._beat.notes.length?o:Ce.Up,c=s.textAlign;for(let c=0;c<i.notes.length;c++){let d=i.notes[c],u=t+r.y;c>0&&c>=(this._beat.notes.length/2|0)&&(l=Ce.Down),l===Ce.Down?u+=r.getNoteY(d,je.Bottom):u+=r.getNoteY(d,je.Top);let p=e+r.x;i.isLastOfVoice?p+=r.width:p+=r.getBeatX(i,Ye.EndBeat),p-=8*this.scale;let g=i.whammyStyle===h.Gradual&&0===c?"grad.":"",f=null;d.isTieOrigin&&(f=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,d.tieDestination.beat.voice.bar),f&&f.staff===r.staff?p=e+f.x+f.getBeatX(d.tieDestination.beat,Ye.MiddleNotes):f=null);let m=Xi.NoteHeadHeight*this.scale*Xi.GraceScale*.5;l===Ce.Up&&(m=-m);let y=i.whammyBarPoints.length>0?this.getBendNoteValue(d,i.whammyBarPoints[i.whammyBarPoints.length-1]):0,b=0,S=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(y)?(b=this.BendNoteHeads[0].getNoteValueY(y)+m,S=!0):f&&(d.isTieOrigin&&d.tieDestination.beat.hasWhammyBar||d.beat.isContinuedWhammy)?(b=t+f.y+f.getNoteY(d.tieDestination,je.Top),S=!0,l===Ce.Down&&(b+=Xi.NoteHeadHeight*this.scale)):d.isTieOrigin&&(b=f?t+f.y+f.getNoteY(d.tieDestination,je.Top):u,l===Ce.Down&&(b+=Xi.NoteHeadHeight*this.scale)),i.whammyBarType){case E.Hold:d.isTieOrigin&&rn.paintTie(s,this.scale,n,u,p,b,o===Ce.Down,22,4);break;case E.Dive:0===c&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.BendNoteHeads[0].containsNoteValue(y)&&(b+=this.BendNoteHeads[0].y)),S?this.drawBendSlur(s,n,u,p,b,l===Ce.Down,this.scale,g):d.isTieOrigin&&rn.paintTie(s,this.scale,n,u,p,b,o===Ce.Down,22,4);break;case E.Dip:if(a===T.SongBook){if(0===c){let i=e+r.x+r.getBeatX(this._beat,Ye.OnNotes)-2*this.scale,a=e+r.x+r.getBeatX(this._beat,Ye.PostNotes)+2*this.scale,n=(i+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();s.font=this.renderer.resources.tablatureFont,s.fillText(o,n,t+this.y);let h=t+this.y+s.font.size+2*this.scale,l=h+wn.SimpleDipHeight*this.scale;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(s.moveTo(i,l),s.lineTo(n,h),s.lineTo(a,l)):(s.moveTo(i,h),s.lineTo(n,l),s.lineTo(a,h)),s.stroke()}d.isTieOrigin&&rn.paintTie(s,this.scale,n,u,p,b,o===Ce.Down,22,4)}else{let e=(n+p)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s);let a=this.getBendNoteValue(d,i.whammyBarPoints[1]),o=this.BendNoteHeads[0].getNoteValueY(a)+m;this.drawBendSlur(s,n,u,e,o,l===Ce.Down,this.scale,g),this.BendNoteHeads[1].x=p-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=t+r.y,this.BendNoteHeads[1].paint(0,0,s),b=this.BendNoteHeads[1].getNoteValueY(y)+m,this.drawBendSlur(s,e,o,p,b,l===Ce.Down,this.scale,g)}break;case E.PrediveDive:case E.Predive:let h=e+r.x+r.getBeatX(d.beat,Ye.PreNotes);h+=r.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let f=t+r.y+r.getScoreY(r.accidentalHelper.getNoteLineForValue(d.displayValue-(d.beat.whammyBarPoints[0].value/2|0),!1))+m;this.drawBendSlur(s,h,f,n,u,l===Ce.Down,this.scale,g),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.drawBendSlur(s,n,u,p,b,l===Ce.Down,this.scale,g))}}s.textAlign=c}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}wn.SimpleDipHeight=2*_n.PerHalfSize,wn.SimpleDipPadding=2;class Bn extends Wi{constructor(e,t,s){super(e,t),this.width=s}}class Tn extends Ui{constructor(e,t,s,i,a){super(e,t,a?Xi.GraceScale:1,s.getSymbol(i)),this._isGrace=a,this._articulation=s}paint(e,t,s){let i=this._isGrace?this.scale:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale*this.scale,this.symbol,!1),this._articulation.techniqueSymbol!==N.None&&this._articulation.techniqueSymbolPlacement===C.Middle&&s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale*this.scale,this._articulation.techniqueSymbol,!1)}doLayout(){let e=(this._isGrace?Xi.GraceScale:1)*this.scale;switch(this.symbol){case N.NoteheadWhole:this.width=14;break;case N.NoteheadCircleX:case N.NoteheadDiamondWhite:this.width=9;break;case N.NoteheadHeavyXHat:case N.NoteheadHeavyX:this.width=13;break;default:this.width=10}this.width=this.width*(this._isGrace?Xi.GraceScale:1)*this.scale,this.height=Xi.NoteHeadHeight*e}}class kn extends Ui{constructor(e,t){super(e,t,Xi.GraceScale,N.ArticStaccatoAbove)}doLayout(){this.width=Xi.QuarterNoteHeadWidth*this.scale,this.height=7*this.scale}paint(e,t,s){super.paint(e+3*this.scale,t+5*this.scale,s)}}class vn extends Ui{constructor(e,t){super(e,t,.5,N.PictEdgeOfCymbal)}doLayout(){this.width=22*this.scale,this.height=15*this.scale}paint(e,t,s){super.paint(e-3*this.scale,t+this.height,s)}}class xn extends Ui{constructor(e,t){super(e,t,Xi.GraceScale,N.GuitarGolpe)}doLayout(){this.width=9*this.scale,this.height=10*this.scale}paint(e,t,s){super.paint(e,t+this.height,s)}}class Nn extends Ka{constructor(){super(...arguments),this._collisionOffset=-1e3,this._skipPaint=!1,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&&(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)}}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===u.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const s=new pn(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=xa.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 Bn(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++){let e=new Sa(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addGlyph(e)}}}else{const t=new un;this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper;let s=new hn(!1);s.renderer=this.renderer;for(let e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),s.addParenthesis(e));if(this.addGlyph(t),s.isEmpty||(this.addGlyph(new Bn(0,0,4*(this.container.beat.graceType!==g.None?Xi.GraceScale:1)*this.scale)),this.addGlyph(s)),this.container.beat.hasWhammyBar){let e=new wn(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addGlyph(new Bn(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++){let t=new Sa(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.container.beat.isRest?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.centerX=this.noteHeads.x+this.noteHeads.width/2}createBeatDot(e,t){let s=this.renderer;t.addGlyph(new tn(0,s.getScoreY(e),1.5*this.scale))}createNoteHeadGlyph(e){let t=this.container.beat.graceType!==g.None;if(e.beat.voice.bar.staff.isPercussion){const s=$.getArticulation(e);if(s)return new Tn(0,0,s,e.beat.duration,t);q.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new sn(0,0,t):e.beat.graceType===g.BendGrace?new Xi(0,0,u.Quarter,!0):e.harmonicType===m.Natural?new an(0,0,e.beat.duration,t):new Xi(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===g.BendGrace&&!e.hasBend)return;let t=this.renderer,s=this.createNoteHeadGlyph(e),a=t.getNoteLine(e);if(s.y=t.getScoreY(a),this.noteHeads.addNoteGlyph(s,e,a),e.harmonicType!==m.None&&e.harmonicType!==m.Natural){let i=e.displayValue+e.harmonicPitch;s=new an(0,0,e.beat.duration,this.container.beat.graceType!==g.None),a=t.accidentalHelper.getNoteLineForValue(i,!1),s.y=t.getScoreY(a),this.noteHeads.addNoteGlyph(s,e,a)}if(e.isStaccato&&!this.noteHeads.aboveBeatEffects.has("Staccato")&&this.noteHeads.belowBeatEffects.set("Staccato",new kn(0,0)),e.accentuated!==i.Normal||this.noteHeads.aboveBeatEffects.has("Accent")||this.noteHeads.belowBeatEffects.set("Accent",new en(0,0,i.Normal)),e.accentuated!==i.Heavy||this.noteHeads.aboveBeatEffects.has("HAccent")||this.noteHeads.belowBeatEffects.set("HAccent",new en(0,0,i.Heavy)),e.isPercussion){const t=$.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==C.Middle){const e=t.techniqueSymbolPlacement===C.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case N.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new vn(0,0));break;case N.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new kn(0,0));break;case N.StringsUpBow:e.set("StringsUpBow",new Nr(0,0,x.Up));break;case N.StringsDownBow:e.set("StringsDownBow",new Nr(0,0,x.Down));break;case N.GuitarGolpe:e.set("GuitarGolpe",new xn(0,0))}}}}}class Pn extends Wi{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=this._beat.brushType===c.ArpeggioUp||this._beat.brushType===c.ArpeggioDown?10*this.scale:0}paint(e,t,s){if(this._beat.brushType===c.ArpeggioUp||this._beat.brushType===c.ArpeggioDown){let i=this.renderer,a=i.lineOffset,r=t+this.y+(i.getNoteY(this._beat.maxNote,je.Bottom)-a),n=t+this.y+i.getNoteY(this._beat.minNote,je.Top)+a,o=e+this.x+this.width/2,h=8*this.scale,l=new Fr(0,0,_.Slight,1.2,!0);l.renderer=this.renderer,l.doLayout();let d=-l.height/2;if(this._beat.brushType===c.ArpeggioUp){let t=r+h,i=n-h;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5*this.scale,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===c.ArpeggioDown){let t=r+h,i=n;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5*this.scale,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 Cn extends $a{get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}doLayout(){if(!this.container.beat.isRest){let e=new fn;e.renderer=this.renderer;let t=new hn(!0);t.renderer=this.renderer;const s=new mn(this.container.beat,!0);this._prebends=s,s.renderer=this.renderer;for(let i of this.container.beat.notes)if(i.isVisible){if(i.hasBend)switch(i.bendType){case l.PrebendBend:case l.Prebend:case l.PrebendRelease:s.addGlyph(i.displayValue-(i.bendPoints[0].value/2|0),!1)}else if(i.beat.hasWhammyBar)switch(i.beat.whammyBarType){case E.PrediveDive:case E.Predive:this._prebends.addGlyph(i.displayValue-(i.beat.whammyBarPoints[0].value/2|0),!1)}this.createAccidentalGlyph(i,e),t.addParenthesis(i)}s.isEmpty||(this.addGlyph(s),this.addGlyph(new Bn(0,0,4*(this.container.beat.graceType!==g.None?Xi.GraceScale:1)*this.scale))),this.container.beat.brushType!==c.None&&(this.addGlyph(new Pn(this.container.beat)),this.addGlyph(new Bn(0,0,4*this.scale))),t.isEmpty||(this.addGlyph(t),this.addGlyph(new Bn(0,0,4*(this.container.beat.graceType!==g.None?Xi.GraceScale:1)*this.scale))),e.isEmpty||(this.accidentals=e,this.addGlyph(new Bn(0,0,2*(this.container.beat.graceType!==g.None?Xi.GraceScale:1)*this.scale)),this.addGlyph(e),this.addGlyph(new Bn(0,0,2*(this.container.beat.graceType!==g.None?Xi.GraceScale:1)*this.scale)))}super.doLayout()}createAccidentalGlyph(e,t){let s=this.renderer,i=s.accidentalHelper.applyAccidental(e),a=s.getNoteLine(e),r=this.container.beat.graceType!==g.None;if(i!==qe.None){let e=new qr(0,s.getScoreY(a),i,r);e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==m.None&&e.harmonicType!==m.Natural){let n=e.displayValue+e.harmonicPitch;i=s.accidentalHelper.applyAccidentalForValue(e.beat,n,r,!1),a=s.accidentalHelper.getNoteLineForValue(n,!1);let o=new qr(0,s.getScoreY(a),i,r);o.renderer=this.renderer,t.addGlyph(o)}}constructor(){super(),this._prebends=null,this.accidentals=null}}class En extends Ui{constructor(e,t,s,i){super(e,t,i,En.getSymbol(s)),this._digit=0,this._scale=0,this._digit=s,this._scale=i}doLayout(){this.width=this.getDigitWidth(this._digit)*this.scale*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 N.TimeSig0;case 1:return N.TimeSig1;case 2:return N.TimeSig2;case 3:return N.TimeSig3;case 4:return N.TimeSig4;case 5:return N.TimeSig5;case 6:return N.TimeSig6;case 7:return N.TimeSig7;case 8:return N.TimeSig8;case 9:return N.TimeSig9;default:return N.None}}}class Fn extends Sa{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 En(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}}}Fn.numberHeight=18;class Ln extends Sa{constructor(e,t,s,i,a){super(e,t),this._numerator=0,this._denominator=0,this._numerator=s,this._denominator=i,this._isCommon=a}doLayout(){if(this._isCommon&&2===this._numerator&&2===this._denominator){let e=new Ui(0,0,this.commonScale,N.TimeSigCutCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){let e=new Ui(0,0,this.commonScale,N.TimeSigCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else{const e=Fn.numberHeight*this.scale;let t=new Fn(0,-e/2,this._numerator,this.numberScale),s=new Fn(0,e/2,this._denominator,this.numberScale);this.addGlyph(t),this.addGlyph(s),super.doLayout();for(let e=0,t=this.glyphs.length;e<t;e++){let t=this.glyphs[e];t.x=(this.width-t.width)/2}}}}class Mn extends Ln{get commonScale(){return 1}get numberScale(){return 1}}class In extends yn{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 l.Bend:case l.PrebendRelease:case l.PrebendBend:{let t=this._endNoteGlyph;t||(t=new mn(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 l.Release:if(!e.isTieOrigin){let t=this._endNoteGlyph;t||(t=new mn(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 l.BendRelease:{let t=this._middleNoteGlyph;t||(t=new mn(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 mn(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,Ye.MiddleNotes),r=e+i.x;this._beat.isLastOfVoice?r+=i.postBeatGlyphsStart:r+=i.getBeatX(this._beat.nextBeat,Ye.PreNotes),r-=8*this.scale;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===g.BendGrace?this._beat.nextBeat:this._beat,c=1===this._notes.length?this.getTieDirection(o,i):Ce.Up;for(let o=0;o<this._notes.length;o++){let d=this._notes[o];o>0&&o>=(this._notes.length/2|0)&&(c=Ce.Down);let u=t+i.y+i.getNoteY(d,je.Top),p=Xi.NoteHeadHeight*this.scale*Xi.GraceScale*.5;c===Ce.Down&&(u+=Xi.NoteHeadHeight*this.scale);let g=d.bendStyle===h.Gradual?"grad.":"";if(d.isTieOrigin){let r=d.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,Ye.MiddleNotes),o=t+n.y+n.getNoteY(r,je.Top);c===Ce.Down&&(o+=Xi.NoteHeadHeight*this.scale),d.bendType===l.Hold||d.bendType===l.Prebend?rn.paintTie(s,this.scale,a,u,i,o,c===Ce.Down,22,4):this.drawBendSlur(s,a,u,i,o,c===Ce.Down,this.scale,g)}else{let r=e+i.x+i.width,n=d.tieDestination.realValue;i.accidentalHelper.applyAccidentalForValue(d.beat,n,!1,!0);let o=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(n,!1));d.bendType===l.Hold||d.bendType===l.Prebend?rn.paintTie(s,this.scale,a,u,r,o,c===Ce.Down,22,4):this.drawBendSlur(s,a,u,r,o,c===Ce.Down,this.scale,g)}switch(d.bendType){case l.Prebend:case l.PrebendBend:case l.PrebendRelease:let r=e+i.x+i.getBeatX(d.beat,Ye.PreNotes);r+=i.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let n=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(d.displayValue-(d.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,r,n,a,u,c===Ce.Down,this.scale)}}else{c===Ce.Up&&(p=-p);let o=0,h=0;switch(d.bendType){case l.Bend:o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,h,c===Ce.Down,this.scale,g);break;case l.BendRelease:let f=this.getBendNoteValue(d,d.bendPoints[1]),m=this._middleNoteGlyph.getNoteValueY(f)+p;this.drawBendSlur(s,a,u,n,m,c===Ce.Down,this.scale,g),o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,n,m,r,h,c===Ce.Down,this.scale,g);break;case l.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,h,c===Ce.Down,this.scale,g));break;case l.Prebend:case l.PrebendBend:case l.PrebendRelease:let y=e+i.x+i.getBeatX(d.beat,Ye.PreNotes);y+=i.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let b=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(d.displayValue-(d.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,y,b,a,u,c===Ce.Down,this.scale),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,h,c===Ce.Down,this.scale,g))}}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class Dn extends rn{constructor(e,t,s=!1){super(e,t,s)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?Ce.Up:t.getBeatDirection(e)===Ce.Up?Ce.Down:Ce.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Ce.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,je.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,je.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===Ce.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===g.None?s===this.tieDirection?this.tieDirection===Ce.Up?e.getNoteY(this.endBeat.maxNote,je.TopWithStem):e.getNoteY(this.endBeat.minNote,je.BottomWithStem):this.tieDirection===Ce.Up?e.getNoteY(this.endBeat.maxNote,je.BottomWithStem):e.getNoteY(this.endBeat.minNote,je.TopWithStem):this.tieDirection===Ce.Up?e.getNoteY(this.endBeat.maxNote,je.Top):e.getNoteY(this.endBeat.minNote,je.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,Ye.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>u.Whole&&e===this.tieDirection?Ye.Stem:Ye.MiddleNotes)}}class An extends Wi{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=12*this.scale,r=e+i.x+i.getNoteX(this._startNote,Qe.Left)-2*this.scale,n=t+i.y+i.getNoteY(this._startNote,je.Center),o=r-a,h=t+i.y;switch(this._inType){case b.IntoFromBelow:h+=i.getNoteY(this._startNote,je.Bottom);break;case b.IntoFromAbove:h+=i.getNoteY(this._startNote,je.Top);break;default:return}let l=this.getAccidentalsWidth(i,this._startNote.beat);o-=l,r-=l,this.paintSlideLine(s,!1,o,r,h,n)}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=12*this.scale,r=1*this.scale,n=2*this.scale,o=0,h=0,l=0,c=0,d=!1;switch(this._outType){case S.Shift:case S.Legato:if(o=e+i.x+i.getBeatX(this._startNote.beat,Ye.PostNotes),h=t+i.y+i.getNoteY(this._startNote,je.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?(l=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,Ye.PreNotes)-r,c=t+s.y+s.getNoteY(this._startNote.slideTarget,je.Center)):(l=e+i.x+i.width,c=h),this._startNote.slideTarget.realValue>this._startNote.realValue?(h+=n,c-=n):(h-=n,c+=n)}else l=e+i.x+this._parent.x,c=h;break;case S.OutUp:o=e+i.x+i.getNoteX(this._startNote,Qe.Right),h=t+i.y+i.getNoteY(this._startNote,je.Center),l=o+a,c=t+i.y+i.getNoteY(this._startNote,je.Top);break;case S.OutDown:o=e+i.x+i.getNoteX(this._startNote,Qe.Right),h=t+i.y+i.getNoteY(this._startNote,je.Center),l=o+a,c=t+i.y+i.getNoteY(this._startNote,je.Bottom);break;case S.PickSlideUp:o=e+i.x+i.getNoteX(this._startNote,Qe.Right),h=t+i.y+i.getNoteY(this._startNote,je.Center),c=t+i.y+i.getNoteY(this._startNote,je.Top),l=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(l=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Ye.PreNotes)),d=!0;break;case S.PickSlideDown:o=e+i.x+i.getNoteX(this._startNote,Qe.Right),h=t+i.y+i.getNoteY(this._startNote,je.Center),c=t+i.y+i.getNoteY(this._startNote,je.Bottom),l=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(l=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Ye.PreNotes)),d=!0;break;default:return}this.paintSlideLine(s,d,o,l,h,c)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new Fr(0,0,_.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 Rn extends Dn{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===Ce.Up?this.startNoteRenderer.getNoteY(this._startNote,je.Top):this.startNoteRenderer.getNoteY(this._startNote,je.Bottom):this.startNoteRenderer.getNoteY(this._startNote,je.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===Ce.Up?this.endNoteRenderer.getNoteY(this._endNote,je.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,je.BottomWithStem):this.tieDirection===Ce.Up?this.endNoteRenderer.getNoteY(this._endNote,je.Top):this.endNoteRenderer.getNoteY(this._endNote,je.Bottom):this.endNoteRenderer.getNoteY(this._endNote,je.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===Ce.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===Ce.Down}isEndCentered(){return this._startNote.beat.graceType===g.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===Ce.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===Ce.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===g.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,Ye.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,Qe.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,Ye.Stem):this.endNoteRenderer.getNoteX(this._endNote,Qe.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,Ye.PreNotes)}}class On extends rn{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)===Ce.Up?Ce.Down:Ce.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Ce.Up?this.startNoteRenderer.getNoteY(this.startNote,je.Top):this.startNoteRenderer.getNoteY(this.startNote,je.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===Ce.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===Ce.Up?e.getNoteY(this.endNote,je.Top):e.getNoteY(this.endNote,je.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,Ye.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,Ye.PreNotes)}}class Gn extends qi{constructor(e,t){super(e,t),this._bend=null,this._effectSlur=null,this._effectEndSlur=null}doLayout(){if(this._effectSlur=null,this._effectEndSlur=null,super.doLayout(),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 Dn(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 Dn(e,this.beat,!0))}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!==g.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){let t=new On(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){let t=new On(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==b.None||e.slideOutType!==S.None){let t=new An(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){let t=new Rn(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){let t=new Rn(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new Rn(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===Ce.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,i=t===Ce.Up?e.beat.minNote:e.beat.maxNote;const a=new Rn(s,i,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new In(e.beat);this._bend=t,t.renderer=this.renderer,this.addTie(t)}this._bend.addBends(e)}}}}class Vn extends Ya{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._firstLineY=0,this._startSpacing=!1,this.accidentalHelper=new Ta(this)}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}get lineOffset(){return(Ya.LineSpacing+1)*this.scale}updateSizes(){let e=this.resources,t=e.tablatureFont.size/2+.2*e.tablatureFont.size;this.topPadding=t*this.scale,this.bottomPadding=t*this.scale,this.height=4*this.lineOffset+this.topPadding+this.bottomPadding,this.updateFirstLineY(),super.updateSizes()}updateFirstLineY(){let e=4*this.lineOffset,t=(this.bar.staff.standardNotationLineCount-1)*this.lineOffset;this._firstLineY=(e-t)/2}doLayout(){if(this.updateFirstLineY(),super.doLayout(),!this.bar.isEmpty&&this.accidentalHelper.maxLineBeat){let e=this.getScoreY(-2),t=this.getScoreY(6),s=this.simpleWhammyOverflow;this.registerOverflowTop(s);let i=this.getScoreY(this.accidentalHelper.maxLine),a=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);a.direction===Ce.Up&&(i-=this.getStemSize(a),i-=a.fingeringCount*this.resources.graceFont.size,a.hasTuplet&&(i-=2*this.resources.effectFont.size)),a.hasTuplet&&(i-=1.5*this.resources.effectFont.size),i<e&&this.registerOverflowTop(Math.abs(i)+s);let r=this.getScoreY(this.accidentalHelper.minLine),n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);n.direction===Ce.Down&&(r+=this.getStemSize(n),r+=n.fingeringCount*this.resources.graceFont.size),r>t&&this.registerOverflowBottom(Math.abs(r)-t)}}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s),this.paintTuplets(e,t,s)}paintTuplets(e,t,s){for(let i of this.bar.voices)if(this.hasVoiceContainer(i)){let a=this.getVoiceContainer(i);for(let i of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,i)}}paintBeams(e,t,s){for(let i=0,a=this.helpers.beamHelpers.length;i<a;i++){let a=this.helpers.beamHelpers[i];for(let i=0,r=a.length;i<r;i++){let r=a[i];this.paintBeamHelper(e+this.beatGlyphsStart,t,s,r)}}}paintBeamHelper(e,t,s,i){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(1===i.beats.length?this.paintFlag(e,t,s,i):this.paintBar(e,t,s,i))}paintTupletHelper(e,t,s,i){let a,r=this.resources,n=s.textAlign,o=s.textBaseline;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=P.Center,s.textBaseline=C.Middle;let h=i.beats[0].tupletNumerator,l=i.beats[0].tupletDenominator;a=2===h&&3===l?"2":3===h&&2===l?"3":4===h&&6===l?"4":5===h&&4===l?"5":6===h&&4===l?"6":7===h&&4===l?"7":9===h&&8===l?"9":10===h&&8===l?"10":11===h&&8===l?"11":12===h&&8===l?"12":13===h&&8===l?"13":h+":"+l;let c=10*this.scale,d=5*this.scale;if(1!==i.beats.length&&i.isFull){let n=i.beats[0],o=i.beats[i.beats.length-1],h=null,l=null;for(let e=0;e<i.beats.length;e++)if(!i.beats[e].isRest){h=i.beats[e];break}for(let e=i.beats.length-1;e>=0;e--)if(!i.beats[e].isRest){l=i.beats[e];break}let u=!1;h||(h=n,u=!0),l||(l=o);let p=this.helpers.beamHelperLookup[i.voice.index].get(n.index),g=this.helpers.beamHelperLookup[i.voice.index].get(o.index),f=p.getBeatLineX(n),m=g.getBeatLineX(o),y=this.helpers.beamHelperLookup[i.voice.index].get(h.index),b=this.helpers.beamHelperLookup[i.voice.index].get(l.index),S=p.direction,_=this.calculateBeamYWithDirection(y,f,S),w=this.calculateBeamYWithDirection(b,m,S);u&&(_=Math.max(_,w),w=_),s.font=r.effectFont;let B=s.measureText(a),T=3*this.scale,k=(f+m)/2,v=k-B/2-T,x=k+B/2+T,N=(w-_)/(m-f),P=_-N*f,C=N*v+P,E=N*k+P,F=N*x+P;S===Ce.Down&&(c*=-1,d*=-1),s.beginPath(),s.moveTo(e+this.x+f,t+this.y+_-c|0),s.lineTo(e+this.x+f,t+this.y+_-c-d|0),s.lineTo(e+this.x+v,t+this.y+C-c-d|0),s.stroke(),s.beginPath(),s.moveTo(e+this.x+x,t+this.y+F-c-d|0),s.lineTo(e+this.x+m,t+this.y+w-c-d|0),s.lineTo(e+this.x+m,t+this.y+w-c|0),s.stroke(),s.fillText(a,e+this.x+k,t+this.y+E-c-d)}else for(let n=0,o=i.beats.length;n<o;n++){let o=i.beats[n],h=this.helpers.beamHelperLookup[i.voice.index].get(o.index);if(!h)continue;let l=h.direction,u=h.getBeatLineX(o),p=this.calculateBeamYWithDirection(h,u,l);l===Ce.Down&&(c*=-1,d*=-1),s.font=r.effectFont,s.fillText(a,e+this.x+u,t+this.y+p-c-d)}s.textAlign=n,s.textBaseline=o}getStemSize(e){let t=1===e.beats.length?this.getFlagStemSize(e.shortestDuration):this.getBarStemSize(e.shortestDuration);return e.isGrace&&(t*=Xi.GraceScale),t}getBarStemSize(e){let t=0;switch(e){case u.QuadrupleWhole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:t=6;break;case u.ThirtySecond:t=8;break;case u.SixtyFourth:case u.OneHundredTwentyEighth:t=9;break;case u.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}getFlagStemSize(e){let t=0;switch(e){case u.QuadrupleWhole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:case u.ThirtySecond:case u.SixtyFourth:case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:t=6;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){let s=super.getNoteY(e,t);if(isNaN(s)){const t=Ta.computeLineWithoutAccidentals(this.bar,e);s=this.getScoreY(t)}return s}calculateBeamY(e,t){return this.calculateBeamYWithDirection(e,t,e.direction)}applyLayoutingInfo(){const e=super.applyLayoutingInfo();if(e&&this.bar.isMultiVoice){let e=this.getScoreY(-2),t=this.getScoreY(6),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 va;e.drawingInfos.set(s,t);const a=e.beats[0],r=e.beats[e.beats.length-1];let n=e.isRestBeamHelper;t.startBeat=a,t.startX=e.getBeatLineX(a),t.startY=n?s===Ce.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===Ce.Up?this.getScoreY(this.accidentalHelper.getMinLine(a))-i:this.getScoreY(this.accidentalHelper.getMaxLine(a))+i,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?s===Ce.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===Ce.Up?this.getScoreY(this.accidentalHelper.getMinLine(r))-i:this.getScoreY(this.accidentalHelper.getMaxLine(r))+i;let o=10*this.scale;if(s===Ce.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),s===Ce.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),s===Ce.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),s===Ce.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(s===Ce.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=j.getIndex(e.shortestDuration)-2;let a=e.isGrace?Xi.GraceScale:1,r=i*(Ya.BeamSpacing+Ya.BeamThickness)*this.scale*a;if(r+=Ya.BeamSpacing,s===Ce.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===Ce.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)}}}}return e.drawingInfos.get(s).calcY(t)}paintBar(e,t,s,i){for(let a=0,r=i.beats.length;a<r;a++){let r=i.beats[a],n=r.graceType!==g.None?Xi.GraceScale:1,o=i.getBeatLineX(r),h=i.direction,l=t+this.y;l+=h===Ce.Up?this.getScoreY(this.accidentalHelper.getMaxLine(r)):this.getScoreY(this.accidentalHelper.getMinLine(r));let c=t+this.y;c+=this.calculateBeamY(i,o),s.lineWidth=Ya.StemWidth*this.scale,s.beginPath(),s.moveTo(e+this.x+o,l),s.lineTo(e+this.x+o,c),s.stroke(),s.lineWidth=this.scale;let d=c;h===Ce.Down?d+=2*s.font.size:0!==a&&(d-=1.5*s.font.size),this.paintFingering(s,r,e+this.x+o,h,d);let u=6*this.scale*n,p=(Ya.BeamSpacing+Ya.BeamThickness)*this.scale*n,f=Ya.BeamThickness*this.scale*n,m=j.getIndex(r.duration)-2,y=t+this.y;h===Ce.Down&&(p=-p,f=-f);for(let t=0;t<m;t++){let n=0,h=0,l=0,c=0,d=y+t*p;if(a<i.beats.length-1){if(xa.isFullBarJoin(r,i.beats[a+1],t))n=o,h=i.getBeatLineX(i.beats[a+1]);else{if(0!==a&&xa.isFullBarJoin(i.beats[a-1],r,t))continue;n=o,h=n+u}l=d+this.calculateBeamY(i,n),c=d+this.calculateBeamY(i,h),Vn.paintSingleBar(s,e+this.x+n,l,e+this.x+h,c,f)}else a>0&&!xa.isFullBarJoin(r,i.beats[a-1],t)&&(n=o-u,h=o,l=d+this.calculateBeamY(i,n),c=d+this.calculateBeamY(i,h),Vn.paintSingleBar(s,e+this.x+n,l,e+this.x+h,c,f))}}}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()}paintFlag(e,t,s,i){let a=i.beats[0];if(a.graceType===g.BendGrace||a.graceType!==g.None&&this.settings.notation.notationMode===T.SongBook)return;let r=a.graceType!==g.None,n=r?Xi.GraceScale:1,o=this.getFlagStemSize(i.shortestDuration),h=i.getBeatLineX(a),l=i.direction,c=this.getScoreY(this.accidentalHelper.getMinLine(a)),d=this.getScoreY(this.accidentalHelper.getMaxLine(a)),u=0,p=0;if(l===Ce.Down?(d+=o*n,u=d,p=t+this.y+d):(c-=o*n,u=c,p=t+this.y+c),this.paintFingering(s,a,e+this.x+h,l,p),i.hasLine){if(s.lineWidth=Ya.StemWidth*this.scale,s.beginPath(),s.moveTo(e+this.x+h,t+this.y+c),s.lineTo(e+this.x+h,t+this.y+d),s.stroke(),s.lineWidth=this.scale,a.graceType===g.BeforeBeat){let i=15*this.scale,a=12*this.scale;s.beginPath(),l===Ce.Down?(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.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.stroke()}if(i.hasFlag){let i=new Yi(h-this.scale/2,u,a.duration,l,r);i.renderer=this,i.doLayout(),i.paint(e+this.x,t+this.y,s)}}}paintFingering(e,t,s,i,a){let r=this.settings;if(r.notation.fingeringMode!==B.ScoreDefault&&r.notation.fingeringMode!==B.ScoreForcePiano)return;i===Ce.Up?s-=10*this.scale:s+=3*this.scale;let n=t.notes.slice(0);n.sort(((e,t)=>e.realValue-t.realValue));for(let i=0;i<n.length;i++){let o=n[i],h=null;o.leftHandFinger!==f.Unknown?h=j.fingerToString(r,t,o.leftHandFinger,!0):o.rightHandFinger!==f.Unknown&&(h=j.fingerToString(r,t,o.rightHandFinger,!1)),h&&(e.fillText(h,s,a),a-=0|e.font.size)}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Zr(0,0,1.5,3)),this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let e=0;switch(this.bar.clef){case r.Neutral:e=this.bar.staff.standardNotationLineCount-1;break;case r.F4:e=2;break;case r.C3:e=4;break;case r.C4:e=2;break;case r.G2:e=6}this.createStartSpacing(),this.addPreBeatGlyph(new Qr(0,this.getScoreY(e)+.5*Ya.StaffLineThickness,this.bar.clef,this.bar.clefOttava))}(0===this.index&&this.bar.masterBar.keySignature!==L.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.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new Jr(0,this.getScoreHeight(-.5),this.bar.index+1))}createBeatGlyphs(){for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];this.hasVoiceContainer(t)&&this.createVoiceGlyphs(t)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new $r(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Kr(0,this.getScoreHeight(-.5),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new jr(0,0))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new Bn(0,0,2*this.scale)),this._startSpacing=!0)}createKeySignatureGlyphs(){let e=0,t=this.bar.masterBar.keySignature,s=this.bar.previousBar?this.bar.previousBar.masterBar.keySignature:0;switch(this.bar.clef){case r.Neutral:e=0;break;case r.G2:e=1;break;case r.F4:e=3;break;case r.C3:e=2;break;case r.C4:e=0}let i=new Map,a=[];if(j.keySignatureIsSharp(t))for(let s=0;s<Math.abs(t);s++){let t=Vn.SharpKsSteps[s]+e;a.push(new qr(0,this.getScoreY(t),qe.Sharp,!1)),i.set(t,!0)}else for(let s=0;s<Math.abs(t);s++){let t=Vn.FlatKsSteps[s]+e;a.push(new qr(0,this.getScoreY(t),qe.Flat,!1)),i.set(t,!0)}let n=Math.abs(s),o=j.keySignatureIsSharp(s)?Vn.SharpKsSteps:Vn.FlatKsSteps;for(let t=0;t<n;t++){let s=o[t]+e;i.has(s)||this.addPreBeatGlyph(new qr(0,this.getScoreY(o[t]+e),qe.Natural,!1))}for(let e of a)this.addPreBeatGlyph(e)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Bn(0,0,5*this.scale));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new Mn(0,this.getScoreY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,s=e.beats.length;t<s;t++){let s=e.beats[t],i=new Gn(s,this.getVoiceContainer(e));i.preNotes=new Cn,i.onNotes=new Nn,this.addBeatGlyph(i)}}getNoteLine(e){return this.accidentalHelper.getNoteLine(e)}getScoreY(e){return this._firstLineY+this.lineOffset+this.getScoreHeight(e)}getScoreHeight(e){return this.lineOffset/2*e}paintBackground(e,t,s){super.paintBackground(e,t,s);let i=this.resources;s.color=i.staffLineColor;for(let i=0;i<this.bar.staff.standardNotationLineCount;i++){const a=t+this.y+this.getScoreY(2*i);s.fillRect(e+this.x,0|a,this.width,this.scale*Ya.StaffLineThickness)}s.color=i.mainGlyphColor,this.paintSimileMark(e,t,s)}completeBeamingHelper(e){if(this.bar.isMultiVoice&&e.highestNoteInHelper&&e.lowestNoteInHelper){let t=this.getNoteY(e.highestNoteInHelper,je.Center),s=this.getNoteY(e.lowestNoteInHelper,je.Center),i=this.getStemSize(e);e.hasTuplet&&(i+=2*this.resources.effectFont.size),e.direction==Ce.Up?t-=i:s+=i;for(const i of e.beats)this.helpers.collisionHelper.reserveBeatSlot(i,t,s)}}}Vn.StaffId="score",Vn.SharpKsSteps=[-1,2,-2,1,4,0,3],Vn.FlatKsSteps=[3,0,4,1,5,2,6];class Hn extends ba{get staffId(){return Vn.StaffId}create(e,t){return new Vn(e,t)}constructor(){super()}}class Wn extends Wi{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=12*this.scale,r=3*this.scale,n=0,o=0,h=0,l=0;switch(this._inType){case b.IntoFromBelow:h=e+i.x+i.getNoteX(this._startNote,Qe.Left),l=t+i.y+i.getNoteY(this._startNote,je.Center),n=h-a,o=t+i.y+i.getNoteY(this._startNote,je.Center)+r;break;case b.IntoFromAbove:h=e+i.x+i.getNoteX(this._startNote,Qe.Left),l=t+i.y+i.getNoteY(this._startNote,je.Center),n=h-a,o=t+i.y+i.getNoteY(this._startNote,je.Center)-r;break;default:return}this.paintSlideLine(s,!1,n,h,o,l)}paintSlideOut(e,t,s){let i=this.renderer,a=12*this.scale,r=3*this.scale,n=0,o=0,h=0,l=0,c=!1;const d=2*this.scale;switch(this._outType){case S.Shift:case S.Legato:if(n=e+i.x+i.getBeatX(this._startNote.beat,Ye.PostNotes),o=t+i.y+i.getNoteY(this._startNote,je.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?(h=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,Ye.OnNotes)-d,l=t+s.y+s.getNoteY(this._startNote.slideTarget,je.Center)):(h=e+i.x+i.width,l=o),this._startNote.slideTarget.fret>this._startNote.fret?(o+=r,l-=r):(o-=r,l+=r)}else h=e+i.x+this._parent.x,l=o;break;case S.OutUp:n=e+i.x+i.getNoteX(this._startNote,Qe.Right),o=t+i.y+i.getNoteY(this._startNote,je.Center),h=n+a-d,l=t+i.y+i.getNoteY(this._startNote,je.Center)-r;break;case S.OutDown:n=e+i.x+i.getNoteX(this._startNote,Qe.Right),o=t+i.y+i.getNoteY(this._startNote,je.Center),h=n+a-d,l=t+i.y+i.getNoteY(this._startNote,je.Center)+r;break;case S.PickSlideDown:n=e+i.x+i.getNoteX(this._startNote,Qe.Right),o=t+i.y+i.getNoteY(this._startNote,je.Center),h=e+i.x+i.getBeatX(this._startNote.beat,Ye.EndBeat),l=o+3*r,c=!0;break;case S.PickSlideUp:n=e+i.x+i.getNoteX(this._startNote,Qe.Right),o=t+i.y+i.getNoteY(this._startNote,je.Center),h=e+i.x+i.getBeatX(this._startNote.beat,Ye.EndBeat),l=o-3*r,c=!0;break;default:return}this.paintSlideLine(s,c,n,h,o,l)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new Fr(0,0,_.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 zn extends rn{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?Ce.Up:zn.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?Ce.Up:Ce.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,je.Center):this.tieDirection===Ce.Up?this.startNoteRenderer.getNoteY(this.startNote,je.Top):this.startNoteRenderer.getNoteY(this.startNote,je.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20*this.scale:this.startNoteRenderer.getNoteX(this.startNote,Qe.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,Qe.Left):this.endNoteRenderer.getNoteX(this.endNote,Qe.Center)}}class Un extends zn{constructor(e,t,s,i=!1){super(e,t,i),this._direction=zn.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!==zn.getBeamDirectionForNote(e))return!1;switch(this._direction){case Ce.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 Ce.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 Xn extends qi{constructor(e,t){super(e,t),this._bend=null,this._effectSlurs=[]}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 zn(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){let t=new zn(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new zn(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 Un(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 Un(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==b.None||e.slideOutType!==S.None){let t=new Wn(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new Sn;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class Yn extends Wi{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 e=this._note,t=e.fret-e.beat.voice.bar.staff.transpositionPitch;if(e.harmonicType===m.Natural&&0!==e.harmonicValue&&(t=e.harmonicValue-e.beat.voice.bar.staff.transpositionPitch),e.isTieDestination)0===e.beat.index&&this.renderer.settings.notation.notationMode==T.GuitarPro||(e.bendType===l.Bend||e.bendType===l.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(k.TabNotesOnTiedBends)?this._noteString="("+(e.tieOrigin.fret-e.beat.voice.bar.staff.transpositionPitch).toString()+")":this._noteString="";else if(this._noteString=e.isDead?"x":t.toString(),e.isGhost)this._noteString="("+this._noteString+")";else if(e.harmonicType===m.Natural){let e=this._noteString.indexOf(String.fromCharCode(46));e>=0&&(this._noteString=this._noteString.substr(0,e+2)),this._noteString="<"+this._noteString+">"}if(e.isTrill)this._trillNoteString="("+(e.trillFret-e.beat.voice.bar.staff.transpositionPitch).toString()+")";else if(j.isAlmostEqualTo(e.harmonicValue,0))this._trillNoteString="";else switch(e.harmonicType){case m.Artificial:case m.Pinch:case m.Tap:case m.Semi:case m.Feedback:let s=(t+e.harmonicValue).toString(),i=s.indexOf(String.fromCharCode(46));i>=0&&(s=s.substr(0,i+2)),this._trillNoteString="<"+s+">";break;default:this._trillNoteString=""}if(this.isEmpty=!this._noteString,!this.isEmpty){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.tablatureFont,this.noteStringWidth=this.renderer.scoreRenderer.canvas.measureText(this._noteString)*this.scale,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.scale+this.renderer.scoreRenderer.canvas.measureText(this._trillNoteString),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*this.scale,t+this.y),this.renderer.scoreRenderer.canvas.font=r,s.fillText(this._noteString,a,t+this.y)}buildBoundingsLookup(e,t,s){let i=new ki;i.note=this._note,i.noteHeadBounds=new rt,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 qn extends Wi{constructor(e,t,s){super(e,t),this._notes=[],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 Qe.Left:break;case Qe.Center:i+=s.noteStringWidth/2;break;case Qe.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 je.Top:case je.TopWithStem:i-=s.height/2+2*this.scale;break;case je.Center:break;case je.Bottom:case je.BottomWithStem:i+=s.height/2}return i}return 0}doLayout(){let e=0,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,je.Center)+s/2,a=7*this.scale;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){e+=this.x,t+=this.y;let i=this.renderer.resources,a=s.textBaseline;s.textBaseline=C.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 Jn extends Ui{constructor(e,t,s,i){super(e,t,1,pn.getSymbol(i)),this._isVisibleRest=s,this._duration=i}doLayout(){this._isVisibleRest?this.width=pn.getSize(this._duration)*this.scale:this.width=10*this.scale}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 jn extends Ka{constructor(){super(...arguments),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 e=this.renderer;if(this.container.beat.isRest){let t=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),s=e.getTabY(t);const i=new Jn(0,s,e.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&&e.showRests){this.addGlyph(new Bn(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new tn(0,s,1.5*this.scale))}}else{let t=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==g.None;const s=new qn(0,0,t);this.noteNumbers=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper;for(let e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);if(this.addGlyph(s),this.container.beat.hasWhammyBar){let e=new _n(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!this.noteNumbers.beatEffects.has("tremolo")){let e=0,t=this.container.beat.tremoloSpeed;switch(t){case u.ThirtySecond:e=10;break;case u.Sixteenth:e=5;break;case u.Eighth:e=0}this.noteNumbers.beatEffects.set("tremolo",new dn(5*this.scale,e*this.scale,t))}if(this.container.beat.dots>0&&e.settings.notation.rhythmMode!==w.Hidden){this.addGlyph(new Bn(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++)this.addGlyph(new tn(0,e.lineOffset*e.bar.staff.tuning.length+e.settings.notation.rhythmHeight*e.scale,1.5*this.scale))}}if(!this.glyphs)return;let t=0;for(let e=0,s=this.glyphs.length;e<s;e++){let s=this.glyphs[e];s.x=t,s.renderer=this.renderer,s.doLayout(),t+=s.width}this.width=t,this.computedWidth=t,this.container.beat.isEmpty?this.centerX=this.width/2:this.container.beat.isRest?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.centerX=this.noteNumbers.x+this.noteNumbers.noteStringWidth/2}updateBeamingHelper(){this.container.beat.isRest?this.restGlyph.updateBeamingHelper(this.container.x+this.x):this.noteNumbers.updateBeamingHelper(this.container.x+this.x)}createNoteGlyph(e){let t=this.renderer,s=new Yn(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 Qn extends Wi{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10*this.scale}paint(e,t,s){let i=this.renderer,a=t+this.x+i.getNoteY(this._beat.maxStringNote,je.Top),r=t+this.y+i.getNoteY(this._beat.minStringNote,je.Bottom),n=e+this.x+this.width/2|0,o=8*this.scale;if(this._beat.brushType!==c.None){if(this._beat.brushType===c.BrushUp||this._beat.brushType===c.BrushDown)s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke();else if(this._beat.brushType===c.ArpeggioUp){let t=new Fr(0,0,_.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let i=a,n=r-o;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4*this.scale,n,-90),t.paint(0,-t.height/2,s),s.endRotate()}else if(this._beat.brushType===c.ArpeggioDown){let t=new Fr(0,0,_.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let i=a+o,n=r;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4*this.scale,i,90),t.paint(0,-t.height/2,s),s.endRotate()}this._beat.brushType===c.BrushUp||this._beat.brushType===c.ArpeggioUp?(s.beginPath(),s.moveTo(n,r),s.lineTo(n+o/2,r-o),s.lineTo(n-o/2,r-o),s.closePath(),s.fill()):(s.beginPath(),s.moveTo(n,a),s.lineTo(n+o/2,a+o),s.lineTo(n-o/2,a+o),s.closePath(),s.fill())}}}class $n extends $a{doLayout(){this.container.beat.brushType===c.None||this.container.beat.isRest||(this.addGlyph(new Qn(this.container.beat)),this.addGlyph(new Bn(0,0,4*this.scale))),super.doLayout()}constructor(){super()}}class Kn extends Wi{constructor(e,t){super(e,t)}doLayout(){this.width=28*this.scale}paint(e,t,s){let i=this.renderer.bar.staff.tuning.length,a=i<=4?N.FourStringTabClef:N.SixStringTabClef,r=i<=4?i/4.5:i/6.5;s.fillMusicFontSymbol(e+this.x+5*this.scale,t+this.y,r*this.scale,a,!1)}}class Zn extends Ln{get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?Xi.GraceScale:1}}class eo extends Ya{constructor(e,t){super(e,t),this._firstLineY=0,this._tupletSize=0,this.showTimeSignature=!1,this.showRests=!1,this.showTiedNotes=!1,this._startSpacing=!1}get lineOffset(){return(eo.TabLineSpacing+1)*this.scale}updateSizes(){let e=this.resources,t=(e.tablatureFont.size/2+.2*e.tablatureFont.size)*this.scale;this.topPadding=t,this.bottomPadding=t,this.height=this.lineOffset*(this.bar.staff.tuning.length-1)+2*t,this.settings.notation.rhythmMode!==w.Hidden&&(this.height+=this.settings.notation.rhythmHeight*this.settings.display.scale,this.bottomPadding+=this.settings.notation.rhythmHeight*this.settings.display.scale),this.updateFirstLineY(),super.updateSizes()}updateFirstLineY(){let e=this.resources;this._firstLineY=(e.tablatureFont.size/2+.2*e.tablatureFont.size)*this.scale}doLayout(){if(this.updateFirstLineY(),super.doLayout(),this.settings.notation.rhythmMode!==w.Hidden){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._tupletSize=.8*this.resources.effectFont.size,this.registerOverflowBottom(this._tupletSize))}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Zr(0,0,1.5,3)),this.isFirstOfLine){let e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new Kn(5*this.scale,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.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new Jr(0,this.getTabHeight(-.5),this.bar.index+1))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new Bn(0,0,2*this.scale)),this._startSpacing=!0)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Bn(0,0,5*this.scale));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new Zn(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,s=e.beats.length;t<s;t++){let s=e.beats[t],i=new Xn(s,this.getVoiceContainer(e));i.preNotes=new $n,i.onNotes=new jn,this.addBeatGlyph(i)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new $r(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Kr(0,this.getTabY(-1),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new jr(0,0))}getTabY(e){return this._firstLineY+this.getTabHeight(e)}getTabHeight(e){return this.lineOffset*e}get middleYPosition(){return this.getTabY(this.bar.staff.tuning.length-1)}paintBackground(e,t,s){super.paintBackground(e,t,s);let i=this.resources;s.color=i.staffLineColor;let a=this.scale,r=[];for(let e=0,t=this.bar.staff.tuning.length;e<t;e++)r.push([]);for(let e of this.bar.voices)if(this.hasVoiceContainer(e)){let t=this.getVoiceContainer(e);for(let e of t.beatGlyphs){let s=e.onNotes,i=s.noteNumbers;if(i)for(const[n,o]of i.notesPerString)o.isEmpty||r[this.bar.staff.tuning.length-n].push(new Float32Array([t.x+e.x+s.x+i.x,i.width+a]))}}for(let e of r)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));for(let i=0,a=this.bar.staff.tuning.length;i<a;i++){const a=this.getTabY(i);let n=0;for(let o of r[i])s.fillRect(e+this.x+n,t+this.y+a|0,o[0]-n,this.scale*Ya.StaffLineThickness),n=o[0]+o[1];s.fillRect(e+this.x+n,t+this.y+a|0,this.width-n,this.scale*Ya.StaffLineThickness)}s.color=i.mainGlyphColor,this.paintSimileMark(e,t,s)}paint(e,t,s){super.paint(e,t,s),this.settings.notation.rhythmMode!==w.Hidden&&(this.paintBeams(e,t,s),this.paintTuplets(e,t,s))}paintBeams(e,t,s){for(let i=0,a=this.helpers.beamHelpers.length;i<a;i++){let a=this.helpers.beamHelpers[i];for(let i=0,r=a.length;i<r;i++){let r=a[i];this.paintBeamHelper(e+this.beatGlyphsStart,t,s,r)}}}paintTuplets(e,t,s){for(let i of this.bar.voices)if(this.hasVoiceContainer(i)){let a=this.getVoiceContainer(i);for(let i of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,i)}}paintBeamHelper(e,t,s,i){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(1===i.beats.length||this.settings.notation.rhythmMode===w.ShowWithBeams?this.paintFooter(e,t,s,i):this.paintBar(e,t,s,i))}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)){let n=i.getBeatLineX(r),o=t+this.y,h=t+this.y+this.height-this._tupletSize,l=this.getOnNotesGlyphForBeat(r);l.noteNumbers&&r.duration!==u.Half?o+=l.noteNumbers.getNoteY(l.noteNumbers.minStringNote,je.Bottom)+this.lineOffset/2:o+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(r,t+this.y,e+this.x+n,o,h,s);let c=6*this.scale,d=-6*this.scale,p=3*this.scale,g=j.getIndex(r.duration)-2,f=h;for(let t=0;t<g;t++){let o=0,h=0,l=0,u=0,g=f+t*d;if(1===i.beats.length)o=n,h=n+c,l=g,u=g,eo.paintSingleBar(s,e+this.x+o,l,e+this.x+h,u,p);else if(a<i.beats.length-1){if(xa.isFullBarJoin(r,i.beats[a+1],t))o=n,h=i.getBeatLineX(i.beats[a+1]);else{if(0!==a&&xa.isFullBarJoin(i.beats[a-1],r,t))continue;o=n,h=o+c}l=g,u=g,eo.paintSingleBar(s,e+this.x+o,l,e+this.x+h,u,p)}else a>0&&!xa.isFullBarJoin(r,i.beats[a-1],t)&&(o=n-c,h=n,l=g,u=g,eo.paintSingleBar(s,e+this.x+o,l,e+this.x+h,u,p))}}}}paintTupletHelper(e,t,s,i){let a,r=this.resources,n=s.textAlign,o=s.textBaseline;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=P.Center,s.textBaseline=C.Middle;let h=i.beats[0].tupletNumerator,l=i.beats[0].tupletDenominator;if(a=2===h&&3===l?"2":3===h&&2===l?"3":4===h&&6===l?"4":5===h&&4===l?"5":6===h&&4===l?"6":7===h&&4===l?"7":9===h&&8===l?"9":10===h&&8===l?"10":11===h&&8===l?"11":12===h&&8===l?"12":13===h&&8===l?"13":h+":"+l,1!==i.beats.length&&i.isFull){let n=i.beats[0],o=i.beats[i.beats.length-1],h=this.helpers.beamHelperLookup[i.voice.index].get(n.index),l=this.helpers.beamHelperLookup[i.voice.index].get(o.index);if(h&&l){let i=h.getBeatLineX(n),c=l.getBeatLineX(o);s.font=r.effectFont;let d=s.measureText(a),u=3*this.scale,p=(i+c)/2,g=p-d/2-u,f=p+d/2+u,m=t+this.y+this.height-this._tupletSize+.5*r.effectFont.size,y=.25*-r.effectFont.size,b=-5*this.scale;s.beginPath(),s.moveTo(e+this.x+i,m-y|0),s.lineTo(e+this.x+i,m-y-b|0),s.lineTo(e+this.x+g,m-y-b|0),s.stroke(),s.beginPath(),s.moveTo(e+this.x+f,m-y-b|0),s.lineTo(e+this.x+c,m-y-b|0),s.lineTo(e+this.x+c,m-y|0),s.stroke(),s.fillText(a,e+this.x+p,m-y-b)}}else for(let n=0,o=i.beats.length;n<o;n++){let o=i.beats[n],h=this.helpers.beamHelperLookup[i.voice.index].get(o.index);if(!h)continue;let l=h.getBeatLineX(o),c=t+this.y+this.height-this._tupletSize+.5*r.effectFont.size;s.font=r.effectFont,s.fillText(a,e+this.x+l,c)}s.textAlign=n,s.textBaseline=o}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()}paintBeamingStem(e,t,s,i,a,r){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()}paintFooter(e,t,s,i){for(let a of i.beats){if(a.graceType!==g.None||a.duration===u.Whole||a.duration===u.DoubleWhole||a.duration===u.QuadrupleWhole)return;let r=i.getBeatLineX(a),n=t+this.y,o=t+this.y+this.height-this._tupletSize,h=this.getOnNotesGlyphForBeat(a);if(h.noteNumbers&&a.duration!==u.Half?n+=h.noteNumbers.getNoteY(h.noteNumbers.minStringNote,je.Bottom):n+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(a,t+this.y,e+this.x+r,n,o,s),a.duration>u.Quarter){let t=new Yi(0,0,a.duration,Ce.Down,!1);t.renderer=this,t.doLayout(),t.paint(e+this.x+r,o,s)}}}}eo.StaffId="tab",eo.TabLineSpacing=10;class to extends ba{get staffId(){return eo.StaffId}constructor(e,t,s){super(),this._showTimeSignature=e,this._showRests=t,this._showTiedNotes=s,this.hideOnPercussionTrack=!0}canCreate(e,t){return t.tuning.length>0&&super.canCreate(e,t)}create(e,t){let s=new eo(e,t);return s.showRests=this._showRests,s.showTimeSignature=this._showTimeSignature,s.showTiedNotes=this._showTiedNotes,s}}class so extends zi{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+so.Padding*this.scale}paint(e,t,s){let i=this.renderer.resources;s.font=i.effectFont;let a=s.textAlign;s.textAlign=P.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+(so.Padding-1)*this.scale,s.font.size/1.6)}}so.Padding=4;class io extends mr{get notationElement(){return k.EffectTap}get sizingMode(){return $e.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new so}}class ao{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"}(Ze||(Ze={}));class ro extends ao{constructor(){super(...arguments),this.align=P.Left,this.frame=Ze.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class no extends ao{constructor(){super(...arguments),this.chord=new oe}}class oo extends ao{}class ho extends ao{}class lo extends ao{constructor(){super(...arguments),this.number=0}}class co extends ao{constructor(){super(...arguments),this.decrescendo=!1}}class uo extends ao{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class po extends ao{constructor(){super(...arguments),this.octave=1}}class go extends ao{}class fo{constructor(){this.defaultClef=r.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class mo{constructor(){this.from=0,this.to=0,this.curly=!1}}class yo{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class bo{constructor(){this._trackChannel=0,this._beamingMode=F.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new le,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 ut;try{s.parse(e)}catch(e){throw new G("Could not parse XML",e)}this.parseDom(s),this.consolidate(),this.score.finish(t)}consolidate(){let e=this.score.tempo;for(const t of this.score.tracks){const s=this._voiceCounts.get(t.index);for(const i of t.staves){for(;i.bars.length<this.score.masterBars.length;)this.addNewBar(i);for(const t of i.bars){for(;t.voices.length<s;)t.addVoice(new _e);for(const e of t.voices)if(0===e.beats.length){const t=new ne;t.isEmpty=!0,e.addBeat(t)}const i=t.masterBar;i.tempoAutomation&&(i.tempoAutomation.value!==e?e=i.tempoAutomation.value:i.tempoAutomation=null)}}}bo.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),bo.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?d.Decrescendo:d.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 G("No valid XML");if("score"!==t.localName)throw new G('Root node of XML was not "score"');this.score=new ue,this.score.tempo=120;for(let e of t.childNodes)if(e.nodeType===Ne.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===Ne.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 Se,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===Ne.Element&&"bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new mo;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===Ne.Element&&"staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new fo;t.description=e.getAttribute("description");for(let s of e.childNodes)if(s.nodeType===Ne.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 r.G2;case"bass":return r.F4;case"alto":case"tenor":return r.C4}return r.G2}parseClefOttava(e){return e.endsWith("-")?n._8vb:e.endsWith("+")?n._8va:n.Regular}parseSystems(e){for(let t of e.childNodes)if(t.nodeType===Ne.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=F.ForceSplitToNext);for(let t of e.childNodes)if(t.nodeType===Ne.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===Ne.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===Ne.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===Ne.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 H;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 le;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,r,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 yo,this._currentVoiceState.currentBarIndex=r-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=Ce.Up;break;case"down":this._currentVoiceState.voiceStemDir=Ce.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const h=n.findChildElement("noteObjects");if(s.attributes.has("tempo")&&(this._currentBar.masterBar.tempoAutomation=new V,this._currentBar.masterBar.tempoAutomation.isLinear=!0,this._currentBar.masterBar.tempoAutomation.type=a.Tempo,this._currentBar.masterBar.tempoAutomation.value=parseInt(s.attributes.get("tempo"))),h)for(let e of h.childNodes)if(e.nodeType===Ne.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 ne;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 _e);(!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 Z;for(let a of t.childNodes)if(a.nodeType===Ne.Element)switch(a.localName){case"stem":switch(a.getAttribute("dir")){case"up":e.preferredBeamDirection=Ce.Up;break;case"down":e.preferredBeamDirection=Ce.Down}break;case"articulation":switch(a.getAttribute("type")){case"staccato":s.isStaccato=!0;break;case"normalAccent":s.accentuated=i.Normal;break;case"strongAccent":s.accentuated=i.Heavy}break;case"lyric":this.parseLyric(e,a);break;case"drawObjects":this.parseBeatDrawObject(e,a);break;case"heads":this.parseHeads(e,s,a);break;case"beam":switch(a.getAttribute("group")){case"force":e.beamingMode=F.ForceMergeWithNext;break;case"divide":e.beamingMode=F.ForceSplitToNext}}}parseHeads(e,t,s){for(let i of s.childNodes)if(i.nodeType===Ne.Element&&"head"===i.localName)this.parseHead(e,t,i)}parseHead(e,t,s){const i=new Z,a=j.parseTuning(s.getAttribute("pitch"));i.octave=a.octave-1,i.tone=a.noteValue,i.isStaccato=t.isStaccato,i.accentuated=t.accentuated,e.addNote(i);for(let e of s.childNodes)if(e.nodeType===Ne.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===Ne.Element&&"drawObj"===s.localName){const t=this.parseDrawObj(s);if(t)if(t instanceof ro)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new ot,e.fermata.type=xe.Medium):"f"===t.text?e.dynamics=p.F:"j"===t.text&&(e.dynamics=p.MF):this._isFirstSystem&&""===this.score.title&&t.align===P.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===P.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===P.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof no);else if(t instanceof ho)e.vibrato=_.Slight;else if(t instanceof co)e.crescendo=t.decrescendo?d.Decrescendo:d.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof oo){const s=t;this._slurs.set(e,s)}else t instanceof uo&&this.applyVolta(t)}}parseBarDrawObject(e){for(let t of e.childNodes)if(t.nodeType===Ne.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof uo&&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===Ne.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 ne;return s.beamingMode=this._beamingMode,this.parseDuration(e,s,t),s}if(1===parseInt(s)){let e=new ne;return e.beamingMode=this._beamingMode,e.duration=u.Whole,e}return q.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return u.DoubleWhole;case"1/1":return u.Whole;case"1/2":return u.Half;case"1/4":return u.Quarter;case"1/8":return u.Eighth;case"1/16":return u.Sixteenth;case"1/32":return u.ThirtySecond;case"1/64":return u.SixtyFourth;case"1/128":return u.OneHundredTwentyEighth;default:return q.warning("Importer","Unsupported duration"),u.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===Ne.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof ro)switch(e.align){case P.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case P.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(let t of e.childNodes)if(t.nodeType===Ne.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===Ne.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 go}parseOctaveClef(e){const t=new po;return e.attributes.has("octave")&&(t.octave=parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new uo;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 co;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new lo;return e.attributes.has("number")&&(t.number=parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new ho}parseSlur(e){return new oo}parseGuitar(e){const t=new no,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 ro;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=P.Left;break;case"center":t.align=P.Center;break;case"right":t.align=P.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=Ze.Rectangle;break;case"ellipse":t.frame=Ze.Ellipse;break;case"circle":t.frame=Ze.Circle;break;case"none":t.frame=Ze.None}if(e.firstElement){for(let s of e.childNodes)if(s.nodeType===Ne.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===Ne.Element)switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class So extends R{get name(){return"Capella"}constructor(){super()}readScore(){q.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new Nt(this.data).read(),q.debug(this.name,"Zip entries loaded"),e.length>0){for(let s of e)if("score.xml"===s.fileName)t=Be.toString(s.data,this.settings.importer.encoding)}else this.data.reset(),t=Be.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new G("No valid capella file");q.debug(this.name,"Start Parsing score.xml");try{let e=new bo;return e.parseXml(t,this.settings),q.debug(this.name,"score.xml parsed"),e.score}catch(e){throw new G("Failed to parse CapXML",e)}}}class _o{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 wo{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 Bo(e,t,s){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var i;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]}if("function"!=typeof i)throw new TypeError("Object not disposable.");e.stack.push({value:t,dispose:i,async:s})}else s&&e.stack.push({async:!0});return t}var To="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 ko(e){function t(t){e.error=e.hasError?new To(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}return function s(){for(;e.stack.length;){var i=e.stack.pop();try{var a=i.dispose&&i.dispose.call(i.value);if(i.async)return Promise.resolve(a).then(s,(function(e){return t(e),s()}))}catch(e){t(e)}}if(e.hasError)throw e.error}()}class vo{static enable(e,t){vo.alphaSkia=t,vo.initializeMusicFont(vo.alphaSkia.AlphaSkiaTypeface.register(e))}static initializeMusicFont(e){vo.musicFont=e}static registerFont(e,t){const s=vo.alphaSkia.AlphaSkiaTypeface.register(e.buffer);t||(t=As.withFamilyList([s.familyName],12,s.isItalic?Ge.Italic:Ge.Plain,s.isBold?Ve.Bold:Ve.Regular));for(const e of t.families)this.customTypeFaces.set(vo.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.settings.display.scale)){if(this._typeFaceIsSystem){const e={stack:[],error:void 0,hasError:!1};try{Bo(e,this._typeFace,!1)}catch(t){e.error=t,e.hasError=!0}finally{ko(e)}}for(const t of this.font.families){var e=vo.customTypefaceKey(t,this.font.isBold,this.font.isItalic);vo.customTypeFaces.has(e)?(this._typeFaceIsSystem=!1,this._typeFace=vo.customTypeFaces.get(e)):(this._typeFaceIsSystem=!0,this._typeFace=vo.alphaSkia.AlphaSkiaTypeface.create(t,this.font.isBold,this.font.isItalic))}this._typeFaceCache=this.font.toCssString(this.settings.display.scale)}return this._typeFace}constructor(){this._color=new fe(0,0,0,0),this._lineWidth=0,this._typeFaceCache="",this._typeFaceIsSystem=!1,this._typeFace=null,this.font=new As("Arial",10,Ge.Plain),this.textAlign=P.Left,this.textBaseline=C.Top,this._canvas=new vo.alphaSkia.AlphaSkiaCanvas,this.color=new fe(0,0,0,255)}destroy(){const e={stack:[],error:void 0,hasError:!1};try{Bo(e,this._canvas,!1)}catch(t){e.error=t,e.hasError=!0}finally{ko(e)}}onRenderFinished(){return null}beginRender(e,t){this._canvas.beginRender(e,t,Po.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=vo.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(0|e,0|t,s,i)}strokeRect(e,t,s,i){this._canvas.strokeRect(0|e,0|t,s,i)}beginPath(){this._canvas.beginPath()}closePath(){this._canvas.closePath()}moveTo(e,t){this._canvas.moveTo(e,t)}lineTo(e,t){this._canvas.lineTo(e,t)}quadraticCurveTo(e,t,s,i){this._canvas.quadraticCurveTo(e,t,s,i)}bezierCurveTo(e,t,s,i,a,r){this._canvas.bezierCurveTo(e,t,s,i,a,r)}fillCircle(e,t,s){this._canvas.fillCircle(e,t,s)}strokeCircle(e,t,s){this._canvas.strokeCircle(e,t,s)}fill(){this._canvas.fill()}stroke(){this._canvas.stroke()}beginGroup(e){}endGroup(){}fillText(e,t,s){if(0==e.length)return;let i=vo.alphaSkia.AlphaSkiaTextAlign.Left;switch(this.textAlign){case P.Left:i=vo.alphaSkia.AlphaSkiaTextAlign.Left;break;case P.Center:i=vo.alphaSkia.AlphaSkiaTextAlign.Center;break;case P.Right:i=vo.alphaSkia.AlphaSkiaTextAlign.Right}let a=vo.alphaSkia.AlphaSkiaTextBaseline.Top;switch(this.textBaseline){case C.Top:a=vo.alphaSkia.AlphaSkiaTextBaseline.Top;break;case C.Middle:a=vo.alphaSkia.AlphaSkiaTextBaseline.Middle;break;case C.Bottom:a=vo.alphaSkia.AlphaSkiaTextBaseline.Bottom}this._canvas.fillText(e,this.getTypeFace(),this.font.size*this.settings.display.scale,t,s,i,a)}measureText(e){return this._canvas.measureText(e,this.getTypeFace(),this.font.size*this.settings.display.scale)}fillMusicFontSymbol(e,t,s,i,a){i!==N.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(let e of i)e!==N.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){this._canvas.fillText(i,vo.musicFont,Po.MusicFontSize*this.settings.display.scale*s,e,t,a?vo.alphaSkia.AlphaSkiaTextAlign.Center:vo.alphaSkia.AlphaSkiaTextAlign.Left,vo.alphaSkia.AlphaSkiaTextBaseline.Alphabetic)}beginRotate(e,t,s){this._canvas.beginRotate(e,t,s)}endRotate(){this._canvas.endRotate()}}vo.musicFont=null,vo.customTypeFaces=new Map;class xo{constructor(e,t){this.vertical=e,this.createLayout=t}}class No{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class Po{static createStyleElement(e,t){let s=e.getElementById("alphaTabStyle");if(!s){if(!t)return void q.error("AlphaTab","Font directory could not be detected, cannot create style element");s=e.createElement("style"),s.id="alphaTabStyle";let i=`\n @font-face {\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 } \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: ${Po.MusicFontSize}px;\n overflow: visible !important;\n }`;s.innerHTML=i,e.getElementsByTagName("head").item(0).appendChild(s),Po.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===Po._globalThis){try{Po._globalThis=globalThis}catch(e){}void 0===Po._globalThis&&(Po._globalThis=self),void 0===Po._globalThis&&(Po._globalThis=global),void 0===Po._globalThis&&(Po._globalThis=window),void 0===Po._globalThis&&(Po._globalThis=Function("return this")())}return this._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in Po.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in Po.globalThis}static throttle(e,t){let s=0;return()=>{Po.globalThis.clearTimeout(s),s=Po.globalThis.setTimeout(e,t)}}static detectScriptFile(){if(!Po.isRunningInWorker&&Po.globalThis.ALPHATAB_ROOT){let e=Po.globalThis.ALPHATAB_ROOT;return e=Po.ensureFullUrl(e),e=Po.appendScriptName(e),e}try{const e=import.meta.url;if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in Po.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=Po.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(!Po.isRunningInWorker&&Po.globalThis.ALPHATAB_FONT)return Po.ensureFullUrl(Po.globalThis.ALPHATAB_FONT);const e=Po.scriptFile;if(e){let t=e.lastIndexOf(String.fromCharCode(47));if(t>=0)return e.substr(0,t)+"/font/"}return null}static registerJQueryPlugin(){if(!Po.isRunningInWorker&&Po.globalThis&&"jQuery"in Po.globalThis){let e=Po.globalThis.jQuery,t=new fa;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:fa.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&Po.renderEngines.has(e)?Po.renderEngines.get(e):Po.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&Po.layoutEngines.has(t)?Po.layoutEngines.get(t):Po.layoutEngines.get(e.Page)}static buildImporters(){return[new st,new Mt,new Pt,new It,new So,new tt]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new No(!0,(()=>new ya))),e.set("default",e.get("svg")),e.set("skia",new No(!1,(()=>new vo))),Po.createPlatformSpecificRenderEngines(e),e}static enableAlphaSkia(e,t){vo.enable(e,t)}static registerAlphaSkiaCustomFont(e,t){return vo.registerFont(e,t)}static createPlatformSpecificRenderEngines(e){e.set("html5",new No(!1,(()=>new Ci)))}static createDefaultStaveProfiles(){const e=new Map;e.set(t.ScoreTab,[new er("score-effects",[new Dr,new Vr,new Br,new Ar,new rr,new gr,new Hr,new Or,new kr(!0),new Wr,new Er,new zr,new Lr,new io,new ir]),new Hn,new er("tab-effects",[new hr,new kr(!1),new cr,new wr,new Or,new Wr,new Er,new zr,new Lr,new Mr,new ur,new br(m.Natural),new br(m.Artificial),new br(m.Pinch),new br(m.Tap),new br(m.Semi),new br(m.Feedback),new Sr,new ar,new fr,new vr,new Pr,new xr,new io]),new to(!1,!1,!1)]),e.set(t.Score,[new er("score-effects",[new Dr,new Vr,new Br,new Ar,new rr,new gr,new Hr,new Or,new kr(!0),new Wr,new Er,new zr,new Lr,new ur,new Sr,new vr,new Pr,new xr,new io,new ir]),new Hn,new er("score-bottom-effects",[new hr,new kr(!1),new cr,new wr])]);let s=[new Dr,new Vr,new Br,new Ar,new rr,new gr,new Or,new Wr,new Er,new zr,new Lr,new Mr,new ur,new br(m.Artificial),new br(m.Pinch),new br(m.Tap),new br(m.Semi),new br(m.Feedback),new Sr,new ar,new fr,new vr,new Pr,new xr,new io,new ir];return e.set(t.Tab,[new er("tab-effects",s),new to(!0,!0,!0),new er("tab-bottom-effects",[new wr])]),e.set(t.TabMixed,[new er("tab-effects",s),new to(!1,!1,!1),new er("tab-bottom-effects",[new wr])]),e}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.Page,new xo(!0,(e=>new Yr(e)))),t.set(e.Horizontal,new xo(!1,(e=>new Xr(e)))),t}static initializeMain(e,t){Po.isRunningInWorker||Po.isRunningInAudioWorklet||(Po.webPlatform!==Ue.Browser&&Po.webPlatform!==Ue.BrowserModule||(Po.registerJQueryPlugin(),Po.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in Po.globalThis||(Po.globalThis.ResizeObserver=_o),"IntersectionObserver"in Po.globalThis||(Po.globalThis.IntersectionObserver=wo),"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)})),Po.createWebWorker=e,Po.createAudioWorklet=t)}static get alphaTabWorker(){return this.globalThis.Worker}static initializeWorker(){if(!Po.isRunningInWorker)throw new O(s.General,"Not running in worker, cannot run worker initialization");Pi.init(),bi.init(),Po.createWebWorker=e=>{throw new O(s.General,"Nested workers are not supported")}}static initializeAudioWorklet(){if(!Po.isRunningInAudioWorklet)throw new O(s.General,"Not running in audio worklet, cannot run worklet initialization");ca.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 Ue.NodeJs}catch(e){}try{const e=import.meta.url;if(e&&"string"==typeof e&&!e.startsWith("file://"))return Ue.BrowserModule}catch(e){}return Ue.Browser}}Po.MusicFontSize=34,Po.HighDpiFactor=1,Po._globalThis=void 0,Po.webPlatform=Po.detectWebPlatform(),Po.isWebPackBundled=Po.detectWebPack(),Po.isViteBundled=Po.detectVite(),Po.scriptFile=Po.detectScriptFile(),Po.fontDirectory=Po.detectFontDirectory(),Po.bravuraFontChecker=new sa(["alphaTab"]),Po.renderEngines=Po.createDefaultRenderEngines(),Po.layoutEngines=Po.createDefaultLayoutEngines(),Po.staveProfiles=Po.createDefaultStaveProfiles();class Co{constructor(){this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=v.Info,this.useWorkers=!0,this.includeNoteBounds=!1,this.scriptFile=Po.scriptFile,this.fontDirectory=Po.fontDirectory}}class Eo{}Eo.version="1.3.1",Eo.date="2024-06-15T16:02:03.898Z";var Fo,Lo=Object.freeze({__proto__:null,ScoreImporter:R,ScoreLoader:Zi,UnsupportedFormatError:G});class Mo{init(e,t){this.data=e,this.settings=t}export(e,t=null){const s=Te.withCapacity(1024);return this.init(s,t??new Ks),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"}(Fo||(Fo={}));class Io{constructor(e,t,s=null){if(this.icon=Fo.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 Do{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new ut;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 a=0;switch(t.isStaccato&&(a|=1),t.accentuated){case i.Normal:a|=8;break;case i.Heavy:a|=4}if(a>0&&(s.addElement("Accent").innerText=a.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 _.Slight:s.addElement("Vibrato").innerText="Slight";break;case _.Wide:s.addElement("Vibrato").innerText="Wide"}if(t.isFingering){switch(t.leftHandFinger){case f.Thumb:s.addElement("LeftFingering").innerText="P";break;case f.IndexFinger:s.addElement("LeftFingering").innerText="I";break;case f.MiddleFinger:s.addElement("LeftFingering").innerText="M";break;case f.AnnularFinger:s.addElement("LeftFingering").innerText="A";break;case f.LittleFinger:s.addElement("LeftFingering").innerText="C"}switch(t.rightHandFinger){case f.Thumb:s.addElement("RightFingering").innerText="P";break;case f.IndexFinger:s.addElement("RightFingering").innerText="I";break;case f.MiddleFinger:s.addElement("RightFingering").innerText="M";break;case f.AnnularFinger:s.addElement("RightFingering").innerText="A";break;case f.LittleFinger:s.addElement("RightFingering").innerText="C"}}t.percussionArticulation>=0?s.addElement("InstrumentArticulation").innerText=t.percussionArticulation.toString():s.addElement("InstrumentArticulation").innerText="0"}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.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!==m.None){switch(t.harmonicType){case m.Natural:this.writeSimplePropertyNode(s,"HarmonicType","HType","Natural");break;case m.Artificial:this.writeSimplePropertyNode(s,"HarmonicType","HType","Artificial");break;case m.Pinch:this.writeSimplePropertyNode(s,"HarmonicType","HType","Pinch");break;case m.Tap:this.writeSimplePropertyNode(s,"HarmonicType","HType","Tap");break;case m.Semi:this.writeSimplePropertyNode(s,"HarmonicType","HType","Semi");break;case m.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 b.IntoFromAbove:i|=32;break;case b.IntoFromBelow:i|=16}switch(t.slideOutType){case S.Shift:i|=1;break;case S.Legato:i|=2;break;case S.OutDown:i|=4;break;case S.OutUp:i|=8;break;case S.PickSlideDown:i|=64;break;case S.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=ye.defaultSteps[a],o=ye.defaultAccidentals[a]};switch(h(),i){case y.Default:break;case y.ForceNone:case y.ForceNatural:o="";break;case y.ForceSharp:o="#";break;case y.ForceDoubleSharp:"#"===o&&(s-=2,h()),o="x";break;case y.ForceFlat:"#"===o&&(s+=1,h()),o="b";break;case y.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 z((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/z.MaxPosition*100}writeBeatNode(e,t,s){const i=e.addElement("Beat");if(i.attributes.set("id",t.id.toString()),i.addElement("Dynamic").innerText=p[t.dynamics],t.fadeIn&&(i.addElement("Fadding").innerText="FadeIn"),t.isTremolo)switch(t.tremoloSpeed){case u.Eighth:i.addElement("Tremolo").innerText="1/2";break;case u.Sixteenth:i.addElement("Tremolo").innerText="1/4";break;case u.ThirtySecond:i.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&i.addElement("Chord").setCData(t.chordId),t.crescendo!==d.None&&(i.addElement("Hairpin").innerText=d[t.crescendo]),t.brushType){case c.ArpeggioUp:i.addElement("Arpeggio").innerText="Up";break;case c.ArpeggioDown:i.addElement("Arpeggio").innerText="Down"}switch(t.text&&i.addElement("FreeText").setCData(t.text),t.graceType){case g.OnBeat:case g.BeforeBeat:i.addElement("GraceNotes").innerText=g[t.graceType]}if(t.ottava!==n.Regular&&(i.addElement("Ottavia").innerText=n[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 Ce.Up:i.addElement("TransposedPitchStemOrientation").innerText="Upward";break;case Ce.Down:i.addElement("TransposedPitchStemOrientation").innerText="Downward"}i.addElement("ConcertPitchStemOrientation").innerText="Undefined",t.isRest||(i.addElement("Notes").innerText=t.notes.map((e=>e.id)).join(" ")),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");t.brushDuration>0&&this.writeSimpleXPropertyNode(s,"687935489","Int",t.brushDuration.toString())}writeBeatProperties(e,t){const s=e.addElement("Properties");switch(t.brushType){case c.BrushUp:this.writeSimplePropertyNode(s,"Brush","Direction","Up");break;case c.BrushDown:this.writeSimplePropertyNode(s,"Brush","Direction","Down")}switch(t.pickStroke){case x.Up:this.writeSimplePropertyNode(s,"PickStroke","Direction","Up");break;case x.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 _.Wide:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Wide");break;case _.Slight:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Slight")}}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 u.QuadrupleWhole:r="Long";break;case u.DoubleWhole:r="DoubleWhole";break;case u.Whole:r="Whole";break;case u.Half:r="Half";break;case u.Quarter:r="Quarter";break;case u.Eighth:r="Eighth";break;case u.Sixteenth:r="16th";break;case u.ThirtySecond:r="32nd";break;case u.SixtyFourth:r="64th";break;case u.OneHundredTwentyEighth:r="128th";break;case u.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 z((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");t.masterBars.length>0&&t.masterBars[0].isAnacrusis&&s.addElement("Anacrusis");const a=i.addElement("Automation");a.addElement("Type").innerText="Tempo",a.addElement("Linear").innerText="false",a.addElement("Bar").innerText="0",a.addElement("Position").innerText="0",a.addElement("Visible").innerText="true",a.addElement("Value").innerText=`${t.tempo} 2`,t.tempoLabel&&(a.addElement("Text").innerText=t.tempoLabel);for(const e of t.masterBars)if(e.index>0&&e.tempoAutomation){const t=i.addElement("Automation");t.addElement("Type").innerText="Tempo",t.addElement("Linear").innerText=e.tempoAutomation.isLinear?"true":"false",t.addElement("Bar").innerText=e.index.toString(),t.addElement("Position").innerText=e.tempoAutomation.ratioPosition.toString(),t.addElement("Visible").innerText="true",t.addElement("Value").innerText=`${e.tempoAutomation.value} 2`,e.tempoAutomation.text&&(t.addElement("Text").innerText=e.tempoAutomation.text)}}writeAudioTracksNode(e,t){e.addElement("AudioTracks")}writeTracksNode(e,t){const s=e.addElement("Tracks");for(const e of t.tracks)this.writeTrackNode(s,e)}writeTrackNode(e,t){const s=e.addElement("Track");s.attributes.set("id",t.index.toString()),s.addElement("Name").setCData(t.name),s.addElement("ShortName").setCData(t.shortName),s.addElement("Color").innerText=`${t.color.r} ${t.color.g} ${t.color.b}`,s.addElement("SystemsDefautLayout").innerText=t.defaultSystemsLayout.toString(),s.addElement("SystemsLayout").innerText=t.systemsLayout.join(" "),s.addElement("AutoBrush"),s.addElement("PalmMute").innerText="0",s.addElement("PlayingStyle").innerText=A.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",s.addElement("UseOneChannelPerString"),s.addElement("IconId").innerText=Do.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?Do.DrumKitProgramInfo.icon:Do.MidiProgramInfoLookup.has(e.program)?Do.MidiProgramInfoLookup.get(e.program).icon:Fo.SteelGuitar}writeSoundAndAutomation(e,t,s,i,a,r,n,o=0){const h=e.addElement("Sound");h.addElement("Name").setCData(s),h.addElement("Label").setCData(s),h.addElement("Path").setCData(i),h.addElement("Role").setCData(a);const l=h.addElement("MIDI");l.addElement("LSB").innerText="0",l.addElement("MSB").innerText="0",l.addElement("Program").innerText=n.toString();const c=t.addElement("Automation");c.addElement("Type").innerText="Sound",c.addElement("Linear").innerText="false",c.addElement("Bar").innerText=r.toString(),c.addElement("Position").innerText=o.toString(),c.addElement("Visible").innerText="true",c.addElement("Value").setCData(`${i};${s};${a}`)}writeSoundsAndAutomations(e,t){const s=e.addElement("Sounds"),i=e.addElement("Automations");if(t.staves.length>0&&t.staves[0].bars.length>0){const e=`Track_${t.index}_Initial`,r=`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 c of h.beats){const h=c.getAutomation(a.Instrument),d=0===l.index&&0===c.index;if(h){const a=d?e:`ProgramChange_${c.id}`,u=d?r:`Midi/${h.value}`,p=d?n:"User";d||o||(this.writeSoundAndAutomation(s,i,e,r,n,t.staves[0].bars[0].index,t.playbackInfo.program),o=!0),this.writeSoundAndAutomation(s,i,a,u,p,l.index,h.value,h.ratioPosition),d&&(o=!0)}}}}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=[f.LittleFinger,f.AnnularFinger,f.MiddleFinger,f.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():f.IndexFinger;for(const e of i){const i=o.addElement("Position");switch(a){case f.LittleFinger:i.attributes.set("finger","Pinky");break;case f.AnnularFinger:i.attributes.set("finger","Ring");break;case f.MiddleFinger:i.attributes.set("finger","Middle");break;case f.IndexFinger:i.attributes.set("finger","Index")}i.attributes.set("fret",(s-t.firstFret+1).toString()),i.attributes.set("string",e.toString())}}}}const h=i.addElement("Property");h.attributes.set("name","ShowName"),h.attributes.set("type","bool"),h.attributes.set("value",t.showName?"true":"false");const l=i.addElement("Property");l.attributes.set("name","ShowDiagram"),l.attributes.set("type","bool"),l.attributes.set("value",t.showDiagram?"true":"false");const c=i.addElement("Property");c.attributes.set("name","ShowFingering"),c.attributes.set("type","bool"),c.attributes.set("value",t.showFingering?"true":"false");const d=i.addElement("Chord"),u=d.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=d.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=d.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const m=d.addElement("Degree");m.attributes.set("interval","Fifth"),m.attributes.set("alteration","Perfect"),m.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,s,i){const a=e.addElement("Property");a.attributes.set("name",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeSimpleXPropertyNode(e,t,s,i){const a=e.addElement("XProperty");a.attributes.set("id",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeLyricsNode(e,t){const s=e.addElement("Lyrics");s.attributes.set("dispatched","true");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 he;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($.instrumentArticulations.values());s.addElement("Name").innerText=Do.DrumKitProgramInfo.instrumentSetName,s.addElement("Type").innerText=Do.DrumKitProgramInfo.instrumentSetType;let i="",r=new ht,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 C.Top:e.addElement("TechniquePlacement").innerText="below";break;case C.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case C.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=Do.MidiProgramInfoLookup.has(t.playbackInfo.program)?Do.MidiProgramInfoLookup.get(t.playbackInfo.program):Do.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===N.None)return"";let t=N[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=I[t.keySignatureType],i.addElement("Sharps").innerText="Sharps",s.addElement("Time").innerText=`${t.timeSignatureNumerator}/${t.timeSignatureDenominator}`;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(" ")}t.tripletFeel!==D.NoTripletFeel&&(s.addElement("TripletFeel").innerText=D[t.tripletFeel]),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/W.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=xe[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=r[t.clef],t.clefOttava!==n.Regular&&(s.addElement("Ottavia").innerText=n[t.clefOttava].substr(1)),t.simileMark!==o.None&&(s.addElement("SimileMark").innerText=o[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(" ")}}Do.MidiProgramInfoLookup=new Map([[0,new Io(Fo.Piano,"Acoustic Piano")],[1,new Io(Fo.Piano,"Acoustic Piano")],[2,new Io(Fo.Piano,"Electric Piano")],[3,new Io(Fo.Piano,"Acoustic Piano")],[4,new Io(Fo.Piano,"Electric Piano")],[5,new Io(Fo.Piano,"Electric Piano")],[6,new Io(Fo.Piano,"Harpsichord")],[7,new Io(Fo.Piano,"Harpsichord")],[8,new Io(Fo.PitchedIdiophone,"Celesta")],[9,new Io(Fo.PitchedIdiophone,"Vibraphone")],[10,new Io(Fo.PitchedIdiophone,"Vibraphone")],[11,new Io(Fo.PitchedIdiophone,"Vibraphone")],[12,new Io(Fo.PitchedIdiophone,"Xylophone")],[13,new Io(Fo.PitchedIdiophone,"Xylophone")],[14,new Io(Fo.PitchedIdiophone,"Vibraphone")],[15,new Io(Fo.Banjo,"Banjo")],[16,new Io(Fo.Piano,"Electric Organ")],[17,new Io(Fo.Piano,"Electric Organ")],[18,new Io(Fo.Piano,"Electric Organ")],[19,new Io(Fo.Piano,"Electric Organ")],[20,new Io(Fo.Piano,"Electric Organ")],[21,new Io(Fo.Piano,"Electric Organ")],[22,new Io(Fo.Woodwind,"Recorder")],[23,new Io(Fo.Piano,"Electric Organ")],[24,new Io(Fo.ClassicalGuitar,"Nylon Guitar")],[25,new Io(Fo.SteelGuitar,"Steel Guitar")],[26,new Io(Fo.SteelGuitar,"Electric Guitar")],[27,new Io(Fo.ElectricGuitar,"Electric Guitar")],[28,new Io(Fo.ElectricGuitar,"Electric Guitar")],[29,new Io(Fo.ElectricGuitar,"Electric Guitar")],[30,new Io(Fo.SteelGuitar,"Electric Guitar")],[31,new Io(Fo.SteelGuitar,"Electric Guitar")],[32,new Io(Fo.Bass,"Acoustic Bass")],[33,new Io(Fo.Bass,"Electric Bass")],[34,new Io(Fo.Bass,"Electric Bass")],[35,new Io(Fo.Bass,"Acoustic Bass")],[36,new Io(Fo.Bass,"Electric Bass")],[37,new Io(Fo.Bass,"Electric Bass")],[38,new Io(Fo.Synth,"Synth Bass")],[39,new Io(Fo.Synth,"Synth Bass")],[40,new Io(Fo.Strings,"Violin")],[41,new Io(Fo.Strings,"Viola")],[42,new Io(Fo.Strings,"Cello")],[43,new Io(Fo.Strings,"Contrabass")],[44,new Io(Fo.Strings,"Violin")],[45,new Io(Fo.Strings,"Violin")],[46,new Io(Fo.Piano,"Harp")],[47,new Io(Fo.Membraphone,"Timpani")],[48,new Io(Fo.Strings,"Violin")],[49,new Io(Fo.Strings,"Violin")],[50,new Io(Fo.Strings,"Violin")],[51,new Io(Fo.Strings,"Violin")],[52,new Io(Fo.Vocal,"Voice")],[53,new Io(Fo.Vocal,"Voice")],[54,new Io(Fo.Vocal,"Voice")],[55,new Io(Fo.Synth,"Pad Synthesizer")],[56,new Io(Fo.Brass,"Trumpet")],[57,new Io(Fo.Brass,"Trombone")],[58,new Io(Fo.Brass,"Tuba")],[59,new Io(Fo.Brass,"Trumpet")],[60,new Io(Fo.Brass,"French Horn")],[61,new Io(Fo.Brass,"Trumpet")],[62,new Io(Fo.Brass,"Trumpet")],[63,new Io(Fo.Brass,"Trumpet")],[64,new Io(Fo.Reed,"Saxophone")],[65,new Io(Fo.Reed,"Saxophone")],[66,new Io(Fo.Reed,"Saxophone")],[67,new Io(Fo.Reed,"Saxophone")],[68,new Io(Fo.Reed,"Oboe")],[69,new Io(Fo.Reed,"English Horn")],[70,new Io(Fo.Reed,"Bassoon")],[71,new Io(Fo.Reed,"Clarinet")],[72,new Io(Fo.Reed,"Piccolo")],[73,new Io(Fo.Woodwind,"Flute")],[74,new Io(Fo.Woodwind,"Recorder")],[75,new Io(Fo.Woodwind,"Flute")],[76,new Io(Fo.Woodwind,"Recorder")],[77,new Io(Fo.Woodwind,"Flute")],[78,new Io(Fo.Woodwind,"Recorder")],[79,new Io(Fo.Woodwind,"Flute")],[80,new Io(Fo.Synth,"Lead Synthesizer")],[81,new Io(Fo.Synth,"Lead Synthesizer")],[82,new Io(Fo.Synth,"Lead Synthesizer")],[83,new Io(Fo.Synth,"Lead Synthesizer")],[84,new Io(Fo.Synth,"Lead Synthesizer")],[85,new Io(Fo.Synth,"Lead Synthesizer")],[86,new Io(Fo.Synth,"Lead Synthesizer")],[87,new Io(Fo.Synth,"Lead Synthesizer")],[88,new Io(Fo.Synth,"Pad Synthesizer")],[89,new Io(Fo.Synth,"Pad Synthesizer")],[90,new Io(Fo.Synth,"Pad Synthesizer")],[91,new Io(Fo.Synth,"Pad Synthesizer")],[92,new Io(Fo.Synth,"Pad Synthesizer")],[93,new Io(Fo.Synth,"Pad Synthesizer")],[94,new Io(Fo.Synth,"Pad Synthesizer")],[95,new Io(Fo.Synth,"Pad Synthesizer")],[96,new Io(Fo.Fx,"Pad Synthesizer")],[97,new Io(Fo.Fx,"Pad Synthesizer")],[98,new Io(Fo.Fx,"Pad Synthesizer")],[99,new Io(Fo.Fx,"Pad Synthesizer")],[100,new Io(Fo.Fx,"Lead Synthesizer")],[101,new Io(Fo.Fx,"Lead Synthesizer")],[102,new Io(Fo.Fx,"Lead Synthesizer")],[103,new Io(Fo.Fx,"Trumpet")],[104,new Io(Fo.ElectricGuitar,"Banjo")],[105,new Io(Fo.Banjo,"Banjo")],[106,new Io(Fo.Ukulele,"Ukulele")],[107,new Io(Fo.Banjo,"Banjo")],[108,new Io(Fo.PitchedIdiophone,"Xylophone")],[109,new Io(Fo.Reed,"Bassoon")],[110,new Io(Fo.Strings,"Violin")],[111,new Io(Fo.Woodwind,"Flute")],[112,new Io(Fo.PitchedIdiophone,"Xylophone")],[113,new Io(Fo.Idiophone,"Celesta")],[114,new Io(Fo.PitchedIdiophone,"Vibraphone")],[115,new Io(Fo.Idiophone,"Xylophone")],[116,new Io(Fo.Membraphone,"Xylophone")],[117,new Io(Fo.Membraphone,"Xylophone")],[118,new Io(Fo.Membraphone,"Xylophone")],[119,new Io(Fo.Idiophone,"Celesta")],[120,new Io(Fo.Fx,"Steel Guitar")],[121,new Io(Fo.Fx,"Recorder")],[122,new Io(Fo.Fx,"Recorder")],[123,new Io(Fo.Fx,"Recorder")],[124,new Io(Fo.Fx,"Recorder")],[125,new Io(Fo.Fx,"Recorder")],[126,new Io(Fo.Fx,"Recorder")],[127,new Io(Fo.Fx,"Timpani")]]),Do.DrumKitProgramInfo=new Io(Fo.PercussionKit,"Drums","drumKit");class Ao{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=Ao.CrcInit,this.reset()}update(e,t,s){for(let i=0;i<s;i++)this._checkValue=Ao.Crc32Lookup[255&(this._checkValue^e[t+i])]^this._checkValue>>>8}reset(){this._checkValue=Ao.CrcInit}}Ao.Crc32Lookup=Ao.buildCrc32Lookup(),Ao.CrcInit=4294967295;class Ro{}Ro.MAX_WBITS=15,Ro.WSIZE=1<<Ro.MAX_WBITS,Ro.WMASK=Ro.WSIZE-1,Ro.MIN_MATCH=3,Ro.MAX_MATCH=258,Ro.DEFAULT_MEM_LEVEL=8,Ro.PENDING_BUF_SIZE=1<<Ro.DEFAULT_MEM_LEVEL+8,Ro.HASH_BITS=Ro.DEFAULT_MEM_LEVEL+7,Ro.HASH_SIZE=1<<Ro.HASH_BITS,Ro.HASH_SHIFT=(Ro.HASH_BITS+Ro.MIN_MATCH-1)/Ro.MIN_MATCH,Ro.HASH_MASK=Ro.HASH_SIZE-1,Ro.MIN_LOOKAHEAD=Ro.MAX_MATCH+Ro.MIN_MATCH+1,Ro.MAX_DIST=Ro.WSIZE-Ro.MIN_LOOKAHEAD;class Oo{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 c=t[0];i=o++,r[2*i]=e,r[2*i+1]=c;let d=Math.min(255&n[e],255&n[c]);for(l=n[e]+n[c]-d+1,n[i]=l,a=0,h=1;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*a+1;for(;h=a,h>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i}while(s>1);this.buildLength(r)}buildLength(e){this.length=new Uint8Array(this.freqs.length);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[Oo.Repeat3To6]++:i<=10?e.freqs[Oo.Repeat3To10]++:e.freqs[Oo.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]=Go.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(Oo.Repeat3To6),this.huffman.pending.writeBits(i-3,2)):i<=10?(e.writeSymbol(Oo.Repeat3To10),this.huffman.pending.writeBits(i-3,3)):(e.writeSymbol(Oo.Repeat11To138),this.huffman.pending.writeBits(i-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}Oo.Repeat3To6=16,Oo.Repeat3To10=17,Oo.Repeat11To138=18;class Go{static staticInit(){let e=0;for(;e<144;)Go.staticLCodes[e]=Go.bitReverse(48+e<<8),Go.staticLLength[e++]=8;for(;e<256;)Go.staticLCodes[e]=Go.bitReverse(256+e<<7),Go.staticLLength[e++]=9;for(;e<280;)Go.staticLCodes[e]=Go.bitReverse(-256+e<<9),Go.staticLLength[e++]=7;for(;e<Go.LITERAL_NUM;)Go.staticLCodes[e]=Go.bitReverse(-88+e<<8),Go.staticLLength[e++]=8;for(e=0;e<Go.DIST_NUM;e++)Go.staticDCodes[e]=Go.bitReverse(e<<11),Go.staticDLength[e]=5}static bitReverse(e){return Go.bit4Reverse[15&e]<<12|Go.bit4Reverse[e>>4&15]<<8|Go.bit4Reverse[e>>8&15]<<4|Go.bit4Reverse[e>>12]}constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new Oo(this,Go.LITERAL_NUM,257,15),this.distTree=new Oo(this,Go.DIST_NUM,1,15),this.blTree=new Oo(this,Go.BITLEN_NUM,4,7),this.d_buf=new Int16Array(Go.BUFSIZE),this.l_buf=new Uint8Array(Go.BUFSIZE)}isFull(){return this.last_lit>=Go.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((Go.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[Go.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[Go.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<Go.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*Go.staticLLength[e];for(let e=0;e<Go.DIST_NUM;e++)n+=this.distTree.freqs[e]*Go.staticDLength[e];r>=n&&(r=n),t>=0&&s+4<r>>3?this.flushStoredBlock(e,t,s,i):r==n?(this.pending.writeBits((Go.STATIC_TREES<<1)+(i?1:0),3),this.literalTree.setStaticCodes(Go.staticLCodes,Go.staticLLength),this.distTree.setStaticCodes(Go.staticDCodes,Go.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((Go.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[Go.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=Go.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=Go.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(Go.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;let s=Go.Lcode(t-3);this.literalTree.freqs[s]++,s>=265&&s<285&&(this.extra_bits+=Math.floor((s-261)/4));let i=Go.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}}Go.BUFSIZE=1<<Ro.DEFAULT_MEM_LEVEL+6,Go.LITERAL_NUM=286,Go.STORED_BLOCK=0,Go.STATIC_TREES=1,Go.DYN_TREES=2,Go.DIST_NUM=30,Go.staticLCodes=new Int16Array(Go.LITERAL_NUM),Go.staticLLength=new Uint8Array(Go.LITERAL_NUM),Go.staticDCodes=new Int16Array(Go.DIST_NUM),Go.staticDLength=new Uint8Array(Go.DIST_NUM),Go.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Go.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),Go.BITLEN_NUM=19,Go.EOF_SYMBOL=256,Go.staticInit();class Vo{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 Go(e),this.inputCrc=new Ao,this.window=new Uint8Array(2*Ro.WSIZE),this.head=new Int16Array(Ro.HASH_SIZE),this.prev=new Int16Array(Ro.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=Ro.MIN_MATCH-1;for(let e=0;e<Ro.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<Ro.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<Ro.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<Ro.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=Ro.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*Ro.WSIZE-Ro.MIN_LOOKAHEAD&&this.slideWindow();let e=this.matchStart,s=this.matchLen;if(this.lookahead>=Ro.MIN_MATCH){let e=this.insertString();0!=e&&this.strstart-e<=Ro.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen==Ro.MIN_MATCH&&this.strstart-this.matchStart>Vo.TooFar&&(this.matchLen=Ro.MIN_MATCH-1)}if(s>=Ro.MIN_MATCH&&this.matchLen<=s){this.huffman.tallyDist(this.strstart-1-e,s),s-=2;do{this.strstart++,this.lookahead--,this.lookahead>=Ro.MIN_MATCH&&this.insertString()}while(--s>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=Ro.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(Ro.MAX_MATCH,this.lookahead)-1,a=Math.max(s-Ro.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,Ro.MIN_MATCH-1),s+this.matchLen>i)return!1;let l=r[s+this.matchLen-1],c=r[s+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,s=this.strstart,r[t+this.matchLen]==c&&r[t+this.matchLen-1]==l&&r[t]==r[s]&&r[++t]==r[++s]){switch((i-s)%8){case 1:if(r[++s]==r[++t])break;break;case 2:if(r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 3:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 4:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 5:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 6:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 7:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break}if(r[s]==r[t])do{if(s==i){++s,++t;break}}while(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]);if(s-this.strstart>this.matchLen){if(this.matchStart=e,this.matchLen=s-this.strstart,this.matchLen>=h)break;l=r[s-1],c=r[s]}e=65535&n[e&Ro.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=Ro.MIN_MATCH}insertString(){let e,t=(this.insertHashIndex<<Ro.HASH_SHIFT^this.window[this.strstart+(Ro.MIN_MATCH-1)])&Ro.HASH_MASK;return e=this.head[t],this.prev[this.strstart&Ro.WMASK]=e,this.head[t]=this.strstart,this.insertHashIndex=t,65535&e}fillWindow(){if(this.strstart>=Ro.WSIZE+Ro.MAX_DIST&&this.slideWindow(),this.lookahead<Ro.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*Ro.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>=Ro.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(Ro.WSIZE,Ro.WSIZE+Ro.WSIZE),0),this.matchStart-=Ro.WSIZE,this.strstart-=Ro.WSIZE,this.blockStart-=Ro.WSIZE;for(let e=0;e<Ro.HASH_SIZE;++e){let t=65535&this.head[e];this.head[e]=t>=Ro.WSIZE?t-Ro.WSIZE:0}for(let e=0;e<Ro.WSIZE;e++){let t=65535&this.prev[e];this.prev[e]=t>=Ro.WSIZE?t-Ro.WSIZE:0}}}Vo.TooFar=4096;class Ho{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 Wo{get inputCrc(){return this._engine.inputCrc.value}constructor(){this._state=0,this._pending=new Ho(Ro.PENDING_BUF_SIZE),this._engine=new Vo(this._pending),this.reset()}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state==Wo.FinishedState&&this._pending.isFlushed}reset(){this._state=Wo.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==Wo.FinishedState)break;if(!this._engine.deflate(!!(this._state&Wo.IsFlushing),!!(this._state&Wo.IsFinishing)))switch(this._state){case Wo.BusyState:return i-s;case Wo.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=Wo.BusyState;break;case Wo.FinishingState:this._pending.alignToByte(),this._state=Wo.FinishedState}}return i-s}finish(){this._state|=Wo.IsFlushing|Wo.IsFinishing}}Wo.IsFlushing=4,Wo.IsFinishing=8,Wo.BusyState=16,Wo.FlushingState=20,Wo.FinishingState=28,Wo.FinishedState=30;class zo{constructor(e,t,s,i,a){this.entry=e,this.crc32=t,this.localHeaderOffset=s,this.compressionMode=i,this.compressedSize=a}}class Uo{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new Wo,this._data=e}writeEntry(e){const t=xt.CompressionMethodDeflate,s=Te.empty(),i=this.compress(s,e.data,t),a=s.toArray(),r=new zo(e,i,this._data.bytesWritten,t,s.length);this._centralDirectoryHeaders.push(r),Be.writeInt32LE(this._data,xt.LocalFileHeaderSignature),Be.writeUInt16LE(this._data,10),Be.writeUInt16LE(this._data,2048),Be.writeUInt16LE(this._data,t),Be.writeInt16LE(this._data,0),Be.writeInt16LE(this._data,0),Be.writeInt32LE(this._data,i),Be.writeInt32LE(this._data,a.length),Be.writeInt32LE(this._data,e.data.length),Be.writeInt16LE(this._data,e.fullName.length),Be.writeInt16LE(this._data,0);const n=Be.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,s){if(s!=xt.CompressionMethodDeflate){const s=new Ao;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){Be.writeInt32LE(this._data,xt.EndOfCentralDirSignature),Be.writeInt16LE(this._data,0),Be.writeInt16LE(this._data,0),Be.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Be.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Be.writeInt32LE(this._data,t-e),Be.writeInt32LE(this._data,e),Be.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){Be.writeInt32LE(this._data,xt.CentralFileHeaderSignature),Be.writeUInt16LE(this._data,10),Be.writeUInt16LE(this._data,10),Be.writeUInt16LE(this._data,2048),Be.writeUInt16LE(this._data,e.compressionMode),Be.writeInt16LE(this._data,0),Be.writeInt16LE(this._data,0),Be.writeInt32LE(this._data,e.crc32),Be.writeInt32LE(this._data,e.compressedSize),Be.writeInt32LE(this._data,e.entry.data.length),Be.writeInt16LE(this._data,e.entry.fullName.length),Be.writeInt16LE(this._data,0),Be.writeInt16LE(this._data,0),Be.writeInt16LE(this._data,0),Be.writeInt16LE(this._data,0),Be.writeInt32LE(this._data,0),Be.writeInt32LE(this._data,e.localHeaderOffset);const t=Be.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}var Xo=Object.freeze({__proto__:null,Gp7Exporter:class extends Mo{get name(){return"Guitar Pro 7"}constructor(){super()}writeScore(e){q.debug(this.name,"Writing data entries");const t=(new Do).writeXml(e),s=nt.writeForScore(e),i=bt.writeForScore(e);q.debug(this.name,"Writing ZIP entries");let a=new Uo(this.data);a.writeEntry(new xt("VERSION",Be.stringToBytes("7.0"))),a.writeEntry(new xt("Content/",new Uint8Array(0))),a.writeEntry(new xt("Content/BinaryStylesheet",s)),a.writeEntry(new xt("Content/PartConfiguration",i)),a.writeEntry(new xt("Content/score.gpif",Be.stringToBytes(t))),a.end()}},ScoreExporter:Mo}),Yo=Object.freeze({__proto__:null,AlphaSynthMidiFileHandler:Ei,AlphaTabMetronomeEvent:Vt,AlphaTabRestEvent:Ht,BeatTickLookup:Ii,ControlChangeEvent:Xt,get ControllerType(){return Oe},EndOfTrackEvent:Qt,MasterBarTickLookup:Di,MidiEvent:Rt,get MidiEventType(){return Le},MidiFile:At,get MidiFileFormat(){return Fe},MidiFileGenerator:Vi,MidiTickLookup:Ri,MidiTickLookupFindBeatResult:Ai,NoteBendEvent:jt,NoteEvent:Wt,NoteOffEvent:Ut,NoteOnEvent:zt,PitchBendEvent:Jt,ProgramChangeEvent:Yt,TempoChangeEvent:qt,TimeSignatureEvent:Ot}),qo=Object.freeze({__proto__:null,get AccentuationType(){return i},get AccidentalType(){return qe},Automation:V,get AutomationType(){return a},Bar:H,Beat:ne,BendPoint:z,get BendStyle(){return h},get BendType(){return l},get BrushType(){return c},Chord:oe,get Clef(){return r},Color:fe,get CrescendoType(){return d},get Duration(){return u},get DynamicValue(){return p},Fermata:ot,get FermataType(){return xe},get Fingers(){return f},Font:As,get FontStyle(){return Ge},get GraceType(){return g},get HarmonicType(){return m},InstrumentArticulation:Q,JsonConverter:mi,get KeySignature(){return L},get KeySignatureType(){return I},Lyrics:he,MasterBar:le,get MusicFontSymbol(){return N},Note:Z,get NoteAccidentalMode(){return y},get Ottavia(){return n},get PickStroke(){return x},PlaybackInformation:me,RenderStylesheet:ce,RepeatGroup:de,Score:ue,Section:pe,get SimileMark(){return o},get SlideInType(){return b},get SlideOutType(){return S},Staff:be,Track:Se,get TripletFeel(){return D},Tuning:ye,TupletGroup:ee,get VibratoType(){return _},Voice:_e,get WhammyType(){return E}}),Jo=Object.freeze({__proto__:null,BarBounds:wi,BeatBounds:Bi,Bounds:rt,BoundsLookup:xi,MasterBarBounds:Ti,NoteBounds:ki,RenderFinishedEventArgs:_i,ScoreRenderer:Ni,StaveGroupBounds:vi}),jo=Object.freeze({__proto__:null,CssFontSvgCanvas:ya,Cursors:la,FontSizes:Si,SvgCanvas:ma,get TextAlign(){return P},get TextBaseline(){return C}}),Qo=Object.freeze({__proto__:null,ActiveBeatsChangedEventArgs:ji,AlphaSynth:Ls,AlphaSynthAudioWorkletOutput:da,AlphaSynthScriptProcessorOutput:ra,AlphaSynthWebAudioOutputBase:aa,AlphaSynthWebWorkerApi:oa,CircularSampleBuffer:ia,MidiEventsPlayedEventArgs:Es,PlaybackRange:Hi,PlaybackRangeChangedEventArgs:Fs,get PlayerState(){return Me},PlayerStateChangedEventArgs:ss,PositionChangedEventArgs:is});export{ga as AlphaTabApi,O as AlphaTabError,s as AlphaTabErrorType,Co as CoreSettings,Os as DisplaySettings,Po as Environment,Ki as FileLoadError,B as FingeringMode,ge as FormatError,Gs as ImporterSettings,e as LayoutMode,v as LogLevel,q as Logger,T as NotationMode,U as NotationSettings,ze as PlayerOutputMode,Ws as PlayerSettings,na as ProgressEventArgs,Rs as RenderingResources,Ji as ResizeEventArgs,We as ScrollMode,Ks as Settings,t as StaveProfile,He as SystemsLayoutMode,w as TabRhythmMode,Vs as VibratoPlaybackSettings,Ue as WebPlatform,Xo as exporter,Lo as importer,Eo as meta,Yo as midi,qo as model,jo as platform,Jo as rendering,Qo as synth};
|
|
2
2
|
//# sourceMappingURL=alphaTab.core.min.mjs.map
|