@coderline/alphatab 1.4.0-alpha.1326 → 1.4.0
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 +4 -4
- package/dist/alphaTab.js +4 -4
- package/dist/alphaTab.min.js +1 -1
- package/dist/alphaTab.mjs +1 -1
- package/dist/alphaTab.vite.js +1 -1
- package/dist/alphaTab.vite.mjs +1 -1
- package/dist/alphaTab.webpack.js +1 -1
- package/dist/alphaTab.webpack.mjs +1 -1
- package/dist/alphaTab.worker.mjs +1 -1
- package/dist/alphaTab.worklet.mjs +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e,t,s,i,a,r,n,o,h,l,d,c,u,p,g,m,f,y,b,S,_,w,B,k,T,x,N,v,P,C,E,F,D,L,M,I,A,O,R,V,H,G,W,z,U,X,J;!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 Y{static getValue(e){return Y._values||(Y._values=new Map),e=e.toLowerCase().replaceAll(" ",""),Y._values.has(e)?Y._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}}Y._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 q{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 j extends Error{constructor(e,t="",s){super(t??"",{cause:s}),this.type=e,Object.setPrototypeOf(this,j.prototype)}}class K extends j{constructor(e=null,t){super(s.Format,e??"Unsupported format",t),Object.setPrototypeOf(this,K.prototype)}}!function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy",e[e.Tenuto=3]="Tenuto"}(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 Q{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 Q;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 Q;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={})),function(e){e[e.Down=0]="Down",e[e.Hold=1]="Hold",e[e.Up=2]="Up"}(h||(h={}));class ${constructor(){this.ratioPosition=0,this.pedalType=h.Down,this.nextPedalMarker=null,this.previousPedalMarker=null}}class Z{constructor(){this.id=Z._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,this.sustainPedals=[]}get masterBar(){return this.staff.track.score.masterBars[this.index]}get isEmpty(){for(let e=0,t=this.voices.length;e<t;e++)if(!this.voices[e].isEmpty)return!1;return!0}addVoice(e){e.bar=this,e.index=this.voices.length,this.voices.push(e)}finish(e,t=null){this.isMultiVoice=!1;for(let s=0,i=this.voices.length;s<i;s++){let i=this.voices[s];i.finish(e,t),s>0&&!i.isEmpty&&(this.isMultiVoice=!0)}if(this.sustainPedals.length>0){let e=null;this.previousBar&&this.previousBar.sustainPedals.length>0&&(e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1]);for(const t of this.sustainPedals)e&&e.pedalType!==h.Up&&(e.nextPedalMarker=t,t.previousPedalMarker=e),t.bar=this,e=t}else if(this.previousBar&&this.previousBar.sustainPedals.length>0){const e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1];if(e.pedalType!==h.Up){const t=new $;t.ratioPosition=0,t.bar=this,t.pedalType=h.Hold,this.sustainPedals.push(t),e.nextPedalMarker=t,t.previousPedalMarker=e}}}calculateDuration(){let e=0;for(let t of this.voices){let s=t.calculateDuration();s>e&&(e=s)}return e}}Z._globalBarId=0;class ee{static ticksToMillis(e,t){return e*(6e4/(t*ee.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*ee.QuarterTime))|0}static toTicks(e){return ee.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),ee.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 ee.MinVelocity+e*ee.VelocityIncrement}}ee.QuarterTime=960,ee.MinVelocity=15,ee.VelocityIncrement=16;class te{constructor(e=0,t=0){this.offset=e,this.value=t}}te.MaxPosition=60,te.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(l||(l={})),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"}(d||(d={})),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"}(u||(u={})),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"}(p||(p={})),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"}(g||(g={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(m||(m={})),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"}(y||(y={})),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"}(b||(b={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(S||(S={})),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"}(_||(_={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(w||(w={})),function(e){e[e.Hidden=0]="Hidden",e[e.ShowWithBeams=1]="ShowWithBeams",e[e.ShowWithBars=2]="ShowWithBars",e[e.Automatic=3]="Automatic"}(B||(B={})),function(e){e[e.ScoreDefault=0]="ScoreDefault",e[e.ScoreForcePiano=1]="ScoreForcePiano",e[e.SingleNoteEffectBand=2]="SingleNoteEffectBand",e[e.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano"}(k||(k={})),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",e[e.EffectFreeTime=41]="EffectFreeTime",e[e.EffectSustainPedal=42]="EffectSustainPedal",e[e.EffectGolpe=43]="EffectGolpe",e[e.EffectWahPedal=44]="EffectWahPedal",e[e.EffectBeatBarre=45]="EffectBeatBarre",e[e.EffectNoteOrnament=46]="EffectNoteOrnament",e[e.EffectRasgueado=47]="EffectRasgueado",e[e.EffectDirections=48]="EffectDirections",e[e.EffectBeatTimer=49]="EffectBeatTimer"}(x||(x={}));class se{constructor(){this.notationMode=T.GuitarPro,this.fingeringMode=k.ScoreDefault,this.elements=new Map,this.rhythmMode=B.Automatic,this.rhythmHeight=15,this.transpositionPitches=[],this.displayTranspositionPitches=[],this.smallGraceTabNotes=!0,this.extendBendArrowsOnTiedNotes=!0,this.extendLineEffectsToBeatEnd=!1,this.slurHeight=5}isNotationElementVisible(e){return this.elements.has(e)?this.elements.get(e):!se.defaultElements.has(e)||se.defaultElements.get(e)}}se.defaultElements=new Map([[x.ZerosOnDiveWhammys,!1]]);class ie{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"}(N||(N={}));class ae{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...s){console.debug(ae.format(e,t),...s)}warning(e,t,...s){console.warn(ae.format(e,t),...s)}info(e,t,...s){console.info(ae.format(e,t),...s)}error(e,t,...s){console.error(ae.format(e,t),...s)}}ae.logLevel=N.Info;class re{static shouldLog(e){return re.logLevel!==N.None&&e>=re.logLevel}static debug(e,t,...s){re.shouldLog(N.Debug)&&re.log.debug(e,t,...s)}static warning(e,t,...s){re.shouldLog(N.Warning)&&re.log.warning(e,t,...s)}static info(e,t,...s){re.shouldLog(N.Info)&&re.log.info(e,t,...s)}static error(e,t,...s){re.shouldLog(N.Error)&&re.log.error(e,t,...s)}}re.logLevel=N.Info,re.log=new ae,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"}(v||(v={})),function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(P||(P={})),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"}(C||(C={}));class ne{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=v.C,this.keySignatureType=P.Major,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.isFreeTime=!1,this.tripletFeel=C.NoTripletFeel,this.section=null,this.tempoAutomations=[],this.fermata=null,this.start=0,this.isAnacrusis=!1,this.displayScale=1,this.displayWidth=-1,this.directions=null}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}get tempoAutomation(){return this.tempoAutomations.length>0?this.tempoAutomations[0]:null}calculateDuration(e=!0){if(this.isAnacrusis&&e){let e=0;for(let t of this.score.tracks)for(let s of t.staves){let t=this.index<s.bars.length?s.bars[this.index].calculateDuration():0;t>e&&(e=t)}return e}return this.timeSignatureNumerator*ee.valueToTicks(this.timeSignatureDenominator)}addFermata(e,t){let s=this.fermata;null===s&&(s=new Map,this.fermata=s),s.set(e,t)}addDirection(e){null==this.directions&&(this.directions=new Set),this.directions.add(e)}getFermata(e){const t=this.fermata;return null===t?null:t.has(e.playbackStart)?t.get(e.playbackStart):null}}ne.MaxAlternateEndings=8;class oe{constructor(){this.note=null,this.tone=new he,this.octave=0}get realValue(){return 12*this.octave+this.tone.noteValue}}class he{constructor(e=0,t=b.Default){this.noteValue=e,this.accidentalMode=t}}class le{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===k.ScoreForcePiano||e.notation.fingeringMode===k.SingleNoteEffectBandForcePiano||Y.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:return null;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!!le.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(!le.TuningLetters.has(a))return null;t+=String.fromCharCode(a)}}if(!s||!t)return null;let i=new oe;return i.octave=parseInt(s)+1,i.note=t.toLowerCase(),i.tone=le.getToneForText(i.note),i.tone.noteValue<0&&(i.octave--,i.tone.noteValue+=12),i}static getTuningForText(e){let t=le.parseTuning(e);return t?t.realValue:-1}static getToneForText(e){const t=e.substring(0,1),s=e.substring(1);let i,a;switch(t.toLowerCase()){case"c":default:i=0;break;case"d":i=2;break;case"e":i=4;break;case"f":i=5;break;case"g":i=7;break;case"a":i=9;break;case"b":i=11}switch(a=le.parseAccidentalMode(s),a){case b.Default:case b.ForceNone:case b.ForceNatural:break;case b.ForceSharp:i++;break;case b.ForceDoubleSharp:i+=2;break;case b.ForceFlat:i--;break;case b.ForceDoubleFlat:i-=2}return new he(i,a)}static parseAccidentalMode(e){const t=e.toLowerCase();return le.accidentalModeMapping.has(t)?le.accidentalModeMapping.get(t):b.Default}static newGuid(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)}static isAlmostEqualTo(e,t){return Math.abs(e-t)<1e-5}static toHexString(e,t=0){let s="";do{s=String.fromCharCode("0123456789ABCDEF".charCodeAt(15&e))+s,e>>=4}while(e>0);for(;s.length<t;)s="0"+s;return s}static getAlternateEndingsList(e){const t=[];for(let s=0;s<ne.MaxAlternateEndings;s++)e&1<<s&&t.push(s);return t}static deltaFretToHarmonicValue(e){switch(e){case 2:return 2.4;case 3:return 3.2;case 4:case 5:case 7:case 9:case 12:case 16:case 17:case 19:case 24:return e;case 8:return 8.2;case 10:return 9.6;case 14:case 15:return 14.7;case 21:case 22:return 21.7;default:return 12}}static clamp(e,t,s){return e<=t?t:e>=s?s:e}}le.TuningLetters=new Set([67,68,69,70,71,65,66,99,100,101,102,103,97,98,35]),le.accidentalModeMapping=new Map([["default",b.Default],["d",b.Default],["forcenone",b.ForceNone],["-",b.ForceNone],["forcenatural",b.ForceNatural],["n",b.ForceNatural],["forcesharp",b.ForceSharp],["#",b.ForceSharp],["forcedoublesharp",b.ForceDoubleSharp],["##",b.ForceDoubleSharp],["x",b.ForceDoubleSharp],["forceflat",b.ForceFlat],["b",b.ForceFlat],["forcedoubleflat",b.ForceDoubleFlat],["bb",b.ForceDoubleFlat]]),function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(E||(E={})),function(e){e[e.None=-1]="None",e[e.Space=32]="Space",e[e.Brace=57344]="Brace",e[e.BracketTop=57347]="BracketTop",e[e.BracketBottom=57348]="BracketBottom",e[e.SystemDivider=57351]="SystemDivider",e[e.GClef=57424]="GClef",e[e.CClef=57436]="CClef",e[e.FClef=57442]="FClef",e[e.UnpitchedPercussionClef1=57449]="UnpitchedPercussionClef1",e[e.SixStringTabClef=57453]="SixStringTabClef",e[e.FourStringTabClef=57454]="FourStringTabClef",e[e.TimeSig0=57472]="TimeSig0",e[e.TimeSig1=57473]="TimeSig1",e[e.TimeSig2=57474]="TimeSig2",e[e.TimeSig3=57475]="TimeSig3",e[e.TimeSig4=57476]="TimeSig4",e[e.TimeSig5=57477]="TimeSig5",e[e.TimeSig6=57478]="TimeSig6",e[e.TimeSig7=57479]="TimeSig7",e[e.TimeSig8=57480]="TimeSig8",e[e.TimeSig9=57481]="TimeSig9",e[e.TimeSigCommon=57482]="TimeSigCommon",e[e.TimeSigCutCommon=57483]="TimeSigCutCommon",e[e.NoteheadDoubleWholeSquare=57505]="NoteheadDoubleWholeSquare",e[e.NoteheadDoubleWhole=57504]="NoteheadDoubleWhole",e[e.NoteheadWhole=57506]="NoteheadWhole",e[e.NoteheadHalf=57507]="NoteheadHalf",e[e.NoteheadBlack=57508]="NoteheadBlack",e[e.NoteheadNull=57509]="NoteheadNull",e[e.NoteheadXOrnate=57514]="NoteheadXOrnate",e[e.NoteheadTriangleUpWhole=57531]="NoteheadTriangleUpWhole",e[e.NoteheadTriangleUpHalf=57532]="NoteheadTriangleUpHalf",e[e.NoteheadTriangleUpBlack=57534]="NoteheadTriangleUpBlack",e[e.NoteheadDiamondBlackWide=57564]="NoteheadDiamondBlackWide",e[e.NoteheadDiamondWhite=57565]="NoteheadDiamondWhite",e[e.NoteheadDiamondWhiteWide=57566]="NoteheadDiamondWhiteWide",e[e.NoteheadCircleX=57523]="NoteheadCircleX",e[e.NoteheadXWhole=57511]="NoteheadXWhole",e[e.NoteheadXHalf=57512]="NoteheadXHalf",e[e.NoteheadXBlack=57513]="NoteheadXBlack",e[e.NoteheadParenthesis=57550]="NoteheadParenthesis",e[e.NoteheadSlashedBlack2=57552]="NoteheadSlashedBlack2",e[e.NoteheadCircleSlash=57591]="NoteheadCircleSlash",e[e.NoteheadHeavyX=57592]="NoteheadHeavyX",e[e.NoteheadHeavyXHat=57593]="NoteheadHeavyXHat",e[e.NoteheadSlashVerticalEnds=57600]="NoteheadSlashVerticalEnds",e[e.NoteheadSlashWhiteWhole=57602]="NoteheadSlashWhiteWhole",e[e.NoteheadSlashWhiteHalf=57603]="NoteheadSlashWhiteHalf",e[e.NoteQuarterUp=57813]="NoteQuarterUp",e[e.NoteEighthUp=57815]="NoteEighthUp",e[e.TextBlackNoteLongStem=57841]="TextBlackNoteLongStem",e[e.TextBlackNoteFrac8thLongStem=57843]="TextBlackNoteFrac8thLongStem",e[e.TextBlackNoteFrac16thLongStem=57845]="TextBlackNoteFrac16thLongStem",e[e.TextBlackNoteFrac32ndLongStem=57846]="TextBlackNoteFrac32ndLongStem",e[e.TextCont8thBeamLongStem=57848]="TextCont8thBeamLongStem",e[e.TextCont16thBeamLongStem=57850]="TextCont16thBeamLongStem",e[e.TextCont32ndBeamLongStem=57851]="TextCont32ndBeamLongStem",e[e.TextAugmentationDot=57852]="TextAugmentationDot",e[e.TextTupletBracketStartLongStem=57857]="TextTupletBracketStartLongStem",e[e.TextTuplet3LongStem=57858]="TextTuplet3LongStem",e[e.TextTupletBracketEndLongStem=57859]="TextTupletBracketEndLongStem",e[e.Tremolo3=57890]="Tremolo3",e[e.Tremolo2=57889]="Tremolo2",e[e.Tremolo1=57888]="Tremolo1",e[e.FlagEighthUp=57920]="FlagEighthUp",e[e.FlagEighthDown=57921]="FlagEighthDown",e[e.FlagSixteenthUp=57922]="FlagSixteenthUp",e[e.FlagSixteenthDown=57923]="FlagSixteenthDown",e[e.FlagThirtySecondUp=57924]="FlagThirtySecondUp",e[e.FlagThirtySecondDown=57925]="FlagThirtySecondDown",e[e.FlagSixtyFourthUp=57926]="FlagSixtyFourthUp",e[e.FlagSixtyFourthDown=57927]="FlagSixtyFourthDown",e[e.FlagOneHundredTwentyEighthUp=57928]="FlagOneHundredTwentyEighthUp",e[e.FlagOneHundredTwentyEighthDown=57929]="FlagOneHundredTwentyEighthDown",e[e.FlagTwoHundredFiftySixthUp=57930]="FlagTwoHundredFiftySixthUp",e[e.FlagTwoHundredFiftySixthDown=57931]="FlagTwoHundredFiftySixthDown",e[e.AccidentalFlat=57952]="AccidentalFlat",e[e.AccidentalNatural=57953]="AccidentalNatural",e[e.AccidentalSharp=57954]="AccidentalSharp",e[e.AccidentalDoubleSharp=57955]="AccidentalDoubleSharp",e[e.AccidentalDoubleFlat=57956]="AccidentalDoubleFlat",e[e.AccidentalQuarterToneFlatArrowUp=57968]="AccidentalQuarterToneFlatArrowUp",e[e.AccidentalQuarterToneSharpArrowUp=57972]="AccidentalQuarterToneSharpArrowUp",e[e.AccidentalQuarterToneNaturalArrowUp=57970]="AccidentalQuarterToneNaturalArrowUp",e[e.Segno=57415]="Segno",e[e.Coda=57416]="Coda",e[e.ArticAccentAbove=58528]="ArticAccentAbove",e[e.ArticAccentBelow=58529]="ArticAccentBelow",e[e.ArticStaccatoAbove=58530]="ArticStaccatoAbove",e[e.ArticStaccatoBelow=58531]="ArticStaccatoBelow",e[e.ArticTenutoAbove=58532]="ArticTenutoAbove",e[e.ArticTenutoBelow=58533]="ArticTenutoBelow",e[e.ArticMarcatoAbove=58540]="ArticMarcatoAbove",e[e.ArticMarcatoBelow=58541]="ArticMarcatoBelow",e[e.FermataAbove=58560]="FermataAbove",e[e.FermataShortAbove=58564]="FermataShortAbove",e[e.FermataLongAbove=58566]="FermataLongAbove",e[e.RestLonga=58593]="RestLonga",e[e.RestDoubleWhole=58594]="RestDoubleWhole",e[e.RestWhole=58595]="RestWhole",e[e.RestHalf=58596]="RestHalf",e[e.RestQuarter=58597]="RestQuarter",e[e.RestEighth=58598]="RestEighth",e[e.RestSixteenth=58599]="RestSixteenth",e[e.RestThirtySecond=58600]="RestThirtySecond",e[e.RestSixtyFourth=58601]="RestSixtyFourth",e[e.RestOneHundredTwentyEighth=58602]="RestOneHundredTwentyEighth",e[e.RestTwoHundredFiftySixth=58603]="RestTwoHundredFiftySixth",e[e.Repeat1Bar=58624]="Repeat1Bar",e[e.Repeat2Bars=58625]="Repeat2Bars",e[e.Ottava=58640]="Ottava",e[e.OttavaAlta=58641]="OttavaAlta",e[e.OttavaBassaVb=58652]="OttavaBassaVb",e[e.Quindicesima=58644]="Quindicesima",e[e.QuindicesimaAlta=58645]="QuindicesimaAlta",e[e.DynamicPPP=58666]="DynamicPPP",e[e.DynamicPP=58667]="DynamicPP",e[e.DynamicPiano=58656]="DynamicPiano",e[e.DynamicMP=58668]="DynamicMP",e[e.DynamicMF=58669]="DynamicMF",e[e.DynamicForte=58658]="DynamicForte",e[e.DynamicFF=58671]="DynamicFF",e[e.DynamicFFF=58672]="DynamicFFF",e[e.OrnamentTrill=58726]="OrnamentTrill",e[e.OrnamentTurn=58727]="OrnamentTurn",e[e.OrnamentTurnInverted=58728]="OrnamentTurnInverted",e[e.OrnamentShortTrill=58732]="OrnamentShortTrill",e[e.OrnamentMordent=58733]="OrnamentMordent",e[e.StringsDownBow=58896]="StringsDownBow",e[e.StringsUpBow=58898]="StringsUpBow",e[e.KeyboardPedalPed=58960]="KeyboardPedalPed",e[e.KeyboardPedalUp=58965]="KeyboardPedalUp",e[e.PictEdgeOfCymbal=59177]="PictEdgeOfCymbal",e[e.GuitarString0=59443]="GuitarString0",e[e.GuitarString1=59444]="GuitarString1",e[e.GuitarString2=59445]="GuitarString2",e[e.GuitarString3=59446]="GuitarString3",e[e.GuitarString4=59447]="GuitarString4",e[e.GuitarString5=59448]="GuitarString5",e[e.GuitarString6=59449]="GuitarString6",e[e.GuitarString7=59450]="GuitarString7",e[e.GuitarString8=59451]="GuitarString8",e[e.GuitarString9=59452]="GuitarString9",e[e.GuitarOpenPedal=59453]="GuitarOpenPedal",e[e.GuitarClosePedal=59455]="GuitarClosePedal",e[e.GuitarGolpe=59458]="GuitarGolpe",e[e.GuitarFadeIn=59459]="GuitarFadeIn",e[e.GuitarFadeOut=59460]="GuitarFadeOut",e[e.GuitarVolumeSwell=59461]="GuitarVolumeSwell",e[e.FretboardX=59481]="FretboardX",e[e.FretboardO=59482]="FretboardO",e[e.WiggleTrill=60068]="WiggleTrill",e[e.WiggleVibratoMediumFast=60126]="WiggleVibratoMediumFast",e[e.OctaveBaselineM=60565]="OctaveBaselineM",e[e.OctaveBaselineB=60563]="OctaveBaselineB"}(F||(F={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(D||(D={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(L||(L={}));class de{constructor(e,t){this.width=e,this.height=t}}class ce{constructor(e="",t=0,s=0,i=F.None,a=F.None,r=F.None,n=F.None,o=L.Middle){this.elementType=e,this.outputMidiNumber=s,this.staffLine=t,this.noteHeadDefault=i,this.noteHeadHalf=a!==F.None?a:i,this.noteHeadWhole=r!==F.None?r:i,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case p.Whole:return this.noteHeadWhole;case p.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class ue{static articulationFromElementVariation(e,t){return e<ue.gp6ElementAndVariationToArticulation.length?(t>=ue.gp6ElementAndVariationToArticulation.length&&(t=0),ue.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]:ue.getArticulationByValue(t)}static getElementAndVariation(e){const t=ue.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<ue.gp6ElementAndVariationToArticulation.length;e++){const s=ue.gp6ElementAndVariationToArticulation[e];for(let i=0;i<s.length;i++){const a=ue.getArticulationByValue(s[i]);if(a?.outputMidiNumber===t.outputMidiNumber)return[e,i]}}return[-1,-1]}static getArticulationByValue(e){return ue.instrumentArticulations.has(e)?ue.instrumentArticulations.get(e):null}}ue.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]],ue.instrumentArticulations=new Map([[38,new ce("snare",3,38,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[37,new ce("snare",3,37,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[91,new ce("snare",3,38,F.NoteheadDiamondWhite,F.NoteheadDiamondWhite,F.NoteheadDiamondWhite)],[42,new ce("hiHat",-1,42,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[92,new ce("hiHat",-1,46,F.NoteheadCircleSlash,F.NoteheadCircleSlash,F.NoteheadCircleSlash)],[46,new ce("hiHat",-1,46,F.NoteheadCircleX,F.NoteheadCircleX,F.NoteheadCircleX)],[44,new ce("hiHat",9,44,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[35,new ce("kickDrum",8,35,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[36,new ce("kickDrum",7,36,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[50,new ce("tom",1,50,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[48,new ce("tom",2,48,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[47,new ce("tom",4,47,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[45,new ce("tom",5,45,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[43,new ce("tom",6,43,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[93,new ce("ride",0,51,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack,F.PictEdgeOfCymbal,L.Bottom)],[51,new ce("ride",0,51,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[53,new ce("ride",0,53,F.NoteheadDiamondWhite,F.NoteheadDiamondWhite,F.NoteheadDiamondWhite)],[94,new ce("ride",0,51,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack,F.ArticStaccatoAbove,L.Top)],[55,new ce("splash",-2,55,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[95,new ce("splash",-2,55,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack,F.ArticStaccatoAbove,L.Bottom)],[52,new ce("china",-3,52,F.NoteheadHeavyXHat,F.NoteheadHeavyXHat,F.NoteheadHeavyXHat)],[96,new ce("china",-3,52,F.NoteheadHeavyXHat,F.NoteheadHeavyXHat,F.NoteheadHeavyXHat)],[49,new ce("crash",-2,49,F.NoteheadHeavyX,F.NoteheadHeavyX,F.NoteheadHeavyX)],[97,new ce("crash",-2,49,F.NoteheadHeavyX,F.NoteheadHeavyX,F.NoteheadHeavyX,F.ArticStaccatoAbove,L.Bottom)],[57,new ce("crash",-1,57,F.NoteheadHeavyX,F.NoteheadHeavyX,F.NoteheadHeavyX)],[98,new ce("crash",-1,57,F.NoteheadHeavyX,F.NoteheadHeavyX,F.NoteheadHeavyX,F.ArticStaccatoAbove,L.Bottom)],[99,new ce("cowbell",1,56,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpHalf,F.NoteheadTriangleUpWhole)],[100,new ce("cowbell",1,56,F.NoteheadXBlack,F.NoteheadXHalf,F.NoteheadXWhole)],[56,new ce("cowbell",0,56,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpHalf,F.NoteheadTriangleUpWhole)],[101,new ce("cowbell",0,56,F.NoteheadXBlack,F.NoteheadXHalf,F.NoteheadXWhole)],[102,new ce("cowbell",-1,56,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpHalf,F.NoteheadTriangleUpWhole)],[103,new ce("cowbell",-1,56,F.NoteheadXBlack,F.NoteheadXHalf,F.NoteheadXWhole)],[77,new ce("woodblock",-9,77,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack)],[76,new ce("woodblock",-10,76,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack)],[60,new ce("bongo",-4,60,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[104,new ce("bongo",-5,60,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.NoteheadParenthesis,L.Middle)],[105,new ce("bongo",-6,60,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[61,new ce("bongo",-7,61,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[106,new ce("bongo",-8,61,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.NoteheadParenthesis,L.Middle)],[107,new ce("bongo",-16,61,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[66,new ce("timbale",10,66,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[65,new ce("timbale",9,65,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[68,new ce("agogo",12,68,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[67,new ce("agogo",11,67,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[64,new ce("conga",17,64,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[108,new ce("conga",16,64,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[109,new ce("conga",15,64,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.NoteheadParenthesis,L.Middle)],[63,new ce("conga",14,63,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[110,new ce("conga",13,63,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[62,new ce("conga",19,62,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.NoteheadParenthesis,L.Middle)],[72,new ce("whistle",-11,72,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[71,new ce("whistle",-17,71,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[73,new ce("guiro",38,73,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[74,new ce("guiro",37,74,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[86,new ce("surdo",36,86,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[87,new ce("surdo",35,87,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadParenthesis,L.Middle)],[54,new ce("tambourine",3,54,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack)],[111,new ce("tambourine",2,54,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack,F.StringsUpBow,L.Bottom)],[112,new ce("tambourine",1,54,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack,F.StringsDownBow,L.Bottom)],[113,new ce("tambourine",-7,54,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[79,new ce("cuica",30,79,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[78,new ce("cuica",29,78,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[58,new ce("vibraslap",28,58,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[81,new ce("triangle",27,81,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[80,new ce("triangle",26,80,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadParenthesis,L.Middle)],[114,new ce("grancassa",25,43,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[115,new ce("piatti",18,49,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[116,new ce("piatti",24,49,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[69,new ce("cabasa",23,69,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[117,new ce("cabasa",22,69,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.StringsUpBow,L.Bottom)],[85,new ce("castanets",21,85,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[75,new ce("claves",20,75,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[70,new ce("maraca",-12,70,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[118,new ce("maraca",-13,70,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.StringsUpBow,L.Bottom)],[119,new ce("maraca",-14,70,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[120,new ce("maraca",-15,70,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.StringsUpBow,L.Bottom)],[82,new ce("shaker",-23,54,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[122,new ce("shaker",-24,54,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.StringsUpBow,L.Bottom)],[84,new ce("bellTree",-18,53,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[123,new ce("bellTree",-19,53,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.StringsUpBow,L.Bottom)],[83,new ce("jingleBell",-20,53,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[124,new ce("unpitched",-21,62,F.NoteheadNull,F.NoteheadNull,F.NoteheadNull,F.GuitarGolpe,L.Top)],[125,new ce("unpitched",-22,62,F.NoteheadNull,F.NoteheadNull,F.NoteheadNull,F.GuitarGolpe,L.Bottom)],[39,new ce("handClap",3,39,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[40,new ce("snare",3,40,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[31,new ce("snare",3,40,F.NoteheadSlashedBlack2,F.NoteheadSlashedBlack2,F.NoteheadSlashedBlack2)],[41,new ce("tom",5,41,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[59,new ce("ride",2,59,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack,F.PictEdgeOfCymbal,L.Bottom)],[126,new ce("ride",2,59,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[127,new ce("ride",2,59,F.NoteheadDiamondWhite,F.NoteheadDiamondWhite,F.NoteheadDiamondWhite)],[29,new ce("ride",2,59,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack,F.ArticStaccatoAbove,L.Top)],[30,new ce("crash",-3,49,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[33,new ce("snare",3,37,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[34,new ce("snare",3,38,F.NoteheadBlack,F.NoteheadBlack,F.NoteheadBlack)]]),ue.instrumentArticulationNames=new Map([["Ride (choke)",29],["Cymbal (hit)",30],["Snare (side stick)",31],["Snare (side stick) 2",33],["Snare (hit)",34],["Kick (hit)",35],["Kick (hit) 2",36],["Snare (side stick) 3",37],["Snare (hit) 2",38],["Hand Clap (hit)",39],["Snare (hit) 3",40],["Low Floor Tom (hit)",41],["Hi-Hat (closed)",42],["Very Low Tom (hit)",43],["Pedal Hi-Hat (hit)",44],["Low Tom (hit)",45],["Hi-Hat (open)",46],["Mid Tom (hit)",47],["High Tom (hit)",48],["Crash high (hit)",49],["High Floor Tom (hit)",50],["Ride (middle)",51],["China (hit)",52],["Ride (bell)",53],["Tambourine (hit)",54],["Splash (hit)",55],["Cowbell medium (hit)",56],["Crash medium (hit)",57],["Vibraslap (hit)",58],["Ride (edge)",59],["Hand (hit)",60],["Hand (hit)",61],["Conga high (mute)",62],["Conga high (hit)",63],["Conga low (hit)",64],["Timbale high (hit)",65],["Timbale low (hit)",66],["Agogo high (hit)",67],["Agogo tow (hit)",68],["Cabasa (hit)",69],["Left Maraca (hit)",70],["Whistle high (hit)",71],["Whistle low (hit)",72],["Guiro (hit)",73],["Guiro (scrap-return)",74],["Claves (hit)",75],["Woodblock high (hit)",76],["Woodblock low (hit)",77],["Cuica (mute)",78],["Cuica (open)",79],["Triangle (rnute)",80],["Triangle (hit)",81],["Shaker (hit)",82],["Tinkle Bell (hat)",83],["Jingle Bell (hit)",83],["Bell Tree (hit)",84],["Castanets (hit)",85],["Surdo (hit)",86],["Surdo (mute)",87],["Snare (rim shot)",91],["Hi-Hat (half)",92],["Ride (edge) 2",93],["Ride (choke) 2",94],["Splash (choke)",95],["China (choke)",96],["Crash high (choke)",97],["Crash medium (choke)",98],["Cowbell low (hit)",99],["Cowbell low (tip)",100],["Cowbell medium (tip)",101],["Cowbell high (hit)",102],["Cowbell high (tip)",103],["Hand (mute)",104],["Hand (slap)",105],["Hand (mute) 2",106],["Hand (slap) 2",107],["Conga low (slap)",108],["Conga low (mute)",109],["Conga high (slap)",110],["Tambourine (return)",111],["Tambourine (roll)",112],["Tambourine (hand)",113],["Grancassa (hit)",114],["Piatti (hat)",115],["Piatti (hand)",116],["Cabasa (return)",117],["Left Maraca (return)",118],["Right Maraca (hit)",119],["Right Maraca (return)",120],["Shaker (return)",122],["Bell Tee (return)",123],["Golpe (thumb)",124],["Golpe (finger)",125],["Ride (middle) 2",126],["Ride (bell) 2",127]]),function(e){e[e.None=0]="None",e[e.InvertedTurn=1]="InvertedTurn",e[e.Turn=2]="Turn",e[e.UpperMordent=3]="UpperMordent",e[e.LowerMordent=4]="LowerMordent"}(M||(M={}));class pe{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1}}class ge{constructor(){this.id=ge.GlobalNoteId++,this.index=0,this.accentuated=i.None,this.bendType=d.None,this.bendStyle=l.Default,this.bendOrigin=null,this.isContinuedBend=!1,this.bendPoints=null,this.maxBendPoint=null,this.fret=-1,this.string=-1,this.showStringNumber=!1,this.octave=-1,this.tone=-1,this.percussionArticulation=-1,this.isVisible=!0,this.isLeftHandTapped=!1,this.isHammerPullOrigin=!1,this.hammerPullOrigin=null,this.hammerPullDestination=null,this.isSlurDestination=!1,this.slurOrigin=null,this.slurDestination=null,this.harmonicType=y.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=S.None,this.slideOutType=_.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=w.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=f.Unknown,this.rightHandFinger=f.Unknown,this.trillValue=-1,this.trillSpeed=p.ThirtySecond,this.durationPercent=1,this.accidentalMode=b.Default,this.dynamics=g.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.ornament=M.None,this._noteIdBag=null}get hasBend(){return null!==this.bendPoints&&this.bendType!==d.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?ue.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?ue.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==y.None}get isTieOrigin(){return null!==this.tieDestination}get isFingering(){return this.leftHandFinger!==f.Unknown||this.rightHandFinger!==f.Unknown}get trillFret(){return this.trillValue-this.stringTuning}get isTrill(){return this.trillValue>=0}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get stringTuning(){return this.beat.voice.bar.staff.capo+ge.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===y.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===y.None||!this.isStringed)return 0;let e=this.harmonicValue;return le.isAlmostEqualTo(e,2.4)?36:le.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!==y.Natural&&this.harmonicType!==y.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===d.None&&(this.bendType=d.Custom)}finish(e,t=null){let s=new ie((()=>ge.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=ge.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case _.Shift:case _.Legato:this.slideTarget=s.value,this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=_.None}let a=null;this.isHammerPullOrigin&&this.hammerPullDestination?a=this.hammerPullDestination:this.slideOutType===_.Legato&&this.slideTarget&&(a=this.slideTarget),a&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===E.None?(this.effectSlurOrigin.effectSlurDestination=a,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=a,this.effectSlurDestination.effectSlurOrigin=this));const r=this.bendPoints,n=null!=r&&r.length>0;if(n){let e=this.isTieDestination&&this.tieOrigin.hasBend;this.isContinuedBend=e}else this.bendType=d.None;if(n&&this.bendType===d.Custom)if(4===r.length){let e=r[0],t=r[1],s=r[2],i=r[3];t.value===s.value?i.value>e.value?t.value>i.value?this.bendType=d.BendRelease:!this.isContinuedBend&&e.value>0?(this.bendType=d.PrebendBend,r.splice(2,1),r.splice(1,1)):(this.bendType=d.Bend,r.splice(2,1),r.splice(1,1)):i.value<e.value?this.isContinuedBend?(this.bendType=d.Release,r.splice(2,1),r.splice(1,1)):(this.bendType=d.PrebendRelease,r.splice(2,1),r.splice(1,1)):t.value>e.value?this.bendType=d.BendRelease:e.value>0&&!this.isContinuedBend?(this.bendType=d.Prebend,r.splice(2,1),r.splice(1,1)):(this.bendType=d.Hold,r.splice(2,1),r.splice(1,1)):re.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===r.length){let e=r[0],t=r[1];t.value>e.value?!this.isContinuedBend&&e.value>0?this.bendType=d.PrebendBend:this.bendType=d.Bend:t.value<e.value?this.isContinuedBend?this.bendType=d.Release:this.bendType=d.PrebendRelease:e.value>0&&!this.isContinuedBend?this.bendType=d.Prebend:this.bendType=d.Hold}this.initialBendValue>0&&(this.accidentalMode=b.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+ge.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+ge.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-ge.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(ge.NoteIdLookupKey)?t=e.get(ge.NoteIdLookupKey):(t=new Map,e.set(ge.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??ge.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 pe),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new pe),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new pe),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new pe),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new pe),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new pe),this._noteIdBag.hammerPullDestinationNoteId=t,!0}return!1}}ge.GlobalNoteId=0,ge.MaxOffsetForSameLineSearch=3,ge.NoteIdLookupKey="NoteIdLookup";class me{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!==m.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 me.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}me.HalfTicks=1920,me.QuarterTicks=960,me.EighthTicks=480,me.SixteenthTicks=240,me.ThirtySecondTicks=120,me.SixtyFourthTicks=60,me.OneHundredTwentyEighthTicks=30,me.TwoHundredFiftySixthTicks=15,me.AllTicks=[me.HalfTicks,me.QuarterTicks,me.EighthTicks,me.SixteenthTicks,me.ThirtySecondTicks,me.SixtyFourthTicks,me.OneHundredTwentyEighthTicks,me.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"}(I||(I={}));class fe{static clone(e){const t=new te;return t.offset=e.offset,t.value=e.value,t}}class ye{static clone(e){const t=new ge;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(fe.clone(s))}return t.fret=e.fret,t.string=e.string,t.showStringNumber=e.showStringNumber,t.octave=e.octave,t.tone=e.tone,t.percussionArticulation=e.percussionArticulation,t.isVisible=e.isVisible,t.isLeftHandTapped=e.isLeftHandTapped,t.isHammerPullOrigin=e.isHammerPullOrigin,t.isSlurDestination=e.isSlurDestination,t.harmonicType=e.harmonicType,t.harmonicValue=e.harmonicValue,t.isGhost=e.isGhost,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.isDead=e.isDead,t.isStaccato=e.isStaccato,t.slideInType=e.slideInType,t.slideOutType=e.slideOutType,t.vibrato=e.vibrato,t.isTieDestination=e.isTieDestination,t.leftHandFinger=e.leftHandFinger,t.rightHandFinger=e.rightHandFinger,t.trillValue=e.trillValue,t.trillSpeed=e.trillSpeed,t.durationPercent=e.durationPercent,t.accidentalMode=e.accidentalMode,t.dynamics=e.dynamics,t.ornament=e.ornament,t}}class be{static clone(e){const t=new Q;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class Se{static clone(e){const t=new we;t.index=e.index,t.notes=[];for(const s of e.notes)t.addNote(ye.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(be.clone(s));if(t.dots=e.dots,t.fade=e.fade,t.lyrics=e.lyrics?e.lyrics.slice():null,t.pop=e.pop,t.slap=e.slap,t.tap=e.tap,t.text=e.text,t.slashed=e.slashed,t.deadSlapped=e.deadSlapped,t.brushType=e.brushType,t.brushDuration=e.brushDuration,t.tupletDenominator=e.tupletDenominator,t.tupletNumerator=e.tupletNumerator,t.isContinuedWhammy=e.isContinuedWhammy,t.whammyBarType=e.whammyBarType,e.whammyBarPoints){t.whammyBarPoints=[];for(const s of e.whammyBarPoints)t.addWhammyBarPoint(fe.clone(s))}return t.vibrato=e.vibrato,t.chordId=e.chordId,t.graceType=e.graceType,t.pickStroke=e.pickStroke,t.tremoloSpeed=e.tremoloSpeed,t.crescendo=e.crescendo,t.displayStart=e.displayStart,t.playbackStart=e.playbackStart,t.displayDuration=e.displayDuration,t.playbackDuration=e.playbackDuration,t.golpe=e.golpe,t.dynamics=e.dynamics,t.invertBeamDirection=e.invertBeamDirection,t.preferredBeamDirection=e.preferredBeamDirection,t.isEffectSlurOrigin=e.isEffectSlurOrigin,t.beamingMode=e.beamingMode,t.wahPedal=e.wahPedal,t.barreFret=e.barreFret,t.barreShape=e.barreShape,t.rasgueado=e.rasgueado,t.showTimer=e.showTimer,t.timer=e.timer,t}}class _e{constructor(){this.beats=[],this.id="empty",this.isComplete=!1}addBeat(e){e.graceIndex=this.beats.length,e.graceGroup=this,this.beats.push(e)}finish(){this.beats.length>0&&(this.id=this.beats[0].absoluteDisplayStart+"_"+this.beats[0].voice.index)}}!function(e){e[e.None=0]="None",e[e.Thumb=1]="Thumb",e[e.Finger=2]="Finger"}(A||(A={})),function(e){e[e.None=0]="None",e[e.FadeIn=1]="FadeIn",e[e.FadeOut=2]="FadeOut",e[e.VolumeSwell=3]="VolumeSwell"}(O||(O={})),function(e){e[e.None=0]="None",e[e.Open=1]="Open",e[e.Closed=2]="Closed"}(R||(R={})),function(e){e[e.None=0]="None",e[e.Full=1]="Full",e[e.Half=2]="Half"}(V||(V={})),function(e){e[e.None=0]="None",e[e.Ii=1]="Ii",e[e.Mi=2]="Mi",e[e.MiiTriplet=3]="MiiTriplet",e[e.MiiAnapaest=4]="MiiAnapaest",e[e.PmpTriplet=5]="PmpTriplet",e[e.PmpAnapaest=6]="PmpAnapaest",e[e.PeiTriplet=7]="PeiTriplet",e[e.PeiAnapaest=8]="PeiAnapaest",e[e.PaiTriplet=9]="PaiTriplet",e[e.PaiAnapaest=10]="PaiAnapaest",e[e.AmiTriplet=11]="AmiTriplet",e[e.AmiAnapaest=12]="AmiAnapaest",e[e.Ppp=13]="Ppp",e[e.Amii=14]="Amii",e[e.Amip=15]="Amip",e[e.Eami=16]="Eami",e[e.Eamii=17]="Eamii",e[e.Peami=18]="Peami"}(H||(H={})),function(e){e[e.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext",e[e.ForceSplitOnSecondaryToNext=3]="ForceSplitOnSecondaryToNext"}(G||(G={}));class we{constructor(){this.id=we._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=l.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=p.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fade=O.None,this.lyrics=null,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.slashed=!1,this.deadSlapped=!1,this.brushType=c.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=I.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=w.None,this.chordId=null,this.graceType=m.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=E.None,this.tremoloSpeed=null,this.crescendo=u.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.golpe=A.None,this.dynamics=g.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=G.Auto,this.wahPedal=R.None,this.barreFret=-1,this.barreShape=V.None,this.rasgueado=H.None,this.showTimer=!1,this.timer=null}get isLastOfVoice(){return this.index===this.voice.beats.length-1}get isLegatoDestination(){return!!this.previousBeat&&this.previousBeat.isLegatoOrigin}get isRest(){return this.isEmpty||!this.deadSlapped&&0===this.notes.length}get isFullBarRest(){return this.isRest&&1===this.voice.beats.length&&this.duration===p.Whole}get fadeIn(){return this.fade===O.FadeIn}set fadeIn(e){this.fade=e?O.FadeIn:O.None}get hasRasgueado(){return this.rasgueado!==H.None}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==I.None}get hasChord(){return!!this.chordId}get chord(){return this.chordId?this.voice.bar.staff.getChord(this.chordId):null}get isTremolo(){return!!this.tremoloSpeed}get absoluteDisplayStart(){return this.voice.bar.masterBar.start+this.displayStart}get absolutePlaybackStart(){return this.voice.bar.masterBar.start+this.playbackStart}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get isBarre(){return this.barreShape!==V.None&&this.barreFret>=0}addWhammyBarPoint(e){let t=this.whammyBarPoints;null===t&&(t=[],this.whammyBarPoints=t),t.push(e),(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e),(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e),this.whammyBarType===I.None&&(this.whammyBarType=I.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=ee.toTicks(this.duration);return 2===this.dots?e=ee.applyDot(e,!0):1===this.dots&&(e=ee.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=ee.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){let e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case m.BeforeBeat:case m.OnBeat:switch(this.duration){case p.Sixteenth:this.playbackDuration=ee.toTicks(p.SixtyFourth);break;case p.ThirtySecond:this.playbackDuration=ee.toTicks(p.OneHundredTwentyEighth);break;default:this.playbackDuration=ee.toTicks(p.ThirtySecond)}this.displayDuration=0;break;case m.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;let t=this.previousBeat;t&&t.graceType===m.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){let e=this.previousBeat,t=e?e.tupletGroup:null;if((this.hasTuplet||this.graceType!==m.None&&t)&&(e&&t&&t.check(this)||(t=new me(this.voice),t.check(this)),this.tupletGroup=t),this.index>0){const e=this.voice.bar.masterBar.calculateDuration(),t=[];for(const s of this.automations)0===s.ratioPosition&&(s.ratioPosition=this.playbackStart/e),s.type!==a.Volume&&t.push(s);this.automations=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(Q.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case m.OnBeat:case m.BeforeBeat:let e=this.graceGroup.beats.length;this.duration=1===e?p.Eighth:2===e?p.Sixteenth:p.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,h=this.notes.length;a<h;a++){let h=this.notes[a];if(h.dynamics=this.dynamics,h.finish(e,t),h.isLetRing&&(this.isLetRing=!0),h.isPalmMute&&(this.isPalmMute=!0),s===T.SongBook&&h.hasBend&&this.graceType!==m.BendGrace){if(!h.isTieOrigin)switch(h.bendType){case d.Bend:case d.PrebendRelease:case d.PrebendBend:r=!0}i||h.bendStyle===l.Gradual?(i=!0,h.bendStyle=l.Gradual,r=!1):h.bendStyle=l.Fast}h.isVisible&&(n++,(!this.minNote||h.realValue<this.minNote.realValue)&&(this.minNote=h),(!this.maxNote||h.realValue>this.maxNote.realValue)&&(this.maxNote=h),(!this.minStringNote||h.string<this.minStringNote.string)&&(this.minStringNote=h),(!this.maxStringNote||h.string>this.maxStringNote.string)&&(this.maxStringNote=h),h.hasEffectSlur&&(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 h=this.whammyBarPoints,c=null!==h&&h.length>0;if(c){const e=!!this.previousBeat&&this.previousBeat.hasWhammyBar;this.isContinuedWhammy=e}else this.whammyBarType=I.None;if(c&&this.whammyBarType===I.Custom&&(s===T.SongBook&&(this.whammyStyle=i?l.Gradual:l.Fast),4===h.length)){let e=h[0],t=h[1],i=h[2],a=h[3];t.value===i.value&&(e.value<t.value&&t.value<a.value||e.value>t.value&&t.value>a.value?(0===e.value||this.isContinuedWhammy?this.whammyBarType=I.Dive:this.whammyBarType=I.PrediveDive,h.splice(2,1),h.splice(1,1)):e.value>t.value&&t.value<a.value||e.value<t.value&&t.value>a.value?(this.whammyBarType=I.Dip,t.offset!==i.offset&&s!==T.SongBook||h.splice(2,1)):e.value===t.value&&t.value===a.value&&(0===e.value||this.isContinuedWhammy?this.whammyBarType=I.Hold:this.whammyBarType=I.Predive,h.splice(2,1),h.splice(1,1)))}if(this.updateDurations(),r){let e=Se.clone(this);e.id=we._globalBeatId++,e.pickStroke=E.None;for(let t=0,s=e.notes.length;t<s;t++){let s=e.notes[t],i=this.notes[t];if(s.bendType=d.None,s.maxBendPoint=null,s.bendPoints=null,s.bendStyle=l.Default,s.id=ge.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=ge.findTieOrigin(i);if(e&&e.hasBend){s.bendType=d.Hold;let e=i.bendPoints[i.bendPoints.length-1];s.addBendPoint(new te(0,e.value)),s.addBendPoint(new te(te.MaxPosition,e.value))}}s.isTieDestination=!0}this.graceType=m.BendGrace,this.graceGroup=new _e,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new _e,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)}}we._globalBeatId=0;class Be{constructor(){this.name="",this.firstFret=1,this.strings=[],this.barreFrets=[],this.showName=!0,this.showDiagram=!0,this.showFingering=!0}get uniqueId(){return[this.name,this.firstFret.toString(),this.strings.join(","),this.barreFrets.join(","),this.showDiagram.toString(),this.showFingering.toString(),this.showName.toString()].join("|")}}!function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.Text=2]="Text",e[e.Comment=3]="Comment",e[e.Dash=4]="Dash"}(W||(W={}));class ke{constructor(){this.startBar=0,this.text=""}finish(e=!1){this.chunks=[],this.parse(this.text,0,this.chunks,e)}parse(e,t,s,i){if(!e)return;let a=W.Begin,r=W.Begin,n=!1,o=0;for(;t<e.length;){let s=e.charCodeAt(t);switch(a){case W.IgnoreSpaces:switch(s){case ke.CharCodeLF:case ke.CharCodeCR:case ke.CharCodeTab:break;case ke.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case W.Begin:if(s!==ke.CharCodeBrackedOpen){o=t,a=W.Text;continue}a=W.Comment;break;case W.Comment:if(s===ke.CharCodeBrackedClose)a=W.Begin;break;case W.Text:switch(s){case ke.CharCodeDash:a=W.Dash;break;case ke.CharCodeCR:case ke.CharCodeLF:case ke.CharCodeSpace:let s=e.substr(o,t-o);this.addChunk(s,i),a=W.IgnoreSpaces,r=W.Begin}break;case W.Dash:if(s!==ke.CharCodeDash){let s=e.substr(o,t-o);this.addChunk(s,i),n=!0,a=W.IgnoreSpaces,r=W.Begin;continue}}t+=1}a===W.Text&&t!==o&&this.addChunk(e.substr(o,t-o),i)}addChunk(e,t){e=this.prepareChunk(e),(!t||e.length>0&&"-"!==e)&&this.chunks.push(e)}prepareChunk(e){let t=e.split("+").join(" "),s=t.length;for(;s>0&&"_"===t.charAt(s-1);)s--;return s!==t.length?t.substr(0,s):t}}ke.CharCodeLF=10,ke.CharCodeTab=9,ke.CharCodeCR=13,ke.CharCodeSpace=32,ke.CharCodeBrackedClose=93,ke.CharCodeBrackedOpen=91,ke.CharCodeDash=45,function(e){e[e.NoBrackets=0]="NoBrackets",e[e.GroupStaves=1]="GroupStaves",e[e.GroupSimilarInstruments=2]="GroupSimilarInstruments"}(z||(z={})),function(e){e[e.Hidden=0]="Hidden",e[e.FirstSystem=1]="FirstSystem",e[e.AllSystems=2]="AllSystems"}(U||(U={})),function(e){e[e.FullName=0]="FullName",e[e.ShortName=1]="ShortName"}(X||(X={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical"}(J||(J={}));class Te{constructor(){this.hideDynamics=!1,this.bracketExtendMode=z.GroupStaves,this.useSystemSignSeparator=!1,this.globalDisplayTuning=!0,this.perTrackDisplayTuning=null,this.globalDisplayChordDiagramsOnTop=!0,this.perTrackChordDiagramsOnTop=null,this.singleTrackTrackNamePolicy=U.FirstSystem,this.multiTrackTrackNamePolicy=U.FirstSystem,this.firstSystemTrackNameMode=X.ShortName,this.otherSystemsTrackNameMode=X.ShortName,this.firstSystemTrackNameOrientation=J.Vertical,this.otherSystemsTrackNameOrientation=J.Vertical}}class xe{constructor(){this.masterBars=[],this.opening=null,this.closings=[],this.isClosed=!1}get openings(){const e=this.opening;return e?[e]:[]}get isOpened(){return!0===this.opening?.isRepeatStart}addMasterBar(e){null===this.opening&&(this.opening=e),this.masterBars.push(e),e.repeatGroup=this,e.isRepeatEnd&&(this.closings.push(e),this.isClosed=!0)}}class Ne{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 Te}rebuildRepeatGroups(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0;for(const e of this.masterBars)this.addMasterBarToRepeatGroups(e)}addMasterBar(e){e.score=this,e.index=this.masterBars.length,0!==this.masterBars.length&&(e.previousMasterBar=this.masterBars[this.masterBars.length-1],e.previousMasterBar.nextMasterBar=e,e.start=e.previousMasterBar.start+(e.previousMasterBar.isAnacrusis?0:e.previousMasterBar.calculateDuration())),this.addMasterBarToRepeatGroups(e),this.masterBars.push(e)}addMasterBarToRepeatGroups(e){e.isRepeatStart?(this._currentRepeatGroup?.isClosed&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--),this._currentRepeatGroup=new xe,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new xe,this._openedRepeatGroups.push(this._currentRepeatGroup)),this._currentRepeatGroup.addMasterBar(e),e.isRepeatEnd&&this._properlyOpenedRepeatGroups>1&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--,this._currentRepeatGroup=this._openedRepeatGroups.length>0?this._openedRepeatGroups[this._openedRepeatGroups.length-1]:null)}addTrack(e){e.score=this,e.index=this.tracks.length,this.tracks.push(e)}finish(e){const t=new Map;for(let s=0,i=this.tracks.length;s<i;s++)this.tracks[s].finish(e,t)}}class ve{constructor(){this.marker="",this.text=""}}class Pe extends j{constructor(e){super(s.Format,e),Object.setPrototypeOf(this,Pe.prototype)}}class Ce{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="#"+le.toHexString(this.r,2)+le.toHexString(this.g,2)+le.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 Ce(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){if(e instanceof Ce)return e;switch(typeof e){case"number":{const t=new Ce(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 Ce(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16));if(5===t.length)return new Ce(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 Ce(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16));if(9===t.length)return new Ce(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 Pe("No values specified for rgb/rgba function");const i=t.substring(e+1,s).split(",");if(3===i.length)return new Ce(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]));if(4===i.length)return new Ce(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]),255*parseFloat(i[3]))}return null}}throw new Pe("Unsupported format for color")}static toJson(e){return e.raw}}Ce.BlackRgb="#000000";class Ee{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 Fe{static getTextForTuning(e,t){let s=Fe.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 Fe._defaultTunings.has(e)?Fe._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return Fe._sevenStrings;case 6:return Fe._sixStrings;case 5:return Fe._fiveStrings;case 4:return Fe._fourStrings}return[]}static initialize(){Fe._defaultTunings.set(7,new Fe("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),Fe._sevenStrings.push(Fe._defaultTunings.get(7)),Fe._defaultTunings.set(6,new Fe("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),Fe._sixStrings.push(Fe._defaultTunings.get(6)),Fe._sixStrings.push(new Fe("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),Fe._sixStrings.push(new Fe("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),Fe._sixStrings.push(new Fe("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),Fe._sixStrings.push(new Fe("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),Fe._sixStrings.push(new Fe("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),Fe._sixStrings.push(new Fe("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),Fe._sixStrings.push(new Fe("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),Fe._sixStrings.push(new Fe("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),Fe._sixStrings.push(new Fe("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),Fe._sixStrings.push(new Fe("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),Fe._sixStrings.push(new Fe("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),Fe._sixStrings.push(new Fe("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),Fe._sixStrings.push(new Fe("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),Fe._sixStrings.push(new Fe("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),Fe._sixStrings.push(new Fe("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),Fe._sixStrings.push(new Fe("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),Fe._sixStrings.push(new Fe("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),Fe._sixStrings.push(new Fe("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),Fe._defaultTunings.set(5,new Fe("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),Fe._fiveStrings.push(Fe._defaultTunings.get(5)),Fe._fiveStrings.push(new Fe("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),Fe._fiveStrings.push(new Fe("Banjo Open D Tuning",[62,57,54,50,69],!1)),Fe._fiveStrings.push(new Fe("Banjo Open G Tuning",[62,59,55,50,67],!1)),Fe._fiveStrings.push(new Fe("Banjo G Minor Tuning",[62,58,55,50,67],!1)),Fe._fiveStrings.push(new Fe("Banjo G Modal Tuning",[62,57,55,50,67],!1)),Fe._defaultTunings.set(4,new Fe("Bass Standard Tuning",[43,38,33,28],!0)),Fe._fourStrings.push(Fe._defaultTunings.get(4)),Fe._fourStrings.push(new Fe("Bass Tune down ½ step",[42,37,32,27],!1)),Fe._fourStrings.push(new Fe("Bass Tune down 1 step",[41,36,31,26],!1)),Fe._fourStrings.push(new Fe("Bass Tune down 2 step",[39,34,29,24],!1)),Fe._fourStrings.push(new Fe("Bass Dropped D Tuning",[43,38,33,26],!1)),Fe._fourStrings.push(new Fe("Ukulele C Tuning",[45,40,36,43],!1)),Fe._fourStrings.push(new Fe("Ukulele G Tuning",[52,47,43,38],!1)),Fe._fourStrings.push(new Fe("Mandolin Standard Tuning",[64,57,50,43],!1)),Fe._fourStrings.push(new Fe("Mandolin or Violin Tuning",[76,69,62,55],!1)),Fe._fourStrings.push(new Fe("Viola Tuning",[69,62,55,48],!1)),Fe._fourStrings.push(new Fe("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){let t=Fe.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=Fe.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}Fe._sevenStrings=[],Fe._sixStrings=[],Fe._fiveStrings=[],Fe._fourStrings=[],Fe._defaultTunings=new Map,Fe.defaultAccidentals=["","#","","#","","","#","","#","","#",""],Fe.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],Fe.initialize();class De{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new Fe("",[],!1),this.showSlash=!1,this.showNumbered=!1,this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=De.DefaultStandardNotationLineCount}get tuning(){return this.stringTuning.tunings}get tuningName(){return this.stringTuning.name}get isStringed(){return this.stringTuning.tunings.length>0}finish(e,t=null){this.stringTuning.finish();for(let s=0,i=this.bars.length;s<i;s++)this.bars[s].finish(e,t)}addChord(e,t){t.staff=this;let s=this.chords;null===s&&(s=new Map,this.chords=s),s.set(e,t)}hasChord(e){return this.chords?.has(e)??!1}getChord(e){return this.chords?.get(e)??null}addBar(e){let t=this.bars;e.staff=this,e.index=t.length,t.length>0&&(e.previousBar=t[t.length-1],e.previousBar.nextBar=e),t.push(e)}}De.DefaultStandardNotationLineCount=5;class Le{constructor(){this.index=0,this.staves=[],this.playbackInfo=new Ee,this.color=new Ce(200,0,0,255),this.name="",this.isVisibleOnMultiTrack=!0,this.shortName="",this.defaultSystemsLayout=3,this.systemsLayout=[],this.percussionArticulations=[]}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new De)}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>Le.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,Le.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)}}}}}Le.ShortNameMaxLength=10;let Me=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===m.None?(i.graceGroup=s,s&&(s.isComplete=!0),s=null):(s||(s=new _e),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===m.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==m.BendGrace){let s=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case m.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 m.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}};Me._globalBarId=0;class Ie{static float64ToBytes(e){return Ie._dataView.setFloat64(0,e,!0),this._conversionByteArray}static bytesToInt64LE(e){Ie._conversionByteArray.set(e,0);const t=Ie._dataView.getBigInt64(0,!0);return t<=Number.MAX_SAFE_INTEGER&&t>=Number.MIN_SAFE_INTEGER?Number(t):Number.MAX_SAFE_INTEGER}static bytesToFloat64LE(e){return Ie._conversionByteArray.set(e,0),Ie._dataView.getFloat64(0,!0)}static bytesToFloat32LE(e){return Ie._conversionByteArray.set(e,0),Ie._dataView.getFloat32(0,!0)}static float32BEToBytes(e){return Ie._dataView.setFloat32(0,e,!1),Ie._conversionByteArray.slice(0,4)}static uint16ToInt16(e){return Ie._dataView.setUint16(0,e,!0),Ie._dataView.getInt16(0,!0)}static int16ToUint32(e){return Ie._dataView.setInt16(0,e,!0),Ie._dataView.getUint32(0,!0)}static int32ToUint16(e){return Ie._dataView.setInt32(0,e,!0),Ie._dataView.getUint16(0,!0)}static int32ToInt16(e){return Ie._dataView.setInt32(0,e,!0),Ie._dataView.getInt16(0,!0)}static int32ToUint32(e){return Ie._dataView.setInt32(0,e,!0),Ie._dataView.getUint32(0,!0)}static uint8ToInt8(e){return Ie._dataView.setUint8(0,e),Ie._dataView.getInt8(0)}}Ie._conversionBuffer=new ArrayBuffer(8),Ie._conversionByteArray=new Uint8Array(Ie._conversionBuffer),Ie._dataView=new DataView(Ie._conversionBuffer);class Ae{static readInt32BE(e){return e.readByte()<<24|e.readByte()<<16|e.readByte()<<8|e.readByte()}static readFloat32BE(e){const t=new Uint8Array(4);return e.read(t,0,t.length),t.reverse(),Ie.bytesToFloat32LE(t)}static readFloat64BE(e){const t=new Uint8Array(8);return e.read(t,0,t.length),t.reverse(),Ie.bytesToFloat64LE(t)}static readInt32LE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static readInt64LE(e){const t=new Uint8Array(8);return e.read(t,0,t.length),Ie.bytesToInt64LE(t)}static readUInt32LE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static decodeUInt32LE(e,t){let s=e[t],i=e[t+1],a=e[t+2];return e[t+3]<<24|a<<16|i<<8|s}static readUInt16LE(e){let t=e.readByte(),s=e.readByte();return Ie.int32ToUint16(s<<8|t)}static readInt16LE(e){let t=e.readByte(),s=e.readByte();return Ie.int32ToInt16(s<<8|t)}static readUInt32BE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte(),a=e.readByte();return Ie.int32ToUint32(t<<24|s<<16|i<<8|a)}static readUInt16BE(e){let t=e.readByte(),s=e.readByte();return Ie.int32ToInt16(t<<8|s)}static readInt16BE(e){let t=e.readByte(),s=e.readByte();return Ie.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),Ae.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 Ie.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){let s=Ae.detectEncoding(e);return s&&(t=s),t||(t="utf-8"),new TextDecoder(t).decode(e.buffer)}static detectEncoding(e){return e.length>2&&254===e[0]&&255===e[1]?"utf-16be":e.length>2&&255===e[0]&&254===e[1]?"utf-16le":e.length>4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3]?"utf-32be":e.length>4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3]?"utf-32le":null}static stringToBytes(e){return(new TextEncoder).encode(e)}static writeInt32BE(e,t){e.writeByte(t>>24&255),e.writeByte(t>>16&255),e.writeByte(t>>8&255),e.writeByte(255&t)}static writeInt32LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255),e.writeByte(t>>16&255),e.writeByte(t>>24&255)}static writeUInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16BE(e,t){e.writeByte(t>>8&255),e.writeByte(255&t)}static writeFloat32BE(e,t){const s=Ie.float32BEToBytes(t);e.write(s,0,s.length)}}class Oe{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return Oe.withCapacity(0)}static withCapacity(e){let t=new Oe;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){let t=new Oe;return t._buffer=e,t.length=e.length,t}static fromString(e){let t=Ae.stringToBytes(e);return Oe.fromBuffer(t)}reset(){this.position=0}skip(e){this.position+=e}readByte(){return this.length-this.position<=0?-1:this._buffer[this.position++]}read(e,t,s){let i=this.length-this.position;return i>s&&(i=s),i<=0?0:(e.set(this._buffer.subarray(this.position,this.position+i),t),this.position+=i,i)}writeByte(e){let t=this.position+1;this.ensureCapacity(t),this._buffer[this.position]=255&e,t>this.length&&(this.length=t),this.position=t}write(e,t,s){let i=this.position+s;this.ensureCapacity(i);let a=Math.min(s,e.length-t);this._buffer.set(e.subarray(t,t+a),this.position),i>this.length&&(this.length=i),this.position=i}ensureCapacity(e){if(e>this._buffer.length){let t=e;t<256&&(t=256),t<2*this._buffer.length&&(t=2*this._buffer.length);let s=new Uint8Array(t);this.length>0&&s.set(this._buffer.subarray(0,0+this.length),0),this._buffer=s}}readAll(){return this.toArray()}toArray(){let e=new Uint8Array(this.length);return e.set(this._buffer.subarray(0,0+this.length),0),e}copyTo(e){e.write(this._buffer,0,this.length)}}class Re{}var Ve,He,Ge,We,ze,Ue,Xe,Je,Ye,qe,je,Ke,Qe,$e;Re.DefaultChannelCount=17,Re.MetronomeChannel=Re.DefaultChannelCount-1,Re.MetronomeKey=33,Re.AudioChannels=2,Re.MinVolume=0,Re.MinProgram=0,Re.MaxProgram=127,Re.MinPlaybackSpeed=.125,Re.MaxPlaybackSpeed=8,Re.PercussionChannel=9,Re.PercussionBank=128,Re.MaxPitchWheel=16384,Re.MaxPitchWheel20=4294967296,Re.DefaultPitchWheel=Re.MaxPitchWheel/2,Re.MicroBufferCount=32,Re.MicroBufferSize=64,function(e){e[e.TargetFine=0]="TargetFine",e[e.TargetSegno=1]="TargetSegno",e[e.TargetSegnoSegno=2]="TargetSegnoSegno",e[e.TargetCoda=3]="TargetCoda",e[e.TargetDoubleCoda=4]="TargetDoubleCoda",e[e.JumpDaCapo=5]="JumpDaCapo",e[e.JumpDaCapoAlCoda=6]="JumpDaCapoAlCoda",e[e.JumpDaCapoAlDoubleCoda=7]="JumpDaCapoAlDoubleCoda",e[e.JumpDaCapoAlFine=8]="JumpDaCapoAlFine",e[e.JumpDalSegno=9]="JumpDalSegno",e[e.JumpDalSegnoAlCoda=10]="JumpDalSegnoAlCoda",e[e.JumpDalSegnoAlDoubleCoda=11]="JumpDalSegnoAlDoubleCoda",e[e.JumpDalSegnoAlFine=12]="JumpDalSegnoAlFine",e[e.JumpDalSegnoSegno=13]="JumpDalSegnoSegno",e[e.JumpDalSegnoSegnoAlCoda=14]="JumpDalSegnoSegnoAlCoda",e[e.JumpDalSegnoSegnoAlDoubleCoda=15]="JumpDalSegnoSegnoAlDoubleCoda",e[e.JumpDalSegnoSegnoAlFine=16]="JumpDalSegnoSegnoAlFine",e[e.JumpDaCoda=17]="JumpDaCoda",e[e.JumpDaDoubleCoda=18]="JumpDaDoubleCoda"}(Ve||(Ve={})),function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(He||(He={}));class Ze{constructor(){this.type=He.Short,this.length=0}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(Ge||(Ge={})),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"}(We||(We={})),function(e){e[e.KnownStaffMeta=0]="KnownStaffMeta",e[e.UnknownStaffMeta=1]="UnknownStaffMeta",e[e.EndOfMetaDetected=2]="EndOfMetaDetected"}(ze||(ze={}));class et extends j{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??We.No,this.symbol=o??We.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 ${We[a]} found a ${We[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)}}!function(e){e[e.Auto=0]="Auto",e[e.Explicit=1]="Explicit"}(Ue||(Ue={}));class tt extends q{constructor(){super(),this._trackChannel=0,this._barIndex=0,this._voiceIndex=0,this._input="",this._ch=tt.Eof,this._curChPos=0,this._line=1,this._col=0,this._lastValidSpot=[0,1,0],this._sy=We.No,this._syData="",this._allowNegatives=!1,this._allowFloat=!1,this._allowTuning=!1,this._currentDuration=p.QuadrupleWhole,this._currentDynamics=g.PPP,this._currentTuplet=0,this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._percussionArticulationNames=new Map,this._sustainPedalToBeat=new Map,this._slurs=new Map,this._accidentalMode=Ue.Explicit,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=Oe.empty(),this._input=e,this.settings=t}readScore(){try{if(this.data.length>0&&(this._input=Ae.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this._sustainPedalToBeat=new Map,this.createDefaultScore(),this._curChPos=0,this._line=1,this._col=0,this.saveValidSpot(),this._currentDuration=p.Quarter,this._currentDynamics=g.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===We.LowerThan)throw new K("Unknown start sign '<' (meant to import as XML?)");if(this._sy!==We.Eof){const e=this.metaData(),t=this.bars();if(!e&&!t)throw new K("No alphaTex data found")}this.consolidate(),this._score.finish(this.settings),this._score.rebuildRepeatGroups();for(const[e,t]of this._lyrics)this._score.tracks[e].applyLyrics(t);for(const[e,t]of this._sustainPedalToBeat)if(0===e.ratioPosition){const s=t.voice.bar.masterBar.calculateDuration();e.ratioPosition=t.playbackStart/s}return this._score}catch(e){throw e instanceof et?new K(e.message,e):e}}consolidate(){if(0===this._score.masterBars.length){const e=new ne;this._score.addMasterBar(e);const t=new Q;t.isLinear=!1,t.type=a.Tempo,t.value=this._score.tempo,e.tempoAutomations.push(t);const s=new Z;this._score.tracks[0].staves[0].addBar(s);const i=new Me;s.addVoice(i);const r=new we;return r.isEmpty=!0,void i.addBeat(r)}for(let e of this._score.tracks)for(let t of e.staves){for(const e of t.bars)for(const t of e.voices)if(t.isEmpty&&0==t.beats.length){const e=new we;e.isEmpty=!0,t.addBeat(e)}const e=0===t.bars.length?1:t.bars[0].voices.length;for(;t.bars.length<this._score.masterBars.length;){const s=new Z;t.addBar(s);for(let t=0;t<e;t++){const e=new Me;s.addVoice(e);const t=new we;t.isEmpty=!0,e.addBeat(t)}}}}error(e,t,s=!0){let i,a=!1;s?(i=this._sy,i!==We.String&&i!==We.Number&&i!==We.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&&re.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&&re.error(this.name,t.message),t}createDefaultScore(){this._score=new Ne,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new Le,this._currentTrack.ensureStaveCount(1),this._currentTrack.playbackInfo.program=25,this._currentTrack.playbackInfo.primaryChannel=this._trackChannel++,this._currentTrack.playbackInfo.secondaryChannel=this._trackChannel++;const e=this._currentTrack.staves[0];e.displayTranspositionPitch=0,e.stringTuning.tunings=Fe.getDefaultTuningFor(6).tunings,this.beginStaff(e),this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=g.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":default:return 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 C.NoTripletFeel;case"t16":case"triplet-16th":return C.Triplet16th;case"t8":case"triplet-8th":return C.Triplet8th;case"d16":case"dotted-16th":return C.Dotted16th;case"d8":case"dotted-8th":return C.Dotted8th;case"s16":case"scottish-16th":return C.Scottish16th;case"s8":case"scottish-8th":return C.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return C.NoTripletFeel;case 1:return C.Triplet16th;case 2:return C.Triplet8th;case 3:return C.Dotted16th;case 4:return C.Dotted8th;case 5:return C.Scottish16th;case 6:return C.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":case"abminor":return v.Cb;case"gb":case"gbmajor":case"ebminor":return v.Gb;case"db":case"dbmajor":case"bbminor":return v.Db;case"ab":case"abmajor":case"fminor":return v.Ab;case"eb":case"ebmajor":case"cminor":return v.Eb;case"bb":case"bbmajor":case"gminor":return v.Bb;case"f":case"fmajor":case"dminor":return v.F;case"c":case"cmajor":case"aminor":default:return v.C;case"g":case"gmajor":case"eminor":return v.G;case"d":case"dmajor":case"bminor":return v.D;case"a":case"amajor":case"f#minor":return v.A;case"e":case"emajor":case"c#minor":return v.E;case"b":case"bmajor":case"g#minor":return v.B;case"f#":case"f#major":case"d#minor":return v.FSharp;case"c#":case"c#major":case"a#minor":return v.CSharp}}parseKeySignatureType(e){return e.toLowerCase().endsWith("minor")?P.Minor:P.Major}nextChar(){return this._curChPos<this._input.length?(this._ch=this._input.charCodeAt(this._curChPos++),10===this._ch?(this._line++,this._col=0):this._col++):this._ch=tt.Eof,this._ch}saveValidSpot(){this._lastValidSpot=[this._curChPos,this._line,this._col]}newSy(){for(this.saveValidSpot(),this._sy=We.No;this._sy===We.No;)if(this._ch===tt.Eof)this._sy=We.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",We.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=We.String;this._ch!==e&&this._ch!==tt.Eof;)92===this._ch?(this._ch=this.nextChar(),92===this._ch?t+="\\":this._ch==e?t+=String.fromCharCode(this._ch):82==this._ch||114==this._ch?t+="\r":78==this._ch||110==this._ch?t+="\n":84==this._ch||116==this._ch?t+="\t":this.errorMessage("Unsupported escape sequence")):t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._ch===tt.Eof&&this.errorMessage("String opened but never closed"),this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)this._allowNegatives?this.readNumberOrName():(this._sy=We.String,this._syData=this.readName());else if(46===this._ch)this._sy=We.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=We.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=We.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=We.MetaCommand,92===this._ch&&(this._ch=this.nextChar()),this._syData=this.readName();else if(41===this._ch)this._sy=We.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=We.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=We.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=We.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=We.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=We.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this.readNumberOrName();else if(tt.isNameLetter(this._ch)){let e=this.readName(),t=this._allowTuning?le.parseTuning(e):null;t?(this._sy=We.Tuning,this._syData=t):(this._sy=We.String,this._syData=e)}else this.error("symbol",We.String,!1);return this._sy}readNumberOrName(){let e="",t=!0;do{e+=String.fromCharCode(this._ch),this.isDigit(this._ch)||(t=!1),this._ch=this.nextChar()}while(this.isDigit(this._ch)||tt.isNameLetter(this._ch));t?(this._sy=We.Number,this._syData=this._allowFloat?parseFloat(e):parseInt(e)):(this._sy=We.String,this._syData=e)}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||42===e||92===e}static isWhiteSpace(e){return 9===e||10===e||11===e||13===e||32===e}isDigit(e){return e>=48&&e<=57||this._allowNegatives&&45===e||this._allowFloat&&46===e}readName(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(tt.isNameLetter(this._ch)||this.isDigit(this._ch));return e}metaData(){let e=!1,t=!1,s=!0;for(;this._sy===We.MetaCommand&&s;){let i=this._syData.toLowerCase();switch(i){case"title":case"subtitle":case"artist":case"album":case"words":case"music":case"copyright":case"instructions":case"notices":case"tab":this._sy=this.newSy(),this._sy!==We.String&&this.error(i,We.String,!0);let a=this._syData;switch(i){case"title":this._score.title=a;break;case"subtitle":this._score.subTitle=a;break;case"artist":this._score.artist=a;break;case"album":this._score.album=a;break;case"words":this._score.words=a;break;case"music":this._score.music=a;break;case"copyright":this._score.copyright=a;break;case"instructions":this._score.instructions=a;break;case"notices":this._score.notices=a;break;case"tab":this._score.tab=a}this._sy=this.newSy(),e=!0;break;case"tempo":this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy===We.Number?this._score.tempo=this._syData:this.error("tempo",We.Number,!0),this._sy=this.newSy(),this._sy===We.String&&(this._score.tempoLabel=this._syData,this._sy=this.newSy()),e=!0;break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===We.Number?(this._score.defaultSystemsLayout=this._syData,this._sy=this.newSy(),e=!0):this.error("default-systems-layout",We.Number,!0);break;case"systemslayout":for(this._sy=this.newSy(),e=!0;this._sy===We.Number;)this._score.systemsLayout.push(this._syData),this._sy=this.newSy();break;case"hidedynamics":this._score.stylesheet.hideDynamics=!0,this._sy=this.newSy(),e=!0;break;case"showdynamics":this._score.stylesheet.hideDynamics=!1,this._sy=this.newSy(),e=!0;break;case"bracketextendmode":this._sy=this.newSy(),this._sy!==We.String&&this.error("bracketExtendMode",We.String,!0),this._score.stylesheet.bracketExtendMode=this.parseBracketExtendMode(this._syData),this._sy=this.newSy(),e=!0;break;case"usesystemsignseparator":this._score.stylesheet.useSystemSignSeparator=!0,this._sy=this.newSy(),e=!0;break;case"singletracktracknamepolicy":this._sy=this.newSy(),this._sy!==We.String&&this.error("singleTrackTrackNamePolicy",We.String,!0),this._score.stylesheet.singleTrackTrackNamePolicy=this.parseTrackNamePolicy(this._syData),this._sy=this.newSy(),e=!0;break;case"multitracktracknamepolicy":this._sy=this.newSy(),this._sy!==We.String&&this.error("multiTrackTrackNamePolicy",We.String,!0),this._score.stylesheet.multiTrackTrackNamePolicy=this.parseTrackNamePolicy(this._syData),this._sy=this.newSy(),e=!0;break;case"firstsystemtracknamemode":this._sy=this.newSy(),this._sy!==We.String&&this.error("firstSystemTrackNameMode",We.String,!0),this._score.stylesheet.firstSystemTrackNameMode=this.parseTrackNameMode(this._syData),this._sy=this.newSy(),e=!0;break;case"othersystemstracknamemode":this._sy=this.newSy(),this._sy!==We.String&&this.error("otherSystemsTrackNameMode",We.String,!0),this._score.stylesheet.otherSystemsTrackNameMode=this.parseTrackNameMode(this._syData),this._sy=this.newSy(),e=!0;break;case"firstsystemtracknameorientation":this._sy=this.newSy(),this._sy!==We.String&&this.error("firstSystemTrackNameOrientation",We.String,!0),this._score.stylesheet.firstSystemTrackNameOrientation=this.parseTrackNameOrientation(this._syData),this._sy=this.newSy(),e=!0;break;case"othersystemstracknameorientation":this._sy=this.newSy(),this._sy!==We.String&&this.error("otherSystemsTrackNameOrientation",We.String,!0),this._score.stylesheet.otherSystemsTrackNameOrientation=this.parseTrackNameOrientation(this._syData),this._sy=this.newSy(),e=!0;break;default:switch(this.handleStaffMeta()){case ze.KnownStaffMeta:t=!0;break;case ze.UnknownStaffMeta:e||t?this.error("metaDataTags",We.String,!1):s=!1;break;case ze.EndOfMetaDetected:s=!1}}}return e?(this._sy!==We.Dot&&this.error("song",We.Dot,!0),this._sy=this.newSy()):this._sy===We.Dot&&(this._sy=this.newSy(),e=!0),e||t}parseTrackNamePolicy(e){switch(e.toLowerCase()){case"hidden":return U.Hidden;case"allsystems":return U.AllSystems;default:return U.FirstSystem}}parseTrackNameMode(e){return"fullname"===e.toLowerCase()?X.FullName:X.ShortName}parseTrackNameOrientation(e){return"horizontal"===e.toLowerCase()?J.Horizontal:J.Vertical}handleStaffMeta(){switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===We.Number?this._currentStaff.capo=this._syData:this.error("capo",We.Number,!0),this._sy=this.newSy(),ze.KnownStaffMeta;case"tuning":this._sy=this.newSy();let e=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case We.String:let e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?this.makeCurrentStaffPitched():this.error("tuning",We.Tuning,!0),this._sy=this.newSy();break;case We.Tuning:let t=[];do{let e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===We.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",We.Tuning,!0)}return this._sy===We.String&&"hide"===this._syData.toLowerCase()&&(this._score.stylesheet.perTrackDisplayTuning||(this._score.stylesheet.perTrackDisplayTuning=new Map),this._score.stylesheet.perTrackDisplayTuning.set(this._currentTrack.index,!1),this._sy=this.newSy()),e!==this._currentStaff.tuning.length&&(this._currentStaff.chords?.size??0)>0&&this.errorMessage("Tuning must be defined before any chord"),ze.KnownStaffMeta;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===We.Number){let e=this._syData;e>=0&&e<=127?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",We.Number,!1)}else if(this._sy===We.String){let e=this._syData.toLowerCase();if("percussion"===e){for(const e of this._currentTrack.staves)this.applyPercussionStaff(e);this._currentTrack.playbackInfo.primaryChannel=Re.PercussionChannel,this._currentTrack.playbackInfo.secondaryChannel=Re.PercussionChannel}else this._currentTrack.playbackInfo.program=Y.getValue(e)}else this.error("instrument",We.Number,!0);return this._sy=this.newSy(),ze.KnownStaffMeta;case"lyrics":this._sy=this.newSy();let t=new ke;return t.startBar=0,t.text="",this._sy===We.Number&&(t.startBar=this._syData,this._sy=this.newSy()),this._sy===We.String?(t.text=this._syData,this._sy=this.newSy()):this.error("lyrics",We.String,!0),this._lyrics.get(this._currentTrack.index).push(t),ze.KnownStaffMeta;case"chord":this._sy=this.newSy();let s=new Be;this.chordProperties(s),this._sy===We.String?(s.name=this._syData,this._sy=this.newSy()):this.error("chord-name",We.String,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===We.Number?s.strings.push(this._syData):this._sy===We.String&&"x"===this._syData.toLowerCase()&&s.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,s.name),s),ze.KnownStaffMeta;case"articulation":this._sy=this.newSy();let i="";if(this._sy===We.String?(i=this._syData,this._sy=this.newSy()):this.error("articulation-name",We.String,!0),"defaults"===i){for(const[e,t]of ue.instrumentArticulationNames)this._percussionArticulationNames.set(e.toLowerCase(),t),this._percussionArticulationNames.set(tt.toArticulationId(e),t);return ze.KnownStaffMeta}let a=0;return this._sy===We.Number?(a=this._syData,this._sy=this.newSy()):this.error("articulation-number",We.Number,!0),ue.instrumentArticulations.has(a)||this.errorMessage(`Unknown articulation ${a}. Refer to https://www.alphatab.net/docs/alphatex/percussion for available ids`),this._percussionArticulationNames.set(i.toLowerCase(),a),ze.KnownStaffMeta;case"accidentals":return this.handleAccidentalMode(),ze.KnownStaffMeta;case"displaytranspose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===We.Number?(this._currentStaff.displayTranspositionPitch=-1*this._syData,this._staffHasExplicitDisplayTransposition=!0):this.error("displaytranspose",We.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),ze.KnownStaffMeta;case"transpose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===We.Number?this._currentStaff.transpositionPitch=-1*this._syData:this.error("transpose",We.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),ze.KnownStaffMeta;case"track":case"staff":return ze.EndOfMetaDetected;case"voice":return this._sy=this.newSy(),this.handleNewVoice()?ze.EndOfMetaDetected:ze.KnownStaffMeta;default:return ze.UnknownStaffMeta}}handleAccidentalMode(){switch(this._sy=this.newSy(),this._sy!==We.String&&this.error("accidental-mode",We.String,!0),this._syData){case"auto":this._accidentalMode=Ue.Auto;break;case"explicit":this._accidentalMode=Ue.Explicit}this._sy=this.newSy()}makeCurrentStaffPitched(){this._currentStaff.stringTuning.tunings=[],this._staffHasExplicitDisplayTransposition||(this._currentStaff.displayTranspositionPitch=0)}static toArticulationId(e){return e.replace(new RegExp("[^a-zA-Z0-9]","g"),"").toLowerCase()}applyPercussionStaff(e){e.isPercussion=!0,e.showTablature=!1}chordProperties(e){if(this._sy===We.LBrace){for(this._sy=this.newSy();this._sy===We.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===We.Number)e.firstFret=this._syData;else this.error("chord-firstfret",We.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case We.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case We.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",We.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case We.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case We.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",We.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case We.String:e.showName="false"!==this._syData.toLowerCase();break;case We.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",We.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===We.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",We.String,!1)}this._sy!==We.RBrace&&this.error("chord-properties",We.RBrace,!0),this._sy=this.newSy()}}bars(){let e=this.bar();for(;this._sy!==We.Eof;)if(this._sy===We.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==We.MetaCommand)break;this.bar()}return e}trackStaffMeta(){if(this._sy!==We.MetaCommand)return!1;if("track"===this._syData.toLowerCase()&&(this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===We.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===We.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy()),this.trackProperties()),this._sy===We.MetaCommand&&"staff"===this._syData.toLowerCase()){if(this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0){const e=this._currentStaff.isPercussion;this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this.beginStaff(this._currentTrack.staves[this._currentTrack.staves.length-1]),e&&this.applyPercussionStaff(this._currentStaff),this._currentDynamics=g.F}this.staffProperties()}return this._sy===We.MetaCommand&&"voice"===this._syData.toLowerCase()&&(this._sy=this.newSy(),this.handleNewVoice()),!0}handleNewVoice(){if(0===this._voiceIndex&&(0==this._currentStaff.bars.length||1===this._currentStaff.bars.length&&this._currentStaff.bars[0].isEmpty))return!1;for(const e of this._currentStaff.bars){const t=new Me;e.addVoice(t)}return this._voiceIndex++,this._barIndex=0,!0}beginStaff(e){this._currentStaff=e,this._slurs.clear(),this._barIndex=0,this._voiceIndex=0}trackProperties(){if(this._sy===We.LBrace){for(this._sy=this.newSy();this._sy===We.String;)switch(this._syData.toLowerCase()){case"color":this._sy=this.newSy(),this._sy!==We.String&&this.error("track-color",We.String,!0),this._currentTrack.color=Ce.fromJson(this._syData),this._sy=this.newSy();break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===We.Number?(this._currentTrack.defaultSystemsLayout=this._syData,this._sy=this.newSy()):this.error("default-systems-layout",We.Number,!0);break;case"systemslayout":for(this._sy=this.newSy();this._sy===We.Number;)this._currentTrack.systemsLayout.push(this._syData),this._sy=this.newSy();break;case"volume":this._sy=this.newSy(),this._sy!==We.Number&&this.error("track-volume",We.Number,!0),this._currentTrack.playbackInfo.volume=le.clamp(this._syData,0,16),this._sy=this.newSy();break;case"balance":this._sy=this.newSy(),this._sy!==We.Number&&this.error("track-balance",We.Number,!0),this._currentTrack.playbackInfo.balance=le.clamp(this._syData,0,16),this._sy=this.newSy();break;case"mute":this._sy=this.newSy(),this._currentTrack.playbackInfo.isMute=!0;break;case"solo":this._sy=this.newSy(),this._currentTrack.playbackInfo.isSolo=!0;break;default:this.error("track-properties",We.String,!1)}this._sy!==We.RBrace&&this.error("track-properties",We.RBrace,!0),this._sy=this.newSy()}}staffProperties(){if(this._sy!==We.LBrace)return;this._sy=this.newSy();let e=!1,t=!1,s=!1,i=!1;for(;this._sy===We.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy(),this._sy===We.Number&&(this._currentStaff.standardNotationLineCount=this._syData,this._sy=this.newSy());break;case"tabs":t=!0,this._sy=this.newSy();break;case"slash":s=!0,this._sy=this.newSy();break;case"numbered":i=!0,this._sy=this.newSy();break;default:this.error("staff-properties",We.String,!1)}(e||t||s||i)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t,this._currentStaff.showSlash=s,this._currentStaff.showNumbered=i),this._sy!==We.RBrace&&this.error("staff-properties",We.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 ne;this._score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.timeSignatureDenominator=e.previousMasterBar.timeSignatureDenominator,e.timeSignatureNumerator=e.previousMasterBar.timeSignatureNumerator,e.tripletFeel=e.previousMasterBar.tripletFeel)}const s=this.barMeta(t),i=this._currentTrack.playbackInfo.program;this._staffTuningApplied||this._staffHasExplicitTuning||(this._currentStaff.stringTuning.tunings=[],15==i||i>=24&&i<=31?this._currentStaff.stringTuning.tunings=Fe.getDefaultTuningFor(6).tunings:i>=32&&i<=39?this._currentStaff.stringTuning.tunings=[43,38,33,28]:40==i||44==i||45==i||48==i||49==i||50==i||51==i?this._currentStaff.stringTuning.tunings=[52,57,50,43]:41==i?this._currentStaff.stringTuning.tunings=[57,50,43,36]:42==i?this._currentStaff.stringTuning.tunings=[45,38,31,24]:43==i?this._currentStaff.stringTuning.tunings=[43,38,33,28]:105==i?this._currentStaff.stringTuning.tunings=[50,47,43,38,55]:106==i?this._currentStaff.stringTuning.tunings=[57,52,45]:107==i?this._currentStaff.stringTuning.tunings=[52,45,38,31]:110==i&&(this._currentStaff.stringTuning.tunings=[64,57,50,43]),this._staffTuningApplied=!0),this._staffHasExplicitDisplayTransposition||(this._currentStaff.displayTranspositionPitch=i>=24&&i<=31||i>=32&&i<=39||43==i?-12:0);let a=!1,r=t.voices[this._voiceIndex];if(!(this._sy===We.MetaCommand&&("track"===this._syData.toLowerCase()||"staff"===this._syData.toLowerCase())))for(;this._sy!==We.Pipe&&this._sy!==We.Eof&&this.beat(r);)a=!0;if(0===r.beats.length){let e=new we;e.isEmpty=!0,r.addBeat(e)}return e||s||a}newBar(e){if(this._barIndex<e.bars.length){const t=e.bars[this._barIndex];return this._barIndex++,t}const t=0===e.bars.length?1:e.bars[0].voices.length,s=new Z;e.addBar(s),s.previousBar&&(s.clef=s.previousBar.clef,s.clefOttava=s.previousBar.clefOttava),this._barIndex++;for(let e=0;e<t;e++){let e=new Me;s.addVoice(e)}return s}beat(e){this.beatDuration();let t=new we;if(e.addBeat(t),this._allowTuning=!this._currentStaff.isPercussion,this._sy===We.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==We.RParensis&&this._sy!==We.Eof&&(this._allowTuning=!this._currentStaff.isPercussion,this.note(t)););this._sy!==We.RParensis&&this.error("note-list",We.RParensis,!0),this._sy=this.newSy()}else if(this._sy===We.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===We.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==We.Number&&this.error("duration",We.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===We.Multiply&&(this._sy=this.newSy(),this._sy!==We.Number?this.error("multiplier",We.Number,!0):s=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let i=0;i<s-1;i++)e.addBeat(Se.clone(t));return!0}beatDuration(){if(this._sy===We.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==We.Number&&this.error("duration",We.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===We.LBrace)){for(this._sy=this.newSy();this._sy===We.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==We.Number&&this.error("duration-tuplet",We.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",We.String,!1)}this._sy!==We.RBrace&&this.error("beat-duration",We.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===We.LBrace){for(this._sy=this.newSy();this._sy===We.String;)this.applyBeatEffect(e)||this.error("beat-effects",We.String,!1);this._sy!==We.RBrace&&this.error("beat-effects",We.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){let t=this._syData.toLowerCase();if("f"===t)e.fade=O.FadeIn;else if("fo"===t)e.fade=O.FadeOut;else if("vs"===t)e.fade=O.VolumeSwell;else if("v"===t)e.vibrato=w.Slight;else if("vw"===t)e.vibrato=w.Wide;else if("s"===t)e.slap=!0;else if("p"===t)e.pop=!0;else if("tt"===t)e.tap=!0;else if("txt"===t){if(this._sy=this.newSy(),this._sy!==We.String)return this.error("beat-text",We.String,!0),!1;e.text=this._syData}else if("dd"===t)e.dots=2;else if("d"===t)e.dots=1;else if("su"===t)e.pickStroke=E.Up;else if("sd"===t)e.pickStroke=E.Down;else{if("tu"===t){if(this._sy=this.newSy(),this._sy!==We.Number)return this.error("tuplet",We.Number,!0),!1;const t=this._syData;if(this._sy=this.newSy(),this._sy===We.Number){const s=this._syData;this._sy=this.newSy(),e.tupletNumerator=t,e.tupletDenominator=s}else tt.applyTuplet(e,t);return!0}if("tb"===t||"tbe"===t){this._sy=this.newSy();let s="tbe"===t;for(this._sy===We.String&&(e.whammyBarType=this.parseWhammyType(this._syData),this._sy=this.newSy()),this._sy===We.String&&(e.whammyStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==We.LParensis&&this.error("tremolobar-effect",We.LParensis,!0),this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy();this._sy!==We.RParensis&&this._sy!==We.Eof;){let t=0,i=0;s?(this._sy!==We.Number&&this.error("tremolobar-effect",We.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==We.Number&&this.error("tremolobar-effect",We.Number,!0),i=this._syData):(this._sy!==We.Number&&this.error("tremolobar-effect",We.Number,!0),t=0,i=this._syData),e.addWhammyBarPoint(new te(t,i)),this._sy=this.newSy()}if(null!=e.whammyBarPoints){for(;e.whammyBarPoints.length>60;)e.removeWhammyBarPoint(e.whammyBarPoints.length-1);if(s)e.whammyBarPoints.sort(((e,t)=>e.offset-t.offset));else{let t=e.whammyBarPoints.length,s=60/t|0,i=0;for(;i<t;)e.whammyBarPoints[i].offset=Math.min(60,i*s),i++}}this._allowNegatives=!1,this._allowFloat=!1,this._sy!==We.RParensis&&this.error("tremolobar-effect",We.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===We.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 Be;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=m.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=m.BendGrace,this._sy=this.newSy()):e.graceType=m.BeforeBeat,!0;if("dy"===t){switch(this._sy=this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=g.PPP;break;case"pp":e.dynamics=g.PP;break;case"p":e.dynamics=g.P;break;case"mp":e.dynamics=g.MP;break;case"mf":e.dynamics=g.MF;break;case"f":e.dynamics=g.F;break;case"ff":e.dynamics=g.FF;break;case"fff":e.dynamics=g.FFF}this._currentDynamics=e.dynamics}else if("cre"===t)e.crescendo=u.Crescendo;else if("dec"===t)e.crescendo=u.Decrescendo;else{if("tempo"===t){const t=this.readTempoAutomation();return e.automations.push(t),e.voice.bar.masterBar.tempoAutomations.push(t),!0}if("tp"===t){if(this._sy=this.newSy(),e.tremoloSpeed=p.Eighth,this._sy===We.Number){switch(this._syData){case 8:default:e.tremoloSpeed=p.Eighth;break;case 16:e.tremoloSpeed=p.Sixteenth;break;case 32:e.tremoloSpeed=p.ThirtySecond}this._sy=this.newSy()}return!0}if("spd"===t){const t=new $;return t.pedalType=h.Down,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spu"===t){const t=new $;return t.pedalType=h.Up,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spe"===t){const t=new $;return t.pedalType=h.Up,t.ratioPosition=1,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("slashed"===t)return e.slashed=!0,this._sy=this.newSy(),!0;if("ds"===t)return e.deadSlapped=!0,this._sy=this.newSy(),!0;if("glpf"===t)return this._sy=this.newSy(),e.golpe=A.Finger,!0;if("glpt"===t)return this._sy=this.newSy(),e.golpe=A.Thumb,!0;if("waho"===t)return this._sy=this.newSy(),e.wahPedal=R.Open,!0;if("wahc"===t)return this._sy=this.newSy(),e.wahPedal=R.Closed,!0;if("barre"===t){if(this._sy=this.newSy(),this._sy!==We.Number&&this.error("beat-barre",We.Number,!0),e.barreFret=this._syData,e.barreShape=V.Full,this._sy=this.newSy(),this._sy===We.String)switch(this._syData.toLowerCase()){case"full":e.barreShape=V.Full,this._sy=this.newSy();break;case"half":e.barreShape=V.Half,this._sy=this.newSy()}return!0}if("rasg"===t){switch(this._sy=this.newSy(),this._sy!==We.String&&this.error("rasgueado",We.String,!0),this._syData.toLowerCase()){case"ii":e.rasgueado=H.Ii;break;case"mi":e.rasgueado=H.Mi;break;case"miitriplet":e.rasgueado=H.MiiTriplet;break;case"miianapaest":e.rasgueado=H.MiiAnapaest;break;case"pmptriplet":e.rasgueado=H.PmpTriplet;break;case"pmpanapaest":e.rasgueado=H.PmpAnapaest;break;case"peitriplet":e.rasgueado=H.PeiTriplet;break;case"peianapaest":e.rasgueado=H.PeiAnapaest;break;case"paitriplet":e.rasgueado=H.PaiTriplet;break;case"paianapaest":e.rasgueado=H.PaiAnapaest;break;case"amitriplet":e.rasgueado=H.AmiTriplet;break;case"amianapaest":e.rasgueado=H.AmiAnapaest;break;case"ppp":e.rasgueado=H.Ppp;break;case"amii":e.rasgueado=H.Amii;break;case"amip":e.rasgueado=H.Amip;break;case"eami":e.rasgueado=H.Eami;break;case"eamii":e.rasgueado=H.Eamii;break;case"peami":e.rasgueado=H.Peami}return this._sy=this.newSy(),!0}if("ot"===t)this._sy=this.newSy(),this._sy!==We.String&&this.error("beat-ottava",We.String,!0),e.ottava=this.parseClefOttavaFromString(this._syData);else if("legatoorigin"===t)e.isLegatoOrigin=!0;else{if("instrument"!==t){if("fermata"===t){this._sy=this.newSy(),this._sy!==We.String&&this.error("fermata",We.Number,!0);const t=new Ze;return t.type=this.parseFermataFromString(this._syData),this._allowFloat=!0,this._sy=this.newSy(),this._sy===We.Number&&(t.length=this._syData,this._sy=this.newSy()),this._allowFloat=!1,e.fermata=t,!0}if("beam"===t){switch(this._sy=this.newSy(),this._sy!==We.String&&this.error("beam",We.Number,!0),this._syData.toLowerCase()){case"invert":e.invertBeamDirection=!0;break;case"up":e.preferredBeamDirection=Ge.Up;break;case"down":e.preferredBeamDirection=Ge.Down;break;case"auto":e.beamingMode=G.Auto;break;case"split":e.beamingMode=G.ForceSplitToNext;break;case"merge":e.beamingMode=G.ForceMergeWithNext;break;case"splitsecondary":e.beamingMode=G.ForceSplitOnSecondaryToNext}return this._sy=this.newSy(),!0}return"timer"===t&&(e.showTimer=!0,this._sy=this.newSy(),!0)}{this._sy=this.newSy();let t=0;this._sy===We.Number?t=this._syData:this._sy===We.String?t=Y.getValue(this._syData):this.error("instrument-change",We.Number,!0);const s=new Q;s.isLinear=!1,s.type=a.Instrument,s.value=t,e.automations.push(s)}}}}}}return this._sy=this.newSy(),!0}parseBracketExtendMode(e){switch(e.toLowerCase()){case"nobrackets":return z.NoBrackets;case"groupstaves":default:return z.GroupStaves;case"groupsimilarinstruments":return z.GroupSimilarInstruments}}parseFermataFromString(e){switch(e.toLowerCase()){case"short":return He.Short;case"medium":default:return He.Medium;case"long":return He.Long}}parseClefOttavaFromString(e){switch(e.toLowerCase()){case"15ma":return n._15ma;case"8va":return n._8va;case"regular":default:return n.Regular;case"8vb":return n._8vb;case"15mb":return n._15mb}}getChordId(e,t){return t.toLowerCase()+e.index+e.track.index}static applyTuplet(e,t){switch(t){case 3:e.tupletNumerator=3,e.tupletDenominator=2;break;case 5:e.tupletNumerator=5,e.tupletDenominator=4;break;case 6:e.tupletNumerator=6,e.tupletDenominator=4;break;case 7:e.tupletNumerator=7,e.tupletDenominator=4;break;case 9:e.tupletNumerator=9,e.tupletDenominator=8;break;case 10:e.tupletNumerator=10,e.tupletDenominator=8;break;case 11:e.tupletNumerator=11,e.tupletDenominator=8;break;case 12:e.tupletNumerator=12,e.tupletDenominator=8;break;default:e.tupletNumerator=1,e.tupletDenominator=1}}isNoteText(e){return"x"===e||"-"===e||"r"===e}note(e){let t=!1,s=!1,i=-1,a=-1,r=-1,n=b.Default;switch(this._sy){case We.Number:i=this._syData,this._currentStaff.isPercussion&&!ue.instrumentArticulations.has(i)&&this.errorMessage(`Unknown percussion articulation ${i}`);break;case We.String:if(this._currentStaff.isPercussion){const e=this._syData.toLowerCase();this._percussionArticulationNames.has(e)?i=this._percussionArticulationNames.get(e):this.errorMessage(`Unknown percussion articulation '${this._syData}'`)}else t="x"===this._syData,s="-"===this._syData,s||t?i=0:this.error("note-fret",We.Number,!0);break;case We.Tuning:0===e.index&&0===e.voice.index&&0===e.voice.bar.index&&this.makeCurrentStaffPitched();let o=this._syData;a=o.octave,r=o.tone.noteValue,this._accidentalMode==Ue.Explicit&&(n=o.tone.accidentalMode);break;default:return!1}this._sy=this.newSy();let o=-1===a&&this._currentStaff.tuning.length>0&&!this._currentStaff.isPercussion,h=-1;o&&(this._sy!==We.Dot&&this.error("note",We.Dot,!0),this._sy=this.newSy(),this._sy!==We.Number&&this.error("note-string",We.Number,!0),h=this._syData,(h<1||h>this._currentStaff.tuning.length)&&this.error("note-string",We.Number,!1),this._sy=this.newSy());let l=new ge;return o?(l.string=this._currentStaff.tuning.length-(h-1),l.isDead=t,l.isTieDestination=s,s||(l.fret=i)):this._currentStaff.isPercussion?l.percussionArticulation=i:(l.octave=a,l.tone=r,l.accidentalMode=n,l.isTieDestination=s),e.addNote(l),this.noteEffects(l),!0}noteEffects(e){if(this._sy===We.LBrace){for(this._sy=this.newSy();this._sy===We.String;){let t=this._syData.toLowerCase();if("b"===t||"be"===t){this._sy=this.newSy();let s="be"===t;for(this._sy===We.String&&(e.bendType=this.parseBendType(this._syData),this._sy=this.newSy()),this._sy===We.String&&(e.bendStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==We.LParensis&&this.error("bend-effect",We.LParensis,!0),this._sy=this.newSy();this._sy!==We.RParensis&&this._sy!==We.Eof;){let t=0,i=0;s?(this._sy!==We.Number&&this.error("bend-effect-value",We.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==We.Number&&this.error("bend-effect-value",We.Number,!0),i=this._syData):(this._sy!==We.Number&&this.error("bend-effect-value",We.Number,!0),i=this._syData),e.addBendPoint(new te(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!==We.RParensis&&this.error("bend-effect",We.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=y.Natural,e.harmonicValue=le.deltaFretToHarmonicValue(e.fret),this._sy=this.newSy();else if("ah"===t)e.harmonicType=y.Artificial,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("th"===t)e.harmonicType=y.Tap,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("ph"===t)e.harmonicType=y.Pinch,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("sh"===t)e.harmonicType=y.Semi,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("fh"===t)e.harmonicType=y.Feedback,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("tr"===t){this._sy=this.newSy(),this._sy!==We.Number&&this.error("trill-effect",We.Number,!0);let t=this._syData;this._sy=this.newSy();let s=p.Sixteenth;if(this._sy===We.Number){switch(this._syData){case 16:default:s=p.Sixteenth;break;case 32:s=p.ThirtySecond;break;case 64:s=p.SixtyFourth}this._sy=this.newSy()}e.trillValue=t+e.stringTuning,e.trillSpeed=s}else if("v"===t)this._sy=this.newSy(),e.vibrato=w.Slight;else if("sl"===t)this._sy=this.newSy(),e.slideOutType=_.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=_.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=S.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=S.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=_.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=_.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=_.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=_.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("ten"===t)this._sy=this.newSy(),e.accentuated=i.Tenuto;else if("pm"===t)this._sy=this.newSy(),e.isPalmMute=!0;else if("st"===t)this._sy=this.newSy(),e.isStaccato=!0;else if("lr"===t)this._sy=this.newSy(),e.isLetRing=!0;else if("x"===t)this._sy=this.newSy(),e.fret=0,e.isDead=!0;else if("-"===t||"t"===t)this._sy=this.newSy(),e.isTieDestination=!0;else if("lf"===t){this._sy=this.newSy();let t=f.Thumb;this._sy===We.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===We.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else if("acc"===t)this._sy=this.newSy(),this._sy!==We.String&&this.error("note-accidental",We.String,!0),e.accidentalMode=le.parseAccidentalMode(this._syData),this._sy=this.newSy();else if("turn"===t)this._sy=this.newSy(),e.ornament=M.Turn;else if("iturn"===t)this._sy=this.newSy(),e.ornament=M.InvertedTurn;else if("umordent"===t)this._sy=this.newSy(),e.ornament=M.UpperMordent;else if("lmordent"===t)this._sy=this.newSy(),e.ornament=M.LowerMordent;else if("string"===t)this._sy=this.newSy(),e.showStringNumber=!0;else if("hide"===t)this._sy=this.newSy(),e.isVisible=!1;else if("slur"===t){this._sy=this.newSy(),this._sy!==We.String&&this.error("slur",We.String,!0);const t=this._syData;if(this._slurs.has(t)){const s=this._slurs.get(t);s.slurDestination=e,e.slurOrigin=s,e.isSlurDestination=!0}else this._slurs.set(t,e);this._sy=this.newSy()}else this.applyBeatEffect(e.beat)||this.error(t,We.String,!1)}this._sy!==We.RBrace&&this.error("note-effect",We.RBrace,!1),this._sy=this.newSy()}}harmonicValue(e){return this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy(),this._sy===We.Number&&(e=this._syData,this._sy=this.newSy()),this._allowNegatives=!1,this._allowFloat=!1,e}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 p.QuadrupleWhole;case-2:return p.DoubleWhole;case 1:return p.Whole;case 2:return p.Half;case 4:return p.Quarter;case 8:return p.Eighth;case 16:return p.Sixteenth;case 32:return p.ThirtySecond;case 64:return p.SixtyFourth;case 128:return p.OneHundredTwentyEighth;case 256:return p.TwoHundredFiftySixth;default:return p.Quarter}}parseBendStyle(e){switch(e.toLowerCase()){case"gradual":return l.Gradual;case"fast":return l.Fast;default:return l.Default}}parseBendType(e){switch(e.toLowerCase()){case"none":return d.None;case"custom":default:return d.Custom;case"bend":return d.Bend;case"release":return d.Release;case"bendrelease":return d.BendRelease;case"hold":return d.Hold;case"prebend":return d.Prebend;case"prebendbend":return d.PrebendBend;case"prebendrelease":return d.PrebendRelease}}barMeta(e){let t=!1,s=e.masterBar,i=!1;for(;!i&&this._sy===We.MetaCommand;){t=!0;let a=this._syData.toLowerCase();if("ts"===a)this._sy=this.newSy(),this._sy===We.String?"common"===this._syData.toLowerCase()?(s.timeSignatureCommon=!0,s.timeSignatureNumerator=4,s.timeSignatureDenominator=4,this._sy=this.newSy()):this.error("timesignature-numerator",We.String,!0):(this._sy!==We.Number&&this.error("timesignature-numerator",We.Number,!0),s.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==We.Number&&this.error("timesignature-denominator",We.Number,!0),s.timeSignatureDenominator=this._syData,this._sy=this.newSy());else if("ft"==a)s.isFreeTime=!0,this._sy=this.newSy();else if("ro"===a)s.isRepeatStart=!0,this._sy=this.newSy();else if("rc"===a)this._sy=this.newSy(),this._sy!==We.Number&&this.error("repeatclose",We.Number,!0),this._syData>2048&&this.error("repeatclose",We.Number,!1),s.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===a)if(this._sy=this.newSy(),this._sy===We.LParensis){for(this._sy=this.newSy(),this._sy!==We.Number&&this.error("alternateending",We.Number,!0),this.applyAlternateEnding(s);this._sy===We.Number;)this.applyAlternateEnding(s);this._sy!==We.RParensis&&this.error("alternateending-list",We.RParensis,!0),this._sy=this.newSy()}else this._sy!==We.Number&&this.error("alternateending",We.Number,!0),this.applyAlternateEnding(s);else if("ks"===a)this._sy=this.newSy(),this._sy!==We.String&&this.error("keysignature",We.String,!0),s.keySignature=this.parseKeySignature(this._syData),s.keySignatureType=this.parseKeySignatureType(this._syData),this._sy=this.newSy();else if("clef"===a){switch(this._sy=this.newSy(),this._sy){case We.String:e.clef=this.parseClefFromString(this._syData);break;case We.Number:e.clef=this.parseClefFromInt(this._syData);break;case We.Tuning:let t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",We.String,!0)}this._sy=this.newSy()}else if("tempo"===a){const e=this.readTempoAutomation();s.tempoAutomations.push(e)}else if("section"===a){this._sy=this.newSy(),this._sy!==We.String&&this.error("section",We.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==We.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());let i=new ve;i.marker=t,i.text=e,s.section=i}else if("tf"===a){switch(this._allowTuning=!1,this._sy=this.newSy(),this._allowTuning=!0,this._sy){case We.String:s.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case We.Number:s.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",We.String,!0)}this._sy=this.newSy()}else if("ac"===a)s.isAnacrusis=!0,this._sy=this.newSy();else if("db"===a)s.isDoubleBar=!0,this._sy=this.newSy();else if("accidentals"===a)this.handleAccidentalMode();else if("jump"===a)this.handleDirections(s);else if("ottava"===a)this._sy=this.newSy(),this._sy!==We.String&&this.error("ottava",We.String,!0),e.clefOttava=this.parseClefOttavaFromString(this._syData),this._sy=this.newSy();else if("simile"===a)this._sy=this.newSy(),this._sy!==We.String&&this.error("simile",We.String,!0),e.simileMark=this.parseSimileMarkFromString(this._syData),this._sy=this.newSy();else if("scale"===a)this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==We.Number&&this.error("scale",We.Number,!0),s.displayScale=this._syData,e.displayScale=this._syData,this._sy=this.newSy();else if("width"===a)this._sy=this.newSy(),this._sy!==We.Number&&this.error("width",We.Number,!0),s.displayWidth=this._syData,e.displayWidth=this._syData,this._sy=this.newSy();else if(0===e.index)switch(this.handleStaffMeta()){case ze.KnownStaffMeta:break;case ze.UnknownStaffMeta:this.error("measure-effects",We.String,!1);break;case ze.EndOfMetaDetected:i=!0}else this.error("measure-effects",We.String,!1)}if(0===s.index&&0===s.tempoAutomations.length){let e=new Q;e.isLinear=!1,e.type=a.Tempo,e.value=this._score.tempo,e.text=this._score.tempoLabel,s.tempoAutomations.push(e)}return t}parseSimileMarkFromString(e){switch(e.toLowerCase()){case"none":default:return o.None;case"simple":return o.Simple;case"firstofdouble":return o.FirstOfDouble;case"secondofdouble":return o.SecondOfDouble}}handleDirections(e){switch(this._sy=this.newSy(),this._sy!==We.String&&this.error("direction",We.String,!0),this._syData.toLowerCase()){case"fine":e.addDirection(Ve.TargetFine);break;case"segno":e.addDirection(Ve.TargetSegno);break;case"segnosegno":e.addDirection(Ve.TargetSegnoSegno);break;case"coda":e.addDirection(Ve.TargetCoda);break;case"doublecoda":e.addDirection(Ve.TargetDoubleCoda);break;case"dacapo":e.addDirection(Ve.JumpDaCapo);break;case"dacapoalcoda":e.addDirection(Ve.JumpDaCapoAlCoda);break;case"dacapoaldoublecoda":e.addDirection(Ve.JumpDaCapoAlDoubleCoda);break;case"dacapoalfine":e.addDirection(Ve.JumpDaCapoAlFine);break;case"dalsegno":e.addDirection(Ve.JumpDalSegno);break;case"dalsegnoalcoda":e.addDirection(Ve.JumpDalSegnoAlCoda);break;case"dalsegnoaldoublecoda":e.addDirection(Ve.JumpDalSegnoAlDoubleCoda);break;case"dalsegnoalfine":e.addDirection(Ve.JumpDalSegnoAlFine);break;case"dalsegnosegno":e.addDirection(Ve.JumpDalSegnoSegno);break;case"dalsegnosegnoalcoda":e.addDirection(Ve.JumpDalSegnoSegnoAlCoda);break;case"dalsegnosegnoaldoublecoda":e.addDirection(Ve.JumpDalSegnoSegnoAlDoubleCoda);break;case"dalsegnosegnoalfine":e.addDirection(Ve.JumpDalSegnoSegnoAlFine);break;case"dacoda":e.addDirection(Ve.JumpDaCoda);break;case"dadoublecoda":e.addDirection(Ve.JumpDaDoubleCoda);break;default:return void this.errorMessage(`Unexpected direction value: '${this._syData}'`)}this._sy=this.newSy()}readTempoAutomation(){this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==We.Number&&this.error("tempo",We.Number,!0);const e=new Q;return e.isLinear=!1,e.type=a.Tempo,e.value=this._syData,this._sy=this.newSy(),this._sy===We.String&&(e.text=this._syData,this._sy=this.newSy()),e}applyAlternateEnding(e){let t=this._syData;t<1&&this.error("alternateending",We.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}parseWhammyType(e){switch(e.toLowerCase()){case"none":return I.None;case"custom":default:return I.Custom;case"dive":return I.Dive;case"dip":return I.Dip;case"hold":return I.Hold;case"predive":return I.Predive;case"predivedive":return I.PrediveDive}}}tt.Eof=0,function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Sharp=2]="Sharp",e[e.Flat=3]="Flat",e[e.NaturalQuarterNoteUp=4]="NaturalQuarterNoteUp",e[e.SharpQuarterNoteUp=5]="SharpQuarterNoteUp",e[e.FlatQuarterNoteUp=6]="FlatQuarterNoteUp",e[e.DoubleSharp=7]="DoubleSharp",e[e.DoubleFlat=8]="DoubleFlat"}(Xe||(Xe={}));class st{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 j(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 it{constructor(e,t,s){this.text=e,this.startPos=t,this.endPos=s}}class at{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 it(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 at(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"}(Je||(Je={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(Ye||(Ye={}));class rt{reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=at.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===Ye.Bold}get isItalic(){return this.style===Je.Italic}constructor(e,t,s=Je.Plain,i=Ye.Regular){this._cssScale=0,this._families=at.parseFamilies(e),this._size=t,this._style=s,this._weight=i,this._css=this.toCssString()}withSize(e){return rt.withFamilyList(this._families,e,this._style,this._weight)}static withFamilyList(e,t,s=Je.Plain,i=Ye.Regular){const a=new rt("",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=>at.quoteFont(e))).join(", "),this._css=t,this._cssScale=e}return this._css}static fromJson(e){if(e instanceof rt)return e;switch(typeof e){case"undefined":default:return null;case"object":{const t=e;let s=t.get("families"),i=t.get("size"),a=st.parseEnum(t.get("style"),Je),r=st.parseEnum(t.get("weight"),Ye);return rt.withFamilyList(s,i,a,r)}case"string":{const t=new at(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=Je.Plain;"italic"===t.style&&(r=Je.Italic);let n=Ye.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=Ye.Bold}return rt.withFamilyList(s,a,r,n)}}}static toJson(e){const t=new Map;return t.set("families",e.families),t.set("size",e.size),t.set("style",e.style),t.set("weight",e.weight),t}}!function(e){e[e.SingleTrackMultiChannel=0]="SingleTrackMultiChannel",e[e.MultiTrack=1]="MultiTrack"}(qe||(qe={}));class nt{constructor(){this.events=[]}addEvent(e){if(0===this.events.length||e.tick>=this.events[this.events.length-1].tick)this.events.push(e);else{let t=this.events.length;for(;t>0;){if(!(this.events[t-1].tick>e.tick))break;t--}this.events.splice(t,0,e)}}writeTo(e){let t=Oe.empty(),s=0;for(let e of this.events){let i=e.tick-s;ot.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();Ae.writeInt32BE(e,a.length),e.write(a,0,a.length)}}class ot{constructor(){this.format=qe.SingleTrackMultiChannel,this.division=ee.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 nt)}addEvent(e){this.format==qe.SingleTrackMultiChannel?(this.ensureTracks(1),this.tracks[0].addEvent(e)):(this.ensureTracks(e.track+1),this.tracks[e.track].addEvent(e))}toBinary(){let e=Oe.empty();return this.writeTo(e),e.toArray()}writeTo(e){let t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),Ae.writeInt32BE(e,6),Ae.writeInt16BE(e,this.format),Ae.writeInt16BE(e,this.tracks.length),Ae.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"}(je||(je={}));class ht{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 lt extends ht{constructor(e,t,s,i,a,r){super(e,t,je.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),ot.writeVariableInt(e,4),e.writeByte(255&this.numerator),e.writeByte(255&this.denominatorIndex),e.writeByte(255&this.midiClocksPerMetronomeClick),e.writeByte(255&this.thirtySecondNodesInQuarter)}}class dt extends ht{constructor(e,t,s){super(e,t,s)}writeTo(e){e.writeByte(240);const t=Oe.withCapacity(16);t.writeByte(dt.AlphaTabManufacturerId),this.writeEventData(t),t.writeByte(247),ot.writeVariableInt(e,t.length),t.copyTo(e)}}dt.AlphaTabManufacturerId=125,dt.MetronomeEventId=0,dt.RestEventId=1;class ct extends dt{constructor(e,t,s,i,a){super(e,t,je.AlphaTabMetronome),this.isMetronome=!0,this.metronomeNumerator=s,this.metronomeDurationInMilliseconds=a,this.metronomeDurationInTicks=i}writeEventData(e){e.writeByte(dt.MetronomeEventId),e.writeByte(this.metronomeNumerator),Ae.writeInt32LE(e,this.metronomeDurationInTicks),Ae.writeInt32LE(e,this.metronomeDurationInMilliseconds)}}class ut extends dt{constructor(e,t,s){super(e,t,je.AlphaTabRest),this.channel=s}writeEventData(e){e.writeByte(dt.RestEventId),e.writeByte(this.channel)}}class pt extends ht{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 gt extends pt{constructor(e,t,s,i,a){super(e,t,je.NoteOn,s,i,a)}writeTo(e){e.writeByte(15&this.channel|144),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class mt extends pt{constructor(e,t,s,i,a){super(e,t,je.NoteOff,s,i,a)}writeTo(e){e.writeByte(15&this.channel|128),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class ft extends ht{constructor(e,t,s,i,a){super(e,t,je.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 ht{constructor(e,t,s,i){super(e,t,je.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 bt extends ht{constructor(e,t){super(0,e,je.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 St extends ht{constructor(e,t,s,i){super(e,t,je.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 _t extends ht{constructor(e,t,s,i,a){super(e,t,je.PerNotePitchBend),this.channel=s,this.noteKey=i,this.value=a}writeTo(e){throw new j(s.General,"Note Bend (Midi2.0) events cannot be exported to SMF1.0")}}class wt extends ht{constructor(e,t){super(e,t,je.EndOfTrack)}writeTo(e){e.writeByte(255),e.writeByte(47),e.writeByte(0)}}class Bt{constructor(){this.copyrightFont=new rt(Bt.sansFont,12,Je.Plain,Ye.Bold),this.titleFont=new rt(Bt.serifFont,32,Je.Plain),this.subTitleFont=new rt(Bt.serifFont,20,Je.Plain),this.wordsFont=new rt(Bt.serifFont,15,Je.Plain),this.effectFont=new rt(Bt.serifFont,12,Je.Italic),this.timerFont=new rt(Bt.serifFont,12,Je.Plain),this.directionsFont=new rt(Bt.serifFont,14,Je.Plain),this.fretboardNumberFont=new rt(Bt.sansFont,11,Je.Plain),this.numberedNotationFont=new rt(Bt.sansFont,16,Je.Plain),this.numberedNotationGraceFont=new rt(Bt.sansFont,14,Je.Plain),this.tablatureFont=new rt(Bt.sansFont,13,Je.Plain),this.graceFont=new rt(Bt.sansFont,11,Je.Plain),this.staffLineColor=new Ce(165,165,165,255),this.barSeparatorColor=new Ce(34,34,17,255),this.barNumberFont=new rt(Bt.sansFont,11,Je.Plain),this.barNumberColor=new Ce(200,0,0,255),this.fingeringFont=new rt(Bt.serifFont,14,Je.Plain),this.inlineFingeringFont=new rt(Bt.serifFont,12,Je.Plain),this.markerFont=new rt(Bt.serifFont,14,Je.Plain,Ye.Bold),this.mainGlyphColor=new Ce(0,0,0,255),this.secondaryGlyphColor=new Ce(0,0,0,100),this.scoreInfoColor=new Ce(0,0,0,255)}}Bt.sansFont="Arial, sans-serif",Bt.serifFont="Georgia, serif",function(e){e[e.Automatic=0]="Automatic",e[e.UseModelLayout=1]="UseModelLayout"}(Ke||(Ke={}));class kt{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 Bt,this.padding=[35,35],this.firstSystemPaddingTop=5,this.systemPaddingTop=10,this.systemPaddingBottom=20,this.lastSystemPaddingBottom=0,this.systemLabelPaddingLeft=0,this.systemLabelPaddingRight=5,this.accoladeBarPaddingRight=3,this.notationStaffPaddingTop=5,this.notationStaffPaddingBottom=5,this.effectStaffPaddingTop=0,this.effectStaffPaddingBottom=0,this.firstStaffPaddingLeft=6,this.staffPaddingLeft=2,this.systemsLayoutMode=Ke.Automatic}}class Tt{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"}(Qe||(Qe={}));class xt{constructor(){this.noteWideLength=240,this.noteWideAmplitude=1,this.noteSlightLength=360,this.noteSlightAmplitude=.5,this.beatWideLength=480,this.beatWideAmplitude=2,this.beatSlightLength=480,this.beatSlightAmplitude=2}}class Nt{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}!function(e){e[e.WebAudioAudioWorklets=0]="WebAudioAudioWorklets",e[e.WebAudioScriptProcessor=1]="WebAudioScriptProcessor"}($e||($e={}));class vt{constructor(){this.soundFont=null,this.scrollElement="html,body",this.outputMode=$e.WebAudioAudioWorklets,this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=Qe.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new xt,this.slide=new Nt,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}class Pt{static fromJson(e,t){t&&st.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=st.parseEnum(s,N),!0;case"useworkers":return e.useWorkers=s,!0;case"includenotebounds":return e.includeNoteBounds=s,!0}return!1}}class Ct{static fromJson(e,t){t&&st.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",rt.toJson(e.copyrightFont)),t.set("titlefont",rt.toJson(e.titleFont)),t.set("subtitlefont",rt.toJson(e.subTitleFont)),t.set("wordsfont",rt.toJson(e.wordsFont)),t.set("effectfont",rt.toJson(e.effectFont)),t.set("timerfont",rt.toJson(e.timerFont)),t.set("directionsfont",rt.toJson(e.directionsFont)),t.set("fretboardnumberfont",rt.toJson(e.fretboardNumberFont)),t.set("numberednotationfont",rt.toJson(e.numberedNotationFont)),t.set("numberednotationgracefont",rt.toJson(e.numberedNotationGraceFont)),t.set("tablaturefont",rt.toJson(e.tablatureFont)),t.set("gracefont",rt.toJson(e.graceFont)),t.set("stafflinecolor",Ce.toJson(e.staffLineColor)),t.set("barseparatorcolor",Ce.toJson(e.barSeparatorColor)),t.set("barnumberfont",rt.toJson(e.barNumberFont)),t.set("barnumbercolor",Ce.toJson(e.barNumberColor)),t.set("fingeringfont",rt.toJson(e.fingeringFont)),t.set("inlinefingeringfont",rt.toJson(e.inlineFingeringFont)),t.set("markerfont",rt.toJson(e.markerFont)),t.set("mainglyphcolor",Ce.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",Ce.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",Ce.toJson(e.scoreInfoColor)),t}static setProperty(e,t,s){switch(t){case"copyrightfont":return e.copyrightFont=rt.fromJson(s),!0;case"titlefont":return e.titleFont=rt.fromJson(s),!0;case"subtitlefont":return e.subTitleFont=rt.fromJson(s),!0;case"wordsfont":return e.wordsFont=rt.fromJson(s),!0;case"effectfont":return e.effectFont=rt.fromJson(s),!0;case"timerfont":return e.timerFont=rt.fromJson(s),!0;case"directionsfont":return e.directionsFont=rt.fromJson(s),!0;case"fretboardnumberfont":return e.fretboardNumberFont=rt.fromJson(s),!0;case"numberednotationfont":return e.numberedNotationFont=rt.fromJson(s),!0;case"numberednotationgracefont":return e.numberedNotationGraceFont=rt.fromJson(s),!0;case"tablaturefont":return e.tablatureFont=rt.fromJson(s),!0;case"gracefont":return e.graceFont=rt.fromJson(s),!0;case"stafflinecolor":return e.staffLineColor=Ce.fromJson(s),!0;case"barseparatorcolor":return e.barSeparatorColor=Ce.fromJson(s),!0;case"barnumberfont":return e.barNumberFont=rt.fromJson(s),!0;case"barnumbercolor":return e.barNumberColor=Ce.fromJson(s),!0;case"fingeringfont":return e.fingeringFont=rt.fromJson(s),!0;case"inlinefingeringfont":return e.inlineFingeringFont=rt.fromJson(s),!0;case"markerfont":return e.markerFont=rt.fromJson(s),!0;case"mainglyphcolor":return e.mainGlyphColor=Ce.fromJson(s),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=Ce.fromJson(s),!0;case"scoreinfocolor":return e.scoreInfoColor=Ce.fromJson(s),!0}return!1}}class Et{static fromJson(e,t){t&&st.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",Ct.toJson(e.resources)),t.set("padding",e.padding),t.set("firstsystempaddingtop",e.firstSystemPaddingTop),t.set("systempaddingtop",e.systemPaddingTop),t.set("systempaddingbottom",e.systemPaddingBottom),t.set("lastsystempaddingbottom",e.lastSystemPaddingBottom),t.set("systemlabelpaddingleft",e.systemLabelPaddingLeft),t.set("systemlabelpaddingright",e.systemLabelPaddingRight),t.set("accoladebarpaddingright",e.accoladeBarPaddingRight),t.set("notationstaffpaddingtop",e.notationStaffPaddingTop),t.set("notationstaffpaddingbottom",e.notationStaffPaddingBottom),t.set("effectstaffpaddingtop",e.effectStaffPaddingTop),t.set("effectstaffpaddingbottom",e.effectStaffPaddingBottom),t.set("firststaffpaddingleft",e.firstStaffPaddingLeft),t.set("staffpaddingleft",e.staffPaddingLeft),t.set("systemslayoutmode",e.systemsLayoutMode),t}static setProperty(s,i,a){switch(i){case"scale":return s.scale=a,!0;case"stretchforce":return s.stretchForce=a,!0;case"layoutmode":return s.layoutMode=st.parseEnum(a,e),!0;case"staveprofile":return s.staveProfile=st.parseEnum(a,t),!0;case"barsperrow":return s.barsPerRow=a,!0;case"startbar":return s.startBar=a,!0;case"barcount":return s.barCount=a,!0;case"barcountperpartial":return s.barCountPerPartial=a,!0;case"justifylastsystem":return s.justifyLastSystem=a,!0;case"padding":return s.padding=a,!0;case"firstsystempaddingtop":return s.firstSystemPaddingTop=a,!0;case"systempaddingtop":return s.systemPaddingTop=a,!0;case"systempaddingbottom":return s.systemPaddingBottom=a,!0;case"lastsystempaddingbottom":return s.lastSystemPaddingBottom=a,!0;case"systemlabelpaddingleft":return s.systemLabelPaddingLeft=a,!0;case"systemlabelpaddingright":return s.systemLabelPaddingRight=a,!0;case"accoladebarpaddingright":return s.accoladeBarPaddingRight=a,!0;case"notationstaffpaddingtop":return s.notationStaffPaddingTop=a,!0;case"notationstaffpaddingbottom":return s.notationStaffPaddingBottom=a,!0;case"effectstaffpaddingtop":return s.effectStaffPaddingTop=a,!0;case"effectstaffpaddingbottom":return s.effectStaffPaddingBottom=a,!0;case"firststaffpaddingleft":return s.firstStaffPaddingLeft=a,!0;case"staffpaddingleft":return s.staffPaddingLeft=a,!0;case"systemslayoutmode":return s.systemsLayoutMode=st.parseEnum(a,Ke),!0}if(["resources"].indexOf(i)>=0)return Ct.fromJson(s.resources,a),!0;for(const e of["resources"])if(0===i.indexOf(e)&&Ct.setProperty(s.resources,i.substring(e.length),a))return!0;return!1}}class Ft{static fromJson(e,t){t&&st.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=st.parseEnum(s,T),!0;case"fingeringmode":return e.fingeringMode=st.parseEnum(s,k),!0;case"elements":return e.elements=new Map,st.forEach(s,((t,s)=>{e.elements.set(st.parseEnum(s,x),t)})),!0;case"rhythmmode":return e.rhythmMode=st.parseEnum(s,B),!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 Dt{static fromJson(e,t){t&&st.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 Lt{static fromJson(e,t){t&&st.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 Mt{static fromJson(e,t){t&&st.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 It{static fromJson(e,t){t&&st.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",Lt.toJson(e.vibrato)),t.set("slide",Mt.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=st.parseEnum(s,$e),!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=st.parseEnum(s,Qe),!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 Lt.fromJson(e.vibrato,s),!0;for(const i of["vibrato"])if(0===t.indexOf(i)&&Lt.setProperty(e.vibrato,t.substring(i.length),s))return!0;if(["slide"].indexOf(t)>=0)return Mt.fromJson(e.slide,s),!0;for(const i of["slide"])if(0===t.indexOf(i)&&Mt.setProperty(e.slide,t.substring(i.length),s))return!0;return!1}}class At{static fromJson(e,t){t&&st.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",Pt.toJson(e.core)),t.set("display",Et.toJson(e.display)),t.set("notation",Ft.toJson(e.notation)),t.set("importer",Dt.toJson(e.importer)),t.set("player",It.toJson(e.player)),t}static setProperty(e,t,s){if(["core",""].indexOf(t)>=0)return Pt.fromJson(e.core,s),!0;for(const i of["core",""])if(0===t.indexOf(i)&&Pt.setProperty(e.core,t.substring(i.length),s))return!0;if(["display",""].indexOf(t)>=0)return Et.fromJson(e.display,s),!0;for(const i of["display",""])if(0===t.indexOf(i)&&Et.setProperty(e.display,t.substring(i.length),s))return!0;if(["notation"].indexOf(t)>=0)return Ft.fromJson(e.notation,s),!0;for(const i of["notation"])if(0===t.indexOf(i)&&Ft.setProperty(e.notation,t.substring(i.length),s))return!0;if(["importer"].indexOf(t)>=0)return Dt.fromJson(e.importer,s),!0;for(const i of["importer"])if(0===t.indexOf(i)&&Dt.setProperty(e.importer,t.substring(i.length),s))return!0;if(["player"].indexOf(t)>=0)return It.fromJson(e.player,s),!0;for(const i of["player"])if(0===t.indexOf(i)&&It.setProperty(e.player,t.substring(i.length),s))return!0;return!1}}class Ot{constructor(){this.core=new xl,this.display=new kt,this.notation=new se,this.importer=new Tt,this.player=new vt}setSongBookModeSettings(){this.notation.notationMode=T.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=k.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(x.ParenthesisOnTiedBends,!1),this.notation.elements.set(x.TabNotesOnTiedBends,!1),this.notation.elements.set(x.ZerosOnDiveWhammys,!0)}static get songBook(){let e=new Ot;return e.setSongBookModeSettings(),e}fillFromJson(e){At.fromJson(this,e)}}class Rt{static fromJson(e,t){t&&st.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 Vt{static fromJson(e,t){t&&st.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=st.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 Ht{static fromJson(e,t){t&&st.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=st.parseEnum(s,He),!0;case"length":return e.length=s,!0}return!1}}class Gt{static fromJson(e,t){t&&st.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("alternateendings",e.alternateEndings),t.set("keysignature",e.keySignature),t.set("keysignaturetype",e.keySignatureType),t.set("isdoublebar",e.isDoubleBar),t.set("isrepeatstart",e.isRepeatStart),t.set("repeatcount",e.repeatCount),t.set("timesignaturenumerator",e.timeSignatureNumerator),t.set("timesignaturedenominator",e.timeSignatureDenominator),t.set("timesignaturecommon",e.timeSignatureCommon),t.set("isfreetime",e.isFreeTime),t.set("tripletfeel",e.tripletFeel),t.set("section",Rt.toJson(e.section)),t.set("tempoautomations",e.tempoAutomations.map((e=>Vt.toJson(e)))),null!==e.fermata){const s=new Map;t.set("fermata",s);for(const[t,i]of e.fermata)s.set(t.toString(),Ht.toJson(i))}if(t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),null!==e.directions){const s=[];t.set("directions",s);for(const t of e.directions)s.push(t)}return t}static setProperty(e,t,s){switch(t){case"alternateendings":return e.alternateEndings=s,!0;case"keysignature":return e.keySignature=st.parseEnum(s,v),!0;case"keysignaturetype":return e.keySignatureType=st.parseEnum(s,P),!0;case"isdoublebar":return e.isDoubleBar=s,!0;case"isrepeatstart":return e.isRepeatStart=s,!0;case"repeatcount":return e.repeatCount=s,!0;case"timesignaturenumerator":return e.timeSignatureNumerator=s,!0;case"timesignaturedenominator":return e.timeSignatureDenominator=s,!0;case"timesignaturecommon":return e.timeSignatureCommon=s,!0;case"isfreetime":return e.isFreeTime=s,!0;case"tripletfeel":return e.tripletFeel=st.parseEnum(s,C),!0;case"tempoautomations":e.tempoAutomations=[];for(const t of s){const s=new Q;Vt.fromJson(s,t),e.tempoAutomations.push(s)}return!0;case"fermata":return e.fermata=new Map,st.forEach(s,((t,s)=>{const i=new Ze;Ht.fromJson(i,t),e.addFermata(parseInt(s),i)})),!0;case"start":return e.start=s,!0;case"isanacrusis":return e.isAnacrusis=s,!0;case"displayscale":return e.displayScale=s,!0;case"displaywidth":return e.displayWidth=s,!0;case"directions":for(const t of s)e.addDirection(st.parseEnum(t,Ve));return!0}return["section"].indexOf(t)>=0&&(s?(e.section=new ve,Rt.fromJson(e.section,s)):e.section=null,!0)}}class Wt{static fromJson(e,t){t&&st.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 zt{static fromJson(e,t){t&&st.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=>Wt.toJson(e)))),t.set("fret",e.fret),t.set("string",e.string),t.set("showstringnumber",e.showStringNumber),t.set("octave",e.octave),t.set("tone",e.tone),t.set("percussionarticulation",e.percussionArticulation),t.set("isvisible",e.isVisible),t.set("islefthandtapped",e.isLeftHandTapped),t.set("ishammerpullorigin",e.isHammerPullOrigin),t.set("isslurdestination",e.isSlurDestination),t.set("harmonictype",e.harmonicType),t.set("harmonicvalue",e.harmonicValue),t.set("isghost",e.isGhost),t.set("isletring",e.isLetRing),t.set("ispalmmute",e.isPalmMute),t.set("isdead",e.isDead),t.set("isstaccato",e.isStaccato),t.set("slideintype",e.slideInType),t.set("slideouttype",e.slideOutType),t.set("vibrato",e.vibrato),t.set("istiedestination",e.isTieDestination),t.set("lefthandfinger",e.leftHandFinger),t.set("righthandfinger",e.rightHandFinger),t.set("trillvalue",e.trillValue),t.set("trillspeed",e.trillSpeed),t.set("durationpercent",e.durationPercent),t.set("accidentalmode",e.accidentalMode),t.set("dynamics",e.dynamics),t.set("ornament",e.ornament),e.toJson(t),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"accentuated":return e.accentuated=st.parseEnum(s,i),!0;case"bendtype":return e.bendType=st.parseEnum(s,d),!0;case"bendstyle":return e.bendStyle=st.parseEnum(s,l),!0;case"iscontinuedbend":return e.isContinuedBend=s,!0;case"bendpoints":if(s){e.bendPoints=[];for(const t of s){const s=new te;Wt.fromJson(s,t),e.addBendPoint(s)}}return!0;case"fret":return e.fret=s,!0;case"string":return e.string=s,!0;case"showstringnumber":return e.showStringNumber=s,!0;case"octave":return e.octave=s,!0;case"tone":return e.tone=s,!0;case"percussionarticulation":return e.percussionArticulation=s,!0;case"isvisible":return e.isVisible=s,!0;case"islefthandtapped":return e.isLeftHandTapped=s,!0;case"ishammerpullorigin":return e.isHammerPullOrigin=s,!0;case"isslurdestination":return e.isSlurDestination=s,!0;case"harmonictype":return e.harmonicType=st.parseEnum(s,y),!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=st.parseEnum(s,S),!0;case"slideouttype":return e.slideOutType=st.parseEnum(s,_),!0;case"vibrato":return e.vibrato=st.parseEnum(s,w),!0;case"istiedestination":return e.isTieDestination=s,!0;case"lefthandfinger":return e.leftHandFinger=st.parseEnum(s,f),!0;case"righthandfinger":return e.rightHandFinger=st.parseEnum(s,f),!0;case"trillvalue":return e.trillValue=s,!0;case"trillspeed":return e.trillSpeed=st.parseEnum(s,p),!0;case"durationpercent":return e.durationPercent=s,!0;case"accidentalmode":return e.accidentalMode=st.parseEnum(s,b),!0;case"dynamics":return e.dynamics=st.parseEnum(s,g),!0;case"ornament":return e.ornament=st.parseEnum(s,M),!0}return e.setProperty(t,s)}}class Ut{static fromJson(e,t){t&&st.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=>zt.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=>Vt.toJson(e)))),t.set("dots",e.dots),t.set("fade",e.fade),t.set("lyrics",e.lyrics),t.set("pop",e.pop),t.set("slap",e.slap),t.set("tap",e.tap),t.set("text",e.text),t.set("slashed",e.slashed),t.set("deadslapped",e.deadSlapped),t.set("brushtype",e.brushType),t.set("brushduration",e.brushDuration),t.set("tupletdenominator",e.tupletDenominator),t.set("tupletnumerator",e.tupletNumerator),t.set("iscontinuedwhammy",e.isContinuedWhammy),t.set("whammybartype",e.whammyBarType),null!==e.whammyBarPoints&&t.set("whammybarpoints",e.whammyBarPoints?.map((e=>Wt.toJson(e)))),t.set("vibrato",e.vibrato),t.set("chordid",e.chordId),t.set("gracetype",e.graceType),t.set("pickstroke",e.pickStroke),t.set("tremolospeed",e.tremoloSpeed),t.set("crescendo",e.crescendo),t.set("displaystart",e.displayStart),t.set("playbackstart",e.playbackStart),t.set("displayduration",e.displayDuration),t.set("playbackduration",e.playbackDuration),t.set("golpe",e.golpe),t.set("dynamics",e.dynamics),t.set("invertbeamdirection",e.invertBeamDirection),t.set("preferredbeamdirection",e.preferredBeamDirection),t.set("beamingmode",e.beamingMode),t.set("wahpedal",e.wahPedal),t.set("barrefret",e.barreFret),t.set("barreshape",e.barreShape),t.set("rasgueado",e.rasgueado),t.set("showtimer",e.showTimer),t.set("timer",e.timer),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"notes":e.notes=[];for(const t of s){const s=new ge;zt.fromJson(s,t),e.addNote(s)}return!0;case"isempty":return e.isEmpty=s,!0;case"whammystyle":return e.whammyStyle=st.parseEnum(s,l),!0;case"ottava":return e.ottava=st.parseEnum(s,n),!0;case"islegatoorigin":return e.isLegatoOrigin=s,!0;case"duration":return e.duration=st.parseEnum(s,p),!0;case"automations":e.automations=[];for(const t of s){const s=new Q;Vt.fromJson(s,t),e.automations.push(s)}return!0;case"dots":return e.dots=s,!0;case"fade":return e.fade=st.parseEnum(s,O),!0;case"lyrics":return e.lyrics=s,!0;case"pop":return e.pop=s,!0;case"slap":return e.slap=s,!0;case"tap":return e.tap=s,!0;case"text":return e.text=s,!0;case"slashed":return e.slashed=s,!0;case"deadslapped":return e.deadSlapped=s,!0;case"brushtype":return e.brushType=st.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=st.parseEnum(s,I),!0;case"whammybarpoints":if(s){e.whammyBarPoints=[];for(const t of s){const s=new te;Wt.fromJson(s,t),e.addWhammyBarPoint(s)}}return!0;case"vibrato":return e.vibrato=st.parseEnum(s,w),!0;case"chordid":return e.chordId=s,!0;case"gracetype":return e.graceType=st.parseEnum(s,m),!0;case"pickstroke":return e.pickStroke=st.parseEnum(s,E),!0;case"tremolospeed":return e.tremoloSpeed=st.parseEnum(s,p),!0;case"crescendo":return e.crescendo=st.parseEnum(s,u),!0;case"displaystart":return e.displayStart=s,!0;case"playbackstart":return e.playbackStart=s,!0;case"displayduration":return e.displayDuration=s,!0;case"playbackduration":return e.playbackDuration=s,!0;case"golpe":return e.golpe=st.parseEnum(s,A),!0;case"dynamics":return e.dynamics=st.parseEnum(s,g),!0;case"invertbeamdirection":return e.invertBeamDirection=s,!0;case"preferredbeamdirection":return e.preferredBeamDirection=st.parseEnum(s,Ge),!0;case"beamingmode":return e.beamingMode=st.parseEnum(s,G),!0;case"wahpedal":return e.wahPedal=st.parseEnum(s,R),!0;case"barrefret":return e.barreFret=s,!0;case"barreshape":return e.barreShape=st.parseEnum(s,V),!0;case"rasgueado":return e.rasgueado=st.parseEnum(s,H),!0;case"showtimer":return e.showTimer=s,!0;case"timer":return e.timer=s,!0}return!1}}class Xt{static fromJson(e,t){t&&st.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=>Ut.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 we;Ut.fromJson(s,t),e.addBeat(s)}return!0;case"isempty":return e.isEmpty=s,!0}return!1}}class Jt{static fromJson(e,t){t&&st.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("ratioposition",e.ratioPosition),t.set("pedaltype",e.pedalType),t}static setProperty(e,t,s){switch(t){case"ratioposition":return e.ratioPosition=s,!0;case"pedaltype":return e.pedalType=st.parseEnum(s,h),!0}return!1}}class Yt{static fromJson(e,t){t&&st.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=>Xt.toJson(e)))),t.set("similemark",e.simileMark),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t.set("sustainpedals",e.sustainPedals.map((e=>Jt.toJson(e)))),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"clef":return e.clef=st.parseEnum(s,r),!0;case"clefottava":return e.clefOttava=st.parseEnum(s,n),!0;case"voices":e.voices=[];for(const t of s){const s=new Me;Xt.fromJson(s,t),e.addVoice(s)}return!0;case"similemark":return e.simileMark=st.parseEnum(s,o),!0;case"displayscale":return e.displayScale=s,!0;case"displaywidth":return e.displayWidth=s,!0;case"sustainpedals":e.sustainPedals=[];for(const t of s){const s=new $;Jt.fromJson(s,t),e.sustainPedals.push(s)}return!0}return!1}}class qt{static fromJson(e,t){t&&st.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 jt{static fromJson(e,t){t&&st.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 Kt{static fromJson(e,t){t&&st.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=>Yt.toJson(e)))),null!==e.chords){const s=new Map;t.set("chords",s);for(const[t,i]of e.chords)s.set(t.toString(),qt.toJson(i))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",jt.toJson(e.stringTuning)),t.set("showslash",e.showSlash),t.set("shownumbered",e.showNumbered),t.set("showtablature",e.showTablature),t.set("showstandardnotation",e.showStandardNotation),t.set("ispercussion",e.isPercussion),t.set("standardnotationlinecount",e.standardNotationLineCount),t}static setProperty(e,t,s){switch(t){case"bars":e.bars=[];for(const t of s){const s=new Z;Yt.fromJson(s,t),e.addBar(s)}return!0;case"chords":return e.chords=new Map,st.forEach(s,((t,s)=>{const i=new Be;qt.fromJson(i,t),e.addChord(s,i)})),!0;case"capo":return e.capo=s,!0;case"transpositionpitch":return e.transpositionPitch=s,!0;case"displaytranspositionpitch":return e.displayTranspositionPitch=s,!0;case"showslash":return e.showSlash=s,!0;case"shownumbered":return e.showNumbered=s,!0;case"showtablature":return e.showTablature=s,!0;case"showstandardnotation":return e.showStandardNotation=s,!0;case"ispercussion":return e.isPercussion=s,!0;case"standardnotationlinecount":return e.standardNotationLineCount=s,!0}return["stringtuning"].indexOf(t)>=0&&(jt.fromJson(e.stringTuning,s),!0)}}class Qt{static fromJson(e,t){t&&st.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 $t{static fromJson(e,t){t&&st.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=st.parseEnum(s,F),!0;case"noteheadhalf":return e.noteHeadHalf=st.parseEnum(s,F),!0;case"noteheadwhole":return e.noteHeadWhole=st.parseEnum(s,F),!0;case"techniquesymbol":return e.techniqueSymbol=st.parseEnum(s,F),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=st.parseEnum(s,L),!0;case"outputmidinumber":return e.outputMidiNumber=s,!0}return!1}}class Zt{static fromJson(e,t){t&&st.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=>Kt.toJson(e)))),t.set("playbackinfo",Qt.toJson(e.playbackInfo)),t.set("color",Ce.toJson(e.color)),t.set("name",e.name),t.set("isvisibleonmultitrack",e.isVisibleOnMultiTrack),t.set("shortname",e.shortName),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("percussionarticulations",e.percussionArticulations.map((e=>$t.toJson(e)))),t}static setProperty(e,t,s){switch(t){case"staves":e.staves=[];for(const t of s){const s=new De;Kt.fromJson(s,t),e.addStaff(s)}return!0;case"color":return e.color=Ce.fromJson(s),!0;case"name":return e.name=s,!0;case"isvisibleonmultitrack":return e.isVisibleOnMultiTrack=s,!0;case"shortname":return e.shortName=s,!0;case"defaultsystemslayout":return e.defaultSystemsLayout=s,!0;case"systemslayout":return e.systemsLayout=s,!0;case"percussionarticulations":e.percussionArticulations=[];for(const t of s){const s=new ce;$t.fromJson(s,t),e.percussionArticulations.push(s)}return!0}return["playbackinfo"].indexOf(t)>=0&&(Qt.fromJson(e.playbackInfo,s),!0)}}class es{static fromJson(e,t){t&&st.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("hidedynamics",e.hideDynamics),t.set("bracketextendmode",e.bracketExtendMode),t.set("usesystemsignseparator",e.useSystemSignSeparator),t.set("globaldisplaytuning",e.globalDisplayTuning),null!==e.perTrackDisplayTuning){const s=new Map;t.set("pertrackdisplaytuning",s);for(const[t,i]of e.perTrackDisplayTuning)s.set(t.toString(),i)}if(t.set("globaldisplaychorddiagramsontop",e.globalDisplayChordDiagramsOnTop),null!==e.perTrackChordDiagramsOnTop){const s=new Map;t.set("pertrackchorddiagramsontop",s);for(const[t,i]of e.perTrackChordDiagramsOnTop)s.set(t.toString(),i)}return t.set("singletracktracknamepolicy",e.singleTrackTrackNamePolicy),t.set("multitracktracknamepolicy",e.multiTrackTrackNamePolicy),t.set("firstsystemtracknamemode",e.firstSystemTrackNameMode),t.set("othersystemstracknamemode",e.otherSystemsTrackNameMode),t.set("firstsystemtracknameorientation",e.firstSystemTrackNameOrientation),t.set("othersystemstracknameorientation",e.otherSystemsTrackNameOrientation),t}static setProperty(e,t,s){switch(t){case"hidedynamics":return e.hideDynamics=s,!0;case"bracketextendmode":return e.bracketExtendMode=st.parseEnum(s,z),!0;case"usesystemsignseparator":return e.useSystemSignSeparator=s,!0;case"globaldisplaytuning":return e.globalDisplayTuning=s,!0;case"pertrackdisplaytuning":return e.perTrackDisplayTuning=new Map,st.forEach(s,((t,s)=>{e.perTrackDisplayTuning.set(parseInt(s),t)})),!0;case"globaldisplaychorddiagramsontop":return e.globalDisplayChordDiagramsOnTop=s,!0;case"pertrackchorddiagramsontop":return e.perTrackChordDiagramsOnTop=new Map,st.forEach(s,((t,s)=>{e.perTrackChordDiagramsOnTop.set(parseInt(s),t)})),!0;case"singletracktracknamepolicy":return e.singleTrackTrackNamePolicy=st.parseEnum(s,U),!0;case"multitracktracknamepolicy":return e.multiTrackTrackNamePolicy=st.parseEnum(s,U),!0;case"firstsystemtracknamemode":return e.firstSystemTrackNameMode=st.parseEnum(s,X),!0;case"othersystemstracknamemode":return e.otherSystemsTrackNameMode=st.parseEnum(s,X),!0;case"firstsystemtracknameorientation":return e.firstSystemTrackNameOrientation=st.parseEnum(s,J),!0;case"othersystemstracknameorientation":return e.otherSystemsTrackNameOrientation=st.parseEnum(s,J),!0}return!1}}class ts{static fromJson(e,t){t&&st.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=>Gt.toJson(e)))),t.set("tracks",e.tracks.map((e=>Zt.toJson(e)))),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("stylesheet",es.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 ne;Gt.fromJson(s,t),e.addMasterBar(s)}return!0;case"tracks":e.tracks=[];for(const t of s){const s=new Le;Zt.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&&(es.fromJson(e.stylesheet,s),!0)}}class ss{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=ss.scoreToJsObject(e);return JSON.stringify(t,ss.jsonReplacer)}static jsonToScore(e,t){return ss.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return ts.toJson(e)}static jsObjectToScore(e,t){let s=new Ne;return ts.fromJson(s,e),s.finish(t??new Ot),s}static settingsToJson(e){let t=ss.settingsToJsObject(e);return JSON.stringify(t,ss.jsonReplacer)}static jsonToSettings(e){return ss.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return At.toJson(e)}static jsObjectToSettings(e){let t=new Ot;return At.fromJson(t,e),t}static jsObjectToMidiFile(e){let t=new ot;return st.forEach(e,((e,s)=>{switch(s){case"division":t.division=e;break;case"tracks":for(let s of e){let e=ss.jsObjectToMidiTrack(s);t.tracks.push(e)}}})),t}static jsObjectToMidiTrack(e){let t=new nt;return st.forEach(e,((e,s)=>{if("events"===s)for(let s of e){let e=ss.jsObjectToMidiEvent(s);t.events.push(e)}})),t}static jsObjectToMidiEvent(e){let t=st.getValue(e,"track"),i=st.getValue(e,"tick"),a=st.getValue(e,"type");switch(a){case je.TimeSignature:return new lt(t,i,st.getValue(e,"numerator"),st.getValue(e,"denominatorIndex"),st.getValue(e,"midiClocksPerMetronomeClick"),st.getValue(e,"thirdySecondNodesInQuarter"));case je.AlphaTabRest:return new ut(t,i,st.getValue(e,"channel"));case je.AlphaTabMetronome:return new ct(t,i,st.getValue(e,"metronomeNumerator"),st.getValue(e,"metronomeDurationInTicks"),st.getValue(e,"metronomeDurationInMilliseconds"));case je.NoteOn:return new gt(t,i,st.getValue(e,"channel"),st.getValue(e,"noteKey"),st.getValue(e,"noteVelocity"));case je.NoteOff:return new mt(t,i,st.getValue(e,"channel"),st.getValue(e,"noteKey"),st.getValue(e,"noteVelocity"));case je.ControlChange:return new ft(t,i,st.getValue(e,"channel"),st.getValue(e,"controller"),st.getValue(e,"value"));case je.ProgramChange:return new yt(t,i,st.getValue(e,"channel"),st.getValue(e,"program"));case je.TempoChange:return new bt(i,st.getValue(e,"microSecondsPerQuarterNote"));case je.PitchBend:return new St(t,i,st.getValue(e,"channel"),st.getValue(e,"value"));case je.PerNotePitchBend:return new _t(t,i,st.getValue(e,"channel"),st.getValue(e,"noteKey"),st.getValue(e,"value"));case je.EndOfTrack:return new wt(t,i)}throw new j(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(ss.midiTrackToJsObject(t));return t.set("tracks",s),t}static midiTrackToJsObject(e){const t=new Map,s=[];for(let t of e.events)s.push(ss.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 je.TimeSignature:t.set("numerator",e.numerator),t.set("denominatorIndex",e.denominatorIndex),t.set("midiClocksPerMetronomeClick",e.midiClocksPerMetronomeClick),t.set("thirdySecondNodesInQuarter",e.thirtySecondNodesInQuarter);break;case je.AlphaTabRest:t.set("channel",e.channel);break;case je.AlphaTabMetronome:t.set("metronomeNumerator",e.metronomeNumerator),t.set("metronomeDurationInMilliseconds",e.metronomeDurationInMilliseconds),t.set("metronomeDurationInTicks",e.metronomeDurationInTicks);break;case je.NoteOn:case je.NoteOff:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("noteVelocity",e.noteVelocity);break;case je.ControlChange:t.set("channel",e.channel),t.set("controller",e.controller),t.set("value",e.value);break;case je.ProgramChange:t.set("channel",e.channel),t.set("program",e.program);break;case je.TempoChange:t.set("microSecondsPerQuarterNote",e.microSecondsPerQuarterNote);break;case je.PitchBend:t.set("channel",e.channel),t.set("value",e.value);break;case je.PerNotePitchBend:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("value",e.value);case je.EndOfTrack:}return t}}var is,as,rs,ns=Object.freeze({__proto__:null,get AccentuationType(){return i},get AccidentalType(){return Xe},Automation:Q,get AutomationType(){return a},Bar:Z,get BarreShape(){return V},Beat:we,get BeatBeamingMode(){return G},BendPoint:te,get BendStyle(){return l},get BendType(){return d},get BracketExtendMode(){return z},get BrushType(){return c},Chord:Be,get Clef(){return r},Color:Ce,get CrescendoType(){return u},get Duration(){return p},get DynamicValue(){return g},get FadeType(){return O},Fermata:Ze,get FermataType(){return He},get Fingers(){return f},Font:rt,get FontStyle(){return Je},get FontWeight(){return Ye},get GraceType(){return m},get HarmonicType(){return y},InstrumentArticulation:ce,JsonConverter:ss,get KeySignature(){return v},get KeySignatureType(){return P},Lyrics:ke,MasterBar:ne,get MusicFontSymbol(){return F},Note:ge,get NoteAccidentalMode(){return b},get NoteOrnament(){return M},get Ottavia(){return n},get PickStroke(){return E},PlaybackInformation:Ee,get Rasgueado(){return H},RenderStylesheet:Te,RepeatGroup:xe,Score:Ne,Section:ve,get SimileMark(){return o},get SlideInType(){return S},get SlideOutType(){return _},Staff:De,SustainPedalMarker:$,get SustainPedalMarkerType(){return h},Track:Le,get TrackNameMode(){return X},get TrackNameOrientation(){return J},get TrackNamePolicy(){return U},get TripletFeel(){return C},Tuning:Fe,TupletGroup:me,get VibratoType(){return w},Voice:Me,get WahPedal(){return R},get WhammyType(){return I}});class os extends q{get name(){return"Guitar Pro 3-5"}constructor(){super(),this._versionNumber=0,this._globalTripletFeel=C.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._beatTextChunksByTrack=new Map,this._directionLookup=new Map}readScore(){if(this._directionLookup.clear(),this.readVersion(),this._score=new Ne,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=hs.gpReadBool(this.data)?C.Triplet8th:C.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=hs.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=Ae.readInt32LE(this.data),this._versionNumber>=510&&hs.gpReadBool(this.data),Ae.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.readDirection(Ve.TargetCoda),this.readDirection(Ve.TargetDoubleCoda),this.readDirection(Ve.TargetSegno),this.readDirection(Ve.TargetSegnoSegno),this.readDirection(Ve.TargetFine),this.readDirection(Ve.JumpDaCapo),this.readDirection(Ve.JumpDaCapoAlCoda),this.readDirection(Ve.JumpDaCapoAlDoubleCoda),this.readDirection(Ve.JumpDaCapoAlFine),this.readDirection(Ve.JumpDalSegno),this.readDirection(Ve.JumpDalSegnoAlCoda),this.readDirection(Ve.JumpDalSegnoAlDoubleCoda),this.readDirection(Ve.JumpDalSegnoAlFine),this.readDirection(Ve.JumpDalSegnoSegno),this.readDirection(Ve.JumpDalSegnoSegnoAlCoda),this.readDirection(Ve.JumpDalSegnoSegnoAlDoubleCoda),this.readDirection(Ve.JumpDalSegnoSegnoAlFine),this.readDirection(Ve.JumpDaCoda),this.readDirection(Ve.JumpDaDoubleCoda),this.data.skip(4)),this._barCount=Ae.readInt32LE(this.data),this._trackCount=Ae.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0){const e=Q.buildTempoAutomation(!1,0,this._score.tempo,2);e.text=this._score.tempoLabel,this._score.masterBars[0].tempoAutomations.push(e)}return this._score.finish(this.settings),this._lyrics&&this._lyricsTrack>=0&&this._score.tracks[this._lyricsTrack].applyLyrics(this._lyrics),this._score}readDirection(e){let t,s=Ae.readInt16LE(this.data);-1!==s&&(s--,this._directionLookup.has(s)?t=this._directionLookup.get(s):(t=[],this._directionLookup.set(s,t)),t.push(e))}readVersion(){let e=hs.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(os.VersionString))throw new K("Unsupported format");e=e.substr(os.VersionString.length+1);let t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*parseInt(e.substr(0,t))+parseInt(e.substr(t+1)),re.debug(this.name,"Guitar Pro version "+e+" detected")}readScoreInformation(){this._score.title=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding);let e=Ae.readInt32LE(this.data),t="";for(let s=0;s<e;s++)s>0&&(t+="\r\n"),t+=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding)?.toString();this._score.notices=t}readLyrics(){this._lyrics=[],this._lyricsTrack=Ae.readInt32LE(this.data)-1;for(let e=0;e<5;e++){let e=new ke;e.startBar=Ae.readInt32LE(this.data)-1,e.text=hs.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(30);for(let e=0;e<10;e++)hs.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){let t=new Ee;t.primaryChannel=e,t.secondaryChannel=e,t.program=Ae.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 ne,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 ve;e.text=hs.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",hs.gpReadColor(this.data,!1),t.section=e}if(64&s?(t.keySignature=Ae.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=C.Triplet8th;break;case 2:t.tripletFeel=C.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=!!(128&s);const i=this._score.masterBars.length;if(this._directionLookup.has(i))for(const e of this._directionLookup.get(i))t.addDirection(e);this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){let e=new Le;e.ensureStaveCount(1),this._score.addTrack(e);let t=e.staves[0],s=this.data.readByte();e.name=hs.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),1&s&&(t.isPercussion=!0),this._versionNumber>=500&&(e.isVisibleOnMultiTrack=!!(8&s)),null===this._score.stylesheet.perTrackDisplayTuning&&(this._score.stylesheet.perTrackDisplayTuning=new Map),this._score.stylesheet.perTrackDisplayTuning.set(e.index,!!(128&s));let i=Ae.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){let t=Ae.readInt32LE(this.data);i>e&&a.push(t)}t.stringTuning.tunings=a;let r=Ae.readInt32LE(this.data),n=Ae.readInt32LE(this.data)-1,o=Ae.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,Y.isGuitar(i.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=i}if(t.capo=Ae.readInt32LE(this.data),e.color=hs.gpReadColor(this.data,!1),this._versionNumber>=500){const s=this.data.readByte();t.showTablature=!!(1&s),t.showStandardNotation=!!(2&s);const i=!!(100&s);null===this._score.stylesheet.perTrackChordDiagramsOnTop&&(this._score.stylesheet.perTrackChordDiagramsOnTop=new Map),this._score.stylesheet.perTrackChordDiagramsOnTop.set(e.index,i),this.data.readByte(),this.data.skip(43)}this._versionNumber>=510&&(this.data.skip(4),hs.gpReadStringIntByte(this.data,this.settings.importer.encoding),hs.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 Z,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=Ae.readInt32LE(this.data);if(0===s)return;let i=new Me;t.addVoice(i);for(let a=0;a<s;a++)this.readBeat(e,t,i)}readBeat(e,t,s){let i=new we,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),Ae.readSInt8(this.data)){case-2:i.duration=p.Whole;break;case-1:i.duration=p.Half;break;case 0:i.duration=p.Quarter;break;case 1:i.duration=p.Eighth;break;case 2:i.duration=p.Sixteenth;break;case 3:i.duration=p.ThirtySecond;break;case 4:i.duration=p.SixtyFourth;break;default:i.duration=p.Quarter}if(32&a)switch(i.tupletNumerator=Ae.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=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const s=new ke;s.text=t.trim(),s.finish(!0);const i=[];for(let e=s.chunks.length-1;e>=0;e--)i.push(s.chunks[e]);this._beatTextChunksByTrack.set(e.index,i)}else i.text=t}let o=y.None;8&a&&(o=this.readBeatEffects(i)),16&a&&this.readMixTableChange(i);let h=this.data.readByte();for(let a=6;a>=0;a--)if(h&1<<a&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,s,i,6-a);o!==y.None&&(r.harmonicType=o,r.harmonicType===y.Natural&&(r.harmonicValue=le.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){const e=Ae.readInt16LE(this.data);if(1&e&&i.index>0&&(s.beats[i.index-1].beamingMode=G.ForceSplitToNext),2&e&&(i.preferredBeamDirection=Ge.Down),4&e&&i.index>0&&(s.beats[i.index-1].beamingMode=G.ForceMergeWithNext),8&e&&(i.preferredBeamDirection=Ge.Up),16&e&&(i.ottava=n._8va),32&e&&(i.ottava=n._8vb),64&e&&(i.ottava=n._15ma),256&e&&(i.ottava=n._15mb),2048&e){const e=0!=this.data.readByte();i.index>0&&e&&(s.beats[i.index-1].beamingMode=G.ForceSplitOnSecondaryToNext)}}r&&!i.isRest&&this._beatTextChunksByTrack.has(e.index)&&this._beatTextChunksByTrack.get(e.index).length>0&&(i.lyrics=[this._beatTextChunksByTrack.get(e.index).pop()])}readChord(e){let t=new Be,s=le.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=hs.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Ae.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Ae.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=hs.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Ae.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Ae.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=hs.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=Ae.readInt32LE(this.data);for(let s=0;s<6;s++){let i=Ae.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=hs.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=Ae.readInt32LE(this.data),t.firstFret>0)for(let i=0;i<s;i++){let s=Ae.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}}t.name&&(e.chordId=s,e.voice.bar.staff.addChord(e.chordId,t))}readBeatEffects(e){let t=this.data.readByte(),s=0;if(this._versionNumber>=400&&(s=this.data.readByte()),16&t&&(e.fade=O.FadeIn),(this._versionNumber<400&&1&t||2&t)&&(e.vibrato=w.Slight),1&s&&(e.rasgueado=H.Ii),32&t&&this._versionNumber>=400){switch(Ae.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(Ae.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=os.toStrokeValue(t)):s>0&&(e.brushType=c.BrushDown,e.brushDuration=os.toStrokeValue(s))}if(2&s)switch(Ae.readSInt8(this.data)){case 0:e.pickStroke=E.None;break;case 1:e.pickStroke=E.Up;break;case 2:e.pickStroke=E.Down}if(this._versionNumber<400){if(4&t)return y.Natural;if(8&t)return y.Artificial}return y.None}readTremoloBarEffect(e){this.data.readByte(),Ae.readInt32LE(this.data);let t=Ae.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new te(0,0);t.offset=Ae.readInt32LE(this.data),t.value=Ae.readInt32LE(this.data)/os.BendStep|0,hs.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 ls;t.instrument=Ae.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=Ae.readSInt8(this.data),t.balance=Ae.readSInt8(this.data);let s=Ae.readSInt8(this.data),i=Ae.readSInt8(this.data),r=Ae.readSInt8(this.data),n=Ae.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=hs.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=Ae.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=Ae.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500){const t=Ae.readSInt8(this.data);t>=100?e.wahPedal=R.Closed:t>=0&&(e.wahPedal=R.Open)}if(this._versionNumber>=510&&(hs.gpReadStringIntByte(this.data,this.settings.importer.encoding),hs.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){let s=new Q;s.isLinear=!0,s.type=a.Volume,s.value=t.volume,e.automations.push(s)}if(t.balance>=0){let s=new Q;s.isLinear=!0,s.type=a.Balance,s.value=t.balance,e.automations.push(s)}if(t.instrument>=0){let s=new Q;s.isLinear=!0,s.type=a.Instrument,s.value=t.instrument,e.automations.push(s)}if(t.tempo>=0){let s=new Q;s.isLinear=!0,s.type=a.Tempo,s.value=t.tempo,e.automations.push(s),e.voice.bar.masterBar.tempoAutomations.push(s)}}readNote(e,t,s,a,r){let n=new ge;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=Ae.readSInt8(this.data);n.dynamics=this.toDynamicValue(e),a.dynamics=n.dynamics}32&o&&(n.fret=Ae.readSInt8(this.data)),128&o&&(n.leftHandFinger=Ae.readSInt8(this.data),n.rightHandFinger=Ae.readSInt8(this.data));let h=!1;if(this._versionNumber>=500){1&o&&(n.durationPercent=Ae.readFloat64BE(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=Fe.defaultAccidentals[n.realValueWithoutHarmonic%12];"#"===e?n.accidentalMode=b.ForceFlat:"b"===e&&(n.accidentalMode=b.ForceSharp)}return n}toDynamicValue(e){switch(e){case 1:return g.PPP;case 2:return g.PP;case 3:return g.P;case 4:return g.MP;case 5:return g.MF;case 6:default:return g.F;case 7:return g.FF;case 8:return g.FFF}}readNoteEffects(e,t,s,i){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=_.Shift),16&r&&this.readArtificialHarmonic(i),32&r&&this.readTrill(i),i.isLetRing=!!(8&a),i.isHammerPullOrigin=!!(2&a),64&r&&(i.vibrato=w.Slight),i.isPalmMute=!!(2&r),i.isStaccato=!!(1&r)}readBend(e){this.data.readByte(),Ae.readInt32LE(this.data);let t=Ae.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new te(0,0);t.offset=Ae.readInt32LE(this.data),t.value=Ae.readInt32LE(this.data)/os.BendStep|0,hs.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){let s=new we,i=new ge;switch(i.string=t.string,i.fret=Ae.readSInt8(this.data),s.duration=p.ThirtySecond,s.dynamics=this.toDynamicValue(Ae.readSInt8(this.data)),Ae.readSInt8(this.data)){case 0:case 2:break;case 1:i.slideOutType=_.Legato,i.slideTarget=t;break;case 3:i.isHammerPullOrigin=!0}if(i.dynamics=s.dynamics,this.data.skip(1),this._versionNumber<500)s.graceType=m.BeforeBeat;else{let e=this.data.readByte();i.isDead=!!(1&e),s.graceType=2&e?m.OnBeat:m.BeforeBeat}e.addGraceBeat(s),s.addNote(i)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=p.Eighth;break;case 2:e.tremoloSpeed=p.Sixteenth;break;case 3:e.tremoloSpeed=p.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){let t=Ae.readSInt8(this.data);1&t?e.slideOutType=_.Shift:2&t?e.slideOutType=_.Legato:4&t?e.slideOutType=_.OutDown:8&t&&(e.slideOutType=_.OutUp),16&t?e.slideInType=S.IntoFromBelow:32&t&&(e.slideInType=S.IntoFromAbove)}else{switch(Ae.readSInt8(this.data)){case 1:e.slideOutType=_.Shift;break;case 2:e.slideOutType=_.Legato;break;case 3:e.slideOutType=_.OutDown;break;case 4:e.slideOutType=_.OutUp;break;case-1:e.slideInType=S.IntoFromBelow;break;case-2:e.slideInType=S.IntoFromAbove}}}readArtificialHarmonic(e){let t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=y.Natural,e.harmonicValue=le.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=y.Artificial;break;case 3:e.harmonicType=y.Tap,e.harmonicValue=le.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=y.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=y.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=y.Natural;break;case 3:e.harmonicType=y.Tap;break;case 4:e.harmonicType=y.Pinch;break;case 5:e.harmonicType=y.Semi;break;case 15:case 17:case 22:e.harmonicType=y.Artificial}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=p.Sixteenth;break;case 2:e.trillSpeed=p.ThirtySecond;break;case 3:e.trillSpeed=p.SixtyFourth}}}os.VersionString="FICHIER GUITAR PRO ",os.BendStep=25;class hs{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 Ce(s,i,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),hs.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return hs.gpReadString(e,Ae.readInt32LE(e),t)}static gpReadStringIntByte(e,t){let s=Ae.readInt32LE(e)-1;return e.readByte(),hs.gpReadString(e,s,t)}static gpReadString(e,t,s){let i=new Uint8Array(t);return e.read(i,0,i.length),Ae.toString(i,s)}static gpWriteString(e,t){const s=Ae.stringToBytes(t);e.writeByte(t.length),e.write(s,0,s.length)}static gpReadStringByteLength(e,t,s){let i=e.readByte(),a=hs.gpReadString(e,i,s);return i<t&&e.skip(t-i),a}}class ls{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class ds{constructor(){this.x=0,this.y=0,this.w=0,this.h=0}scaleWith(e){this.x*=e,this.y*=e,this.w*=e,this.h*=e}}!function(e){e[e.Boolean=0]="Boolean",e[e.Integer=1]="Integer",e[e.Float=2]="Float",e[e.String=3]="String",e[e.Point=4]="Point",e[e.Size=5]="Size",e[e.Rectangle=6]="Rectangle",e[e.Color=7]="Color"}(is||(is={}));class cs{constructor(e){this._types=new Map,this.raw=new Map,e&&this.read(e)}read(e){let t=Oe.fromBuffer(e),s=Ae.readInt32BE(t);for(let e=0;e<s;e++){let e=hs.gpReadString(t,t.readByte(),"utf-8"),s=t.readByte();switch(this._types.set(e,s),s){case is.Boolean:let s=1===t.readByte();this.addValue(e,s);break;case is.Integer:let i=Ae.readInt32BE(t);this.addValue(e,i);break;case is.Float:let a=Ae.readFloat32BE(t);this.addValue(e,a);break;case is.String:let r=hs.gpReadString(t,Ae.readInt16BE(t),"utf-8");this.addValue(e,r);break;case is.Point:let n=Ae.readInt32BE(t),o=Ae.readInt32BE(t);this.addValue(e,new te(n,o));break;case is.Size:let h=Ae.readInt32BE(t),l=Ae.readInt32BE(t);this.addValue(e,new te(h,l));break;case is.Rectangle:let d=new ds;d.x=Ae.readInt32BE(t),d.y=Ae.readInt32BE(t),d.w=Ae.readInt32BE(t),d.h=Ae.readInt32BE(t),this.addValue(e,d);break;case is.Color:let c=hs.gpReadColor(t,!0);this.addValue(e,c)}}}apply(e){for(const[t,s]of this.raw)switch(t){case"StandardNotation/hideDynamics":e.stylesheet.hideDynamics=s;break;case"System/bracketExtendMode":e.stylesheet.bracketExtendMode=s;break;case"Global/useSystemSignSeparator":e.stylesheet.useSystemSignSeparator=s;break;case"Global/DisplayTuning":e.stylesheet.globalDisplayTuning=s;break;case"Global/DrawChords":e.stylesheet.globalDisplayChordDiagramsOnTop=s;break;case"System/showTrackNameSingle":s||(e.stylesheet.singleTrackTrackNamePolicy=U.Hidden);break;case"System/showTrackNameMulti":s||(e.stylesheet.multiTrackTrackNamePolicy=U.Hidden);break;case"System/trackNameModeSingle":if(e.stylesheet.singleTrackTrackNamePolicy!==U.Hidden)switch(s){case 0:case 1:e.stylesheet.singleTrackTrackNamePolicy=U.FirstSystem;break;case 2:e.stylesheet.singleTrackTrackNamePolicy=U.AllSystems}break;case"System/trackNameModeMulti":if(e.stylesheet.multiTrackTrackNamePolicy!==U.Hidden)switch(s){case 0:case 1:e.stylesheet.multiTrackTrackNamePolicy=U.FirstSystem;break;case 2:e.stylesheet.multiTrackTrackNamePolicy=U.AllSystems}break;case"System/shortTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameMode=s?X.ShortName:X.FullName;break;case"System/shortTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameMode=s?X.ShortName:X.FullName;break;case"System/horizontalTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameOrientation=s?J.Horizontal:J.Vertical;break;case"System/horizontalTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameOrientation=s?J.Horizontal:J.Vertical}}addValue(e,t,s){this.raw.set(e,t),void 0!==s&&this._types.set(e,s)}writeTo(e){Ae.writeInt32BE(e,this.raw.size);for(const[t,s]of this.raw){const i=this.getDataType(t,s);switch(hs.gpWriteString(e,t),e.writeByte(i),i){case is.Boolean:e.writeByte(s?1:0);break;case is.Integer:Ae.writeInt32BE(e,s);break;case is.Float:Ae.writeFloat32BE(e,s);break;case is.String:const t=Ae.stringToBytes(s);Ae.writeInt16BE(e,t.length),e.write(t,0,t.length);break;case is.Point:case is.Size:Ae.writeInt32BE(e,s.offset),Ae.writeInt32BE(e,s.value);break;case is.Rectangle:Ae.writeInt32BE(e,s.x),Ae.writeInt32BE(e,s.y),Ae.writeInt32BE(e,s.w),Ae.writeInt32BE(e,s.h);break;case is.Color:e.writeByte(s.r),e.writeByte(s.g),e.writeByte(s.b),e.writeByte(s.a)}}}getDataType(e,t){if(this._types.has(e))return this._types.get(e);const i=typeof t;switch(typeof t){case"string":return is.String;case"number":return t==(0|t)?is.Integer:is.Float;case"object":if(t instanceof te)return is.Point;if(t instanceof ds)return is.Rectangle;if(t instanceof Ce)return is.Color}throw new j(s.General,`Unknown value type in BinaryStylesheet: ${i}`)}static writeForScore(e){const t=new cs;switch(t.addValue("StandardNotation/hideDynamics",e.stylesheet.hideDynamics,is.Boolean),t.addValue("System/bracketExtendMode",e.stylesheet.bracketExtendMode,is.Integer),t.addValue("Global/useSystemSignSeparator",e.stylesheet.useSystemSignSeparator,is.Boolean),t.addValue("Global/DisplayTuning",e.stylesheet.globalDisplayTuning,is.Boolean),t.addValue("Global/DrawChords",e.stylesheet.globalDisplayChordDiagramsOnTop,is.Boolean),e.stylesheet.singleTrackTrackNamePolicy){case U.Hidden:t.addValue("System/showTrackNameSingle",!1,is.Boolean);break;case U.FirstSystem:t.addValue("System/trackNameModeSingle",0,is.Integer);break;case U.AllSystems:t.addValue("System/trackNameModeSingle",2,is.Integer)}switch(e.stylesheet.multiTrackTrackNamePolicy){case U.Hidden:t.addValue("System/trackNameModeMulti",!1,is.Boolean);break;case U.FirstSystem:t.addValue("System/trackNameModeMulti",0,is.Integer);break;case U.AllSystems:t.addValue("System/trackNameModeMulti",2,is.Integer)}switch(e.stylesheet.firstSystemTrackNameMode){case X.FullName:t.addValue("System/shortTrackNameOnFirstSystem",!1,is.Boolean);break;case X.ShortName:t.addValue("System/shortTrackNameOnFirstSystem",!0,is.Boolean)}switch(e.stylesheet.otherSystemsTrackNameMode){case X.FullName:t.addValue("System/shortTrackNameOnOtherSystems",!1,is.Boolean);break;case X.ShortName:t.addValue("System/shortTrackNameOnOtherSystems",!0,is.Boolean)}switch(e.stylesheet.firstSystemTrackNameOrientation){case J.Horizontal:t.addValue("System/horizontalTrackNameOnFirstSystem",!0,is.Boolean);break;case J.Vertical:t.addValue("System/horizontalTrackNameOnFirstSystem",!1,is.Boolean)}switch(e.stylesheet.otherSystemsTrackNameOrientation){case J.Horizontal:t.addValue("System/horizontalTrackNameOnOtherSystems",!0,is.Boolean);break;case J.Vertical:t.addValue("System/horizontalTrackNameOnOtherSystems",!1,is.Boolean)}const s=Oe.withCapacity(128);return t.writeTo(s),s.toArray()}}!function(e){e[e.None=0]="None",e[e.Element=1]="Element",e[e.Text=2]="Text",e[e.CDATA=3]="CDATA",e[e.Document=4]="Document",e[e.DocumentType=5]="DocumentType"}(as||(as={}));class us{constructor(){this.nodeType=as.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!==as.Element&&e.nodeType!==as.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===as.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===as.Element&&t.localName===e)return t;return null}addElement(e){const t=new us;return t.nodeType=as.Element,t.localName=e,this.addChild(t),t}get innerText(){if(this.nodeType===as.Element||this.nodeType===as.Document){if(this.firstElement&&this.firstElement.nodeType===as.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 us;t.nodeType=as.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new us;t.nodeType=as.CDATA,t.value=e,this.childNodes=[t]}}class ps extends j{constructor(e,t,i){super(s.Format,e),this.pos=0,this.xml=t,this.pos=i,Object.setPrototypeOf(this,ps.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"}(rs||(rs={}));class gs{static parse(e,t,s){let i=e.charCodeAt(t),a=rs.Begin,r=rs.Begin,n=0,o="",h=rs.Begin,l=null,d=null,c=0,u=0;for(;t<e.length;){switch(i=e.charCodeAt(t),a){case rs.IgnoreSpaces:switch(i){case gs.CharCodeLF:case gs.CharCodeCR:case gs.CharCodeTab:case gs.CharCodeSpace:break;default:a=r;continue}break;case rs.Begin:if(i!==gs.CharCodeLowerThan){n=t,a=rs.Pcdata;continue}a=rs.IgnoreSpaces,r=rs.BeginNode;break;case rs.Pcdata:if(i===gs.CharCodeLowerThan){o+=e.substr(n,t-n);let i=new us;i.nodeType=as.Text,i.value=o,o="",s.addChild(i),a=rs.IgnoreSpaces,r=rs.BeginNode}else i===gs.CharCodeAmp&&(o+=e.substr(n,t-n),a=rs.Escape,h=rs.Pcdata,n=t+1);break;case rs.Cdata:if(i===gs.CharCodeBrackedClose&&e.charCodeAt(t+1)===gs.CharCodeBrackedClose&&e.charCodeAt(t+2)===gs.CharCodeGreaterThan){let i=new us;i.nodeType=as.CDATA,i.value=e.substr(n,t-n),s.addChild(i),t+=2,a=rs.Begin}break;case rs.BeginNode:switch(i){case gs.CharCodeExclamation:if(e.charCodeAt(t+1)===gs.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new ps("Expected <![CDATA[",e,t);t+=5,a=rs.Cdata,n=t+1}else if(e.charCodeAt(t+1)===gs.CharCodeUpperD||e.charCodeAt(t+1)===gs.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new ps("Expected <!DOCTYPE",e,t);t+=8,a=rs.Doctype,n=t+1}else{if(e.charCodeAt(t+1)!==gs.CharCodeMinus||e.charCodeAt(t+2)!==gs.CharCodeMinus)throw new ps("Expected \x3c!--",e,t);t+=2,a=rs.Comment,n=t+1}break;case gs.CharCodeQuestion:a=rs.Header,n=t;break;case gs.CharCodeSlash:if(!s)throw new ps("Expected node name",e,t);n=t+1,a=rs.IgnoreSpaces,r=rs.Close;break;default:a=rs.TagName,n=t;continue}break;case rs.TagName:if(!gs.isValidChar(i)){if(t===n)throw new ps("Expected node name",e,t);l=new us,l.nodeType=as.Element,l.localName=e.substr(n,t-n),s.addChild(l),a=rs.IgnoreSpaces,r=rs.Body;continue}break;case rs.Body:switch(i){case gs.CharCodeSlash:a=rs.WaitEnd;break;case gs.CharCodeGreaterThan:a=rs.Childs;break;default:a=rs.AttribName,n=t;continue}break;case rs.AttribName:if(!gs.isValidChar(i)){if(n===t)throw new ps("Expected attribute name",e,t);if(d=e.substr(n,t-n),l.attributes.has(d))throw new ps(`Duplicate attribute [${d}]`,e,t);a=rs.IgnoreSpaces,r=rs.Equals;continue}break;case rs.Equals:if(i!==gs.CharCodeEquals)throw new ps("Expected =",e,t);a=rs.IgnoreSpaces,r=rs.AttvalBegin;break;case rs.AttvalBegin:switch(i){case gs.CharCodeDoubleQuote:case gs.CharCodeSingleQuote:o="",a=rs.AttribVal,n=t+1,u=i}break;case rs.AttribVal:if(i===gs.CharCodeAmp)o+=e.substr(n,t-n),a=rs.Escape,h=rs.AttribVal,n=t+1;else if(i===u){o+=e.substr(n,t-n);let s=o;o="",l.attributes.set(d,s),a=rs.IgnoreSpaces,r=rs.Body}break;case rs.Childs:n=t=gs.parse(e,t,l),a=rs.Begin;break;case rs.WaitEnd:if(i!==gs.CharCodeGreaterThan)throw new ps("Expected >",e,t);a=rs.Begin;break;case rs.WaitEndRet:if(i===gs.CharCodeGreaterThan)return t;throw new ps("Expected >",e,t);case rs.Close:if(!gs.isValidChar(i)){if(n===t)throw new ps("Expected node name",e,t);if(e.substr(n,t-n)!==s.localName)throw new ps("Expected </"+s.localName+">",e,t);a=rs.IgnoreSpaces,r=rs.WaitEndRet;continue}break;case rs.Comment:i===gs.CharCodeMinus&&e.charCodeAt(t+1)===gs.CharCodeMinus&&e.charCodeAt(t+2)===gs.CharCodeGreaterThan&&(t+=2,a=rs.Begin);break;case rs.Doctype:if(i===gs.CharCodeBrackedOpen)c++;else if(i===gs.CharCodeBrackedClose)c--;else if(i===gs.CharCodeGreaterThan&&0===c){let i=new us;i.nodeType=as.DocumentType,i.value=e.substr(n,t-n),s.addChild(i),a=rs.Begin}break;case rs.Header:i===gs.CharCodeQuestion&&e.charCodeAt(t+1)===gs.CharCodeGreaterThan&&(t++,a=rs.Begin);break;case rs.Escape:if(i===gs.CharCodeSemi){let s=e.substr(n,t-n);if(s.charCodeAt(0)===gs.CharCodeSharp){let e=s.charCodeAt(1)===gs.CharCodeLowerX?parseInt("0"+s.substr(1,s.length-1)):parseInt(s.substr(1,s.length-1));o+=String.fromCharCode(e)}else gs.Escapes.has(s)?o+=gs.Escapes.get(s):o+=("&"+s+";")?.toString();n=t+1,a=h}else gs.isValidChar(i)||i===gs.CharCodeSharp||(o+="&",o+=e.substr(n,t-n),n=--t+1,a=h)}t++}if(a===rs.Begin&&(n=t,a=rs.Pcdata),a===rs.Pcdata){if(t!==n){o+=e.substr(n,t-n);let i=new us;i.nodeType=as.Text,i.value=o,s.addChild(i)}return t}if(a===rs.Escape&&h===rs.Pcdata){o+="&",o+=e.substr(n,t-n);let i=new us;return i.nodeType=as.Text,i.value=o,s.addChild(i),t}throw new ps("Unexpected end",e,t)}static isValidChar(e){return e>=gs.CharCodeLowerA&&e<=gs.CharCodeLowerZ||e>=gs.CharCodeUpperA&&e<=gs.CharCodeUpperZ||e>=gs.CharCode0&&e<=gs.CharCode9||e===gs.CharCodeColon||e===gs.CharCodeDot||e===gs.CharCodeUnderscore||e===gs.CharCodeMinus}}gs.CharCodeLF=10,gs.CharCodeTab=9,gs.CharCodeCR=13,gs.CharCodeSpace=32,gs.CharCodeLowerThan=60,gs.CharCodeAmp=38,gs.CharCodeBrackedClose=93,gs.CharCodeBrackedOpen=91,gs.CharCodeGreaterThan=62,gs.CharCodeExclamation=33,gs.CharCodeUpperD=68,gs.CharCodeLowerD=100,gs.CharCodeMinus=45,gs.CharCodeQuestion=63,gs.CharCodeSlash=47,gs.CharCodeEquals=61,gs.CharCodeDoubleQuote=34,gs.CharCodeSingleQuote=39,gs.CharCodeSharp=35,gs.CharCodeLowerX=120,gs.CharCodeLowerA=97,gs.CharCodeLowerZ=122,gs.CharCodeUpperA=65,gs.CharCodeUpperZ=90,gs.CharCode0=48,gs.CharCode9=57,gs.CharCodeColon=58,gs.CharCodeDot=46,gs.CharCodeUnderscore=95,gs.CharCodeSemi=59,gs.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class ms{static write(e,t,s){const i=new ms(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 as.None:break;case as.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===as.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case as.Text:e.value&&this.write(e.value);break;case as.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case as.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case as.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 fs extends us{constructor(){super(),this.nodeType=as.Document}parse(e){gs.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return ms.write(this,e,t)}}class ys{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=p.Quarter}}class bs{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return this.path+";"+this.name+";"+this.role}}class Ss{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1}parseXml(e,t){this._masterTrackAutomations=new Map,this._automationsPerTrackIdAndBarIndex=new Map,this._sustainPedalsPerTrackIdAndBarIndex=new Map,this._tracksMapping=[],this._tracksById=new Map,this._masterBars=[],this._barsOfMasterBar=[],this._voicesOfBar=new Map,this._barsById=new Map,this._voiceById=new Map,this._beatsOfVoice=new Map,this._beatById=new Map,this._rhythmOfBeat=new Map,this._rhythmById=new Map,this._notesOfBeat=new Map,this._noteById=new Map,this._tappedNotes=new Map,this._lyricsByTrack=new Map,this._soundsByTrack=new Map,this._skipApplyLyrics=!1;let s=new fs;try{s.parse(e)}catch(e){throw new K("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 K("Root node of XML was not GPIF");this.score=new Ne;for(let e of t.childNodes)if(e.nodeType===as.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===as.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===as.Element)switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null,null);break;case"Tracks":this._tracksMapping=t.innerText.split(" ");break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,s,i){for(let a of e.childNodes)if(a.nodeType===as.Element&&"Automation"===a.localName)this.parseAutomation(a,t,s,i)}parseAutomation(e,t,s,i){let a=null,r=!1,n=-1,o=0,l=0,d=null,c=0,u=null;for(let t of e.childNodes)if(t.nodeType===as.Element)switch(t.localName){case"Type":a=t.innerText;break;case"Linear":r="true"===t.innerText.toLowerCase();break;case"Bar":n=parseInt(t.innerText);break;case"Position":o=parseFloat(t.innerText);break;case"Value":if(t.firstElement&&t.firstElement.nodeType===as.CDATA)d=t.innerText;else{let e=t.innerText.split(" ");1===e.length?(l=parseFloat(e[0]),c=1):(l=parseFloat(e[0]),c=parseInt(e[1]))}break;case"Text":u=t.innerText}if(!a)return;let p=null;switch(a){case"Tempo":p=Q.buildTempoAutomation(r,o,l,c);break;case"Sound":d&&s&&s.has(d)&&(p=Q.buildInstrumentAutomation(r,o,s.get(d).program));break;case"SustainPedal":if(i){let e;i.has(n)?e=i.get(n):(e=[],i.set(n,e));const t=new $;switch(t.ratioPosition=o,c){case 1:t.pedalType=h.Down;break;case 3:t.pedalType=h.Up}e.push(t)}}p&&(u&&(p.text=u),n>=0&&(t.has(n)||t.set(n,[]),t.get(n).push(p)))}parseTracksNode(e){for(let t of e.childNodes)if(t.nodeType===as.Element&&"Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;let t=new Le;t.ensureStaveCount(1),t.staves[0].showStandardNotation=!0;let s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===as.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 Ce(s,i,a,255)}break;case"Instrument":let a=i.getAttribute("ref");(a.endsWith("-gs")||a.endsWith("GrandStaff"))&&(t.ensureStaveCount(2),t.staves[1].showStandardNotation=!0);break;case"InstrumentSet":this.parseInstrumentSet(t,i);break;case"NotationPatch":this.parseNotationPatch(t,i);break;case"ShortName":t.shortName=i.innerText;break;case"SystemsDefautLayout":t.defaultSystemsLayout=parseInt(i.innerText);break;case"SystemsLayout":t.systemsLayout=i.innerText.split(" ").map((e=>parseInt(e)));break;case"Lyrics":this.parseLyrics(s,i);break;case"Properties":this.parseTrackProperties(t,i);break;case"GeneralMidi":case"MidiConnection":case"MIDISettings":this.parseGeneralMidi(t,i);break;case"Sounds":this.parseSounds(s,t,i);break;case"PlaybackState":let r=i.innerText;t.playbackInfo.isSolo="Solo"===r,t.playbackInfo.isMute="Mute"===r;break;case"PartSounding":this.parsePartSounding(t,i);break;case"Staves":this.parseStaves(t,i);break;case"Transpose":this.parseTranspose(t,i);break;case"RSE":this.parseRSE(t,i);break;case"Automations":this.parseTrackAutomations(s,i)}this._tracksById.set(s,t)}parseTrackAutomations(e,t){const s=new Map;this._automationsPerTrackIdAndBarIndex.set(e,s);const i=new Map;this._sustainPedalsPerTrackIdAndBarIndex.set(e,i),this.parseAutomations(t,s,this._soundsByTrack.get(e),i)}parseNotationPatch(e,t){for(let s of t.childNodes)if(s.nodeType===as.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===as.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===as.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===as.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===as.Element&&"Articulation"===i.localName)this.parseArticulation(e,i,s)}parseArticulation(e,t,s){const i=new ce;i.outputMidiNumber=-1,i.elementType=s;let a="";for(let e of t.childNodes)if(e.nodeType===as.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=L.Bottom;break;case"inside":i.techniqueSymbolPlacement=L.Middle;break;case"below":i.techniqueSymbolPlacement=L.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==F.None&&(i.noteHeadHalf=i.noteHeadDefault),i.noteHeadWhole==F.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 F.PictEdgeOfCymbal;case"articStaccatoAbove":return F.ArticStaccatoAbove;case"noteheadParenthesis":return F.NoteheadParenthesis;case"stringsUpBow":return F.StringsUpBow;case"stringsDownBow":return F.StringsDownBow;case"guitarGolpe":return F.GuitarGolpe;default:return F.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return F.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return F.NoteheadDoubleWhole;case"noteheadWhole":return F.NoteheadWhole;case"noteheadHalf":return F.NoteheadHalf;case"noteheadBlack":return F.NoteheadBlack;case"noteheadNull":return F.NoteheadNull;case"noteheadXOrnate":return F.NoteheadXOrnate;case"noteheadTriangleUpWhole":return F.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return F.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return F.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return F.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return F.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return F.NoteheadDiamondWhiteWide;case"noteheadCircleX":return F.NoteheadCircleX;case"noteheadXWhole":return F.NoteheadXWhole;case"noteheadXHalf":return F.NoteheadXHalf;case"noteheadXBlack":return F.NoteheadXBlack;case"noteheadParenthesis":return F.NoteheadParenthesis;case"noteheadSlashedBlack2":return F.NoteheadSlashedBlack2;case"noteheadCircleSlash":return F.NoteheadCircleSlash;case"noteheadHeavyX":return F.NoteheadHeavyX;case"noteheadHeavyXHat":return F.NoteheadHeavyXHat;default:return re.warning("GPIF","Unknown notehead symbol",e),F.None}}parseStaves(e,t){let s=0;for(let i of t.childNodes)if(i.nodeType===as.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===as.Element&&"Properties"===s.localName)this.parseStaffProperties(e,s)}parseStaffProperties(e,t){for(let s of t.childNodes)if(s.nodeType===as.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===as.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===as.Element&&"Line"===e.localName)s.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,s)}parseLyricsLine(e){let t=new ke;for(let s of e.childNodes)if(s.nodeType===as.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===as.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===as.Element&&"Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){let s=new Be,i=t.getAttribute("id");for(let t of e.staves)t.addChord(i,s);this.parseDiagramItemForChord(s,t)}parseDiagramItemForStaff(e,t){let s=new Be,i=t.getAttribute("id");e.addChord(i,s),this.parseDiagramItemForChord(s,t)}parseDiagramItemForChord(e,t){e.name=t.getAttribute("name");let s=t.findChildElement("Diagram");if(!s)return e.showDiagram=!1,void(e.showFingering=!1);let i=parseInt(s.getAttribute("stringCount")),a=s.attributes.has("baseFret")?parseInt(s.getAttribute("baseFret")):0;e.firstFret=a+1;for(let t=0;t<i;t++)e.strings.push(-1);for(let t of s.childNodes)if(t.nodeType===as.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===as.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===as.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===as.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===as.Element&&"Sound"===i.localName)this.parseSound(e,t,i)}parseSound(e,t,s){const i=new bs;for(let e of s.childNodes)if(e.nodeType===as.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===as.Element&&"Program"===s.localName)e.program=parseInt(s.innerText)}parsePartSounding(e,t){for(let s of t.childNodes)if(s.nodeType===as.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===as.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===as.Element&&"ChannelStrip"===s.localName)this.parseChannelStrip(e,s)}parseChannelStrip(e,t){for(let s of t.childNodes)if(s.nodeType===as.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===as.Element&&"MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){let t=new ne;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(let s of e.childNodes)if(s.nodeType===as.Element)switch(s.localName){case"Time":let e=s.innerText.split("/");t.timeSignatureNumerator=parseInt(e[0]),t.timeSignatureDenominator=parseInt(e[1]);break;case"FreeTime":t.isFreeTime=!0;break;case"DoubleBar":t.isDoubleBar=!0;break;case"Section":t.section=new ve,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=C.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=C.Triplet8th;break;case"Triplet16th":t.tripletFeel=C.Triplet16th;break;case"Dotted8th":t.tripletFeel=C.Dotted8th;break;case"Dotted16th":t.tripletFeel=C.Dotted16th;break;case"Scottish8th":t.tripletFeel=C.Scottish8th;break;case"Scottish16th":t.tripletFeel=C.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=P.Major;break;case"minor":t.keySignatureType=P.Minor}break;case"Fermatas":this.parseFermatas(t,s);break;case"XProperties":this.parseMasterBarXProperties(t,s);break;case"Directions":this.parseDirections(t,s)}this._masterBars.push(t)}parseDirections(e,t){for(let s of t.childNodes)if(s.nodeType===as.Element)switch(s.localName){case"Target":switch(s.innerText){case"Coda":e.addDirection(Ve.TargetCoda);break;case"DoubleCoda":e.addDirection(Ve.TargetDoubleCoda);break;case"Segno":e.addDirection(Ve.TargetSegno);break;case"SegnoSegno":e.addDirection(Ve.TargetSegnoSegno);break;case"Fine":e.addDirection(Ve.TargetFine)}break;case"Jump":switch(s.innerText){case"DaCapo":e.addDirection(Ve.JumpDaCapo);break;case"DaCapoAlCoda":e.addDirection(Ve.JumpDaCapoAlCoda);break;case"DaCapoAlDoubleCoda":e.addDirection(Ve.JumpDaCapoAlDoubleCoda);break;case"DaCapoAlFine":e.addDirection(Ve.JumpDaCapoAlFine);break;case"DaSegno":e.addDirection(Ve.JumpDalSegno);break;case"DaSegnoAlCoda":e.addDirection(Ve.JumpDalSegnoAlCoda);break;case"DaSegnoAlDoubleCoda":e.addDirection(Ve.JumpDalSegnoAlDoubleCoda);break;case"DaSegnoAlFine":e.addDirection(Ve.JumpDalSegnoAlFine);break;case"DaSegnoSegno":e.addDirection(Ve.JumpDalSegnoSegno);break;case"DaSegnoSegnoAlCoda":e.addDirection(Ve.JumpDalSegnoSegnoAlCoda);break;case"DaSegnoSegnoAlDoubleCoda":e.addDirection(Ve.JumpDalSegnoSegnoAlDoubleCoda);break;case"DaSegnoSegnoAlFine":e.addDirection(Ve.JumpDalSegnoSegnoAlFine);break;case"DaCoda":e.addDirection(Ve.JumpDaCoda);break;case"DaDoubleCoda":e.addDirection(Ve.JumpDaDoubleCoda)}}}parseFermatas(e,t){for(let s of t.childNodes)if(s.nodeType===as.Element&&"Fermata"===s.localName)this.parseFermata(e,s)}parseFermata(e,t){let s=0,i=new Ze;for(let e of t.childNodes)if(e.nodeType===as.Element)switch(e.localName){case"Type":switch(e.innerText){case"Short":i.type=He.Short;break;case"Medium":i.type=He.Medium;break;case"Long":i.type=He.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])*ee.QuarterTime|0}}e.addFermata(s,i)}parseBars(e){for(let t of e.childNodes)if(t.nodeType===as.Element&&"Bar"===t.localName)this.parseBar(t)}parseBar(e){let t=new Z,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===as.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===as.Element&&"Voice"===t.localName)this.parseVoice(t)}parseVoice(e){let t=new Me,s=e.getAttribute("id");for(let t of e.childNodes)if(t.nodeType===as.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===as.Element&&"Beat"===t.localName)this.parseBeat(t)}parseBeat(e){let t=new we,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===as.Element)switch(i.localName){case"Notes":this._notesOfBeat.set(s,i.innerText.split(" "));break;case"Rhythm":this._rhythmOfBeat.set(s,i.getAttribute("ref"));break;case"Fadding":switch(i.innerText){case"FadeIn":t.fade=O.FadeIn;break;case"FadeOut":t.fade=O.FadeOut;break;case"VolumeSwell":t.fade=O.VolumeSwell}break;case"Tremolo":switch(i.innerText){case"1/2":t.tremoloSpeed=p.Eighth;break;case"1/4":t.tremoloSpeed=p.Sixteenth;break;case"1/8":t.tremoloSpeed=p.ThirtySecond}break;case"Chord":t.chordId=i.innerText;break;case"Hairpin":switch(i.innerText){case"Crescendo":t.crescendo=u.Crescendo;break;case"Decrescendo":t.crescendo=u.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=Ge.Up;break;case"Downward":t.preferredBeamDirection=Ge.Down}break;case"Dynamic":switch(i.innerText){case"PPP":t.dynamics=g.PPP;break;case"PP":t.dynamics=g.PP;break;case"P":t.dynamics=g.P;break;case"MP":t.dynamics=g.MP;break;case"MF":t.dynamics=g.MF;break;case"F":t.dynamics=g.F;break;case"FF":t.dynamics=g.FF;break;case"FFF":t.dynamics=g.FFF}break;case"GraceNotes":switch(i.innerText){case"OnBeat":t.graceType=m.OnBeat;break;case"BeforeBeat":t.graceType=m.BeforeBeat}break;case"Legato":"true"===i.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":let e=new te(0,0);e.value=this.toBendValue(parseFloat(i.getAttribute("originValue"))),e.offset=this.toBendOffset(parseFloat(i.getAttribute("originOffset"))),t.addWhammyBarPoint(e);let a=new te(0,0);a.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),a.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);let r=new te(0,0);r.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),r.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);let o=new te(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;break;case"Slashed":t.slashed=!0;break;case"DeadSlapped":t.deadSlapped=!0;break;case"Golpe":switch(i.innerText){case"Finger":t.golpe=A.Finger;break;case"Thumb":t.golpe=A.Thumb}break;case"Wah":switch(i.innerText){case"Open":t.wahPedal=R.Open;break;case"Closed":t.wahPedal=R.Closed}break;case"UserTransposedPitchStemOrientation":switch(i.innerText){case"Downward":t.preferredBeamDirection=Ge.Down;break;case"Upward":t.preferredBeamDirection=Ge.Up}break;case"Timer":t.showTimer=!0,i.innerText.length>0&&(t.timer=parseInt(i.innerText))}this._beatById.set(s,t)}parseBeatLyrics(e){const t=[];for(let s of e.childNodes)if(s.nodeType===as.Element&&"Line"===s.localName)t.push(s.innerText);return t}parseBeatXProperties(e,t){for(let s of e.childNodes)if(s.nodeType===as.Element&&"XProperty"===s.localName){let e=0;switch(s.getAttribute("id")){case"1124204546":switch(e=parseInt(s.findChildElement("Int").innerText),e){case 1:t.beamingMode=G.ForceMergeWithNext;break;case 2:t.beamingMode=G.ForceSplitToNext}break;case"1124204552":if(e=parseInt(s.findChildElement("Int").innerText),1===e)t.beamingMode!==G.ForceSplitToNext&&(t.beamingMode=G.ForceSplitOnSecondaryToNext);break;case"1124204545":e=parseInt(s.findChildElement("Int").innerText),t.invertBeamDirection=1===e;break;case"687935489":e=parseInt(s.findChildElement("Int").innerText),t.brushDuration=e}}}parseBarXProperties(e,t){for(let s of e.childNodes)if(s.nodeType===as.Element&&"XProperty"===s.localName){if("1124139520"===s.getAttribute("id")){const e=s.findChildElement("Double")??s.findChildElement("Float");t.displayScale=parseFloat(e.innerText)}}}parseMasterBarXProperties(e,t){for(let s of t.childNodes)if(s.nodeType===as.Element&&"XProperty"===s.localName){if("1124073984"===s.getAttribute("id"))e.displayScale=parseFloat(s.findChildElement("Double").innerText)}}parseBeatProperties(e,t){let s=!1,i=null,a=null,r=null,n=null,o=null;for(let h of e.childNodes)if(h.nodeType===as.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=E.Up:t.pickStroke=E.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=w.Wide;break;case"Slight":t.vibrato=w.Slight}break;case"WhammyBar":s=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":i||(i=new te(0,0)),i.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":i||(i=new te(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 te(te.MaxPosition,0)),o.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new te(0,0)),o.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"BarreFret":t.barreFret=parseInt(h.findChildElement("Fret").innerText);break;case"BarreString":switch(h.findChildElement("String").innerText){case"0":t.barreShape=V.Full;break;case"1":t.barreShape=V.Half}break;case"Rasgueado":switch(h.findChildElement("Rasgueado").innerText){case"ii_1":t.rasgueado=H.Ii;break;case"mi_1":t.rasgueado=H.Mi;break;case"mii_1":t.rasgueado=H.MiiTriplet;break;case"mii_2":t.rasgueado=H.MiiAnapaest;break;case"pmp_1":t.rasgueado=H.PmpTriplet;break;case"pmp_2":t.rasgueado=H.PmpAnapaest;break;case"pei_1":t.rasgueado=H.PeiTriplet;break;case"pei_2":t.rasgueado=H.PeiAnapaest;break;case"pai_1":t.rasgueado=H.PaiTriplet;break;case"pai_2":t.rasgueado=H.PaiAnapaest;break;case"ami_1":t.rasgueado=H.AmiTriplet;break;case"ami_2":t.rasgueado=H.AmiAnapaest;break;case"ppp_1":t.rasgueado=H.Ppp;break;case"amii_1":t.rasgueado=H.Amii;break;case"amip_1":t.rasgueado=H.Amip;break;case"eami_1":t.rasgueado=H.Eami;break;case"eamii_1":t.rasgueado=H.Eamii;break;case"peami_1":t.rasgueado=H.Peami}}}s&&(i||(i=new te(0,0)),o||(o=new te(te.MaxPosition,0)),t.addWhammyBarPoint(i),r&&a&&t.addWhammyBarPoint(new te(r,a)),n&&a&&t.addWhammyBarPoint(new te(n,a)),r||n||!a||t.addWhammyBarPoint(new te(te.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(let t of e.childNodes)if(t.nodeType===as.Element&&"Note"===t.localName)this.parseNote(t)}parseNote(e){let t=new ge,s=e.getAttribute("id");for(let a of e.childNodes)if(a.nodeType===as.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=p.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),16&e&&(t.accentuated=i.Tenuto);break;case"Tie":"true"===a.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(a.innerText){case"Slight":t.vibrato=w.Slight;break;case"Wide":t.vibrato=w.Wide}break;case"LeftFingering":switch(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(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);break;case"Ornament":switch(a.innerText){case"Turn":t.ornament=M.Turn;break;case"InvertedTurn":t.ornament=M.InvertedTurn;break;case"UpperMordent":t.ornament=M.UpperMordent;break;case"LowerMordent":t.ornament=M.LowerMordent}}this._noteById.set(s,t)}parseNoteProperties(e,t,s){let i=!1,a=null,r=null,n=null,o=null,h=null,l=-1,d=-1;for(let c of e.childNodes)if(c.nodeType===as.Element&&"Property"===c.localName){switch(c.getAttribute("name")){case"ShowStringNumber":c.findChildElement("Enable")&&(t.showStringNumber=!0);break;case"String":t.string=parseInt(c.findChildElement("String").innerText)+1;break;case"Fret":t.fret=parseInt(c.findChildElement("Fret").innerText);break;case"Element":l=parseInt(c.findChildElement("Element").innerText);break;case"Variation":d=parseInt(c.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(s,!0);break;case"HarmonicType":let e=c.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=y.None;break;case"Natural":t.harmonicType=y.Natural;break;case"Artificial":t.harmonicType=y.Artificial;break;case"Pinch":t.harmonicType=y.Pinch;break;case"Tap":t.harmonicType=y.Tap;break;case"Semi":t.harmonicType=y.Semi;break;case"Feedback":t.harmonicType=y.Feedback}break;case"HarmonicFret":let u=c.findChildElement("HFret");u&&(t.harmonicValue=parseFloat(u.innerText));break;case"Muted":c.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":c.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=parseInt(c.findChildElement("Number").innerText),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=parseInt(c.findChildElement("Step").innerText);break;case"ConcertPitch":this.parseConcertPitch(c,t);break;case"Bended":i=!0;break;case"BendOriginValue":a||(a=new te(0,0)),a.value=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new te(0,0)),a.offset=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleValue":r=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleOffset1":n=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleOffset2":o=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendDestinationValue":h||(h=new te(te.MaxPosition,0)),h.value=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new te(0,0)),h.offset=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"HopoOrigin":c.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":let p=parseInt(c.findChildElement("Flags").innerText);1&p?t.slideOutType=_.Shift:2&p?t.slideOutType=_.Legato:4&p?t.slideOutType=_.OutDown:8&p&&(t.slideOutType=_.OutUp),16&p?t.slideInType=S.IntoFromBelow:32&p&&(t.slideInType=S.IntoFromAbove),64&p?t.slideOutType=_.PickSlideDown:128&p&&(t.slideOutType=_.PickSlideUp)}}i&&(a||(a=new te(0,0)),h||(h=new te(te.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new te(n,r)),o&&r&&t.addBendPoint(new te(o,r)),n||o||!r||t.addBendPoint(new te(te.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==d&&(t.percussionArticulation=ue.articulationFromElementVariation(l,d))}parseConcertPitch(e,t){const s=e.findChildElement("Pitch");if(s)for(let e of s.childNodes)if(e.nodeType===as.Element&&"Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=b.ForceDoubleSharp;break;case"#":t.accidentalMode=b.ForceSharp;break;case"b":t.accidentalMode=b.ForceFlat;break;case"bb":t.accidentalMode=b.ForceDoubleFlat}}toBendValue(e){return e*Ss.BendPointValueFactor|0}toBendOffset(e){return e*Ss.BendPointPositionFactor}parseRhythms(e){for(let t of e.childNodes)if(t.nodeType===as.Element&&"Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){let t=new ys,s=e.getAttribute("id");t.id=s;for(let s of e.childNodes)if(s.nodeType===as.Element)switch(s.localName){case"NoteValue":switch(s.innerText){case"Long":t.value=p.QuadrupleWhole;break;case"DoubleWhole":t.value=p.DoubleWhole;break;case"Whole":t.value=p.Whole;break;case"Half":t.value=p.Half;break;case"Quarter":t.value=p.Quarter;break;case"Eighth":t.value=p.Eighth;break;case"16th":t.value=p.Sixteenth;break;case"32nd":t.value=p.ThirtySecond;break;case"64th":t.value=p.SixtyFourth;break;case"128th":t.value=p.OneHundredTwentyEighth;break;case"256th":t.value=p.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!==Ss.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!==Ss.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!==Ss.InvalidId){let t=Se.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!==Ss.InvalidId){const e=ye.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 Me;e.addVoice(t);let s=new we;s.isEmpty=!0,s.duration=p.Quarter,t.addBeat(s)}t===s.staves.length-1?(i++,t=0):t++}else i++}}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e),s=!1;for(const e of t.staves)if(e.isPercussion){s=!0;break}if(s||(t.percussionArticulations=[]),this._automationsPerTrackIdAndBarIndex.has(e)){const s=this._automationsPerTrackIdAndBarIndex.get(e);for(const[e,i]of s)if(t.staves.length>0&&e<t.staves[0].bars.length){const s=t.staves[0].bars[e];if(s.voices.length>0&&s.voices[0].beats.length>0){const e=s.voices[0].beats[0];for(const t of i)e.automations.push(t)}}}if(this._sustainPedalsPerTrackIdAndBarIndex.has(e)){const s=this._sustainPedalsPerTrackIdAndBarIndex.get(e);for(const[e,i]of s)if(t.staves.length>0&&e<t.staves[0].bars.length){t.staves[0].bars[e].sustainPedals=i}}}for(const[e,t]of this._masterTrackAutomations){let s=this.score.masterBars[e];for(let i=0,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.tempoAutomations.push(r))}}}}Ss.InvalidId="-1",Ss.BendPointPositionFactor=te.MaxPosition/100,Ss.BendPointValueFactor=.04;class _s{constructor(){this.isMultiRest=!1,this.trackViewGroups=[]}}class ws{constructor(){this.showNumbered=!1,this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class Bs{apply(e){if(this.scoreViews.length>0){let t=0;for(let s of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){const i=e.tracks[t];for(const e of i.staves)e.showTablature=s.showTablature,e.showStandardNotation=s.showStandardNotation,e.showSlash=s.showSlash,e.showNumbered=s.showNumbered}t++}}}constructor(e){this.scoreViews=[];let t=Oe.fromBuffer(e);const s=Ae.readInt32BE(t);for(let e=0;e<s;e++){const e=new _s;this.scoreViews.push(e),e.isMultiRest=hs.gpReadBool(t);const s=Ae.readInt32BE(t);for(let i=0;i<s;i++){let s=t.readByte();0===s&&(s=1);let i=new ws;i.showStandardNotation=!!(1&s),i.showTablature=!!(2&s),i.showSlash=!!(4&s),i.showNumbered=!!(8&s),e.trackViewGroups.push(i)}}}static writeForScore(e){const t=Oe.withCapacity(128),s=[new _s];for(const t of e.tracks){const e=new ws;e.showStandardNotation=t.staves[0].showStandardNotation,e.showTablature=t.staves[0].showTablature,e.showSlash=t.staves[0].showSlash,e.showNumbered=t.staves[0].showNumbered,s[0].trackViewGroups.push(e);const i=new _s;i.trackViewGroups.push(e),s.push(i)}Ae.writeInt32BE(t,s.length);for(const e of s){t.writeByte(e.isMultiRest?1:0),Ae.writeInt32BE(t,e.trackViewGroups.length);for(const s of e.trackViewGroups){let e=0;s.showStandardNotation&&(e|=1),s.showTablature&&(e|=2),s.showSlash&&(e|=4),s.showNumbered&&(e|=8),t.writeByte(e)}}return Ae.writeInt32BE(t,1),t.toArray()}}let ks=class{};class Ts extends ks{constructor(e){super(),this.n=e}}class xs extends ks{constructor(e,t){super(),this.left=e,this.right=t}}class Ns extends ks{constructor(e,t){super(),this.n=e,this.table=t}}class vs{static make(e,t,s,i){let a=[],r=[];if(i>32)throw new Pe("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 Pe("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 vs.treeCompress(new xs(vs.treeMake(o,i,0,1),vs.treeMake(o,i,1,1)))}static treeMake(e,t,s,i){if(i>t)throw new Pe("Invalid huffman");let a=s<<5|i;return e.has(a)?new Ts(e.get(a)):(s<<=1,i+=1,new xs(vs.treeMake(e,t,s,i),vs.treeMake(e,t,1|s,i)))}static treeCompress(e){let t=vs.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof xs)return new xs(vs.treeCompress(e.left),vs.treeCompress(e.right));throw new Pe("assert")}let s=1<<t,i=[];for(let e=0;e<s;e++)i.push(new Ts(-1));return vs.treeWalk(i,0,0,t,e),new Ns(t,i)}static treeWalk(e,t,s,i,a){a instanceof xs&&i>0?(vs.treeWalk(e,t,s+1,i-1,a.left),vs.treeWalk(e,t|1<<s,s+1,i-1,a.right)):e[t]=vs.treeCompress(a)}static treeDepth(e){if(e instanceof Ts)return 0;if(e instanceof Ns)throw new Pe("assert");if(e instanceof xs){let t=vs.treeDepth(e.left),s=vs.treeDepth(e.right);return 1+(t<s?t:s)}return 0}}var Ps,Cs,Es,Fs,Ds,Ls,Ms,Is,As,Os,Rs,Vs,Hs,Gs,Ws,zs,Us,Xs;!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"}(Ps||(Ps={}));class Js{constructor(){this.buffer=new Uint8Array(Js.BufferSize),this.pos=0}slide(){let e=new Uint8Array(Js.BufferSize);this.pos-=Js.Size,e.set(this.buffer.subarray(Js.Size,Js.Size+this.pos),0),this.buffer=e}addBytes(e,t,s){this.pos+s>Js.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+s),this.pos),this.pos+=s}addByte(e){this.pos===Js.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}Js.Size=32768,Js.BufferSize=65536;class Ys{static buildFixedHuffman(){let e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return vs.make(e,0,288,10)}constructor(e){this._nbits=0,this._bits=0,this._state=Ps.Block,this._isFinal=!1,this._huffman=Ys._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new Js,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 Ps.Head:let e=this._input.readByte();if(8!==(15&e))throw new Pe("Invalid data");let t=this._input.readByte(),s=!!(32&t);if(((e<<8)+t)%31!=0)throw new Pe("Invalid data");if(s)throw new Pe("Unsupported dictionary");return this._state=Ps.Block,!0;case Ps.Crc:return this._state=Ps.Done,!0;case Ps.Done:return!1;case Ps.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:if(this._len=Ae.readUInt16LE(this._input),Ae.readUInt16LE(this._input)!==65535-this._len)throw new Pe("Invalid data");this._state=Ps.Flat;let e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=Ys._fixedHuffman,this._huffdist=null,this._state=Ps.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[Ys.CodeLengthsPos[e]]=this.getBits(3);for(let e=i;e<19;e++)this._lengths[Ys.CodeLengthsPos[e]]=0;this._huffman=vs.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=vs.make(a,t,s,16),this._huffman=vs.make(a,0,t,16),this._state=Ps.CData,!0;default:throw new Pe("Invalid data")}case Ps.Flat:{let e=this._len<this._needed?this._len:this._needed,t=Ae.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?Ps.Crc:Ps.Block),this._needed>0}case Ps.DistOne:{let e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=Ps.CData),this._needed>0}case Ps.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=Ps.CData),this._needed>0;case Ps.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?Ps.Crc:Ps.Block,!0;{i=i-257&255;let e=Ys.LenExtraBitsTbl[i];if(-1===e)throw new Pe("Invalid data");this._len=Ys.LenBaseValTbl[i]+this.getBits(e);let t=this._huffdist,s=t?this.applyHuffman(t):this.getRevBits(5);if(e=Ys.DistExtraBitsTbl[s],-1===e)throw new Pe("Invalid data");if(this._dist=Ys.DistBaseValTbl[s]+this.getBits(e),this._dist>this._window.available())throw new Pe("Invalid data");return this._state=1===this._dist?Ps.DistOne:Ps.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 Pe("Invalid data");for(;s<r;)e[s]=i,s++;break;case 17:if(s+=3+this.getBits(3),s>t)throw new Pe("Invalid data");break;case 18:if(s+=11+this.getBits(7),s>t)throw new Pe("Invalid data");break;default:throw new Pe("Invalid data")}}}applyHuffman(e){if(e instanceof Ts)return e.n;if(e instanceof xs)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof Ns)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new Pe("Invalid data")}}Ys.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],Ys.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],Ys.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],Ys.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],Ys.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Ys._fixedHuffman=Ys.buildFixedHuffman();class qs{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}}qs.OptionalDataDescriptorSignature=134695760,qs.CompressionMethodDeflate=8,qs.LocalFileHeaderSignature=67324752,qs.CentralFileHeaderSignature=33639248,qs.EndOfCentralDirSignature=101010256;class js{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(Ae.readInt32LE(e)!==qs.LocalFileHeaderSignature)return null;Ae.readUInt16LE(e);let t=Ae.readUInt16LE(e),s=Ae.readUInt16LE(e),i=0!==s;if(i&&s!==qs.CompressionMethodDeflate)return null;Ae.readInt16LE(this._readable),Ae.readInt16LE(this._readable),Ae.readInt32LE(e),Ae.readInt32LE(e);let a,r=Ae.readInt32LE(e),n=Ae.readInt16LE(e),o=Ae.readInt16LE(e),h=Ae.toString(Ae.readByteArray(e,n),"utf-8");if(e.skip(o),i){let e=Oe.empty(),t=new Ys(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=Ae.readByteArray(this._readable,r);if(8&t){Ae.readInt32LE(this._readable)===qs.OptionalDataDescriptorSignature&&Ae.readInt32LE(this._readable),Ae.readInt32LE(this._readable),Ae.readInt32LE(this._readable)}return new qs(h,a)}}class Ks{constructor(){this.trackViewGroups=[]}}class Qs{constructor(){this.isVisible=!1}}!function(e){e[e.PageVertical=0]="PageVertical",e[e.PageGrid=1]="PageGrid",e[e.PageParchment=2]="PageParchment",e[e.ScreenVertical=3]="ScreenVertical",e[e.ScreenHorizontal=4]="ScreenHorizontal",e[e.PageHorizontal=5]="PageHorizontal"}(Cs||(Cs={}));class $s{constructor(e,t){this.zoomLevel=4,this.view=Cs.PageVertical,this.muiltiVoiceCursor=!1,this.scoreViews=[];const s=Oe.fromBuffer(t);this.zoomLevel=Ae.readInt32BE(s),this.view=s.readByte(),this.muiltiVoiceCursor=0!=s.readByte();const i=e.scoreViews.length;for(let t=0;t<i;t++){const i=new Ks;this.scoreViews.push(i);const a=e.scoreViews[t];for(let e=0;e<a.trackViewGroups.length;e++){const e=new Qs;e.isVisible=0!=s.readByte(),i.trackViewGroups.push(e)}}}apply(e){if(this.scoreViews.length>0){let t=0;for(let s of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){e.tracks[t].isVisibleOnMultiTrack=s.isVisible}t++}}}static writeForScore(e){const t=Oe.withCapacity(128);Ae.writeInt32BE(t,4),t.writeByte(0);const s=e.tracks.length>0&&e.tracks[0].staves[0].bars[0].isMultiVoice;t.writeByte(s?255:0);for(const s of e.tracks)t.writeByte(s.isVisibleOnMultiTrack?255:0);for(const s of e.tracks)t.writeByte(255);return t.toArray()}}class Zs extends q{get name(){return"Guitar Pro 7-8"}constructor(){super()}readScore(){re.debug(this.name,"Loading ZIP entries");let e,t=new js(this.data);try{e=t.read()}catch(e){throw new K("No Zip archive",e)}re.debug(this.name,"Zip entries loaded");let s=null,i=null,a=null,r=null;for(let t of e)switch(t.fileName){case"score.gpif":s=Ae.toString(t.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=t.data;break;case"PartConfiguration":a=t.data;break;case"LayoutConfiguration":r=t.data}if(!s)throw new K("No score.gpif found in zip archive");re.debug(this.name,"Start Parsing score.gpif");let n=new Ss;n.parseXml(s,this.settings),re.debug(this.name,"score.gpif parsed");let o=n.score;if(i){re.debug(this.name,"Start Parsing BinaryStylesheet"),new cs(i).apply(o),re.debug(this.name,"BinaryStylesheet parsed")}let h=null;if(a&&(re.debug(this.name,"Start Parsing Part Configuration"),h=new Bs(a),h.apply(o),re.debug(this.name,"Part Configuration parsed")),r&&null!=h){re.debug(this.name,"Start Parsing Layout Configuration"),new $s(h,r).apply(o),re.debug(this.name,"Layout Configuration parsed")}return o}}class ei extends j{constructor(){super(s.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,ei.prototype)}}class ti{constructor(e){this._currentByte=0,this._position=ti.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 ei;this._position=0}const e=this._currentByte>>ti.ByteSize-this._position-1&1;return this._position++,e}readAll(){let e=Oe.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof ei))throw e}return e.toArray()}}ti.ByteSize=8;class si{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class ii{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){let t=new ti(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){let s,i=Oe.empty(),a=this.getInteger(e.readBytes(4),0);try{for(;i.length<a;){if(1===e.readBits(1)){let t=e.readBits(4),a=e.readBitsReversed(t),r=e.readBitsReversed(t),n=i.length-a,o=Math.min(a,r);s=i.getBuffer(),i.write(s,n,o)}else{let t=e.readBitsReversed(2);for(let s=0;s<t;s++)i.writeByte(e.readByte())}}}catch(e){if(!(e instanceof ei))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 K("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 si;i.fileName=this.getString(e,s+4,127),i.fileSize=this.getInteger(e,s+140);let a=!this.fileFilter||this.fileFilter(i.fileName);a&&this.files.push(i);let r=s+148,n=0,o=0,h=a?Oe.withCapacity(i.fileSize):null;for(;n=this.getInteger(e,r+4*o++),0!==n;)s=n*t,a&&h.write(e,s,t);if(a){i.data=new Uint8Array(Math.min(i.fileSize,h.length));let e=h.toArray();i.data.set(e.subarray(0,0+i.data.length),0)}}s+=t}}getString(e,t,s){let i="";for(let a=0;a<s;a++){let s=255&e[t+a];if(0===s)break;i+=String.fromCharCode(s)}return i}getInteger(e,t){return e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}}ii.HeaderBcFs="BCFS",ii.HeaderBcFz="BCFZ";class ai extends q{get name(){return"Guitar Pro 6"}constructor(){super()}readScore(){re.debug(this.name,"Loading GPX filesystem");let e=new ii;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration")||e.endsWith("LayoutConfiguration"),e.load(this.data),re.debug(this.name,"GPX filesystem loaded");let t=null,s=null,i=null,a=null;for(let r of e.files)switch(r.fileName){case"score.gpif":t=Ae.toString(r.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=r.data;break;case"PartConfiguration":i=r.data;break;case"LayoutConfiguration":a=r.data}if(!t)throw new K("No score.gpif found in GPX");re.debug(this.name,"Start Parsing score.gpif");let r=new Ss;r.parseXml(t,this.settings),re.debug(this.name,"score.gpif parsed");let n=r.score;if(s){re.debug(this.name,"Start Parsing BinaryStylesheet"),new cs(s).apply(n),re.debug(this.name,"BinaryStylesheet parsed")}let o=null;if(i&&(re.debug(this.name,"Start Parsing Part Configuration"),o=new Bs(i),o.apply(n),re.debug(this.name,"Part Configuration parsed")),a&&null!=o){re.debug(this.name,"Start Parsing Layout Configuration"),new $s(o,a).apply(n),re.debug(this.name,"Layout Configuration parsed")}return n}}class ri extends q{get name(){return"MusicXML"}constructor(){super(),this._currentPartGroup=null,this._trackFirstMeasureNumber=0,this._maxVoices=0,this._currentDirection=null,this._currentChord=null,this._divisionsPerQuarterNote=0,this._voiceOfStaff=new Map,this._isBeamContinue=!1,this._previousBeatWasPulled=!1,this._previousBeat=null}readScore(){this._trackById=new Map,this._partGroups=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._slurStarts=new Map;let e=this.extractMusicXml(),t=new fs;try{t.parse(e)}catch(e){throw new K("Unsupported format")}return this._score=new Ne,this._score.tempo=120,this.parseDom(t),this.settings.importer.mergePartGroupsInMusicXml&&this.mergePartGroups(),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}extractMusicXml(){const e=new js(this.data);let t;try{t=e.read()}catch(e){t=[]}if(0===t.length)return this.data.reset(),Ae.toString(this.data.readAll(),this.settings.importer.encoding);const s=t.find((e=>"META-INF/container.xml"===e.fullName));if(!s)throw new K("No compressed MusicXML");const i=new fs;try{i.parse(Ae.toString(s.data,this.settings.importer.encoding))}catch(e){throw new K("Malformed container.xml, could not parse as XML",e)}let a=i.firstElement;if(!a||"container"!==a.localName)throw new K("Malformed container.xml, root element not 'container'");const r=a.findChildElement("rootfiles");if(!r)throw new K("Malformed container.xml, 'container/rootfiles' not found");let n="";for(const e of r.childNodes)if(e.nodeType==as.Element&&"rootfile"===e.localName){n=e.getAttribute("full-path");break}if(!n)throw new K("Unsupported compressed MusicXML, missing rootfile");const o=t.find((e=>e.fullName===n));if(!o)throw new K(`Malformed container.xml, '${n}' not contained in zip`);return Ae.toString(o.data,this.settings.importer.encoding)}mergePartGroups(){let e=!1;for(const t of this._partGroups.values())t.length>1&&(this.mergeGroup(t),e=!0);if(e)for(let e=0;e<this._score.tracks.length;e++)this._score.tracks[e].index=e}mergeGroup(e){let t=e[0];for(let s=1;s<e.length;s++){let i=e[s];for(let e of i.staves)t.addStaff(e);let a=this._score.tracks.indexOf(i);this._score.tracks.splice(a,1)}}parseDom(e){let t=e.firstElement;if(!t)throw new K("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":break;default:throw new K("Unsupported format")}}parsePartwise(e){for(let t of e.childNodes)if(t.nodeType===as.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===as.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===as.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 Z;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===as.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 Me;e.addVoice(t);let s=new we;s.isEmpty=!0,s.chordId=this._currentChord,t.addBeat(s)}}getOrCreateBeat(e,t,s){let i=0,a=e.getElementsByTagName("voice",!1);a.length>0&&(i=parseInt(a[0].innerText)-1);let r=this._previousBeatWasPulled;this._previousBeatWasPulled=!1;let n,o,h=e.getElementsByTagName("staff",!1),l=1;if(h.length>0){l=parseInt(h[0].innerText),(this._isBeamContinue||r)&&this._previousBeat.voice.bar.staff.index!==l-1&&(l=this._previousBeat.voice.bar.staff.index+1,this._previousBeatWasPulled=!0);let e=t[0].staff.track.index+"-"+l;this._voiceOfStaff.has(e)||this._voiceOfStaff.set(e,i)}l--,n=l<0?t[0]:l>=t.length?t[t.length-1]:t[l];let d=this.getOrCreateVoice(n,i);return s&&d.beats.length>0||1===d.beats.length&&d.isEmpty?o=d.beats[d.beats.length-1]:(o=new we,o.isEmpty=!1,d.addBeat(o)),this._isBeamContinue=!1,this._previousBeat=o,o}parseForward(e,t){let s=this.getOrCreateBeat(e,t,!1),i=parseInt(e.findChildElement("duration").innerText)*p.Quarter/this._divisionsPerQuarterNote,a=[p.SixtyFourth,p.ThirtySecond,p.Sixteenth,p.Eighth,p.Quarter,p.Half,p.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===as.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===as.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=le.getTuningForText(i+a)+r;for(let e of t.staves)e.tuning[e.tuning.length-s]=n}parseHarmony(e,t,s){let i=new Be;for(let t of e.childNodes)if(t.nodeType===as.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=le.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===as.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===as.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===as.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 ge;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===as.Element)switch(t.localName){case"grace":i.graceType=m.BeforeBeat,i.duration=p.ThirtySecond;break;case"duration":if(i.isRest&&!r){switch(parseInt(t.innerText)){case 1:i.duration=p.Whole;break;case 2:i.duration=p.Half;break;case 4:default:i.duration=p.Quarter;break;case 8:i.duration=p.Eighth;break;case 16:i.duration=p.Sixteenth;break;case 32:i.duration=p.ThirtySecond;break;case 64:i.duration=p.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!==m.None&&i.duration<p.Sixteenth&&(i.duration=p.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=p.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 p.SixtyFourth;case"32nd":return p.ThirtySecond;case"16th":return p.Sixteenth;case"eighth":return p.Eighth;case"quarter":return p.Quarter;case"half":return p.Half;case"long":case"breve":case"whole":return p.Whole}return p.Quarter}parseLyric(e,t){for(let s of e.childNodes)if(s.nodeType===as.Element&&"text"===s.localName)t.text?t.text+=" "+s.innerText:t.text=s.innerText}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=b.ForceSharp;break;case"natural":t.accidentalMode=b.ForceNatural;break;case"flat":t.accidentalMode=b.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===as.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=_.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===as.Element&&"tremolo"===s.localName){switch(parseInt(s.innerText)){case 1:t.beat.tremoloSpeed=p.Eighth;break;case 2:t.beat.tremoloSpeed=p.Sixteenth;break;case 3:t.beat.tremoloSpeed=p.ThirtySecond}}}parseTechnical(e,t){let s=[];for(let i of e.childNodes)if(i.nodeType===as.Element)switch(i.localName){case"string":t.string=parseInt(i.innerText),-2147483648!==t.string&&(t.string=t.beat.voice.bar.staff.tuning.length-t.string+1);break;case"fret":t.fret=parseInt(i.innerText);break;case"down-bow":t.beat.pickStroke=E.Down;break;case"up-bow":t.beat.pickStroke=E.Up;break;case"bend":s.push(i)}s.length>0&&this.parseBends(s,t),-2147483648!==t.string&&-2147483648!==t.fret||(t.string=-1,t.fret=-1)}parseBends(e,t){let s=te.MaxPosition/e.length,i=0,a=0,r=!0;for(let n of e){let e=n.findChildElement("bend-alter");if(e){let o=Math.round(2*Math.abs(parseFloat(e.innerText)));n.findChildElement("pre-bend")?r?(i+=o,t.addBendPoint(new te(a,i)),a+=s,t.addBendPoint(new te(a,i)),r=!1):a+=s:n.findChildElement("release")?(r&&(i+=o),t.addBendPoint(new te(a,i)),a+=s,i-=o,t.addBendPoint(new te(a,i)),r=!1):(t.addBendPoint(new te(a,i)),i+=o,a+=s,t.addBendPoint(new te(a,i)),r=!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;break;case"tenuto":t.accentuated=i.Tenuto}}parseDynamics(e,t){for(let s of e.childNodes)if(s.nodeType===as.Element)switch(s.localName){case"p":t.dynamics=g.P;break;case"pp":t.dynamics=g.PP;break;case"ppp":t.dynamics=g.PPP;break;case"f":t.dynamics=g.F;break;case"ff":t.dynamics=g.FF;break;case"fff":t.dynamics=g.FFF;break;case"mp":t.dynamics=g.MP;break;case"mf":t.dynamics=g.MF}}parseTimeModification(e,t){for(let s of e.childNodes)if(s.nodeType===as.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===as.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+le.getToneForText(s).noteValue+i;t.octave=r/12|0,t.tone=r-12*t.octave}parsePitch(e,t){let s="",i=0,a=0;for(let t of e.childNodes)if(t.nodeType===as.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+le.getToneForText(s).noteValue+(0|i);t.octave=r/12|0,t.tone=r-12*t.octave}getOrCreateVoice(e,t){if(t<e.voices.length)return e.voices[t];for(let s=e.voices.length;s<=t;s++)e.addVoice(new Me);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===as.Element)switch(s.localName){case"sound":let e=s.getAttribute("tempo");if(e){let s=new Q;s.isLinear=!0,s.type=a.Tempo,s.value=parseInt(e),t.tempoAutomations.push(s),0===t.index&&(t.score.tempo=s.value)}break;case"direction-type":let i=s.firstElement;switch(i.localName){case"words":this._currentDirection=i.innerText;break;case"metronome":this.parseMetronome(i,t)}}}parseMetronome(e,t){let s=p.Quarter,i=120;for(let t of e.childNodes)if(t.nodeType===as.Element)switch(t.localName){case"beat-unit":s=this.getDuration(t.innerText);break;case"per-minute":i=parseInt(t.innerText)}let r=new Q;r.type=a.Tempo,r.value=i*(s/4)|0,this.hasSameTempo(t,r)||(t.tempoAutomations.push(r),0===t.index&&(t.score.tempo=r.value))}hasSameTempo(e,t){for(const s of e.tempoAutomations)if(t.ratioPosition===s.ratioPosition&&t.value==s.value)return!0;return!1}parseAttributes(e,t,s,i){let a=0,r=!1;for(let n of e.childNodes)if(n.nodeType===as.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===as.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===as.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===as.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===as.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:v.C,t.keySignatureType="minor"===i?P.Minor:P.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 ne;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===as.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===as.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 Le;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===as.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===as.Element)switch(s.localName){case"midi-channel":t.playbackInfo.primaryChannel=parseInt(s.innerText);break;case"midi-program":t.playbackInfo.program=parseInt(s.innerText);break;case"volume":t.playbackInfo.volume=Math.floor(parseInt(s.innerText)/100*16);break;case"pan":t.playbackInfo.balance=Math.max(0,Math.min(16,Math.floor((parseInt(s.innerText)+90)/180*16)))}}}class ni{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event.type==je.AlphaTabMetronome}static newMetronomeEvent(e,t,s,i,a){const r=new ct(0,t,s,i,a);return new ni(e,r)}}class oi{constructor(e,t,s){this.bpm=e,this.ticks=t,this.time=s}}class hi{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=ee.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class li{get isPlayingMain(){return this._currentState==this._mainState}get isPlayingOneTimeMidi(){return this._currentState==this._oneTimeState}get isPlayingCountIn(){return this._currentState==this._countInState}constructor(e){this._oneTimeState=null,this._countInState=null,this.isLooping=!1,this.playbackSpeed=1,this.instrumentPrograms=new Set,this.percussionKeys=new Set,this._synthesizer=e,this._mainState=new hi,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(Re.MicroBufferSize);this._mainState.currentTime=s;let i=Date.now()-t;re.debug("Sequencer","Silent seek finished in "+i+"ms (main)")}loadOneTimeMidi(e){this._oneTimeState=this.createStateFromFile(e),this._currentState=this._oneTimeState}loadMidi(e){this.instrumentPrograms.clear(),this.percussionKeys.clear(),this._mainState=this.createStateFromFile(e),this._currentState=this._mainState}createStateFromFile(e){const t=new hi;this.percussionKeys.add(Re.MetronomeKey),t.tempoChanges=[],t.division=e.division,t.eventIndex=0,t.currentTime=0,t.synthData=[];let s=120,i=0,a=0,r=0,n=0,o=0,h=0,l=0,d=0;for(let c of e.events){let u=new ni(t.synthData.length,c);t.synthData.push(u);let p=c.tick-d;if(i+=p,a+=p*(6e4/(s*e.division)),u.time=a,d=c.tick,n>0)for(;h<i;){let e=ni.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(c.type===je.TempoChange){s=6e7/c.microSecondsPerQuarterNote,t.tempoChanges.push(new oi(s,i,a)),o=n*(6e4/(s*e.division))}else if(c.type===je.TimeSignature){let i=c,a=Math.pow(2,i.denominatorIndex);r=i.numerator,n=t.division*(4/a)|0,o=n*(6e4/(s*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=i.numerator,t.firstTimeSignatureDenominator=a)}else if(c.type===je.ProgramChange){const e=c;let s=e.channel;t.firstProgramEventPerChannel.has(s)||t.firstProgramEventPerChannel.set(s,u);s===Re.PercussionChannel||this.instrumentPrograms.add(e.program)}else if(c.type==je.NoteOn){const e=c;e.channel===Re.PercussionChannel&&this.percussionKeys.add(e.noteKey)}}return t.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),t.endTime=a,t.endTick=i,t}fillMidiEventQueue(){return this.fillMidiEventQueueLimited(-1)}fillMidiEventQueueLimited(e){let t=Re.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 hi;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 oi(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=ni.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"}(Es||(Es={}));class di{constructor(e,t){this.state=e,this.stopped=t}}class ci{constructor(e,t,s,i,a){this.currentTime=e,this.endTime=t,this.currentTick=s,this.endTick=i,this.isSeek=a}}class ui{constructor(){this.id="",this.size=0}static load(e,t,s){if(e&&ui.HeaderSize>e.size)return!1;if(s.position+ui.HeaderSize>=s.length)return!1;if(t.id=Ae.read8BitStringLength(s,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=Ae.readUInt32LE(s),e&&ui.HeaderSize+t.size>e.size)return!1;e&&(e.size-=ui.HeaderSize+t.size);let i="RIFF"===t.id,a="LIST"===t.id;return(!i||!e)&&(!i&&!a||(t.id=Ae.read8BitStringLength(s,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}ui.HeaderSize=8;class pi{constructor(e,t,s,i){this.packetData=e,this.isBeginningOfStream=t,this.isEndOfStream=s,this.granulePosition=s?i:null}addData(e){const t=this.packetData,s=new Uint8Array(t.length+e.length);s.set(t,0),s.set(e,t.length)}}!function(e){e[e.ContinuesPacket=1]="ContinuesPacket",e[e.BeginningOfStream=2]="BeginningOfStream",e[e.EndOfStream=4]="EndOfStream"}(Fs||(Fs={}));class gi{constructor(e){this._readable=e}read(){const e=[];for(;this.findAndReadPage(e););return e}findAndReadPage(e){return!!this.seekPageHeader()&&this.readPage(e)}seekPageHeader(){for(let e=0;e<65536;e++){if(1399285583==Ae.readInt32LE(this._readable))return!0;this._readable.position-=3}return!1}readPage(e){const t=this._readable.readByte();if(-1===t||0!==t)return!1;const i=this._readable.readByte(),a=Ae.readInt64LE(this._readable);this._readable.skip(4),this._readable.skip(4),this._readable.skip(4);const r=this._readable.readByte();if(-1==r)return!1;const n=[];let o=0;for(let e=0;e<r;e++){const e=this._readable.readByte();o==n.length&&n.push(0),n[o]+=e,e<255&&o++}for(let t=0;t<n.length;t++){const r=new Uint8Array(n[t]);if(this._readable.read(r,0,r.length)!=r.length)return!1;if(i&Fs.ContinuesPacket){if(0==e.length)throw new j(s.Format,"OGG: Continuation page without any previous packets");e[e.length-1].addData(r)}else{const s=new pi(r,!!(i&Fs.BeginningOfStream)&&0==t,!!(i&Fs.EndOfStream)&&t==n.length-1,a);e.push(s)}}return!0}}class mi{constructor(){this.audioChannels=0,this.audioSampleRate=0,this.samples=new Float32Array(0),this.bitrateMaximum=0,this.bitrateNominal=0,this.bitrateMinimum=0,this.blocksize0=0,this.blocksize1=0}}class fi{constructor(){this.value=0,this.bitsRead=0}}class yi{constructor(e){this._bitBucket=0n,this._bitCount=0n,this._overflowBits=0n,this._source=e}readByte(){return this.readBits(yi.ByteSize)}readBit(){return 1==this.readBits(1)}readBytes(e){const t=new Uint8Array(e);for(let s=0;s<e;s++)t[s]=255&this.readByte();return t}readBits(e){if(0==e)return 0;const t=this.tryPeekBits(e);return this.skipBits(e),t.value}tryPeekBits(e){if(e<0||e>32)throw new j(s.General,"IO: Cannot read more than 32 bits in one go");if(0==e)return new fi;const t=new fi;for(;this._bitCount<e;){const e=BigInt(this._source.readByte());if(-1n==e)return t.bitsRead=Number(this._bitCount),t.value=Number(this._bitBucket),this._bitBucket=0n,this._bitCount=0n,t;this._bitBucket=(0xffn&e)<<this._bitCount|this._bitBucket,this._bitCount+=8n,this._bitCount>32&&(this._overflowBits=e>>40n-this._bitCount&0xffn)}let i=this._bitBucket;return e<64&&(i&=(1n<<BigInt(e))-1n),t.value=Number(i),t.bitsRead=e,t}skipBits(e){let t=BigInt(e);if(0==e);else if(this._bitCount>t){if(this._bitBucket=e>31?0n:this._bitBucket>>t,this._bitCount>32){const s=this._bitCount-32n;this._bitBucket=this._bitBucket|this._overflowBits<<this._bitCount-t-s,s>e&&(this._overflowBits=this._overflowBits>>t&0xffn)}this._bitCount-=t}else if(this._bitCount==t)this._bitBucket=0n,this._bitCount=0n;else{for(t-=this._bitCount,this._bitCount=0n,this._bitBucket=0n;t>8;){if(-1==this._source.readByte()){t=0n;break}t-=8n}if(t>0){const e=BigInt(this._source.readByte());-1n==e||(this._bitBucket=e>>t,this._bitCount=8n-t)}}}}yi.ByteSize=8;class bi{constructor(){this.codebooks=[],this.timeDomainTransforms=[],this.floors=[],this.residues=[],this.mappings=[],this.modes=[]}}class Si{static ilog(e){let t=0;for(;e>0;)++t,e>>=1;return t}static bitReverse(e,t=32){let s=BigInt(e);s=(s&BigInt(2863311530))>>1n|(s&BigInt(1431655765))<<1n,s=(s&BigInt(3435973836))>>2n|(s&BigInt(858993459))<<2n,s=(s&BigInt(4042322160))>>4n|(s&BigInt(252645135))<<4n,s=(s&BigInt(4278255360))>>8n|(s&BigInt(16711935))<<8n,s=(s>>16n|s<<16n)>>32n-BigInt(t);return Number(BigInt.asUintN(32,s))}static convertFromVorbisFloat32(e){const t=BigInt(e);let s=t&BigInt(2097151);const i=t&BigInt(2147483648),a=(t&BigInt(2145386496))>>21n;return 0n!==i&&(s=-s),Number(s)*Math.pow(2,Number(a)-788)}}class _i{constructor(e){this._data=e}get(e){return this._data[e]}}class wi{get(e){return e}}wi.instance=new wi;class Bi{constructor(e,t){this._maxBits=0,this._overflowList=null,this._prefixList=null,this._prefixBitLength=0,this.dimensions=0,this.entries=0,this.mapType=0;if(5653314!=e.readBits(24))throw new j(s.Format,"Vorbis: Book header had invalid signature!");this.dimensions=e.readBits(16),this.entries=e.readBits(24),this._lengths=new Int32Array(this.entries),this.initTree(e,t),this.initLookupTable(e)}get(e,t){return this._lookupTable[e*this.dimensions+t]}decodeScalar(e){let t=e.tryPeekBits(this._prefixBitLength);if(0==t.bitsRead)return-1;let s=this._prefixList[t.value];if(null!=s)return e.skipBits(s.length),s.value;if(t=e.tryPeekBits(this._maxBits),null!==this._overflowList)for(let i=0;i<this._overflowList.length;i++){s=this._overflowList[i];const a=t.value&s.mask;if(s.bits==a)return e.skipBits(s.length),s.value}return-1}initTree(e,t){let i,a,r=0;if(e.readBit()){let t=e.readBits(5)+1;for(let s=0;s<this.entries;){let i=e.readBits(Si.ilog(this.entries-s));for(;--i>=0;)this._lengths[s++]=t;++t}r=0,i=!1,a=t}else{a=-1,i=e.readBit();for(let t=0;t<this.entries;t++)!i||e.readBit()?(this._lengths[t]=e.readBits(5)+1,++r):this._lengths[t]=-1,this._lengths[t]>a&&(a=this._lengths[t])}if(this._maxBits=a,a>-1){let e,a=null;i&&r>=this.entries>>2&&(a=new Int32Array(this.entries),a.set(this._lengths.subarray(0,this.entries),0),i=!1),e=i?r:0;let n=null,o=null;if(i?0!=e&&(a=new Int32Array(e),o=new Int32Array(e),n=new Int32Array(e)):o=new Int32Array(this.entries),!this.computeCodewords(i,o,a,this._lengths,this.entries,n))throw new j(s.Format,"Vorbis: Failed to compute codewords");const h=null==n?wi.instance:new _i(n);t.generateTable(h,a??this._lengths,o),this._prefixList=t.prefixTree,this._prefixBitLength=t.tableBits,this._overflowList=t.overflowList}}computeCodewords(e,t,s,i,a,r){const n=new Uint32Array(32);let o=0,h=0;for(o=0;o<a&&!(i[o]>0);++o);if(o==a)return!0;this.addEntry(e,t,s,0,o,h++,i[o],r);for(let e=1;e<=i[o];++e)n[e]=1<<32-e;for(let l=o+1;l<a;++l){let a=i[l];if(a<=0)continue;for(;a>0&&0==n[a];)--a;if(0==a)return!1;let o=n[a];if(n[a]=0,this.addEntry(e,t,s,Si.bitReverse(o),l,h++,i[l],r),a!=i[l])for(let e=i[l];e>a;--e)n[e]=o+(1<<32-e)}return!0}addEntry(e,t,s,i,a,r,n,o){e?(t[r]=i,s[r]=n,o[r]=a):t[a]=i}initLookupTable(e){if(this.mapType=e.readBits(4),0==this.mapType)return;const t=Si.convertFromVorbisFloat32(e.readBits(32)),s=Si.convertFromVorbisFloat32(e.readBits(32)),i=e.readBits(4)+1,a=e.readBit();let r=this.entries*this.dimensions;const n=new Float32Array(r);1==this.mapType&&(r=this.lookup1Values());const o=new Uint32Array(r);for(let t=0;t<r;t++)o[t]=e.readBits(i);if(1==this.mapType)for(let e=0;e<this.entries;e++){let i=0,h=1;for(let l=0;l<this.dimensions;l++){const d=o[e/h%r|0]*s+t+i;n[e*this.dimensions+l]=d,a&&(i=d),h*=r}}else for(let e=0;e<this.entries;e++){let i=0,r=e*this.dimensions;for(let h=0;h<this.dimensions;h++){const l=o[r]*s+t+i;n[e*this.dimensions+h]=l,a&&(i=l),++r}}this._lookupTable=n}lookup1Values(){let e=Math.floor(Math.exp(Math.log(this.entries)/this.dimensions));return Math.floor(Math.pow(e+1,this.dimensions))<=this.entries&&++e,e}}class ki{constructor(){this.value=0,this.length=0,this.bits=0,this.mask=0}}class Ti{constructor(){this.tableBits=0,this.prefixTree=[],this.overflowList=null}generateTable(e,t,s){const i=new Array(t.length);let a=0;for(let r=0;r<i.length;r++){const n=new ki;n.value=e.get(r),n.length=t[r]<=0?99999:t[r],n.bits=s[r],n.mask=(1<<t[r])-1,i[r]=n,t[r]>0&&a<t[r]&&(a=t[r])}i.sort(((e,t)=>{const s=e.length-t.length;return 0===s?e.bits-t.bits:s}));const r=a>Ti.MAX_TABLE_BITS?Ti.MAX_TABLE_BITS:a,n=[];let o=null;for(let e=0;e<i.length&&i[e].length<99999;e++){const t=i[e].length;if(t>r)for(o=[];e<i.length&&i[e].length<99999;e++)o.push(i[e]);else{const s=1<<r-t,a=i[e];for(let e=0;e<s;e++){const s=e<<t|a.bits;for(;n.length<=s;)n.push(null);n[s]=a}}}for(;n.length<1<<r;)n.push(null);this.tableBits=r,this.prefixTree=n,this.overflowList=o}}Ti.MAX_TABLE_BITS=10;class xi{constructor(e){e.readBits(16)}}class Ni{get executeChannel(){return(this.forceEnergy||this.amp>0)&&!this.forceNoEnergy}constructor(e){this.amp=0,this.forceEnergy=!1,this.forceNoEnergy=!1,this.coeff=e}}class vi{constructor(e,t,i,a){if(this._order=e.readBits(8),this._rate=e.readBits(16),this._bark_map_size=e.readBits(16),this._ampBits=e.readBits(6),this._ampOfs=e.readBits(8),this._books=new Array(e.readBits(4)+1),this._order<1||this._rate<1||this._bark_map_size<1||0==this._books.length)throw new j(s.Format,"Vorbis: Invalid Floor0 Data");this._ampDiv=(1<<this._ampBits)-1;for(let t=0;t<this._books.length;t++){const i=e.readBits(8);if(i<0||i>=a.length)throw new j(s.Format,"Vorbis: Invalid Floor0 Data");const r=a[i];if(0==r.mapType||r.dimensions<1)throw new j(s.Format,"Vorbis: Invalid Floor0 Data");this._books[t]=r}this._bookBits=Si.ilog(this._books.length),this._barkMaps=new Map([[t,this.synthesizeBarkCurve(t/2)],[i,this.synthesizeBarkCurve(i/2)]]),this._wMap=new Map([[t,this.synthesizeWDelMap(t/2)],[i,this.synthesizeWDelMap(i/2)]])}synthesizeBarkCurve(e){const t=this._bark_map_size/vi.toBARK(this._rate/2),s=new Int32Array(e+1);for(let i=0;i<e-1;i++)s[i]=Math.min(this._bark_map_size-1,Math.floor(vi.toBARK(this._rate/2/e*i)*t));return s[e]=-1,s}static toBARK(e){return 13.1*Math.atan(74e-5*e)+2.24*Math.atan(1.85e-8*e*e)+1e-4*e}synthesizeWDelMap(e){const t=Math.PI/this._bark_map_size,s=new Float32Array(e);for(let i=0;i<e;i++)s[i]=2*Math.cos(t*i);return s}unpack(e,t,s){var i=new Ni(new Float32Array(this._order+1));if(i.amp=e.readBits(this._ampBits),i.amp>0){i.amp=i.amp/this._ampDiv*this._ampOfs;const t=e.readBits(this._bookBits);if(t>=this._books.length)return i.amp=0,i;const s=this._books[t];for(let t=0;t<this._order;){const a=s.decodeScalar(e);if(-1==a)return i.amp=0,i;for(let e=0;t<this._order&&e<s.dimensions;e++,t++)i.coeff[t]=s.get(a,e)}let a=0;for(let e=0;e<this._order;){for(let t=0;e<this._order&&t<s.dimensions;e++,t++)i.coeff[e]+=a;a=i.coeff[e-1]}}return i}apply(e,t,s){const i=e;var a=t/2;if(i.amp>0){const e=this._barkMaps.get(t),r=this._wMap.get(t);let n=0;for(n=0;n<this._order;n++)i.coeff[n]=2*Math.cos(i.coeff[n]);for(n=0;n<a;){let t=0;const a=e[n];let o=.5,h=.5,l=r[a];for(t=1;t<this._order;t+=2)h*=l-i.coeff[t-1],o*=l-i.coeff[t];for(t==this._order?(h*=l-i.coeff[t-1],o*=o*(4-l*l),h*=h):(o*=o*(2-l),h*=h*(2+l)),h=i.amp/Math.sqrt(o+h)-this._ampOfs,h=Math.exp(.11512925*h),s[n]*=h;e[++n]==a;)s[n]*=h}}else s.fill(0,0,a)}}class Pi{constructor(){this.posts=new Int32Array(64),this.postCount=0,this.forceEnergy=!1,this.forceNoEnergy=!1}get executeChannel(){return(this.forceEnergy||this.postCount>0)&&!this.forceNoEnergy}}class Ci{constructor(e,t){let i=-1;this._partitionClass=new Int32Array(e.readBits(5));for(let t=0;t<this._partitionClass.length;t++)this._partitionClass[t]=e.readBits(4),this._partitionClass[t]>i&&(i=this._partitionClass[t]);++i,this._classDimensions=new Int32Array(i),this._classSubclasses=new Int32Array(i),this._classMasterbooks=new Array(i),this._classMasterBookIndex=new Int32Array(i),this._subclassBooks=new Array(i),this._subclassBookIndex=new Array(i);for(let s=0;s<i;s++){this._classDimensions[s]=e.readBits(3)+1,this._classSubclasses[s]=e.readBits(2),this._classSubclasses[s]>0&&(this._classMasterBookIndex[s]=e.readBits(8),this._classMasterbooks[s]=t[this._classMasterBookIndex[s]]),this._subclassBooks[s]=new Array(1<<this._classSubclasses[s]),this._subclassBookIndex[s]=new Int32Array(this._subclassBooks[s].length);for(let i=0;i<this._subclassBooks[s].length;i++){const a=e.readBits(8)-1;a>=0&&(this._subclassBooks[s][i]=t[a]),this._subclassBookIndex[s][i]=a}}this._multiplier=e.readBits(2),this._range=Ci._rangeLookup[this._multiplier],this._yBits=Ci._yBitsLookup[this._multiplier],++this._multiplier;const a=e.readBits(4),r=[];r.push(0),r.push(1<<a);for(let t=0;t<this._partitionClass.length;t++){const s=this._partitionClass[t];for(let t=0;t<this._classDimensions[s];t++)r.push(e.readBits(a))}this._xList=new Int32Array(r),this._lNeigh=new Int32Array(r.length),this._hNeigh=new Int32Array(r.length),this._sortIdx=new Int32Array(r.length),this._sortIdx[0]=0,this._sortIdx[1]=1;for(let e=2;e<this._lNeigh.length;e++){this._lNeigh[e]=0,this._hNeigh[e]=1,this._sortIdx[e]=e;for(let t=2;t<e;t++){const s=this._xList[t];s<this._xList[e]?s>this._xList[this._lNeigh[e]]&&(this._lNeigh[e]=t):s<this._xList[this._hNeigh[e]]&&(this._hNeigh[e]=t)}}for(let e=0;e<this._sortIdx.length-1;e++)for(let t=e+1;t<this._sortIdx.length;t++){if(this._xList[e]==this._xList[t])throw new j(s.Format,"Vorbis: Invalid Floor1 Data");if(this._xList[this._sortIdx[e]]>this._xList[this._sortIdx[t]]){const s=this._sortIdx[e];this._sortIdx[e]=this._sortIdx[t],this._sortIdx[t]=s}}}unpack(e,t,s){var i=new Pi;if(e.readBit()){let t=2;i.posts[0]=e.readBits(this._yBits),i.posts[1]=e.readBits(this._yBits);for(let s=0;s<this._partitionClass.length;s++){const a=this._partitionClass[s],r=this._classDimensions[a],n=this._classSubclasses[a],o=(1<<n)-1;let h=0;if(n>0&&(h=this._classMasterbooks[a].decodeScalar(e),-1==h)){t=0;break}for(let l=0;l<r;l++){const r=this._subclassBooks[a][h&o];if(h>>=n,null!=r&&(i.posts[t]=r.decodeScalar(e),-1==i.posts[t])){t=0,s=this._partitionClass.length;break}++t}}i.postCount=t}return i}apply(e,t,s){const i=e,a=t/2;if(i.postCount>0){const e=this.unwrapPosts(i);let t=0,h=i.posts[0]*this._multiplier;for(let l=1;l<i.postCount;l++){var r=this._sortIdx[l];if(e[r]){var n=this._xList[r],o=i.posts[r]*this._multiplier;t<a&&this.renderLineMulti(t,h,Math.min(n,a),o,s),t=n,h=o}if(t>=a)break}t<a&&this.renderLineMulti(t,h,a,h,s)}else s.fill(0,0,a)}unwrapPosts(e){const t=new Array(64);t.fill(!1),t[0]=!0,t[1]=!0;const s=new Int32Array(64);s[0]=e.posts[0],s[1]=e.posts[1];for(let i=2;i<e.postCount;i++){const a=this._lNeigh[i],r=this._hNeigh[i],n=this.renderPoint(this._xList[a],s[a],this._xList[r],s[r],this._xList[i]),o=e.posts[i],h=this._range-n,l=n;let d;d=h<l?2*h:2*l,0!=o?(t[a]=!0,t[r]=!0,t[i]=!0,s[i]=o>=d?h>l?o-l+n:n-o+h-1:o%2==1?n-(o+1)/2:n+o/2):(t[i]=!1,s[i]=n)}for(let t=0;t<e.postCount;t++)e.posts[t]=s[t];return t}renderPoint(e,t,s,i,a){var r=i-t,n=s-e,o=Math.abs(r)*(a-e)/n|0;return r<0?t-o:t+o}renderLineMulti(e,t,s,i,a){const r=i-t,n=s-e;let o=Math.abs(r);const h=1-2*(r>>31&1),l=r/n|0;let d=e,c=t,u=-n;for(a[e]*=Ci.inverse_dB_table[t],o-=Math.abs(l)*n;++d<s;)c+=l,u+=o,u>=0&&(u-=n,c+=h),a[d]*=Ci.inverse_dB_table[c]}}Ci._rangeLookup=[256,128,86,64],Ci._yBitsLookup=[8,7,7,6],Ci.inverse_dB_table=new Float32Array([1.0649863e-7,1.1341951e-7,1.2079015e-7,1.2863978e-7,1.3699951e-7,1.4590251e-7,1.5538408e-7,1.6548181e-7,1.7623575e-7,1.8768855e-7,1.9988561e-7,2.128753e-7,2.2670913e-7,2.4144197e-7,2.5713223e-7,2.7384213e-7,2.9163793e-7,3.1059021e-7,3.3077411e-7,3.5226968e-7,3.7516214e-7,3.9954229e-7,4.255068e-7,4.5315863e-7,4.8260743e-7,5.1396998e-7,5.4737065e-7,5.8294187e-7,6.2082472e-7,6.6116941e-7,7.0413592e-7,7.4989464e-7,7.9862701e-7,8.505263e-7,9.0579828e-7,9.6466216e-7,10273513e-13,10941144e-13,11652161e-13,12409384e-13,13215816e-13,14074654e-13,14989305e-13,15963394e-13,17000785e-13,18105592e-13,19282195e-13,20535261e-13,21869758e-13,23290978e-13,24804557e-13,26416497e-13,2813319e-12,29961443e-13,31908506e-13,33982101e-13,36190449e-13,38542308e-13,41047004e-13,4371447e-12,46555282e-13,49580707e-13,5280274e-12,5623416e-12,59888572e-13,63780469e-13,67925283e-13,72339451e-13,77040476e-13,82047e-10,87378876e-13,93057248e-13,99104632e-13,10554501e-12,11240392e-12,11970856e-12,12748789e-12,13577278e-12,14459606e-12,15399272e-12,16400004e-12,17465768e-12,18600792e-12,19809576e-12,21096914e-12,22467911e-12,23928002e-12,25482978e-12,27139006e-12,28902651e-12,30780908e-12,32781225e-12,34911534e-12,37180282e-12,39596466e-12,42169667e-12,4491009e-11,47828601e-12,50936773e-12,54246931e-12,57772202e-12,61526565e-12,65524908e-12,69783085e-12,74317983e-12,79147585e-12,8429104e-11,89768747e-12,95602426e-12,.00010181521,.00010843174,.00011547824,.00012298267,.00013097477,.00013948625,.00014855085,.00015820453,.00016848555,.00017943469,.00019109536,.00020351382,.00021673929,.00023082423,.00024582449,.00026179955,.00027881276,.00029693158,.00031622787,.00033677814,.00035866388,.00038197188,.00040679456,.00043323036,.00046138411,.00049136745,.00052329927,.00055730621,.00059352311,.00063209358,.00067317058,716917e-9,.0007635063,.00081312324,.00086596457,.00092223983,.00098217216,.0010459992,.0011139742,.0011863665,.0012634633,.0013455702,.0014330129,.0015261382,.0016253153,.0017309374,.0018434235,.0019632195,.0020908006,.0022266726,.0023713743,.0025254795,.0026895994,.0028643847,.0030505286,.0032487691,.0034598925,.0036847358,.0039241906,.0041792066,.004450795,.0047400328,.0050480668,.0053761186,.0057254891,.0060975636,.0064938176,.0069158225,.0073652516,.0078438871,.0083536271,.0088964928,.009474637,.010090352,.01074608,.011444421,.012188144,.012980198,.013823725,.014722068,.015678791,.016697687,.017782797,.018938423,.020169149,.021479854,.022875735,.02436233,.025945531,.027631618,.029427276,.031339626,.033376252,.035545228,.037855157,.040315199,.042935108,.045725273,.048696758,.051861348,.055231591,.05882085,.062643361,.066714279,.071049749,.075666962,.080584227,.085821044,.091398179,.097337747,.1036633,.11039993,.11757434,.12521498,.13335215,.14201813,.15124727,.16107617,.1715438,.18269168,.19456402,.20720788,.22067342,.23501402,.25028656,.26655159,.28387361,.30232132,.32196786,.34289114,.36517414,.38890521,.41417847,.44109412,.4697589,.50028648,.53279791,.56742212,.6042964,.64356699,.68538959,.72993007,.77736504,.8278826,.88168307,.9389798,1]);class Ei{constructor(e,t,i,a){const r=e.readBits(16);switch(r){case 0:this.floor=new vi(e,t,i,a);break;case 1:this.floor=new Ci(e,a);break;default:throw new j(s.Format,"Vorbis: Invalid Floor type: "+r)}}apply(e,t,s){this.floor.apply(e,t,s)}unpack(e,t,s){return this.floor.unpack(e,t,s)}}class Fi{constructor(e,t,i){this._begin=e.readBits(24),this._end=e.readBits(24),this._partitionSize=e.readBits(24)+1,this._classifications=e.readBits(6)+1,this._classBook=i[e.readBits(8)],this._cascade=new Int32Array(this._classifications);let a=0;for(let t=0;t<this._classifications;t++){const s=e.readBits(3);e.readBit()?this._cascade[t]=e.readBits(5)<<3|s:this._cascade[t]=s,a+=Fi.icount(this._cascade[t])}const r=new Int32Array(a);for(let t=0;t<a;t++)if(r[t]=e.readBits(8),0==i[r[t]].mapType)throw new j(s.Format,"Vorbis: Invalid Residue 0");const n=this._classBook.entries;let o=this._classBook.dimensions,h=1;for(;o>0;){if(h*=this._classifications,h>n)throw new j(s.Format,"Vorbis: Invalid Residue 0");--o}this._books=new Array(this._classifications),a=0;let l,d=0;for(let e=0;e<this._classifications;e++)if(l=Si.ilog(this._cascade[e]),this._books[e]=new Array(l),l>0){d=Math.max(d,l);for(let t=0;t<l;t++)(this._cascade[e]&1<<t)>0&&(this._books[e][t]=i[r[a++]])}this._maxStages=d,this._decodeMap=new Array(h);for(let e=0;e<h;e++){let t=e,s=h/this._classifications|0;this._decodeMap[e]=new Int32Array(this._classBook.dimensions);for(let i=0;i<this._classBook.dimensions;i++){const a=t/s|0;t-=a*s,s=s/this._classifications|0,this._decodeMap[e][i]=a}}this._channels=t}static icount(e){let t=0;for(;0!=e;)t+=1&e,e>>=1;return t}decode(e,t,s,i){const a=(this._end<s/2?this._end:s/2)-this._begin;if(a>0&&-1!==t.indexOf(!1)){const t=a/this._partitionSize,s=(t+this._classBook.dimensions-1)/this._classBook.dimensions|0,r=[];for(let e=0;e<this._channels;e++)r.push(new Array(s));for(let s=0;s<this._maxStages;s++)for(let a=0,n=0;a<t;n++){if(0==s)for(let i=0;i<this._channels;i++){const o=this._classBook.decodeScalar(e);if(!(o>=0&&o<this._decodeMap.length)){a=t,s=this._maxStages;break}r[i][n]=this._decodeMap[o]}for(let o=0;a<t&&o<this._classBook.dimensions;o++,a++){const h=this._begin+a*this._partitionSize;for(let l=0;l<this._channels;l++){const d=r[l][n][o];if(this._cascade[d]&1<<s){const r=this._books[d][s];if(r&&this.writeVectors(r,e,i,l,h,this._partitionSize)){a=t,s=this._maxStages;break}}}}}}}writeVectors(e,t,s,i,a,r){const n=s[i],o=r/e.dimensions,h=new Int32Array(o);for(let s=0;s<o;s++)if(h[s]=e.decodeScalar(t),-1==h[s])return!0;for(let t=0;t<e.dimensions;t++)for(let s=0;s<o;s++,a++)n[a]+=e.get(h[s],t);return!1}}class Di extends Fi{constructor(e,t,s){super(e,t,s)}writeVectors(e,t,s,i,a,r){const n=s[i];for(let s=0;s<r;){const i=e.decodeScalar(t);if(-1==i)return!0;for(let t=0;t<e.dimensions;s++,t++)n[a+s]+=e.get(i,t)}return!1}}class Li extends Fi{constructor(e,t,s){super(e,1,s),this._realChannels=t}decode(e,t,s,i){super.decode(e,t,s*this._realChannels,i)}writeVectors(e,t,s,i,a,r){let n=0;a/=this._realChannels;for(let i=0;i<r;){const r=e.decodeScalar(t);if(-1==r)return!0;for(let t=0;t<e.dimensions;t++,i++)s[n][a]+=e.get(r,t),++n==this._realChannels&&(n=0,a++)}return!1}}class Mi{constructor(e,t,i){const a=e.readBits(16);switch(a){case 0:this.residue=new Fi(e,t,i);break;case 1:this.residue=new Di(e,t,i);break;case 2:this.residue=new Li(e,t,i);break;default:throw new j(s.Format,"Vorbis: Invalid Residue type: "+a)}}decode(e,t,s,i){this.residue.decode(e,t,s,i)}}class Ii{constructor(e,t,i,a,r){if(0!==e.readBits(16))throw new j(s.Format,"Vorbis: Invalid mapping type!");let n=1;e.readBit()&&(n+=e.readBits(4));let o=0;e.readBit()&&(o=e.readBits(8)+1);const h=Si.ilog(t-1);this._couplingAngle=new Int32Array(o),this._couplingMangitude=new Int32Array(o);for(let i=0;i<o;i++){const a=e.readBits(h),r=e.readBits(h);if(a==r||a>t-1||r>t-1)throw new j(s.Format,"Vorbis: Invalid magnitude or angle in mapping header!");this._couplingAngle[i]=r,this._couplingMangitude[i]=a}if(0!=e.readBits(2))throw new j(s.Format,"Vorbis: Reserved bits not 0 in mapping header.");const l=new Int32Array(t);if(n>1)for(let i=0;i<t;i++)if(l[i]=e.readBits(4),l[i]>n)throw new j(s.Format,"Vorbis: Invalid channel mux submap index in mapping header!");this._submapFloor=new Array(n),this._submapResidue=new Array(n);for(let t=0;t<n;t++){e.skipBits(8);const r=e.readBits(8);if(r>=i.length)throw new j(s.Format,"Vorbis: Invalid floor number in mapping header!");const n=e.readBits(8);if(n>=a.length)throw new j(s.Format,"Vorbis: Invalid residue number in mapping header!");this._submapFloor[t]=i[r],this._submapResidue[t]=a[n]}this._channelFloor=new Array(t),this._channelResidue=new Array(t);for(let e=0;e<t;e++)this._channelFloor[e]=this._submapFloor[l[e]],this._channelResidue[e]=this._submapResidue[l[e]];this._mdct=r}decodePacket(e,t,s){const i=t>>1,a=new Array(this._channelFloor.length),r=new Array(this._channelFloor.length);r.fill(!1);for(let n=0;n<this._channelFloor.length;n++)a[n]=this._channelFloor[n].unpack(e,t,n),r[n]=!a[n].executeChannel,s[n].fill(0,0,i);for(let e=0;e<this._couplingAngle.length;e++)(a[this._couplingAngle[e]].executeChannel||a[this._couplingMangitude[e]].executeChannel)&&(a[this._couplingAngle[e]].forceEnergy=!0,a[this._couplingMangitude[e]].forceEnergy=!0);for(let i=0;i<this._submapFloor.length;i++){for(let e=0;e<this._channelFloor.length;e++)this._submapFloor[i]==this._channelFloor[e]&&this._submapResidue[i]==this._channelResidue[e]||(a[e].forceNoEnergy=!0);this._submapResidue[i].decode(e,r,t,s)}for(let e=this._couplingAngle.length-1;e>=0;e--)if(a[this._couplingAngle[e]].executeChannel||a[this._couplingMangitude[e]].executeChannel){const t=s[this._couplingMangitude[e]],a=s[this._couplingAngle[e]];for(var n=0;n<i;n++){let e,s;const i=t[n],r=a[n];i>0?r>0?(e=i,s=i-r):(s=i,e=i+r):r>0?(e=i,s=i+r):(s=i,e=i-r),t[n]=e,a[n]=s}}for(let e=0;e<this._channelFloor.length;e++)a[e].executeChannel?(this._channelFloor[e].apply(a[e],t,s[e]),this._mdct.reverse(s[e],t)):s[e].fill(0,i,2*i)}}class Ai{constructor(){this.packetStartIndex=0,this.packetTotalLength=0,this.packetValidLength=0}}class Oi{constructor(){this.overlapInfo=new Ai,this.windowIndex=0}}class Ri{constructor(e=null){this.samplePosition=null,this.samplePosition=e}}class Vi{constructor(e,t,i,a,r){if(this._overlapInfo=null,this._channels=t,this._blockFlag=e.readBit(),0!=e.readBits(32))throw new j(s.Format,"Vorbis: Mode header had invalid window or transform type!");const n=e.readBits(8);if(n>=r.length)throw new j(s.Format,"Vorbis: Mode header had invalid mapping index!");this._mapping=r[n],this._blockFlag?(this._blockSize=a,this._windows=[Vi.calcWindow(i,a,i),Vi.calcWindow(a,a,i),Vi.calcWindow(i,a,a),Vi.calcWindow(a,a,a)],this._overlapInfo=[Vi.calcOverlap(i,a,i),Vi.calcOverlap(a,a,i),Vi.calcOverlap(i,a,a),Vi.calcOverlap(a,a,a)]):(this._blockSize=i,this._windows=[Vi.calcWindow(i,i,i)])}decode(e,t){const s=this.getPacketInfo(e);this._mapping.decodePacket(e,this._blockSize,t);const i=this._windows[s.windowIndex];for(let e=0;e<this._blockSize;e++)for(let s=0;s<this._channels;s++)t[s][e]*=i[e];return s.overlapInfo}getPacketInfo(e){const t=new Oi;if(this._blockFlag){const s=e.readBit(),i=e.readBit();t.windowIndex=(s?1:0)+(i?2:0);const a=this._overlapInfo[t.windowIndex];t.overlapInfo.packetStartIndex=a.packetStartIndex,t.overlapInfo.packetValidLength=a.packetValidLength,t.overlapInfo.packetTotalLength=a.packetTotalLength}else t.windowIndex=0,t.overlapInfo.packetStartIndex=0,t.overlapInfo.packetValidLength=this._blockSize/2,t.overlapInfo.packetTotalLength=this._blockSize;return t}static calcWindow(e,t,s){const i=new Float32Array(t),a=e/2,r=s/2,n=t/4-a/2,o=t-t/4-r/2;for(let e=0;e<a;e++){let t=Math.sin((e+.5)/a*Vi.M_PI2);t*=t,i[n+e]=Math.sin(t*Vi.M_PI2)}for(let e=n+a;e<o;e++)i[e]=1;for(let e=0;e<r;e++){let t=Math.sin((r-e-.5)/r*Vi.M_PI2);t*=t,i[o+e]=Math.sin(t*Vi.M_PI2)}return i}static calcOverlap(e,t,s){const i=s/4,a=t/4-e/4,r=t/4*3+i,n=r-2*i,o=new Ai;return o.packetStartIndex=a,o.packetValidLength=n,o.packetTotalLength=r,o}}Vi.M_PI2=1.57079632695;class Hi{constructor(e){this._n=e,this._n2=e>>1,this._n4=this._n2>>1,this._n8=this._n4>>1,this._ld=Si.ilog(e)-1,this._a=new Float32Array(this._n2),this._b=new Float32Array(this._n2),this._c=new Float32Array(this._n4);let t=0,s=0;for(;t<this._n4;++t,s+=2)this._a[s]=Math.cos(4*t*Hi.M_PI/e),this._a[s+1]=-Math.sin(4*t*Hi.M_PI/e),this._b[s]=.5*Math.cos((s+1)*Hi.M_PI/e/2),this._b[s+1]=.5*Math.sin((s+1)*Hi.M_PI/e/2);for(t=0,s=0;t<this._n8;++t,s+=2)this._c[s]=Math.cos(2*(s+1)*Hi.M_PI/e),this._c[s+1]=-Math.sin(2*(s+1)*Hi.M_PI/e);this._bitrev=new Uint16Array(this._n8);for(let e=0;e<this._n8;++e)this._bitrev[e]=Ie.int32ToUint16(Si.bitReverse(e,this._ld-3)<<2)}calcReverse(e){let t,s;const i=new Float32Array(this._n2);{let t=this._n2-2,s=0,a=0,r=this._n2;for(;a!=r;)i[t+1]=e[a]*this._a[s]-e[a+2]*this._a[s+1],i[t]=e[a]*this._a[s+1]+e[a+2]*this._a[s],t-=2,s+=2,a+=4;for(a=this._n2-3;t>=0;)i[t+1]=-e[a+2]*this._a[s]- -e[a]*this._a[s+1],i[t]=-e[a+2]*this._a[s+1]+-e[a]*this._a[s],t-=2,s+=2,a-=4}t=e,s=i;{let e=this._n2-8,i=this._n4,a=0,r=this._n4,n=0;for(;e>=0;){let o,h;h=s[i+1]-s[a+1],o=s[i]-s[a],t[r+1]=s[i+1]+s[a+1],t[r]=s[i]+s[a],t[n+1]=h*this._a[e+4]-o*this._a[e+5],t[n]=o*this._a[e+4]+h*this._a[e+5],h=s[i+3]-s[a+3],o=s[i+2]-s[a+2],t[r+3]=s[i+3]+s[a+3],t[r+2]=s[i+2]+s[a+2],t[n+3]=h*this._a[e]-o*this._a[e+1],t[n+2]=o*this._a[e]+h*this._a[e+1],e-=8,r+=4,n+=4,i+=4,a+=4}}this.step3_iter0_loop(this._n>>4,t,this._n2-1-0*this._n4,-this._n8),this.step3_iter0_loop(this._n>>4,t,this._n2-1-1*this._n4,-this._n8),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-0*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-1*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-2*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-3*this._n8,-(this._n>>4),16);let a=2;for(;a<this._ld-3>>1;++a){const e=this._n>>a+2,s=e>>1,i=1<<a+1;for(let r=0;r<i;++r)this.step3_inner_r_loop(this._n>>a+4,t,this._n2-1-e*r,-s,1<<a+3)}for(;a<this._ld-6;++a){const e=this._n>>a+2,s=1<<a+3,i=e>>1,r=this._n>>a+6,n=1<<a+1;let o=this._n2-1,h=0;for(let a=r;a>0;--a)this.step3_inner_s_loop(n,t,o,-i,h,s,e),h+=4*s,o-=8}this.step3_inner_s_loop_ld654(this._n>>5,t,this._n2-1,this._n);{let e=0,i=this._n4-4,a=this._n2-4;for(;i>=0;){let r;r=this._bitrev[e],s[a+3]=t[r],s[a+2]=t[r+1],s[i+3]=t[r+2],s[i+2]=t[r+3],r=this._bitrev[e+1],s[a+1]=t[r],s[a]=t[r+1],s[i+1]=t[r+2],s[i]=t[r+3],i-=4,a-=4,e+=2}}for(var r=0,n=0,o=this._n2-4;n<o;){let e,t,i,a,h,l;e=s[n]-s[o+2],t=s[n+1]+s[o+3],i=this._c[r+1]*e+this._c[r]*t,a=this._c[r+1]*t-this._c[r]*e,h=s[n]+s[o+2],l=s[n+1]-s[o+3],s[n]=h+i,s[n+1]=l+a,s[o+2]=h-i,s[o+3]=a-l,e=s[n+2]-s[o],t=s[n+3]+s[o+1],i=this._c[r+3]*e+this._c[r+2]*t,a=this._c[r+3]*t-this._c[r+2]*e,h=s[n+2]+s[o],l=s[n+3]-s[o+1],s[n+2]=h+i,s[n+3]=l+a,s[o]=h-i,s[o+1]=a-l,r+=4,n+=4,o-=4}{let t=this._n2-8,s=this._n2-8,a=0,r=this._n2-4,n=this._n2,o=this._n-4;for(;s>=0;){let h,l,d,c;c=i[s+6]*this._b[t+7]-i[s+7]*this._b[t+6],d=-i[s+6]*this._b[t+6]-i[s+7]*this._b[t+7],e[a]=c,e[r+3]=-c,e[n]=d,e[o+3]=d,l=i[s+4]*this._b[t+5]-i[s+5]*this._b[t+4],h=-i[s+4]*this._b[t+4]-i[s+5]*this._b[t+5],e[a+1]=l,e[r+2]=-l,e[n+1]=h,e[o+2]=h,c=i[s+2]*this._b[t+3]-i[s+3]*this._b[t+2],d=-i[s+2]*this._b[t+2]-i[s+3]*this._b[t+3],e[a+2]=c,e[r+1]=-c,e[n+2]=d,e[o+1]=d,l=i[s]*this._b[t+1]-i[s+1]*this._b[t],h=-i[s]*this._b[t]-i[s+1]*this._b[t+1],e[a+3]=l,e[r]=-l,e[n+3]=h,e[o]=h,t-=8,s-=8,a+=4,n+=4,r-=4,o-=4}}}step3_inner_r_loop(e,t,s,i,a){let r,n,o=s,h=o+i,l=0;for(let s=e>>2;s>0;--s)r=t[o]-t[h],n=t[o-1]-t[h-1],t[o]+=t[h],t[o-1]+=t[h-1],t[h]=r*this._a[l]-n*this._a[l+1],t[h-1]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-2]-t[h-2],n=t[o-3]-t[h-3],t[o-2]+=t[h-2],t[o-3]+=t[h-3],t[h-2]=r*this._a[l]-n*this._a[l+1],t[h-3]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-4]-t[h-4],n=t[o-5]-t[h-5],t[o-4]+=t[h-4],t[o-5]+=t[h-5],t[h-4]=r*this._a[l]-n*this._a[l+1],t[h-5]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-6]-t[h-6],n=t[o-7]-t[h-7],t[o-6]+=t[h-6],t[o-7]+=t[h-7],t[h-6]=r*this._a[l]-n*this._a[l+1],t[h-7]=n*this._a[l]+r*this._a[l+1],l+=a,o-=8,h-=8}step3_iter0_loop(e,t,s,i){var a=s,r=a+i,n=0;for(let s=e>>2;s>0;--s){let e,s;e=t[a]-t[r],s=t[a-1]-t[r-1],t[a]+=t[r],t[a-1]+=t[r-1],t[r]=e*this._a[n]-s*this._a[n+1],t[r-1]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-2]-t[r-2],s=t[a-3]-t[r-3],t[a-2]+=t[r-2],t[a-3]+=t[r-3],t[r-2]=e*this._a[n]-s*this._a[n+1],t[r-3]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-4]-t[r-4],s=t[a-5]-t[r-5],t[a-4]+=t[r-4],t[a-5]+=t[r-5],t[r-4]=e*this._a[n]-s*this._a[n+1],t[r-5]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-6]-t[r-6],s=t[a-7]-t[r-7],t[a-6]+=t[r-6],t[a-7]+=t[r-7],t[r-6]=e*this._a[n]-s*this._a[n+1],t[r-7]=s*this._a[n]+e*this._a[n+1],n+=8,a-=8,r-=8}}step3_inner_s_loop(e,t,s,i,a,r,n){var o=this._a[a],h=this._a[a+1],l=this._a[a+r],d=this._a[a+r+1],c=this._a[a+2*r],u=this._a[a+2*r+1],p=this._a[a+3*r],g=this._a[a+3*r+1];let m,f,y=s,b=y+i;for(let s=e;s>0;--s)m=t[y]-t[b],f=t[y-1]-t[b-1],t[y]+=t[b],t[y-1]+=t[b-1],t[b]=m*o-f*h,t[b-1]=f*o+m*h,m=t[y-2]-t[b-2],f=t[y-3]-t[b-3],t[y-2]+=t[b-2],t[y-3]+=t[b-3],t[b-2]=m*l-f*d,t[b-3]=f*l+m*d,m=t[y-4]-t[b-4],f=t[y-5]-t[b-5],t[y-4]+=t[b-4],t[y-5]+=t[b-5],t[b-4]=m*c-f*u,t[b-5]=f*c+m*u,m=t[y-6]-t[b-6],f=t[y-7]-t[b-7],t[y-6]+=t[b-6],t[y-7]+=t[b-7],t[b-6]=m*p-f*g,t[b-7]=f*p+m*g,y-=n,b-=n}step3_inner_s_loop_ld654(e,t,s,i){const a=i>>3,r=this._a[a];let n=s;const o=n-16*e;for(;n>o;){let e,s;e=t[n]-t[n-8],s=t[n-1]-t[n-9],t[n]+=t[n-8],t[n-1]+=t[n-9],t[n-8]=e,t[n-9]=s,e=t[n-2]-t[n-10],s=t[n-3]-t[n-11],t[n-2]+=t[n-10],t[n-3]+=t[n-11],t[n-10]=(e+s)*r,t[n-11]=(s-e)*r,e=t[n-12]-t[n-4],s=t[n-5]-t[n-13],t[n-4]+=t[n-12],t[n-5]+=t[n-13],t[n-12]=s,t[n-13]=e,e=t[n-14]-t[n-6],s=t[n-7]-t[n-15],t[n-6]+=t[n-14],t[n-7]+=t[n-15],t[n-14]=(e+s)*r,t[n-15]=(e-s)*r,this.iter_54(t,n),this.iter_54(t,n-8),n-=16}}iter_54(e,t){let s,i,a,r,n,o,h,l;s=e[t]-e[t-4],n=e[t]+e[t-4],h=e[t-2]+e[t-6],a=e[t-2]-e[t-6],e[t]=n+h,e[t-2]=n-h,r=e[t-3]-e[t-7],e[t-4]=s+r,e[t-6]=s-r,i=e[t-1]-e[t-5],o=e[t-1]+e[t-5],l=e[t-3]+e[t-7],e[t-1]=o+l,e[t-3]=o-l,e[t-5]=i-a,e[t-7]=i+a}}Hi.M_PI=3.141592653589793;class Gi{constructor(){this._setupCache=new Map}reverse(e,t){let s;this._setupCache.has(t)?s=this._setupCache.get(t):(s=new Hi(t),this._setupCache.set(t,s)),s.calcReverse(e)}}class Wi{constructor(e,t,s){this._packetIndex=0,this._stream=e,this._setup=t,this._packets=s,this._currentPosition=0,this._prevPacketBuf=null,this._prevPacketStart=0,this._prevPacketEnd=0,this._prevPacketStop=0,this._nextPacketBuf=null,this._eosFound=!1,this._hasPosition=!1,this._modeFieldBits=Si.ilog(t.modes.length-1)}decode(){let e=new Float32Array(this._packets[this._packets.length-1].granulePosition*this._stream.audioChannels);const t=new Float32Array(.2*this._stream.audioSampleRate*this._stream.audioChannels);let s=0,i=0;for(;s=this.read(t,0,t.length),0!==s;){if(i+s>=e.length){const s=new Float32Array(e.length+t.length);s.set(e,0),e=s}e.set(t.subarray(0,s),i),i+=s}return e.subarray(0,i)}read(e,t,s){if(0==s)return 0;let i=t;const a=t+s;for(;i<a;){if(this._prevPacketStart==this._prevPacketEnd){if(this._eosFound){this._nextPacketBuf=null,this._prevPacketBuf=null;break}const e=this.readNextPacket((i-t)/this._stream.audioChannels);null===e&&(this._prevPacketEnd=this._prevPacketStop),null===e||null===e.samplePosition||this._hasPosition||(this._hasPosition=!0,this._currentPosition=e.samplePosition-(this._prevPacketEnd-this._prevPacketStart)-(i-t)/this._stream.audioChannels)}const s=Math.min((a-i)/this._stream.audioChannels,this._prevPacketEnd-this._prevPacketStart);s>0&&(i+=this.copyBuffer(e,i,s))}return s=i-t,this._currentPosition+=s/this._stream.audioChannels,s}copyBuffer(e,t,s){let i=t;for(;s>0;this._prevPacketStart++,s--)for(let t=0;t<this._stream.audioChannels;t++)e[i++]=this._prevPacketBuf[t][this._prevPacketStart];return i-t}readNextPacket(e){const t=this.decodeNextPacket();if(this._eosFound=this._eosFound||t.isEndOfStream,null==t.curPacket)return null;if(null!==t.samplePosition&&t.isEndOfStream){const s=this._currentPosition+e+t.validLen-t.startIndex,i=t.samplePosition-s;i<0&&(t.validLen+=i,t.validLen<0&&(t.validLen=0))}return this._prevPacketEnd>0?(Wi.overlapBuffers(this._prevPacketBuf,t.curPacket,this._prevPacketStart,this._prevPacketStop,t.startIndex,this._stream.audioChannels),this._prevPacketStart=t.startIndex):null==this._prevPacketBuf&&(this._prevPacketStart=t.validLen),this._nextPacketBuf=this._prevPacketBuf,this._prevPacketEnd=t.validLen,this._prevPacketStop=t.totalLen,this._prevPacketBuf=t.curPacket,new Ri(t.samplePosition)}static overlapBuffers(e,t,s,i,a,r){for(;s<i;s++,a++)for(let i=0;i<r;i++)t[i][a]+=e[i][s]}decodeNextPacket(){const e=new zi;let t=null;if(this._packetIndex>=this._packets.length)e.isEndOfStream=!0;else{t=this._packets[this._packetIndex++];const s=new yi(Oe.fromBuffer(t.packetData));if(e.isEndOfStream=t.isEndOfStream,!s.readBit()){const i=this._setup.modes[s.readBits(this._modeFieldBits)];if(null==this._nextPacketBuf){this._nextPacketBuf=new Array(this._stream.audioChannels);for(let e=0;e<this._stream.audioChannels;e++)this._nextPacketBuf[e]=new Float32Array(this._stream.blocksize1)}const a=i.decode(s,this._nextPacketBuf);return e.startIndex=a.packetStartIndex,e.validLen=a.packetValidLength,e.totalLen=a.packetTotalLength,e.samplePosition=t.granulePosition,e.curPacket=this._nextPacketBuf,e}}return e}}class zi{constructor(){this.curPacket=null,this.startIndex=0,this.validLen=0,this.totalLen=0,this.isEndOfStream=!1,this.samplePosition=null}}!function(e){e[e.IdentificationHeader=1]="IdentificationHeader",e[e.Comment=3]="Comment",e[e.SetupHeader=5]="SetupHeader"}(Ds||(Ds={}));class Ui{constructor(e){this._packetIndex=-1,this._packets=e}read(){let e;for(;;){if(e=this.nextPacket(),null==e)return null;if(e.isBeginningOfStream){var t=this.readStream(e);if(null!=t)return t}}}nextPacket(){return this._packetIndex++,this._packetIndex<this._packets.length?this._packets[this._packetIndex]:null}readStream(e){const t=new mi;if(!this.readIdentificationHeader(t,e))return null;if(!this.readComments(this.nextPacket()))return null;const s=new bi;if(!this.readSetupHeader(t,s,this.nextPacket()))return null;const i=[];let a;for(;a=this.nextPacket(),null!=a&&(i.push(a),!a.isEndOfStream););const r=new Wi(t,s,i);return t.samples=r.decode(),t}comonHeaderDecode(e,t){const s=new Uint8Array(7);if(t.read(s,0,s.length),s[0]!==e)return!1;for(let e=0;e<Ui.VorbisHeaderMarker.length;e++)if(s[1+e]!==Ui.VorbisHeaderMarker[e])return!1;return!0}comonHeaderDecodeBit(e,t){const s=t.readBytes(7);if(s[0]!==e)return!1;for(let e=0;e<Ui.VorbisHeaderMarker.length;e++)if(s[1+e]!==Ui.VorbisHeaderMarker[e])return!1;return!0}readIdentificationHeader(e,t){const s=Oe.fromBuffer(t.packetData);if(!this.comonHeaderDecode(Ds.IdentificationHeader,s))return!1;if(0!=Ae.readUInt32LE(s))return!1;if(e.audioChannels=s.readByte(),e.audioSampleRate=Ae.readUInt32LE(s),e.audioChannels<=0||e.audioSampleRate<=0)return!1;e.bitrateMaximum=Ae.readInt32LE(s),e.bitrateNominal=Ae.readInt32LE(s),e.bitrateMinimum=Ae.readInt32LE(s);var i=s.readByte();if(e.blocksize0=1<<(15&i),e.blocksize1=1<<(i>>4),e.blocksize0>e.blocksize1||!Ui.isAllowedBlockSize(e.blocksize0)||!Ui.isAllowedBlockSize(e.blocksize0))return!1;return 0!==s.readByte()}static isAllowedBlockSize(e){switch(e){case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:return!0;default:return!1}}readComments(e){if(null==e)return!1;var t=Oe.fromBuffer(e.packetData);if(!this.comonHeaderDecode(Ds.Comment,t))return!1;const s=Ae.readUInt32LE(t);t.skip(s);var i=Ae.readUInt32LE(t);for(let e=0;e<i;e++){const e=Ae.readUInt32LE(t);t.skip(e)}return 0!=t.readByte()}readSetupHeader(e,t,s){if(null==s)return!1;const i=new yi(Oe.fromBuffer(s.packetData)),a=new Gi,r=new Ti;if(!this.comonHeaderDecodeBit(Ds.SetupHeader,i))return!1;let n=i.readByte()+1;for(let e=0;e<n;e++)t.codebooks.push(new Bi(i,r));n=i.readBits(6)+1;for(let e=0;e<n;e++)t.timeDomainTransforms.push(new xi(i));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.floors.push(new Ei(i,e.blocksize0,e.blocksize1,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.residues.push(new Mi(i,e.audioChannels,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.mappings.push(new Ii(i,e.audioChannels,t.floors,t.residues,a));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.modes.push(new Vi(i,e.audioChannels,e.blocksize0,e.blocksize1,t.mappings));return!!i.readBit()}}Ui.VorbisHeaderMarker=new Uint8Array(["v".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"b".charCodeAt(0),"i".charCodeAt(0),"s".charCodeAt(0)]);class Xi{constructor(e){this.streams=[];for(var t=new gi(e).read(),s=new Ui(t);;){let e=s.read();if(null==e)break;this.streams.push(e)}}}class Ji{constructor(){this.phdrs=[],this.pbags=[],this.pmods=[],this.pgens=[],this.insts=[],this.ibags=[],this.imods=[],this.igens=[],this.sHdrs=[],this.sampleData=new Uint8Array(0),this._sampleCache=new Map}decodeSamples(e,t,s){const i=`${e}_${t}_${s}`;if(!this._sampleCache.has(i)){let a;const r=this.sampleData.slice(e,t);if(s){a=new Xi(Oe.fromBuffer(r)).streams[0].samples}else{let e=new Int16Array(r.buffer);a=new Float32Array(e.length);for(let t=0;t<e.length;t++)a[t]=e[t]/32767}return this._sampleCache.set(i,a),a}return this._sampleCache.get(i)}load(e){const t=new ui,s=new ui;if(!ui.load(null,t,e)||"sfbk"!==t.id)throw new Pe("Soundfont is not a valid Soundfont2 file");for(;ui.load(t,s,e);){let t=new ui;if("pdta"===s.id)for(;ui.load(s,t,e);)switch(t.id){case"phdr":for(let s=0,i=t.size/Zi.SizeInFile|0;s<i;s++)this.phdrs.push(new Zi(e));break;case"pbag":for(let s=0,i=t.size/Qi.SizeInFile|0;s<i;s++)this.pbags.push(new Qi(e));break;case"pmod":for(let s=0,i=t.size/ea.SizeInFile|0;s<i;s++)this.pmods.push(new ea(e));break;case"pgen":for(let s=0,i=t.size/$i.SizeInFile|0;s<i;s++)this.pgens.push(new $i(e));break;case"inst":for(let s=0,i=t.size/Ki.SizeInFile|0;s<i;s++)this.insts.push(new Ki(e));break;case"ibag":for(let s=0,i=t.size/Yi.SizeInFile|0;s<i;s++)this.ibags.push(new Yi(e));break;case"imod":for(let s=0,i=t.size/qi.SizeInFile|0;s<i;s++)this.imods.push(new qi(e));break;case"igen":for(let s=0,i=t.size/ji.SizeInFile|0;s<i;s++)this.igens.push(new ji(e));break;case"shdr":for(let s=0,i=t.size/ta.SizeInFile|0;s<i;s++)this.sHdrs.push(new ta(e));break;default:e.position+=t.size}else if("sdta"===s.id)for(;ui.load(s,t,e);)if("smpl"===t.id)this.sampleData=new Uint8Array(t.size),e.read(this.sampleData,0,t.size);else e.position+=t.size;else e.position+=s.size}}}class Yi{constructor(e){this.instGenNdx=Ae.readUInt16LE(e),this.instModNdx=Ae.readUInt16LE(e)}}Yi.SizeInFile=4;class qi{constructor(e){this.modSrcOper=Ae.readUInt16LE(e),this.modDestOper=Ae.readUInt16LE(e),this.modAmount=Ae.readInt16LE(e),this.modAmtSrcOper=Ae.readUInt16LE(e),this.modTransOper=Ae.readUInt16LE(e)}}qi.SizeInFile=10;class ji{constructor(e){this.genOper=Ae.readUInt16LE(e),this.genAmount=new sa(e)}}ji.SizeInFile=4;class Ki{constructor(e){this.instName=Ae.read8BitStringLength(e,20),this.instBagNdx=Ae.readUInt16LE(e)}}Ki.SizeInFile=22;class Qi{constructor(e){this.genNdx=Ae.readUInt16LE(e),this.modNdx=Ae.readUInt16LE(e)}}Qi.SizeInFile=4;class $i{constructor(e){this.genOper=Ae.readUInt16LE(e),this.genAmount=new sa(e)}}$i.SizeInFile=4,$i.GenInstrument=41,$i.GenKeyRange=43,$i.GenVelRange=44,$i.GenSampleId=53;class Zi{constructor(e){this.presetName=Ae.read8BitStringLength(e,20),this.preset=Ae.readUInt16LE(e),this.bank=Ae.readUInt16LE(e),this.presetBagNdx=Ae.readUInt16LE(e),this.library=Ae.readUInt32LE(e),this.genre=Ae.readUInt32LE(e),this.morphology=Ae.readUInt32LE(e)}}Zi.SizeInFile=38;class ea{constructor(e){this.modSrcOper=Ae.readUInt16LE(e),this.modDestOper=Ae.readUInt16LE(e),this.modAmount=Ae.readUInt16LE(e),this.modAmtSrcOper=Ae.readUInt16LE(e),this.modTransOper=Ae.readUInt16LE(e)}}ea.SizeInFile=10;class ta{constructor(e){this.sampleName=Ae.read8BitStringLength(e,20),this.start=Ae.readUInt32LE(e),this.end=Ae.readUInt32LE(e),this.startLoop=Ae.readUInt32LE(e),this.endLoop=Ae.readUInt32LE(e),this.sampleRate=Ae.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=Ae.readSInt8(e),this.sampleLink=Ae.readUInt16LE(e),this.sampleType=Ae.readUInt16LE(e)}}ta.SizeInFile=46;class sa{get shortAmount(){return Ie.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}constructor(e){this.wordAmount=Ae.readUInt16LE(e)}}class ia{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 aa{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"}(Ls||(Ls={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(Ms||(Ms={}));class ra{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null}}class na{static timecents2Secs(e){return Math.pow(2,e/1200)}static decibelsToGain(e){return e>-100?Math.pow(10,.05*e):0}static gainToDecibels(e){return e<=1e-5?-100:20*Math.log10(e)}static cents2Hertz(e){return 8.176*Math.pow(2,e/1200)}}class oa{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:na.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:na.timecents2Secs(this.attack),this.release=this.release<-11950?0:na.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:na.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:na.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?na.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"}(Is||(Is={}));class ha{constructor(e){this.loopMode=Ls.None,this.samples=ha.NoSamples,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv=new oa,this.modEnv=new oa,this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,e&&(this.loopMode=e.loopMode,this.samples=e.samples,this.sampleRate=e.sampleRate,this.loKey=e.loKey,this.hiKey=e.hiKey,this.loVel=e.loVel,this.hiVel=e.hiVel,this.group=e.group,this.offset=e.offset,this.end=e.end,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this.transpose=e.transpose,this.tune=e.tune,this.pitchKeyCenter=e.pitchKeyCenter,this.pitchKeyTrack=e.pitchKeyTrack,this.attenuation=e.attenuation,this.pan=e.pan,this.ampEnv=new oa(e.ampEnv),this.modEnv=new oa(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=Ls.None,this.samples=ha.NoSamples,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv.clear(),this.modEnv.clear(),this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,this.hiKey=127,this.hiVel=127,this.pitchKeyCenter=60,e||(this.pitchKeyTrack=100,this.pitchKeyCenter=-1,this.ampEnv.delay=-12e3,this.ampEnv.attack=-12e3,this.ampEnv.hold=-12e3,this.ampEnv.decay=-12e3,this.ampEnv.release=-12e3,this.modEnv.delay=-12e3,this.modEnv.attack=-12e3,this.modEnv.hold=-12e3,this.modEnv.decay=-12e3,this.modEnv.release=-12e3,this.initialFilterFc=13500,this.delayModLFO=-12e3,this.delayVibLFO=-12e3)}operator(e,t){switch(e){case Is.StartAddrsOffset:this.offset+=Ie.int16ToUint32(t.shortAmount);break;case Is.EndAddrsOffset:this.end+=Ie.int16ToUint32(t.shortAmount);break;case Is.StartloopAddrsOffset:this.loopStart+=Ie.int16ToUint32(t.shortAmount);break;case Is.EndloopAddrsOffset:this.loopEnd+=Ie.int16ToUint32(t.shortAmount);break;case Is.StartAddrsCoarseOffset:this.offset+=32768*Ie.int16ToUint32(t.shortAmount);break;case Is.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case Is.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case Is.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case Is.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case Is.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case Is.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case Is.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case Is.EndAddrsCoarseOffset:this.end+=32768*Ie.int16ToUint32(t.shortAmount);break;case Is.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case Is.Pan:this.pan=t.shortAmount/1e3;break;case Is.DelayModLFO:this.delayModLFO=t.shortAmount;break;case Is.FreqModLFO:this.freqModLFO=t.shortAmount;break;case Is.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case Is.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case Is.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case Is.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case Is.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case Is.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case Is.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case Is.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case Is.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case Is.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case Is.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case Is.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case Is.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case Is.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case Is.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case Is.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case Is.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case Is.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case Is.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case Is.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case Is.StartloopAddrsCoarseOffset:this.loopStart+=32768*Ie.int16ToUint32(t.shortAmount);break;case Is.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case Is.EndloopAddrsCoarseOffset:this.loopEnd+=32768*Ie.int16ToUint32(t.shortAmount);break;case Is.CoarseTune:this.transpose+=t.shortAmount;break;case Is.FineTune:this.tune+=t.shortAmount;break;case Is.SampleModes:this.loopMode=3&~t.wordAmount?1==(3&t.wordAmount)?Ls.Continuous:Ls.None:Ls.Sustain;break;case Is.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case Is.ExclusiveClass:this.group=t.wordAmount;break;case Is.OverridingRootKey:this.pitchKeyCenter=t.shortAmount}}}ha.NoSamples=new Float32Array(0),function(e){e[e.None=0]="None",e[e.Delay=1]="Delay",e[e.Attack=2]="Attack",e[e.Hold=3]="Hold",e[e.Decay=4]="Decay",e[e.Sustain=5]="Sustain",e[e.Release=6]="Release",e[e.Done=7]="Done"}(As||(As={}));class la{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=As.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case As.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=As.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=As.Delay;break;case As.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=As.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=As.Attack;break;case As.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=As.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=As.Hold;break;case As.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=As.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=As.Decay;break;case As.Decay:return this.segment=As.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case As.Sustain:if(this.segment=As.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?la.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=As.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,s,i,a){this.parameters=new oa(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:na.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:na.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|s,this.isAmpEnv=i,this.nextSegment(As.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)}}la.FastReleaseTime=.01;class da{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,s){this.samplesUntil=e*s|0,this.delta=4*na.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 ca{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 ua{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 la,this.modEnv=new la,this.lowPass=new ca,this.modLfo=new da,this.vibLfo=new da,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/(na.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(As.Sustain,e),this.modEnv.nextSegment(As.Sustain,e),this.region.loopMode===Ls.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(As.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(As.Sustain,e)}render(e,t,s,i,a){if(!this.region)return;let r=this.region,n=r.samples,o=0,h=e.outputMode===Ms.StereoUnweaved?i:-1,l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,d=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),c=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,m=r.end,f=g+1,y=this.sourceSamplePosition,b=new ca(this.lowPass),S=0!==r.modLfoToFilterFc||0!==r.modEnvToFilterFc,_=0,w=0,B=0,k=0,T=0!==r.modLfoToPitch||0!==r.modEnvToPitch||0!==r.vibLfoToPitch,x=0,N=0,v=0,P=0,C=0!==r.modLfoToVolume,E=0,F=0;for(S?(_=e.outSampleRate,w=r.initialFilterFc,B=r.modLfoToFilterFc,k=r.modEnvToFilterFc):(_=0,w=0,B=0,k=0),T?(x=0,N=r.modLfoToPitch,v=r.vibLfoToPitch,P=r.modEnvToPitch):(x=na.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,N=0,v=0,P=0),C?F=.1*r.modLfoToVolume:(E=na.decibelsToGain(this.noteGainDb),F=0);i>0;){let r,D,L=0,M=i>ua.RenderEffectSampleBlock?ua.RenderEffectSampleBlock:i;if(i-=M,S){let e=w+this.modLfo.level*B+this.modEnv.level*k;b.active=e<=13500,b.active&&b.setup(na.cents2Hertz(e)/_)}switch(T&&(x=na.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*N+this.vibLfo.level*v+this.modEnv.level*P))*this.pitchOutputFactor),C&&(E=na.decibelsToGain(this.noteGainDb+this.modLfo.level*F)),r=E*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(M,e.outSampleRate),l&&this.modEnv.process(M,e.outSampleRate),d&&this.modLfo.process(M),c&&this.vibLfo.process(M),e.outputMode){case Ms.StereoInterleaved:for(D=r*this.panFactorLeft,L=r*this.panFactorRight;M-- >0&&y<m;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*D,o++,t[s+o]+=r*L,o++,y+=x,y>=f&&u&&(y-=g-p+1)}break;case Ms.StereoUnweaved:for(D=r*this.panFactorLeft,L=r*this.panFactorRight;M-- >0&&y<m;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*D,o++,t[s+h]+=r*L,h++,y+=x,y>=f&&u&&(y-=g-p+1)}break;case Ms.Mono:for(;M-- >0&&y<m;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,h=n[e]*(1-a)+n[i]*a;b.active&&(h=b.process(h)),t[s+o]=h*r,o++,y+=x,y>=f&&u&&(y-=g-p+1)}}if(y>=m||this.ampEnv.segment===As.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}ua.RenderEffectSampleBlock=Re.MicroBufferSize;class pa{constructor(){this._items=[],this._position=0,this.isEmpty=!0}clear(){this._items=[],this._position=0,this.isEmpty=!0}enqueue(e){this.isEmpty=!1,this._items.push(e)}peek(){return this._items[this._position]}dequeue(){const e=this._items[this._position];return this._position++,this._position>=this._items.length/2&&(this._items=this._items.slice(this._position),this._position=0),this.isEmpty=0==this._items.length,e}toArray(){const e=this._items.slice(this._position);return e.reverse(),e}}!function(e){e[e.BankSelectCoarse=0]="BankSelectCoarse",e[e.ModulationCoarse=1]="ModulationCoarse",e[e.DataEntryCoarse=6]="DataEntryCoarse",e[e.VolumeCoarse=7]="VolumeCoarse",e[e.PanCoarse=10]="PanCoarse",e[e.ExpressionControllerCoarse=11]="ExpressionControllerCoarse",e[e.BankSelectFine=32]="BankSelectFine",e[e.ModulationFine=33]="ModulationFine",e[e.DataEntryFine=38]="DataEntryFine",e[e.VolumeFine=39]="VolumeFine",e[e.PanFine=42]="PanFine",e[e.ExpressionControllerFine=43]="ExpressionControllerFine",e[e.HoldPedal=64]="HoldPedal",e[e.LegatoPedal=68]="LegatoPedal",e[e.NonRegisteredParameterFine=98]="NonRegisteredParameterFine",e[e.NonRegisteredParameterCourse=99]="NonRegisteredParameterCourse",e[e.RegisteredParameterFine=100]="RegisteredParameterFine",e[e.RegisteredParameterCourse=101]="RegisteredParameterCourse",e[e.AllSoundOff=120]="AllSoundOff",e[e.ResetControllers=121]="ResetControllers",e[e.AllNotesOff=123]="AllNotesOff"}(Os||(Os={}));class ga{constructor(e){this._midiEventQueue=new pa,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this._transpositionPitches=new Map,this._liveTranspositionPitches=new Map,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=Ms.StereoInterleaved,this.outSampleRate=0,this.globalGainDb=0,this.outSampleRate=e}synthesize(e,t,s){return this.fillWorkingBuffer(e,t,s)}synthesizeSilent(e){this.fillWorkingBuffer(null,0,e)}channelGetMixVolume(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].mixVolume:1}channelSetMixVolume(e,t){let s=this.channelInit(e);for(let s of this._voices)s.playingChannel===e&&-1!==s.playingPreset&&(s.mixVolume=t);s.mixVolume=t}channelSetMute(e,t){t?this._mutedChannels.set(e,!0):this._mutedChannels.delete(e)}channelSetSolo(e,t){t?this._soloChannels.set(e,!0):this._soloChannels.delete(e),this._isAnySolo=this._soloChannels.size>0}resetChannelStates(){this._mutedChannels=new Map,this._soloChannels=new Map,this._liveTranspositionPitches=new Map,this.applyTranspositionPitches(new Map),this._isAnySolo=!1}setChannelTranspositionPitch(e,t){let s=0;this._liveTranspositionPitches.has(e)&&(s=this._liveTranspositionPitches.get(e)),0===t?this._liveTranspositionPitches.delete(e):this._liveTranspositionPitches.set(e,t);for(const i of this._voices)if(i.playingChannel===e&&9!==i.playingChannel){let e=0;e-=s,e+=t,i.playingKey+=e,this._channels&&i.updatePitchRatio(this._channels.channelList[i.playingChannel],this.outSampleRate)}}applyTranspositionPitches(e){const t=this._transpositionPitches;for(const s of this._voices)if(s.playingChannel>=0&&9!==s.playingChannel){let i=0;t.has(s.playingChannel)&&(i-=t.get(s.playingChannel)),e.has(s.playingChannel)&&(i+=e.get(s.playingChannel)),s.playingKey+=i,this._channels&&s.updatePitchRatio(this._channels.channelList[s.playingChannel],this.outSampleRate)}this._transpositionPitches=e}dispatchEvent(e){this._midiEventQueue.enqueue(e)}fillWorkingBuffer(e,t,s){const i=this._isAnySolo,a=[];for(;!this._midiEventQueue.isEmpty;){let e=this._midiEventQueue.dequeue();e.isMetronome&&this.metronomeVolume>0?(this.channelNoteOff(Re.MetronomeChannel,Re.MetronomeKey),this.channelNoteOn(Re.MetronomeChannel,Re.MetronomeKey,95/127)):e.event&&this.processMidiMessage(e.event),a.push(e)}for(const a of this._voices)if(-1!==a.playingPreset){const r=a.playingChannel,n=this._mutedChannels.has(r)||i&&r!=Re.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,s,n):a.kill()}return a}processMidiMessage(e){re.debug("Midi","Processing Midi message "+je[e.type]+"/"+e.tick);switch(e.type){case je.TimeSignature:const t=e;this.timeSignatureNumerator=t.numerator,this.timeSignatureDenominator=Math.pow(2,t.denominatorIndex);break;case je.NoteOn:const s=e;this.channelNoteOn(s.channel,s.noteKey,s.noteVelocity/127);break;case je.NoteOff:const i=e;this.channelNoteOff(i.channel,i.noteKey);break;case je.ControlChange:const a=e;this.channelMidiControl(a.channel,a.controller,a.value);break;case je.ProgramChange:const r=e;this.channelSetPresetNumber(r.channel,r.program,9===r.channel);break;case je.TempoChange:const n=e;this.currentTempo=6e7/n.microSecondsPerQuarterNote;break;case je.PitchBend:const o=e;this.channelSetPitchWheel(o.channel,o.value);break;case je.PerNotePitchBend:const h=e;let l=h.value;l=l*Re.MaxPitchWheel/Re.MaxPitchWheel20,this.channelSetPerNotePitchWheel(h.channel,h.noteKey,l)}}get metronomeVolume(){return this.channelGetMixVolume(Re.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Re.MetronomeChannel,e),e>0&&(this.channelSetVolume(Re.MetronomeChannel,1),this.channelSetPresetNumber(Re.MetronomeChannel,0,!0))}get masterVolume(){return na.decibelsToGain(this.globalGainDb)}set masterVolume(e){var t=na.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<As.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<As.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 ua;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-na.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!==Ls.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(na.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>=As.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>=As.Release)||r.end(this.outSampleRate)}bankNoteOff(e,t,s){const i=this.getPresetIndex(e,t);return-1!==i&&(this.noteOff(i,s),!0)}noteOffAll(e){for(const t of this._voices)-1!==t.playingPreset&&(e?t.endQuick(this.outSampleRate):t.ampEnv.segment<As.Release&&t.end(this.outSampleRate))}get activeVoiceCount(){let e=0;for(const t of this._voices)-1!==t.playingPreset&&e++;return e}channelInit(e){if(this._channels&&e<this._channels.channelList.length)return this._channels.channelList[e];this._channels||(this._channels=new aa);for(let t=this._channels.channelList.length;t<=e;t++){let e=new ia;e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0,e.mixVolume=1,this._channels.channelList.push(e)}return this._channels.channelList[e]}getPresetIndex(e,t){if(!this.presets)return-1;for(let s=this.presets.length-1;s>=0;s--){let i=this.presets[s];if(i.presetNumber===t&&i.bank===e)return s}return-1}getPresetName(e){return this.presets?e<0||e>=this.presets.length?null:this.presets[e].name:null}bankGetPresetName(e,t){return this.getPresetName(this.getPresetIndex(e,t))}channelNoteOn(e,t,s){!this._channels||e>this._channels.channelList.length||(this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e)),this._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,s))}channelNoteOff(e,t){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e));const s=[];let i=null,a=null;for(const r of this._voices)-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=As.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>=As.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<As.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<As.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=Ie.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=Ie.int32ToUint16(t)}channelSetBankPreset(e,t,s){const i=this.channelInit(e),a=this.getPresetIndex(t,s);return-1!==a&&(i.presetIndex=Ie.int32ToUint16(a),i.bank=Ie.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=na.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=Ie.int32ToUint16(t),this.channelApplyPitch(e,s))}channelSetPerNotePitchWheel(e,t,s){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e));const i=this.channelInit(e);i.perNotePitchWheel.has(t)&&i.perNotePitchWheel.get(t)===s||(i.perNotePitchWheel.set(t,s),this.channelApplyPitch(e,i,t))}channelApplyPitch(e,t,s=-1){for(const i of this._voices)i.playingChannel!==e||-1===i.playingPreset||-1!=s&&i.playingKey!==s||i.updatePitchRatio(t,this.outSampleRate)}channelSetPitchRange(e,t){const s=this.channelInit(e);s.pitchRange!==t&&(s.pitchRange=t,8192!==s.pitchWheel&&this.channelApplyPitch(e,s))}channelSetTuning(e,t){const s=this.channelInit(e);s.tuning!==t&&(s.tuning=t,this.channelApplyPitch(e,s))}channelMidiControl(e,t,s){let i=this.channelInit(e);switch(t){case Os.DataEntryFine:return i.midiData=Ie.int32ToUint16(16256&i.midiData|s),void(0===i.midiRpn?this.channelSetPitchRange(e,(i.midiData>>7)+.01*(127&i.midiData)):1===i.midiRpn?this.channelSetTuning(e,(0|i.tuning)+(i.midiData-8192)/8192):2===i.midiRpn&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Os.VolumeCoarse:return i.midiVolume=Ie.int32ToUint16(127&i.midiVolume|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.VolumeFine:return i.midiVolume=Ie.int32ToUint16(16256&i.midiVolume|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.ExpressionControllerCoarse:return i.midiExpression=Ie.int32ToUint16(127&i.midiExpression|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.ExpressionControllerFine:return i.midiExpression=Ie.int32ToUint16(16256&i.midiExpression|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.PanCoarse:return i.midiPan=Ie.int32ToUint16(127&i.midiPan|s<<7),void this.channelSetPan(e,i.midiPan/16383);case Os.PanFine:return i.midiPan=Ie.int32ToUint16(16256&i.midiPan|s),void this.channelSetPan(e,i.midiPan/16383);case Os.DataEntryCoarse:return i.midiData=Ie.int32ToUint16(127&i.midiData|s<<7),void(0===i.midiRpn?this.channelSetPitchRange(e,(i.midiData>>7)+.01*(127&i.midiData)):1===i.midiRpn?this.channelSetTuning(e,(0|i.tuning)+(i.midiData-8192)/8192):2===i.midiRpn&&t===Os.DataEntryCoarse&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Os.BankSelectCoarse:return void(i.bank=Ie.int32ToUint16(32768|s));case Os.BankSelectFine:return void(i.bank=Ie.int32ToUint16((32768&i.bank?(127&i.bank)<<7:0)|s));case Os.RegisteredParameterCourse:return void(i.midiRpn=Ie.int32ToUint16(127&(65535===i.midiRpn?0:i.midiRpn)|s<<7));case Os.RegisteredParameterFine:return void(i.midiRpn=Ie.int32ToUint16(16256&(65535===i.midiRpn?0:i.midiRpn)|s));case Os.NonRegisteredParameterFine:case Os.NonRegisteredParameterCourse:return void(i.midiRpn=65535);case Os.AllSoundOff:return void this.channelSoundsOffAll(e);case Os.AllNotesOff:return void this.channelNoteOffAll(e);case Os.ResetControllers:return i.midiVolume=16383,i.midiExpression=16383,i.midiPan=8192,i.bank=0,this.channelSetVolume(e,1),this.channelSetPan(e,.5),void this.channelSetPitchRange(e,2)}}channelGetPresetIndex(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].presetIndex:0}channelGetPresetBank(e){return this._channels&&e<this._channels.channelList.length?32767&this._channels.channelList[e].bank:0}channelGetPan(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].panOffset-.5:.5}channelGetVolume(e){return this._channels&&e<this._channels.channelList.length?na.decibelsToGain(this._channels.channelList[e].gainDb):1}channelGetPitchWheel(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchWheel:8192}channelGetPitchRange(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchRange:2}channelGetTuning(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].tuning:0}resetPresets(){this.presets=[]}loadPresets(e,t,s,i){const a=[];for(let i=0;i<e.phdrs.length-1;i++){const r=e.phdrs[i];let n=0;const o=new ra;a.push(o),o.name=r.presetName,o.bank=r.bank,o.presetNumber=r.preset;let h=0;for(let t=r.presetBagNdx;t<e.phdrs[i+1].presetBagNdx;t++){let s=0,i=127,a=0,r=127;for(let n=e.pbags[t].genNdx;n<e.pbags[t+1].genNdx;n++){let t=e.pgens[n];if(t.genOper!==$i.GenKeyRange)if(t.genOper!==$i.GenVelRange){if(t.genOper===$i.GenInstrument&&!(t.genAmount.wordAmount>=e.insts.length))for(let n=e.insts[t.genAmount.wordAmount].instBagNdx;n<e.insts[t.genAmount.wordAmount+1].instBagNdx;n++){let t=0,o=127,l=0,d=127;for(let c=e.ibags[n].instGenNdx;c<e.ibags[n+1].instGenNdx;c++){let n=e.igens[c];n.genOper!==$i.GenKeyRange?n.genOper!==$i.GenVelRange?53===n.genOper&&o>=s&&t<=i&&d>=a&&l<=r&&h++:(l=n.genAmount.lowByteAmount,d=n.genAmount.highByteAmount):(t=n.genAmount.lowByteAmount,o=n.genAmount.highByteAmount)}}}else a=t.genAmount.lowByteAmount,r=t.genAmount.highByteAmount;else s=t.genAmount.lowByteAmount,i=t.genAmount.highByteAmount}}o.regions=new Array(h);let l=new ha;l.clear(!0);for(let a=r.presetBagNdx;a<e.phdrs[i+1].presetBagNdx;a++){const i=e.pbags[a],h=new ha(l);let d=!1;for(let l=i.genNdx;l<e.pbags[a+1].genNdx;l++){const i=e.pgens[l];if(i.genOper===$i.GenInstrument){let a=i.genAmount.wordAmount;if(a>=e.insts.length)continue;let l=new ha;l.clear(!1);let c=e.insts[a];for(let i=c.instBagNdx;i<e.insts[a+1].instBagNdx;i++){let a=e.ibags[i],d=new ha(l),u=!1;for(let l=a.instGenNdx;l<e.ibags[i+1].instGenNdx;l++){let i=e.igens[l];if(i.genOper===$i.GenSampleId){if(d.hiKey<h.loKey||d.loKey>h.hiKey)continue;if(d.hiVel<h.loVel||d.loVel>h.hiVel)continue;h.loKey>d.loKey&&(d.loKey=h.loKey),h.hiKey<d.hiKey&&(d.hiKey=h.hiKey),h.loVel>d.loVel&&(d.loVel=h.loVel),h.hiVel<d.hiVel&&(d.hiVel=h.hiVel),d.offset+=h.offset,d.end+=h.end,d.loopStart+=h.loopStart,d.loopEnd+=h.loopEnd,d.transpose+=h.transpose,d.tune+=h.tune,d.pitchKeyTrack+=h.pitchKeyTrack,d.attenuation+=h.attenuation,d.pan+=h.pan,d.ampEnv.delay+=h.ampEnv.delay,d.ampEnv.attack+=h.ampEnv.attack,d.ampEnv.hold+=h.ampEnv.hold,d.ampEnv.decay+=h.ampEnv.decay,d.ampEnv.sustain+=h.ampEnv.sustain,d.ampEnv.release+=h.ampEnv.release,d.modEnv.delay+=h.modEnv.delay,d.modEnv.attack+=h.modEnv.attack,d.modEnv.hold+=h.modEnv.hold,d.modEnv.decay+=h.modEnv.decay,d.modEnv.sustain+=h.modEnv.sustain,d.modEnv.release+=h.modEnv.release,d.initialFilterQ+=h.initialFilterQ,d.initialFilterFc+=h.initialFilterFc,d.modEnvToPitch+=h.modEnvToPitch,d.modEnvToFilterFc+=h.modEnvToFilterFc,d.delayModLFO+=h.delayModLFO,d.freqModLFO+=h.freqModLFO,d.modLfoToPitch+=h.modLfoToPitch,d.modLfoToFilterFc+=h.modLfoToFilterFc,d.modLfoToVolume+=h.modLfoToVolume,d.delayVibLFO+=h.delayVibLFO,d.freqVibLFO+=h.freqVibLFO,d.vibLfoToPitch+=h.vibLfoToPitch,d.ampEnv.envToSecs(!0),d.modEnv.envToSecs(!1),d.delayModLFO=d.delayModLFO<-11950?0:na.timecents2Secs(d.delayModLFO),d.delayVibLFO=d.delayVibLFO<-11950?0:na.timecents2Secs(d.delayVibLFO),d.pan<-.5?d.pan=-.5:d.pan>.5&&(d.pan=.5),(d.initialFilterQ<1500||d.initialFilterQ>13500)&&(d.initialFilterQ=0);let a=e.sHdrs[i.genAmount.wordAmount];d.offset+=a.start,d.end+=a.end,d.loopStart+=a.startLoop,d.loopEnd+=a.endLoop,a.endLoop>0&&(d.loopEnd-=1),-1===d.pitchKeyCenter&&(d.pitchKeyCenter=a.originalPitch),d.tune+=a.pitchCorrection,d.sampleRate=a.sampleRate;const l=r.bank==Re.PercussionBank;if(l&&ga.setContainsRange(s,d.loKey,d.hiKey)||!l&&t.has(r.preset))if(1&a.sampleType){re.debug("AlphaSynth",`Loading of used sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`);!!(16&a.sampleType)?d.samples=e.decodeSamples(a.start,a.end,!0):(d.samples=e.decodeSamples(2*d.offset,2*d.end,!1),d.loopStart>0&&(d.loopStart-=d.offset),d.loopEnd>0&&(d.loopEnd-=d.offset)),d.offset=0,d.end=d.samples.length-1}else re.warning("AlphaSynth",`Skipping load of unsupported sample ${a.sampleName} for preset ${r.presetName}, sample type ${a.sampleType} is not supported (bank ${o.bank} program ${o.presetNumber})`),d.samples=new Float32Array(0);else re.debug("AlphaSynth",`Skipping load of unused sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`),d.samples=new Float32Array(0);o.regions[n]=new ha(d),n++,u=!0}else d.operator(i.genOper,i.genAmount)}a!==e.ibags[c.instBagNdx]||u||(l=new ha(d))}d=!0}else h.operator(i.genOper,i.genAmount)}i!==e.pbags[r.presetBagNdx]||d||(l=h)}}if(i&&this.presets)for(const e of a)this.presets.push(e);else this.presets=a}static setContainsRange(e,t,s){for(let i=t;i<=s;i++)if(e.has(i))return!0;return!1}hasSamplesForProgram(e){const t=this.presets;if(!t)return!1;for(const s of t)if(s.presetNumber===e)for(const e of s.regions)if(e.samples.length>0)return!0;return!1}hasSamplesForPercussion(e){const t=this.presets;if(!t)return!1;for(const s of t)if(s.bank==Re.PercussionBank)for(const t of s.regions)if(t.loKey>=e&&t.hiKey<=e&&t.samples.length>0)return!0;return!1}}class ma{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 fa{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 ya{constructor(e){this.events=e}}class ba{constructor(e){this.playbackRange=e}}class Sa{get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return re.logLevel}set logLevel(e){re.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Re.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Re.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Re.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=le.clamp(e,Re.MinPlaybackSpeed,Re.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){re.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 ba(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){re.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 pa,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this._synthStopping=!1,this.isReady=!1,this.state=Es.Paused,this._loadedSoundFonts=[],this.ready=new ma,this.readyForPlayback=new ma,this.finished=new ma,this.soundFontLoaded=new ma,this.soundFontLoadFailed=new fa,this.midiLoaded=new fa,this.midiLoadFailed=new fa,this.stateChanged=new fa,this.positionChanged=new fa,this.midiEventsPlayed=new fa,this.playbackRangeChanged=new fa,re.debug("AlphaSynth","Initializing player"),this.state=Es.Paused,re.debug("AlphaSynth","Creating output"),this.output=e,re.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new ga(this.output.sampleRate),this._sequencer=new li(this._synthesizer),re.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this.state==Es.Playing&&(!this._sequencer.isFinished||this._synthesizer.activeVoiceCount>0)){let e=new Float32Array(Re.MicroBufferSize*Re.MicroBufferCount*Re.AudioChannels),t=0;for(let s=0;s<Re.MicroBufferCount;s++){this._sequencer.fillMidiEventQueue();const s=this._synthesizer.synthesize(e,t,Re.MicroBufferSize);t+=Re.MicroBufferSize*Re.AudioChannels;for(const e of s)this._midiEventsPlayedFilter.has(e.event.type)&&this._playedEventsQueue.enqueue(e);if(this._sequencer.isFinished)break}t<e.length&&(e=e.subarray(0,t)),this._notPlayedSamples+=e.length,this.output.addSamples(e)}else{let e=new Float32Array(0);this.output.addSamples(e)}})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open(t)}play(){return!(this.state!==Es.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(re.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(re.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),re.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this._synthStopping=!1,this.state=Es.Playing,this.stateChanged.trigger(new di(this.state,!1))}pause(){this.state!==Es.Paused&&this._isMidiLoaded&&(re.debug("AlphaSynth","Pausing playback"),this.state=Es.Paused,this.stateChanged.trigger(new di(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===Es.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(re.debug("AlphaSynth","Stopping playback"),this.state=Es.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 di(this.state,!0)))}playOneTimeMidiFile(e){this._sequencer.isPlayingOneTimeMidi?this.stopOneTimeMidi():this.pause(),this._sequencer.loadOneTimeMidi(e),this._synthesizer.noteOffAll(!0),this.updateTimePosition(0,!0),this._notPlayedSamples=0,this.output.resetSamples(),this.output.play()}resetSoundFonts(){this.stop(),this._synthesizer.resetPresets(),this._loadedSoundFonts=[],this._isSoundFontLoaded=!1,this.soundFontLoaded.trigger()}loadSoundFont(e,t){this.pause();let s=Oe.fromBuffer(e);try{re.debug("AlphaSynth","Loading soundfont from bytes");let e=new Ji;e.load(s),t||(this._loadedSoundFonts=[]),this._loadedSoundFonts.push(e),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),re.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){re.error("AlphaSynth","Could not load soundfont from bytes "+e),this.soundFontLoadFailed.trigger(e)}}checkReadyForPlayback(){if(this.isReadyForPlayback){this._synthesizer.setupMetronomeChannel(this.metronomeVolume);const e=this._sequencer.instrumentPrograms,t=this._sequencer.percussionKeys;let s=!1;for(const i of this._loadedSoundFonts)this._synthesizer.loadPresets(i,e,t,s),s=!0;this.readyForPlayback.trigger()}}loadMidiFile(e){this.stop();try{re.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new ci(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),re.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){re.error("AlphaSynth","Could not load midi from model "+e),this.midiLoadFailed.trigger(e)}}applyTranspositionPitches(e){this._synthesizer.applyTranspositionPitches(e)}setChannelTranspositionPitch(e,t){this._synthesizer.setChannelTranspositionPitch(e,t)}setChannelMute(e,t){this._synthesizer.channelSetMute(e,t)}resetChannelStates(){this._synthesizer.resetChannelStates()}setChannelSolo(e,t){this._synthesizer.channelSetSolo(e,t)}setChannelVolume(e,t){t=Math.max(t,Re.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;let t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*Re.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?(re.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(re.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=Es.Paused,this.stopOneTimeMidi()):this.isLooping?(re.debug("AlphaSynth","Finished playback (main looping)"),this.finished.trigger(),this.tickPosition=e,this._synthStopping=!1):this._synthesizer.activeVoiceCount>0?this._synthStopping||(this._synthesizer.noteOffAll(!0),this._synthStopping=!0):(this._synthStopping=!1,re.debug("AlphaSynth","Finished playback (main)"),this.finished.trigger(),this.stop()))}stopOneTimeMidi(){this.output.pause(),this._synthesizer.noteOffAll(!0),this._sequencer.resetOneTimeMidi(),this.timePosition=this._sequencer.currentTime}updateTimePosition(e,t){let s=e;this._timePosition=s;let i=this._sequencer.currentTimePositionToTickPosition(s);this._tickPosition=i;const a=this._sequencer.currentEndTime,r=this._sequencer.currentEndTick;s>a&&(s=a,i=r);const n=this._sequencer.isPlayingMain?"main":this._sequencer.isPlayingCountIn?"count-in":"one-time";if(re.debug("AlphaSynth",`Position changed: (time: ${s}/${a}, tick: ${i}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new ci(s,a,i,r,t)),t)this._playedEventsQueue.clear();else{const e=new pa;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<s;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new ya(e.toArray()))}}hasSamplesForProgram(e){return this._synthesizer.hasSamplesForProgram(e)}hasSamplesForPercussion(e){return this._synthesizer.hasSamplesForPercussion(e)}}class _a{constructor(){this.ready=new ma,this.samplesPlayed=new fa,this.sampleRequest=new ma}get sampleRate(){return _a.preferredSampleRate}open(){re.debug("AlphaSynth","Initializing synth worker"),this._worker=Tl.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 _a.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case _a.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(){}}_a.CmdOutputPrefix="alphaSynth.output.",_a.CmdOutputAddSamples=_a.CmdOutputPrefix+"addSamples",_a.CmdOutputPlay=_a.CmdOutputPrefix+"play",_a.CmdOutputPause=_a.CmdOutputPrefix+"pause",_a.CmdOutputResetSamples=_a.CmdOutputPrefix+"resetSamples",_a.CmdOutputStop=_a.CmdOutputPrefix+"stop",_a.CmdOutputSampleRequest=_a.CmdOutputPrefix+"sampleRequest",_a.CmdOutputSamplesPlayed=_a.CmdOutputPrefix+"samplesPlayed",_a.preferredSampleRate=0;class wa{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new Sa(new _a,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=Tl.globalThis;e.addEventListener("message",(t=>{let s=t.data;if("alphaSynth.initialize"===s.cmd)_a.preferredSampleRate=s.sampleRate,re.logLevel=s.logLevel,Tl.globalThis.alphaSynthWebWorker=new wa(e,s.bufferTimeInMilliseconds)}))}handleMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":re.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(ss.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(ss.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);break;case"alphaSynth.setChannelTranspositionPitch":this._player.setChannelTranspositionPitch(t.channel,t.semitones);break;case"alphaSynth.setChannelSolo":this._player.setChannelSolo(t.channel,t.solo);break;case"alphaSynth.setChannelVolume":this._player.setChannelVolume(t.channel,t.volume);break;case"alphaSynth.resetChannelStates":this._player.resetChannelStates();break;case"alphaSynth.destroy":this._player.destroy(),this._main.postMessage({cmd:"alphaSynth.destroyed"});break;case"alphaSynth.applyTranspositionPitches":this._player.applyTranspositionPitches(new Map(JSON.parse(t.transpositionPitches)))}}onPositionChanged(e){this._main.postMessage({cmd:"alphaSynth.positionChanged",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onPlayerStateChanged(e){this._main.postMessage({cmd:"alphaSynth.playerStateChanged",state:e.state,stopped:e.stopped})}onFinished(){this._main.postMessage({cmd:"alphaSynth.finished"})}onSoundFontLoaded(){this._main.postMessage({cmd:"alphaSynth.soundFontLoaded"})}onSoundFontLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.soundFontLoadFailed",error:this.serializeException(e)})}serializeException(e){let t=JSON.parse(JSON.stringify(e));return e.message&&(t.message=e.message),e.stack&&(t.stack=e.stack),e.constructor&&e.constructor.name&&(t.type=e.constructor.name),t}onMidiLoaded(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onMidiLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",error:this.serializeException(e)})}onReadyForPlayback(){this._main.postMessage({cmd:"alphaSynth.readyForPlayback"})}onMidiEventsPlayed(e){this._main.postMessage({cmd:"alphaSynth.midiEventsPlayed",events:e.events.map(ss.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}!function(e){e[e.Browser=0]="Browser",e[e.NodeJs=1]="NodeJs",e[e.BrowserModule=2]="BrowserModule"}(Rs||(Rs={}));class Ba{constructor(e,t){this.characterWidths=e,this.fontSizeToHeight=t}}class ka{static generateFontLookup(e){if(!ka.FontSizeLookupTables.has(e))if(Tl.isRunningInWorker||Tl.webPlatform==Rs.NodeJs){const t=new Ba(new Uint8Array([8]),1.2);ka.FontSizeLookupTables.set(e,t)}else{let t=document.createElement("canvas").getContext("2d");const s=11;t.font=`${s}px ${e}`;const i=[];let a="";for(let e=ka.ControlChars;e<255;e++){let s=String.fromCharCode(e);a+=s;const r=t.measureText(s);i.push(r.width)}const r=t.measureText(a+"ÄÖÜÁÈ"),n=0-Math.abs(r.fontBoundingBoxAscent),o=0+Math.abs(r.fontBoundingBoxDescent)-n,h=new Ba(new Uint8Array(i),o/s);ka.FontSizeLookupTables.set(e,h)}}static measureString(e,t,s,i,a){let r,n=t[0];for(let e=0;e<t.length;e++)if(ka.FontSizeLookupTables.has(t[e])){n=t[e];break}ka.FontSizeLookupTables.has(n)||ka.generateFontLookup(n),r=ka.FontSizeLookupTables.get(n);let o=1;i===Je.Italic&&(o*=1.1),a===Ye.Bold&&(o*=1.1);let h=0;for(let t=0;t<e.length;t++){let i=Math.min(r.characterWidths.length-1,e.charCodeAt(t)-ka.ControlChars);i>=0&&(h+=r.characterWidths[i]*s/11)}return o*=1.07,new de(h*o,s*r.fontSizeToHeight)}}ka.FontSizeLookupTables=new Map,ka.ControlChars=32;class Ta{constructor(){this.id=le.newGuid(),this.x=0,this.y=0,this.width=0,this.height=0,this.totalWidth=0,this.totalHeight=0,this.firstMasterBarIndex=-1,this.lastMasterBarIndex=-1,this.renderResult=null}}class xa{constructor(){this.beats=[]}addBeat(e){e.barBounds=this,this.beats.push(e),this.masterBarBounds.addBeat(e)}findBeatAtPos(e){let t=null;for(let s of this.beats)if(!t||s.realBounds.x<e)t=s;else if(s.realBounds.x>e)break;return t}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.beats.sort(((e,t)=>e.realBounds.x-t.realBounds.x));for(const t of this.beats)t.finish(e)}}class Na{constructor(){this.onNotesX=0,this.notes=null}addNote(e){this.notes||(this.notes=[]),e.beatBounds=this,this.notes.push(e)}findNoteAtPos(e,t){const s=this.notes;if(!s)return null;for(let i of s){let s=i.noteHeadBounds.y+i.noteHeadBounds.h,a=i.noteHeadBounds.x+i.noteHeadBounds.w;if(i.noteHeadBounds.x<=e&&i.noteHeadBounds.y<=t&&e<=a&&t<=s)return i.note}return null}finish(e=1){if(this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.notes)for(const t of this.notes)t.finish(e)}}class va{constructor(){this.index=0,this.isFirstOfLine=!1,this.bars=[],this.staffSystemBounds=null}get staveGroupBounds(){return this.staffSystemBounds}addBar(e){e.masterBarBounds=this,this.bars.push(e)}findBeatAtPos(e,t){let s=null;for(let t of this.bars){let i=t.findBeatAtPos(e);if(i&&(!s||s.realBounds.x<i.realBounds.x)){const t=Math.abs(i.realBounds.x-e);(!s||t<1e7)&&(s=i)}}return s?s.beat:null}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.lineAlignedBounds.scaleWith(e),this.bars.sort(((e,t)=>e.realBounds.y<t.realBounds.y?-1:e.realBounds.y>t.realBounds.y?1:e.realBounds.x<t.realBounds.x?-1:e.realBounds.x>t.realBounds.x?1:0));for(const t of this.bars)t.finish(e)}addBeat(e){this.staffSystemBounds.boundsLookup.addBeat(e)}}class Pa{finish(e=1){this.noteHeadBounds.scaleWith(e)}}class Ca{constructor(){this.index=0,this.bars=[]}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e);for(let t of this.bars)t.finish(e)}addBar(e){this.boundsLookup.addMasterBar(e),e.staffSystemBounds=this,this.bars.push(e)}findBarAtPos(e){let t=null;for(let s of this.bars)if(!t||s.realBounds.x<e)t=s;else if(e>s.realBounds.x+s.realBounds.w)break;return t}}class Ea{constructor(){this._beatLookup=new Map,this._masterBarLookup=new Map,this._currentStaffSystem=null,this.staffSystems=[],this.isFinished=!1}toJson(){let e={},t=[];e.staffSystems=t;for(let e of this.staffSystems){let s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.bars=[];for(let t of e.bars){let e={};e.lineAlignedBounds=this.boundsToJson(t.lineAlignedBounds),e.visualBounds=this.boundsToJson(t.visualBounds),e.realBounds=this.boundsToJson(t.realBounds),e.index=t.index,e.bars=[];for(let s of t.bars){let t={};t.visualBounds=this.boundsToJson(s.visualBounds),t.realBounds=this.boundsToJson(s.realBounds),t.beats=[];for(let e of s.beats){let s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.onNotesX=e.onNotesX;let i=s;if(i.beatIndex=e.beat.index,i.voiceIndex=e.beat.voice.index,i.barIndex=e.beat.voice.bar.index,i.staffIndex=e.beat.voice.bar.staff.index,i.trackIndex=e.beat.voice.bar.staff.track.index,e.notes){let t=s.notes=[];for(let s of e.notes){let e={};e.index=s.note.index,e.noteHeadBounds=this.boundsToJson(s.noteHeadBounds),t.push(e)}}t.beats.push(s)}e.bars.push(t)}s.bars.push(e)}t.push(s)}return e}static fromJson(e,t){let s=new Ea,i=e.staffSystems;for(let e of i){let i=new Ca;i.visualBounds=Ea.boundsFromJson(e.visualBounds),i.realBounds=Ea.boundsFromJson(e.realBounds),s.addStaffSystem(i);for(let s of e.bars){let e=new va;e.index=s.index,e.isFirstOfLine=s.isFirstOfLine,e.lineAlignedBounds=Ea.boundsFromJson(s.lineAlignedBounds),e.visualBounds=Ea.boundsFromJson(s.visualBounds),e.realBounds=Ea.boundsFromJson(s.realBounds),i.addBar(e);for(let i of s.bars){let s=new xa;s.visualBounds=Ea.boundsFromJson(i.visualBounds),s.realBounds=Ea.boundsFromJson(i.realBounds),e.addBar(s);for(let e of i.beats){let i=new Na;i.visualBounds=Ea.boundsFromJson(e.visualBounds),i.realBounds=Ea.boundsFromJson(e.realBounds),i.onNotesX=e.onNotesX;let a=e;if(i.beat=t.tracks[a.trackIndex].staves[a.staffIndex].bars[a.barIndex].voices[a.voiceIndex].beats[a.beatIndex],e.notes){i.notes=[];for(let t of e.notes){let e=new Pa,s=t;e.note=i.beat.notes[s.index],e.noteHeadBounds=t.noteHeadBounds,i.addNote(e)}}s.addBeat(i)}}}}return s}static boundsFromJson(e){const t=new ds;return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}boundsToJson(e){let t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(e=1){for(let t of this.staffSystems)t.finish(e);this.isFinished=!0}addStaffSystem(e){e.index=this.staffSystems.length,e.boundsLookup=this,this.staffSystems.push(e),this._currentStaffSystem=e}addMasterBar(e){e.staffSystemBounds?this._masterBarLookup.set(e.index,e):(e.staffSystemBounds=this._currentStaffSystem,this._masterBarLookup.set(e.index,e),this._currentStaffSystem.addBar(e))}addBeat(e){this._beatLookup.has(e.beat.id)||this._beatLookup.set(e.beat.id,[]),this._beatLookup.get(e.beat.id)?.push(e)}findMasterBarByIndex(e){return this._masterBarLookup.has(e)?this._masterBarLookup.get(e):null}findMasterBar(e){let t=e.index;return this._masterBarLookup.has(t)?this._masterBarLookup.get(t):null}findBeat(e){const t=this.findBeats(e);return t?t[0]:null}findBeats(e){let t=e.id;return this._beatLookup.has(t)?this._beatLookup.get(t):null}getBeatAtPos(e,t){let s=0,i=this.staffSystems.length-1,a=-1;for(;s<=i;){let e=(i+s)/2|0,r=this.staffSystems[e];if(t>=r.realBounds.y&&t<=r.realBounds.y+r.realBounds.h){a=e;break}t<r.realBounds.y?i=e-1:s=e+1}if(-1===a)return null;let r=this.staffSystems[a].findBarAtPos(e);return r?r.findBeatAtPos(e,t):null}getNoteAtPos(e,t,s){const i=this.findBeats(e);if(i)for(const e of i){const i=e.findNoteAtPos(t,s);if(i)return i}return null}}class Fa{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 fa,this.renderFinished=new fa,this.partialRenderFinished=new fa,this.partialLayoutFinished=new fa,this.postRenderFinished=new ma,this.error=new fa,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=Tl.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=Tl.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?(re.debug("Rendering","Request render of lazy partial "+e),t.renderLazyPartial(e)):re.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 Ea,this.recreateCanvas(),this.canvas.lineWidth=1,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){re.debug("Rendering","Rendering "+this.tracks.length+" tracks");for(let e=0;e<this.tracks.length;e++){let t=this.tracks[e];re.debug("Rendering","Track "+e+": "+t.name)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),re.debug("Rendering","Rendering finished")}else re.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),re.debug("Rendering","Clearing finished");else re.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(re.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(re.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new Ea,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):re.debug("Rendering","Current layout does not support dynamic resizing, nothing was done",null),re.debug("Rendering","Resize finished")}layoutAndRender(){re.debug("Rendering","Rendering at scale "+this.settings.display.scale+" with layout "+this.layout.name,null),this.layout.layoutAndRender(),this._renderedTracks=this.tracks,this.onRenderFinished(),this.postRenderFinished.trigger()}onRenderFinished(){this.boundsLookup?.finish(this.settings.display.scale);const e=new Ta;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}class Da{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){Tl.globalThis.alphaTabWebWorker=new Da(Tl.globalThis)}handleMessage(e){let t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":let e=ss.jsObjectToSettings(t.settings);re.logLevel=e.core.logLevel,this._renderer=new Fa(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:ss.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(s,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(!(e instanceof Map)){const t=e;e=new Map;for(const s in t)e.set(s,t[s])}if(e){ka.FontSizeLookupTables||(ka.FontSizeLookupTables=new Map);for(let[t,s]of e)ka.FontSizeLookupTables.set(t,s)}}updateSettings(e){At.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){re.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class La{constructor(){this._canvas=null,this._color=new Ce(0,0,0,255),this._font=new rt("Arial",10,Je.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 rt(s,parseFloat(t.fontSize),Je.Plain),this._measureCanvas=document.createElement("canvas"),this._measureCanvas.width=10,this._measureCanvas.height=10,this._measureCanvas.style.width="10px",this._measureCanvas.style.height="10px",this._measureContext=this._measureCanvas.getContext("2d"),this._measureContext.textBaseline="hanging"}destroy(){}onRenderFinished(){return null}beginRender(e,t){const s=this.settings.display.scale;this._canvas=document.createElement("canvas"),this._canvas.width=e*Tl.HighDpiFactor|0,this._canvas.height=t*Tl.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(Tl.HighDpiFactor*s,Tl.HighDpiFactor*s),this._context.lineWidth=this._lineWidth}endRender(){let e=this._canvas;return this._canvas=null,e}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._context.strokeStyle=e.rgba,this._context.fillStyle=e.rgba)}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._context&&(this._context.lineWidth=e)}fillRect(e,t,s,i){s>0&&this._context.fillRect(0|e,0|t,s,i)}strokeRect(e,t,s,i){const a=this.lineWidth%2==0?0:.5;this._context.strokeRect((0|e)+a,(0|t)+a,s,i)}beginPath(){this._context.beginPath()}closePath(){this._context.closePath()}moveTo(e,t){this._context.moveTo(e,t)}lineTo(e,t){this._context.lineTo(e,t)}quadraticCurveTo(e,t,s,i){this._context.quadraticCurveTo(e,t,s,i)}bezierCurveTo(e,t,s,i,a,r){this._context.bezierCurveTo(e,t,s,i,a,r)}fillCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.fill()}strokeCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.stroke()}fill(){this._context.fill(),this._context.beginPath()}stroke(){this._context.stroke(),this._context.beginPath()}get font(){return this._font}set font(e){this._font=e,this._context&&(this._context.font=e.toCssString(1)),this._measureContext.font=e.toCssString(1)}get textAlign(){switch(this._context.textAlign){case"left":default:return D.Left;case"center":return D.Center;case"right":return D.Right}}set textAlign(e){switch(e){case D.Left:this._context.textAlign="left";break;case D.Center:this._context.textAlign="center";break;case D.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return L.Top;case"middle":return L.Middle;case"bottom":return L.Bottom}}set textBaseline(e){switch(e){case L.Top:this._context.textBaseline="hanging";break;case L.Middle:this._context.textBaseline="middle";break;case L.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,s){this._context.fillText(e,t,s)}measureText(e){const t=this._measureContext.measureText(e);return new de(t.width,t.actualBoundingBoxDescent-t.actualBoundingBoxAscent)}fillMusicFontSymbol(e,t,s,i,a=!1){i!==F.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!==F.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){let r=this._context.textAlign,n=this._context.textBaseline,o=this._context.font;this._context.font=this._musicFont.toCssString(s),this._context.textBaseline="middle",this._context.textAlign=a?"center":"left",this._context.fillText(i,e,t),this._context.textBaseline=n,this._context.font=o,this._context.textAlign=r}beginRotate(e,t,s){this._context.save(),this._context.translate(e,t),this._context.rotate(s*Math.PI/180)}endRotate(){this._context.restore()}}class Ma{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 lt(0,e,t,i,48,8))}addRest(e,t,s){this._smf1Mode||this._midiFile.addEvent(new ut(e,t,s))}addNote(e,t,s,i,a,r){this._midiFile.addEvent(new gt(e,t,r,Ma.fixValue(i),Ma.fixValue(a))),this._midiFile.addEvent(new mt(e,t+s,r,Ma.fixValue(i),Ma.fixValue(a)))}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,s,i,a){this._midiFile.addEvent(new ft(e,t,s,i,Ma.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 bt(e,s))}addBend(e,t,s,i){i=i>=Re.MaxPitchWheel?Re.MaxPitchWheel:Math.floor(i),this._midiFile.addEvent(new St(e,t,s,i))}addNoteBend(e,t,s,i,a){this._smf1Mode?this.addBend(e,t,s,a):(a=a*Re.MaxPitchWheel20/Re.MaxPitchWheel,this._midiFile.addEvent(new _t(e,t,s,i,a)))}finishTrack(e,t){this._midiFile.format!=qe.MultiTrack&&0!=e||this._midiFile.addEvent(new wt(e,t))}}class Ia{constructor(e,t){this.closingIndex=0,this.group=e,this.opening=t,e.closings=e.closings.sort(((e,t)=>e.index-t.index)),this.iterations=e.closings.map((e=>0))}}!function(e){e[e.PlayingNormally=0]="PlayingNormally",e[e.DirectionJumped=1]="DirectionJumped",e[e.DirectionJumpedAlCoda=2]="DirectionJumpedAlCoda",e[e.DirectionJumpedAlDoubleCoda=3]="DirectionJumpedAlDoubleCoda",e[e.DirectionJumpedAlFine=4]="DirectionJumpedAlFine"}(Vs||(Vs={}));class Aa{get finished(){return this.index>=this._score.masterBars.length}constructor(e){this._repeatStack=[],this._groupsOnStack=new Set,this._previousAlternateEndings=0,this._state=Vs.PlayingNormally,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}processCurrent(){const e=this._score.masterBars[this.index];if(this._state===Vs.PlayingNormally){let t=e.alternateEndings;if(0===t&&(t=this._previousAlternateEndings),e===e.repeatGroup.opening&&e.repeatGroup.isClosed&&!this._groupsOnStack.has(e.repeatGroup)){const s=new Ia(e.repeatGroup,e);this._repeatStack.push(s),this._groupsOnStack.add(e.repeatGroup),this._previousAlternateEndings=0,t=e.alternateEndings}if(0===this._repeatStack.length||0===t)this.shouldPlay=!0;else{const e=this._repeatStack[this._repeatStack.length-1],s=e.iterations[e.closingIndex];this._previousAlternateEndings=t,this.shouldPlay=!!(t&1<<s)}}else this.shouldPlay=!0;this.shouldPlay&&(this.currentTick+=e.calculateDuration())}moveNext(){this.moveNextWithDirections()||this.moveNextWithNormalRepeats()}resetRepeats(){this._groupsOnStack.clear(),this._previousAlternateEndings=0,this._repeatStack=[]}handleDaCapo(e,t,s){return!!e.has(t)&&(this.index=0,this._state=s,this.resetRepeats(),!0)}handleDalSegno(e,t,s,i){if(e.has(t)){const e=this.findJumpTarget(i,this.index,!0);return-1!==e&&(this.index=e,this._state=s,this.resetRepeats(),!0)}return!1}handleDaCoda(e,t,s){if(e.has(t)){const e=this.findJumpTarget(s,this.index,!1);return-1===e?(this.index++,!0):(this.index=e,this._state=Vs.PlayingNormally,!0)}return!1}moveNextWithDirections(){const e=this._score.masterBars[this.index],t=null!==e.directions&&e.directions.size>0;if(this._state===Vs.PlayingNormally&&!t)return!1;if(!t)return this.index++,!0;switch(this._state){case Vs.PlayingNormally:return!!(this.handleDaCapo(e.directions,Ve.JumpDaCapo,Vs.DirectionJumped)||this.handleDaCapo(e.directions,Ve.JumpDaCapoAlCoda,Vs.DirectionJumpedAlCoda)||this.handleDaCapo(e.directions,Ve.JumpDaCapoAlDoubleCoda,Vs.DirectionJumpedAlDoubleCoda)||this.handleDaCapo(e.directions,Ve.JumpDaCapoAlFine,Vs.DirectionJumpedAlFine))||(!!(this.handleDalSegno(e.directions,Ve.JumpDalSegno,Vs.DirectionJumped,Ve.TargetSegno)||this.handleDalSegno(e.directions,Ve.JumpDalSegnoAlCoda,Vs.DirectionJumpedAlCoda,Ve.TargetSegno)||this.handleDalSegno(e.directions,Ve.JumpDalSegnoAlDoubleCoda,Vs.DirectionJumpedAlDoubleCoda,Ve.TargetSegno)||this.handleDalSegno(e.directions,Ve.JumpDalSegnoAlFine,Vs.DirectionJumpedAlFine,Ve.TargetSegno))||!!(this.handleDalSegno(e.directions,Ve.JumpDalSegnoSegno,Vs.DirectionJumped,Ve.TargetSegnoSegno)||this.handleDalSegno(e.directions,Ve.JumpDalSegnoSegnoAlCoda,Vs.DirectionJumpedAlCoda,Ve.TargetSegnoSegno)||this.handleDalSegno(e.directions,Ve.JumpDalSegnoSegnoAlDoubleCoda,Vs.DirectionJumpedAlDoubleCoda,Ve.TargetSegnoSegno)||this.handleDalSegno(e.directions,Ve.JumpDalSegnoSegnoAlFine,Vs.DirectionJumpedAlFine,Ve.TargetSegnoSegno)));case Vs.DirectionJumped:return this.index++,!0;case Vs.DirectionJumpedAlCoda:return this.handleDaCoda(e.directions,Ve.JumpDaCoda,Ve.TargetCoda)||this.index++,!0;case Vs.DirectionJumpedAlDoubleCoda:return this.handleDaCoda(e.directions,Ve.JumpDaDoubleCoda,Ve.TargetDoubleCoda)||this.index++,!0;case Vs.DirectionJumpedAlFine:return e.directions.has(Ve.TargetFine)?(this.index=this._score.masterBars.length,!0):(this.index++,!0)}return!0}findJumpTarget(e,t,s){if(s){let s=this.findJumpTargetBackwards(e,t);return-1===s&&(s=this.findJumpTargetForwards(e,t)),s}{let s=this.findJumpTargetForwards(e,t);return-1===s&&(s=this.findJumpTargetBackwards(e,t)),s}}findJumpTargetForwards(e,t){let s=t;for(;s<this._score.masterBars.length;){const t=this._score.masterBars[s].directions;if(t&&t.has(e))return s;s++}return-1}findJumpTargetBackwards(e,t){let s=t;for(;s>=0;){const t=this._score.masterBars[s].directions;if(t&&t.has(e))return s;s--}return-1}moveNextWithNormalRepeats(){const e=this._score.masterBars[this.index].repeatCount-1;if(this._repeatStack.length>0&&e>0){const t=this._repeatStack[this._repeatStack.length-1];if(t.iterations[t.closingIndex]<e){this.index=t.opening.index,t.iterations[t.closingIndex]++;for(let e=0;e<t.closingIndex;e++)t.iterations[e]=0;t.closingIndex=0,this._previousAlternateEndings=0}else t.closingIndex<t.group.closings.length-1?(t.closingIndex++,this.index++):(this._repeatStack.pop(),this._groupsOnStack.delete(t.group),this.index++)}else this.index++}}class Oa{constructor(e,t){this.beat=e,this.playbackStart=t}}class Ra{get duration(){return this.end-this.start}constructor(e,t){this._highlightedBeats=new Map,this.highlightedBeats=[],this.nextBeat=null,this.previousBeat=null,this.start=e,this.end=t}highlightBeat(e,t){e.isEmpty&&!e.voice.isEmpty||this._highlightedBeats.has(e.id)||(this._highlightedBeats.set(e.id,!0),this.highlightedBeats.push(new Oa(e,t)))}getVisibleBeatAtStart(e){for(const t of this.highlightedBeats)if(t.playbackStart==this.start&&e.has(t.beat.voice.bar.staff.track.index))return t.beat;return null}}class Va{constructor(e,t){this.tick=e,this.tempo=t}}class Ha{constructor(){this.start=0,this.end=0,this.tempoChanges=[],this.firstBeat=null,this.lastBeat=null,this.nextMasterBar=null,this.previousMasterBar=null}get tempo(){return this.tempoChanges[0].tempo}insertAfter(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.nextBeat=e.nextBeat,t.previousBeat=e,e.nextBeat&&(e.nextBeat.previousBeat=t),e.nextBeat=t,e==this.lastBeat&&(this.lastBeat=t))}insertBefore(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.previousBeat=e.previousBeat,t.nextBeat=e,e.previousBeat&&(e.previousBeat.nextBeat=t),e.previousBeat=t,e==this.firstBeat&&(this.firstBeat=t))}addBeat(e,t,i,a){const r=i+a;if(null==this.firstBeat){const s=new Ra(i,r);s.highlightBeat(e,t),this.insertAfter(this.firstBeat,s)}else if(i>=this.lastBeat.end){const s=new Ra(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 j(s.General,"Error on building lookup, unknown variant")}if(i<a.start)if(r==a.start){const s=new Ra(i,a.start);s.highlightBeat(e,t),this.insertBefore(this.firstBeat,s)}else if(r<a.end){const s=new Ra(i,a.start);s.highlightBeat(e,t),this.insertBefore(a,s);const n=new Ra(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 Ra(i,a.start);s.highlightBeat(e,t),a.highlightBeat(e,t),this.insertBefore(a,s)}else{const s=new Ra(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 Ra(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 Ra(a.start,i);this.insertBefore(a,s);const n=new Ra(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 Ra(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 Ra(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 Ga{get start(){return this.masterBar.start+this.beatLookup.start}get end(){return this.start+this.tickDuration}constructor(e){this.nextBeat=null,this.tickDuration=0,this.duration=0,this.masterBar=e}calculateDuration(){if(1===this.masterBar.tempoChanges.length)this.duration=ee.ticksToMillis(this.tickDuration,this.masterBar.tempoChanges[0].tempo);else{let e=0,t=this.start,s=this.masterBar.tempoChanges[0].tempo;const i=this.end;for(const a of this.masterBar.tempoChanges)if(a.tick<t)s=a.tempo;else{if(a.tick>i)break;e+=ee.ticksToMillis(a.tick-t,s),s=a.tempo,t=a.tick}i>t&&(e+=ee.ticksToMillis(i-t,s)),this.duration=e}}}class Wa{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[]}findBeat(e,t,s=null){let i=null;return s&&(i=this.findBeatFast(e,s,t)),i||(i=this.findBeatSlow(e,s,t,!1)),i}findBeatFast(e,t,s){if(s>=t.start&&s<t.end)return t;if(t.nextBeat&&s>=t.nextBeat.start&&s<t.nextBeat.end){const s=t.nextBeat;return this.fillNextBeat(s,e),s}return null}fillNextBeat(e,t){e.nextBeat=this.findBeatInMasterBar(e.masterBar,e.beatLookup.nextBeat,e.end,t,!1,!0),null==e.nextBeat&&(e.nextBeat=this.findBeatSlow(t,e,e.end,!0)),e.nextBeat&&(e.tickDuration=e.nextBeat.start-e.start,e.calculateDuration()),e.nextBeat||(e.tickDuration=e.masterBar.end-e.start,e.calculateDuration())}findBeatSlow(e,t,s,i){let a=null;if(null!=t&&(t.masterBar.start<=s&&t.masterBar.end>s?a=t.masterBar:t.masterBar.nextMasterBar&&t.masterBar.nextMasterBar.start<=s&&t.masterBar.nextMasterBar.end>s&&(a=t.masterBar.nextMasterBar)),a||(a=this.findMasterBar(s)),!a)return null;for(;a;){if(a.firstBeat){let t=this.findBeatInMasterBar(a,a.firstBeat,s,e,!0,i);if(t)return t}a=a.nextMasterBar}return null}findBeatInMasterBar(e,t,s,i,a,r){if(!t)return null;let n=null,o=null;const h=s-e.start;for(;null!=t&&null==o;){if(t.start<=h&&h<t.end){if(n=t,o=t.getVisibleBeatAtStart(i),!o)if(r){let s=e;for(;null!=s&&null==o;){for(;null!=t;){if(o=t.getVisibleBeatAtStart(i),o){n=t,e=s;break}t=t.nextBeat}o&&n||(s=s.nextMasterBar,t=s?.firstBeat??null)}}else{let s=e;for(;null!=s&&null==o;){for(;null!=t;){if(o=t.getVisibleBeatAtStart(i),o){n=t,e=s;break}t=t.previousBeat}o&&n||(s=s.previousMasterBar,t=s?.firstBeat??null)}}}else if(t.end>h)break;t=t?.nextBeat??null}if(null==o)return null;return this.createResult(e,n,o,a,i)}createResult(e,t,s,i,a){const r=new Ga(e);return r.beat=s,r.beatLookup=t,r.tickDuration=t.end-t.start,i&&this.fillNextBeat(r,a),r.calculateDuration(),r}findMasterBar(e){const t=this.masterBars;let s=0,i=t.length-1;for(;s<=i;){const a=(i+s)/2|0,r=t[a];if(e>=r.start&&e<r.end)return r;e<r.start?i=a-1:s=a+1}return null}getMasterBar(e){if(!this.masterBarLookup.has(e.index)){const t=new Ha;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 za{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Ua{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class Xa{constructor(){this.durations=[],this.brushInfos=[]}}class Ja{constructor(e,t,s){this._programsPerChannel=new Map,this._currentTime=0,this._calculatedBeatTimers=new Set,this.tickLookup=new Wa,this.applyTranspositionPitches=!0,this.transpositionPitches=new Map,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new Ot,this._handler=s}generate(){this.transpositionPitches.clear(),this._calculatedBeatTimers.clear(),this._currentTime=0;for(const e of this._score.tracks)this.generateTrack(e);re.debug("Midi","Begin midi generation");const e=new Aa(this._score);let t=null,s=this._score.tempo;for(;!e.finished;){const i=e.index,a=this._score.masterBars[i],r=e.currentTick;if(e.processCurrent(),e.shouldPlay){this.generateMasterBar(a,t,r,s),a.tempoAutomations.length>0&&(s=a.tempoAutomations[0].value);for(const e of this._score.tracks)for(const t of e.staves)i<t.bars.length&&this.generateBar(t.bars[i],r,s);a.tempoAutomations.length>0&&(s=a.tempoAutomations[a.tempoAutomations.length-1].value)}e.moveNext(),t=a}for(const t of this._score.tracks)this._handler.finishTrack(t.index,e.currentTick);re.debug("Midi","Midi generation done")}generateTrack(e){this.generateChannel(e,e.playbackInfo.primaryChannel,e.playbackInfo),e.playbackInfo.primaryChannel!==e.playbackInfo.secondaryChannel&&this.generateChannel(e,e.playbackInfo.secondaryChannel,e.playbackInfo)}addProgramChange(e,t,s,i){this._programsPerChannel.has(s)&&this._programsPerChannel.get(s)===i||(this._handler.addProgramChange(e.index,t,s,i),this._programsPerChannel.set(s,i))}static buildTranspositionPitches(e,t){const s=new Map;for(const i of e.tracks){const e=i.index<t.notation.transpositionPitches.length?t.notation.transpositionPitches[i.index]:-i.staves[0].transpositionPitch;s.set(i.playbackInfo.primaryChannel,e),s.set(i.playbackInfo.secondaryChannel,e)}return s}generateChannel(e,t,s){const i=e.index<this._settings.notation.transpositionPitches.length?this._settings.notation.transpositionPitches[e.index]:-e.staves[0].transpositionPitch;this.transpositionPitches.set(t,i);let a=Ja.toChannelShort(s.volume),r=Ja.toChannelShort(s.balance);this._handler.addControlChange(e.index,0,t,Os.VolumeCoarse,a),this._handler.addControlChange(e.index,0,t,Os.PanCoarse,r),this._handler.addControlChange(e.index,0,t,Os.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,Os.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,Os.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,Os.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,Os.DataEntryCoarse,Ja.PitchBendRangeInSemitones),this.addProgramChange(e,0,t,s.program)}static toChannelShort(e){const t=Math.max(-32768,Math.min(32767,8*e-1));return Math.max(t,-1)+1}generateMasterBar(e,t,s,i){t&&t.timeSignatureDenominator===e.timeSignatureDenominator&&t.timeSignatureNumerator===e.timeSignatureNumerator||this._handler.addTimeSignature(s,e.timeSignatureNumerator,e.timeSignatureDenominator);const a=e.calculateDuration(),r=new Ha;if(e.tempoAutomations.length>0){e.tempoAutomations[0].ratioPosition>0&&r.tempoChanges.push(new Va(s,i));for(const t of e.tempoAutomations){const e=s+a*t.ratioPosition;this._handler.addTempo(e,t.value),r.tempoChanges.push(new Va(e,t.value))}}else t?r.tempoChanges.push(new Va(s,i)):(this._handler.addTempo(s,e.score.tempo),r.tempoChanges.push(new Va(s,e.score.tempo)));r.masterBar=e,r.start=s,r.end=r.start+a,this.tickLookup.addMasterBar(r)}generateBar(e,t,s){let i=this.getPlaybackBar(e);const a=this._currentTime;for(const r of i.voices)this._currentTime=a,this.generateVoice(r,t,e,s);const r=i.masterBar,n=r.calculateDuration(),o=r.tempoAutomations.slice();if(0===o.length)this._currentTime=a+ee.ticksToMillis(n,s);else{this._currentTime=a;let e=t,i=s;const r=t+n;for(const t of o){const s=n*t.ratioPosition-e;s>0&&(this._currentTime+=ee.ticksToMillis(s,i)),i=t.value,e+=s}const h=r-e;h>0&&(this._currentTime+=ee.ticksToMillis(h,i))}i.id!==e.id&&this.tickLookup.addBeat(e.voices[0].beats[0],0,n)}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,i){if(e.isEmpty&&(!e.bar.isEmpty||0!==e.index))return;const a=s.masterBar.tempoAutomations.slice();let r=i;const n=s.masterBar.calculateDuration();for(const i of e.beats){const e=i.playbackStart/n;for(;a.length>0&&a[0].ratioPosition<=e;)r=a.shift().value;this.generateBeat(i,t,s,r)}}generateBeat(e,t,s,i){let a=e.playbackStart,r=e.playbackDuration;const n=e.voice.bar.masterBar.calculateDuration();e.voice.bar.isEmpty?r=n:e.voice.bar.masterBar.tripletFeel!==C.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(a-=this._currentTripletFeel.secondBeatStartOffset,r=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=Ja.calculateTripletFeelInfo(a,r,e),this._currentTripletFeel&&(r=this._currentTripletFeel.firstBeatDuration))),e.showTimer&&!this._calculatedBeatTimers.has(e.id)&&(e.timer=this._currentTime,this._calculatedBeatTimers.add(e.id)),this._currentTime+=ee.ticksToMillis(r,i),s===e.voice.bar&&this.tickLookup.addBeat(e,a,r);const o=e.voice.bar.staff.track;for(const s of e.automations)this.generateNonTempoAutomation(e,s,t);if(e.isRest)this._handler.addRest(o.index,t+a,o.playbackInfo.primaryChannel);else if(e.deadSlapped)this.generateDeadSlap(e,t+a);else{let s=this.getBrushInfo(e),n=this.getRasgueadoInfo(e,r);for(const o of e.notes)this.generateNote(o,t+a,r,i,s,n)}if(e.fade!==O.None&&this.generateFade(e,t+a,r),e.vibrato!==w.None){let s=240,i=3;switch(e.vibrato){case w.Slight:s=this._settings.player.vibrato.beatSlightLength,i=this._settings.player.vibrato.beatSlightAmplitude;break;case w.Wide:s=this._settings.player.vibrato.beatWideLength,i=this._settings.player.vibrato.beatWideAmplitude}this.generateVibratorWithParams(t+a,e.playbackDuration,s,0,i,((t,s)=>{this._handler.addBend(e.voice.bar.staff.track.index,t,o.playbackInfo.secondaryChannel,s)}))}}static calculateTripletFeelInfo(e,t,s){let i;switch(s.voice.bar.masterBar.tripletFeel){case C.Triplet8th:case C.Dotted8th:case C.Scottish8th:i=p.Eighth;break;case C.Triplet16th:case C.Dotted16th:case C.Scottish16th:i=p.Sixteenth;break;default:return null}const a=ee.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 Ua;switch(s.voice.bar.masterBar.tripletFeel){case C.Triplet8th:r.firstBeatDuration=ee.applyTuplet(ee.toTicks(p.Quarter),3,2),r.secondBeatDuration=ee.applyTuplet(ee.toTicks(p.Eighth),3,2);break;case C.Dotted8th:r.firstBeatDuration=ee.applyDot(ee.toTicks(p.Eighth),!1),r.secondBeatDuration=ee.toTicks(p.Sixteenth);break;case C.Scottish8th:r.firstBeatDuration=ee.toTicks(p.Sixteenth),r.secondBeatDuration=ee.applyDot(ee.toTicks(p.Eighth),!1);break;case C.Triplet16th:r.firstBeatDuration=ee.applyTuplet(ee.toTicks(p.Eighth),3,2),r.secondBeatDuration=ee.applyTuplet(ee.toTicks(p.Sixteenth),3,2);break;case C.Dotted16th:r.firstBeatDuration=ee.applyDot(ee.toTicks(p.Sixteenth),!1),r.secondBeatDuration=ee.toTicks(p.ThirtySecond);break;case C.Scottish16th:r.firstBeatDuration=ee.toTicks(p.ThirtySecond),r.secondBeatDuration=ee.applyDot(ee.toTicks(p.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateDeadSlap(e,t){const s=ee.toTicks(p.SixtyFourth),i=e.voice.bar.staff;if(i.tuning.length>0)for(const e of i.tuning)this._handler.addNote(i.track.index,t,s,e,ee.dynamicToVelocity(g.F),i.track.playbackInfo.primaryChannel)}needsSecondaryChannel(e){return e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==w.None}determineChannel(e,t){if(this.needsSecondaryChannel(t))return e.playbackInfo.secondaryChannel;let s=t;for(;s.isTieDestination;)if(s=s.tieOrigin,this.needsSecondaryChannel(s))return e.playbackInfo.secondaryChannel;for(s=t;s.isTieOrigin;)if(s=s.tieDestination,this.needsSecondaryChannel(s))return e.playbackInfo.secondaryChannel;return e.playbackInfo.primaryChannel}generateNote(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.beat.voice.bar.staff;let h=e.calculateRealValue(this.applyTranspositionPitches,!0);if(e.isPercussion){const t=ue.getArticulation(e);t&&(h=t.outputMidiNumber)}const l=null==r&&e.isStringed&&e.string<=a.length?a[e.string-1]:0,d=t+l,c=this.getNoteDuration(e,s,i);c.untilTieOrSlideEnd-=l,c.noteOnly-=l,c.letRingEnd-=l;const u=Ja.getNoteVelocity(e),p=this.determineChannel(n,e);let g=0,m=Math.max(c.untilTieOrSlideEnd,c.letRingEnd);g=e.hasBend?Ja.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?Ja.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===_.Legato?-1:Ja.getPitchWheel(0),g>=0&&this._handler.addNoteBend(n.index,d,p,h,g),e.beat.hasRasgueado?this.generateRasgueado(n,e,d,h,u,p,r):e.ornament===M.None?!e.isTrill||o.isPercussion?e.beat.isTremolo?this.generateTremoloPicking(e,d,c,h,u,p):(e.hasBend?this.generateBend(e,d,c,h,p,i):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,d,c,p,i):e.slideInType!==S.None||e.slideOutType!==_.None?this.generateSlide(e,d,c,h,p,i):(e.vibrato!==w.None||e.isTieDestination&&e.tieOrigin.vibrato!==w.None)&&this.generateVibrato(e,d,c,h,p),e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===_.Legato||this._handler.addNote(n.index,d,m,h,u,p)):this.generateTrill(e,d,c,h,u,p):this.generateOrnament(n,e,d,m,h,u,p)}generateOrnament(e,t,s,i,a,r,n){let o,h;const l=a%12,d=1/3;switch(t.ornament){case M.Turn:o=[a+Ja.OrnamentKeysUp[l],a,a+Ja.OrnamentKeysDown[l]],h=[ee.toTicks(p.Sixteenth)*d,ee.toTicks(p.Sixteenth)*d,ee.toTicks(p.Sixteenth)*d];break;case M.InvertedTurn:o=[a+Ja.OrnamentKeysDown[l],a,a+Ja.OrnamentKeysUp[l]],h=[ee.toTicks(p.Sixteenth)*d,ee.toTicks(p.Sixteenth)*d,ee.toTicks(p.Sixteenth)*d];break;case M.UpperMordent:o=[a,a+Ja.OrnamentKeysUp[l]],h=[ee.toTicks(p.ThirtySecond),ee.toTicks(p.ThirtySecond)];break;case M.LowerMordent:o=[a,a+Ja.OrnamentKeysDown[l]],h=[ee.toTicks(p.ThirtySecond),ee.toTicks(p.ThirtySecond)];break;default:return}let c=1;i<ee.QuarterTime&&(c=i/ee.QuarterTime),r-=ee.VelocityIncrement;let u=0;for(let t=0;t<o.length;t++){const i=h[t]*c;this._handler.addNote(e.index,s,i,o[t],r,n),s+=i,u+=i}const g=i-u;this._handler.addNote(e.index,s,g,a,r,n)}getNoteDuration(e,t,s){const i=new za;if(i.noteOnly=t,i.untilTieOrSlideEnd=t,i.letRingEnd=t,e.isDead)return i.noteOnly=this.applyStaticDuration(Ja.DefaultDurationDead,t,s),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isPalmMute)return i.noteOnly=this.applyStaticDuration(Ja.DefaultDurationPalmMute,t,s),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isStaccato)return i.noteOnly=t/2|0,i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isTieOrigin){const a=e.tieDestination;if(a)if(e.isTieDestination){const e=this.getNoteDuration(a,a.beat.playbackDuration,s);i.untilTieOrSlideEnd=t+e.untilTieOrSlideEnd}else{const t=e.beat.absolutePlaybackStart,r=this.getNoteDuration(a,a.beat.playbackDuration,s),n=a.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;i.untilTieOrSlideEnd=n-t}}else if(e.slideOutType===_.Legato){const t=e.slideTarget;if(t){const a=e.beat.absolutePlaybackStart,r=this.getNoteDuration(t,t.beat.playbackDuration,s),n=t.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;i.untilTieOrSlideEnd=n-a}}if(e.isLetRing&&this._settings.notation.notationMode===T.GuitarPro){let s=e.beat,a=0;const r=e.beat.voice.bar.masterBar.calculateDuration();for(;s.nextBeat;){let t=s.nextBeat;if(t.isRest)break;if(e.isStringed&&t.hasNoteOnString(e.string))break;if(s=s.nextBeat,a=s.absolutePlaybackStart-e.beat.absolutePlaybackStart+s.playbackDuration,a>r){a=r;break}}s===e.beat?i.letRingEnd=t:i.letRingEnd=a}else i.letRingEnd=i.untilTieOrSlideEnd;return i}applyStaticDuration(e,t,s){const i=s*e/te.MaxPosition|0;return Math.min(i,t)}static getNoteVelocity(e){let t=e.dynamics;switch(!e.beat.voice.bar.staff.isPercussion&&e.hammerPullOrigin&&t--,e.isGhost&&t--,e.accentuated){case i.Normal:t++;break;case i.Heavy:t+=2}return ee.dynamicToVelocity(t)}generateFade(e,t,s){const i=e.voice.bar.staff.track;switch(e.fade){case O.FadeIn:this.generateFadeSteps(i,t,s,0,Ja.toChannelShort(i.playbackInfo.volume));break;case O.FadeOut:this.generateFadeSteps(i,t,s,Ja.toChannelShort(i.playbackInfo.volume),0);break;case O.VolumeSwell:const e=s/2|0;this.generateFadeSteps(i,t,e,0,Ja.toChannelShort(i.playbackInfo.volume)),this.generateFadeSteps(i,t+e,e,Ja.toChannelShort(i.playbackInfo.volume),0)}}generateFadeSteps(e,t,s,i,a){const r=(a-i)/(s=.8*s|0),n=s/120+1|0,o=t+s;for(let s=0;s<n;s++){const h=s===n-1,l=h?o:t+120*s,d=h?a:Math.round(i+(l-t)*r);this._handler.addControlChange(e.index,l,e.playbackInfo.primaryChannel,Os.VolumeCoarse,d),this._handler.addControlChange(e.index,l,e.playbackInfo.secondaryChannel,Os.VolumeCoarse,d)}}generateVibrato(e,t,s,i,a){let r=0,n=0;switch(e.vibrato!==w.None?e.vibrato:e.isTieDestination?e.tieOrigin.vibrato:w.Slight){case w.Slight:r=this._settings.player.vibrato.noteSlightLength,n=this._settings.player.vibrato.noteSlightAmplitude;break;case w.Wide:r=this._settings.player.vibrato.noteWideLength,n=this._settings.player.vibrato.noteWideAmplitude;break;default:return}const o=e.beat.voice.bar.staff.track;let h=0;if(e.isTieDestination&&e.tieOrigin.hasBend){const t=e.tieOrigin.bendPoints;h=t[t.length-1].value}this.generateVibratorWithParams(t,s.noteOnly,r,h,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)}))}generateVibratorWithParams(e,t,s,i,a,r){const n=this.vibratoResolution,o=s/2|0,h=e+t;for(;e<h;){let t=0;const l=e+s<h?s:h-e;for(;t<l;){let s=i+a*Math.sin(t*Math.PI/o);r(e+t|0,Ja.getPitchWheel(s)),t+=n}e+=s}r(0|h,Ja.getPitchWheel(i))}static getPitchWheel(e){return Re.DefaultPitchWheel+e/2*Ja.PitchValuePerSemitone}generateSlide(e,t,s,i,a,r){let n=e.slideOutType===_.Legato?s.noteOnly:s.untilTieOrSlideEnd,o=[],h=e.beat.voice.bar.staff.track;const l=this._settings.player.slide.simpleSlidePitchOffset,d=Math.floor(te.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),c=Math.floor(te.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case S.IntoFromAbove:o.push(new te(0,l)),o.push(new te(d,0));break;case S.IntoFromBelow:o.push(new te(0,-l)),o.push(new te(d,0))}switch(e.slideOutType){case _.Legato:case _.Shift:o.push(new te(c,0));const t=2*(e.slideTarget.calculateRealValue(this.applyTranspositionPitches,!0)-e.calculateRealValue(this.applyTranspositionPitches,!0));o.push(new te(te.MaxPosition,t));break;case _.OutDown:o.push(new te(te.MaxPosition-d,0)),o.push(new te(te.MaxPosition,-l));break;case _.OutUp:o.push(new te(te.MaxPosition-d,0)),o.push(new te(te.MaxPosition,l))}this.generateWhammyOrBend(t,n,o,r,((e,t)=>{this._handler.addNoteBend(h.index,e,a,i,t)}))}generateBend(e,t,s,i,a,r){let n=e.bendPoints,o=e.beat.voice.bar.staff.track;const h=(e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)};let c,u=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend&&t.tieDestination.vibrato==w.None;)t=t.tieDestination;c=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration,r).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==m.None){switch(e.tieDestination.bendType){case d.Bend:case d.BendRelease:case d.PrebendBend:u=e.tieDestination.bendPoints[1].value;break;case d.Prebend:case d.PrebendRelease:u=e.tieDestination.bendPoints[0].value}c=Math.max(s.noteOnly,ee.millisToTicks(this._settings.player.songBookBendDuration,r))}else c=s.noteOnly;n[0].value>0&&!e.isContinuedBend&&t>0&&t--;const p=Math.min(c,ee.millisToTicks(this._settings.player.songBookBendDuration,r));let g=[];switch(e.bendType){case d.Custom:g=n;break;case d.Bend:case d.Release:switch(e.bendStyle){case l.Default:g=n;break;case l.Gradual:g.push(new te(0,e.bendPoints[0].value)),(!u||u<e.bendPoints[1].value)&&(u=e.bendPoints[1].value),g.push(new te(te.MaxPosition,u));break;case l.Fast:return(!u||u<e.bendPoints[1].value)&&(u=e.bendPoints[1].value),void(e.beat.graceType===m.BendGrace?this.generateSongBookWhammyOrBend(t,c,!0,[e.bendPoints[0].value,u],p,r,h):this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,u],p,r,h))}break;case d.BendRelease:switch(e.bendStyle){case l.Default:g=n;break;case l.Gradual:g.push(new te(0,e.bendPoints[0].value)),g.push(new te(te.MaxPosition/2|0,e.bendPoints[1].value)),g.push(new te(te.MaxPosition,e.bendPoints[2].value));break;case l.Fast:return void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],p,r,h)}break;case d.Hold:case d.Prebend:g=n;break;case d.PrebendBend:switch(e.bendStyle){case l.Default:g=n;break;case l.Gradual:g.push(new te(0,e.bendPoints[0].value)),g.push(new te(te.MaxPosition,e.bendPoints[1].value));break;case l.Fast:return h(t,0|Ja.getPitchWheel(e.bendPoints[0].value)),(!u||u<e.bendPoints[1].value)&&(u=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,u],p,r,h)}break;case d.PrebendRelease:switch(e.bendStyle){case l.Default:g=n;break;case l.Gradual:g.push(new te(0,e.bendPoints[0].value)),g.push(new te(te.MaxPosition,e.bendPoints[1].value));break;case l.Fast:return h(t,0|Ja.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,e.bendPoints[1].value],p,r,h)}}this.generateWhammyOrBend(t,c,g,r,h)}generateSongBookWhammyOrBend(e,t,s,i,a,r,n){const o=s?e:e+t-a,h=a/(i.length-1);for(let e=0;e<i.length-1;e++){const t=Ja.getPitchWheel(i[e]),s=Ja.getPitchWheel(i[e+1]),a=o+h*e;this.generateBendValues(a,h,t,s,r,n)}}generateWhammy(e,t,s,i,a){const r=e.whammyBarPoints,n=e.voice.bar.staff.track,o=s.noteOnly;r[0].value>0&&!e.isContinuedWhammy&&t--;const h=(e,t)=>{this._handler.addBend(n.index,e,i,t)};let d=[];switch(e.whammyBarType){case I.Custom:d=r;break;case I.Dive:switch(e.whammyStyle){case l.Default:d=r;break;case l.Gradual:d.push(new te(0,r[0].value)),d.push(new te(te.MaxPosition,r[1].value));break;case l.Fast:const e=Math.min(o,ee.millisToTicks(this._settings.player.songBookBendDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!1,[r[0].value,r[1].value],e,a,h)}break;case I.Dip:switch(e.whammyStyle){case l.Default:d=r;break;case l.Gradual:d.push(new te(0,r[0].value)),d.push(new te(te.MaxPosition/2|0,r[1].value)),d.push(new te(te.MaxPosition,r[2].value));break;case l.Fast:const e=Math.min(o,ee.millisToTicks(this._settings.player.songBookDipDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!0,[r[0].value,r[1].value,r[2].value],e,a,h)}break;case I.Hold:case I.Predive:d=r;break;case I.PrediveDive:switch(e.whammyStyle){case l.Default:d=r;break;case l.Gradual:d.push(new te(0,r[0].value)),d.push(new te(te.MaxPosition/2|0,r[0].value)),d.push(new te(te.MaxPosition,r[1].value));break;case l.Fast:const e=Ja.getPitchWheel(r[0].value);this._handler.addBend(n.index,t,i,0|e);const s=Math.min(o,ee.millisToTicks(this._settings.player.songBookBendDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!1,[r[0].value,r[1].value],s,a,h)}}this.generateWhammyOrBend(t,o,d,a,h)}generateWhammyOrBend(e,t,s,i,a){const r=t/te.MaxPosition;for(let t=0;t<s.length-1;t++){const n=s[t],o=s[t+1],h=Ja.getPitchWheel(n.value),l=Ja.getPitchWheel(o.value),d=r*(o.offset-n.offset),c=e+r*n.offset;this.generateBendValues(c,d,h,l,i,a)}}generateBendValues(e,t,s,i,a,r){const n=ee.ticksToMillis(t,a),o=Math.abs(i-s)/Ja.PitchValuePerSemitone,h=Math.max(Ja.MinBreakpointsPerSemitone*o,n/Ja.MillisecondsPerBreakpoint),l=t/h,d=(i-s)/h,c=e+t;for(let t=0;t<h;t++)r(0|e,Math.round(s)),s+=d,e+=l;r(0|c,i)}generateRasgueado(e,t,s,i,a,r,n){let o=s;for(let s=0;s<n.durations.length;s++){const h=n.brushInfos[s],l=t.isStringed&&t.string<=h.length?h[t.string-1]:0,d=n.durations[s];this._handler.addNote(e.index,o+l,d-l,i,a,r),o+=d}}generateTrill(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=ee.toTicks(e.trillSpeed),l=!0,d=t,c=t+s.untilTieOrSlideEnd;for(;d+10<c;)d+h>=c&&(h=c-d),this._handler.addNote(n.index,d,h,l?o:i,a,r),l=!l,d+=h}generateTremoloPicking(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track;let o=ee.toTicks(e.beat.tremoloSpeed),h=t;const l=t+s.untilTieOrSlideEnd;for(;h+10<l;)h+o>=l&&(o=l-h),this._handler.addNote(n.index,h,o,i,a,r),h+=o}getRasgueadoInfo(e,t){if(!e.hasRasgueado)return null;const s=new Xa,i=Ja.RasgueadoDurations.get(e.rasgueado).reduce(((e,t)=>e+t),0);s.durations=Ja.RasgueadoDurations.get(e.rasgueado).map((e=>t*e/i)),s.brushInfos=new Array(s.durations.length);const a=ee.toTicks(p.Sixteenth);let r=0,n=0;for(const t of e.notes)t.isTieDestination||(r|=1<<t.string-1,n++);const o=Ja.RasgueadoDirections.get(e.rasgueado);for(let t=0;t<s.durations.length;t++){const i=s.durations[t]*a/ee.QuarterTime,h=new Int32Array(e.voice.bar.staff.tuning.length);s.brushInfos[t]=h;const l=o[t];l!==c.None&&this.fillBrushInfo(e,h,l===c.ArpeggioDown||l===c.BrushDown,r,n,i)}return s}getBrushInfo(e){const t=new Int32Array(e.voice.bar.staff.tuning.length);if(e.brushType){let s=0,i=0;for(const t of e.notes)t.isTieDestination||(s|=1<<t.string-1,i++);this.fillBrushInfo(e,t,e.brushType===c.ArpeggioDown||e.brushType===c.BrushDown,s,i,e.brushDuration)}return t}fillBrushInfo(e,t,s,i,a,r){if(e.notes.length>0){let n=0;const o=r/(a-1)|0;for(let a=0;a<e.voice.bar.staff.tuning.length;a++){let e=s?a:t.length-1-a;i&1<<e&&(t[e]=n,n+=o)}}return t}generateNonTempoAutomation(e,t,s){switch(t.type){case 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=Ja.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Os.PanCoarse,i),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Os.PanCoarse,i);break;case a.Volume:let r=Ja.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Os.VolumeCoarse,r),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Os.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);const o=e.playbackStart/n.calculateDuration();for(const e of n.tempoAutomations){if(!(e.ratioPosition<=o))break;t=e.value}-1===s&&(s=r.playbackInfo.program);const h=r.playbackInfo.volume;this.generateTrack(r),this._handler.addTimeSignature(0,n.timeSignatureNumerator,n.timeSignatureDenominator),this._handler.addTempo(0,t);let l=Ja.toChannelShort(h);return this._handler.addControlChange(0,0,r.playbackInfo.primaryChannel,Os.VolumeCoarse,l),this._handler.addControlChange(0,0,r.playbackInfo.secondaryChannel,Os.VolumeCoarse,l),t}generateSingleBeat(e){const t=this.prepareSingleBeat(e);this.generateBeat(e,-e.playbackStart,e.voice.bar,t)}generateSingleNote(e){const t=this.prepareSingleBeat(e.beat);this.generateNote(e,0,e.beat.playbackDuration,t,new Int32Array(e.beat.voice.bar.staff.tuning.length),null)}}Ja.DefaultDurationDead=30,Ja.DefaultDurationPalmMute=80,Ja.OrnamentKeysUp=[2,2,2,1,1,2,2,2,2,2,1,1],Ja.OrnamentKeysDown=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],Ja.PitchBendRangeInSemitones=16,Ja.PitchValuePerSemitone=Re.DefaultPitchWheel/Ja.PitchBendRangeInSemitones,Ja.MinBreakpointsPerSemitone=6,Ja.MillisecondsPerBreakpoint=150,Ja.RasgueadoDirections=new Map([[H.Ii,[c.BrushDown,c.BrushUp]],[H.Mi,[c.BrushDown,c.BrushDown]],[H.MiiTriplet,[c.BrushDown,c.BrushDown,c.BrushUp]],[H.MiiAnapaest,[c.BrushDown,c.BrushDown,c.BrushUp]],[H.PmpTriplet,[c.BrushUp,c.BrushDown,c.BrushDown]],[H.PmpAnapaest,[c.BrushUp,c.BrushDown,c.BrushDown]],[H.PeiTriplet,[c.BrushUp,c.BrushDown,c.BrushDown]],[H.PeiAnapaest,[c.BrushUp,c.BrushDown,c.BrushDown]],[H.PaiTriplet,[c.BrushUp,c.BrushDown,c.BrushDown]],[H.PaiAnapaest,[c.BrushUp,c.BrushDown,c.BrushDown]],[H.AmiTriplet,[c.BrushDown,c.BrushDown,c.BrushDown]],[H.AmiAnapaest,[c.BrushDown,c.BrushDown,c.BrushDown]],[H.Ppp,[c.None,c.BrushDown,c.BrushUp]],[H.Amii,[c.BrushDown,c.BrushDown,c.BrushDown,c.BrushUp]],[H.Amip,[c.BrushDown,c.BrushDown,c.BrushDown,c.BrushUp]],[H.Eami,[c.BrushDown,c.BrushDown,c.BrushDown,c.BrushDown]],[H.Eamii,[c.BrushDown,c.BrushDown,c.BrushDown,c.BrushDown,c.BrushUp]],[H.Peami,[c.BrushDown,c.BrushDown,c.BrushDown,c.BrushDown,c.BrushUp]]]),Ja.RasgueadoDurations=new Map([[H.Ii,[ee.toTicks(p.Eighth),ee.toTicks(p.Eighth)]],[H.Mi,[ee.toTicks(p.Eighth),ee.toTicks(p.Eighth)]],[H.MiiTriplet,[ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3]],[H.MiiAnapaest,[ee.toTicks(p.Sixteenth),ee.toTicks(p.Sixteenth),ee.toTicks(p.Eighth)]],[H.PmpTriplet,[ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3]],[H.PmpAnapaest,[ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Eighth)/3]],[H.PeiTriplet,[ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3]],[H.PeiAnapaest,[ee.toTicks(p.Sixteenth),ee.toTicks(p.Sixteenth),ee.toTicks(p.Eighth)]],[H.PaiTriplet,[ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3]],[H.PaiAnapaest,[ee.toTicks(p.Sixteenth),ee.toTicks(p.Sixteenth),ee.toTicks(p.Eighth)]],[H.AmiTriplet,[ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3]],[H.AmiAnapaest,[ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Eighth)/3]],[H.Ppp,[ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Eighth)/3]],[H.Amii,[ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Eighth)]],[H.Amip,[ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Eighth)]],[H.Eami,[ee.toTicks(p.Sixteenth),ee.toTicks(p.Sixteenth),ee.toTicks(p.Sixteenth),ee.toTicks(p.Sixteenth)]],[H.Eamii,[ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5]],[H.Peami,[ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5]]]);class Ya{constructor(){this.startTick=0,this.endTick=0}}class qa{constructor(e,t){this.width=0,this.height=0,this.x=e,this.y=t}doLayout(){}paint(e,t,s){}}class ja extends qa{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Ka extends ja{constructor(e,t,s,i){super(e,t),this.glyphScale=0,this.center=!1,this.glyphScale=s,this.symbol=i}paint(e,t,s){s.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale,this.symbol,this.center)}}class Qa extends Ka{constructor(e,t,s,i){super(e,t,i?Qa.GraceScale:1,Qa.getSymbol(s)),this._isGrace=i,this._duration=s}paint(e,t,s){let i=this._isGrace?1:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale,this.symbol,!1)}doLayout(){let e=this._isGrace?Qa.GraceScale:1;switch(this._duration){case p.QuadrupleWhole:this.width=14*e;break;case p.DoubleWhole:case p.Whole:this.width=14*(this._isGrace?Qa.GraceScale:1);break;default:this.width=Qa.QuarterNoteHeadWidth*(this._isGrace?Qa.GraceScale:1)}this.height=Qa.NoteHeadHeight*e}static getSymbol(e){switch(e){case p.QuadrupleWhole:return F.NoteheadDoubleWholeSquare;case p.DoubleWhole:return F.NoteheadDoubleWhole;case p.Whole:return F.NoteheadWhole;case p.Half:return F.NoteheadHalf;default:return F.NoteheadBlack}}}Qa.GraceScale=.75,Qa.NoteHeadHeight=8,Qa.QuarterNoteHeadWidth=9;class $a extends Ka{constructor(e,t,s,i,a){super(e,t,a?Qa.GraceScale:1,$a.getSymbol(s,i,a))}doLayout(){this.width=0}static getSymbol(e,t,s){if(s&&(e=p.Eighth),t===Ge.Up)switch(e){case p.Eighth:return F.FlagEighthUp;case p.Sixteenth:return F.FlagSixteenthUp;case p.ThirtySecond:return F.FlagThirtySecondUp;case p.SixtyFourth:return F.FlagSixtyFourthUp;case p.OneHundredTwentyEighth:return F.FlagOneHundredTwentyEighthUp;case p.TwoHundredFiftySixth:return F.FlagTwoHundredFiftySixthUp;default:return F.FlagEighthUp}switch(e){case p.Eighth:return F.FlagEighthDown;case p.Sixteenth:return F.FlagSixteenthDown;case p.ThirtySecond:return F.FlagThirtySecondDown;case p.SixtyFourth:return F.FlagSixtyFourthDown;case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:return F.FlagOneHundredTwentyEighthDown;default:return F.FlagEighthDown}}}$a.FlagWidth=11;class Za extends qa{get onTimeX(){return this.onNotes.x+this.onNotes.centerX}constructor(e,t){super(0,0),this.ties=[],this.minWidth=0,this.beat=e,this.ties=[],this.voiceContainer=t}addTie(e){e.renderer=this.renderer,this.ties.push(e)}drawBeamHelperAsFlags(e){return e.hasFlag(!1,void 0)}registerLayoutingInfo(e){let t=this.preNotes.computedWidth+this.onNotes.centerX,s=this.onNotes.computedWidth-this.onNotes.centerX;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);this.beat.graceType!==m.None?1===this.beat.graceGroup.beats.length?s+=$a.FlagWidth*Qa.GraceScale:this.beat.graceIndex<this.beat.graceGroup.beats.length-1?s+=7:s+=Za.GraceBeatPadding:i&&this.drawBeamHelperAsFlags(i)&&(s+=$a.FlagWidth);for(const e of this.ties)s+=e.width;e.addBeatSpring(this.beat,t,s)}applyLayoutingInfo(e){this.onNotes.updateBeamingHelper(),this.updateWidth()}doLayout(){this.preNotes.x=0,this.preNotes.renderer=this.renderer,this.preNotes.container=this,this.preNotes.doLayout(),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.renderer=this.renderer,this.onNotes.container=this,this.onNotes.doLayout();let e=this.beat.notes.length-1;for(;e>=0;)this.createTies(this.beat.notes[e--]);this.renderer.registerTies(this.ties),this.updateWidth()}updateWidth(){if(this.minWidth=this.preNotes.width+this.onNotes.width,!this.beat.isRest)if(1===this.onNotes.beamingHelper.beats.length)this.beat.duration>=p.Eighth&&(this.minWidth+=20);else switch(this.beat.duration){case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:this.minWidth+=10}let e=0;for(let t of this.ties)t.width>e&&(e=t.width);this.minWidth+=e,this.width=this.minWidth}scaleToWidth(e){this.onNotes.updateBeamingHelper(),this.width=e}createTies(e){}static getGroupId(e){return"b"+e.id}paint(e,t,s){if(this.beat.voice.isEmpty)return;if(this.preNotes.isEmpty&&this.onNotes.isEmpty&&0===this.ties.length)return;s.beginGroup(Za.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 Na;if(a.beat=this.beat,this.beat.isEmpty)a.visualBounds=new ds,a.visualBounds.x=t+this.x,a.visualBounds.y=e.visualBounds.y,a.visualBounds.w=this.width,a.visualBounds.h=e.visualBounds.h,a.realBounds=new ds,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,a.onNotesX=t+this.x+this.onNotes.centerX;else{a.visualBounds=new ds,a.visualBounds.x=t+this.x,this.preNotes.isEmpty?this.onNotes.isEmpty?a.visualBounds.x=t+this.x:a.visualBounds.x=t+this.x+this.onNotes.x:a.visualBounds.x=t+this.x+this.preNotes.x;let s=0;s=this.onNotes.isEmpty?this.preNotes.isEmpty?t+this.x+this.width:t+this.x+this.preNotes.x+this.preNotes.width:t+this.x+this.onNotes.x+this.onNotes.width,a.visualBounds.w=s-a.visualBounds.x;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);(i&&this.drawBeamHelperAsFlags(i)||this.beat.graceType!==m.None)&&(a.visualBounds.w+=$a.FlagWidth*(this.beat.graceType!==m.None?Qa.GraceScale:1)),a.visualBounds.y=e.visualBounds.y,a.visualBounds.h=e.visualBounds.h,a.realBounds=new ds,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,a.onNotesX=t+this.x+this.onNotes.x+this.onNotes.centerX}e.addBeat(a),this.renderer.settings.core.includeNoteBounds&&this.onNotes.buildBoundingsLookup(a,t+this.x,s+this.y)}}Za.GraceBeatPadding=3;class er{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new xl}causeIssue(){return this.settings=null,!0}}class tr{constructor(e){this.activeBeats=e}}class sr{constructor(e){this.bounds=null,this.beat=e}}class ir{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=Es.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=Es.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new fa,this.activeBeatsChanged=new fa,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new fa,this.beatMouseMove=new fa,this.beatMouseUp=new fa,this.noteMouseDown=new fa,this.noteMouseMove=new fa,this.noteMouseUp=new fa,this.scoreLoaded=new fa,this.resize=new fa,this.renderStarted=new fa,this.renderFinished=new fa,this.postRenderFinished=new ma,this.error=new fa,this.playerReady=new ma,this.playerFinished=new ma,this.soundFontLoaded=new ma,this.midiLoad=new fa,this.midiLoaded=new fa,this.playerStateChanged=new fa,this.playerPositionChanged=new fa,this.midiEventsPlayed=new fa,this.playbackRangeChanged=new fa,this.settingsUpdated=new ma,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),re.logLevel=this.settings.core.logLevel,this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&Tl.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new Fa(this.settings),this.container.resize.on(Tl.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));let s=new er;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;re.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&&le.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?(this.setupPlayer(),e&&this.player?.applyTranspositionPitches(Ja.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 j(s.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(t,e)}}internalRenderTracks(e,t){if(le.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 er;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 re.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{re.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:Es.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=Es.Paused,this.destroyCursors())}setupPlayer(){this.updateCursors(),this.player||(this.player=this.uiFacade.createWorkerPlayer(),this.player&&(this.player.ready.on((()=>{this.loadMidiForScore()})),this.player.readyForPlayback.on((()=>{if(this.onPlayerReady(),this.tracks)for(let e of this.tracks){let t=e.playbackInfo.volume/16;this.player.setChannelVolume(e.playbackInfo.primaryChannel,t),this.player.setChannelVolume(e.playbackInfo.secondaryChannel,t)}})),this.player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this.player.soundFontLoadFailed.on((e=>{this.onError(e)})),this.player.midiLoaded.on(this.onMidiLoaded.bind(this)),this.player.midiLoadFailed.on((e=>{this.onError(e)})),this.player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this.player.positionChanged.on(this.onPlayerPositionChanged.bind(this)),this.player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this.player.playbackRangeChanged.on(this.onPlaybackRangeChanged.bind(this)),this.player.finished.on(this.onPlayerFinished.bind(this)),this.setupPlayerEvents()))}loadMidiForScore(){if(!this.score)return;re.debug("AlphaTab","Generating Midi");let e=new ot,t=new Ma(e),s=new Ja(this.score,this.settings,t);s.applyTranspositionPitches=!1,s.generate(),this._tickCache=s.tickLookup,this.onMidiLoad(e);const i=this.player;i&&(i.loadMidiFile(e),i.applyTranspositionPitches(s.transpositionPitches))}changeTrackVolume(e,t){if(this.player)for(let s of e)this.player.setChannelVolume(s.playbackInfo.primaryChannel,t),this.player.setChannelVolume(s.playbackInfo.secondaryChannel,t)}changeTrackSolo(e,t){if(this.player)for(let s of e)this.player.setChannelSolo(s.playbackInfo.primaryChannel,t),this.player.setChannelSolo(s.playbackInfo.secondaryChannel,t)}changeTrackMute(e,t){if(this.player)for(let s of e)this.player.setChannelMute(s.playbackInfo.primaryChannel,t),this.player.setChannelMute(s.playbackInfo.secondaryChannel,t)}changeTrackTranspositionPitch(e,t){if(this.player)for(let s of e)this.player.setChannelTranspositionPitch(s.playbackInfo.primaryChannel,t),this.player.setChannelTranspositionPitch(s.playbackInfo.secondaryChannel,t)}play(){return!!this.player&&this.player.play()}pause(){this.player&&this.player.pause()}playPause(){this.player&&this.player.playPause()}stop(){this.player&&this.player.stop()}playBeat(e){if(!this.player)return;let t=new ot,s=new Ma(t);new Ja(e.voice.bar.staff.track.score,this.settings,s).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;let t=new ot,s=new Ma(t);new Ja(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=Es.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===Es.Paused){let e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getBeatStart(e.beat))}})))}cursorUpdateTick(e,t,s=!1){let i=this._tickCache;if(i){let a=this._trackIndexLookup;if(null!=a&&a.size>0){let r=i.findBeat(a,e,this._currentBeat);r&&this.cursorUpdateBeat(r,t,s)}}}cursorUpdateBeat(e,t,s,i=!1){const a=e.beat,r=e.nextBeat?.beat??null,n=e.duration,o=e.beatLookup.highlightedBeats;if(!a)return;let h=this.renderer.boundsLookup;if(!h)return;let l=this._currentBeat,d=this._previousCursorCache,c=this._previousStateForCursor;if(!i&&a===l?.beat&&h===d&&c===this._playerState)return;let u=h.findBeat(a);u&&(this._currentBeat=e,this._previousCursorCache=h,this._previousStateForCursor=this._playerState,this.uiFacade.beginInvoke((()=>{this.internalCursorUpdateBeat(a,r,n,t,o,h,u,s)})))}scrollToCursor(){const e=this._currentBarBounds;e&&this.internalScrollToCursor(e)}internalScrollToCursor(e){let t=this.uiFacade.getScrollContainer(),s=Tl.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 Qe.Continuous:let i=this.uiFacade.getOffset(t,this.container);this.uiFacade.scrollToY(t,i.y+s,this.settings.player.scrollSpeed);break;case Qe.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 Qe.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 Qe.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 d=n.barBounds.masterBarBounds,c=d.visualBounds;this._currentBarBounds=d,h&&h.setBounds(c.x,c.y,c.w,c.h),l&&(this.settings.player.enableAnimatedBeatCursor&&l.stopAnimation(),l.setBounds(n.onNotesX,c.y,1,c.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let u=!1;if(this._playerState===Es.Playing&&!i){if(this.settings.player.enableElementHighlighting)for(let t of a){let s=Za.getGroupId(t.beat);this.uiFacade.highlightElements(s,e.voice.bar.index)}if(this.settings.player.enableAnimatedBeatCursor){let e=d.visualBounds.x+d.visualBounds.w;if(t){let s=r.findBeat(t);s&&s.barBounds.masterBarBounds.staffSystemBounds===d.staffSystemBounds&&(e=s.onNotesX)}this.uiFacade.beginInvoke((()=>{l&&l.transitionToX(s/this.playbackSpeed,e)}))}o=!i,u=!0}o&&!this._beatMouseDown&&this.settings.player.scrollMode!==Qe.Off&&this.internalScrollToCursor(d),u&&(this.onPlayedBeatChanged(e),this.onActiveBeatsChanged(new tr(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 sr(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 sr(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===Es.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 Ya;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 sr(t.beat),i=new sr(s.beat);this.cursorSelectRange(e,i)}}else this.cursorSelectRange(null,null)}setupClickHandling(){this.canvasElement.mouseDown.on((e=>{if(!e.isLeftMouseButton)return;this.settings.player.enableUserInteraction&&e.preventDefault();let t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(i&&(this.onBeatMouseDown(e,i),this.settings.core.includeNoteBounds)){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s);a&&this.onNoteMouseDown(e,a)}})),this.canvasElement.mouseMove.on((e=>{if(!this._beatMouseDown)return;let t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(i&&(this.onBeatMouseMove(e,i),this._noteMouseDown)){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s);a&&this.onNoteMouseMove(e,a)}})),this.canvasElement.mouseUp.on((e=>{if(!this._beatMouseDown)return;this.settings.player.enableUserInteraction&&e.preventDefault();let t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(this.onBeatMouseUp(e,i),this._noteMouseDown)if(i){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s)??null;this.onNoteMouseUp(e,a)}else this.onNoteMouseUp(e,null)})),this.renderer.postRenderFinished.on((()=>{this._selectionStart&&this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&this.cursorSelectRange(this._selectionStart,this._selectionEnd)}))}cursorSelectRange(e,t){let s=this.renderer.boundsLookup;if(!s)return;let i=this._selectionWrapper;if(!i)return;if(i.clear(),!e||!t||e.beat===t.beat)return;e.bounds||(e.bounds=s.findBeat(e.beat)),t.bounds||(t.bounds=s.findBeat(t.beat));let a=this._tickCache?.getBeatStart(e.beat)??e.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(t.beat)??t.beat.absolutePlaybackStart)<a){let s=e;e=t,t=s}let r=e.bounds.realBounds.x,n=t.bounds.realBounds.x+t.bounds.realBounds.w;if(t.beat.index===t.beat.voice.beats.length-1&&(n=t.bounds.barBounds.masterBarBounds.realBounds.x+t.bounds.barBounds.masterBarBounds.realBounds.w),e.bounds.barBounds.masterBarBounds.staffSystemBounds!==t.bounds.barBounds.masterBarBounds.staffSystemBounds){let a=e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.x,o=e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.x+e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.w,h=this.uiFacade.createSelectionElement();h.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,o-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(h);let l=e.bounds.barBounds.masterBarBounds.staffSystemBounds.index+1,d=t.bounds.barBounds.masterBarBounds.staffSystemBounds.index;for(let e=l;e<d;e++){let t=s.staffSystems[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),i.appendChild(r)}let c=this.uiFacade.createSelectionElement();c.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(c)}else{let t=this.uiFacade.createSelectionElement();t.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,n-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(t)}}onScoreLoaded(e){this._isDestroyed||(this.scoreLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"scoreLoaded",e))}onResize(e){this._isDestroyed||(this.resize.trigger(e),this.uiFacade.triggerEvent(this.container,"resize",e))}onRenderStarted(e){this._isDestroyed||(this.renderStarted.trigger(e),this.uiFacade.triggerEvent(this.container,"renderStarted",e))}onRenderFinished(e){this._isDestroyed||(this.renderFinished.trigger(e),this.uiFacade.triggerEvent(this.container,"renderFinished",e))}onPostRenderFinished(){this._isDestroyed||(this.postRenderFinished.trigger(),this.uiFacade.triggerEvent(this.container,"postRenderFinished",null))}onError(e){this._isDestroyed||(re.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 ar extends j{constructor(e,t){super(s.General,e),this.xhr=t,Object.setPrototypeOf(this,ar.prototype)}}class rr{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=rr.loadScoreFromBytes(s,i);t(r)}catch(e){s(e)}else 0===a.status?s(new ar("You are offline!!\n Please Check Your Network.",a)):404===a.status?s(new ar("Requested URL not found.",a)):500===a.status?s(new ar("Internel Server Error.",a)):"parsererror"===a.statusText?s(new ar("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?s(new ar("Request Time out.",a)):s(new ar("Unknow Error: "+a.responseText,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Ot);let s=Tl.buildImporters();re.debug("ScoreLoader",`Loading score from ${e.length} bytes using ${s.length} importers`);let i=null,a=Oe.fromBuffer(e);for(let e of s){a.reset();try{re.debug("ScoreLoader","Importing using importer "+e.name),e.init(a,t),i=e.readScore(),re.debug("ScoreLoader","Score imported using "+e.name);break}catch(t){if(!(t instanceof K))throw re.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;re.debug("ScoreLoader",e.name+" does not support the file")}}if(i)return i;throw new K("No compatible importer found for file")}}class nr{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 or{get width(){return this.element.offsetWidth}set width(e){this.element.style.width=e+"px"}get scrollLeft(){return this.element.scrollLeft}set scrollLeft(e){this.element.scrollLeft=e}get scrollTop(){return this.element.scrollTop}set scrollTop(e){this.element.scrollTop=e}get height(){return this.element.offsetHeight}set height(e){this.element.style.height=e>=0?e+"px":"100%"}get isVisible(){return!!this.element.offsetWidth||!!this.element.offsetHeight||!!this.element.getClientRects().length}constructor(e){this._resizeListeners=0,this.lastBounds=new ds,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new nr(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new nr(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new nr(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&or.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,or.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=""}}or.resizeObserver=new ie((()=>new ResizeObserver((e=>{for(const t of e){let e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class hr{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new fa,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(Tl.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0,t=window.setInterval((()=>{re.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);re.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);let s=e=>{this._families.length>1?(re.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(re.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},i=e=>{re.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 re.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){re.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 lr{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 dr{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new ma,this.samplesPlayed=new fa,this.sampleRequest=new ma}get sampleRate(){return this._context?this._context.sampleRate:dr.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(re.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{re.debug("WebAudio",`Audio Context resume success: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}`),e&&e()}),(e=>{re.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,dr.PreferredSampleRate),s=e.createBufferSource();s.buffer=t,s.connect(e.destination),s.start(0),s.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in Tl.globalThis)return new AudioContext;if("webkitAudioContext"in Tl.globalThis)return new webkitAudioContext;throw new j(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,dr.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()}}dr.BufferSize=4096,dr.PreferredSampleRate=44100;class cr extends dr{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/dr.BufferSize),this._circularBuffer=new lr(dr.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*dr.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*dr.BufferSize<t){for(let t=0;t<e;t++)this.onSampleRequest();this._requestedBufferCount+=e}}generateSound(e){let t=e.outputBuffer.getChannelData(0),s=e.outputBuffer.getChannelData(1),i=t.length+s.length,a=this._outputBuffer;a.length!==i&&(a=new Float32Array(i),this._outputBuffer=a);const r=this._circularBuffer.read(a,0,Math.min(a.length,this._circularBuffer.count));let n=0;const o=Math.min(t.length,r);for(let e=0;e<o;e++)t[e]=a[n++],s[e]=a[n++];if(r<t.length)for(let e=r;e<t.length;e++)t[e]=0,s[e]=0;this.onSamplesPlayed(r/Re.AudioChannels),this.requestBuffers()}}class ur{constructor(e,t){this.loaded=e,this.total=t}}class pr{get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return re.logLevel}set logLevel(e){re.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Re.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Re.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Re.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=le.clamp(e,Re.MinPlaybackSpeed,Re.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=Es.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 ma,this.readyForPlayback=new ma,this.finished=new ma,this.soundFontLoaded=new ma,this.soundFontLoadFailed=new fa,this.midiLoaded=new fa,this.midiLoadFailed=new fa,this.stateChanged=new fa,this.positionChanged=new fa,this.midiEventsPlayed=new fa,this.playbackRangeChanged=new fa,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Es.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=Tl.createWebWorker(t)}catch(e){re.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:ss.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,s){re.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=>{re.error("AlphaSynth","Loading failed: "+e.message),this.soundFontLoadFailed.trigger(new ar(e.message,i))},i.onprogress=e=>{re.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),s(new ur(e.loaded,e.total))},i.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:ss.midiFileToJsObject(e)})}applyTranspositionPitches(e){this._synth.postMessage({cmd:"alphaSynth.applyTranspositionPitches",transpositionPitches:JSON.stringify(Array.from(e.entries()))})}setChannelTranspositionPitch(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelTranspositionPitch",channel:e,semitones:t})}setChannelMute(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelMute",channel:e,mute:t})}resetChannelStates(){this._synth.postMessage({cmd:"alphaSynth.resetChannelStates"})}setChannelSolo(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelSolo",channel:e,solo:t})}setChannelVolume(e,t){t=Math.max(t,Re.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 ci(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new ya(t.events.map(ss.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new di(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new ba(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 ci(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 gr{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new fa,this.partialRenderFinished=new fa,this.partialLayoutFinished=new fa,this.renderFinished=new fa,this.postRenderFinished=new ma,this.error=new fa,this._api=e;try{this._worker=Tl.createWebWorker(t)}catch(e){return void re.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=ss.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=Ea.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:ss.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:s,trackIndexes:t,fontSizes:ka.FontSizeLookupTables})}}class mr{constructor(e,t,s,i){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=s,this.selectionWrapper=i}}class fr{static init(){var e;fr._isRegistered||(fr._isRegistered=!0,registerProcessor("alphatab",((e=class extends AudioWorkletProcessor{constructor(t){super(t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,this._isStopped=!1,re.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new lr(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){let t=e.data;switch(t.cmd){case _a.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case _a.CmdOutputResetSamples:this._circularBuffer.clear();break;case _a.CmdOutputStop:this._isStopped=!0}}process(e,t,s){if(1!==t.length&&2!==t[0].length)return!1;let i=t[0][0],a=t[0][1];if(!i||!a)return!0;let r=i.length+a.length,n=this._outputBuffer;n.length!==r&&(n=new Float32Array(r),this._outputBuffer=n);const o=this._circularBuffer.read(n,0,Math.min(n.length,this._circularBuffer.count));let h=0;const l=Math.min(i.length,o);for(let e=0;e<l;e++)i[e]=n[h++],a[e]=n[h++];if(o<i.length)for(let e=o;e<i.length;e++)i[e]=0,a[e]=0;return this.port.postMessage({cmd:_a.CmdOutputSamplesPlayed,samples:o/Re.AudioChannels}),this.requestBuffers(),this._circularBuffer.count>0||!this._isStopped}requestBuffers(){const t=this._bufferCount/2|0;let s=t*e.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*e.BufferSize<s){for(let e=0;e<t;e++)this.port.postMessage({cmd:_a.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}fr._isRegistered=!1;class yr extends dr{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;Tl.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=>{re.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){let t=e.data;switch(t.cmd){case _a.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case _a.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.postMessage({cmd:_a.CmdOutputStop}),this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){this._worklet?.port.postMessage({cmd:_a.CmdOutputAddSamples,samples:e})}resetSamples(){this._worklet?.port.postMessage({cmd:_a.CmdOutputResetSamples})}}class br extends or{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"}(Hs||(Hs={}));class Sr{get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(Tl.bravuraFontChecker.checkForFontAvailability(),!Tl.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(re.debug("Font","All fonts loaded: "+this._fontCheckers.size),!0)}onFontLoaded(e){ka.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 ma,this.canRenderChanged=new ma,this._highlightedElements=[],this._scrollContainer=null,Tl.webPlatform!==Rs.Browser&&Tl.webPlatform!==Rs.BrowserModule)throw new j(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 or(e),this.areWorkersSupported="Worker"in window,Tl.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!==Hs.RenderRequested&&(s.resultState=Hs.RenderRequested,this._api.renderer.renderResult(s.layoutResultId)):e.replaceChildren():s.resultState===Hs.Detached&&(e.replaceChildren(...s.renderedResult),s.resultState=Hs.RenderDone):s.resultState===Hs.RenderDone&&(s.resultState=Hs.Detached,s.replaceChildren())}}}createWorkerRenderer(){return new gr(this._api,this._api.settings)}initialize(e,t){let s;this._api=e,s=t instanceof Ot?t:ss.jsObjectToSettings(t);let i=this.getDataAttributes();At.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 hr(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 or(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 Ne)return t(e),!0;if(e instanceof ArrayBuffer){let s=new Uint8Array(e);return t(rr.loadScoreFromBytes(s,this._api.settings)),!0}return e instanceof Uint8Array?(t(rr.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(rr.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&&rr.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;Tl.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=Hs.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=Hs.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===$e.WebAudioAudioWorklets?(re.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),e=new pr(new yr(this._api.settings),this._api.settings)):t&&(re.debug("Player","Will use webworkers for synthesizing and web audio api with ScriptProcessor for playback"),e=new pr(new cr,this._api.settings)),e?e.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):re.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 mr(new or(t),i,a,new or(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 ds;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 or(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new br(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 _r extends ir{constructor(e,t){super(new Sr(e),t),this.soundFontLoad=new fa}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,d=a.offsetWidth+50,c=window.innerHeight,u=(h/2|0)-(d/2|0)+n,p=(l/2|0)-(c/2|0)+o;i.resizeTo(d,c),i.moveTo(u,p),i.focus();let g=ss.jsObjectToSettings(ss.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,At.fromJson(g,s);let m=new _r(a,g);i.onunload=()=>{m.destroy()},m.renderer.postRenderFinished.on((()=>{i.print()})),m.renderTracks(this.tracks)}downloadMidi(e=qe.SingleTrackMultiChannel){if(!this.score)return;let t=new ot;t.format=e;let s=new Ma(t,!0);new Ja(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 wr{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 re.error("Api","Method '"+t+"' does not exist on jQuery.alphaTab"),null}init(e,t,s){if(!t){t=new _r(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 Br{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.scale=1,this.color=new Ce(255,255,255,255),this.lineWidth=1,this.font=new rt("Arial",10,Je.Plain),this.textAlign=D.Left,this.textBaseline=L.Top}destroy(){}beginRender(e,t){this.scale=this.settings.display.scale,this.buffer=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${0|e}px" height="${0|t}px" class="at-surface-svg">\n`,this._currentPath="",this._currentPathIsEmpty=!0,this.textBaseline=L.Top}beginGroup(e){this.buffer+=`<g class="${e}">`}endGroup(){this.buffer+="</g>"}endRender(){return this.buffer+="</svg>",this.buffer}fillRect(e,t,s,i){s>0&&(this.buffer+=`<rect x="${e*this.scale|0}" y="${t*this.scale|0}" width="${s*this.scale}" height="${i*this.scale}" fill="${this.color.rgba}" />\n`)}strokeRect(e,t,s,i){const a=this.lineWidth*this.scale%2==0?0:.5;this.buffer+=`<rect x="${(e*this.scale|0)+a}" y="${(t*this.scale|0)+a}" width="${s*this.scale}" height="${i*this.scale}" stroke="${this.color.rgba}"`,1!==this.lineWidth&&(this.buffer+=` stroke-width="${this.lineWidth*this.scale}"`),this.buffer+=' fill="transparent" />\n'}beginPath(){}closePath(){this._currentPath+=" z"}moveTo(e,t){this._currentPath+=` M${e*this.scale},${t*this.scale}`}lineTo(e,t){this._currentPathIsEmpty=!1,this._currentPath+=` L${e*this.scale},${t*this.scale}`}quadraticCurveTo(e,t,s,i){this._currentPathIsEmpty=!1,this._currentPath+=` Q${e*this.scale},${t*this.scale},${s*this.scale},${i*this.scale}`}bezierCurveTo(e,t,s,i,a,r){this._currentPathIsEmpty=!1,this._currentPath+=` C${e*this.scale},${t*this.scale},${s*this.scale},${i*this.scale},${a*this.scale},${r*this.scale}`}fillCircle(e,t,s){this._currentPathIsEmpty=!1,e*=this.scale,t*=this.scale,s*=this.scale,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.fill()}strokeCircle(e,t,s){this._currentPathIsEmpty=!1,e*=this.scale,t*=this.scale,s*=this.scale,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.stroke()}fill(){this._currentPathIsEmpty||(this.buffer+=`<path d="${this._currentPath}"`,"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),this.buffer+=' style="stroke: none"/>'),this._currentPath="",this._currentPathIsEmpty=!0}stroke(){if(!this._currentPathIsEmpty){let e=`<path d="${this._currentPath}" stroke="${this.color.rgba}"`;1===this.lineWidth&&1===this.scale||(e+=` stroke-width="${this.lineWidth*this.scale}"`),e+=' style="fill: none" />',this.buffer+=e}this._currentPath="",this._currentPathIsEmpty=!0}fillText(e,t,s){if(""===e)return;let i=`<text x="${t*this.scale|0}" y="${s*this.scale|0}" style='stroke: none; font:${this.font.toCssString(this.settings.display.scale)}; ${this.getSvgBaseLine()}'`;"#000000"!==this.color.rgba&&(i+=` fill="${this.color.rgba}"`),this.textAlign!==D.Left&&(i+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),i+=`>${Br.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 D.Left:return"start";case D.Center:return"middle";case D.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case L.Top:return"dominant-baseline: hanging";case L.Bottom:return"dominant-baseline: ideographic";default:return""}}measureText(e){return e?ka.measureString(e,this.font.families,this.font.size*this.scale,this.font.style,this.font.weight):new de(0,0)}onRenderFinished(){return null}beginRotate(e,t,s){this.buffer+='<g transform="translate('+e*this.scale+" ,"+t*this.scale+") rotate( "+s+')">'}endRotate(){this.buffer+="</g>"}}class kr extends Br{constructor(){super()}fillMusicFontSymbol(e,t,s,i,a){i!==F.None&&this.fillMusicFontSymbolText(e,t,s,`&#${i};`,a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(let e of i)e!==F.None&&(r+=`&#${e};`);this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){e*=this.scale,t*=this.scale,this.buffer+=`<g transform="translate(${e} ${t})" class="at" ><text`;const r=this.scale*s;this.buffer+=1!==r?` style="font-size: ${100*r}%; stroke:none"`:' style="stroke:none"',"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),a&&(this.buffer+=' text-anchor="'+this.getSvgTextAlignment(D.Center)+'"'),this.buffer+=`>${i}</text></g>`}}class Tr{constructor(){this.isInsideBracket=!0,this.isRelevantForBoundsLookup=!0,this.hideOnMultiTrack=!1,this.hideOnPercussionTrack=!1}canCreate(e,t){return!this.hideOnPercussionTrack||!t.isPercussion}}!function(e){e[e.PreNotes=0]="PreNotes",e[e.OnNotes=1]="OnNotes",e[e.MiddleNotes=2]="MiddleNotes",e[e.Stem=3]="Stem",e[e.PostNotes=4]="PostNotes",e[e.EndBeat=5]="EndBeat"}(Gs||(Gs={}));class xr extends qa{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 Nr extends xr{constructor(){super(0,0),this.glyphs=[]}addGlyph(e){e.x=0===this.glyphs.length?0:this.glyphs[this.glyphs.length-1].x+this.glyphs[this.glyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.width=e.x+e.width,super.addGlyph(e)}}class vr extends xr{constructor(e,t,s){super(e,t),this.voice=s,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){let t=this.renderer.layoutingInfo.spaceToForce(e);this.scaleToForce(t)}scaleToForce(e){this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e);let t=this.renderer.layoutingInfo.buildOnTimePositions(e),s=this.beatGlyphs;for(let e=0,i=s.length;e<i;e++){let a=s[e];if(a.beat.graceType===m.None)a.x=t.get(a.beat.absoluteDisplayStart)-a.onTimeX;else{const i=a.beat.graceGroup.beats[0].absoluteDisplayStart,r=a.beat.graceGroup.id;if(a.beat.graceGroup.isComplete&&t.has(i)){a.x=t.get(i)-a.onTimeX;let e=this.renderer.layoutingInfo.allGraceRods.get(r);const s=a.beat.graceGroup.beats[a.beat.graceGroup.beats.length-1].nextBeat,n=s?this.renderer.layoutingInfo.getPreBeatSize(s)+Za.GraceBeatPadding:0;a.x-=n,a.x-=e[a.beat.graceIndex].postSpringWidth,a.x+=e[a.beat.graceIndex].graceBeatWidth;const o=e[a.beat.graceGroup.beats.length-1];a.x-=o.graceBeatWidth}else{let t=this.renderer.layoutingInfo.incompleteGraceRods.get(r);const i=t[a.beat.graceIndex].postSpringWidth-t[a.beat.graceIndex].preSpringWidth;e>0?0===a.beat.graceIndex?a.x=s[e-1].x+s[e-1].width:a.x=s[e-1].x+t[a.beat.graceIndex-1].postSpringWidth-t[a.beat.graceIndex-1].preSpringWidth-i:a.x=-i}}if(e>0){let t=a.x-s[e-1].x;s[e-1].scaleToWidth(t)}if(e===i-1){let e=this.width-s[s.length-1].x;a.scaleToWidth(e)}}}registerLayoutingInfo(e){let t=this.beatGlyphs;for(let s of t)s.registerLayoutingInfo(e)}applyLayoutingInfo(e){let t=this.beatGlyphs;for(let s of t)s.applyLayoutingInfo(e);this.scaleToForce(Math.max(this.renderer.settings.display.stretchForce,e.minStretchForce))}addGlyph(e){let t=e;e.x=0===this.beatGlyphs.length?0:this.beatGlyphs[this.beatGlyphs.length-1].x+this.beatGlyphs[this.beatGlyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.beatGlyphs.push(t),this.width=e.x+e.width,t.beat.hasTuplet&&t.beat.tupletGroup.beats[0].id===t.beat.id&&this.tupletGroups.push(t.beat.tupletGroup)}doLayout(){}paint(e,t,s){s.color=0===this.voice.index?this.renderer.resources.mainGlyphColor:this.renderer.resources.secondaryGlyphColor;for(let i=0,a=this.beatGlyphs.length;i<a;i++)this.beatGlyphs[i].paint(e+this.x,t+this.y,s)}}vr.KeySizeBeat="Beat";class Pr{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class Cr{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:ue.getArticulationByValue(t)?.staffLine??0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case b.ForceDoubleFlat:t+=2;break;case b.ForceDoubleSharp:t-=2;break;case b.ForceFlat:t+=1;break;case b.ForceSharp:t-=1}return t}applyAccidental(e){const t=Cr.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=Cr.getNoteValue(t);return s=e.staff.isPercussion?Cr.getPercussionLine(e,i):Cr.calculateNoteLine(e,i),s}static computeAccidental(e,t,s,i,a=null){let r=e+7,n=s%12,o=r<7?Xe.Flat:Xe.Sharp,h=Cr.KeySignatureLookup[r][n],l=Cr.AccidentalNotes[n],d=Xe.None;if(i)switch(d=l?o:Xe.Natural,d){case Xe.Natural:d=Xe.NaturalQuarterNoteUp;break;case Xe.Sharp:d=Xe.SharpQuarterNoteUp;break;case Xe.Flat:d=Xe.FlatQuarterNoteUp}else{switch(t){case b.ForceSharp:d=Xe.Sharp;break;case b.ForceDoubleSharp:d=Xe.DoubleSharp;break;case b.ForceFlat:d=Xe.Flat;break;case b.ForceDoubleFlat:d=Xe.DoubleFlat;break;default:l?d=o:h&&(d=Xe.Natural)}d!==Xe.None?null!=a?a===d&&(d=Xe.None):h&&d===o&&(d=Xe.None):null!==a&&(d=a===Xe.Natural?Xe.None:Xe.Natural)}return d}getAccidental(e,t,s,i,a=null){let r=0,n=Xe.None;if(this._bar.staff.isPercussion)r=Cr.getPercussionLine(this._bar,e);else{const s=a?a.accidentalMode:b.Default;r=Cr.calculateNoteLine(this._bar,e);const i=this._registeredAccidentals.has(r)?this._registeredAccidentals.get(r):null;n=Cr.computeAccidental(this._bar.masterBar.keySignature,s,e,t,i);let o=!1;switch(n){case Xe.NaturalQuarterNoteUp:case Xe.SharpQuarterNoteUp:case Xe.FlatQuarterNoteUp:break;default:if(a&&a.isTieDestination&&0===a.beat.index){const e=this._barRenderer.previousRenderer;if(e){e.accidentalHelper.getNoteLine(a.tieOrigin)===r&&(o=!0)}}o?n=Xe.None:n!==Xe.None&&this._registeredAccidentals.set(r,n)}}return a?(this._appliedScoreLines.set(a.id,r),this._notesByValue.set(e,a)):this._appliedScoreLinesByValue.set(e,r),(-1e3===this.minLine||this.minLine<r)&&(this.minLine=r,this.minLineBeat=s),(-1e3===this.maxLine||this.maxLine>r)&&(this.maxLine=r,this.maxLineBeat=s),i||this.registerLine(s,r),n}registerLine(e,t){let s;this._beatLines.has(e.id)?s=this._beatLines.get(e.id):(s=new Pr,this._beatLines.set(e.id,s)),(-1e3===s.minLine||t<s.minLine)&&(s.minLine=t),(-1e3===s.minLine||t>s.maxLine)&&(s.maxLine=t)}getMaxLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).maxLine:0}getMinLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).minLine:0}static calculateNoteLine(e,t){let s=t,i=e.masterBar.keySignature,a=e.clef,r=s%12,n=(s/12|0)-1,o=Cr.OctaveSteps[a];return o-=n*Cr.StepsPerOctave,o-=(le.keySignatureIsSharp(i)||le.keySignatureIsNatural(i)?Cr.SharpNoteSteps:Cr.FlatNoteSteps)[r],o}getNoteLine(e){return this._appliedScoreLines.get(e.id)}getNoteLineForValue(e,t=!1){return this._appliedScoreLinesByValue.has(e)?this._appliedScoreLinesByValue.get(e):t&&this._notesByValue.has(e)?this.getNoteLine(this._notesByValue.get(e)):0}}Cr.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]],Cr.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],Cr.StepsPerOctave=7,Cr.OctaveSteps=[38,32,30,26,38],Cr.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],Cr.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class Er{constructor(){this.staffId="",this.up=0,this.down=0}}class Fr{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 Dr{get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}hasLine(e,t){return e&&this.beatHasLine(t)||!e&&1===this.beats.length&&this.beatHasLine(t)}beatHasLine(e){return e.duration>p.Whole}hasFlag(e,t){return e&&this.beatHasFlag(t)||!e&&1===this.beats.length&&this.beatHasFlag(this.beats[0])}beatHasFlag(e){return!e.isRest&&(e.duration>p.Quarter||e.graceType!==m.None)}constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=p.QuadrupleWhole,this.hasTuplet=!1,this.slashBeats=[],this._firstBeatLowestNoteCompareValue=-1,this._firstBeatHighestNoteCompareValue=-1,this._lastBeatLowestNoteCompareValue=-1,this._lastBeatHighestNoteCompareValue=-1,this.lowestNoteInHelper=null,this._lowestNoteCompareValueInHelper=-1,this.highestNoteInHelper=null,this._highestNoteCompareValueInHelper=-1,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isGrace=!1,this.minRestLine=null,this.beatOfMinRestLine=null,this.maxRestLine=null,this.beatOfMaxRestLine=null,this.direction=Ge.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}getBeatLineX(e,t){return t=t??this.direction,this.hasBeatLineX(e)?t===Ge.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 Er),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(Ge.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==m.None)&&(e=this.invert(Ge.Up)):e=Ge.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){let t=this._renderer.getNoteY(this.highestNoteInHelper,zs.Center),s=this._renderer.getNoteY(this.lowestNoteInHelper,zs.Center);if(null===e){const i=(t+s)/2;e=this.invert(this._renderer.middleYPosition<i?Ge.Up:Ge.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(Ge.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:return[2,2];case p.Whole:return[0,1];case p.Half:return[1,0];case p.Quarter:return[3,3];case p.Eighth:return[2,2];case p.Sixteenth:return[2,4];case p.ThirtySecond:return[4,4];case p.SixtyFourth:return[4,6];case p.OneHundredTwentyEighth:return[6,6];case p.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=Dr.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===Ge.Down?Ge.Up:Ge.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 G.Auto:case G.ForceSplitOnSecondaryToNext:t=Dr.canJoin(this.beats[this.beats.length-1],e);break;case G.ForceSplitToNext:t=!1;break;case G.ForceMergeWithNext:t=!0}return t&&(null==this.preferredBeamDirection&&null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.hasTuplet&&(this.hasTuplet=!0),e.graceType!==m.None&&(this.isGrace=!0),e.isRest?0===this.beats.length&&this.beats.push(e):(this.isRestBeamHelper&&(this.beats=[]),this.beats.push(e),this.checkNote(e.minNote),this.checkNote(e.maxNote),this.shortestDuration<e.duration&&(this.shortestDuration=e.duration),this._firstNonRestBeat||(this._firstNonRestBeat=e),this._lastNonRestBeat=e),e.slashed&&this.slashBeats.push(e)),t}checkNote(e){if(!e)return;let t,s;this.voice&&e.isPercussion?(t=-Cr.getPercussionLine(this.voice.bar,Cr.getNoteValue(e)),s=t):(t=Cr.getNoteValue(e),s=t,e.harmonicType!==y.None&&e.harmonicType!==y.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===m.BendGrace||t.graceType===m.BendGrace)return!1;if(e.graceType!==m.None&&t.graceType!==m.None)return!0;let s=e.voice.bar;if(s!==t.voice.bar)return!1;let i=e.playbackStart,a=t.playbackStart;if(!Dr.canJoinDuration(e.duration)||!Dr.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=ee.QuarterTime;if(8===s.masterBar.timeSignatureDenominator)s.masterBar.timeSignatureNumerator%3==0&&(r+=ee.QuarterTime/2|0);return((r+i)/r|0)===((r+a)/r|0)}static canJoinDuration(e){switch(e){case p.Whole:case p.Half:case p.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,s){return le.getIndex(e.duration)-2-s>0&&le.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 Lr{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class Mr{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new Lr(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 Ir{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 Mr(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=Dr.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 Ar{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this.preferredBeamDirection=null,this._renderer=e,this.collisionHelper=new Ir}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!==m.None?n=i:(n=s,i=null),n&&n.checkBeat(o)||(n&&n.finish(),n=new Dr(t.staff,e),n.preferredBeamDirection=this.preferredBeamDirection,n.checkBeat(o),o.graceType!==m.None?i=n:s=n,this.beamHelpers[r.index].push(n)),this.beamHelperLookup[r.index].set(o.index,n)}s&&s.finish(),i&&i.finish(),s=null,i=null}}getBeamingHelperForBeat(e){return this.beamHelperLookup[e.voice.index].get(e.index)}}class Or extends ja{constructor(e,t,s){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=s}doLayout(){super.doLayout();let e=this.renderer.resources;this._textRow=1.5*e.effectFont.size,this._fretRow=1.5*e.effectFont.size,this._chord.firstFret>1?this._firstFretSpacing=Or.FretSpacing:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+Or.Frets*Or.FretSpacing+2*Or.Padding[1],this.width=this._firstFretSpacing+(this._chord.staff.tuning.length-1)*Or.StringSpacing+2*Or.Padding[0]}paint(e,t,s){e+=this.x+Or.Padding[0]+this._firstFretSpacing,t+=this.y;let i=Or.StringSpacing,a=Or.FretSpacing,r=this.renderer.resources,n=Or.CircleRadius,o=this.width-2*Or.Padding[0]-this._firstFretSpacing,h=s.textAlign,l=s.textBaseline;s.font=r.effectFont,s.textAlign=D.Center,s.textBaseline=L.Top,this._chord.showName&&s.fillText(this._chord.name,e+o/2,t+r.effectFont.size/2),t+=this._textRow,s.font=r.fretboardNumberFont,s.textBaseline=L.Middle;for(let a=0;a<this._chord.staff.tuning.length;a++){let r=e+a*i,n=t+this._fretRow/2,o=this._chord.strings[this._chord.staff.tuning.length-a-1];o<0?s.fillMusicFontSymbol(r,n,1,F.FretboardX,!0):0===o?s.fillMusicFontSymbol(r,n,1,F.FretboardO,!0):(o-=this._chord.firstFret-1,s.fillText(o.toString(),r,n))}t+=this._fretRow;for(let r=0;r<this._chord.staff.tuning.length;r++){let n=e+r*i;s.fillRect(n,t,1,a*Or.Frets+1)}this._chord.firstFret>1&&(s.textAlign=D.Left,s.fillText(this._chord.firstFret.toString(),e-this._firstFretSpacing,t+a/2)),s.fillRect(e,t-1,o,2);for(let i=0;i<=Or.Frets;i++){let r=t+i*a;s.fillRect(e,r,o,1)}let d=new Map;for(let e of this._chord.barreFrets){let t=[-1,-1];d.set(e-this._chord.firstFret,t)}for(let r=0;r<this._chord.strings.length;r++){let o=this._chord.strings[r];if(o>0){if(o-=this._chord.firstFret,d.has(o)){let e=d.get(o);(-1===e[0]||r<e[0])&&(e[0]=r),(-1===e[1]||r>e[1])&&(e[1]=r)}let h=t+o*a+a/2+.5,l=e+(this._chord.strings.length-r-1)*i;s.fillCircle(l,h,n)}}for(const[r,o]of d){let h=t+r*a+a/2+.5,l=e+(this._chord.strings.length-o[1]-1)*i,d=e+(this._chord.strings.length-o[0]-1)*i;s.fillRect(l,h-n,d-l,2*n)}s.textAlign=h,s.textBaseline=l}}Or.Padding=[5,2],Or.Frets=5,Or.CircleRadius=2.5,Or.StringSpacing=10,Or.FretSpacing=12;class Rr extends xr{constructor(e,t,s=D.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=s}doLayout(){let e=0;switch(this._align){case D.Left:e=0;break;case D.Center:e=(this.width-this._glyphWidth)/2;break;case D.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 Vr extends xr{constructor(e,t,s=D.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=s}doLayout(){let e=0,t=0,s=Vr.Padding;this._rows=[];let i=new Rr(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 Rr(e,t,this._align),i.width=this.width,i.addGlyphToRow(a),e+=a.width);i.isEmpty||(i.doLayout(),this._rows.push(i),t+=i.height+s),this.height=t}paint(e,t,s){for(let i of this._rows)i.paint(e+this.x,t+this.y,s)}}Vr.Padding=3;class Hr extends Vr{constructor(e,t){super(e,t)}addChord(e){if(e.strings.length>0){let t=new Or(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}}class Gr extends ja{constructor(e,t,s,i,a=D.Left,r=null){super(e,t),this._lineHeights=null,this._lines=s.split("\n"),this.font=i,this.textAlign=a,this.textBaseline=r}doLayout(){super.doLayout(),this._lineHeights=[];const e=this.renderer.scoreRenderer.canvas;for(const t of this._lines){e.font=this.font;const s=e.measureText(t),i=s.height;this._lineHeights.push(i),this.height+=i,this.width=Math.max(this.width,s.width)}}paint(e,t,s){let i=s.color;s.color=i,s.font=this.font;let a=s.textAlign,r=s.textBaseline;s.textAlign=this.textAlign,null!==this.textBaseline&&(s.textBaseline=this.textBaseline);let n=t+this.y;for(let t=0;t<this._lines.length;t++)s.fillText(this._lines[t],e+this.x,n),n+=this._lineHeights[t];s.textAlign=a,s.textBaseline=r}}class Wr{get staveId(){return this._factory.staffId}get contentTop(){return this.y+this.staveTop+this.topSpacing+this.topOverflow}get contentBottom(){return this.y+this.topSpacing+this.topOverflow+this.staveBottom}constructor(e,t,s){this._sharedLayoutData=new Map,this.barRenderers=[],this.x=0,this.y=0,this.height=0,this.index=0,this.staffIndex=0,this.isFirstInSystem=!1,this.trackIndex=0,this.staveTop=0,this.topSpacing=0,this.bottomSpacing=0,this.staveBottom=0,this._factory=s,this.trackIndex=e,this.modelStaff=t}getSharedLayoutData(e,t){return this._sharedLayoutData.has(e)?this._sharedLayoutData.get(e):t}setSharedLayoutData(e,t){this._sharedLayoutData.set(e,t)}get isInsideBracket(){return this._factory.isInsideBracket}get isRelevantForBoundsLookup(){return this._factory.isRelevantForBoundsLookup}registerStaffTop(e){this.staveTop=e}registerStaffBottom(e){this.staveBottom=e}addBarRenderer(e){e.staff=this,e.index=this.barRenderers.length,e.reLayout(),this.barRenderers.push(e),this.system.layout.registerBarRenderer(this.staveId,e)}addBar(e,t){let s;s=e?this._factory.create(this.system.layout.renderer,e):new tn(this.system.layout.renderer,e),s.staff=this,s.index=this.barRenderers.length,s.layoutingInfo=t,s.doLayout(),s.registerLayoutingInfo();const i=s.barDisplayWidth;i>0&&this.system.layout.systemsLayoutMode==Ws.FromModelWithWidths&&(s.width=i),this.barRenderers.push(s),e&&this.system.layout.registerBarRenderer(this.staveId,s)}revertLastBar(){let e=this.barRenderers[this.barRenderers.length-1];this.barRenderers.splice(this.barRenderers.length-1,1),this.system.layout.unregisterBarRenderer(this.staveId,e);for(const e of this.barRenderers)e.applyLayoutingInfo();return e}scaleToWidth(e){this._sharedLayoutData=new Map;let t=this.topOverflow,s=0;switch(this.system.layout.systemsLayoutMode){case Ws.Automatic:let i=(e-this.system.computedWidth)/this.barRenderers.length;for(const e of this.barRenderers){e.x=s,e.y=this.topSpacing+t;let a=e.computedWidth+i;e.scaleToWidth(a),s+=e.width}break;case Ws.FromModelWithScale:e-=this.system.accoladeWidth;const a=this.system.totalBarDisplayScale;for(const i of this.barRenderers){i.x=s,i.y=this.topSpacing+t;const r=i.barDisplayScale*e/a;i.scaleToWidth(r),s+=i.width}break;case Ws.FromModelWithWidths:for(const e of this.barRenderers){e.x=s,e.y=this.topSpacing+t;const i=e.barDisplayWidth;i>0?e.scaleToWidth(i):e.scaleToWidth(e.computedWidth),s+=e.width}}}get topOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){let s=this.barRenderers[t];s.topOverflow>e&&(e=s.topOverflow)}return e}get bottomOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){let s=this.barRenderers[t];s.bottomOverflow>e&&(e=s.bottomOverflow)}return e}calculateHeightForAccolade(){this.topSpacing=this._factory.getStaffPaddingTop(this),this.bottomSpacing=this._factory.getStaffPaddingBottom(this),this.height=this.barRenderers.length>0?this.barRenderers[0].height:0,this.height>0&&(this.height+=this.topSpacing+this.topOverflow+this.bottomOverflow+this.bottomSpacing)}finalizeStaff(){this.topSpacing=this._factory.getStaffPaddingTop(this),this.bottomSpacing=this._factory.getStaffPaddingBottom(this),this.height=0;let e=!1,t=this.topOverflow;for(let s=0;s<this.barRenderers.length;s++)this.barRenderers[s].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[s].height),this.barRenderers[s].finalizeRenderer()&&(e=!0);if(e){t=this.topOverflow;for(let e=0;e<this.barRenderers.length;e++)this.barRenderers[e].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[e].height),this.barRenderers[e].finalizeRenderer()}this.height>0&&(this.height+=this.topSpacing+t+this.bottomOverflow+this.bottomSpacing)}paint(e,t,s,i,a){if(0!==this.height&&0!==a)for(let r=i,n=Math.min(i+a,this.barRenderers.length);r<n;r++)this.barRenderers[r].paint(e+this.x,t+this.y,s)}}class zr{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 Ur{constructor(){this._timeSortedSprings=[],this._xMin=0,this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,this.version=0,this.preBeatSize=0,this.postBeatSize=0,this.minStretchForce=0,this.totalSpringConstant=0,this.incompleteGraceRods=new Map,this.allGraceRods=new Map,this.springs=new Map,this.height=0}updateMinStretchForce(e){this.minStretchForce<e&&(this.minStretchForce=e)}getPreBeatSize(e){if(e.graceType!==m.None){const t=e.graceGroup.id;return this.allGraceRods.get(t)[e.graceIndex].preBeatWidth}{const t=e.absoluteDisplayStart;return this.springs.has(t)?this.springs.get(t).preBeatWidth:0}}getPostBeatSize(e){if(e.graceType!==m.None){const t=e.graceGroup.id;return this.allGraceRods.get(t)[e.graceIndex].postSpringWidth}{const t=e.absoluteDisplayStart;return this.springs.has(t)?this.springs.get(t).postSpringWidth:0}}addSpring(e,t,s,i,a){let r;if(this.version++,this.springs.has(e))r=this.springs.get(e),r.postSpringWidth<a&&(r.postSpringWidth=a),r.graceBeatWidth<s&&(r.graceBeatWidth=s),r.preBeatWidth<i&&(r.preBeatWidth=i),t<r.smallestDuration&&(r.smallestDuration=t),t>r.longestDuration&&(r.longestDuration=t),r.allDurations.add(t);else{if(r=new zr,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!==m.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 zr;r.timePosition=i,r.postSpringWidth=s,r.preBeatWidth=t,e.graceGroup.isComplete||(this.incompleteGraceRods.get(a)[e.graceIndex]=r),this.allGraceRods.get(a)[e.graceIndex]=r}}else{let a=0;if(e.graceGroup&&this.allGraceRods.has(e.graceGroup.id))for(const t of this.allGraceRods.get(e.graceGroup.id))a+=t.springWidth;this.addSpring(i,e.displayDuration,a,t,s)}}finish(){for(const[e,t]of this.allGraceRods){let e=0;for(const s of t)e+=s.preBeatWidth,s.graceBeatWidth=e,e+=s.postSpringWidth}this._incompleteGraceRodsWidth=0;for(const e of this.incompleteGraceRods.values())for(const t of e)this._incompleteGraceRodsWidth+=t.preBeatWidth+t.postSpringWidth;this.calculateSpringConstants(),this.version++}calculateSpringConstants(){this._xMin=0;let e=this.springs;for(const t of e.values())t.springWidth<this._xMin&&(this._xMin=t.springWidth);let t=0,s=this._timeSortedSprings;if(0===s.length)return this.totalSpringConstant=-1,void(this.minStretchForce=-1);for(let e=0;e<s.length;e++){let i=s[e],a=0;if(e===s.length-1)a=i.longestDuration;else{let t=s[e+1];a=Math.abs(t.timePosition-i.timePosition)}i.springConstant=this.calculateSpringConstant(i,a),t+=1/i.springConstant}this.totalSpringConstant=1/t,this.minStretchForce=0;for(let e=0;e<s.length;e++){let t=s[e],i=0;if(e===s.length-1)i=t.postSpringWidth;else{let a=s[e+1];i=t.postSpringWidth+a.preSpringWidth}0===e&&(i+=t.preSpringWidth);let a=i*t.springConstant;this.updateMinStretchForce(a)}}paint(e,t,s){}calculateSpringConstant(e,t){return t<=0&&(t=ee.toTicks(p.SixtyFourth)),0===e.smallestDuration&&(e.smallestDuration=t),e.smallestDuration/t*(1/((1+.85*Math.log2(t/Ur.MinDuration))*Ur.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(le.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}}Ur.MinDuration=30,Ur.MinDurationWidth=7;class Xr{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.renderers=[]}}class Jr{constructor(e,t){this.staves=[],this.stavesRelevantForBoundsLookup=[],this.firstStaffInBracket=null,this.lastStaffInBracket=null,this.bracket=null,this.staffSystem=e,this.track=t}addStaff(e){this.staves.push(e),e.isRelevantForBoundsLookup&&this.stavesRelevantForBoundsLookup.push(e)}}class Yr{constructor(){this.firstStaffInBracket=null,this.lastStaffInBracket=null,this.drawAsBrace=!1,this.braceScale=1,this.width=0,this.index=0}finalizeBracket(){if(this.firstStaffInBracket===this.lastStaffInBracket)return void(this.width=0);if(this.width=3,!this.drawAsBrace||!this.firstStaffInBracket||!this.lastStaffInBracket)return;const e=this.firstStaffInBracket.contentTop,t=(this.lastStaffInBracket.contentBottom-e)/Tl.MusicFontSize;this.braceScale=t,this.width=3*this.braceScale}}class qr extends Yr{constructor(e){super(),this.track=e,this.drawAsBrace=qr.isTrackDrawAsBrace(e)}includesStaff(e){return e.modelStaff.track===this.track}static isTrackDrawAsBrace(e){return e.staves.filter((e=>e.showStandardNotation)).length>1}}class jr extends qr{constructor(e){super(e)}includesStaff(e){return e.modelStaff.track===this.track||!this.drawAsBrace&&this.track.playbackInfo.program==e.modelStaff.track.playbackInfo.program}}class Kr{constructor(e){this._allStaves=[],this._firstStaffInBrackets=null,this._lastStaffInBrackets=null,this._accoladeSpacingCalculated=!1,this._brackets=[],this._hasSystemSeparator=!1,this.x=0,this.y=0,this.index=0,this.accoladeWidth=0,this.isFull=!1,this.width=0,this.computedWidth=0,this.totalBarDisplayScale=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[],this.layout=e,this.topPadding=e.renderer.settings.display.systemPaddingTop,this.bottomPadding=e.renderer.settings.display.systemPaddingBottom}get firstBarIndex(){return this.masterBarsRenderers[0].masterBar.index}get lastBarIndex(){return this.masterBarsRenderers[this.masterBarsRenderers.length-1].masterBar.index}addMasterBarRenderers(e,t){if(0===e.length)return null;this.masterBarsRenderers.push(t),t.layoutingInfo.preBeatSize=0;let s=0;for(let e=0,i=this.staves.length;e<i;e++){let i=this.staves[e];for(let e=0,a=i.staves.length;e<a;e++){let a=i.staves[e],r=t.renderers[s++];a.addBarRenderer(r)}}return this.calculateAccoladeSpacing(e),this.updateWidthFromLastBar(),t}addBars(e,t){if(0===e.length)return null;let s=new Xr;s.layoutingInfo=new Ur,s.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(s);let i=s.layoutingInfo;for(let e of this.staves)for(let a of e.staves){let r=e.track.staves[a.modelStaff.index].bars[t];a.addBar(r,i);let n=a.barRenderers[a.barRenderers.length-1];s.renderers.push(n),n.isLinkedToPrevious&&(s.isLinkedToPrevious=!0),n.canWrap||(s.canWrap=!1)}return this.calculateAccoladeSpacing(e),i.finish(),s.width=this.updateWidthFromLastBar(),s}revertLastBar(){if(this.masterBarsRenderers.length>1){let e=this.masterBarsRenderers[this.masterBarsRenderers.length-1];this.masterBarsRenderers.splice(this.masterBarsRenderers.length-1,1);let t=0,s=0;for(let e=0,i=this._allStaves.length;e<i;e++){let i=this._allStaves[e].revertLastBar();const a=i.computedWidth;a>t&&(t=a);const r=i.barDisplayScale;r>s&&(s=r)}return this.width-=t,this.computedWidth-=t,this.totalBarDisplayScale-=s,e}return null}updateWidthFromLastBar(){let e=0,t=0;for(let s=0,i=this._allStaves.length;s<i;s++){let i=this._allStaves[s];const a=i.barRenderers[i.barRenderers.length-1];a.applyLayoutingInfo(),a.computedWidth>e&&(e=a.computedWidth);const r=a.barDisplayScale;r>t&&(t=r)}return this.width+=e,this.computedWidth+=e,this.totalBarDisplayScale+=t,e}calculateAccoladeSpacing(e){const t=this.layout.renderer.settings;if(!this._accoladeSpacingCalculated){this._accoladeSpacingCalculated=!0,this.accoladeWidth=0;const s=this.layout.renderer.score.stylesheet;if(this.layout.renderer.settings.notation.isNotationElementVisible(x.TrackNames)){const i=1===this.layout.renderer.tracks.length?s.singleTrackTrackNamePolicy:s.multiTrackTrackNamePolicy,a=0===this.index?s.firstSystemTrackNameMode:s.otherSystemsTrackNameMode,r=0===this.index?s.firstSystemTrackNameOrientation:s.otherSystemsTrackNameOrientation;let n=!1;switch(i){case U.Hidden:break;case U.FirstSystem:n=0===this.index;break;case U.AllSystems:n=!0}let o=!1;if(n){let s=this.layout.renderer.canvas,i=t.display.resources.effectFont;s.font=i;for(let t of e){let e="";switch(a){case X.FullName:e=t.name;break;case X.ShortName:e=t.shortName}if(e.length>0){o=!0;const t=s.measureText(e);switch(r){case J.Horizontal:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,t.width));break;case J.Vertical:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,t.height))}}}o&&(this.accoladeWidth+=t.display.systemLabelPaddingLeft,this.accoladeWidth+=t.display.systemLabelPaddingRight)}}let i=0;for(let e of this._allStaves)e.y=i,e.calculateHeightForAccolade(),i+=e.height;let a=0;for(const e of this._brackets)e.finalizeBracket(),a=Math.max(a,e.width);this.accoladeWidth+=a,this.width+=this.accoladeWidth,this.computedWidth+=this.accoladeWidth}}getStaffTrackGroup(e){for(let t=0,s=this.staves.length;t<s;t++){let s=this.staves[t];if(s.track===e)return s}return null}addStaff(e,t){let s=this.getStaffTrackGroup(e);if(s||(s=new Jr(this,e),this.staves.push(s)),t.staffTrackGroup=s,t.system=this,t.index=this._allStaves.length,this._allStaves.push(t),s.addStaff(t),t.isInsideBracket){this._firstStaffInBrackets||(this._firstStaffInBrackets=t,t.isFirstInSystem=!0),s.firstStaffInBracket||(s.firstStaffInBracket=t),this._lastStaffInBrackets=t,s.lastStaffInBracket=t;let i=this._brackets.find((e=>e.includesStaff(t)));if(!i)switch(e.score.stylesheet.bracketExtendMode){case z.NoBrackets:break;case z.GroupStaves:i=new qr(e),i.index=this._brackets.length,this._brackets.push(i);break;case z.GroupSimilarInstruments:i=new jr(e),i.index=this._brackets.length,this._brackets.push(i)}i&&(i.firstStaffInBracket||(i.firstStaffInBracket=t),i.lastStaffInBracket=t,s.bracket=i)}}get height(){return 0===this._allStaves.length?0:this._allStaves[this._allStaves.length-1].y+this._allStaves[this._allStaves.length-1].height+this.topPadding+this.bottomPadding}scaleToWidth(e){for(let t=0,s=this._allStaves.length;t<s;t++)this._allStaves[t].scaleToWidth(e);this.width=e}paint(e,t,s){t+=this.topPadding,this.paintPartial(e+this.x,t+this.y,s,0,this.masterBarsRenderers.length),this._hasSystemSeparator&&(s.fillMusicFontSymbol(e+this.x,t+this.y+this.height-10,1,F.SystemDivider,!1),s.fillMusicFontSymbol(e+this.x+this.width-Kr.SystemSignSeparatorWidth,t+this.y+this.height-Kr.SystemSignSeparatorPadding,1,F.SystemDivider,!1))}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){s.color=r.barSeparatorColor;const i=this._firstStaffInBrackets,a=this._lastStaffInBrackets;if(i&&a){let r=t+i.contentTop,n=t+a.contentBottom,o=e+i.x;s.beginPath(),s.moveTo(o,r),s.lineTo(o,n),s.stroke()}const n=this.layout.renderer.settings,o=this.layout.renderer.settings.notation.isNotationElementVisible(x.TrackNames);if(s.font=r.effectFont,o){const i=this.layout.renderer.score.stylesheet,a=1===this.layout.renderer.tracks.length?i.singleTrackTrackNamePolicy:i.multiTrackTrackNamePolicy,r=0===this.index?i.firstSystemTrackNameMode:i.otherSystemsTrackNameMode,o=0===this.index?i.firstSystemTrackNameOrientation:i.otherSystemsTrackNameOrientation;let h=!1;switch(a){case U.Hidden:break;case U.FirstSystem:h=0===this.index;break;case U.AllSystems:h=!0}if(h){const i=s.textBaseline,a=s.textAlign;for(const i of this.staves)if(i.firstStaffInBracket&&i.lastStaffInBracket){let a=t+i.firstStaffInBracket.contentTop,h=t+i.lastStaffInBracket.contentBottom,l="";switch(r){case X.FullName:l=i.track.name;break;case X.ShortName:l=i.track.shortName}if(l.length>0){const t=e+i.firstStaffInBracket.x-n.display.accoladeBarPaddingRight-(i.bracket?.width??0)-n.display.systemLabelPaddingRight;switch(o){case J.Horizontal:s.textBaseline=L.Middle,s.textAlign=D.Right,s.fillText(l,t,(a+h)/2);break;case J.Vertical:s.textBaseline=L.Bottom,s.textAlign=D.Center;const e=.1;s.beginRotate(t,(a+h)/2,-90-e),s.fillText(l,0,0),s.endRotate()}}}s.textBaseline=i,s.textAlign=a}}for(const i of this._brackets)if(i.firstStaffInBracket&&i.lastStaffInBracket){const a=e+i.firstStaffInBracket.x,r=i.width,o=n.display.accoladeBarPaddingRight;let h=t+i.firstStaffInBracket.contentTop,l=t+i.lastStaffInBracket.contentBottom;if(i.drawAsBrace)s.fillMusicFontSymbol(a-o-r,l,i.braceScale,F.Brace);else if(i.firstStaffInBracket!==i.lastStaffInBracket){const e=r/2;h-=e,l+=2*e,s.fillRect(a-o-r,h,r,Math.ceil(l-h));let t=a-o-r-.5;s.fillMusicFontSymbol(t,h,1,F.BracketTop),s.fillMusicFontSymbol(t,Math.floor(l),1,F.BracketBottom)}}}}finalizeSystem(){const e=this.layout.renderer.settings;0===this.index&&(this.topPadding=e.display.firstSystemPaddingTop),this.isLast?this.bottomPadding=e.display.lastSystemPaddingBottom:this.layout.renderer.score.stylesheet.useSystemSignSeparator&&this.layout.renderer.tracks.length>1&&(this.bottomPadding+=Kr.SystemSignSeparatorHeight,this._hasSystemSeparator=!0);let t=0;for(let e of this._allStaves)e.x=this.accoladeWidth,e.y=t,e.finalizeStaff(),t+=e.height;for(const e of this._brackets)e.finalizeBracket()}buildBoundingsLookup(e,t){if(this.layout.renderer.boundsLookup.isFinished)return;const s=this._firstStaffInBrackets,i=this._lastStaffInBrackets;if(!s||!i)return;t+=this.topPadding;let a=this._allStaves[this._allStaves.length-1],r=t+this.y+s.y,n=t+this.y+i.y+i.height,o=t+this.y+this._allStaves[0].y,h=t+this.y+a.y+a.height,l=t+this.y+s.y+s.topSpacing+s.topOverflow+(s.barRenderers.length>0?s.barRenderers[0].topPadding:0),d=n-r,c=t+this.y+a.y+a.height-a.bottomSpacing-a.bottomOverflow-(a.barRenderers.length>0?a.barRenderers[0].bottomPadding:0)-l,u=h-o,p=this.x+s.x,g=new Ca;g.visualBounds=new ds,g.visualBounds.x=e+this.x,g.visualBounds.y=t+this.y,g.visualBounds.w=this.width,g.visualBounds.h=this.height-this.topPadding-this.bottomPadding,g.realBounds=new ds,g.realBounds.x=e+this.x,g.realBounds.y=t+this.y,g.realBounds.w=this.width,g.realBounds.h=this.height,this.layout.renderer.boundsLookup.addStaffSystem(g);let m=new Map;for(let e=0;e<this.staves.length;e++)for(let s of this.staves[e].stavesRelevantForBoundsLookup)for(let e of s.barRenderers){let i;m.has(e.bar.masterBar.index)?i=m.get(e.bar.masterBar.index):(i=new va,i.index=e.bar.masterBar.index,i.isFirstOfLine=e.isFirstOfLine,i.realBounds=new ds,i.realBounds.x=p+e.x,i.realBounds.y=o,i.realBounds.w=e.width,i.realBounds.h=u,i.visualBounds=new ds,i.visualBounds.x=p+e.x,i.visualBounds.y=r,i.visualBounds.w=e.width,i.visualBounds.h=d,i.lineAlignedBounds=new ds,i.lineAlignedBounds.x=p+e.x,i.lineAlignedBounds.y=l,i.lineAlignedBounds.w=e.width,i.lineAlignedBounds.h=c,this.layout.renderer.boundsLookup.addMasterBar(i),m.set(i.index,i)),e.buildBoundingsLookup(i,p,t+this.y+s.y)}}getBarX(e){if(!this._firstStaffInBrackets||0===this.layout.renderer.tracks.length)return 0;let t=this.layout.renderer.tracks[0].staves[0].bars[e];return this.layout.getRendererForBar(this._firstStaffInBrackets.staveId,t).x}}Kr.SystemSignSeparatorHeight=40,Kr.SystemSignSeparatorPadding=10,Kr.SystemSignSeparatorWidth=36;class Qr extends xr{constructor(e,t,s,i){super(e,t),this._tuning=s,this._trackLabel=i,this.glyphs=[]}doLayout(){if(!(this.glyphs.length>0)){this.createGlyphs(this._tuning);for(const e of this.glyphs)e.renderer=this.renderer,e.doLayout()}}paint(e,t,s){s.textBaseline=L.Middle,super.paint(e,t,s)}createGlyphs(e){const t=this.renderer.resources;this.height=0;if(this._trackLabel.length>0){const e=new Gr(0,this.height,this._trackLabel,t.effectFont,D.Left);e.renderer=this.renderer,e.doLayout(),this.height+=e.height,e.y+=e.height/2,this.addGlyph(e)}const s=new Gr(0,this.height,e.name,t.effectFont,D.Left);s.renderer=this.renderer,s.doLayout(),this.height+=s.height,s.y+=s.height/2,this.addGlyph(s);if(this.renderer.scoreRenderer.canvas.font=t.effectFont,this.width=Math.max(this.renderer.scoreRenderer.canvas.measureText(this._trackLabel).width,Math.max(this.renderer.scoreRenderer.canvas.measureText(e.name).width,128)),!e.isStandard){this.height+=15;const s=Qr.CircleNumberScale,i=Qr.CircleNumberHeight*s;let a=0|Math.ceil(e.tunings.length/2),r=0,n=this.height;for(let o=0,h=e.tunings.length;o<h;o++){const h=F.GuitarString0+(o+1);this.addGlyph(new Ka(r,n+i/2.5,s,h));const l="= "+Fe.getTextForTuning(e.tunings[o],!1);this.addGlyph(new Gr(r+i+1,n,l,t.effectFont,D.Left)),n+=15,o===a-1&&(n=this.height,r+=64)}this.height+=15*a}this.width+=15}}Qr.CircleNumberHeight=20,Qr.CircleNumberScale=.7;class $r extends Vr{constructor(e,t){super(e,t,D.Left)}addTuning(e,t){if(e.tunings.length>0){let s=new Qr(0,0,e,t);s.renderer=this.renderer,s.doLayout(),this.glyphs.push(s)}}}class Zr{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"}(Ws||(Ws={}));class en{get scaledWidth(){return this.width/this.renderer.settings.display.scale}constructor(e){this._barRendererLookup=new Map,this.width=0,this.height=0,this.scoreInfoGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this.systemsLayoutMode=Ws.Automatic,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t)),this.firstBarIndex=t;let s=this.renderer.settings.display.barCount;s<0&&(s=e.masterBars.length),s=t+s-1,s=Math.min(e.masterBars.length-1,Math.max(0,s)),this.lastBarIndex=s,this.createScoreInfoGlyphs(),this.doLayoutAndRender()}registerPartial(e,t){if(0==e.height)return;const s=this.renderer.settings.display.scale;e.x*=s,e.y*=s,e.width*=s,e.height*=s,e.totalWidth*=s,e.totalHeight*=s,this.renderer.settings.core.enableLazyLoading?(this._lazyPartials.set(e.id,new Zr(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(){re.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(x.ScoreTitle)&&this.scoreInfoGlyphs.set(x.ScoreTitle,new Gr(0,0,t.title,s.titleFont,D.Center)),t.subTitle&&e.isNotationElementVisible(x.ScoreSubTitle)&&this.scoreInfoGlyphs.set(x.ScoreSubTitle,new Gr(0,0,t.subTitle,s.subTitleFont,D.Center)),t.artist&&e.isNotationElementVisible(x.ScoreArtist)&&this.scoreInfoGlyphs.set(x.ScoreArtist,new Gr(0,0,t.artist,s.subTitleFont,D.Center)),t.album&&e.isNotationElementVisible(x.ScoreAlbum)&&this.scoreInfoGlyphs.set(x.ScoreAlbum,new Gr(0,0,t.album,s.subTitleFont,D.Center)),t.music&&t.music===t.words&&e.isNotationElementVisible(x.ScoreWordsAndMusic)?this.scoreInfoGlyphs.set(x.ScoreWordsAndMusic,new Gr(0,0,"Music and Words by "+t.words,s.wordsFont,D.Center)):(t.music&&e.isNotationElementVisible(x.ScoreMusic)&&this.scoreInfoGlyphs.set(x.ScoreMusic,new Gr(0,0,"Music by "+t.music,s.wordsFont,D.Right)),t.words&&e.isNotationElementVisible(x.ScoreWords)&&this.scoreInfoGlyphs.set(x.ScoreWords,new Gr(0,0,"Words by "+t.words,s.wordsFont,D.Left)));const i=new tn(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);for(const[e,t]of this.scoreInfoGlyphs)t.renderer=i,t.doLayout();if(e.isNotationElementVisible(x.GuitarTuning)){let e=[];for(let s of this.renderer.tracks)for(let i of s.staves){let a=!i.isPercussion&&i.isStringed&&i.tuning.length>0&&i.showTablature;if(t.stylesheet.perTrackDisplayTuning&&t.stylesheet.perTrackDisplayTuning.has(s.index)&&!1===t.stylesheet.perTrackDisplayTuning.get(s.index)&&(a=!1),a){e.push(i);break}}if(e.length>0&&t.stylesheet.globalDisplayTuning){this.tuningGlyph=new $r(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(x.ChordDiagrams)){this.chordDiagrams=new Hr(0,0),this.chordDiagrams.renderer=i;let e=new Set;for(let s of this.renderer.tracks){if(t.stylesheet.globalDisplayChordDiagramsOnTop&&(null==t.stylesheet.perTrackChordDiagramsOnTop||!t.stylesheet.perTrackChordDiagramsOnTop.has(s.index)||t.stylesheet.perTrackChordDiagramsOnTop.get(s.index)))for(let t of s.staves){const s=t.chords;if(s)for(const[,t]of s)e.has(t.uniqueId)||t.showDiagram&&(e.add(t.uniqueId),this.chordDiagrams.addChord(t))}}}}createEmptyStaffSystem(){let e=new Kr(this);for(let t=0;t<this.renderer.tracks.length;t++){let s=this.renderer.tracks[t];for(let i=0;i<s.staves.length;i++){let a=s.staves[i],r=Tl.staveProfiles.get(this.renderer.settings.display.staveProfile);for(let i of r)i.canCreate(s,a)&&e.addStaff(s,new Wr(t,a,i))}}return e}registerBarRenderer(e,t){this._barRendererLookup.has(e)||this._barRendererLookup.set(e,new Map),this._barRendererLookup.get(e).set(t.bar.id,t)}unregisterBarRenderer(e,t){if(this._barRendererLookup.has(e)){this._barRendererLookup.get(e).delete(t.bar.id)}}getRendererForBar(e,t){let s=t.id;return this._barRendererLookup.has(e)&&this._barRendererLookup.get(e).has(s)?this._barRendererLookup.get(e).get(s):null}layoutAndRenderAnnotation(e){let t="rendered by alphaTab",s=this.renderer.settings.display.resources,i=Math.floor(12);const a=new Ta,r=rt.withFamilyList(s.copyrightFont.families,12,Je.Plain,Ye.Bold);this.renderer.canvas.font=r;const n=Tl.getLayoutEngineFactory(this.renderer.settings.display.layoutMode).vertical;return a.width=this.renderer.canvas.measureText(t).width/this.renderer.settings.display.scale,a.height=i,a.x=n?(this.scaledWidth-a.width)/2:this.firstBarX,a.y=e,a.totalWidth=this.scaledWidth,a.totalHeight=e+i,a.firstMasterBarIndex=-1,a.lastMasterBarIndex=-1,this.registerPartial(a,(e=>{e.color=s.mainGlyphColor,e.font=r,e.textAlign=D.Left,e.textBaseline=L.Top,e.fillText(t,0,0)})),e+i}}!function(e){e[e.TopWithStem=0]="TopWithStem",e[e.Top=1]="Top",e[e.Center=2]="Center",e[e.Bottom=3]="Bottom",e[e.BottomWithStem=4]="BottomWithStem"}(zs||(zs={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Us||(Us={}));class tn{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 Nr,this._voiceContainers=new Map,this._postBeatGlyphs=new Nr,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 Ar(this))}registerTies(e){this._ties.push(...e)}get middleYPosition(){return 0}registerOverflowTop(e){return e>this.topOverflow&&(this.topOverflow=e,!0)}registerOverflowBottom(e){return e>this.bottomOverflow&&(this.bottomOverflow=e,!0)}scaleToWidth(e){let t=e-this._preBeatGlyphs.width-this._postBeatGlyphs.width;for(const e of this._voiceContainers.values())e.scaleToWidth(t);this._postBeatGlyphs.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width+t,this.width=e}get resources(){return this.settings.display.resources}get settings(){return this.scoreRenderer.settings}get barDisplayScale(){return this.staff.system.staves.length>1?this.bar.masterBar.displayScale:this.bar.displayScale}get barDisplayWidth(){return this.staff.system.staves.length>1?this.bar.masterBar.displayWidth:this.bar.displayWidth}get isFirstOfLine(){return 0===this.index}get isLast(){return!this.bar||this.bar.index===this.scoreRenderer.layout.lastBarIndex}registerLayoutingInfo(){let e=this.layoutingInfo,t=this._preBeatGlyphs.width;e.preBeatSize<t&&(e.preBeatSize=t);for(const t of this._voiceContainers.values())t.registerLayoutingInfo(e),t.x,t.width;let s=this._postBeatGlyphs.width;e.postBeatSize<s&&(e.postBeatSize=s)}applyLayoutingInfo(){if(this._appliedLayoutingInfo>=this.layoutingInfo.version)return!1;this._appliedLayoutingInfo=this.layoutingInfo.version,this._preBeatGlyphs.width=this.layoutingInfo.preBeatSize;let e=this._preBeatGlyphs.x+this._preBeatGlyphs.width;for(const t of this._voiceContainers.values()){t.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width,t.applyLayoutingInfo(this.layoutingInfo);let s=t.x+t.width;e<s&&(e=s)}this._postBeatGlyphs.x=Math.floor(e),this._postBeatGlyphs.width=this.layoutingInfo.postBeatSize,this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.computedWidth=this.width;const t=this.barDisplayWidth;return t>0&&this.scoreRenderer.layout.systemsLayoutMode==Ws.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 Nr,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new Nr,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 vr(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}addPreBeatGlyph(e){e.renderer=this,this._preBeatGlyphs.addGlyph(e)}addBeatGlyph(e){e.renderer=this,e.preNotes.renderer=this,e.onNotes.renderer=this,e.onNotes.beamingHelper=this.helpers.beamHelperLookup[e.beat.voice.index].get(e.beat.index),this.getVoiceContainer(e.beat.voice).addGlyph(e)}getVoiceContainer(e){return this._voiceContainers.has(e.index)?this._voiceContainers.get(e.index):void 0}getBeatContainer(e){return this.getVoiceContainer(e.voice)?.beatGlyphs?.[e.index]}getPreNotesGlyphForBeat(e){return this.getBeatContainer(e)?.preNotes}getOnNotesGlyphForBeat(e){return this.getBeatContainer(e)?.onNotes}paint(e,t,s){this.paintBackground(e,t,s),s.color=this.resources.mainGlyphColor,this._preBeatGlyphs.paint(e+this.x,t+this.y,s);for(const i of this._voiceContainers.values())s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.paint(e+this.x,t+this.y,s);s.color=this.resources.mainGlyphColor,this._postBeatGlyphs.paint(e+this.x,t+this.y,s)}paintBackground(e,t,s){this.layoutingInfo.paint(e+this.x+this._preBeatGlyphs.x+this._preBeatGlyphs.width,t+this.y+this.height,s)}buildBoundingsLookup(e,t,s){let i=new xa;i.bar=this.bar,i.visualBounds=new ds,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 ds,i.realBounds.x=t+this.x,i.realBounds.y=s+this.y,i.realBounds.w=this.width,i.realBounds.h=this.height,e.addBar(i);for(const[e,a]of this._voiceContainers){let r=this.bar.isEmpty&&0===e;if(!a.voice.isEmpty||r)for(let e=0,n=a.beatGlyphs.length;e<n;e++){a.beatGlyphs[e].buildBoundingsLookup(i,t+this.x+a.x,s+this.y+a.y,r)}}}addPostBeatGlyph(e){this._postBeatGlyphs.addGlyph(e)}createPreBeatGlyphs(){this._wasFirstOfLine=this.isFirstOfLine}createBeatGlyphs(){for(const e of this.bar.voices)this.hasVoiceContainer(e)&&this.createVoiceGlyphs(e)}createVoiceGlyphs(e){}createPostBeatGlyphs(){}get beatGlyphsStart(){return this._preBeatGlyphs.x+this._preBeatGlyphs.width}get postBeatGlyphsStart(){return this._postBeatGlyphs.x}getBeatX(e,t=Gs.PreNotes){let s=this.getBeatContainer(e);if(s)switch(t){case Gs.PreNotes:return s.voiceContainer.x+s.x;case Gs.OnNotes:return s.voiceContainer.x+s.x+s.onNotes.x;case Gs.MiddleNotes:return s.voiceContainer.x+s.x+s.onTimeX;case Gs.Stem:const t=s.onNotes.beamingHelper?s.onNotes.beamingHelper.getBeatLineX(e):s.onNotes.x+s.onNotes.width/2;return s.voiceContainer.x+t;case Gs.PostNotes:return s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.width;case Gs.EndBeat:return s.voiceContainer.x+s.x+s.width}return 0}getRatioPositionX(e){const t=this.bar.isEmpty?this.beatGlyphsStart:this.getBeatX(this.bar.voices[0].beats[0],Gs.OnNotes);return t+(this.postBeatGlyphsStart-t)*e}getNoteX(e,t){let s=this.getBeatContainer(e.beat);return s?s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.getNoteX(e,t):0}getNoteY(e,t){let s=this.getOnNotesGlyphForBeat(e.beat);return s?s.getNoteY(e,t):NaN}reLayout(){(this._wasFirstOfLine&&!this.isFirstOfLine||!this._wasFirstOfLine&&this.isFirstOfLine)&&this.recreatePreBeatGlyphs(),this.updateSizes(),this.registerLayoutingInfo()}recreatePreBeatGlyphs(){this._preBeatGlyphs=new Nr,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()}paintSimileMark(e,t,s){switch(this.bar.simileMark){case o.Simple:s.fillMusicFontSymbol(e+this.x+(this.width-20)/2,t+this.y+this.height/2,1,F.Repeat1Bar,!1);break;case o.SecondOfDouble:s.fillMusicFontSymbol(e+this.x-14,t+this.y+this.height/2,1,F.Repeat2Bars,!1)}}completeBeamingHelper(e){}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}}tn.RawLineSpacing=8,tn.StemWidth=.12*tn.RawLineSpacing,tn.StaffLineThickness=.13*tn.RawLineSpacing,tn.BeamThickness=.5*tn.RawLineSpacing,tn.BeamSpacing=.25*tn.RawLineSpacing,function(e){e[e.SinglePreBeat=0]="SinglePreBeat",e[e.SingleOnBeat=1]="SingleOnBeat",e[e.SingleOnBeatToEnd=2]="SingleOnBeatToEnd",e[e.GroupedOnBeat=3]="GroupedOnBeat",e[e.GroupedOnBeatToEnd=4]="GroupedOnBeatToEnd",e[e.FullBar=5]="FullBar"}(Xs||(Xs={}));class sn extends qa{constructor(e,t){super(0,0),this._uniqueEffectGlyphs=[],this._effectGlyphs=[],this.isEmpty=!0,this.previousBand=null,this.isLinkedToPrevious=!1,this.firstBeat=null,this.lastBeat=null,this.height=0,this.originalHeight=0,this.slot=null,this.voice=e,this.info=t}doLayout(){super.doLayout();for(let e=0;e<this.renderer.bar.voices.length;e++)this._effectGlyphs.push(new Map),this._uniqueEffectGlyphs.push([])}createGlyph(e){if(e.voice===this.voice&&this.info.shouldCreateGlyph(this.renderer.settings,e)&&(!this.info.hideOnMultiTrack||0===this.renderer.staff.trackIndex)){if(this.isEmpty=!1,this.firstBeat&&!e.isBefore(this.firstBeat)||(this.firstBeat=e),!this.lastBeat||e.isAfter(this.lastBeat))switch(this.lastBeat=e,this.info.sizingMode){case Xs.SingleOnBeatToEnd:case Xs.GroupedOnBeatToEnd:this.lastBeat.nextBeat&&(this.lastBeat=this.lastBeat.nextBeat)}let t=this.createOrResizeGlyph(this.info.sizingMode,e);t.height>this.height&&(this.height=t.height,this.originalHeight=t.height)}}resetHeight(){this.height=this.originalHeight}createOrResizeGlyph(e,t){let s;switch(e){case Xs.FullBar:case Xs.SinglePreBeat:case Xs.SingleOnBeat:case Xs.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 Xs.GroupedOnBeat:case Xs.GroupedOnBeatToEnd:let i=e===Xs.GroupedOnBeat?Xs.SingleOnBeat:Xs.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(Xs.SingleOnBeat,t)}}paint(e,t,s){super.paint(e,t,s);for(let i=0,a=this._uniqueEffectGlyphs.length;i<a;i++){let a=this._uniqueEffectGlyphs[i];for(let i=0,r=a.length;i<r;i++){a[i].paint(e+this.x,t+this.y,s)}}}alignGlyphs(){for(let e=0;e<this._effectGlyphs.length;e++)for(const t of this._effectGlyphs[e].keys())this.alignGlyph(this.info.sizingMode,this.renderer.bar.voices[e].beats[t])}alignGlyph(e,t){let s=this._effectGlyphs[t.voice.index].get(t.index),i=this.renderer.getBeatContainer(t);switch(e){case Xs.SinglePreBeat:const e=this.renderer.layoutingInfo.getPreBeatSize(t);s.x=this.renderer.beatGlyphsStart+i.x-e;break;case Xs.SingleOnBeat:case Xs.GroupedOnBeat:s.x=this.renderer.beatGlyphsStart+i.x;break;case Xs.SingleOnBeatToEnd:case Xs.GroupedOnBeatToEnd:if(s.x=this.renderer.beatGlyphsStart+i.x,i.beat.isLastOfVoice)s.width=this.renderer.width-s.x;else{const e=this.renderer.layoutingInfo.getPostBeatSize(t);s.width=e}break;case Xs.FullBar:s.width=this.renderer.width}}}class an{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class rn{constructor(){this.bands=[],this.shared=new an}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 nn{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 rn;return this.slots.push(t),t}register(e){let t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class on extends xr{constructor(){super(0,0),this.computedWidth=0}doLayout(){let e=0;if(this.glyphs)for(let t=0,s=this.glyphs.length;t<s;t++){let s=this.glyphs[t];s.x=e,s.renderer=this.renderer,s.doLayout(),e+=s.width}this.width=e,this.computedWidth=e}noteLoop(e){for(let t=this.container.beat.notes.length-1;t>=0;t--)e(this.container.beat.notes[t])}}class hn extends on{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,s){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class ln extends tn{constructor(e,t,s){super(e,t),this._bands=[],this._bandLookup=new Map,this.sizingInfo=null,this._infos=s}updateSizes(){this.topOverflow=0,this.bottomOverflow=0,this.topPadding=0,this.bottomPadding=0,this.updateHeight(),super.updateSizes()}finalizeRenderer(){let e=super.finalizeRenderer();return this.updateHeight()&&(e=!0),e}updateHeight(){if(!this.sizingInfo)return!1;let e=0;for(let t of this.sizingInfo.slots){t.shared.y=e;for(let s of t.bands)s.y=e,s.height=t.shared.height;e+=t.shared.height}return e!==this.height&&(this.height=e,!0)}applyLayoutingInfo(){const e=!super.applyLayoutingInfo();if(this.index>0){let e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new nn;for(let e of this._bands)e.resetHeight(),e.alignGlyphs(),e.isEmpty||this.sizingInfo.register(e);return this.updateHeight(),e}scaleToWidth(e){super.scaleToWidth(e);for(let e of this._bands)e.alignGlyphs()}createBeatGlyphs(){this._bands=[],this._bandLookup=new Map;for(let e of this.bar.voices)if(this.hasVoiceContainer(e))for(let t of this._infos){let s=new sn(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 Za(t,this.getVoiceContainer(e));s.preNotes=new on,s.onNotes=new hn,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 dn extends Tr{get staffId(){return this._staffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.effectStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.effectStaffPaddingBottom}constructor(e,t,s=null){super(),this.infos=t,this._staffId=e,this.isInsideBracket=!1,this.isRelevantForBoundsLookup=!1,this.shouldShow=s}canCreate(e,t){const s=this.shouldShow;return super.canCreate(e,t)&&(!s||s(e,t))}create(e,t){return new ln(e,t,this.infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class cn extends ja{constructor(e,t,s){super(e,t),this._endingsString="",this._endings=le.getAlternateEndingsList(s)}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(cn.Padding+2);let e="";for(let t=0,s=this._endings.length;t<s;t++)e+=this._endings[t]+1,e+=". ";this._endingsString=e}paint(e,t,s){super.paint(e,t,s);let i=s.textBaseline;if(s.textBaseline=L.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+cn.Padding,t+this.y)}s.textBaseline=i}}cn.Padding=3;class un{get effectId(){return this.notationElement.toString()}}class pn extends un{get notationElement(){return x.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Xs.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){return new cn(0,0,t.voice.bar.masterBar.alternateEndings)}canExpand(e,t){return!0}}class gn extends un{get notationElement(){return x.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Gr(0,0,"Capo. fret "+t.voice.bar.staff.capo,e.resources.effectFont,D.Left)}canExpand(e,t){return!1}}class mn extends un{get notationElement(){return x.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Gr(0,0,t.chord.name,e.resources.effectFont,D.Center)}canExpand(e,t){return!1}}class fn extends ja{constructor(e){super(),this.forceGroupedRendering=!1,this.endOnBarLine=!1,this.endPosition=e}get isLinkedWithPrevious(){return!!this.previousGlyph&&this.previousGlyph.renderer.staff.system===this.renderer.staff.system}get isLinkedWithNext(){return!!this.nextGlyph&&this.nextGlyph.renderer.isFinalized&&this.nextGlyph.renderer.staff.system===this.renderer.staff.system}paint(e,t,s){if(this.isLinkedWithPrevious)return;if(!this.isLinkedWithNext&&!this.forceGroupedRendering)return void this.paintNonGrouped(e,t,s);let i;if(!this.isLinkedWithNext&&this.forceGroupedRendering)i=this;else for(i=this.nextGlyph;i.isLinkedWithNext;)i=i.nextGlyph;let a=i.renderer,r=i.beat,n=this.endPosition,o=e-this.renderer.x,h=this.calculateEndX(a,r,o,n);this.paintGrouped(e,t,h,s)}calculateEndX(e,t,s,i){return t?s+e.x+e.getBeatX(t,i):s+e.x+this.x+this.width}paintNonGrouped(e,t,s){let i=e-this.renderer.x,a=this.calculateEndX(this.renderer,this.beat,i,this.endPosition);this.paintGrouped(e,t,a,s)}}class yn extends fn{constructor(e,t,s){super(Gs.EndBeat),this._crescendo=u.None,this._crescendo=s,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17}paintGrouped(e,t,s,i){let a=e+this.x,r=this.height;i.beginPath(),this._crescendo===u.Crescendo?(s-=yn.Padding,i.moveTo(s,t+this.y),i.lineTo(a,t+this.y+r/2),i.lineTo(s,t+this.y+r)):(s-=yn.Padding,i.moveTo(a,t+this.y),i.lineTo(s,t+this.y+r/2),i.lineTo(a,t+this.y+r)),i.stroke()}}yn.Padding=Qa.QuarterNoteHeadWidth/2|0;class bn extends un{get notationElement(){return x.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==u.None}createNewGlyph(e,t){return new yn(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class Sn extends Ka{constructor(e,t,s){super(e,t,.6,Sn.getSymbol(s))}doLayout(){super.doLayout(),this.height=17,this.y+=this.height/2}static getSymbol(e){switch(e){case g.PPP:return F.DynamicPPP;case g.PP:return F.DynamicPP;case g.P:return F.DynamicPiano;case g.MP:return F.DynamicMP;case g.MF:return F.DynamicMF;case g.F:return F.DynamicForte;case g.FF:return F.DynamicFF;case g.FFF:return F.DynamicFFF;default:return F.None}}}class _n extends un{get notationElement(){return x.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Xs.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!==m.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===m.None)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new Sn(0,0,t.dynamics)}canExpand(e,t){return!0}}class wn extends Ka{constructor(e){super(0,0,1,wn.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case O.FadeIn:return F.GuitarFadeIn;case O.FadeOut:return F.GuitarFadeOut;case O.VolumeSwell:return F.GuitarVolumeSwell}return F.None}doLayout(){this.width=13,this.symbol==F.GuitarVolumeSwell&&(this.width*=2),this.height=13}paint(e,t,s){super.paint(e,t+this.height,s)}}class Bn extends un{get notationElement(){return x.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return t.fade!=O.None}createNewGlyph(e,t){return new wn(t.fade)}canExpand(e,t){return!0}}class kn extends Ka{constructor(e,t,s){super(e,t,1,kn.getSymbol(s))}static getSymbol(e){switch(e){case He.Short:return F.FermataShortAbove;case He.Medium:return F.FermataAbove;case He.Long:return F.FermataLongAbove;default:return F.None}}doLayout(){this.width=23,this.height=12}paint(e,t,s){super.paint(e-this.width/2,t+this.height,s)}}class Tn extends un{get notationElement(){return x.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new kn(0,0,t.fermata.type)}canExpand(e,t){return!0}}class xn extends un{get notationElement(){return x.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return!(0!==t.voice.index||t.isRest||e.notation.fingeringMode!==k.SingleNoteEffectBand&&e.notation.fingeringMode!==k.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=le.fingerToString(e.settings,t,s,i)??"";return new Gr(0,0,r,e.resources.fingeringFont,D.Left)}canExpand(e,t){return!0}}class Nn extends un{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 vn extends fn{constructor(e,t=!0){super(Gs.OnNotes),this._label=e,this._dashed=t}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=Gs.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=D.Center,s.fillText(this._label,e+this.x,t+this.y),s.textAlign=a}paintGrouped(e,t,s,i){this.paintNonGrouped(e,t,i);let a=i.measureText(this._label).width,r=e+this.x+a/2+3,n=t+this.y+4;if(this._dashed){if(s>r){let e=r;for(;e<s;)i.beginPath(),i.moveTo(e,0|n),i.lineTo(Math.min(e+8,s),0|n),e+=11,i.stroke();i.beginPath(),i.moveTo(s,n-5|0),i.lineTo(s,n+5|0),i.stroke()}}else i.beginPath(),i.moveTo(r,0|n),i.lineTo(s,0|n),i.lineTo(s,n+5|0),i.stroke()}}vn.LineSpacing=3,vn.LineTopPadding=4,vn.LineTopOffset=5,vn.LineSize=8;class Pn extends Nn{get effectId(){return this._effectId}get notationElement(){return x.EffectHarmonics}constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case y.None:this._effectId="harmonics-none";break;case y.Natural:this._effectId="harmonics-natural";break;case y.Artificial:this._effectId="harmonics-artificial";break;case y.Pinch:this._effectId="harmonics-pinch";break;case y.Tap:this._effectId="harmonics-tap";break;case y.Semi:this._effectId="harmonics-semi";break;case y.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 Xs.GroupedOnBeat}createNewGlyph(e,t){return new vn(Pn.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case y.Natural:return"N.H.";case y.Artificial:return"A.H.";case y.Pinch:return"P.H.";case y.Tap:return"T.H.";case y.Semi:return"S.H.";case y.Feedback:return"Fdbk."}return""}}class Cn extends un{get notationElement(){return x.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return Xs.GroupedOnBeat}createNewGlyph(e,t){return new vn("LetRing")}canExpand(e,t){return!0}}class En extends ja{constructor(e,t,s,i,a=D.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 Fn extends un{get notationElement(){return x.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new En(0,0,t.lyrics,e.resources.effectFont,D.Center)}canExpand(e,t){return!0}}class Dn extends un{get notationElement(){return x.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return Xs.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 Gr(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,D.Left)}canExpand(e,t){return!0}}class Ln extends fn{constructor(e,t){super(Gs.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=13}paintNonGrouped(e,t,s){this.paintOttava(e,t,s)}paintOttava(e,t,s){let i=0;switch(this._ottava){case n._15ma:i=37,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,F.QuindicesimaAlta,!1);break;case n._8va:i=26,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,F.OttavaAlta,!1);break;case n._8vb:i=23,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,F.OttavaBassaVb,!1);break;case n._15mb:i=36,s.fillMusicFontSymbols(e+this.x-i/2,t+this.y+this.height,.8,[F.Quindicesima,F.OctaveBaselineM,F.OctaveBaselineB],!1)}return i/2}paintGrouped(e,t,s,i){let a=this.paintOttava(e,t,i),r=e+this.x+a+3,n=t+this.y;n+=this._aboveStaff?2:this.height-2;if(s>r){let e=r;for(;e<s;)i.beginPath(),i.moveTo(e,0|n),i.lineTo(Math.min(e+8,s),0|n),e+=11,i.stroke();i.beginPath(),this._aboveStaff?(i.moveTo(s,n),i.lineTo(s,t+this.y+this.height)):(i.moveTo(s,n),i.lineTo(s,t+this.y)),i.stroke()}}}class Mn extends un{get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return x.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.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 Ln(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class In extends Nn{get notationElement(){return x.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return Xs.GroupedOnBeat}createNewGlyph(e,t){return new vn("P.M.")}constructor(){super()}}class An extends Nn{get notationElement(){return x.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===_.PickSlideDown||e.slideOutType===_.PickSlideUp}get sizingMode(){return Xs.GroupedOnBeat}createNewGlyph(e,t){return new vn("P.S.")}constructor(){super()}}class On extends Ka{constructor(e,t,s){super(e,t,Qa.GraceScale,On.getSymbol(s))}doLayout(){this.width=9,this.height=13}paint(e,t,s){super.paint(e,t+this.height,s)}static getSymbol(e){switch(e){case E.Up:return F.StringsUpBow;case E.Down:return F.StringsDownBow;default:return F.None}}}class Rn extends un{get notationElement(){return x.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==E.None}createNewGlyph(e,t){return new On(0,0,t.pickStroke)}canExpand(e,t){return!0}}class Vn extends fn{constructor(e){super(Gs.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case w.Slight:this._stepSize=12;break;case w.Wide:this._stepSize=23}this.height=18}paintGrouped(e,t,s,i){let a=e+this.x,r=s-a,n=Math.max(1,r/this._stepSize);i.beginPath(),i.moveTo(a,t+this.y);for(let e=0;e<n;e++)i.lineTo(a+this._stepSize/2,t+this.y+this.height),i.lineTo(a+this._stepSize,t+this.y),a+=this._stepSize;i.stroke()}}class Hn extends un{get notationElement(){return x.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===w.Slight}createNewGlyph(e,t){return new Vn(w.Slight)}canExpand(e,t){return!0}}class Gn extends fn{constructor(e,t,s,i=1.2,a=!1){super(Gs.EndBeat),this._scale=0,this._symbol=F.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 w.Slight:this._symbol=F.WiggleTrill,this._symbolSize=9*this._scale,e=6*this._scale;break;case w.Wide:this._symbol=F.WiggleVibratoMediumFast,this._symbolSize=10*this._scale,e=10*this._scale}this.height=e}paintGrouped(e,t,s,i){let a=s-(e+this.x),r=this._symbolSize,n=a/r;this._partialWaves||(n=Math.floor(n)),n<1&&(n=1);let o=0;for(let s=0;s<n;s++)i.fillMusicFontSymbol(e+this.x+o,t+this.y+2*this.height,this._scale,this._symbol,!1),o+=r}}class Wn extends Nn{get notationElement(){return x.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){let t=e.vibrato===w.Slight||e.isTieDestination&&e.tieOrigin.vibrato===w.Slight;return this._hideOnTiedBend&&t&&e.isTieDestination&&e.tieOrigin.hasBend&&(t=!1),t}get sizingMode(){return Xs.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Gn(0,0,w.Slight,1.2)}constructor(e){super(),this._hideOnTiedBend=e}}class zn extends un{get notationElement(){return x.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){let s=e.resources;return t.slap?new Gr(0,0,"S",s.effectFont,D.Left):t.pop?new Gr(0,0,"P",s.effectFont,D.Left):new Gr(0,0,"T",s.effectFont,D.Left)}canExpand(e,t){return!0}}var Un,Xn,Jn=Object.freeze({__proto__:null,CssFontSvgCanvas:kr,Cursors:mr,FontSizes:ka,SvgCanvas:Br,get TextAlign(){return D},get TextBaseline(){return L}});class Yn extends ja{constructor(e){super(0,0),this.tempoAutomations=e}doLayout(){super.doLayout(),this.height=25}paint(e,t,s){for(const i of this.tempoAutomations){let a=e+this.renderer.getRatioPositionX(i.ratioPosition);const r=this.renderer.resources;if(s.font=r.markerFont,s.textBaseline=L.Top,i.text){const e=s.measureText(i.text);s.fillText(i.text,a,t+this.y+s.font.size/2),a+=e.width+.7*s.font.size}s.fillMusicFontSymbol(a,t+this.y+.8*this.height,.5,F.NoteQuarterUp,!0),s.fillText("= "+i.value.toString(),a+8,t+this.y+s.font.size/2)}}}class qn extends un{get notationElement(){return x.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Xs.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&t.voice.bar.masterBar.tempoAutomations.length>0}createNewGlyph(e,t){return new Yn(t.voice.bar.masterBar.tempoAutomations)}canExpand(e,t){return!0}}class jn extends un{get notationElement(){return x.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Gr(0,0,t.text,e.resources.effectFont,D.Left)}canExpand(e,t){return!0}}class Kn extends ja{constructor(e,t){super(e,t)}doLayout(){super.doLayout(),this.height=this.renderer.resources.markerFont.size}paint(e,t,s){let i=this.renderer.resources;s.font=i.markerFont;let a=s.measureText("tr").width;s.fillText("tr",e+this.x,t+this.y);let r=a+3,n=this.width-r,o=Math.max(1,(n-r)/13.2),h=r,l=t+this.y+1.2*this.height;for(let t=0;t<o;t++)s.fillMusicFontSymbol(e+this.x+h,l,1.2,F.WiggleTrill,!1),h+=13.2}}class Qn extends Nn{get notationElement(){return x.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return Xs.SingleOnBeat}createNewGlyph(e,t){return new Kn(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(Un||(Un={}));class $n extends ja{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25}paint(e,t,s){e+=this.x;let i=(t+=this.y)+this.height*Qa.GraceScale,a=i+8;s.font=this.renderer.resources.effectFont,s.fillText("(",e,t+.3*this.height);let r=e+10,n=e+40,o=[],h=[],l=[],d=[];switch(this._tripletFeel){case C.NoTripletFeel:o=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac8thLongStem],l=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac8thLongStem];break;case C.Triplet8th:o=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac8thLongStem],l=[F.TextBlackNoteLongStem,F.Space,F.NoteEighthUp],d=[F.TextTupletBracketStartLongStem,F.TextTuplet3LongStem,F.TextTupletBracketEndLongStem];break;case C.Triplet16th:o=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac8thLongStem],l=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac16thLongStem],d=[F.TextTupletBracketStartLongStem,F.TextTuplet3LongStem,F.TextTupletBracketEndLongStem];break;case C.Dotted8th:o=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac8thLongStem],h=[F.TextAugmentationDot],l=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac16thLongStem];break;case C.Dotted16th:o=[F.TextBlackNoteLongStem,F.TextCont16thBeamLongStem,F.TextBlackNoteFrac16thLongStem],h=[F.TextAugmentationDot],l=[F.TextBlackNoteLongStem,F.TextCont16thBeamLongStem,F.TextBlackNoteFrac32ndLongStem],s.fillCircle(n+9,i,1);break;case C.Scottish8th:o=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac8thLongStem],l=[F.TextBlackNoteLongStem,F.TextCont16thBeamLongStem,F.TextBlackNoteFrac8thLongStem,F.TextAugmentationDot];break;case C.Scottish16th:o=[F.TextBlackNoteLongStem,F.TextCont16thBeamLongStem,F.TextBlackNoteFrac16thLongStem],l=[F.TextBlackNoteLongStem,F.TextCont32ndBeamLongStem,F.TextBlackNoteFrac16thLongStem,F.TextAugmentationDot]}s.fillMusicFontSymbols(r,i,$n.NoteScale,o,!1),s.fillText("=",e+32,t+5),s.fillMusicFontSymbols(n,i,$n.NoteScale,l,!1),h.length>0&&s.fillMusicFontSymbols(n+7,i,$n.NoteScale,h,!1),d.length>0&&s.fillMusicFontSymbols(n,a,$n.TupletScale,d,!1),s.fillText(")",e+65,t+.3*this.height)}}$n.NoteScale=.5,$n.TupletScale=.7;class Zn extends un{get notationElement(){return x.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Xs.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==C.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new $n(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class eo extends un{get notationElement(){return x.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Xs.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new vn("w/bar")}canExpand(e,t){return!0}}class to extends un{get notationElement(){return x.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===w.Wide}createNewGlyph(e,t){return new Vn(w.Wide)}canExpand(e,t){return!0}}class so extends Nn{get notationElement(){return x.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===w.Wide||e.isTieDestination&&e.tieOrigin.vibrato===w.Wide}get sizingMode(){return Xs.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Gn(0,0,w.Wide,1.2)}}class io{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class ao extends en{get name(){return"HorizontalScreen"}constructor(e){super(e),this._system=null,this._pagePadding=null}get supportsResize(){return!1}get firstBarX(){let e=this._pagePadding[0];return this._system&&(e+=this._system.accoladeWidth),e}doResize(){}doLayoutAndRender(){switch(this._pagePadding=this.renderer.settings.display.padding,this.renderer.settings.display.systemsLayoutMode){case Ke.Automatic:this.systemsLayoutMode=Ws.Automatic;break;case Ke.UseModelLayout:this.systemsLayoutMode=Ws.FromModelWithWidths}this._pagePadding||(this._pagePadding=[0,0,0,0]),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let 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._system=this.createEmptyStaffSystem(),this._system.isLast=!0,this._system.x=this._pagePadding[0],this._system.y=this._pagePadding[1];let a=this.renderer.settings.display.barCountPerPartial,r=[],n=new io,o=0;for(;s<=i;){let t=this._system.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._system.accoladeWidth+this._pagePadding[0]),o+=n.width,r.push(n),re.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null),n=new io,n.x=o);s++}n.masterBars.length>0&&(0===r.length&&(n.width+=this._system.accoladeWidth+this._pagePadding[0]),r.push(n),re.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null)),this.finalizeStaffSystem();const h=this.renderer.settings.display.scale;this.height=Math.floor(this._system.y+this._system.height)*h,this.width=(this._system.x+this._system.width+this._pagePadding[2])*h,s=0;let l=0;for(let e=0;e<r.length;e++){const t=r[e],i=new Ta;i.x=l,i.y=0,i.totalWidth=this.width/h,i.totalHeight=this.height/h,i.width=t.width,i.height=this.height/h,i.firstMasterBarIndex=t.masterBars[0].index,i.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,l+=t.width;const a=s,n=e;this._system.buildBoundingsLookup(0,0),this.registerPartial(i,(e=>{let s=this._system.getBarX(t.masterBars[0].index)+this._system.accoladeWidth;0===n&&(s-=this._system.x+this._system.accoladeWidth),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=D.Left,re.debug(this.name,"Rendering partial from bar "+t.masterBars[0].index+" to "+t.masterBars[t.masterBars.length-1].index,null),this._system.paintPartial(-s,this._system.y,e,a,t.masterBars.length)})),s+=t.masterBars.length}this.height=this.layoutAndRenderAnnotation(this.height)+this._pagePadding[3]}finalizeStaffSystem(){this._system.scaleToWidth(this._system.width),this._system.finalizeSystem()}}class ro extends en{get name(){return"PageView"}constructor(e){super(e),this._systems=[],this._allMasterBarRenderers=[],this._barsFromPreviousSystem=[],this._pagePadding=null}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case Ke.Automatic:this.systemsLayoutMode=Ws.Automatic;break;case Ke.UseModelLayout:this.systemsLayoutMode=Ws.FromModelWithScale}this._pagePadding=this.renderer.settings.display.padding.map((e=>e/this.renderer.settings.display.scale)),this._pagePadding||(this._pagePadding=[0,0,0,0]),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let e=this._pagePadding[1];this.width=this.renderer.width,this._allMasterBarRenderers=[],e=this.layoutAndRenderScoreInfo(e,-1),e=this.layoutAndRenderTunings(e,-1),e=this.layoutAndRenderChordDiagrams(e,-1),e=this.layoutAndRenderScore(e),e=this.layoutAndRenderAnnotation(e),this.height=(e+this._pagePadding[3])*this.renderer.settings.display.scale}get supportsResize(){return!0}get firstBarX(){let e=this._pagePadding[0];return this._systems.length>0&&(e+=this._systems[0].accoladeWidth),e}doResize(){let e=this._pagePadding[1];this.width=this.renderer.width;let t=this.height;e=this.layoutAndRenderScoreInfo(e,t),e=this.layoutAndRenderTunings(e,t),e=this.layoutAndRenderChordDiagrams(e,t),e=this.resizeAndRenderScore(e,t),e=this.layoutAndRenderAnnotation(e),this.height=(e+this._pagePadding[3])*this.renderer.settings.display.scale}layoutAndRenderTunings(e,t=-1){if(!this.tuningGlyph)return e;let s=this.renderer.settings.display.resources;this.tuningGlyph.x=this._pagePadding[0],this.tuningGlyph.width=this.scaledWidth,this.tuningGlyph.doLayout();let i=this.tuningGlyph.height;const a=new Ta;return a.x=0,a.y=e,a.width=this.scaledWidth,a.height=i,a.totalWidth=this.scaledWidth,a.totalHeight=t<0?e+a.height:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=D.Center,this.tuningGlyph.paint(0,0,e)})),e+i}layoutAndRenderChordDiagrams(e,t=-1){if(!this.chordDiagrams)return e;const s=this.renderer.settings.display.resources;this.chordDiagrams.width=this.scaledWidth,this.chordDiagrams.doLayout();const i=Math.floor(this.chordDiagrams.height),a=new Ta;return a.x=0,a.y=e,a.width=this.scaledWidth,a.height=i,a.totalWidth=this.scaledWidth,a.totalHeight=t<0?e+i:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=D.Center,this.chordDiagrams.paint(0,0,e)})),e+i}layoutAndRenderScoreInfo(e,t=-1){re.debug(this.name,"Layouting score info");const s=new Ta;s.x=0,s.y=e;let i=0,a=this.renderer.settings.display.resources,r=[x.ScoreTitle,x.ScoreSubTitle,x.ScoreArtist,x.ScoreAlbum,x.ScoreWordsAndMusic];for(let e=0;e<r.length;e++)if(this.scoreInfoGlyphs.has(r[e])){let t=this.scoreInfoGlyphs.get(r[e]);t.x=this.scaledWidth/2,t.y=i,t.textAlign=D.Center,i+=t.font.size}let n=!1,o=0;if(this.scoreInfoGlyphs.has(x.ScoreMusic)){let e=this.scoreInfoGlyphs.get(x.ScoreMusic);e.x=this.scaledWidth-this._pagePadding[2],e.y=i,e.textAlign=D.Right,n=!0,o=e.font.size}if(this.scoreInfoGlyphs.has(x.ScoreWords)){let e=this.scoreInfoGlyphs.get(x.ScoreWords);e.x=this._pagePadding[0],e.y=i,e.textAlign=D.Left,n=!0,o=e.font.size}return n&&(i+=o),this.scoreInfoGlyphs.size>0&&(i=Math.floor(i+17),s.width=this.scaledWidth,s.height=i,s.totalWidth=this.scaledWidth,s.totalHeight=t<0?e+s.height:t,this.registerPartial(s,(e=>{e.color=a.scoreInfoColor,e.textAlign=D.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==Ws.FromModelWithScale)for(let s=0;s<this._systems.length;s++){let i=this._systems[s];this.fitSystem(i),e+=this.paintSystem(i,t)}else{this._systems=[];let s=0,i=this.maxWidth,a=this.createEmptyStaffSystem();for(a.index=this._systems.length,a.x=this._pagePadding[0],a.y=e;s<this._allMasterBarRenderers.length;){let r=this._allMasterBarRenderers[s];if(a.width+r.width<=i||0===a.masterBarsRenderers.length)a.addMasterBarRenderers(this.renderer.tracks,r),s++;else{for(;r&&!r.canWrap&&a.masterBarsRenderers.length>1;)r=a.revertLastBar(),s--;a.isFull=!0,a.isLast=this.lastBarIndex===a.lastBarIndex,this._systems.push(a),this.fitSystem(a),e+=this.paintSystem(a,t),a=this.createEmptyStaffSystem(),a.index=this._systems.length,a.x=this._pagePadding[0],a.y=e}}a.isLast=this.lastBarIndex===a.lastBarIndex,this.fitSystem(a),e+=this.paintSystem(a,t)}return e}layoutAndRenderScore(e){let t=this.firstBarIndex,s=this.lastBarIndex;for(this._systems=[];t<=s;){let i=this.createStaffSystem(t,s);this._systems.push(i),i.x=this._pagePadding[0],i.y=e,t=i.lastBarIndex+1,this.fitSystem(i),re.debug(this.name,"Rendering partial from bar "+i.firstBarIndex+" to "+i.lastBarIndex,null),e+=this.paintSystem(i,e)}return e}paintSystem(e,t){let s=Math.floor(e.height);const i=new Ta;return i.x=0,i.y=e.y,i.totalWidth=this.scaledWidth,i.totalHeight=t,i.width=this.scaledWidth,i.height=s,i.firstMasterBarIndex=e.firstBarIndex,i.lastMasterBarIndex=e.lastBarIndex,e.buildBoundingsLookup(0,0),this.registerPartial(i,(t=>{this.renderer.canvas.color=this.renderer.settings.display.resources.mainGlyphColor,this.renderer.canvas.textAlign=D.Left,e.paint(0,-i.y/this.renderer.settings.display.scale,t)})),s}fitSystem(e){e.isFull||e.width>this.maxWidth||this.renderer.settings.display.justifyLastSystem?e.scaleToWidth(this.maxWidth):e.scaleToWidth(e.width),e.finalizeSystem()}getBarsPerSystem(e){let t=this.renderer.settings.display.barsPerRow;if(this.systemsLayoutMode==Ws.FromModelWithScale){let s,i;this.renderer.tracks.length>1?(s=this.renderer.score.defaultSystemsLayout,i=this.renderer.score.systemsLayout):(s=this.renderer.tracks[0].defaultSystemsLayout,i=this.renderer.tracks[0].systemsLayout),t=e<i.length?i[e]:s}return t}createStaffSystem(e,t){let s=this.createEmptyStaffSystem();s.index=this._systems.length;let i=this.getBarsPerSystem(s.index),a=this.maxWidth,r=t+1,n=e;for(;n<r;){if(this._barsFromPreviousSystem.length>0)for(let e of this._barsFromPreviousSystem)s.addMasterBarRenderers(this.renderer.tracks,e),n=e.masterBar.index;else{let e=s.addBars(this.renderer.tracks,n);e&&this._allMasterBarRenderers.push(e)}this._barsFromPreviousSystem=[];let e=!1;if((-1===i&&s.width>=a&&0!==s.masterBarsRenderers.length||s.masterBarsRenderers.length===i+1)&&(e=!0),e){let e=s.revertLastBar();if(e)for(this._barsFromPreviousSystem.push(e);e&&!e.canWrap&&s.masterBarsRenderers.length>1;)e=s.revertLastBar(),e&&this._barsFromPreviousSystem.push(e);return s.isFull=!0,s.isLast=!1,this._barsFromPreviousSystem.reverse(),s}s.x=0,n++}return s.isLast=t===s.lastBarIndex,s}get maxWidth(){return this.scaledWidth-this._pagePadding[0]-this._pagePadding[2]}}class no extends Ka{constructor(e,t,s,i){super(e,t,i,no.getMusicSymbol(s)),this._accidentalType=s}static getMusicSymbol(e){switch(e){case Xe.Natural:return F.AccidentalNatural;case Xe.Sharp:return F.AccidentalSharp;case Xe.Flat:return F.AccidentalFlat;case Xe.NaturalQuarterNoteUp:return F.AccidentalQuarterToneNaturalArrowUp;case Xe.SharpQuarterNoteUp:return F.AccidentalQuarterToneSharpArrowUp;case Xe.FlatQuarterNoteUp:return F.AccidentalQuarterToneFlatArrowUp;case Xe.DoubleSharp:return F.AccidentalDoubleSharp;case Xe.DoubleFlat:return F.AccidentalDoubleFlat}return F.None}doLayout(){if(this._accidentalType===Xe.DoubleFlat)this.width=18;else this.width=8;this.width=this.width*this.glyphScale}}class oo extends Ka{constructor(e,t,s,i){super(e,t,1,oo.getSymbol(s)),this._clef=s,this._clefOttava=i}doLayout(){switch(this._clef){case r.Neutral:this.width=15;break;case r.C3:case r.C4:case r.F4:case r.G2:this.width=28}}static getSymbol(e){switch(e){case r.Neutral:return F.UnpitchedPercussionClef1;case r.C3:case r.C4:return F.CClef;case r.F4:return F.FClef;case r.G2:return F.GClef;default:return F.None}}paint(e,t,s){let i;super.paint(e,t,s);let a=!1;switch(this._clefOttava){case n._15ma:i=new Ka(-4,0,.5,F.Quindicesima),a=!0;break;case n._8va:i=new Ka(-2,0,.5,F.Ottava),a=!0;break;case n._8vb:i=new Ka(-6,0,.5,F.Ottava);break;case n._15mb:i=new Ka(-8,0,.5,F.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,t+this.y+o,s)}}class ho extends ja{constructor(e,t,s){super(e,t),this._note=s}static getSymbol(e,t){switch(e){case i.None:return F.None;case i.Normal:return t?F.ArticAccentAbove:F.ArticAccentBelow;case i.Heavy:return t?F.ArticMarcatoAbove:F.ArticMarcatoBelow;case i.Tenuto:return t?F.ArticTenutoAbove:F.ArticTenutoBelow;default:return F.None}}doLayout(){this.width=9,this.height=9}paint(e,t,s){const i=this.renderer.getBeatDirection(this._note.beat),a=ho.getSymbol(this._note.accentuated,i==Ge.Down),r=i==Ge.Up?t+this.y:t+this.y+this.height-2;s.fillMusicFontSymbol(e+this.x-2,r,1,a,!1)}}class lo extends qa{constructor(e,t,s){super(e,t),this._size=0,this._size=s}doLayout(){this.width=this._size+3}paint(e,t,s){s.fillCircle(e+this.x,t+this.y,this._size)}}class co extends Ka{constructor(e,t,s){super(e,t,s?Qa.GraceScale:1,F.NoteheadXOrnate),this._isGrace=s}doLayout(){this.width=9*(this._isGrace?Qa.GraceScale:1),this.height=Qa.NoteHeadHeight}}class uo extends Ka{constructor(e,t,s,i){super(e,t,i?Qa.GraceScale:1,uo.getSymbol(s)),this._isGrace=i}static getSymbol(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:case p.Half:return F.NoteheadDiamondWhiteWide;default:return F.NoteheadDiamondBlackWide}}doLayout(){this.width=9*(this._isGrace?Qa.GraceScale:1),this.height=Qa.NoteHeadHeight}}class po extends qa{constructor(e,t,s){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=Ge.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=po.calculateActualTieHeight(1,this._startX,this._startY,this._endX,this._endY,this.tieDirection===Ge.Down,this._tieHeight,4).h),this.tieDirection===Ge.Up&&(this.y-=this.height))}paint(e,t,s){this._shouldDraw&&(this.shouldDrawBendSlur()?po.drawBendSlur(s,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Ge.Down,1):po.paintTie(s,1,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Ge.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,s,i){return 22}getBeamDirection(e,t){return Ge.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=po.computeBezierControlPoints(e,t,s,i,a,r,n,o);t=h[0],s=h[1];const l=h[2],d=h[3];i=h[6],a=h[7];const c=(t-l)/(t-2*l+i),u=po.calculateExtrema(t,s,l,d,i,a,c),p=u.length>0?Math.min(t,i,u[0]):Math.min(t,i),g=u.length>0?Math.max(t,i,u[0]):Math.max(t,i),m=(s-d)/(s-2*d+a),f=po.calculateExtrema(t,s,l,d,i,a,m),y=f.length>0?Math.min(s,a,f[1]):Math.min(s,a),b=f.length>0?Math.max(s,a,f[1]):Math.max(s,a),S=new ds;return S.x=p,S.y=y,S.w=g-p,S.h=b-y,S}static calculateExtrema(e,t,s,i,a,r,n){if(n<=0||1<=n)return[];const o=e+(s-e)*n,h=t+(i-t)*n;return[o+(s+(a-s)*n-o)*n,h+(i+(r-i)*n-h)*n]}static computeBezierControlPoints(e,t,s,i,a,r,n,o){if(t===i&&s===a)return[];if(i<t){let e=t;t=i,i=e,e=s,s=a,a=e}n*=e,o*=e;let h=a-s,l=i-t,d=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=d,l/=d;let c=(i+t)/2,u=(a+s)/2;return[t,s,c+n*h,u+n*l,c+(n-o)*h,u+(n-o)*l,i,a]}static paintTie(e,t,s,i,a,r,n=!1,o=22,h=4){const l=po.computeBezierControlPoints(t,s,i,a,r,n,o,h);e.beginPath(),e.moveTo(l[0],l[1]),e.quadraticCurveTo(l[2],l[3],l[6],l[7]),e.quadraticCurveTo(l[4],l[5],l[0],l[1]),e.closePath(),e.fill()}static drawBendSlur(e,t,s,i,a,r,n,o){let h=a-s,l=i-t,d=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=d,l/=d;let c=(i+t)/2,u=(a+s)/2,p=po.BendSlurHeight*n;i-t<20&&(p/=2);let g=c+p*h,m=u+p*l;if(e.beginPath(),e.moveTo(t,s),e.lineTo(g,m),e.lineTo(i,a),e.stroke(),o){let t=e.measureText(o).width,s=r?0:-e.font.size;e.fillText(o,g-t/2,m+s)}}}po.BendSlurHeight=11;class go extends qa{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=go.Size}paint(e,t,s){this._isOpen?po.paintTie(s,1,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):po.paintTie(s,1,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3)}}go.Size=6;class mo{constructor(e,t){this.line=0,this.line=e,this.isGhost=t}}class fo extends qa{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(x.ParenthesisOnTiedBends);this.addParenthesisOnLine(s,i)}addParenthesisOnLine(e,t){let s=new mo(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 go(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 yo{constructor(e,t){this.line=0,this.glyph=e,this.line=t}}class bo extends qa{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new ma,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){let s=new yo(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===Ge.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===Ge.Down?-e:0,r+=this._noteHeadPadding,this.upLineX=r,this.downLineX=0),this.displacedX=e,this.width=r}paint(e,t,s){e+=this.x,t+=this.y;let i=this.renderer,a=this.width-this.noteStartX+6;if(this.hasTopOverflow){let r=s.color;s.color=i.resources.staffLineColor;let n=-2;for(;n>=this.minNote.line;){let r=t+i.getScoreY(n);s.fillRect(e-3+this.noteStartX,r,a,1),n-=2}s.color=r}if(this.hasBottomOverflow){let r=s.color;s.color=i.resources.staffLineColor;let n=10;for(;n<=this.maxNote.line;){let r=t+i.getScoreY(n);s.fillRect(e-3+this.noteStartX,r,a,1),n+=2}s.color=r}let r=this._infos,n=e+this._noteHeadPadding;for(let e of r)e.glyph.renderer=this.renderer,e.glyph.paint(n,t,s)}}class So extends Ka{constructor(e,t,s){super(e,t,1,So.getSymbol(s))}doLayout(){this.width=12}static getSymbol(e){switch(e){case p.ThirtySecond:return F.Tremolo3;case p.Sixteenth:return F.Tremolo2;case p.Eighth:return F.Tremolo1;default:return F.None}}}class _o extends qa{constructor(){super(0,0)}doLayout(){this.width=26}paint(e,t,s){const i=this.renderer,a=i.getLineHeight(i.heightLineCount-1),r=i.getLineY(0)+i.getLineHeight(i.drawnLineCount-1)/2-a/2,n=s.lineWidth;s.lineWidth=2,s.moveTo(e+this.x,t+r),s.lineTo(e+this.x+this.width,t+r+a),s.moveTo(e+this.x,t+r+a),s.lineTo(e+this.x+this.width,t+r),s.stroke(),s.lineWidth=n}}class wo extends bo{constructor(){super(),this._noteGlyphLookup=new Map,this._notes=[],this._deadSlapped=null,this._tremoloPicking=null,this.aboveBeatEffects=new Map,this.belowBeatEffects=new Map}get direction(){return this.beamingHelper.direction}getNoteX(e,t){if(this._noteGlyphLookup.has(e.id)){let s=this._noteGlyphLookup.get(e.id),i=this.x+s.x+this._noteHeadPadding;switch(t){case Us.Left:break;case Us.Center:i+=s.width/2;break;case Us.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 zs.TopWithStem:i-=this.renderer.getStemSize(this.beamingHelper);break;case zs.Top:i-=s.height/2;break;case zs.Center:break;case zs.Bottom:i+=s.height/2;break;case zs.BottomWithStem:i+=this.renderer.getStemSize(this.beamingHelper)}return i}return 0}addNoteGlyph(e,t,s){super.add(e,s),this._noteGlyphLookup.set(t.id,e),this._notes.push(t)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.upLineX,e+this.x+this.downLineX)}doLayout(){super.doLayout();let e=this.renderer;this.beat.deadSlapped&&(this._deadSlapped=new _o,this._deadSlapped.renderer=this.renderer,this._deadSlapped.doLayout(),this.width=this._deadSlapped.width);let t=this.direction,s=0,i=0,a=1,r=-a,n=!1,o=!1;this.beat.deadSlapped?(i=e.getScoreY(0),s=e.getScoreY(e.heightLineCount)):this.direction===Ge.Up?(n=!1,o=!0,i=e.getScoreY(this.maxNote.line+2),s=e.getScoreY(this.minNote.line)-e.getStemSize(this.beamingHelper,!0)):(n=!0,o=!1,i=e.getScoreY(this.minNote.line-1),a*=-1,r*=-1,s=e.getScoreY(this.maxNote.line)+e.getStemSize(this.beamingHelper,!0));let h=null,l=null;for(const e of this.aboveBeatEffects.values())e.renderer=this.renderer,e.doLayout(),o&&(s+=r*e.height),e.y=s,(null===h||h>s)&&(h=s),(null===l||l<s)&&(l=s),o||(s+=r*e.height);for(const e of this.belowBeatEffects.values())e.renderer=this.renderer,e.doLayout(),n&&(i+=a*e.height),e.y=i,(null===h||h>i)&&(h=i),(null===l||l<i)&&(l=i),n||(i+=a*e.height);if(null!==h&&e.registerBeatEffectOverflows(h,l??0),this.beat.isTremolo&&!this.beat.deadSlapped){let e=0,s=t===Ge.Up?this.minNote:this.maxNote,i=t===Ge.Up?this.displacedX:0,a=this.beat.tremoloSpeed;switch(a){case p.ThirtySecond:e=t===Ge.Up?-15:15;break;case p.Sixteenth:e=t===Ge.Up?-12:15;break;case p.Eighth:e=t===Ge.Up?-10:10;break;default:e=t===Ge.Up?-10:15}this.beat.duration<p.Half&&(i=this.width/2),this._tremoloPicking=new So(i,s.glyph.y+e,a),this._tremoloPicking.renderer=this.renderer,this._tremoloPicking.doLayout()}}buildBoundingsLookup(e,t,s){for(let i of this._notes)if(this._noteGlyphLookup.has(i.id)){let a=this._noteGlyphLookup.get(i.id),r=new Pa;r.note=i,r.noteHeadBounds=new ds,r.noteHeadBounds.x=t+this.x+this._noteHeadPadding+a.x,r.noteHeadBounds.y=s+this.y+a.y-a.height/2,r.noteHeadBounds.w=a.width,r.noteHeadBounds.h=a.height,e.addNote(r)}}paint(e,t,s){for(const i of this.aboveBeatEffects.values())i.paint(e+this.x+2,t+this.y,s);for(const i of this.belowBeatEffects.values())i.paint(e+this.x+2,t+this.y,s);super.paint(e,t,s),this._tremoloPicking&&this._tremoloPicking.paint(e,t,s),this._deadSlapped&&this._deadSlapped.paint(e,t,s)}}class Bo extends Ka{constructor(e,t,s){super(e,t,1,Bo.getSymbol(s)),this._duration=s}static getSymbol(e){switch(e){case p.QuadrupleWhole:return F.RestLonga;case p.DoubleWhole:return F.RestDoubleWhole;case p.Whole:return F.RestWhole;case p.Half:return F.RestHalf;case p.Quarter:return F.RestQuarter;case p.Eighth:return F.RestEighth;case p.Sixteenth:return F.RestSixteenth;case p.ThirtySecond:return F.RestThirtySecond;case p.SixtyFourth:return F.RestSixtyFourth;case p.OneHundredTwentyEighth:return F.RestOneHundredTwentyEighth;case p.TwoHundredFiftySixth:return F.RestTwoHundredFiftySixth;default:return F.None}}static getSize(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:return 9;case p.ThirtySecond:return 12;case p.SixtyFourth:return 14;case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:return 20}return 10}doLayout(){this.width=Bo.getSize(this._duration)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class ko{constructor(){this.x=0,this.y=-3e3,this.width=0}}class To extends xr{constructor(){super(0,0)}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);this.glyphs.sort(((e,t)=>e.y<t.y?-1:e.y>t.y?1:0));let e=[];e.push(new ko);for(let t=0,s=this.glyphs.length;t<s;t++){let s=this.glyphs[t];s.renderer=this.renderer,s.doLayout();let i=0;for(;e[i].y>s.y;)i++,i===e.length&&e.push(new ko);s.x=i,e[i].y=s.y+21,e[i].width<s.width&&(e[i].width=s.width)}this.width=0;for(const t of e)this.width+=t.width,t.x=this.width;for(let t=0,s=this.glyphs.length;t<s;t++){let s=this.glyphs[t];const i=e[s.x];s.x=this.width-i.x}}}class xo extends bo{get direction(){return Ge.Up}constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new To,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new fo(!0),this._postNoteParenthesis=new fo(!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 Qa(0,0,p.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!==Xe.None){let e=new no(0,i.y,a,Qa.GraceScale);e.renderer=this.renderer,this._accidentals.renderer=this.renderer,this._accidentals.addGlyph(e)}this._noteValueLookup.set(e,i),this.add(i,r),this.isEmpty=!1}doLayout(){let e=0;this._showParenthesis&&(this._preNoteParenthesis.x=e,this._preNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.doLayout(),e+=this._preNoteParenthesis.width+xo.ElementPadding),this._accidentals.isEmpty||(e+=this._accidentals.width+xo.ElementPadding,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+xo.ElementPadding),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+xo.ElementPadding,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+xo.ElementPadding)}paint(e,t,s){this._accidentals.isEmpty||this._accidentals.paint(e+this.x,t+this.y,s),this._showParenthesis&&(this._preNoteParenthesis.paint(e+this.x,t+this.y,s),this._postNoteParenthesis.paint(e+this.x,t+this.y,s)),super.paint(e,t,s)}}xo.ElementPadding=2;class No extends qa{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,s,i,a,r,n,o){po.drawBendSlur(e,t,s,i,a,r,n,o)}doLayout(){super.doLayout(),this.width=0;for(let e of this.BendNoteHeads)e.doLayout(),this.width+=e.width+10}getTieDirection(e,t){return t.getBeatDirection(e)===Ge.Up?Ge.Down:Ge.Up}}No.EndPadding=8;class vo extends te{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class Po extends qa{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 d.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 d.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 d.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 d.Prebend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s);break;case d.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 d.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*Po.BendValueHeight;this.renderer.registerOverflowTop(e);let t=0;for(let e of this._notes){let s=this._renderPoints.get(e.id);switch(e.bendType){case d.Bend:s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case d.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t);break;case d.BendRelease:s[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[2].lineValue=t);break;case d.Prebend:s[0].lineValue=this._preBendMinValue;break;case d.PrebendBend:s[0].lineValue=this._preBendMinValue,s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case d.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 d.Custom:for(let s of e.bendPoints)t.push(new vo(s.offset,s.value));break;case d.BendRelease:t.push(new vo(0,e.bendPoints[0].value)),t.push(new vo(te.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new vo(te.MaxPosition,e.bendPoints[3].value));break;case d.Bend:case d.Hold:case d.Prebend:case d.PrebendBend:case d.PrebendRelease:case d.Release:t.push(new vo(0,e.bendPoints[0].value)),t.push(new vo(te.MaxPosition,e.bendPoints[1].value))}return t}paint(e,t,s){let i=s.color;this._notes.length>1&&(s.color=this.renderer.resources.secondaryGlyphColor);for(let a of this._notes){let r=this._renderPoints.get(a.id),n=this.renderer,o=a,h=!1,c=null,u=!1,p=a.bendStyle===l.Gradual?"grad.":"",g=null;for(;o.isTieOrigin;){let e=o.tieDestination;if(c=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,e.beat.voice.bar),!c||n.staff!==c.staff)break;if(o=e,h=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes||o.vibrato!=w.None){u=!0;break}}g=o.beat,c=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,g.voice.bar),g.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(g=null);let m=0,f=0,y=t+n.y;m=e+n.x,r[0].value>0||a.isContinuedBend?m+=n.getBeatX(a.beat,Gs.MiddleNotes):m+=n.getNoteX(a,Us.Right),f=!g||g.isLastOfVoice&&!u?e+c.x+c.postBeatGlyphsStart:u||!g.nextBeat?e+c.x+c.getBeatX(g,Gs.MiddleNotes):a.bendType===d.Hold?e+c.x+c.getBeatX(g.nextBeat,Gs.OnNotes):e+c.x+c.getBeatX(g.nextBeat,Gs.PreNotes),h||(f-=Po.ArrowSize);let b=(f-m)/te.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 vo(0,0),t,m,y,b,p,s),a.bendType!==d.Prebend?(0===e&&(m+=2),this.paintBend(a,t,i,m,y,b,p,s)):a.isTieOrigin&&a.tieDestination.hasBend&&(i=new vo(te.MaxPosition,t.value),i.lineValue=t.lineValue,this.paintBend(a,t,i,m,y,b,p,s))}if(o.vibrato!==w.None){const i=f-e+Po.ArrowSize-c.x,a=y-t-Po.BendValueHeight*r[r.length-1].lineValue,n=new Gn(i,a,o.vibrato,1.2);n.beat=o.beat,n.renderer=c,n.doLayout(),n.paint(e+c.x,t,s)}s.color=i}}paintBend(e,t,s,i,a,r,n,o){let h=this.renderer,l=this.renderer.resources,d=h.lineOffset/2,c=i+r*t.offset,u=Po.BendValueHeight,p=a-u*t.lineValue;0===t.value?s.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,zs.Top):p+=h.getNoteY(e,zs.Center):p+=d;let g=i+r*s.offset,m=a-u*s.lineValue;0===s.lineValue?m+=h.getNoteY(e,zs.Center):m+=d;let f=0,y=Po.ArrowSize;if(s.value>t.value?(m+y>p&&(m=p-y),o.beginPath(),o.moveTo(g,m),o.lineTo(g-.5*y,m+y),o.lineTo(g+.5*y,m+y),o.closePath(),o.fill(),f=y):s.value!==t.value&&(m<p&&(m=p+y),o.beginPath(),o.moveTo(g,m),o.lineTo(g-.5*y,m-y),o.lineTo(g+.5*y,m-y),o.closePath(),o.fill(),f=-y),o.beginPath(),t.value===s.value){if(t.lineValue>0){let e=g,t=Po.DashSize,s=c+t;if((e-c)/(2*t)<1)o.moveTo(e,p),o.lineTo(c,p);else for(;e>s;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>c?(o.moveTo(c,p),o.bezierCurveTo((c+g)/2,p,g,p,g,m+f),o.stroke()):(o.moveTo(c,p),o.lineTo(g,m),o.stroke());if(n&&t.offset<s.offset){o.font=l.graceFont;let e=o.measureText(n).width,t=0,s=0;if(p>m){let i=Math.abs(p-m);t=i>1.3*o.font.size?p-i/2:p,s=(c+g-e)/2}else t=p,s=g-e;o.fillText(n,s,t)}if(0!==s.value&&t.value!==s.value){let e=s.value,i=s.value>t.value;e=Math.abs(e);let r="";if(4===e)r="full",e-=4;else if(e>=4||e<=-4){let t=e/4|0;r+=t,e-=4*t}if(e>0&&(r+=Po.getFractionSign(e)),""!==r){m=a-u*s.value;let e=m;i||(e=p+1*Math.abs(m-p)/3),o.font=l.tablatureFont;let t=o.measureText(r).width,n=e-.5*l.tablatureFont.size-2,h=g-t/2;o.fillText(r,h,n)}}}static getFractionSign(e){switch(e){case 1:return"¼";case 2:return"½";case 3:return"¾";default:return e+"/ 4"}}}Po.ArrowSize=6,Po.DashSize=3,Po.BendValueHeight=6;class Co extends qa{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===I.Custom)return e.whammyBarPoints;let t=[];switch(e.whammyBarType){case I.Dive:case I.Hold:case I.PrediveDive:case I.Predive:t.push(new te(0,e.whammyBarPoints[0].value)),t.push(new te(te.MaxPosition,e.whammyBarPoints[1].value));break;case I.Dip:t.push(new te(0,e.whammyBarPoints[0].value)),t.push(new te(te.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new te(te.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===I.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(x.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(Co.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(Co.TopOffsetSharedDataKey,i)}getOffset(e){if(0===e)return 0;let t=Co.PerHalfSize+Math.log2(Math.abs(e)/2)*Co.PerHalfSize;return e<0&&(t=-t),t}paint(e,t,s){let i=this.renderer,a=this._beat.nextBeat,r=null,n=Gs.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===I.Dip?Gs.PreNotes:Gs.MiddleNotes:(a=null,r=null));let o=0,h=0;this._isSimpleDip?(o=e+i.x+i.getBeatX(this._beat,Gs.OnNotes)-2,h=e+i.x+i.getBeatX(this._beat,Gs.PostNotes)+2):(o=e+i.x+i.getBeatX(this._beat,Gs.MiddleNotes),h=r?e+r.x+r.getBeatX(a,n):e+i.x+i.width-2);let d=s.textAlign;if(s.textAlign=D.Center,this._renderPoints.length>=2){let e=(h-o)/te.MaxPosition;s.beginPath();let i=t+this.renderer.staff.getSharedLayoutData(Co.TopOffsetSharedDataKey,0),a=this._beat.whammyStyle===l.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,d=0===t;0!==t||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new te(0,0),n,h,o,i,e,s),d=!1),this.paintWhammy(d,n,h,l,o,i,e,s,a),a=""}s.stroke()}s.textAlign=d}paintWhammy(e,t,s,i,a,r,n,o,h){let l=a+n*t.offset,d=a+n*s.offset,c=r-this.getOffset(t.value),u=r-this.getOffset(s.value);if(t.offset===s.offset){let e=Co.DashSize;if(Math.abs(u-c)/(2*e)<1)o.moveTo(l,c),o.lineTo(d,u);else{let t=Math.max(c,u),s=Math.min(c,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=Co.DashSize;if(Math.abs(d-l)/(2*e)<1)o.moveTo(l,c),o.lineTo(d,u);else{let t=Math.max(l,d),s=Math.min(l,d);for(;t>s;)o.moveTo(t,c),o.lineTo(t-e,c),t-=2*e}o.stroke()}else o.moveTo(l,c),o.lineTo(d,u);let p=this.renderer.resources;if(e&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let e=c;e-=p.tablatureFont.size+2,this.renderer.settings.notation.isNotationElementVisible(x.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2,o.fillText(h,l,e))}let g=Math.abs(s.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(x.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+=Po.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(c,u)-p.tablatureFont.size-2:(a=t.offset===s.offset?Math.min(c,u):u,a-=p.tablatureFont.size+2,i&&i.value>s.value&&(a-=2));let r=d;o.fillText(e,r,a)}}}Co.TopOffsetSharedDataKey="tab.whammy.topoffset",Co.PerHalfSize=6,Co.DashSize=3;class Eo extends No{constructor(e){super(0,0),this._beat=e}doLayout(){let e=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case I.None:case I.Custom:case I.Hold:return;case I.Dive:case I.PrediveDive:{let e=new xo(this._beat,!1);e.renderer=this.renderer;let t=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let s of this._beat.notes)s.isTieOrigin||e.addGlyph(this.getBendNoteValue(s,t),t.value%2!=0);e.doLayout(),this.BendNoteHeads.push(e)}break;case I.Dip:if(e===T.SongBook){let e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+Eo.SimpleDipHeight+Eo.SimpleDipPadding}else{let e=new xo(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 xo(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 I.Predive:}super.doLayout()}paint(e,t,s){let i=this._beat;switch(i.whammyBarType){case I.None:case I.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,Gs.MiddleNotes),o=this.getTieDirection(i,r),h=1===this._beat.notes.length?o:Ge.Up,d=s.textAlign;for(let d=0;d<i.notes.length;d++){let c=i.notes[d],u=t+r.y;d>0&&d>=(this._beat.notes.length/2|0)&&(h=Ge.Down),h===Ge.Down?u+=r.getNoteY(c,zs.Bottom):u+=r.getNoteY(c,zs.Top);let p=e+r.x;i.isLastOfVoice?p+=r.width:p+=r.getBeatX(i,Gs.EndBeat),p-=8;let g=i.whammyStyle===l.Gradual&&0===d?"grad.":"",m=null;c.isTieOrigin&&(m=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,c.tieDestination.beat.voice.bar),m&&m.staff===r.staff?p=e+m.x+m.getBeatX(c.tieDestination.beat,Gs.MiddleNotes):m=null);let f=Qa.NoteHeadHeight*Qa.GraceScale*.5;h===Ge.Up&&(f=-f);let y=i.whammyBarPoints.length>0?this.getBendNoteValue(c,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)+f,S=!0):m&&(c.isTieOrigin&&c.tieDestination.beat.hasWhammyBar||c.beat.isContinuedWhammy)?(b=t+m.y+m.getNoteY(c.tieDestination,zs.Top),S=!0,h===Ge.Down&&(b+=Qa.NoteHeadHeight)):c.isTieOrigin&&(b=m?t+m.y+m.getNoteY(c.tieDestination,zs.Top):u,h===Ge.Down&&(b+=Qa.NoteHeadHeight)),i.whammyBarType){case I.Hold:c.isTieOrigin&&po.paintTie(s,1,n,u,p,b,o===Ge.Down,22,4);break;case I.Dive:0===d&&(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,h===Ge.Down,1,g):c.isTieOrigin&&po.paintTie(s,1,n,u,p,b,o===Ge.Down,22,4);break;case I.Dip:if(a===T.SongBook){if(0===d){let i=e+r.x+r.getBeatX(this._beat,Gs.OnNotes)-2,a=e+r.x+r.getBeatX(this._beat,Gs.PostNotes)+2,n=(i+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();s.font=this.renderer.resources.tablatureFont,s.fillText(o,n,t+this.y);let h=t+this.y+s.font.size+2,l=h+Eo.SimpleDipHeight;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(s.moveTo(i,l),s.lineTo(n,h),s.lineTo(a,l)):(s.moveTo(i,h),s.lineTo(n,l),s.lineTo(a,h)),s.stroke()}c.isTieOrigin&&po.paintTie(s,1,n,u,p,b,o===Ge.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(c,i.whammyBarPoints[1]),o=this.BendNoteHeads[0].getNoteValueY(a)+f;this.drawBendSlur(s,n,u,e,o,h===Ge.Down,1,g),this.BendNoteHeads[1].x=p-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=t+r.y,this.BendNoteHeads[1].paint(0,0,s),b=this.BendNoteHeads[1].getNoteValueY(y)+f,this.drawBendSlur(s,e,o,p,b,h===Ge.Down,1,g)}break;case I.PrediveDive:case I.Predive:let l=e+r.x+r.getBeatX(c.beat,Gs.PreNotes);l+=r.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;let m=t+r.y+r.getScoreY(r.accidentalHelper.getNoteLineForValue(c.displayValue-(c.beat.whammyBarPoints[0].value/2|0),!1))+f;this.drawBendSlur(s,l,m,n,u,h===Ge.Down,1,g),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.drawBendSlur(s,n,u,p,b,h===Ge.Down,1,g))}}s.textAlign=d}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}Eo.SimpleDipHeight=2*Co.PerHalfSize,Eo.SimpleDipPadding=2;class Fo extends qa{constructor(e,t,s){super(e,t),this.width=s}}class Do extends Ka{constructor(e,t,s,i,a){super(e,t,a?Qa.GraceScale:1,s.getSymbol(i)),this._isGrace=a,this._articulation=s}paint(e,t,s){let i=this._isGrace?1:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale,this.symbol,!1),this._articulation.techniqueSymbol!==F.None&&this._articulation.techniqueSymbolPlacement===L.Middle&&s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale,this._articulation.techniqueSymbol,!1)}doLayout(){const e=this._isGrace?Qa.GraceScale:1;switch(this.symbol){case F.NoteheadWhole:this.width=14;break;case F.NoteheadCircleX:case F.NoteheadDiamondWhite:this.width=9;break;case F.NoteheadHeavyXHat:case F.NoteheadHeavyX:this.width=13;break;default:this.width=10}this.width=this.width*e,this.height=Qa.NoteHeadHeight*e}}class Lo extends Ka{constructor(e,t){super(e,t,Qa.GraceScale,F.ArticStaccatoAbove)}doLayout(){this.width=Qa.QuarterNoteHeadWidth,this.height=7}paint(e,t,s){super.paint(e+3,t+5,s)}}class Mo extends Ka{constructor(e,t){super(e,t,.5,F.PictEdgeOfCymbal)}doLayout(){this.width=22,this.height=15}paint(e,t,s){super.paint(e-3,t+this.height,s)}}class Io extends ja{constructor(e,t,s=!1){super(e,t),this._center=s}doLayout(){this.width=9,this.height=10}paint(e,t,s){s.fillMusicFontSymbol(e+this.x,t+this.y+this.height,Qa.GraceScale,F.GuitarGolpe,this._center)}}class Ao extends ja{constructor(){super(...arguments),this._strings=new Set}addString(e){this._strings.add(e)}doLayout(){const e=Qr.CircleNumberHeight*Qr.CircleNumberScale;this.height=(e+3)*this._strings.size,this.width=e}paint(e,t,s){const i=this.renderer.bar.staff.tuning.length;let a=0;const r=Qr.CircleNumberHeight*Qr.CircleNumberScale;for(const n of this._strings){const o=i-n,h=F.GuitarString1+o;s.fillMusicFontSymbol(e+this.x+Qa.NoteHeadHeight/2,t+this.y+r+a,Qr.CircleNumberScale,h,!0),a+=r+3}}}class Oo extends ja{constructor(e,t,s,i){super(e,t),this.beatEffects=new Map,this._isGrace=i,this._duration=s,this._symbol=Oo.getSymbol(s)}paint(e,t,s){let i=this._isGrace?1:0;const a=this._isGrace?Qa.GraceScale:1;s.fillMusicFontSymbol(e+this.x,t+this.y+i,a,this._symbol,!1);for(const i of this.beatEffects.values())i.paint(e+this.x,t+this.y,s)}doLayout(){const e=this._isGrace?Qa.GraceScale:1;switch(this._duration){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:this.width=Oo.WholeNoteHeadWidth*e;break;case p.Half:this.width=Oo.HalfNoteHeadWidth*e;break;default:this.width=Oo.QuarterNoteHeadWidth*e}this.height=Oo.NoteHeadHeight*e;let t=Oo.NoteHeadHeight;for(const e of this.beatEffects.values())e.y+=t,e.x+=this.width/2,e.renderer=this.renderer,t+=7,e.doLayout()}static getSymbol(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:return F.NoteheadSlashWhiteWhole;case p.Half:return F.NoteheadSlashWhiteHalf;default:return F.NoteheadSlashVerticalEnds}}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width,e+this.x)}}Oo.NoteHeadHeight=17,Oo.QuarterNoteHeadWidth=12,Oo.HalfNoteHeadWidth=25,Oo.WholeNoteHeadWidth=32;class Ro extends hn{constructor(){super(...arguments),this._collisionOffset=-1e3,this._skipPaint=!1,this.slash=null,this.noteHeads=null,this.restGlyph=null}getNoteX(e,t){return this.noteHeads?this.noteHeads.getNoteX(e,t):0}buildBoundingsLookup(e,t,s){this.noteHeads&&this.noteHeads.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteY(e,t){return this.noteHeads?this.noteHeads.getNoteY(e,t):0}updateBeamingHelper(){if(this.noteHeads)this.noteHeads.updateBeamingHelper(this.container.x+this.x);else if(this.restGlyph){if(this.restGlyph.updateBeamingHelper(this.container.x+this.x),this.renderer.bar.isMultiVoice&&-1e3===this._collisionOffset){this._collisionOffset=this.renderer.helpers.collisionHelper.applyRestCollisionOffset(this.container.beat,this.restGlyph.y,this.renderer.getScoreHeight(1)),this.y+=this._collisionOffset;const e=this.renderer.helpers.collisionHelper.restDurationsByDisplayTime;e.has(this.container.beat.playbackStart)&&e.get(this.container.beat.playbackStart).has(this.container.beat.playbackDuration)&&e.get(this.container.beat.playbackStart).get(this.container.beat.playbackDuration)!==this.container.beat.id&&(this._skipPaint=!0)}}else this.slash&&this.slash.updateBeamingHelper(this.container.x+this.x)}paint(e,t,s){this._skipPaint||super.paint(e,t,s)}doLayout(){let e=this.renderer;if(!this.container.beat.isEmpty)if(this.container.beat.isRest){let t=2*Math.ceil((this.renderer.bar.staff.standardNotationLineCount-1)/2);this.container.beat.duration===p.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const s=new Bo(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=Dr.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 Fo(0,0,5));for(let e=0;e<this.container.beat.dots;e++){let e=new xr(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addGlyph(e)}}}else{if(this.container.beat.slashed){const t=this.container.beat.graceType!==m.None,s=(e.heightLineCount-1)/2,i=e.getLineY(s),a=new Oo(0,i,this.container.beat.duration,t);this.slash=a,a.beat=this.container.beat,a.beamingHelper=this.beamingHelper,this.addGlyph(a)}else{const e=new wo;this.noteHeads=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;let t=new fo(!1);t.renderer=this.renderer;for(let e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),t.addParenthesis(e));this.addGlyph(e),t.isEmpty||(this.addGlyph(new Fo(0,0,4*(this.container.beat.graceType!==m.None?Qa.GraceScale:1))),this.addGlyph(t))}if(this.container.beat.hasWhammyBar){let e=new Eo(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addGlyph(new Fo(0,0,5));for(let t=0;t<this.container.beat.dots;t++){let t=new xr(0,0);t.renderer=this.renderer;for(let s of this.container.beat.notes)this.createBeatDot(e.getNoteLine(s),t);this.addGlyph(t)}}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.slash&&(this.centerX=this.slash.x+this.slash.width/2)}createBeatDot(e,t){let s=this.renderer;t.addGlyph(new lo(0,s.getScoreY(e),1.5))}createNoteHeadGlyph(e){let t=this.container.beat.graceType!==m.None;if(e.beat.voice.bar.staff.isPercussion){const s=ue.getArticulation(e);if(s)return new Do(0,0,s,e.beat.duration,t);re.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new co(0,0,t):e.beat.graceType===m.BendGrace?new Qa(0,0,p.Quarter,!0):e.harmonicType===y.Natural?new uo(0,0,e.beat.duration,t):new Qa(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===m.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!==y.None&&e.harmonicType!==y.Natural){let i=e.displayValue+e.harmonicPitch;s=new uo(0,0,e.beat.duration,this.container.beat.graceType!==m.None),a=t.accidentalHelper.getNoteLineForValue(i,!1),s.y=t.getScoreY(a),this.noteHeads.addNoteGlyph(s,e,a)}const r=this.noteHeads.belowBeatEffects,n=this.noteHeads.aboveBeatEffects;if(e.isStaccato&&!r.has("Staccato")&&r.set("Staccato",new Lo(0,0)),e.accentuated!==i.Normal||r.has("Accent")||r.set("Accent",new ho(0,0,e)),e.accentuated!==i.Heavy||r.has("HAccent")||r.set("HAccent",new ho(0,0,e)),e.accentuated!==i.Tenuto||r.has("Tenuto")||r.set("Tenuto",new ho(0,0,e)),e.showStringNumber&&e.isStringed){let t;n.has("StringNumber")?t=n.get("StringNumber"):(t=new Ao(0,0),n.set("StringNumber",t)),t.addString(e.string)}if(e.isPercussion){const t=ue.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==L.Middle){const e=t.techniqueSymbolPlacement===L.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case F.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new Mo(0,0));break;case F.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new Lo(0,0));break;case F.StringsUpBow:e.set("StringsUpBow",new On(0,0,E.Up));break;case F.StringsDownBow:e.set("StringsDownBow",new On(0,0,E.Down));break;case F.GuitarGolpe:e.set("GuitarGolpe",new Io(0,0))}}}}}class Vo extends qa{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=this._beat.brushType===c.ArpeggioUp||this._beat.brushType===c.ArpeggioDown?10: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,zs.Bottom)-a),n=t+this.y+i.getNoteY(this._beat.minNote,zs.Top)+a,o=e+this.x+this.width/2,h=8,l=new Gn(0,0,w.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,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,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 Ho{constructor(e,t){this.line=0,this.line=e,this.text=t}}class Go extends xr{constructor(){super(0,0),this._infos=new Map}get isEmpty(){return 0===this._infos.size}addFingers(e){const t=this.renderer.settings;if(t.notation.fingeringMode!==k.ScoreDefault&&t.notation.fingeringMode!==k.ScoreForcePiano)return;const s=le.fingerToString(this.renderer.settings,e.beat,e.leftHandFinger,!0);s&&this.addFinger(e,s);const i=le.fingerToString(this.renderer.settings,e.beat,e.rightHandFinger,!1);i&&this.addFinger(e,i)}addFinger(e,t){let s=this.renderer.getNoteLine(e);if(this._infos.has(s)){this._infos.get(s).text+=t}else{const e=new Ho(s,t);this._infos.set(s,e)}}doLayout(){let e=this.renderer;for(const[t,s]of this._infos){const t=new Gr(0,0,s.text,e.resources.inlineFingeringFont,D.Left,L.Middle);t.renderer=e,t.y=e.getScoreY(s.line),t.doLayout(),this.addGlyph(t),this.width=Math.max(this.width,t.width)}}}class Wo extends on{get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}doLayout(){if(!this.container.beat.isRest){let e=new To;e.renderer=this.renderer;let t=new Go;t.renderer=this.renderer;let s=new fo(!0);s.renderer=this.renderer;const i=new xo(this.container.beat,!0);this._prebends=i,i.renderer=this.renderer;for(let a of this.container.beat.notes)if(a.isVisible){if(a.hasBend)switch(a.bendType){case d.PrebendBend:case d.Prebend:case d.PrebendRelease:i.addGlyph(a.displayValue-(a.bendPoints[0].value/2|0),!1)}else if(a.beat.hasWhammyBar)switch(a.beat.whammyBarType){case I.PrediveDive:case I.Predive:this._prebends.addGlyph(a.displayValue-(a.beat.whammyBarPoints[0].value/2|0),!1)}this.createAccidentalGlyph(a,e),s.addParenthesis(a),t.addFingers(a)}i.isEmpty||(this.addGlyph(i),this.addGlyph(new Fo(0,0,4*(this.container.beat.graceType!==m.None?Qa.GraceScale:1)))),this.container.beat.brushType!==c.None&&(this.addGlyph(new Vo(this.container.beat)),this.addGlyph(new Fo(0,0,4))),t.isEmpty||(this.isEmpty||this.addGlyph(new Fo(0,0,2*(this.container.beat.graceType!==m.None?Qa.GraceScale:1))),this.addGlyph(t),this.addGlyph(new Fo(0,0,2*(this.container.beat.graceType!==m.None?Qa.GraceScale:1)))),s.isEmpty||(this.addGlyph(s),this.addGlyph(new Fo(0,0,4*(this.container.beat.graceType!==m.None?Qa.GraceScale:1)))),e.isEmpty||(this.accidentals=e,this.isEmpty||this.addGlyph(new Fo(0,0,2*(this.container.beat.graceType!==m.None?Qa.GraceScale:1))),this.addGlyph(e),this.addGlyph(new Fo(0,0,2*(this.container.beat.graceType!==m.None?Qa.GraceScale:1))))}super.doLayout()}createAccidentalGlyph(e,t){let s=this.renderer,i=s.accidentalHelper.applyAccidental(e),a=s.getNoteLine(e),r=this.container.beat.graceType!==m.None;const n=r?Qa.GraceScale:1;if(i!==Xe.None){let e=new no(0,s.getScoreY(a),i,n);e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==y.None&&e.harmonicType!==y.Natural){let o=e.displayValue+e.harmonicPitch;i=s.accidentalHelper.applyAccidentalForValue(e.beat,o,r,!1),a=s.accidentalHelper.getNoteLineForValue(o,!1);let h=new no(0,s.getScoreY(a),i,n);h.renderer=this.renderer,t.addGlyph(h)}}constructor(){super(),this._prebends=null,this.accidentals=null}}class zo extends Ka{constructor(e,t,s,i){super(e,t,i,zo.getSymbol(s)),this._digit=0,this._scale=0,this._digit=s,this._scale=i}doLayout(){this.width=this.getDigitWidth(this._digit)*this._scale}getDigitWidth(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:return 14;case 1:return 10;default:return 0}}static getSymbol(e){switch(e){case 0:return F.TimeSig0;case 1:return F.TimeSig1;case 2:return F.TimeSig2;case 3:return F.TimeSig3;case 4:return F.TimeSig4;case 5:return F.TimeSig5;case 6:return F.TimeSig6;case 7:return F.TimeSig7;case 8:return F.TimeSig8;case 9:return F.TimeSig9;default:return F.None}}}class Uo extends xr{constructor(e,t,s,i=1){super(e,t),this._number=0,this._scale=0,this._number=s,this._scale=i}doLayout(){let e=this._number;for(;e>0;){let t=new zo(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}}}Uo.numberHeight=18;class Xo extends xr{constructor(e,t,s,i,a,r){super(e,t),this._numerator=0,this._denominator=0,this._numerator=s,this._denominator=i,this._isCommon=a,this._isFreeTime=r}doLayout(){let e=0;const t=Uo.numberHeight;if(this._isFreeTime){const s=new go(!0);s.renderer=this.renderer,s.y=-t,s.height=2*t,s.doLayout(),this.addGlyph(s),e+=s.width+10}if(this._isCommon&&2===this._numerator&&2===this._denominator){let t=new Ka(e,0,this.commonScale,F.TimeSigCutCommon);t.width=14,this.addGlyph(t),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){let t=new Ka(e,0,this.commonScale,F.TimeSigCommon);t.width=14,this.addGlyph(t),super.doLayout()}else{let s=new Uo(e,-t/2,this._numerator,this.numberScale),i=new Uo(e,t/2,this._denominator,this.numberScale);this.addGlyph(s),this.addGlyph(i),super.doLayout();const a=this.width-e;s.x=e+(a-s.width)/2,i.x=e+(a-i.width)/2}if(this._isFreeTime){const e=new go(!1);e.renderer=this.renderer,e.x=this.width+13,e.y=-t,e.height=2*t,e.doLayout(),this.addGlyph(e),this.width=e.x+e.width}}}class Jo extends Xo{get commonScale(){return 1}get numberScale(){return 1}}class Yo extends No{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 d.Bend:case d.PrebendRelease:case d.PrebendBend:{let t=this._endNoteGlyph;t||(t=new xo(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let s=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,s),s.value%2!=0)}break;case d.Release:if(!e.isTieOrigin){let t=this._endNoteGlyph;t||(t=new xo(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let s=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,s),s.value%2!=0)}break;case d.BendRelease:{let t=this._middleNoteGlyph;t||(t=new xo(e.beat,!1),this._middleNoteGlyph=t,t.renderer=this.renderer,this.BendNoteHeads.push(t));let s=e.bendPoints[1];t.addGlyph(this.getBendNoteValue(e,e.bendPoints[1]),s.value%2!=0);let i=this._endNoteGlyph;i||(i=new xo(e.beat,!1),i.renderer=this.renderer,this._endNoteGlyph=i,this.BendNoteHeads.push(i));let a=e.bendPoints[e.bendPoints.length-1];i.addGlyph(this.getBendNoteValue(e,a),a.value%2!=0)}}}paint(e,t,s){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._beat.voice.bar),a=e+i.x+i.getBeatX(this._beat,Gs.MiddleNotes),r=e+i.x;this._beat.isLastOfVoice?r+=i.postBeatGlyphsStart:r+=i.getBeatX(this._beat.nextBeat,Gs.PreNotes),r-=8;let n=(a+r)/2;this._middleNoteGlyph&&(this._middleNoteGlyph.x=n-this._middleNoteGlyph.noteHeadOffset,this._middleNoteGlyph.y=t+i.y,this._middleNoteGlyph.paint(0,0,s)),this._endNoteGlyph&&(this._endNoteGlyph.x=r-this._endNoteGlyph.noteHeadOffset,this._endNoteGlyph.y=t+i.y,this._endNoteGlyph.paint(0,0,s)),this._notes.sort(((e,t)=>t.displayValue-e.displayValue));let o=this._beat.graceType===m.BendGrace?this._beat.nextBeat:this._beat,h=1===this._notes.length?this.getTieDirection(o,i):Ge.Up;for(let o=0;o<this._notes.length;o++){let c=this._notes[o];o>0&&o>=(this._notes.length/2|0)&&(h=Ge.Down);let u=t+i.y+i.getNoteY(c,zs.Top),p=Qa.NoteHeadHeight*Qa.GraceScale*.5;h===Ge.Down&&(u+=Qa.NoteHeadHeight);let g=c.bendStyle===l.Gradual?"grad.":"";if(c.isTieOrigin){let r=c.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,Gs.MiddleNotes),o=t+n.y+n.getNoteY(r,zs.Top);h===Ge.Down&&(o+=Qa.NoteHeadHeight),c.bendType===d.Hold||c.bendType===d.Prebend?po.paintTie(s,1,a,u,i,o,h===Ge.Down,22,4):this.drawBendSlur(s,a,u,i,o,h===Ge.Down,1,g)}else{let r=e+i.x+i.width,n=c.tieDestination.realValue;i.accidentalHelper.applyAccidentalForValue(c.beat,n,!1,!0);let o=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(n,!1));c.bendType===d.Hold||c.bendType===d.Prebend?po.paintTie(s,1,a,u,r,o,h===Ge.Down,22,4):this.drawBendSlur(s,a,u,r,o,h===Ge.Down,1,g)}switch(c.bendType){case d.Prebend:case d.PrebendBend:case d.PrebendRelease:let r=e+i.x+i.getBeatX(c.beat,Gs.PreNotes);r+=i.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;let n=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,r,n,a,u,h===Ge.Down,1)}}else{h===Ge.Up&&(p=-p);let o=0,l=0;switch(c.bendType){case d.Bend:o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,l,h===Ge.Down,1,g);break;case d.BendRelease:let m=this.getBendNoteValue(c,c.bendPoints[1]),f=this._middleNoteGlyph.getNoteValueY(m)+p;this.drawBendSlur(s,a,u,n,f,h===Ge.Down,1,g),o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,n,f,r,l,h===Ge.Down,1,g);break;case d.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,l,h===Ge.Down,1,g));break;case d.Prebend:case d.PrebendBend:case d.PrebendRelease:let y=e+i.x+i.getBeatX(c.beat,Gs.PreNotes);y+=i.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;let b=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,y,b,a,u,h===Ge.Down,1),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,l,h===Ge.Down,1,g))}}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class qo extends po{constructor(e,t,s=!1){super(e,t,s)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?Ge.Up:t.getBeatDirection(e)===Ge.Up?Ge.Down:Ge.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Ge.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,zs.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,zs.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===Ge.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===m.None?s===this.tieDirection?this.tieDirection===Ge.Up?e.getNoteY(this.endBeat.maxNote,zs.TopWithStem):e.getNoteY(this.endBeat.minNote,zs.BottomWithStem):this.tieDirection===Ge.Up?e.getNoteY(this.endBeat.maxNote,zs.BottomWithStem):e.getNoteY(this.endBeat.minNote,zs.TopWithStem):this.tieDirection===Ge.Up?e.getNoteY(this.endBeat.maxNote,zs.Top):e.getNoteY(this.endBeat.minNote,zs.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,Gs.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>p.Whole&&e===this.tieDirection?Gs.Stem:Gs.MiddleNotes)}}class jo extends qa{constructor(e,t,s,i){super(0,0),this._outType=t,this._inType=e,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.drawSlideOut(e,t,s)}paintSlideIn(e,t,s){let i=this.renderer,a=e+i.x+i.getNoteX(this._startNote,Us.Left)-2,r=t+i.y+i.getNoteY(this._startNote,zs.Center),n=a-12,o=t+i.y;switch(this._inType){case S.IntoFromBelow:o+=i.getNoteY(this._startNote,zs.Bottom);break;case S.IntoFromAbove:o+=i.getNoteY(this._startNote,zs.Top);break;default:return}let h=this.getAccidentalsWidth(i,this._startNote.beat);n-=h,a-=h,this.paintSlideLine(s,!1,n,a,o,r)}getAccidentalsWidth(e,t){let s=e.getPreNotesGlyphForBeat(t);return s&&s.accidentals?s.accidentals.width:0}drawSlideOut(e,t,s){let i=this.renderer,a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case _.Shift:case _.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,Gs.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,zs.Center),this._startNote.slideTarget){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,Gs.PreNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,zs.Center)):(n=e+i.x+i.width,o=r),this._startNote.slideTarget.realValue>this._startNote.realValue?(r+=2,o-=2):(r-=2,o+=2)}else n=e+i.x+this._parent.x,o=r;break;case _.OutUp:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+2,r=t+i.y+i.getNoteY(this._startNote,zs.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,zs.Top);break;case _.OutDown:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+2,r=t+i.y+i.getNoteY(this._startNote,zs.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,zs.Bottom);break;case _.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+4,r=t+i.y+i.getNoteY(this._startNote,zs.Center),o=t+i.y+i.getNoteY(this._startNote,zs.Top),n=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Gs.PreNotes)),h=!0;break;case _.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+4,r=t+i.y+i.getNoteY(this._startNote,zs.Center),o=t+i.y+i.getNoteY(this._startNote,zs.Bottom),n=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Gs.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new Gn(0,0,w.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 Ko extends qo{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===Ge.Up?this.startNoteRenderer.getNoteY(this._startNote,zs.Top):this.startNoteRenderer.getNoteY(this._startNote,zs.Bottom):this.startNoteRenderer.getNoteY(this._startNote,zs.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===Ge.Up?this.endNoteRenderer.getNoteY(this._endNote,zs.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,zs.BottomWithStem):this.tieDirection===Ge.Up?this.endNoteRenderer.getNoteY(this._endNote,zs.Top):this.endNoteRenderer.getNoteY(this._endNote,zs.Bottom):this.endNoteRenderer.getNoteY(this._endNote,zs.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===Ge.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===Ge.Down}isEndCentered(){return this._startNote.beat.graceType===m.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===Ge.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===Ge.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===m.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,Gs.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,Us.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,Gs.Stem):this.endNoteRenderer.getNoteX(this._endNote,Us.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,Gs.PreNotes)}}class Qo extends po{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)===Ge.Up?Ge.Down:Ge.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Ge.Up?this.startNoteRenderer.getNoteY(this.startNote,zs.Top):this.startNoteRenderer.getNoteY(this.startNote,zs.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===Ge.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===Ge.Up?e.getNoteY(this.endNote,zs.Top):e.getNoteY(this.endNote,zs.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,Gs.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,Gs.PreNotes)}}class $o extends Za{constructor(e,t){super(e,t),this._bend=null,this._effectSlur=null,this._effectEndSlur=null}doLayout(){this._effectSlur=null,this._effectEndSlur=null,super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(e.isVisible){if(e.isTieOrigin&&!e.hasBend&&!e.beat.hasWhammyBar&&e.beat.graceType!==m.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){let t=new Qo(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){let t=new Qo(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==S.None||e.slideOutType!==_.None){let t=new jo(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){let t=new Ko(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){let t=new Ko(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new Ko(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===Ge.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,i=t===Ge.Up?e.beat.minNote:e.beat.maxNote;const a=new Ko(s,i,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new Yo(e.beat);this._bend=t,t.renderer=this.renderer,this.addTie(t)}this._bend.addBends(e)}if(this.beat.isLegatoOrigin){if(!this.beat.previousBeat||!this.beat.previousBeat.isLegatoOrigin){let e=this.beat.nextBeat;for(;e.nextBeat&&e.nextBeat.isLegatoDestination;)e=e.nextBeat;this.addTie(new qo(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 qo(e,this.beat,!0))}}}}class Zo extends qa{constructor(e,t,s,i){super(e,t),this._dotOffset=0,this._circleSize=0,this._dotOffset=0,this._circleSize=0,this._dotOffset=i,this._circleSize=s}doLayout(){this.width=13}paint(e,t,s){let i=t+this.y+this.renderer.topPadding,a=t+this.y+this.renderer.height-this.renderer.bottomPadding,r=e+this.x+.5,n=a-i;s.fillRect(r,i,4,n),r+=7.5,s.beginPath(),s.moveTo(r,i),s.lineTo(r,a),s.stroke(),r+=3;let o=this._circleSize,h=(i+a)/2;s.fillCircle(r,h-o*this._dotOffset,o),s.fillCircle(r,h+o*this._dotOffset,o)}}class eh extends qa{constructor(e,t){super(e,t)}doLayout(){this.renderer.isLast?this.width=15:this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart?this.width=2:(this.width=2,this.renderer.bar.masterBar.isDoubleBar&&(this.width+=2))}paint(e,t,s){let i=t+this.y+this.renderer.topPadding,a=t+this.y+this.renderer.height-this.renderer.bottomPadding,r=e+this.x,n=a-i;if(this.renderer.isLast)s.fillRect(r+this.width-4-4,i,1,n),s.fillRect(r+this.width-4,i,4,n);else if(!this.renderer.nextRenderer||this.renderer.nextRenderer.staff!==this.renderer.staff||!this.renderer.nextRenderer.bar.masterBar.isRepeatStart)if(this.renderer.bar.masterBar.isFreeTime){const e=eh.DashSize,t=.5+(r+this.width-1|0),o=Math.ceil(n/2/e);if(s.beginPath(),o<1)s.moveTo(t,i),s.lineTo(t,a);else{let r=i;const h=(n-o*e)/(o-1);for(;r<a;)s.moveTo(t,r),s.lineTo(t,r+e),r+=e+h}s.stroke()}else s.fillRect(r+this.width-1,i,1,n),this.renderer.bar.masterBar.isDoubleBar&&s.fillRect(r+this.width-5,i,1,n)}}eh.DashSize=4;class th extends qa{constructor(e,t){super(e,t)}doLayout(){this.width=11}paint(e,t,s){let i=t+this.y+this.renderer.topPadding,a=t+this.y+this.renderer.height-this.renderer.bottomPadding,r=e+this.x,n=a-i,o=1.5,h=(i+a)/2;s.fillCircle(r,h-4.5,o),s.fillCircle(r,h+4.5,o),r+=4,s.beginPath(),s.moveTo(r,i),s.lineTo(r,a),s.stroke(),r+=3.5,s.fillRect(r,i,4,n)}}class sh extends qa{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=D.Right;let r="x"+this._count,n=s.measureText(r).width/1.5;s.fillText(r,e+this.x-n,t+this.y),s.textAlign=a}}class ih extends qa{constructor(e,t,s){super(e,t),this._number=0,this._number=s}doLayout(){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.barNumberFont,this.width=this.renderer.scoreRenderer.canvas.measureText(this._number.toString()).width+5}paint(e,t,s){if(!this.renderer.staff.isFirstInSystem)return;let i=this.renderer.resources,a=s.color;const r=s.textBaseline;s.textBaseline=L.Top,s.color=i.barNumberColor,s.font=i.barNumberFont,s.fillText(this._number.toString(),e+this.x,t+this.y),s.color=a,s.textBaseline=r}}class ah extends tn{constructor(e,t){super(e,t),this.firstLineY=0,this._startSpacing=!1,this.tupletSize=0}get lineOffset(){return this.lineSpacing+1}get tupletOffset(){return 10}get topGlyphOverflow(){const e=this.resources;return e.tablatureFont.size/2+.2*e.tablatureFont.size}get bottomGlyphOverflow(){const e=this.resources;return e.tablatureFont.size/2+.2*e.tablatureFont.size}initLineBasedSizes(){this.topPadding=this.topGlyphOverflow,this.bottomPadding=this.bottomGlyphOverflow,this.height=this.lineOffset*(this.heightLineCount-1)+this.topPadding+this.bottomPadding}updateSizes(){this.initLineBasedSizes(),this.adjustSizes(),this.updateFirstLineY(),super.updateSizes()}adjustSizes(){}updateFirstLineY(){let e=this.lineOffset*(this.heightLineCount-1),t=(this.drawnLineCount-1)*this.lineOffset;this.firstLineY=this.topPadding+(e-t)/2}doLayout(){this.initLineBasedSizes(),this.updateFirstLineY(),this.tupletSize=15+.3*this.resources.effectFont.size,super.doLayout()}getLineY(e){return this.firstLineY+this.getLineHeight(e)}getLineHeight(e){return this.lineOffset*e}paintBackground(e,t,s){super.paintBackground(e,t,s);const i=this.resources;s.color=i.staffLineColor;const a=[];for(let e=0,t=this.drawnLineCount;e<t;e++)a.push([]);this.collectSpaces(a);for(const e of a)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));for(let i=0;i<this.drawnLineCount;i++){const r=this.getLineY(i);let n=0;for(let o of a[i])s.fillRect(e+this.x+n,t+this.y+r|0,o[0]-n,tn.StaffLineThickness),n=o[0]+o[1];s.fillRect(e+this.x+n,t+this.y+r|0,this.width-n,tn.StaffLineThickness)}s.color=i.mainGlyphColor,this.paintSimileMark(e,t,s)}collectSpaces(e){}createStartSpacing(){if(this._startSpacing)return;const e=0===this.index?this.settings.display.firstStaffPaddingLeft:this.settings.display.staffPaddingLeft;this.addPreBeatGlyph(new Fo(0,0,e)),this._startSpacing=!0}paintTuplets(e,t,s,i=!1){for(const a of this.bar.voices)if(this.hasVoiceContainer(a)){const r=this.getVoiceContainer(a);for(const a of r.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,a,i)}}getTupletBeamDirection(e){return this.getBeamDirection(e)}paintTupletHelper(e,t,s,i,a){const r=this.resources;let n,o=s.textAlign,h=s.textBaseline;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=D.Center,s.textBaseline=L.Middle;let l=i.beats[0].tupletNumerator,d=i.beats[0].tupletDenominator;n=2===l&&3===d?"2":3===l&&2===d?"3":4===l&&6===d?"4":5===l&&4===d?"5":6===l&&4===d?"6":7===l&&4===d?"7":9===l&&8===d?"9":10===l&&8===d?"10":11===l&&8===d?"11":12===l&&8===d?"12":13===l&&8===d?"13":l+":"+d;let c=this.tupletOffset,u=5;if(1!==i.beats.length&&i.isFull){let o=i.beats[0],h=i.beats[i.beats.length-1],l=null,d=null;for(let e=0;e<i.beats.length;e++)if(!i.beats[e].isRest){l=i.beats[e];break}for(let e=i.beats.length-1;e>=0;e--)if(!i.beats[e].isRest){d=i.beats[e];break}let p=!1;l||(l=o,p=!0),d||(d=h);let g=this.helpers.beamHelperLookup[i.voice.index].get(o.index),m=this.helpers.beamHelperLookup[i.voice.index].get(h.index),f=g.getBeatLineX(o),y=m.getBeatLineX(h),b=this.helpers.beamHelperLookup[i.voice.index].get(l.index),S=this.helpers.beamHelperLookup[i.voice.index].get(d.index),_=this.getTupletBeamDirection(g),w=this.calculateBeamYWithDirection(b,f,_),B=this.calculateBeamYWithDirection(S,y,_);p&&(w=Math.max(w,B),B=w),s.font=r.effectFont;let k=s.measureText(n).width,T=3,x=(f+y)/2,N=x-k/2-T,v=x+k/2+T,P=(B-w)/(y-f),C=w-P*f,E=P*N+C,F=P*x+C,D=P*v+C;_===Ge.Down&&(c*=-1,u*=-1),s.beginPath(),s.moveTo(e+this.x+f,t+this.y+w-c|0),a?s.quadraticCurveTo(e+this.x+(N+f)/2,t+this.y+E-c-u|0,e+this.x+N,t+this.y+E-c-u|0):(s.lineTo(e+this.x+f,t+this.y+w-c-u|0),s.lineTo(e+this.x+N,t+this.y+E-c-u|0)),s.stroke(),s.beginPath(),s.moveTo(e+this.x+v,t+this.y+D-c-u|0),a?s.quadraticCurveTo(e+this.x+(y+v)/2,t+this.y+D-c-u|0,e+this.x+y,t+this.y+B-c|0):(s.lineTo(e+this.x+y,t+this.y+B-c-u|0),s.lineTo(e+this.x+y,t+this.y+B-c|0)),s.stroke(),s.fillText(n,e+this.x+x,t+this.y+F-c-u)}else for(const a of i.beats){let o=this.helpers.beamHelperLookup[i.voice.index].get(a.index);if(!o)continue;let h=this.getTupletBeamDirection(o),l=o.getBeatLineX(a),d=this.calculateBeamYWithDirection(o,l,h);h===Ge.Down?d+=c+u:d-=c+u,s.font=r.effectFont,s.fillText(n,e+this.x+l,t+this.y+d)}s.textAlign=o,s.textBaseline=h}paintBeams(e,t,s){for(const i of this.helpers.beamHelpers)for(const a of i)this.paintBeamHelper(e+this.beatGlyphsStart,t,s,a)}drawBeamHelperAsFlags(e){return 1===e.beats.length}paintBeamHelper(e,t,s,i){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(this.drawBeamHelperAsFlags(i)?this.paintFlag(e,t,s,i):this.paintBar(e,t,s,i))}shouldPaintFlag(e,t){return e.graceType!==m.BendGrace&&(!e.deadSlapped&&(!!t.hasBeatLineX(e)&&((e.graceType===m.None||this.settings.notation.notationMode!==T.SongBook)&&(e.duration!==p.Whole&&e.duration!==p.DoubleWhole&&e.duration!==p.QuadrupleWhole))))}paintFlag(e,t,s,i){for(const a of i.beats){if(!this.shouldPaintFlag(a,i))continue;let r=a.graceType!==m.None,n=r?Qa.GraceScale:1,o=this.getFlagStemSize(i.shortestDuration),h=i.getBeatLineX(a),l=this.getBeamDirection(i),d=this.getFlagTopY(a,l),c=this.getFlagBottomY(a,l),u=0;if(l===Ge.Down?(c+=o*n,u=c):(d-=o*n,u=d),i.hasLine(!0,a)){if(this.paintBeamingStem(a,t+this.y,e+this.x+h,t+this.y+d,t+this.y+c,s),a.graceType===m.BeforeBeat){let i=15,a=12;s.beginPath(),l===Ge.Down?(s.moveTo(e+this.x+h-a/2,t+this.y+c-i),s.lineTo(e+this.x+h+a/2,t+this.y+c)):(s.moveTo(e+this.x+h-a/2,t+this.y+d+i),s.lineTo(e+this.x+h+a/2,t+this.y+d)),s.stroke()}if(i.hasFlag(!0,a)){let i=new $a(h-.5,u,a.duration,l,r);i.renderer=this,i.doLayout(),i.paint(e+this.x,t+this.y,s)}}}}getFlagStemSize(e,t=!1){let s=0;switch(e){case p.QuadrupleWhole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:case p.ThirtySecond:case p.SixtyFourth:case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:s=3;break;default:s=t?3:0}return this.getLineHeight(s)}recreatePreBeatGlyphs(){this._startSpacing=!1,super.recreatePreBeatGlyphs()}calculateBeamY(e,t){return this.calculateBeamYWithDirection(e,t,this.getBeamDirection(e))}createPreBeatGlyphs(){super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Zo(0,0,1.5,3)),this.createLinePreBeatGlyphs(),this.addPreBeatGlyph(new ih(0,this.getLineHeight(-.25),this.bar.index+1))}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new th(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new sh(0,this.getLineHeight(-.25),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new eh(0,0))}paintBar(e,t,s,i){for(let a=0,r=i.beats.length;a<r;a++){let r=i.beats[a];if(!i.hasBeatLineX(r)||r.deadSlapped)continue;let n=r.graceType!==m.None?Qa.GraceScale:1,o=i.getBeatLineX(r),h=this.getBeamDirection(i),l=t+this.y+this.getBarLineStart(r,h),d=t+this.y+this.calculateBeamY(i,o);this.paintBeamingStem(r,t+this.y,e+this.x+o,l,d,s);let c=d;h===Ge.Down?c+=2*s.font.size:0!==a&&(c-=1.5*s.font.size);let u=6*n,p=(tn.BeamSpacing+tn.BeamThickness)*n,g=tn.BeamThickness*n,f=le.getIndex(r.duration)-2,y=t+this.y;h===Ge.Down&&(p=-p,g=-g);for(let t=0;t<f;t++){let n=0,h=0,l=0,d=0,c=y+t*p;if(a<i.beats.length-1){const p=Dr.isFullBarJoin(r,i.beats[a+1],t);if(t===f-1&&p&&r.beamingMode===G.ForceSplitOnSecondaryToNext)n=o,h=n+u,l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),ah.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g),h=i.getBeatLineX(i.beats[a+1]),n=h-u,l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),ah.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g);else{if(p)n=o,h=i.getBeatLineX(i.beats[a+1]);else{if(0!==a&&Dr.isFullBarJoin(i.beats[a-1],r,t))continue;n=o,h=n+u}l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),ah.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g)}}else a>0&&!Dr.isFullBarJoin(r,i.beats[a-1],t)&&(n=o-u,h=o,l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),ah.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g))}}}static paintSingleBar(e,t,s,i,a,r){e.beginPath(),e.moveTo(t,s),e.lineTo(i,a),e.lineTo(i,a+r),e.lineTo(t,s+r),e.closePath(),e.fill()}}class rh extends ah{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.beatEffectsMinY=null,this.beatEffectsMaxY=null,this.accidentalHelper=new Cr(this)}get lineSpacing(){return tn.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return this.bar.staff.standardNotationLineCount}registerBeatEffectOverflows(e,t){const s=this.beatEffectsMinY;(null==s||e<s)&&(this.beatEffectsMinY=e);const i=this.beatEffectsMaxY;(null==i||t>i)&&(this.beatEffectsMaxY=t)}getScoreY(e){return super.getLineY(e/2)}getScoreHeight(e){return super.getLineHeight(e/2)}doLayout(){if(super.doLayout(),!this.bar.isEmpty&&this.accidentalHelper.maxLineBeat){let e=this.getScoreY(-2),t=this.getScoreY(10),s=this.simpleWhammyOverflow;const i=this.beatEffectsMinY;if(null!==i){const t=e-i;t>0&&this.registerOverflowTop(t)}const a=this.beatEffectsMaxY;if(null!==a){const e=a-t;e>0&&this.registerOverflowBottom(e)}this.registerOverflowTop(s);let r=this.getScoreY(this.accidentalHelper.maxLine),n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);n.direction===Ge.Up&&(r-=this.getStemSize(n),n.hasTuplet&&(r-=this.tupletSize)),r<e&&this.registerOverflowTop(Math.abs(r)+s);let o=this.getScoreY(this.accidentalHelper.minLine),h=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);h.direction===Ge.Down&&(o+=this.getStemSize(h),h.hasTuplet&&(o+=this.tupletSize)),o>t&&this.registerOverflowBottom(Math.abs(o)-t)}}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s),this.paintTuplets(e,t,s)}getSlashFlagY(e,t){let s=(this.heightLineCount-1)/2,i=0;switch(e){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:i+=2;break;default:i+=1}t==Ge.Down?s+=i:s-=i;return this.getLineY(s)}getFlagTopY(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):this.getScoreY(this.accidentalHelper.getMinLine(e))}getFlagBottomY(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):this.getScoreY(this.accidentalHelper.getMaxLine(e))}getBeamDirection(e){return e.direction}getStemSize(e,t=!1){let s=1===e.beats.length?this.getFlagStemSize(e.shortestDuration,t):this.getBarStemSize(e.shortestDuration);return e.isGrace&&(s*=Qa.GraceScale),s}getBarStemSize(e){let t=0;switch(e){case p.QuadrupleWhole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:t=6;break;case p.ThirtySecond:t=8;break;case p.SixtyFourth:case p.OneHundredTwentyEighth:t=9;break;case p.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){if(e.beat.slashed){let e=(this.heightLineCount-1)/2;return this.getLineY(e)}let s=super.getNoteY(e,t);if(isNaN(s)){const t=Cr.computeLineWithoutAccidentals(this.bar,e);s=this.getScoreY(t)}return s}applyLayoutingInfo(){const e=super.applyLayoutingInfo();if(e&&this.bar.isMultiVoice){let e=this.getScoreY(-2),t=this.getScoreY(10),s=this.helpers.collisionHelper.getBeatMinMaxY();s[0]<e&&this.registerOverflowTop(Math.abs(s[0])),s[1]>t&&this.registerOverflowBottom(Math.abs(s[1])-t)}return e}calculateBeamYWithDirection(e,t,s){let i=this.getStemSize(e);if(!e.drawingInfos.has(s)){let t=new Fr;e.drawingInfos.set(s,t);const a=e.beats[0],r=e.beats[e.beats.length-1],n=e.isRestBeamHelper;t.startBeat=a,t.startX=e.getBeatLineX(a),t.startY=n?s===Ge.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===Ge.Up?this.getFlagTopY(a,s)-i:this.getFlagBottomY(a,s)+i,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?s===Ge.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===Ge.Up?this.getFlagTopY(r,s)-i:this.getFlagBottomY(r,s)+i;let o=10;if(s===Ge.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),s===Ge.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),s===Ge.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),s===Ge.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(s===Ge.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=le.getIndex(e.shortestDuration)-2;let a=e.isGrace?Qa.GraceScale:1,r=i*(tn.BeamSpacing+tn.BeamThickness)*a;if(r+=tn.BeamSpacing,s===Ge.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===Ge.Down&&null!==e.maxRestLine){const s=this.getScoreY(e.maxRestLine)+r-t.calcY(e.getBeatLineX(e.beatOfMaxRestLine));s>0&&(t.startY+=s,t.endY+=s)}}if(e.slashBeats.length>0)for(const a of e.slashBeats){const r=t.calcY(e.getBeatLineX(a));let n=this.getSlashFlagY(a.duration,s);s===Ge.Up?n-=i:s===Ge.Down&&(n+=i);const o=n-r;o>0&&(t.startY+=o,t.endY+=o)}}}return e.drawingInfos.get(s).calcY(t)}getBarLineStart(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):t===Ge.Up?this.getScoreY(this.accidentalHelper.getMaxLine(e)):this.getScoreY(this.accidentalHelper.getMinLine(e))}createLinePreBeatGlyphs(){if(this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let e=0;switch(this.bar.clef){case 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 oo(0,this.getScoreY(e)+.5*tn.StaffLineThickness,this.bar.clef,this.bar.clefOttava))}(0===this.index&&this.bar.masterBar.keySignature!==v.C||this.bar.previousBar&&this.bar.masterBar.keySignature!==this.bar.previousBar.masterBar.keySignature)&&(this.createStartSpacing(),this.createKeySignatureGlyphs()),(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createKeySignatureGlyphs(){let e=0,t=this.bar.masterBar.keySignature,s=this.bar.previousBar?this.bar.previousBar.masterBar.keySignature:0;switch(this.bar.clef){case 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(le.keySignatureIsSharp(t))for(let s=0;s<Math.abs(t);s++){let t=rh.SharpKsSteps[s]+e;a.push(new no(0,this.getScoreY(t),Xe.Sharp,1)),i.set(t,!0)}else for(let s=0;s<Math.abs(t);s++){let t=rh.FlatKsSteps[s]+e;a.push(new no(0,this.getScoreY(t),Xe.Flat,1)),i.set(t,!0)}if(this.bar.masterBar.keySignature===v.C){let t=Math.abs(s),a=le.keySignatureIsSharp(s)?rh.SharpKsSteps:rh.FlatKsSteps;for(let s=0;s<t;s++){let t=a[s]+e;i.has(t)||this.addPreBeatGlyph(new no(0,this.getScoreY(a[s]+e),Xe.Natural,1))}}for(let e of a)this.addPreBeatGlyph(e)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Fo(0,0,5));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new Jo(0,this.getScoreY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon,this.bar.masterBar.isFreeTime))}createVoiceGlyphs(e){for(const t of e.beats){let s=new $o(t,this.getVoiceContainer(e));s.preNotes=new Wo,s.onNotes=new Ro,this.addBeatGlyph(s)}}getNoteLine(e){return this.accidentalHelper.getNoteLine(e)}completeBeamingHelper(e){if(this.bar.isMultiVoice&&e.highestNoteInHelper&&e.lowestNoteInHelper){let t=this.getNoteY(e.highestNoteInHelper,zs.Center),s=this.getNoteY(e.lowestNoteInHelper,zs.Center),i=this.getStemSize(e);e.hasTuplet&&(i+=2*this.resources.effectFont.size),e.direction==Ge.Up?t-=i:s+=i;for(const i of e.beats)this.helpers.collisionHelper.reserveBeatSlot(i,t,s)}}paintBeamingStem(e,t,s,i,a,r){r.lineWidth=tn.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}}rh.StaffId="score",rh.SharpKsSteps=[-1,2,-2,1,4,0,3],rh.FlatKsSteps=[3,0,4,1,5,2,6];class nh extends Tr{get staffId(){return rh.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new rh(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showStandardNotation}constructor(){super()}}class oh extends qa{constructor(e,t,s,i){super(0,0),this._inType=e,this._outType=t,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.paintSlideOut(e,t,s)}paintSlideIn(e,t,s){let i=this.renderer,a=0,r=0,n=0,o=0;switch(this._inType){case S.IntoFromBelow:n=e+i.x+i.getNoteX(this._startNote,Us.Left)-2,o=t+i.y+i.getNoteY(this._startNote,zs.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,zs.Center)+3;break;case S.IntoFromAbove:n=e+i.x+i.getNoteX(this._startNote,Us.Left)-2,o=t+i.y+i.getNoteY(this._startNote,zs.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,zs.Center)-3;break;default:return}this.paintSlideLine(s,!1,a,n,r,o)}paintSlideOut(e,t,s){let i=this.renderer,a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case _.Shift:case _.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,Gs.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,zs.Center),this._startNote.slideTarget){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,Gs.OnNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,zs.Center)):(n=e+i.x+i.width,o=r),this._startNote.slideTarget.fret>this._startNote.fret?(r+=3,o-=3):(r-=3,o+=3)}else n=e+i.x+this._parent.x,o=r;break;case _.OutUp:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+2,r=t+i.y+i.getNoteY(this._startNote,zs.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,zs.Center)-3;break;case _.OutDown:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+2,r=t+i.y+i.getNoteY(this._startNote,zs.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,zs.Center)+3;break;case _.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+4,r=t+i.y+i.getNoteY(this._startNote,zs.Center),n=e+i.x+i.width,o=r+9,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Gs.PreNotes)),h=!0;break;case _.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+4,r=t+i.y+i.getNoteY(this._startNote,zs.Center),n=e+i.x+i.width,o=r-9,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Gs.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new Gn(0,0,w.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 hh extends po{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?Ge.Up:hh.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?Ge.Up:Ge.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,zs.Center):this.tieDirection===Ge.Up?this.startNoteRenderer.getNoteY(this.startNote,zs.Top):this.startNoteRenderer.getNoteY(this.startNote,zs.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Us.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,Us.Left):this.endNoteRenderer.getNoteX(this.endNote,Us.Center)}}class lh extends hh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=hh.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!==hh.getBeamDirectionForNote(e))return!1;switch(this._direction){case Ge.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 Ge.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 dh extends Za{constructor(e,t){super(e,t),this._bend=null,this._effectSlurs=[]}drawBeamHelperAsFlags(e){return e.hasFlag(this.renderer.drawBeamHelperAsFlags(e),this.beat)}doLayout(){this._effectSlurs=[],super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(!e.isVisible)return;let t=this.renderer;if(e.isTieOrigin&&t.showTiedNotes&&e.tieDestination.isVisible){let t=new hh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){let t=new hh(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new hh(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 lh(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 lh(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==S.None||e.slideOutType!==_.None){let t=new oh(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new Po;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class ch extends qa{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===y.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===d.Bend||e.bendType===d.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(x.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===y.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(le.isAlmostEqualTo(e.harmonicValue,0))this._trillNoteString="";else switch(e.harmonicType){case y.Artificial:case y.Pinch:case y.Tap:case y.Semi:case y.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).width,this.width=this.noteStringWidth,this.height=this.renderer.scoreRenderer.canvas.font.size,!!this._trillNoteString&&(this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,this._trillNoteStringWidth=3+this.renderer.scoreRenderer.canvas.measureText(this._trillNoteString).width,this.width+=this._trillNoteStringWidth)}}paint(e,t,s){if(this.isEmpty)return;let i=this.noteStringWidth+this._trillNoteStringWidth,a=e+this.x+(this.width-i)/2,r=this.renderer.scoreRenderer.canvas.font;this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,s.fillText(this._trillNoteString,a+this.noteStringWidth+3,t+this.y),this.renderer.scoreRenderer.canvas.font=r,s.fillText(this._noteString,a,t+this.y)}buildBoundingsLookup(e,t,s){let i=new Pa;i.note=this._note,i.noteHeadBounds=new ds,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 uh extends qa{constructor(e,t,s){super(e,t),this._notes=[],this._deadSlapped=null,this.minStringNote=null,this.beatEffects=new Map,this.notesPerString=new Map,this.noteStringWidth=0,this._isGrace=s}buildBoundingsLookup(e,t,s){for(const i of this._notes)i.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteX(e,t){if(this.notesPerString.has(e.string)){let s=this.notesPerString.get(e.string),i=this.x+s.x;switch(t){case Us.Left:break;case Us.Center:i+=s.noteStringWidth/2;break;case Us.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 zs.Top:case zs.TopWithStem:i-=s.height/2+2;break;case zs.Center:break;case zs.Bottom:case zs.BottomWithStem:i+=s.height/2}return i}return 0}doLayout(){let e=0;if(this.beat.deadSlapped)this._deadSlapped=new _o,this._deadSlapped.renderer=this.renderer,this._deadSlapped.doLayout(),e=this._deadSlapped.width,this.noteStringWidth=e;else{let t=0;for(let s=0,i=this._notes.length;s<i;s++){let i=this._notes[s];i.renderer=this.renderer,i.doLayout(),i.width>e&&(e=i.width),i.noteStringWidth>t&&(t=i.noteStringWidth)}this.noteStringWidth=t;let s=this.renderer.resources.tablatureFont.size,i=this.getNoteY(this.minStringNote,zs.Center)+s/2,a=7;for(const e of this.beatEffects.values())e.y+=i,e.x+=this.width/2,e.renderer=this.renderer,i+=a,e.doLayout()}this.width=e}addNoteGlyph(e,t){this._notes.push(e),this.notesPerString.set(t.string,e),(!this.minStringNote||t.string<this.minStringNote.string)&&(this.minStringNote=t)}paint(e,t,s){if(e+=this.x,t+=this.y,this.beat.deadSlapped)this._deadSlapped?.paint(e,t,s);else{let i=this.renderer.resources,a=s.textBaseline;s.textBaseline=L.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 ph extends Ka{constructor(e,t,s,i){super(e,t,1,Bo.getSymbol(i)),this._isVisibleRest=s,this._duration=i}doLayout(){this._isVisibleRest?this.width=Bo.getSize(this._duration):this.width=10}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){this._isVisibleRest&&super.paint(e,t,s)}}class gh extends hn{constructor(){super(...arguments),this.slash=null,this.noteNumbers=null,this.restGlyph=null}getNoteX(e,t){return this.noteNumbers?this.noteNumbers.getNoteX(e,t):0}getNoteY(e,t){return this.noteNumbers?this.noteNumbers.getNoteY(e,t):0}buildBoundingsLookup(e,t,s){this.noteNumbers&&this.noteNumbers.buildBoundingsLookup(e,t+this.x,s+this.y)}doLayout(){let 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 ph(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 Fo(0,0,5));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new lo(0,s,1.5))}}else{let t,s=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==m.None;if(this.container.beat.slashed&&!this.container.beat.notes.some((e=>e.isTieDestination))){const i=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),a=e.getLineY(i),r=new Oo(0,a,this.container.beat.duration,s);this.slash=r,r.beat=this.container.beat,r.beamingHelper=this.beamingHelper,this.addGlyph(r),t=r.beatEffects}else{const e=new uh(0,0,s);this.noteNumbers=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;for(let e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);this.addGlyph(e),t=e.beatEffects}if(this.container.beat.hasWhammyBar){let e=new Co(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!t.has("tremolo")){let e=0,s=this.container.beat.tremoloSpeed,i=5;switch(s){case p.ThirtySecond:e=10;break;case p.Sixteenth:e=5;break;case p.Eighth:e=0}this.container.beat.duration<p.Half&&(i=0),t.set("tremolo",new So(i,e,s))}if(this.container.beat.dots>0&&e.rhythmMode!==B.Hidden){this.addGlyph(new Fo(0,0,5));for(let t=0;t<this.container.beat.dots;t++)this.addGlyph(new lo(0,e.lineOffset*e.bar.staff.tuning.length+e.settings.notation.rhythmHeight,1.5))}}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.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteNumbers?this.centerX=this.noteNumbers.x+this.noteNumbers.noteStringWidth/2:this.slash&&(this.centerX=this.slash.x+this.slash.width/2)}updateBeamingHelper(){this.noteNumbers?this.noteNumbers.updateBeamingHelper(this.container.x+this.x):this.restGlyph?this.restGlyph.updateBeamingHelper(this.container.x+this.x):this.slash&&this.slash.updateBeamingHelper(this.container.x+this.x)}createNoteGlyph(e){let t=this.renderer,s=new ch(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 mh extends qa{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10}paint(e,t,s){let i=this.renderer,a=t+this.x+i.getNoteY(this._beat.maxStringNote,zs.Top),r=t+this.y+i.getNoteY(this._beat.minStringNote,zs.Bottom),n=e+this.x+this.width/2|0;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 Gn(0,0,w.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let i=a,n=r-8;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4,n,-90),t.paint(0,-t.height/2,s),s.endRotate()}else if(this._beat.brushType===c.ArpeggioDown){let t=new Gn(0,0,w.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let i=a+8,n=r;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4,i,90),t.paint(0,-t.height/2,s),s.endRotate()}this._beat.brushType===c.BrushUp||this._beat.brushType===c.ArpeggioUp?(s.beginPath(),s.moveTo(n,r),s.lineTo(n+4,r-8),s.lineTo(n-4,r-8),s.closePath(),s.fill()):(s.beginPath(),s.moveTo(n,a),s.lineTo(n+4,a+8),s.lineTo(n-4,a+8),s.closePath(),s.fill())}}}class fh extends on{doLayout(){this.container.beat.brushType===c.None||this.container.beat.isRest||(this.addGlyph(new mh(this.container.beat)),this.addGlyph(new Fo(0,0,4))),super.doLayout()}constructor(){super()}}class yh extends qa{constructor(e,t){super(e,t)}doLayout(){this.width=28}paint(e,t,s){let i=this.renderer.bar.staff.tuning.length,a=i<=4?F.FourStringTabClef:F.SixStringTabClef,r=i<=4?i/4.5:i/6.5;s.fillMusicFontSymbol(e+this.x+5,t+this.y,r,a,!1)}}class bh extends Xo{get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?Qa.GraceScale:1}}class Sh extends ah{constructor(e,t){super(e,t),this._hasTuplets=!1,this.showTimeSignature=!1,this.showRests=!1,this.showTiedNotes=!1,t.staff.showStandardNotation||(this.showTimeSignature=!0,this.showRests=!0,this.showTiedNotes=!0)}get lineSpacing(){return Sh.TabLineSpacing}get heightLineCount(){return this.bar.staff.tuning.length}get drawnLineCount(){return this.bar.staff.tuning.length}get rhythmMode(){let e=this.settings.notation.rhythmMode;return e===B.Automatic&&(e=this.bar.staff.showStandardNotation?B.Hidden:B.ShowWithBars),e}getTabY(e){return super.getLineY(e)}getTabHeight(e){return super.getLineHeight(e)}collectSpaces(e){for(let t of this.bar.voices)if(this.hasVoiceContainer(t)){let s=this.getVoiceContainer(t);for(let t of s.beatGlyphs){let i=t.onNotes,a=i.noteNumbers;if(a)for(const[r,n]of a.notesPerString)n.isEmpty||e[this.bar.staff.tuning.length-r].push(new Float32Array([s.x+t.x+i.x+a.x,a.width+1]))}}}adjustSizes(){this.rhythmMode!==B.Hidden&&(this.height+=this.settings.notation.rhythmHeight,this.bottomPadding+=this.settings.notation.rhythmHeight)}doLayout(){if(super.doLayout(),this.rhythmMode!==B.Hidden){this._hasTuplets=!1;for(let e of this.bar.voices)if(this.hasVoiceContainer(e)){if(this.getVoiceContainer(e).tupletGroups.length>0){this._hasTuplets=!0;break}}this._hasTuplets&&this.registerOverflowBottom(this.tupletSize)}}createLinePreBeatGlyphs(){if(this.isFirstOfLine){let e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new yh(5,this.getTabY(e)))}this.showTimeSignature&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Fo(0,0,5));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new bh(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon,this.bar.masterBar.isFreeTime))}createVoiceGlyphs(e){for(const t of e.beats){let s=new dh(t,this.getVoiceContainer(e));s.preNotes=new fh,s.onNotes=new gh,this.addBeatGlyph(s)}}paint(e,t,s){super.paint(e,t,s),this.rhythmMode!==B.Hidden&&(this.paintBeams(e,t,s),this.paintTuplets(e,t,s))}drawBeamHelperAsFlags(e){return super.drawBeamHelperAsFlags(e)||this.rhythmMode===B.ShowWithBeams}getFlagTopY(e,t){const s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==p.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,zs.Bottom):this.height-this.settings.notation.rhythmHeight-this.tupletSize}getFlagBottomY(e,t){return this.getFlagAndBarPos()}getFlagStemSize(e,t=!1){return 0}getBarLineStart(e,t){let s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==p.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,zs.Bottom)+this.lineOffset/2:this.height-this.settings.notation.rhythmHeight-this.tupletSize}getBeamDirection(e){return Ge.Down}getFlagAndBarPos(){return this.height-(this._hasTuplets?this.tupletSize/2:0)}calculateBeamYWithDirection(e,t,s){return this.getFlagAndBarPos()}shouldPaintFlag(e,t){return!!super.shouldPaintFlag(e,t)&&(e.graceType===m.None&&this.drawBeamHelperAsFlags(t))}paintBeamingStem(e,t,s,i,a,r){if(a<i){const e=a;a=i,i=e}r.lineWidth=tn.StemWidth,r.beginPath();let n=[];this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.has(e.displayStart)&&(n=this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.get(e.displayStart).slots.slice(),n.sort(((e,t)=>e.topY-t.topY)));let o=a;for(;o>i;){r.moveTo(s,o);let e=i;if(!(n.length>0&&n[n.length-1].bottomY>e)){r.lineTo(s,e);break}{const i=n.pop();e=t+i.bottomY,r.lineTo(s,e),o=t+i.topY}}r.stroke(),r.lineWidth=1}}Sh.StaffId="tab",Sh.TabLineSpacing=10;class _h extends Tr{get staffId(){return Sh.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}constructor(){super(),this.showTimeSignature=null,this.showRests=null,this.showTiedNotes=null,this.hideOnPercussionTrack=!0}canCreate(e,t){return t.showTablature&&t.tuning.length>0&&super.canCreate(e,t)}create(e,t){let s=new Sh(e,t);return null!==this.showRests&&(s.showRests=this.showRests),null!==this.showTimeSignature&&(s.showTimeSignature=this.showTimeSignature),null!==this.showTiedNotes&&(s.showTiedNotes=this.showTiedNotes),s}}class wh extends ja{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+wh.Padding}paint(e,t,s){let i=this.renderer.resources;s.font=i.effectFont;let a=s.textAlign;s.textAlign=D.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+(wh.Padding-1),s.font.size/1.6)}}wh.Padding=4;class Bh extends Nn{get notationElement(){return x.EffectTap}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new wh}}class kh{constructor(){this.noteRange=1,this.x=0,this.y=0}}!function(e){e[e.None=0]="None",e[e.Rectangle=1]="Rectangle",e[e.Ellipse=2]="Ellipse",e[e.Circle=3]="Circle"}(Xn||(Xn={}));class Th extends kh{constructor(){super(...arguments),this.align=D.Left,this.frame=Xn.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class xh extends kh{constructor(){super(...arguments),this.chord=new Be}}class Nh extends kh{}class vh extends kh{}class Ph extends kh{constructor(){super(...arguments),this.number=0}}class Ch extends kh{constructor(){super(...arguments),this.decrescendo=!1}}class Eh extends kh{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class Fh extends kh{constructor(){super(...arguments),this.octave=1}}class Dh extends kh{}class Lh{constructor(){this.defaultClef=r.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class Mh{constructor(){this.from=0,this.to=0,this.curly=!1}}class Ih{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class Ah{constructor(){this._trackChannel=0,this._beamingMode=G.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new ne,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 fs;try{s.parse(e)}catch(e){throw new K("Could not parse XML",e)}this.parseDom(s),this.consolidate(),this.score.finish(t)}consolidate(){for(const e of this.score.tracks){const t=this._voiceCounts.get(e.index);for(const s of e.staves){for(;s.bars.length<this.score.masterBars.length;)this.addNewBar(s);for(const e of s.bars){for(;e.voices.length<t;)e.addVoice(new Me);for(const t of e.voices)if(0===t.beats.length){const e=new we;e.isEmpty=!0,t.addBeat(e)}}}}Ah.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),Ah.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?u.Decrescendo:u.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 K("No valid XML");if("score"!==t.localName)throw new K('Root node of XML was not "score"');this.score=new Ne,this.score.tempo=120;for(let e of t.childNodes)if(e.nodeType===as.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===as.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 Le,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===as.Element&&"bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new Mh;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===as.Element&&"staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new Lh;t.description=e.getAttribute("description");for(let s of e.childNodes)if(s.nodeType===as.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===as.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=G.ForceSplitToNext);for(let t of e.childNodes)if(t.nodeType===as.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===as.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===as.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===as.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 Z;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 ne;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 Ih,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=Ge.Up;break;case"down":this._currentVoiceState.voiceStemDir=Ge.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const h=n.findChildElement("noteObjects");if(s.attributes.has("tempo")){const e=new Q;e.isLinear=!0,e.type=a.Tempo,e.value=parseInt(s.attributes.get("tempo")),e.ratioPosition=this._currentVoiceState.currentPosition/this._currentVoiceState.currentBarDuration,this._currentBar.masterBar.tempoAutomations.push(e)}if(h)for(let e of h.childNodes)if(e.nodeType===as.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 we;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 Me);(!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 ge;for(let a of t.childNodes)if(a.nodeType===as.Element)switch(a.localName){case"stem":switch(a.getAttribute("dir")){case"up":e.preferredBeamDirection=Ge.Up;break;case"down":e.preferredBeamDirection=Ge.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=G.ForceMergeWithNext;break;case"divide":e.beamingMode=G.ForceSplitToNext}}}parseHeads(e,t,s){for(let i of s.childNodes)if(i.nodeType===as.Element&&"head"===i.localName)this.parseHead(e,t,i)}parseHead(e,t,s){const i=new ge,a=le.parseTuning(s.getAttribute("pitch"));i.octave=a.octave-1,i.tone=a.tone.noteValue,i.isStaccato=t.isStaccato,i.accentuated=t.accentuated,e.addNote(i);for(let e of s.childNodes)if(e.nodeType===as.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===as.Element&&"drawObj"===s.localName){const t=this.parseDrawObj(s);if(t)if(t instanceof Th)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new Ze,e.fermata.type=He.Medium):"f"===t.text?e.dynamics=g.F:"j"===t.text&&(e.dynamics=g.MF):this._isFirstSystem&&""===this.score.title&&t.align===D.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===D.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===D.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof xh);else if(t instanceof vh)e.vibrato=w.Slight;else if(t instanceof Ch)e.crescendo=t.decrescendo?u.Decrescendo:u.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof Nh){const s=t;this._slurs.set(e,s)}else t instanceof Eh&&this.applyVolta(t)}}parseBarDrawObject(e){for(let t of e.childNodes)if(t.nodeType===as.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof Eh&&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===as.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 we;return s.beamingMode=this._beamingMode,this.parseDuration(e,s,t),s}if(1===parseInt(s)){let e=new we;return e.beamingMode=this._beamingMode,e.duration=p.Whole,e}return re.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return p.DoubleWhole;case"1/1":return p.Whole;case"1/2":return p.Half;case"1/4":return p.Quarter;case"1/8":return p.Eighth;case"1/16":return p.Sixteenth;case"1/32":return p.ThirtySecond;case"1/64":return p.SixtyFourth;case"1/128":return p.OneHundredTwentyEighth;default:return re.warning("Importer","Unsupported duration"),p.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===as.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof Th)switch(e.align){case D.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case D.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(let t of e.childNodes)if(t.nodeType===as.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===as.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 Dh}parseOctaveClef(e){const t=new Fh;return e.attributes.has("octave")&&(t.octave=parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new Eh;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 Ch;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new Ph;return e.attributes.has("number")&&(t.number=parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new vh}parseSlur(e){return new Nh}parseGuitar(e){const t=new xh,s=e.innerText.trim();for(let e=0;e<s.length;e++)"/"===s.charAt(e)?t.chord.strings.push(0):t.chord.strings.push(parseInt(s.charAt(e)));return t}parseText(e){const t=new Th;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=D.Left;break;case"center":t.align=D.Center;break;case"right":t.align=D.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=Xn.Rectangle;break;case"ellipse":t.frame=Xn.Ellipse;break;case"circle":t.frame=Xn.Circle;break;case"none":t.frame=Xn.None}if(e.firstElement){for(let s of e.childNodes)if(s.nodeType===as.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===as.Element)switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class Oh extends q{get name(){return"Capella"}constructor(){super()}readScore(){re.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new js(this.data).read(),re.debug(this.name,"Zip entries loaded"),e.length>0){for(let s of e)if("score.xml"===s.fileName)t=Ae.toString(s.data,this.settings.importer.encoding)}else this.data.reset(),t=Ae.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new K("No valid capella file");re.debug(this.name,"Start Parsing score.xml");try{let e=new Ah;return e.parseXml(t,this.settings),re.debug(this.name,"score.xml parsed"),e.score}catch(e){throw new K("Failed to parse CapXML",e)}}}class Rh{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 Vh{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 Hh(e,t,s){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var i,a;if(s){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=t[Symbol.asyncDispose]}if(void 0===i){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=t[Symbol.dispose],s&&(a=i)}if("function"!=typeof i)throw new TypeError("Object not disposable.");a&&(i=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:i,async:s})}else s&&e.stack.push({async:!0});return t}var Gh="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 Wh(e){function t(t){e.error=e.hasError?new Gh(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var s,i=0;return function a(){for(;s=e.stack.pop();)try{if(!s.async&&1===i)return i=0,e.stack.push(s),Promise.resolve().then(a);if(s.dispose){var r=s.dispose.call(s.value);if(s.async)return i|=2,Promise.resolve(r).then(a,(function(e){return t(e),a()}))}else i|=1}catch(e){t(e)}if(1===i)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}class zh{static enable(e,t){zh.alphaSkia=t,zh.initializeMusicFont(zh.alphaSkia.AlphaSkiaTypeface.register(e))}static initializeMusicFont(e){zh.musicFont=e}static registerFont(e,t){const s=zh.alphaSkia.AlphaSkiaTypeface.register(e.buffer);t||(t=rt.withFamilyList([s.familyName],12,s.isItalic?Je.Italic:Je.Plain,s.isBold?Ye.Bold:Ye.Regular));for(const e of t.families)this.customTypeFaces.set(zh.customTypefaceKey(e,t.isBold,t.isItalic),s);return t}static customTypefaceKey(e,t,s){return e.toLowerCase()+"_"+t+"_"+s}getTypeFace(){if(this._typeFaceCache!=this.font.toCssString(this._scale)){if(this._typeFaceIsSystem){const e={stack:[],error:void 0,hasError:!1};try{Hh(e,this._typeFace,!1)}catch(t){e.error=t,e.hasError=!0}finally{Wh(e)}}for(const t of this.font.families){var e=zh.customTypefaceKey(t,this.font.isBold,this.font.isItalic);zh.customTypeFaces.has(e)?(this._typeFaceIsSystem=!1,this._typeFace=zh.customTypeFaces.get(e)):(this._typeFaceIsSystem=!0,this._typeFace=zh.alphaSkia.AlphaSkiaTypeface.create(t,this.font.isBold,this.font.isItalic))}this._typeFaceCache=this.font.toCssString(this._scale)}return this._typeFace}constructor(){this._color=new Ce(0,0,0,0),this._lineWidth=0,this._typeFaceCache="",this._typeFaceIsSystem=!1,this._typeFace=null,this._scale=1,this.font=new rt("Arial",10,Je.Plain),this.textAlign=D.Left,this.textBaseline=L.Top,this._initialMeasure=!0,this._canvas=new zh.alphaSkia.AlphaSkiaCanvas,this.color=new Ce(0,0,0,255)}destroy(){const e={stack:[],error:void 0,hasError:!1};try{Hh(e,this._canvas,!1)}catch(t){e.error=t,e.hasError=!0}finally{Wh(e)}}onRenderFinished(){return null}beginRender(e,t){this._scale=this.settings.display.scale,this._canvas.beginRender(e,t,Tl.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=zh.alphaSkia.AlphaSkiaCanvas.rgbaToColor(e.r,e.g,e.b,e.a))}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._canvas.lineWidth=e}fillRect(e,t,s,i){s>0&&this._canvas.fillRect(e*this._scale|0,t*this._scale|0,s*this._scale,i*this._scale)}strokeRect(e,t,s,i){const a=this.lineWidth%2==0?0:.5;this._canvas.strokeRect((e*this._scale|0)+a,(t*this._scale|0)+a,s*this._scale,i*this._scale)}beginPath(){this._canvas.beginPath()}closePath(){this._canvas.closePath()}moveTo(e,t){this._canvas.moveTo(e*this._scale,t*this._scale)}lineTo(e,t){this._canvas.lineTo(e*this._scale,t*this._scale)}quadraticCurveTo(e,t,s,i){this._canvas.quadraticCurveTo(e*this._scale,t*this._scale,s*this._scale,i*this._scale)}bezierCurveTo(e,t,s,i,a,r){this._canvas.bezierCurveTo(e*this._scale,t*this._scale,s*this._scale,i*this._scale,a*this._scale,r*this._scale)}fillCircle(e,t,s){this._canvas.fillCircle(e*this._scale,t*this._scale,s*this._scale)}strokeCircle(e,t,s){this._canvas.strokeCircle(e*this._scale,t*this._scale,s*this._scale)}fill(){this._canvas.fill()}stroke(){this._canvas.stroke()}beginGroup(e){}endGroup(){}fillText(e,t,s){if(0==e.length)return;let i=zh.alphaSkia.AlphaSkiaTextAlign.Left;switch(this.textAlign){case D.Left:i=zh.alphaSkia.AlphaSkiaTextAlign.Left;break;case D.Center:i=zh.alphaSkia.AlphaSkiaTextAlign.Center;break;case D.Right:i=zh.alphaSkia.AlphaSkiaTextAlign.Right}let a=zh.alphaSkia.AlphaSkiaTextBaseline.Top;switch(this.textBaseline){case L.Top:a=zh.alphaSkia.AlphaSkiaTextBaseline.Top;break;case L.Middle:a=zh.alphaSkia.AlphaSkiaTextBaseline.Middle;break;case L.Bottom:a=zh.alphaSkia.AlphaSkiaTextBaseline.Bottom}this._canvas.fillText(e,this.getTypeFace(),this.font.size*this._scale,t*this._scale,s*this._scale,i,a)}measureText(e){return this._initialMeasure&&(this._canvas.measureText(e,this.getTypeFace(),this.font.size*this._scale),this._initialMeasure=!1),new de(this._canvas.measureText(e,this.getTypeFace(),this.font.size*this._scale),this.font.size*this._scale*zh.FontSizeToLineHeight)}fillMusicFontSymbol(e,t,s,i,a){i!==F.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(let e of i)e!==F.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){this._canvas.fillText(i,zh.musicFont,Tl.MusicFontSize*this._scale*s,e*this._scale,t*this._scale,a?zh.alphaSkia.AlphaSkiaTextAlign.Center:zh.alphaSkia.AlphaSkiaTextAlign.Left,zh.alphaSkia.AlphaSkiaTextBaseline.Alphabetic)}beginRotate(e,t,s){this._canvas.beginRotate(e*this._scale,t*this._scale,s)}endRotate(){this._canvas.endRotate()}}zh.musicFont=null,zh.customTypeFaces=new Map,zh.FontSizeToLineHeight=1.2;class Uh extends po{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 Ge.Down}static getBeamDirectionForNote(e){return Ge.Down}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,zs.Center)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Us.Right)}getEndX(){return this.endNoteRenderer.getNoteX(this.endNote,Us.Left)}}class Xh extends Za{constructor(e,t){super(e,t),this._tiedNoteTie=null}createTies(e){if(e.isVisible){if(!this._tiedNoteTie&&e.isTieOrigin&&e.tieDestination.isVisible){let t=new Uh(e,e.tieDestination,!1);this._tiedNoteTie=t,this.addTie(t)}if(!this._tiedNoteTie&&e.isTieDestination){let t=new Uh(e.tieOrigin,e,!0);this._tiedNoteTie=t,this.addTie(t)}}}}class Jh extends Bo{constructor(e,t,s){super(e,t,s)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class Yh extends hn{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.restGlyph=null}getNoteX(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=s.x;switch(t){case Us.Left:break;case Us.Center:e+=s.width/2;break;case Us.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new Pa;i.note=this.container.beat.notes[0],i.noteHeadBounds=new ds,i.noteHeadBounds.x=t+this.x+this.noteHeads.x,i.noteHeadBounds.y=s+this.y+this.noteHeads.y-this.noteHeads.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}getNoteY(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=this.y+s.y;switch(t){case zs.Top:case zs.TopWithStem:e-=s.height/2+2;break;case zs.Center:break;case zs.Bottom:case zs.BottomWithStem:e+=s.height/2}return e}return 0}updateBeamingHelper(){this.noteHeads?this.noteHeads.updateBeamingHelper(this.container.x+this.x):this.deadSlapped?this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.container.beat,this.container.x+this.x+this.deadSlapped.x+this.width,this.container.x+this.x+this.deadSlapped.x):this.restGlyph&&this.restGlyph.updateBeamingHelper(this.container.x+this.x)}doLayout(){let e=this.renderer;const t=e.getNoteLine(),s=e.getLineY(t);if(this.container.beat.deadSlapped){const e=new _o;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addGlyph(e)}else if(!this.container.beat.isEmpty)if(this.container.beat.isRest){const e=new Jh(0,s,this.container.beat.duration);this.restGlyph=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper,this.addGlyph(e),this.beamingHelper&&this.beamingHelper.applyRest(this.container.beat,0)}else{const e=this.container.beat.graceType!==m.None,t=new Oo(0,s,this.container.beat.duration,e);this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper,this.addGlyph(t)}if(this.container.beat.dots>0){this.addGlyph(new Fo(0,0,5));for(let t=0;t<this.container.beat.dots;t++)this.addGlyph(new lo(0,e.getLineY(e.getNoteLine())-e.getLineHeight(.5),1.5))}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.deadSlapped&&(this.centerX=this.deadSlapped.x+this.deadSlapped.width/2)}}class qh extends ah{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._isOnlySlash=!t.staff.showTablature&&!t.staff.showStandardNotation,this.helpers.preferredBeamDirection=Ge.Up}get lineSpacing(){return tn.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return 1}get bottomGlyphOverflow(){return 0}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s),this.paintTuplets(e,t,s)}doLayout(){super.doLayout();let e=!1;for(let t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}e&&this.registerOverflowTop(this.tupletSize)}getNoteLine(){return 0}getFlagTopY(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}getFlagBottomY(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}getBeamDirection(e){return Ge.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return isNaN(s)&&(s=this.getLineY(0)),s}calculateBeamYWithDirection(e,t,s){return this.getLineY(0)-this.getFlagStemSize(e.shortestDuration)}getBarLineStart(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}createLinePreBeatGlyphs(){this._isOnlySlash&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Fo(0,0,5));const e=this.bar.masterBar;this.addPreBeatGlyph(new Jo(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime)))}createVoiceGlyphs(e){for(const t of e.beats){let s=new Xh(t,this.getVoiceContainer(e));s.preNotes=new on,s.onNotes=0==e.index?new Yh:new hn,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){r.lineWidth=tn.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}}qh.StaffId="slash";class jh extends Tr{get staffId(){return qh.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new qh(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showSlash}constructor(){super()}}class Kh extends po{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 Ge.Up}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,zs.Top)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Us.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,Us.Left):this.endNoteRenderer.getNoteX(this.endNote,Us.Center)}}class Qh extends hh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=Ge.Up,this._forSlide=s}getTieHeight(e,t,s,i){return Math.log(s-e+1)*this.renderer.settings.notation.slurHeight}tryExpand(e,t,s,i){if(this._forSlide!==s)return!1;if(this.forEnd!==i)return!1;if(this.startNote.beat.id!==e.beat.id)return!1;if(this.endNote.beat.id!==t.beat.id)return!1;switch(this._direction){case Ge.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 Ge.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,s){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar),a=this.getBeamDirection(this.startBeat,i),r="numbered.slur."+this.startNote.beat.id+"."+this.endNote.beat.id+"."+a,n=this.renderer;n.staff.getSharedLayoutData(r,!1)||(n.staff.setSharedLayoutData(r,!0),super.paint(e,t,s))}}class $h extends Za{constructor(e,t){super(e,t),this._effectSlurs=[]}createTies(e){if(e.isVisible){if(e.isTieOrigin&&e.tieDestination.isVisible){let t=new Kh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination){let t=new Kh(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new Kh(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 Qh(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 Qh(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}}}}class Zh extends qa{constructor(e,t,s,i){super(e,t),this._isGrace=i,this._number=s}paint(e,t,s){const i=this.renderer.resources;s.font=this._isGrace?i.numberedNotationGraceFont:i.numberedNotationFont,s.textBaseline=L.Middle,s.textAlign=D.Left,s.fillText(this._number.toString(),e+this.x,t+this.y)}doLayout(){const e=this._isGrace?Qa.GraceScale:1;this.width=Zh.NoteHeadWidth*e,this.height=Zh.NoteHeadHeight*e}}Zh.NoteHeadHeight=17,Zh.NoteHeadWidth=12;class el extends qa{doLayout(){this.width=14+el.Padding,this.height=al.BarSize}paint(e,t,s){const i=el.Padding;s.fillRect(e+this.x,t+this.y,this.width-i,this.height)}}el.Padding=3;class tl extends on{constructor(){super(...arguments),this.isNaturalizeAccidental=!1,this.accidental=Xe.None}doLayout(){if(!this.container.beat.isRest&&!this.container.beat.isEmpty){let e=new To;if(e.renderer=this.renderer,this.container.beat.notes.length>0){const t=this.container.beat.notes[0],s=t?t.accidentalMode:b.Default,i=Cr.getNoteValue(t);let a=Cr.computeAccidental(this.renderer.bar.masterBar.keySignature,s,i,t.hasQuarterToneOffset);if(a==Xe.Natural){a=this.renderer.bar.masterBar.keySignature+7<7?Xe.Sharp:Xe.Flat,this.isNaturalizeAccidental=!0}if(a!==Xe.None){this.accidental=a;let s=this.renderer,i=new no(0,s.getLineY(0),a,t.beat.graceType!==m.None?Qa.GraceScale*Qa.GraceScale:Qa.GraceScale);i.renderer=this.renderer,e.addGlyph(i),this.addGlyph(e),this.addGlyph(new Fo(0,0,4))}}}super.doLayout()}}class sl extends hn{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.octaveDots=0}getNoteX(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=s.x;switch(t){case Us.Left:break;case Us.Center:e+=s.width/2;break;case Us.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new Pa;i.note=this.container.beat.notes[0],i.noteHeadBounds=new ds,i.noteHeadBounds.x=t+this.x+this.noteHeads.x,i.noteHeadBounds.y=s+this.y+this.noteHeads.y-this.noteHeads.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}getNoteY(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=this.y+s.y;switch(t){case zs.Top:case zs.TopWithStem:e-=s.height/2+2;break;case zs.Center:break;case zs.Bottom:case zs.BottomWithStem:e+=s.height/2}return e}return 0}updateBeamingHelper(){if(this.beamingHelper){let e=null;this.noteHeads?e=this.noteHeads:this.deadSlapped&&(e=this.deadSlapped),e&&this.beamingHelper.registerBeatLineX("numbered",this.container.beat,this.container.x+this.x+e.x,this.container.x+this.x+e.x+e.width)}}doLayout(){let e=this.renderer;e.shortestDuration<this.container.beat.duration&&(e.shortestDuration=this.container.beat.duration);const t=e.getLineY(e.getNoteLine());if(!this.container.beat.isEmpty){let s="0";if(this.container.beat.notes.length>0){const t=this.renderer.bar.masterBar.keySignatureType,i=this.renderer.bar.masterBar.keySignature,a=i+7,r=(t===P.Minor?sl.MinorKeySignatureOneValues:sl.MajorKeySignatureOneValues)[a],n=this.container.beat.notes[0];if(n.isDead)s="X";else{let t=n.displayValue-r,o=t<0?(t%12+12)%12:t%12,h=t<0?(Math.abs(t)+12)/12|0:t/12|0;t<0&&(h*=-1),this.octaveDots=h,e.registerOctave(h);let l=(le.keySignatureIsSharp(i)||le.keySignatureIsNatural(i)?Cr.FlatNoteSteps:Cr.SharpNoteSteps)[o]+1;Cr.AccidentalNotes[o]&&!this.container.preNotes.isNaturalizeAccidental&&(a<7?l++:l--),s=l.toString()}}if(this.container.beat.deadSlapped){const e=new _o;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addGlyph(e)}else{const e=this.container.beat.graceType!==m.None,i=new Zh(0,t,s,e);this.noteHeads=i,this.addGlyph(i)}if(this.container.beat.dots>0&&this.container.beat.duration>=p.Quarter){this.addGlyph(new Fo(0,0,5));for(let t=0;t<this.container.beat.dots;t++){const t=new lo(0,e.getLineY(0),1.5);t.renderer=this.renderer,this.addGlyph(t)}}let i=0;switch(this.container.beat.duration){case p.QuadrupleWhole:i=16;break;case p.DoubleWhole:i=8;break;case p.Whole:i=4;break;case p.Half:i=2}let a=i;for(let e=0;e<this.container.beat.dots;e++)a=a/2|0,i+=a;for(let t=0;t<i-1;t++){const t=new el(0,e.getLineY(0));t.renderer=this.renderer,this.addGlyph(t)}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.deadSlapped&&(this.centerX=this.deadSlapped.x+this.deadSlapped.width/2)}}sl.MajorKeySignatureOneValues=[59,66,61,68,63,58,65,60,67,62,69,64,71,66,61],sl.MinorKeySignatureOneValues=[71,66,73,68,63,70,65,72,67,74,69,64,71,66,73];class il extends qa{constructor(e,t,s,i){super(e,t),this._text="",this._accidental=Xe.None,this._accidentalOffset=0,this._keySignature=s,this._keySignatureType=i}doLayout(){super.doLayout();const e="1 = ";let t="",s=Xe.None;switch(this._keySignatureType){case P.Major:switch(this._keySignature){case v.Cb:t=" C",s=Xe.Flat;break;case v.Gb:t=" G",s=Xe.Flat;break;case v.Db:t=" D",s=Xe.Flat;break;case v.Ab:t=" A",s=Xe.Flat;break;case v.Eb:t=" E",s=Xe.Flat;break;case v.Bb:t=" B",s=Xe.Flat;break;case v.F:t="F";break;case v.C:t="C",s=Xe.None;break;case v.G:t="G",s=Xe.None;break;case v.D:t="D",s=Xe.None;break;case v.A:t="A",s=Xe.None;break;case v.E:t="E",s=Xe.None;break;case v.B:t="B",s=Xe.None;break;case v.FSharp:t=" F",s=Xe.Sharp;break;case v.CSharp:t=" C",s=Xe.Sharp}break;case P.Minor:switch(this._keySignature){case v.Cb:t=" a",s=Xe.Flat;break;case v.Gb:t=" e",s=Xe.Flat;break;case v.Db:t=" b",s=Xe.Flat;break;case v.Ab:t="f",s=Xe.None;break;case v.Eb:t="c",s=Xe.None;break;case v.Bb:t="g",s=Xe.None;break;case v.F:t="d";break;case v.C:t="a",s=Xe.None;break;case v.G:t="e",s=Xe.None;break;case v.D:t="b",s=Xe.None;break;case v.A:t=" f",s=Xe.Sharp;break;case v.E:t=" c",s=Xe.Sharp;break;case v.B:t=" g",s=Xe.Sharp;break;case v.FSharp:t=" d",s=Xe.Sharp;break;case v.CSharp:t=" a",s=Xe.Sharp}}this._text=e+t,this._accidental=s;const i=this.renderer.scoreRenderer.canvas,a=this.renderer.resources;i.font=a.numberedNotationFont,this._accidentalOffset=i.measureText(e).width,this.width=i.measureText(e+t).width}paint(e,t,s){const i=this.renderer.resources;s.font=i.numberedNotationFont,s.textBaseline=L.Middle,s.fillText(this._text,e+this.x,t+this.y),this._accidental!=Xe.None&&s.fillMusicFontSymbol(e+this.x+this._accidentalOffset,t+this.y,.7,no.getMusicSymbol(this._accidental),!1)}}class al extends ah{registerOctave(e){null===this.lowestOctave?(this.lowestOctave=e,this.highestOctave=e):(e<this.lowestOctave&&(this.lowestOctave=e),e>this.highestOctave&&(this.highestOctave=e))}constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.shortestDuration=p.QuadrupleWhole,this.lowestOctave=null,this.highestOctave=null,this._isOnlyNumbered=!t.staff.showSlash&&!t.staff.showTablature&&!t.staff.showStandardNotation}get lineSpacing(){return tn.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return 0}get bottomGlyphOverflow(){return 0}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s),this.paintTuplets(e,t,s,!0)}doLayout(){super.doLayout();let e=!1;for(let t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}if(e&&this.registerOverflowTop(this.tupletSize),!this.bar.isEmpty){let e=le.getIndex(this.shortestDuration)-2;if(e>0){let t=(e-1)*al.BarSpacing+al.BarSize,s=0;const i=this.lowestOctave;null!==i&&(s=Math.abs(i)*al.DotSpacing+al.DotSize),this.registerOverflowBottom(t+s)}const t=this.highestOctave;if(null!==t){const e=Math.abs(t)*al.DotSpacing+al.DotSize;this.registerOverflowTop(e)}}}paintFlag(e,t,s,i){this.paintBar(e,t,s,i)}paintBar(e,t,s,i){const a=this.resources;for(let n=0,o=i.beats.length;n<o;n++){let o=i.beats[n],h=al.BarSpacing,l=al.BarSize,d=le.getIndex(o.duration)-2,c=t+this.y,u=this.getBeatX(o,Gs.PreNotes)-this.beatGlyphsStart;var r=this.calculateBeamY(i,u);for(let t=0;t<d;t++){let a=0,d=0,p=0,g=c+t*h;n===i.beats.length-1?(a=u,d=this.getBeatX(o,Gs.PostNotes)-this.beatGlyphsStart):(a=u,d=this.getBeatX(i.beats[n+1],Gs.PreNotes)-this.beatGlyphsStart),p=g+r|0,ah.paintSingleBar(s,e+this.x+a,p,e+this.x+d,p,l)}let p=this.getBeatContainer(o).onNotes.octaveDots,g=0,m=0;p>0?(g=c+this.getLineY(0)-a.numberedNotationFont.size/1.5,m=-1*al.DotSpacing):p<0&&(g=c+r+d*h,m=al.DotSpacing);let f=this.getBeatX(o,Gs.OnNotes)+4-this.beatGlyphsStart;p=Math.abs(p);for(let t=0;t<p;t++)s.fillCircle(e+this.x+f,g,al.DotSize),g+=m}}getNoteLine(){return 0}get tupletOffset(){return super.tupletOffset+this.resources.numberedNotationFont.size}getFlagTopY(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}getFlagBottomY(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}getBeamDirection(e){return Ge.Down}getTupletBeamDirection(e){return Ge.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return isNaN(s)&&(s=this.getLineY(0)),s}calculateBeamYWithDirection(e,t,s){const i=this.resources.numberedNotationFont;return this.getLineY(0)+i.size}getBarLineStart(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}createLinePreBeatGlyphs(){this.bar.previousBar&&this.bar.masterBar.keySignature===this.bar.previousBar.masterBar.keySignature||(this.createStartSpacing(),this.createKeySignatureGlyphs()),this._isOnlyNumbered&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createKeySignatureGlyphs(){this.addPreBeatGlyph(new il(0,this.getLineY(0),this.bar.masterBar.keySignature,this.bar.masterBar.keySignatureType))}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Fo(0,0,5));const e=this.bar.masterBar;this.addPreBeatGlyph(new Jo(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime)))}createPostBeatGlyphs(){this._isOnlyNumbered&&super.createPostBeatGlyphs()}createVoiceGlyphs(e){for(const t of e.beats){let s=new $h(t,this.getVoiceContainer(e));s.preNotes=0==e.index?new tl:new on,s.onNotes=0==e.index?new sl:new hn,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){r.lineWidth=tn.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}}al.StaffId="numbered",al.BarSpacing=tn.BeamSpacing+tn.BeamThickness,al.BarSize=2,al.DotSpacing=5,al.DotSize=2;class rl extends Tr{get staffId(){return qh.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new al(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showNumbered}constructor(){super()}}class nl extends un{get notationElement(){return x.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SinglePreBeat}shouldCreateGlyph(e,t){const s=t.voice.bar.masterBar;return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&s.isFreeTime&&(0===s.index||s.isFreeTime!=s.previousMasterBar.isFreeTime)}createNewGlyph(e,t){return new Gr(0,0,"Free time",e.resources.effectFont,D.Left)}canExpand(e,t){return!0}}class ol extends ja{constructor(){super(0,0)}doLayout(){super.doLayout(),this.height=ol.TextHeight}paint(e,t,s){const i=this.renderer,a=t+this.y,r=this.height;let n=i.bar.sustainPedals,o=0;for(;o<n.length;){let t=n[o];for(;null!=t;){const i=e+this.renderer.getRatioPositionX(t.ratioPosition);let l=0;if(t.pedalType===h.Down?(s.fillMusicFontSymbol(i,a+r,1,F.KeyboardPedalPed,!0),l=ol.TextWidth/2+ol.TextLinePadding):t.pedalType===h.Up&&(s.fillMusicFontSymbol(i,a+r,1,F.KeyboardPedalUp,!0),l=ol.StarSize/2+ol.StarLinePadding),t.nextPedalMarker)if(t.nextPedalMarker.bar===t.bar){let n=e+this.renderer.getRatioPositionX(t.nextPedalMarker.ratioPosition);switch(t.nextPedalMarker.pedalType){case h.Down:n-=ol.TextWidth/2;break;case h.Hold:break;case h.Up:n-=ol.StarSize/2}const o=i+l;n>o&&s.fillRect(o,a+r-1,n-o,1)}else{const t=e+this.x+this.width,n=i+l;s.fillRect(n,a+r-1,t-n,1)}if(0===o&&t.previousPedalMarker){const t=e+this.x,n=i-l;s.fillRect(t,a+r-1,n-t,1)}o++,null!=t.nextPedalMarker&&t.nextPedalMarker.bar!==t.bar?(t=null,o=n.length):t=t.nextPedalMarker}}}}ol.TextHeight=19,ol.TextWidth=35,ol.TextLinePadding=3,ol.StarSize=16,ol.StarLinePadding=3;class hl extends un{get notationElement(){return x.EffectSustainPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Xs.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&t.voice.bar.sustainPedals.length>0}createNewGlyph(e,t){return new ol}canExpand(e,t){return!0}}class ll extends un{constructor(e,t){super(),this._type=e,this._shouldCreate=t}get notationElement(){return x.EffectGolpe}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){const s=this._shouldCreate;return t.golpe==this._type&&(!s||s(e,t))}createNewGlyph(e,t){return new Io(0,0,!0)}canExpand(e,t){return!1}}class dl extends Ka{constructor(e){super(0,0,1,dl.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case R.Open:return F.GuitarOpenPedal;case R.Closed:return F.GuitarClosePedal}return F.None}doLayout(){this.width=11,this.height=11}paint(e,t,s){super.paint(e,t+this.height,s)}}class cl extends un{get notationElement(){return x.EffectWahPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return t.wahPedal!==R.None}createNewGlyph(e,t){return new dl(t.wahPedal)}canExpand(e,t){return!1}}class ul extends un{get notationElement(){return x.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isBarre}get sizingMode(){return Xs.GroupedOnBeat}createNewGlyph(e,t){let s="";switch(t.barreShape){case V.None:case V.Full:break;case V.Half:s+="1/2"}return s+="B "+ul.toRoman(t.barreFret),new vn(s,!1)}static toRoman(e){let t="";if(e>0)for(var[s,i]of ul.RomanLetters){const a=Math.floor(e/i);e-=a*i,t+=s.repeat(a)}return t}canExpand(e,t){return e.barreFret===t.barreFret&&e.barreShape===t.barreShape}}ul.RomanLetters=new Map([["L",50],["XL",40],["X",10],["IX",9],["V",5],["IV",4],["I",1]]);class pl extends Ka{constructor(e){super(0,0,1,pl.getSymbol(e)),this.center=!0}doLayout(){this.width=26,this.height=18}static getSymbol(e){switch(e){case M.InvertedTurn:return F.OrnamentTurnInverted;case M.Turn:return F.OrnamentTurn;case M.UpperMordent:return F.OrnamentShortTrill;case M.LowerMordent:return F.OrnamentMordent}return F.None}paint(e,t,s){super.paint(e,t+this.height-4,s)}}class gl extends un{get notationElement(){return x.EffectNoteOrnament}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return t.notes.some((e=>e.ornament!==M.None))}createNewGlyph(e,t){return new pl(t.notes.find((e=>e.ornament!=M.None)).ornament)}canExpand(e,t){return!1}}class ml extends un{get notationElement(){return x.EffectRasgueado}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.hasRasgueado}get sizingMode(){return Xs.GroupedOnBeat}createNewGlyph(e,t){return new vn("rasg.")}canExpand(e,t){return!0}}class fl extends qa{constructor(e){super(0,0),this._symbols=e}doLayout(){this.height=27}paint(e,t,s){s.fillMusicFontSymbols(e+this.x,t+this.y+this.height,.8,this._symbols,!0)}}class yl extends qa{constructor(e){super(0,0),this._text=e}doLayout(){this.height=1.5*this.renderer.resources.directionsFont.size}paint(e,t,s){const i=s.font,a=s.textBaseline,r=s.textAlign;s.font=this.renderer.resources.directionsFont,s.textBaseline=L.Middle,s.textAlign=D.Right,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=i,s.textBaseline=a,s.textAlign=r}}class bl extends ja{constructor(e,t,s){super(e,t),this._barBeginGlyphs=[],this._barEndGlyphs=[],this._directions=s}doLayout(){const e=this._directions;e.has(Ve.TargetSegnoSegno)&&this._barBeginGlyphs.push(new fl([F.Segno,F.Segno])),e.has(Ve.TargetSegno)&&this._barBeginGlyphs.push(new fl([F.Segno])),e.has(Ve.TargetDoubleCoda)&&this._barBeginGlyphs.push(new fl([F.Coda,F.Coda])),e.has(Ve.TargetCoda)&&this._barBeginGlyphs.push(new fl([F.Coda])),e.has(Ve.TargetFine)&&this._barEndGlyphs.push(new yl("Fine")),e.has(Ve.JumpDaDoubleCoda)&&this._barEndGlyphs.push(new yl("To Double Coda")),e.has(Ve.JumpDaCoda)&&this._barEndGlyphs.push(new yl("To Coda")),e.has(Ve.JumpDalSegnoSegno)&&this._barEndGlyphs.push(new yl("D.S.S.")),e.has(Ve.JumpDalSegnoSegnoAlCoda)&&this._barEndGlyphs.push(new yl("D.S.S. al Coda")),e.has(Ve.JumpDalSegnoSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new yl("D.S.S. al Double Coda")),e.has(Ve.JumpDalSegnoSegnoAlFine)&&this._barEndGlyphs.push(new yl("D.S.S. al Fine")),e.has(Ve.JumpDalSegno)&&this._barEndGlyphs.push(new yl("D.S.")),e.has(Ve.JumpDalSegnoAlCoda)&&this._barEndGlyphs.push(new yl("D.S. al Coda")),e.has(Ve.JumpDalSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new yl("D.S. al Double Coda")),e.has(Ve.JumpDalSegnoAlFine)&&this._barEndGlyphs.push(new yl("D.S. al Fine")),e.has(Ve.JumpDaCapo)&&this._barEndGlyphs.push(new yl("D.C.")),e.has(Ve.JumpDaCapoAlCoda)&&this._barEndGlyphs.push(new yl("D.C. al Coda")),e.has(Ve.JumpDaCapoAlDoubleCoda)&&this._barEndGlyphs.push(new yl("D.C. al Double Coda")),e.has(Ve.JumpDaCapoAlFine)&&this._barEndGlyphs.push(new yl("D.C. al Fine"));const t=this.doSideLayout(this._barBeginGlyphs),s=this.doSideLayout(this._barEndGlyphs);this.height=Math.max(t,s)}doSideLayout(e){let t=0;for(const s of e)s.y=t,s.renderer=this.renderer,s.doLayout(),t+=s.height+3;return t}paint(e,t,s){for(const i of this._barBeginGlyphs)i.paint(e+this.x,t+this.y,s);for(const i of this._barEndGlyphs)i.paint(e+this.x+this.width,t+this.y,s)}}class Sl extends un{get notationElement(){return x.EffectDirections}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Xs.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&null!==t.voice.bar.masterBar.directions&&t.voice.bar.masterBar.directions.size>0}createNewGlyph(e,t){return new bl(0,0,t.voice.bar.masterBar.directions)}canExpand(e,t){return!0}}class _l extends ja{constructor(e){super(0,0),this._text="",this._textWidth=0,this._textHeight=0,this._timer=e}doLayout(){const e=this._timer/6e4|0,t=(this._timer-6e4*e)/1e3|0;this._text=`${e}:${t.toString().padStart(2,"0")}`;const s=this.renderer.scoreRenderer.canvas;s.font=this.renderer.resources.timerFont;const i=s.measureText(this._text);this._textHeight=s.font.size+2*_l.PaddingY,this._textWidth=i.width+2*_l.PaddingX,this.height=this._textHeight+2*_l.MarginY}paint(e,t,s){const i=this._textWidth/2|0;s.strokeRect(e+this.x-i,t+this.y+_l.MarginY,this._textWidth,this._textHeight);const a=s.font,r=s.textBaseline,n=s.textAlign;s.font=this.renderer.resources.timerFont,s.textBaseline=L.Middle,s.textAlign=D.Center,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=a,s.textBaseline=r,s.textAlign=n}}_l.PaddingX=2,_l.PaddingY=2,_l.MarginY=2;class wl extends un{get notationElement(){return x.EffectBeatTimer}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return t.showTimer}createNewGlyph(e,t){return new _l(t.timer??0)}canExpand(e,t){return!0}}class Bl{constructor(e,t){this.vertical=e,this.createLayout=t}}class kl{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class Tl{static createStyleElement(e,t){let s=e.getElementById("alphaTabStyle");if(!s){if(!t)return void re.error("AlphaTab","Font directory could not be detected, cannot create style element");s=e.createElement("style"),s.id="alphaTabStyle";let i=`\n @font-face {\n font-display: block;\n font-family: 'alphaTab';\n src: url('${t}Bravura.eot');\n src: url('${t}Bravura.eot?#iefix') format('embedded-opentype')\n , url('${t}Bravura.woff') format('woff')\n , url('${t}Bravura.otf') format('opentype')\n , url('${t}Bravura.svg#Bravura') format('svg');\n font-weight: normal;\n font-style: normal;\n }\n .at-surface * {\n cursor: default;\n vertical-align: top;\n overflow: visible;\n }\n .at-surface-svg text {\n dominant-baseline: central;\n white-space:pre;\n }\n .at {\n font-family: 'alphaTab';\n speak: none;\n font-style: normal;\n font-weight: normal;\n font-variant: normal;\n text-transform: none;\n line-height: 1;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n font-size: ${Tl.MusicFontSize}px;\n overflow: visible !important;\n }`;s.innerHTML=i,e.getElementsByTagName("head").item(0).appendChild(s),Tl.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===Tl._globalThis){try{Tl._globalThis=globalThis}catch(e){}void 0===Tl._globalThis&&(Tl._globalThis=self),void 0===Tl._globalThis&&(Tl._globalThis=global),void 0===Tl._globalThis&&(Tl._globalThis=window),void 0===Tl._globalThis&&(Tl._globalThis=Function("return this")())}return this._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in Tl.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in Tl.globalThis}static throttle(e,t){let s=0;return()=>{Tl.globalThis.clearTimeout(s),s=Tl.globalThis.setTimeout(e,t)}}static detectScriptFile(){if(!Tl.isRunningInWorker&&Tl.globalThis.ALPHATAB_ROOT){let e=Tl.globalThis.ALPHATAB_ROOT;return e=Tl.ensureFullUrl(e),e=Tl.appendScriptName(e),e}try{const e=import.meta.url;if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in Tl.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=Tl.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(!Tl.isRunningInWorker&&Tl.globalThis.ALPHATAB_FONT)return Tl.ensureFullUrl(Tl.globalThis.ALPHATAB_FONT);const e=Tl.scriptFile;if(e){let t=e.lastIndexOf(String.fromCharCode(47));if(t>=0)return e.substr(0,t)+"/font/"}return null}static registerJQueryPlugin(){if(!Tl.isRunningInWorker&&Tl.globalThis&&"jQuery"in Tl.globalThis){let e=Tl.globalThis.jQuery,t=new wr;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:wr.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&Tl.renderEngines.has(e)?Tl.renderEngines.get(e):Tl.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&Tl.layoutEngines.has(t)?Tl.layoutEngines.get(t):Tl.layoutEngines.get(e.Page)}static buildImporters(){return[new os,new ai,new Zs,new ri,new Oh,new tt]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new kl(!0,(()=>new kr))),e.set("default",e.get("svg")),e.set("skia",new kl(!1,(()=>new zh))),Tl.createPlatformSpecificRenderEngines(e),e}static enableAlphaSkia(e,t){zh.enable(e,t)}static registerAlphaSkiaCustomFont(e,t){return zh.registerFont(e,t)}static createPlatformSpecificRenderEngines(e){e.set("html5",new kl(!1,(()=>new La)))}static createDefaultRenderers(){return[new dn(Tl.StaffIdBeforeSlashAlways,[new qn,new Zn,new Dn,new Sl,new pn,new nl,new jn,new wl,new mn]),new jh,new dn(Tl.StaffIdBeforeScoreAlways,[new Tn,new ul,new gl,new ml,new cl]),new dn(Tl.StaffIdBeforeScoreHideable,[new eo,new Qn,new Mn(!0),new to,new Hn,new so,new Wn(!1),new Bh,new ll(A.Finger)],((e,t)=>t.showStandardNotation)),new nh,new dn(Tl.StaffIdBeforeNumberedAlways,[new bn,new Mn(!1),new _n,new ll(A.Thumb,((e,t)=>t.voice.bar.staff.showStandardNotation)),new hl]),new rl,new dn(Tl.StaffIdBeforeTabAlways,[new Fn]),new dn(Tl.StaffIdBeforeTabHideable,[new Qn,new to,new Hn,new so,new Wn(!0),new zn,new Bn,new Pn(y.Natural),new Pn(y.Artificial),new Pn(y.Pinch),new Pn(y.Tap),new Pn(y.Semi),new Pn(y.Feedback),new Cn,new gn,new xn,new In,new Rn,new An,new Bh,new ll(A.Finger,((e,t)=>!t.voice.bar.staff.showStandardNotation))],((e,t)=>t.showTablature)),new _h,new dn(Tl.StaffIdBeforeEndAlways,[new ll(A.Thumb,((e,t)=>!t.voice.bar.staff.showStandardNotation))])]}static createDefaultStaveProfiles(){const e=new Map,s=Tl.createDefaultRenderers();e.set(t.Default,s),e.set(t.ScoreTab,s);const i=new Set([Tl.StaffIdBeforeSlashAlways,Tl.StaffIdBeforeScoreAlways,Tl.StaffIdBeforeNumberedAlways,Tl.StaffIdBeforeTabAlways,rh.StaffId,Tl.StaffIdBeforeEndAlways]);e.set(t.Score,s.filter((e=>i.has(e.staffId))));const a=new Set([Tl.StaffIdBeforeSlashAlways,Tl.StaffIdBeforeScoreAlways,Tl.StaffIdBeforeNumberedAlways,Tl.StaffIdBeforeTabAlways,Sh.StaffId,Tl.StaffIdBeforeEndAlways]);return e.set(t.Tab,Tl.createDefaultRenderers().filter((e=>{if(e instanceof _h){const t=e;t.showTimeSignature=!0,t.showRests=!0,t.showTiedNotes=!0}return a.has(e.staffId)}))),e.set(t.TabMixed,Tl.createDefaultRenderers().filter((e=>{if(e instanceof _h){const t=e;t.showTimeSignature=!1,t.showRests=!1,t.showTiedNotes=!1}return a.has(e.staffId)}))),e}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.Page,new Bl(!0,(e=>new ro(e)))),t.set(e.Horizontal,new Bl(!1,(e=>new ao(e)))),t}static initializeMain(e,t){Tl.isRunningInWorker||Tl.isRunningInAudioWorklet||(Tl.webPlatform!==Rs.Browser&&Tl.webPlatform!==Rs.BrowserModule||(Tl.registerJQueryPlugin(),Tl.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in Tl.globalThis||(Tl.globalThis.ResizeObserver=Rh),"IntersectionObserver"in Tl.globalThis||(Tl.globalThis.IntersectionObserver=Vh),"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)})),Tl.createWebWorker=e,Tl.createAudioWorklet=t)}static get alphaTabWorker(){return this.globalThis.Worker}static get alphaTabUrl(){return this.globalThis.URL}static initializeWorker(){if(!Tl.isRunningInWorker)throw new j(s.General,"Not running in worker, cannot run worker initialization");Da.init(),wa.init(),Tl.createWebWorker=e=>{throw new j(s.General,"Nested workers are not supported")}}static initializeAudioWorklet(){if(!Tl.isRunningInAudioWorklet)throw new j(s.General,"Not running in audio worklet, cannot run worklet initialization");fr.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 Rs.NodeJs}catch(e){}try{const e=import.meta.url;if(e&&"string"==typeof e&&!e.startsWith("file://"))return Rs.BrowserModule}catch(e){}return Rs.Browser}}Tl.StaffIdBeforeSlashAlways="before-slash-always",Tl.StaffIdBeforeScoreAlways="before-score-always",Tl.StaffIdBeforeScoreHideable="before-score-hideable",Tl.StaffIdBeforeNumberedAlways="before-numbered-always",Tl.StaffIdBeforeTabAlways="before-tab-always",Tl.StaffIdBeforeTabHideable="before-tab-hideable",Tl.StaffIdBeforeEndAlways="before-end-always",Tl.MusicFontSize=34,Tl.HighDpiFactor=1,Tl._globalThis=void 0,Tl.webPlatform=Tl.detectWebPlatform(),Tl.isWebPackBundled=Tl.detectWebPack(),Tl.isViteBundled=Tl.detectVite(),Tl.scriptFile=Tl.detectScriptFile(),Tl.fontDirectory=Tl.detectFontDirectory(),Tl.bravuraFontChecker=new hr(["alphaTab"]),Tl.renderEngines=Tl.createDefaultRenderEngines(),Tl.layoutEngines=Tl.createDefaultLayoutEngines(),Tl.staveProfiles=Tl.createDefaultStaveProfiles();class xl{constructor(){this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=N.Info,this.useWorkers=!0,this.includeNoteBounds=!1,this.scriptFile=Tl.scriptFile,this.fontDirectory=Tl.fontDirectory}}class Nl{}Nl.version="1.4.0-alpha.1326",Nl.date="2025-02-27T17:49:57.997Z";var vl,Pl=Object.freeze({__proto__:null,ScoreImporter:q,ScoreLoader:rr,UnsupportedFormatError:K});class Cl{init(e,t){this.data=e,this.settings=t}export(e,t=null){const s=Oe.withCapacity(1024);return this.init(s,t??new Ot),this.writeScore(e),s.toArray()}}!function(e){e[e.SteelGuitar=1]="SteelGuitar",e[e.AcousticGuitar=2]="AcousticGuitar",e[e.TwelveStringGuitar=3]="TwelveStringGuitar",e[e.ElectricGuitar=4]="ElectricGuitar",e[e.Bass=5]="Bass",e[e.ClassicalGuitar=23]="ClassicalGuitar",e[e.UprightBass=6]="UprightBass",e[e.Ukulele=7]="Ukulele",e[e.Banjo=8]="Banjo",e[e.Mandolin=9]="Mandolin",e[e.Piano=10]="Piano",e[e.Synth=12]="Synth",e[e.Strings=11]="Strings",e[e.Brass=13]="Brass",e[e.Reed=14]="Reed",e[e.Woodwind=15]="Woodwind",e[e.Vocal=16]="Vocal",e[e.PitchedIdiophone=17]="PitchedIdiophone",e[e.Fx=21]="Fx",e[e.PercussionKit=18]="PercussionKit",e[e.Idiophone=19]="Idiophone",e[e.Membraphone=20]="Membraphone"}(vl||(vl={}));class El{constructor(e,t,s=null){if(this.icon=vl.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 Fl{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new fs;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;break;case i.Tenuto:a|=16}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 w.Slight:s.addElement("Vibrato").innerText="Slight";break;case w.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",t.ornament!==M.None&&(s.addElement("Ornament").innerText=M[t.ornament])}writeNoteProperties(e,t){const s=e.addElement("Properties");if(this.writeConcertPitch(s,t),this.writeTransposedPitch(s,t),t.isStringed&&(this.writeSimplePropertyNode(s,"String","String",(t.string-1).toString()),this.writeSimplePropertyNode(s,"Fret","Fret",t.fret.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString()),t.showStringNumber&&this.writeSimplePropertyNode(s,"ShowStringNumber","Enable",null)),t.isPiano&&(this.writeSimplePropertyNode(s,"Octave","Number",t.octave.toString()),this.writeSimplePropertyNode(s,"Tone","Step",t.tone.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString())),t.beat.tap&&this.writeSimplePropertyNode(s,"Tapped","Enable",null),t.harmonicType!==y.None){switch(t.harmonicType){case y.Natural:this.writeSimplePropertyNode(s,"HarmonicType","HType","Natural");break;case y.Artificial:this.writeSimplePropertyNode(s,"HarmonicType","HType","Artificial");break;case y.Pinch:this.writeSimplePropertyNode(s,"HarmonicType","HType","Pinch");break;case y.Tap:this.writeSimplePropertyNode(s,"HarmonicType","HType","Tap");break;case y.Semi:this.writeSimplePropertyNode(s,"HarmonicType","HType","Semi");break;case y.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 S.IntoFromAbove:i|=32;break;case S.IntoFromBelow:i|=16}switch(t.slideOutType){case _.Shift:i|=1;break;case _.Legato:i|=2;break;case _.OutDown:i|=4;break;case _.OutUp:i|=8;break;case _.PickSlideDown:i|=64;break;case _.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=Fe.defaultSteps[a],o=Fe.defaultAccidentals[a]};switch(h(),i){case b.Default:break;case b.ForceNone:case b.ForceNatural:o="";break;case b.ForceSharp:o="#";break;case b.ForceDoubleSharp:"#"===o&&(s-=2,h()),o="x";break;case b.ForceFlat:"#"===o&&(s+=1,h()),o="b";break;case b.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 te((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/te.MaxPosition*100}writeBeatNode(e,t,s){const i=e.addElement("Beat");if(i.attributes.set("id",t.id.toString()),i.addElement("Dynamic").innerText=g[t.dynamics],t.fade!==O.None&&(i.addElement("Fadding").innerText=O[t.fade]),t.isTremolo)switch(t.tremoloSpeed){case p.Eighth:i.addElement("Tremolo").innerText="1/2";break;case p.Sixteenth:i.addElement("Tremolo").innerText="1/4";break;case p.ThirtySecond:i.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&i.addElement("Chord").setCData(t.chordId),t.crescendo!==u.None&&(i.addElement("Hairpin").innerText=u[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 m.OnBeat:case m.BeforeBeat:i.addElement("GraceNotes").innerText=m[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 Ge.Up:i.addElement("TransposedPitchStemOrientation").innerText="Upward",i.addElement("UserTransposedPitchStemOrientation").innerText="Upward";break;case Ge.Down:i.addElement("TransposedPitchStemOrientation").innerText="Downward",i.addElement("UserTransposedPitchStemOrientation").innerText="Downward"}i.addElement("ConcertPitchStemOrientation").innerText="Undefined",t.slashed&&i.addElement("Slashed"),t.deadSlapped&&i.addElement("DeadSlapped"),t.notes.length>0&&(i.addElement("Notes").innerText=t.notes.map((e=>e.id)).join(" ")),t.golpe!==A.None&&(i.addElement("Golpe").innerText=A[t.golpe]),t.wahPedal!==R.None&&(i.addElement("Wah").innerText=R[t.wahPedal]),t.showTimer&&(i.addElement("Timer").innerText=(t.timer??0).toString()),this.writeBeatProperties(i,t),this.writeBeatXProperties(i,t),t.lyrics&&t.lyrics.length>0&&this.writeBeatLyrics(i,t.lyrics)}writeBeatLyrics(e,t){const s=e.addElement("Lyrics");for(const e of t){s.addElement("Line").setCData(e)}}writeBeatXProperties(e,t){const s=e.addElement("XProperties");switch(t.brushDuration>0&&this.writeSimpleXPropertyNode(s,"687935489","Int",t.brushDuration.toString()),t.beamingMode){case G.ForceSplitToNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","2");break;case G.ForceMergeWithNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","1");break;case G.ForceSplitOnSecondaryToNext:this.writeSimpleXPropertyNode(s,"1124204552","Int","1")}}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 E.Up:this.writeSimplePropertyNode(s,"PickStroke","Direction","Up");break;case E.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 w.Wide:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Wide");break;case w.Slight:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Slight")}if(t.isBarre)switch(this.writeSimplePropertyNode(s,"BarreFret","Fret",t.barreFret.toString()),t.barreShape){case V.Full:this.writeSimplePropertyNode(s,"BarreString","String","0");break;case V.Half:this.writeSimplePropertyNode(s,"BarreString","String","1")}if(t.rasgueado!=H.None){let e="";switch(t.rasgueado){case H.Ii:e="ii_1";break;case H.Mi:e="mi_1";break;case H.MiiTriplet:e="mii_1";break;case H.MiiAnapaest:e="mii_2";break;case H.PmpTriplet:e="pmp_1";break;case H.PmpAnapaest:e="pmp_2";break;case H.PeiTriplet:e="pei_1";break;case H.PeiAnapaest:e="pei_2";break;case H.PaiTriplet:e="pai_1";break;case H.PaiAnapaest:e="pai_2";break;case H.AmiTriplet:e="ami_1";break;case H.AmiAnapaest:e="ami_2";break;case H.Ppp:e="ppp_1";break;case H.Amii:e="amii_1";break;case H.Amip:e="amip_1";break;case H.Eami:e="eami_1";break;case H.Eamii:e="eamii_1";break;case H.Peami:e="peami_1"}this.writeSimplePropertyNode(s,"Rasgueado","Rasgueado",e)}}writeRhythm(e,t,s){const i=`${t.duration}_${t.dots}_${t.tupletNumerator}_${t.tupletDenominator}';`;let a;if(this._rhythmIdLookup.has(i))a=this._rhythmIdLookup.get(i);else{a=this._rhythmIdLookup.size.toString(),this._rhythmIdLookup.set(i,a);const e=s.addElement("Rhythm");if(e.attributes.set("id",a),t.hasTuplet){const s=e.addElement("PrimaryTuplet");s.attributes.set("num",t.tupletNumerator.toString()),s.attributes.set("den",t.tupletDenominator.toString())}t.dots>0&&e.addElement("AugmentationDot").attributes.set("count",t.dots.toString());let r="Quarter";switch(t.duration){case p.QuadrupleWhole:r="Long";break;case p.DoubleWhole:r="DoubleWhole";break;case p.Whole:r="Whole";break;case p.Half:r="Half";break;case p.Quarter:r="Quarter";break;case p.Eighth:r="Eighth";break;case p.Sixteenth:r="16th";break;case p.ThirtySecond:r="32nd";break;case p.SixtyFourth:r="64th";break;case p.OneHundredTwentyEighth:r="128th";break;case p.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 te((r.offset+n.offset)/2,(r.value+n.value)/2)}s.attributes.set("destinationOffset",this.toBendOffset(n.offset).toString()),s.attributes.set("destinationValue",this.toBendValue(n.value).toString()),s.attributes.set("middleOffset1",this.toBendOffset(i.offset).toString()),s.attributes.set("middleOffset2",this.toBendOffset(a.offset).toString()),s.attributes.set("middleValue",this.toBendValue(i.value).toString()),s.attributes.set("originOffset",this.toBendOffset(r.offset).toString()),s.attributes.set("originValue",this.toBendValue(r.value).toString())}writeScoreNode(e,t){const s=e.addElement("Score");s.addElement("Title").setCData(t.title),s.addElement("SubTitle").setCData(t.subTitle),s.addElement("Artist").setCData(t.artist),s.addElement("Album").setCData(t.album),s.addElement("Words").setCData(t.words),s.addElement("Music").setCData(t.music),s.addElement("WordsAndMusic").setCData(t.words===t.music?t.words:""),s.addElement("Copyright").setCData(t.copyright),s.addElement("Tabber").setCData(t.tab),s.addElement("Instructions").setCData(t.instructions),s.addElement("Notices").setCData(t.notices),s.addElement("FirstPageHeader").setCData(""),s.addElement("FirstPageFooter").setCData(""),s.addElement("PageHeader").setCData(""),s.addElement("PageFooter").setCData(""),s.addElement("ScoreSystemsDefaultLayout").setCData(t.defaultSystemsLayout.toString()),s.addElement("ScoreSystemsLayout").setCData(t.systemsLayout.join(" ")),s.addElement("ScoreZoomPolicy").innerText="Value",s.addElement("ScoreZoom").innerText="1",s.addElement("MultiVoice").innerText="1>"}writeMasterTrackNode(e,t){const s=e.addElement("MasterTrack");s.addElement("Tracks").innerText=t.tracks.map((e=>e.index)).join(" ");const i=s.addElement("Automations");if(t.masterBars.length>0&&t.masterBars[0].isAnacrusis&&s.addElement("Anacrusis"),0===t.masterBars[0].tempoAutomations.length){const e=i.addElement("Automation");e.addElement("Type").innerText="Tempo",e.addElement("Linear").innerText="false",e.addElement("Bar").innerText="0",e.addElement("Position").innerText="0",e.addElement("Visible").innerText="true",e.addElement("Value").innerText=`${t.tempo} 2`,t.tempoLabel&&(e.addElement("Text").innerText=t.tempoLabel)}for(const e of t.masterBars)for(const t of e.tempoAutomations){const s=i.addElement("Automation");s.addElement("Type").innerText="Tempo",s.addElement("Linear").innerText=t.isLinear?"true":"false",s.addElement("Bar").innerText=e.index.toString(),s.addElement("Position").innerText=t.ratioPosition.toString(),s.addElement("Visible").innerText="true",s.addElement("Value").innerText=`${t.value} 2`,t.text&&(s.addElement("Text").innerText=t.text)}}writeAudioTracksNode(e,t){e.addElement("AudioTracks")}writeTracksNode(e,t){const s=e.addElement("Tracks");for(const e of t.tracks)this.writeTrackNode(s,e)}writeTrackNode(e,t){const s=e.addElement("Track");s.attributes.set("id",t.index.toString()),s.addElement("Name").setCData(t.name),s.addElement("ShortName").setCData(t.shortName),s.addElement("Color").innerText=`${t.color.r} ${t.color.g} ${t.color.b}`,s.addElement("SystemsDefautLayout").innerText=t.defaultSystemsLayout.toString(),s.addElement("SystemsLayout").innerText=t.systemsLayout.join(" "),s.addElement("AutoBrush"),s.addElement("PalmMute").innerText="0",s.addElement("PlayingStyle").innerText=Y.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",s.addElement("UseOneChannelPerString"),s.addElement("IconId").innerText=Fl.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?Fl.DrumKitProgramInfo.icon:Fl.MidiProgramInfoLookup.has(e.program)?Fl.MidiProgramInfoLookup.get(e.program).icon:vl.SteelGuitar}writeSoundAndAutomation(e,t,s,i,a,r,n,o=0){const h=e.addElement("Sound");h.addElement("Name").setCData(s),h.addElement("Label").setCData(s),h.addElement("Path").setCData(i),h.addElement("Role").setCData(a);const l=h.addElement("MIDI");l.addElement("LSB").innerText="0",l.addElement("MSB").innerText="0",l.addElement("Program").innerText=n.toString();const d=t.addElement("Automation");d.addElement("Type").innerText="Sound",d.addElement("Linear").innerText="false",d.addElement("Bar").innerText=r.toString(),d.addElement("Position").innerText=o.toString(),d.addElement("Visible").innerText="true",d.addElement("Value").setCData(`${i};${s};${a}`)}writeSoundsAndAutomations(e,t){const s=e.addElement("Sounds"),i=e.addElement("Automations");if(t.staves.length>0&&t.staves[0].bars.length>0){const e=`Track_${t.index}_Initial`,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 d of h.beats){const h=d.getAutomation(a.Instrument),c=0===l.index&&0===d.index;if(h){const a=c?e:`ProgramChange_${d.id}`,u=c?r:`Midi/${h.value}`,p=c?n:"User";c||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),c&&(o=!0)}}}for(const e of t.staves)for(const t of e.bars)for(const e of t.sustainPedals)if(e.pedalType!==h.Hold){const s=i.addElement("Automation");switch(s.addElement("Type").innerText="SustainPedal",s.addElement("Linear").innerText="false",s.addElement("Bar").innerText=t.index.toString(),s.addElement("Position").innerText=e.ratioPosition.toString(),s.addElement("Visible").innerText="true",e.pedalType){case h.Down:s.addElement("Value").innerText="0 1";break;case h.Up:s.addElement("Value").innerText="0 3"}}}writeMidiConnectionNode(e,t){const s=e.addElement("MidiConnection");s.addElement("Port").innerText=t.playbackInfo.port.toString(),s.addElement("PrimaryChannel").innerText=t.playbackInfo.primaryChannel.toString(),s.addElement("SecondaryChannel").innerText=t.playbackInfo.secondaryChannel.toString(),s.addElement("ForeOneChannelPerString").innerText="false"}writeRseNode(e,t){const s=e.addElement("RSE").addElement("ChannelStrip");s.attributes.set("version","E56");s.addElement("Parameters").innerText=`0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1 0.5 ${t.playbackInfo.balance/16} ${t.playbackInfo.volume/16} 0.5 0.5 0.5`}writeStavesNode(e,t){const s=e.addElement("Staves");for(const e of t.staves)this.writeStaffNode(s,e)}writeStaffNode(e,t){const s=e.addElement("Staff").addElement("Properties");if(this.writeSimplePropertyNode(s,"CapoFret","Fret",t.capo.toString()),this.writeSimplePropertyNode(s,"FretCount","Fret","24"),t.tuning.length>0){const e=s.addElement("Property");switch(e.attributes.set("name","Tuning"),e.addElement("Pitches").innerText=t.tuning.slice().reverse().join(" "),e.addElement("Label").setCData(t.tuningName),e.addElement("LabelVisible").innerText=t.tuningName?"true":"false",e.addElement("Flat"),t.tuning.length){case 3:e.addElement("Instrument").innerText="Shamisen";break;case 4:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":42==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Cello":43==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Contrabass":40==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Violin":41==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Viola":e.addElement("Instrument").innerText="Bass";break;case 5:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":e.addElement("Instrument").innerText="Bass";break;case 6:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;case 7:t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;default:e.addElement("Instrument").innerText="Guitar"}}this.writeSimplePropertyNode(s,"PartialCapoFret","Fret","0"),this.writeSimplePropertyNode(s,"PartialCapoStringFlags","Bitset",t.tuning.map((e=>"0")).join("")),this.writeSimplePropertyNode(s,"TuningFlat","Enable",null),this.writeDiagramCollection(s,t,"DiagramCollection"),this.writeDiagramCollection(s,t,"DiagramWorkingSet")}writeDiagramCollection(e,t,s){const i=e.addElement("Property");i.attributes.set("name",s);const a=i.addElement("Items"),r=t.chords;if(r)for(const[e,t]of r){const s=a.addElement("Item");s.attributes.set("id",e),s.attributes.set("name",t.name);const i=s.addElement("Diagram");i.attributes.set("stringCount",t.strings.length.toString()),i.attributes.set("fretCount","5"),i.attributes.set("baseFret",(t.firstFret-1).toString()),i.attributes.set("barStates",t.strings.map((e=>"1")).join(" "));const r=[],n=new Map;for(let e=0;e<t.strings.length;e++){let s=t.strings[e];if(-1!==s){const a=i.addElement("Fret"),o=t.strings.length-1-e;a.attributes.set("string",o.toString()),a.attributes.set("fret",(s-t.firstFret+1).toString()),n.has(s)||(n.set(s,[]),r.push(s)),n.get(s).push(o)}}r.sort();const o=i.addElement("Fingering");if(t.barreFrets.length>0){const e=[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 d=i.addElement("Property");d.attributes.set("name","ShowFingering"),d.attributes.set("type","bool"),d.attributes.set("value",t.showFingering?"true":"false");const c=i.addElement("Chord"),u=c.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=c.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=c.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const m=c.addElement("Degree");m.attributes.set("interval","Fifth"),m.attributes.set("alteration","Perfect"),m.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,s,i){const a=e.addElement("Property");a.attributes.set("name",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeSimpleXPropertyNode(e,t,s,i){const a=e.addElement("XProperty");a.attributes.set("id",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeLyricsNode(e,t){const s=e.addElement("Lyrics");s.attributes.set("dispatched","true");let i=[];for(const e of t.staves[0].bars)for(const t of e.voices)if(!t.isEmpty)for(const s of t.beats)if(s.lyrics)for(let t=0;t<s.lyrics.length;t++){for(;t>=i.length;){const t=new ke;t.startBar=e.index,t.text="[Empty]",i.push(t)}const a=i[t];a.text="[Empty]"==a.text?s.lyrics[t]:a.text+" "+s.lyrics[t].split(" ").join("+")}for(let e=0;e<i.length;e++){const t=s.addElement("Line");t.addElement("Text").setCData(i[e].text),t.addElement("Offset").innerText=i[e].startBar.toString()}}writeTransposeNode(e,t){const s=e.addElement("Transpose"),i=Math.floor(t.staves[0].displayTranspositionPitch/12),a=t.staves[0].displayTranspositionPitch-12*i;s.addElement("Chromatic").innerText=a.toString(),s.addElement("Octave").innerText=i.toString()}writeInstrumentSetNode(e,t){const s=e.addElement("InstrumentSet"),i=t.staves[0];if(s.addElement("LineCount").innerText=i.standardNotationLineCount.toString(),t.percussionArticulations.length>0||i.isPercussion){const e=t.percussionArticulations.length>0?t.percussionArticulations:Array.from(ue.instrumentArticulations.values());s.addElement("Name").innerText=Fl.DrumKitProgramInfo.instrumentSetName,s.addElement("Type").innerText=Fl.DrumKitProgramInfo.instrumentSetType;let i="",r=new us,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 L.Top:e.addElement("TechniquePlacement").innerText="below";break;case L.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case L.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=Fl.MidiProgramInfoLookup.has(t.playbackInfo.program)?Fl.MidiProgramInfoLookup.get(t.playbackInfo.program):Fl.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===F.None)return"";let t=F[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=P[t.keySignatureType],i.addElement("Sharps").innerText="Sharps",s.addElement("Time").innerText=`${t.timeSignatureNumerator}/${t.timeSignatureDenominator}`,t.isFreeTime&&s.addElement("FreeTime");let a=[];for(const e of t.score.tracks)for(const s of e.staves)a.push(s.bars[t.index].id.toString());if(s.addElement("Bars").innerText=a.join(" "),t.isDoubleBar&&s.addElement("DoubleBar"),t.isSectionStart){const e=s.addElement("Section");e.addElement("Letter").setCData(t.section.marker),e.addElement("Text").setCData(t.section.text)}if(t.isRepeatStart||t.isRepeatEnd){const e=s.addElement("Repeat");e.attributes.set("start",t.isRepeatStart?"true":"false"),e.attributes.set("end",t.isRepeatEnd?"true":"false"),t.isRepeatEnd&&e.attributes.set("count",t.repeatCount.toString())}if(t.alternateEndings>0){let e=t.alternateEndings;const i=[];let a=0;for(;e>0;)1==(e>>a&1)&&(i.push(a+1),e&=~(1<<a)),a++;s.addElement("AlternateEndings").innerText=i.join(" ")}if(t.tripletFeel!==C.NoTripletFeel&&(s.addElement("TripletFeel").innerText=C[t.tripletFeel]),t.directions&&t.directions.size>0){const e=s.addElement("Directions");for(const s of t.directions)switch(s){case Ve.TargetFine:e.addElement("Target").innerText="Fine";break;case Ve.TargetSegno:e.addElement("Target").innerText="Segno";break;case Ve.TargetSegnoSegno:e.addElement("Target").innerText="SegnoSegno";break;case Ve.TargetCoda:e.addElement("Target").innerText="Coda";break;case Ve.TargetDoubleCoda:e.addElement("Target").innerText="DoubleCoda";break;case Ve.JumpDaCapo:e.addElement("Jump").innerText="DaCapo";break;case Ve.JumpDaCapoAlCoda:e.addElement("Jump").innerText="DaCapoAlCoda";break;case Ve.JumpDaCapoAlDoubleCoda:e.addElement("Jump").innerText="DaCapoAlDoubleCoda";break;case Ve.JumpDaCapoAlFine:e.addElement("Jump").innerText="DaCapoAlFine";break;case Ve.JumpDalSegno:e.addElement("Jump").innerText="DaSegno";break;case Ve.JumpDalSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoAlCoda";break;case Ve.JumpDalSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoAlDoubleCoda";break;case Ve.JumpDalSegnoAlFine:e.addElement("Jump").innerText="DaSegnoAlFine";break;case Ve.JumpDalSegnoSegno:e.addElement("Jump").innerText="DaSegnoSegno";break;case Ve.JumpDalSegnoSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlCoda";break;case Ve.JumpDalSegnoSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlDoubleCoda";break;case Ve.JumpDalSegnoSegnoAlFine:e.addElement("Jump").innerText="DaSegnoSegnoAlFine";break;case Ve.JumpDaCoda:e.addElement("Jump").innerText="DaCoda";break;case Ve.JumpDaDoubleCoda:e.addElement("Jump").innerText="DaDoubleCoda"}}this.writeFermatas(s,t)}writeFermatas(e,t){const s=t.fermata?.size??0;if(0!==s&&s>0){const s=e.addElement("Fermatas");for(const[e,i]of t.fermata)this.writeFermata(s,e,i)}}writeFermata(e,t,s){let i=-1,a=1;if(t>0)for(;a<10&&(i=t/ee.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=He[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(" ")}}Fl.MidiProgramInfoLookup=new Map([[0,new El(vl.Piano,"Acoustic Piano")],[1,new El(vl.Piano,"Acoustic Piano")],[2,new El(vl.Piano,"Electric Piano")],[3,new El(vl.Piano,"Acoustic Piano")],[4,new El(vl.Piano,"Electric Piano")],[5,new El(vl.Piano,"Electric Piano")],[6,new El(vl.Piano,"Harpsichord")],[7,new El(vl.Piano,"Harpsichord")],[8,new El(vl.PitchedIdiophone,"Celesta")],[9,new El(vl.PitchedIdiophone,"Vibraphone")],[10,new El(vl.PitchedIdiophone,"Vibraphone")],[11,new El(vl.PitchedIdiophone,"Vibraphone")],[12,new El(vl.PitchedIdiophone,"Xylophone")],[13,new El(vl.PitchedIdiophone,"Xylophone")],[14,new El(vl.PitchedIdiophone,"Vibraphone")],[15,new El(vl.Banjo,"Banjo")],[16,new El(vl.Piano,"Electric Organ")],[17,new El(vl.Piano,"Electric Organ")],[18,new El(vl.Piano,"Electric Organ")],[19,new El(vl.Piano,"Electric Organ")],[20,new El(vl.Piano,"Electric Organ")],[21,new El(vl.Piano,"Electric Organ")],[22,new El(vl.Woodwind,"Recorder")],[23,new El(vl.Piano,"Electric Organ")],[24,new El(vl.ClassicalGuitar,"Nylon Guitar")],[25,new El(vl.SteelGuitar,"Steel Guitar")],[26,new El(vl.SteelGuitar,"Electric Guitar")],[27,new El(vl.ElectricGuitar,"Electric Guitar")],[28,new El(vl.ElectricGuitar,"Electric Guitar")],[29,new El(vl.ElectricGuitar,"Electric Guitar")],[30,new El(vl.SteelGuitar,"Electric Guitar")],[31,new El(vl.SteelGuitar,"Electric Guitar")],[32,new El(vl.Bass,"Acoustic Bass")],[33,new El(vl.Bass,"Electric Bass")],[34,new El(vl.Bass,"Electric Bass")],[35,new El(vl.Bass,"Acoustic Bass")],[36,new El(vl.Bass,"Electric Bass")],[37,new El(vl.Bass,"Electric Bass")],[38,new El(vl.Synth,"Synth Bass")],[39,new El(vl.Synth,"Synth Bass")],[40,new El(vl.Strings,"Violin")],[41,new El(vl.Strings,"Viola")],[42,new El(vl.Strings,"Cello")],[43,new El(vl.Strings,"Contrabass")],[44,new El(vl.Strings,"Violin")],[45,new El(vl.Strings,"Violin")],[46,new El(vl.Piano,"Harp")],[47,new El(vl.Membraphone,"Timpani")],[48,new El(vl.Strings,"Violin")],[49,new El(vl.Strings,"Violin")],[50,new El(vl.Strings,"Violin")],[51,new El(vl.Strings,"Violin")],[52,new El(vl.Vocal,"Voice")],[53,new El(vl.Vocal,"Voice")],[54,new El(vl.Vocal,"Voice")],[55,new El(vl.Synth,"Pad Synthesizer")],[56,new El(vl.Brass,"Trumpet")],[57,new El(vl.Brass,"Trombone")],[58,new El(vl.Brass,"Tuba")],[59,new El(vl.Brass,"Trumpet")],[60,new El(vl.Brass,"French Horn")],[61,new El(vl.Brass,"Trumpet")],[62,new El(vl.Brass,"Trumpet")],[63,new El(vl.Brass,"Trumpet")],[64,new El(vl.Reed,"Saxophone")],[65,new El(vl.Reed,"Saxophone")],[66,new El(vl.Reed,"Saxophone")],[67,new El(vl.Reed,"Saxophone")],[68,new El(vl.Reed,"Oboe")],[69,new El(vl.Reed,"English Horn")],[70,new El(vl.Reed,"Bassoon")],[71,new El(vl.Reed,"Clarinet")],[72,new El(vl.Reed,"Piccolo")],[73,new El(vl.Woodwind,"Flute")],[74,new El(vl.Woodwind,"Recorder")],[75,new El(vl.Woodwind,"Flute")],[76,new El(vl.Woodwind,"Recorder")],[77,new El(vl.Woodwind,"Flute")],[78,new El(vl.Woodwind,"Recorder")],[79,new El(vl.Woodwind,"Flute")],[80,new El(vl.Synth,"Lead Synthesizer")],[81,new El(vl.Synth,"Lead Synthesizer")],[82,new El(vl.Synth,"Lead Synthesizer")],[83,new El(vl.Synth,"Lead Synthesizer")],[84,new El(vl.Synth,"Lead Synthesizer")],[85,new El(vl.Synth,"Lead Synthesizer")],[86,new El(vl.Synth,"Lead Synthesizer")],[87,new El(vl.Synth,"Lead Synthesizer")],[88,new El(vl.Synth,"Pad Synthesizer")],[89,new El(vl.Synth,"Pad Synthesizer")],[90,new El(vl.Synth,"Pad Synthesizer")],[91,new El(vl.Synth,"Pad Synthesizer")],[92,new El(vl.Synth,"Pad Synthesizer")],[93,new El(vl.Synth,"Pad Synthesizer")],[94,new El(vl.Synth,"Pad Synthesizer")],[95,new El(vl.Synth,"Pad Synthesizer")],[96,new El(vl.Fx,"Pad Synthesizer")],[97,new El(vl.Fx,"Pad Synthesizer")],[98,new El(vl.Fx,"Pad Synthesizer")],[99,new El(vl.Fx,"Pad Synthesizer")],[100,new El(vl.Fx,"Lead Synthesizer")],[101,new El(vl.Fx,"Lead Synthesizer")],[102,new El(vl.Fx,"Lead Synthesizer")],[103,new El(vl.Fx,"Trumpet")],[104,new El(vl.ElectricGuitar,"Banjo")],[105,new El(vl.Banjo,"Banjo")],[106,new El(vl.Ukulele,"Ukulele")],[107,new El(vl.Banjo,"Banjo")],[108,new El(vl.PitchedIdiophone,"Xylophone")],[109,new El(vl.Reed,"Bassoon")],[110,new El(vl.Strings,"Violin")],[111,new El(vl.Woodwind,"Flute")],[112,new El(vl.PitchedIdiophone,"Xylophone")],[113,new El(vl.Idiophone,"Celesta")],[114,new El(vl.PitchedIdiophone,"Vibraphone")],[115,new El(vl.Idiophone,"Xylophone")],[116,new El(vl.Membraphone,"Xylophone")],[117,new El(vl.Membraphone,"Xylophone")],[118,new El(vl.Membraphone,"Xylophone")],[119,new El(vl.Idiophone,"Celesta")],[120,new El(vl.Fx,"Steel Guitar")],[121,new El(vl.Fx,"Recorder")],[122,new El(vl.Fx,"Recorder")],[123,new El(vl.Fx,"Recorder")],[124,new El(vl.Fx,"Recorder")],[125,new El(vl.Fx,"Recorder")],[126,new El(vl.Fx,"Recorder")],[127,new El(vl.Fx,"Timpani")]]),Fl.DrumKitProgramInfo=new El(vl.PercussionKit,"Drums","drumKit");class Dl{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=Dl.CrcInit,this.reset()}update(e,t,s){for(let i=0;i<s;i++)this._checkValue=Dl.Crc32Lookup[255&(this._checkValue^e[t+i])]^this._checkValue>>>8}reset(){this._checkValue=Dl.CrcInit}}Dl.Crc32Lookup=Dl.buildCrc32Lookup(),Dl.CrcInit=4294967295;class Ll{}Ll.MAX_WBITS=15,Ll.WSIZE=1<<Ll.MAX_WBITS,Ll.WMASK=Ll.WSIZE-1,Ll.MIN_MATCH=3,Ll.MAX_MATCH=258,Ll.DEFAULT_MEM_LEVEL=8,Ll.PENDING_BUF_SIZE=1<<Ll.DEFAULT_MEM_LEVEL+8,Ll.HASH_BITS=Ll.DEFAULT_MEM_LEVEL+7,Ll.HASH_SIZE=1<<Ll.HASH_BITS,Ll.HASH_SHIFT=(Ll.HASH_BITS+Ll.MIN_MATCH-1)/Ll.MIN_MATCH,Ll.HASH_MASK=Ll.HASH_SIZE-1,Ll.MIN_LOOKAHEAD=Ll.MAX_MATCH+Ll.MIN_MATCH+1,Ll.MAX_DIST=Ll.WSIZE-Ll.MIN_LOOKAHEAD;class Ml{constructor(e,t,s,i){this.length=null,this.numCodes=0,this.codes=null,this.huffman=e,this.minNumCodes=s,this.maxLength=i,this.freqs=new Int16Array(t),this.bitLengthCounts=new Int32Array(i)}reset(){for(let e=0;e<this.freqs.length;e++)this.freqs[e]=0;this.codes=null,this.length=null}buildTree(){let e=this.freqs.length,t=new Int32Array(e),s=0,i=0;for(let a=0;a<e;a++){let e=this.freqs[a];if(0!==e){let r=s++;for(;r>0;){let s=Math.floor((r-1)/2);if(!(this.freqs[t[s]]>e))break;t[r]=t[s],r=s}t[r]=a,i=a}}for(;s<2;){let e=i<2?++i:0;t[s++]=e}this.numCodes=Math.max(i+1,this.minNumCodes);let a=s,r=new Int32Array(4*s-2),n=new Int32Array(2*s-1),o=a;for(let e=0;e<s;e++){let s=t[e];r[2*e]=s,r[2*e+1]=-1,n[e]=this.freqs[s]<<8,t[e]=e}do{let e=t[0],i=t[--s],a=0,h=1;for(;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*h+1;let l=n[i];for(;h=a,a>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i;let d=t[0];i=o++,r[2*i]=e,r[2*i+1]=d;let c=Math.min(255&n[e],255&n[d]);for(l=n[e]+n[d]-c+1,n[i]=l,a=0,h=1;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*a+1;for(;h=a,h>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i}while(s>1);this.buildLength(r)}buildLength(e){this.length=new Uint8Array(this.freqs.length);let t=Math.floor(e.length/2),s=Math.floor((t+1)/2),i=0;for(let e=0;e<this.maxLength;e++)this.bitLengthCounts[e]=0;let a=new Int32Array(t);a[t-1]=0;for(let s=t-1;s>=0;s--)if(-1!=e[2*s+1]){let t=a[s]+1;t>this.maxLength&&(t=this.maxLength,i++),a[e[2*s]]=t,a[e[2*s+1]]=t}else{let t=a[s];this.bitLengthCounts[t-1]++,this.length[e[2*s]]=a[s]}if(0==i)return;let r=this.maxLength-1;do{for(;0==this.bitLengthCounts[--r];);do{this.bitLengthCounts[r]--,this.bitLengthCounts[++r]++,i-=1<<this.maxLength-1-r}while(i>0&&r<this.maxLength-1)}while(i>0);this.bitLengthCounts[this.maxLength-1]+=i,this.bitLengthCounts[this.maxLength-2]-=i;let n=2*s;for(let t=this.maxLength;0!=t;t--){let s=this.bitLengthCounts[t-1];for(;s>0;){let i=2*e[n++];-1==e[i+1]&&(this.length[e[i]]=t,s--)}}}getEncodedLength(){let e=0;for(let t=0;t<this.freqs.length;t++)e+=this.freqs[t]*this.length[t];return e}calcBLFreq(e){let t,s,i,a=-1,r=0;for(;r<this.numCodes;){i=1;let n=this.length[r];for(0==n?(t=138,s=3):(t=6,s=3,a!=n&&(e.freqs[n]++,i=0)),a=n,r++;r<this.numCodes&&a==this.length[r]&&(r++,!(++i>=t)););i<s?e.freqs[a]+=i:0!=a?e.freqs[Ml.Repeat3To6]++:i<=10?e.freqs[Ml.Repeat3To10]++:e.freqs[Ml.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]=Il.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(Ml.Repeat3To6),this.huffman.pending.writeBits(i-3,2)):i<=10?(e.writeSymbol(Ml.Repeat3To10),this.huffman.pending.writeBits(i-3,3)):(e.writeSymbol(Ml.Repeat11To138),this.huffman.pending.writeBits(i-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}Ml.Repeat3To6=16,Ml.Repeat3To10=17,Ml.Repeat11To138=18;class Il{static staticInit(){let e=0;for(;e<144;)Il.staticLCodes[e]=Il.bitReverse(48+e<<8),Il.staticLLength[e++]=8;for(;e<256;)Il.staticLCodes[e]=Il.bitReverse(256+e<<7),Il.staticLLength[e++]=9;for(;e<280;)Il.staticLCodes[e]=Il.bitReverse(-256+e<<9),Il.staticLLength[e++]=7;for(;e<Il.LITERAL_NUM;)Il.staticLCodes[e]=Il.bitReverse(-88+e<<8),Il.staticLLength[e++]=8;for(e=0;e<Il.DIST_NUM;e++)Il.staticDCodes[e]=Il.bitReverse(e<<11),Il.staticDLength[e]=5}static bitReverse(e){return Il.bit4Reverse[15&e]<<12|Il.bit4Reverse[e>>4&15]<<8|Il.bit4Reverse[e>>8&15]<<4|Il.bit4Reverse[e>>12]}constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new Ml(this,Il.LITERAL_NUM,257,15),this.distTree=new Ml(this,Il.DIST_NUM,1,15),this.blTree=new Ml(this,Il.BITLEN_NUM,4,7),this.d_buf=new Int16Array(Il.BUFSIZE),this.l_buf=new Uint8Array(Il.BUFSIZE)}isFull(){return this.last_lit>=Il.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((Il.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[Il.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[Il.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<Il.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*Il.staticLLength[e];for(let e=0;e<Il.DIST_NUM;e++)n+=this.distTree.freqs[e]*Il.staticDLength[e];r>=n&&(r=n),t>=0&&s+4<r>>3?this.flushStoredBlock(e,t,s,i):r==n?(this.pending.writeBits((Il.STATIC_TREES<<1)+(i?1:0),3),this.literalTree.setStaticCodes(Il.staticLCodes,Il.staticLLength),this.distTree.setStaticCodes(Il.staticDCodes,Il.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((Il.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[Il.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=Il.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=Il.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(Il.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;let s=Il.Lcode(t-3);this.literalTree.freqs[s]++,s>=265&&s<285&&(this.extra_bits+=Math.floor((s-261)/4));let i=Il.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}}Il.BUFSIZE=1<<Ll.DEFAULT_MEM_LEVEL+6,Il.LITERAL_NUM=286,Il.STORED_BLOCK=0,Il.STATIC_TREES=1,Il.DYN_TREES=2,Il.DIST_NUM=30,Il.staticLCodes=new Int16Array(Il.LITERAL_NUM),Il.staticLLength=new Uint8Array(Il.LITERAL_NUM),Il.staticDCodes=new Int16Array(Il.DIST_NUM),Il.staticDLength=new Uint8Array(Il.DIST_NUM),Il.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Il.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),Il.BITLEN_NUM=19,Il.EOF_SYMBOL=256,Il.staticInit();class Al{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 Il(e),this.inputCrc=new Dl,this.window=new Uint8Array(2*Ll.WSIZE),this.head=new Int16Array(Ll.HASH_SIZE),this.prev=new Int16Array(Ll.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=Ll.MIN_MATCH-1;for(let e=0;e<Ll.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<Ll.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<Ll.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<Ll.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=Ll.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*Ll.WSIZE-Ll.MIN_LOOKAHEAD&&this.slideWindow();let e=this.matchStart,s=this.matchLen;if(this.lookahead>=Ll.MIN_MATCH){let e=this.insertString();0!=e&&this.strstart-e<=Ll.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen==Ll.MIN_MATCH&&this.strstart-this.matchStart>Al.TooFar&&(this.matchLen=Ll.MIN_MATCH-1)}if(s>=Ll.MIN_MATCH&&this.matchLen<=s){this.huffman.tallyDist(this.strstart-1-e,s),s-=2;do{this.strstart++,this.lookahead--,this.lookahead>=Ll.MIN_MATCH&&this.insertString()}while(--s>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=Ll.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(Ll.MAX_MATCH,this.lookahead)-1,a=Math.max(s-Ll.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,Ll.MIN_MATCH-1),s+this.matchLen>i)return!1;let l=r[s+this.matchLen-1],d=r[s+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,s=this.strstart,r[t+this.matchLen]==d&&r[t+this.matchLen-1]==l&&r[t]==r[s]&&r[++t]==r[++s]){switch((i-s)%8){case 1:if(r[++s]==r[++t])break;break;case 2:if(r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 3:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 4:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 5:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 6:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 7:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break}if(r[s]==r[t])do{if(s==i){++s,++t;break}}while(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]);if(s-this.strstart>this.matchLen){if(this.matchStart=e,this.matchLen=s-this.strstart,this.matchLen>=h)break;l=r[s-1],d=r[s]}e=65535&n[e&Ll.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=Ll.MIN_MATCH}insertString(){let e,t=(this.insertHashIndex<<Ll.HASH_SHIFT^this.window[this.strstart+(Ll.MIN_MATCH-1)])&Ll.HASH_MASK;return e=this.head[t],this.prev[this.strstart&Ll.WMASK]=e,this.head[t]=this.strstart,this.insertHashIndex=t,65535&e}fillWindow(){if(this.strstart>=Ll.WSIZE+Ll.MAX_DIST&&this.slideWindow(),this.lookahead<Ll.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*Ll.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>=Ll.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(Ll.WSIZE,Ll.WSIZE+Ll.WSIZE),0),this.matchStart-=Ll.WSIZE,this.strstart-=Ll.WSIZE,this.blockStart-=Ll.WSIZE;for(let e=0;e<Ll.HASH_SIZE;++e){let t=65535&this.head[e];this.head[e]=t>=Ll.WSIZE?t-Ll.WSIZE:0}for(let e=0;e<Ll.WSIZE;e++){let t=65535&this.prev[e];this.prev[e]=t>=Ll.WSIZE?t-Ll.WSIZE:0}}}Al.TooFar=4096;class Ol{get isFlushed(){return 0===this._end}constructor(e){this._start=0,this._end=0,this._bits=0,this.bitCount=0,this._buffer=new Uint8Array(e)}reset(){this._start=0,this._end=0,this.bitCount=0}writeShortMSB(e){this._buffer[this._end++]=e>>8&255,this._buffer[this._end++]=255&e}writeShort(e){this._buffer[this._end++]=e,this._buffer[this._end++]=e>>8}writeBlock(e,t,s){this._buffer.set(e.subarray(t,t+s),this._end),this._end+=s}flush(e,t,s){return this.bitCount>=8&&(this._buffer[this._end++]=255&this._bits,this._bits>>=8,this.bitCount-=8),s>this._end-this._start?(s=this._end-this._start,e.set(this._buffer.subarray(this._start,this._start+s),t),this._start=0,this._end=0):(e.set(this._buffer.subarray(this._start,this._start+s),t),this._start+=s),s}writeBits(e,t){this._bits|=e<<this.bitCount,this.bitCount+=t,this.bitCount>=16&&(this._buffer[this._end++]=255&this._bits,this._buffer[this._end++]=this._bits>>8&255,this._bits>>=16,this.bitCount-=16)}alignToByte(){this.bitCount>0&&(this._buffer[this._end++]=255&this._bits,this.bitCount>8&&(this._buffer[this._end++]=this._bits>>8&255)),this._bits=0,this.bitCount=0}}class Rl{get inputCrc(){return this._engine.inputCrc.value}constructor(){this._state=0,this._pending=new Ol(Ll.PENDING_BUF_SIZE),this._engine=new Al(this._pending),this.reset()}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state==Rl.FinishedState&&this._pending.isFlushed}reset(){this._state=Rl.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==Rl.FinishedState)break;if(!this._engine.deflate(!!(this._state&Rl.IsFlushing),!!(this._state&Rl.IsFinishing)))switch(this._state){case Rl.BusyState:return i-s;case Rl.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=Rl.BusyState;break;case Rl.FinishingState:this._pending.alignToByte(),this._state=Rl.FinishedState}}return i-s}finish(){this._state|=Rl.IsFlushing|Rl.IsFinishing}}Rl.IsFlushing=4,Rl.IsFinishing=8,Rl.BusyState=16,Rl.FlushingState=20,Rl.FinishingState=28,Rl.FinishedState=30;class Vl{constructor(e,t,s,i,a){this.entry=e,this.crc32=t,this.localHeaderOffset=s,this.compressionMode=i,this.compressedSize=a}}class Hl{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new Rl,this._data=e}writeEntry(e){const t=qs.CompressionMethodDeflate,s=Oe.empty(),i=this.compress(s,e.data,t),a=s.toArray(),r=new Vl(e,i,this._data.bytesWritten,t,s.length);this._centralDirectoryHeaders.push(r),Ae.writeInt32LE(this._data,qs.LocalFileHeaderSignature),Ae.writeUInt16LE(this._data,10),Ae.writeUInt16LE(this._data,2048),Ae.writeUInt16LE(this._data,t),Ae.writeInt16LE(this._data,0),Ae.writeInt16LE(this._data,0),Ae.writeInt32LE(this._data,i),Ae.writeInt32LE(this._data,a.length),Ae.writeInt32LE(this._data,e.data.length),Ae.writeInt16LE(this._data,e.fullName.length),Ae.writeInt16LE(this._data,0);const n=Ae.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,s){if(s!=qs.CompressionMethodDeflate){const s=new Dl;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){Ae.writeInt32LE(this._data,qs.EndOfCentralDirSignature),Ae.writeInt16LE(this._data,0),Ae.writeInt16LE(this._data,0),Ae.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Ae.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Ae.writeInt32LE(this._data,t-e),Ae.writeInt32LE(this._data,e),Ae.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){Ae.writeInt32LE(this._data,qs.CentralFileHeaderSignature),Ae.writeUInt16LE(this._data,10),Ae.writeUInt16LE(this._data,10),Ae.writeUInt16LE(this._data,2048),Ae.writeUInt16LE(this._data,e.compressionMode),Ae.writeInt16LE(this._data,0),Ae.writeInt16LE(this._data,0),Ae.writeInt32LE(this._data,e.crc32),Ae.writeInt32LE(this._data,e.compressedSize),Ae.writeInt32LE(this._data,e.entry.data.length),Ae.writeInt16LE(this._data,e.entry.fullName.length),Ae.writeInt16LE(this._data,0),Ae.writeInt16LE(this._data,0),Ae.writeInt16LE(this._data,0),Ae.writeInt16LE(this._data,0),Ae.writeInt32LE(this._data,0),Ae.writeInt32LE(this._data,e.localHeaderOffset);const t=Ae.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}var Gl=Object.freeze({__proto__:null,Gp7Exporter:class extends Cl{get name(){return"Guitar Pro 7"}constructor(){super()}writeScore(e){re.debug(this.name,"Writing data entries");const t=(new Fl).writeXml(e),s=cs.writeForScore(e),i=Bs.writeForScore(e),a=$s.writeForScore(e);re.debug(this.name,"Writing ZIP entries");let r=new Hl(this.data);r.writeEntry(new qs("VERSION",Ae.stringToBytes("7.0"))),r.writeEntry(new qs("Content/",new Uint8Array(0))),r.writeEntry(new qs("Content/BinaryStylesheet",s)),r.writeEntry(new qs("Content/PartConfiguration",i)),r.writeEntry(new qs("Content/LayoutConfiguration",a)),r.writeEntry(new qs("Content/score.gpif",Ae.stringToBytes(t))),r.end()}},ScoreExporter:Cl}),Wl=Object.freeze({__proto__:null,AlphaSynthMidiFileHandler:Ma,AlphaTabMetronomeEvent:ct,AlphaTabRestEvent:ut,BeatTickLookup:Ra,ControlChangeEvent:ft,get ControllerType(){return Os},EndOfTrackEvent:wt,MasterBarTickLookup:Ha,MidiEvent:ht,get MidiEventType(){return je},MidiFile:ot,get MidiFileFormat(){return qe},MidiFileGenerator:Ja,MidiTickLookup:Wa,MidiTickLookupFindBeatResult:Ga,NoteBendEvent:_t,NoteEvent:pt,NoteOffEvent:mt,NoteOnEvent:gt,PitchBendEvent:St,ProgramChangeEvent:yt,TempoChangeEvent:bt,TimeSignatureEvent:lt}),zl=Object.freeze({__proto__:null,BarBounds:xa,BeatBounds:Na,Bounds:ds,BoundsLookup:Ea,MasterBarBounds:va,NoteBounds:Pa,RenderFinishedEventArgs:Ta,ScoreRenderer:Fa,StaffSystemBounds:Ca}),Ul=Object.freeze({__proto__:null,ActiveBeatsChangedEventArgs:tr,AlphaSynth:Sa,AlphaSynthAudioWorkletOutput:yr,AlphaSynthScriptProcessorOutput:cr,AlphaSynthWebAudioOutputBase:dr,AlphaSynthWebWorkerApi:pr,CircularSampleBuffer:lr,MidiEventsPlayedEventArgs:ya,PlaybackRange:Ya,PlaybackRangeChangedEventArgs:ba,get PlayerState(){return Es},PlayerStateChangedEventArgs:di,PositionChangedEventArgs:ci}),Xl=Object.freeze({__proto__:null});export{_r as AlphaTabApi,j as AlphaTabError,s as AlphaTabErrorType,ae as ConsoleLogger,xl as CoreSettings,kt as DisplaySettings,Tl as Environment,ar as FileLoadError,k as FingeringMode,Pe as FormatError,Tt as ImporterSettings,Bl as LayoutEngineFactory,e as LayoutMode,N as LogLevel,re as Logger,x as NotationElement,T as NotationMode,se as NotationSettings,$e as PlayerOutputMode,vt as PlayerSettings,ur as ProgressEventArgs,kl as RenderEngineFactory,Bt as RenderingResources,er as ResizeEventArgs,Qe as ScrollMode,Ot as Settings,t as StaveProfile,Ke as SystemsLayoutMode,B as TabRhythmMode,xt as VibratoPlaybackSettings,Rs as WebPlatform,Gl as exporter,Pl as importer,Xl as json,Nl as meta,Wl as midi,ns as model,Jn as platform,zl as rendering,Ul as synth};
|
|
1
|
+
var e,t,s,i,a,r,n,o,h,l,d,c,u,p,g,m,f,y,b,S,_,w,B,k,T,x,N,v,P,C,E,F,D,L,M,I,A,O,R,V,H,G,W,z,U,X,J;!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 Y{static getValue(e){return Y._values||(Y._values=new Map),e=e.toLowerCase().replaceAll(" ",""),Y._values.has(e)?Y._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}}Y._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 q{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 j extends Error{constructor(e,t="",s){super(t??"",{cause:s}),this.type=e,Object.setPrototypeOf(this,j.prototype)}}class K extends j{constructor(e=null,t){super(s.Format,e??"Unsupported format",t),Object.setPrototypeOf(this,K.prototype)}}!function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy",e[e.Tenuto=3]="Tenuto"}(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 Q{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 Q;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 Q;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={})),function(e){e[e.Down=0]="Down",e[e.Hold=1]="Hold",e[e.Up=2]="Up"}(h||(h={}));class ${constructor(){this.ratioPosition=0,this.pedalType=h.Down,this.nextPedalMarker=null,this.previousPedalMarker=null}}class Z{constructor(){this.id=Z._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,this.sustainPedals=[]}get masterBar(){return this.staff.track.score.masterBars[this.index]}get isEmpty(){for(let e=0,t=this.voices.length;e<t;e++)if(!this.voices[e].isEmpty)return!1;return!0}addVoice(e){e.bar=this,e.index=this.voices.length,this.voices.push(e)}finish(e,t=null){this.isMultiVoice=!1;for(let s=0,i=this.voices.length;s<i;s++){let i=this.voices[s];i.finish(e,t),s>0&&!i.isEmpty&&(this.isMultiVoice=!0)}if(this.sustainPedals.length>0){let e=null;this.previousBar&&this.previousBar.sustainPedals.length>0&&(e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1]);for(const t of this.sustainPedals)e&&e.pedalType!==h.Up&&(e.nextPedalMarker=t,t.previousPedalMarker=e),t.bar=this,e=t}else if(this.previousBar&&this.previousBar.sustainPedals.length>0){const e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1];if(e.pedalType!==h.Up){const t=new $;t.ratioPosition=0,t.bar=this,t.pedalType=h.Hold,this.sustainPedals.push(t),e.nextPedalMarker=t,t.previousPedalMarker=e}}}calculateDuration(){let e=0;for(let t of this.voices){let s=t.calculateDuration();s>e&&(e=s)}return e}}Z._globalBarId=0;class ee{static ticksToMillis(e,t){return e*(6e4/(t*ee.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*ee.QuarterTime))|0}static toTicks(e){return ee.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),ee.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 ee.MinVelocity+e*ee.VelocityIncrement}}ee.QuarterTime=960,ee.MinVelocity=15,ee.VelocityIncrement=16;class te{constructor(e=0,t=0){this.offset=e,this.value=t}}te.MaxPosition=60,te.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(l||(l={})),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"}(d||(d={})),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"}(u||(u={})),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"}(p||(p={})),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"}(g||(g={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(m||(m={})),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"}(y||(y={})),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"}(b||(b={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(S||(S={})),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"}(_||(_={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(w||(w={})),function(e){e[e.Hidden=0]="Hidden",e[e.ShowWithBeams=1]="ShowWithBeams",e[e.ShowWithBars=2]="ShowWithBars",e[e.Automatic=3]="Automatic"}(B||(B={})),function(e){e[e.ScoreDefault=0]="ScoreDefault",e[e.ScoreForcePiano=1]="ScoreForcePiano",e[e.SingleNoteEffectBand=2]="SingleNoteEffectBand",e[e.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano"}(k||(k={})),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",e[e.EffectFreeTime=41]="EffectFreeTime",e[e.EffectSustainPedal=42]="EffectSustainPedal",e[e.EffectGolpe=43]="EffectGolpe",e[e.EffectWahPedal=44]="EffectWahPedal",e[e.EffectBeatBarre=45]="EffectBeatBarre",e[e.EffectNoteOrnament=46]="EffectNoteOrnament",e[e.EffectRasgueado=47]="EffectRasgueado",e[e.EffectDirections=48]="EffectDirections",e[e.EffectBeatTimer=49]="EffectBeatTimer"}(x||(x={}));class se{constructor(){this.notationMode=T.GuitarPro,this.fingeringMode=k.ScoreDefault,this.elements=new Map,this.rhythmMode=B.Automatic,this.rhythmHeight=15,this.transpositionPitches=[],this.displayTranspositionPitches=[],this.smallGraceTabNotes=!0,this.extendBendArrowsOnTiedNotes=!0,this.extendLineEffectsToBeatEnd=!1,this.slurHeight=5}isNotationElementVisible(e){return this.elements.has(e)?this.elements.get(e):!se.defaultElements.has(e)||se.defaultElements.get(e)}}se.defaultElements=new Map([[x.ZerosOnDiveWhammys,!1]]);class ie{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"}(N||(N={}));class ae{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...s){console.debug(ae.format(e,t),...s)}warning(e,t,...s){console.warn(ae.format(e,t),...s)}info(e,t,...s){console.info(ae.format(e,t),...s)}error(e,t,...s){console.error(ae.format(e,t),...s)}}ae.logLevel=N.Info;class re{static shouldLog(e){return re.logLevel!==N.None&&e>=re.logLevel}static debug(e,t,...s){re.shouldLog(N.Debug)&&re.log.debug(e,t,...s)}static warning(e,t,...s){re.shouldLog(N.Warning)&&re.log.warning(e,t,...s)}static info(e,t,...s){re.shouldLog(N.Info)&&re.log.info(e,t,...s)}static error(e,t,...s){re.shouldLog(N.Error)&&re.log.error(e,t,...s)}}re.logLevel=N.Info,re.log=new ae,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"}(v||(v={})),function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(P||(P={})),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"}(C||(C={}));class ne{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=v.C,this.keySignatureType=P.Major,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.isFreeTime=!1,this.tripletFeel=C.NoTripletFeel,this.section=null,this.tempoAutomations=[],this.fermata=null,this.start=0,this.isAnacrusis=!1,this.displayScale=1,this.displayWidth=-1,this.directions=null}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}get tempoAutomation(){return this.tempoAutomations.length>0?this.tempoAutomations[0]:null}calculateDuration(e=!0){if(this.isAnacrusis&&e){let e=0;for(let t of this.score.tracks)for(let s of t.staves){let t=this.index<s.bars.length?s.bars[this.index].calculateDuration():0;t>e&&(e=t)}return e}return this.timeSignatureNumerator*ee.valueToTicks(this.timeSignatureDenominator)}addFermata(e,t){let s=this.fermata;null===s&&(s=new Map,this.fermata=s),s.set(e,t)}addDirection(e){null==this.directions&&(this.directions=new Set),this.directions.add(e)}getFermata(e){const t=this.fermata;return null===t?null:t.has(e.playbackStart)?t.get(e.playbackStart):null}}ne.MaxAlternateEndings=8;class oe{constructor(){this.note=null,this.tone=new he,this.octave=0}get realValue(){return 12*this.octave+this.tone.noteValue}}class he{constructor(e=0,t=b.Default){this.noteValue=e,this.accidentalMode=t}}class le{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===k.ScoreForcePiano||e.notation.fingeringMode===k.SingleNoteEffectBandForcePiano||Y.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:return null;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!!le.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(!le.TuningLetters.has(a))return null;t+=String.fromCharCode(a)}}if(!s||!t)return null;let i=new oe;return i.octave=parseInt(s)+1,i.note=t.toLowerCase(),i.tone=le.getToneForText(i.note),i.tone.noteValue<0&&(i.octave--,i.tone.noteValue+=12),i}static getTuningForText(e){let t=le.parseTuning(e);return t?t.realValue:-1}static getToneForText(e){const t=e.substring(0,1),s=e.substring(1);let i,a;switch(t.toLowerCase()){case"c":default:i=0;break;case"d":i=2;break;case"e":i=4;break;case"f":i=5;break;case"g":i=7;break;case"a":i=9;break;case"b":i=11}switch(a=le.parseAccidentalMode(s),a){case b.Default:case b.ForceNone:case b.ForceNatural:break;case b.ForceSharp:i++;break;case b.ForceDoubleSharp:i+=2;break;case b.ForceFlat:i--;break;case b.ForceDoubleFlat:i-=2}return new he(i,a)}static parseAccidentalMode(e){const t=e.toLowerCase();return le.accidentalModeMapping.has(t)?le.accidentalModeMapping.get(t):b.Default}static newGuid(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)}static isAlmostEqualTo(e,t){return Math.abs(e-t)<1e-5}static toHexString(e,t=0){let s="";do{s=String.fromCharCode("0123456789ABCDEF".charCodeAt(15&e))+s,e>>=4}while(e>0);for(;s.length<t;)s="0"+s;return s}static getAlternateEndingsList(e){const t=[];for(let s=0;s<ne.MaxAlternateEndings;s++)e&1<<s&&t.push(s);return t}static deltaFretToHarmonicValue(e){switch(e){case 2:return 2.4;case 3:return 3.2;case 4:case 5:case 7:case 9:case 12:case 16:case 17:case 19:case 24:return e;case 8:return 8.2;case 10:return 9.6;case 14:case 15:return 14.7;case 21:case 22:return 21.7;default:return 12}}static clamp(e,t,s){return e<=t?t:e>=s?s:e}}le.TuningLetters=new Set([67,68,69,70,71,65,66,99,100,101,102,103,97,98,35]),le.accidentalModeMapping=new Map([["default",b.Default],["d",b.Default],["forcenone",b.ForceNone],["-",b.ForceNone],["forcenatural",b.ForceNatural],["n",b.ForceNatural],["forcesharp",b.ForceSharp],["#",b.ForceSharp],["forcedoublesharp",b.ForceDoubleSharp],["##",b.ForceDoubleSharp],["x",b.ForceDoubleSharp],["forceflat",b.ForceFlat],["b",b.ForceFlat],["forcedoubleflat",b.ForceDoubleFlat],["bb",b.ForceDoubleFlat]]),function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(E||(E={})),function(e){e[e.None=-1]="None",e[e.Space=32]="Space",e[e.Brace=57344]="Brace",e[e.BracketTop=57347]="BracketTop",e[e.BracketBottom=57348]="BracketBottom",e[e.SystemDivider=57351]="SystemDivider",e[e.GClef=57424]="GClef",e[e.CClef=57436]="CClef",e[e.FClef=57442]="FClef",e[e.UnpitchedPercussionClef1=57449]="UnpitchedPercussionClef1",e[e.SixStringTabClef=57453]="SixStringTabClef",e[e.FourStringTabClef=57454]="FourStringTabClef",e[e.TimeSig0=57472]="TimeSig0",e[e.TimeSig1=57473]="TimeSig1",e[e.TimeSig2=57474]="TimeSig2",e[e.TimeSig3=57475]="TimeSig3",e[e.TimeSig4=57476]="TimeSig4",e[e.TimeSig5=57477]="TimeSig5",e[e.TimeSig6=57478]="TimeSig6",e[e.TimeSig7=57479]="TimeSig7",e[e.TimeSig8=57480]="TimeSig8",e[e.TimeSig9=57481]="TimeSig9",e[e.TimeSigCommon=57482]="TimeSigCommon",e[e.TimeSigCutCommon=57483]="TimeSigCutCommon",e[e.NoteheadDoubleWholeSquare=57505]="NoteheadDoubleWholeSquare",e[e.NoteheadDoubleWhole=57504]="NoteheadDoubleWhole",e[e.NoteheadWhole=57506]="NoteheadWhole",e[e.NoteheadHalf=57507]="NoteheadHalf",e[e.NoteheadBlack=57508]="NoteheadBlack",e[e.NoteheadNull=57509]="NoteheadNull",e[e.NoteheadXOrnate=57514]="NoteheadXOrnate",e[e.NoteheadTriangleUpWhole=57531]="NoteheadTriangleUpWhole",e[e.NoteheadTriangleUpHalf=57532]="NoteheadTriangleUpHalf",e[e.NoteheadTriangleUpBlack=57534]="NoteheadTriangleUpBlack",e[e.NoteheadDiamondBlackWide=57564]="NoteheadDiamondBlackWide",e[e.NoteheadDiamondWhite=57565]="NoteheadDiamondWhite",e[e.NoteheadDiamondWhiteWide=57566]="NoteheadDiamondWhiteWide",e[e.NoteheadCircleX=57523]="NoteheadCircleX",e[e.NoteheadXWhole=57511]="NoteheadXWhole",e[e.NoteheadXHalf=57512]="NoteheadXHalf",e[e.NoteheadXBlack=57513]="NoteheadXBlack",e[e.NoteheadParenthesis=57550]="NoteheadParenthesis",e[e.NoteheadSlashedBlack2=57552]="NoteheadSlashedBlack2",e[e.NoteheadCircleSlash=57591]="NoteheadCircleSlash",e[e.NoteheadHeavyX=57592]="NoteheadHeavyX",e[e.NoteheadHeavyXHat=57593]="NoteheadHeavyXHat",e[e.NoteheadSlashVerticalEnds=57600]="NoteheadSlashVerticalEnds",e[e.NoteheadSlashWhiteWhole=57602]="NoteheadSlashWhiteWhole",e[e.NoteheadSlashWhiteHalf=57603]="NoteheadSlashWhiteHalf",e[e.NoteQuarterUp=57813]="NoteQuarterUp",e[e.NoteEighthUp=57815]="NoteEighthUp",e[e.TextBlackNoteLongStem=57841]="TextBlackNoteLongStem",e[e.TextBlackNoteFrac8thLongStem=57843]="TextBlackNoteFrac8thLongStem",e[e.TextBlackNoteFrac16thLongStem=57845]="TextBlackNoteFrac16thLongStem",e[e.TextBlackNoteFrac32ndLongStem=57846]="TextBlackNoteFrac32ndLongStem",e[e.TextCont8thBeamLongStem=57848]="TextCont8thBeamLongStem",e[e.TextCont16thBeamLongStem=57850]="TextCont16thBeamLongStem",e[e.TextCont32ndBeamLongStem=57851]="TextCont32ndBeamLongStem",e[e.TextAugmentationDot=57852]="TextAugmentationDot",e[e.TextTupletBracketStartLongStem=57857]="TextTupletBracketStartLongStem",e[e.TextTuplet3LongStem=57858]="TextTuplet3LongStem",e[e.TextTupletBracketEndLongStem=57859]="TextTupletBracketEndLongStem",e[e.Tremolo3=57890]="Tremolo3",e[e.Tremolo2=57889]="Tremolo2",e[e.Tremolo1=57888]="Tremolo1",e[e.FlagEighthUp=57920]="FlagEighthUp",e[e.FlagEighthDown=57921]="FlagEighthDown",e[e.FlagSixteenthUp=57922]="FlagSixteenthUp",e[e.FlagSixteenthDown=57923]="FlagSixteenthDown",e[e.FlagThirtySecondUp=57924]="FlagThirtySecondUp",e[e.FlagThirtySecondDown=57925]="FlagThirtySecondDown",e[e.FlagSixtyFourthUp=57926]="FlagSixtyFourthUp",e[e.FlagSixtyFourthDown=57927]="FlagSixtyFourthDown",e[e.FlagOneHundredTwentyEighthUp=57928]="FlagOneHundredTwentyEighthUp",e[e.FlagOneHundredTwentyEighthDown=57929]="FlagOneHundredTwentyEighthDown",e[e.FlagTwoHundredFiftySixthUp=57930]="FlagTwoHundredFiftySixthUp",e[e.FlagTwoHundredFiftySixthDown=57931]="FlagTwoHundredFiftySixthDown",e[e.AccidentalFlat=57952]="AccidentalFlat",e[e.AccidentalNatural=57953]="AccidentalNatural",e[e.AccidentalSharp=57954]="AccidentalSharp",e[e.AccidentalDoubleSharp=57955]="AccidentalDoubleSharp",e[e.AccidentalDoubleFlat=57956]="AccidentalDoubleFlat",e[e.AccidentalQuarterToneFlatArrowUp=57968]="AccidentalQuarterToneFlatArrowUp",e[e.AccidentalQuarterToneSharpArrowUp=57972]="AccidentalQuarterToneSharpArrowUp",e[e.AccidentalQuarterToneNaturalArrowUp=57970]="AccidentalQuarterToneNaturalArrowUp",e[e.Segno=57415]="Segno",e[e.Coda=57416]="Coda",e[e.ArticAccentAbove=58528]="ArticAccentAbove",e[e.ArticAccentBelow=58529]="ArticAccentBelow",e[e.ArticStaccatoAbove=58530]="ArticStaccatoAbove",e[e.ArticStaccatoBelow=58531]="ArticStaccatoBelow",e[e.ArticTenutoAbove=58532]="ArticTenutoAbove",e[e.ArticTenutoBelow=58533]="ArticTenutoBelow",e[e.ArticMarcatoAbove=58540]="ArticMarcatoAbove",e[e.ArticMarcatoBelow=58541]="ArticMarcatoBelow",e[e.FermataAbove=58560]="FermataAbove",e[e.FermataShortAbove=58564]="FermataShortAbove",e[e.FermataLongAbove=58566]="FermataLongAbove",e[e.RestLonga=58593]="RestLonga",e[e.RestDoubleWhole=58594]="RestDoubleWhole",e[e.RestWhole=58595]="RestWhole",e[e.RestHalf=58596]="RestHalf",e[e.RestQuarter=58597]="RestQuarter",e[e.RestEighth=58598]="RestEighth",e[e.RestSixteenth=58599]="RestSixteenth",e[e.RestThirtySecond=58600]="RestThirtySecond",e[e.RestSixtyFourth=58601]="RestSixtyFourth",e[e.RestOneHundredTwentyEighth=58602]="RestOneHundredTwentyEighth",e[e.RestTwoHundredFiftySixth=58603]="RestTwoHundredFiftySixth",e[e.Repeat1Bar=58624]="Repeat1Bar",e[e.Repeat2Bars=58625]="Repeat2Bars",e[e.Ottava=58640]="Ottava",e[e.OttavaAlta=58641]="OttavaAlta",e[e.OttavaBassaVb=58652]="OttavaBassaVb",e[e.Quindicesima=58644]="Quindicesima",e[e.QuindicesimaAlta=58645]="QuindicesimaAlta",e[e.DynamicPPP=58666]="DynamicPPP",e[e.DynamicPP=58667]="DynamicPP",e[e.DynamicPiano=58656]="DynamicPiano",e[e.DynamicMP=58668]="DynamicMP",e[e.DynamicMF=58669]="DynamicMF",e[e.DynamicForte=58658]="DynamicForte",e[e.DynamicFF=58671]="DynamicFF",e[e.DynamicFFF=58672]="DynamicFFF",e[e.OrnamentTrill=58726]="OrnamentTrill",e[e.OrnamentTurn=58727]="OrnamentTurn",e[e.OrnamentTurnInverted=58728]="OrnamentTurnInverted",e[e.OrnamentShortTrill=58732]="OrnamentShortTrill",e[e.OrnamentMordent=58733]="OrnamentMordent",e[e.StringsDownBow=58896]="StringsDownBow",e[e.StringsUpBow=58898]="StringsUpBow",e[e.KeyboardPedalPed=58960]="KeyboardPedalPed",e[e.KeyboardPedalUp=58965]="KeyboardPedalUp",e[e.PictEdgeOfCymbal=59177]="PictEdgeOfCymbal",e[e.GuitarString0=59443]="GuitarString0",e[e.GuitarString1=59444]="GuitarString1",e[e.GuitarString2=59445]="GuitarString2",e[e.GuitarString3=59446]="GuitarString3",e[e.GuitarString4=59447]="GuitarString4",e[e.GuitarString5=59448]="GuitarString5",e[e.GuitarString6=59449]="GuitarString6",e[e.GuitarString7=59450]="GuitarString7",e[e.GuitarString8=59451]="GuitarString8",e[e.GuitarString9=59452]="GuitarString9",e[e.GuitarOpenPedal=59453]="GuitarOpenPedal",e[e.GuitarClosePedal=59455]="GuitarClosePedal",e[e.GuitarGolpe=59458]="GuitarGolpe",e[e.GuitarFadeIn=59459]="GuitarFadeIn",e[e.GuitarFadeOut=59460]="GuitarFadeOut",e[e.GuitarVolumeSwell=59461]="GuitarVolumeSwell",e[e.FretboardX=59481]="FretboardX",e[e.FretboardO=59482]="FretboardO",e[e.WiggleTrill=60068]="WiggleTrill",e[e.WiggleVibratoMediumFast=60126]="WiggleVibratoMediumFast",e[e.OctaveBaselineM=60565]="OctaveBaselineM",e[e.OctaveBaselineB=60563]="OctaveBaselineB"}(F||(F={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(D||(D={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(L||(L={}));class de{constructor(e,t){this.width=e,this.height=t}}class ce{constructor(e="",t=0,s=0,i=F.None,a=F.None,r=F.None,n=F.None,o=L.Middle){this.elementType=e,this.outputMidiNumber=s,this.staffLine=t,this.noteHeadDefault=i,this.noteHeadHalf=a!==F.None?a:i,this.noteHeadWhole=r!==F.None?r:i,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case p.Whole:return this.noteHeadWhole;case p.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class ue{static articulationFromElementVariation(e,t){return e<ue.gp6ElementAndVariationToArticulation.length?(t>=ue.gp6ElementAndVariationToArticulation.length&&(t=0),ue.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]:ue.getArticulationByValue(t)}static getElementAndVariation(e){const t=ue.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<ue.gp6ElementAndVariationToArticulation.length;e++){const s=ue.gp6ElementAndVariationToArticulation[e];for(let i=0;i<s.length;i++){const a=ue.getArticulationByValue(s[i]);if(a?.outputMidiNumber===t.outputMidiNumber)return[e,i]}}return[-1,-1]}static getArticulationByValue(e){return ue.instrumentArticulations.has(e)?ue.instrumentArticulations.get(e):null}}ue.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]],ue.instrumentArticulations=new Map([[38,new ce("snare",3,38,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[37,new ce("snare",3,37,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[91,new ce("snare",3,38,F.NoteheadDiamondWhite,F.NoteheadDiamondWhite,F.NoteheadDiamondWhite)],[42,new ce("hiHat",-1,42,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[92,new ce("hiHat",-1,46,F.NoteheadCircleSlash,F.NoteheadCircleSlash,F.NoteheadCircleSlash)],[46,new ce("hiHat",-1,46,F.NoteheadCircleX,F.NoteheadCircleX,F.NoteheadCircleX)],[44,new ce("hiHat",9,44,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[35,new ce("kickDrum",8,35,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[36,new ce("kickDrum",7,36,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[50,new ce("tom",1,50,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[48,new ce("tom",2,48,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[47,new ce("tom",4,47,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[45,new ce("tom",5,45,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[43,new ce("tom",6,43,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[93,new ce("ride",0,51,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack,F.PictEdgeOfCymbal,L.Bottom)],[51,new ce("ride",0,51,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[53,new ce("ride",0,53,F.NoteheadDiamondWhite,F.NoteheadDiamondWhite,F.NoteheadDiamondWhite)],[94,new ce("ride",0,51,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack,F.ArticStaccatoAbove,L.Top)],[55,new ce("splash",-2,55,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[95,new ce("splash",-2,55,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack,F.ArticStaccatoAbove,L.Bottom)],[52,new ce("china",-3,52,F.NoteheadHeavyXHat,F.NoteheadHeavyXHat,F.NoteheadHeavyXHat)],[96,new ce("china",-3,52,F.NoteheadHeavyXHat,F.NoteheadHeavyXHat,F.NoteheadHeavyXHat)],[49,new ce("crash",-2,49,F.NoteheadHeavyX,F.NoteheadHeavyX,F.NoteheadHeavyX)],[97,new ce("crash",-2,49,F.NoteheadHeavyX,F.NoteheadHeavyX,F.NoteheadHeavyX,F.ArticStaccatoAbove,L.Bottom)],[57,new ce("crash",-1,57,F.NoteheadHeavyX,F.NoteheadHeavyX,F.NoteheadHeavyX)],[98,new ce("crash",-1,57,F.NoteheadHeavyX,F.NoteheadHeavyX,F.NoteheadHeavyX,F.ArticStaccatoAbove,L.Bottom)],[99,new ce("cowbell",1,56,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpHalf,F.NoteheadTriangleUpWhole)],[100,new ce("cowbell",1,56,F.NoteheadXBlack,F.NoteheadXHalf,F.NoteheadXWhole)],[56,new ce("cowbell",0,56,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpHalf,F.NoteheadTriangleUpWhole)],[101,new ce("cowbell",0,56,F.NoteheadXBlack,F.NoteheadXHalf,F.NoteheadXWhole)],[102,new ce("cowbell",-1,56,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpHalf,F.NoteheadTriangleUpWhole)],[103,new ce("cowbell",-1,56,F.NoteheadXBlack,F.NoteheadXHalf,F.NoteheadXWhole)],[77,new ce("woodblock",-9,77,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack)],[76,new ce("woodblock",-10,76,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack)],[60,new ce("bongo",-4,60,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[104,new ce("bongo",-5,60,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.NoteheadParenthesis,L.Middle)],[105,new ce("bongo",-6,60,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[61,new ce("bongo",-7,61,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[106,new ce("bongo",-8,61,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.NoteheadParenthesis,L.Middle)],[107,new ce("bongo",-16,61,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[66,new ce("timbale",10,66,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[65,new ce("timbale",9,65,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[68,new ce("agogo",12,68,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[67,new ce("agogo",11,67,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[64,new ce("conga",17,64,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[108,new ce("conga",16,64,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[109,new ce("conga",15,64,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.NoteheadParenthesis,L.Middle)],[63,new ce("conga",14,63,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[110,new ce("conga",13,63,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[62,new ce("conga",19,62,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.NoteheadParenthesis,L.Middle)],[72,new ce("whistle",-11,72,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[71,new ce("whistle",-17,71,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[73,new ce("guiro",38,73,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[74,new ce("guiro",37,74,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[86,new ce("surdo",36,86,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[87,new ce("surdo",35,87,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadParenthesis,L.Middle)],[54,new ce("tambourine",3,54,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack)],[111,new ce("tambourine",2,54,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack,F.StringsUpBow,L.Bottom)],[112,new ce("tambourine",1,54,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack,F.NoteheadTriangleUpBlack,F.StringsDownBow,L.Bottom)],[113,new ce("tambourine",-7,54,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[79,new ce("cuica",30,79,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[78,new ce("cuica",29,78,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[58,new ce("vibraslap",28,58,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[81,new ce("triangle",27,81,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[80,new ce("triangle",26,80,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadParenthesis,L.Middle)],[114,new ce("grancassa",25,43,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[115,new ce("piatti",18,49,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[116,new ce("piatti",24,49,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[69,new ce("cabasa",23,69,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[117,new ce("cabasa",22,69,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.StringsUpBow,L.Bottom)],[85,new ce("castanets",21,85,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[75,new ce("claves",20,75,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[70,new ce("maraca",-12,70,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[118,new ce("maraca",-13,70,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.StringsUpBow,L.Bottom)],[119,new ce("maraca",-14,70,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[120,new ce("maraca",-15,70,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.StringsUpBow,L.Bottom)],[82,new ce("shaker",-23,54,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[122,new ce("shaker",-24,54,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.StringsUpBow,L.Bottom)],[84,new ce("bellTree",-18,53,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[123,new ce("bellTree",-19,53,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole,F.StringsUpBow,L.Bottom)],[83,new ce("jingleBell",-20,53,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[124,new ce("unpitched",-21,62,F.NoteheadNull,F.NoteheadNull,F.NoteheadNull,F.GuitarGolpe,L.Top)],[125,new ce("unpitched",-22,62,F.NoteheadNull,F.NoteheadNull,F.NoteheadNull,F.GuitarGolpe,L.Bottom)],[39,new ce("handClap",3,39,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[40,new ce("snare",3,40,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[31,new ce("snare",3,40,F.NoteheadSlashedBlack2,F.NoteheadSlashedBlack2,F.NoteheadSlashedBlack2)],[41,new ce("tom",5,41,F.NoteheadBlack,F.NoteheadHalf,F.NoteheadWhole)],[59,new ce("ride",2,59,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack,F.PictEdgeOfCymbal,L.Bottom)],[126,new ce("ride",2,59,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[127,new ce("ride",2,59,F.NoteheadDiamondWhite,F.NoteheadDiamondWhite,F.NoteheadDiamondWhite)],[29,new ce("ride",2,59,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack,F.ArticStaccatoAbove,L.Top)],[30,new ce("crash",-3,49,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[33,new ce("snare",3,37,F.NoteheadXBlack,F.NoteheadXBlack,F.NoteheadXBlack)],[34,new ce("snare",3,38,F.NoteheadBlack,F.NoteheadBlack,F.NoteheadBlack)]]),ue.instrumentArticulationNames=new Map([["Ride (choke)",29],["Cymbal (hit)",30],["Snare (side stick)",31],["Snare (side stick) 2",33],["Snare (hit)",34],["Kick (hit)",35],["Kick (hit) 2",36],["Snare (side stick) 3",37],["Snare (hit) 2",38],["Hand Clap (hit)",39],["Snare (hit) 3",40],["Low Floor Tom (hit)",41],["Hi-Hat (closed)",42],["Very Low Tom (hit)",43],["Pedal Hi-Hat (hit)",44],["Low Tom (hit)",45],["Hi-Hat (open)",46],["Mid Tom (hit)",47],["High Tom (hit)",48],["Crash high (hit)",49],["High Floor Tom (hit)",50],["Ride (middle)",51],["China (hit)",52],["Ride (bell)",53],["Tambourine (hit)",54],["Splash (hit)",55],["Cowbell medium (hit)",56],["Crash medium (hit)",57],["Vibraslap (hit)",58],["Ride (edge)",59],["Hand (hit)",60],["Hand (hit)",61],["Conga high (mute)",62],["Conga high (hit)",63],["Conga low (hit)",64],["Timbale high (hit)",65],["Timbale low (hit)",66],["Agogo high (hit)",67],["Agogo tow (hit)",68],["Cabasa (hit)",69],["Left Maraca (hit)",70],["Whistle high (hit)",71],["Whistle low (hit)",72],["Guiro (hit)",73],["Guiro (scrap-return)",74],["Claves (hit)",75],["Woodblock high (hit)",76],["Woodblock low (hit)",77],["Cuica (mute)",78],["Cuica (open)",79],["Triangle (rnute)",80],["Triangle (hit)",81],["Shaker (hit)",82],["Tinkle Bell (hat)",83],["Jingle Bell (hit)",83],["Bell Tree (hit)",84],["Castanets (hit)",85],["Surdo (hit)",86],["Surdo (mute)",87],["Snare (rim shot)",91],["Hi-Hat (half)",92],["Ride (edge) 2",93],["Ride (choke) 2",94],["Splash (choke)",95],["China (choke)",96],["Crash high (choke)",97],["Crash medium (choke)",98],["Cowbell low (hit)",99],["Cowbell low (tip)",100],["Cowbell medium (tip)",101],["Cowbell high (hit)",102],["Cowbell high (tip)",103],["Hand (mute)",104],["Hand (slap)",105],["Hand (mute) 2",106],["Hand (slap) 2",107],["Conga low (slap)",108],["Conga low (mute)",109],["Conga high (slap)",110],["Tambourine (return)",111],["Tambourine (roll)",112],["Tambourine (hand)",113],["Grancassa (hit)",114],["Piatti (hat)",115],["Piatti (hand)",116],["Cabasa (return)",117],["Left Maraca (return)",118],["Right Maraca (hit)",119],["Right Maraca (return)",120],["Shaker (return)",122],["Bell Tee (return)",123],["Golpe (thumb)",124],["Golpe (finger)",125],["Ride (middle) 2",126],["Ride (bell) 2",127]]),function(e){e[e.None=0]="None",e[e.InvertedTurn=1]="InvertedTurn",e[e.Turn=2]="Turn",e[e.UpperMordent=3]="UpperMordent",e[e.LowerMordent=4]="LowerMordent"}(M||(M={}));class pe{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1}}class ge{constructor(){this.id=ge.GlobalNoteId++,this.index=0,this.accentuated=i.None,this.bendType=d.None,this.bendStyle=l.Default,this.bendOrigin=null,this.isContinuedBend=!1,this.bendPoints=null,this.maxBendPoint=null,this.fret=-1,this.string=-1,this.showStringNumber=!1,this.octave=-1,this.tone=-1,this.percussionArticulation=-1,this.isVisible=!0,this.isLeftHandTapped=!1,this.isHammerPullOrigin=!1,this.hammerPullOrigin=null,this.hammerPullDestination=null,this.isSlurDestination=!1,this.slurOrigin=null,this.slurDestination=null,this.harmonicType=y.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=S.None,this.slideOutType=_.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=w.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=f.Unknown,this.rightHandFinger=f.Unknown,this.trillValue=-1,this.trillSpeed=p.ThirtySecond,this.durationPercent=1,this.accidentalMode=b.Default,this.dynamics=g.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.ornament=M.None,this._noteIdBag=null}get hasBend(){return null!==this.bendPoints&&this.bendType!==d.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?ue.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?ue.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==y.None}get isTieOrigin(){return null!==this.tieDestination}get isFingering(){return this.leftHandFinger!==f.Unknown||this.rightHandFinger!==f.Unknown}get trillFret(){return this.trillValue-this.stringTuning}get isTrill(){return this.trillValue>=0}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get stringTuning(){return this.beat.voice.bar.staff.capo+ge.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===y.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===y.None||!this.isStringed)return 0;let e=this.harmonicValue;return le.isAlmostEqualTo(e,2.4)?36:le.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!==y.Natural&&this.harmonicType!==y.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===d.None&&(this.bendType=d.Custom)}finish(e,t=null){let s=new ie((()=>ge.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=ge.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case _.Shift:case _.Legato:this.slideTarget=s.value,this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=_.None}let a=null;this.isHammerPullOrigin&&this.hammerPullDestination?a=this.hammerPullDestination:this.slideOutType===_.Legato&&this.slideTarget&&(a=this.slideTarget),a&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===E.None?(this.effectSlurOrigin.effectSlurDestination=a,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=a,this.effectSlurDestination.effectSlurOrigin=this));const r=this.bendPoints,n=null!=r&&r.length>0;if(n){let e=this.isTieDestination&&this.tieOrigin.hasBend;this.isContinuedBend=e}else this.bendType=d.None;if(n&&this.bendType===d.Custom)if(4===r.length){let e=r[0],t=r[1],s=r[2],i=r[3];t.value===s.value?i.value>e.value?t.value>i.value?this.bendType=d.BendRelease:!this.isContinuedBend&&e.value>0?(this.bendType=d.PrebendBend,r.splice(2,1),r.splice(1,1)):(this.bendType=d.Bend,r.splice(2,1),r.splice(1,1)):i.value<e.value?this.isContinuedBend?(this.bendType=d.Release,r.splice(2,1),r.splice(1,1)):(this.bendType=d.PrebendRelease,r.splice(2,1),r.splice(1,1)):t.value>e.value?this.bendType=d.BendRelease:e.value>0&&!this.isContinuedBend?(this.bendType=d.Prebend,r.splice(2,1),r.splice(1,1)):(this.bendType=d.Hold,r.splice(2,1),r.splice(1,1)):re.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===r.length){let e=r[0],t=r[1];t.value>e.value?!this.isContinuedBend&&e.value>0?this.bendType=d.PrebendBend:this.bendType=d.Bend:t.value<e.value?this.isContinuedBend?this.bendType=d.Release:this.bendType=d.PrebendRelease:e.value>0&&!this.isContinuedBend?this.bendType=d.Prebend:this.bendType=d.Hold}this.initialBendValue>0&&(this.accidentalMode=b.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+ge.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+ge.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-ge.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(ge.NoteIdLookupKey)?t=e.get(ge.NoteIdLookupKey):(t=new Map,e.set(ge.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??ge.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 pe),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new pe),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new pe),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new pe),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new pe),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new pe),this._noteIdBag.hammerPullDestinationNoteId=t,!0}return!1}}ge.GlobalNoteId=0,ge.MaxOffsetForSameLineSearch=3,ge.NoteIdLookupKey="NoteIdLookup";class me{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!==m.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 me.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}me.HalfTicks=1920,me.QuarterTicks=960,me.EighthTicks=480,me.SixteenthTicks=240,me.ThirtySecondTicks=120,me.SixtyFourthTicks=60,me.OneHundredTwentyEighthTicks=30,me.TwoHundredFiftySixthTicks=15,me.AllTicks=[me.HalfTicks,me.QuarterTicks,me.EighthTicks,me.SixteenthTicks,me.ThirtySecondTicks,me.SixtyFourthTicks,me.OneHundredTwentyEighthTicks,me.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"}(I||(I={}));class fe{static clone(e){const t=new te;return t.offset=e.offset,t.value=e.value,t}}class ye{static clone(e){const t=new ge;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(fe.clone(s))}return t.fret=e.fret,t.string=e.string,t.showStringNumber=e.showStringNumber,t.octave=e.octave,t.tone=e.tone,t.percussionArticulation=e.percussionArticulation,t.isVisible=e.isVisible,t.isLeftHandTapped=e.isLeftHandTapped,t.isHammerPullOrigin=e.isHammerPullOrigin,t.isSlurDestination=e.isSlurDestination,t.harmonicType=e.harmonicType,t.harmonicValue=e.harmonicValue,t.isGhost=e.isGhost,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.isDead=e.isDead,t.isStaccato=e.isStaccato,t.slideInType=e.slideInType,t.slideOutType=e.slideOutType,t.vibrato=e.vibrato,t.isTieDestination=e.isTieDestination,t.leftHandFinger=e.leftHandFinger,t.rightHandFinger=e.rightHandFinger,t.trillValue=e.trillValue,t.trillSpeed=e.trillSpeed,t.durationPercent=e.durationPercent,t.accidentalMode=e.accidentalMode,t.dynamics=e.dynamics,t.ornament=e.ornament,t}}class be{static clone(e){const t=new Q;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class Se{static clone(e){const t=new we;t.index=e.index,t.notes=[];for(const s of e.notes)t.addNote(ye.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(be.clone(s));if(t.dots=e.dots,t.fade=e.fade,t.lyrics=e.lyrics?e.lyrics.slice():null,t.pop=e.pop,t.slap=e.slap,t.tap=e.tap,t.text=e.text,t.slashed=e.slashed,t.deadSlapped=e.deadSlapped,t.brushType=e.brushType,t.brushDuration=e.brushDuration,t.tupletDenominator=e.tupletDenominator,t.tupletNumerator=e.tupletNumerator,t.isContinuedWhammy=e.isContinuedWhammy,t.whammyBarType=e.whammyBarType,e.whammyBarPoints){t.whammyBarPoints=[];for(const s of e.whammyBarPoints)t.addWhammyBarPoint(fe.clone(s))}return t.vibrato=e.vibrato,t.chordId=e.chordId,t.graceType=e.graceType,t.pickStroke=e.pickStroke,t.tremoloSpeed=e.tremoloSpeed,t.crescendo=e.crescendo,t.displayStart=e.displayStart,t.playbackStart=e.playbackStart,t.displayDuration=e.displayDuration,t.playbackDuration=e.playbackDuration,t.golpe=e.golpe,t.dynamics=e.dynamics,t.invertBeamDirection=e.invertBeamDirection,t.preferredBeamDirection=e.preferredBeamDirection,t.isEffectSlurOrigin=e.isEffectSlurOrigin,t.beamingMode=e.beamingMode,t.wahPedal=e.wahPedal,t.barreFret=e.barreFret,t.barreShape=e.barreShape,t.rasgueado=e.rasgueado,t.showTimer=e.showTimer,t.timer=e.timer,t}}class _e{constructor(){this.beats=[],this.id="empty",this.isComplete=!1}addBeat(e){e.graceIndex=this.beats.length,e.graceGroup=this,this.beats.push(e)}finish(){this.beats.length>0&&(this.id=this.beats[0].absoluteDisplayStart+"_"+this.beats[0].voice.index)}}!function(e){e[e.None=0]="None",e[e.Thumb=1]="Thumb",e[e.Finger=2]="Finger"}(A||(A={})),function(e){e[e.None=0]="None",e[e.FadeIn=1]="FadeIn",e[e.FadeOut=2]="FadeOut",e[e.VolumeSwell=3]="VolumeSwell"}(O||(O={})),function(e){e[e.None=0]="None",e[e.Open=1]="Open",e[e.Closed=2]="Closed"}(R||(R={})),function(e){e[e.None=0]="None",e[e.Full=1]="Full",e[e.Half=2]="Half"}(V||(V={})),function(e){e[e.None=0]="None",e[e.Ii=1]="Ii",e[e.Mi=2]="Mi",e[e.MiiTriplet=3]="MiiTriplet",e[e.MiiAnapaest=4]="MiiAnapaest",e[e.PmpTriplet=5]="PmpTriplet",e[e.PmpAnapaest=6]="PmpAnapaest",e[e.PeiTriplet=7]="PeiTriplet",e[e.PeiAnapaest=8]="PeiAnapaest",e[e.PaiTriplet=9]="PaiTriplet",e[e.PaiAnapaest=10]="PaiAnapaest",e[e.AmiTriplet=11]="AmiTriplet",e[e.AmiAnapaest=12]="AmiAnapaest",e[e.Ppp=13]="Ppp",e[e.Amii=14]="Amii",e[e.Amip=15]="Amip",e[e.Eami=16]="Eami",e[e.Eamii=17]="Eamii",e[e.Peami=18]="Peami"}(H||(H={})),function(e){e[e.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext",e[e.ForceSplitOnSecondaryToNext=3]="ForceSplitOnSecondaryToNext"}(G||(G={}));class we{constructor(){this.id=we._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=l.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=p.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fade=O.None,this.lyrics=null,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.slashed=!1,this.deadSlapped=!1,this.brushType=c.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=I.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=w.None,this.chordId=null,this.graceType=m.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=E.None,this.tremoloSpeed=null,this.crescendo=u.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.golpe=A.None,this.dynamics=g.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=G.Auto,this.wahPedal=R.None,this.barreFret=-1,this.barreShape=V.None,this.rasgueado=H.None,this.showTimer=!1,this.timer=null}get isLastOfVoice(){return this.index===this.voice.beats.length-1}get isLegatoDestination(){return!!this.previousBeat&&this.previousBeat.isLegatoOrigin}get isRest(){return this.isEmpty||!this.deadSlapped&&0===this.notes.length}get isFullBarRest(){return this.isRest&&1===this.voice.beats.length&&this.duration===p.Whole}get fadeIn(){return this.fade===O.FadeIn}set fadeIn(e){this.fade=e?O.FadeIn:O.None}get hasRasgueado(){return this.rasgueado!==H.None}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==I.None}get hasChord(){return!!this.chordId}get chord(){return this.chordId?this.voice.bar.staff.getChord(this.chordId):null}get isTremolo(){return!!this.tremoloSpeed}get absoluteDisplayStart(){return this.voice.bar.masterBar.start+this.displayStart}get absolutePlaybackStart(){return this.voice.bar.masterBar.start+this.playbackStart}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get isBarre(){return this.barreShape!==V.None&&this.barreFret>=0}addWhammyBarPoint(e){let t=this.whammyBarPoints;null===t&&(t=[],this.whammyBarPoints=t),t.push(e),(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e),(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e),this.whammyBarType===I.None&&(this.whammyBarType=I.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=ee.toTicks(this.duration);return 2===this.dots?e=ee.applyDot(e,!0):1===this.dots&&(e=ee.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=ee.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){let e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case m.BeforeBeat:case m.OnBeat:switch(this.duration){case p.Sixteenth:this.playbackDuration=ee.toTicks(p.SixtyFourth);break;case p.ThirtySecond:this.playbackDuration=ee.toTicks(p.OneHundredTwentyEighth);break;default:this.playbackDuration=ee.toTicks(p.ThirtySecond)}this.displayDuration=0;break;case m.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;let t=this.previousBeat;t&&t.graceType===m.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){let e=this.previousBeat,t=e?e.tupletGroup:null;if((this.hasTuplet||this.graceType!==m.None&&t)&&(e&&t&&t.check(this)||(t=new me(this.voice),t.check(this)),this.tupletGroup=t),this.index>0){const e=this.voice.bar.masterBar.calculateDuration(),t=[];for(const s of this.automations)0===s.ratioPosition&&(s.ratioPosition=this.playbackStart/e),s.type!==a.Volume&&t.push(s);this.automations=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(Q.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case m.OnBeat:case m.BeforeBeat:let e=this.graceGroup.beats.length;this.duration=1===e?p.Eighth:2===e?p.Sixteenth:p.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,h=this.notes.length;a<h;a++){let h=this.notes[a];if(h.dynamics=this.dynamics,h.finish(e,t),h.isLetRing&&(this.isLetRing=!0),h.isPalmMute&&(this.isPalmMute=!0),s===T.SongBook&&h.hasBend&&this.graceType!==m.BendGrace){if(!h.isTieOrigin)switch(h.bendType){case d.Bend:case d.PrebendRelease:case d.PrebendBend:r=!0}i||h.bendStyle===l.Gradual?(i=!0,h.bendStyle=l.Gradual,r=!1):h.bendStyle=l.Fast}h.isVisible&&(n++,(!this.minNote||h.realValue<this.minNote.realValue)&&(this.minNote=h),(!this.maxNote||h.realValue>this.maxNote.realValue)&&(this.maxNote=h),(!this.minStringNote||h.string<this.minStringNote.string)&&(this.minStringNote=h),(!this.maxStringNote||h.string>this.maxStringNote.string)&&(this.maxStringNote=h),h.hasEffectSlur&&(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 h=this.whammyBarPoints,c=null!==h&&h.length>0;if(c){const e=!!this.previousBeat&&this.previousBeat.hasWhammyBar;this.isContinuedWhammy=e}else this.whammyBarType=I.None;if(c&&this.whammyBarType===I.Custom&&(s===T.SongBook&&(this.whammyStyle=i?l.Gradual:l.Fast),4===h.length)){let e=h[0],t=h[1],i=h[2],a=h[3];t.value===i.value&&(e.value<t.value&&t.value<a.value||e.value>t.value&&t.value>a.value?(0===e.value||this.isContinuedWhammy?this.whammyBarType=I.Dive:this.whammyBarType=I.PrediveDive,h.splice(2,1),h.splice(1,1)):e.value>t.value&&t.value<a.value||e.value<t.value&&t.value>a.value?(this.whammyBarType=I.Dip,t.offset!==i.offset&&s!==T.SongBook||h.splice(2,1)):e.value===t.value&&t.value===a.value&&(0===e.value||this.isContinuedWhammy?this.whammyBarType=I.Hold:this.whammyBarType=I.Predive,h.splice(2,1),h.splice(1,1)))}if(this.updateDurations(),r){let e=Se.clone(this);e.id=we._globalBeatId++,e.pickStroke=E.None;for(let t=0,s=e.notes.length;t<s;t++){let s=e.notes[t],i=this.notes[t];if(s.bendType=d.None,s.maxBendPoint=null,s.bendPoints=null,s.bendStyle=l.Default,s.id=ge.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=ge.findTieOrigin(i);if(e&&e.hasBend){s.bendType=d.Hold;let e=i.bendPoints[i.bendPoints.length-1];s.addBendPoint(new te(0,e.value)),s.addBendPoint(new te(te.MaxPosition,e.value))}}s.isTieDestination=!0}this.graceType=m.BendGrace,this.graceGroup=new _e,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new _e,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)}}we._globalBeatId=0;class Be{constructor(){this.name="",this.firstFret=1,this.strings=[],this.barreFrets=[],this.showName=!0,this.showDiagram=!0,this.showFingering=!0}get uniqueId(){return[this.name,this.firstFret.toString(),this.strings.join(","),this.barreFrets.join(","),this.showDiagram.toString(),this.showFingering.toString(),this.showName.toString()].join("|")}}!function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.Text=2]="Text",e[e.Comment=3]="Comment",e[e.Dash=4]="Dash"}(W||(W={}));class ke{constructor(){this.startBar=0,this.text=""}finish(e=!1){this.chunks=[],this.parse(this.text,0,this.chunks,e)}parse(e,t,s,i){if(!e)return;let a=W.Begin,r=W.Begin,n=!1,o=0;for(;t<e.length;){let s=e.charCodeAt(t);switch(a){case W.IgnoreSpaces:switch(s){case ke.CharCodeLF:case ke.CharCodeCR:case ke.CharCodeTab:break;case ke.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case W.Begin:if(s!==ke.CharCodeBrackedOpen){o=t,a=W.Text;continue}a=W.Comment;break;case W.Comment:if(s===ke.CharCodeBrackedClose)a=W.Begin;break;case W.Text:switch(s){case ke.CharCodeDash:a=W.Dash;break;case ke.CharCodeCR:case ke.CharCodeLF:case ke.CharCodeSpace:let s=e.substr(o,t-o);this.addChunk(s,i),a=W.IgnoreSpaces,r=W.Begin}break;case W.Dash:if(s!==ke.CharCodeDash){let s=e.substr(o,t-o);this.addChunk(s,i),n=!0,a=W.IgnoreSpaces,r=W.Begin;continue}}t+=1}a===W.Text&&t!==o&&this.addChunk(e.substr(o,t-o),i)}addChunk(e,t){e=this.prepareChunk(e),(!t||e.length>0&&"-"!==e)&&this.chunks.push(e)}prepareChunk(e){let t=e.split("+").join(" "),s=t.length;for(;s>0&&"_"===t.charAt(s-1);)s--;return s!==t.length?t.substr(0,s):t}}ke.CharCodeLF=10,ke.CharCodeTab=9,ke.CharCodeCR=13,ke.CharCodeSpace=32,ke.CharCodeBrackedClose=93,ke.CharCodeBrackedOpen=91,ke.CharCodeDash=45,function(e){e[e.NoBrackets=0]="NoBrackets",e[e.GroupStaves=1]="GroupStaves",e[e.GroupSimilarInstruments=2]="GroupSimilarInstruments"}(z||(z={})),function(e){e[e.Hidden=0]="Hidden",e[e.FirstSystem=1]="FirstSystem",e[e.AllSystems=2]="AllSystems"}(U||(U={})),function(e){e[e.FullName=0]="FullName",e[e.ShortName=1]="ShortName"}(X||(X={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical"}(J||(J={}));class Te{constructor(){this.hideDynamics=!1,this.bracketExtendMode=z.GroupStaves,this.useSystemSignSeparator=!1,this.globalDisplayTuning=!0,this.perTrackDisplayTuning=null,this.globalDisplayChordDiagramsOnTop=!0,this.perTrackChordDiagramsOnTop=null,this.singleTrackTrackNamePolicy=U.FirstSystem,this.multiTrackTrackNamePolicy=U.FirstSystem,this.firstSystemTrackNameMode=X.ShortName,this.otherSystemsTrackNameMode=X.ShortName,this.firstSystemTrackNameOrientation=J.Vertical,this.otherSystemsTrackNameOrientation=J.Vertical}}class xe{constructor(){this.masterBars=[],this.opening=null,this.closings=[],this.isClosed=!1}get openings(){const e=this.opening;return e?[e]:[]}get isOpened(){return!0===this.opening?.isRepeatStart}addMasterBar(e){null===this.opening&&(this.opening=e),this.masterBars.push(e),e.repeatGroup=this,e.isRepeatEnd&&(this.closings.push(e),this.isClosed=!0)}}class Ne{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 Te}rebuildRepeatGroups(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0;for(const e of this.masterBars)this.addMasterBarToRepeatGroups(e)}addMasterBar(e){e.score=this,e.index=this.masterBars.length,0!==this.masterBars.length&&(e.previousMasterBar=this.masterBars[this.masterBars.length-1],e.previousMasterBar.nextMasterBar=e,e.start=e.previousMasterBar.start+(e.previousMasterBar.isAnacrusis?0:e.previousMasterBar.calculateDuration())),this.addMasterBarToRepeatGroups(e),this.masterBars.push(e)}addMasterBarToRepeatGroups(e){e.isRepeatStart?(this._currentRepeatGroup?.isClosed&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--),this._currentRepeatGroup=new xe,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new xe,this._openedRepeatGroups.push(this._currentRepeatGroup)),this._currentRepeatGroup.addMasterBar(e),e.isRepeatEnd&&this._properlyOpenedRepeatGroups>1&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--,this._currentRepeatGroup=this._openedRepeatGroups.length>0?this._openedRepeatGroups[this._openedRepeatGroups.length-1]:null)}addTrack(e){e.score=this,e.index=this.tracks.length,this.tracks.push(e)}finish(e){const t=new Map;for(let s=0,i=this.tracks.length;s<i;s++)this.tracks[s].finish(e,t)}}class ve{constructor(){this.marker="",this.text=""}}class Pe extends j{constructor(e){super(s.Format,e),Object.setPrototypeOf(this,Pe.prototype)}}class Ce{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="#"+le.toHexString(this.r,2)+le.toHexString(this.g,2)+le.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 Ce(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){if(e instanceof Ce)return e;switch(typeof e){case"number":{const t=new Ce(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 Ce(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16));if(5===t.length)return new Ce(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 Ce(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16));if(9===t.length)return new Ce(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 Pe("No values specified for rgb/rgba function");const i=t.substring(e+1,s).split(",");if(3===i.length)return new Ce(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]));if(4===i.length)return new Ce(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]),255*parseFloat(i[3]))}return null}}throw new Pe("Unsupported format for color")}static toJson(e){return e.raw}}Ce.BlackRgb="#000000";class Ee{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 Fe{static getTextForTuning(e,t){let s=Fe.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 Fe._defaultTunings.has(e)?Fe._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return Fe._sevenStrings;case 6:return Fe._sixStrings;case 5:return Fe._fiveStrings;case 4:return Fe._fourStrings}return[]}static initialize(){Fe._defaultTunings.set(7,new Fe("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),Fe._sevenStrings.push(Fe._defaultTunings.get(7)),Fe._defaultTunings.set(6,new Fe("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),Fe._sixStrings.push(Fe._defaultTunings.get(6)),Fe._sixStrings.push(new Fe("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),Fe._sixStrings.push(new Fe("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),Fe._sixStrings.push(new Fe("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),Fe._sixStrings.push(new Fe("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),Fe._sixStrings.push(new Fe("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),Fe._sixStrings.push(new Fe("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),Fe._sixStrings.push(new Fe("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),Fe._sixStrings.push(new Fe("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),Fe._sixStrings.push(new Fe("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),Fe._sixStrings.push(new Fe("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),Fe._sixStrings.push(new Fe("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),Fe._sixStrings.push(new Fe("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),Fe._sixStrings.push(new Fe("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),Fe._sixStrings.push(new Fe("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),Fe._sixStrings.push(new Fe("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),Fe._sixStrings.push(new Fe("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),Fe._sixStrings.push(new Fe("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),Fe._sixStrings.push(new Fe("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),Fe._sixStrings.push(new Fe("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),Fe._defaultTunings.set(5,new Fe("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),Fe._fiveStrings.push(Fe._defaultTunings.get(5)),Fe._fiveStrings.push(new Fe("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),Fe._fiveStrings.push(new Fe("Banjo Open D Tuning",[62,57,54,50,69],!1)),Fe._fiveStrings.push(new Fe("Banjo Open G Tuning",[62,59,55,50,67],!1)),Fe._fiveStrings.push(new Fe("Banjo G Minor Tuning",[62,58,55,50,67],!1)),Fe._fiveStrings.push(new Fe("Banjo G Modal Tuning",[62,57,55,50,67],!1)),Fe._defaultTunings.set(4,new Fe("Bass Standard Tuning",[43,38,33,28],!0)),Fe._fourStrings.push(Fe._defaultTunings.get(4)),Fe._fourStrings.push(new Fe("Bass Tune down ½ step",[42,37,32,27],!1)),Fe._fourStrings.push(new Fe("Bass Tune down 1 step",[41,36,31,26],!1)),Fe._fourStrings.push(new Fe("Bass Tune down 2 step",[39,34,29,24],!1)),Fe._fourStrings.push(new Fe("Bass Dropped D Tuning",[43,38,33,26],!1)),Fe._fourStrings.push(new Fe("Ukulele C Tuning",[45,40,36,43],!1)),Fe._fourStrings.push(new Fe("Ukulele G Tuning",[52,47,43,38],!1)),Fe._fourStrings.push(new Fe("Mandolin Standard Tuning",[64,57,50,43],!1)),Fe._fourStrings.push(new Fe("Mandolin or Violin Tuning",[76,69,62,55],!1)),Fe._fourStrings.push(new Fe("Viola Tuning",[69,62,55,48],!1)),Fe._fourStrings.push(new Fe("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){let t=Fe.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=Fe.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}Fe._sevenStrings=[],Fe._sixStrings=[],Fe._fiveStrings=[],Fe._fourStrings=[],Fe._defaultTunings=new Map,Fe.defaultAccidentals=["","#","","#","","","#","","#","","#",""],Fe.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],Fe.initialize();class De{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new Fe("",[],!1),this.showSlash=!1,this.showNumbered=!1,this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=De.DefaultStandardNotationLineCount}get tuning(){return this.stringTuning.tunings}get tuningName(){return this.stringTuning.name}get isStringed(){return this.stringTuning.tunings.length>0}finish(e,t=null){this.stringTuning.finish();for(let s=0,i=this.bars.length;s<i;s++)this.bars[s].finish(e,t)}addChord(e,t){t.staff=this;let s=this.chords;null===s&&(s=new Map,this.chords=s),s.set(e,t)}hasChord(e){return this.chords?.has(e)??!1}getChord(e){return this.chords?.get(e)??null}addBar(e){let t=this.bars;e.staff=this,e.index=t.length,t.length>0&&(e.previousBar=t[t.length-1],e.previousBar.nextBar=e),t.push(e)}}De.DefaultStandardNotationLineCount=5;class Le{constructor(){this.index=0,this.staves=[],this.playbackInfo=new Ee,this.color=new Ce(200,0,0,255),this.name="",this.isVisibleOnMultiTrack=!0,this.shortName="",this.defaultSystemsLayout=3,this.systemsLayout=[],this.percussionArticulations=[]}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new De)}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>Le.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,Le.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)}}}}}Le.ShortNameMaxLength=10;let Me=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===m.None?(i.graceGroup=s,s&&(s.isComplete=!0),s=null):(s||(s=new _e),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===m.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==m.BendGrace){let s=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case m.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 m.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}};Me._globalBarId=0;class Ie{static float64ToBytes(e){return Ie._dataView.setFloat64(0,e,!0),this._conversionByteArray}static bytesToInt64LE(e){Ie._conversionByteArray.set(e,0);const t=Ie._dataView.getBigInt64(0,!0);return t<=Number.MAX_SAFE_INTEGER&&t>=Number.MIN_SAFE_INTEGER?Number(t):Number.MAX_SAFE_INTEGER}static bytesToFloat64LE(e){return Ie._conversionByteArray.set(e,0),Ie._dataView.getFloat64(0,!0)}static bytesToFloat32LE(e){return Ie._conversionByteArray.set(e,0),Ie._dataView.getFloat32(0,!0)}static float32BEToBytes(e){return Ie._dataView.setFloat32(0,e,!1),Ie._conversionByteArray.slice(0,4)}static uint16ToInt16(e){return Ie._dataView.setUint16(0,e,!0),Ie._dataView.getInt16(0,!0)}static int16ToUint32(e){return Ie._dataView.setInt16(0,e,!0),Ie._dataView.getUint32(0,!0)}static int32ToUint16(e){return Ie._dataView.setInt32(0,e,!0),Ie._dataView.getUint16(0,!0)}static int32ToInt16(e){return Ie._dataView.setInt32(0,e,!0),Ie._dataView.getInt16(0,!0)}static int32ToUint32(e){return Ie._dataView.setInt32(0,e,!0),Ie._dataView.getUint32(0,!0)}static uint8ToInt8(e){return Ie._dataView.setUint8(0,e),Ie._dataView.getInt8(0)}}Ie._conversionBuffer=new ArrayBuffer(8),Ie._conversionByteArray=new Uint8Array(Ie._conversionBuffer),Ie._dataView=new DataView(Ie._conversionBuffer);class Ae{static readInt32BE(e){return e.readByte()<<24|e.readByte()<<16|e.readByte()<<8|e.readByte()}static readFloat32BE(e){const t=new Uint8Array(4);return e.read(t,0,t.length),t.reverse(),Ie.bytesToFloat32LE(t)}static readFloat64BE(e){const t=new Uint8Array(8);return e.read(t,0,t.length),t.reverse(),Ie.bytesToFloat64LE(t)}static readInt32LE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static readInt64LE(e){const t=new Uint8Array(8);return e.read(t,0,t.length),Ie.bytesToInt64LE(t)}static readUInt32LE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static decodeUInt32LE(e,t){let s=e[t],i=e[t+1],a=e[t+2];return e[t+3]<<24|a<<16|i<<8|s}static readUInt16LE(e){let t=e.readByte(),s=e.readByte();return Ie.int32ToUint16(s<<8|t)}static readInt16LE(e){let t=e.readByte(),s=e.readByte();return Ie.int32ToInt16(s<<8|t)}static readUInt32BE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte(),a=e.readByte();return Ie.int32ToUint32(t<<24|s<<16|i<<8|a)}static readUInt16BE(e){let t=e.readByte(),s=e.readByte();return Ie.int32ToInt16(t<<8|s)}static readInt16BE(e){let t=e.readByte(),s=e.readByte();return Ie.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),Ae.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 Ie.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){let s=Ae.detectEncoding(e);return s&&(t=s),t||(t="utf-8"),new TextDecoder(t).decode(e.buffer)}static detectEncoding(e){return e.length>2&&254===e[0]&&255===e[1]?"utf-16be":e.length>2&&255===e[0]&&254===e[1]?"utf-16le":e.length>4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3]?"utf-32be":e.length>4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3]?"utf-32le":null}static stringToBytes(e){return(new TextEncoder).encode(e)}static writeInt32BE(e,t){e.writeByte(t>>24&255),e.writeByte(t>>16&255),e.writeByte(t>>8&255),e.writeByte(255&t)}static writeInt32LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255),e.writeByte(t>>16&255),e.writeByte(t>>24&255)}static writeUInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16BE(e,t){e.writeByte(t>>8&255),e.writeByte(255&t)}static writeFloat32BE(e,t){const s=Ie.float32BEToBytes(t);e.write(s,0,s.length)}}class Oe{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return Oe.withCapacity(0)}static withCapacity(e){let t=new Oe;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){let t=new Oe;return t._buffer=e,t.length=e.length,t}static fromString(e){let t=Ae.stringToBytes(e);return Oe.fromBuffer(t)}reset(){this.position=0}skip(e){this.position+=e}readByte(){return this.length-this.position<=0?-1:this._buffer[this.position++]}read(e,t,s){let i=this.length-this.position;return i>s&&(i=s),i<=0?0:(e.set(this._buffer.subarray(this.position,this.position+i),t),this.position+=i,i)}writeByte(e){let t=this.position+1;this.ensureCapacity(t),this._buffer[this.position]=255&e,t>this.length&&(this.length=t),this.position=t}write(e,t,s){let i=this.position+s;this.ensureCapacity(i);let a=Math.min(s,e.length-t);this._buffer.set(e.subarray(t,t+a),this.position),i>this.length&&(this.length=i),this.position=i}ensureCapacity(e){if(e>this._buffer.length){let t=e;t<256&&(t=256),t<2*this._buffer.length&&(t=2*this._buffer.length);let s=new Uint8Array(t);this.length>0&&s.set(this._buffer.subarray(0,0+this.length),0),this._buffer=s}}readAll(){return this.toArray()}toArray(){let e=new Uint8Array(this.length);return e.set(this._buffer.subarray(0,0+this.length),0),e}copyTo(e){e.write(this._buffer,0,this.length)}}class Re{}var Ve,He,Ge,We,ze,Ue,Xe,Je,Ye,qe,je,Ke,Qe,$e;Re.DefaultChannelCount=17,Re.MetronomeChannel=Re.DefaultChannelCount-1,Re.MetronomeKey=33,Re.AudioChannels=2,Re.MinVolume=0,Re.MinProgram=0,Re.MaxProgram=127,Re.MinPlaybackSpeed=.125,Re.MaxPlaybackSpeed=8,Re.PercussionChannel=9,Re.PercussionBank=128,Re.MaxPitchWheel=16384,Re.MaxPitchWheel20=4294967296,Re.DefaultPitchWheel=Re.MaxPitchWheel/2,Re.MicroBufferCount=32,Re.MicroBufferSize=64,function(e){e[e.TargetFine=0]="TargetFine",e[e.TargetSegno=1]="TargetSegno",e[e.TargetSegnoSegno=2]="TargetSegnoSegno",e[e.TargetCoda=3]="TargetCoda",e[e.TargetDoubleCoda=4]="TargetDoubleCoda",e[e.JumpDaCapo=5]="JumpDaCapo",e[e.JumpDaCapoAlCoda=6]="JumpDaCapoAlCoda",e[e.JumpDaCapoAlDoubleCoda=7]="JumpDaCapoAlDoubleCoda",e[e.JumpDaCapoAlFine=8]="JumpDaCapoAlFine",e[e.JumpDalSegno=9]="JumpDalSegno",e[e.JumpDalSegnoAlCoda=10]="JumpDalSegnoAlCoda",e[e.JumpDalSegnoAlDoubleCoda=11]="JumpDalSegnoAlDoubleCoda",e[e.JumpDalSegnoAlFine=12]="JumpDalSegnoAlFine",e[e.JumpDalSegnoSegno=13]="JumpDalSegnoSegno",e[e.JumpDalSegnoSegnoAlCoda=14]="JumpDalSegnoSegnoAlCoda",e[e.JumpDalSegnoSegnoAlDoubleCoda=15]="JumpDalSegnoSegnoAlDoubleCoda",e[e.JumpDalSegnoSegnoAlFine=16]="JumpDalSegnoSegnoAlFine",e[e.JumpDaCoda=17]="JumpDaCoda",e[e.JumpDaDoubleCoda=18]="JumpDaDoubleCoda"}(Ve||(Ve={})),function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(He||(He={}));class Ze{constructor(){this.type=He.Short,this.length=0}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(Ge||(Ge={})),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"}(We||(We={})),function(e){e[e.KnownStaffMeta=0]="KnownStaffMeta",e[e.UnknownStaffMeta=1]="UnknownStaffMeta",e[e.EndOfMetaDetected=2]="EndOfMetaDetected"}(ze||(ze={}));class et extends j{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??We.No,this.symbol=o??We.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 ${We[a]} found a ${We[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)}}!function(e){e[e.Auto=0]="Auto",e[e.Explicit=1]="Explicit"}(Ue||(Ue={}));class tt extends q{constructor(){super(),this._trackChannel=0,this._barIndex=0,this._voiceIndex=0,this._input="",this._ch=tt.Eof,this._curChPos=0,this._line=1,this._col=0,this._lastValidSpot=[0,1,0],this._sy=We.No,this._syData="",this._allowNegatives=!1,this._allowFloat=!1,this._allowTuning=!1,this._currentDuration=p.QuadrupleWhole,this._currentDynamics=g.PPP,this._currentTuplet=0,this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._percussionArticulationNames=new Map,this._sustainPedalToBeat=new Map,this._slurs=new Map,this._accidentalMode=Ue.Explicit,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=Oe.empty(),this._input=e,this.settings=t}readScore(){try{if(this.data.length>0&&(this._input=Ae.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this._sustainPedalToBeat=new Map,this.createDefaultScore(),this._curChPos=0,this._line=1,this._col=0,this.saveValidSpot(),this._currentDuration=p.Quarter,this._currentDynamics=g.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===We.LowerThan)throw new K("Unknown start sign '<' (meant to import as XML?)");if(this._sy!==We.Eof){const e=this.metaData(),t=this.bars();if(!e&&!t)throw new K("No alphaTex data found")}this.consolidate(),this._score.finish(this.settings),this._score.rebuildRepeatGroups();for(const[e,t]of this._lyrics)this._score.tracks[e].applyLyrics(t);for(const[e,t]of this._sustainPedalToBeat)if(0===e.ratioPosition){const s=t.voice.bar.masterBar.calculateDuration();e.ratioPosition=t.playbackStart/s}return this._score}catch(e){throw e instanceof et?new K(e.message,e):e}}consolidate(){if(0===this._score.masterBars.length){const e=new ne;this._score.addMasterBar(e);const t=new Q;t.isLinear=!1,t.type=a.Tempo,t.value=this._score.tempo,e.tempoAutomations.push(t);const s=new Z;this._score.tracks[0].staves[0].addBar(s);const i=new Me;s.addVoice(i);const r=new we;return r.isEmpty=!0,void i.addBeat(r)}for(let e of this._score.tracks)for(let t of e.staves){for(const e of t.bars)for(const t of e.voices)if(t.isEmpty&&0==t.beats.length){const e=new we;e.isEmpty=!0,t.addBeat(e)}const e=0===t.bars.length?1:t.bars[0].voices.length;for(;t.bars.length<this._score.masterBars.length;){const s=new Z;t.addBar(s);for(let t=0;t<e;t++){const e=new Me;s.addVoice(e);const t=new we;t.isEmpty=!0,e.addBeat(t)}}}}error(e,t,s=!0){let i,a=!1;s?(i=this._sy,i!==We.String&&i!==We.Number&&i!==We.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&&re.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&&re.error(this.name,t.message),t}createDefaultScore(){this._score=new Ne,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new Le,this._currentTrack.ensureStaveCount(1),this._currentTrack.playbackInfo.program=25,this._currentTrack.playbackInfo.primaryChannel=this._trackChannel++,this._currentTrack.playbackInfo.secondaryChannel=this._trackChannel++;const e=this._currentTrack.staves[0];e.displayTranspositionPitch=0,e.stringTuning.tunings=Fe.getDefaultTuningFor(6).tunings,this.beginStaff(e),this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=g.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":default:return 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 C.NoTripletFeel;case"t16":case"triplet-16th":return C.Triplet16th;case"t8":case"triplet-8th":return C.Triplet8th;case"d16":case"dotted-16th":return C.Dotted16th;case"d8":case"dotted-8th":return C.Dotted8th;case"s16":case"scottish-16th":return C.Scottish16th;case"s8":case"scottish-8th":return C.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return C.NoTripletFeel;case 1:return C.Triplet16th;case 2:return C.Triplet8th;case 3:return C.Dotted16th;case 4:return C.Dotted8th;case 5:return C.Scottish16th;case 6:return C.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":case"abminor":return v.Cb;case"gb":case"gbmajor":case"ebminor":return v.Gb;case"db":case"dbmajor":case"bbminor":return v.Db;case"ab":case"abmajor":case"fminor":return v.Ab;case"eb":case"ebmajor":case"cminor":return v.Eb;case"bb":case"bbmajor":case"gminor":return v.Bb;case"f":case"fmajor":case"dminor":return v.F;case"c":case"cmajor":case"aminor":default:return v.C;case"g":case"gmajor":case"eminor":return v.G;case"d":case"dmajor":case"bminor":return v.D;case"a":case"amajor":case"f#minor":return v.A;case"e":case"emajor":case"c#minor":return v.E;case"b":case"bmajor":case"g#minor":return v.B;case"f#":case"f#major":case"d#minor":return v.FSharp;case"c#":case"c#major":case"a#minor":return v.CSharp}}parseKeySignatureType(e){return e.toLowerCase().endsWith("minor")?P.Minor:P.Major}nextChar(){return this._curChPos<this._input.length?(this._ch=this._input.charCodeAt(this._curChPos++),10===this._ch?(this._line++,this._col=0):this._col++):this._ch=tt.Eof,this._ch}saveValidSpot(){this._lastValidSpot=[this._curChPos,this._line,this._col]}newSy(){for(this.saveValidSpot(),this._sy=We.No;this._sy===We.No;)if(this._ch===tt.Eof)this._sy=We.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",We.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=We.String;this._ch!==e&&this._ch!==tt.Eof;)92===this._ch?(this._ch=this.nextChar(),92===this._ch?t+="\\":this._ch==e?t+=String.fromCharCode(this._ch):82==this._ch||114==this._ch?t+="\r":78==this._ch||110==this._ch?t+="\n":84==this._ch||116==this._ch?t+="\t":this.errorMessage("Unsupported escape sequence")):t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._ch===tt.Eof&&this.errorMessage("String opened but never closed"),this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)this._allowNegatives?this.readNumberOrName():(this._sy=We.String,this._syData=this.readName());else if(46===this._ch)this._sy=We.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=We.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=We.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=We.MetaCommand,92===this._ch&&(this._ch=this.nextChar()),this._syData=this.readName();else if(41===this._ch)this._sy=We.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=We.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=We.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=We.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=We.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=We.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this.readNumberOrName();else if(tt.isNameLetter(this._ch)){let e=this.readName(),t=this._allowTuning?le.parseTuning(e):null;t?(this._sy=We.Tuning,this._syData=t):(this._sy=We.String,this._syData=e)}else this.error("symbol",We.String,!1);return this._sy}readNumberOrName(){let e="",t=!0;do{e+=String.fromCharCode(this._ch),this.isDigit(this._ch)||(t=!1),this._ch=this.nextChar()}while(this.isDigit(this._ch)||tt.isNameLetter(this._ch));t?(this._sy=We.Number,this._syData=this._allowFloat?parseFloat(e):parseInt(e)):(this._sy=We.String,this._syData=e)}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||42===e||92===e}static isWhiteSpace(e){return 9===e||10===e||11===e||13===e||32===e}isDigit(e){return e>=48&&e<=57||this._allowNegatives&&45===e||this._allowFloat&&46===e}readName(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(tt.isNameLetter(this._ch)||this.isDigit(this._ch));return e}metaData(){let e=!1,t=!1,s=!0;for(;this._sy===We.MetaCommand&&s;){let i=this._syData.toLowerCase();switch(i){case"title":case"subtitle":case"artist":case"album":case"words":case"music":case"copyright":case"instructions":case"notices":case"tab":this._sy=this.newSy(),this._sy!==We.String&&this.error(i,We.String,!0);let a=this._syData;switch(i){case"title":this._score.title=a;break;case"subtitle":this._score.subTitle=a;break;case"artist":this._score.artist=a;break;case"album":this._score.album=a;break;case"words":this._score.words=a;break;case"music":this._score.music=a;break;case"copyright":this._score.copyright=a;break;case"instructions":this._score.instructions=a;break;case"notices":this._score.notices=a;break;case"tab":this._score.tab=a}this._sy=this.newSy(),e=!0;break;case"tempo":this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy===We.Number?this._score.tempo=this._syData:this.error("tempo",We.Number,!0),this._sy=this.newSy(),this._sy===We.String&&(this._score.tempoLabel=this._syData,this._sy=this.newSy()),e=!0;break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===We.Number?(this._score.defaultSystemsLayout=this._syData,this._sy=this.newSy(),e=!0):this.error("default-systems-layout",We.Number,!0);break;case"systemslayout":for(this._sy=this.newSy(),e=!0;this._sy===We.Number;)this._score.systemsLayout.push(this._syData),this._sy=this.newSy();break;case"hidedynamics":this._score.stylesheet.hideDynamics=!0,this._sy=this.newSy(),e=!0;break;case"showdynamics":this._score.stylesheet.hideDynamics=!1,this._sy=this.newSy(),e=!0;break;case"bracketextendmode":this._sy=this.newSy(),this._sy!==We.String&&this.error("bracketExtendMode",We.String,!0),this._score.stylesheet.bracketExtendMode=this.parseBracketExtendMode(this._syData),this._sy=this.newSy(),e=!0;break;case"usesystemsignseparator":this._score.stylesheet.useSystemSignSeparator=!0,this._sy=this.newSy(),e=!0;break;case"singletracktracknamepolicy":this._sy=this.newSy(),this._sy!==We.String&&this.error("singleTrackTrackNamePolicy",We.String,!0),this._score.stylesheet.singleTrackTrackNamePolicy=this.parseTrackNamePolicy(this._syData),this._sy=this.newSy(),e=!0;break;case"multitracktracknamepolicy":this._sy=this.newSy(),this._sy!==We.String&&this.error("multiTrackTrackNamePolicy",We.String,!0),this._score.stylesheet.multiTrackTrackNamePolicy=this.parseTrackNamePolicy(this._syData),this._sy=this.newSy(),e=!0;break;case"firstsystemtracknamemode":this._sy=this.newSy(),this._sy!==We.String&&this.error("firstSystemTrackNameMode",We.String,!0),this._score.stylesheet.firstSystemTrackNameMode=this.parseTrackNameMode(this._syData),this._sy=this.newSy(),e=!0;break;case"othersystemstracknamemode":this._sy=this.newSy(),this._sy!==We.String&&this.error("otherSystemsTrackNameMode",We.String,!0),this._score.stylesheet.otherSystemsTrackNameMode=this.parseTrackNameMode(this._syData),this._sy=this.newSy(),e=!0;break;case"firstsystemtracknameorientation":this._sy=this.newSy(),this._sy!==We.String&&this.error("firstSystemTrackNameOrientation",We.String,!0),this._score.stylesheet.firstSystemTrackNameOrientation=this.parseTrackNameOrientation(this._syData),this._sy=this.newSy(),e=!0;break;case"othersystemstracknameorientation":this._sy=this.newSy(),this._sy!==We.String&&this.error("otherSystemsTrackNameOrientation",We.String,!0),this._score.stylesheet.otherSystemsTrackNameOrientation=this.parseTrackNameOrientation(this._syData),this._sy=this.newSy(),e=!0;break;default:switch(this.handleStaffMeta()){case ze.KnownStaffMeta:t=!0;break;case ze.UnknownStaffMeta:e||t?this.error("metaDataTags",We.String,!1):s=!1;break;case ze.EndOfMetaDetected:s=!1}}}return e?(this._sy!==We.Dot&&this.error("song",We.Dot,!0),this._sy=this.newSy()):this._sy===We.Dot&&(this._sy=this.newSy(),e=!0),e||t}parseTrackNamePolicy(e){switch(e.toLowerCase()){case"hidden":return U.Hidden;case"allsystems":return U.AllSystems;default:return U.FirstSystem}}parseTrackNameMode(e){return"fullname"===e.toLowerCase()?X.FullName:X.ShortName}parseTrackNameOrientation(e){return"horizontal"===e.toLowerCase()?J.Horizontal:J.Vertical}handleStaffMeta(){switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===We.Number?this._currentStaff.capo=this._syData:this.error("capo",We.Number,!0),this._sy=this.newSy(),ze.KnownStaffMeta;case"tuning":this._sy=this.newSy();let e=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case We.String:let e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?this.makeCurrentStaffPitched():this.error("tuning",We.Tuning,!0),this._sy=this.newSy();break;case We.Tuning:let t=[];do{let e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===We.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",We.Tuning,!0)}return this._sy===We.String&&"hide"===this._syData.toLowerCase()&&(this._score.stylesheet.perTrackDisplayTuning||(this._score.stylesheet.perTrackDisplayTuning=new Map),this._score.stylesheet.perTrackDisplayTuning.set(this._currentTrack.index,!1),this._sy=this.newSy()),e!==this._currentStaff.tuning.length&&(this._currentStaff.chords?.size??0)>0&&this.errorMessage("Tuning must be defined before any chord"),ze.KnownStaffMeta;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===We.Number){let e=this._syData;e>=0&&e<=127?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",We.Number,!1)}else if(this._sy===We.String){let e=this._syData.toLowerCase();if("percussion"===e){for(const e of this._currentTrack.staves)this.applyPercussionStaff(e);this._currentTrack.playbackInfo.primaryChannel=Re.PercussionChannel,this._currentTrack.playbackInfo.secondaryChannel=Re.PercussionChannel}else this._currentTrack.playbackInfo.program=Y.getValue(e)}else this.error("instrument",We.Number,!0);return this._sy=this.newSy(),ze.KnownStaffMeta;case"lyrics":this._sy=this.newSy();let t=new ke;return t.startBar=0,t.text="",this._sy===We.Number&&(t.startBar=this._syData,this._sy=this.newSy()),this._sy===We.String?(t.text=this._syData,this._sy=this.newSy()):this.error("lyrics",We.String,!0),this._lyrics.get(this._currentTrack.index).push(t),ze.KnownStaffMeta;case"chord":this._sy=this.newSy();let s=new Be;this.chordProperties(s),this._sy===We.String?(s.name=this._syData,this._sy=this.newSy()):this.error("chord-name",We.String,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===We.Number?s.strings.push(this._syData):this._sy===We.String&&"x"===this._syData.toLowerCase()&&s.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,s.name),s),ze.KnownStaffMeta;case"articulation":this._sy=this.newSy();let i="";if(this._sy===We.String?(i=this._syData,this._sy=this.newSy()):this.error("articulation-name",We.String,!0),"defaults"===i){for(const[e,t]of ue.instrumentArticulationNames)this._percussionArticulationNames.set(e.toLowerCase(),t),this._percussionArticulationNames.set(tt.toArticulationId(e),t);return ze.KnownStaffMeta}let a=0;return this._sy===We.Number?(a=this._syData,this._sy=this.newSy()):this.error("articulation-number",We.Number,!0),ue.instrumentArticulations.has(a)||this.errorMessage(`Unknown articulation ${a}. Refer to https://www.alphatab.net/docs/alphatex/percussion for available ids`),this._percussionArticulationNames.set(i.toLowerCase(),a),ze.KnownStaffMeta;case"accidentals":return this.handleAccidentalMode(),ze.KnownStaffMeta;case"displaytranspose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===We.Number?(this._currentStaff.displayTranspositionPitch=-1*this._syData,this._staffHasExplicitDisplayTransposition=!0):this.error("displaytranspose",We.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),ze.KnownStaffMeta;case"transpose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===We.Number?this._currentStaff.transpositionPitch=-1*this._syData:this.error("transpose",We.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),ze.KnownStaffMeta;case"track":case"staff":return ze.EndOfMetaDetected;case"voice":return this._sy=this.newSy(),this.handleNewVoice()?ze.EndOfMetaDetected:ze.KnownStaffMeta;default:return ze.UnknownStaffMeta}}handleAccidentalMode(){switch(this._sy=this.newSy(),this._sy!==We.String&&this.error("accidental-mode",We.String,!0),this._syData){case"auto":this._accidentalMode=Ue.Auto;break;case"explicit":this._accidentalMode=Ue.Explicit}this._sy=this.newSy()}makeCurrentStaffPitched(){this._currentStaff.stringTuning.tunings=[],this._staffHasExplicitDisplayTransposition||(this._currentStaff.displayTranspositionPitch=0)}static toArticulationId(e){return e.replace(new RegExp("[^a-zA-Z0-9]","g"),"").toLowerCase()}applyPercussionStaff(e){e.isPercussion=!0,e.showTablature=!1}chordProperties(e){if(this._sy===We.LBrace){for(this._sy=this.newSy();this._sy===We.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===We.Number)e.firstFret=this._syData;else this.error("chord-firstfret",We.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case We.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case We.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",We.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case We.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case We.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",We.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case We.String:e.showName="false"!==this._syData.toLowerCase();break;case We.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",We.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===We.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",We.String,!1)}this._sy!==We.RBrace&&this.error("chord-properties",We.RBrace,!0),this._sy=this.newSy()}}bars(){let e=this.bar();for(;this._sy!==We.Eof;)if(this._sy===We.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==We.MetaCommand)break;this.bar()}return e}trackStaffMeta(){if(this._sy!==We.MetaCommand)return!1;if("track"===this._syData.toLowerCase()&&(this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===We.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===We.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy()),this.trackProperties()),this._sy===We.MetaCommand&&"staff"===this._syData.toLowerCase()){if(this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0){const e=this._currentStaff.isPercussion;this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this.beginStaff(this._currentTrack.staves[this._currentTrack.staves.length-1]),e&&this.applyPercussionStaff(this._currentStaff),this._currentDynamics=g.F}this.staffProperties()}return this._sy===We.MetaCommand&&"voice"===this._syData.toLowerCase()&&(this._sy=this.newSy(),this.handleNewVoice()),!0}handleNewVoice(){if(0===this._voiceIndex&&(0==this._currentStaff.bars.length||1===this._currentStaff.bars.length&&this._currentStaff.bars[0].isEmpty))return!1;for(const e of this._currentStaff.bars){const t=new Me;e.addVoice(t)}return this._voiceIndex++,this._barIndex=0,!0}beginStaff(e){this._currentStaff=e,this._slurs.clear(),this._barIndex=0,this._voiceIndex=0}trackProperties(){if(this._sy===We.LBrace){for(this._sy=this.newSy();this._sy===We.String;)switch(this._syData.toLowerCase()){case"color":this._sy=this.newSy(),this._sy!==We.String&&this.error("track-color",We.String,!0),this._currentTrack.color=Ce.fromJson(this._syData),this._sy=this.newSy();break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===We.Number?(this._currentTrack.defaultSystemsLayout=this._syData,this._sy=this.newSy()):this.error("default-systems-layout",We.Number,!0);break;case"systemslayout":for(this._sy=this.newSy();this._sy===We.Number;)this._currentTrack.systemsLayout.push(this._syData),this._sy=this.newSy();break;case"volume":this._sy=this.newSy(),this._sy!==We.Number&&this.error("track-volume",We.Number,!0),this._currentTrack.playbackInfo.volume=le.clamp(this._syData,0,16),this._sy=this.newSy();break;case"balance":this._sy=this.newSy(),this._sy!==We.Number&&this.error("track-balance",We.Number,!0),this._currentTrack.playbackInfo.balance=le.clamp(this._syData,0,16),this._sy=this.newSy();break;case"mute":this._sy=this.newSy(),this._currentTrack.playbackInfo.isMute=!0;break;case"solo":this._sy=this.newSy(),this._currentTrack.playbackInfo.isSolo=!0;break;default:this.error("track-properties",We.String,!1)}this._sy!==We.RBrace&&this.error("track-properties",We.RBrace,!0),this._sy=this.newSy()}}staffProperties(){if(this._sy!==We.LBrace)return;this._sy=this.newSy();let e=!1,t=!1,s=!1,i=!1;for(;this._sy===We.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy(),this._sy===We.Number&&(this._currentStaff.standardNotationLineCount=this._syData,this._sy=this.newSy());break;case"tabs":t=!0,this._sy=this.newSy();break;case"slash":s=!0,this._sy=this.newSy();break;case"numbered":i=!0,this._sy=this.newSy();break;default:this.error("staff-properties",We.String,!1)}(e||t||s||i)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t,this._currentStaff.showSlash=s,this._currentStaff.showNumbered=i),this._sy!==We.RBrace&&this.error("staff-properties",We.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 ne;this._score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.timeSignatureDenominator=e.previousMasterBar.timeSignatureDenominator,e.timeSignatureNumerator=e.previousMasterBar.timeSignatureNumerator,e.tripletFeel=e.previousMasterBar.tripletFeel)}const s=this.barMeta(t),i=this._currentTrack.playbackInfo.program;this._staffTuningApplied||this._staffHasExplicitTuning||(this._currentStaff.stringTuning.tunings=[],15==i||i>=24&&i<=31?this._currentStaff.stringTuning.tunings=Fe.getDefaultTuningFor(6).tunings:i>=32&&i<=39?this._currentStaff.stringTuning.tunings=[43,38,33,28]:40==i||44==i||45==i||48==i||49==i||50==i||51==i?this._currentStaff.stringTuning.tunings=[52,57,50,43]:41==i?this._currentStaff.stringTuning.tunings=[57,50,43,36]:42==i?this._currentStaff.stringTuning.tunings=[45,38,31,24]:43==i?this._currentStaff.stringTuning.tunings=[43,38,33,28]:105==i?this._currentStaff.stringTuning.tunings=[50,47,43,38,55]:106==i?this._currentStaff.stringTuning.tunings=[57,52,45]:107==i?this._currentStaff.stringTuning.tunings=[52,45,38,31]:110==i&&(this._currentStaff.stringTuning.tunings=[64,57,50,43]),this._staffTuningApplied=!0),this._staffHasExplicitDisplayTransposition||(this._currentStaff.displayTranspositionPitch=i>=24&&i<=31||i>=32&&i<=39||43==i?-12:0);let a=!1,r=t.voices[this._voiceIndex];if(!(this._sy===We.MetaCommand&&("track"===this._syData.toLowerCase()||"staff"===this._syData.toLowerCase())))for(;this._sy!==We.Pipe&&this._sy!==We.Eof&&this.beat(r);)a=!0;if(0===r.beats.length){let e=new we;e.isEmpty=!0,r.addBeat(e)}return e||s||a}newBar(e){if(this._barIndex<e.bars.length){const t=e.bars[this._barIndex];return this._barIndex++,t}const t=0===e.bars.length?1:e.bars[0].voices.length,s=new Z;e.addBar(s),s.previousBar&&(s.clef=s.previousBar.clef,s.clefOttava=s.previousBar.clefOttava),this._barIndex++;for(let e=0;e<t;e++){let e=new Me;s.addVoice(e)}return s}beat(e){this.beatDuration();let t=new we;if(e.addBeat(t),this._allowTuning=!this._currentStaff.isPercussion,this._sy===We.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==We.RParensis&&this._sy!==We.Eof&&(this._allowTuning=!this._currentStaff.isPercussion,this.note(t)););this._sy!==We.RParensis&&this.error("note-list",We.RParensis,!0),this._sy=this.newSy()}else if(this._sy===We.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===We.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==We.Number&&this.error("duration",We.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===We.Multiply&&(this._sy=this.newSy(),this._sy!==We.Number?this.error("multiplier",We.Number,!0):s=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let i=0;i<s-1;i++)e.addBeat(Se.clone(t));return!0}beatDuration(){if(this._sy===We.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==We.Number&&this.error("duration",We.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===We.LBrace)){for(this._sy=this.newSy();this._sy===We.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==We.Number&&this.error("duration-tuplet",We.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",We.String,!1)}this._sy!==We.RBrace&&this.error("beat-duration",We.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===We.LBrace){for(this._sy=this.newSy();this._sy===We.String;)this.applyBeatEffect(e)||this.error("beat-effects",We.String,!1);this._sy!==We.RBrace&&this.error("beat-effects",We.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){let t=this._syData.toLowerCase();if("f"===t)e.fade=O.FadeIn;else if("fo"===t)e.fade=O.FadeOut;else if("vs"===t)e.fade=O.VolumeSwell;else if("v"===t)e.vibrato=w.Slight;else if("vw"===t)e.vibrato=w.Wide;else if("s"===t)e.slap=!0;else if("p"===t)e.pop=!0;else if("tt"===t)e.tap=!0;else if("txt"===t){if(this._sy=this.newSy(),this._sy!==We.String)return this.error("beat-text",We.String,!0),!1;e.text=this._syData}else if("dd"===t)e.dots=2;else if("d"===t)e.dots=1;else if("su"===t)e.pickStroke=E.Up;else if("sd"===t)e.pickStroke=E.Down;else{if("tu"===t){if(this._sy=this.newSy(),this._sy!==We.Number)return this.error("tuplet",We.Number,!0),!1;const t=this._syData;if(this._sy=this.newSy(),this._sy===We.Number){const s=this._syData;this._sy=this.newSy(),e.tupletNumerator=t,e.tupletDenominator=s}else tt.applyTuplet(e,t);return!0}if("tb"===t||"tbe"===t){this._sy=this.newSy();let s="tbe"===t;for(this._sy===We.String&&(e.whammyBarType=this.parseWhammyType(this._syData),this._sy=this.newSy()),this._sy===We.String&&(e.whammyStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==We.LParensis&&this.error("tremolobar-effect",We.LParensis,!0),this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy();this._sy!==We.RParensis&&this._sy!==We.Eof;){let t=0,i=0;s?(this._sy!==We.Number&&this.error("tremolobar-effect",We.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==We.Number&&this.error("tremolobar-effect",We.Number,!0),i=this._syData):(this._sy!==We.Number&&this.error("tremolobar-effect",We.Number,!0),t=0,i=this._syData),e.addWhammyBarPoint(new te(t,i)),this._sy=this.newSy()}if(null!=e.whammyBarPoints){for(;e.whammyBarPoints.length>60;)e.removeWhammyBarPoint(e.whammyBarPoints.length-1);if(s)e.whammyBarPoints.sort(((e,t)=>e.offset-t.offset));else{let t=e.whammyBarPoints.length,s=60/t|0,i=0;for(;i<t;)e.whammyBarPoints[i].offset=Math.min(60,i*s),i++}}this._allowNegatives=!1,this._allowFloat=!1,this._sy!==We.RParensis&&this.error("tremolobar-effect",We.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===We.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 Be;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=m.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=m.BendGrace,this._sy=this.newSy()):e.graceType=m.BeforeBeat,!0;if("dy"===t){switch(this._sy=this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=g.PPP;break;case"pp":e.dynamics=g.PP;break;case"p":e.dynamics=g.P;break;case"mp":e.dynamics=g.MP;break;case"mf":e.dynamics=g.MF;break;case"f":e.dynamics=g.F;break;case"ff":e.dynamics=g.FF;break;case"fff":e.dynamics=g.FFF}this._currentDynamics=e.dynamics}else if("cre"===t)e.crescendo=u.Crescendo;else if("dec"===t)e.crescendo=u.Decrescendo;else{if("tempo"===t){const t=this.readTempoAutomation();return e.automations.push(t),e.voice.bar.masterBar.tempoAutomations.push(t),!0}if("tp"===t){if(this._sy=this.newSy(),e.tremoloSpeed=p.Eighth,this._sy===We.Number){switch(this._syData){case 8:default:e.tremoloSpeed=p.Eighth;break;case 16:e.tremoloSpeed=p.Sixteenth;break;case 32:e.tremoloSpeed=p.ThirtySecond}this._sy=this.newSy()}return!0}if("spd"===t){const t=new $;return t.pedalType=h.Down,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spu"===t){const t=new $;return t.pedalType=h.Up,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spe"===t){const t=new $;return t.pedalType=h.Up,t.ratioPosition=1,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("slashed"===t)return e.slashed=!0,this._sy=this.newSy(),!0;if("ds"===t)return e.deadSlapped=!0,this._sy=this.newSy(),!0;if("glpf"===t)return this._sy=this.newSy(),e.golpe=A.Finger,!0;if("glpt"===t)return this._sy=this.newSy(),e.golpe=A.Thumb,!0;if("waho"===t)return this._sy=this.newSy(),e.wahPedal=R.Open,!0;if("wahc"===t)return this._sy=this.newSy(),e.wahPedal=R.Closed,!0;if("barre"===t){if(this._sy=this.newSy(),this._sy!==We.Number&&this.error("beat-barre",We.Number,!0),e.barreFret=this._syData,e.barreShape=V.Full,this._sy=this.newSy(),this._sy===We.String)switch(this._syData.toLowerCase()){case"full":e.barreShape=V.Full,this._sy=this.newSy();break;case"half":e.barreShape=V.Half,this._sy=this.newSy()}return!0}if("rasg"===t){switch(this._sy=this.newSy(),this._sy!==We.String&&this.error("rasgueado",We.String,!0),this._syData.toLowerCase()){case"ii":e.rasgueado=H.Ii;break;case"mi":e.rasgueado=H.Mi;break;case"miitriplet":e.rasgueado=H.MiiTriplet;break;case"miianapaest":e.rasgueado=H.MiiAnapaest;break;case"pmptriplet":e.rasgueado=H.PmpTriplet;break;case"pmpanapaest":e.rasgueado=H.PmpAnapaest;break;case"peitriplet":e.rasgueado=H.PeiTriplet;break;case"peianapaest":e.rasgueado=H.PeiAnapaest;break;case"paitriplet":e.rasgueado=H.PaiTriplet;break;case"paianapaest":e.rasgueado=H.PaiAnapaest;break;case"amitriplet":e.rasgueado=H.AmiTriplet;break;case"amianapaest":e.rasgueado=H.AmiAnapaest;break;case"ppp":e.rasgueado=H.Ppp;break;case"amii":e.rasgueado=H.Amii;break;case"amip":e.rasgueado=H.Amip;break;case"eami":e.rasgueado=H.Eami;break;case"eamii":e.rasgueado=H.Eamii;break;case"peami":e.rasgueado=H.Peami}return this._sy=this.newSy(),!0}if("ot"===t)this._sy=this.newSy(),this._sy!==We.String&&this.error("beat-ottava",We.String,!0),e.ottava=this.parseClefOttavaFromString(this._syData);else if("legatoorigin"===t)e.isLegatoOrigin=!0;else{if("instrument"!==t){if("fermata"===t){this._sy=this.newSy(),this._sy!==We.String&&this.error("fermata",We.Number,!0);const t=new Ze;return t.type=this.parseFermataFromString(this._syData),this._allowFloat=!0,this._sy=this.newSy(),this._sy===We.Number&&(t.length=this._syData,this._sy=this.newSy()),this._allowFloat=!1,e.fermata=t,!0}if("beam"===t){switch(this._sy=this.newSy(),this._sy!==We.String&&this.error("beam",We.Number,!0),this._syData.toLowerCase()){case"invert":e.invertBeamDirection=!0;break;case"up":e.preferredBeamDirection=Ge.Up;break;case"down":e.preferredBeamDirection=Ge.Down;break;case"auto":e.beamingMode=G.Auto;break;case"split":e.beamingMode=G.ForceSplitToNext;break;case"merge":e.beamingMode=G.ForceMergeWithNext;break;case"splitsecondary":e.beamingMode=G.ForceSplitOnSecondaryToNext}return this._sy=this.newSy(),!0}return"timer"===t&&(e.showTimer=!0,this._sy=this.newSy(),!0)}{this._sy=this.newSy();let t=0;this._sy===We.Number?t=this._syData:this._sy===We.String?t=Y.getValue(this._syData):this.error("instrument-change",We.Number,!0);const s=new Q;s.isLinear=!1,s.type=a.Instrument,s.value=t,e.automations.push(s)}}}}}}return this._sy=this.newSy(),!0}parseBracketExtendMode(e){switch(e.toLowerCase()){case"nobrackets":return z.NoBrackets;case"groupstaves":default:return z.GroupStaves;case"groupsimilarinstruments":return z.GroupSimilarInstruments}}parseFermataFromString(e){switch(e.toLowerCase()){case"short":return He.Short;case"medium":default:return He.Medium;case"long":return He.Long}}parseClefOttavaFromString(e){switch(e.toLowerCase()){case"15ma":return n._15ma;case"8va":return n._8va;case"regular":default:return n.Regular;case"8vb":return n._8vb;case"15mb":return n._15mb}}getChordId(e,t){return t.toLowerCase()+e.index+e.track.index}static applyTuplet(e,t){switch(t){case 3:e.tupletNumerator=3,e.tupletDenominator=2;break;case 5:e.tupletNumerator=5,e.tupletDenominator=4;break;case 6:e.tupletNumerator=6,e.tupletDenominator=4;break;case 7:e.tupletNumerator=7,e.tupletDenominator=4;break;case 9:e.tupletNumerator=9,e.tupletDenominator=8;break;case 10:e.tupletNumerator=10,e.tupletDenominator=8;break;case 11:e.tupletNumerator=11,e.tupletDenominator=8;break;case 12:e.tupletNumerator=12,e.tupletDenominator=8;break;default:e.tupletNumerator=1,e.tupletDenominator=1}}isNoteText(e){return"x"===e||"-"===e||"r"===e}note(e){let t=!1,s=!1,i=-1,a=-1,r=-1,n=b.Default;switch(this._sy){case We.Number:i=this._syData,this._currentStaff.isPercussion&&!ue.instrumentArticulations.has(i)&&this.errorMessage(`Unknown percussion articulation ${i}`);break;case We.String:if(this._currentStaff.isPercussion){const e=this._syData.toLowerCase();this._percussionArticulationNames.has(e)?i=this._percussionArticulationNames.get(e):this.errorMessage(`Unknown percussion articulation '${this._syData}'`)}else t="x"===this._syData,s="-"===this._syData,s||t?i=0:this.error("note-fret",We.Number,!0);break;case We.Tuning:0===e.index&&0===e.voice.index&&0===e.voice.bar.index&&this.makeCurrentStaffPitched();let o=this._syData;a=o.octave,r=o.tone.noteValue,this._accidentalMode==Ue.Explicit&&(n=o.tone.accidentalMode);break;default:return!1}this._sy=this.newSy();let o=-1===a&&this._currentStaff.tuning.length>0&&!this._currentStaff.isPercussion,h=-1;o&&(this._sy!==We.Dot&&this.error("note",We.Dot,!0),this._sy=this.newSy(),this._sy!==We.Number&&this.error("note-string",We.Number,!0),h=this._syData,(h<1||h>this._currentStaff.tuning.length)&&this.error("note-string",We.Number,!1),this._sy=this.newSy());let l=new ge;return o?(l.string=this._currentStaff.tuning.length-(h-1),l.isDead=t,l.isTieDestination=s,s||(l.fret=i)):this._currentStaff.isPercussion?l.percussionArticulation=i:(l.octave=a,l.tone=r,l.accidentalMode=n,l.isTieDestination=s),e.addNote(l),this.noteEffects(l),!0}noteEffects(e){if(this._sy===We.LBrace){for(this._sy=this.newSy();this._sy===We.String;){let t=this._syData.toLowerCase();if("b"===t||"be"===t){this._sy=this.newSy();let s="be"===t;for(this._sy===We.String&&(e.bendType=this.parseBendType(this._syData),this._sy=this.newSy()),this._sy===We.String&&(e.bendStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==We.LParensis&&this.error("bend-effect",We.LParensis,!0),this._sy=this.newSy();this._sy!==We.RParensis&&this._sy!==We.Eof;){let t=0,i=0;s?(this._sy!==We.Number&&this.error("bend-effect-value",We.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==We.Number&&this.error("bend-effect-value",We.Number,!0),i=this._syData):(this._sy!==We.Number&&this.error("bend-effect-value",We.Number,!0),i=this._syData),e.addBendPoint(new te(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!==We.RParensis&&this.error("bend-effect",We.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=y.Natural,e.harmonicValue=le.deltaFretToHarmonicValue(e.fret),this._sy=this.newSy();else if("ah"===t)e.harmonicType=y.Artificial,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("th"===t)e.harmonicType=y.Tap,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("ph"===t)e.harmonicType=y.Pinch,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("sh"===t)e.harmonicType=y.Semi,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("fh"===t)e.harmonicType=y.Feedback,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("tr"===t){this._sy=this.newSy(),this._sy!==We.Number&&this.error("trill-effect",We.Number,!0);let t=this._syData;this._sy=this.newSy();let s=p.Sixteenth;if(this._sy===We.Number){switch(this._syData){case 16:default:s=p.Sixteenth;break;case 32:s=p.ThirtySecond;break;case 64:s=p.SixtyFourth}this._sy=this.newSy()}e.trillValue=t+e.stringTuning,e.trillSpeed=s}else if("v"===t)this._sy=this.newSy(),e.vibrato=w.Slight;else if("sl"===t)this._sy=this.newSy(),e.slideOutType=_.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=_.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=S.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=S.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=_.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=_.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=_.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=_.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("ten"===t)this._sy=this.newSy(),e.accentuated=i.Tenuto;else if("pm"===t)this._sy=this.newSy(),e.isPalmMute=!0;else if("st"===t)this._sy=this.newSy(),e.isStaccato=!0;else if("lr"===t)this._sy=this.newSy(),e.isLetRing=!0;else if("x"===t)this._sy=this.newSy(),e.fret=0,e.isDead=!0;else if("-"===t||"t"===t)this._sy=this.newSy(),e.isTieDestination=!0;else if("lf"===t){this._sy=this.newSy();let t=f.Thumb;this._sy===We.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===We.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else if("acc"===t)this._sy=this.newSy(),this._sy!==We.String&&this.error("note-accidental",We.String,!0),e.accidentalMode=le.parseAccidentalMode(this._syData),this._sy=this.newSy();else if("turn"===t)this._sy=this.newSy(),e.ornament=M.Turn;else if("iturn"===t)this._sy=this.newSy(),e.ornament=M.InvertedTurn;else if("umordent"===t)this._sy=this.newSy(),e.ornament=M.UpperMordent;else if("lmordent"===t)this._sy=this.newSy(),e.ornament=M.LowerMordent;else if("string"===t)this._sy=this.newSy(),e.showStringNumber=!0;else if("hide"===t)this._sy=this.newSy(),e.isVisible=!1;else if("slur"===t){this._sy=this.newSy(),this._sy!==We.String&&this.error("slur",We.String,!0);const t=this._syData;if(this._slurs.has(t)){const s=this._slurs.get(t);s.slurDestination=e,e.slurOrigin=s,e.isSlurDestination=!0}else this._slurs.set(t,e);this._sy=this.newSy()}else this.applyBeatEffect(e.beat)||this.error(t,We.String,!1)}this._sy!==We.RBrace&&this.error("note-effect",We.RBrace,!1),this._sy=this.newSy()}}harmonicValue(e){return this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy(),this._sy===We.Number&&(e=this._syData,this._sy=this.newSy()),this._allowNegatives=!1,this._allowFloat=!1,e}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 p.QuadrupleWhole;case-2:return p.DoubleWhole;case 1:return p.Whole;case 2:return p.Half;case 4:return p.Quarter;case 8:return p.Eighth;case 16:return p.Sixteenth;case 32:return p.ThirtySecond;case 64:return p.SixtyFourth;case 128:return p.OneHundredTwentyEighth;case 256:return p.TwoHundredFiftySixth;default:return p.Quarter}}parseBendStyle(e){switch(e.toLowerCase()){case"gradual":return l.Gradual;case"fast":return l.Fast;default:return l.Default}}parseBendType(e){switch(e.toLowerCase()){case"none":return d.None;case"custom":default:return d.Custom;case"bend":return d.Bend;case"release":return d.Release;case"bendrelease":return d.BendRelease;case"hold":return d.Hold;case"prebend":return d.Prebend;case"prebendbend":return d.PrebendBend;case"prebendrelease":return d.PrebendRelease}}barMeta(e){let t=!1,s=e.masterBar,i=!1;for(;!i&&this._sy===We.MetaCommand;){t=!0;let a=this._syData.toLowerCase();if("ts"===a)this._sy=this.newSy(),this._sy===We.String?"common"===this._syData.toLowerCase()?(s.timeSignatureCommon=!0,s.timeSignatureNumerator=4,s.timeSignatureDenominator=4,this._sy=this.newSy()):this.error("timesignature-numerator",We.String,!0):(this._sy!==We.Number&&this.error("timesignature-numerator",We.Number,!0),s.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==We.Number&&this.error("timesignature-denominator",We.Number,!0),s.timeSignatureDenominator=this._syData,this._sy=this.newSy());else if("ft"==a)s.isFreeTime=!0,this._sy=this.newSy();else if("ro"===a)s.isRepeatStart=!0,this._sy=this.newSy();else if("rc"===a)this._sy=this.newSy(),this._sy!==We.Number&&this.error("repeatclose",We.Number,!0),this._syData>2048&&this.error("repeatclose",We.Number,!1),s.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===a)if(this._sy=this.newSy(),this._sy===We.LParensis){for(this._sy=this.newSy(),this._sy!==We.Number&&this.error("alternateending",We.Number,!0),this.applyAlternateEnding(s);this._sy===We.Number;)this.applyAlternateEnding(s);this._sy!==We.RParensis&&this.error("alternateending-list",We.RParensis,!0),this._sy=this.newSy()}else this._sy!==We.Number&&this.error("alternateending",We.Number,!0),this.applyAlternateEnding(s);else if("ks"===a)this._sy=this.newSy(),this._sy!==We.String&&this.error("keysignature",We.String,!0),s.keySignature=this.parseKeySignature(this._syData),s.keySignatureType=this.parseKeySignatureType(this._syData),this._sy=this.newSy();else if("clef"===a){switch(this._sy=this.newSy(),this._sy){case We.String:e.clef=this.parseClefFromString(this._syData);break;case We.Number:e.clef=this.parseClefFromInt(this._syData);break;case We.Tuning:let t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",We.String,!0)}this._sy=this.newSy()}else if("tempo"===a){const e=this.readTempoAutomation();s.tempoAutomations.push(e)}else if("section"===a){this._sy=this.newSy(),this._sy!==We.String&&this.error("section",We.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==We.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());let i=new ve;i.marker=t,i.text=e,s.section=i}else if("tf"===a){switch(this._allowTuning=!1,this._sy=this.newSy(),this._allowTuning=!0,this._sy){case We.String:s.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case We.Number:s.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",We.String,!0)}this._sy=this.newSy()}else if("ac"===a)s.isAnacrusis=!0,this._sy=this.newSy();else if("db"===a)s.isDoubleBar=!0,this._sy=this.newSy();else if("accidentals"===a)this.handleAccidentalMode();else if("jump"===a)this.handleDirections(s);else if("ottava"===a)this._sy=this.newSy(),this._sy!==We.String&&this.error("ottava",We.String,!0),e.clefOttava=this.parseClefOttavaFromString(this._syData),this._sy=this.newSy();else if("simile"===a)this._sy=this.newSy(),this._sy!==We.String&&this.error("simile",We.String,!0),e.simileMark=this.parseSimileMarkFromString(this._syData),this._sy=this.newSy();else if("scale"===a)this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==We.Number&&this.error("scale",We.Number,!0),s.displayScale=this._syData,e.displayScale=this._syData,this._sy=this.newSy();else if("width"===a)this._sy=this.newSy(),this._sy!==We.Number&&this.error("width",We.Number,!0),s.displayWidth=this._syData,e.displayWidth=this._syData,this._sy=this.newSy();else if(0===e.index)switch(this.handleStaffMeta()){case ze.KnownStaffMeta:break;case ze.UnknownStaffMeta:this.error("measure-effects",We.String,!1);break;case ze.EndOfMetaDetected:i=!0}else this.error("measure-effects",We.String,!1)}if(0===s.index&&0===s.tempoAutomations.length){let e=new Q;e.isLinear=!1,e.type=a.Tempo,e.value=this._score.tempo,e.text=this._score.tempoLabel,s.tempoAutomations.push(e)}return t}parseSimileMarkFromString(e){switch(e.toLowerCase()){case"none":default:return o.None;case"simple":return o.Simple;case"firstofdouble":return o.FirstOfDouble;case"secondofdouble":return o.SecondOfDouble}}handleDirections(e){switch(this._sy=this.newSy(),this._sy!==We.String&&this.error("direction",We.String,!0),this._syData.toLowerCase()){case"fine":e.addDirection(Ve.TargetFine);break;case"segno":e.addDirection(Ve.TargetSegno);break;case"segnosegno":e.addDirection(Ve.TargetSegnoSegno);break;case"coda":e.addDirection(Ve.TargetCoda);break;case"doublecoda":e.addDirection(Ve.TargetDoubleCoda);break;case"dacapo":e.addDirection(Ve.JumpDaCapo);break;case"dacapoalcoda":e.addDirection(Ve.JumpDaCapoAlCoda);break;case"dacapoaldoublecoda":e.addDirection(Ve.JumpDaCapoAlDoubleCoda);break;case"dacapoalfine":e.addDirection(Ve.JumpDaCapoAlFine);break;case"dalsegno":e.addDirection(Ve.JumpDalSegno);break;case"dalsegnoalcoda":e.addDirection(Ve.JumpDalSegnoAlCoda);break;case"dalsegnoaldoublecoda":e.addDirection(Ve.JumpDalSegnoAlDoubleCoda);break;case"dalsegnoalfine":e.addDirection(Ve.JumpDalSegnoAlFine);break;case"dalsegnosegno":e.addDirection(Ve.JumpDalSegnoSegno);break;case"dalsegnosegnoalcoda":e.addDirection(Ve.JumpDalSegnoSegnoAlCoda);break;case"dalsegnosegnoaldoublecoda":e.addDirection(Ve.JumpDalSegnoSegnoAlDoubleCoda);break;case"dalsegnosegnoalfine":e.addDirection(Ve.JumpDalSegnoSegnoAlFine);break;case"dacoda":e.addDirection(Ve.JumpDaCoda);break;case"dadoublecoda":e.addDirection(Ve.JumpDaDoubleCoda);break;default:return void this.errorMessage(`Unexpected direction value: '${this._syData}'`)}this._sy=this.newSy()}readTempoAutomation(){this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==We.Number&&this.error("tempo",We.Number,!0);const e=new Q;return e.isLinear=!1,e.type=a.Tempo,e.value=this._syData,this._sy=this.newSy(),this._sy===We.String&&(e.text=this._syData,this._sy=this.newSy()),e}applyAlternateEnding(e){let t=this._syData;t<1&&this.error("alternateending",We.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}parseWhammyType(e){switch(e.toLowerCase()){case"none":return I.None;case"custom":default:return I.Custom;case"dive":return I.Dive;case"dip":return I.Dip;case"hold":return I.Hold;case"predive":return I.Predive;case"predivedive":return I.PrediveDive}}}tt.Eof=0,function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Sharp=2]="Sharp",e[e.Flat=3]="Flat",e[e.NaturalQuarterNoteUp=4]="NaturalQuarterNoteUp",e[e.SharpQuarterNoteUp=5]="SharpQuarterNoteUp",e[e.FlatQuarterNoteUp=6]="FlatQuarterNoteUp",e[e.DoubleSharp=7]="DoubleSharp",e[e.DoubleFlat=8]="DoubleFlat"}(Xe||(Xe={}));class st{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 j(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 it{constructor(e,t,s){this.text=e,this.startPos=t,this.endPos=s}}class at{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 it(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 at(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"}(Je||(Je={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(Ye||(Ye={}));class rt{reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=at.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===Ye.Bold}get isItalic(){return this.style===Je.Italic}constructor(e,t,s=Je.Plain,i=Ye.Regular){this._cssScale=0,this._families=at.parseFamilies(e),this._size=t,this._style=s,this._weight=i,this._css=this.toCssString()}withSize(e){return rt.withFamilyList(this._families,e,this._style,this._weight)}static withFamilyList(e,t,s=Je.Plain,i=Ye.Regular){const a=new rt("",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=>at.quoteFont(e))).join(", "),this._css=t,this._cssScale=e}return this._css}static fromJson(e){if(e instanceof rt)return e;switch(typeof e){case"undefined":default:return null;case"object":{const t=e;let s=t.get("families"),i=t.get("size"),a=st.parseEnum(t.get("style"),Je),r=st.parseEnum(t.get("weight"),Ye);return rt.withFamilyList(s,i,a,r)}case"string":{const t=new at(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=Je.Plain;"italic"===t.style&&(r=Je.Italic);let n=Ye.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=Ye.Bold}return rt.withFamilyList(s,a,r,n)}}}static toJson(e){const t=new Map;return t.set("families",e.families),t.set("size",e.size),t.set("style",e.style),t.set("weight",e.weight),t}}!function(e){e[e.SingleTrackMultiChannel=0]="SingleTrackMultiChannel",e[e.MultiTrack=1]="MultiTrack"}(qe||(qe={}));class nt{constructor(){this.events=[]}addEvent(e){if(0===this.events.length||e.tick>=this.events[this.events.length-1].tick)this.events.push(e);else{let t=this.events.length;for(;t>0;){if(!(this.events[t-1].tick>e.tick))break;t--}this.events.splice(t,0,e)}}writeTo(e){let t=Oe.empty(),s=0;for(let e of this.events){let i=e.tick-s;ot.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();Ae.writeInt32BE(e,a.length),e.write(a,0,a.length)}}class ot{constructor(){this.format=qe.SingleTrackMultiChannel,this.division=ee.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 nt)}addEvent(e){this.format==qe.SingleTrackMultiChannel?(this.ensureTracks(1),this.tracks[0].addEvent(e)):(this.ensureTracks(e.track+1),this.tracks[e.track].addEvent(e))}toBinary(){let e=Oe.empty();return this.writeTo(e),e.toArray()}writeTo(e){let t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),Ae.writeInt32BE(e,6),Ae.writeInt16BE(e,this.format),Ae.writeInt16BE(e,this.tracks.length),Ae.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"}(je||(je={}));class ht{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 lt extends ht{constructor(e,t,s,i,a,r){super(e,t,je.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),ot.writeVariableInt(e,4),e.writeByte(255&this.numerator),e.writeByte(255&this.denominatorIndex),e.writeByte(255&this.midiClocksPerMetronomeClick),e.writeByte(255&this.thirtySecondNodesInQuarter)}}class dt extends ht{constructor(e,t,s){super(e,t,s)}writeTo(e){e.writeByte(240);const t=Oe.withCapacity(16);t.writeByte(dt.AlphaTabManufacturerId),this.writeEventData(t),t.writeByte(247),ot.writeVariableInt(e,t.length),t.copyTo(e)}}dt.AlphaTabManufacturerId=125,dt.MetronomeEventId=0,dt.RestEventId=1;class ct extends dt{constructor(e,t,s,i,a){super(e,t,je.AlphaTabMetronome),this.isMetronome=!0,this.metronomeNumerator=s,this.metronomeDurationInMilliseconds=a,this.metronomeDurationInTicks=i}writeEventData(e){e.writeByte(dt.MetronomeEventId),e.writeByte(this.metronomeNumerator),Ae.writeInt32LE(e,this.metronomeDurationInTicks),Ae.writeInt32LE(e,this.metronomeDurationInMilliseconds)}}class ut extends dt{constructor(e,t,s){super(e,t,je.AlphaTabRest),this.channel=s}writeEventData(e){e.writeByte(dt.RestEventId),e.writeByte(this.channel)}}class pt extends ht{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 gt extends pt{constructor(e,t,s,i,a){super(e,t,je.NoteOn,s,i,a)}writeTo(e){e.writeByte(15&this.channel|144),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class mt extends pt{constructor(e,t,s,i,a){super(e,t,je.NoteOff,s,i,a)}writeTo(e){e.writeByte(15&this.channel|128),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class ft extends ht{constructor(e,t,s,i,a){super(e,t,je.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 ht{constructor(e,t,s,i){super(e,t,je.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 bt extends ht{constructor(e,t){super(0,e,je.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 St extends ht{constructor(e,t,s,i){super(e,t,je.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 _t extends ht{constructor(e,t,s,i,a){super(e,t,je.PerNotePitchBend),this.channel=s,this.noteKey=i,this.value=a}writeTo(e){throw new j(s.General,"Note Bend (Midi2.0) events cannot be exported to SMF1.0")}}class wt extends ht{constructor(e,t){super(e,t,je.EndOfTrack)}writeTo(e){e.writeByte(255),e.writeByte(47),e.writeByte(0)}}class Bt{constructor(){this.copyrightFont=new rt(Bt.sansFont,12,Je.Plain,Ye.Bold),this.titleFont=new rt(Bt.serifFont,32,Je.Plain),this.subTitleFont=new rt(Bt.serifFont,20,Je.Plain),this.wordsFont=new rt(Bt.serifFont,15,Je.Plain),this.effectFont=new rt(Bt.serifFont,12,Je.Italic),this.timerFont=new rt(Bt.serifFont,12,Je.Plain),this.directionsFont=new rt(Bt.serifFont,14,Je.Plain),this.fretboardNumberFont=new rt(Bt.sansFont,11,Je.Plain),this.numberedNotationFont=new rt(Bt.sansFont,16,Je.Plain),this.numberedNotationGraceFont=new rt(Bt.sansFont,14,Je.Plain),this.tablatureFont=new rt(Bt.sansFont,13,Je.Plain),this.graceFont=new rt(Bt.sansFont,11,Je.Plain),this.staffLineColor=new Ce(165,165,165,255),this.barSeparatorColor=new Ce(34,34,17,255),this.barNumberFont=new rt(Bt.sansFont,11,Je.Plain),this.barNumberColor=new Ce(200,0,0,255),this.fingeringFont=new rt(Bt.serifFont,14,Je.Plain),this.inlineFingeringFont=new rt(Bt.serifFont,12,Je.Plain),this.markerFont=new rt(Bt.serifFont,14,Je.Plain,Ye.Bold),this.mainGlyphColor=new Ce(0,0,0,255),this.secondaryGlyphColor=new Ce(0,0,0,100),this.scoreInfoColor=new Ce(0,0,0,255)}}Bt.sansFont="Arial, sans-serif",Bt.serifFont="Georgia, serif",function(e){e[e.Automatic=0]="Automatic",e[e.UseModelLayout=1]="UseModelLayout"}(Ke||(Ke={}));class kt{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 Bt,this.padding=[35,35],this.firstSystemPaddingTop=5,this.systemPaddingTop=10,this.systemPaddingBottom=20,this.lastSystemPaddingBottom=0,this.systemLabelPaddingLeft=0,this.systemLabelPaddingRight=5,this.accoladeBarPaddingRight=3,this.notationStaffPaddingTop=5,this.notationStaffPaddingBottom=5,this.effectStaffPaddingTop=0,this.effectStaffPaddingBottom=0,this.firstStaffPaddingLeft=6,this.staffPaddingLeft=2,this.systemsLayoutMode=Ke.Automatic}}class Tt{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"}(Qe||(Qe={}));class xt{constructor(){this.noteWideLength=240,this.noteWideAmplitude=1,this.noteSlightLength=360,this.noteSlightAmplitude=.5,this.beatWideLength=480,this.beatWideAmplitude=2,this.beatSlightLength=480,this.beatSlightAmplitude=2}}class Nt{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}!function(e){e[e.WebAudioAudioWorklets=0]="WebAudioAudioWorklets",e[e.WebAudioScriptProcessor=1]="WebAudioScriptProcessor"}($e||($e={}));class vt{constructor(){this.soundFont=null,this.scrollElement="html,body",this.outputMode=$e.WebAudioAudioWorklets,this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=Qe.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new xt,this.slide=new Nt,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}class Pt{static fromJson(e,t){t&&st.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=st.parseEnum(s,N),!0;case"useworkers":return e.useWorkers=s,!0;case"includenotebounds":return e.includeNoteBounds=s,!0}return!1}}class Ct{static fromJson(e,t){t&&st.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",rt.toJson(e.copyrightFont)),t.set("titlefont",rt.toJson(e.titleFont)),t.set("subtitlefont",rt.toJson(e.subTitleFont)),t.set("wordsfont",rt.toJson(e.wordsFont)),t.set("effectfont",rt.toJson(e.effectFont)),t.set("timerfont",rt.toJson(e.timerFont)),t.set("directionsfont",rt.toJson(e.directionsFont)),t.set("fretboardnumberfont",rt.toJson(e.fretboardNumberFont)),t.set("numberednotationfont",rt.toJson(e.numberedNotationFont)),t.set("numberednotationgracefont",rt.toJson(e.numberedNotationGraceFont)),t.set("tablaturefont",rt.toJson(e.tablatureFont)),t.set("gracefont",rt.toJson(e.graceFont)),t.set("stafflinecolor",Ce.toJson(e.staffLineColor)),t.set("barseparatorcolor",Ce.toJson(e.barSeparatorColor)),t.set("barnumberfont",rt.toJson(e.barNumberFont)),t.set("barnumbercolor",Ce.toJson(e.barNumberColor)),t.set("fingeringfont",rt.toJson(e.fingeringFont)),t.set("inlinefingeringfont",rt.toJson(e.inlineFingeringFont)),t.set("markerfont",rt.toJson(e.markerFont)),t.set("mainglyphcolor",Ce.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",Ce.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",Ce.toJson(e.scoreInfoColor)),t}static setProperty(e,t,s){switch(t){case"copyrightfont":return e.copyrightFont=rt.fromJson(s),!0;case"titlefont":return e.titleFont=rt.fromJson(s),!0;case"subtitlefont":return e.subTitleFont=rt.fromJson(s),!0;case"wordsfont":return e.wordsFont=rt.fromJson(s),!0;case"effectfont":return e.effectFont=rt.fromJson(s),!0;case"timerfont":return e.timerFont=rt.fromJson(s),!0;case"directionsfont":return e.directionsFont=rt.fromJson(s),!0;case"fretboardnumberfont":return e.fretboardNumberFont=rt.fromJson(s),!0;case"numberednotationfont":return e.numberedNotationFont=rt.fromJson(s),!0;case"numberednotationgracefont":return e.numberedNotationGraceFont=rt.fromJson(s),!0;case"tablaturefont":return e.tablatureFont=rt.fromJson(s),!0;case"gracefont":return e.graceFont=rt.fromJson(s),!0;case"stafflinecolor":return e.staffLineColor=Ce.fromJson(s),!0;case"barseparatorcolor":return e.barSeparatorColor=Ce.fromJson(s),!0;case"barnumberfont":return e.barNumberFont=rt.fromJson(s),!0;case"barnumbercolor":return e.barNumberColor=Ce.fromJson(s),!0;case"fingeringfont":return e.fingeringFont=rt.fromJson(s),!0;case"inlinefingeringfont":return e.inlineFingeringFont=rt.fromJson(s),!0;case"markerfont":return e.markerFont=rt.fromJson(s),!0;case"mainglyphcolor":return e.mainGlyphColor=Ce.fromJson(s),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=Ce.fromJson(s),!0;case"scoreinfocolor":return e.scoreInfoColor=Ce.fromJson(s),!0}return!1}}class Et{static fromJson(e,t){t&&st.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",Ct.toJson(e.resources)),t.set("padding",e.padding),t.set("firstsystempaddingtop",e.firstSystemPaddingTop),t.set("systempaddingtop",e.systemPaddingTop),t.set("systempaddingbottom",e.systemPaddingBottom),t.set("lastsystempaddingbottom",e.lastSystemPaddingBottom),t.set("systemlabelpaddingleft",e.systemLabelPaddingLeft),t.set("systemlabelpaddingright",e.systemLabelPaddingRight),t.set("accoladebarpaddingright",e.accoladeBarPaddingRight),t.set("notationstaffpaddingtop",e.notationStaffPaddingTop),t.set("notationstaffpaddingbottom",e.notationStaffPaddingBottom),t.set("effectstaffpaddingtop",e.effectStaffPaddingTop),t.set("effectstaffpaddingbottom",e.effectStaffPaddingBottom),t.set("firststaffpaddingleft",e.firstStaffPaddingLeft),t.set("staffpaddingleft",e.staffPaddingLeft),t.set("systemslayoutmode",e.systemsLayoutMode),t}static setProperty(s,i,a){switch(i){case"scale":return s.scale=a,!0;case"stretchforce":return s.stretchForce=a,!0;case"layoutmode":return s.layoutMode=st.parseEnum(a,e),!0;case"staveprofile":return s.staveProfile=st.parseEnum(a,t),!0;case"barsperrow":return s.barsPerRow=a,!0;case"startbar":return s.startBar=a,!0;case"barcount":return s.barCount=a,!0;case"barcountperpartial":return s.barCountPerPartial=a,!0;case"justifylastsystem":return s.justifyLastSystem=a,!0;case"padding":return s.padding=a,!0;case"firstsystempaddingtop":return s.firstSystemPaddingTop=a,!0;case"systempaddingtop":return s.systemPaddingTop=a,!0;case"systempaddingbottom":return s.systemPaddingBottom=a,!0;case"lastsystempaddingbottom":return s.lastSystemPaddingBottom=a,!0;case"systemlabelpaddingleft":return s.systemLabelPaddingLeft=a,!0;case"systemlabelpaddingright":return s.systemLabelPaddingRight=a,!0;case"accoladebarpaddingright":return s.accoladeBarPaddingRight=a,!0;case"notationstaffpaddingtop":return s.notationStaffPaddingTop=a,!0;case"notationstaffpaddingbottom":return s.notationStaffPaddingBottom=a,!0;case"effectstaffpaddingtop":return s.effectStaffPaddingTop=a,!0;case"effectstaffpaddingbottom":return s.effectStaffPaddingBottom=a,!0;case"firststaffpaddingleft":return s.firstStaffPaddingLeft=a,!0;case"staffpaddingleft":return s.staffPaddingLeft=a,!0;case"systemslayoutmode":return s.systemsLayoutMode=st.parseEnum(a,Ke),!0}if(["resources"].indexOf(i)>=0)return Ct.fromJson(s.resources,a),!0;for(const e of["resources"])if(0===i.indexOf(e)&&Ct.setProperty(s.resources,i.substring(e.length),a))return!0;return!1}}class Ft{static fromJson(e,t){t&&st.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=st.parseEnum(s,T),!0;case"fingeringmode":return e.fingeringMode=st.parseEnum(s,k),!0;case"elements":return e.elements=new Map,st.forEach(s,((t,s)=>{e.elements.set(st.parseEnum(s,x),t)})),!0;case"rhythmmode":return e.rhythmMode=st.parseEnum(s,B),!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 Dt{static fromJson(e,t){t&&st.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 Lt{static fromJson(e,t){t&&st.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 Mt{static fromJson(e,t){t&&st.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 It{static fromJson(e,t){t&&st.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",Lt.toJson(e.vibrato)),t.set("slide",Mt.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=st.parseEnum(s,$e),!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=st.parseEnum(s,Qe),!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 Lt.fromJson(e.vibrato,s),!0;for(const i of["vibrato"])if(0===t.indexOf(i)&&Lt.setProperty(e.vibrato,t.substring(i.length),s))return!0;if(["slide"].indexOf(t)>=0)return Mt.fromJson(e.slide,s),!0;for(const i of["slide"])if(0===t.indexOf(i)&&Mt.setProperty(e.slide,t.substring(i.length),s))return!0;return!1}}class At{static fromJson(e,t){t&&st.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",Pt.toJson(e.core)),t.set("display",Et.toJson(e.display)),t.set("notation",Ft.toJson(e.notation)),t.set("importer",Dt.toJson(e.importer)),t.set("player",It.toJson(e.player)),t}static setProperty(e,t,s){if(["core",""].indexOf(t)>=0)return Pt.fromJson(e.core,s),!0;for(const i of["core",""])if(0===t.indexOf(i)&&Pt.setProperty(e.core,t.substring(i.length),s))return!0;if(["display",""].indexOf(t)>=0)return Et.fromJson(e.display,s),!0;for(const i of["display",""])if(0===t.indexOf(i)&&Et.setProperty(e.display,t.substring(i.length),s))return!0;if(["notation"].indexOf(t)>=0)return Ft.fromJson(e.notation,s),!0;for(const i of["notation"])if(0===t.indexOf(i)&&Ft.setProperty(e.notation,t.substring(i.length),s))return!0;if(["importer"].indexOf(t)>=0)return Dt.fromJson(e.importer,s),!0;for(const i of["importer"])if(0===t.indexOf(i)&&Dt.setProperty(e.importer,t.substring(i.length),s))return!0;if(["player"].indexOf(t)>=0)return It.fromJson(e.player,s),!0;for(const i of["player"])if(0===t.indexOf(i)&&It.setProperty(e.player,t.substring(i.length),s))return!0;return!1}}class Ot{constructor(){this.core=new xl,this.display=new kt,this.notation=new se,this.importer=new Tt,this.player=new vt}setSongBookModeSettings(){this.notation.notationMode=T.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=k.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(x.ParenthesisOnTiedBends,!1),this.notation.elements.set(x.TabNotesOnTiedBends,!1),this.notation.elements.set(x.ZerosOnDiveWhammys,!0)}static get songBook(){let e=new Ot;return e.setSongBookModeSettings(),e}fillFromJson(e){At.fromJson(this,e)}}class Rt{static fromJson(e,t){t&&st.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 Vt{static fromJson(e,t){t&&st.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=st.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 Ht{static fromJson(e,t){t&&st.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=st.parseEnum(s,He),!0;case"length":return e.length=s,!0}return!1}}class Gt{static fromJson(e,t){t&&st.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("alternateendings",e.alternateEndings),t.set("keysignature",e.keySignature),t.set("keysignaturetype",e.keySignatureType),t.set("isdoublebar",e.isDoubleBar),t.set("isrepeatstart",e.isRepeatStart),t.set("repeatcount",e.repeatCount),t.set("timesignaturenumerator",e.timeSignatureNumerator),t.set("timesignaturedenominator",e.timeSignatureDenominator),t.set("timesignaturecommon",e.timeSignatureCommon),t.set("isfreetime",e.isFreeTime),t.set("tripletfeel",e.tripletFeel),t.set("section",Rt.toJson(e.section)),t.set("tempoautomations",e.tempoAutomations.map((e=>Vt.toJson(e)))),null!==e.fermata){const s=new Map;t.set("fermata",s);for(const[t,i]of e.fermata)s.set(t.toString(),Ht.toJson(i))}if(t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),null!==e.directions){const s=[];t.set("directions",s);for(const t of e.directions)s.push(t)}return t}static setProperty(e,t,s){switch(t){case"alternateendings":return e.alternateEndings=s,!0;case"keysignature":return e.keySignature=st.parseEnum(s,v),!0;case"keysignaturetype":return e.keySignatureType=st.parseEnum(s,P),!0;case"isdoublebar":return e.isDoubleBar=s,!0;case"isrepeatstart":return e.isRepeatStart=s,!0;case"repeatcount":return e.repeatCount=s,!0;case"timesignaturenumerator":return e.timeSignatureNumerator=s,!0;case"timesignaturedenominator":return e.timeSignatureDenominator=s,!0;case"timesignaturecommon":return e.timeSignatureCommon=s,!0;case"isfreetime":return e.isFreeTime=s,!0;case"tripletfeel":return e.tripletFeel=st.parseEnum(s,C),!0;case"tempoautomations":e.tempoAutomations=[];for(const t of s){const s=new Q;Vt.fromJson(s,t),e.tempoAutomations.push(s)}return!0;case"fermata":return e.fermata=new Map,st.forEach(s,((t,s)=>{const i=new Ze;Ht.fromJson(i,t),e.addFermata(parseInt(s),i)})),!0;case"start":return e.start=s,!0;case"isanacrusis":return e.isAnacrusis=s,!0;case"displayscale":return e.displayScale=s,!0;case"displaywidth":return e.displayWidth=s,!0;case"directions":for(const t of s)e.addDirection(st.parseEnum(t,Ve));return!0}return["section"].indexOf(t)>=0&&(s?(e.section=new ve,Rt.fromJson(e.section,s)):e.section=null,!0)}}class Wt{static fromJson(e,t){t&&st.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 zt{static fromJson(e,t){t&&st.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=>Wt.toJson(e)))),t.set("fret",e.fret),t.set("string",e.string),t.set("showstringnumber",e.showStringNumber),t.set("octave",e.octave),t.set("tone",e.tone),t.set("percussionarticulation",e.percussionArticulation),t.set("isvisible",e.isVisible),t.set("islefthandtapped",e.isLeftHandTapped),t.set("ishammerpullorigin",e.isHammerPullOrigin),t.set("isslurdestination",e.isSlurDestination),t.set("harmonictype",e.harmonicType),t.set("harmonicvalue",e.harmonicValue),t.set("isghost",e.isGhost),t.set("isletring",e.isLetRing),t.set("ispalmmute",e.isPalmMute),t.set("isdead",e.isDead),t.set("isstaccato",e.isStaccato),t.set("slideintype",e.slideInType),t.set("slideouttype",e.slideOutType),t.set("vibrato",e.vibrato),t.set("istiedestination",e.isTieDestination),t.set("lefthandfinger",e.leftHandFinger),t.set("righthandfinger",e.rightHandFinger),t.set("trillvalue",e.trillValue),t.set("trillspeed",e.trillSpeed),t.set("durationpercent",e.durationPercent),t.set("accidentalmode",e.accidentalMode),t.set("dynamics",e.dynamics),t.set("ornament",e.ornament),e.toJson(t),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"accentuated":return e.accentuated=st.parseEnum(s,i),!0;case"bendtype":return e.bendType=st.parseEnum(s,d),!0;case"bendstyle":return e.bendStyle=st.parseEnum(s,l),!0;case"iscontinuedbend":return e.isContinuedBend=s,!0;case"bendpoints":if(s){e.bendPoints=[];for(const t of s){const s=new te;Wt.fromJson(s,t),e.addBendPoint(s)}}return!0;case"fret":return e.fret=s,!0;case"string":return e.string=s,!0;case"showstringnumber":return e.showStringNumber=s,!0;case"octave":return e.octave=s,!0;case"tone":return e.tone=s,!0;case"percussionarticulation":return e.percussionArticulation=s,!0;case"isvisible":return e.isVisible=s,!0;case"islefthandtapped":return e.isLeftHandTapped=s,!0;case"ishammerpullorigin":return e.isHammerPullOrigin=s,!0;case"isslurdestination":return e.isSlurDestination=s,!0;case"harmonictype":return e.harmonicType=st.parseEnum(s,y),!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=st.parseEnum(s,S),!0;case"slideouttype":return e.slideOutType=st.parseEnum(s,_),!0;case"vibrato":return e.vibrato=st.parseEnum(s,w),!0;case"istiedestination":return e.isTieDestination=s,!0;case"lefthandfinger":return e.leftHandFinger=st.parseEnum(s,f),!0;case"righthandfinger":return e.rightHandFinger=st.parseEnum(s,f),!0;case"trillvalue":return e.trillValue=s,!0;case"trillspeed":return e.trillSpeed=st.parseEnum(s,p),!0;case"durationpercent":return e.durationPercent=s,!0;case"accidentalmode":return e.accidentalMode=st.parseEnum(s,b),!0;case"dynamics":return e.dynamics=st.parseEnum(s,g),!0;case"ornament":return e.ornament=st.parseEnum(s,M),!0}return e.setProperty(t,s)}}class Ut{static fromJson(e,t){t&&st.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=>zt.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=>Vt.toJson(e)))),t.set("dots",e.dots),t.set("fade",e.fade),t.set("lyrics",e.lyrics),t.set("pop",e.pop),t.set("slap",e.slap),t.set("tap",e.tap),t.set("text",e.text),t.set("slashed",e.slashed),t.set("deadslapped",e.deadSlapped),t.set("brushtype",e.brushType),t.set("brushduration",e.brushDuration),t.set("tupletdenominator",e.tupletDenominator),t.set("tupletnumerator",e.tupletNumerator),t.set("iscontinuedwhammy",e.isContinuedWhammy),t.set("whammybartype",e.whammyBarType),null!==e.whammyBarPoints&&t.set("whammybarpoints",e.whammyBarPoints?.map((e=>Wt.toJson(e)))),t.set("vibrato",e.vibrato),t.set("chordid",e.chordId),t.set("gracetype",e.graceType),t.set("pickstroke",e.pickStroke),t.set("tremolospeed",e.tremoloSpeed),t.set("crescendo",e.crescendo),t.set("displaystart",e.displayStart),t.set("playbackstart",e.playbackStart),t.set("displayduration",e.displayDuration),t.set("playbackduration",e.playbackDuration),t.set("golpe",e.golpe),t.set("dynamics",e.dynamics),t.set("invertbeamdirection",e.invertBeamDirection),t.set("preferredbeamdirection",e.preferredBeamDirection),t.set("beamingmode",e.beamingMode),t.set("wahpedal",e.wahPedal),t.set("barrefret",e.barreFret),t.set("barreshape",e.barreShape),t.set("rasgueado",e.rasgueado),t.set("showtimer",e.showTimer),t.set("timer",e.timer),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"notes":e.notes=[];for(const t of s){const s=new ge;zt.fromJson(s,t),e.addNote(s)}return!0;case"isempty":return e.isEmpty=s,!0;case"whammystyle":return e.whammyStyle=st.parseEnum(s,l),!0;case"ottava":return e.ottava=st.parseEnum(s,n),!0;case"islegatoorigin":return e.isLegatoOrigin=s,!0;case"duration":return e.duration=st.parseEnum(s,p),!0;case"automations":e.automations=[];for(const t of s){const s=new Q;Vt.fromJson(s,t),e.automations.push(s)}return!0;case"dots":return e.dots=s,!0;case"fade":return e.fade=st.parseEnum(s,O),!0;case"lyrics":return e.lyrics=s,!0;case"pop":return e.pop=s,!0;case"slap":return e.slap=s,!0;case"tap":return e.tap=s,!0;case"text":return e.text=s,!0;case"slashed":return e.slashed=s,!0;case"deadslapped":return e.deadSlapped=s,!0;case"brushtype":return e.brushType=st.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=st.parseEnum(s,I),!0;case"whammybarpoints":if(s){e.whammyBarPoints=[];for(const t of s){const s=new te;Wt.fromJson(s,t),e.addWhammyBarPoint(s)}}return!0;case"vibrato":return e.vibrato=st.parseEnum(s,w),!0;case"chordid":return e.chordId=s,!0;case"gracetype":return e.graceType=st.parseEnum(s,m),!0;case"pickstroke":return e.pickStroke=st.parseEnum(s,E),!0;case"tremolospeed":return e.tremoloSpeed=st.parseEnum(s,p),!0;case"crescendo":return e.crescendo=st.parseEnum(s,u),!0;case"displaystart":return e.displayStart=s,!0;case"playbackstart":return e.playbackStart=s,!0;case"displayduration":return e.displayDuration=s,!0;case"playbackduration":return e.playbackDuration=s,!0;case"golpe":return e.golpe=st.parseEnum(s,A),!0;case"dynamics":return e.dynamics=st.parseEnum(s,g),!0;case"invertbeamdirection":return e.invertBeamDirection=s,!0;case"preferredbeamdirection":return e.preferredBeamDirection=st.parseEnum(s,Ge),!0;case"beamingmode":return e.beamingMode=st.parseEnum(s,G),!0;case"wahpedal":return e.wahPedal=st.parseEnum(s,R),!0;case"barrefret":return e.barreFret=s,!0;case"barreshape":return e.barreShape=st.parseEnum(s,V),!0;case"rasgueado":return e.rasgueado=st.parseEnum(s,H),!0;case"showtimer":return e.showTimer=s,!0;case"timer":return e.timer=s,!0}return!1}}class Xt{static fromJson(e,t){t&&st.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=>Ut.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 we;Ut.fromJson(s,t),e.addBeat(s)}return!0;case"isempty":return e.isEmpty=s,!0}return!1}}class Jt{static fromJson(e,t){t&&st.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("ratioposition",e.ratioPosition),t.set("pedaltype",e.pedalType),t}static setProperty(e,t,s){switch(t){case"ratioposition":return e.ratioPosition=s,!0;case"pedaltype":return e.pedalType=st.parseEnum(s,h),!0}return!1}}class Yt{static fromJson(e,t){t&&st.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=>Xt.toJson(e)))),t.set("similemark",e.simileMark),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t.set("sustainpedals",e.sustainPedals.map((e=>Jt.toJson(e)))),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"clef":return e.clef=st.parseEnum(s,r),!0;case"clefottava":return e.clefOttava=st.parseEnum(s,n),!0;case"voices":e.voices=[];for(const t of s){const s=new Me;Xt.fromJson(s,t),e.addVoice(s)}return!0;case"similemark":return e.simileMark=st.parseEnum(s,o),!0;case"displayscale":return e.displayScale=s,!0;case"displaywidth":return e.displayWidth=s,!0;case"sustainpedals":e.sustainPedals=[];for(const t of s){const s=new $;Jt.fromJson(s,t),e.sustainPedals.push(s)}return!0}return!1}}class qt{static fromJson(e,t){t&&st.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 jt{static fromJson(e,t){t&&st.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 Kt{static fromJson(e,t){t&&st.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=>Yt.toJson(e)))),null!==e.chords){const s=new Map;t.set("chords",s);for(const[t,i]of e.chords)s.set(t.toString(),qt.toJson(i))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",jt.toJson(e.stringTuning)),t.set("showslash",e.showSlash),t.set("shownumbered",e.showNumbered),t.set("showtablature",e.showTablature),t.set("showstandardnotation",e.showStandardNotation),t.set("ispercussion",e.isPercussion),t.set("standardnotationlinecount",e.standardNotationLineCount),t}static setProperty(e,t,s){switch(t){case"bars":e.bars=[];for(const t of s){const s=new Z;Yt.fromJson(s,t),e.addBar(s)}return!0;case"chords":return e.chords=new Map,st.forEach(s,((t,s)=>{const i=new Be;qt.fromJson(i,t),e.addChord(s,i)})),!0;case"capo":return e.capo=s,!0;case"transpositionpitch":return e.transpositionPitch=s,!0;case"displaytranspositionpitch":return e.displayTranspositionPitch=s,!0;case"showslash":return e.showSlash=s,!0;case"shownumbered":return e.showNumbered=s,!0;case"showtablature":return e.showTablature=s,!0;case"showstandardnotation":return e.showStandardNotation=s,!0;case"ispercussion":return e.isPercussion=s,!0;case"standardnotationlinecount":return e.standardNotationLineCount=s,!0}return["stringtuning"].indexOf(t)>=0&&(jt.fromJson(e.stringTuning,s),!0)}}class Qt{static fromJson(e,t){t&&st.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 $t{static fromJson(e,t){t&&st.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=st.parseEnum(s,F),!0;case"noteheadhalf":return e.noteHeadHalf=st.parseEnum(s,F),!0;case"noteheadwhole":return e.noteHeadWhole=st.parseEnum(s,F),!0;case"techniquesymbol":return e.techniqueSymbol=st.parseEnum(s,F),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=st.parseEnum(s,L),!0;case"outputmidinumber":return e.outputMidiNumber=s,!0}return!1}}class Zt{static fromJson(e,t){t&&st.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=>Kt.toJson(e)))),t.set("playbackinfo",Qt.toJson(e.playbackInfo)),t.set("color",Ce.toJson(e.color)),t.set("name",e.name),t.set("isvisibleonmultitrack",e.isVisibleOnMultiTrack),t.set("shortname",e.shortName),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("percussionarticulations",e.percussionArticulations.map((e=>$t.toJson(e)))),t}static setProperty(e,t,s){switch(t){case"staves":e.staves=[];for(const t of s){const s=new De;Kt.fromJson(s,t),e.addStaff(s)}return!0;case"color":return e.color=Ce.fromJson(s),!0;case"name":return e.name=s,!0;case"isvisibleonmultitrack":return e.isVisibleOnMultiTrack=s,!0;case"shortname":return e.shortName=s,!0;case"defaultsystemslayout":return e.defaultSystemsLayout=s,!0;case"systemslayout":return e.systemsLayout=s,!0;case"percussionarticulations":e.percussionArticulations=[];for(const t of s){const s=new ce;$t.fromJson(s,t),e.percussionArticulations.push(s)}return!0}return["playbackinfo"].indexOf(t)>=0&&(Qt.fromJson(e.playbackInfo,s),!0)}}class es{static fromJson(e,t){t&&st.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("hidedynamics",e.hideDynamics),t.set("bracketextendmode",e.bracketExtendMode),t.set("usesystemsignseparator",e.useSystemSignSeparator),t.set("globaldisplaytuning",e.globalDisplayTuning),null!==e.perTrackDisplayTuning){const s=new Map;t.set("pertrackdisplaytuning",s);for(const[t,i]of e.perTrackDisplayTuning)s.set(t.toString(),i)}if(t.set("globaldisplaychorddiagramsontop",e.globalDisplayChordDiagramsOnTop),null!==e.perTrackChordDiagramsOnTop){const s=new Map;t.set("pertrackchorddiagramsontop",s);for(const[t,i]of e.perTrackChordDiagramsOnTop)s.set(t.toString(),i)}return t.set("singletracktracknamepolicy",e.singleTrackTrackNamePolicy),t.set("multitracktracknamepolicy",e.multiTrackTrackNamePolicy),t.set("firstsystemtracknamemode",e.firstSystemTrackNameMode),t.set("othersystemstracknamemode",e.otherSystemsTrackNameMode),t.set("firstsystemtracknameorientation",e.firstSystemTrackNameOrientation),t.set("othersystemstracknameorientation",e.otherSystemsTrackNameOrientation),t}static setProperty(e,t,s){switch(t){case"hidedynamics":return e.hideDynamics=s,!0;case"bracketextendmode":return e.bracketExtendMode=st.parseEnum(s,z),!0;case"usesystemsignseparator":return e.useSystemSignSeparator=s,!0;case"globaldisplaytuning":return e.globalDisplayTuning=s,!0;case"pertrackdisplaytuning":return e.perTrackDisplayTuning=new Map,st.forEach(s,((t,s)=>{e.perTrackDisplayTuning.set(parseInt(s),t)})),!0;case"globaldisplaychorddiagramsontop":return e.globalDisplayChordDiagramsOnTop=s,!0;case"pertrackchorddiagramsontop":return e.perTrackChordDiagramsOnTop=new Map,st.forEach(s,((t,s)=>{e.perTrackChordDiagramsOnTop.set(parseInt(s),t)})),!0;case"singletracktracknamepolicy":return e.singleTrackTrackNamePolicy=st.parseEnum(s,U),!0;case"multitracktracknamepolicy":return e.multiTrackTrackNamePolicy=st.parseEnum(s,U),!0;case"firstsystemtracknamemode":return e.firstSystemTrackNameMode=st.parseEnum(s,X),!0;case"othersystemstracknamemode":return e.otherSystemsTrackNameMode=st.parseEnum(s,X),!0;case"firstsystemtracknameorientation":return e.firstSystemTrackNameOrientation=st.parseEnum(s,J),!0;case"othersystemstracknameorientation":return e.otherSystemsTrackNameOrientation=st.parseEnum(s,J),!0}return!1}}class ts{static fromJson(e,t){t&&st.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=>Gt.toJson(e)))),t.set("tracks",e.tracks.map((e=>Zt.toJson(e)))),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("stylesheet",es.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 ne;Gt.fromJson(s,t),e.addMasterBar(s)}return!0;case"tracks":e.tracks=[];for(const t of s){const s=new Le;Zt.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&&(es.fromJson(e.stylesheet,s),!0)}}class ss{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=ss.scoreToJsObject(e);return JSON.stringify(t,ss.jsonReplacer)}static jsonToScore(e,t){return ss.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return ts.toJson(e)}static jsObjectToScore(e,t){let s=new Ne;return ts.fromJson(s,e),s.finish(t??new Ot),s}static settingsToJson(e){let t=ss.settingsToJsObject(e);return JSON.stringify(t,ss.jsonReplacer)}static jsonToSettings(e){return ss.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return At.toJson(e)}static jsObjectToSettings(e){let t=new Ot;return At.fromJson(t,e),t}static jsObjectToMidiFile(e){let t=new ot;return st.forEach(e,((e,s)=>{switch(s){case"division":t.division=e;break;case"tracks":for(let s of e){let e=ss.jsObjectToMidiTrack(s);t.tracks.push(e)}}})),t}static jsObjectToMidiTrack(e){let t=new nt;return st.forEach(e,((e,s)=>{if("events"===s)for(let s of e){let e=ss.jsObjectToMidiEvent(s);t.events.push(e)}})),t}static jsObjectToMidiEvent(e){let t=st.getValue(e,"track"),i=st.getValue(e,"tick"),a=st.getValue(e,"type");switch(a){case je.TimeSignature:return new lt(t,i,st.getValue(e,"numerator"),st.getValue(e,"denominatorIndex"),st.getValue(e,"midiClocksPerMetronomeClick"),st.getValue(e,"thirdySecondNodesInQuarter"));case je.AlphaTabRest:return new ut(t,i,st.getValue(e,"channel"));case je.AlphaTabMetronome:return new ct(t,i,st.getValue(e,"metronomeNumerator"),st.getValue(e,"metronomeDurationInTicks"),st.getValue(e,"metronomeDurationInMilliseconds"));case je.NoteOn:return new gt(t,i,st.getValue(e,"channel"),st.getValue(e,"noteKey"),st.getValue(e,"noteVelocity"));case je.NoteOff:return new mt(t,i,st.getValue(e,"channel"),st.getValue(e,"noteKey"),st.getValue(e,"noteVelocity"));case je.ControlChange:return new ft(t,i,st.getValue(e,"channel"),st.getValue(e,"controller"),st.getValue(e,"value"));case je.ProgramChange:return new yt(t,i,st.getValue(e,"channel"),st.getValue(e,"program"));case je.TempoChange:return new bt(i,st.getValue(e,"microSecondsPerQuarterNote"));case je.PitchBend:return new St(t,i,st.getValue(e,"channel"),st.getValue(e,"value"));case je.PerNotePitchBend:return new _t(t,i,st.getValue(e,"channel"),st.getValue(e,"noteKey"),st.getValue(e,"value"));case je.EndOfTrack:return new wt(t,i)}throw new j(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(ss.midiTrackToJsObject(t));return t.set("tracks",s),t}static midiTrackToJsObject(e){const t=new Map,s=[];for(let t of e.events)s.push(ss.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 je.TimeSignature:t.set("numerator",e.numerator),t.set("denominatorIndex",e.denominatorIndex),t.set("midiClocksPerMetronomeClick",e.midiClocksPerMetronomeClick),t.set("thirdySecondNodesInQuarter",e.thirtySecondNodesInQuarter);break;case je.AlphaTabRest:t.set("channel",e.channel);break;case je.AlphaTabMetronome:t.set("metronomeNumerator",e.metronomeNumerator),t.set("metronomeDurationInMilliseconds",e.metronomeDurationInMilliseconds),t.set("metronomeDurationInTicks",e.metronomeDurationInTicks);break;case je.NoteOn:case je.NoteOff:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("noteVelocity",e.noteVelocity);break;case je.ControlChange:t.set("channel",e.channel),t.set("controller",e.controller),t.set("value",e.value);break;case je.ProgramChange:t.set("channel",e.channel),t.set("program",e.program);break;case je.TempoChange:t.set("microSecondsPerQuarterNote",e.microSecondsPerQuarterNote);break;case je.PitchBend:t.set("channel",e.channel),t.set("value",e.value);break;case je.PerNotePitchBend:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("value",e.value);case je.EndOfTrack:}return t}}var is,as,rs,ns=Object.freeze({__proto__:null,get AccentuationType(){return i},get AccidentalType(){return Xe},Automation:Q,get AutomationType(){return a},Bar:Z,get BarreShape(){return V},Beat:we,get BeatBeamingMode(){return G},BendPoint:te,get BendStyle(){return l},get BendType(){return d},get BracketExtendMode(){return z},get BrushType(){return c},Chord:Be,get Clef(){return r},Color:Ce,get CrescendoType(){return u},get Duration(){return p},get DynamicValue(){return g},get FadeType(){return O},Fermata:Ze,get FermataType(){return He},get Fingers(){return f},Font:rt,get FontStyle(){return Je},get FontWeight(){return Ye},get GraceType(){return m},get HarmonicType(){return y},InstrumentArticulation:ce,JsonConverter:ss,get KeySignature(){return v},get KeySignatureType(){return P},Lyrics:ke,MasterBar:ne,get MusicFontSymbol(){return F},Note:ge,get NoteAccidentalMode(){return b},get NoteOrnament(){return M},get Ottavia(){return n},get PickStroke(){return E},PlaybackInformation:Ee,get Rasgueado(){return H},RenderStylesheet:Te,RepeatGroup:xe,Score:Ne,Section:ve,get SimileMark(){return o},get SlideInType(){return S},get SlideOutType(){return _},Staff:De,SustainPedalMarker:$,get SustainPedalMarkerType(){return h},Track:Le,get TrackNameMode(){return X},get TrackNameOrientation(){return J},get TrackNamePolicy(){return U},get TripletFeel(){return C},Tuning:Fe,TupletGroup:me,get VibratoType(){return w},Voice:Me,get WahPedal(){return R},get WhammyType(){return I}});class os extends q{get name(){return"Guitar Pro 3-5"}constructor(){super(),this._versionNumber=0,this._globalTripletFeel=C.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._beatTextChunksByTrack=new Map,this._directionLookup=new Map}readScore(){if(this._directionLookup.clear(),this.readVersion(),this._score=new Ne,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=hs.gpReadBool(this.data)?C.Triplet8th:C.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=hs.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=Ae.readInt32LE(this.data),this._versionNumber>=510&&hs.gpReadBool(this.data),Ae.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.readDirection(Ve.TargetCoda),this.readDirection(Ve.TargetDoubleCoda),this.readDirection(Ve.TargetSegno),this.readDirection(Ve.TargetSegnoSegno),this.readDirection(Ve.TargetFine),this.readDirection(Ve.JumpDaCapo),this.readDirection(Ve.JumpDaCapoAlCoda),this.readDirection(Ve.JumpDaCapoAlDoubleCoda),this.readDirection(Ve.JumpDaCapoAlFine),this.readDirection(Ve.JumpDalSegno),this.readDirection(Ve.JumpDalSegnoAlCoda),this.readDirection(Ve.JumpDalSegnoAlDoubleCoda),this.readDirection(Ve.JumpDalSegnoAlFine),this.readDirection(Ve.JumpDalSegnoSegno),this.readDirection(Ve.JumpDalSegnoSegnoAlCoda),this.readDirection(Ve.JumpDalSegnoSegnoAlDoubleCoda),this.readDirection(Ve.JumpDalSegnoSegnoAlFine),this.readDirection(Ve.JumpDaCoda),this.readDirection(Ve.JumpDaDoubleCoda),this.data.skip(4)),this._barCount=Ae.readInt32LE(this.data),this._trackCount=Ae.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0){const e=Q.buildTempoAutomation(!1,0,this._score.tempo,2);e.text=this._score.tempoLabel,this._score.masterBars[0].tempoAutomations.push(e)}return this._score.finish(this.settings),this._lyrics&&this._lyricsTrack>=0&&this._score.tracks[this._lyricsTrack].applyLyrics(this._lyrics),this._score}readDirection(e){let t,s=Ae.readInt16LE(this.data);-1!==s&&(s--,this._directionLookup.has(s)?t=this._directionLookup.get(s):(t=[],this._directionLookup.set(s,t)),t.push(e))}readVersion(){let e=hs.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(os.VersionString))throw new K("Unsupported format");e=e.substr(os.VersionString.length+1);let t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*parseInt(e.substr(0,t))+parseInt(e.substr(t+1)),re.debug(this.name,"Guitar Pro version "+e+" detected")}readScoreInformation(){this._score.title=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding);let e=Ae.readInt32LE(this.data),t="";for(let s=0;s<e;s++)s>0&&(t+="\r\n"),t+=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding)?.toString();this._score.notices=t}readLyrics(){this._lyrics=[],this._lyricsTrack=Ae.readInt32LE(this.data)-1;for(let e=0;e<5;e++){let e=new ke;e.startBar=Ae.readInt32LE(this.data)-1,e.text=hs.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(30);for(let e=0;e<10;e++)hs.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){let t=new Ee;t.primaryChannel=e,t.secondaryChannel=e,t.program=Ae.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 ne,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 ve;e.text=hs.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",hs.gpReadColor(this.data,!1),t.section=e}if(64&s?(t.keySignature=Ae.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=C.Triplet8th;break;case 2:t.tripletFeel=C.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=!!(128&s);const i=this._score.masterBars.length;if(this._directionLookup.has(i))for(const e of this._directionLookup.get(i))t.addDirection(e);this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){let e=new Le;e.ensureStaveCount(1),this._score.addTrack(e);let t=e.staves[0],s=this.data.readByte();e.name=hs.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),1&s&&(t.isPercussion=!0),this._versionNumber>=500&&(e.isVisibleOnMultiTrack=!!(8&s)),null===this._score.stylesheet.perTrackDisplayTuning&&(this._score.stylesheet.perTrackDisplayTuning=new Map),this._score.stylesheet.perTrackDisplayTuning.set(e.index,!!(128&s));let i=Ae.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){let t=Ae.readInt32LE(this.data);i>e&&a.push(t)}t.stringTuning.tunings=a;let r=Ae.readInt32LE(this.data),n=Ae.readInt32LE(this.data)-1,o=Ae.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,Y.isGuitar(i.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=i}if(t.capo=Ae.readInt32LE(this.data),e.color=hs.gpReadColor(this.data,!1),this._versionNumber>=500){const s=this.data.readByte();t.showTablature=!!(1&s),t.showStandardNotation=!!(2&s);const i=!!(100&s);null===this._score.stylesheet.perTrackChordDiagramsOnTop&&(this._score.stylesheet.perTrackChordDiagramsOnTop=new Map),this._score.stylesheet.perTrackChordDiagramsOnTop.set(e.index,i),this.data.readByte(),this.data.skip(43)}this._versionNumber>=510&&(this.data.skip(4),hs.gpReadStringIntByte(this.data,this.settings.importer.encoding),hs.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 Z,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=Ae.readInt32LE(this.data);if(0===s)return;let i=new Me;t.addVoice(i);for(let a=0;a<s;a++)this.readBeat(e,t,i)}readBeat(e,t,s){let i=new we,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),Ae.readSInt8(this.data)){case-2:i.duration=p.Whole;break;case-1:i.duration=p.Half;break;case 0:i.duration=p.Quarter;break;case 1:i.duration=p.Eighth;break;case 2:i.duration=p.Sixteenth;break;case 3:i.duration=p.ThirtySecond;break;case 4:i.duration=p.SixtyFourth;break;default:i.duration=p.Quarter}if(32&a)switch(i.tupletNumerator=Ae.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=hs.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const s=new ke;s.text=t.trim(),s.finish(!0);const i=[];for(let e=s.chunks.length-1;e>=0;e--)i.push(s.chunks[e]);this._beatTextChunksByTrack.set(e.index,i)}else i.text=t}let o=y.None;8&a&&(o=this.readBeatEffects(i)),16&a&&this.readMixTableChange(i);let h=this.data.readByte();for(let a=6;a>=0;a--)if(h&1<<a&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,s,i,6-a);o!==y.None&&(r.harmonicType=o,r.harmonicType===y.Natural&&(r.harmonicValue=le.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){const e=Ae.readInt16LE(this.data);if(1&e&&i.index>0&&(s.beats[i.index-1].beamingMode=G.ForceSplitToNext),2&e&&(i.preferredBeamDirection=Ge.Down),4&e&&i.index>0&&(s.beats[i.index-1].beamingMode=G.ForceMergeWithNext),8&e&&(i.preferredBeamDirection=Ge.Up),16&e&&(i.ottava=n._8va),32&e&&(i.ottava=n._8vb),64&e&&(i.ottava=n._15ma),256&e&&(i.ottava=n._15mb),2048&e){const e=0!=this.data.readByte();i.index>0&&e&&(s.beats[i.index-1].beamingMode=G.ForceSplitOnSecondaryToNext)}}r&&!i.isRest&&this._beatTextChunksByTrack.has(e.index)&&this._beatTextChunksByTrack.get(e.index).length>0&&(i.lyrics=[this._beatTextChunksByTrack.get(e.index).pop()])}readChord(e){let t=new Be,s=le.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=hs.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Ae.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Ae.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=hs.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Ae.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Ae.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=hs.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=Ae.readInt32LE(this.data);for(let s=0;s<6;s++){let i=Ae.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=hs.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=Ae.readInt32LE(this.data),t.firstFret>0)for(let i=0;i<s;i++){let s=Ae.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}}t.name&&(e.chordId=s,e.voice.bar.staff.addChord(e.chordId,t))}readBeatEffects(e){let t=this.data.readByte(),s=0;if(this._versionNumber>=400&&(s=this.data.readByte()),16&t&&(e.fade=O.FadeIn),(this._versionNumber<400&&1&t||2&t)&&(e.vibrato=w.Slight),1&s&&(e.rasgueado=H.Ii),32&t&&this._versionNumber>=400){switch(Ae.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(Ae.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=os.toStrokeValue(t)):s>0&&(e.brushType=c.BrushDown,e.brushDuration=os.toStrokeValue(s))}if(2&s)switch(Ae.readSInt8(this.data)){case 0:e.pickStroke=E.None;break;case 1:e.pickStroke=E.Up;break;case 2:e.pickStroke=E.Down}if(this._versionNumber<400){if(4&t)return y.Natural;if(8&t)return y.Artificial}return y.None}readTremoloBarEffect(e){this.data.readByte(),Ae.readInt32LE(this.data);let t=Ae.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new te(0,0);t.offset=Ae.readInt32LE(this.data),t.value=Ae.readInt32LE(this.data)/os.BendStep|0,hs.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 ls;t.instrument=Ae.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=Ae.readSInt8(this.data),t.balance=Ae.readSInt8(this.data);let s=Ae.readSInt8(this.data),i=Ae.readSInt8(this.data),r=Ae.readSInt8(this.data),n=Ae.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=hs.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=Ae.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=Ae.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500){const t=Ae.readSInt8(this.data);t>=100?e.wahPedal=R.Closed:t>=0&&(e.wahPedal=R.Open)}if(this._versionNumber>=510&&(hs.gpReadStringIntByte(this.data,this.settings.importer.encoding),hs.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){let s=new Q;s.isLinear=!0,s.type=a.Volume,s.value=t.volume,e.automations.push(s)}if(t.balance>=0){let s=new Q;s.isLinear=!0,s.type=a.Balance,s.value=t.balance,e.automations.push(s)}if(t.instrument>=0){let s=new Q;s.isLinear=!0,s.type=a.Instrument,s.value=t.instrument,e.automations.push(s)}if(t.tempo>=0){let s=new Q;s.isLinear=!0,s.type=a.Tempo,s.value=t.tempo,e.automations.push(s),e.voice.bar.masterBar.tempoAutomations.push(s)}}readNote(e,t,s,a,r){let n=new ge;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=Ae.readSInt8(this.data);n.dynamics=this.toDynamicValue(e),a.dynamics=n.dynamics}32&o&&(n.fret=Ae.readSInt8(this.data)),128&o&&(n.leftHandFinger=Ae.readSInt8(this.data),n.rightHandFinger=Ae.readSInt8(this.data));let h=!1;if(this._versionNumber>=500){1&o&&(n.durationPercent=Ae.readFloat64BE(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=Fe.defaultAccidentals[n.realValueWithoutHarmonic%12];"#"===e?n.accidentalMode=b.ForceFlat:"b"===e&&(n.accidentalMode=b.ForceSharp)}return n}toDynamicValue(e){switch(e){case 1:return g.PPP;case 2:return g.PP;case 3:return g.P;case 4:return g.MP;case 5:return g.MF;case 6:default:return g.F;case 7:return g.FF;case 8:return g.FFF}}readNoteEffects(e,t,s,i){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=_.Shift),16&r&&this.readArtificialHarmonic(i),32&r&&this.readTrill(i),i.isLetRing=!!(8&a),i.isHammerPullOrigin=!!(2&a),64&r&&(i.vibrato=w.Slight),i.isPalmMute=!!(2&r),i.isStaccato=!!(1&r)}readBend(e){this.data.readByte(),Ae.readInt32LE(this.data);let t=Ae.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new te(0,0);t.offset=Ae.readInt32LE(this.data),t.value=Ae.readInt32LE(this.data)/os.BendStep|0,hs.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){let s=new we,i=new ge;switch(i.string=t.string,i.fret=Ae.readSInt8(this.data),s.duration=p.ThirtySecond,s.dynamics=this.toDynamicValue(Ae.readSInt8(this.data)),Ae.readSInt8(this.data)){case 0:case 2:break;case 1:i.slideOutType=_.Legato,i.slideTarget=t;break;case 3:i.isHammerPullOrigin=!0}if(i.dynamics=s.dynamics,this.data.skip(1),this._versionNumber<500)s.graceType=m.BeforeBeat;else{let e=this.data.readByte();i.isDead=!!(1&e),s.graceType=2&e?m.OnBeat:m.BeforeBeat}e.addGraceBeat(s),s.addNote(i)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=p.Eighth;break;case 2:e.tremoloSpeed=p.Sixteenth;break;case 3:e.tremoloSpeed=p.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){let t=Ae.readSInt8(this.data);1&t?e.slideOutType=_.Shift:2&t?e.slideOutType=_.Legato:4&t?e.slideOutType=_.OutDown:8&t&&(e.slideOutType=_.OutUp),16&t?e.slideInType=S.IntoFromBelow:32&t&&(e.slideInType=S.IntoFromAbove)}else{switch(Ae.readSInt8(this.data)){case 1:e.slideOutType=_.Shift;break;case 2:e.slideOutType=_.Legato;break;case 3:e.slideOutType=_.OutDown;break;case 4:e.slideOutType=_.OutUp;break;case-1:e.slideInType=S.IntoFromBelow;break;case-2:e.slideInType=S.IntoFromAbove}}}readArtificialHarmonic(e){let t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=y.Natural,e.harmonicValue=le.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=y.Artificial;break;case 3:e.harmonicType=y.Tap,e.harmonicValue=le.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=y.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=y.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=y.Natural;break;case 3:e.harmonicType=y.Tap;break;case 4:e.harmonicType=y.Pinch;break;case 5:e.harmonicType=y.Semi;break;case 15:case 17:case 22:e.harmonicType=y.Artificial}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=p.Sixteenth;break;case 2:e.trillSpeed=p.ThirtySecond;break;case 3:e.trillSpeed=p.SixtyFourth}}}os.VersionString="FICHIER GUITAR PRO ",os.BendStep=25;class hs{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 Ce(s,i,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),hs.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return hs.gpReadString(e,Ae.readInt32LE(e),t)}static gpReadStringIntByte(e,t){let s=Ae.readInt32LE(e)-1;return e.readByte(),hs.gpReadString(e,s,t)}static gpReadString(e,t,s){let i=new Uint8Array(t);return e.read(i,0,i.length),Ae.toString(i,s)}static gpWriteString(e,t){const s=Ae.stringToBytes(t);e.writeByte(t.length),e.write(s,0,s.length)}static gpReadStringByteLength(e,t,s){let i=e.readByte(),a=hs.gpReadString(e,i,s);return i<t&&e.skip(t-i),a}}class ls{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class ds{constructor(){this.x=0,this.y=0,this.w=0,this.h=0}scaleWith(e){this.x*=e,this.y*=e,this.w*=e,this.h*=e}}!function(e){e[e.Boolean=0]="Boolean",e[e.Integer=1]="Integer",e[e.Float=2]="Float",e[e.String=3]="String",e[e.Point=4]="Point",e[e.Size=5]="Size",e[e.Rectangle=6]="Rectangle",e[e.Color=7]="Color"}(is||(is={}));class cs{constructor(e){this._types=new Map,this.raw=new Map,e&&this.read(e)}read(e){let t=Oe.fromBuffer(e),s=Ae.readInt32BE(t);for(let e=0;e<s;e++){let e=hs.gpReadString(t,t.readByte(),"utf-8"),s=t.readByte();switch(this._types.set(e,s),s){case is.Boolean:let s=1===t.readByte();this.addValue(e,s);break;case is.Integer:let i=Ae.readInt32BE(t);this.addValue(e,i);break;case is.Float:let a=Ae.readFloat32BE(t);this.addValue(e,a);break;case is.String:let r=hs.gpReadString(t,Ae.readInt16BE(t),"utf-8");this.addValue(e,r);break;case is.Point:let n=Ae.readInt32BE(t),o=Ae.readInt32BE(t);this.addValue(e,new te(n,o));break;case is.Size:let h=Ae.readInt32BE(t),l=Ae.readInt32BE(t);this.addValue(e,new te(h,l));break;case is.Rectangle:let d=new ds;d.x=Ae.readInt32BE(t),d.y=Ae.readInt32BE(t),d.w=Ae.readInt32BE(t),d.h=Ae.readInt32BE(t),this.addValue(e,d);break;case is.Color:let c=hs.gpReadColor(t,!0);this.addValue(e,c)}}}apply(e){for(const[t,s]of this.raw)switch(t){case"StandardNotation/hideDynamics":e.stylesheet.hideDynamics=s;break;case"System/bracketExtendMode":e.stylesheet.bracketExtendMode=s;break;case"Global/useSystemSignSeparator":e.stylesheet.useSystemSignSeparator=s;break;case"Global/DisplayTuning":e.stylesheet.globalDisplayTuning=s;break;case"Global/DrawChords":e.stylesheet.globalDisplayChordDiagramsOnTop=s;break;case"System/showTrackNameSingle":s||(e.stylesheet.singleTrackTrackNamePolicy=U.Hidden);break;case"System/showTrackNameMulti":s||(e.stylesheet.multiTrackTrackNamePolicy=U.Hidden);break;case"System/trackNameModeSingle":if(e.stylesheet.singleTrackTrackNamePolicy!==U.Hidden)switch(s){case 0:case 1:e.stylesheet.singleTrackTrackNamePolicy=U.FirstSystem;break;case 2:e.stylesheet.singleTrackTrackNamePolicy=U.AllSystems}break;case"System/trackNameModeMulti":if(e.stylesheet.multiTrackTrackNamePolicy!==U.Hidden)switch(s){case 0:case 1:e.stylesheet.multiTrackTrackNamePolicy=U.FirstSystem;break;case 2:e.stylesheet.multiTrackTrackNamePolicy=U.AllSystems}break;case"System/shortTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameMode=s?X.ShortName:X.FullName;break;case"System/shortTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameMode=s?X.ShortName:X.FullName;break;case"System/horizontalTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameOrientation=s?J.Horizontal:J.Vertical;break;case"System/horizontalTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameOrientation=s?J.Horizontal:J.Vertical}}addValue(e,t,s){this.raw.set(e,t),void 0!==s&&this._types.set(e,s)}writeTo(e){Ae.writeInt32BE(e,this.raw.size);for(const[t,s]of this.raw){const i=this.getDataType(t,s);switch(hs.gpWriteString(e,t),e.writeByte(i),i){case is.Boolean:e.writeByte(s?1:0);break;case is.Integer:Ae.writeInt32BE(e,s);break;case is.Float:Ae.writeFloat32BE(e,s);break;case is.String:const t=Ae.stringToBytes(s);Ae.writeInt16BE(e,t.length),e.write(t,0,t.length);break;case is.Point:case is.Size:Ae.writeInt32BE(e,s.offset),Ae.writeInt32BE(e,s.value);break;case is.Rectangle:Ae.writeInt32BE(e,s.x),Ae.writeInt32BE(e,s.y),Ae.writeInt32BE(e,s.w),Ae.writeInt32BE(e,s.h);break;case is.Color:e.writeByte(s.r),e.writeByte(s.g),e.writeByte(s.b),e.writeByte(s.a)}}}getDataType(e,t){if(this._types.has(e))return this._types.get(e);const i=typeof t;switch(typeof t){case"string":return is.String;case"number":return t==(0|t)?is.Integer:is.Float;case"object":if(t instanceof te)return is.Point;if(t instanceof ds)return is.Rectangle;if(t instanceof Ce)return is.Color}throw new j(s.General,`Unknown value type in BinaryStylesheet: ${i}`)}static writeForScore(e){const t=new cs;switch(t.addValue("StandardNotation/hideDynamics",e.stylesheet.hideDynamics,is.Boolean),t.addValue("System/bracketExtendMode",e.stylesheet.bracketExtendMode,is.Integer),t.addValue("Global/useSystemSignSeparator",e.stylesheet.useSystemSignSeparator,is.Boolean),t.addValue("Global/DisplayTuning",e.stylesheet.globalDisplayTuning,is.Boolean),t.addValue("Global/DrawChords",e.stylesheet.globalDisplayChordDiagramsOnTop,is.Boolean),e.stylesheet.singleTrackTrackNamePolicy){case U.Hidden:t.addValue("System/showTrackNameSingle",!1,is.Boolean);break;case U.FirstSystem:t.addValue("System/trackNameModeSingle",0,is.Integer);break;case U.AllSystems:t.addValue("System/trackNameModeSingle",2,is.Integer)}switch(e.stylesheet.multiTrackTrackNamePolicy){case U.Hidden:t.addValue("System/trackNameModeMulti",!1,is.Boolean);break;case U.FirstSystem:t.addValue("System/trackNameModeMulti",0,is.Integer);break;case U.AllSystems:t.addValue("System/trackNameModeMulti",2,is.Integer)}switch(e.stylesheet.firstSystemTrackNameMode){case X.FullName:t.addValue("System/shortTrackNameOnFirstSystem",!1,is.Boolean);break;case X.ShortName:t.addValue("System/shortTrackNameOnFirstSystem",!0,is.Boolean)}switch(e.stylesheet.otherSystemsTrackNameMode){case X.FullName:t.addValue("System/shortTrackNameOnOtherSystems",!1,is.Boolean);break;case X.ShortName:t.addValue("System/shortTrackNameOnOtherSystems",!0,is.Boolean)}switch(e.stylesheet.firstSystemTrackNameOrientation){case J.Horizontal:t.addValue("System/horizontalTrackNameOnFirstSystem",!0,is.Boolean);break;case J.Vertical:t.addValue("System/horizontalTrackNameOnFirstSystem",!1,is.Boolean)}switch(e.stylesheet.otherSystemsTrackNameOrientation){case J.Horizontal:t.addValue("System/horizontalTrackNameOnOtherSystems",!0,is.Boolean);break;case J.Vertical:t.addValue("System/horizontalTrackNameOnOtherSystems",!1,is.Boolean)}const s=Oe.withCapacity(128);return t.writeTo(s),s.toArray()}}!function(e){e[e.None=0]="None",e[e.Element=1]="Element",e[e.Text=2]="Text",e[e.CDATA=3]="CDATA",e[e.Document=4]="Document",e[e.DocumentType=5]="DocumentType"}(as||(as={}));class us{constructor(){this.nodeType=as.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!==as.Element&&e.nodeType!==as.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===as.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===as.Element&&t.localName===e)return t;return null}addElement(e){const t=new us;return t.nodeType=as.Element,t.localName=e,this.addChild(t),t}get innerText(){if(this.nodeType===as.Element||this.nodeType===as.Document){if(this.firstElement&&this.firstElement.nodeType===as.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 us;t.nodeType=as.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new us;t.nodeType=as.CDATA,t.value=e,this.childNodes=[t]}}class ps extends j{constructor(e,t,i){super(s.Format,e),this.pos=0,this.xml=t,this.pos=i,Object.setPrototypeOf(this,ps.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"}(rs||(rs={}));class gs{static parse(e,t,s){let i=e.charCodeAt(t),a=rs.Begin,r=rs.Begin,n=0,o="",h=rs.Begin,l=null,d=null,c=0,u=0;for(;t<e.length;){switch(i=e.charCodeAt(t),a){case rs.IgnoreSpaces:switch(i){case gs.CharCodeLF:case gs.CharCodeCR:case gs.CharCodeTab:case gs.CharCodeSpace:break;default:a=r;continue}break;case rs.Begin:if(i!==gs.CharCodeLowerThan){n=t,a=rs.Pcdata;continue}a=rs.IgnoreSpaces,r=rs.BeginNode;break;case rs.Pcdata:if(i===gs.CharCodeLowerThan){o+=e.substr(n,t-n);let i=new us;i.nodeType=as.Text,i.value=o,o="",s.addChild(i),a=rs.IgnoreSpaces,r=rs.BeginNode}else i===gs.CharCodeAmp&&(o+=e.substr(n,t-n),a=rs.Escape,h=rs.Pcdata,n=t+1);break;case rs.Cdata:if(i===gs.CharCodeBrackedClose&&e.charCodeAt(t+1)===gs.CharCodeBrackedClose&&e.charCodeAt(t+2)===gs.CharCodeGreaterThan){let i=new us;i.nodeType=as.CDATA,i.value=e.substr(n,t-n),s.addChild(i),t+=2,a=rs.Begin}break;case rs.BeginNode:switch(i){case gs.CharCodeExclamation:if(e.charCodeAt(t+1)===gs.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new ps("Expected <![CDATA[",e,t);t+=5,a=rs.Cdata,n=t+1}else if(e.charCodeAt(t+1)===gs.CharCodeUpperD||e.charCodeAt(t+1)===gs.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new ps("Expected <!DOCTYPE",e,t);t+=8,a=rs.Doctype,n=t+1}else{if(e.charCodeAt(t+1)!==gs.CharCodeMinus||e.charCodeAt(t+2)!==gs.CharCodeMinus)throw new ps("Expected \x3c!--",e,t);t+=2,a=rs.Comment,n=t+1}break;case gs.CharCodeQuestion:a=rs.Header,n=t;break;case gs.CharCodeSlash:if(!s)throw new ps("Expected node name",e,t);n=t+1,a=rs.IgnoreSpaces,r=rs.Close;break;default:a=rs.TagName,n=t;continue}break;case rs.TagName:if(!gs.isValidChar(i)){if(t===n)throw new ps("Expected node name",e,t);l=new us,l.nodeType=as.Element,l.localName=e.substr(n,t-n),s.addChild(l),a=rs.IgnoreSpaces,r=rs.Body;continue}break;case rs.Body:switch(i){case gs.CharCodeSlash:a=rs.WaitEnd;break;case gs.CharCodeGreaterThan:a=rs.Childs;break;default:a=rs.AttribName,n=t;continue}break;case rs.AttribName:if(!gs.isValidChar(i)){if(n===t)throw new ps("Expected attribute name",e,t);if(d=e.substr(n,t-n),l.attributes.has(d))throw new ps(`Duplicate attribute [${d}]`,e,t);a=rs.IgnoreSpaces,r=rs.Equals;continue}break;case rs.Equals:if(i!==gs.CharCodeEquals)throw new ps("Expected =",e,t);a=rs.IgnoreSpaces,r=rs.AttvalBegin;break;case rs.AttvalBegin:switch(i){case gs.CharCodeDoubleQuote:case gs.CharCodeSingleQuote:o="",a=rs.AttribVal,n=t+1,u=i}break;case rs.AttribVal:if(i===gs.CharCodeAmp)o+=e.substr(n,t-n),a=rs.Escape,h=rs.AttribVal,n=t+1;else if(i===u){o+=e.substr(n,t-n);let s=o;o="",l.attributes.set(d,s),a=rs.IgnoreSpaces,r=rs.Body}break;case rs.Childs:n=t=gs.parse(e,t,l),a=rs.Begin;break;case rs.WaitEnd:if(i!==gs.CharCodeGreaterThan)throw new ps("Expected >",e,t);a=rs.Begin;break;case rs.WaitEndRet:if(i===gs.CharCodeGreaterThan)return t;throw new ps("Expected >",e,t);case rs.Close:if(!gs.isValidChar(i)){if(n===t)throw new ps("Expected node name",e,t);if(e.substr(n,t-n)!==s.localName)throw new ps("Expected </"+s.localName+">",e,t);a=rs.IgnoreSpaces,r=rs.WaitEndRet;continue}break;case rs.Comment:i===gs.CharCodeMinus&&e.charCodeAt(t+1)===gs.CharCodeMinus&&e.charCodeAt(t+2)===gs.CharCodeGreaterThan&&(t+=2,a=rs.Begin);break;case rs.Doctype:if(i===gs.CharCodeBrackedOpen)c++;else if(i===gs.CharCodeBrackedClose)c--;else if(i===gs.CharCodeGreaterThan&&0===c){let i=new us;i.nodeType=as.DocumentType,i.value=e.substr(n,t-n),s.addChild(i),a=rs.Begin}break;case rs.Header:i===gs.CharCodeQuestion&&e.charCodeAt(t+1)===gs.CharCodeGreaterThan&&(t++,a=rs.Begin);break;case rs.Escape:if(i===gs.CharCodeSemi){let s=e.substr(n,t-n);if(s.charCodeAt(0)===gs.CharCodeSharp){let e=s.charCodeAt(1)===gs.CharCodeLowerX?parseInt("0"+s.substr(1,s.length-1)):parseInt(s.substr(1,s.length-1));o+=String.fromCharCode(e)}else gs.Escapes.has(s)?o+=gs.Escapes.get(s):o+=("&"+s+";")?.toString();n=t+1,a=h}else gs.isValidChar(i)||i===gs.CharCodeSharp||(o+="&",o+=e.substr(n,t-n),n=--t+1,a=h)}t++}if(a===rs.Begin&&(n=t,a=rs.Pcdata),a===rs.Pcdata){if(t!==n){o+=e.substr(n,t-n);let i=new us;i.nodeType=as.Text,i.value=o,s.addChild(i)}return t}if(a===rs.Escape&&h===rs.Pcdata){o+="&",o+=e.substr(n,t-n);let i=new us;return i.nodeType=as.Text,i.value=o,s.addChild(i),t}throw new ps("Unexpected end",e,t)}static isValidChar(e){return e>=gs.CharCodeLowerA&&e<=gs.CharCodeLowerZ||e>=gs.CharCodeUpperA&&e<=gs.CharCodeUpperZ||e>=gs.CharCode0&&e<=gs.CharCode9||e===gs.CharCodeColon||e===gs.CharCodeDot||e===gs.CharCodeUnderscore||e===gs.CharCodeMinus}}gs.CharCodeLF=10,gs.CharCodeTab=9,gs.CharCodeCR=13,gs.CharCodeSpace=32,gs.CharCodeLowerThan=60,gs.CharCodeAmp=38,gs.CharCodeBrackedClose=93,gs.CharCodeBrackedOpen=91,gs.CharCodeGreaterThan=62,gs.CharCodeExclamation=33,gs.CharCodeUpperD=68,gs.CharCodeLowerD=100,gs.CharCodeMinus=45,gs.CharCodeQuestion=63,gs.CharCodeSlash=47,gs.CharCodeEquals=61,gs.CharCodeDoubleQuote=34,gs.CharCodeSingleQuote=39,gs.CharCodeSharp=35,gs.CharCodeLowerX=120,gs.CharCodeLowerA=97,gs.CharCodeLowerZ=122,gs.CharCodeUpperA=65,gs.CharCodeUpperZ=90,gs.CharCode0=48,gs.CharCode9=57,gs.CharCodeColon=58,gs.CharCodeDot=46,gs.CharCodeUnderscore=95,gs.CharCodeSemi=59,gs.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class ms{static write(e,t,s){const i=new ms(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 as.None:break;case as.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===as.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case as.Text:e.value&&this.write(e.value);break;case as.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case as.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case as.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 fs extends us{constructor(){super(),this.nodeType=as.Document}parse(e){gs.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return ms.write(this,e,t)}}class ys{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=p.Quarter}}class bs{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return this.path+";"+this.name+";"+this.role}}class Ss{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1}parseXml(e,t){this._masterTrackAutomations=new Map,this._automationsPerTrackIdAndBarIndex=new Map,this._sustainPedalsPerTrackIdAndBarIndex=new Map,this._tracksMapping=[],this._tracksById=new Map,this._masterBars=[],this._barsOfMasterBar=[],this._voicesOfBar=new Map,this._barsById=new Map,this._voiceById=new Map,this._beatsOfVoice=new Map,this._beatById=new Map,this._rhythmOfBeat=new Map,this._rhythmById=new Map,this._notesOfBeat=new Map,this._noteById=new Map,this._tappedNotes=new Map,this._lyricsByTrack=new Map,this._soundsByTrack=new Map,this._skipApplyLyrics=!1;let s=new fs;try{s.parse(e)}catch(e){throw new K("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 K("Root node of XML was not GPIF");this.score=new Ne;for(let e of t.childNodes)if(e.nodeType===as.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===as.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===as.Element)switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null,null);break;case"Tracks":this._tracksMapping=t.innerText.split(" ");break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,s,i){for(let a of e.childNodes)if(a.nodeType===as.Element&&"Automation"===a.localName)this.parseAutomation(a,t,s,i)}parseAutomation(e,t,s,i){let a=null,r=!1,n=-1,o=0,l=0,d=null,c=0,u=null;for(let t of e.childNodes)if(t.nodeType===as.Element)switch(t.localName){case"Type":a=t.innerText;break;case"Linear":r="true"===t.innerText.toLowerCase();break;case"Bar":n=parseInt(t.innerText);break;case"Position":o=parseFloat(t.innerText);break;case"Value":if(t.firstElement&&t.firstElement.nodeType===as.CDATA)d=t.innerText;else{let e=t.innerText.split(" ");1===e.length?(l=parseFloat(e[0]),c=1):(l=parseFloat(e[0]),c=parseInt(e[1]))}break;case"Text":u=t.innerText}if(!a)return;let p=null;switch(a){case"Tempo":p=Q.buildTempoAutomation(r,o,l,c);break;case"Sound":d&&s&&s.has(d)&&(p=Q.buildInstrumentAutomation(r,o,s.get(d).program));break;case"SustainPedal":if(i){let e;i.has(n)?e=i.get(n):(e=[],i.set(n,e));const t=new $;switch(t.ratioPosition=o,c){case 1:t.pedalType=h.Down;break;case 3:t.pedalType=h.Up}e.push(t)}}p&&(u&&(p.text=u),n>=0&&(t.has(n)||t.set(n,[]),t.get(n).push(p)))}parseTracksNode(e){for(let t of e.childNodes)if(t.nodeType===as.Element&&"Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;let t=new Le;t.ensureStaveCount(1),t.staves[0].showStandardNotation=!0;let s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===as.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 Ce(s,i,a,255)}break;case"Instrument":let a=i.getAttribute("ref");(a.endsWith("-gs")||a.endsWith("GrandStaff"))&&(t.ensureStaveCount(2),t.staves[1].showStandardNotation=!0);break;case"InstrumentSet":this.parseInstrumentSet(t,i);break;case"NotationPatch":this.parseNotationPatch(t,i);break;case"ShortName":t.shortName=i.innerText;break;case"SystemsDefautLayout":t.defaultSystemsLayout=parseInt(i.innerText);break;case"SystemsLayout":t.systemsLayout=i.innerText.split(" ").map((e=>parseInt(e)));break;case"Lyrics":this.parseLyrics(s,i);break;case"Properties":this.parseTrackProperties(t,i);break;case"GeneralMidi":case"MidiConnection":case"MIDISettings":this.parseGeneralMidi(t,i);break;case"Sounds":this.parseSounds(s,t,i);break;case"PlaybackState":let r=i.innerText;t.playbackInfo.isSolo="Solo"===r,t.playbackInfo.isMute="Mute"===r;break;case"PartSounding":this.parsePartSounding(t,i);break;case"Staves":this.parseStaves(t,i);break;case"Transpose":this.parseTranspose(t,i);break;case"RSE":this.parseRSE(t,i);break;case"Automations":this.parseTrackAutomations(s,i)}this._tracksById.set(s,t)}parseTrackAutomations(e,t){const s=new Map;this._automationsPerTrackIdAndBarIndex.set(e,s);const i=new Map;this._sustainPedalsPerTrackIdAndBarIndex.set(e,i),this.parseAutomations(t,s,this._soundsByTrack.get(e),i)}parseNotationPatch(e,t){for(let s of t.childNodes)if(s.nodeType===as.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===as.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===as.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===as.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===as.Element&&"Articulation"===i.localName)this.parseArticulation(e,i,s)}parseArticulation(e,t,s){const i=new ce;i.outputMidiNumber=-1,i.elementType=s;let a="";for(let e of t.childNodes)if(e.nodeType===as.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=L.Bottom;break;case"inside":i.techniqueSymbolPlacement=L.Middle;break;case"below":i.techniqueSymbolPlacement=L.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==F.None&&(i.noteHeadHalf=i.noteHeadDefault),i.noteHeadWhole==F.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 F.PictEdgeOfCymbal;case"articStaccatoAbove":return F.ArticStaccatoAbove;case"noteheadParenthesis":return F.NoteheadParenthesis;case"stringsUpBow":return F.StringsUpBow;case"stringsDownBow":return F.StringsDownBow;case"guitarGolpe":return F.GuitarGolpe;default:return F.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return F.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return F.NoteheadDoubleWhole;case"noteheadWhole":return F.NoteheadWhole;case"noteheadHalf":return F.NoteheadHalf;case"noteheadBlack":return F.NoteheadBlack;case"noteheadNull":return F.NoteheadNull;case"noteheadXOrnate":return F.NoteheadXOrnate;case"noteheadTriangleUpWhole":return F.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return F.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return F.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return F.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return F.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return F.NoteheadDiamondWhiteWide;case"noteheadCircleX":return F.NoteheadCircleX;case"noteheadXWhole":return F.NoteheadXWhole;case"noteheadXHalf":return F.NoteheadXHalf;case"noteheadXBlack":return F.NoteheadXBlack;case"noteheadParenthesis":return F.NoteheadParenthesis;case"noteheadSlashedBlack2":return F.NoteheadSlashedBlack2;case"noteheadCircleSlash":return F.NoteheadCircleSlash;case"noteheadHeavyX":return F.NoteheadHeavyX;case"noteheadHeavyXHat":return F.NoteheadHeavyXHat;default:return re.warning("GPIF","Unknown notehead symbol",e),F.None}}parseStaves(e,t){let s=0;for(let i of t.childNodes)if(i.nodeType===as.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===as.Element&&"Properties"===s.localName)this.parseStaffProperties(e,s)}parseStaffProperties(e,t){for(let s of t.childNodes)if(s.nodeType===as.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===as.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===as.Element&&"Line"===e.localName)s.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,s)}parseLyricsLine(e){let t=new ke;for(let s of e.childNodes)if(s.nodeType===as.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===as.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===as.Element&&"Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){let s=new Be,i=t.getAttribute("id");for(let t of e.staves)t.addChord(i,s);this.parseDiagramItemForChord(s,t)}parseDiagramItemForStaff(e,t){let s=new Be,i=t.getAttribute("id");e.addChord(i,s),this.parseDiagramItemForChord(s,t)}parseDiagramItemForChord(e,t){e.name=t.getAttribute("name");let s=t.findChildElement("Diagram");if(!s)return e.showDiagram=!1,void(e.showFingering=!1);let i=parseInt(s.getAttribute("stringCount")),a=s.attributes.has("baseFret")?parseInt(s.getAttribute("baseFret")):0;e.firstFret=a+1;for(let t=0;t<i;t++)e.strings.push(-1);for(let t of s.childNodes)if(t.nodeType===as.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===as.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===as.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===as.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===as.Element&&"Sound"===i.localName)this.parseSound(e,t,i)}parseSound(e,t,s){const i=new bs;for(let e of s.childNodes)if(e.nodeType===as.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===as.Element&&"Program"===s.localName)e.program=parseInt(s.innerText)}parsePartSounding(e,t){for(let s of t.childNodes)if(s.nodeType===as.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===as.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===as.Element&&"ChannelStrip"===s.localName)this.parseChannelStrip(e,s)}parseChannelStrip(e,t){for(let s of t.childNodes)if(s.nodeType===as.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===as.Element&&"MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){let t=new ne;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(let s of e.childNodes)if(s.nodeType===as.Element)switch(s.localName){case"Time":let e=s.innerText.split("/");t.timeSignatureNumerator=parseInt(e[0]),t.timeSignatureDenominator=parseInt(e[1]);break;case"FreeTime":t.isFreeTime=!0;break;case"DoubleBar":t.isDoubleBar=!0;break;case"Section":t.section=new ve,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=C.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=C.Triplet8th;break;case"Triplet16th":t.tripletFeel=C.Triplet16th;break;case"Dotted8th":t.tripletFeel=C.Dotted8th;break;case"Dotted16th":t.tripletFeel=C.Dotted16th;break;case"Scottish8th":t.tripletFeel=C.Scottish8th;break;case"Scottish16th":t.tripletFeel=C.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=P.Major;break;case"minor":t.keySignatureType=P.Minor}break;case"Fermatas":this.parseFermatas(t,s);break;case"XProperties":this.parseMasterBarXProperties(t,s);break;case"Directions":this.parseDirections(t,s)}this._masterBars.push(t)}parseDirections(e,t){for(let s of t.childNodes)if(s.nodeType===as.Element)switch(s.localName){case"Target":switch(s.innerText){case"Coda":e.addDirection(Ve.TargetCoda);break;case"DoubleCoda":e.addDirection(Ve.TargetDoubleCoda);break;case"Segno":e.addDirection(Ve.TargetSegno);break;case"SegnoSegno":e.addDirection(Ve.TargetSegnoSegno);break;case"Fine":e.addDirection(Ve.TargetFine)}break;case"Jump":switch(s.innerText){case"DaCapo":e.addDirection(Ve.JumpDaCapo);break;case"DaCapoAlCoda":e.addDirection(Ve.JumpDaCapoAlCoda);break;case"DaCapoAlDoubleCoda":e.addDirection(Ve.JumpDaCapoAlDoubleCoda);break;case"DaCapoAlFine":e.addDirection(Ve.JumpDaCapoAlFine);break;case"DaSegno":e.addDirection(Ve.JumpDalSegno);break;case"DaSegnoAlCoda":e.addDirection(Ve.JumpDalSegnoAlCoda);break;case"DaSegnoAlDoubleCoda":e.addDirection(Ve.JumpDalSegnoAlDoubleCoda);break;case"DaSegnoAlFine":e.addDirection(Ve.JumpDalSegnoAlFine);break;case"DaSegnoSegno":e.addDirection(Ve.JumpDalSegnoSegno);break;case"DaSegnoSegnoAlCoda":e.addDirection(Ve.JumpDalSegnoSegnoAlCoda);break;case"DaSegnoSegnoAlDoubleCoda":e.addDirection(Ve.JumpDalSegnoSegnoAlDoubleCoda);break;case"DaSegnoSegnoAlFine":e.addDirection(Ve.JumpDalSegnoSegnoAlFine);break;case"DaCoda":e.addDirection(Ve.JumpDaCoda);break;case"DaDoubleCoda":e.addDirection(Ve.JumpDaDoubleCoda)}}}parseFermatas(e,t){for(let s of t.childNodes)if(s.nodeType===as.Element&&"Fermata"===s.localName)this.parseFermata(e,s)}parseFermata(e,t){let s=0,i=new Ze;for(let e of t.childNodes)if(e.nodeType===as.Element)switch(e.localName){case"Type":switch(e.innerText){case"Short":i.type=He.Short;break;case"Medium":i.type=He.Medium;break;case"Long":i.type=He.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])*ee.QuarterTime|0}}e.addFermata(s,i)}parseBars(e){for(let t of e.childNodes)if(t.nodeType===as.Element&&"Bar"===t.localName)this.parseBar(t)}parseBar(e){let t=new Z,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===as.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===as.Element&&"Voice"===t.localName)this.parseVoice(t)}parseVoice(e){let t=new Me,s=e.getAttribute("id");for(let t of e.childNodes)if(t.nodeType===as.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===as.Element&&"Beat"===t.localName)this.parseBeat(t)}parseBeat(e){let t=new we,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===as.Element)switch(i.localName){case"Notes":this._notesOfBeat.set(s,i.innerText.split(" "));break;case"Rhythm":this._rhythmOfBeat.set(s,i.getAttribute("ref"));break;case"Fadding":switch(i.innerText){case"FadeIn":t.fade=O.FadeIn;break;case"FadeOut":t.fade=O.FadeOut;break;case"VolumeSwell":t.fade=O.VolumeSwell}break;case"Tremolo":switch(i.innerText){case"1/2":t.tremoloSpeed=p.Eighth;break;case"1/4":t.tremoloSpeed=p.Sixteenth;break;case"1/8":t.tremoloSpeed=p.ThirtySecond}break;case"Chord":t.chordId=i.innerText;break;case"Hairpin":switch(i.innerText){case"Crescendo":t.crescendo=u.Crescendo;break;case"Decrescendo":t.crescendo=u.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=Ge.Up;break;case"Downward":t.preferredBeamDirection=Ge.Down}break;case"Dynamic":switch(i.innerText){case"PPP":t.dynamics=g.PPP;break;case"PP":t.dynamics=g.PP;break;case"P":t.dynamics=g.P;break;case"MP":t.dynamics=g.MP;break;case"MF":t.dynamics=g.MF;break;case"F":t.dynamics=g.F;break;case"FF":t.dynamics=g.FF;break;case"FFF":t.dynamics=g.FFF}break;case"GraceNotes":switch(i.innerText){case"OnBeat":t.graceType=m.OnBeat;break;case"BeforeBeat":t.graceType=m.BeforeBeat}break;case"Legato":"true"===i.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":let e=new te(0,0);e.value=this.toBendValue(parseFloat(i.getAttribute("originValue"))),e.offset=this.toBendOffset(parseFloat(i.getAttribute("originOffset"))),t.addWhammyBarPoint(e);let a=new te(0,0);a.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),a.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);let r=new te(0,0);r.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),r.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);let o=new te(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;break;case"Slashed":t.slashed=!0;break;case"DeadSlapped":t.deadSlapped=!0;break;case"Golpe":switch(i.innerText){case"Finger":t.golpe=A.Finger;break;case"Thumb":t.golpe=A.Thumb}break;case"Wah":switch(i.innerText){case"Open":t.wahPedal=R.Open;break;case"Closed":t.wahPedal=R.Closed}break;case"UserTransposedPitchStemOrientation":switch(i.innerText){case"Downward":t.preferredBeamDirection=Ge.Down;break;case"Upward":t.preferredBeamDirection=Ge.Up}break;case"Timer":t.showTimer=!0,i.innerText.length>0&&(t.timer=parseInt(i.innerText))}this._beatById.set(s,t)}parseBeatLyrics(e){const t=[];for(let s of e.childNodes)if(s.nodeType===as.Element&&"Line"===s.localName)t.push(s.innerText);return t}parseBeatXProperties(e,t){for(let s of e.childNodes)if(s.nodeType===as.Element&&"XProperty"===s.localName){let e=0;switch(s.getAttribute("id")){case"1124204546":switch(e=parseInt(s.findChildElement("Int").innerText),e){case 1:t.beamingMode=G.ForceMergeWithNext;break;case 2:t.beamingMode=G.ForceSplitToNext}break;case"1124204552":if(e=parseInt(s.findChildElement("Int").innerText),1===e)t.beamingMode!==G.ForceSplitToNext&&(t.beamingMode=G.ForceSplitOnSecondaryToNext);break;case"1124204545":e=parseInt(s.findChildElement("Int").innerText),t.invertBeamDirection=1===e;break;case"687935489":e=parseInt(s.findChildElement("Int").innerText),t.brushDuration=e}}}parseBarXProperties(e,t){for(let s of e.childNodes)if(s.nodeType===as.Element&&"XProperty"===s.localName){if("1124139520"===s.getAttribute("id")){const e=s.findChildElement("Double")??s.findChildElement("Float");t.displayScale=parseFloat(e.innerText)}}}parseMasterBarXProperties(e,t){for(let s of t.childNodes)if(s.nodeType===as.Element&&"XProperty"===s.localName){if("1124073984"===s.getAttribute("id"))e.displayScale=parseFloat(s.findChildElement("Double").innerText)}}parseBeatProperties(e,t){let s=!1,i=null,a=null,r=null,n=null,o=null;for(let h of e.childNodes)if(h.nodeType===as.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=E.Up:t.pickStroke=E.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=w.Wide;break;case"Slight":t.vibrato=w.Slight}break;case"WhammyBar":s=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":i||(i=new te(0,0)),i.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":i||(i=new te(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 te(te.MaxPosition,0)),o.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new te(0,0)),o.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText));break;case"BarreFret":t.barreFret=parseInt(h.findChildElement("Fret").innerText);break;case"BarreString":switch(h.findChildElement("String").innerText){case"0":t.barreShape=V.Full;break;case"1":t.barreShape=V.Half}break;case"Rasgueado":switch(h.findChildElement("Rasgueado").innerText){case"ii_1":t.rasgueado=H.Ii;break;case"mi_1":t.rasgueado=H.Mi;break;case"mii_1":t.rasgueado=H.MiiTriplet;break;case"mii_2":t.rasgueado=H.MiiAnapaest;break;case"pmp_1":t.rasgueado=H.PmpTriplet;break;case"pmp_2":t.rasgueado=H.PmpAnapaest;break;case"pei_1":t.rasgueado=H.PeiTriplet;break;case"pei_2":t.rasgueado=H.PeiAnapaest;break;case"pai_1":t.rasgueado=H.PaiTriplet;break;case"pai_2":t.rasgueado=H.PaiAnapaest;break;case"ami_1":t.rasgueado=H.AmiTriplet;break;case"ami_2":t.rasgueado=H.AmiAnapaest;break;case"ppp_1":t.rasgueado=H.Ppp;break;case"amii_1":t.rasgueado=H.Amii;break;case"amip_1":t.rasgueado=H.Amip;break;case"eami_1":t.rasgueado=H.Eami;break;case"eamii_1":t.rasgueado=H.Eamii;break;case"peami_1":t.rasgueado=H.Peami}}}s&&(i||(i=new te(0,0)),o||(o=new te(te.MaxPosition,0)),t.addWhammyBarPoint(i),r&&a&&t.addWhammyBarPoint(new te(r,a)),n&&a&&t.addWhammyBarPoint(new te(n,a)),r||n||!a||t.addWhammyBarPoint(new te(te.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(let t of e.childNodes)if(t.nodeType===as.Element&&"Note"===t.localName)this.parseNote(t)}parseNote(e){let t=new ge,s=e.getAttribute("id");for(let a of e.childNodes)if(a.nodeType===as.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=p.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),16&e&&(t.accentuated=i.Tenuto);break;case"Tie":"true"===a.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(a.innerText){case"Slight":t.vibrato=w.Slight;break;case"Wide":t.vibrato=w.Wide}break;case"LeftFingering":switch(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(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);break;case"Ornament":switch(a.innerText){case"Turn":t.ornament=M.Turn;break;case"InvertedTurn":t.ornament=M.InvertedTurn;break;case"UpperMordent":t.ornament=M.UpperMordent;break;case"LowerMordent":t.ornament=M.LowerMordent}}this._noteById.set(s,t)}parseNoteProperties(e,t,s){let i=!1,a=null,r=null,n=null,o=null,h=null,l=-1,d=-1;for(let c of e.childNodes)if(c.nodeType===as.Element&&"Property"===c.localName){switch(c.getAttribute("name")){case"ShowStringNumber":c.findChildElement("Enable")&&(t.showStringNumber=!0);break;case"String":t.string=parseInt(c.findChildElement("String").innerText)+1;break;case"Fret":t.fret=parseInt(c.findChildElement("Fret").innerText);break;case"Element":l=parseInt(c.findChildElement("Element").innerText);break;case"Variation":d=parseInt(c.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(s,!0);break;case"HarmonicType":let e=c.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=y.None;break;case"Natural":t.harmonicType=y.Natural;break;case"Artificial":t.harmonicType=y.Artificial;break;case"Pinch":t.harmonicType=y.Pinch;break;case"Tap":t.harmonicType=y.Tap;break;case"Semi":t.harmonicType=y.Semi;break;case"Feedback":t.harmonicType=y.Feedback}break;case"HarmonicFret":let u=c.findChildElement("HFret");u&&(t.harmonicValue=parseFloat(u.innerText));break;case"Muted":c.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":c.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=parseInt(c.findChildElement("Number").innerText),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=parseInt(c.findChildElement("Step").innerText);break;case"ConcertPitch":this.parseConcertPitch(c,t);break;case"Bended":i=!0;break;case"BendOriginValue":a||(a=new te(0,0)),a.value=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new te(0,0)),a.offset=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleValue":r=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleOffset1":n=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleOffset2":o=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendDestinationValue":h||(h=new te(te.MaxPosition,0)),h.value=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new te(0,0)),h.offset=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"HopoOrigin":c.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":let p=parseInt(c.findChildElement("Flags").innerText);1&p?t.slideOutType=_.Shift:2&p?t.slideOutType=_.Legato:4&p?t.slideOutType=_.OutDown:8&p&&(t.slideOutType=_.OutUp),16&p?t.slideInType=S.IntoFromBelow:32&p&&(t.slideInType=S.IntoFromAbove),64&p?t.slideOutType=_.PickSlideDown:128&p&&(t.slideOutType=_.PickSlideUp)}}i&&(a||(a=new te(0,0)),h||(h=new te(te.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new te(n,r)),o&&r&&t.addBendPoint(new te(o,r)),n||o||!r||t.addBendPoint(new te(te.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==d&&(t.percussionArticulation=ue.articulationFromElementVariation(l,d))}parseConcertPitch(e,t){const s=e.findChildElement("Pitch");if(s)for(let e of s.childNodes)if(e.nodeType===as.Element&&"Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=b.ForceDoubleSharp;break;case"#":t.accidentalMode=b.ForceSharp;break;case"b":t.accidentalMode=b.ForceFlat;break;case"bb":t.accidentalMode=b.ForceDoubleFlat}}toBendValue(e){return e*Ss.BendPointValueFactor|0}toBendOffset(e){return e*Ss.BendPointPositionFactor}parseRhythms(e){for(let t of e.childNodes)if(t.nodeType===as.Element&&"Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){let t=new ys,s=e.getAttribute("id");t.id=s;for(let s of e.childNodes)if(s.nodeType===as.Element)switch(s.localName){case"NoteValue":switch(s.innerText){case"Long":t.value=p.QuadrupleWhole;break;case"DoubleWhole":t.value=p.DoubleWhole;break;case"Whole":t.value=p.Whole;break;case"Half":t.value=p.Half;break;case"Quarter":t.value=p.Quarter;break;case"Eighth":t.value=p.Eighth;break;case"16th":t.value=p.Sixteenth;break;case"32nd":t.value=p.ThirtySecond;break;case"64th":t.value=p.SixtyFourth;break;case"128th":t.value=p.OneHundredTwentyEighth;break;case"256th":t.value=p.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!==Ss.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!==Ss.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!==Ss.InvalidId){let t=Se.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!==Ss.InvalidId){const e=ye.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 Me;e.addVoice(t);let s=new we;s.isEmpty=!0,s.duration=p.Quarter,t.addBeat(s)}t===s.staves.length-1?(i++,t=0):t++}else i++}}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e),s=!1;for(const e of t.staves)if(e.isPercussion){s=!0;break}if(s||(t.percussionArticulations=[]),this._automationsPerTrackIdAndBarIndex.has(e)){const s=this._automationsPerTrackIdAndBarIndex.get(e);for(const[e,i]of s)if(t.staves.length>0&&e<t.staves[0].bars.length){const s=t.staves[0].bars[e];if(s.voices.length>0&&s.voices[0].beats.length>0){const e=s.voices[0].beats[0];for(const t of i)e.automations.push(t)}}}if(this._sustainPedalsPerTrackIdAndBarIndex.has(e)){const s=this._sustainPedalsPerTrackIdAndBarIndex.get(e);for(const[e,i]of s)if(t.staves.length>0&&e<t.staves[0].bars.length){t.staves[0].bars[e].sustainPedals=i}}}for(const[e,t]of this._masterTrackAutomations){let s=this.score.masterBars[e];for(let i=0,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.tempoAutomations.push(r))}}}}Ss.InvalidId="-1",Ss.BendPointPositionFactor=te.MaxPosition/100,Ss.BendPointValueFactor=.04;class _s{constructor(){this.isMultiRest=!1,this.trackViewGroups=[]}}class ws{constructor(){this.showNumbered=!1,this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class Bs{apply(e){if(this.scoreViews.length>0){let t=0;for(let s of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){const i=e.tracks[t];for(const e of i.staves)e.showTablature=s.showTablature,e.showStandardNotation=s.showStandardNotation,e.showSlash=s.showSlash,e.showNumbered=s.showNumbered}t++}}}constructor(e){this.scoreViews=[];let t=Oe.fromBuffer(e);const s=Ae.readInt32BE(t);for(let e=0;e<s;e++){const e=new _s;this.scoreViews.push(e),e.isMultiRest=hs.gpReadBool(t);const s=Ae.readInt32BE(t);for(let i=0;i<s;i++){let s=t.readByte();0===s&&(s=1);let i=new ws;i.showStandardNotation=!!(1&s),i.showTablature=!!(2&s),i.showSlash=!!(4&s),i.showNumbered=!!(8&s),e.trackViewGroups.push(i)}}}static writeForScore(e){const t=Oe.withCapacity(128),s=[new _s];for(const t of e.tracks){const e=new ws;e.showStandardNotation=t.staves[0].showStandardNotation,e.showTablature=t.staves[0].showTablature,e.showSlash=t.staves[0].showSlash,e.showNumbered=t.staves[0].showNumbered,s[0].trackViewGroups.push(e);const i=new _s;i.trackViewGroups.push(e),s.push(i)}Ae.writeInt32BE(t,s.length);for(const e of s){t.writeByte(e.isMultiRest?1:0),Ae.writeInt32BE(t,e.trackViewGroups.length);for(const s of e.trackViewGroups){let e=0;s.showStandardNotation&&(e|=1),s.showTablature&&(e|=2),s.showSlash&&(e|=4),s.showNumbered&&(e|=8),t.writeByte(e)}}return Ae.writeInt32BE(t,1),t.toArray()}}let ks=class{};class Ts extends ks{constructor(e){super(),this.n=e}}class xs extends ks{constructor(e,t){super(),this.left=e,this.right=t}}class Ns extends ks{constructor(e,t){super(),this.n=e,this.table=t}}class vs{static make(e,t,s,i){let a=[],r=[];if(i>32)throw new Pe("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 Pe("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 vs.treeCompress(new xs(vs.treeMake(o,i,0,1),vs.treeMake(o,i,1,1)))}static treeMake(e,t,s,i){if(i>t)throw new Pe("Invalid huffman");let a=s<<5|i;return e.has(a)?new Ts(e.get(a)):(s<<=1,i+=1,new xs(vs.treeMake(e,t,s,i),vs.treeMake(e,t,1|s,i)))}static treeCompress(e){let t=vs.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof xs)return new xs(vs.treeCompress(e.left),vs.treeCompress(e.right));throw new Pe("assert")}let s=1<<t,i=[];for(let e=0;e<s;e++)i.push(new Ts(-1));return vs.treeWalk(i,0,0,t,e),new Ns(t,i)}static treeWalk(e,t,s,i,a){a instanceof xs&&i>0?(vs.treeWalk(e,t,s+1,i-1,a.left),vs.treeWalk(e,t|1<<s,s+1,i-1,a.right)):e[t]=vs.treeCompress(a)}static treeDepth(e){if(e instanceof Ts)return 0;if(e instanceof Ns)throw new Pe("assert");if(e instanceof xs){let t=vs.treeDepth(e.left),s=vs.treeDepth(e.right);return 1+(t<s?t:s)}return 0}}var Ps,Cs,Es,Fs,Ds,Ls,Ms,Is,As,Os,Rs,Vs,Hs,Gs,Ws,zs,Us,Xs;!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"}(Ps||(Ps={}));class Js{constructor(){this.buffer=new Uint8Array(Js.BufferSize),this.pos=0}slide(){let e=new Uint8Array(Js.BufferSize);this.pos-=Js.Size,e.set(this.buffer.subarray(Js.Size,Js.Size+this.pos),0),this.buffer=e}addBytes(e,t,s){this.pos+s>Js.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+s),this.pos),this.pos+=s}addByte(e){this.pos===Js.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}Js.Size=32768,Js.BufferSize=65536;class Ys{static buildFixedHuffman(){let e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return vs.make(e,0,288,10)}constructor(e){this._nbits=0,this._bits=0,this._state=Ps.Block,this._isFinal=!1,this._huffman=Ys._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new Js,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 Ps.Head:let e=this._input.readByte();if(8!==(15&e))throw new Pe("Invalid data");let t=this._input.readByte(),s=!!(32&t);if(((e<<8)+t)%31!=0)throw new Pe("Invalid data");if(s)throw new Pe("Unsupported dictionary");return this._state=Ps.Block,!0;case Ps.Crc:return this._state=Ps.Done,!0;case Ps.Done:return!1;case Ps.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:if(this._len=Ae.readUInt16LE(this._input),Ae.readUInt16LE(this._input)!==65535-this._len)throw new Pe("Invalid data");this._state=Ps.Flat;let e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=Ys._fixedHuffman,this._huffdist=null,this._state=Ps.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[Ys.CodeLengthsPos[e]]=this.getBits(3);for(let e=i;e<19;e++)this._lengths[Ys.CodeLengthsPos[e]]=0;this._huffman=vs.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=vs.make(a,t,s,16),this._huffman=vs.make(a,0,t,16),this._state=Ps.CData,!0;default:throw new Pe("Invalid data")}case Ps.Flat:{let e=this._len<this._needed?this._len:this._needed,t=Ae.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?Ps.Crc:Ps.Block),this._needed>0}case Ps.DistOne:{let e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=Ps.CData),this._needed>0}case Ps.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=Ps.CData),this._needed>0;case Ps.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?Ps.Crc:Ps.Block,!0;{i=i-257&255;let e=Ys.LenExtraBitsTbl[i];if(-1===e)throw new Pe("Invalid data");this._len=Ys.LenBaseValTbl[i]+this.getBits(e);let t=this._huffdist,s=t?this.applyHuffman(t):this.getRevBits(5);if(e=Ys.DistExtraBitsTbl[s],-1===e)throw new Pe("Invalid data");if(this._dist=Ys.DistBaseValTbl[s]+this.getBits(e),this._dist>this._window.available())throw new Pe("Invalid data");return this._state=1===this._dist?Ps.DistOne:Ps.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 Pe("Invalid data");for(;s<r;)e[s]=i,s++;break;case 17:if(s+=3+this.getBits(3),s>t)throw new Pe("Invalid data");break;case 18:if(s+=11+this.getBits(7),s>t)throw new Pe("Invalid data");break;default:throw new Pe("Invalid data")}}}applyHuffman(e){if(e instanceof Ts)return e.n;if(e instanceof xs)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof Ns)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new Pe("Invalid data")}}Ys.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],Ys.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],Ys.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],Ys.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],Ys.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Ys._fixedHuffman=Ys.buildFixedHuffman();class qs{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}}qs.OptionalDataDescriptorSignature=134695760,qs.CompressionMethodDeflate=8,qs.LocalFileHeaderSignature=67324752,qs.CentralFileHeaderSignature=33639248,qs.EndOfCentralDirSignature=101010256;class js{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(Ae.readInt32LE(e)!==qs.LocalFileHeaderSignature)return null;Ae.readUInt16LE(e);let t=Ae.readUInt16LE(e),s=Ae.readUInt16LE(e),i=0!==s;if(i&&s!==qs.CompressionMethodDeflate)return null;Ae.readInt16LE(this._readable),Ae.readInt16LE(this._readable),Ae.readInt32LE(e),Ae.readInt32LE(e);let a,r=Ae.readInt32LE(e),n=Ae.readInt16LE(e),o=Ae.readInt16LE(e),h=Ae.toString(Ae.readByteArray(e,n),"utf-8");if(e.skip(o),i){let e=Oe.empty(),t=new Ys(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=Ae.readByteArray(this._readable,r);if(8&t){Ae.readInt32LE(this._readable)===qs.OptionalDataDescriptorSignature&&Ae.readInt32LE(this._readable),Ae.readInt32LE(this._readable),Ae.readInt32LE(this._readable)}return new qs(h,a)}}class Ks{constructor(){this.trackViewGroups=[]}}class Qs{constructor(){this.isVisible=!1}}!function(e){e[e.PageVertical=0]="PageVertical",e[e.PageGrid=1]="PageGrid",e[e.PageParchment=2]="PageParchment",e[e.ScreenVertical=3]="ScreenVertical",e[e.ScreenHorizontal=4]="ScreenHorizontal",e[e.PageHorizontal=5]="PageHorizontal"}(Cs||(Cs={}));class $s{constructor(e,t){this.zoomLevel=4,this.view=Cs.PageVertical,this.muiltiVoiceCursor=!1,this.scoreViews=[];const s=Oe.fromBuffer(t);this.zoomLevel=Ae.readInt32BE(s),this.view=s.readByte(),this.muiltiVoiceCursor=0!=s.readByte();const i=e.scoreViews.length;for(let t=0;t<i;t++){const i=new Ks;this.scoreViews.push(i);const a=e.scoreViews[t];for(let e=0;e<a.trackViewGroups.length;e++){const e=new Qs;e.isVisible=0!=s.readByte(),i.trackViewGroups.push(e)}}}apply(e){if(this.scoreViews.length>0){let t=0;for(let s of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){e.tracks[t].isVisibleOnMultiTrack=s.isVisible}t++}}}static writeForScore(e){const t=Oe.withCapacity(128);Ae.writeInt32BE(t,4),t.writeByte(0);const s=e.tracks.length>0&&e.tracks[0].staves[0].bars[0].isMultiVoice;t.writeByte(s?255:0);for(const s of e.tracks)t.writeByte(s.isVisibleOnMultiTrack?255:0);for(const s of e.tracks)t.writeByte(255);return t.toArray()}}class Zs extends q{get name(){return"Guitar Pro 7-8"}constructor(){super()}readScore(){re.debug(this.name,"Loading ZIP entries");let e,t=new js(this.data);try{e=t.read()}catch(e){throw new K("No Zip archive",e)}re.debug(this.name,"Zip entries loaded");let s=null,i=null,a=null,r=null;for(let t of e)switch(t.fileName){case"score.gpif":s=Ae.toString(t.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=t.data;break;case"PartConfiguration":a=t.data;break;case"LayoutConfiguration":r=t.data}if(!s)throw new K("No score.gpif found in zip archive");re.debug(this.name,"Start Parsing score.gpif");let n=new Ss;n.parseXml(s,this.settings),re.debug(this.name,"score.gpif parsed");let o=n.score;if(i){re.debug(this.name,"Start Parsing BinaryStylesheet"),new cs(i).apply(o),re.debug(this.name,"BinaryStylesheet parsed")}let h=null;if(a&&(re.debug(this.name,"Start Parsing Part Configuration"),h=new Bs(a),h.apply(o),re.debug(this.name,"Part Configuration parsed")),r&&null!=h){re.debug(this.name,"Start Parsing Layout Configuration"),new $s(h,r).apply(o),re.debug(this.name,"Layout Configuration parsed")}return o}}class ei extends j{constructor(){super(s.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,ei.prototype)}}class ti{constructor(e){this._currentByte=0,this._position=ti.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 ei;this._position=0}const e=this._currentByte>>ti.ByteSize-this._position-1&1;return this._position++,e}readAll(){let e=Oe.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof ei))throw e}return e.toArray()}}ti.ByteSize=8;class si{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class ii{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){let t=new ti(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){let s,i=Oe.empty(),a=this.getInteger(e.readBytes(4),0);try{for(;i.length<a;){if(1===e.readBits(1)){let t=e.readBits(4),a=e.readBitsReversed(t),r=e.readBitsReversed(t),n=i.length-a,o=Math.min(a,r);s=i.getBuffer(),i.write(s,n,o)}else{let t=e.readBitsReversed(2);for(let s=0;s<t;s++)i.writeByte(e.readByte())}}}catch(e){if(!(e instanceof ei))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 K("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 si;i.fileName=this.getString(e,s+4,127),i.fileSize=this.getInteger(e,s+140);let a=!this.fileFilter||this.fileFilter(i.fileName);a&&this.files.push(i);let r=s+148,n=0,o=0,h=a?Oe.withCapacity(i.fileSize):null;for(;n=this.getInteger(e,r+4*o++),0!==n;)s=n*t,a&&h.write(e,s,t);if(a){i.data=new Uint8Array(Math.min(i.fileSize,h.length));let e=h.toArray();i.data.set(e.subarray(0,0+i.data.length),0)}}s+=t}}getString(e,t,s){let i="";for(let a=0;a<s;a++){let s=255&e[t+a];if(0===s)break;i+=String.fromCharCode(s)}return i}getInteger(e,t){return e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}}ii.HeaderBcFs="BCFS",ii.HeaderBcFz="BCFZ";class ai extends q{get name(){return"Guitar Pro 6"}constructor(){super()}readScore(){re.debug(this.name,"Loading GPX filesystem");let e=new ii;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration")||e.endsWith("LayoutConfiguration"),e.load(this.data),re.debug(this.name,"GPX filesystem loaded");let t=null,s=null,i=null,a=null;for(let r of e.files)switch(r.fileName){case"score.gpif":t=Ae.toString(r.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=r.data;break;case"PartConfiguration":i=r.data;break;case"LayoutConfiguration":a=r.data}if(!t)throw new K("No score.gpif found in GPX");re.debug(this.name,"Start Parsing score.gpif");let r=new Ss;r.parseXml(t,this.settings),re.debug(this.name,"score.gpif parsed");let n=r.score;if(s){re.debug(this.name,"Start Parsing BinaryStylesheet"),new cs(s).apply(n),re.debug(this.name,"BinaryStylesheet parsed")}let o=null;if(i&&(re.debug(this.name,"Start Parsing Part Configuration"),o=new Bs(i),o.apply(n),re.debug(this.name,"Part Configuration parsed")),a&&null!=o){re.debug(this.name,"Start Parsing Layout Configuration"),new $s(o,a).apply(n),re.debug(this.name,"Layout Configuration parsed")}return n}}class ri extends q{get name(){return"MusicXML"}constructor(){super(),this._currentPartGroup=null,this._trackFirstMeasureNumber=0,this._maxVoices=0,this._currentDirection=null,this._currentChord=null,this._divisionsPerQuarterNote=0,this._voiceOfStaff=new Map,this._isBeamContinue=!1,this._previousBeatWasPulled=!1,this._previousBeat=null}readScore(){this._trackById=new Map,this._partGroups=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._slurStarts=new Map;let e=this.extractMusicXml(),t=new fs;try{t.parse(e)}catch(e){throw new K("Unsupported format")}return this._score=new Ne,this._score.tempo=120,this.parseDom(t),this.settings.importer.mergePartGroupsInMusicXml&&this.mergePartGroups(),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}extractMusicXml(){const e=new js(this.data);let t;try{t=e.read()}catch(e){t=[]}if(0===t.length)return this.data.reset(),Ae.toString(this.data.readAll(),this.settings.importer.encoding);const s=t.find((e=>"META-INF/container.xml"===e.fullName));if(!s)throw new K("No compressed MusicXML");const i=new fs;try{i.parse(Ae.toString(s.data,this.settings.importer.encoding))}catch(e){throw new K("Malformed container.xml, could not parse as XML",e)}let a=i.firstElement;if(!a||"container"!==a.localName)throw new K("Malformed container.xml, root element not 'container'");const r=a.findChildElement("rootfiles");if(!r)throw new K("Malformed container.xml, 'container/rootfiles' not found");let n="";for(const e of r.childNodes)if(e.nodeType==as.Element&&"rootfile"===e.localName){n=e.getAttribute("full-path");break}if(!n)throw new K("Unsupported compressed MusicXML, missing rootfile");const o=t.find((e=>e.fullName===n));if(!o)throw new K(`Malformed container.xml, '${n}' not contained in zip`);return Ae.toString(o.data,this.settings.importer.encoding)}mergePartGroups(){let e=!1;for(const t of this._partGroups.values())t.length>1&&(this.mergeGroup(t),e=!0);if(e)for(let e=0;e<this._score.tracks.length;e++)this._score.tracks[e].index=e}mergeGroup(e){let t=e[0];for(let s=1;s<e.length;s++){let i=e[s];for(let e of i.staves)t.addStaff(e);let a=this._score.tracks.indexOf(i);this._score.tracks.splice(a,1)}}parseDom(e){let t=e.firstElement;if(!t)throw new K("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":break;default:throw new K("Unsupported format")}}parsePartwise(e){for(let t of e.childNodes)if(t.nodeType===as.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===as.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===as.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 Z;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===as.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 Me;e.addVoice(t);let s=new we;s.isEmpty=!0,s.chordId=this._currentChord,t.addBeat(s)}}getOrCreateBeat(e,t,s){let i=0,a=e.getElementsByTagName("voice",!1);a.length>0&&(i=parseInt(a[0].innerText)-1);let r=this._previousBeatWasPulled;this._previousBeatWasPulled=!1;let n,o,h=e.getElementsByTagName("staff",!1),l=1;if(h.length>0){l=parseInt(h[0].innerText),(this._isBeamContinue||r)&&this._previousBeat.voice.bar.staff.index!==l-1&&(l=this._previousBeat.voice.bar.staff.index+1,this._previousBeatWasPulled=!0);let e=t[0].staff.track.index+"-"+l;this._voiceOfStaff.has(e)||this._voiceOfStaff.set(e,i)}l--,n=l<0?t[0]:l>=t.length?t[t.length-1]:t[l];let d=this.getOrCreateVoice(n,i);return s&&d.beats.length>0||1===d.beats.length&&d.isEmpty?o=d.beats[d.beats.length-1]:(o=new we,o.isEmpty=!1,d.addBeat(o)),this._isBeamContinue=!1,this._previousBeat=o,o}parseForward(e,t){let s=this.getOrCreateBeat(e,t,!1),i=parseInt(e.findChildElement("duration").innerText)*p.Quarter/this._divisionsPerQuarterNote,a=[p.SixtyFourth,p.ThirtySecond,p.Sixteenth,p.Eighth,p.Quarter,p.Half,p.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===as.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===as.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=le.getTuningForText(i+a)+r;for(let e of t.staves)e.tuning[e.tuning.length-s]=n}parseHarmony(e,t,s){let i=new Be;for(let t of e.childNodes)if(t.nodeType===as.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=le.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===as.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===as.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===as.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 ge;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===as.Element)switch(t.localName){case"grace":i.graceType=m.BeforeBeat,i.duration=p.ThirtySecond;break;case"duration":if(i.isRest&&!r){switch(parseInt(t.innerText)){case 1:i.duration=p.Whole;break;case 2:i.duration=p.Half;break;case 4:default:i.duration=p.Quarter;break;case 8:i.duration=p.Eighth;break;case 16:i.duration=p.Sixteenth;break;case 32:i.duration=p.ThirtySecond;break;case 64:i.duration=p.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!==m.None&&i.duration<p.Sixteenth&&(i.duration=p.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=p.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 p.SixtyFourth;case"32nd":return p.ThirtySecond;case"16th":return p.Sixteenth;case"eighth":return p.Eighth;case"quarter":return p.Quarter;case"half":return p.Half;case"long":case"breve":case"whole":return p.Whole}return p.Quarter}parseLyric(e,t){for(let s of e.childNodes)if(s.nodeType===as.Element&&"text"===s.localName)t.text?t.text+=" "+s.innerText:t.text=s.innerText}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=b.ForceSharp;break;case"natural":t.accidentalMode=b.ForceNatural;break;case"flat":t.accidentalMode=b.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===as.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=_.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===as.Element&&"tremolo"===s.localName){switch(parseInt(s.innerText)){case 1:t.beat.tremoloSpeed=p.Eighth;break;case 2:t.beat.tremoloSpeed=p.Sixteenth;break;case 3:t.beat.tremoloSpeed=p.ThirtySecond}}}parseTechnical(e,t){let s=[];for(let i of e.childNodes)if(i.nodeType===as.Element)switch(i.localName){case"string":t.string=parseInt(i.innerText),-2147483648!==t.string&&(t.string=t.beat.voice.bar.staff.tuning.length-t.string+1);break;case"fret":t.fret=parseInt(i.innerText);break;case"down-bow":t.beat.pickStroke=E.Down;break;case"up-bow":t.beat.pickStroke=E.Up;break;case"bend":s.push(i)}s.length>0&&this.parseBends(s,t),-2147483648!==t.string&&-2147483648!==t.fret||(t.string=-1,t.fret=-1)}parseBends(e,t){let s=te.MaxPosition/e.length,i=0,a=0,r=!0;for(let n of e){let e=n.findChildElement("bend-alter");if(e){let o=Math.round(2*Math.abs(parseFloat(e.innerText)));n.findChildElement("pre-bend")?r?(i+=o,t.addBendPoint(new te(a,i)),a+=s,t.addBendPoint(new te(a,i)),r=!1):a+=s:n.findChildElement("release")?(r&&(i+=o),t.addBendPoint(new te(a,i)),a+=s,i-=o,t.addBendPoint(new te(a,i)),r=!1):(t.addBendPoint(new te(a,i)),i+=o,a+=s,t.addBendPoint(new te(a,i)),r=!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;break;case"tenuto":t.accentuated=i.Tenuto}}parseDynamics(e,t){for(let s of e.childNodes)if(s.nodeType===as.Element)switch(s.localName){case"p":t.dynamics=g.P;break;case"pp":t.dynamics=g.PP;break;case"ppp":t.dynamics=g.PPP;break;case"f":t.dynamics=g.F;break;case"ff":t.dynamics=g.FF;break;case"fff":t.dynamics=g.FFF;break;case"mp":t.dynamics=g.MP;break;case"mf":t.dynamics=g.MF}}parseTimeModification(e,t){for(let s of e.childNodes)if(s.nodeType===as.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===as.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+le.getToneForText(s).noteValue+i;t.octave=r/12|0,t.tone=r-12*t.octave}parsePitch(e,t){let s="",i=0,a=0;for(let t of e.childNodes)if(t.nodeType===as.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+le.getToneForText(s).noteValue+(0|i);t.octave=r/12|0,t.tone=r-12*t.octave}getOrCreateVoice(e,t){if(t<e.voices.length)return e.voices[t];for(let s=e.voices.length;s<=t;s++)e.addVoice(new Me);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===as.Element)switch(s.localName){case"sound":let e=s.getAttribute("tempo");if(e){let s=new Q;s.isLinear=!0,s.type=a.Tempo,s.value=parseInt(e),t.tempoAutomations.push(s),0===t.index&&(t.score.tempo=s.value)}break;case"direction-type":let i=s.firstElement;switch(i.localName){case"words":this._currentDirection=i.innerText;break;case"metronome":this.parseMetronome(i,t)}}}parseMetronome(e,t){let s=p.Quarter,i=120;for(let t of e.childNodes)if(t.nodeType===as.Element)switch(t.localName){case"beat-unit":s=this.getDuration(t.innerText);break;case"per-minute":i=parseInt(t.innerText)}let r=new Q;r.type=a.Tempo,r.value=i*(s/4)|0,this.hasSameTempo(t,r)||(t.tempoAutomations.push(r),0===t.index&&(t.score.tempo=r.value))}hasSameTempo(e,t){for(const s of e.tempoAutomations)if(t.ratioPosition===s.ratioPosition&&t.value==s.value)return!0;return!1}parseAttributes(e,t,s,i){let a=0,r=!1;for(let n of e.childNodes)if(n.nodeType===as.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===as.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===as.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===as.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===as.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:v.C,t.keySignatureType="minor"===i?P.Minor:P.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 ne;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===as.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===as.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 Le;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===as.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===as.Element)switch(s.localName){case"midi-channel":t.playbackInfo.primaryChannel=parseInt(s.innerText);break;case"midi-program":t.playbackInfo.program=parseInt(s.innerText);break;case"volume":t.playbackInfo.volume=Math.floor(parseInt(s.innerText)/100*16);break;case"pan":t.playbackInfo.balance=Math.max(0,Math.min(16,Math.floor((parseInt(s.innerText)+90)/180*16)))}}}class ni{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event.type==je.AlphaTabMetronome}static newMetronomeEvent(e,t,s,i,a){const r=new ct(0,t,s,i,a);return new ni(e,r)}}class oi{constructor(e,t,s){this.bpm=e,this.ticks=t,this.time=s}}class hi{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=ee.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class li{get isPlayingMain(){return this._currentState==this._mainState}get isPlayingOneTimeMidi(){return this._currentState==this._oneTimeState}get isPlayingCountIn(){return this._currentState==this._countInState}constructor(e){this._oneTimeState=null,this._countInState=null,this.isLooping=!1,this.playbackSpeed=1,this.instrumentPrograms=new Set,this.percussionKeys=new Set,this._synthesizer=e,this._mainState=new hi,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(Re.MicroBufferSize);this._mainState.currentTime=s;let i=Date.now()-t;re.debug("Sequencer","Silent seek finished in "+i+"ms (main)")}loadOneTimeMidi(e){this._oneTimeState=this.createStateFromFile(e),this._currentState=this._oneTimeState}loadMidi(e){this.instrumentPrograms.clear(),this.percussionKeys.clear(),this._mainState=this.createStateFromFile(e),this._currentState=this._mainState}createStateFromFile(e){const t=new hi;this.percussionKeys.add(Re.MetronomeKey),t.tempoChanges=[],t.division=e.division,t.eventIndex=0,t.currentTime=0,t.synthData=[];let s=120,i=0,a=0,r=0,n=0,o=0,h=0,l=0,d=0;for(let c of e.events){let u=new ni(t.synthData.length,c);t.synthData.push(u);let p=c.tick-d;if(i+=p,a+=p*(6e4/(s*e.division)),u.time=a,d=c.tick,n>0)for(;h<i;){let e=ni.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(c.type===je.TempoChange){s=6e7/c.microSecondsPerQuarterNote,t.tempoChanges.push(new oi(s,i,a)),o=n*(6e4/(s*e.division))}else if(c.type===je.TimeSignature){let i=c,a=Math.pow(2,i.denominatorIndex);r=i.numerator,n=t.division*(4/a)|0,o=n*(6e4/(s*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=i.numerator,t.firstTimeSignatureDenominator=a)}else if(c.type===je.ProgramChange){const e=c;let s=e.channel;t.firstProgramEventPerChannel.has(s)||t.firstProgramEventPerChannel.set(s,u);s===Re.PercussionChannel||this.instrumentPrograms.add(e.program)}else if(c.type==je.NoteOn){const e=c;e.channel===Re.PercussionChannel&&this.percussionKeys.add(e.noteKey)}}return t.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),t.endTime=a,t.endTick=i,t}fillMidiEventQueue(){return this.fillMidiEventQueueLimited(-1)}fillMidiEventQueueLimited(e){let t=Re.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 hi;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 oi(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=ni.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"}(Es||(Es={}));class di{constructor(e,t){this.state=e,this.stopped=t}}class ci{constructor(e,t,s,i,a){this.currentTime=e,this.endTime=t,this.currentTick=s,this.endTick=i,this.isSeek=a}}class ui{constructor(){this.id="",this.size=0}static load(e,t,s){if(e&&ui.HeaderSize>e.size)return!1;if(s.position+ui.HeaderSize>=s.length)return!1;if(t.id=Ae.read8BitStringLength(s,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=Ae.readUInt32LE(s),e&&ui.HeaderSize+t.size>e.size)return!1;e&&(e.size-=ui.HeaderSize+t.size);let i="RIFF"===t.id,a="LIST"===t.id;return(!i||!e)&&(!i&&!a||(t.id=Ae.read8BitStringLength(s,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}ui.HeaderSize=8;class pi{constructor(e,t,s,i){this.packetData=e,this.isBeginningOfStream=t,this.isEndOfStream=s,this.granulePosition=s?i:null}addData(e){const t=this.packetData,s=new Uint8Array(t.length+e.length);s.set(t,0),s.set(e,t.length)}}!function(e){e[e.ContinuesPacket=1]="ContinuesPacket",e[e.BeginningOfStream=2]="BeginningOfStream",e[e.EndOfStream=4]="EndOfStream"}(Fs||(Fs={}));class gi{constructor(e){this._readable=e}read(){const e=[];for(;this.findAndReadPage(e););return e}findAndReadPage(e){return!!this.seekPageHeader()&&this.readPage(e)}seekPageHeader(){for(let e=0;e<65536;e++){if(1399285583==Ae.readInt32LE(this._readable))return!0;this._readable.position-=3}return!1}readPage(e){const t=this._readable.readByte();if(-1===t||0!==t)return!1;const i=this._readable.readByte(),a=Ae.readInt64LE(this._readable);this._readable.skip(4),this._readable.skip(4),this._readable.skip(4);const r=this._readable.readByte();if(-1==r)return!1;const n=[];let o=0;for(let e=0;e<r;e++){const e=this._readable.readByte();o==n.length&&n.push(0),n[o]+=e,e<255&&o++}for(let t=0;t<n.length;t++){const r=new Uint8Array(n[t]);if(this._readable.read(r,0,r.length)!=r.length)return!1;if(i&Fs.ContinuesPacket){if(0==e.length)throw new j(s.Format,"OGG: Continuation page without any previous packets");e[e.length-1].addData(r)}else{const s=new pi(r,!!(i&Fs.BeginningOfStream)&&0==t,!!(i&Fs.EndOfStream)&&t==n.length-1,a);e.push(s)}}return!0}}class mi{constructor(){this.audioChannels=0,this.audioSampleRate=0,this.samples=new Float32Array(0),this.bitrateMaximum=0,this.bitrateNominal=0,this.bitrateMinimum=0,this.blocksize0=0,this.blocksize1=0}}class fi{constructor(){this.value=0,this.bitsRead=0}}class yi{constructor(e){this._bitBucket=0n,this._bitCount=0n,this._overflowBits=0n,this._source=e}readByte(){return this.readBits(yi.ByteSize)}readBit(){return 1==this.readBits(1)}readBytes(e){const t=new Uint8Array(e);for(let s=0;s<e;s++)t[s]=255&this.readByte();return t}readBits(e){if(0==e)return 0;const t=this.tryPeekBits(e);return this.skipBits(e),t.value}tryPeekBits(e){if(e<0||e>32)throw new j(s.General,"IO: Cannot read more than 32 bits in one go");if(0==e)return new fi;const t=new fi;for(;this._bitCount<e;){const e=BigInt(this._source.readByte());if(-1n==e)return t.bitsRead=Number(this._bitCount),t.value=Number(this._bitBucket),this._bitBucket=0n,this._bitCount=0n,t;this._bitBucket=(0xffn&e)<<this._bitCount|this._bitBucket,this._bitCount+=8n,this._bitCount>32&&(this._overflowBits=e>>40n-this._bitCount&0xffn)}let i=this._bitBucket;return e<64&&(i&=(1n<<BigInt(e))-1n),t.value=Number(i),t.bitsRead=e,t}skipBits(e){let t=BigInt(e);if(0==e);else if(this._bitCount>t){if(this._bitBucket=e>31?0n:this._bitBucket>>t,this._bitCount>32){const s=this._bitCount-32n;this._bitBucket=this._bitBucket|this._overflowBits<<this._bitCount-t-s,s>e&&(this._overflowBits=this._overflowBits>>t&0xffn)}this._bitCount-=t}else if(this._bitCount==t)this._bitBucket=0n,this._bitCount=0n;else{for(t-=this._bitCount,this._bitCount=0n,this._bitBucket=0n;t>8;){if(-1==this._source.readByte()){t=0n;break}t-=8n}if(t>0){const e=BigInt(this._source.readByte());-1n==e||(this._bitBucket=e>>t,this._bitCount=8n-t)}}}}yi.ByteSize=8;class bi{constructor(){this.codebooks=[],this.timeDomainTransforms=[],this.floors=[],this.residues=[],this.mappings=[],this.modes=[]}}class Si{static ilog(e){let t=0;for(;e>0;)++t,e>>=1;return t}static bitReverse(e,t=32){let s=BigInt(e);s=(s&BigInt(2863311530))>>1n|(s&BigInt(1431655765))<<1n,s=(s&BigInt(3435973836))>>2n|(s&BigInt(858993459))<<2n,s=(s&BigInt(4042322160))>>4n|(s&BigInt(252645135))<<4n,s=(s&BigInt(4278255360))>>8n|(s&BigInt(16711935))<<8n,s=(s>>16n|s<<16n)>>32n-BigInt(t);return Number(BigInt.asUintN(32,s))}static convertFromVorbisFloat32(e){const t=BigInt(e);let s=t&BigInt(2097151);const i=t&BigInt(2147483648),a=(t&BigInt(2145386496))>>21n;return 0n!==i&&(s=-s),Number(s)*Math.pow(2,Number(a)-788)}}class _i{constructor(e){this._data=e}get(e){return this._data[e]}}class wi{get(e){return e}}wi.instance=new wi;class Bi{constructor(e,t){this._maxBits=0,this._overflowList=null,this._prefixList=null,this._prefixBitLength=0,this.dimensions=0,this.entries=0,this.mapType=0;if(5653314!=e.readBits(24))throw new j(s.Format,"Vorbis: Book header had invalid signature!");this.dimensions=e.readBits(16),this.entries=e.readBits(24),this._lengths=new Int32Array(this.entries),this.initTree(e,t),this.initLookupTable(e)}get(e,t){return this._lookupTable[e*this.dimensions+t]}decodeScalar(e){let t=e.tryPeekBits(this._prefixBitLength);if(0==t.bitsRead)return-1;let s=this._prefixList[t.value];if(null!=s)return e.skipBits(s.length),s.value;if(t=e.tryPeekBits(this._maxBits),null!==this._overflowList)for(let i=0;i<this._overflowList.length;i++){s=this._overflowList[i];const a=t.value&s.mask;if(s.bits==a)return e.skipBits(s.length),s.value}return-1}initTree(e,t){let i,a,r=0;if(e.readBit()){let t=e.readBits(5)+1;for(let s=0;s<this.entries;){let i=e.readBits(Si.ilog(this.entries-s));for(;--i>=0;)this._lengths[s++]=t;++t}r=0,i=!1,a=t}else{a=-1,i=e.readBit();for(let t=0;t<this.entries;t++)!i||e.readBit()?(this._lengths[t]=e.readBits(5)+1,++r):this._lengths[t]=-1,this._lengths[t]>a&&(a=this._lengths[t])}if(this._maxBits=a,a>-1){let e,a=null;i&&r>=this.entries>>2&&(a=new Int32Array(this.entries),a.set(this._lengths.subarray(0,this.entries),0),i=!1),e=i?r:0;let n=null,o=null;if(i?0!=e&&(a=new Int32Array(e),o=new Int32Array(e),n=new Int32Array(e)):o=new Int32Array(this.entries),!this.computeCodewords(i,o,a,this._lengths,this.entries,n))throw new j(s.Format,"Vorbis: Failed to compute codewords");const h=null==n?wi.instance:new _i(n);t.generateTable(h,a??this._lengths,o),this._prefixList=t.prefixTree,this._prefixBitLength=t.tableBits,this._overflowList=t.overflowList}}computeCodewords(e,t,s,i,a,r){const n=new Uint32Array(32);let o=0,h=0;for(o=0;o<a&&!(i[o]>0);++o);if(o==a)return!0;this.addEntry(e,t,s,0,o,h++,i[o],r);for(let e=1;e<=i[o];++e)n[e]=1<<32-e;for(let l=o+1;l<a;++l){let a=i[l];if(a<=0)continue;for(;a>0&&0==n[a];)--a;if(0==a)return!1;let o=n[a];if(n[a]=0,this.addEntry(e,t,s,Si.bitReverse(o),l,h++,i[l],r),a!=i[l])for(let e=i[l];e>a;--e)n[e]=o+(1<<32-e)}return!0}addEntry(e,t,s,i,a,r,n,o){e?(t[r]=i,s[r]=n,o[r]=a):t[a]=i}initLookupTable(e){if(this.mapType=e.readBits(4),0==this.mapType)return;const t=Si.convertFromVorbisFloat32(e.readBits(32)),s=Si.convertFromVorbisFloat32(e.readBits(32)),i=e.readBits(4)+1,a=e.readBit();let r=this.entries*this.dimensions;const n=new Float32Array(r);1==this.mapType&&(r=this.lookup1Values());const o=new Uint32Array(r);for(let t=0;t<r;t++)o[t]=e.readBits(i);if(1==this.mapType)for(let e=0;e<this.entries;e++){let i=0,h=1;for(let l=0;l<this.dimensions;l++){const d=o[e/h%r|0]*s+t+i;n[e*this.dimensions+l]=d,a&&(i=d),h*=r}}else for(let e=0;e<this.entries;e++){let i=0,r=e*this.dimensions;for(let h=0;h<this.dimensions;h++){const l=o[r]*s+t+i;n[e*this.dimensions+h]=l,a&&(i=l),++r}}this._lookupTable=n}lookup1Values(){let e=Math.floor(Math.exp(Math.log(this.entries)/this.dimensions));return Math.floor(Math.pow(e+1,this.dimensions))<=this.entries&&++e,e}}class ki{constructor(){this.value=0,this.length=0,this.bits=0,this.mask=0}}class Ti{constructor(){this.tableBits=0,this.prefixTree=[],this.overflowList=null}generateTable(e,t,s){const i=new Array(t.length);let a=0;for(let r=0;r<i.length;r++){const n=new ki;n.value=e.get(r),n.length=t[r]<=0?99999:t[r],n.bits=s[r],n.mask=(1<<t[r])-1,i[r]=n,t[r]>0&&a<t[r]&&(a=t[r])}i.sort(((e,t)=>{const s=e.length-t.length;return 0===s?e.bits-t.bits:s}));const r=a>Ti.MAX_TABLE_BITS?Ti.MAX_TABLE_BITS:a,n=[];let o=null;for(let e=0;e<i.length&&i[e].length<99999;e++){const t=i[e].length;if(t>r)for(o=[];e<i.length&&i[e].length<99999;e++)o.push(i[e]);else{const s=1<<r-t,a=i[e];for(let e=0;e<s;e++){const s=e<<t|a.bits;for(;n.length<=s;)n.push(null);n[s]=a}}}for(;n.length<1<<r;)n.push(null);this.tableBits=r,this.prefixTree=n,this.overflowList=o}}Ti.MAX_TABLE_BITS=10;class xi{constructor(e){e.readBits(16)}}class Ni{get executeChannel(){return(this.forceEnergy||this.amp>0)&&!this.forceNoEnergy}constructor(e){this.amp=0,this.forceEnergy=!1,this.forceNoEnergy=!1,this.coeff=e}}class vi{constructor(e,t,i,a){if(this._order=e.readBits(8),this._rate=e.readBits(16),this._bark_map_size=e.readBits(16),this._ampBits=e.readBits(6),this._ampOfs=e.readBits(8),this._books=new Array(e.readBits(4)+1),this._order<1||this._rate<1||this._bark_map_size<1||0==this._books.length)throw new j(s.Format,"Vorbis: Invalid Floor0 Data");this._ampDiv=(1<<this._ampBits)-1;for(let t=0;t<this._books.length;t++){const i=e.readBits(8);if(i<0||i>=a.length)throw new j(s.Format,"Vorbis: Invalid Floor0 Data");const r=a[i];if(0==r.mapType||r.dimensions<1)throw new j(s.Format,"Vorbis: Invalid Floor0 Data");this._books[t]=r}this._bookBits=Si.ilog(this._books.length),this._barkMaps=new Map([[t,this.synthesizeBarkCurve(t/2)],[i,this.synthesizeBarkCurve(i/2)]]),this._wMap=new Map([[t,this.synthesizeWDelMap(t/2)],[i,this.synthesizeWDelMap(i/2)]])}synthesizeBarkCurve(e){const t=this._bark_map_size/vi.toBARK(this._rate/2),s=new Int32Array(e+1);for(let i=0;i<e-1;i++)s[i]=Math.min(this._bark_map_size-1,Math.floor(vi.toBARK(this._rate/2/e*i)*t));return s[e]=-1,s}static toBARK(e){return 13.1*Math.atan(74e-5*e)+2.24*Math.atan(1.85e-8*e*e)+1e-4*e}synthesizeWDelMap(e){const t=Math.PI/this._bark_map_size,s=new Float32Array(e);for(let i=0;i<e;i++)s[i]=2*Math.cos(t*i);return s}unpack(e,t,s){var i=new Ni(new Float32Array(this._order+1));if(i.amp=e.readBits(this._ampBits),i.amp>0){i.amp=i.amp/this._ampDiv*this._ampOfs;const t=e.readBits(this._bookBits);if(t>=this._books.length)return i.amp=0,i;const s=this._books[t];for(let t=0;t<this._order;){const a=s.decodeScalar(e);if(-1==a)return i.amp=0,i;for(let e=0;t<this._order&&e<s.dimensions;e++,t++)i.coeff[t]=s.get(a,e)}let a=0;for(let e=0;e<this._order;){for(let t=0;e<this._order&&t<s.dimensions;e++,t++)i.coeff[e]+=a;a=i.coeff[e-1]}}return i}apply(e,t,s){const i=e;var a=t/2;if(i.amp>0){const e=this._barkMaps.get(t),r=this._wMap.get(t);let n=0;for(n=0;n<this._order;n++)i.coeff[n]=2*Math.cos(i.coeff[n]);for(n=0;n<a;){let t=0;const a=e[n];let o=.5,h=.5,l=r[a];for(t=1;t<this._order;t+=2)h*=l-i.coeff[t-1],o*=l-i.coeff[t];for(t==this._order?(h*=l-i.coeff[t-1],o*=o*(4-l*l),h*=h):(o*=o*(2-l),h*=h*(2+l)),h=i.amp/Math.sqrt(o+h)-this._ampOfs,h=Math.exp(.11512925*h),s[n]*=h;e[++n]==a;)s[n]*=h}}else s.fill(0,0,a)}}class Pi{constructor(){this.posts=new Int32Array(64),this.postCount=0,this.forceEnergy=!1,this.forceNoEnergy=!1}get executeChannel(){return(this.forceEnergy||this.postCount>0)&&!this.forceNoEnergy}}class Ci{constructor(e,t){let i=-1;this._partitionClass=new Int32Array(e.readBits(5));for(let t=0;t<this._partitionClass.length;t++)this._partitionClass[t]=e.readBits(4),this._partitionClass[t]>i&&(i=this._partitionClass[t]);++i,this._classDimensions=new Int32Array(i),this._classSubclasses=new Int32Array(i),this._classMasterbooks=new Array(i),this._classMasterBookIndex=new Int32Array(i),this._subclassBooks=new Array(i),this._subclassBookIndex=new Array(i);for(let s=0;s<i;s++){this._classDimensions[s]=e.readBits(3)+1,this._classSubclasses[s]=e.readBits(2),this._classSubclasses[s]>0&&(this._classMasterBookIndex[s]=e.readBits(8),this._classMasterbooks[s]=t[this._classMasterBookIndex[s]]),this._subclassBooks[s]=new Array(1<<this._classSubclasses[s]),this._subclassBookIndex[s]=new Int32Array(this._subclassBooks[s].length);for(let i=0;i<this._subclassBooks[s].length;i++){const a=e.readBits(8)-1;a>=0&&(this._subclassBooks[s][i]=t[a]),this._subclassBookIndex[s][i]=a}}this._multiplier=e.readBits(2),this._range=Ci._rangeLookup[this._multiplier],this._yBits=Ci._yBitsLookup[this._multiplier],++this._multiplier;const a=e.readBits(4),r=[];r.push(0),r.push(1<<a);for(let t=0;t<this._partitionClass.length;t++){const s=this._partitionClass[t];for(let t=0;t<this._classDimensions[s];t++)r.push(e.readBits(a))}this._xList=new Int32Array(r),this._lNeigh=new Int32Array(r.length),this._hNeigh=new Int32Array(r.length),this._sortIdx=new Int32Array(r.length),this._sortIdx[0]=0,this._sortIdx[1]=1;for(let e=2;e<this._lNeigh.length;e++){this._lNeigh[e]=0,this._hNeigh[e]=1,this._sortIdx[e]=e;for(let t=2;t<e;t++){const s=this._xList[t];s<this._xList[e]?s>this._xList[this._lNeigh[e]]&&(this._lNeigh[e]=t):s<this._xList[this._hNeigh[e]]&&(this._hNeigh[e]=t)}}for(let e=0;e<this._sortIdx.length-1;e++)for(let t=e+1;t<this._sortIdx.length;t++){if(this._xList[e]==this._xList[t])throw new j(s.Format,"Vorbis: Invalid Floor1 Data");if(this._xList[this._sortIdx[e]]>this._xList[this._sortIdx[t]]){const s=this._sortIdx[e];this._sortIdx[e]=this._sortIdx[t],this._sortIdx[t]=s}}}unpack(e,t,s){var i=new Pi;if(e.readBit()){let t=2;i.posts[0]=e.readBits(this._yBits),i.posts[1]=e.readBits(this._yBits);for(let s=0;s<this._partitionClass.length;s++){const a=this._partitionClass[s],r=this._classDimensions[a],n=this._classSubclasses[a],o=(1<<n)-1;let h=0;if(n>0&&(h=this._classMasterbooks[a].decodeScalar(e),-1==h)){t=0;break}for(let l=0;l<r;l++){const r=this._subclassBooks[a][h&o];if(h>>=n,null!=r&&(i.posts[t]=r.decodeScalar(e),-1==i.posts[t])){t=0,s=this._partitionClass.length;break}++t}}i.postCount=t}return i}apply(e,t,s){const i=e,a=t/2;if(i.postCount>0){const e=this.unwrapPosts(i);let t=0,h=i.posts[0]*this._multiplier;for(let l=1;l<i.postCount;l++){var r=this._sortIdx[l];if(e[r]){var n=this._xList[r],o=i.posts[r]*this._multiplier;t<a&&this.renderLineMulti(t,h,Math.min(n,a),o,s),t=n,h=o}if(t>=a)break}t<a&&this.renderLineMulti(t,h,a,h,s)}else s.fill(0,0,a)}unwrapPosts(e){const t=new Array(64);t.fill(!1),t[0]=!0,t[1]=!0;const s=new Int32Array(64);s[0]=e.posts[0],s[1]=e.posts[1];for(let i=2;i<e.postCount;i++){const a=this._lNeigh[i],r=this._hNeigh[i],n=this.renderPoint(this._xList[a],s[a],this._xList[r],s[r],this._xList[i]),o=e.posts[i],h=this._range-n,l=n;let d;d=h<l?2*h:2*l,0!=o?(t[a]=!0,t[r]=!0,t[i]=!0,s[i]=o>=d?h>l?o-l+n:n-o+h-1:o%2==1?n-(o+1)/2:n+o/2):(t[i]=!1,s[i]=n)}for(let t=0;t<e.postCount;t++)e.posts[t]=s[t];return t}renderPoint(e,t,s,i,a){var r=i-t,n=s-e,o=Math.abs(r)*(a-e)/n|0;return r<0?t-o:t+o}renderLineMulti(e,t,s,i,a){const r=i-t,n=s-e;let o=Math.abs(r);const h=1-2*(r>>31&1),l=r/n|0;let d=e,c=t,u=-n;for(a[e]*=Ci.inverse_dB_table[t],o-=Math.abs(l)*n;++d<s;)c+=l,u+=o,u>=0&&(u-=n,c+=h),a[d]*=Ci.inverse_dB_table[c]}}Ci._rangeLookup=[256,128,86,64],Ci._yBitsLookup=[8,7,7,6],Ci.inverse_dB_table=new Float32Array([1.0649863e-7,1.1341951e-7,1.2079015e-7,1.2863978e-7,1.3699951e-7,1.4590251e-7,1.5538408e-7,1.6548181e-7,1.7623575e-7,1.8768855e-7,1.9988561e-7,2.128753e-7,2.2670913e-7,2.4144197e-7,2.5713223e-7,2.7384213e-7,2.9163793e-7,3.1059021e-7,3.3077411e-7,3.5226968e-7,3.7516214e-7,3.9954229e-7,4.255068e-7,4.5315863e-7,4.8260743e-7,5.1396998e-7,5.4737065e-7,5.8294187e-7,6.2082472e-7,6.6116941e-7,7.0413592e-7,7.4989464e-7,7.9862701e-7,8.505263e-7,9.0579828e-7,9.6466216e-7,10273513e-13,10941144e-13,11652161e-13,12409384e-13,13215816e-13,14074654e-13,14989305e-13,15963394e-13,17000785e-13,18105592e-13,19282195e-13,20535261e-13,21869758e-13,23290978e-13,24804557e-13,26416497e-13,2813319e-12,29961443e-13,31908506e-13,33982101e-13,36190449e-13,38542308e-13,41047004e-13,4371447e-12,46555282e-13,49580707e-13,5280274e-12,5623416e-12,59888572e-13,63780469e-13,67925283e-13,72339451e-13,77040476e-13,82047e-10,87378876e-13,93057248e-13,99104632e-13,10554501e-12,11240392e-12,11970856e-12,12748789e-12,13577278e-12,14459606e-12,15399272e-12,16400004e-12,17465768e-12,18600792e-12,19809576e-12,21096914e-12,22467911e-12,23928002e-12,25482978e-12,27139006e-12,28902651e-12,30780908e-12,32781225e-12,34911534e-12,37180282e-12,39596466e-12,42169667e-12,4491009e-11,47828601e-12,50936773e-12,54246931e-12,57772202e-12,61526565e-12,65524908e-12,69783085e-12,74317983e-12,79147585e-12,8429104e-11,89768747e-12,95602426e-12,.00010181521,.00010843174,.00011547824,.00012298267,.00013097477,.00013948625,.00014855085,.00015820453,.00016848555,.00017943469,.00019109536,.00020351382,.00021673929,.00023082423,.00024582449,.00026179955,.00027881276,.00029693158,.00031622787,.00033677814,.00035866388,.00038197188,.00040679456,.00043323036,.00046138411,.00049136745,.00052329927,.00055730621,.00059352311,.00063209358,.00067317058,716917e-9,.0007635063,.00081312324,.00086596457,.00092223983,.00098217216,.0010459992,.0011139742,.0011863665,.0012634633,.0013455702,.0014330129,.0015261382,.0016253153,.0017309374,.0018434235,.0019632195,.0020908006,.0022266726,.0023713743,.0025254795,.0026895994,.0028643847,.0030505286,.0032487691,.0034598925,.0036847358,.0039241906,.0041792066,.004450795,.0047400328,.0050480668,.0053761186,.0057254891,.0060975636,.0064938176,.0069158225,.0073652516,.0078438871,.0083536271,.0088964928,.009474637,.010090352,.01074608,.011444421,.012188144,.012980198,.013823725,.014722068,.015678791,.016697687,.017782797,.018938423,.020169149,.021479854,.022875735,.02436233,.025945531,.027631618,.029427276,.031339626,.033376252,.035545228,.037855157,.040315199,.042935108,.045725273,.048696758,.051861348,.055231591,.05882085,.062643361,.066714279,.071049749,.075666962,.080584227,.085821044,.091398179,.097337747,.1036633,.11039993,.11757434,.12521498,.13335215,.14201813,.15124727,.16107617,.1715438,.18269168,.19456402,.20720788,.22067342,.23501402,.25028656,.26655159,.28387361,.30232132,.32196786,.34289114,.36517414,.38890521,.41417847,.44109412,.4697589,.50028648,.53279791,.56742212,.6042964,.64356699,.68538959,.72993007,.77736504,.8278826,.88168307,.9389798,1]);class Ei{constructor(e,t,i,a){const r=e.readBits(16);switch(r){case 0:this.floor=new vi(e,t,i,a);break;case 1:this.floor=new Ci(e,a);break;default:throw new j(s.Format,"Vorbis: Invalid Floor type: "+r)}}apply(e,t,s){this.floor.apply(e,t,s)}unpack(e,t,s){return this.floor.unpack(e,t,s)}}class Fi{constructor(e,t,i){this._begin=e.readBits(24),this._end=e.readBits(24),this._partitionSize=e.readBits(24)+1,this._classifications=e.readBits(6)+1,this._classBook=i[e.readBits(8)],this._cascade=new Int32Array(this._classifications);let a=0;for(let t=0;t<this._classifications;t++){const s=e.readBits(3);e.readBit()?this._cascade[t]=e.readBits(5)<<3|s:this._cascade[t]=s,a+=Fi.icount(this._cascade[t])}const r=new Int32Array(a);for(let t=0;t<a;t++)if(r[t]=e.readBits(8),0==i[r[t]].mapType)throw new j(s.Format,"Vorbis: Invalid Residue 0");const n=this._classBook.entries;let o=this._classBook.dimensions,h=1;for(;o>0;){if(h*=this._classifications,h>n)throw new j(s.Format,"Vorbis: Invalid Residue 0");--o}this._books=new Array(this._classifications),a=0;let l,d=0;for(let e=0;e<this._classifications;e++)if(l=Si.ilog(this._cascade[e]),this._books[e]=new Array(l),l>0){d=Math.max(d,l);for(let t=0;t<l;t++)(this._cascade[e]&1<<t)>0&&(this._books[e][t]=i[r[a++]])}this._maxStages=d,this._decodeMap=new Array(h);for(let e=0;e<h;e++){let t=e,s=h/this._classifications|0;this._decodeMap[e]=new Int32Array(this._classBook.dimensions);for(let i=0;i<this._classBook.dimensions;i++){const a=t/s|0;t-=a*s,s=s/this._classifications|0,this._decodeMap[e][i]=a}}this._channels=t}static icount(e){let t=0;for(;0!=e;)t+=1&e,e>>=1;return t}decode(e,t,s,i){const a=(this._end<s/2?this._end:s/2)-this._begin;if(a>0&&-1!==t.indexOf(!1)){const t=a/this._partitionSize,s=(t+this._classBook.dimensions-1)/this._classBook.dimensions|0,r=[];for(let e=0;e<this._channels;e++)r.push(new Array(s));for(let s=0;s<this._maxStages;s++)for(let a=0,n=0;a<t;n++){if(0==s)for(let i=0;i<this._channels;i++){const o=this._classBook.decodeScalar(e);if(!(o>=0&&o<this._decodeMap.length)){a=t,s=this._maxStages;break}r[i][n]=this._decodeMap[o]}for(let o=0;a<t&&o<this._classBook.dimensions;o++,a++){const h=this._begin+a*this._partitionSize;for(let l=0;l<this._channels;l++){const d=r[l][n][o];if(this._cascade[d]&1<<s){const r=this._books[d][s];if(r&&this.writeVectors(r,e,i,l,h,this._partitionSize)){a=t,s=this._maxStages;break}}}}}}}writeVectors(e,t,s,i,a,r){const n=s[i],o=r/e.dimensions,h=new Int32Array(o);for(let s=0;s<o;s++)if(h[s]=e.decodeScalar(t),-1==h[s])return!0;for(let t=0;t<e.dimensions;t++)for(let s=0;s<o;s++,a++)n[a]+=e.get(h[s],t);return!1}}class Di extends Fi{constructor(e,t,s){super(e,t,s)}writeVectors(e,t,s,i,a,r){const n=s[i];for(let s=0;s<r;){const i=e.decodeScalar(t);if(-1==i)return!0;for(let t=0;t<e.dimensions;s++,t++)n[a+s]+=e.get(i,t)}return!1}}class Li extends Fi{constructor(e,t,s){super(e,1,s),this._realChannels=t}decode(e,t,s,i){super.decode(e,t,s*this._realChannels,i)}writeVectors(e,t,s,i,a,r){let n=0;a/=this._realChannels;for(let i=0;i<r;){const r=e.decodeScalar(t);if(-1==r)return!0;for(let t=0;t<e.dimensions;t++,i++)s[n][a]+=e.get(r,t),++n==this._realChannels&&(n=0,a++)}return!1}}class Mi{constructor(e,t,i){const a=e.readBits(16);switch(a){case 0:this.residue=new Fi(e,t,i);break;case 1:this.residue=new Di(e,t,i);break;case 2:this.residue=new Li(e,t,i);break;default:throw new j(s.Format,"Vorbis: Invalid Residue type: "+a)}}decode(e,t,s,i){this.residue.decode(e,t,s,i)}}class Ii{constructor(e,t,i,a,r){if(0!==e.readBits(16))throw new j(s.Format,"Vorbis: Invalid mapping type!");let n=1;e.readBit()&&(n+=e.readBits(4));let o=0;e.readBit()&&(o=e.readBits(8)+1);const h=Si.ilog(t-1);this._couplingAngle=new Int32Array(o),this._couplingMangitude=new Int32Array(o);for(let i=0;i<o;i++){const a=e.readBits(h),r=e.readBits(h);if(a==r||a>t-1||r>t-1)throw new j(s.Format,"Vorbis: Invalid magnitude or angle in mapping header!");this._couplingAngle[i]=r,this._couplingMangitude[i]=a}if(0!=e.readBits(2))throw new j(s.Format,"Vorbis: Reserved bits not 0 in mapping header.");const l=new Int32Array(t);if(n>1)for(let i=0;i<t;i++)if(l[i]=e.readBits(4),l[i]>n)throw new j(s.Format,"Vorbis: Invalid channel mux submap index in mapping header!");this._submapFloor=new Array(n),this._submapResidue=new Array(n);for(let t=0;t<n;t++){e.skipBits(8);const r=e.readBits(8);if(r>=i.length)throw new j(s.Format,"Vorbis: Invalid floor number in mapping header!");const n=e.readBits(8);if(n>=a.length)throw new j(s.Format,"Vorbis: Invalid residue number in mapping header!");this._submapFloor[t]=i[r],this._submapResidue[t]=a[n]}this._channelFloor=new Array(t),this._channelResidue=new Array(t);for(let e=0;e<t;e++)this._channelFloor[e]=this._submapFloor[l[e]],this._channelResidue[e]=this._submapResidue[l[e]];this._mdct=r}decodePacket(e,t,s){const i=t>>1,a=new Array(this._channelFloor.length),r=new Array(this._channelFloor.length);r.fill(!1);for(let n=0;n<this._channelFloor.length;n++)a[n]=this._channelFloor[n].unpack(e,t,n),r[n]=!a[n].executeChannel,s[n].fill(0,0,i);for(let e=0;e<this._couplingAngle.length;e++)(a[this._couplingAngle[e]].executeChannel||a[this._couplingMangitude[e]].executeChannel)&&(a[this._couplingAngle[e]].forceEnergy=!0,a[this._couplingMangitude[e]].forceEnergy=!0);for(let i=0;i<this._submapFloor.length;i++){for(let e=0;e<this._channelFloor.length;e++)this._submapFloor[i]==this._channelFloor[e]&&this._submapResidue[i]==this._channelResidue[e]||(a[e].forceNoEnergy=!0);this._submapResidue[i].decode(e,r,t,s)}for(let e=this._couplingAngle.length-1;e>=0;e--)if(a[this._couplingAngle[e]].executeChannel||a[this._couplingMangitude[e]].executeChannel){const t=s[this._couplingMangitude[e]],a=s[this._couplingAngle[e]];for(var n=0;n<i;n++){let e,s;const i=t[n],r=a[n];i>0?r>0?(e=i,s=i-r):(s=i,e=i+r):r>0?(e=i,s=i+r):(s=i,e=i-r),t[n]=e,a[n]=s}}for(let e=0;e<this._channelFloor.length;e++)a[e].executeChannel?(this._channelFloor[e].apply(a[e],t,s[e]),this._mdct.reverse(s[e],t)):s[e].fill(0,i,2*i)}}class Ai{constructor(){this.packetStartIndex=0,this.packetTotalLength=0,this.packetValidLength=0}}class Oi{constructor(){this.overlapInfo=new Ai,this.windowIndex=0}}class Ri{constructor(e=null){this.samplePosition=null,this.samplePosition=e}}class Vi{constructor(e,t,i,a,r){if(this._overlapInfo=null,this._channels=t,this._blockFlag=e.readBit(),0!=e.readBits(32))throw new j(s.Format,"Vorbis: Mode header had invalid window or transform type!");const n=e.readBits(8);if(n>=r.length)throw new j(s.Format,"Vorbis: Mode header had invalid mapping index!");this._mapping=r[n],this._blockFlag?(this._blockSize=a,this._windows=[Vi.calcWindow(i,a,i),Vi.calcWindow(a,a,i),Vi.calcWindow(i,a,a),Vi.calcWindow(a,a,a)],this._overlapInfo=[Vi.calcOverlap(i,a,i),Vi.calcOverlap(a,a,i),Vi.calcOverlap(i,a,a),Vi.calcOverlap(a,a,a)]):(this._blockSize=i,this._windows=[Vi.calcWindow(i,i,i)])}decode(e,t){const s=this.getPacketInfo(e);this._mapping.decodePacket(e,this._blockSize,t);const i=this._windows[s.windowIndex];for(let e=0;e<this._blockSize;e++)for(let s=0;s<this._channels;s++)t[s][e]*=i[e];return s.overlapInfo}getPacketInfo(e){const t=new Oi;if(this._blockFlag){const s=e.readBit(),i=e.readBit();t.windowIndex=(s?1:0)+(i?2:0);const a=this._overlapInfo[t.windowIndex];t.overlapInfo.packetStartIndex=a.packetStartIndex,t.overlapInfo.packetValidLength=a.packetValidLength,t.overlapInfo.packetTotalLength=a.packetTotalLength}else t.windowIndex=0,t.overlapInfo.packetStartIndex=0,t.overlapInfo.packetValidLength=this._blockSize/2,t.overlapInfo.packetTotalLength=this._blockSize;return t}static calcWindow(e,t,s){const i=new Float32Array(t),a=e/2,r=s/2,n=t/4-a/2,o=t-t/4-r/2;for(let e=0;e<a;e++){let t=Math.sin((e+.5)/a*Vi.M_PI2);t*=t,i[n+e]=Math.sin(t*Vi.M_PI2)}for(let e=n+a;e<o;e++)i[e]=1;for(let e=0;e<r;e++){let t=Math.sin((r-e-.5)/r*Vi.M_PI2);t*=t,i[o+e]=Math.sin(t*Vi.M_PI2)}return i}static calcOverlap(e,t,s){const i=s/4,a=t/4-e/4,r=t/4*3+i,n=r-2*i,o=new Ai;return o.packetStartIndex=a,o.packetValidLength=n,o.packetTotalLength=r,o}}Vi.M_PI2=1.57079632695;class Hi{constructor(e){this._n=e,this._n2=e>>1,this._n4=this._n2>>1,this._n8=this._n4>>1,this._ld=Si.ilog(e)-1,this._a=new Float32Array(this._n2),this._b=new Float32Array(this._n2),this._c=new Float32Array(this._n4);let t=0,s=0;for(;t<this._n4;++t,s+=2)this._a[s]=Math.cos(4*t*Hi.M_PI/e),this._a[s+1]=-Math.sin(4*t*Hi.M_PI/e),this._b[s]=.5*Math.cos((s+1)*Hi.M_PI/e/2),this._b[s+1]=.5*Math.sin((s+1)*Hi.M_PI/e/2);for(t=0,s=0;t<this._n8;++t,s+=2)this._c[s]=Math.cos(2*(s+1)*Hi.M_PI/e),this._c[s+1]=-Math.sin(2*(s+1)*Hi.M_PI/e);this._bitrev=new Uint16Array(this._n8);for(let e=0;e<this._n8;++e)this._bitrev[e]=Ie.int32ToUint16(Si.bitReverse(e,this._ld-3)<<2)}calcReverse(e){let t,s;const i=new Float32Array(this._n2);{let t=this._n2-2,s=0,a=0,r=this._n2;for(;a!=r;)i[t+1]=e[a]*this._a[s]-e[a+2]*this._a[s+1],i[t]=e[a]*this._a[s+1]+e[a+2]*this._a[s],t-=2,s+=2,a+=4;for(a=this._n2-3;t>=0;)i[t+1]=-e[a+2]*this._a[s]- -e[a]*this._a[s+1],i[t]=-e[a+2]*this._a[s+1]+-e[a]*this._a[s],t-=2,s+=2,a-=4}t=e,s=i;{let e=this._n2-8,i=this._n4,a=0,r=this._n4,n=0;for(;e>=0;){let o,h;h=s[i+1]-s[a+1],o=s[i]-s[a],t[r+1]=s[i+1]+s[a+1],t[r]=s[i]+s[a],t[n+1]=h*this._a[e+4]-o*this._a[e+5],t[n]=o*this._a[e+4]+h*this._a[e+5],h=s[i+3]-s[a+3],o=s[i+2]-s[a+2],t[r+3]=s[i+3]+s[a+3],t[r+2]=s[i+2]+s[a+2],t[n+3]=h*this._a[e]-o*this._a[e+1],t[n+2]=o*this._a[e]+h*this._a[e+1],e-=8,r+=4,n+=4,i+=4,a+=4}}this.step3_iter0_loop(this._n>>4,t,this._n2-1-0*this._n4,-this._n8),this.step3_iter0_loop(this._n>>4,t,this._n2-1-1*this._n4,-this._n8),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-0*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-1*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-2*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-3*this._n8,-(this._n>>4),16);let a=2;for(;a<this._ld-3>>1;++a){const e=this._n>>a+2,s=e>>1,i=1<<a+1;for(let r=0;r<i;++r)this.step3_inner_r_loop(this._n>>a+4,t,this._n2-1-e*r,-s,1<<a+3)}for(;a<this._ld-6;++a){const e=this._n>>a+2,s=1<<a+3,i=e>>1,r=this._n>>a+6,n=1<<a+1;let o=this._n2-1,h=0;for(let a=r;a>0;--a)this.step3_inner_s_loop(n,t,o,-i,h,s,e),h+=4*s,o-=8}this.step3_inner_s_loop_ld654(this._n>>5,t,this._n2-1,this._n);{let e=0,i=this._n4-4,a=this._n2-4;for(;i>=0;){let r;r=this._bitrev[e],s[a+3]=t[r],s[a+2]=t[r+1],s[i+3]=t[r+2],s[i+2]=t[r+3],r=this._bitrev[e+1],s[a+1]=t[r],s[a]=t[r+1],s[i+1]=t[r+2],s[i]=t[r+3],i-=4,a-=4,e+=2}}for(var r=0,n=0,o=this._n2-4;n<o;){let e,t,i,a,h,l;e=s[n]-s[o+2],t=s[n+1]+s[o+3],i=this._c[r+1]*e+this._c[r]*t,a=this._c[r+1]*t-this._c[r]*e,h=s[n]+s[o+2],l=s[n+1]-s[o+3],s[n]=h+i,s[n+1]=l+a,s[o+2]=h-i,s[o+3]=a-l,e=s[n+2]-s[o],t=s[n+3]+s[o+1],i=this._c[r+3]*e+this._c[r+2]*t,a=this._c[r+3]*t-this._c[r+2]*e,h=s[n+2]+s[o],l=s[n+3]-s[o+1],s[n+2]=h+i,s[n+3]=l+a,s[o]=h-i,s[o+1]=a-l,r+=4,n+=4,o-=4}{let t=this._n2-8,s=this._n2-8,a=0,r=this._n2-4,n=this._n2,o=this._n-4;for(;s>=0;){let h,l,d,c;c=i[s+6]*this._b[t+7]-i[s+7]*this._b[t+6],d=-i[s+6]*this._b[t+6]-i[s+7]*this._b[t+7],e[a]=c,e[r+3]=-c,e[n]=d,e[o+3]=d,l=i[s+4]*this._b[t+5]-i[s+5]*this._b[t+4],h=-i[s+4]*this._b[t+4]-i[s+5]*this._b[t+5],e[a+1]=l,e[r+2]=-l,e[n+1]=h,e[o+2]=h,c=i[s+2]*this._b[t+3]-i[s+3]*this._b[t+2],d=-i[s+2]*this._b[t+2]-i[s+3]*this._b[t+3],e[a+2]=c,e[r+1]=-c,e[n+2]=d,e[o+1]=d,l=i[s]*this._b[t+1]-i[s+1]*this._b[t],h=-i[s]*this._b[t]-i[s+1]*this._b[t+1],e[a+3]=l,e[r]=-l,e[n+3]=h,e[o]=h,t-=8,s-=8,a+=4,n+=4,r-=4,o-=4}}}step3_inner_r_loop(e,t,s,i,a){let r,n,o=s,h=o+i,l=0;for(let s=e>>2;s>0;--s)r=t[o]-t[h],n=t[o-1]-t[h-1],t[o]+=t[h],t[o-1]+=t[h-1],t[h]=r*this._a[l]-n*this._a[l+1],t[h-1]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-2]-t[h-2],n=t[o-3]-t[h-3],t[o-2]+=t[h-2],t[o-3]+=t[h-3],t[h-2]=r*this._a[l]-n*this._a[l+1],t[h-3]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-4]-t[h-4],n=t[o-5]-t[h-5],t[o-4]+=t[h-4],t[o-5]+=t[h-5],t[h-4]=r*this._a[l]-n*this._a[l+1],t[h-5]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-6]-t[h-6],n=t[o-7]-t[h-7],t[o-6]+=t[h-6],t[o-7]+=t[h-7],t[h-6]=r*this._a[l]-n*this._a[l+1],t[h-7]=n*this._a[l]+r*this._a[l+1],l+=a,o-=8,h-=8}step3_iter0_loop(e,t,s,i){var a=s,r=a+i,n=0;for(let s=e>>2;s>0;--s){let e,s;e=t[a]-t[r],s=t[a-1]-t[r-1],t[a]+=t[r],t[a-1]+=t[r-1],t[r]=e*this._a[n]-s*this._a[n+1],t[r-1]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-2]-t[r-2],s=t[a-3]-t[r-3],t[a-2]+=t[r-2],t[a-3]+=t[r-3],t[r-2]=e*this._a[n]-s*this._a[n+1],t[r-3]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-4]-t[r-4],s=t[a-5]-t[r-5],t[a-4]+=t[r-4],t[a-5]+=t[r-5],t[r-4]=e*this._a[n]-s*this._a[n+1],t[r-5]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-6]-t[r-6],s=t[a-7]-t[r-7],t[a-6]+=t[r-6],t[a-7]+=t[r-7],t[r-6]=e*this._a[n]-s*this._a[n+1],t[r-7]=s*this._a[n]+e*this._a[n+1],n+=8,a-=8,r-=8}}step3_inner_s_loop(e,t,s,i,a,r,n){var o=this._a[a],h=this._a[a+1],l=this._a[a+r],d=this._a[a+r+1],c=this._a[a+2*r],u=this._a[a+2*r+1],p=this._a[a+3*r],g=this._a[a+3*r+1];let m,f,y=s,b=y+i;for(let s=e;s>0;--s)m=t[y]-t[b],f=t[y-1]-t[b-1],t[y]+=t[b],t[y-1]+=t[b-1],t[b]=m*o-f*h,t[b-1]=f*o+m*h,m=t[y-2]-t[b-2],f=t[y-3]-t[b-3],t[y-2]+=t[b-2],t[y-3]+=t[b-3],t[b-2]=m*l-f*d,t[b-3]=f*l+m*d,m=t[y-4]-t[b-4],f=t[y-5]-t[b-5],t[y-4]+=t[b-4],t[y-5]+=t[b-5],t[b-4]=m*c-f*u,t[b-5]=f*c+m*u,m=t[y-6]-t[b-6],f=t[y-7]-t[b-7],t[y-6]+=t[b-6],t[y-7]+=t[b-7],t[b-6]=m*p-f*g,t[b-7]=f*p+m*g,y-=n,b-=n}step3_inner_s_loop_ld654(e,t,s,i){const a=i>>3,r=this._a[a];let n=s;const o=n-16*e;for(;n>o;){let e,s;e=t[n]-t[n-8],s=t[n-1]-t[n-9],t[n]+=t[n-8],t[n-1]+=t[n-9],t[n-8]=e,t[n-9]=s,e=t[n-2]-t[n-10],s=t[n-3]-t[n-11],t[n-2]+=t[n-10],t[n-3]+=t[n-11],t[n-10]=(e+s)*r,t[n-11]=(s-e)*r,e=t[n-12]-t[n-4],s=t[n-5]-t[n-13],t[n-4]+=t[n-12],t[n-5]+=t[n-13],t[n-12]=s,t[n-13]=e,e=t[n-14]-t[n-6],s=t[n-7]-t[n-15],t[n-6]+=t[n-14],t[n-7]+=t[n-15],t[n-14]=(e+s)*r,t[n-15]=(e-s)*r,this.iter_54(t,n),this.iter_54(t,n-8),n-=16}}iter_54(e,t){let s,i,a,r,n,o,h,l;s=e[t]-e[t-4],n=e[t]+e[t-4],h=e[t-2]+e[t-6],a=e[t-2]-e[t-6],e[t]=n+h,e[t-2]=n-h,r=e[t-3]-e[t-7],e[t-4]=s+r,e[t-6]=s-r,i=e[t-1]-e[t-5],o=e[t-1]+e[t-5],l=e[t-3]+e[t-7],e[t-1]=o+l,e[t-3]=o-l,e[t-5]=i-a,e[t-7]=i+a}}Hi.M_PI=3.141592653589793;class Gi{constructor(){this._setupCache=new Map}reverse(e,t){let s;this._setupCache.has(t)?s=this._setupCache.get(t):(s=new Hi(t),this._setupCache.set(t,s)),s.calcReverse(e)}}class Wi{constructor(e,t,s){this._packetIndex=0,this._stream=e,this._setup=t,this._packets=s,this._currentPosition=0,this._prevPacketBuf=null,this._prevPacketStart=0,this._prevPacketEnd=0,this._prevPacketStop=0,this._nextPacketBuf=null,this._eosFound=!1,this._hasPosition=!1,this._modeFieldBits=Si.ilog(t.modes.length-1)}decode(){let e=new Float32Array(this._packets[this._packets.length-1].granulePosition*this._stream.audioChannels);const t=new Float32Array(.2*this._stream.audioSampleRate*this._stream.audioChannels);let s=0,i=0;for(;s=this.read(t,0,t.length),0!==s;){if(i+s>=e.length){const s=new Float32Array(e.length+t.length);s.set(e,0),e=s}e.set(t.subarray(0,s),i),i+=s}return e.subarray(0,i)}read(e,t,s){if(0==s)return 0;let i=t;const a=t+s;for(;i<a;){if(this._prevPacketStart==this._prevPacketEnd){if(this._eosFound){this._nextPacketBuf=null,this._prevPacketBuf=null;break}const e=this.readNextPacket((i-t)/this._stream.audioChannels);null===e&&(this._prevPacketEnd=this._prevPacketStop),null===e||null===e.samplePosition||this._hasPosition||(this._hasPosition=!0,this._currentPosition=e.samplePosition-(this._prevPacketEnd-this._prevPacketStart)-(i-t)/this._stream.audioChannels)}const s=Math.min((a-i)/this._stream.audioChannels,this._prevPacketEnd-this._prevPacketStart);s>0&&(i+=this.copyBuffer(e,i,s))}return s=i-t,this._currentPosition+=s/this._stream.audioChannels,s}copyBuffer(e,t,s){let i=t;for(;s>0;this._prevPacketStart++,s--)for(let t=0;t<this._stream.audioChannels;t++)e[i++]=this._prevPacketBuf[t][this._prevPacketStart];return i-t}readNextPacket(e){const t=this.decodeNextPacket();if(this._eosFound=this._eosFound||t.isEndOfStream,null==t.curPacket)return null;if(null!==t.samplePosition&&t.isEndOfStream){const s=this._currentPosition+e+t.validLen-t.startIndex,i=t.samplePosition-s;i<0&&(t.validLen+=i,t.validLen<0&&(t.validLen=0))}return this._prevPacketEnd>0?(Wi.overlapBuffers(this._prevPacketBuf,t.curPacket,this._prevPacketStart,this._prevPacketStop,t.startIndex,this._stream.audioChannels),this._prevPacketStart=t.startIndex):null==this._prevPacketBuf&&(this._prevPacketStart=t.validLen),this._nextPacketBuf=this._prevPacketBuf,this._prevPacketEnd=t.validLen,this._prevPacketStop=t.totalLen,this._prevPacketBuf=t.curPacket,new Ri(t.samplePosition)}static overlapBuffers(e,t,s,i,a,r){for(;s<i;s++,a++)for(let i=0;i<r;i++)t[i][a]+=e[i][s]}decodeNextPacket(){const e=new zi;let t=null;if(this._packetIndex>=this._packets.length)e.isEndOfStream=!0;else{t=this._packets[this._packetIndex++];const s=new yi(Oe.fromBuffer(t.packetData));if(e.isEndOfStream=t.isEndOfStream,!s.readBit()){const i=this._setup.modes[s.readBits(this._modeFieldBits)];if(null==this._nextPacketBuf){this._nextPacketBuf=new Array(this._stream.audioChannels);for(let e=0;e<this._stream.audioChannels;e++)this._nextPacketBuf[e]=new Float32Array(this._stream.blocksize1)}const a=i.decode(s,this._nextPacketBuf);return e.startIndex=a.packetStartIndex,e.validLen=a.packetValidLength,e.totalLen=a.packetTotalLength,e.samplePosition=t.granulePosition,e.curPacket=this._nextPacketBuf,e}}return e}}class zi{constructor(){this.curPacket=null,this.startIndex=0,this.validLen=0,this.totalLen=0,this.isEndOfStream=!1,this.samplePosition=null}}!function(e){e[e.IdentificationHeader=1]="IdentificationHeader",e[e.Comment=3]="Comment",e[e.SetupHeader=5]="SetupHeader"}(Ds||(Ds={}));class Ui{constructor(e){this._packetIndex=-1,this._packets=e}read(){let e;for(;;){if(e=this.nextPacket(),null==e)return null;if(e.isBeginningOfStream){var t=this.readStream(e);if(null!=t)return t}}}nextPacket(){return this._packetIndex++,this._packetIndex<this._packets.length?this._packets[this._packetIndex]:null}readStream(e){const t=new mi;if(!this.readIdentificationHeader(t,e))return null;if(!this.readComments(this.nextPacket()))return null;const s=new bi;if(!this.readSetupHeader(t,s,this.nextPacket()))return null;const i=[];let a;for(;a=this.nextPacket(),null!=a&&(i.push(a),!a.isEndOfStream););const r=new Wi(t,s,i);return t.samples=r.decode(),t}comonHeaderDecode(e,t){const s=new Uint8Array(7);if(t.read(s,0,s.length),s[0]!==e)return!1;for(let e=0;e<Ui.VorbisHeaderMarker.length;e++)if(s[1+e]!==Ui.VorbisHeaderMarker[e])return!1;return!0}comonHeaderDecodeBit(e,t){const s=t.readBytes(7);if(s[0]!==e)return!1;for(let e=0;e<Ui.VorbisHeaderMarker.length;e++)if(s[1+e]!==Ui.VorbisHeaderMarker[e])return!1;return!0}readIdentificationHeader(e,t){const s=Oe.fromBuffer(t.packetData);if(!this.comonHeaderDecode(Ds.IdentificationHeader,s))return!1;if(0!=Ae.readUInt32LE(s))return!1;if(e.audioChannels=s.readByte(),e.audioSampleRate=Ae.readUInt32LE(s),e.audioChannels<=0||e.audioSampleRate<=0)return!1;e.bitrateMaximum=Ae.readInt32LE(s),e.bitrateNominal=Ae.readInt32LE(s),e.bitrateMinimum=Ae.readInt32LE(s);var i=s.readByte();if(e.blocksize0=1<<(15&i),e.blocksize1=1<<(i>>4),e.blocksize0>e.blocksize1||!Ui.isAllowedBlockSize(e.blocksize0)||!Ui.isAllowedBlockSize(e.blocksize0))return!1;return 0!==s.readByte()}static isAllowedBlockSize(e){switch(e){case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:return!0;default:return!1}}readComments(e){if(null==e)return!1;var t=Oe.fromBuffer(e.packetData);if(!this.comonHeaderDecode(Ds.Comment,t))return!1;const s=Ae.readUInt32LE(t);t.skip(s);var i=Ae.readUInt32LE(t);for(let e=0;e<i;e++){const e=Ae.readUInt32LE(t);t.skip(e)}return 0!=t.readByte()}readSetupHeader(e,t,s){if(null==s)return!1;const i=new yi(Oe.fromBuffer(s.packetData)),a=new Gi,r=new Ti;if(!this.comonHeaderDecodeBit(Ds.SetupHeader,i))return!1;let n=i.readByte()+1;for(let e=0;e<n;e++)t.codebooks.push(new Bi(i,r));n=i.readBits(6)+1;for(let e=0;e<n;e++)t.timeDomainTransforms.push(new xi(i));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.floors.push(new Ei(i,e.blocksize0,e.blocksize1,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.residues.push(new Mi(i,e.audioChannels,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.mappings.push(new Ii(i,e.audioChannels,t.floors,t.residues,a));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.modes.push(new Vi(i,e.audioChannels,e.blocksize0,e.blocksize1,t.mappings));return!!i.readBit()}}Ui.VorbisHeaderMarker=new Uint8Array(["v".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"b".charCodeAt(0),"i".charCodeAt(0),"s".charCodeAt(0)]);class Xi{constructor(e){this.streams=[];for(var t=new gi(e).read(),s=new Ui(t);;){let e=s.read();if(null==e)break;this.streams.push(e)}}}class Ji{constructor(){this.phdrs=[],this.pbags=[],this.pmods=[],this.pgens=[],this.insts=[],this.ibags=[],this.imods=[],this.igens=[],this.sHdrs=[],this.sampleData=new Uint8Array(0),this._sampleCache=new Map}decodeSamples(e,t,s){const i=`${e}_${t}_${s}`;if(!this._sampleCache.has(i)){let a;const r=this.sampleData.slice(e,t);if(s){a=new Xi(Oe.fromBuffer(r)).streams[0].samples}else{let e=new Int16Array(r.buffer);a=new Float32Array(e.length);for(let t=0;t<e.length;t++)a[t]=e[t]/32767}return this._sampleCache.set(i,a),a}return this._sampleCache.get(i)}load(e){const t=new ui,s=new ui;if(!ui.load(null,t,e)||"sfbk"!==t.id)throw new Pe("Soundfont is not a valid Soundfont2 file");for(;ui.load(t,s,e);){let t=new ui;if("pdta"===s.id)for(;ui.load(s,t,e);)switch(t.id){case"phdr":for(let s=0,i=t.size/Zi.SizeInFile|0;s<i;s++)this.phdrs.push(new Zi(e));break;case"pbag":for(let s=0,i=t.size/Qi.SizeInFile|0;s<i;s++)this.pbags.push(new Qi(e));break;case"pmod":for(let s=0,i=t.size/ea.SizeInFile|0;s<i;s++)this.pmods.push(new ea(e));break;case"pgen":for(let s=0,i=t.size/$i.SizeInFile|0;s<i;s++)this.pgens.push(new $i(e));break;case"inst":for(let s=0,i=t.size/Ki.SizeInFile|0;s<i;s++)this.insts.push(new Ki(e));break;case"ibag":for(let s=0,i=t.size/Yi.SizeInFile|0;s<i;s++)this.ibags.push(new Yi(e));break;case"imod":for(let s=0,i=t.size/qi.SizeInFile|0;s<i;s++)this.imods.push(new qi(e));break;case"igen":for(let s=0,i=t.size/ji.SizeInFile|0;s<i;s++)this.igens.push(new ji(e));break;case"shdr":for(let s=0,i=t.size/ta.SizeInFile|0;s<i;s++)this.sHdrs.push(new ta(e));break;default:e.position+=t.size}else if("sdta"===s.id)for(;ui.load(s,t,e);)if("smpl"===t.id)this.sampleData=new Uint8Array(t.size),e.read(this.sampleData,0,t.size);else e.position+=t.size;else e.position+=s.size}}}class Yi{constructor(e){this.instGenNdx=Ae.readUInt16LE(e),this.instModNdx=Ae.readUInt16LE(e)}}Yi.SizeInFile=4;class qi{constructor(e){this.modSrcOper=Ae.readUInt16LE(e),this.modDestOper=Ae.readUInt16LE(e),this.modAmount=Ae.readInt16LE(e),this.modAmtSrcOper=Ae.readUInt16LE(e),this.modTransOper=Ae.readUInt16LE(e)}}qi.SizeInFile=10;class ji{constructor(e){this.genOper=Ae.readUInt16LE(e),this.genAmount=new sa(e)}}ji.SizeInFile=4;class Ki{constructor(e){this.instName=Ae.read8BitStringLength(e,20),this.instBagNdx=Ae.readUInt16LE(e)}}Ki.SizeInFile=22;class Qi{constructor(e){this.genNdx=Ae.readUInt16LE(e),this.modNdx=Ae.readUInt16LE(e)}}Qi.SizeInFile=4;class $i{constructor(e){this.genOper=Ae.readUInt16LE(e),this.genAmount=new sa(e)}}$i.SizeInFile=4,$i.GenInstrument=41,$i.GenKeyRange=43,$i.GenVelRange=44,$i.GenSampleId=53;class Zi{constructor(e){this.presetName=Ae.read8BitStringLength(e,20),this.preset=Ae.readUInt16LE(e),this.bank=Ae.readUInt16LE(e),this.presetBagNdx=Ae.readUInt16LE(e),this.library=Ae.readUInt32LE(e),this.genre=Ae.readUInt32LE(e),this.morphology=Ae.readUInt32LE(e)}}Zi.SizeInFile=38;class ea{constructor(e){this.modSrcOper=Ae.readUInt16LE(e),this.modDestOper=Ae.readUInt16LE(e),this.modAmount=Ae.readUInt16LE(e),this.modAmtSrcOper=Ae.readUInt16LE(e),this.modTransOper=Ae.readUInt16LE(e)}}ea.SizeInFile=10;class ta{constructor(e){this.sampleName=Ae.read8BitStringLength(e,20),this.start=Ae.readUInt32LE(e),this.end=Ae.readUInt32LE(e),this.startLoop=Ae.readUInt32LE(e),this.endLoop=Ae.readUInt32LE(e),this.sampleRate=Ae.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=Ae.readSInt8(e),this.sampleLink=Ae.readUInt16LE(e),this.sampleType=Ae.readUInt16LE(e)}}ta.SizeInFile=46;class sa{get shortAmount(){return Ie.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}constructor(e){this.wordAmount=Ae.readUInt16LE(e)}}class ia{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 aa{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"}(Ls||(Ls={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(Ms||(Ms={}));class ra{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null}}class na{static timecents2Secs(e){return Math.pow(2,e/1200)}static decibelsToGain(e){return e>-100?Math.pow(10,.05*e):0}static gainToDecibels(e){return e<=1e-5?-100:20*Math.log10(e)}static cents2Hertz(e){return 8.176*Math.pow(2,e/1200)}}class oa{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:na.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:na.timecents2Secs(this.attack),this.release=this.release<-11950?0:na.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:na.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:na.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?na.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"}(Is||(Is={}));class ha{constructor(e){this.loopMode=Ls.None,this.samples=ha.NoSamples,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv=new oa,this.modEnv=new oa,this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,e&&(this.loopMode=e.loopMode,this.samples=e.samples,this.sampleRate=e.sampleRate,this.loKey=e.loKey,this.hiKey=e.hiKey,this.loVel=e.loVel,this.hiVel=e.hiVel,this.group=e.group,this.offset=e.offset,this.end=e.end,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this.transpose=e.transpose,this.tune=e.tune,this.pitchKeyCenter=e.pitchKeyCenter,this.pitchKeyTrack=e.pitchKeyTrack,this.attenuation=e.attenuation,this.pan=e.pan,this.ampEnv=new oa(e.ampEnv),this.modEnv=new oa(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=Ls.None,this.samples=ha.NoSamples,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv.clear(),this.modEnv.clear(),this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,this.hiKey=127,this.hiVel=127,this.pitchKeyCenter=60,e||(this.pitchKeyTrack=100,this.pitchKeyCenter=-1,this.ampEnv.delay=-12e3,this.ampEnv.attack=-12e3,this.ampEnv.hold=-12e3,this.ampEnv.decay=-12e3,this.ampEnv.release=-12e3,this.modEnv.delay=-12e3,this.modEnv.attack=-12e3,this.modEnv.hold=-12e3,this.modEnv.decay=-12e3,this.modEnv.release=-12e3,this.initialFilterFc=13500,this.delayModLFO=-12e3,this.delayVibLFO=-12e3)}operator(e,t){switch(e){case Is.StartAddrsOffset:this.offset+=Ie.int16ToUint32(t.shortAmount);break;case Is.EndAddrsOffset:this.end+=Ie.int16ToUint32(t.shortAmount);break;case Is.StartloopAddrsOffset:this.loopStart+=Ie.int16ToUint32(t.shortAmount);break;case Is.EndloopAddrsOffset:this.loopEnd+=Ie.int16ToUint32(t.shortAmount);break;case Is.StartAddrsCoarseOffset:this.offset+=32768*Ie.int16ToUint32(t.shortAmount);break;case Is.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case Is.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case Is.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case Is.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case Is.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case Is.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case Is.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case Is.EndAddrsCoarseOffset:this.end+=32768*Ie.int16ToUint32(t.shortAmount);break;case Is.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case Is.Pan:this.pan=t.shortAmount/1e3;break;case Is.DelayModLFO:this.delayModLFO=t.shortAmount;break;case Is.FreqModLFO:this.freqModLFO=t.shortAmount;break;case Is.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case Is.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case Is.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case Is.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case Is.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case Is.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case Is.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case Is.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case Is.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case Is.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case Is.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case Is.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case Is.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case Is.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case Is.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case Is.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case Is.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case Is.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case Is.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case Is.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case Is.StartloopAddrsCoarseOffset:this.loopStart+=32768*Ie.int16ToUint32(t.shortAmount);break;case Is.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case Is.EndloopAddrsCoarseOffset:this.loopEnd+=32768*Ie.int16ToUint32(t.shortAmount);break;case Is.CoarseTune:this.transpose+=t.shortAmount;break;case Is.FineTune:this.tune+=t.shortAmount;break;case Is.SampleModes:this.loopMode=3&~t.wordAmount?1==(3&t.wordAmount)?Ls.Continuous:Ls.None:Ls.Sustain;break;case Is.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case Is.ExclusiveClass:this.group=t.wordAmount;break;case Is.OverridingRootKey:this.pitchKeyCenter=t.shortAmount}}}ha.NoSamples=new Float32Array(0),function(e){e[e.None=0]="None",e[e.Delay=1]="Delay",e[e.Attack=2]="Attack",e[e.Hold=3]="Hold",e[e.Decay=4]="Decay",e[e.Sustain=5]="Sustain",e[e.Release=6]="Release",e[e.Done=7]="Done"}(As||(As={}));class la{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=As.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case As.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=As.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=As.Delay;break;case As.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=As.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=As.Attack;break;case As.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=As.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=As.Hold;break;case As.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=As.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=As.Decay;break;case As.Decay:return this.segment=As.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case As.Sustain:if(this.segment=As.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?la.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=As.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,s,i,a){this.parameters=new oa(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:na.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:na.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|s,this.isAmpEnv=i,this.nextSegment(As.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)}}la.FastReleaseTime=.01;class da{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,s){this.samplesUntil=e*s|0,this.delta=4*na.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 ca{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 ua{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 la,this.modEnv=new la,this.lowPass=new ca,this.modLfo=new da,this.vibLfo=new da,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/(na.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(As.Sustain,e),this.modEnv.nextSegment(As.Sustain,e),this.region.loopMode===Ls.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(As.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(As.Sustain,e)}render(e,t,s,i,a){if(!this.region)return;let r=this.region,n=r.samples,o=0,h=e.outputMode===Ms.StereoUnweaved?i:-1,l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,d=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),c=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,m=r.end,f=g+1,y=this.sourceSamplePosition,b=new ca(this.lowPass),S=0!==r.modLfoToFilterFc||0!==r.modEnvToFilterFc,_=0,w=0,B=0,k=0,T=0!==r.modLfoToPitch||0!==r.modEnvToPitch||0!==r.vibLfoToPitch,x=0,N=0,v=0,P=0,C=0!==r.modLfoToVolume,E=0,F=0;for(S?(_=e.outSampleRate,w=r.initialFilterFc,B=r.modLfoToFilterFc,k=r.modEnvToFilterFc):(_=0,w=0,B=0,k=0),T?(x=0,N=r.modLfoToPitch,v=r.vibLfoToPitch,P=r.modEnvToPitch):(x=na.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,N=0,v=0,P=0),C?F=.1*r.modLfoToVolume:(E=na.decibelsToGain(this.noteGainDb),F=0);i>0;){let r,D,L=0,M=i>ua.RenderEffectSampleBlock?ua.RenderEffectSampleBlock:i;if(i-=M,S){let e=w+this.modLfo.level*B+this.modEnv.level*k;b.active=e<=13500,b.active&&b.setup(na.cents2Hertz(e)/_)}switch(T&&(x=na.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*N+this.vibLfo.level*v+this.modEnv.level*P))*this.pitchOutputFactor),C&&(E=na.decibelsToGain(this.noteGainDb+this.modLfo.level*F)),r=E*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(M,e.outSampleRate),l&&this.modEnv.process(M,e.outSampleRate),d&&this.modLfo.process(M),c&&this.vibLfo.process(M),e.outputMode){case Ms.StereoInterleaved:for(D=r*this.panFactorLeft,L=r*this.panFactorRight;M-- >0&&y<m;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*D,o++,t[s+o]+=r*L,o++,y+=x,y>=f&&u&&(y-=g-p+1)}break;case Ms.StereoUnweaved:for(D=r*this.panFactorLeft,L=r*this.panFactorRight;M-- >0&&y<m;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*D,o++,t[s+h]+=r*L,h++,y+=x,y>=f&&u&&(y-=g-p+1)}break;case Ms.Mono:for(;M-- >0&&y<m;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,h=n[e]*(1-a)+n[i]*a;b.active&&(h=b.process(h)),t[s+o]=h*r,o++,y+=x,y>=f&&u&&(y-=g-p+1)}}if(y>=m||this.ampEnv.segment===As.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}ua.RenderEffectSampleBlock=Re.MicroBufferSize;class pa{constructor(){this._items=[],this._position=0,this.isEmpty=!0}clear(){this._items=[],this._position=0,this.isEmpty=!0}enqueue(e){this.isEmpty=!1,this._items.push(e)}peek(){return this._items[this._position]}dequeue(){const e=this._items[this._position];return this._position++,this._position>=this._items.length/2&&(this._items=this._items.slice(this._position),this._position=0),this.isEmpty=0==this._items.length,e}toArray(){const e=this._items.slice(this._position);return e.reverse(),e}}!function(e){e[e.BankSelectCoarse=0]="BankSelectCoarse",e[e.ModulationCoarse=1]="ModulationCoarse",e[e.DataEntryCoarse=6]="DataEntryCoarse",e[e.VolumeCoarse=7]="VolumeCoarse",e[e.PanCoarse=10]="PanCoarse",e[e.ExpressionControllerCoarse=11]="ExpressionControllerCoarse",e[e.BankSelectFine=32]="BankSelectFine",e[e.ModulationFine=33]="ModulationFine",e[e.DataEntryFine=38]="DataEntryFine",e[e.VolumeFine=39]="VolumeFine",e[e.PanFine=42]="PanFine",e[e.ExpressionControllerFine=43]="ExpressionControllerFine",e[e.HoldPedal=64]="HoldPedal",e[e.LegatoPedal=68]="LegatoPedal",e[e.NonRegisteredParameterFine=98]="NonRegisteredParameterFine",e[e.NonRegisteredParameterCourse=99]="NonRegisteredParameterCourse",e[e.RegisteredParameterFine=100]="RegisteredParameterFine",e[e.RegisteredParameterCourse=101]="RegisteredParameterCourse",e[e.AllSoundOff=120]="AllSoundOff",e[e.ResetControllers=121]="ResetControllers",e[e.AllNotesOff=123]="AllNotesOff"}(Os||(Os={}));class ga{constructor(e){this._midiEventQueue=new pa,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this._transpositionPitches=new Map,this._liveTranspositionPitches=new Map,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=Ms.StereoInterleaved,this.outSampleRate=0,this.globalGainDb=0,this.outSampleRate=e}synthesize(e,t,s){return this.fillWorkingBuffer(e,t,s)}synthesizeSilent(e){this.fillWorkingBuffer(null,0,e)}channelGetMixVolume(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].mixVolume:1}channelSetMixVolume(e,t){let s=this.channelInit(e);for(let s of this._voices)s.playingChannel===e&&-1!==s.playingPreset&&(s.mixVolume=t);s.mixVolume=t}channelSetMute(e,t){t?this._mutedChannels.set(e,!0):this._mutedChannels.delete(e)}channelSetSolo(e,t){t?this._soloChannels.set(e,!0):this._soloChannels.delete(e),this._isAnySolo=this._soloChannels.size>0}resetChannelStates(){this._mutedChannels=new Map,this._soloChannels=new Map,this._liveTranspositionPitches=new Map,this.applyTranspositionPitches(new Map),this._isAnySolo=!1}setChannelTranspositionPitch(e,t){let s=0;this._liveTranspositionPitches.has(e)&&(s=this._liveTranspositionPitches.get(e)),0===t?this._liveTranspositionPitches.delete(e):this._liveTranspositionPitches.set(e,t);for(const i of this._voices)if(i.playingChannel===e&&9!==i.playingChannel){let e=0;e-=s,e+=t,i.playingKey+=e,this._channels&&i.updatePitchRatio(this._channels.channelList[i.playingChannel],this.outSampleRate)}}applyTranspositionPitches(e){const t=this._transpositionPitches;for(const s of this._voices)if(s.playingChannel>=0&&9!==s.playingChannel){let i=0;t.has(s.playingChannel)&&(i-=t.get(s.playingChannel)),e.has(s.playingChannel)&&(i+=e.get(s.playingChannel)),s.playingKey+=i,this._channels&&s.updatePitchRatio(this._channels.channelList[s.playingChannel],this.outSampleRate)}this._transpositionPitches=e}dispatchEvent(e){this._midiEventQueue.enqueue(e)}fillWorkingBuffer(e,t,s){const i=this._isAnySolo,a=[];for(;!this._midiEventQueue.isEmpty;){let e=this._midiEventQueue.dequeue();e.isMetronome&&this.metronomeVolume>0?(this.channelNoteOff(Re.MetronomeChannel,Re.MetronomeKey),this.channelNoteOn(Re.MetronomeChannel,Re.MetronomeKey,95/127)):e.event&&this.processMidiMessage(e.event),a.push(e)}for(const a of this._voices)if(-1!==a.playingPreset){const r=a.playingChannel,n=this._mutedChannels.has(r)||i&&r!=Re.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,s,n):a.kill()}return a}processMidiMessage(e){re.debug("Midi","Processing Midi message "+je[e.type]+"/"+e.tick);switch(e.type){case je.TimeSignature:const t=e;this.timeSignatureNumerator=t.numerator,this.timeSignatureDenominator=Math.pow(2,t.denominatorIndex);break;case je.NoteOn:const s=e;this.channelNoteOn(s.channel,s.noteKey,s.noteVelocity/127);break;case je.NoteOff:const i=e;this.channelNoteOff(i.channel,i.noteKey);break;case je.ControlChange:const a=e;this.channelMidiControl(a.channel,a.controller,a.value);break;case je.ProgramChange:const r=e;this.channelSetPresetNumber(r.channel,r.program,9===r.channel);break;case je.TempoChange:const n=e;this.currentTempo=6e7/n.microSecondsPerQuarterNote;break;case je.PitchBend:const o=e;this.channelSetPitchWheel(o.channel,o.value);break;case je.PerNotePitchBend:const h=e;let l=h.value;l=l*Re.MaxPitchWheel/Re.MaxPitchWheel20,this.channelSetPerNotePitchWheel(h.channel,h.noteKey,l)}}get metronomeVolume(){return this.channelGetMixVolume(Re.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Re.MetronomeChannel,e),e>0&&(this.channelSetVolume(Re.MetronomeChannel,1),this.channelSetPresetNumber(Re.MetronomeChannel,0,!0))}get masterVolume(){return na.decibelsToGain(this.globalGainDb)}set masterVolume(e){var t=na.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<As.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<As.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 ua;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-na.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!==Ls.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(na.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>=As.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>=As.Release)||r.end(this.outSampleRate)}bankNoteOff(e,t,s){const i=this.getPresetIndex(e,t);return-1!==i&&(this.noteOff(i,s),!0)}noteOffAll(e){for(const t of this._voices)-1!==t.playingPreset&&(e?t.endQuick(this.outSampleRate):t.ampEnv.segment<As.Release&&t.end(this.outSampleRate))}get activeVoiceCount(){let e=0;for(const t of this._voices)-1!==t.playingPreset&&e++;return e}channelInit(e){if(this._channels&&e<this._channels.channelList.length)return this._channels.channelList[e];this._channels||(this._channels=new aa);for(let t=this._channels.channelList.length;t<=e;t++){let e=new ia;e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0,e.mixVolume=1,this._channels.channelList.push(e)}return this._channels.channelList[e]}getPresetIndex(e,t){if(!this.presets)return-1;for(let s=this.presets.length-1;s>=0;s--){let i=this.presets[s];if(i.presetNumber===t&&i.bank===e)return s}return-1}getPresetName(e){return this.presets?e<0||e>=this.presets.length?null:this.presets[e].name:null}bankGetPresetName(e,t){return this.getPresetName(this.getPresetIndex(e,t))}channelNoteOn(e,t,s){!this._channels||e>this._channels.channelList.length||(this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e)),this._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,s))}channelNoteOff(e,t){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e));const s=[];let i=null,a=null;for(const r of this._voices)-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=As.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>=As.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<As.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<As.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=Ie.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=Ie.int32ToUint16(t)}channelSetBankPreset(e,t,s){const i=this.channelInit(e),a=this.getPresetIndex(t,s);return-1!==a&&(i.presetIndex=Ie.int32ToUint16(a),i.bank=Ie.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=na.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=Ie.int32ToUint16(t),this.channelApplyPitch(e,s))}channelSetPerNotePitchWheel(e,t,s){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e));const i=this.channelInit(e);i.perNotePitchWheel.has(t)&&i.perNotePitchWheel.get(t)===s||(i.perNotePitchWheel.set(t,s),this.channelApplyPitch(e,i,t))}channelApplyPitch(e,t,s=-1){for(const i of this._voices)i.playingChannel!==e||-1===i.playingPreset||-1!=s&&i.playingKey!==s||i.updatePitchRatio(t,this.outSampleRate)}channelSetPitchRange(e,t){const s=this.channelInit(e);s.pitchRange!==t&&(s.pitchRange=t,8192!==s.pitchWheel&&this.channelApplyPitch(e,s))}channelSetTuning(e,t){const s=this.channelInit(e);s.tuning!==t&&(s.tuning=t,this.channelApplyPitch(e,s))}channelMidiControl(e,t,s){let i=this.channelInit(e);switch(t){case Os.DataEntryFine:return i.midiData=Ie.int32ToUint16(16256&i.midiData|s),void(0===i.midiRpn?this.channelSetPitchRange(e,(i.midiData>>7)+.01*(127&i.midiData)):1===i.midiRpn?this.channelSetTuning(e,(0|i.tuning)+(i.midiData-8192)/8192):2===i.midiRpn&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Os.VolumeCoarse:return i.midiVolume=Ie.int32ToUint16(127&i.midiVolume|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.VolumeFine:return i.midiVolume=Ie.int32ToUint16(16256&i.midiVolume|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.ExpressionControllerCoarse:return i.midiExpression=Ie.int32ToUint16(127&i.midiExpression|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.ExpressionControllerFine:return i.midiExpression=Ie.int32ToUint16(16256&i.midiExpression|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Os.PanCoarse:return i.midiPan=Ie.int32ToUint16(127&i.midiPan|s<<7),void this.channelSetPan(e,i.midiPan/16383);case Os.PanFine:return i.midiPan=Ie.int32ToUint16(16256&i.midiPan|s),void this.channelSetPan(e,i.midiPan/16383);case Os.DataEntryCoarse:return i.midiData=Ie.int32ToUint16(127&i.midiData|s<<7),void(0===i.midiRpn?this.channelSetPitchRange(e,(i.midiData>>7)+.01*(127&i.midiData)):1===i.midiRpn?this.channelSetTuning(e,(0|i.tuning)+(i.midiData-8192)/8192):2===i.midiRpn&&t===Os.DataEntryCoarse&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Os.BankSelectCoarse:return void(i.bank=Ie.int32ToUint16(32768|s));case Os.BankSelectFine:return void(i.bank=Ie.int32ToUint16((32768&i.bank?(127&i.bank)<<7:0)|s));case Os.RegisteredParameterCourse:return void(i.midiRpn=Ie.int32ToUint16(127&(65535===i.midiRpn?0:i.midiRpn)|s<<7));case Os.RegisteredParameterFine:return void(i.midiRpn=Ie.int32ToUint16(16256&(65535===i.midiRpn?0:i.midiRpn)|s));case Os.NonRegisteredParameterFine:case Os.NonRegisteredParameterCourse:return void(i.midiRpn=65535);case Os.AllSoundOff:return void this.channelSoundsOffAll(e);case Os.AllNotesOff:return void this.channelNoteOffAll(e);case Os.ResetControllers:return i.midiVolume=16383,i.midiExpression=16383,i.midiPan=8192,i.bank=0,this.channelSetVolume(e,1),this.channelSetPan(e,.5),void this.channelSetPitchRange(e,2)}}channelGetPresetIndex(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].presetIndex:0}channelGetPresetBank(e){return this._channels&&e<this._channels.channelList.length?32767&this._channels.channelList[e].bank:0}channelGetPan(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].panOffset-.5:.5}channelGetVolume(e){return this._channels&&e<this._channels.channelList.length?na.decibelsToGain(this._channels.channelList[e].gainDb):1}channelGetPitchWheel(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchWheel:8192}channelGetPitchRange(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchRange:2}channelGetTuning(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].tuning:0}resetPresets(){this.presets=[]}loadPresets(e,t,s,i){const a=[];for(let i=0;i<e.phdrs.length-1;i++){const r=e.phdrs[i];let n=0;const o=new ra;a.push(o),o.name=r.presetName,o.bank=r.bank,o.presetNumber=r.preset;let h=0;for(let t=r.presetBagNdx;t<e.phdrs[i+1].presetBagNdx;t++){let s=0,i=127,a=0,r=127;for(let n=e.pbags[t].genNdx;n<e.pbags[t+1].genNdx;n++){let t=e.pgens[n];if(t.genOper!==$i.GenKeyRange)if(t.genOper!==$i.GenVelRange){if(t.genOper===$i.GenInstrument&&!(t.genAmount.wordAmount>=e.insts.length))for(let n=e.insts[t.genAmount.wordAmount].instBagNdx;n<e.insts[t.genAmount.wordAmount+1].instBagNdx;n++){let t=0,o=127,l=0,d=127;for(let c=e.ibags[n].instGenNdx;c<e.ibags[n+1].instGenNdx;c++){let n=e.igens[c];n.genOper!==$i.GenKeyRange?n.genOper!==$i.GenVelRange?53===n.genOper&&o>=s&&t<=i&&d>=a&&l<=r&&h++:(l=n.genAmount.lowByteAmount,d=n.genAmount.highByteAmount):(t=n.genAmount.lowByteAmount,o=n.genAmount.highByteAmount)}}}else a=t.genAmount.lowByteAmount,r=t.genAmount.highByteAmount;else s=t.genAmount.lowByteAmount,i=t.genAmount.highByteAmount}}o.regions=new Array(h);let l=new ha;l.clear(!0);for(let a=r.presetBagNdx;a<e.phdrs[i+1].presetBagNdx;a++){const i=e.pbags[a],h=new ha(l);let d=!1;for(let l=i.genNdx;l<e.pbags[a+1].genNdx;l++){const i=e.pgens[l];if(i.genOper===$i.GenInstrument){let a=i.genAmount.wordAmount;if(a>=e.insts.length)continue;let l=new ha;l.clear(!1);let c=e.insts[a];for(let i=c.instBagNdx;i<e.insts[a+1].instBagNdx;i++){let a=e.ibags[i],d=new ha(l),u=!1;for(let l=a.instGenNdx;l<e.ibags[i+1].instGenNdx;l++){let i=e.igens[l];if(i.genOper===$i.GenSampleId){if(d.hiKey<h.loKey||d.loKey>h.hiKey)continue;if(d.hiVel<h.loVel||d.loVel>h.hiVel)continue;h.loKey>d.loKey&&(d.loKey=h.loKey),h.hiKey<d.hiKey&&(d.hiKey=h.hiKey),h.loVel>d.loVel&&(d.loVel=h.loVel),h.hiVel<d.hiVel&&(d.hiVel=h.hiVel),d.offset+=h.offset,d.end+=h.end,d.loopStart+=h.loopStart,d.loopEnd+=h.loopEnd,d.transpose+=h.transpose,d.tune+=h.tune,d.pitchKeyTrack+=h.pitchKeyTrack,d.attenuation+=h.attenuation,d.pan+=h.pan,d.ampEnv.delay+=h.ampEnv.delay,d.ampEnv.attack+=h.ampEnv.attack,d.ampEnv.hold+=h.ampEnv.hold,d.ampEnv.decay+=h.ampEnv.decay,d.ampEnv.sustain+=h.ampEnv.sustain,d.ampEnv.release+=h.ampEnv.release,d.modEnv.delay+=h.modEnv.delay,d.modEnv.attack+=h.modEnv.attack,d.modEnv.hold+=h.modEnv.hold,d.modEnv.decay+=h.modEnv.decay,d.modEnv.sustain+=h.modEnv.sustain,d.modEnv.release+=h.modEnv.release,d.initialFilterQ+=h.initialFilterQ,d.initialFilterFc+=h.initialFilterFc,d.modEnvToPitch+=h.modEnvToPitch,d.modEnvToFilterFc+=h.modEnvToFilterFc,d.delayModLFO+=h.delayModLFO,d.freqModLFO+=h.freqModLFO,d.modLfoToPitch+=h.modLfoToPitch,d.modLfoToFilterFc+=h.modLfoToFilterFc,d.modLfoToVolume+=h.modLfoToVolume,d.delayVibLFO+=h.delayVibLFO,d.freqVibLFO+=h.freqVibLFO,d.vibLfoToPitch+=h.vibLfoToPitch,d.ampEnv.envToSecs(!0),d.modEnv.envToSecs(!1),d.delayModLFO=d.delayModLFO<-11950?0:na.timecents2Secs(d.delayModLFO),d.delayVibLFO=d.delayVibLFO<-11950?0:na.timecents2Secs(d.delayVibLFO),d.pan<-.5?d.pan=-.5:d.pan>.5&&(d.pan=.5),(d.initialFilterQ<1500||d.initialFilterQ>13500)&&(d.initialFilterQ=0);let a=e.sHdrs[i.genAmount.wordAmount];d.offset+=a.start,d.end+=a.end,d.loopStart+=a.startLoop,d.loopEnd+=a.endLoop,a.endLoop>0&&(d.loopEnd-=1),-1===d.pitchKeyCenter&&(d.pitchKeyCenter=a.originalPitch),d.tune+=a.pitchCorrection,d.sampleRate=a.sampleRate;const l=r.bank==Re.PercussionBank;if(l&&ga.setContainsRange(s,d.loKey,d.hiKey)||!l&&t.has(r.preset))if(1&a.sampleType){re.debug("AlphaSynth",`Loading of used sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`);!!(16&a.sampleType)?d.samples=e.decodeSamples(a.start,a.end,!0):(d.samples=e.decodeSamples(2*d.offset,2*d.end,!1),d.loopStart>0&&(d.loopStart-=d.offset),d.loopEnd>0&&(d.loopEnd-=d.offset)),d.offset=0,d.end=d.samples.length-1}else re.warning("AlphaSynth",`Skipping load of unsupported sample ${a.sampleName} for preset ${r.presetName}, sample type ${a.sampleType} is not supported (bank ${o.bank} program ${o.presetNumber})`),d.samples=new Float32Array(0);else re.debug("AlphaSynth",`Skipping load of unused sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`),d.samples=new Float32Array(0);o.regions[n]=new ha(d),n++,u=!0}else d.operator(i.genOper,i.genAmount)}a!==e.ibags[c.instBagNdx]||u||(l=new ha(d))}d=!0}else h.operator(i.genOper,i.genAmount)}i!==e.pbags[r.presetBagNdx]||d||(l=h)}}if(i&&this.presets)for(const e of a)this.presets.push(e);else this.presets=a}static setContainsRange(e,t,s){for(let i=t;i<=s;i++)if(e.has(i))return!0;return!1}hasSamplesForProgram(e){const t=this.presets;if(!t)return!1;for(const s of t)if(s.presetNumber===e)for(const e of s.regions)if(e.samples.length>0)return!0;return!1}hasSamplesForPercussion(e){const t=this.presets;if(!t)return!1;for(const s of t)if(s.bank==Re.PercussionBank)for(const t of s.regions)if(t.loKey>=e&&t.hiKey<=e&&t.samples.length>0)return!0;return!1}}class ma{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 fa{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 ya{constructor(e){this.events=e}}class ba{constructor(e){this.playbackRange=e}}class Sa{get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return re.logLevel}set logLevel(e){re.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Re.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Re.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Re.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=le.clamp(e,Re.MinPlaybackSpeed,Re.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){re.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 ba(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){re.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 pa,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this._synthStopping=!1,this.isReady=!1,this.state=Es.Paused,this._loadedSoundFonts=[],this.ready=new ma,this.readyForPlayback=new ma,this.finished=new ma,this.soundFontLoaded=new ma,this.soundFontLoadFailed=new fa,this.midiLoaded=new fa,this.midiLoadFailed=new fa,this.stateChanged=new fa,this.positionChanged=new fa,this.midiEventsPlayed=new fa,this.playbackRangeChanged=new fa,re.debug("AlphaSynth","Initializing player"),this.state=Es.Paused,re.debug("AlphaSynth","Creating output"),this.output=e,re.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new ga(this.output.sampleRate),this._sequencer=new li(this._synthesizer),re.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this.state==Es.Playing&&(!this._sequencer.isFinished||this._synthesizer.activeVoiceCount>0)){let e=new Float32Array(Re.MicroBufferSize*Re.MicroBufferCount*Re.AudioChannels),t=0;for(let s=0;s<Re.MicroBufferCount;s++){this._sequencer.fillMidiEventQueue();const s=this._synthesizer.synthesize(e,t,Re.MicroBufferSize);t+=Re.MicroBufferSize*Re.AudioChannels;for(const e of s)this._midiEventsPlayedFilter.has(e.event.type)&&this._playedEventsQueue.enqueue(e);if(this._sequencer.isFinished)break}t<e.length&&(e=e.subarray(0,t)),this._notPlayedSamples+=e.length,this.output.addSamples(e)}else{let e=new Float32Array(0);this.output.addSamples(e)}})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open(t)}play(){return!(this.state!==Es.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(re.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(re.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),re.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this._synthStopping=!1,this.state=Es.Playing,this.stateChanged.trigger(new di(this.state,!1))}pause(){this.state!==Es.Paused&&this._isMidiLoaded&&(re.debug("AlphaSynth","Pausing playback"),this.state=Es.Paused,this.stateChanged.trigger(new di(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===Es.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(re.debug("AlphaSynth","Stopping playback"),this.state=Es.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 di(this.state,!0)))}playOneTimeMidiFile(e){this._sequencer.isPlayingOneTimeMidi?this.stopOneTimeMidi():this.pause(),this._sequencer.loadOneTimeMidi(e),this._synthesizer.noteOffAll(!0),this.updateTimePosition(0,!0),this._notPlayedSamples=0,this.output.resetSamples(),this.output.play()}resetSoundFonts(){this.stop(),this._synthesizer.resetPresets(),this._loadedSoundFonts=[],this._isSoundFontLoaded=!1,this.soundFontLoaded.trigger()}loadSoundFont(e,t){this.pause();let s=Oe.fromBuffer(e);try{re.debug("AlphaSynth","Loading soundfont from bytes");let e=new Ji;e.load(s),t||(this._loadedSoundFonts=[]),this._loadedSoundFonts.push(e),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),re.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){re.error("AlphaSynth","Could not load soundfont from bytes "+e),this.soundFontLoadFailed.trigger(e)}}checkReadyForPlayback(){if(this.isReadyForPlayback){this._synthesizer.setupMetronomeChannel(this.metronomeVolume);const e=this._sequencer.instrumentPrograms,t=this._sequencer.percussionKeys;let s=!1;for(const i of this._loadedSoundFonts)this._synthesizer.loadPresets(i,e,t,s),s=!0;this.readyForPlayback.trigger()}}loadMidiFile(e){this.stop();try{re.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new ci(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),re.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){re.error("AlphaSynth","Could not load midi from model "+e),this.midiLoadFailed.trigger(e)}}applyTranspositionPitches(e){this._synthesizer.applyTranspositionPitches(e)}setChannelTranspositionPitch(e,t){this._synthesizer.setChannelTranspositionPitch(e,t)}setChannelMute(e,t){this._synthesizer.channelSetMute(e,t)}resetChannelStates(){this._synthesizer.resetChannelStates()}setChannelSolo(e,t){this._synthesizer.channelSetSolo(e,t)}setChannelVolume(e,t){t=Math.max(t,Re.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;let t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*Re.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?(re.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(re.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=Es.Paused,this.stopOneTimeMidi()):this.isLooping?(re.debug("AlphaSynth","Finished playback (main looping)"),this.finished.trigger(),this.tickPosition=e,this._synthStopping=!1):this._synthesizer.activeVoiceCount>0?this._synthStopping||(this._synthesizer.noteOffAll(!0),this._synthStopping=!0):(this._synthStopping=!1,re.debug("AlphaSynth","Finished playback (main)"),this.finished.trigger(),this.stop()))}stopOneTimeMidi(){this.output.pause(),this._synthesizer.noteOffAll(!0),this._sequencer.resetOneTimeMidi(),this.timePosition=this._sequencer.currentTime}updateTimePosition(e,t){let s=e;this._timePosition=s;let i=this._sequencer.currentTimePositionToTickPosition(s);this._tickPosition=i;const a=this._sequencer.currentEndTime,r=this._sequencer.currentEndTick;s>a&&(s=a,i=r);const n=this._sequencer.isPlayingMain?"main":this._sequencer.isPlayingCountIn?"count-in":"one-time";if(re.debug("AlphaSynth",`Position changed: (time: ${s}/${a}, tick: ${i}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new ci(s,a,i,r,t)),t)this._playedEventsQueue.clear();else{const e=new pa;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<s;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new ya(e.toArray()))}}hasSamplesForProgram(e){return this._synthesizer.hasSamplesForProgram(e)}hasSamplesForPercussion(e){return this._synthesizer.hasSamplesForPercussion(e)}}class _a{constructor(){this.ready=new ma,this.samplesPlayed=new fa,this.sampleRequest=new ma}get sampleRate(){return _a.preferredSampleRate}open(){re.debug("AlphaSynth","Initializing synth worker"),this._worker=Tl.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 _a.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case _a.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(){}}_a.CmdOutputPrefix="alphaSynth.output.",_a.CmdOutputAddSamples=_a.CmdOutputPrefix+"addSamples",_a.CmdOutputPlay=_a.CmdOutputPrefix+"play",_a.CmdOutputPause=_a.CmdOutputPrefix+"pause",_a.CmdOutputResetSamples=_a.CmdOutputPrefix+"resetSamples",_a.CmdOutputStop=_a.CmdOutputPrefix+"stop",_a.CmdOutputSampleRequest=_a.CmdOutputPrefix+"sampleRequest",_a.CmdOutputSamplesPlayed=_a.CmdOutputPrefix+"samplesPlayed",_a.preferredSampleRate=0;class wa{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new Sa(new _a,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=Tl.globalThis;e.addEventListener("message",(t=>{let s=t.data;if("alphaSynth.initialize"===s.cmd)_a.preferredSampleRate=s.sampleRate,re.logLevel=s.logLevel,Tl.globalThis.alphaSynthWebWorker=new wa(e,s.bufferTimeInMilliseconds)}))}handleMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":re.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(ss.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(ss.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);break;case"alphaSynth.setChannelTranspositionPitch":this._player.setChannelTranspositionPitch(t.channel,t.semitones);break;case"alphaSynth.setChannelSolo":this._player.setChannelSolo(t.channel,t.solo);break;case"alphaSynth.setChannelVolume":this._player.setChannelVolume(t.channel,t.volume);break;case"alphaSynth.resetChannelStates":this._player.resetChannelStates();break;case"alphaSynth.destroy":this._player.destroy(),this._main.postMessage({cmd:"alphaSynth.destroyed"});break;case"alphaSynth.applyTranspositionPitches":this._player.applyTranspositionPitches(new Map(JSON.parse(t.transpositionPitches)))}}onPositionChanged(e){this._main.postMessage({cmd:"alphaSynth.positionChanged",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onPlayerStateChanged(e){this._main.postMessage({cmd:"alphaSynth.playerStateChanged",state:e.state,stopped:e.stopped})}onFinished(){this._main.postMessage({cmd:"alphaSynth.finished"})}onSoundFontLoaded(){this._main.postMessage({cmd:"alphaSynth.soundFontLoaded"})}onSoundFontLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.soundFontLoadFailed",error:this.serializeException(e)})}serializeException(e){let t=JSON.parse(JSON.stringify(e));return e.message&&(t.message=e.message),e.stack&&(t.stack=e.stack),e.constructor&&e.constructor.name&&(t.type=e.constructor.name),t}onMidiLoaded(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onMidiLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",error:this.serializeException(e)})}onReadyForPlayback(){this._main.postMessage({cmd:"alphaSynth.readyForPlayback"})}onMidiEventsPlayed(e){this._main.postMessage({cmd:"alphaSynth.midiEventsPlayed",events:e.events.map(ss.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}!function(e){e[e.Browser=0]="Browser",e[e.NodeJs=1]="NodeJs",e[e.BrowserModule=2]="BrowserModule"}(Rs||(Rs={}));class Ba{constructor(e,t){this.characterWidths=e,this.fontSizeToHeight=t}}class ka{static generateFontLookup(e){if(!ka.FontSizeLookupTables.has(e))if(Tl.isRunningInWorker||Tl.webPlatform==Rs.NodeJs){const t=new Ba(new Uint8Array([8]),1.2);ka.FontSizeLookupTables.set(e,t)}else{let t=document.createElement("canvas").getContext("2d");const s=11;t.font=`${s}px ${e}`;const i=[];let a="";for(let e=ka.ControlChars;e<255;e++){let s=String.fromCharCode(e);a+=s;const r=t.measureText(s);i.push(r.width)}const r=t.measureText(a+"ÄÖÜÁÈ"),n=0-Math.abs(r.fontBoundingBoxAscent),o=0+Math.abs(r.fontBoundingBoxDescent)-n,h=new Ba(new Uint8Array(i),o/s);ka.FontSizeLookupTables.set(e,h)}}static measureString(e,t,s,i,a){let r,n=t[0];for(let e=0;e<t.length;e++)if(ka.FontSizeLookupTables.has(t[e])){n=t[e];break}ka.FontSizeLookupTables.has(n)||ka.generateFontLookup(n),r=ka.FontSizeLookupTables.get(n);let o=1;i===Je.Italic&&(o*=1.1),a===Ye.Bold&&(o*=1.1);let h=0;for(let t=0;t<e.length;t++){let i=Math.min(r.characterWidths.length-1,e.charCodeAt(t)-ka.ControlChars);i>=0&&(h+=r.characterWidths[i]*s/11)}return o*=1.07,new de(h*o,s*r.fontSizeToHeight)}}ka.FontSizeLookupTables=new Map,ka.ControlChars=32;class Ta{constructor(){this.id=le.newGuid(),this.x=0,this.y=0,this.width=0,this.height=0,this.totalWidth=0,this.totalHeight=0,this.firstMasterBarIndex=-1,this.lastMasterBarIndex=-1,this.renderResult=null}}class xa{constructor(){this.beats=[]}addBeat(e){e.barBounds=this,this.beats.push(e),this.masterBarBounds.addBeat(e)}findBeatAtPos(e){let t=null;for(let s of this.beats)if(!t||s.realBounds.x<e)t=s;else if(s.realBounds.x>e)break;return t}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.beats.sort(((e,t)=>e.realBounds.x-t.realBounds.x));for(const t of this.beats)t.finish(e)}}class Na{constructor(){this.onNotesX=0,this.notes=null}addNote(e){this.notes||(this.notes=[]),e.beatBounds=this,this.notes.push(e)}findNoteAtPos(e,t){const s=this.notes;if(!s)return null;for(let i of s){let s=i.noteHeadBounds.y+i.noteHeadBounds.h,a=i.noteHeadBounds.x+i.noteHeadBounds.w;if(i.noteHeadBounds.x<=e&&i.noteHeadBounds.y<=t&&e<=a&&t<=s)return i.note}return null}finish(e=1){if(this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.notes)for(const t of this.notes)t.finish(e)}}class va{constructor(){this.index=0,this.isFirstOfLine=!1,this.bars=[],this.staffSystemBounds=null}get staveGroupBounds(){return this.staffSystemBounds}addBar(e){e.masterBarBounds=this,this.bars.push(e)}findBeatAtPos(e,t){let s=null;for(let t of this.bars){let i=t.findBeatAtPos(e);if(i&&(!s||s.realBounds.x<i.realBounds.x)){const t=Math.abs(i.realBounds.x-e);(!s||t<1e7)&&(s=i)}}return s?s.beat:null}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.lineAlignedBounds.scaleWith(e),this.bars.sort(((e,t)=>e.realBounds.y<t.realBounds.y?-1:e.realBounds.y>t.realBounds.y?1:e.realBounds.x<t.realBounds.x?-1:e.realBounds.x>t.realBounds.x?1:0));for(const t of this.bars)t.finish(e)}addBeat(e){this.staffSystemBounds.boundsLookup.addBeat(e)}}class Pa{finish(e=1){this.noteHeadBounds.scaleWith(e)}}class Ca{constructor(){this.index=0,this.bars=[]}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e);for(let t of this.bars)t.finish(e)}addBar(e){this.boundsLookup.addMasterBar(e),e.staffSystemBounds=this,this.bars.push(e)}findBarAtPos(e){let t=null;for(let s of this.bars)if(!t||s.realBounds.x<e)t=s;else if(e>s.realBounds.x+s.realBounds.w)break;return t}}class Ea{constructor(){this._beatLookup=new Map,this._masterBarLookup=new Map,this._currentStaffSystem=null,this.staffSystems=[],this.isFinished=!1}toJson(){let e={},t=[];e.staffSystems=t;for(let e of this.staffSystems){let s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.bars=[];for(let t of e.bars){let e={};e.lineAlignedBounds=this.boundsToJson(t.lineAlignedBounds),e.visualBounds=this.boundsToJson(t.visualBounds),e.realBounds=this.boundsToJson(t.realBounds),e.index=t.index,e.bars=[];for(let s of t.bars){let t={};t.visualBounds=this.boundsToJson(s.visualBounds),t.realBounds=this.boundsToJson(s.realBounds),t.beats=[];for(let e of s.beats){let s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.onNotesX=e.onNotesX;let i=s;if(i.beatIndex=e.beat.index,i.voiceIndex=e.beat.voice.index,i.barIndex=e.beat.voice.bar.index,i.staffIndex=e.beat.voice.bar.staff.index,i.trackIndex=e.beat.voice.bar.staff.track.index,e.notes){let t=s.notes=[];for(let s of e.notes){let e={};e.index=s.note.index,e.noteHeadBounds=this.boundsToJson(s.noteHeadBounds),t.push(e)}}t.beats.push(s)}e.bars.push(t)}s.bars.push(e)}t.push(s)}return e}static fromJson(e,t){let s=new Ea,i=e.staffSystems;for(let e of i){let i=new Ca;i.visualBounds=Ea.boundsFromJson(e.visualBounds),i.realBounds=Ea.boundsFromJson(e.realBounds),s.addStaffSystem(i);for(let s of e.bars){let e=new va;e.index=s.index,e.isFirstOfLine=s.isFirstOfLine,e.lineAlignedBounds=Ea.boundsFromJson(s.lineAlignedBounds),e.visualBounds=Ea.boundsFromJson(s.visualBounds),e.realBounds=Ea.boundsFromJson(s.realBounds),i.addBar(e);for(let i of s.bars){let s=new xa;s.visualBounds=Ea.boundsFromJson(i.visualBounds),s.realBounds=Ea.boundsFromJson(i.realBounds),e.addBar(s);for(let e of i.beats){let i=new Na;i.visualBounds=Ea.boundsFromJson(e.visualBounds),i.realBounds=Ea.boundsFromJson(e.realBounds),i.onNotesX=e.onNotesX;let a=e;if(i.beat=t.tracks[a.trackIndex].staves[a.staffIndex].bars[a.barIndex].voices[a.voiceIndex].beats[a.beatIndex],e.notes){i.notes=[];for(let t of e.notes){let e=new Pa,s=t;e.note=i.beat.notes[s.index],e.noteHeadBounds=Ea.boundsFromJson(t.noteHeadBounds),i.addNote(e)}}s.addBeat(i)}}}}return s}static boundsFromJson(e){const t=new ds;return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}boundsToJson(e){let t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(e=1){for(let t of this.staffSystems)t.finish(e);this.isFinished=!0}addStaffSystem(e){e.index=this.staffSystems.length,e.boundsLookup=this,this.staffSystems.push(e),this._currentStaffSystem=e}addMasterBar(e){e.staffSystemBounds?this._masterBarLookup.set(e.index,e):(e.staffSystemBounds=this._currentStaffSystem,this._masterBarLookup.set(e.index,e),this._currentStaffSystem.addBar(e))}addBeat(e){this._beatLookup.has(e.beat.id)||this._beatLookup.set(e.beat.id,[]),this._beatLookup.get(e.beat.id)?.push(e)}findMasterBarByIndex(e){return this._masterBarLookup.has(e)?this._masterBarLookup.get(e):null}findMasterBar(e){let t=e.index;return this._masterBarLookup.has(t)?this._masterBarLookup.get(t):null}findBeat(e){const t=this.findBeats(e);return t?t[0]:null}findBeats(e){let t=e.id;return this._beatLookup.has(t)?this._beatLookup.get(t):null}getBeatAtPos(e,t){let s=0,i=this.staffSystems.length-1,a=-1;for(;s<=i;){let e=(i+s)/2|0,r=this.staffSystems[e];if(t>=r.realBounds.y&&t<=r.realBounds.y+r.realBounds.h){a=e;break}t<r.realBounds.y?i=e-1:s=e+1}if(-1===a)return null;let r=this.staffSystems[a].findBarAtPos(e);return r?r.findBeatAtPos(e,t):null}getNoteAtPos(e,t,s){const i=this.findBeats(e);if(i)for(const e of i){const i=e.findNoteAtPos(t,s);if(i)return i}return null}}class Fa{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 fa,this.renderFinished=new fa,this.partialRenderFinished=new fa,this.partialLayoutFinished=new fa,this.postRenderFinished=new ma,this.error=new fa,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=Tl.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=Tl.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?(re.debug("Rendering","Request render of lazy partial "+e),t.renderLazyPartial(e)):re.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 Ea,this.recreateCanvas(),this.canvas.lineWidth=1,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){re.debug("Rendering","Rendering "+this.tracks.length+" tracks");for(let e=0;e<this.tracks.length;e++){let t=this.tracks[e];re.debug("Rendering","Track "+e+": "+t.name)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),re.debug("Rendering","Rendering finished")}else re.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),re.debug("Rendering","Clearing finished");else re.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(re.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(re.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new Ea,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):re.debug("Rendering","Current layout does not support dynamic resizing, nothing was done",null),re.debug("Rendering","Resize finished")}layoutAndRender(){re.debug("Rendering","Rendering at scale "+this.settings.display.scale+" with layout "+this.layout.name,null),this.layout.layoutAndRender(),this._renderedTracks=this.tracks,this.onRenderFinished(),this.postRenderFinished.trigger()}onRenderFinished(){this.boundsLookup?.finish(this.settings.display.scale);const e=new Ta;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}class Da{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){Tl.globalThis.alphaTabWebWorker=new Da(Tl.globalThis)}handleMessage(e){let t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":let e=ss.jsObjectToSettings(t.settings);re.logLevel=e.core.logLevel,this._renderer=new Fa(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:ss.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(s,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(!(e instanceof Map)){const t=e;e=new Map;for(const s in t)e.set(s,t[s])}if(e){ka.FontSizeLookupTables||(ka.FontSizeLookupTables=new Map);for(let[t,s]of e)ka.FontSizeLookupTables.set(t,s)}}updateSettings(e){At.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){re.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class La{constructor(){this._canvas=null,this._color=new Ce(0,0,0,255),this._font=new rt("Arial",10,Je.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 rt(s,parseFloat(t.fontSize),Je.Plain),this._measureCanvas=document.createElement("canvas"),this._measureCanvas.width=10,this._measureCanvas.height=10,this._measureCanvas.style.width="10px",this._measureCanvas.style.height="10px",this._measureContext=this._measureCanvas.getContext("2d"),this._measureContext.textBaseline="hanging"}destroy(){}onRenderFinished(){return null}beginRender(e,t){const s=this.settings.display.scale;this._canvas=document.createElement("canvas"),this._canvas.width=e*Tl.HighDpiFactor|0,this._canvas.height=t*Tl.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(Tl.HighDpiFactor*s,Tl.HighDpiFactor*s),this._context.lineWidth=this._lineWidth}endRender(){let e=this._canvas;return this._canvas=null,e}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._context.strokeStyle=e.rgba,this._context.fillStyle=e.rgba)}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._context&&(this._context.lineWidth=e)}fillRect(e,t,s,i){s>0&&this._context.fillRect(0|e,0|t,s,i)}strokeRect(e,t,s,i){const a=this.lineWidth%2==0?0:.5;this._context.strokeRect((0|e)+a,(0|t)+a,s,i)}beginPath(){this._context.beginPath()}closePath(){this._context.closePath()}moveTo(e,t){this._context.moveTo(e,t)}lineTo(e,t){this._context.lineTo(e,t)}quadraticCurveTo(e,t,s,i){this._context.quadraticCurveTo(e,t,s,i)}bezierCurveTo(e,t,s,i,a,r){this._context.bezierCurveTo(e,t,s,i,a,r)}fillCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.fill()}strokeCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.stroke()}fill(){this._context.fill(),this._context.beginPath()}stroke(){this._context.stroke(),this._context.beginPath()}get font(){return this._font}set font(e){this._font=e,this._context&&(this._context.font=e.toCssString(1)),this._measureContext.font=e.toCssString(1)}get textAlign(){switch(this._context.textAlign){case"left":default:return D.Left;case"center":return D.Center;case"right":return D.Right}}set textAlign(e){switch(e){case D.Left:this._context.textAlign="left";break;case D.Center:this._context.textAlign="center";break;case D.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return L.Top;case"middle":return L.Middle;case"bottom":return L.Bottom}}set textBaseline(e){switch(e){case L.Top:this._context.textBaseline="hanging";break;case L.Middle:this._context.textBaseline="middle";break;case L.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,s){this._context.fillText(e,t,s)}measureText(e){const t=this._measureContext.measureText(e);return new de(t.width,t.actualBoundingBoxDescent-t.actualBoundingBoxAscent)}fillMusicFontSymbol(e,t,s,i,a=!1){i!==F.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!==F.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){let r=this._context.textAlign,n=this._context.textBaseline,o=this._context.font;this._context.font=this._musicFont.toCssString(s),this._context.textBaseline="middle",this._context.textAlign=a?"center":"left",this._context.fillText(i,e,t),this._context.textBaseline=n,this._context.font=o,this._context.textAlign=r}beginRotate(e,t,s){this._context.save(),this._context.translate(e,t),this._context.rotate(s*Math.PI/180)}endRotate(){this._context.restore()}}class Ma{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 lt(0,e,t,i,48,8))}addRest(e,t,s){this._smf1Mode||this._midiFile.addEvent(new ut(e,t,s))}addNote(e,t,s,i,a,r){this._midiFile.addEvent(new gt(e,t,r,Ma.fixValue(i),Ma.fixValue(a))),this._midiFile.addEvent(new mt(e,t+s,r,Ma.fixValue(i),Ma.fixValue(a)))}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,s,i,a){this._midiFile.addEvent(new ft(e,t,s,i,Ma.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 bt(e,s))}addBend(e,t,s,i){i=i>=Re.MaxPitchWheel?Re.MaxPitchWheel:Math.floor(i),this._midiFile.addEvent(new St(e,t,s,i))}addNoteBend(e,t,s,i,a){this._smf1Mode?this.addBend(e,t,s,a):(a=a*Re.MaxPitchWheel20/Re.MaxPitchWheel,this._midiFile.addEvent(new _t(e,t,s,i,a)))}finishTrack(e,t){this._midiFile.format!=qe.MultiTrack&&0!=e||this._midiFile.addEvent(new wt(e,t))}}class Ia{constructor(e,t){this.closingIndex=0,this.group=e,this.opening=t,e.closings=e.closings.sort(((e,t)=>e.index-t.index)),this.iterations=e.closings.map((e=>0))}}!function(e){e[e.PlayingNormally=0]="PlayingNormally",e[e.DirectionJumped=1]="DirectionJumped",e[e.DirectionJumpedAlCoda=2]="DirectionJumpedAlCoda",e[e.DirectionJumpedAlDoubleCoda=3]="DirectionJumpedAlDoubleCoda",e[e.DirectionJumpedAlFine=4]="DirectionJumpedAlFine"}(Vs||(Vs={}));class Aa{get finished(){return this.index>=this._score.masterBars.length}constructor(e){this._repeatStack=[],this._groupsOnStack=new Set,this._previousAlternateEndings=0,this._state=Vs.PlayingNormally,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}processCurrent(){const e=this._score.masterBars[this.index];if(this._state===Vs.PlayingNormally){let t=e.alternateEndings;if(0===t&&(t=this._previousAlternateEndings),e===e.repeatGroup.opening&&e.repeatGroup.isClosed&&!this._groupsOnStack.has(e.repeatGroup)){const s=new Ia(e.repeatGroup,e);this._repeatStack.push(s),this._groupsOnStack.add(e.repeatGroup),this._previousAlternateEndings=0,t=e.alternateEndings}if(0===this._repeatStack.length||0===t)this.shouldPlay=!0;else{const e=this._repeatStack[this._repeatStack.length-1],s=e.iterations[e.closingIndex];this._previousAlternateEndings=t,this.shouldPlay=!!(t&1<<s)}}else this.shouldPlay=!0;this.shouldPlay&&(this.currentTick+=e.calculateDuration())}moveNext(){this.moveNextWithDirections()||this.moveNextWithNormalRepeats()}resetRepeats(){this._groupsOnStack.clear(),this._previousAlternateEndings=0,this._repeatStack=[]}handleDaCapo(e,t,s){return!!e.has(t)&&(this.index=0,this._state=s,this.resetRepeats(),!0)}handleDalSegno(e,t,s,i){if(e.has(t)){const e=this.findJumpTarget(i,this.index,!0);return-1!==e&&(this.index=e,this._state=s,this.resetRepeats(),!0)}return!1}handleDaCoda(e,t,s){if(e.has(t)){const e=this.findJumpTarget(s,this.index,!1);return-1===e?(this.index++,!0):(this.index=e,this._state=Vs.PlayingNormally,!0)}return!1}moveNextWithDirections(){const e=this._score.masterBars[this.index],t=null!==e.directions&&e.directions.size>0;if(this._state===Vs.PlayingNormally&&!t)return!1;if(!t)return this.index++,!0;switch(this._state){case Vs.PlayingNormally:return!!(this.handleDaCapo(e.directions,Ve.JumpDaCapo,Vs.DirectionJumped)||this.handleDaCapo(e.directions,Ve.JumpDaCapoAlCoda,Vs.DirectionJumpedAlCoda)||this.handleDaCapo(e.directions,Ve.JumpDaCapoAlDoubleCoda,Vs.DirectionJumpedAlDoubleCoda)||this.handleDaCapo(e.directions,Ve.JumpDaCapoAlFine,Vs.DirectionJumpedAlFine))||(!!(this.handleDalSegno(e.directions,Ve.JumpDalSegno,Vs.DirectionJumped,Ve.TargetSegno)||this.handleDalSegno(e.directions,Ve.JumpDalSegnoAlCoda,Vs.DirectionJumpedAlCoda,Ve.TargetSegno)||this.handleDalSegno(e.directions,Ve.JumpDalSegnoAlDoubleCoda,Vs.DirectionJumpedAlDoubleCoda,Ve.TargetSegno)||this.handleDalSegno(e.directions,Ve.JumpDalSegnoAlFine,Vs.DirectionJumpedAlFine,Ve.TargetSegno))||!!(this.handleDalSegno(e.directions,Ve.JumpDalSegnoSegno,Vs.DirectionJumped,Ve.TargetSegnoSegno)||this.handleDalSegno(e.directions,Ve.JumpDalSegnoSegnoAlCoda,Vs.DirectionJumpedAlCoda,Ve.TargetSegnoSegno)||this.handleDalSegno(e.directions,Ve.JumpDalSegnoSegnoAlDoubleCoda,Vs.DirectionJumpedAlDoubleCoda,Ve.TargetSegnoSegno)||this.handleDalSegno(e.directions,Ve.JumpDalSegnoSegnoAlFine,Vs.DirectionJumpedAlFine,Ve.TargetSegnoSegno)));case Vs.DirectionJumped:return this.index++,!0;case Vs.DirectionJumpedAlCoda:return this.handleDaCoda(e.directions,Ve.JumpDaCoda,Ve.TargetCoda)||this.index++,!0;case Vs.DirectionJumpedAlDoubleCoda:return this.handleDaCoda(e.directions,Ve.JumpDaDoubleCoda,Ve.TargetDoubleCoda)||this.index++,!0;case Vs.DirectionJumpedAlFine:return e.directions.has(Ve.TargetFine)?(this.index=this._score.masterBars.length,!0):(this.index++,!0)}return!0}findJumpTarget(e,t,s){if(s){let s=this.findJumpTargetBackwards(e,t);return-1===s&&(s=this.findJumpTargetForwards(e,t)),s}{let s=this.findJumpTargetForwards(e,t);return-1===s&&(s=this.findJumpTargetBackwards(e,t)),s}}findJumpTargetForwards(e,t){let s=t;for(;s<this._score.masterBars.length;){const t=this._score.masterBars[s].directions;if(t&&t.has(e))return s;s++}return-1}findJumpTargetBackwards(e,t){let s=t;for(;s>=0;){const t=this._score.masterBars[s].directions;if(t&&t.has(e))return s;s--}return-1}moveNextWithNormalRepeats(){const e=this._score.masterBars[this.index].repeatCount-1;if(this._repeatStack.length>0&&e>0){const t=this._repeatStack[this._repeatStack.length-1];if(t.iterations[t.closingIndex]<e){this.index=t.opening.index,t.iterations[t.closingIndex]++;for(let e=0;e<t.closingIndex;e++)t.iterations[e]=0;t.closingIndex=0,this._previousAlternateEndings=0}else t.closingIndex<t.group.closings.length-1?(t.closingIndex++,this.index++):(this._repeatStack.pop(),this._groupsOnStack.delete(t.group),this.index++)}else this.index++}}class Oa{constructor(e,t){this.beat=e,this.playbackStart=t}}class Ra{get duration(){return this.end-this.start}constructor(e,t){this._highlightedBeats=new Map,this.highlightedBeats=[],this.nextBeat=null,this.previousBeat=null,this.start=e,this.end=t}highlightBeat(e,t){e.isEmpty&&!e.voice.isEmpty||this._highlightedBeats.has(e.id)||(this._highlightedBeats.set(e.id,!0),this.highlightedBeats.push(new Oa(e,t)))}getVisibleBeatAtStart(e){for(const t of this.highlightedBeats)if(t.playbackStart==this.start&&e.has(t.beat.voice.bar.staff.track.index))return t.beat;return null}}class Va{constructor(e,t){this.tick=e,this.tempo=t}}class Ha{constructor(){this.start=0,this.end=0,this.tempoChanges=[],this.firstBeat=null,this.lastBeat=null,this.nextMasterBar=null,this.previousMasterBar=null}get tempo(){return this.tempoChanges[0].tempo}insertAfter(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.nextBeat=e.nextBeat,t.previousBeat=e,e.nextBeat&&(e.nextBeat.previousBeat=t),e.nextBeat=t,e==this.lastBeat&&(this.lastBeat=t))}insertBefore(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.previousBeat=e.previousBeat,t.nextBeat=e,e.previousBeat&&(e.previousBeat.nextBeat=t),e.previousBeat=t,e==this.firstBeat&&(this.firstBeat=t))}addBeat(e,t,i,a){const r=i+a;if(null==this.firstBeat){const s=new Ra(i,r);s.highlightBeat(e,t),this.insertAfter(this.firstBeat,s)}else if(i>=this.lastBeat.end){const s=new Ra(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 j(s.General,"Error on building lookup, unknown variant")}if(i<a.start)if(r==a.start){const s=new Ra(i,a.start);s.highlightBeat(e,t),this.insertBefore(this.firstBeat,s)}else if(r<a.end){const s=new Ra(i,a.start);s.highlightBeat(e,t),this.insertBefore(a,s);const n=new Ra(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 Ra(i,a.start);s.highlightBeat(e,t),a.highlightBeat(e,t),this.insertBefore(a,s)}else{const s=new Ra(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 Ra(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 Ra(a.start,i);this.insertBefore(a,s);const n=new Ra(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 Ra(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 Ra(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 Ga{get start(){return this.masterBar.start+this.beatLookup.start}get end(){return this.start+this.tickDuration}constructor(e){this.nextBeat=null,this.tickDuration=0,this.duration=0,this.masterBar=e}calculateDuration(){if(1===this.masterBar.tempoChanges.length)this.duration=ee.ticksToMillis(this.tickDuration,this.masterBar.tempoChanges[0].tempo);else{let e=0,t=this.start,s=this.masterBar.tempoChanges[0].tempo;const i=this.end;for(const a of this.masterBar.tempoChanges)if(a.tick<t)s=a.tempo;else{if(a.tick>i)break;e+=ee.ticksToMillis(a.tick-t,s),s=a.tempo,t=a.tick}i>t&&(e+=ee.ticksToMillis(i-t,s)),this.duration=e}}}class Wa{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[]}findBeat(e,t,s=null){let i=null;return s&&(i=this.findBeatFast(e,s,t)),i||(i=this.findBeatSlow(e,s,t,!1)),i}findBeatFast(e,t,s){if(s>=t.start&&s<t.end)return t;if(t.nextBeat&&s>=t.nextBeat.start&&s<t.nextBeat.end){const s=t.nextBeat;return this.fillNextBeat(s,e),s}return null}fillNextBeat(e,t){e.nextBeat=this.findBeatInMasterBar(e.masterBar,e.beatLookup.nextBeat,e.end,t,!1,!0),null==e.nextBeat&&(e.nextBeat=this.findBeatSlow(t,e,e.end,!0)),e.nextBeat&&(e.tickDuration=e.nextBeat.start-e.start,e.calculateDuration()),e.nextBeat||(e.tickDuration=e.masterBar.end-e.start,e.calculateDuration())}findBeatSlow(e,t,s,i){let a=null;if(null!=t&&(t.masterBar.start<=s&&t.masterBar.end>s?a=t.masterBar:t.masterBar.nextMasterBar&&t.masterBar.nextMasterBar.start<=s&&t.masterBar.nextMasterBar.end>s&&(a=t.masterBar.nextMasterBar)),a||(a=this.findMasterBar(s)),!a)return null;for(;a;){if(a.firstBeat){let t=this.findBeatInMasterBar(a,a.firstBeat,s,e,!0,i);if(t)return t}a=a.nextMasterBar}return null}findBeatInMasterBar(e,t,s,i,a,r){if(!t)return null;let n=null,o=null;const h=s-e.start;for(;null!=t&&null==o;){if(t.start<=h&&h<t.end){if(n=t,o=t.getVisibleBeatAtStart(i),!o)if(r){let s=e;for(;null!=s&&null==o;){for(;null!=t;){if(o=t.getVisibleBeatAtStart(i),o){n=t,e=s;break}t=t.nextBeat}o&&n||(s=s.nextMasterBar,t=s?.firstBeat??null)}}else{let s=e;for(;null!=s&&null==o;){for(;null!=t;){if(o=t.getVisibleBeatAtStart(i),o){n=t,e=s;break}t=t.previousBeat}o&&n||(s=s.previousMasterBar,t=s?.firstBeat??null)}}}else if(t.end>h)break;t=t?.nextBeat??null}if(null==o)return null;return this.createResult(e,n,o,a,i)}createResult(e,t,s,i,a){const r=new Ga(e);return r.beat=s,r.beatLookup=t,r.tickDuration=t.end-t.start,i&&this.fillNextBeat(r,a),r.calculateDuration(),r}findMasterBar(e){const t=this.masterBars;let s=0,i=t.length-1;for(;s<=i;){const a=(i+s)/2|0,r=t[a];if(e>=r.start&&e<r.end)return r;e<r.start?i=a-1:s=a+1}return null}getMasterBar(e){if(!this.masterBarLookup.has(e.index)){const t=new Ha;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 za{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Ua{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class Xa{constructor(){this.durations=[],this.brushInfos=[]}}class Ja{constructor(e,t,s){this._programsPerChannel=new Map,this._currentTime=0,this._calculatedBeatTimers=new Set,this.tickLookup=new Wa,this.applyTranspositionPitches=!0,this.transpositionPitches=new Map,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new Ot,this._handler=s}generate(){this.transpositionPitches.clear(),this._calculatedBeatTimers.clear(),this._currentTime=0;for(const e of this._score.tracks)this.generateTrack(e);re.debug("Midi","Begin midi generation");const e=new Aa(this._score);let t=null,s=this._score.tempo;for(;!e.finished;){const i=e.index,a=this._score.masterBars[i],r=e.currentTick;if(e.processCurrent(),e.shouldPlay){this.generateMasterBar(a,t,r,s),a.tempoAutomations.length>0&&(s=a.tempoAutomations[0].value);for(const e of this._score.tracks)for(const t of e.staves)i<t.bars.length&&this.generateBar(t.bars[i],r,s);a.tempoAutomations.length>0&&(s=a.tempoAutomations[a.tempoAutomations.length-1].value)}e.moveNext(),t=a}for(const t of this._score.tracks)this._handler.finishTrack(t.index,e.currentTick);re.debug("Midi","Midi generation done")}generateTrack(e){this.generateChannel(e,e.playbackInfo.primaryChannel,e.playbackInfo),e.playbackInfo.primaryChannel!==e.playbackInfo.secondaryChannel&&this.generateChannel(e,e.playbackInfo.secondaryChannel,e.playbackInfo)}addProgramChange(e,t,s,i){this._programsPerChannel.has(s)&&this._programsPerChannel.get(s)===i||(this._handler.addProgramChange(e.index,t,s,i),this._programsPerChannel.set(s,i))}static buildTranspositionPitches(e,t){const s=new Map;for(const i of e.tracks){const e=i.index<t.notation.transpositionPitches.length?t.notation.transpositionPitches[i.index]:-i.staves[0].transpositionPitch;s.set(i.playbackInfo.primaryChannel,e),s.set(i.playbackInfo.secondaryChannel,e)}return s}generateChannel(e,t,s){const i=e.index<this._settings.notation.transpositionPitches.length?this._settings.notation.transpositionPitches[e.index]:-e.staves[0].transpositionPitch;this.transpositionPitches.set(t,i);let a=Ja.toChannelShort(s.volume),r=Ja.toChannelShort(s.balance);this._handler.addControlChange(e.index,0,t,Os.VolumeCoarse,a),this._handler.addControlChange(e.index,0,t,Os.PanCoarse,r),this._handler.addControlChange(e.index,0,t,Os.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,Os.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,Os.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,Os.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,Os.DataEntryCoarse,Ja.PitchBendRangeInSemitones),this.addProgramChange(e,0,t,s.program)}static toChannelShort(e){const t=Math.max(-32768,Math.min(32767,8*e-1));return Math.max(t,-1)+1}generateMasterBar(e,t,s,i){t&&t.timeSignatureDenominator===e.timeSignatureDenominator&&t.timeSignatureNumerator===e.timeSignatureNumerator||this._handler.addTimeSignature(s,e.timeSignatureNumerator,e.timeSignatureDenominator);const a=e.calculateDuration(),r=new Ha;if(e.tempoAutomations.length>0){e.tempoAutomations[0].ratioPosition>0&&r.tempoChanges.push(new Va(s,i));for(const t of e.tempoAutomations){const e=s+a*t.ratioPosition;this._handler.addTempo(e,t.value),r.tempoChanges.push(new Va(e,t.value))}}else t?r.tempoChanges.push(new Va(s,i)):(this._handler.addTempo(s,e.score.tempo),r.tempoChanges.push(new Va(s,e.score.tempo)));r.masterBar=e,r.start=s,r.end=r.start+a,this.tickLookup.addMasterBar(r)}generateBar(e,t,s){let i=this.getPlaybackBar(e);const a=this._currentTime;for(const r of i.voices)this._currentTime=a,this.generateVoice(r,t,e,s);const r=i.masterBar,n=r.calculateDuration(),o=r.tempoAutomations.slice();if(0===o.length)this._currentTime=a+ee.ticksToMillis(n,s);else{this._currentTime=a;let e=t,i=s;const r=t+n;for(const t of o){const s=n*t.ratioPosition-e;s>0&&(this._currentTime+=ee.ticksToMillis(s,i)),i=t.value,e+=s}const h=r-e;h>0&&(this._currentTime+=ee.ticksToMillis(h,i))}i.id!==e.id&&this.tickLookup.addBeat(e.voices[0].beats[0],0,n)}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,i){if(e.isEmpty&&(!e.bar.isEmpty||0!==e.index))return;const a=s.masterBar.tempoAutomations.slice();let r=i;const n=s.masterBar.calculateDuration();for(const i of e.beats){const e=i.playbackStart/n;for(;a.length>0&&a[0].ratioPosition<=e;)r=a.shift().value;this.generateBeat(i,t,s,r)}}generateBeat(e,t,s,i){let a=e.playbackStart,r=e.playbackDuration;const n=e.voice.bar.masterBar.calculateDuration();e.voice.bar.isEmpty?r=n:e.voice.bar.masterBar.tripletFeel!==C.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(a-=this._currentTripletFeel.secondBeatStartOffset,r=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=Ja.calculateTripletFeelInfo(a,r,e),this._currentTripletFeel&&(r=this._currentTripletFeel.firstBeatDuration))),e.showTimer&&!this._calculatedBeatTimers.has(e.id)&&(e.timer=this._currentTime,this._calculatedBeatTimers.add(e.id)),this._currentTime+=ee.ticksToMillis(r,i),s===e.voice.bar&&this.tickLookup.addBeat(e,a,r);const o=e.voice.bar.staff.track;for(const s of e.automations)this.generateNonTempoAutomation(e,s,t);if(e.isRest)this._handler.addRest(o.index,t+a,o.playbackInfo.primaryChannel);else if(e.deadSlapped)this.generateDeadSlap(e,t+a);else{let s=this.getBrushInfo(e),n=this.getRasgueadoInfo(e,r);for(const o of e.notes)this.generateNote(o,t+a,r,i,s,n)}if(e.fade!==O.None&&this.generateFade(e,t+a,r),e.vibrato!==w.None){let s=240,i=3;switch(e.vibrato){case w.Slight:s=this._settings.player.vibrato.beatSlightLength,i=this._settings.player.vibrato.beatSlightAmplitude;break;case w.Wide:s=this._settings.player.vibrato.beatWideLength,i=this._settings.player.vibrato.beatWideAmplitude}this.generateVibratorWithParams(t+a,e.playbackDuration,s,0,i,((t,s)=>{this._handler.addBend(e.voice.bar.staff.track.index,t,o.playbackInfo.secondaryChannel,s)}))}}static calculateTripletFeelInfo(e,t,s){let i;switch(s.voice.bar.masterBar.tripletFeel){case C.Triplet8th:case C.Dotted8th:case C.Scottish8th:i=p.Eighth;break;case C.Triplet16th:case C.Dotted16th:case C.Scottish16th:i=p.Sixteenth;break;default:return null}const a=ee.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 Ua;switch(s.voice.bar.masterBar.tripletFeel){case C.Triplet8th:r.firstBeatDuration=ee.applyTuplet(ee.toTicks(p.Quarter),3,2),r.secondBeatDuration=ee.applyTuplet(ee.toTicks(p.Eighth),3,2);break;case C.Dotted8th:r.firstBeatDuration=ee.applyDot(ee.toTicks(p.Eighth),!1),r.secondBeatDuration=ee.toTicks(p.Sixteenth);break;case C.Scottish8th:r.firstBeatDuration=ee.toTicks(p.Sixteenth),r.secondBeatDuration=ee.applyDot(ee.toTicks(p.Eighth),!1);break;case C.Triplet16th:r.firstBeatDuration=ee.applyTuplet(ee.toTicks(p.Eighth),3,2),r.secondBeatDuration=ee.applyTuplet(ee.toTicks(p.Sixteenth),3,2);break;case C.Dotted16th:r.firstBeatDuration=ee.applyDot(ee.toTicks(p.Sixteenth),!1),r.secondBeatDuration=ee.toTicks(p.ThirtySecond);break;case C.Scottish16th:r.firstBeatDuration=ee.toTicks(p.ThirtySecond),r.secondBeatDuration=ee.applyDot(ee.toTicks(p.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateDeadSlap(e,t){const s=ee.toTicks(p.SixtyFourth),i=e.voice.bar.staff;if(i.tuning.length>0)for(const e of i.tuning)this._handler.addNote(i.track.index,t,s,e,ee.dynamicToVelocity(g.F),i.track.playbackInfo.primaryChannel)}needsSecondaryChannel(e){return e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==w.None}determineChannel(e,t){if(this.needsSecondaryChannel(t))return e.playbackInfo.secondaryChannel;let s=t;for(;s.isTieDestination;)if(s=s.tieOrigin,this.needsSecondaryChannel(s))return e.playbackInfo.secondaryChannel;for(s=t;s.isTieOrigin;)if(s=s.tieDestination,this.needsSecondaryChannel(s))return e.playbackInfo.secondaryChannel;return e.playbackInfo.primaryChannel}generateNote(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.beat.voice.bar.staff;let h=e.calculateRealValue(this.applyTranspositionPitches,!0);if(e.isPercussion){const t=ue.getArticulation(e);t&&(h=t.outputMidiNumber)}const l=null==r&&e.isStringed&&e.string<=a.length?a[e.string-1]:0,d=t+l,c=this.getNoteDuration(e,s,i);c.untilTieOrSlideEnd-=l,c.noteOnly-=l,c.letRingEnd-=l;const u=Ja.getNoteVelocity(e),p=this.determineChannel(n,e);let g=0,m=Math.max(c.untilTieOrSlideEnd,c.letRingEnd);g=e.hasBend?Ja.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?Ja.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===_.Legato?-1:Ja.getPitchWheel(0),g>=0&&this._handler.addNoteBend(n.index,d,p,h,g),e.beat.hasRasgueado?this.generateRasgueado(n,e,d,h,u,p,r):e.ornament===M.None?!e.isTrill||o.isPercussion?e.beat.isTremolo?this.generateTremoloPicking(e,d,c,h,u,p):(e.hasBend?this.generateBend(e,d,c,h,p,i):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,d,c,p,i):e.slideInType!==S.None||e.slideOutType!==_.None?this.generateSlide(e,d,c,h,p,i):(e.vibrato!==w.None||e.isTieDestination&&e.tieOrigin.vibrato!==w.None)&&this.generateVibrato(e,d,c,h,p),e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===_.Legato||this._handler.addNote(n.index,d,m,h,u,p)):this.generateTrill(e,d,c,h,u,p):this.generateOrnament(n,e,d,m,h,u,p)}generateOrnament(e,t,s,i,a,r,n){let o,h;const l=a%12,d=1/3;switch(t.ornament){case M.Turn:o=[a+Ja.OrnamentKeysUp[l],a,a+Ja.OrnamentKeysDown[l]],h=[ee.toTicks(p.Sixteenth)*d,ee.toTicks(p.Sixteenth)*d,ee.toTicks(p.Sixteenth)*d];break;case M.InvertedTurn:o=[a+Ja.OrnamentKeysDown[l],a,a+Ja.OrnamentKeysUp[l]],h=[ee.toTicks(p.Sixteenth)*d,ee.toTicks(p.Sixteenth)*d,ee.toTicks(p.Sixteenth)*d];break;case M.UpperMordent:o=[a,a+Ja.OrnamentKeysUp[l]],h=[ee.toTicks(p.ThirtySecond),ee.toTicks(p.ThirtySecond)];break;case M.LowerMordent:o=[a,a+Ja.OrnamentKeysDown[l]],h=[ee.toTicks(p.ThirtySecond),ee.toTicks(p.ThirtySecond)];break;default:return}let c=1;i<ee.QuarterTime&&(c=i/ee.QuarterTime),r-=ee.VelocityIncrement;let u=0;for(let t=0;t<o.length;t++){const i=h[t]*c;this._handler.addNote(e.index,s,i,o[t],r,n),s+=i,u+=i}const g=i-u;this._handler.addNote(e.index,s,g,a,r,n)}getNoteDuration(e,t,s){const i=new za;if(i.noteOnly=t,i.untilTieOrSlideEnd=t,i.letRingEnd=t,e.isDead)return i.noteOnly=this.applyStaticDuration(Ja.DefaultDurationDead,t,s),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isPalmMute)return i.noteOnly=this.applyStaticDuration(Ja.DefaultDurationPalmMute,t,s),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isStaccato)return i.noteOnly=t/2|0,i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isTieOrigin){const a=e.tieDestination;if(a)if(e.isTieDestination){const e=this.getNoteDuration(a,a.beat.playbackDuration,s);i.untilTieOrSlideEnd=t+e.untilTieOrSlideEnd}else{const t=e.beat.absolutePlaybackStart,r=this.getNoteDuration(a,a.beat.playbackDuration,s),n=a.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;i.untilTieOrSlideEnd=n-t}}else if(e.slideOutType===_.Legato){const t=e.slideTarget;if(t){const a=e.beat.absolutePlaybackStart,r=this.getNoteDuration(t,t.beat.playbackDuration,s),n=t.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;i.untilTieOrSlideEnd=n-a}}if(e.isLetRing&&this._settings.notation.notationMode===T.GuitarPro){let s=e.beat,a=0;const r=e.beat.voice.bar.masterBar.calculateDuration();for(;s.nextBeat;){let t=s.nextBeat;if(t.isRest)break;if(e.isStringed&&t.hasNoteOnString(e.string))break;if(s=s.nextBeat,a=s.absolutePlaybackStart-e.beat.absolutePlaybackStart+s.playbackDuration,a>r){a=r;break}}s===e.beat?i.letRingEnd=t:i.letRingEnd=a}else i.letRingEnd=i.untilTieOrSlideEnd;return i}applyStaticDuration(e,t,s){const i=s*e/te.MaxPosition|0;return Math.min(i,t)}static getNoteVelocity(e){let t=e.dynamics;switch(!e.beat.voice.bar.staff.isPercussion&&e.hammerPullOrigin&&t--,e.isGhost&&t--,e.accentuated){case i.Normal:t++;break;case i.Heavy:t+=2}return ee.dynamicToVelocity(t)}generateFade(e,t,s){const i=e.voice.bar.staff.track;switch(e.fade){case O.FadeIn:this.generateFadeSteps(i,t,s,0,Ja.toChannelShort(i.playbackInfo.volume));break;case O.FadeOut:this.generateFadeSteps(i,t,s,Ja.toChannelShort(i.playbackInfo.volume),0);break;case O.VolumeSwell:const e=s/2|0;this.generateFadeSteps(i,t,e,0,Ja.toChannelShort(i.playbackInfo.volume)),this.generateFadeSteps(i,t+e,e,Ja.toChannelShort(i.playbackInfo.volume),0)}}generateFadeSteps(e,t,s,i,a){const r=(a-i)/(s=.8*s|0),n=s/120+1|0,o=t+s;for(let s=0;s<n;s++){const h=s===n-1,l=h?o:t+120*s,d=h?a:Math.round(i+(l-t)*r);this._handler.addControlChange(e.index,l,e.playbackInfo.primaryChannel,Os.VolumeCoarse,d),this._handler.addControlChange(e.index,l,e.playbackInfo.secondaryChannel,Os.VolumeCoarse,d)}}generateVibrato(e,t,s,i,a){let r=0,n=0;switch(e.vibrato!==w.None?e.vibrato:e.isTieDestination?e.tieOrigin.vibrato:w.Slight){case w.Slight:r=this._settings.player.vibrato.noteSlightLength,n=this._settings.player.vibrato.noteSlightAmplitude;break;case w.Wide:r=this._settings.player.vibrato.noteWideLength,n=this._settings.player.vibrato.noteWideAmplitude;break;default:return}const o=e.beat.voice.bar.staff.track;let h=0;if(e.isTieDestination&&e.tieOrigin.hasBend){const t=e.tieOrigin.bendPoints;h=t[t.length-1].value}this.generateVibratorWithParams(t,s.noteOnly,r,h,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)}))}generateVibratorWithParams(e,t,s,i,a,r){const n=this.vibratoResolution,o=s/2|0,h=e+t;for(;e<h;){let t=0;const l=e+s<h?s:h-e;for(;t<l;){let s=i+a*Math.sin(t*Math.PI/o);r(e+t|0,Ja.getPitchWheel(s)),t+=n}e+=s}r(0|h,Ja.getPitchWheel(i))}static getPitchWheel(e){return Re.DefaultPitchWheel+e/2*Ja.PitchValuePerSemitone}generateSlide(e,t,s,i,a,r){let n=e.slideOutType===_.Legato?s.noteOnly:s.untilTieOrSlideEnd,o=[],h=e.beat.voice.bar.staff.track;const l=this._settings.player.slide.simpleSlidePitchOffset,d=Math.floor(te.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),c=Math.floor(te.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case S.IntoFromAbove:o.push(new te(0,l)),o.push(new te(d,0));break;case S.IntoFromBelow:o.push(new te(0,-l)),o.push(new te(d,0))}switch(e.slideOutType){case _.Legato:case _.Shift:o.push(new te(c,0));const t=2*(e.slideTarget.calculateRealValue(this.applyTranspositionPitches,!0)-e.calculateRealValue(this.applyTranspositionPitches,!0));o.push(new te(te.MaxPosition,t));break;case _.OutDown:o.push(new te(te.MaxPosition-d,0)),o.push(new te(te.MaxPosition,-l));break;case _.OutUp:o.push(new te(te.MaxPosition-d,0)),o.push(new te(te.MaxPosition,l))}this.generateWhammyOrBend(t,n,o,r,((e,t)=>{this._handler.addNoteBend(h.index,e,a,i,t)}))}generateBend(e,t,s,i,a,r){let n=e.bendPoints,o=e.beat.voice.bar.staff.track;const h=(e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)};let c,u=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend&&t.tieDestination.vibrato==w.None;)t=t.tieDestination;c=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration,r).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==m.None){switch(e.tieDestination.bendType){case d.Bend:case d.BendRelease:case d.PrebendBend:u=e.tieDestination.bendPoints[1].value;break;case d.Prebend:case d.PrebendRelease:u=e.tieDestination.bendPoints[0].value}c=Math.max(s.noteOnly,ee.millisToTicks(this._settings.player.songBookBendDuration,r))}else c=s.noteOnly;n[0].value>0&&!e.isContinuedBend&&t>0&&t--;const p=Math.min(c,ee.millisToTicks(this._settings.player.songBookBendDuration,r));let g=[];switch(e.bendType){case d.Custom:g=n;break;case d.Bend:case d.Release:switch(e.bendStyle){case l.Default:g=n;break;case l.Gradual:g.push(new te(0,e.bendPoints[0].value)),(!u||u<e.bendPoints[1].value)&&(u=e.bendPoints[1].value),g.push(new te(te.MaxPosition,u));break;case l.Fast:return(!u||u<e.bendPoints[1].value)&&(u=e.bendPoints[1].value),void(e.beat.graceType===m.BendGrace?this.generateSongBookWhammyOrBend(t,c,!0,[e.bendPoints[0].value,u],p,r,h):this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,u],p,r,h))}break;case d.BendRelease:switch(e.bendStyle){case l.Default:g=n;break;case l.Gradual:g.push(new te(0,e.bendPoints[0].value)),g.push(new te(te.MaxPosition/2|0,e.bendPoints[1].value)),g.push(new te(te.MaxPosition,e.bendPoints[2].value));break;case l.Fast:return void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],p,r,h)}break;case d.Hold:case d.Prebend:g=n;break;case d.PrebendBend:switch(e.bendStyle){case l.Default:g=n;break;case l.Gradual:g.push(new te(0,e.bendPoints[0].value)),g.push(new te(te.MaxPosition,e.bendPoints[1].value));break;case l.Fast:return h(t,0|Ja.getPitchWheel(e.bendPoints[0].value)),(!u||u<e.bendPoints[1].value)&&(u=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,u],p,r,h)}break;case d.PrebendRelease:switch(e.bendStyle){case l.Default:g=n;break;case l.Gradual:g.push(new te(0,e.bendPoints[0].value)),g.push(new te(te.MaxPosition,e.bendPoints[1].value));break;case l.Fast:return h(t,0|Ja.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,e.bendPoints[1].value],p,r,h)}}this.generateWhammyOrBend(t,c,g,r,h)}generateSongBookWhammyOrBend(e,t,s,i,a,r,n){const o=s?e:e+t-a,h=a/(i.length-1);for(let e=0;e<i.length-1;e++){const t=Ja.getPitchWheel(i[e]),s=Ja.getPitchWheel(i[e+1]),a=o+h*e;this.generateBendValues(a,h,t,s,r,n)}}generateWhammy(e,t,s,i,a){const r=e.whammyBarPoints,n=e.voice.bar.staff.track,o=s.noteOnly;r[0].value>0&&!e.isContinuedWhammy&&t--;const h=(e,t)=>{this._handler.addBend(n.index,e,i,t)};let d=[];switch(e.whammyBarType){case I.Custom:d=r;break;case I.Dive:switch(e.whammyStyle){case l.Default:d=r;break;case l.Gradual:d.push(new te(0,r[0].value)),d.push(new te(te.MaxPosition,r[1].value));break;case l.Fast:const e=Math.min(o,ee.millisToTicks(this._settings.player.songBookBendDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!1,[r[0].value,r[1].value],e,a,h)}break;case I.Dip:switch(e.whammyStyle){case l.Default:d=r;break;case l.Gradual:d.push(new te(0,r[0].value)),d.push(new te(te.MaxPosition/2|0,r[1].value)),d.push(new te(te.MaxPosition,r[2].value));break;case l.Fast:const e=Math.min(o,ee.millisToTicks(this._settings.player.songBookDipDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!0,[r[0].value,r[1].value,r[2].value],e,a,h)}break;case I.Hold:case I.Predive:d=r;break;case I.PrediveDive:switch(e.whammyStyle){case l.Default:d=r;break;case l.Gradual:d.push(new te(0,r[0].value)),d.push(new te(te.MaxPosition/2|0,r[0].value)),d.push(new te(te.MaxPosition,r[1].value));break;case l.Fast:const e=Ja.getPitchWheel(r[0].value);this._handler.addBend(n.index,t,i,0|e);const s=Math.min(o,ee.millisToTicks(this._settings.player.songBookBendDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!1,[r[0].value,r[1].value],s,a,h)}}this.generateWhammyOrBend(t,o,d,a,h)}generateWhammyOrBend(e,t,s,i,a){const r=t/te.MaxPosition;for(let t=0;t<s.length-1;t++){const n=s[t],o=s[t+1],h=Ja.getPitchWheel(n.value),l=Ja.getPitchWheel(o.value),d=r*(o.offset-n.offset),c=e+r*n.offset;this.generateBendValues(c,d,h,l,i,a)}}generateBendValues(e,t,s,i,a,r){const n=ee.ticksToMillis(t,a),o=Math.abs(i-s)/Ja.PitchValuePerSemitone,h=Math.max(Ja.MinBreakpointsPerSemitone*o,n/Ja.MillisecondsPerBreakpoint),l=t/h,d=(i-s)/h,c=e+t;for(let t=0;t<h;t++)r(0|e,Math.round(s)),s+=d,e+=l;r(0|c,i)}generateRasgueado(e,t,s,i,a,r,n){let o=s;for(let s=0;s<n.durations.length;s++){const h=n.brushInfos[s],l=t.isStringed&&t.string<=h.length?h[t.string-1]:0,d=n.durations[s];this._handler.addNote(e.index,o+l,d-l,i,a,r),o+=d}}generateTrill(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=ee.toTicks(e.trillSpeed),l=!0,d=t,c=t+s.untilTieOrSlideEnd;for(;d+10<c;)d+h>=c&&(h=c-d),this._handler.addNote(n.index,d,h,l?o:i,a,r),l=!l,d+=h}generateTremoloPicking(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track;let o=ee.toTicks(e.beat.tremoloSpeed),h=t;const l=t+s.untilTieOrSlideEnd;for(;h+10<l;)h+o>=l&&(o=l-h),this._handler.addNote(n.index,h,o,i,a,r),h+=o}getRasgueadoInfo(e,t){if(!e.hasRasgueado)return null;const s=new Xa,i=Ja.RasgueadoDurations.get(e.rasgueado).reduce(((e,t)=>e+t),0);s.durations=Ja.RasgueadoDurations.get(e.rasgueado).map((e=>t*e/i)),s.brushInfos=new Array(s.durations.length);const a=ee.toTicks(p.Sixteenth);let r=0,n=0;for(const t of e.notes)t.isTieDestination||(r|=1<<t.string-1,n++);const o=Ja.RasgueadoDirections.get(e.rasgueado);for(let t=0;t<s.durations.length;t++){const i=s.durations[t]*a/ee.QuarterTime,h=new Int32Array(e.voice.bar.staff.tuning.length);s.brushInfos[t]=h;const l=o[t];l!==c.None&&this.fillBrushInfo(e,h,l===c.ArpeggioDown||l===c.BrushDown,r,n,i)}return s}getBrushInfo(e){const t=new Int32Array(e.voice.bar.staff.tuning.length);if(e.brushType){let s=0,i=0;for(const t of e.notes)t.isTieDestination||(s|=1<<t.string-1,i++);this.fillBrushInfo(e,t,e.brushType===c.ArpeggioDown||e.brushType===c.BrushDown,s,i,e.brushDuration)}return t}fillBrushInfo(e,t,s,i,a,r){if(e.notes.length>0){let n=0;const o=r/(a-1)|0;for(let a=0;a<e.voice.bar.staff.tuning.length;a++){let e=s?a:t.length-1-a;i&1<<e&&(t[e]=n,n+=o)}}return t}generateNonTempoAutomation(e,t,s){switch(t.type){case 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=Ja.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Os.PanCoarse,i),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Os.PanCoarse,i);break;case a.Volume:let r=Ja.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Os.VolumeCoarse,r),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Os.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);const o=e.playbackStart/n.calculateDuration();for(const e of n.tempoAutomations){if(!(e.ratioPosition<=o))break;t=e.value}-1===s&&(s=r.playbackInfo.program);const h=r.playbackInfo.volume;this.generateTrack(r),this._handler.addTimeSignature(0,n.timeSignatureNumerator,n.timeSignatureDenominator),this._handler.addTempo(0,t);let l=Ja.toChannelShort(h);return this._handler.addControlChange(0,0,r.playbackInfo.primaryChannel,Os.VolumeCoarse,l),this._handler.addControlChange(0,0,r.playbackInfo.secondaryChannel,Os.VolumeCoarse,l),t}generateSingleBeat(e){const t=this.prepareSingleBeat(e);this.generateBeat(e,-e.playbackStart,e.voice.bar,t)}generateSingleNote(e){const t=this.prepareSingleBeat(e.beat);this.generateNote(e,0,e.beat.playbackDuration,t,new Int32Array(e.beat.voice.bar.staff.tuning.length),null)}}Ja.DefaultDurationDead=30,Ja.DefaultDurationPalmMute=80,Ja.OrnamentKeysUp=[2,2,2,1,1,2,2,2,2,2,1,1],Ja.OrnamentKeysDown=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],Ja.PitchBendRangeInSemitones=16,Ja.PitchValuePerSemitone=Re.DefaultPitchWheel/Ja.PitchBendRangeInSemitones,Ja.MinBreakpointsPerSemitone=6,Ja.MillisecondsPerBreakpoint=150,Ja.RasgueadoDirections=new Map([[H.Ii,[c.BrushDown,c.BrushUp]],[H.Mi,[c.BrushDown,c.BrushDown]],[H.MiiTriplet,[c.BrushDown,c.BrushDown,c.BrushUp]],[H.MiiAnapaest,[c.BrushDown,c.BrushDown,c.BrushUp]],[H.PmpTriplet,[c.BrushUp,c.BrushDown,c.BrushDown]],[H.PmpAnapaest,[c.BrushUp,c.BrushDown,c.BrushDown]],[H.PeiTriplet,[c.BrushUp,c.BrushDown,c.BrushDown]],[H.PeiAnapaest,[c.BrushUp,c.BrushDown,c.BrushDown]],[H.PaiTriplet,[c.BrushUp,c.BrushDown,c.BrushDown]],[H.PaiAnapaest,[c.BrushUp,c.BrushDown,c.BrushDown]],[H.AmiTriplet,[c.BrushDown,c.BrushDown,c.BrushDown]],[H.AmiAnapaest,[c.BrushDown,c.BrushDown,c.BrushDown]],[H.Ppp,[c.None,c.BrushDown,c.BrushUp]],[H.Amii,[c.BrushDown,c.BrushDown,c.BrushDown,c.BrushUp]],[H.Amip,[c.BrushDown,c.BrushDown,c.BrushDown,c.BrushUp]],[H.Eami,[c.BrushDown,c.BrushDown,c.BrushDown,c.BrushDown]],[H.Eamii,[c.BrushDown,c.BrushDown,c.BrushDown,c.BrushDown,c.BrushUp]],[H.Peami,[c.BrushDown,c.BrushDown,c.BrushDown,c.BrushDown,c.BrushUp]]]),Ja.RasgueadoDurations=new Map([[H.Ii,[ee.toTicks(p.Eighth),ee.toTicks(p.Eighth)]],[H.Mi,[ee.toTicks(p.Eighth),ee.toTicks(p.Eighth)]],[H.MiiTriplet,[ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3]],[H.MiiAnapaest,[ee.toTicks(p.Sixteenth),ee.toTicks(p.Sixteenth),ee.toTicks(p.Eighth)]],[H.PmpTriplet,[ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3]],[H.PmpAnapaest,[ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Eighth)/3]],[H.PeiTriplet,[ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3]],[H.PeiAnapaest,[ee.toTicks(p.Sixteenth),ee.toTicks(p.Sixteenth),ee.toTicks(p.Eighth)]],[H.PaiTriplet,[ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3]],[H.PaiAnapaest,[ee.toTicks(p.Sixteenth),ee.toTicks(p.Sixteenth),ee.toTicks(p.Eighth)]],[H.AmiTriplet,[ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3,ee.toTicks(p.Eighth)/3]],[H.AmiAnapaest,[ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Eighth)/3]],[H.Ppp,[ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Eighth)/3]],[H.Amii,[ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Eighth)]],[H.Amip,[ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Sixteenth)/3,ee.toTicks(p.Eighth)]],[H.Eami,[ee.toTicks(p.Sixteenth),ee.toTicks(p.Sixteenth),ee.toTicks(p.Sixteenth),ee.toTicks(p.Sixteenth)]],[H.Eamii,[ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5]],[H.Peami,[ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5,ee.toTicks(p.Sixteenth)/5]]]);class Ya{constructor(){this.startTick=0,this.endTick=0}}class qa{constructor(e,t){this.width=0,this.height=0,this.x=e,this.y=t}doLayout(){}paint(e,t,s){}}class ja extends qa{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Ka extends ja{constructor(e,t,s,i){super(e,t),this.glyphScale=0,this.center=!1,this.glyphScale=s,this.symbol=i}paint(e,t,s){s.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale,this.symbol,this.center)}}class Qa extends Ka{constructor(e,t,s,i){super(e,t,i?Qa.GraceScale:1,Qa.getSymbol(s)),this._isGrace=i,this._duration=s}paint(e,t,s){let i=this._isGrace?1:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale,this.symbol,!1)}doLayout(){let e=this._isGrace?Qa.GraceScale:1;switch(this._duration){case p.QuadrupleWhole:this.width=14*e;break;case p.DoubleWhole:case p.Whole:this.width=14*(this._isGrace?Qa.GraceScale:1);break;default:this.width=Qa.QuarterNoteHeadWidth*(this._isGrace?Qa.GraceScale:1)}this.height=Qa.NoteHeadHeight*e}static getSymbol(e){switch(e){case p.QuadrupleWhole:return F.NoteheadDoubleWholeSquare;case p.DoubleWhole:return F.NoteheadDoubleWhole;case p.Whole:return F.NoteheadWhole;case p.Half:return F.NoteheadHalf;default:return F.NoteheadBlack}}}Qa.GraceScale=.75,Qa.NoteHeadHeight=8,Qa.QuarterNoteHeadWidth=9;class $a extends Ka{constructor(e,t,s,i,a){super(e,t,a?Qa.GraceScale:1,$a.getSymbol(s,i,a))}doLayout(){this.width=0}static getSymbol(e,t,s){if(s&&(e=p.Eighth),t===Ge.Up)switch(e){case p.Eighth:return F.FlagEighthUp;case p.Sixteenth:return F.FlagSixteenthUp;case p.ThirtySecond:return F.FlagThirtySecondUp;case p.SixtyFourth:return F.FlagSixtyFourthUp;case p.OneHundredTwentyEighth:return F.FlagOneHundredTwentyEighthUp;case p.TwoHundredFiftySixth:return F.FlagTwoHundredFiftySixthUp;default:return F.FlagEighthUp}switch(e){case p.Eighth:return F.FlagEighthDown;case p.Sixteenth:return F.FlagSixteenthDown;case p.ThirtySecond:return F.FlagThirtySecondDown;case p.SixtyFourth:return F.FlagSixtyFourthDown;case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:return F.FlagOneHundredTwentyEighthDown;default:return F.FlagEighthDown}}}$a.FlagWidth=11;class Za extends qa{get onTimeX(){return this.onNotes.x+this.onNotes.centerX}constructor(e,t){super(0,0),this.ties=[],this.minWidth=0,this.beat=e,this.ties=[],this.voiceContainer=t}addTie(e){e.renderer=this.renderer,this.ties.push(e)}drawBeamHelperAsFlags(e){return e.hasFlag(!1,void 0)}registerLayoutingInfo(e){let t=this.preNotes.computedWidth+this.onNotes.centerX,s=this.onNotes.computedWidth-this.onNotes.centerX;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);this.beat.graceType!==m.None?1===this.beat.graceGroup.beats.length?s+=$a.FlagWidth*Qa.GraceScale:this.beat.graceIndex<this.beat.graceGroup.beats.length-1?s+=7:s+=Za.GraceBeatPadding:i&&this.drawBeamHelperAsFlags(i)&&(s+=$a.FlagWidth);for(const e of this.ties)s+=e.width;e.addBeatSpring(this.beat,t,s)}applyLayoutingInfo(e){this.onNotes.updateBeamingHelper(),this.updateWidth()}doLayout(){this.preNotes.x=0,this.preNotes.renderer=this.renderer,this.preNotes.container=this,this.preNotes.doLayout(),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.renderer=this.renderer,this.onNotes.container=this,this.onNotes.doLayout();let e=this.beat.notes.length-1;for(;e>=0;)this.createTies(this.beat.notes[e--]);this.renderer.registerTies(this.ties),this.updateWidth()}updateWidth(){if(this.minWidth=this.preNotes.width+this.onNotes.width,!this.beat.isRest)if(1===this.onNotes.beamingHelper.beats.length)this.beat.duration>=p.Eighth&&(this.minWidth+=20);else switch(this.beat.duration){case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:this.minWidth+=10}let e=0;for(let t of this.ties)t.width>e&&(e=t.width);this.minWidth+=e,this.width=this.minWidth}scaleToWidth(e){this.onNotes.updateBeamingHelper(),this.width=e}createTies(e){}static getGroupId(e){return"b"+e.id}paint(e,t,s){if(this.beat.voice.isEmpty)return;if(this.preNotes.isEmpty&&this.onNotes.isEmpty&&0===this.ties.length)return;s.beginGroup(Za.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 Na;if(a.beat=this.beat,this.beat.isEmpty)a.visualBounds=new ds,a.visualBounds.x=t+this.x,a.visualBounds.y=e.visualBounds.y,a.visualBounds.w=this.width,a.visualBounds.h=e.visualBounds.h,a.realBounds=new ds,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,a.onNotesX=t+this.x+this.onNotes.centerX;else{a.visualBounds=new ds,a.visualBounds.x=t+this.x,this.preNotes.isEmpty?this.onNotes.isEmpty?a.visualBounds.x=t+this.x:a.visualBounds.x=t+this.x+this.onNotes.x:a.visualBounds.x=t+this.x+this.preNotes.x;let s=0;s=this.onNotes.isEmpty?this.preNotes.isEmpty?t+this.x+this.width:t+this.x+this.preNotes.x+this.preNotes.width:t+this.x+this.onNotes.x+this.onNotes.width,a.visualBounds.w=s-a.visualBounds.x;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);(i&&this.drawBeamHelperAsFlags(i)||this.beat.graceType!==m.None)&&(a.visualBounds.w+=$a.FlagWidth*(this.beat.graceType!==m.None?Qa.GraceScale:1)),a.visualBounds.y=e.visualBounds.y,a.visualBounds.h=e.visualBounds.h,a.realBounds=new ds,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,a.onNotesX=t+this.x+this.onNotes.x+this.onNotes.centerX}e.addBeat(a),this.renderer.settings.core.includeNoteBounds&&this.onNotes.buildBoundingsLookup(a,t+this.x,s+this.y)}}Za.GraceBeatPadding=3;class er{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new xl}causeIssue(){return this.settings=null,!0}}class tr{constructor(e){this.activeBeats=e}}class sr{constructor(e){this.bounds=null,this.beat=e}}class ir{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=Es.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=Es.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new fa,this.activeBeatsChanged=new fa,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new fa,this.beatMouseMove=new fa,this.beatMouseUp=new fa,this.noteMouseDown=new fa,this.noteMouseMove=new fa,this.noteMouseUp=new fa,this.scoreLoaded=new fa,this.resize=new fa,this.renderStarted=new fa,this.renderFinished=new fa,this.postRenderFinished=new ma,this.error=new fa,this.playerReady=new ma,this.playerFinished=new ma,this.soundFontLoaded=new ma,this.midiLoad=new fa,this.midiLoaded=new fa,this.playerStateChanged=new fa,this.playerPositionChanged=new fa,this.midiEventsPlayed=new fa,this.playbackRangeChanged=new fa,this.settingsUpdated=new ma,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),re.logLevel=this.settings.core.logLevel,this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&Tl.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new Fa(this.settings),this.container.resize.on(Tl.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));let s=new er;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;re.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&&le.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?(this.setupPlayer(),e&&this.player?.applyTranspositionPitches(Ja.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 j(s.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(t,e)}}internalRenderTracks(e,t){if(le.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 er;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 re.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{re.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:Es.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=Es.Paused,this.destroyCursors())}setupPlayer(){this.updateCursors(),this.player||(this.player=this.uiFacade.createWorkerPlayer(),this.player&&(this.player.ready.on((()=>{this.loadMidiForScore()})),this.player.readyForPlayback.on((()=>{if(this.onPlayerReady(),this.tracks)for(let e of this.tracks){let t=e.playbackInfo.volume/16;this.player.setChannelVolume(e.playbackInfo.primaryChannel,t),this.player.setChannelVolume(e.playbackInfo.secondaryChannel,t)}})),this.player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this.player.soundFontLoadFailed.on((e=>{this.onError(e)})),this.player.midiLoaded.on(this.onMidiLoaded.bind(this)),this.player.midiLoadFailed.on((e=>{this.onError(e)})),this.player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this.player.positionChanged.on(this.onPlayerPositionChanged.bind(this)),this.player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this.player.playbackRangeChanged.on(this.onPlaybackRangeChanged.bind(this)),this.player.finished.on(this.onPlayerFinished.bind(this)),this.setupPlayerEvents()))}loadMidiForScore(){if(!this.score)return;re.debug("AlphaTab","Generating Midi");let e=new ot,t=new Ma(e),s=new Ja(this.score,this.settings,t);s.applyTranspositionPitches=!1,s.generate(),this._tickCache=s.tickLookup,this.onMidiLoad(e);const i=this.player;i&&(i.loadMidiFile(e),i.applyTranspositionPitches(s.transpositionPitches))}changeTrackVolume(e,t){if(this.player)for(let s of e)this.player.setChannelVolume(s.playbackInfo.primaryChannel,t),this.player.setChannelVolume(s.playbackInfo.secondaryChannel,t)}changeTrackSolo(e,t){if(this.player)for(let s of e)this.player.setChannelSolo(s.playbackInfo.primaryChannel,t),this.player.setChannelSolo(s.playbackInfo.secondaryChannel,t)}changeTrackMute(e,t){if(this.player)for(let s of e)this.player.setChannelMute(s.playbackInfo.primaryChannel,t),this.player.setChannelMute(s.playbackInfo.secondaryChannel,t)}changeTrackTranspositionPitch(e,t){if(this.player)for(let s of e)this.player.setChannelTranspositionPitch(s.playbackInfo.primaryChannel,t),this.player.setChannelTranspositionPitch(s.playbackInfo.secondaryChannel,t)}play(){return!!this.player&&this.player.play()}pause(){this.player&&this.player.pause()}playPause(){this.player&&this.player.playPause()}stop(){this.player&&this.player.stop()}playBeat(e){if(!this.player)return;let t=new ot,s=new Ma(t);new Ja(e.voice.bar.staff.track.score,this.settings,s).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;let t=new ot,s=new Ma(t);new Ja(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=Es.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===Es.Paused){let e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getBeatStart(e.beat))}})))}cursorUpdateTick(e,t,s=!1){let i=this._tickCache;if(i){let a=this._trackIndexLookup;if(null!=a&&a.size>0){let r=i.findBeat(a,e,this._currentBeat);r&&this.cursorUpdateBeat(r,t,s)}}}cursorUpdateBeat(e,t,s,i=!1){const a=e.beat,r=e.nextBeat?.beat??null,n=e.duration,o=e.beatLookup.highlightedBeats;if(!a)return;let h=this.renderer.boundsLookup;if(!h)return;let l=this._currentBeat,d=this._previousCursorCache,c=this._previousStateForCursor;if(!i&&a===l?.beat&&h===d&&c===this._playerState)return;let u=h.findBeat(a);u&&(this._currentBeat=e,this._previousCursorCache=h,this._previousStateForCursor=this._playerState,this.uiFacade.beginInvoke((()=>{this.internalCursorUpdateBeat(a,r,n,t,o,h,u,s)})))}scrollToCursor(){const e=this._currentBarBounds;e&&this.internalScrollToCursor(e)}internalScrollToCursor(e){let t=this.uiFacade.getScrollContainer(),s=Tl.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 Qe.Continuous:let i=this.uiFacade.getOffset(t,this.container);this.uiFacade.scrollToY(t,i.y+s,this.settings.player.scrollSpeed);break;case Qe.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 Qe.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 Qe.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 d=n.barBounds.masterBarBounds,c=d.visualBounds;this._currentBarBounds=d,h&&h.setBounds(c.x,c.y,c.w,c.h),l&&(this.settings.player.enableAnimatedBeatCursor&&l.stopAnimation(),l.setBounds(n.onNotesX,c.y,1,c.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let u=!1;if(this._playerState===Es.Playing&&!i){if(this.settings.player.enableElementHighlighting)for(let t of a){let s=Za.getGroupId(t.beat);this.uiFacade.highlightElements(s,e.voice.bar.index)}if(this.settings.player.enableAnimatedBeatCursor){let e=d.visualBounds.x+d.visualBounds.w;if(t){let s=r.findBeat(t);s&&s.barBounds.masterBarBounds.staffSystemBounds===d.staffSystemBounds&&(e=s.onNotesX)}this.uiFacade.beginInvoke((()=>{l&&l.transitionToX(s/this.playbackSpeed,e)}))}o=!i,u=!0}o&&!this._beatMouseDown&&this.settings.player.scrollMode!==Qe.Off&&this.internalScrollToCursor(d),u&&(this.onPlayedBeatChanged(e),this.onActiveBeatsChanged(new tr(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 sr(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 sr(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===Es.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 Ya;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 sr(t.beat),i=new sr(s.beat);this.cursorSelectRange(e,i)}}else this.cursorSelectRange(null,null)}setupClickHandling(){this.canvasElement.mouseDown.on((e=>{if(!e.isLeftMouseButton)return;this.settings.player.enableUserInteraction&&e.preventDefault();let t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(i&&(this.onBeatMouseDown(e,i),this.settings.core.includeNoteBounds)){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s);a&&this.onNoteMouseDown(e,a)}})),this.canvasElement.mouseMove.on((e=>{if(!this._beatMouseDown)return;let t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(i&&(this.onBeatMouseMove(e,i),this._noteMouseDown)){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s);a&&this.onNoteMouseMove(e,a)}})),this.canvasElement.mouseUp.on((e=>{if(!this._beatMouseDown)return;this.settings.player.enableUserInteraction&&e.preventDefault();let t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(this.onBeatMouseUp(e,i),this._noteMouseDown)if(i){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s)??null;this.onNoteMouseUp(e,a)}else this.onNoteMouseUp(e,null)})),this.renderer.postRenderFinished.on((()=>{this._selectionStart&&this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&this.cursorSelectRange(this._selectionStart,this._selectionEnd)}))}cursorSelectRange(e,t){let s=this.renderer.boundsLookup;if(!s)return;let i=this._selectionWrapper;if(!i)return;if(i.clear(),!e||!t||e.beat===t.beat)return;e.bounds||(e.bounds=s.findBeat(e.beat)),t.bounds||(t.bounds=s.findBeat(t.beat));let a=this._tickCache?.getBeatStart(e.beat)??e.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(t.beat)??t.beat.absolutePlaybackStart)<a){let s=e;e=t,t=s}let r=e.bounds.realBounds.x,n=t.bounds.realBounds.x+t.bounds.realBounds.w;if(t.beat.index===t.beat.voice.beats.length-1&&(n=t.bounds.barBounds.masterBarBounds.realBounds.x+t.bounds.barBounds.masterBarBounds.realBounds.w),e.bounds.barBounds.masterBarBounds.staffSystemBounds!==t.bounds.barBounds.masterBarBounds.staffSystemBounds){let a=e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.x,o=e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.x+e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.w,h=this.uiFacade.createSelectionElement();h.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,o-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(h);let l=e.bounds.barBounds.masterBarBounds.staffSystemBounds.index+1,d=t.bounds.barBounds.masterBarBounds.staffSystemBounds.index;for(let e=l;e<d;e++){let t=s.staffSystems[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),i.appendChild(r)}let c=this.uiFacade.createSelectionElement();c.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(c)}else{let t=this.uiFacade.createSelectionElement();t.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,n-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(t)}}onScoreLoaded(e){this._isDestroyed||(this.scoreLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"scoreLoaded",e))}onResize(e){this._isDestroyed||(this.resize.trigger(e),this.uiFacade.triggerEvent(this.container,"resize",e))}onRenderStarted(e){this._isDestroyed||(this.renderStarted.trigger(e),this.uiFacade.triggerEvent(this.container,"renderStarted",e))}onRenderFinished(e){this._isDestroyed||(this.renderFinished.trigger(e),this.uiFacade.triggerEvent(this.container,"renderFinished",e))}onPostRenderFinished(){this._isDestroyed||(this.postRenderFinished.trigger(),this.uiFacade.triggerEvent(this.container,"postRenderFinished",null))}onError(e){this._isDestroyed||(re.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 ar extends j{constructor(e,t){super(s.General,e),this.xhr=t,Object.setPrototypeOf(this,ar.prototype)}}class rr{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=rr.loadScoreFromBytes(s,i);t(r)}catch(e){s(e)}else 0===a.status?s(new ar("You are offline!!\n Please Check Your Network.",a)):404===a.status?s(new ar("Requested URL not found.",a)):500===a.status?s(new ar("Internel Server Error.",a)):"parsererror"===a.statusText?s(new ar("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?s(new ar("Request Time out.",a)):s(new ar("Unknow Error: "+a.responseText,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Ot);let s=Tl.buildImporters();re.debug("ScoreLoader",`Loading score from ${e.length} bytes using ${s.length} importers`);let i=null,a=Oe.fromBuffer(e);for(let e of s){a.reset();try{re.debug("ScoreLoader","Importing using importer "+e.name),e.init(a,t),i=e.readScore(),re.debug("ScoreLoader","Score imported using "+e.name);break}catch(t){if(!(t instanceof K))throw re.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;re.debug("ScoreLoader",e.name+" does not support the file")}}if(i)return i;throw new K("No compatible importer found for file")}}class nr{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 or{get width(){return this.element.offsetWidth}set width(e){this.element.style.width=e+"px"}get scrollLeft(){return this.element.scrollLeft}set scrollLeft(e){this.element.scrollLeft=e}get scrollTop(){return this.element.scrollTop}set scrollTop(e){this.element.scrollTop=e}get height(){return this.element.offsetHeight}set height(e){this.element.style.height=e>=0?e+"px":"100%"}get isVisible(){return!!this.element.offsetWidth||!!this.element.offsetHeight||!!this.element.getClientRects().length}constructor(e){this._resizeListeners=0,this.lastBounds=new ds,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new nr(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new nr(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new nr(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&or.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,or.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=""}}or.resizeObserver=new ie((()=>new ResizeObserver((e=>{for(const t of e){let e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class hr{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new fa,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(Tl.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0,t=window.setInterval((()=>{re.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);re.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);let s=e=>{this._families.length>1?(re.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(re.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},i=e=>{re.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 re.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){re.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 lr{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 dr{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new ma,this.samplesPlayed=new fa,this.sampleRequest=new ma}get sampleRate(){return this._context?this._context.sampleRate:dr.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(re.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{re.debug("WebAudio",`Audio Context resume success: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}`),e&&e()}),(e=>{re.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,dr.PreferredSampleRate),s=e.createBufferSource();s.buffer=t,s.connect(e.destination),s.start(0),s.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in Tl.globalThis)return new AudioContext;if("webkitAudioContext"in Tl.globalThis)return new webkitAudioContext;throw new j(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,dr.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()}}dr.BufferSize=4096,dr.PreferredSampleRate=44100;class cr extends dr{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/dr.BufferSize),this._circularBuffer=new lr(dr.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*dr.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*dr.BufferSize<t){for(let t=0;t<e;t++)this.onSampleRequest();this._requestedBufferCount+=e}}generateSound(e){let t=e.outputBuffer.getChannelData(0),s=e.outputBuffer.getChannelData(1),i=t.length+s.length,a=this._outputBuffer;a.length!==i&&(a=new Float32Array(i),this._outputBuffer=a);const r=this._circularBuffer.read(a,0,Math.min(a.length,this._circularBuffer.count));let n=0;const o=Math.min(t.length,r);for(let e=0;e<o;e++)t[e]=a[n++],s[e]=a[n++];if(r<t.length)for(let e=r;e<t.length;e++)t[e]=0,s[e]=0;this.onSamplesPlayed(r/Re.AudioChannels),this.requestBuffers()}}class ur{constructor(e,t){this.loaded=e,this.total=t}}class pr{get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return re.logLevel}set logLevel(e){re.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Re.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Re.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Re.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=le.clamp(e,Re.MinPlaybackSpeed,Re.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=Es.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 ma,this.readyForPlayback=new ma,this.finished=new ma,this.soundFontLoaded=new ma,this.soundFontLoadFailed=new fa,this.midiLoaded=new fa,this.midiLoadFailed=new fa,this.stateChanged=new fa,this.positionChanged=new fa,this.midiEventsPlayed=new fa,this.playbackRangeChanged=new fa,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Es.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=Tl.createWebWorker(t)}catch(e){re.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:ss.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,s){re.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=>{re.error("AlphaSynth","Loading failed: "+e.message),this.soundFontLoadFailed.trigger(new ar(e.message,i))},i.onprogress=e=>{re.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),s(new ur(e.loaded,e.total))},i.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:ss.midiFileToJsObject(e)})}applyTranspositionPitches(e){this._synth.postMessage({cmd:"alphaSynth.applyTranspositionPitches",transpositionPitches:JSON.stringify(Array.from(e.entries()))})}setChannelTranspositionPitch(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelTranspositionPitch",channel:e,semitones:t})}setChannelMute(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelMute",channel:e,mute:t})}resetChannelStates(){this._synth.postMessage({cmd:"alphaSynth.resetChannelStates"})}setChannelSolo(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelSolo",channel:e,solo:t})}setChannelVolume(e,t){t=Math.max(t,Re.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 ci(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new ya(t.events.map(ss.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new di(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new ba(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 ci(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 gr{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new fa,this.partialRenderFinished=new fa,this.partialLayoutFinished=new fa,this.renderFinished=new fa,this.postRenderFinished=new ma,this.error=new fa,this._api=e;try{this._worker=Tl.createWebWorker(t)}catch(e){return void re.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=ss.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=Ea.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:ss.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:s,trackIndexes:t,fontSizes:ka.FontSizeLookupTables})}}class mr{constructor(e,t,s,i){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=s,this.selectionWrapper=i}}class fr{static init(){var e;fr._isRegistered||(fr._isRegistered=!0,registerProcessor("alphatab",((e=class extends AudioWorkletProcessor{constructor(t){super(t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,this._isStopped=!1,re.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new lr(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){let t=e.data;switch(t.cmd){case _a.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case _a.CmdOutputResetSamples:this._circularBuffer.clear();break;case _a.CmdOutputStop:this._isStopped=!0}}process(e,t,s){if(1!==t.length&&2!==t[0].length)return!1;let i=t[0][0],a=t[0][1];if(!i||!a)return!0;let r=i.length+a.length,n=this._outputBuffer;n.length!==r&&(n=new Float32Array(r),this._outputBuffer=n);const o=this._circularBuffer.read(n,0,Math.min(n.length,this._circularBuffer.count));let h=0;const l=Math.min(i.length,o);for(let e=0;e<l;e++)i[e]=n[h++],a[e]=n[h++];if(o<i.length)for(let e=o;e<i.length;e++)i[e]=0,a[e]=0;return this.port.postMessage({cmd:_a.CmdOutputSamplesPlayed,samples:o/Re.AudioChannels}),this.requestBuffers(),this._circularBuffer.count>0||!this._isStopped}requestBuffers(){const t=this._bufferCount/2|0;let s=t*e.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*e.BufferSize<s){for(let e=0;e<t;e++)this.port.postMessage({cmd:_a.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}fr._isRegistered=!1;class yr extends dr{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;Tl.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=>{re.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){let t=e.data;switch(t.cmd){case _a.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case _a.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.postMessage({cmd:_a.CmdOutputStop}),this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){this._worklet?.port.postMessage({cmd:_a.CmdOutputAddSamples,samples:e})}resetSamples(){this._worklet?.port.postMessage({cmd:_a.CmdOutputResetSamples})}}class br extends or{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"}(Hs||(Hs={}));class Sr{get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(Tl.bravuraFontChecker.checkForFontAvailability(),!Tl.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(re.debug("Font","All fonts loaded: "+this._fontCheckers.size),!0)}onFontLoaded(e){ka.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 ma,this.canRenderChanged=new ma,this._highlightedElements=[],this._scrollContainer=null,Tl.webPlatform!==Rs.Browser&&Tl.webPlatform!==Rs.BrowserModule)throw new j(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 or(e),this.areWorkersSupported="Worker"in window,Tl.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!==Hs.RenderRequested&&(s.resultState=Hs.RenderRequested,this._api.renderer.renderResult(s.layoutResultId)):e.replaceChildren():s.resultState===Hs.Detached&&(e.replaceChildren(...s.renderedResult),s.resultState=Hs.RenderDone):s.resultState===Hs.RenderDone&&(s.resultState=Hs.Detached,s.replaceChildren())}}}createWorkerRenderer(){return new gr(this._api,this._api.settings)}initialize(e,t){let s;this._api=e,s=t instanceof Ot?t:ss.jsObjectToSettings(t);let i=this.getDataAttributes();At.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 hr(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 or(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 Ne)return t(e),!0;if(e instanceof ArrayBuffer){let s=new Uint8Array(e);return t(rr.loadScoreFromBytes(s,this._api.settings)),!0}return e instanceof Uint8Array?(t(rr.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(rr.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&&rr.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;Tl.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=Hs.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=Hs.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===$e.WebAudioAudioWorklets?(re.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),e=new pr(new yr(this._api.settings),this._api.settings)):t&&(re.debug("Player","Will use webworkers for synthesizing and web audio api with ScriptProcessor for playback"),e=new pr(new cr,this._api.settings)),e?e.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):re.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 mr(new or(t),i,a,new or(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 ds;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 or(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new br(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 _r extends ir{constructor(e,t){super(new Sr(e),t),this.soundFontLoad=new fa}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,d=a.offsetWidth+50,c=window.innerHeight,u=(h/2|0)-(d/2|0)+n,p=(l/2|0)-(c/2|0)+o;i.resizeTo(d,c),i.moveTo(u,p),i.focus();let g=ss.jsObjectToSettings(ss.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,At.fromJson(g,s);let m=new _r(a,g);i.onunload=()=>{m.destroy()},m.renderer.postRenderFinished.on((()=>{i.print()})),m.renderTracks(this.tracks)}downloadMidi(e=qe.SingleTrackMultiChannel){if(!this.score)return;let t=new ot;t.format=e;let s=new Ma(t,!0);new Ja(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 wr{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 re.error("Api","Method '"+t+"' does not exist on jQuery.alphaTab"),null}init(e,t,s){if(!t){t=new _r(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 Br{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.scale=1,this.color=new Ce(255,255,255,255),this.lineWidth=1,this.font=new rt("Arial",10,Je.Plain),this.textAlign=D.Left,this.textBaseline=L.Top}destroy(){}beginRender(e,t){this.scale=this.settings.display.scale,this.buffer=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${0|e}px" height="${0|t}px" class="at-surface-svg">\n`,this._currentPath="",this._currentPathIsEmpty=!0,this.textBaseline=L.Top}beginGroup(e){this.buffer+=`<g class="${e}">`}endGroup(){this.buffer+="</g>"}endRender(){return this.buffer+="</svg>",this.buffer}fillRect(e,t,s,i){s>0&&(this.buffer+=`<rect x="${e*this.scale|0}" y="${t*this.scale|0}" width="${s*this.scale}" height="${i*this.scale}" fill="${this.color.rgba}" />\n`)}strokeRect(e,t,s,i){const a=this.lineWidth*this.scale%2==0?0:.5;this.buffer+=`<rect x="${(e*this.scale|0)+a}" y="${(t*this.scale|0)+a}" width="${s*this.scale}" height="${i*this.scale}" stroke="${this.color.rgba}"`,1!==this.lineWidth&&(this.buffer+=` stroke-width="${this.lineWidth*this.scale}"`),this.buffer+=' fill="transparent" />\n'}beginPath(){}closePath(){this._currentPath+=" z"}moveTo(e,t){this._currentPath+=` M${e*this.scale},${t*this.scale}`}lineTo(e,t){this._currentPathIsEmpty=!1,this._currentPath+=` L${e*this.scale},${t*this.scale}`}quadraticCurveTo(e,t,s,i){this._currentPathIsEmpty=!1,this._currentPath+=` Q${e*this.scale},${t*this.scale},${s*this.scale},${i*this.scale}`}bezierCurveTo(e,t,s,i,a,r){this._currentPathIsEmpty=!1,this._currentPath+=` C${e*this.scale},${t*this.scale},${s*this.scale},${i*this.scale},${a*this.scale},${r*this.scale}`}fillCircle(e,t,s){this._currentPathIsEmpty=!1,e*=this.scale,t*=this.scale,s*=this.scale,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.fill()}strokeCircle(e,t,s){this._currentPathIsEmpty=!1,e*=this.scale,t*=this.scale,s*=this.scale,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.stroke()}fill(){this._currentPathIsEmpty||(this.buffer+=`<path d="${this._currentPath}"`,"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),this.buffer+=' style="stroke: none"/>'),this._currentPath="",this._currentPathIsEmpty=!0}stroke(){if(!this._currentPathIsEmpty){let e=`<path d="${this._currentPath}" stroke="${this.color.rgba}"`;1===this.lineWidth&&1===this.scale||(e+=` stroke-width="${this.lineWidth*this.scale}"`),e+=' style="fill: none" />',this.buffer+=e}this._currentPath="",this._currentPathIsEmpty=!0}fillText(e,t,s){if(""===e)return;let i=`<text x="${t*this.scale|0}" y="${s*this.scale|0}" style='stroke: none; font:${this.font.toCssString(this.settings.display.scale)}; ${this.getSvgBaseLine()}'`;"#000000"!==this.color.rgba&&(i+=` fill="${this.color.rgba}"`),this.textAlign!==D.Left&&(i+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),i+=`>${Br.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 D.Left:return"start";case D.Center:return"middle";case D.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case L.Top:return"dominant-baseline: hanging";case L.Bottom:return"dominant-baseline: ideographic";default:return""}}measureText(e){return e?ka.measureString(e,this.font.families,this.font.size*this.scale,this.font.style,this.font.weight):new de(0,0)}onRenderFinished(){return null}beginRotate(e,t,s){this.buffer+='<g transform="translate('+e*this.scale+" ,"+t*this.scale+") rotate( "+s+')">'}endRotate(){this.buffer+="</g>"}}class kr extends Br{constructor(){super()}fillMusicFontSymbol(e,t,s,i,a){i!==F.None&&this.fillMusicFontSymbolText(e,t,s,`&#${i};`,a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(let e of i)e!==F.None&&(r+=`&#${e};`);this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){e*=this.scale,t*=this.scale,this.buffer+=`<g transform="translate(${e} ${t})" class="at" ><text`;const r=this.scale*s;this.buffer+=1!==r?` style="font-size: ${100*r}%; stroke:none"`:' style="stroke:none"',"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),a&&(this.buffer+=' text-anchor="'+this.getSvgTextAlignment(D.Center)+'"'),this.buffer+=`>${i}</text></g>`}}class Tr{constructor(){this.isInsideBracket=!0,this.isRelevantForBoundsLookup=!0,this.hideOnMultiTrack=!1,this.hideOnPercussionTrack=!1}canCreate(e,t){return!this.hideOnPercussionTrack||!t.isPercussion}}!function(e){e[e.PreNotes=0]="PreNotes",e[e.OnNotes=1]="OnNotes",e[e.MiddleNotes=2]="MiddleNotes",e[e.Stem=3]="Stem",e[e.PostNotes=4]="PostNotes",e[e.EndBeat=5]="EndBeat"}(Gs||(Gs={}));class xr extends qa{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 Nr extends xr{constructor(){super(0,0),this.glyphs=[]}addGlyph(e){e.x=0===this.glyphs.length?0:this.glyphs[this.glyphs.length-1].x+this.glyphs[this.glyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.width=e.x+e.width,super.addGlyph(e)}}class vr extends xr{constructor(e,t,s){super(e,t),this.voice=s,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){let t=this.renderer.layoutingInfo.spaceToForce(e);this.scaleToForce(t)}scaleToForce(e){this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e);let t=this.renderer.layoutingInfo.buildOnTimePositions(e),s=this.beatGlyphs;for(let e=0,i=s.length;e<i;e++){let a=s[e];if(a.beat.graceType===m.None)a.x=t.get(a.beat.absoluteDisplayStart)-a.onTimeX;else{const i=a.beat.graceGroup.beats[0].absoluteDisplayStart,r=a.beat.graceGroup.id;if(a.beat.graceGroup.isComplete&&t.has(i)){a.x=t.get(i)-a.onTimeX;let e=this.renderer.layoutingInfo.allGraceRods.get(r);const s=a.beat.graceGroup.beats[a.beat.graceGroup.beats.length-1].nextBeat,n=s?this.renderer.layoutingInfo.getPreBeatSize(s)+Za.GraceBeatPadding:0;a.x-=n,a.x-=e[a.beat.graceIndex].postSpringWidth,a.x+=e[a.beat.graceIndex].graceBeatWidth;const o=e[a.beat.graceGroup.beats.length-1];a.x-=o.graceBeatWidth}else{let t=this.renderer.layoutingInfo.incompleteGraceRods.get(r);const i=t[a.beat.graceIndex].postSpringWidth-t[a.beat.graceIndex].preSpringWidth;e>0?0===a.beat.graceIndex?a.x=s[e-1].x+s[e-1].width:a.x=s[e-1].x+t[a.beat.graceIndex-1].postSpringWidth-t[a.beat.graceIndex-1].preSpringWidth-i:a.x=-i}}if(e>0){let t=a.x-s[e-1].x;s[e-1].scaleToWidth(t)}if(e===i-1){let e=this.width-s[s.length-1].x;a.scaleToWidth(e)}}}registerLayoutingInfo(e){let t=this.beatGlyphs;for(let s of t)s.registerLayoutingInfo(e)}applyLayoutingInfo(e){let t=this.beatGlyphs;for(let s of t)s.applyLayoutingInfo(e);this.scaleToForce(Math.max(this.renderer.settings.display.stretchForce,e.minStretchForce))}addGlyph(e){let t=e;e.x=0===this.beatGlyphs.length?0:this.beatGlyphs[this.beatGlyphs.length-1].x+this.beatGlyphs[this.beatGlyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.beatGlyphs.push(t),this.width=e.x+e.width,t.beat.hasTuplet&&t.beat.tupletGroup.beats[0].id===t.beat.id&&this.tupletGroups.push(t.beat.tupletGroup)}doLayout(){}paint(e,t,s){s.color=0===this.voice.index?this.renderer.resources.mainGlyphColor:this.renderer.resources.secondaryGlyphColor;for(let i=0,a=this.beatGlyphs.length;i<a;i++)this.beatGlyphs[i].paint(e+this.x,t+this.y,s)}}vr.KeySizeBeat="Beat";class Pr{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class Cr{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:ue.getArticulationByValue(t)?.staffLine??0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case b.ForceDoubleFlat:t+=2;break;case b.ForceDoubleSharp:t-=2;break;case b.ForceFlat:t+=1;break;case b.ForceSharp:t-=1}return t}applyAccidental(e){const t=Cr.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=Cr.getNoteValue(t);return s=e.staff.isPercussion?Cr.getPercussionLine(e,i):Cr.calculateNoteLine(e,i),s}static computeAccidental(e,t,s,i,a=null){let r=e+7,n=s%12,o=r<7?Xe.Flat:Xe.Sharp,h=Cr.KeySignatureLookup[r][n],l=Cr.AccidentalNotes[n],d=Xe.None;if(i)switch(d=l?o:Xe.Natural,d){case Xe.Natural:d=Xe.NaturalQuarterNoteUp;break;case Xe.Sharp:d=Xe.SharpQuarterNoteUp;break;case Xe.Flat:d=Xe.FlatQuarterNoteUp}else{switch(t){case b.ForceSharp:d=Xe.Sharp;break;case b.ForceDoubleSharp:d=Xe.DoubleSharp;break;case b.ForceFlat:d=Xe.Flat;break;case b.ForceDoubleFlat:d=Xe.DoubleFlat;break;default:l?d=o:h&&(d=Xe.Natural)}d!==Xe.None?null!=a?a===d&&(d=Xe.None):h&&d===o&&(d=Xe.None):null!==a&&(d=a===Xe.Natural?Xe.None:Xe.Natural)}return d}getAccidental(e,t,s,i,a=null){let r=0,n=Xe.None;if(this._bar.staff.isPercussion)r=Cr.getPercussionLine(this._bar,e);else{const s=a?a.accidentalMode:b.Default;r=Cr.calculateNoteLine(this._bar,e);const i=this._registeredAccidentals.has(r)?this._registeredAccidentals.get(r):null;n=Cr.computeAccidental(this._bar.masterBar.keySignature,s,e,t,i);let o=!1;switch(n){case Xe.NaturalQuarterNoteUp:case Xe.SharpQuarterNoteUp:case Xe.FlatQuarterNoteUp:break;default:if(a&&a.isTieDestination&&0===a.beat.index){const e=this._barRenderer.previousRenderer;if(e){e.accidentalHelper.getNoteLine(a.tieOrigin)===r&&(o=!0)}}o?n=Xe.None:n!==Xe.None&&this._registeredAccidentals.set(r,n)}}return a?(this._appliedScoreLines.set(a.id,r),this._notesByValue.set(e,a)):this._appliedScoreLinesByValue.set(e,r),(-1e3===this.minLine||this.minLine<r)&&(this.minLine=r,this.minLineBeat=s),(-1e3===this.maxLine||this.maxLine>r)&&(this.maxLine=r,this.maxLineBeat=s),i||this.registerLine(s,r),n}registerLine(e,t){let s;this._beatLines.has(e.id)?s=this._beatLines.get(e.id):(s=new Pr,this._beatLines.set(e.id,s)),(-1e3===s.minLine||t<s.minLine)&&(s.minLine=t),(-1e3===s.minLine||t>s.maxLine)&&(s.maxLine=t)}getMaxLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).maxLine:0}getMinLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).minLine:0}static calculateNoteLine(e,t){let s=t,i=e.masterBar.keySignature,a=e.clef,r=s%12,n=(s/12|0)-1,o=Cr.OctaveSteps[a];return o-=n*Cr.StepsPerOctave,o-=(le.keySignatureIsSharp(i)||le.keySignatureIsNatural(i)?Cr.SharpNoteSteps:Cr.FlatNoteSteps)[r],o}getNoteLine(e){return this._appliedScoreLines.get(e.id)}getNoteLineForValue(e,t=!1){return this._appliedScoreLinesByValue.has(e)?this._appliedScoreLinesByValue.get(e):t&&this._notesByValue.has(e)?this.getNoteLine(this._notesByValue.get(e)):0}}Cr.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]],Cr.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],Cr.StepsPerOctave=7,Cr.OctaveSteps=[38,32,30,26,38],Cr.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],Cr.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class Er{constructor(){this.staffId="",this.up=0,this.down=0}}class Fr{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 Dr{get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}hasLine(e,t){return e&&this.beatHasLine(t)||!e&&1===this.beats.length&&this.beatHasLine(t)}beatHasLine(e){return e.duration>p.Whole}hasFlag(e,t){return e&&this.beatHasFlag(t)||!e&&1===this.beats.length&&this.beatHasFlag(this.beats[0])}beatHasFlag(e){return!e.isRest&&(e.duration>p.Quarter||e.graceType!==m.None)}constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=p.QuadrupleWhole,this.hasTuplet=!1,this.slashBeats=[],this._firstBeatLowestNoteCompareValue=-1,this._firstBeatHighestNoteCompareValue=-1,this._lastBeatLowestNoteCompareValue=-1,this._lastBeatHighestNoteCompareValue=-1,this.lowestNoteInHelper=null,this._lowestNoteCompareValueInHelper=-1,this.highestNoteInHelper=null,this._highestNoteCompareValueInHelper=-1,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isGrace=!1,this.minRestLine=null,this.beatOfMinRestLine=null,this.maxRestLine=null,this.beatOfMaxRestLine=null,this.direction=Ge.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}getBeatLineX(e,t){return t=t??this.direction,this.hasBeatLineX(e)?t===Ge.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 Er),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(Ge.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==m.None)&&(e=this.invert(Ge.Up)):e=Ge.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){let t=this._renderer.getNoteY(this.highestNoteInHelper,zs.Center),s=this._renderer.getNoteY(this.lowestNoteInHelper,zs.Center);if(null===e){const i=(t+s)/2;e=this.invert(this._renderer.middleYPosition<i?Ge.Up:Ge.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(Ge.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:return[2,2];case p.Whole:return[0,1];case p.Half:return[1,0];case p.Quarter:return[3,3];case p.Eighth:return[2,2];case p.Sixteenth:return[2,4];case p.ThirtySecond:return[4,4];case p.SixtyFourth:return[4,6];case p.OneHundredTwentyEighth:return[6,6];case p.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=Dr.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===Ge.Down?Ge.Up:Ge.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 G.Auto:case G.ForceSplitOnSecondaryToNext:t=Dr.canJoin(this.beats[this.beats.length-1],e);break;case G.ForceSplitToNext:t=!1;break;case G.ForceMergeWithNext:t=!0}return t&&(null==this.preferredBeamDirection&&null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.hasTuplet&&(this.hasTuplet=!0),e.graceType!==m.None&&(this.isGrace=!0),e.isRest?0===this.beats.length&&this.beats.push(e):(this.isRestBeamHelper&&(this.beats=[]),this.beats.push(e),this.checkNote(e.minNote),this.checkNote(e.maxNote),this.shortestDuration<e.duration&&(this.shortestDuration=e.duration),this._firstNonRestBeat||(this._firstNonRestBeat=e),this._lastNonRestBeat=e),e.slashed&&this.slashBeats.push(e)),t}checkNote(e){if(!e)return;let t,s;this.voice&&e.isPercussion?(t=-Cr.getPercussionLine(this.voice.bar,Cr.getNoteValue(e)),s=t):(t=Cr.getNoteValue(e),s=t,e.harmonicType!==y.None&&e.harmonicType!==y.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===m.BendGrace||t.graceType===m.BendGrace)return!1;if(e.graceType!==m.None&&t.graceType!==m.None)return!0;let s=e.voice.bar;if(s!==t.voice.bar)return!1;let i=e.playbackStart,a=t.playbackStart;if(!Dr.canJoinDuration(e.duration)||!Dr.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=ee.QuarterTime;if(8===s.masterBar.timeSignatureDenominator)s.masterBar.timeSignatureNumerator%3==0&&(r+=ee.QuarterTime/2|0);return((r+i)/r|0)===((r+a)/r|0)}static canJoinDuration(e){switch(e){case p.Whole:case p.Half:case p.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,s){return le.getIndex(e.duration)-2-s>0&&le.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 Lr{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class Mr{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new Lr(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 Ir{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 Mr(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=Dr.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 Ar{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this.preferredBeamDirection=null,this._renderer=e,this.collisionHelper=new Ir}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!==m.None?n=i:(n=s,i=null),n&&n.checkBeat(o)||(n&&n.finish(),n=new Dr(t.staff,e),n.preferredBeamDirection=this.preferredBeamDirection,n.checkBeat(o),o.graceType!==m.None?i=n:s=n,this.beamHelpers[r.index].push(n)),this.beamHelperLookup[r.index].set(o.index,n)}s&&s.finish(),i&&i.finish(),s=null,i=null}}getBeamingHelperForBeat(e){return this.beamHelperLookup[e.voice.index].get(e.index)}}class Or extends ja{constructor(e,t,s){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=s}doLayout(){super.doLayout();let e=this.renderer.resources;this._textRow=1.5*e.effectFont.size,this._fretRow=1.5*e.effectFont.size,this._chord.firstFret>1?this._firstFretSpacing=Or.FretSpacing:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+Or.Frets*Or.FretSpacing+2*Or.Padding[1],this.width=this._firstFretSpacing+(this._chord.staff.tuning.length-1)*Or.StringSpacing+2*Or.Padding[0]}paint(e,t,s){e+=this.x+Or.Padding[0]+this._firstFretSpacing,t+=this.y;let i=Or.StringSpacing,a=Or.FretSpacing,r=this.renderer.resources,n=Or.CircleRadius,o=this.width-2*Or.Padding[0]-this._firstFretSpacing,h=s.textAlign,l=s.textBaseline;s.font=r.effectFont,s.textAlign=D.Center,s.textBaseline=L.Top,this._chord.showName&&s.fillText(this._chord.name,e+o/2,t+r.effectFont.size/2),t+=this._textRow,s.font=r.fretboardNumberFont,s.textBaseline=L.Middle;for(let a=0;a<this._chord.staff.tuning.length;a++){let r=e+a*i,n=t+this._fretRow/2,o=this._chord.strings[this._chord.staff.tuning.length-a-1];o<0?s.fillMusicFontSymbol(r,n,1,F.FretboardX,!0):0===o?s.fillMusicFontSymbol(r,n,1,F.FretboardO,!0):(o-=this._chord.firstFret-1,s.fillText(o.toString(),r,n))}t+=this._fretRow;for(let r=0;r<this._chord.staff.tuning.length;r++){let n=e+r*i;s.fillRect(n,t,1,a*Or.Frets+1)}this._chord.firstFret>1&&(s.textAlign=D.Left,s.fillText(this._chord.firstFret.toString(),e-this._firstFretSpacing,t+a/2)),s.fillRect(e,t-1,o,2);for(let i=0;i<=Or.Frets;i++){let r=t+i*a;s.fillRect(e,r,o,1)}let d=new Map;for(let e of this._chord.barreFrets){let t=[-1,-1];d.set(e-this._chord.firstFret,t)}for(let r=0;r<this._chord.strings.length;r++){let o=this._chord.strings[r];if(o>0){if(o-=this._chord.firstFret,d.has(o)){let e=d.get(o);(-1===e[0]||r<e[0])&&(e[0]=r),(-1===e[1]||r>e[1])&&(e[1]=r)}let h=t+o*a+a/2+.5,l=e+(this._chord.strings.length-r-1)*i;s.fillCircle(l,h,n)}}for(const[r,o]of d){let h=t+r*a+a/2+.5,l=e+(this._chord.strings.length-o[1]-1)*i,d=e+(this._chord.strings.length-o[0]-1)*i;s.fillRect(l,h-n,d-l,2*n)}s.textAlign=h,s.textBaseline=l}}Or.Padding=[5,2],Or.Frets=5,Or.CircleRadius=2.5,Or.StringSpacing=10,Or.FretSpacing=12;class Rr extends xr{constructor(e,t,s=D.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=s}doLayout(){let e=0;switch(this._align){case D.Left:e=0;break;case D.Center:e=(this.width-this._glyphWidth)/2;break;case D.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 Vr extends xr{constructor(e,t,s=D.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=s}doLayout(){let e=0,t=0,s=Vr.Padding;this._rows=[];let i=new Rr(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 Rr(e,t,this._align),i.width=this.width,i.addGlyphToRow(a),e+=a.width);i.isEmpty||(i.doLayout(),this._rows.push(i),t+=i.height+s),this.height=t}paint(e,t,s){for(let i of this._rows)i.paint(e+this.x,t+this.y,s)}}Vr.Padding=3;class Hr extends Vr{constructor(e,t){super(e,t)}addChord(e){if(e.strings.length>0){let t=new Or(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}}class Gr extends ja{constructor(e,t,s,i,a=D.Left,r=null){super(e,t),this._lineHeights=null,this._lines=s.split("\n"),this.font=i,this.textAlign=a,this.textBaseline=r}doLayout(){super.doLayout(),this._lineHeights=[];const e=this.renderer.scoreRenderer.canvas;for(const t of this._lines){e.font=this.font;const s=e.measureText(t),i=s.height;this._lineHeights.push(i),this.height+=i,this.width=Math.max(this.width,s.width)}}paint(e,t,s){let i=s.color;s.color=i,s.font=this.font;let a=s.textAlign,r=s.textBaseline;s.textAlign=this.textAlign,null!==this.textBaseline&&(s.textBaseline=this.textBaseline);let n=t+this.y;for(let t=0;t<this._lines.length;t++)s.fillText(this._lines[t],e+this.x,n),n+=this._lineHeights[t];s.textAlign=a,s.textBaseline=r}}class Wr{get staveId(){return this._factory.staffId}get contentTop(){return this.y+this.staveTop+this.topSpacing+this.topOverflow}get contentBottom(){return this.y+this.topSpacing+this.topOverflow+this.staveBottom}constructor(e,t,s){this._sharedLayoutData=new Map,this.barRenderers=[],this.x=0,this.y=0,this.height=0,this.index=0,this.staffIndex=0,this.isFirstInSystem=!1,this.trackIndex=0,this.staveTop=0,this.topSpacing=0,this.bottomSpacing=0,this.staveBottom=0,this._factory=s,this.trackIndex=e,this.modelStaff=t}getSharedLayoutData(e,t){return this._sharedLayoutData.has(e)?this._sharedLayoutData.get(e):t}setSharedLayoutData(e,t){this._sharedLayoutData.set(e,t)}get isInsideBracket(){return this._factory.isInsideBracket}get isRelevantForBoundsLookup(){return this._factory.isRelevantForBoundsLookup}registerStaffTop(e){this.staveTop=e}registerStaffBottom(e){this.staveBottom=e}addBarRenderer(e){e.staff=this,e.index=this.barRenderers.length,e.reLayout(),this.barRenderers.push(e),this.system.layout.registerBarRenderer(this.staveId,e)}addBar(e,t){let s;s=e?this._factory.create(this.system.layout.renderer,e):new tn(this.system.layout.renderer,e),s.staff=this,s.index=this.barRenderers.length,s.layoutingInfo=t,s.doLayout(),s.registerLayoutingInfo();const i=s.barDisplayWidth;i>0&&this.system.layout.systemsLayoutMode==Ws.FromModelWithWidths&&(s.width=i),this.barRenderers.push(s),e&&this.system.layout.registerBarRenderer(this.staveId,s)}revertLastBar(){let e=this.barRenderers[this.barRenderers.length-1];this.barRenderers.splice(this.barRenderers.length-1,1),this.system.layout.unregisterBarRenderer(this.staveId,e);for(const e of this.barRenderers)e.applyLayoutingInfo();return e}scaleToWidth(e){this._sharedLayoutData=new Map;let t=this.topOverflow,s=0;switch(this.system.layout.systemsLayoutMode){case Ws.Automatic:let i=(e-this.system.computedWidth)/this.barRenderers.length;for(const e of this.barRenderers){e.x=s,e.y=this.topSpacing+t;let a=e.computedWidth+i;e.scaleToWidth(a),s+=e.width}break;case Ws.FromModelWithScale:e-=this.system.accoladeWidth;const a=this.system.totalBarDisplayScale;for(const i of this.barRenderers){i.x=s,i.y=this.topSpacing+t;const r=i.barDisplayScale*e/a;i.scaleToWidth(r),s+=i.width}break;case Ws.FromModelWithWidths:for(const e of this.barRenderers){e.x=s,e.y=this.topSpacing+t;const i=e.barDisplayWidth;i>0?e.scaleToWidth(i):e.scaleToWidth(e.computedWidth),s+=e.width}}}get topOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){let s=this.barRenderers[t];s.topOverflow>e&&(e=s.topOverflow)}return e}get bottomOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){let s=this.barRenderers[t];s.bottomOverflow>e&&(e=s.bottomOverflow)}return e}calculateHeightForAccolade(){this.topSpacing=this._factory.getStaffPaddingTop(this),this.bottomSpacing=this._factory.getStaffPaddingBottom(this),this.height=this.barRenderers.length>0?this.barRenderers[0].height:0,this.height>0&&(this.height+=this.topSpacing+this.topOverflow+this.bottomOverflow+this.bottomSpacing)}finalizeStaff(){this.topSpacing=this._factory.getStaffPaddingTop(this),this.bottomSpacing=this._factory.getStaffPaddingBottom(this),this.height=0;let e=!1,t=this.topOverflow;for(let s=0;s<this.barRenderers.length;s++)this.barRenderers[s].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[s].height),this.barRenderers[s].finalizeRenderer()&&(e=!0);if(e){t=this.topOverflow;for(let e=0;e<this.barRenderers.length;e++)this.barRenderers[e].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[e].height),this.barRenderers[e].finalizeRenderer()}this.height>0&&(this.height+=this.topSpacing+t+this.bottomOverflow+this.bottomSpacing)}paint(e,t,s,i,a){if(0!==this.height&&0!==a)for(let r=i,n=Math.min(i+a,this.barRenderers.length);r<n;r++)this.barRenderers[r].paint(e+this.x,t+this.y,s)}}class zr{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 Ur{constructor(){this._timeSortedSprings=[],this._xMin=0,this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,this.version=0,this.preBeatSize=0,this.postBeatSize=0,this.minStretchForce=0,this.totalSpringConstant=0,this.incompleteGraceRods=new Map,this.allGraceRods=new Map,this.springs=new Map,this.height=0}updateMinStretchForce(e){this.minStretchForce<e&&(this.minStretchForce=e)}getPreBeatSize(e){if(e.graceType!==m.None){const t=e.graceGroup.id;return this.allGraceRods.get(t)[e.graceIndex].preBeatWidth}{const t=e.absoluteDisplayStart;return this.springs.has(t)?this.springs.get(t).preBeatWidth:0}}getPostBeatSize(e){if(e.graceType!==m.None){const t=e.graceGroup.id;return this.allGraceRods.get(t)[e.graceIndex].postSpringWidth}{const t=e.absoluteDisplayStart;return this.springs.has(t)?this.springs.get(t).postSpringWidth:0}}addSpring(e,t,s,i,a){let r;if(this.version++,this.springs.has(e))r=this.springs.get(e),r.postSpringWidth<a&&(r.postSpringWidth=a),r.graceBeatWidth<s&&(r.graceBeatWidth=s),r.preBeatWidth<i&&(r.preBeatWidth=i),t<r.smallestDuration&&(r.smallestDuration=t),t>r.longestDuration&&(r.longestDuration=t),r.allDurations.add(t);else{if(r=new zr,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!==m.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 zr;r.timePosition=i,r.postSpringWidth=s,r.preBeatWidth=t,e.graceGroup.isComplete||(this.incompleteGraceRods.get(a)[e.graceIndex]=r),this.allGraceRods.get(a)[e.graceIndex]=r}}else{let a=0;if(e.graceGroup&&this.allGraceRods.has(e.graceGroup.id))for(const t of this.allGraceRods.get(e.graceGroup.id))a+=t.springWidth;this.addSpring(i,e.displayDuration,a,t,s)}}finish(){for(const[e,t]of this.allGraceRods){let e=0;for(const s of t)e+=s.preBeatWidth,s.graceBeatWidth=e,e+=s.postSpringWidth}this._incompleteGraceRodsWidth=0;for(const e of this.incompleteGraceRods.values())for(const t of e)this._incompleteGraceRodsWidth+=t.preBeatWidth+t.postSpringWidth;this.calculateSpringConstants(),this.version++}calculateSpringConstants(){this._xMin=0;let e=this.springs;for(const t of e.values())t.springWidth<this._xMin&&(this._xMin=t.springWidth);let t=0,s=this._timeSortedSprings;if(0===s.length)return this.totalSpringConstant=-1,void(this.minStretchForce=-1);for(let e=0;e<s.length;e++){let i=s[e],a=0;if(e===s.length-1)a=i.longestDuration;else{let t=s[e+1];a=Math.abs(t.timePosition-i.timePosition)}i.springConstant=this.calculateSpringConstant(i,a),t+=1/i.springConstant}this.totalSpringConstant=1/t,this.minStretchForce=0;for(let e=0;e<s.length;e++){let t=s[e],i=0;if(e===s.length-1)i=t.postSpringWidth;else{let a=s[e+1];i=t.postSpringWidth+a.preSpringWidth}0===e&&(i+=t.preSpringWidth);let a=i*t.springConstant;this.updateMinStretchForce(a)}}paint(e,t,s){}calculateSpringConstant(e,t){return t<=0&&(t=ee.toTicks(p.SixtyFourth)),0===e.smallestDuration&&(e.smallestDuration=t),e.smallestDuration/t*(1/((1+.85*Math.log2(t/Ur.MinDuration))*Ur.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(le.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}}Ur.MinDuration=30,Ur.MinDurationWidth=7;class Xr{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.renderers=[]}}class Jr{constructor(e,t){this.staves=[],this.stavesRelevantForBoundsLookup=[],this.firstStaffInBracket=null,this.lastStaffInBracket=null,this.bracket=null,this.staffSystem=e,this.track=t}addStaff(e){this.staves.push(e),e.isRelevantForBoundsLookup&&this.stavesRelevantForBoundsLookup.push(e)}}class Yr{constructor(){this.firstStaffInBracket=null,this.lastStaffInBracket=null,this.drawAsBrace=!1,this.braceScale=1,this.width=0,this.index=0}finalizeBracket(){if(this.firstStaffInBracket===this.lastStaffInBracket)return void(this.width=0);if(this.width=3,!this.drawAsBrace||!this.firstStaffInBracket||!this.lastStaffInBracket)return;const e=this.firstStaffInBracket.contentTop,t=(this.lastStaffInBracket.contentBottom-e)/Tl.MusicFontSize;this.braceScale=t,this.width=3*this.braceScale}}class qr extends Yr{constructor(e){super(),this.track=e,this.drawAsBrace=qr.isTrackDrawAsBrace(e)}includesStaff(e){return e.modelStaff.track===this.track}static isTrackDrawAsBrace(e){return e.staves.filter((e=>e.showStandardNotation)).length>1}}class jr extends qr{constructor(e){super(e)}includesStaff(e){return e.modelStaff.track===this.track||!this.drawAsBrace&&this.track.playbackInfo.program==e.modelStaff.track.playbackInfo.program}}class Kr{constructor(e){this._allStaves=[],this._firstStaffInBrackets=null,this._lastStaffInBrackets=null,this._accoladeSpacingCalculated=!1,this._brackets=[],this._hasSystemSeparator=!1,this.x=0,this.y=0,this.index=0,this.accoladeWidth=0,this.isFull=!1,this.width=0,this.computedWidth=0,this.totalBarDisplayScale=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[],this.layout=e,this.topPadding=e.renderer.settings.display.systemPaddingTop,this.bottomPadding=e.renderer.settings.display.systemPaddingBottom}get firstBarIndex(){return this.masterBarsRenderers[0].masterBar.index}get lastBarIndex(){return this.masterBarsRenderers[this.masterBarsRenderers.length-1].masterBar.index}addMasterBarRenderers(e,t){if(0===e.length)return null;this.masterBarsRenderers.push(t),t.layoutingInfo.preBeatSize=0;let s=0;for(let e=0,i=this.staves.length;e<i;e++){let i=this.staves[e];for(let e=0,a=i.staves.length;e<a;e++){let a=i.staves[e],r=t.renderers[s++];a.addBarRenderer(r)}}return this.calculateAccoladeSpacing(e),this.updateWidthFromLastBar(),t}addBars(e,t){if(0===e.length)return null;let s=new Xr;s.layoutingInfo=new Ur,s.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(s);let i=s.layoutingInfo;for(let e of this.staves)for(let a of e.staves){let r=e.track.staves[a.modelStaff.index].bars[t];a.addBar(r,i);let n=a.barRenderers[a.barRenderers.length-1];s.renderers.push(n),n.isLinkedToPrevious&&(s.isLinkedToPrevious=!0),n.canWrap||(s.canWrap=!1)}return this.calculateAccoladeSpacing(e),i.finish(),s.width=this.updateWidthFromLastBar(),s}revertLastBar(){if(this.masterBarsRenderers.length>1){let e=this.masterBarsRenderers[this.masterBarsRenderers.length-1];this.masterBarsRenderers.splice(this.masterBarsRenderers.length-1,1);let t=0,s=0;for(let e=0,i=this._allStaves.length;e<i;e++){let i=this._allStaves[e].revertLastBar();const a=i.computedWidth;a>t&&(t=a);const r=i.barDisplayScale;r>s&&(s=r)}return this.width-=t,this.computedWidth-=t,this.totalBarDisplayScale-=s,e}return null}updateWidthFromLastBar(){let e=0,t=0;for(let s=0,i=this._allStaves.length;s<i;s++){let i=this._allStaves[s];const a=i.barRenderers[i.barRenderers.length-1];a.applyLayoutingInfo(),a.computedWidth>e&&(e=a.computedWidth);const r=a.barDisplayScale;r>t&&(t=r)}return this.width+=e,this.computedWidth+=e,this.totalBarDisplayScale+=t,e}calculateAccoladeSpacing(e){const t=this.layout.renderer.settings;if(!this._accoladeSpacingCalculated){this._accoladeSpacingCalculated=!0,this.accoladeWidth=0;const s=this.layout.renderer.score.stylesheet;if(this.layout.renderer.settings.notation.isNotationElementVisible(x.TrackNames)){const i=1===this.layout.renderer.tracks.length?s.singleTrackTrackNamePolicy:s.multiTrackTrackNamePolicy,a=0===this.index?s.firstSystemTrackNameMode:s.otherSystemsTrackNameMode,r=0===this.index?s.firstSystemTrackNameOrientation:s.otherSystemsTrackNameOrientation;let n=!1;switch(i){case U.Hidden:break;case U.FirstSystem:n=0===this.index;break;case U.AllSystems:n=!0}let o=!1;if(n){let s=this.layout.renderer.canvas,i=t.display.resources.effectFont;s.font=i;for(let t of e){let e="";switch(a){case X.FullName:e=t.name;break;case X.ShortName:e=t.shortName}if(e.length>0){o=!0;const t=s.measureText(e);switch(r){case J.Horizontal:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,t.width));break;case J.Vertical:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,t.height))}}}o&&(this.accoladeWidth+=t.display.systemLabelPaddingLeft,this.accoladeWidth+=t.display.systemLabelPaddingRight)}}let i=0;for(let e of this._allStaves)e.y=i,e.calculateHeightForAccolade(),i+=e.height;let a=0;for(const e of this._brackets)e.finalizeBracket(),a=Math.max(a,e.width);this.accoladeWidth+=a,this.width+=this.accoladeWidth,this.computedWidth+=this.accoladeWidth}}getStaffTrackGroup(e){for(let t=0,s=this.staves.length;t<s;t++){let s=this.staves[t];if(s.track===e)return s}return null}addStaff(e,t){let s=this.getStaffTrackGroup(e);if(s||(s=new Jr(this,e),this.staves.push(s)),t.staffTrackGroup=s,t.system=this,t.index=this._allStaves.length,this._allStaves.push(t),s.addStaff(t),t.isInsideBracket){this._firstStaffInBrackets||(this._firstStaffInBrackets=t,t.isFirstInSystem=!0),s.firstStaffInBracket||(s.firstStaffInBracket=t),this._lastStaffInBrackets=t,s.lastStaffInBracket=t;let i=this._brackets.find((e=>e.includesStaff(t)));if(!i)switch(e.score.stylesheet.bracketExtendMode){case z.NoBrackets:break;case z.GroupStaves:i=new qr(e),i.index=this._brackets.length,this._brackets.push(i);break;case z.GroupSimilarInstruments:i=new jr(e),i.index=this._brackets.length,this._brackets.push(i)}i&&(i.firstStaffInBracket||(i.firstStaffInBracket=t),i.lastStaffInBracket=t,s.bracket=i)}}get height(){return 0===this._allStaves.length?0:this._allStaves[this._allStaves.length-1].y+this._allStaves[this._allStaves.length-1].height+this.topPadding+this.bottomPadding}scaleToWidth(e){for(let t=0,s=this._allStaves.length;t<s;t++)this._allStaves[t].scaleToWidth(e);this.width=e}paint(e,t,s){t+=this.topPadding,this.paintPartial(e+this.x,t+this.y,s,0,this.masterBarsRenderers.length),this._hasSystemSeparator&&(s.fillMusicFontSymbol(e+this.x,t+this.y+this.height-10,1,F.SystemDivider,!1),s.fillMusicFontSymbol(e+this.x+this.width-Kr.SystemSignSeparatorWidth,t+this.y+this.height-Kr.SystemSignSeparatorPadding,1,F.SystemDivider,!1))}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){s.color=r.barSeparatorColor;const i=this._firstStaffInBrackets,a=this._lastStaffInBrackets;if(i&&a){let r=t+i.contentTop,n=t+a.contentBottom,o=e+i.x;s.beginPath(),s.moveTo(o,r),s.lineTo(o,n),s.stroke()}const n=this.layout.renderer.settings,o=this.layout.renderer.settings.notation.isNotationElementVisible(x.TrackNames);if(s.font=r.effectFont,o){const i=this.layout.renderer.score.stylesheet,a=1===this.layout.renderer.tracks.length?i.singleTrackTrackNamePolicy:i.multiTrackTrackNamePolicy,r=0===this.index?i.firstSystemTrackNameMode:i.otherSystemsTrackNameMode,o=0===this.index?i.firstSystemTrackNameOrientation:i.otherSystemsTrackNameOrientation;let h=!1;switch(a){case U.Hidden:break;case U.FirstSystem:h=0===this.index;break;case U.AllSystems:h=!0}if(h){const i=s.textBaseline,a=s.textAlign;for(const i of this.staves)if(i.firstStaffInBracket&&i.lastStaffInBracket){let a=t+i.firstStaffInBracket.contentTop,h=t+i.lastStaffInBracket.contentBottom,l="";switch(r){case X.FullName:l=i.track.name;break;case X.ShortName:l=i.track.shortName}if(l.length>0){const t=e+i.firstStaffInBracket.x-n.display.accoladeBarPaddingRight-(i.bracket?.width??0)-n.display.systemLabelPaddingRight;switch(o){case J.Horizontal:s.textBaseline=L.Middle,s.textAlign=D.Right,s.fillText(l,t,(a+h)/2);break;case J.Vertical:s.textBaseline=L.Bottom,s.textAlign=D.Center;const e=.1;s.beginRotate(t,(a+h)/2,-90-e),s.fillText(l,0,0),s.endRotate()}}}s.textBaseline=i,s.textAlign=a}}for(const i of this._brackets)if(i.firstStaffInBracket&&i.lastStaffInBracket){const a=e+i.firstStaffInBracket.x,r=i.width,o=n.display.accoladeBarPaddingRight;let h=t+i.firstStaffInBracket.contentTop,l=t+i.lastStaffInBracket.contentBottom;if(i.drawAsBrace)s.fillMusicFontSymbol(a-o-r,l,i.braceScale,F.Brace);else if(i.firstStaffInBracket!==i.lastStaffInBracket){const e=r/2;h-=e,l+=2*e,s.fillRect(a-o-r,h,r,Math.ceil(l-h));let t=a-o-r-.5;s.fillMusicFontSymbol(t,h,1,F.BracketTop),s.fillMusicFontSymbol(t,Math.floor(l),1,F.BracketBottom)}}}}finalizeSystem(){const e=this.layout.renderer.settings;0===this.index&&(this.topPadding=e.display.firstSystemPaddingTop),this.isLast?this.bottomPadding=e.display.lastSystemPaddingBottom:this.layout.renderer.score.stylesheet.useSystemSignSeparator&&this.layout.renderer.tracks.length>1&&(this.bottomPadding+=Kr.SystemSignSeparatorHeight,this._hasSystemSeparator=!0);let t=0;for(let e of this._allStaves)e.x=this.accoladeWidth,e.y=t,e.finalizeStaff(),t+=e.height;for(const e of this._brackets)e.finalizeBracket()}buildBoundingsLookup(e,t){if(this.layout.renderer.boundsLookup.isFinished)return;const s=this._firstStaffInBrackets,i=this._lastStaffInBrackets;if(!s||!i)return;t+=this.topPadding;let a=this._allStaves[this._allStaves.length-1],r=t+this.y+s.y,n=t+this.y+i.y+i.height,o=t+this.y+this._allStaves[0].y,h=t+this.y+a.y+a.height,l=t+this.y+s.y+s.topSpacing+s.topOverflow+(s.barRenderers.length>0?s.barRenderers[0].topPadding:0),d=n-r,c=t+this.y+a.y+a.height-a.bottomSpacing-a.bottomOverflow-(a.barRenderers.length>0?a.barRenderers[0].bottomPadding:0)-l,u=h-o,p=this.x+s.x,g=new Ca;g.visualBounds=new ds,g.visualBounds.x=e+this.x,g.visualBounds.y=t+this.y,g.visualBounds.w=this.width,g.visualBounds.h=this.height-this.topPadding-this.bottomPadding,g.realBounds=new ds,g.realBounds.x=e+this.x,g.realBounds.y=t+this.y,g.realBounds.w=this.width,g.realBounds.h=this.height,this.layout.renderer.boundsLookup.addStaffSystem(g);let m=new Map;for(let e=0;e<this.staves.length;e++)for(let s of this.staves[e].stavesRelevantForBoundsLookup)for(let e of s.barRenderers){let i;m.has(e.bar.masterBar.index)?i=m.get(e.bar.masterBar.index):(i=new va,i.index=e.bar.masterBar.index,i.isFirstOfLine=e.isFirstOfLine,i.realBounds=new ds,i.realBounds.x=p+e.x,i.realBounds.y=o,i.realBounds.w=e.width,i.realBounds.h=u,i.visualBounds=new ds,i.visualBounds.x=p+e.x,i.visualBounds.y=r,i.visualBounds.w=e.width,i.visualBounds.h=d,i.lineAlignedBounds=new ds,i.lineAlignedBounds.x=p+e.x,i.lineAlignedBounds.y=l,i.lineAlignedBounds.w=e.width,i.lineAlignedBounds.h=c,this.layout.renderer.boundsLookup.addMasterBar(i),m.set(i.index,i)),e.buildBoundingsLookup(i,p,t+this.y+s.y)}}getBarX(e){if(!this._firstStaffInBrackets||0===this.layout.renderer.tracks.length)return 0;let t=this.layout.renderer.tracks[0].staves[0].bars[e];return this.layout.getRendererForBar(this._firstStaffInBrackets.staveId,t).x}}Kr.SystemSignSeparatorHeight=40,Kr.SystemSignSeparatorPadding=10,Kr.SystemSignSeparatorWidth=36;class Qr extends xr{constructor(e,t,s,i){super(e,t),this._tuning=s,this._trackLabel=i,this.glyphs=[]}doLayout(){if(!(this.glyphs.length>0)){this.createGlyphs(this._tuning);for(const e of this.glyphs)e.renderer=this.renderer,e.doLayout()}}paint(e,t,s){s.textBaseline=L.Middle,super.paint(e,t,s)}createGlyphs(e){const t=this.renderer.resources;this.height=0;if(this._trackLabel.length>0){const e=new Gr(0,this.height,this._trackLabel,t.effectFont,D.Left);e.renderer=this.renderer,e.doLayout(),this.height+=e.height,e.y+=e.height/2,this.addGlyph(e)}const s=new Gr(0,this.height,e.name,t.effectFont,D.Left);s.renderer=this.renderer,s.doLayout(),this.height+=s.height,s.y+=s.height/2,this.addGlyph(s);if(this.renderer.scoreRenderer.canvas.font=t.effectFont,this.width=Math.max(this.renderer.scoreRenderer.canvas.measureText(this._trackLabel).width,Math.max(this.renderer.scoreRenderer.canvas.measureText(e.name).width,128)),!e.isStandard){this.height+=15;const s=Qr.CircleNumberScale,i=Qr.CircleNumberHeight*s;let a=0|Math.ceil(e.tunings.length/2),r=0,n=this.height;for(let o=0,h=e.tunings.length;o<h;o++){const h=F.GuitarString0+(o+1);this.addGlyph(new Ka(r,n+i/2.5,s,h));const l="= "+Fe.getTextForTuning(e.tunings[o],!1);this.addGlyph(new Gr(r+i+1,n,l,t.effectFont,D.Left)),n+=15,o===a-1&&(n=this.height,r+=64)}this.height+=15*a}this.width+=15}}Qr.CircleNumberHeight=20,Qr.CircleNumberScale=.7;class $r extends Vr{constructor(e,t){super(e,t,D.Left)}addTuning(e,t){if(e.tunings.length>0){let s=new Qr(0,0,e,t);s.renderer=this.renderer,s.doLayout(),this.glyphs.push(s)}}}class Zr{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"}(Ws||(Ws={}));class en{get scaledWidth(){return this.width/this.renderer.settings.display.scale}constructor(e){this._barRendererLookup=new Map,this.width=0,this.height=0,this.scoreInfoGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this.systemsLayoutMode=Ws.Automatic,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t)),this.firstBarIndex=t;let s=this.renderer.settings.display.barCount;s<0&&(s=e.masterBars.length),s=t+s-1,s=Math.min(e.masterBars.length-1,Math.max(0,s)),this.lastBarIndex=s,this.createScoreInfoGlyphs(),this.doLayoutAndRender()}registerPartial(e,t){if(0==e.height)return;const s=this.renderer.settings.display.scale;e.x*=s,e.y*=s,e.width*=s,e.height*=s,e.totalWidth*=s,e.totalHeight*=s,this.renderer.settings.core.enableLazyLoading?(this._lazyPartials.set(e.id,new Zr(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(){re.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(x.ScoreTitle)&&this.scoreInfoGlyphs.set(x.ScoreTitle,new Gr(0,0,t.title,s.titleFont,D.Center)),t.subTitle&&e.isNotationElementVisible(x.ScoreSubTitle)&&this.scoreInfoGlyphs.set(x.ScoreSubTitle,new Gr(0,0,t.subTitle,s.subTitleFont,D.Center)),t.artist&&e.isNotationElementVisible(x.ScoreArtist)&&this.scoreInfoGlyphs.set(x.ScoreArtist,new Gr(0,0,t.artist,s.subTitleFont,D.Center)),t.album&&e.isNotationElementVisible(x.ScoreAlbum)&&this.scoreInfoGlyphs.set(x.ScoreAlbum,new Gr(0,0,t.album,s.subTitleFont,D.Center)),t.music&&t.music===t.words&&e.isNotationElementVisible(x.ScoreWordsAndMusic)?this.scoreInfoGlyphs.set(x.ScoreWordsAndMusic,new Gr(0,0,"Music and Words by "+t.words,s.wordsFont,D.Center)):(t.music&&e.isNotationElementVisible(x.ScoreMusic)&&this.scoreInfoGlyphs.set(x.ScoreMusic,new Gr(0,0,"Music by "+t.music,s.wordsFont,D.Right)),t.words&&e.isNotationElementVisible(x.ScoreWords)&&this.scoreInfoGlyphs.set(x.ScoreWords,new Gr(0,0,"Words by "+t.words,s.wordsFont,D.Left)));const i=new tn(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);for(const[e,t]of this.scoreInfoGlyphs)t.renderer=i,t.doLayout();if(e.isNotationElementVisible(x.GuitarTuning)){let e=[];for(let s of this.renderer.tracks)for(let i of s.staves){let a=!i.isPercussion&&i.isStringed&&i.tuning.length>0&&i.showTablature;if(t.stylesheet.perTrackDisplayTuning&&t.stylesheet.perTrackDisplayTuning.has(s.index)&&!1===t.stylesheet.perTrackDisplayTuning.get(s.index)&&(a=!1),a){e.push(i);break}}if(e.length>0&&t.stylesheet.globalDisplayTuning){this.tuningGlyph=new $r(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(x.ChordDiagrams)){this.chordDiagrams=new Hr(0,0),this.chordDiagrams.renderer=i;let e=new Set;for(let s of this.renderer.tracks){if(t.stylesheet.globalDisplayChordDiagramsOnTop&&(null==t.stylesheet.perTrackChordDiagramsOnTop||!t.stylesheet.perTrackChordDiagramsOnTop.has(s.index)||t.stylesheet.perTrackChordDiagramsOnTop.get(s.index)))for(let t of s.staves){const s=t.chords;if(s)for(const[,t]of s)e.has(t.uniqueId)||t.showDiagram&&(e.add(t.uniqueId),this.chordDiagrams.addChord(t))}}}}createEmptyStaffSystem(){let e=new Kr(this);for(let t=0;t<this.renderer.tracks.length;t++){let s=this.renderer.tracks[t];for(let i=0;i<s.staves.length;i++){let a=s.staves[i],r=Tl.staveProfiles.get(this.renderer.settings.display.staveProfile);for(let i of r)i.canCreate(s,a)&&e.addStaff(s,new Wr(t,a,i))}}return e}registerBarRenderer(e,t){this._barRendererLookup.has(e)||this._barRendererLookup.set(e,new Map),this._barRendererLookup.get(e).set(t.bar.id,t)}unregisterBarRenderer(e,t){if(this._barRendererLookup.has(e)){this._barRendererLookup.get(e).delete(t.bar.id)}}getRendererForBar(e,t){let s=t.id;return this._barRendererLookup.has(e)&&this._barRendererLookup.get(e).has(s)?this._barRendererLookup.get(e).get(s):null}layoutAndRenderAnnotation(e){let t="rendered by alphaTab",s=this.renderer.settings.display.resources,i=Math.floor(12);const a=new Ta,r=rt.withFamilyList(s.copyrightFont.families,12,Je.Plain,Ye.Bold);this.renderer.canvas.font=r;const n=Tl.getLayoutEngineFactory(this.renderer.settings.display.layoutMode).vertical;return a.width=this.renderer.canvas.measureText(t).width/this.renderer.settings.display.scale,a.height=i,a.x=n?(this.scaledWidth-a.width)/2:this.firstBarX,a.y=e,a.totalWidth=this.scaledWidth,a.totalHeight=e+i,a.firstMasterBarIndex=-1,a.lastMasterBarIndex=-1,this.registerPartial(a,(e=>{e.color=s.mainGlyphColor,e.font=r,e.textAlign=D.Left,e.textBaseline=L.Top,e.fillText(t,0,0)})),e+i}}!function(e){e[e.TopWithStem=0]="TopWithStem",e[e.Top=1]="Top",e[e.Center=2]="Center",e[e.Bottom=3]="Bottom",e[e.BottomWithStem=4]="BottomWithStem"}(zs||(zs={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Us||(Us={}));class tn{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 Nr,this._voiceContainers=new Map,this._postBeatGlyphs=new Nr,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 Ar(this))}registerTies(e){this._ties.push(...e)}get middleYPosition(){return 0}registerOverflowTop(e){return e>this.topOverflow&&(this.topOverflow=e,!0)}registerOverflowBottom(e){return e>this.bottomOverflow&&(this.bottomOverflow=e,!0)}scaleToWidth(e){let t=e-this._preBeatGlyphs.width-this._postBeatGlyphs.width;for(const e of this._voiceContainers.values())e.scaleToWidth(t);this._postBeatGlyphs.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width+t,this.width=e}get resources(){return this.settings.display.resources}get settings(){return this.scoreRenderer.settings}get barDisplayScale(){return this.staff.system.staves.length>1?this.bar.masterBar.displayScale:this.bar.displayScale}get barDisplayWidth(){return this.staff.system.staves.length>1?this.bar.masterBar.displayWidth:this.bar.displayWidth}get isFirstOfLine(){return 0===this.index}get isLast(){return!this.bar||this.bar.index===this.scoreRenderer.layout.lastBarIndex}registerLayoutingInfo(){let e=this.layoutingInfo,t=this._preBeatGlyphs.width;e.preBeatSize<t&&(e.preBeatSize=t);for(const t of this._voiceContainers.values())t.registerLayoutingInfo(e),t.x,t.width;let s=this._postBeatGlyphs.width;e.postBeatSize<s&&(e.postBeatSize=s)}applyLayoutingInfo(){if(this._appliedLayoutingInfo>=this.layoutingInfo.version)return!1;this._appliedLayoutingInfo=this.layoutingInfo.version,this._preBeatGlyphs.width=this.layoutingInfo.preBeatSize;let e=this._preBeatGlyphs.x+this._preBeatGlyphs.width;for(const t of this._voiceContainers.values()){t.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width,t.applyLayoutingInfo(this.layoutingInfo);let s=t.x+t.width;e<s&&(e=s)}this._postBeatGlyphs.x=Math.floor(e),this._postBeatGlyphs.width=this.layoutingInfo.postBeatSize,this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.computedWidth=this.width;const t=this.barDisplayWidth;return t>0&&this.scoreRenderer.layout.systemsLayoutMode==Ws.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 Nr,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new Nr,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 vr(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}addPreBeatGlyph(e){e.renderer=this,this._preBeatGlyphs.addGlyph(e)}addBeatGlyph(e){e.renderer=this,e.preNotes.renderer=this,e.onNotes.renderer=this,e.onNotes.beamingHelper=this.helpers.beamHelperLookup[e.beat.voice.index].get(e.beat.index),this.getVoiceContainer(e.beat.voice).addGlyph(e)}getVoiceContainer(e){return this._voiceContainers.has(e.index)?this._voiceContainers.get(e.index):void 0}getBeatContainer(e){return this.getVoiceContainer(e.voice)?.beatGlyphs?.[e.index]}getPreNotesGlyphForBeat(e){return this.getBeatContainer(e)?.preNotes}getOnNotesGlyphForBeat(e){return this.getBeatContainer(e)?.onNotes}paint(e,t,s){this.paintBackground(e,t,s),s.color=this.resources.mainGlyphColor,this._preBeatGlyphs.paint(e+this.x,t+this.y,s);for(const i of this._voiceContainers.values())s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.paint(e+this.x,t+this.y,s);s.color=this.resources.mainGlyphColor,this._postBeatGlyphs.paint(e+this.x,t+this.y,s)}paintBackground(e,t,s){this.layoutingInfo.paint(e+this.x+this._preBeatGlyphs.x+this._preBeatGlyphs.width,t+this.y+this.height,s)}buildBoundingsLookup(e,t,s){let i=new xa;i.bar=this.bar,i.visualBounds=new ds,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 ds,i.realBounds.x=t+this.x,i.realBounds.y=s+this.y,i.realBounds.w=this.width,i.realBounds.h=this.height,e.addBar(i);for(const[e,a]of this._voiceContainers){let r=this.bar.isEmpty&&0===e;if(!a.voice.isEmpty||r)for(let e=0,n=a.beatGlyphs.length;e<n;e++){a.beatGlyphs[e].buildBoundingsLookup(i,t+this.x+a.x,s+this.y+a.y,r)}}}addPostBeatGlyph(e){this._postBeatGlyphs.addGlyph(e)}createPreBeatGlyphs(){this._wasFirstOfLine=this.isFirstOfLine}createBeatGlyphs(){for(const e of this.bar.voices)this.hasVoiceContainer(e)&&this.createVoiceGlyphs(e)}createVoiceGlyphs(e){}createPostBeatGlyphs(){}get beatGlyphsStart(){return this._preBeatGlyphs.x+this._preBeatGlyphs.width}get postBeatGlyphsStart(){return this._postBeatGlyphs.x}getBeatX(e,t=Gs.PreNotes){let s=this.getBeatContainer(e);if(s)switch(t){case Gs.PreNotes:return s.voiceContainer.x+s.x;case Gs.OnNotes:return s.voiceContainer.x+s.x+s.onNotes.x;case Gs.MiddleNotes:return s.voiceContainer.x+s.x+s.onTimeX;case Gs.Stem:const t=s.onNotes.beamingHelper?s.onNotes.beamingHelper.getBeatLineX(e):s.onNotes.x+s.onNotes.width/2;return s.voiceContainer.x+t;case Gs.PostNotes:return s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.width;case Gs.EndBeat:return s.voiceContainer.x+s.x+s.width}return 0}getRatioPositionX(e){const t=this.bar.isEmpty?this.beatGlyphsStart:this.getBeatX(this.bar.voices[0].beats[0],Gs.OnNotes);return t+(this.postBeatGlyphsStart-t)*e}getNoteX(e,t){let s=this.getBeatContainer(e.beat);return s?s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.getNoteX(e,t):0}getNoteY(e,t){let s=this.getOnNotesGlyphForBeat(e.beat);return s?s.getNoteY(e,t):NaN}reLayout(){(this._wasFirstOfLine&&!this.isFirstOfLine||!this._wasFirstOfLine&&this.isFirstOfLine)&&this.recreatePreBeatGlyphs(),this.updateSizes(),this.registerLayoutingInfo()}recreatePreBeatGlyphs(){this._preBeatGlyphs=new Nr,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()}paintSimileMark(e,t,s){switch(this.bar.simileMark){case o.Simple:s.fillMusicFontSymbol(e+this.x+(this.width-20)/2,t+this.y+this.height/2,1,F.Repeat1Bar,!1);break;case o.SecondOfDouble:s.fillMusicFontSymbol(e+this.x-14,t+this.y+this.height/2,1,F.Repeat2Bars,!1)}}completeBeamingHelper(e){}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}}tn.RawLineSpacing=8,tn.StemWidth=.12*tn.RawLineSpacing,tn.StaffLineThickness=.13*tn.RawLineSpacing,tn.BeamThickness=.5*tn.RawLineSpacing,tn.BeamSpacing=.25*tn.RawLineSpacing,function(e){e[e.SinglePreBeat=0]="SinglePreBeat",e[e.SingleOnBeat=1]="SingleOnBeat",e[e.SingleOnBeatToEnd=2]="SingleOnBeatToEnd",e[e.GroupedOnBeat=3]="GroupedOnBeat",e[e.GroupedOnBeatToEnd=4]="GroupedOnBeatToEnd",e[e.FullBar=5]="FullBar"}(Xs||(Xs={}));class sn extends qa{constructor(e,t){super(0,0),this._uniqueEffectGlyphs=[],this._effectGlyphs=[],this.isEmpty=!0,this.previousBand=null,this.isLinkedToPrevious=!1,this.firstBeat=null,this.lastBeat=null,this.height=0,this.originalHeight=0,this.slot=null,this.voice=e,this.info=t}doLayout(){super.doLayout();for(let e=0;e<this.renderer.bar.voices.length;e++)this._effectGlyphs.push(new Map),this._uniqueEffectGlyphs.push([])}createGlyph(e){if(e.voice===this.voice&&this.info.shouldCreateGlyph(this.renderer.settings,e)&&(!this.info.hideOnMultiTrack||0===this.renderer.staff.trackIndex)){if(this.isEmpty=!1,this.firstBeat&&!e.isBefore(this.firstBeat)||(this.firstBeat=e),!this.lastBeat||e.isAfter(this.lastBeat))switch(this.lastBeat=e,this.info.sizingMode){case Xs.SingleOnBeatToEnd:case Xs.GroupedOnBeatToEnd:this.lastBeat.nextBeat&&(this.lastBeat=this.lastBeat.nextBeat)}let t=this.createOrResizeGlyph(this.info.sizingMode,e);t.height>this.height&&(this.height=t.height,this.originalHeight=t.height)}}resetHeight(){this.height=this.originalHeight}createOrResizeGlyph(e,t){let s;switch(e){case Xs.FullBar:case Xs.SinglePreBeat:case Xs.SingleOnBeat:case Xs.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 Xs.GroupedOnBeat:case Xs.GroupedOnBeatToEnd:let i=e===Xs.GroupedOnBeat?Xs.SingleOnBeat:Xs.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(Xs.SingleOnBeat,t)}}paint(e,t,s){super.paint(e,t,s);for(let i=0,a=this._uniqueEffectGlyphs.length;i<a;i++){let a=this._uniqueEffectGlyphs[i];for(let i=0,r=a.length;i<r;i++){a[i].paint(e+this.x,t+this.y,s)}}}alignGlyphs(){for(let e=0;e<this._effectGlyphs.length;e++)for(const t of this._effectGlyphs[e].keys())this.alignGlyph(this.info.sizingMode,this.renderer.bar.voices[e].beats[t])}alignGlyph(e,t){let s=this._effectGlyphs[t.voice.index].get(t.index),i=this.renderer.getBeatContainer(t);switch(e){case Xs.SinglePreBeat:const e=this.renderer.layoutingInfo.getPreBeatSize(t);s.x=this.renderer.beatGlyphsStart+i.x-e;break;case Xs.SingleOnBeat:case Xs.GroupedOnBeat:s.x=this.renderer.beatGlyphsStart+i.x;break;case Xs.SingleOnBeatToEnd:case Xs.GroupedOnBeatToEnd:if(s.x=this.renderer.beatGlyphsStart+i.x,i.beat.isLastOfVoice)s.width=this.renderer.width-s.x;else{const e=this.renderer.layoutingInfo.getPostBeatSize(t);s.width=e}break;case Xs.FullBar:s.width=this.renderer.width}}}class an{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class rn{constructor(){this.bands=[],this.shared=new an}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 nn{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 rn;return this.slots.push(t),t}register(e){let t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class on extends xr{constructor(){super(0,0),this.computedWidth=0}doLayout(){let e=0;if(this.glyphs)for(let t=0,s=this.glyphs.length;t<s;t++){let s=this.glyphs[t];s.x=e,s.renderer=this.renderer,s.doLayout(),e+=s.width}this.width=e,this.computedWidth=e}noteLoop(e){for(let t=this.container.beat.notes.length-1;t>=0;t--)e(this.container.beat.notes[t])}}class hn extends on{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,s){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class ln extends tn{constructor(e,t,s){super(e,t),this._bands=[],this._bandLookup=new Map,this.sizingInfo=null,this._infos=s}updateSizes(){this.topOverflow=0,this.bottomOverflow=0,this.topPadding=0,this.bottomPadding=0,this.updateHeight(),super.updateSizes()}finalizeRenderer(){let e=super.finalizeRenderer();return this.updateHeight()&&(e=!0),e}updateHeight(){if(!this.sizingInfo)return!1;let e=0;for(let t of this.sizingInfo.slots){t.shared.y=e;for(let s of t.bands)s.y=e,s.height=t.shared.height;e+=t.shared.height}return e!==this.height&&(this.height=e,!0)}applyLayoutingInfo(){const e=!super.applyLayoutingInfo();if(this.index>0){let e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new nn;for(let e of this._bands)e.resetHeight(),e.alignGlyphs(),e.isEmpty||this.sizingInfo.register(e);return this.updateHeight(),e}scaleToWidth(e){super.scaleToWidth(e);for(let e of this._bands)e.alignGlyphs()}createBeatGlyphs(){this._bands=[],this._bandLookup=new Map;for(let e of this.bar.voices)if(this.hasVoiceContainer(e))for(let t of this._infos){let s=new sn(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 Za(t,this.getVoiceContainer(e));s.preNotes=new on,s.onNotes=new hn,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 dn extends Tr{get staffId(){return this._staffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.effectStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.effectStaffPaddingBottom}constructor(e,t,s=null){super(),this.infos=t,this._staffId=e,this.isInsideBracket=!1,this.isRelevantForBoundsLookup=!1,this.shouldShow=s}canCreate(e,t){const s=this.shouldShow;return super.canCreate(e,t)&&(!s||s(e,t))}create(e,t){return new ln(e,t,this.infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class cn extends ja{constructor(e,t,s){super(e,t),this._endingsString="",this._endings=le.getAlternateEndingsList(s)}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(cn.Padding+2);let e="";for(let t=0,s=this._endings.length;t<s;t++)e+=this._endings[t]+1,e+=". ";this._endingsString=e}paint(e,t,s){super.paint(e,t,s);let i=s.textBaseline;if(s.textBaseline=L.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+cn.Padding,t+this.y)}s.textBaseline=i}}cn.Padding=3;class un{get effectId(){return this.notationElement.toString()}}class pn extends un{get notationElement(){return x.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Xs.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){return new cn(0,0,t.voice.bar.masterBar.alternateEndings)}canExpand(e,t){return!0}}class gn extends un{get notationElement(){return x.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Gr(0,0,"Capo. fret "+t.voice.bar.staff.capo,e.resources.effectFont,D.Left)}canExpand(e,t){return!1}}class mn extends un{get notationElement(){return x.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Gr(0,0,t.chord.name,e.resources.effectFont,D.Center)}canExpand(e,t){return!1}}class fn extends ja{constructor(e){super(),this.forceGroupedRendering=!1,this.endOnBarLine=!1,this.endPosition=e}get isLinkedWithPrevious(){return!!this.previousGlyph&&this.previousGlyph.renderer.staff.system===this.renderer.staff.system}get isLinkedWithNext(){return!!this.nextGlyph&&this.nextGlyph.renderer.isFinalized&&this.nextGlyph.renderer.staff.system===this.renderer.staff.system}paint(e,t,s){if(this.isLinkedWithPrevious)return;if(!this.isLinkedWithNext&&!this.forceGroupedRendering)return void this.paintNonGrouped(e,t,s);let i;if(!this.isLinkedWithNext&&this.forceGroupedRendering)i=this;else for(i=this.nextGlyph;i.isLinkedWithNext;)i=i.nextGlyph;let a=i.renderer,r=i.beat,n=this.endPosition,o=e-this.renderer.x,h=this.calculateEndX(a,r,o,n);this.paintGrouped(e,t,h,s)}calculateEndX(e,t,s,i){return t?s+e.x+e.getBeatX(t,i):s+e.x+this.x+this.width}paintNonGrouped(e,t,s){let i=e-this.renderer.x,a=this.calculateEndX(this.renderer,this.beat,i,this.endPosition);this.paintGrouped(e,t,a,s)}}class yn extends fn{constructor(e,t,s){super(Gs.EndBeat),this._crescendo=u.None,this._crescendo=s,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17}paintGrouped(e,t,s,i){let a=e+this.x,r=this.height;i.beginPath(),this._crescendo===u.Crescendo?(s-=yn.Padding,i.moveTo(s,t+this.y),i.lineTo(a,t+this.y+r/2),i.lineTo(s,t+this.y+r)):(s-=yn.Padding,i.moveTo(a,t+this.y),i.lineTo(s,t+this.y+r/2),i.lineTo(a,t+this.y+r)),i.stroke()}}yn.Padding=Qa.QuarterNoteHeadWidth/2|0;class bn extends un{get notationElement(){return x.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==u.None}createNewGlyph(e,t){return new yn(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class Sn extends Ka{constructor(e,t,s){super(e,t,.6,Sn.getSymbol(s))}doLayout(){super.doLayout(),this.height=17,this.y+=this.height/2}static getSymbol(e){switch(e){case g.PPP:return F.DynamicPPP;case g.PP:return F.DynamicPP;case g.P:return F.DynamicPiano;case g.MP:return F.DynamicMP;case g.MF:return F.DynamicMF;case g.F:return F.DynamicForte;case g.FF:return F.DynamicFF;case g.FFF:return F.DynamicFFF;default:return F.None}}}class _n extends un{get notationElement(){return x.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Xs.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!==m.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===m.None)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new Sn(0,0,t.dynamics)}canExpand(e,t){return!0}}class wn extends Ka{constructor(e){super(0,0,1,wn.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case O.FadeIn:return F.GuitarFadeIn;case O.FadeOut:return F.GuitarFadeOut;case O.VolumeSwell:return F.GuitarVolumeSwell}return F.None}doLayout(){this.width=13,this.symbol==F.GuitarVolumeSwell&&(this.width*=2),this.height=13}paint(e,t,s){super.paint(e,t+this.height,s)}}class Bn extends un{get notationElement(){return x.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return t.fade!=O.None}createNewGlyph(e,t){return new wn(t.fade)}canExpand(e,t){return!0}}class kn extends Ka{constructor(e,t,s){super(e,t,1,kn.getSymbol(s))}static getSymbol(e){switch(e){case He.Short:return F.FermataShortAbove;case He.Medium:return F.FermataAbove;case He.Long:return F.FermataLongAbove;default:return F.None}}doLayout(){this.width=23,this.height=12}paint(e,t,s){super.paint(e-this.width/2,t+this.height,s)}}class Tn extends un{get notationElement(){return x.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new kn(0,0,t.fermata.type)}canExpand(e,t){return!0}}class xn extends un{get notationElement(){return x.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return!(0!==t.voice.index||t.isRest||e.notation.fingeringMode!==k.SingleNoteEffectBand&&e.notation.fingeringMode!==k.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=le.fingerToString(e.settings,t,s,i)??"";return new Gr(0,0,r,e.resources.fingeringFont,D.Left)}canExpand(e,t){return!0}}class Nn extends un{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 vn extends fn{constructor(e,t=!0){super(Gs.OnNotes),this._label=e,this._dashed=t}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=Gs.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=D.Center,s.fillText(this._label,e+this.x,t+this.y),s.textAlign=a}paintGrouped(e,t,s,i){this.paintNonGrouped(e,t,i);let a=i.measureText(this._label).width,r=e+this.x+a/2+3,n=t+this.y+4;if(this._dashed){if(s>r){let e=r;for(;e<s;)i.beginPath(),i.moveTo(e,0|n),i.lineTo(Math.min(e+8,s),0|n),e+=11,i.stroke();i.beginPath(),i.moveTo(s,n-5|0),i.lineTo(s,n+5|0),i.stroke()}}else i.beginPath(),i.moveTo(r,0|n),i.lineTo(s,0|n),i.lineTo(s,n+5|0),i.stroke()}}vn.LineSpacing=3,vn.LineTopPadding=4,vn.LineTopOffset=5,vn.LineSize=8;class Pn extends Nn{get effectId(){return this._effectId}get notationElement(){return x.EffectHarmonics}constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case y.None:this._effectId="harmonics-none";break;case y.Natural:this._effectId="harmonics-natural";break;case y.Artificial:this._effectId="harmonics-artificial";break;case y.Pinch:this._effectId="harmonics-pinch";break;case y.Tap:this._effectId="harmonics-tap";break;case y.Semi:this._effectId="harmonics-semi";break;case y.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 Xs.GroupedOnBeat}createNewGlyph(e,t){return new vn(Pn.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case y.Natural:return"N.H.";case y.Artificial:return"A.H.";case y.Pinch:return"P.H.";case y.Tap:return"T.H.";case y.Semi:return"S.H.";case y.Feedback:return"Fdbk."}return""}}class Cn extends un{get notationElement(){return x.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return Xs.GroupedOnBeat}createNewGlyph(e,t){return new vn("LetRing")}canExpand(e,t){return!0}}class En extends ja{constructor(e,t,s,i,a=D.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 Fn extends un{get notationElement(){return x.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new En(0,0,t.lyrics,e.resources.effectFont,D.Center)}canExpand(e,t){return!0}}class Dn extends un{get notationElement(){return x.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return Xs.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 Gr(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,D.Left)}canExpand(e,t){return!0}}class Ln extends fn{constructor(e,t){super(Gs.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=13}paintNonGrouped(e,t,s){this.paintOttava(e,t,s)}paintOttava(e,t,s){let i=0;switch(this._ottava){case n._15ma:i=37,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,F.QuindicesimaAlta,!1);break;case n._8va:i=26,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,F.OttavaAlta,!1);break;case n._8vb:i=23,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,F.OttavaBassaVb,!1);break;case n._15mb:i=36,s.fillMusicFontSymbols(e+this.x-i/2,t+this.y+this.height,.8,[F.Quindicesima,F.OctaveBaselineM,F.OctaveBaselineB],!1)}return i/2}paintGrouped(e,t,s,i){let a=this.paintOttava(e,t,i),r=e+this.x+a+3,n=t+this.y;n+=this._aboveStaff?2:this.height-2;if(s>r){let e=r;for(;e<s;)i.beginPath(),i.moveTo(e,0|n),i.lineTo(Math.min(e+8,s),0|n),e+=11,i.stroke();i.beginPath(),this._aboveStaff?(i.moveTo(s,n),i.lineTo(s,t+this.y+this.height)):(i.moveTo(s,n),i.lineTo(s,t+this.y)),i.stroke()}}}class Mn extends un{get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return x.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.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 Ln(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class In extends Nn{get notationElement(){return x.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return Xs.GroupedOnBeat}createNewGlyph(e,t){return new vn("P.M.")}constructor(){super()}}class An extends Nn{get notationElement(){return x.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===_.PickSlideDown||e.slideOutType===_.PickSlideUp}get sizingMode(){return Xs.GroupedOnBeat}createNewGlyph(e,t){return new vn("P.S.")}constructor(){super()}}class On extends Ka{constructor(e,t,s){super(e,t,Qa.GraceScale,On.getSymbol(s))}doLayout(){this.width=9,this.height=13}paint(e,t,s){super.paint(e,t+this.height,s)}static getSymbol(e){switch(e){case E.Up:return F.StringsUpBow;case E.Down:return F.StringsDownBow;default:return F.None}}}class Rn extends un{get notationElement(){return x.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==E.None}createNewGlyph(e,t){return new On(0,0,t.pickStroke)}canExpand(e,t){return!0}}class Vn extends fn{constructor(e){super(Gs.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case w.Slight:this._stepSize=12;break;case w.Wide:this._stepSize=23}this.height=18}paintGrouped(e,t,s,i){let a=e+this.x,r=s-a,n=Math.max(1,r/this._stepSize);i.beginPath(),i.moveTo(a,t+this.y);for(let e=0;e<n;e++)i.lineTo(a+this._stepSize/2,t+this.y+this.height),i.lineTo(a+this._stepSize,t+this.y),a+=this._stepSize;i.stroke()}}class Hn extends un{get notationElement(){return x.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===w.Slight}createNewGlyph(e,t){return new Vn(w.Slight)}canExpand(e,t){return!0}}class Gn extends fn{constructor(e,t,s,i=1.2,a=!1){super(Gs.EndBeat),this._scale=0,this._symbol=F.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 w.Slight:this._symbol=F.WiggleTrill,this._symbolSize=9*this._scale,e=6*this._scale;break;case w.Wide:this._symbol=F.WiggleVibratoMediumFast,this._symbolSize=10*this._scale,e=10*this._scale}this.height=e}paintGrouped(e,t,s,i){let a=s-(e+this.x),r=this._symbolSize,n=a/r;this._partialWaves||(n=Math.floor(n)),n<1&&(n=1);let o=0;for(let s=0;s<n;s++)i.fillMusicFontSymbol(e+this.x+o,t+this.y+2*this.height,this._scale,this._symbol,!1),o+=r}}class Wn extends Nn{get notationElement(){return x.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){let t=e.vibrato===w.Slight||e.isTieDestination&&e.tieOrigin.vibrato===w.Slight;return this._hideOnTiedBend&&t&&e.isTieDestination&&e.tieOrigin.hasBend&&(t=!1),t}get sizingMode(){return Xs.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Gn(0,0,w.Slight,1.2)}constructor(e){super(),this._hideOnTiedBend=e}}class zn extends un{get notationElement(){return x.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){let s=e.resources;return t.slap?new Gr(0,0,"S",s.effectFont,D.Left):t.pop?new Gr(0,0,"P",s.effectFont,D.Left):new Gr(0,0,"T",s.effectFont,D.Left)}canExpand(e,t){return!0}}var Un,Xn,Jn=Object.freeze({__proto__:null,CssFontSvgCanvas:kr,Cursors:mr,FontSizes:ka,SvgCanvas:Br,get TextAlign(){return D},get TextBaseline(){return L}});class Yn extends ja{constructor(e){super(0,0),this.tempoAutomations=e}doLayout(){super.doLayout(),this.height=25}paint(e,t,s){for(const i of this.tempoAutomations){let a=e+this.renderer.getRatioPositionX(i.ratioPosition);const r=this.renderer.resources;if(s.font=r.markerFont,s.textBaseline=L.Top,i.text){const e=s.measureText(i.text);s.fillText(i.text,a,t+this.y+s.font.size/2),a+=e.width+.7*s.font.size}s.fillMusicFontSymbol(a,t+this.y+.8*this.height,.5,F.NoteQuarterUp,!0),s.fillText("= "+i.value.toString(),a+8,t+this.y+s.font.size/2)}}}class qn extends un{get notationElement(){return x.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Xs.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&t.voice.bar.masterBar.tempoAutomations.length>0}createNewGlyph(e,t){return new Yn(t.voice.bar.masterBar.tempoAutomations)}canExpand(e,t){return!0}}class jn extends un{get notationElement(){return x.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Gr(0,0,t.text,e.resources.effectFont,D.Left)}canExpand(e,t){return!0}}class Kn extends ja{constructor(e,t){super(e,t)}doLayout(){super.doLayout(),this.height=this.renderer.resources.markerFont.size}paint(e,t,s){let i=this.renderer.resources;s.font=i.markerFont;let a=s.measureText("tr").width;s.fillText("tr",e+this.x,t+this.y);let r=a+3,n=this.width-r,o=Math.max(1,(n-r)/13.2),h=r,l=t+this.y+1.2*this.height;for(let t=0;t<o;t++)s.fillMusicFontSymbol(e+this.x+h,l,1.2,F.WiggleTrill,!1),h+=13.2}}class Qn extends Nn{get notationElement(){return x.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return Xs.SingleOnBeat}createNewGlyph(e,t){return new Kn(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(Un||(Un={}));class $n extends ja{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25}paint(e,t,s){e+=this.x;let i=(t+=this.y)+this.height*Qa.GraceScale,a=i+8;s.font=this.renderer.resources.effectFont,s.fillText("(",e,t+.3*this.height);let r=e+10,n=e+40,o=[],h=[],l=[],d=[];switch(this._tripletFeel){case C.NoTripletFeel:o=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac8thLongStem],l=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac8thLongStem];break;case C.Triplet8th:o=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac8thLongStem],l=[F.TextBlackNoteLongStem,F.Space,F.NoteEighthUp],d=[F.TextTupletBracketStartLongStem,F.TextTuplet3LongStem,F.TextTupletBracketEndLongStem];break;case C.Triplet16th:o=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac8thLongStem],l=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac16thLongStem],d=[F.TextTupletBracketStartLongStem,F.TextTuplet3LongStem,F.TextTupletBracketEndLongStem];break;case C.Dotted8th:o=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac8thLongStem],h=[F.TextAugmentationDot],l=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac16thLongStem];break;case C.Dotted16th:o=[F.TextBlackNoteLongStem,F.TextCont16thBeamLongStem,F.TextBlackNoteFrac16thLongStem],h=[F.TextAugmentationDot],l=[F.TextBlackNoteLongStem,F.TextCont16thBeamLongStem,F.TextBlackNoteFrac32ndLongStem],s.fillCircle(n+9,i,1);break;case C.Scottish8th:o=[F.TextBlackNoteLongStem,F.TextCont8thBeamLongStem,F.TextBlackNoteFrac8thLongStem],l=[F.TextBlackNoteLongStem,F.TextCont16thBeamLongStem,F.TextBlackNoteFrac8thLongStem,F.TextAugmentationDot];break;case C.Scottish16th:o=[F.TextBlackNoteLongStem,F.TextCont16thBeamLongStem,F.TextBlackNoteFrac16thLongStem],l=[F.TextBlackNoteLongStem,F.TextCont32ndBeamLongStem,F.TextBlackNoteFrac16thLongStem,F.TextAugmentationDot]}s.fillMusicFontSymbols(r,i,$n.NoteScale,o,!1),s.fillText("=",e+32,t+5),s.fillMusicFontSymbols(n,i,$n.NoteScale,l,!1),h.length>0&&s.fillMusicFontSymbols(n+7,i,$n.NoteScale,h,!1),d.length>0&&s.fillMusicFontSymbols(n,a,$n.TupletScale,d,!1),s.fillText(")",e+65,t+.3*this.height)}}$n.NoteScale=.5,$n.TupletScale=.7;class Zn extends un{get notationElement(){return x.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Xs.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==C.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new $n(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class eo extends un{get notationElement(){return x.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Xs.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new vn("w/bar")}canExpand(e,t){return!0}}class to extends un{get notationElement(){return x.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===w.Wide}createNewGlyph(e,t){return new Vn(w.Wide)}canExpand(e,t){return!0}}class so extends Nn{get notationElement(){return x.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===w.Wide||e.isTieDestination&&e.tieOrigin.vibrato===w.Wide}get sizingMode(){return Xs.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Gn(0,0,w.Wide,1.2)}}class io{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class ao extends en{get name(){return"HorizontalScreen"}constructor(e){super(e),this._system=null,this._pagePadding=null}get supportsResize(){return!1}get firstBarX(){let e=this._pagePadding[0];return this._system&&(e+=this._system.accoladeWidth),e}doResize(){}doLayoutAndRender(){switch(this._pagePadding=this.renderer.settings.display.padding,this.renderer.settings.display.systemsLayoutMode){case Ke.Automatic:this.systemsLayoutMode=Ws.Automatic;break;case Ke.UseModelLayout:this.systemsLayoutMode=Ws.FromModelWithWidths}this._pagePadding||(this._pagePadding=[0,0,0,0]),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let 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._system=this.createEmptyStaffSystem(),this._system.isLast=!0,this._system.x=this._pagePadding[0],this._system.y=this._pagePadding[1];let a=this.renderer.settings.display.barCountPerPartial,r=[],n=new io,o=0;for(;s<=i;){let t=this._system.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._system.accoladeWidth+this._pagePadding[0]),o+=n.width,r.push(n),re.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null),n=new io,n.x=o);s++}n.masterBars.length>0&&(0===r.length&&(n.width+=this._system.accoladeWidth+this._pagePadding[0]),r.push(n),re.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null)),this.finalizeStaffSystem();const h=this.renderer.settings.display.scale;this.height=Math.floor(this._system.y+this._system.height)*h,this.width=(this._system.x+this._system.width+this._pagePadding[2])*h,s=0;let l=0;for(let e=0;e<r.length;e++){const t=r[e],i=new Ta;i.x=l,i.y=0,i.totalWidth=this.width/h,i.totalHeight=this.height/h,i.width=t.width,i.height=this.height/h,i.firstMasterBarIndex=t.masterBars[0].index,i.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,l+=t.width;const a=s,n=e;this._system.buildBoundingsLookup(0,0),this.registerPartial(i,(e=>{let s=this._system.getBarX(t.masterBars[0].index)+this._system.accoladeWidth;0===n&&(s-=this._system.x+this._system.accoladeWidth),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=D.Left,re.debug(this.name,"Rendering partial from bar "+t.masterBars[0].index+" to "+t.masterBars[t.masterBars.length-1].index,null),this._system.paintPartial(-s,this._system.y,e,a,t.masterBars.length)})),s+=t.masterBars.length}this.height=this.layoutAndRenderAnnotation(this.height)+this._pagePadding[3]}finalizeStaffSystem(){this._system.scaleToWidth(this._system.width),this._system.finalizeSystem()}}class ro extends en{get name(){return"PageView"}constructor(e){super(e),this._systems=[],this._allMasterBarRenderers=[],this._barsFromPreviousSystem=[],this._pagePadding=null}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case Ke.Automatic:this.systemsLayoutMode=Ws.Automatic;break;case Ke.UseModelLayout:this.systemsLayoutMode=Ws.FromModelWithScale}this._pagePadding=this.renderer.settings.display.padding.map((e=>e/this.renderer.settings.display.scale)),this._pagePadding||(this._pagePadding=[0,0,0,0]),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let e=this._pagePadding[1];this.width=this.renderer.width,this._allMasterBarRenderers=[],e=this.layoutAndRenderScoreInfo(e,-1),e=this.layoutAndRenderTunings(e,-1),e=this.layoutAndRenderChordDiagrams(e,-1),e=this.layoutAndRenderScore(e),e=this.layoutAndRenderAnnotation(e),this.height=(e+this._pagePadding[3])*this.renderer.settings.display.scale}get supportsResize(){return!0}get firstBarX(){let e=this._pagePadding[0];return this._systems.length>0&&(e+=this._systems[0].accoladeWidth),e}doResize(){let e=this._pagePadding[1];this.width=this.renderer.width;let t=this.height;e=this.layoutAndRenderScoreInfo(e,t),e=this.layoutAndRenderTunings(e,t),e=this.layoutAndRenderChordDiagrams(e,t),e=this.resizeAndRenderScore(e,t),e=this.layoutAndRenderAnnotation(e),this.height=(e+this._pagePadding[3])*this.renderer.settings.display.scale}layoutAndRenderTunings(e,t=-1){if(!this.tuningGlyph)return e;let s=this.renderer.settings.display.resources;this.tuningGlyph.x=this._pagePadding[0],this.tuningGlyph.width=this.scaledWidth,this.tuningGlyph.doLayout();let i=this.tuningGlyph.height;const a=new Ta;return a.x=0,a.y=e,a.width=this.scaledWidth,a.height=i,a.totalWidth=this.scaledWidth,a.totalHeight=t<0?e+a.height:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=D.Center,this.tuningGlyph.paint(0,0,e)})),e+i}layoutAndRenderChordDiagrams(e,t=-1){if(!this.chordDiagrams)return e;const s=this.renderer.settings.display.resources;this.chordDiagrams.width=this.scaledWidth,this.chordDiagrams.doLayout();const i=Math.floor(this.chordDiagrams.height),a=new Ta;return a.x=0,a.y=e,a.width=this.scaledWidth,a.height=i,a.totalWidth=this.scaledWidth,a.totalHeight=t<0?e+i:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=D.Center,this.chordDiagrams.paint(0,0,e)})),e+i}layoutAndRenderScoreInfo(e,t=-1){re.debug(this.name,"Layouting score info");const s=new Ta;s.x=0,s.y=e;let i=0,a=this.renderer.settings.display.resources,r=[x.ScoreTitle,x.ScoreSubTitle,x.ScoreArtist,x.ScoreAlbum,x.ScoreWordsAndMusic];for(let e=0;e<r.length;e++)if(this.scoreInfoGlyphs.has(r[e])){let t=this.scoreInfoGlyphs.get(r[e]);t.x=this.scaledWidth/2,t.y=i,t.textAlign=D.Center,i+=t.font.size}let n=!1,o=0;if(this.scoreInfoGlyphs.has(x.ScoreMusic)){let e=this.scoreInfoGlyphs.get(x.ScoreMusic);e.x=this.scaledWidth-this._pagePadding[2],e.y=i,e.textAlign=D.Right,n=!0,o=e.font.size}if(this.scoreInfoGlyphs.has(x.ScoreWords)){let e=this.scoreInfoGlyphs.get(x.ScoreWords);e.x=this._pagePadding[0],e.y=i,e.textAlign=D.Left,n=!0,o=e.font.size}return n&&(i+=o),this.scoreInfoGlyphs.size>0&&(i=Math.floor(i+17),s.width=this.scaledWidth,s.height=i,s.totalWidth=this.scaledWidth,s.totalHeight=t<0?e+s.height:t,this.registerPartial(s,(e=>{e.color=a.scoreInfoColor,e.textAlign=D.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==Ws.FromModelWithScale)for(let s=0;s<this._systems.length;s++){let i=this._systems[s];this.fitSystem(i),e+=this.paintSystem(i,t)}else{this._systems=[];let s=0,i=this.maxWidth,a=this.createEmptyStaffSystem();for(a.index=this._systems.length,a.x=this._pagePadding[0],a.y=e;s<this._allMasterBarRenderers.length;){let r=this._allMasterBarRenderers[s];if(a.width+r.width<=i||0===a.masterBarsRenderers.length)a.addMasterBarRenderers(this.renderer.tracks,r),s++;else{for(;r&&!r.canWrap&&a.masterBarsRenderers.length>1;)r=a.revertLastBar(),s--;a.isFull=!0,a.isLast=this.lastBarIndex===a.lastBarIndex,this._systems.push(a),this.fitSystem(a),e+=this.paintSystem(a,t),a=this.createEmptyStaffSystem(),a.index=this._systems.length,a.x=this._pagePadding[0],a.y=e}}a.isLast=this.lastBarIndex===a.lastBarIndex,this.fitSystem(a),e+=this.paintSystem(a,t)}return e}layoutAndRenderScore(e){let t=this.firstBarIndex,s=this.lastBarIndex;for(this._systems=[];t<=s;){let i=this.createStaffSystem(t,s);this._systems.push(i),i.x=this._pagePadding[0],i.y=e,t=i.lastBarIndex+1,this.fitSystem(i),re.debug(this.name,"Rendering partial from bar "+i.firstBarIndex+" to "+i.lastBarIndex,null),e+=this.paintSystem(i,e)}return e}paintSystem(e,t){let s=Math.floor(e.height);const i=new Ta;return i.x=0,i.y=e.y,i.totalWidth=this.scaledWidth,i.totalHeight=t,i.width=this.scaledWidth,i.height=s,i.firstMasterBarIndex=e.firstBarIndex,i.lastMasterBarIndex=e.lastBarIndex,e.buildBoundingsLookup(0,0),this.registerPartial(i,(t=>{this.renderer.canvas.color=this.renderer.settings.display.resources.mainGlyphColor,this.renderer.canvas.textAlign=D.Left,e.paint(0,-i.y/this.renderer.settings.display.scale,t)})),s}fitSystem(e){e.isFull||e.width>this.maxWidth||this.renderer.settings.display.justifyLastSystem?e.scaleToWidth(this.maxWidth):e.scaleToWidth(e.width),e.finalizeSystem()}getBarsPerSystem(e){let t=this.renderer.settings.display.barsPerRow;if(this.systemsLayoutMode==Ws.FromModelWithScale){let s,i;this.renderer.tracks.length>1?(s=this.renderer.score.defaultSystemsLayout,i=this.renderer.score.systemsLayout):(s=this.renderer.tracks[0].defaultSystemsLayout,i=this.renderer.tracks[0].systemsLayout),t=e<i.length?i[e]:s}return t}createStaffSystem(e,t){let s=this.createEmptyStaffSystem();s.index=this._systems.length;let i=this.getBarsPerSystem(s.index),a=this.maxWidth,r=t+1,n=e;for(;n<r;){if(this._barsFromPreviousSystem.length>0)for(let e of this._barsFromPreviousSystem)s.addMasterBarRenderers(this.renderer.tracks,e),n=e.masterBar.index;else{let e=s.addBars(this.renderer.tracks,n);e&&this._allMasterBarRenderers.push(e)}this._barsFromPreviousSystem=[];let e=!1;if((-1===i&&s.width>=a&&0!==s.masterBarsRenderers.length||s.masterBarsRenderers.length===i+1)&&(e=!0),e){let e=s.revertLastBar();if(e)for(this._barsFromPreviousSystem.push(e);e&&!e.canWrap&&s.masterBarsRenderers.length>1;)e=s.revertLastBar(),e&&this._barsFromPreviousSystem.push(e);return s.isFull=!0,s.isLast=!1,this._barsFromPreviousSystem.reverse(),s}s.x=0,n++}return s.isLast=t===s.lastBarIndex,s}get maxWidth(){return this.scaledWidth-this._pagePadding[0]-this._pagePadding[2]}}class no extends Ka{constructor(e,t,s,i){super(e,t,i,no.getMusicSymbol(s)),this._accidentalType=s}static getMusicSymbol(e){switch(e){case Xe.Natural:return F.AccidentalNatural;case Xe.Sharp:return F.AccidentalSharp;case Xe.Flat:return F.AccidentalFlat;case Xe.NaturalQuarterNoteUp:return F.AccidentalQuarterToneNaturalArrowUp;case Xe.SharpQuarterNoteUp:return F.AccidentalQuarterToneSharpArrowUp;case Xe.FlatQuarterNoteUp:return F.AccidentalQuarterToneFlatArrowUp;case Xe.DoubleSharp:return F.AccidentalDoubleSharp;case Xe.DoubleFlat:return F.AccidentalDoubleFlat}return F.None}doLayout(){if(this._accidentalType===Xe.DoubleFlat)this.width=18;else this.width=8;this.width=this.width*this.glyphScale}}class oo extends Ka{constructor(e,t,s,i){super(e,t,1,oo.getSymbol(s)),this._clef=s,this._clefOttava=i}doLayout(){switch(this._clef){case r.Neutral:this.width=15;break;case r.C3:case r.C4:case r.F4:case r.G2:this.width=28}}static getSymbol(e){switch(e){case r.Neutral:return F.UnpitchedPercussionClef1;case r.C3:case r.C4:return F.CClef;case r.F4:return F.FClef;case r.G2:return F.GClef;default:return F.None}}paint(e,t,s){let i;super.paint(e,t,s);let a=!1;switch(this._clefOttava){case n._15ma:i=new Ka(-4,0,.5,F.Quindicesima),a=!0;break;case n._8va:i=new Ka(-2,0,.5,F.Ottava),a=!0;break;case n._8vb:i=new Ka(-6,0,.5,F.Ottava);break;case n._15mb:i=new Ka(-8,0,.5,F.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,t+this.y+o,s)}}class ho extends ja{constructor(e,t,s){super(e,t),this._note=s}static getSymbol(e,t){switch(e){case i.None:return F.None;case i.Normal:return t?F.ArticAccentAbove:F.ArticAccentBelow;case i.Heavy:return t?F.ArticMarcatoAbove:F.ArticMarcatoBelow;case i.Tenuto:return t?F.ArticTenutoAbove:F.ArticTenutoBelow;default:return F.None}}doLayout(){this.width=9,this.height=9}paint(e,t,s){const i=this.renderer.getBeatDirection(this._note.beat),a=ho.getSymbol(this._note.accentuated,i==Ge.Down),r=i==Ge.Up?t+this.y:t+this.y+this.height-2;s.fillMusicFontSymbol(e+this.x-2,r,1,a,!1)}}class lo extends qa{constructor(e,t,s){super(e,t),this._size=0,this._size=s}doLayout(){this.width=this._size+3}paint(e,t,s){s.fillCircle(e+this.x,t+this.y,this._size)}}class co extends Ka{constructor(e,t,s){super(e,t,s?Qa.GraceScale:1,F.NoteheadXOrnate),this._isGrace=s}doLayout(){this.width=9*(this._isGrace?Qa.GraceScale:1),this.height=Qa.NoteHeadHeight}}class uo extends Ka{constructor(e,t,s,i){super(e,t,i?Qa.GraceScale:1,uo.getSymbol(s)),this._isGrace=i}static getSymbol(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:case p.Half:return F.NoteheadDiamondWhiteWide;default:return F.NoteheadDiamondBlackWide}}doLayout(){this.width=9*(this._isGrace?Qa.GraceScale:1),this.height=Qa.NoteHeadHeight}}class po extends qa{constructor(e,t,s){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=Ge.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=po.calculateActualTieHeight(1,this._startX,this._startY,this._endX,this._endY,this.tieDirection===Ge.Down,this._tieHeight,4).h),this.tieDirection===Ge.Up&&(this.y-=this.height))}paint(e,t,s){this._shouldDraw&&(this.shouldDrawBendSlur()?po.drawBendSlur(s,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Ge.Down,1):po.paintTie(s,1,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Ge.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,s,i){return 22}getBeamDirection(e,t){return Ge.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=po.computeBezierControlPoints(e,t,s,i,a,r,n,o);t=h[0],s=h[1];const l=h[2],d=h[3];i=h[6],a=h[7];const c=(t-l)/(t-2*l+i),u=po.calculateExtrema(t,s,l,d,i,a,c),p=u.length>0?Math.min(t,i,u[0]):Math.min(t,i),g=u.length>0?Math.max(t,i,u[0]):Math.max(t,i),m=(s-d)/(s-2*d+a),f=po.calculateExtrema(t,s,l,d,i,a,m),y=f.length>0?Math.min(s,a,f[1]):Math.min(s,a),b=f.length>0?Math.max(s,a,f[1]):Math.max(s,a),S=new ds;return S.x=p,S.y=y,S.w=g-p,S.h=b-y,S}static calculateExtrema(e,t,s,i,a,r,n){if(n<=0||1<=n)return[];const o=e+(s-e)*n,h=t+(i-t)*n;return[o+(s+(a-s)*n-o)*n,h+(i+(r-i)*n-h)*n]}static computeBezierControlPoints(e,t,s,i,a,r,n,o){if(t===i&&s===a)return[];if(i<t){let e=t;t=i,i=e,e=s,s=a,a=e}n*=e,o*=e;let h=a-s,l=i-t,d=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=d,l/=d;let c=(i+t)/2,u=(a+s)/2;return[t,s,c+n*h,u+n*l,c+(n-o)*h,u+(n-o)*l,i,a]}static paintTie(e,t,s,i,a,r,n=!1,o=22,h=4){const l=po.computeBezierControlPoints(t,s,i,a,r,n,o,h);e.beginPath(),e.moveTo(l[0],l[1]),e.quadraticCurveTo(l[2],l[3],l[6],l[7]),e.quadraticCurveTo(l[4],l[5],l[0],l[1]),e.closePath(),e.fill()}static drawBendSlur(e,t,s,i,a,r,n,o){let h=a-s,l=i-t,d=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=d,l/=d;let c=(i+t)/2,u=(a+s)/2,p=po.BendSlurHeight*n;i-t<20&&(p/=2);let g=c+p*h,m=u+p*l;if(e.beginPath(),e.moveTo(t,s),e.lineTo(g,m),e.lineTo(i,a),e.stroke(),o){let t=e.measureText(o).width,s=r?0:-e.font.size;e.fillText(o,g-t/2,m+s)}}}po.BendSlurHeight=11;class go extends qa{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=go.Size}paint(e,t,s){this._isOpen?po.paintTie(s,1,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):po.paintTie(s,1,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3)}}go.Size=6;class mo{constructor(e,t){this.line=0,this.line=e,this.isGhost=t}}class fo extends qa{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(x.ParenthesisOnTiedBends);this.addParenthesisOnLine(s,i)}addParenthesisOnLine(e,t){let s=new mo(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 go(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 yo{constructor(e,t){this.line=0,this.glyph=e,this.line=t}}class bo extends qa{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new ma,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){let s=new yo(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===Ge.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===Ge.Down?-e:0,r+=this._noteHeadPadding,this.upLineX=r,this.downLineX=0),this.displacedX=e,this.width=r}paint(e,t,s){e+=this.x,t+=this.y;let i=this.renderer,a=this.width-this.noteStartX+6;if(this.hasTopOverflow){let r=s.color;s.color=i.resources.staffLineColor;let n=-2;for(;n>=this.minNote.line;){let r=t+i.getScoreY(n);s.fillRect(e-3+this.noteStartX,r,a,1),n-=2}s.color=r}if(this.hasBottomOverflow){let r=s.color;s.color=i.resources.staffLineColor;let n=10;for(;n<=this.maxNote.line;){let r=t+i.getScoreY(n);s.fillRect(e-3+this.noteStartX,r,a,1),n+=2}s.color=r}let r=this._infos,n=e+this._noteHeadPadding;for(let e of r)e.glyph.renderer=this.renderer,e.glyph.paint(n,t,s)}}class So extends Ka{constructor(e,t,s){super(e,t,1,So.getSymbol(s))}doLayout(){this.width=12}static getSymbol(e){switch(e){case p.ThirtySecond:return F.Tremolo3;case p.Sixteenth:return F.Tremolo2;case p.Eighth:return F.Tremolo1;default:return F.None}}}class _o extends qa{constructor(){super(0,0)}doLayout(){this.width=26}paint(e,t,s){const i=this.renderer,a=i.getLineHeight(i.heightLineCount-1),r=i.getLineY(0)+i.getLineHeight(i.drawnLineCount-1)/2-a/2,n=s.lineWidth;s.lineWidth=2,s.moveTo(e+this.x,t+r),s.lineTo(e+this.x+this.width,t+r+a),s.moveTo(e+this.x,t+r+a),s.lineTo(e+this.x+this.width,t+r),s.stroke(),s.lineWidth=n}}class wo extends bo{constructor(){super(),this._noteGlyphLookup=new Map,this._notes=[],this._deadSlapped=null,this._tremoloPicking=null,this.aboveBeatEffects=new Map,this.belowBeatEffects=new Map}get direction(){return this.beamingHelper.direction}getNoteX(e,t){if(this._noteGlyphLookup.has(e.id)){let s=this._noteGlyphLookup.get(e.id),i=this.x+s.x+this._noteHeadPadding;switch(t){case Us.Left:break;case Us.Center:i+=s.width/2;break;case Us.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 zs.TopWithStem:i-=this.renderer.getStemSize(this.beamingHelper);break;case zs.Top:i-=s.height/2;break;case zs.Center:break;case zs.Bottom:i+=s.height/2;break;case zs.BottomWithStem:i+=this.renderer.getStemSize(this.beamingHelper)}return i}return 0}addNoteGlyph(e,t,s){super.add(e,s),this._noteGlyphLookup.set(t.id,e),this._notes.push(t)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.upLineX,e+this.x+this.downLineX)}doLayout(){super.doLayout();let e=this.renderer;this.beat.deadSlapped&&(this._deadSlapped=new _o,this._deadSlapped.renderer=this.renderer,this._deadSlapped.doLayout(),this.width=this._deadSlapped.width);let t=this.direction,s=0,i=0,a=1,r=-a,n=!1,o=!1;this.beat.deadSlapped?(i=e.getScoreY(0),s=e.getScoreY(e.heightLineCount)):this.direction===Ge.Up?(n=!1,o=!0,i=e.getScoreY(this.maxNote.line+2),s=e.getScoreY(this.minNote.line)-e.getStemSize(this.beamingHelper,!0)):(n=!0,o=!1,i=e.getScoreY(this.minNote.line-1),a*=-1,r*=-1,s=e.getScoreY(this.maxNote.line)+e.getStemSize(this.beamingHelper,!0));let h=null,l=null;for(const e of this.aboveBeatEffects.values())e.renderer=this.renderer,e.doLayout(),o&&(s+=r*e.height),e.y=s,(null===h||h>s)&&(h=s),(null===l||l<s)&&(l=s),o||(s+=r*e.height);for(const e of this.belowBeatEffects.values())e.renderer=this.renderer,e.doLayout(),n&&(i+=a*e.height),e.y=i,(null===h||h>i)&&(h=i),(null===l||l<i)&&(l=i),n||(i+=a*e.height);if(null!==h&&e.registerBeatEffectOverflows(h,l??0),this.beat.isTremolo&&!this.beat.deadSlapped){let e=0,s=t===Ge.Up?this.minNote:this.maxNote,i=t===Ge.Up?this.displacedX:0,a=this.beat.tremoloSpeed;switch(a){case p.ThirtySecond:e=t===Ge.Up?-15:15;break;case p.Sixteenth:e=t===Ge.Up?-12:15;break;case p.Eighth:e=t===Ge.Up?-10:10;break;default:e=t===Ge.Up?-10:15}this.beat.duration<p.Half&&(i=this.width/2),this._tremoloPicking=new So(i,s.glyph.y+e,a),this._tremoloPicking.renderer=this.renderer,this._tremoloPicking.doLayout()}}buildBoundingsLookup(e,t,s){for(let i of this._notes)if(this._noteGlyphLookup.has(i.id)){let a=this._noteGlyphLookup.get(i.id),r=new Pa;r.note=i,r.noteHeadBounds=new ds,r.noteHeadBounds.x=t+this.x+this._noteHeadPadding+a.x,r.noteHeadBounds.y=s+this.y+a.y-a.height/2,r.noteHeadBounds.w=a.width,r.noteHeadBounds.h=a.height,e.addNote(r)}}paint(e,t,s){for(const i of this.aboveBeatEffects.values())i.paint(e+this.x+2,t+this.y,s);for(const i of this.belowBeatEffects.values())i.paint(e+this.x+2,t+this.y,s);super.paint(e,t,s),this._tremoloPicking&&this._tremoloPicking.paint(e,t,s),this._deadSlapped&&this._deadSlapped.paint(e,t,s)}}class Bo extends Ka{constructor(e,t,s){super(e,t,1,Bo.getSymbol(s)),this._duration=s}static getSymbol(e){switch(e){case p.QuadrupleWhole:return F.RestLonga;case p.DoubleWhole:return F.RestDoubleWhole;case p.Whole:return F.RestWhole;case p.Half:return F.RestHalf;case p.Quarter:return F.RestQuarter;case p.Eighth:return F.RestEighth;case p.Sixteenth:return F.RestSixteenth;case p.ThirtySecond:return F.RestThirtySecond;case p.SixtyFourth:return F.RestSixtyFourth;case p.OneHundredTwentyEighth:return F.RestOneHundredTwentyEighth;case p.TwoHundredFiftySixth:return F.RestTwoHundredFiftySixth;default:return F.None}}static getSize(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:return 9;case p.ThirtySecond:return 12;case p.SixtyFourth:return 14;case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:return 20}return 10}doLayout(){this.width=Bo.getSize(this._duration)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class ko{constructor(){this.x=0,this.y=-3e3,this.width=0}}class To extends xr{constructor(){super(0,0)}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);this.glyphs.sort(((e,t)=>e.y<t.y?-1:e.y>t.y?1:0));let e=[];e.push(new ko);for(let t=0,s=this.glyphs.length;t<s;t++){let s=this.glyphs[t];s.renderer=this.renderer,s.doLayout();let i=0;for(;e[i].y>s.y;)i++,i===e.length&&e.push(new ko);s.x=i,e[i].y=s.y+21,e[i].width<s.width&&(e[i].width=s.width)}this.width=0;for(const t of e)this.width+=t.width,t.x=this.width;for(let t=0,s=this.glyphs.length;t<s;t++){let s=this.glyphs[t];const i=e[s.x];s.x=this.width-i.x}}}class xo extends bo{get direction(){return Ge.Up}constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new To,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new fo(!0),this._postNoteParenthesis=new fo(!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 Qa(0,0,p.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!==Xe.None){let e=new no(0,i.y,a,Qa.GraceScale);e.renderer=this.renderer,this._accidentals.renderer=this.renderer,this._accidentals.addGlyph(e)}this._noteValueLookup.set(e,i),this.add(i,r),this.isEmpty=!1}doLayout(){let e=0;this._showParenthesis&&(this._preNoteParenthesis.x=e,this._preNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.doLayout(),e+=this._preNoteParenthesis.width+xo.ElementPadding),this._accidentals.isEmpty||(e+=this._accidentals.width+xo.ElementPadding,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+xo.ElementPadding),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+xo.ElementPadding,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+xo.ElementPadding)}paint(e,t,s){this._accidentals.isEmpty||this._accidentals.paint(e+this.x,t+this.y,s),this._showParenthesis&&(this._preNoteParenthesis.paint(e+this.x,t+this.y,s),this._postNoteParenthesis.paint(e+this.x,t+this.y,s)),super.paint(e,t,s)}}xo.ElementPadding=2;class No extends qa{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,s,i,a,r,n,o){po.drawBendSlur(e,t,s,i,a,r,n,o)}doLayout(){super.doLayout(),this.width=0;for(let e of this.BendNoteHeads)e.doLayout(),this.width+=e.width+10}getTieDirection(e,t){return t.getBeatDirection(e)===Ge.Up?Ge.Down:Ge.Up}}No.EndPadding=8;class vo extends te{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class Po extends qa{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 d.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 d.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 d.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 d.Prebend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s);break;case d.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 d.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*Po.BendValueHeight;this.renderer.registerOverflowTop(e);let t=0;for(let e of this._notes){let s=this._renderPoints.get(e.id);switch(e.bendType){case d.Bend:s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case d.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t);break;case d.BendRelease:s[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[2].lineValue=t);break;case d.Prebend:s[0].lineValue=this._preBendMinValue;break;case d.PrebendBend:s[0].lineValue=this._preBendMinValue,s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case d.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 d.Custom:for(let s of e.bendPoints)t.push(new vo(s.offset,s.value));break;case d.BendRelease:t.push(new vo(0,e.bendPoints[0].value)),t.push(new vo(te.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new vo(te.MaxPosition,e.bendPoints[3].value));break;case d.Bend:case d.Hold:case d.Prebend:case d.PrebendBend:case d.PrebendRelease:case d.Release:t.push(new vo(0,e.bendPoints[0].value)),t.push(new vo(te.MaxPosition,e.bendPoints[1].value))}return t}paint(e,t,s){let i=s.color;this._notes.length>1&&(s.color=this.renderer.resources.secondaryGlyphColor);for(let a of this._notes){let r=this._renderPoints.get(a.id),n=this.renderer,o=a,h=!1,c=null,u=!1,p=a.bendStyle===l.Gradual?"grad.":"",g=null;for(;o.isTieOrigin;){let e=o.tieDestination;if(c=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,e.beat.voice.bar),!c||n.staff!==c.staff)break;if(o=e,h=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes||o.vibrato!=w.None){u=!0;break}}g=o.beat,c=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,g.voice.bar),g.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(g=null);let m=0,f=0,y=t+n.y;m=e+n.x,r[0].value>0||a.isContinuedBend?m+=n.getBeatX(a.beat,Gs.MiddleNotes):m+=n.getNoteX(a,Us.Right),f=!g||g.isLastOfVoice&&!u?e+c.x+c.postBeatGlyphsStart:u||!g.nextBeat?e+c.x+c.getBeatX(g,Gs.MiddleNotes):a.bendType===d.Hold?e+c.x+c.getBeatX(g.nextBeat,Gs.OnNotes):e+c.x+c.getBeatX(g.nextBeat,Gs.PreNotes),h||(f-=Po.ArrowSize);let b=(f-m)/te.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 vo(0,0),t,m,y,b,p,s),a.bendType!==d.Prebend?(0===e&&(m+=2),this.paintBend(a,t,i,m,y,b,p,s)):a.isTieOrigin&&a.tieDestination.hasBend&&(i=new vo(te.MaxPosition,t.value),i.lineValue=t.lineValue,this.paintBend(a,t,i,m,y,b,p,s))}if(o.vibrato!==w.None){const i=f-e+Po.ArrowSize-c.x,a=y-t-Po.BendValueHeight*r[r.length-1].lineValue,n=new Gn(i,a,o.vibrato,1.2);n.beat=o.beat,n.renderer=c,n.doLayout(),n.paint(e+c.x,t,s)}s.color=i}}paintBend(e,t,s,i,a,r,n,o){let h=this.renderer,l=this.renderer.resources,d=h.lineOffset/2,c=i+r*t.offset,u=Po.BendValueHeight,p=a-u*t.lineValue;0===t.value?s.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,zs.Top):p+=h.getNoteY(e,zs.Center):p+=d;let g=i+r*s.offset,m=a-u*s.lineValue;0===s.lineValue?m+=h.getNoteY(e,zs.Center):m+=d;let f=0,y=Po.ArrowSize;if(s.value>t.value?(m+y>p&&(m=p-y),o.beginPath(),o.moveTo(g,m),o.lineTo(g-.5*y,m+y),o.lineTo(g+.5*y,m+y),o.closePath(),o.fill(),f=y):s.value!==t.value&&(m<p&&(m=p+y),o.beginPath(),o.moveTo(g,m),o.lineTo(g-.5*y,m-y),o.lineTo(g+.5*y,m-y),o.closePath(),o.fill(),f=-y),o.beginPath(),t.value===s.value){if(t.lineValue>0){let e=g,t=Po.DashSize,s=c+t;if((e-c)/(2*t)<1)o.moveTo(e,p),o.lineTo(c,p);else for(;e>s;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>c?(o.moveTo(c,p),o.bezierCurveTo((c+g)/2,p,g,p,g,m+f),o.stroke()):(o.moveTo(c,p),o.lineTo(g,m),o.stroke());if(n&&t.offset<s.offset){o.font=l.graceFont;let e=o.measureText(n).width,t=0,s=0;if(p>m){let i=Math.abs(p-m);t=i>1.3*o.font.size?p-i/2:p,s=(c+g-e)/2}else t=p,s=g-e;o.fillText(n,s,t)}if(0!==s.value&&t.value!==s.value){let e=s.value,i=s.value>t.value;e=Math.abs(e);let r="";if(4===e)r="full",e-=4;else if(e>=4||e<=-4){let t=e/4|0;r+=t,e-=4*t}if(e>0&&(r+=Po.getFractionSign(e)),""!==r){m=a-u*s.value;let e=m;i||(e=p+1*Math.abs(m-p)/3),o.font=l.tablatureFont;let t=o.measureText(r).width,n=e-.5*l.tablatureFont.size-2,h=g-t/2;o.fillText(r,h,n)}}}static getFractionSign(e){switch(e){case 1:return"¼";case 2:return"½";case 3:return"¾";default:return e+"/ 4"}}}Po.ArrowSize=6,Po.DashSize=3,Po.BendValueHeight=6;class Co extends qa{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===I.Custom)return e.whammyBarPoints;let t=[];switch(e.whammyBarType){case I.Dive:case I.Hold:case I.PrediveDive:case I.Predive:t.push(new te(0,e.whammyBarPoints[0].value)),t.push(new te(te.MaxPosition,e.whammyBarPoints[1].value));break;case I.Dip:t.push(new te(0,e.whammyBarPoints[0].value)),t.push(new te(te.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new te(te.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===I.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(x.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(Co.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(Co.TopOffsetSharedDataKey,i)}getOffset(e){if(0===e)return 0;let t=Co.PerHalfSize+Math.log2(Math.abs(e)/2)*Co.PerHalfSize;return e<0&&(t=-t),t}paint(e,t,s){let i=this.renderer,a=this._beat.nextBeat,r=null,n=Gs.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===I.Dip?Gs.PreNotes:Gs.MiddleNotes:(a=null,r=null));let o=0,h=0;this._isSimpleDip?(o=e+i.x+i.getBeatX(this._beat,Gs.OnNotes)-2,h=e+i.x+i.getBeatX(this._beat,Gs.PostNotes)+2):(o=e+i.x+i.getBeatX(this._beat,Gs.MiddleNotes),h=r?e+r.x+r.getBeatX(a,n):e+i.x+i.width-2);let d=s.textAlign;if(s.textAlign=D.Center,this._renderPoints.length>=2){let e=(h-o)/te.MaxPosition;s.beginPath();let i=t+this.renderer.staff.getSharedLayoutData(Co.TopOffsetSharedDataKey,0),a=this._beat.whammyStyle===l.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,d=0===t;0!==t||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new te(0,0),n,h,o,i,e,s),d=!1),this.paintWhammy(d,n,h,l,o,i,e,s,a),a=""}s.stroke()}s.textAlign=d}paintWhammy(e,t,s,i,a,r,n,o,h){let l=a+n*t.offset,d=a+n*s.offset,c=r-this.getOffset(t.value),u=r-this.getOffset(s.value);if(t.offset===s.offset){let e=Co.DashSize;if(Math.abs(u-c)/(2*e)<1)o.moveTo(l,c),o.lineTo(d,u);else{let t=Math.max(c,u),s=Math.min(c,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=Co.DashSize;if(Math.abs(d-l)/(2*e)<1)o.moveTo(l,c),o.lineTo(d,u);else{let t=Math.max(l,d),s=Math.min(l,d);for(;t>s;)o.moveTo(t,c),o.lineTo(t-e,c),t-=2*e}o.stroke()}else o.moveTo(l,c),o.lineTo(d,u);let p=this.renderer.resources;if(e&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let e=c;e-=p.tablatureFont.size+2,this.renderer.settings.notation.isNotationElementVisible(x.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2,o.fillText(h,l,e))}let g=Math.abs(s.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(x.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+=Po.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(c,u)-p.tablatureFont.size-2:(a=t.offset===s.offset?Math.min(c,u):u,a-=p.tablatureFont.size+2,i&&i.value>s.value&&(a-=2));let r=d;o.fillText(e,r,a)}}}Co.TopOffsetSharedDataKey="tab.whammy.topoffset",Co.PerHalfSize=6,Co.DashSize=3;class Eo extends No{constructor(e){super(0,0),this._beat=e}doLayout(){let e=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case I.None:case I.Custom:case I.Hold:return;case I.Dive:case I.PrediveDive:{let e=new xo(this._beat,!1);e.renderer=this.renderer;let t=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let s of this._beat.notes)s.isTieOrigin||e.addGlyph(this.getBendNoteValue(s,t),t.value%2!=0);e.doLayout(),this.BendNoteHeads.push(e)}break;case I.Dip:if(e===T.SongBook){let e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+Eo.SimpleDipHeight+Eo.SimpleDipPadding}else{let e=new xo(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 xo(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 I.Predive:}super.doLayout()}paint(e,t,s){let i=this._beat;switch(i.whammyBarType){case I.None:case I.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,Gs.MiddleNotes),o=this.getTieDirection(i,r),h=1===this._beat.notes.length?o:Ge.Up,d=s.textAlign;for(let d=0;d<i.notes.length;d++){let c=i.notes[d],u=t+r.y;d>0&&d>=(this._beat.notes.length/2|0)&&(h=Ge.Down),h===Ge.Down?u+=r.getNoteY(c,zs.Bottom):u+=r.getNoteY(c,zs.Top);let p=e+r.x;i.isLastOfVoice?p+=r.width:p+=r.getBeatX(i,Gs.EndBeat),p-=8;let g=i.whammyStyle===l.Gradual&&0===d?"grad.":"",m=null;c.isTieOrigin&&(m=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,c.tieDestination.beat.voice.bar),m&&m.staff===r.staff?p=e+m.x+m.getBeatX(c.tieDestination.beat,Gs.MiddleNotes):m=null);let f=Qa.NoteHeadHeight*Qa.GraceScale*.5;h===Ge.Up&&(f=-f);let y=i.whammyBarPoints.length>0?this.getBendNoteValue(c,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)+f,S=!0):m&&(c.isTieOrigin&&c.tieDestination.beat.hasWhammyBar||c.beat.isContinuedWhammy)?(b=t+m.y+m.getNoteY(c.tieDestination,zs.Top),S=!0,h===Ge.Down&&(b+=Qa.NoteHeadHeight)):c.isTieOrigin&&(b=m?t+m.y+m.getNoteY(c.tieDestination,zs.Top):u,h===Ge.Down&&(b+=Qa.NoteHeadHeight)),i.whammyBarType){case I.Hold:c.isTieOrigin&&po.paintTie(s,1,n,u,p,b,o===Ge.Down,22,4);break;case I.Dive:0===d&&(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,h===Ge.Down,1,g):c.isTieOrigin&&po.paintTie(s,1,n,u,p,b,o===Ge.Down,22,4);break;case I.Dip:if(a===T.SongBook){if(0===d){let i=e+r.x+r.getBeatX(this._beat,Gs.OnNotes)-2,a=e+r.x+r.getBeatX(this._beat,Gs.PostNotes)+2,n=(i+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();s.font=this.renderer.resources.tablatureFont,s.fillText(o,n,t+this.y);let h=t+this.y+s.font.size+2,l=h+Eo.SimpleDipHeight;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(s.moveTo(i,l),s.lineTo(n,h),s.lineTo(a,l)):(s.moveTo(i,h),s.lineTo(n,l),s.lineTo(a,h)),s.stroke()}c.isTieOrigin&&po.paintTie(s,1,n,u,p,b,o===Ge.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(c,i.whammyBarPoints[1]),o=this.BendNoteHeads[0].getNoteValueY(a)+f;this.drawBendSlur(s,n,u,e,o,h===Ge.Down,1,g),this.BendNoteHeads[1].x=p-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=t+r.y,this.BendNoteHeads[1].paint(0,0,s),b=this.BendNoteHeads[1].getNoteValueY(y)+f,this.drawBendSlur(s,e,o,p,b,h===Ge.Down,1,g)}break;case I.PrediveDive:case I.Predive:let l=e+r.x+r.getBeatX(c.beat,Gs.PreNotes);l+=r.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;let m=t+r.y+r.getScoreY(r.accidentalHelper.getNoteLineForValue(c.displayValue-(c.beat.whammyBarPoints[0].value/2|0),!1))+f;this.drawBendSlur(s,l,m,n,u,h===Ge.Down,1,g),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.drawBendSlur(s,n,u,p,b,h===Ge.Down,1,g))}}s.textAlign=d}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}Eo.SimpleDipHeight=2*Co.PerHalfSize,Eo.SimpleDipPadding=2;class Fo extends qa{constructor(e,t,s){super(e,t),this.width=s}}class Do extends Ka{constructor(e,t,s,i,a){super(e,t,a?Qa.GraceScale:1,s.getSymbol(i)),this._isGrace=a,this._articulation=s}paint(e,t,s){let i=this._isGrace?1:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale,this.symbol,!1),this._articulation.techniqueSymbol!==F.None&&this._articulation.techniqueSymbolPlacement===L.Middle&&s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale,this._articulation.techniqueSymbol,!1)}doLayout(){const e=this._isGrace?Qa.GraceScale:1;switch(this.symbol){case F.NoteheadWhole:this.width=14;break;case F.NoteheadCircleX:case F.NoteheadDiamondWhite:this.width=9;break;case F.NoteheadHeavyXHat:case F.NoteheadHeavyX:this.width=13;break;default:this.width=10}this.width=this.width*e,this.height=Qa.NoteHeadHeight*e}}class Lo extends Ka{constructor(e,t){super(e,t,Qa.GraceScale,F.ArticStaccatoAbove)}doLayout(){this.width=Qa.QuarterNoteHeadWidth,this.height=7}paint(e,t,s){super.paint(e+3,t+5,s)}}class Mo extends Ka{constructor(e,t){super(e,t,.5,F.PictEdgeOfCymbal)}doLayout(){this.width=22,this.height=15}paint(e,t,s){super.paint(e-3,t+this.height,s)}}class Io extends ja{constructor(e,t,s=!1){super(e,t),this._center=s}doLayout(){this.width=9,this.height=10}paint(e,t,s){s.fillMusicFontSymbol(e+this.x,t+this.y+this.height,Qa.GraceScale,F.GuitarGolpe,this._center)}}class Ao extends ja{constructor(){super(...arguments),this._strings=new Set}addString(e){this._strings.add(e)}doLayout(){const e=Qr.CircleNumberHeight*Qr.CircleNumberScale;this.height=(e+3)*this._strings.size,this.width=e}paint(e,t,s){const i=this.renderer.bar.staff.tuning.length;let a=0;const r=Qr.CircleNumberHeight*Qr.CircleNumberScale;for(const n of this._strings){const o=i-n,h=F.GuitarString1+o;s.fillMusicFontSymbol(e+this.x+Qa.NoteHeadHeight/2,t+this.y+r+a,Qr.CircleNumberScale,h,!0),a+=r+3}}}class Oo extends ja{constructor(e,t,s,i){super(e,t),this.beatEffects=new Map,this._isGrace=i,this._duration=s,this._symbol=Oo.getSymbol(s)}paint(e,t,s){let i=this._isGrace?1:0;const a=this._isGrace?Qa.GraceScale:1;s.fillMusicFontSymbol(e+this.x,t+this.y+i,a,this._symbol,!1);for(const i of this.beatEffects.values())i.paint(e+this.x,t+this.y,s)}doLayout(){const e=this._isGrace?Qa.GraceScale:1;switch(this._duration){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:this.width=Oo.WholeNoteHeadWidth*e;break;case p.Half:this.width=Oo.HalfNoteHeadWidth*e;break;default:this.width=Oo.QuarterNoteHeadWidth*e}this.height=Oo.NoteHeadHeight*e;let t=Oo.NoteHeadHeight;for(const e of this.beatEffects.values())e.y+=t,e.x+=this.width/2,e.renderer=this.renderer,t+=7,e.doLayout()}static getSymbol(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:return F.NoteheadSlashWhiteWhole;case p.Half:return F.NoteheadSlashWhiteHalf;default:return F.NoteheadSlashVerticalEnds}}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width,e+this.x)}}Oo.NoteHeadHeight=17,Oo.QuarterNoteHeadWidth=12,Oo.HalfNoteHeadWidth=25,Oo.WholeNoteHeadWidth=32;class Ro extends hn{constructor(){super(...arguments),this._collisionOffset=-1e3,this._skipPaint=!1,this.slash=null,this.noteHeads=null,this.restGlyph=null}getNoteX(e,t){return this.noteHeads?this.noteHeads.getNoteX(e,t):0}buildBoundingsLookup(e,t,s){this.noteHeads&&this.noteHeads.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteY(e,t){return this.noteHeads?this.noteHeads.getNoteY(e,t):0}updateBeamingHelper(){if(this.noteHeads)this.noteHeads.updateBeamingHelper(this.container.x+this.x);else if(this.restGlyph){if(this.restGlyph.updateBeamingHelper(this.container.x+this.x),this.renderer.bar.isMultiVoice&&-1e3===this._collisionOffset){this._collisionOffset=this.renderer.helpers.collisionHelper.applyRestCollisionOffset(this.container.beat,this.restGlyph.y,this.renderer.getScoreHeight(1)),this.y+=this._collisionOffset;const e=this.renderer.helpers.collisionHelper.restDurationsByDisplayTime;e.has(this.container.beat.playbackStart)&&e.get(this.container.beat.playbackStart).has(this.container.beat.playbackDuration)&&e.get(this.container.beat.playbackStart).get(this.container.beat.playbackDuration)!==this.container.beat.id&&(this._skipPaint=!0)}}else this.slash&&this.slash.updateBeamingHelper(this.container.x+this.x)}paint(e,t,s){this._skipPaint||super.paint(e,t,s)}doLayout(){let e=this.renderer;if(!this.container.beat.isEmpty)if(this.container.beat.isRest){let t=2*Math.ceil((this.renderer.bar.staff.standardNotationLineCount-1)/2);this.container.beat.duration===p.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const s=new Bo(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=Dr.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 Fo(0,0,5));for(let e=0;e<this.container.beat.dots;e++){let e=new xr(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addGlyph(e)}}}else{if(this.container.beat.slashed){const t=this.container.beat.graceType!==m.None,s=(e.heightLineCount-1)/2,i=e.getLineY(s),a=new Oo(0,i,this.container.beat.duration,t);this.slash=a,a.beat=this.container.beat,a.beamingHelper=this.beamingHelper,this.addGlyph(a)}else{const e=new wo;this.noteHeads=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;let t=new fo(!1);t.renderer=this.renderer;for(let e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),t.addParenthesis(e));this.addGlyph(e),t.isEmpty||(this.addGlyph(new Fo(0,0,4*(this.container.beat.graceType!==m.None?Qa.GraceScale:1))),this.addGlyph(t))}if(this.container.beat.hasWhammyBar){let e=new Eo(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addGlyph(new Fo(0,0,5));for(let t=0;t<this.container.beat.dots;t++){let t=new xr(0,0);t.renderer=this.renderer;for(let s of this.container.beat.notes)this.createBeatDot(e.getNoteLine(s),t);this.addGlyph(t)}}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.slash&&(this.centerX=this.slash.x+this.slash.width/2)}createBeatDot(e,t){let s=this.renderer;t.addGlyph(new lo(0,s.getScoreY(e),1.5))}createNoteHeadGlyph(e){let t=this.container.beat.graceType!==m.None;if(e.beat.voice.bar.staff.isPercussion){const s=ue.getArticulation(e);if(s)return new Do(0,0,s,e.beat.duration,t);re.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new co(0,0,t):e.beat.graceType===m.BendGrace?new Qa(0,0,p.Quarter,!0):e.harmonicType===y.Natural?new uo(0,0,e.beat.duration,t):new Qa(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===m.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!==y.None&&e.harmonicType!==y.Natural){let i=e.displayValue+e.harmonicPitch;s=new uo(0,0,e.beat.duration,this.container.beat.graceType!==m.None),a=t.accidentalHelper.getNoteLineForValue(i,!1),s.y=t.getScoreY(a),this.noteHeads.addNoteGlyph(s,e,a)}const r=this.noteHeads.belowBeatEffects,n=this.noteHeads.aboveBeatEffects;if(e.isStaccato&&!r.has("Staccato")&&r.set("Staccato",new Lo(0,0)),e.accentuated!==i.Normal||r.has("Accent")||r.set("Accent",new ho(0,0,e)),e.accentuated!==i.Heavy||r.has("HAccent")||r.set("HAccent",new ho(0,0,e)),e.accentuated!==i.Tenuto||r.has("Tenuto")||r.set("Tenuto",new ho(0,0,e)),e.showStringNumber&&e.isStringed){let t;n.has("StringNumber")?t=n.get("StringNumber"):(t=new Ao(0,0),n.set("StringNumber",t)),t.addString(e.string)}if(e.isPercussion){const t=ue.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==L.Middle){const e=t.techniqueSymbolPlacement===L.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case F.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new Mo(0,0));break;case F.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new Lo(0,0));break;case F.StringsUpBow:e.set("StringsUpBow",new On(0,0,E.Up));break;case F.StringsDownBow:e.set("StringsDownBow",new On(0,0,E.Down));break;case F.GuitarGolpe:e.set("GuitarGolpe",new Io(0,0))}}}}}class Vo extends qa{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=this._beat.brushType===c.ArpeggioUp||this._beat.brushType===c.ArpeggioDown?10: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,zs.Bottom)-a),n=t+this.y+i.getNoteY(this._beat.minNote,zs.Top)+a,o=e+this.x+this.width/2,h=8,l=new Gn(0,0,w.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,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,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 Ho{constructor(e,t){this.line=0,this.line=e,this.text=t}}class Go extends xr{constructor(){super(0,0),this._infos=new Map}get isEmpty(){return 0===this._infos.size}addFingers(e){const t=this.renderer.settings;if(t.notation.fingeringMode!==k.ScoreDefault&&t.notation.fingeringMode!==k.ScoreForcePiano)return;const s=le.fingerToString(this.renderer.settings,e.beat,e.leftHandFinger,!0);s&&this.addFinger(e,s);const i=le.fingerToString(this.renderer.settings,e.beat,e.rightHandFinger,!1);i&&this.addFinger(e,i)}addFinger(e,t){let s=this.renderer.getNoteLine(e);if(this._infos.has(s)){this._infos.get(s).text+=t}else{const e=new Ho(s,t);this._infos.set(s,e)}}doLayout(){let e=this.renderer;for(const[t,s]of this._infos){const t=new Gr(0,0,s.text,e.resources.inlineFingeringFont,D.Left,L.Middle);t.renderer=e,t.y=e.getScoreY(s.line),t.doLayout(),this.addGlyph(t),this.width=Math.max(this.width,t.width)}}}class Wo extends on{get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}doLayout(){if(!this.container.beat.isRest){let e=new To;e.renderer=this.renderer;let t=new Go;t.renderer=this.renderer;let s=new fo(!0);s.renderer=this.renderer;const i=new xo(this.container.beat,!0);this._prebends=i,i.renderer=this.renderer;for(let a of this.container.beat.notes)if(a.isVisible){if(a.hasBend)switch(a.bendType){case d.PrebendBend:case d.Prebend:case d.PrebendRelease:i.addGlyph(a.displayValue-(a.bendPoints[0].value/2|0),!1)}else if(a.beat.hasWhammyBar)switch(a.beat.whammyBarType){case I.PrediveDive:case I.Predive:this._prebends.addGlyph(a.displayValue-(a.beat.whammyBarPoints[0].value/2|0),!1)}this.createAccidentalGlyph(a,e),s.addParenthesis(a),t.addFingers(a)}i.isEmpty||(this.addGlyph(i),this.addGlyph(new Fo(0,0,4*(this.container.beat.graceType!==m.None?Qa.GraceScale:1)))),this.container.beat.brushType!==c.None&&(this.addGlyph(new Vo(this.container.beat)),this.addGlyph(new Fo(0,0,4))),t.isEmpty||(this.isEmpty||this.addGlyph(new Fo(0,0,2*(this.container.beat.graceType!==m.None?Qa.GraceScale:1))),this.addGlyph(t),this.addGlyph(new Fo(0,0,2*(this.container.beat.graceType!==m.None?Qa.GraceScale:1)))),s.isEmpty||(this.addGlyph(s),this.addGlyph(new Fo(0,0,4*(this.container.beat.graceType!==m.None?Qa.GraceScale:1)))),e.isEmpty||(this.accidentals=e,this.isEmpty||this.addGlyph(new Fo(0,0,2*(this.container.beat.graceType!==m.None?Qa.GraceScale:1))),this.addGlyph(e),this.addGlyph(new Fo(0,0,2*(this.container.beat.graceType!==m.None?Qa.GraceScale:1))))}super.doLayout()}createAccidentalGlyph(e,t){let s=this.renderer,i=s.accidentalHelper.applyAccidental(e),a=s.getNoteLine(e),r=this.container.beat.graceType!==m.None;const n=r?Qa.GraceScale:1;if(i!==Xe.None){let e=new no(0,s.getScoreY(a),i,n);e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==y.None&&e.harmonicType!==y.Natural){let o=e.displayValue+e.harmonicPitch;i=s.accidentalHelper.applyAccidentalForValue(e.beat,o,r,!1),a=s.accidentalHelper.getNoteLineForValue(o,!1);let h=new no(0,s.getScoreY(a),i,n);h.renderer=this.renderer,t.addGlyph(h)}}constructor(){super(),this._prebends=null,this.accidentals=null}}class zo extends Ka{constructor(e,t,s,i){super(e,t,i,zo.getSymbol(s)),this._digit=0,this._scale=0,this._digit=s,this._scale=i}doLayout(){this.width=this.getDigitWidth(this._digit)*this._scale}getDigitWidth(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:return 14;case 1:return 10;default:return 0}}static getSymbol(e){switch(e){case 0:return F.TimeSig0;case 1:return F.TimeSig1;case 2:return F.TimeSig2;case 3:return F.TimeSig3;case 4:return F.TimeSig4;case 5:return F.TimeSig5;case 6:return F.TimeSig6;case 7:return F.TimeSig7;case 8:return F.TimeSig8;case 9:return F.TimeSig9;default:return F.None}}}class Uo extends xr{constructor(e,t,s,i=1){super(e,t),this._number=0,this._scale=0,this._number=s,this._scale=i}doLayout(){let e=this._number;for(;e>0;){let t=new zo(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}}}Uo.numberHeight=18;class Xo extends xr{constructor(e,t,s,i,a,r){super(e,t),this._numerator=0,this._denominator=0,this._numerator=s,this._denominator=i,this._isCommon=a,this._isFreeTime=r}doLayout(){let e=0;const t=Uo.numberHeight;if(this._isFreeTime){const s=new go(!0);s.renderer=this.renderer,s.y=-t,s.height=2*t,s.doLayout(),this.addGlyph(s),e+=s.width+10}if(this._isCommon&&2===this._numerator&&2===this._denominator){let t=new Ka(e,0,this.commonScale,F.TimeSigCutCommon);t.width=14,this.addGlyph(t),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){let t=new Ka(e,0,this.commonScale,F.TimeSigCommon);t.width=14,this.addGlyph(t),super.doLayout()}else{let s=new Uo(e,-t/2,this._numerator,this.numberScale),i=new Uo(e,t/2,this._denominator,this.numberScale);this.addGlyph(s),this.addGlyph(i),super.doLayout();const a=this.width-e;s.x=e+(a-s.width)/2,i.x=e+(a-i.width)/2}if(this._isFreeTime){const e=new go(!1);e.renderer=this.renderer,e.x=this.width+13,e.y=-t,e.height=2*t,e.doLayout(),this.addGlyph(e),this.width=e.x+e.width}}}class Jo extends Xo{get commonScale(){return 1}get numberScale(){return 1}}class Yo extends No{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 d.Bend:case d.PrebendRelease:case d.PrebendBend:{let t=this._endNoteGlyph;t||(t=new xo(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let s=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,s),s.value%2!=0)}break;case d.Release:if(!e.isTieOrigin){let t=this._endNoteGlyph;t||(t=new xo(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let s=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,s),s.value%2!=0)}break;case d.BendRelease:{let t=this._middleNoteGlyph;t||(t=new xo(e.beat,!1),this._middleNoteGlyph=t,t.renderer=this.renderer,this.BendNoteHeads.push(t));let s=e.bendPoints[1];t.addGlyph(this.getBendNoteValue(e,e.bendPoints[1]),s.value%2!=0);let i=this._endNoteGlyph;i||(i=new xo(e.beat,!1),i.renderer=this.renderer,this._endNoteGlyph=i,this.BendNoteHeads.push(i));let a=e.bendPoints[e.bendPoints.length-1];i.addGlyph(this.getBendNoteValue(e,a),a.value%2!=0)}}}paint(e,t,s){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._beat.voice.bar),a=e+i.x+i.getBeatX(this._beat,Gs.MiddleNotes),r=e+i.x;this._beat.isLastOfVoice?r+=i.postBeatGlyphsStart:r+=i.getBeatX(this._beat.nextBeat,Gs.PreNotes),r-=8;let n=(a+r)/2;this._middleNoteGlyph&&(this._middleNoteGlyph.x=n-this._middleNoteGlyph.noteHeadOffset,this._middleNoteGlyph.y=t+i.y,this._middleNoteGlyph.paint(0,0,s)),this._endNoteGlyph&&(this._endNoteGlyph.x=r-this._endNoteGlyph.noteHeadOffset,this._endNoteGlyph.y=t+i.y,this._endNoteGlyph.paint(0,0,s)),this._notes.sort(((e,t)=>t.displayValue-e.displayValue));let o=this._beat.graceType===m.BendGrace?this._beat.nextBeat:this._beat,h=1===this._notes.length?this.getTieDirection(o,i):Ge.Up;for(let o=0;o<this._notes.length;o++){let c=this._notes[o];o>0&&o>=(this._notes.length/2|0)&&(h=Ge.Down);let u=t+i.y+i.getNoteY(c,zs.Top),p=Qa.NoteHeadHeight*Qa.GraceScale*.5;h===Ge.Down&&(u+=Qa.NoteHeadHeight);let g=c.bendStyle===l.Gradual?"grad.":"";if(c.isTieOrigin){let r=c.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,Gs.MiddleNotes),o=t+n.y+n.getNoteY(r,zs.Top);h===Ge.Down&&(o+=Qa.NoteHeadHeight),c.bendType===d.Hold||c.bendType===d.Prebend?po.paintTie(s,1,a,u,i,o,h===Ge.Down,22,4):this.drawBendSlur(s,a,u,i,o,h===Ge.Down,1,g)}else{let r=e+i.x+i.width,n=c.tieDestination.realValue;i.accidentalHelper.applyAccidentalForValue(c.beat,n,!1,!0);let o=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(n,!1));c.bendType===d.Hold||c.bendType===d.Prebend?po.paintTie(s,1,a,u,r,o,h===Ge.Down,22,4):this.drawBendSlur(s,a,u,r,o,h===Ge.Down,1,g)}switch(c.bendType){case d.Prebend:case d.PrebendBend:case d.PrebendRelease:let r=e+i.x+i.getBeatX(c.beat,Gs.PreNotes);r+=i.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;let n=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,r,n,a,u,h===Ge.Down,1)}}else{h===Ge.Up&&(p=-p);let o=0,l=0;switch(c.bendType){case d.Bend:o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,l,h===Ge.Down,1,g);break;case d.BendRelease:let m=this.getBendNoteValue(c,c.bendPoints[1]),f=this._middleNoteGlyph.getNoteValueY(m)+p;this.drawBendSlur(s,a,u,n,f,h===Ge.Down,1,g),o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,n,f,r,l,h===Ge.Down,1,g);break;case d.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,l,h===Ge.Down,1,g));break;case d.Prebend:case d.PrebendBend:case d.PrebendRelease:let y=e+i.x+i.getBeatX(c.beat,Gs.PreNotes);y+=i.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;let b=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,y,b,a,u,h===Ge.Down,1),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,l,h===Ge.Down,1,g))}}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class qo extends po{constructor(e,t,s=!1){super(e,t,s)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?Ge.Up:t.getBeatDirection(e)===Ge.Up?Ge.Down:Ge.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Ge.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,zs.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,zs.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===Ge.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===m.None?s===this.tieDirection?this.tieDirection===Ge.Up?e.getNoteY(this.endBeat.maxNote,zs.TopWithStem):e.getNoteY(this.endBeat.minNote,zs.BottomWithStem):this.tieDirection===Ge.Up?e.getNoteY(this.endBeat.maxNote,zs.BottomWithStem):e.getNoteY(this.endBeat.minNote,zs.TopWithStem):this.tieDirection===Ge.Up?e.getNoteY(this.endBeat.maxNote,zs.Top):e.getNoteY(this.endBeat.minNote,zs.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,Gs.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>p.Whole&&e===this.tieDirection?Gs.Stem:Gs.MiddleNotes)}}class jo extends qa{constructor(e,t,s,i){super(0,0),this._outType=t,this._inType=e,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.drawSlideOut(e,t,s)}paintSlideIn(e,t,s){let i=this.renderer,a=e+i.x+i.getNoteX(this._startNote,Us.Left)-2,r=t+i.y+i.getNoteY(this._startNote,zs.Center),n=a-12,o=t+i.y;switch(this._inType){case S.IntoFromBelow:o+=i.getNoteY(this._startNote,zs.Bottom);break;case S.IntoFromAbove:o+=i.getNoteY(this._startNote,zs.Top);break;default:return}let h=this.getAccidentalsWidth(i,this._startNote.beat);n-=h,a-=h,this.paintSlideLine(s,!1,n,a,o,r)}getAccidentalsWidth(e,t){let s=e.getPreNotesGlyphForBeat(t);return s&&s.accidentals?s.accidentals.width:0}drawSlideOut(e,t,s){let i=this.renderer,a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case _.Shift:case _.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,Gs.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,zs.Center),this._startNote.slideTarget){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,Gs.PreNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,zs.Center)):(n=e+i.x+i.width,o=r),this._startNote.slideTarget.realValue>this._startNote.realValue?(r+=2,o-=2):(r-=2,o+=2)}else n=e+i.x+this._parent.x,o=r;break;case _.OutUp:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+2,r=t+i.y+i.getNoteY(this._startNote,zs.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,zs.Top);break;case _.OutDown:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+2,r=t+i.y+i.getNoteY(this._startNote,zs.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,zs.Bottom);break;case _.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+4,r=t+i.y+i.getNoteY(this._startNote,zs.Center),o=t+i.y+i.getNoteY(this._startNote,zs.Top),n=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Gs.PreNotes)),h=!0;break;case _.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+4,r=t+i.y+i.getNoteY(this._startNote,zs.Center),o=t+i.y+i.getNoteY(this._startNote,zs.Bottom),n=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Gs.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new Gn(0,0,w.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 Ko extends qo{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===Ge.Up?this.startNoteRenderer.getNoteY(this._startNote,zs.Top):this.startNoteRenderer.getNoteY(this._startNote,zs.Bottom):this.startNoteRenderer.getNoteY(this._startNote,zs.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===Ge.Up?this.endNoteRenderer.getNoteY(this._endNote,zs.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,zs.BottomWithStem):this.tieDirection===Ge.Up?this.endNoteRenderer.getNoteY(this._endNote,zs.Top):this.endNoteRenderer.getNoteY(this._endNote,zs.Bottom):this.endNoteRenderer.getNoteY(this._endNote,zs.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===Ge.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===Ge.Down}isEndCentered(){return this._startNote.beat.graceType===m.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===Ge.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===Ge.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===m.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,Gs.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,Us.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,Gs.Stem):this.endNoteRenderer.getNoteX(this._endNote,Us.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,Gs.PreNotes)}}class Qo extends po{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)===Ge.Up?Ge.Down:Ge.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Ge.Up?this.startNoteRenderer.getNoteY(this.startNote,zs.Top):this.startNoteRenderer.getNoteY(this.startNote,zs.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===Ge.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===Ge.Up?e.getNoteY(this.endNote,zs.Top):e.getNoteY(this.endNote,zs.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,Gs.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,Gs.PreNotes)}}class $o extends Za{constructor(e,t){super(e,t),this._bend=null,this._effectSlur=null,this._effectEndSlur=null}doLayout(){this._effectSlur=null,this._effectEndSlur=null,super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(e.isVisible){if(e.isTieOrigin&&!e.hasBend&&!e.beat.hasWhammyBar&&e.beat.graceType!==m.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){let t=new Qo(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){let t=new Qo(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==S.None||e.slideOutType!==_.None){let t=new jo(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){let t=new Ko(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){let t=new Ko(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new Ko(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===Ge.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,i=t===Ge.Up?e.beat.minNote:e.beat.maxNote;const a=new Ko(s,i,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new Yo(e.beat);this._bend=t,t.renderer=this.renderer,this.addTie(t)}this._bend.addBends(e)}if(this.beat.isLegatoOrigin){if(!this.beat.previousBeat||!this.beat.previousBeat.isLegatoOrigin){let e=this.beat.nextBeat;for(;e.nextBeat&&e.nextBeat.isLegatoDestination;)e=e.nextBeat;this.addTie(new qo(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 qo(e,this.beat,!0))}}}}class Zo extends qa{constructor(e,t,s,i){super(e,t),this._dotOffset=0,this._circleSize=0,this._dotOffset=0,this._circleSize=0,this._dotOffset=i,this._circleSize=s}doLayout(){this.width=13}paint(e,t,s){let i=t+this.y+this.renderer.topPadding,a=t+this.y+this.renderer.height-this.renderer.bottomPadding,r=e+this.x+.5,n=a-i;s.fillRect(r,i,4,n),r+=7.5,s.beginPath(),s.moveTo(r,i),s.lineTo(r,a),s.stroke(),r+=3;let o=this._circleSize,h=(i+a)/2;s.fillCircle(r,h-o*this._dotOffset,o),s.fillCircle(r,h+o*this._dotOffset,o)}}class eh extends qa{constructor(e,t){super(e,t)}doLayout(){this.renderer.isLast?this.width=15:this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart?this.width=2:(this.width=2,this.renderer.bar.masterBar.isDoubleBar&&(this.width+=2))}paint(e,t,s){let i=t+this.y+this.renderer.topPadding,a=t+this.y+this.renderer.height-this.renderer.bottomPadding,r=e+this.x,n=a-i;if(this.renderer.isLast)s.fillRect(r+this.width-4-4,i,1,n),s.fillRect(r+this.width-4,i,4,n);else if(!this.renderer.nextRenderer||this.renderer.nextRenderer.staff!==this.renderer.staff||!this.renderer.nextRenderer.bar.masterBar.isRepeatStart)if(this.renderer.bar.masterBar.isFreeTime){const e=eh.DashSize,t=.5+(r+this.width-1|0),o=Math.ceil(n/2/e);if(s.beginPath(),o<1)s.moveTo(t,i),s.lineTo(t,a);else{let r=i;const h=(n-o*e)/(o-1);for(;r<a;)s.moveTo(t,r),s.lineTo(t,r+e),r+=e+h}s.stroke()}else s.fillRect(r+this.width-1,i,1,n),this.renderer.bar.masterBar.isDoubleBar&&s.fillRect(r+this.width-5,i,1,n)}}eh.DashSize=4;class th extends qa{constructor(e,t){super(e,t)}doLayout(){this.width=11}paint(e,t,s){let i=t+this.y+this.renderer.topPadding,a=t+this.y+this.renderer.height-this.renderer.bottomPadding,r=e+this.x,n=a-i,o=1.5,h=(i+a)/2;s.fillCircle(r,h-4.5,o),s.fillCircle(r,h+4.5,o),r+=4,s.beginPath(),s.moveTo(r,i),s.lineTo(r,a),s.stroke(),r+=3.5,s.fillRect(r,i,4,n)}}class sh extends qa{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=D.Right;let r="x"+this._count,n=s.measureText(r).width/1.5;s.fillText(r,e+this.x-n,t+this.y),s.textAlign=a}}class ih extends qa{constructor(e,t,s){super(e,t),this._number=0,this._number=s}doLayout(){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.barNumberFont,this.width=this.renderer.scoreRenderer.canvas.measureText(this._number.toString()).width+5}paint(e,t,s){if(!this.renderer.staff.isFirstInSystem)return;let i=this.renderer.resources,a=s.color;const r=s.textBaseline;s.textBaseline=L.Top,s.color=i.barNumberColor,s.font=i.barNumberFont,s.fillText(this._number.toString(),e+this.x,t+this.y),s.color=a,s.textBaseline=r}}class ah extends tn{constructor(e,t){super(e,t),this.firstLineY=0,this._startSpacing=!1,this.tupletSize=0}get lineOffset(){return this.lineSpacing+1}get tupletOffset(){return 10}get topGlyphOverflow(){const e=this.resources;return e.tablatureFont.size/2+.2*e.tablatureFont.size}get bottomGlyphOverflow(){const e=this.resources;return e.tablatureFont.size/2+.2*e.tablatureFont.size}initLineBasedSizes(){this.topPadding=this.topGlyphOverflow,this.bottomPadding=this.bottomGlyphOverflow,this.height=this.lineOffset*(this.heightLineCount-1)+this.topPadding+this.bottomPadding}updateSizes(){this.initLineBasedSizes(),this.adjustSizes(),this.updateFirstLineY(),super.updateSizes()}adjustSizes(){}updateFirstLineY(){let e=this.lineOffset*(this.heightLineCount-1),t=(this.drawnLineCount-1)*this.lineOffset;this.firstLineY=this.topPadding+(e-t)/2}doLayout(){this.initLineBasedSizes(),this.updateFirstLineY(),this.tupletSize=15+.3*this.resources.effectFont.size,super.doLayout()}getLineY(e){return this.firstLineY+this.getLineHeight(e)}getLineHeight(e){return this.lineOffset*e}paintBackground(e,t,s){super.paintBackground(e,t,s);const i=this.resources;s.color=i.staffLineColor;const a=[];for(let e=0,t=this.drawnLineCount;e<t;e++)a.push([]);this.collectSpaces(a);for(const e of a)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));for(let i=0;i<this.drawnLineCount;i++){const r=this.getLineY(i);let n=0;for(let o of a[i])s.fillRect(e+this.x+n,t+this.y+r|0,o[0]-n,tn.StaffLineThickness),n=o[0]+o[1];s.fillRect(e+this.x+n,t+this.y+r|0,this.width-n,tn.StaffLineThickness)}s.color=i.mainGlyphColor,this.paintSimileMark(e,t,s)}collectSpaces(e){}createStartSpacing(){if(this._startSpacing)return;const e=0===this.index?this.settings.display.firstStaffPaddingLeft:this.settings.display.staffPaddingLeft;this.addPreBeatGlyph(new Fo(0,0,e)),this._startSpacing=!0}paintTuplets(e,t,s,i=!1){for(const a of this.bar.voices)if(this.hasVoiceContainer(a)){const r=this.getVoiceContainer(a);for(const a of r.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,a,i)}}getTupletBeamDirection(e){return this.getBeamDirection(e)}paintTupletHelper(e,t,s,i,a){const r=this.resources;let n,o=s.textAlign,h=s.textBaseline;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=D.Center,s.textBaseline=L.Middle;let l=i.beats[0].tupletNumerator,d=i.beats[0].tupletDenominator;n=2===l&&3===d?"2":3===l&&2===d?"3":4===l&&6===d?"4":5===l&&4===d?"5":6===l&&4===d?"6":7===l&&4===d?"7":9===l&&8===d?"9":10===l&&8===d?"10":11===l&&8===d?"11":12===l&&8===d?"12":13===l&&8===d?"13":l+":"+d;let c=this.tupletOffset,u=5;if(1!==i.beats.length&&i.isFull){let o=i.beats[0],h=i.beats[i.beats.length-1],l=null,d=null;for(let e=0;e<i.beats.length;e++)if(!i.beats[e].isRest){l=i.beats[e];break}for(let e=i.beats.length-1;e>=0;e--)if(!i.beats[e].isRest){d=i.beats[e];break}let p=!1;l||(l=o,p=!0),d||(d=h);let g=this.helpers.beamHelperLookup[i.voice.index].get(o.index),m=this.helpers.beamHelperLookup[i.voice.index].get(h.index),f=g.getBeatLineX(o),y=m.getBeatLineX(h),b=this.helpers.beamHelperLookup[i.voice.index].get(l.index),S=this.helpers.beamHelperLookup[i.voice.index].get(d.index),_=this.getTupletBeamDirection(g),w=this.calculateBeamYWithDirection(b,f,_),B=this.calculateBeamYWithDirection(S,y,_);p&&(w=Math.max(w,B),B=w),s.font=r.effectFont;let k=s.measureText(n).width,T=3,x=(f+y)/2,N=x-k/2-T,v=x+k/2+T,P=(B-w)/(y-f),C=w-P*f,E=P*N+C,F=P*x+C,D=P*v+C;_===Ge.Down&&(c*=-1,u*=-1),s.beginPath(),s.moveTo(e+this.x+f,t+this.y+w-c|0),a?s.quadraticCurveTo(e+this.x+(N+f)/2,t+this.y+E-c-u|0,e+this.x+N,t+this.y+E-c-u|0):(s.lineTo(e+this.x+f,t+this.y+w-c-u|0),s.lineTo(e+this.x+N,t+this.y+E-c-u|0)),s.stroke(),s.beginPath(),s.moveTo(e+this.x+v,t+this.y+D-c-u|0),a?s.quadraticCurveTo(e+this.x+(y+v)/2,t+this.y+D-c-u|0,e+this.x+y,t+this.y+B-c|0):(s.lineTo(e+this.x+y,t+this.y+B-c-u|0),s.lineTo(e+this.x+y,t+this.y+B-c|0)),s.stroke(),s.fillText(n,e+this.x+x,t+this.y+F-c-u)}else for(const a of i.beats){let o=this.helpers.beamHelperLookup[i.voice.index].get(a.index);if(!o)continue;let h=this.getTupletBeamDirection(o),l=o.getBeatLineX(a),d=this.calculateBeamYWithDirection(o,l,h);h===Ge.Down?d+=c+u:d-=c+u,s.font=r.effectFont,s.fillText(n,e+this.x+l,t+this.y+d)}s.textAlign=o,s.textBaseline=h}paintBeams(e,t,s){for(const i of this.helpers.beamHelpers)for(const a of i)this.paintBeamHelper(e+this.beatGlyphsStart,t,s,a)}drawBeamHelperAsFlags(e){return 1===e.beats.length}paintBeamHelper(e,t,s,i){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(this.drawBeamHelperAsFlags(i)?this.paintFlag(e,t,s,i):this.paintBar(e,t,s,i))}shouldPaintFlag(e,t){return e.graceType!==m.BendGrace&&(!e.deadSlapped&&(!!t.hasBeatLineX(e)&&((e.graceType===m.None||this.settings.notation.notationMode!==T.SongBook)&&(e.duration!==p.Whole&&e.duration!==p.DoubleWhole&&e.duration!==p.QuadrupleWhole))))}paintFlag(e,t,s,i){for(const a of i.beats){if(!this.shouldPaintFlag(a,i))continue;let r=a.graceType!==m.None,n=r?Qa.GraceScale:1,o=this.getFlagStemSize(i.shortestDuration),h=i.getBeatLineX(a),l=this.getBeamDirection(i),d=this.getFlagTopY(a,l),c=this.getFlagBottomY(a,l),u=0;if(l===Ge.Down?(c+=o*n,u=c):(d-=o*n,u=d),i.hasLine(!0,a)){if(this.paintBeamingStem(a,t+this.y,e+this.x+h,t+this.y+d,t+this.y+c,s),a.graceType===m.BeforeBeat){let i=15,a=12;s.beginPath(),l===Ge.Down?(s.moveTo(e+this.x+h-a/2,t+this.y+c-i),s.lineTo(e+this.x+h+a/2,t+this.y+c)):(s.moveTo(e+this.x+h-a/2,t+this.y+d+i),s.lineTo(e+this.x+h+a/2,t+this.y+d)),s.stroke()}if(i.hasFlag(!0,a)){let i=new $a(h-.5,u,a.duration,l,r);i.renderer=this,i.doLayout(),i.paint(e+this.x,t+this.y,s)}}}}getFlagStemSize(e,t=!1){let s=0;switch(e){case p.QuadrupleWhole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:case p.ThirtySecond:case p.SixtyFourth:case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:s=3;break;default:s=t?3:0}return this.getLineHeight(s)}recreatePreBeatGlyphs(){this._startSpacing=!1,super.recreatePreBeatGlyphs()}calculateBeamY(e,t){return this.calculateBeamYWithDirection(e,t,this.getBeamDirection(e))}createPreBeatGlyphs(){super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Zo(0,0,1.5,3)),this.createLinePreBeatGlyphs(),this.addPreBeatGlyph(new ih(0,this.getLineHeight(-.25),this.bar.index+1))}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new th(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new sh(0,this.getLineHeight(-.25),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new eh(0,0))}paintBar(e,t,s,i){for(let a=0,r=i.beats.length;a<r;a++){let r=i.beats[a];if(!i.hasBeatLineX(r)||r.deadSlapped)continue;let n=r.graceType!==m.None?Qa.GraceScale:1,o=i.getBeatLineX(r),h=this.getBeamDirection(i),l=t+this.y+this.getBarLineStart(r,h),d=t+this.y+this.calculateBeamY(i,o);this.paintBeamingStem(r,t+this.y,e+this.x+o,l,d,s);let c=d;h===Ge.Down?c+=2*s.font.size:0!==a&&(c-=1.5*s.font.size);let u=6*n,p=(tn.BeamSpacing+tn.BeamThickness)*n,g=tn.BeamThickness*n,f=le.getIndex(r.duration)-2,y=t+this.y;h===Ge.Down&&(p=-p,g=-g);for(let t=0;t<f;t++){let n=0,h=0,l=0,d=0,c=y+t*p;if(a<i.beats.length-1){const p=Dr.isFullBarJoin(r,i.beats[a+1],t);if(t===f-1&&p&&r.beamingMode===G.ForceSplitOnSecondaryToNext)n=o,h=n+u,l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),ah.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g),h=i.getBeatLineX(i.beats[a+1]),n=h-u,l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),ah.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g);else{if(p)n=o,h=i.getBeatLineX(i.beats[a+1]);else{if(0!==a&&Dr.isFullBarJoin(i.beats[a-1],r,t))continue;n=o,h=n+u}l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),ah.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g)}}else a>0&&!Dr.isFullBarJoin(r,i.beats[a-1],t)&&(n=o-u,h=o,l=c+this.calculateBeamY(i,n),d=c+this.calculateBeamY(i,h),ah.paintSingleBar(s,e+this.x+n,l,e+this.x+h,d,g))}}}static paintSingleBar(e,t,s,i,a,r){e.beginPath(),e.moveTo(t,s),e.lineTo(i,a),e.lineTo(i,a+r),e.lineTo(t,s+r),e.closePath(),e.fill()}}class rh extends ah{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.beatEffectsMinY=null,this.beatEffectsMaxY=null,this.accidentalHelper=new Cr(this)}get lineSpacing(){return tn.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return this.bar.staff.standardNotationLineCount}registerBeatEffectOverflows(e,t){const s=this.beatEffectsMinY;(null==s||e<s)&&(this.beatEffectsMinY=e);const i=this.beatEffectsMaxY;(null==i||t>i)&&(this.beatEffectsMaxY=t)}getScoreY(e){return super.getLineY(e/2)}getScoreHeight(e){return super.getLineHeight(e/2)}doLayout(){if(super.doLayout(),!this.bar.isEmpty&&this.accidentalHelper.maxLineBeat){let e=this.getScoreY(-2),t=this.getScoreY(10),s=this.simpleWhammyOverflow;const i=this.beatEffectsMinY;if(null!==i){const t=e-i;t>0&&this.registerOverflowTop(t)}const a=this.beatEffectsMaxY;if(null!==a){const e=a-t;e>0&&this.registerOverflowBottom(e)}this.registerOverflowTop(s);let r=this.getScoreY(this.accidentalHelper.maxLine),n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);n.direction===Ge.Up&&(r-=this.getStemSize(n),n.hasTuplet&&(r-=this.tupletSize)),r<e&&this.registerOverflowTop(Math.abs(r)+s);let o=this.getScoreY(this.accidentalHelper.minLine),h=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);h.direction===Ge.Down&&(o+=this.getStemSize(h),h.hasTuplet&&(o+=this.tupletSize)),o>t&&this.registerOverflowBottom(Math.abs(o)-t)}}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s),this.paintTuplets(e,t,s)}getSlashFlagY(e,t){let s=(this.heightLineCount-1)/2,i=0;switch(e){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:i+=2;break;default:i+=1}t==Ge.Down?s+=i:s-=i;return this.getLineY(s)}getFlagTopY(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):this.getScoreY(this.accidentalHelper.getMinLine(e))}getFlagBottomY(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):this.getScoreY(this.accidentalHelper.getMaxLine(e))}getBeamDirection(e){return e.direction}getStemSize(e,t=!1){let s=1===e.beats.length?this.getFlagStemSize(e.shortestDuration,t):this.getBarStemSize(e.shortestDuration);return e.isGrace&&(s*=Qa.GraceScale),s}getBarStemSize(e){let t=0;switch(e){case p.QuadrupleWhole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:t=6;break;case p.ThirtySecond:t=8;break;case p.SixtyFourth:case p.OneHundredTwentyEighth:t=9;break;case p.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){if(e.beat.slashed){let e=(this.heightLineCount-1)/2;return this.getLineY(e)}let s=super.getNoteY(e,t);if(isNaN(s)){const t=Cr.computeLineWithoutAccidentals(this.bar,e);s=this.getScoreY(t)}return s}applyLayoutingInfo(){const e=super.applyLayoutingInfo();if(e&&this.bar.isMultiVoice){let e=this.getScoreY(-2),t=this.getScoreY(10),s=this.helpers.collisionHelper.getBeatMinMaxY();s[0]<e&&this.registerOverflowTop(Math.abs(s[0])),s[1]>t&&this.registerOverflowBottom(Math.abs(s[1])-t)}return e}calculateBeamYWithDirection(e,t,s){let i=this.getStemSize(e);if(!e.drawingInfos.has(s)){let t=new Fr;e.drawingInfos.set(s,t);const a=e.beats[0],r=e.beats[e.beats.length-1],n=e.isRestBeamHelper;t.startBeat=a,t.startX=e.getBeatLineX(a),t.startY=n?s===Ge.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===Ge.Up?this.getFlagTopY(a,s)-i:this.getFlagBottomY(a,s)+i,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?s===Ge.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===Ge.Up?this.getFlagTopY(r,s)-i:this.getFlagBottomY(r,s)+i;let o=10;if(s===Ge.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),s===Ge.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),s===Ge.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),s===Ge.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(s===Ge.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=le.getIndex(e.shortestDuration)-2;let a=e.isGrace?Qa.GraceScale:1,r=i*(tn.BeamSpacing+tn.BeamThickness)*a;if(r+=tn.BeamSpacing,s===Ge.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===Ge.Down&&null!==e.maxRestLine){const s=this.getScoreY(e.maxRestLine)+r-t.calcY(e.getBeatLineX(e.beatOfMaxRestLine));s>0&&(t.startY+=s,t.endY+=s)}}if(e.slashBeats.length>0)for(const a of e.slashBeats){const r=t.calcY(e.getBeatLineX(a));let n=this.getSlashFlagY(a.duration,s);s===Ge.Up?n-=i:s===Ge.Down&&(n+=i);const o=n-r;o>0&&(t.startY+=o,t.endY+=o)}}}return e.drawingInfos.get(s).calcY(t)}getBarLineStart(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):t===Ge.Up?this.getScoreY(this.accidentalHelper.getMaxLine(e)):this.getScoreY(this.accidentalHelper.getMinLine(e))}createLinePreBeatGlyphs(){if(this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let e=0;switch(this.bar.clef){case 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 oo(0,this.getScoreY(e)+.5*tn.StaffLineThickness,this.bar.clef,this.bar.clefOttava))}(0===this.index&&this.bar.masterBar.keySignature!==v.C||this.bar.previousBar&&this.bar.masterBar.keySignature!==this.bar.previousBar.masterBar.keySignature)&&(this.createStartSpacing(),this.createKeySignatureGlyphs()),(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createKeySignatureGlyphs(){let e=0,t=this.bar.masterBar.keySignature,s=this.bar.previousBar?this.bar.previousBar.masterBar.keySignature:0;switch(this.bar.clef){case 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(le.keySignatureIsSharp(t))for(let s=0;s<Math.abs(t);s++){let t=rh.SharpKsSteps[s]+e;a.push(new no(0,this.getScoreY(t),Xe.Sharp,1)),i.set(t,!0)}else for(let s=0;s<Math.abs(t);s++){let t=rh.FlatKsSteps[s]+e;a.push(new no(0,this.getScoreY(t),Xe.Flat,1)),i.set(t,!0)}if(this.bar.masterBar.keySignature===v.C){let t=Math.abs(s),a=le.keySignatureIsSharp(s)?rh.SharpKsSteps:rh.FlatKsSteps;for(let s=0;s<t;s++){let t=a[s]+e;i.has(t)||this.addPreBeatGlyph(new no(0,this.getScoreY(a[s]+e),Xe.Natural,1))}}for(let e of a)this.addPreBeatGlyph(e)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Fo(0,0,5));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new Jo(0,this.getScoreY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon,this.bar.masterBar.isFreeTime))}createVoiceGlyphs(e){for(const t of e.beats){let s=new $o(t,this.getVoiceContainer(e));s.preNotes=new Wo,s.onNotes=new Ro,this.addBeatGlyph(s)}}getNoteLine(e){return this.accidentalHelper.getNoteLine(e)}completeBeamingHelper(e){if(this.bar.isMultiVoice&&e.highestNoteInHelper&&e.lowestNoteInHelper){let t=this.getNoteY(e.highestNoteInHelper,zs.Center),s=this.getNoteY(e.lowestNoteInHelper,zs.Center),i=this.getStemSize(e);e.hasTuplet&&(i+=2*this.resources.effectFont.size),e.direction==Ge.Up?t-=i:s+=i;for(const i of e.beats)this.helpers.collisionHelper.reserveBeatSlot(i,t,s)}}paintBeamingStem(e,t,s,i,a,r){r.lineWidth=tn.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}}rh.StaffId="score",rh.SharpKsSteps=[-1,2,-2,1,4,0,3],rh.FlatKsSteps=[3,0,4,1,5,2,6];class nh extends Tr{get staffId(){return rh.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new rh(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showStandardNotation}constructor(){super()}}class oh extends qa{constructor(e,t,s,i){super(0,0),this._inType=e,this._outType=t,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.paintSlideOut(e,t,s)}paintSlideIn(e,t,s){let i=this.renderer,a=0,r=0,n=0,o=0;switch(this._inType){case S.IntoFromBelow:n=e+i.x+i.getNoteX(this._startNote,Us.Left)-2,o=t+i.y+i.getNoteY(this._startNote,zs.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,zs.Center)+3;break;case S.IntoFromAbove:n=e+i.x+i.getNoteX(this._startNote,Us.Left)-2,o=t+i.y+i.getNoteY(this._startNote,zs.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,zs.Center)-3;break;default:return}this.paintSlideLine(s,!1,a,n,r,o)}paintSlideOut(e,t,s){let i=this.renderer,a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case _.Shift:case _.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,Gs.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,zs.Center),this._startNote.slideTarget){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,Gs.OnNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,zs.Center)):(n=e+i.x+i.width,o=r),this._startNote.slideTarget.fret>this._startNote.fret?(r+=3,o-=3):(r-=3,o+=3)}else n=e+i.x+this._parent.x,o=r;break;case _.OutUp:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+2,r=t+i.y+i.getNoteY(this._startNote,zs.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,zs.Center)-3;break;case _.OutDown:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+2,r=t+i.y+i.getNoteY(this._startNote,zs.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,zs.Center)+3;break;case _.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+4,r=t+i.y+i.getNoteY(this._startNote,zs.Center),n=e+i.x+i.width,o=r+9,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Gs.PreNotes)),h=!0;break;case _.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,Us.Right)+4,r=t+i.y+i.getNoteY(this._startNote,zs.Center),n=e+i.x+i.width,o=r-9,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Gs.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new Gn(0,0,w.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 hh extends po{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?Ge.Up:hh.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?Ge.Up:Ge.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,zs.Center):this.tieDirection===Ge.Up?this.startNoteRenderer.getNoteY(this.startNote,zs.Top):this.startNoteRenderer.getNoteY(this.startNote,zs.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Us.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,Us.Left):this.endNoteRenderer.getNoteX(this.endNote,Us.Center)}}class lh extends hh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=hh.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!==hh.getBeamDirectionForNote(e))return!1;switch(this._direction){case Ge.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 Ge.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 dh extends Za{constructor(e,t){super(e,t),this._bend=null,this._effectSlurs=[]}drawBeamHelperAsFlags(e){return e.hasFlag(this.renderer.drawBeamHelperAsFlags(e),this.beat)}doLayout(){this._effectSlurs=[],super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(!e.isVisible)return;let t=this.renderer;if(e.isTieOrigin&&t.showTiedNotes&&e.tieDestination.isVisible){let t=new hh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){let t=new hh(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new hh(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 lh(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 lh(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==S.None||e.slideOutType!==_.None){let t=new oh(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new Po;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class ch extends qa{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===y.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===d.Bend||e.bendType===d.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(x.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===y.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(le.isAlmostEqualTo(e.harmonicValue,0))this._trillNoteString="";else switch(e.harmonicType){case y.Artificial:case y.Pinch:case y.Tap:case y.Semi:case y.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).width,this.width=this.noteStringWidth,this.height=this.renderer.scoreRenderer.canvas.font.size,!!this._trillNoteString&&(this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,this._trillNoteStringWidth=3+this.renderer.scoreRenderer.canvas.measureText(this._trillNoteString).width,this.width+=this._trillNoteStringWidth)}}paint(e,t,s){if(this.isEmpty)return;let i=this.noteStringWidth+this._trillNoteStringWidth,a=e+this.x+(this.width-i)/2,r=this.renderer.scoreRenderer.canvas.font;this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,s.fillText(this._trillNoteString,a+this.noteStringWidth+3,t+this.y),this.renderer.scoreRenderer.canvas.font=r,s.fillText(this._noteString,a,t+this.y)}buildBoundingsLookup(e,t,s){let i=new Pa;i.note=this._note,i.noteHeadBounds=new ds,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 uh extends qa{constructor(e,t,s){super(e,t),this._notes=[],this._deadSlapped=null,this.minStringNote=null,this.beatEffects=new Map,this.notesPerString=new Map,this.noteStringWidth=0,this._isGrace=s}buildBoundingsLookup(e,t,s){for(const i of this._notes)i.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteX(e,t){if(this.notesPerString.has(e.string)){let s=this.notesPerString.get(e.string),i=this.x+s.x;switch(t){case Us.Left:break;case Us.Center:i+=s.noteStringWidth/2;break;case Us.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 zs.Top:case zs.TopWithStem:i-=s.height/2+2;break;case zs.Center:break;case zs.Bottom:case zs.BottomWithStem:i+=s.height/2}return i}return 0}doLayout(){let e=0;if(this.beat.deadSlapped)this._deadSlapped=new _o,this._deadSlapped.renderer=this.renderer,this._deadSlapped.doLayout(),e=this._deadSlapped.width,this.noteStringWidth=e;else{let t=0;for(let s=0,i=this._notes.length;s<i;s++){let i=this._notes[s];i.renderer=this.renderer,i.doLayout(),i.width>e&&(e=i.width),i.noteStringWidth>t&&(t=i.noteStringWidth)}this.noteStringWidth=t;let s=this.renderer.resources.tablatureFont.size,i=this.getNoteY(this.minStringNote,zs.Center)+s/2,a=7;for(const e of this.beatEffects.values())e.y+=i,e.x+=this.width/2,e.renderer=this.renderer,i+=a,e.doLayout()}this.width=e}addNoteGlyph(e,t){this._notes.push(e),this.notesPerString.set(t.string,e),(!this.minStringNote||t.string<this.minStringNote.string)&&(this.minStringNote=t)}paint(e,t,s){if(e+=this.x,t+=this.y,this.beat.deadSlapped)this._deadSlapped?.paint(e,t,s);else{let i=this.renderer.resources,a=s.textBaseline;s.textBaseline=L.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 ph extends Ka{constructor(e,t,s,i){super(e,t,1,Bo.getSymbol(i)),this._isVisibleRest=s,this._duration=i}doLayout(){this._isVisibleRest?this.width=Bo.getSize(this._duration):this.width=10}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){this._isVisibleRest&&super.paint(e,t,s)}}class gh extends hn{constructor(){super(...arguments),this.slash=null,this.noteNumbers=null,this.restGlyph=null}getNoteX(e,t){return this.noteNumbers?this.noteNumbers.getNoteX(e,t):0}getNoteY(e,t){return this.noteNumbers?this.noteNumbers.getNoteY(e,t):0}buildBoundingsLookup(e,t,s){this.noteNumbers&&this.noteNumbers.buildBoundingsLookup(e,t+this.x,s+this.y)}doLayout(){let 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 ph(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 Fo(0,0,5));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new lo(0,s,1.5))}}else{let t,s=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==m.None;if(this.container.beat.slashed&&!this.container.beat.notes.some((e=>e.isTieDestination))){const i=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),a=e.getLineY(i),r=new Oo(0,a,this.container.beat.duration,s);this.slash=r,r.beat=this.container.beat,r.beamingHelper=this.beamingHelper,this.addGlyph(r),t=r.beatEffects}else{const e=new uh(0,0,s);this.noteNumbers=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;for(let e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);this.addGlyph(e),t=e.beatEffects}if(this.container.beat.hasWhammyBar){let e=new Co(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!t.has("tremolo")){let e=0,s=this.container.beat.tremoloSpeed,i=5;switch(s){case p.ThirtySecond:e=10;break;case p.Sixteenth:e=5;break;case p.Eighth:e=0}this.container.beat.duration<p.Half&&(i=0),t.set("tremolo",new So(i,e,s))}if(this.container.beat.dots>0&&e.rhythmMode!==B.Hidden){this.addGlyph(new Fo(0,0,5));for(let t=0;t<this.container.beat.dots;t++)this.addGlyph(new lo(0,e.lineOffset*e.bar.staff.tuning.length+e.settings.notation.rhythmHeight,1.5))}}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.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteNumbers?this.centerX=this.noteNumbers.x+this.noteNumbers.noteStringWidth/2:this.slash&&(this.centerX=this.slash.x+this.slash.width/2)}updateBeamingHelper(){this.noteNumbers?this.noteNumbers.updateBeamingHelper(this.container.x+this.x):this.restGlyph?this.restGlyph.updateBeamingHelper(this.container.x+this.x):this.slash&&this.slash.updateBeamingHelper(this.container.x+this.x)}createNoteGlyph(e){let t=this.renderer,s=new ch(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 mh extends qa{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10}paint(e,t,s){let i=this.renderer,a=t+this.x+i.getNoteY(this._beat.maxStringNote,zs.Top),r=t+this.y+i.getNoteY(this._beat.minStringNote,zs.Bottom),n=e+this.x+this.width/2|0;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 Gn(0,0,w.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let i=a,n=r-8;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4,n,-90),t.paint(0,-t.height/2,s),s.endRotate()}else if(this._beat.brushType===c.ArpeggioDown){let t=new Gn(0,0,w.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let i=a+8,n=r;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4,i,90),t.paint(0,-t.height/2,s),s.endRotate()}this._beat.brushType===c.BrushUp||this._beat.brushType===c.ArpeggioUp?(s.beginPath(),s.moveTo(n,r),s.lineTo(n+4,r-8),s.lineTo(n-4,r-8),s.closePath(),s.fill()):(s.beginPath(),s.moveTo(n,a),s.lineTo(n+4,a+8),s.lineTo(n-4,a+8),s.closePath(),s.fill())}}}class fh extends on{doLayout(){this.container.beat.brushType===c.None||this.container.beat.isRest||(this.addGlyph(new mh(this.container.beat)),this.addGlyph(new Fo(0,0,4))),super.doLayout()}constructor(){super()}}class yh extends qa{constructor(e,t){super(e,t)}doLayout(){this.width=28}paint(e,t,s){let i=this.renderer.bar.staff.tuning.length,a=i<=4?F.FourStringTabClef:F.SixStringTabClef,r=i<=4?i/4.5:i/6.5;s.fillMusicFontSymbol(e+this.x+5,t+this.y,r,a,!1)}}class bh extends Xo{get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?Qa.GraceScale:1}}class Sh extends ah{constructor(e,t){super(e,t),this._hasTuplets=!1,this.showTimeSignature=!1,this.showRests=!1,this.showTiedNotes=!1,t.staff.showStandardNotation||(this.showTimeSignature=!0,this.showRests=!0,this.showTiedNotes=!0)}get lineSpacing(){return Sh.TabLineSpacing}get heightLineCount(){return this.bar.staff.tuning.length}get drawnLineCount(){return this.bar.staff.tuning.length}get rhythmMode(){let e=this.settings.notation.rhythmMode;return e===B.Automatic&&(e=this.bar.staff.showStandardNotation?B.Hidden:B.ShowWithBars),e}getTabY(e){return super.getLineY(e)}getTabHeight(e){return super.getLineHeight(e)}collectSpaces(e){for(let t of this.bar.voices)if(this.hasVoiceContainer(t)){let s=this.getVoiceContainer(t);for(let t of s.beatGlyphs){let i=t.onNotes,a=i.noteNumbers;if(a)for(const[r,n]of a.notesPerString)n.isEmpty||e[this.bar.staff.tuning.length-r].push(new Float32Array([s.x+t.x+i.x+a.x,a.width+1]))}}}adjustSizes(){this.rhythmMode!==B.Hidden&&(this.height+=this.settings.notation.rhythmHeight,this.bottomPadding+=this.settings.notation.rhythmHeight)}doLayout(){if(super.doLayout(),this.rhythmMode!==B.Hidden){this._hasTuplets=!1;for(let e of this.bar.voices)if(this.hasVoiceContainer(e)){if(this.getVoiceContainer(e).tupletGroups.length>0){this._hasTuplets=!0;break}}this._hasTuplets&&this.registerOverflowBottom(this.tupletSize)}}createLinePreBeatGlyphs(){if(this.isFirstOfLine){let e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new yh(5,this.getTabY(e)))}this.showTimeSignature&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Fo(0,0,5));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new bh(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon,this.bar.masterBar.isFreeTime))}createVoiceGlyphs(e){for(const t of e.beats){let s=new dh(t,this.getVoiceContainer(e));s.preNotes=new fh,s.onNotes=new gh,this.addBeatGlyph(s)}}paint(e,t,s){super.paint(e,t,s),this.rhythmMode!==B.Hidden&&(this.paintBeams(e,t,s),this.paintTuplets(e,t,s))}drawBeamHelperAsFlags(e){return super.drawBeamHelperAsFlags(e)||this.rhythmMode===B.ShowWithBeams}getFlagTopY(e,t){const s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==p.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,zs.Bottom):this.height-this.settings.notation.rhythmHeight-this.tupletSize}getFlagBottomY(e,t){return this.getFlagAndBarPos()}getFlagStemSize(e,t=!1){return 0}getBarLineStart(e,t){let s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==p.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,zs.Bottom)+this.lineOffset/2:this.height-this.settings.notation.rhythmHeight-this.tupletSize}getBeamDirection(e){return Ge.Down}getFlagAndBarPos(){return this.height-(this._hasTuplets?this.tupletSize/2:0)}calculateBeamYWithDirection(e,t,s){return this.getFlagAndBarPos()}shouldPaintFlag(e,t){return!!super.shouldPaintFlag(e,t)&&(e.graceType===m.None&&this.drawBeamHelperAsFlags(t))}paintBeamingStem(e,t,s,i,a,r){if(a<i){const e=a;a=i,i=e}r.lineWidth=tn.StemWidth,r.beginPath();let n=[];this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.has(e.displayStart)&&(n=this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.get(e.displayStart).slots.slice(),n.sort(((e,t)=>e.topY-t.topY)));let o=a;for(;o>i;){r.moveTo(s,o);let e=i;if(!(n.length>0&&n[n.length-1].bottomY>e)){r.lineTo(s,e);break}{const i=n.pop();e=t+i.bottomY,r.lineTo(s,e),o=t+i.topY}}r.stroke(),r.lineWidth=1}}Sh.StaffId="tab",Sh.TabLineSpacing=10;class _h extends Tr{get staffId(){return Sh.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}constructor(){super(),this.showTimeSignature=null,this.showRests=null,this.showTiedNotes=null,this.hideOnPercussionTrack=!0}canCreate(e,t){return t.showTablature&&t.tuning.length>0&&super.canCreate(e,t)}create(e,t){let s=new Sh(e,t);return null!==this.showRests&&(s.showRests=this.showRests),null!==this.showTimeSignature&&(s.showTimeSignature=this.showTimeSignature),null!==this.showTiedNotes&&(s.showTiedNotes=this.showTiedNotes),s}}class wh extends ja{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+wh.Padding}paint(e,t,s){let i=this.renderer.resources;s.font=i.effectFont;let a=s.textAlign;s.textAlign=D.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+(wh.Padding-1),s.font.size/1.6)}}wh.Padding=4;class Bh extends Nn{get notationElement(){return x.EffectTap}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new wh}}class kh{constructor(){this.noteRange=1,this.x=0,this.y=0}}!function(e){e[e.None=0]="None",e[e.Rectangle=1]="Rectangle",e[e.Ellipse=2]="Ellipse",e[e.Circle=3]="Circle"}(Xn||(Xn={}));class Th extends kh{constructor(){super(...arguments),this.align=D.Left,this.frame=Xn.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class xh extends kh{constructor(){super(...arguments),this.chord=new Be}}class Nh extends kh{}class vh extends kh{}class Ph extends kh{constructor(){super(...arguments),this.number=0}}class Ch extends kh{constructor(){super(...arguments),this.decrescendo=!1}}class Eh extends kh{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class Fh extends kh{constructor(){super(...arguments),this.octave=1}}class Dh extends kh{}class Lh{constructor(){this.defaultClef=r.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class Mh{constructor(){this.from=0,this.to=0,this.curly=!1}}class Ih{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class Ah{constructor(){this._trackChannel=0,this._beamingMode=G.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new ne,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 fs;try{s.parse(e)}catch(e){throw new K("Could not parse XML",e)}this.parseDom(s),this.consolidate(),this.score.finish(t)}consolidate(){for(const e of this.score.tracks){const t=this._voiceCounts.get(e.index);for(const s of e.staves){for(;s.bars.length<this.score.masterBars.length;)this.addNewBar(s);for(const e of s.bars){for(;e.voices.length<t;)e.addVoice(new Me);for(const t of e.voices)if(0===t.beats.length){const e=new we;e.isEmpty=!0,t.addBeat(e)}}}}Ah.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),Ah.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?u.Decrescendo:u.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 K("No valid XML");if("score"!==t.localName)throw new K('Root node of XML was not "score"');this.score=new Ne,this.score.tempo=120;for(let e of t.childNodes)if(e.nodeType===as.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===as.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 Le,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===as.Element&&"bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new Mh;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===as.Element&&"staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new Lh;t.description=e.getAttribute("description");for(let s of e.childNodes)if(s.nodeType===as.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===as.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=G.ForceSplitToNext);for(let t of e.childNodes)if(t.nodeType===as.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===as.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===as.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===as.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 Z;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 ne;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 Ih,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=Ge.Up;break;case"down":this._currentVoiceState.voiceStemDir=Ge.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const h=n.findChildElement("noteObjects");if(s.attributes.has("tempo")){const e=new Q;e.isLinear=!0,e.type=a.Tempo,e.value=parseInt(s.attributes.get("tempo")),e.ratioPosition=this._currentVoiceState.currentPosition/this._currentVoiceState.currentBarDuration,this._currentBar.masterBar.tempoAutomations.push(e)}if(h)for(let e of h.childNodes)if(e.nodeType===as.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 we;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 Me);(!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 ge;for(let a of t.childNodes)if(a.nodeType===as.Element)switch(a.localName){case"stem":switch(a.getAttribute("dir")){case"up":e.preferredBeamDirection=Ge.Up;break;case"down":e.preferredBeamDirection=Ge.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=G.ForceMergeWithNext;break;case"divide":e.beamingMode=G.ForceSplitToNext}}}parseHeads(e,t,s){for(let i of s.childNodes)if(i.nodeType===as.Element&&"head"===i.localName)this.parseHead(e,t,i)}parseHead(e,t,s){const i=new ge,a=le.parseTuning(s.getAttribute("pitch"));i.octave=a.octave-1,i.tone=a.tone.noteValue,i.isStaccato=t.isStaccato,i.accentuated=t.accentuated,e.addNote(i);for(let e of s.childNodes)if(e.nodeType===as.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===as.Element&&"drawObj"===s.localName){const t=this.parseDrawObj(s);if(t)if(t instanceof Th)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new Ze,e.fermata.type=He.Medium):"f"===t.text?e.dynamics=g.F:"j"===t.text&&(e.dynamics=g.MF):this._isFirstSystem&&""===this.score.title&&t.align===D.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===D.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===D.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof xh);else if(t instanceof vh)e.vibrato=w.Slight;else if(t instanceof Ch)e.crescendo=t.decrescendo?u.Decrescendo:u.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof Nh){const s=t;this._slurs.set(e,s)}else t instanceof Eh&&this.applyVolta(t)}}parseBarDrawObject(e){for(let t of e.childNodes)if(t.nodeType===as.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof Eh&&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===as.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 we;return s.beamingMode=this._beamingMode,this.parseDuration(e,s,t),s}if(1===parseInt(s)){let e=new we;return e.beamingMode=this._beamingMode,e.duration=p.Whole,e}return re.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return p.DoubleWhole;case"1/1":return p.Whole;case"1/2":return p.Half;case"1/4":return p.Quarter;case"1/8":return p.Eighth;case"1/16":return p.Sixteenth;case"1/32":return p.ThirtySecond;case"1/64":return p.SixtyFourth;case"1/128":return p.OneHundredTwentyEighth;default:return re.warning("Importer","Unsupported duration"),p.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===as.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof Th)switch(e.align){case D.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case D.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(let t of e.childNodes)if(t.nodeType===as.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===as.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 Dh}parseOctaveClef(e){const t=new Fh;return e.attributes.has("octave")&&(t.octave=parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new Eh;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 Ch;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new Ph;return e.attributes.has("number")&&(t.number=parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new vh}parseSlur(e){return new Nh}parseGuitar(e){const t=new xh,s=e.innerText.trim();for(let e=0;e<s.length;e++)"/"===s.charAt(e)?t.chord.strings.push(0):t.chord.strings.push(parseInt(s.charAt(e)));return t}parseText(e){const t=new Th;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=D.Left;break;case"center":t.align=D.Center;break;case"right":t.align=D.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=Xn.Rectangle;break;case"ellipse":t.frame=Xn.Ellipse;break;case"circle":t.frame=Xn.Circle;break;case"none":t.frame=Xn.None}if(e.firstElement){for(let s of e.childNodes)if(s.nodeType===as.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===as.Element)switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class Oh extends q{get name(){return"Capella"}constructor(){super()}readScore(){re.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new js(this.data).read(),re.debug(this.name,"Zip entries loaded"),e.length>0){for(let s of e)if("score.xml"===s.fileName)t=Ae.toString(s.data,this.settings.importer.encoding)}else this.data.reset(),t=Ae.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new K("No valid capella file");re.debug(this.name,"Start Parsing score.xml");try{let e=new Ah;return e.parseXml(t,this.settings),re.debug(this.name,"score.xml parsed"),e.score}catch(e){throw new K("Failed to parse CapXML",e)}}}class Rh{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 Vh{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 Hh(e,t,s){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var i,a;if(s){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=t[Symbol.asyncDispose]}if(void 0===i){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=t[Symbol.dispose],s&&(a=i)}if("function"!=typeof i)throw new TypeError("Object not disposable.");a&&(i=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:i,async:s})}else s&&e.stack.push({async:!0});return t}var Gh="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 Wh(e){function t(t){e.error=e.hasError?new Gh(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var s,i=0;return function a(){for(;s=e.stack.pop();)try{if(!s.async&&1===i)return i=0,e.stack.push(s),Promise.resolve().then(a);if(s.dispose){var r=s.dispose.call(s.value);if(s.async)return i|=2,Promise.resolve(r).then(a,(function(e){return t(e),a()}))}else i|=1}catch(e){t(e)}if(1===i)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}class zh{static enable(e,t){zh.alphaSkia=t,zh.initializeMusicFont(zh.alphaSkia.AlphaSkiaTypeface.register(e))}static initializeMusicFont(e){zh.musicFont=e}static registerFont(e,t){const s=zh.alphaSkia.AlphaSkiaTypeface.register(e.buffer);t||(t=rt.withFamilyList([s.familyName],12,s.isItalic?Je.Italic:Je.Plain,s.isBold?Ye.Bold:Ye.Regular));for(const e of t.families)this.customTypeFaces.set(zh.customTypefaceKey(e,t.isBold,t.isItalic),s);return t}static customTypefaceKey(e,t,s){return e.toLowerCase()+"_"+t+"_"+s}getTypeFace(){if(this._typeFaceCache!=this.font.toCssString(this._scale)){if(this._typeFaceIsSystem){const e={stack:[],error:void 0,hasError:!1};try{Hh(e,this._typeFace,!1)}catch(t){e.error=t,e.hasError=!0}finally{Wh(e)}}for(const t of this.font.families){var e=zh.customTypefaceKey(t,this.font.isBold,this.font.isItalic);zh.customTypeFaces.has(e)?(this._typeFaceIsSystem=!1,this._typeFace=zh.customTypeFaces.get(e)):(this._typeFaceIsSystem=!0,this._typeFace=zh.alphaSkia.AlphaSkiaTypeface.create(t,this.font.isBold,this.font.isItalic))}this._typeFaceCache=this.font.toCssString(this._scale)}return this._typeFace}constructor(){this._color=new Ce(0,0,0,0),this._lineWidth=0,this._typeFaceCache="",this._typeFaceIsSystem=!1,this._typeFace=null,this._scale=1,this.font=new rt("Arial",10,Je.Plain),this.textAlign=D.Left,this.textBaseline=L.Top,this._initialMeasure=!0,this._canvas=new zh.alphaSkia.AlphaSkiaCanvas,this.color=new Ce(0,0,0,255)}destroy(){const e={stack:[],error:void 0,hasError:!1};try{Hh(e,this._canvas,!1)}catch(t){e.error=t,e.hasError=!0}finally{Wh(e)}}onRenderFinished(){return null}beginRender(e,t){this._scale=this.settings.display.scale,this._canvas.beginRender(e,t,Tl.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=zh.alphaSkia.AlphaSkiaCanvas.rgbaToColor(e.r,e.g,e.b,e.a))}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._canvas.lineWidth=e}fillRect(e,t,s,i){s>0&&this._canvas.fillRect(e*this._scale|0,t*this._scale|0,s*this._scale,i*this._scale)}strokeRect(e,t,s,i){const a=this.lineWidth%2==0?0:.5;this._canvas.strokeRect((e*this._scale|0)+a,(t*this._scale|0)+a,s*this._scale,i*this._scale)}beginPath(){this._canvas.beginPath()}closePath(){this._canvas.closePath()}moveTo(e,t){this._canvas.moveTo(e*this._scale,t*this._scale)}lineTo(e,t){this._canvas.lineTo(e*this._scale,t*this._scale)}quadraticCurveTo(e,t,s,i){this._canvas.quadraticCurveTo(e*this._scale,t*this._scale,s*this._scale,i*this._scale)}bezierCurveTo(e,t,s,i,a,r){this._canvas.bezierCurveTo(e*this._scale,t*this._scale,s*this._scale,i*this._scale,a*this._scale,r*this._scale)}fillCircle(e,t,s){this._canvas.fillCircle(e*this._scale,t*this._scale,s*this._scale)}strokeCircle(e,t,s){this._canvas.strokeCircle(e*this._scale,t*this._scale,s*this._scale)}fill(){this._canvas.fill()}stroke(){this._canvas.stroke()}beginGroup(e){}endGroup(){}fillText(e,t,s){if(0==e.length)return;let i=zh.alphaSkia.AlphaSkiaTextAlign.Left;switch(this.textAlign){case D.Left:i=zh.alphaSkia.AlphaSkiaTextAlign.Left;break;case D.Center:i=zh.alphaSkia.AlphaSkiaTextAlign.Center;break;case D.Right:i=zh.alphaSkia.AlphaSkiaTextAlign.Right}let a=zh.alphaSkia.AlphaSkiaTextBaseline.Top;switch(this.textBaseline){case L.Top:a=zh.alphaSkia.AlphaSkiaTextBaseline.Top;break;case L.Middle:a=zh.alphaSkia.AlphaSkiaTextBaseline.Middle;break;case L.Bottom:a=zh.alphaSkia.AlphaSkiaTextBaseline.Bottom}this._canvas.fillText(e,this.getTypeFace(),this.font.size*this._scale,t*this._scale,s*this._scale,i,a)}measureText(e){return this._initialMeasure&&(this._canvas.measureText(e,this.getTypeFace(),this.font.size*this._scale),this._initialMeasure=!1),new de(this._canvas.measureText(e,this.getTypeFace(),this.font.size*this._scale),this.font.size*this._scale*zh.FontSizeToLineHeight)}fillMusicFontSymbol(e,t,s,i,a){i!==F.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(let e of i)e!==F.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){this._canvas.fillText(i,zh.musicFont,Tl.MusicFontSize*this._scale*s,e*this._scale,t*this._scale,a?zh.alphaSkia.AlphaSkiaTextAlign.Center:zh.alphaSkia.AlphaSkiaTextAlign.Left,zh.alphaSkia.AlphaSkiaTextBaseline.Alphabetic)}beginRotate(e,t,s){this._canvas.beginRotate(e*this._scale,t*this._scale,s)}endRotate(){this._canvas.endRotate()}}zh.musicFont=null,zh.customTypeFaces=new Map,zh.FontSizeToLineHeight=1.2;class Uh extends po{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 Ge.Down}static getBeamDirectionForNote(e){return Ge.Down}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,zs.Center)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Us.Right)}getEndX(){return this.endNoteRenderer.getNoteX(this.endNote,Us.Left)}}class Xh extends Za{constructor(e,t){super(e,t),this._tiedNoteTie=null}createTies(e){if(e.isVisible){if(!this._tiedNoteTie&&e.isTieOrigin&&e.tieDestination.isVisible){let t=new Uh(e,e.tieDestination,!1);this._tiedNoteTie=t,this.addTie(t)}if(!this._tiedNoteTie&&e.isTieDestination){let t=new Uh(e.tieOrigin,e,!0);this._tiedNoteTie=t,this.addTie(t)}}}}class Jh extends Bo{constructor(e,t,s){super(e,t,s)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class Yh extends hn{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.restGlyph=null}getNoteX(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=s.x;switch(t){case Us.Left:break;case Us.Center:e+=s.width/2;break;case Us.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new Pa;i.note=this.container.beat.notes[0],i.noteHeadBounds=new ds,i.noteHeadBounds.x=t+this.x+this.noteHeads.x,i.noteHeadBounds.y=s+this.y+this.noteHeads.y-this.noteHeads.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}getNoteY(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=this.y+s.y;switch(t){case zs.Top:case zs.TopWithStem:e-=s.height/2+2;break;case zs.Center:break;case zs.Bottom:case zs.BottomWithStem:e+=s.height/2}return e}return 0}updateBeamingHelper(){this.noteHeads?this.noteHeads.updateBeamingHelper(this.container.x+this.x):this.deadSlapped?this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.container.beat,this.container.x+this.x+this.deadSlapped.x+this.width,this.container.x+this.x+this.deadSlapped.x):this.restGlyph&&this.restGlyph.updateBeamingHelper(this.container.x+this.x)}doLayout(){let e=this.renderer;const t=e.getNoteLine(),s=e.getLineY(t);if(this.container.beat.deadSlapped){const e=new _o;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addGlyph(e)}else if(!this.container.beat.isEmpty)if(this.container.beat.isRest){const e=new Jh(0,s,this.container.beat.duration);this.restGlyph=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper,this.addGlyph(e),this.beamingHelper&&this.beamingHelper.applyRest(this.container.beat,0)}else{const e=this.container.beat.graceType!==m.None,t=new Oo(0,s,this.container.beat.duration,e);this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper,this.addGlyph(t)}if(this.container.beat.dots>0){this.addGlyph(new Fo(0,0,5));for(let t=0;t<this.container.beat.dots;t++)this.addGlyph(new lo(0,e.getLineY(e.getNoteLine())-e.getLineHeight(.5),1.5))}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.deadSlapped&&(this.centerX=this.deadSlapped.x+this.deadSlapped.width/2)}}class qh extends ah{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._isOnlySlash=!t.staff.showTablature&&!t.staff.showStandardNotation,this.helpers.preferredBeamDirection=Ge.Up}get lineSpacing(){return tn.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return 1}get bottomGlyphOverflow(){return 0}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s),this.paintTuplets(e,t,s)}doLayout(){super.doLayout();let e=!1;for(let t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}e&&this.registerOverflowTop(this.tupletSize)}getNoteLine(){return 0}getFlagTopY(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}getFlagBottomY(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}getBeamDirection(e){return Ge.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return isNaN(s)&&(s=this.getLineY(0)),s}calculateBeamYWithDirection(e,t,s){return this.getLineY(0)-this.getFlagStemSize(e.shortestDuration)}getBarLineStart(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}createLinePreBeatGlyphs(){this._isOnlySlash&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Fo(0,0,5));const e=this.bar.masterBar;this.addPreBeatGlyph(new Jo(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime)))}createVoiceGlyphs(e){for(const t of e.beats){let s=new Xh(t,this.getVoiceContainer(e));s.preNotes=new on,s.onNotes=0==e.index?new Yh:new hn,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){r.lineWidth=tn.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}}qh.StaffId="slash";class jh extends Tr{get staffId(){return qh.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new qh(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showSlash}constructor(){super()}}class Kh extends po{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 Ge.Up}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,zs.Top)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Us.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,Us.Left):this.endNoteRenderer.getNoteX(this.endNote,Us.Center)}}class Qh extends hh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=Ge.Up,this._forSlide=s}getTieHeight(e,t,s,i){return Math.log(s-e+1)*this.renderer.settings.notation.slurHeight}tryExpand(e,t,s,i){if(this._forSlide!==s)return!1;if(this.forEnd!==i)return!1;if(this.startNote.beat.id!==e.beat.id)return!1;if(this.endNote.beat.id!==t.beat.id)return!1;switch(this._direction){case Ge.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 Ge.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,s){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar),a=this.getBeamDirection(this.startBeat,i),r="numbered.slur."+this.startNote.beat.id+"."+this.endNote.beat.id+"."+a,n=this.renderer;n.staff.getSharedLayoutData(r,!1)||(n.staff.setSharedLayoutData(r,!0),super.paint(e,t,s))}}class $h extends Za{constructor(e,t){super(e,t),this._effectSlurs=[]}createTies(e){if(e.isVisible){if(e.isTieOrigin&&e.tieDestination.isVisible){let t=new Kh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination){let t=new Kh(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new Kh(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 Qh(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 Qh(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}}}}class Zh extends qa{constructor(e,t,s,i){super(e,t),this._isGrace=i,this._number=s}paint(e,t,s){const i=this.renderer.resources;s.font=this._isGrace?i.numberedNotationGraceFont:i.numberedNotationFont,s.textBaseline=L.Middle,s.textAlign=D.Left,s.fillText(this._number.toString(),e+this.x,t+this.y)}doLayout(){const e=this._isGrace?Qa.GraceScale:1;this.width=Zh.NoteHeadWidth*e,this.height=Zh.NoteHeadHeight*e}}Zh.NoteHeadHeight=17,Zh.NoteHeadWidth=12;class el extends qa{doLayout(){this.width=14+el.Padding,this.height=al.BarSize}paint(e,t,s){const i=el.Padding;s.fillRect(e+this.x,t+this.y,this.width-i,this.height)}}el.Padding=3;class tl extends on{constructor(){super(...arguments),this.isNaturalizeAccidental=!1,this.accidental=Xe.None}doLayout(){if(!this.container.beat.isRest&&!this.container.beat.isEmpty){let e=new To;if(e.renderer=this.renderer,this.container.beat.notes.length>0){const t=this.container.beat.notes[0],s=t?t.accidentalMode:b.Default,i=Cr.getNoteValue(t);let a=Cr.computeAccidental(this.renderer.bar.masterBar.keySignature,s,i,t.hasQuarterToneOffset);if(a==Xe.Natural){a=this.renderer.bar.masterBar.keySignature+7<7?Xe.Sharp:Xe.Flat,this.isNaturalizeAccidental=!0}if(a!==Xe.None){this.accidental=a;let s=this.renderer,i=new no(0,s.getLineY(0),a,t.beat.graceType!==m.None?Qa.GraceScale*Qa.GraceScale:Qa.GraceScale);i.renderer=this.renderer,e.addGlyph(i),this.addGlyph(e),this.addGlyph(new Fo(0,0,4))}}}super.doLayout()}}class sl extends hn{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.octaveDots=0}getNoteX(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=s.x;switch(t){case Us.Left:break;case Us.Center:e+=s.width/2;break;case Us.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new Pa;i.note=this.container.beat.notes[0],i.noteHeadBounds=new ds,i.noteHeadBounds.x=t+this.x+this.noteHeads.x,i.noteHeadBounds.y=s+this.y+this.noteHeads.y-this.noteHeads.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}getNoteY(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=this.y+s.y;switch(t){case zs.Top:case zs.TopWithStem:e-=s.height/2+2;break;case zs.Center:break;case zs.Bottom:case zs.BottomWithStem:e+=s.height/2}return e}return 0}updateBeamingHelper(){if(this.beamingHelper){let e=null;this.noteHeads?e=this.noteHeads:this.deadSlapped&&(e=this.deadSlapped),e&&this.beamingHelper.registerBeatLineX("numbered",this.container.beat,this.container.x+this.x+e.x,this.container.x+this.x+e.x+e.width)}}doLayout(){let e=this.renderer;e.shortestDuration<this.container.beat.duration&&(e.shortestDuration=this.container.beat.duration);const t=e.getLineY(e.getNoteLine());if(!this.container.beat.isEmpty){let s="0";if(this.container.beat.notes.length>0){const t=this.renderer.bar.masterBar.keySignatureType,i=this.renderer.bar.masterBar.keySignature,a=i+7,r=(t===P.Minor?sl.MinorKeySignatureOneValues:sl.MajorKeySignatureOneValues)[a],n=this.container.beat.notes[0];if(n.isDead)s="X";else{let t=n.displayValue-r,o=t<0?(t%12+12)%12:t%12,h=t<0?(Math.abs(t)+12)/12|0:t/12|0;t<0&&(h*=-1),this.octaveDots=h,e.registerOctave(h);let l=(le.keySignatureIsSharp(i)||le.keySignatureIsNatural(i)?Cr.FlatNoteSteps:Cr.SharpNoteSteps)[o]+1;Cr.AccidentalNotes[o]&&!this.container.preNotes.isNaturalizeAccidental&&(a<7?l++:l--),s=l.toString()}}if(this.container.beat.deadSlapped){const e=new _o;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addGlyph(e)}else{const e=this.container.beat.graceType!==m.None,i=new Zh(0,t,s,e);this.noteHeads=i,this.addGlyph(i)}if(this.container.beat.dots>0&&this.container.beat.duration>=p.Quarter){this.addGlyph(new Fo(0,0,5));for(let t=0;t<this.container.beat.dots;t++){const t=new lo(0,e.getLineY(0),1.5);t.renderer=this.renderer,this.addGlyph(t)}}let i=0;switch(this.container.beat.duration){case p.QuadrupleWhole:i=16;break;case p.DoubleWhole:i=8;break;case p.Whole:i=4;break;case p.Half:i=2}let a=i;for(let e=0;e<this.container.beat.dots;e++)a=a/2|0,i+=a;for(let t=0;t<i-1;t++){const t=new el(0,e.getLineY(0));t.renderer=this.renderer,this.addGlyph(t)}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.deadSlapped&&(this.centerX=this.deadSlapped.x+this.deadSlapped.width/2)}}sl.MajorKeySignatureOneValues=[59,66,61,68,63,58,65,60,67,62,69,64,71,66,61],sl.MinorKeySignatureOneValues=[71,66,73,68,63,70,65,72,67,74,69,64,71,66,73];class il extends qa{constructor(e,t,s,i){super(e,t),this._text="",this._accidental=Xe.None,this._accidentalOffset=0,this._keySignature=s,this._keySignatureType=i}doLayout(){super.doLayout();const e="1 = ";let t="",s=Xe.None;switch(this._keySignatureType){case P.Major:switch(this._keySignature){case v.Cb:t=" C",s=Xe.Flat;break;case v.Gb:t=" G",s=Xe.Flat;break;case v.Db:t=" D",s=Xe.Flat;break;case v.Ab:t=" A",s=Xe.Flat;break;case v.Eb:t=" E",s=Xe.Flat;break;case v.Bb:t=" B",s=Xe.Flat;break;case v.F:t="F";break;case v.C:t="C",s=Xe.None;break;case v.G:t="G",s=Xe.None;break;case v.D:t="D",s=Xe.None;break;case v.A:t="A",s=Xe.None;break;case v.E:t="E",s=Xe.None;break;case v.B:t="B",s=Xe.None;break;case v.FSharp:t=" F",s=Xe.Sharp;break;case v.CSharp:t=" C",s=Xe.Sharp}break;case P.Minor:switch(this._keySignature){case v.Cb:t=" a",s=Xe.Flat;break;case v.Gb:t=" e",s=Xe.Flat;break;case v.Db:t=" b",s=Xe.Flat;break;case v.Ab:t="f",s=Xe.None;break;case v.Eb:t="c",s=Xe.None;break;case v.Bb:t="g",s=Xe.None;break;case v.F:t="d";break;case v.C:t="a",s=Xe.None;break;case v.G:t="e",s=Xe.None;break;case v.D:t="b",s=Xe.None;break;case v.A:t=" f",s=Xe.Sharp;break;case v.E:t=" c",s=Xe.Sharp;break;case v.B:t=" g",s=Xe.Sharp;break;case v.FSharp:t=" d",s=Xe.Sharp;break;case v.CSharp:t=" a",s=Xe.Sharp}}this._text=e+t,this._accidental=s;const i=this.renderer.scoreRenderer.canvas,a=this.renderer.resources;i.font=a.numberedNotationFont,this._accidentalOffset=i.measureText(e).width,this.width=i.measureText(e+t).width}paint(e,t,s){const i=this.renderer.resources;s.font=i.numberedNotationFont,s.textBaseline=L.Middle,s.fillText(this._text,e+this.x,t+this.y),this._accidental!=Xe.None&&s.fillMusicFontSymbol(e+this.x+this._accidentalOffset,t+this.y,.7,no.getMusicSymbol(this._accidental),!1)}}class al extends ah{registerOctave(e){null===this.lowestOctave?(this.lowestOctave=e,this.highestOctave=e):(e<this.lowestOctave&&(this.lowestOctave=e),e>this.highestOctave&&(this.highestOctave=e))}constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.shortestDuration=p.QuadrupleWhole,this.lowestOctave=null,this.highestOctave=null,this._isOnlyNumbered=!t.staff.showSlash&&!t.staff.showTablature&&!t.staff.showStandardNotation}get lineSpacing(){return tn.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return 0}get bottomGlyphOverflow(){return 0}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s),this.paintTuplets(e,t,s,!0)}doLayout(){super.doLayout();let e=!1;for(let t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}if(e&&this.registerOverflowTop(this.tupletSize),!this.bar.isEmpty){let e=le.getIndex(this.shortestDuration)-2;if(e>0){let t=(e-1)*al.BarSpacing+al.BarSize,s=0;const i=this.lowestOctave;null!==i&&(s=Math.abs(i)*al.DotSpacing+al.DotSize),this.registerOverflowBottom(t+s)}const t=this.highestOctave;if(null!==t){const e=Math.abs(t)*al.DotSpacing+al.DotSize;this.registerOverflowTop(e)}}}paintFlag(e,t,s,i){this.paintBar(e,t,s,i)}paintBar(e,t,s,i){const a=this.resources;for(let n=0,o=i.beats.length;n<o;n++){let o=i.beats[n],h=al.BarSpacing,l=al.BarSize,d=le.getIndex(o.duration)-2,c=t+this.y,u=this.getBeatX(o,Gs.PreNotes)-this.beatGlyphsStart;var r=this.calculateBeamY(i,u);for(let t=0;t<d;t++){let a=0,d=0,p=0,g=c+t*h;n===i.beats.length-1?(a=u,d=this.getBeatX(o,Gs.PostNotes)-this.beatGlyphsStart):(a=u,d=this.getBeatX(i.beats[n+1],Gs.PreNotes)-this.beatGlyphsStart),p=g+r|0,ah.paintSingleBar(s,e+this.x+a,p,e+this.x+d,p,l)}let p=this.getBeatContainer(o).onNotes.octaveDots,g=0,m=0;p>0?(g=c+this.getLineY(0)-a.numberedNotationFont.size/1.5,m=-1*al.DotSpacing):p<0&&(g=c+r+d*h,m=al.DotSpacing);let f=this.getBeatX(o,Gs.OnNotes)+4-this.beatGlyphsStart;p=Math.abs(p);for(let t=0;t<p;t++)s.fillCircle(e+this.x+f,g,al.DotSize),g+=m}}getNoteLine(){return 0}get tupletOffset(){return super.tupletOffset+this.resources.numberedNotationFont.size}getFlagTopY(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}getFlagBottomY(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}getBeamDirection(e){return Ge.Down}getTupletBeamDirection(e){return Ge.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return isNaN(s)&&(s=this.getLineY(0)),s}calculateBeamYWithDirection(e,t,s){const i=this.resources.numberedNotationFont;return this.getLineY(0)+i.size}getBarLineStart(e,t){return this.getLineY(0)-Oo.NoteHeadHeight/2}createLinePreBeatGlyphs(){this.bar.previousBar&&this.bar.masterBar.keySignature===this.bar.previousBar.masterBar.keySignature||(this.createStartSpacing(),this.createKeySignatureGlyphs()),this._isOnlyNumbered&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createKeySignatureGlyphs(){this.addPreBeatGlyph(new il(0,this.getLineY(0),this.bar.masterBar.keySignature,this.bar.masterBar.keySignatureType))}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Fo(0,0,5));const e=this.bar.masterBar;this.addPreBeatGlyph(new Jo(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime)))}createPostBeatGlyphs(){this._isOnlyNumbered&&super.createPostBeatGlyphs()}createVoiceGlyphs(e){for(const t of e.beats){let s=new $h(t,this.getVoiceContainer(e));s.preNotes=0==e.index?new tl:new on,s.onNotes=0==e.index?new sl:new hn,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){r.lineWidth=tn.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}}al.StaffId="numbered",al.BarSpacing=tn.BeamSpacing+tn.BeamThickness,al.BarSize=2,al.DotSpacing=5,al.DotSize=2;class rl extends Tr{get staffId(){return qh.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new al(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showNumbered}constructor(){super()}}class nl extends un{get notationElement(){return x.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SinglePreBeat}shouldCreateGlyph(e,t){const s=t.voice.bar.masterBar;return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&s.isFreeTime&&(0===s.index||s.isFreeTime!=s.previousMasterBar.isFreeTime)}createNewGlyph(e,t){return new Gr(0,0,"Free time",e.resources.effectFont,D.Left)}canExpand(e,t){return!0}}class ol extends ja{constructor(){super(0,0)}doLayout(){super.doLayout(),this.height=ol.TextHeight}paint(e,t,s){const i=this.renderer,a=t+this.y,r=this.height;let n=i.bar.sustainPedals,o=0;for(;o<n.length;){let t=n[o];for(;null!=t;){const i=e+this.renderer.getRatioPositionX(t.ratioPosition);let l=0;if(t.pedalType===h.Down?(s.fillMusicFontSymbol(i,a+r,1,F.KeyboardPedalPed,!0),l=ol.TextWidth/2+ol.TextLinePadding):t.pedalType===h.Up&&(s.fillMusicFontSymbol(i,a+r,1,F.KeyboardPedalUp,!0),l=ol.StarSize/2+ol.StarLinePadding),t.nextPedalMarker)if(t.nextPedalMarker.bar===t.bar){let n=e+this.renderer.getRatioPositionX(t.nextPedalMarker.ratioPosition);switch(t.nextPedalMarker.pedalType){case h.Down:n-=ol.TextWidth/2;break;case h.Hold:break;case h.Up:n-=ol.StarSize/2}const o=i+l;n>o&&s.fillRect(o,a+r-1,n-o,1)}else{const t=e+this.x+this.width,n=i+l;s.fillRect(n,a+r-1,t-n,1)}if(0===o&&t.previousPedalMarker){const t=e+this.x,n=i-l;s.fillRect(t,a+r-1,n-t,1)}o++,null!=t.nextPedalMarker&&t.nextPedalMarker.bar!==t.bar?(t=null,o=n.length):t=t.nextPedalMarker}}}}ol.TextHeight=19,ol.TextWidth=35,ol.TextLinePadding=3,ol.StarSize=16,ol.StarLinePadding=3;class hl extends un{get notationElement(){return x.EffectSustainPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Xs.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&t.voice.bar.sustainPedals.length>0}createNewGlyph(e,t){return new ol}canExpand(e,t){return!0}}class ll extends un{constructor(e,t){super(),this._type=e,this._shouldCreate=t}get notationElement(){return x.EffectGolpe}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){const s=this._shouldCreate;return t.golpe==this._type&&(!s||s(e,t))}createNewGlyph(e,t){return new Io(0,0,!0)}canExpand(e,t){return!1}}class dl extends Ka{constructor(e){super(0,0,1,dl.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case R.Open:return F.GuitarOpenPedal;case R.Closed:return F.GuitarClosePedal}return F.None}doLayout(){this.width=11,this.height=11}paint(e,t,s){super.paint(e,t+this.height,s)}}class cl extends un{get notationElement(){return x.EffectWahPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return t.wahPedal!==R.None}createNewGlyph(e,t){return new dl(t.wahPedal)}canExpand(e,t){return!1}}class ul extends un{get notationElement(){return x.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isBarre}get sizingMode(){return Xs.GroupedOnBeat}createNewGlyph(e,t){let s="";switch(t.barreShape){case V.None:case V.Full:break;case V.Half:s+="1/2"}return s+="B "+ul.toRoman(t.barreFret),new vn(s,!1)}static toRoman(e){let t="";if(e>0)for(var[s,i]of ul.RomanLetters){const a=Math.floor(e/i);e-=a*i,t+=s.repeat(a)}return t}canExpand(e,t){return e.barreFret===t.barreFret&&e.barreShape===t.barreShape}}ul.RomanLetters=new Map([["L",50],["XL",40],["X",10],["IX",9],["V",5],["IV",4],["I",1]]);class pl extends Ka{constructor(e){super(0,0,1,pl.getSymbol(e)),this.center=!0}doLayout(){this.width=26,this.height=18}static getSymbol(e){switch(e){case M.InvertedTurn:return F.OrnamentTurnInverted;case M.Turn:return F.OrnamentTurn;case M.UpperMordent:return F.OrnamentShortTrill;case M.LowerMordent:return F.OrnamentMordent}return F.None}paint(e,t,s){super.paint(e,t+this.height-4,s)}}class gl extends un{get notationElement(){return x.EffectNoteOrnament}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return t.notes.some((e=>e.ornament!==M.None))}createNewGlyph(e,t){return new pl(t.notes.find((e=>e.ornament!=M.None)).ornament)}canExpand(e,t){return!1}}class ml extends un{get notationElement(){return x.EffectRasgueado}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.hasRasgueado}get sizingMode(){return Xs.GroupedOnBeat}createNewGlyph(e,t){return new vn("rasg.")}canExpand(e,t){return!0}}class fl extends qa{constructor(e){super(0,0),this._symbols=e}doLayout(){this.height=27}paint(e,t,s){s.fillMusicFontSymbols(e+this.x,t+this.y+this.height,.8,this._symbols,!0)}}class yl extends qa{constructor(e){super(0,0),this._text=e}doLayout(){this.height=1.5*this.renderer.resources.directionsFont.size}paint(e,t,s){const i=s.font,a=s.textBaseline,r=s.textAlign;s.font=this.renderer.resources.directionsFont,s.textBaseline=L.Middle,s.textAlign=D.Right,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=i,s.textBaseline=a,s.textAlign=r}}class bl extends ja{constructor(e,t,s){super(e,t),this._barBeginGlyphs=[],this._barEndGlyphs=[],this._directions=s}doLayout(){const e=this._directions;e.has(Ve.TargetSegnoSegno)&&this._barBeginGlyphs.push(new fl([F.Segno,F.Segno])),e.has(Ve.TargetSegno)&&this._barBeginGlyphs.push(new fl([F.Segno])),e.has(Ve.TargetDoubleCoda)&&this._barBeginGlyphs.push(new fl([F.Coda,F.Coda])),e.has(Ve.TargetCoda)&&this._barBeginGlyphs.push(new fl([F.Coda])),e.has(Ve.TargetFine)&&this._barEndGlyphs.push(new yl("Fine")),e.has(Ve.JumpDaDoubleCoda)&&this._barEndGlyphs.push(new yl("To Double Coda")),e.has(Ve.JumpDaCoda)&&this._barEndGlyphs.push(new yl("To Coda")),e.has(Ve.JumpDalSegnoSegno)&&this._barEndGlyphs.push(new yl("D.S.S.")),e.has(Ve.JumpDalSegnoSegnoAlCoda)&&this._barEndGlyphs.push(new yl("D.S.S. al Coda")),e.has(Ve.JumpDalSegnoSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new yl("D.S.S. al Double Coda")),e.has(Ve.JumpDalSegnoSegnoAlFine)&&this._barEndGlyphs.push(new yl("D.S.S. al Fine")),e.has(Ve.JumpDalSegno)&&this._barEndGlyphs.push(new yl("D.S.")),e.has(Ve.JumpDalSegnoAlCoda)&&this._barEndGlyphs.push(new yl("D.S. al Coda")),e.has(Ve.JumpDalSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new yl("D.S. al Double Coda")),e.has(Ve.JumpDalSegnoAlFine)&&this._barEndGlyphs.push(new yl("D.S. al Fine")),e.has(Ve.JumpDaCapo)&&this._barEndGlyphs.push(new yl("D.C.")),e.has(Ve.JumpDaCapoAlCoda)&&this._barEndGlyphs.push(new yl("D.C. al Coda")),e.has(Ve.JumpDaCapoAlDoubleCoda)&&this._barEndGlyphs.push(new yl("D.C. al Double Coda")),e.has(Ve.JumpDaCapoAlFine)&&this._barEndGlyphs.push(new yl("D.C. al Fine"));const t=this.doSideLayout(this._barBeginGlyphs),s=this.doSideLayout(this._barEndGlyphs);this.height=Math.max(t,s)}doSideLayout(e){let t=0;for(const s of e)s.y=t,s.renderer=this.renderer,s.doLayout(),t+=s.height+3;return t}paint(e,t,s){for(const i of this._barBeginGlyphs)i.paint(e+this.x,t+this.y,s);for(const i of this._barEndGlyphs)i.paint(e+this.x+this.width,t+this.y,s)}}class Sl extends un{get notationElement(){return x.EffectDirections}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Xs.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&null!==t.voice.bar.masterBar.directions&&t.voice.bar.masterBar.directions.size>0}createNewGlyph(e,t){return new bl(0,0,t.voice.bar.masterBar.directions)}canExpand(e,t){return!0}}class _l extends ja{constructor(e){super(0,0),this._text="",this._textWidth=0,this._textHeight=0,this._timer=e}doLayout(){const e=this._timer/6e4|0,t=(this._timer-6e4*e)/1e3|0;this._text=`${e}:${t.toString().padStart(2,"0")}`;const s=this.renderer.scoreRenderer.canvas;s.font=this.renderer.resources.timerFont;const i=s.measureText(this._text);this._textHeight=s.font.size+2*_l.PaddingY,this._textWidth=i.width+2*_l.PaddingX,this.height=this._textHeight+2*_l.MarginY}paint(e,t,s){const i=this._textWidth/2|0;s.strokeRect(e+this.x-i,t+this.y+_l.MarginY,this._textWidth,this._textHeight);const a=s.font,r=s.textBaseline,n=s.textAlign;s.font=this.renderer.resources.timerFont,s.textBaseline=L.Middle,s.textAlign=D.Center,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=a,s.textBaseline=r,s.textAlign=n}}_l.PaddingX=2,_l.PaddingY=2,_l.MarginY=2;class wl extends un{get notationElement(){return x.EffectBeatTimer}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return Xs.SingleOnBeat}shouldCreateGlyph(e,t){return t.showTimer}createNewGlyph(e,t){return new _l(t.timer??0)}canExpand(e,t){return!0}}class Bl{constructor(e,t){this.vertical=e,this.createLayout=t}}class kl{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class Tl{static createStyleElement(e,t){let s=e.getElementById("alphaTabStyle");if(!s){if(!t)return void re.error("AlphaTab","Font directory could not be detected, cannot create style element");s=e.createElement("style"),s.id="alphaTabStyle";let i=`\n @font-face {\n font-display: block;\n font-family: 'alphaTab';\n src: url('${t}Bravura.eot');\n src: url('${t}Bravura.eot?#iefix') format('embedded-opentype')\n , url('${t}Bravura.woff') format('woff')\n , url('${t}Bravura.otf') format('opentype')\n , url('${t}Bravura.svg#Bravura') format('svg');\n font-weight: normal;\n font-style: normal;\n }\n .at-surface * {\n cursor: default;\n vertical-align: top;\n overflow: visible;\n }\n .at-surface-svg text {\n dominant-baseline: central;\n white-space:pre;\n }\n .at {\n font-family: 'alphaTab';\n speak: none;\n font-style: normal;\n font-weight: normal;\n font-variant: normal;\n text-transform: none;\n line-height: 1;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n font-size: ${Tl.MusicFontSize}px;\n overflow: visible !important;\n }`;s.innerHTML=i,e.getElementsByTagName("head").item(0).appendChild(s),Tl.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===Tl._globalThis){try{Tl._globalThis=globalThis}catch(e){}void 0===Tl._globalThis&&(Tl._globalThis=self),void 0===Tl._globalThis&&(Tl._globalThis=global),void 0===Tl._globalThis&&(Tl._globalThis=window),void 0===Tl._globalThis&&(Tl._globalThis=Function("return this")())}return this._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in Tl.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in Tl.globalThis}static throttle(e,t){let s=0;return()=>{Tl.globalThis.clearTimeout(s),s=Tl.globalThis.setTimeout(e,t)}}static detectScriptFile(){if(!Tl.isRunningInWorker&&Tl.globalThis.ALPHATAB_ROOT){let e=Tl.globalThis.ALPHATAB_ROOT;return e=Tl.ensureFullUrl(e),e=Tl.appendScriptName(e),e}try{const e=import.meta.url;if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in Tl.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=Tl.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(!Tl.isRunningInWorker&&Tl.globalThis.ALPHATAB_FONT)return Tl.ensureFullUrl(Tl.globalThis.ALPHATAB_FONT);const e=Tl.scriptFile;if(e){let t=e.lastIndexOf(String.fromCharCode(47));if(t>=0)return e.substr(0,t)+"/font/"}return null}static registerJQueryPlugin(){if(!Tl.isRunningInWorker&&Tl.globalThis&&"jQuery"in Tl.globalThis){let e=Tl.globalThis.jQuery,t=new wr;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:wr.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&Tl.renderEngines.has(e)?Tl.renderEngines.get(e):Tl.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&Tl.layoutEngines.has(t)?Tl.layoutEngines.get(t):Tl.layoutEngines.get(e.Page)}static buildImporters(){return[new os,new ai,new Zs,new ri,new Oh,new tt]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new kl(!0,(()=>new kr))),e.set("default",e.get("svg")),e.set("skia",new kl(!1,(()=>new zh))),Tl.createPlatformSpecificRenderEngines(e),e}static enableAlphaSkia(e,t){zh.enable(e,t)}static registerAlphaSkiaCustomFont(e,t){return zh.registerFont(e,t)}static createPlatformSpecificRenderEngines(e){e.set("html5",new kl(!1,(()=>new La)))}static createDefaultRenderers(){return[new dn(Tl.StaffIdBeforeSlashAlways,[new qn,new Zn,new Dn,new Sl,new pn,new nl,new jn,new wl,new mn]),new jh,new dn(Tl.StaffIdBeforeScoreAlways,[new Tn,new ul,new gl,new ml,new cl]),new dn(Tl.StaffIdBeforeScoreHideable,[new eo,new Qn,new Mn(!0),new to,new Hn,new so,new Wn(!1),new Bh,new ll(A.Finger)],((e,t)=>t.showStandardNotation)),new nh,new dn(Tl.StaffIdBeforeNumberedAlways,[new bn,new Mn(!1),new _n,new ll(A.Thumb,((e,t)=>t.voice.bar.staff.showStandardNotation)),new hl]),new rl,new dn(Tl.StaffIdBeforeTabAlways,[new Fn]),new dn(Tl.StaffIdBeforeTabHideable,[new Qn,new to,new Hn,new so,new Wn(!0),new zn,new Bn,new Pn(y.Natural),new Pn(y.Artificial),new Pn(y.Pinch),new Pn(y.Tap),new Pn(y.Semi),new Pn(y.Feedback),new Cn,new gn,new xn,new In,new Rn,new An,new Bh,new ll(A.Finger,((e,t)=>!t.voice.bar.staff.showStandardNotation))],((e,t)=>t.showTablature)),new _h,new dn(Tl.StaffIdBeforeEndAlways,[new ll(A.Thumb,((e,t)=>!t.voice.bar.staff.showStandardNotation))])]}static createDefaultStaveProfiles(){const e=new Map,s=Tl.createDefaultRenderers();e.set(t.Default,s),e.set(t.ScoreTab,s);const i=new Set([Tl.StaffIdBeforeSlashAlways,Tl.StaffIdBeforeScoreAlways,Tl.StaffIdBeforeNumberedAlways,Tl.StaffIdBeforeTabAlways,rh.StaffId,Tl.StaffIdBeforeEndAlways]);e.set(t.Score,s.filter((e=>i.has(e.staffId))));const a=new Set([Tl.StaffIdBeforeSlashAlways,Tl.StaffIdBeforeScoreAlways,Tl.StaffIdBeforeNumberedAlways,Tl.StaffIdBeforeTabAlways,Sh.StaffId,Tl.StaffIdBeforeEndAlways]);return e.set(t.Tab,Tl.createDefaultRenderers().filter((e=>{if(e instanceof _h){const t=e;t.showTimeSignature=!0,t.showRests=!0,t.showTiedNotes=!0}return a.has(e.staffId)}))),e.set(t.TabMixed,Tl.createDefaultRenderers().filter((e=>{if(e instanceof _h){const t=e;t.showTimeSignature=!1,t.showRests=!1,t.showTiedNotes=!1}return a.has(e.staffId)}))),e}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.Page,new Bl(!0,(e=>new ro(e)))),t.set(e.Horizontal,new Bl(!1,(e=>new ao(e)))),t}static initializeMain(e,t){Tl.isRunningInWorker||Tl.isRunningInAudioWorklet||(Tl.webPlatform!==Rs.Browser&&Tl.webPlatform!==Rs.BrowserModule||(Tl.registerJQueryPlugin(),Tl.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in Tl.globalThis||(Tl.globalThis.ResizeObserver=Rh),"IntersectionObserver"in Tl.globalThis||(Tl.globalThis.IntersectionObserver=Vh),"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)})),Tl.createWebWorker=e,Tl.createAudioWorklet=t)}static get alphaTabWorker(){return this.globalThis.Worker}static get alphaTabUrl(){return this.globalThis.URL}static initializeWorker(){if(!Tl.isRunningInWorker)throw new j(s.General,"Not running in worker, cannot run worker initialization");Da.init(),wa.init(),Tl.createWebWorker=e=>{throw new j(s.General,"Nested workers are not supported")}}static initializeAudioWorklet(){if(!Tl.isRunningInAudioWorklet)throw new j(s.General,"Not running in audio worklet, cannot run worklet initialization");fr.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 Rs.NodeJs}catch(e){}try{const e=import.meta.url;if(e&&"string"==typeof e&&!e.startsWith("file://"))return Rs.BrowserModule}catch(e){}return Rs.Browser}}Tl.StaffIdBeforeSlashAlways="before-slash-always",Tl.StaffIdBeforeScoreAlways="before-score-always",Tl.StaffIdBeforeScoreHideable="before-score-hideable",Tl.StaffIdBeforeNumberedAlways="before-numbered-always",Tl.StaffIdBeforeTabAlways="before-tab-always",Tl.StaffIdBeforeTabHideable="before-tab-hideable",Tl.StaffIdBeforeEndAlways="before-end-always",Tl.MusicFontSize=34,Tl.HighDpiFactor=1,Tl._globalThis=void 0,Tl.webPlatform=Tl.detectWebPlatform(),Tl.isWebPackBundled=Tl.detectWebPack(),Tl.isViteBundled=Tl.detectVite(),Tl.scriptFile=Tl.detectScriptFile(),Tl.fontDirectory=Tl.detectFontDirectory(),Tl.bravuraFontChecker=new hr(["alphaTab"]),Tl.renderEngines=Tl.createDefaultRenderEngines(),Tl.layoutEngines=Tl.createDefaultLayoutEngines(),Tl.staveProfiles=Tl.createDefaultStaveProfiles();class xl{constructor(){this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=N.Info,this.useWorkers=!0,this.includeNoteBounds=!1,this.scriptFile=Tl.scriptFile,this.fontDirectory=Tl.fontDirectory}}class Nl{}Nl.version="1.4.0",Nl.date="2025-03-02T15:59:05.431Z";var vl,Pl=Object.freeze({__proto__:null,ScoreImporter:q,ScoreLoader:rr,UnsupportedFormatError:K});class Cl{init(e,t){this.data=e,this.settings=t}export(e,t=null){const s=Oe.withCapacity(1024);return this.init(s,t??new Ot),this.writeScore(e),s.toArray()}}!function(e){e[e.SteelGuitar=1]="SteelGuitar",e[e.AcousticGuitar=2]="AcousticGuitar",e[e.TwelveStringGuitar=3]="TwelveStringGuitar",e[e.ElectricGuitar=4]="ElectricGuitar",e[e.Bass=5]="Bass",e[e.ClassicalGuitar=23]="ClassicalGuitar",e[e.UprightBass=6]="UprightBass",e[e.Ukulele=7]="Ukulele",e[e.Banjo=8]="Banjo",e[e.Mandolin=9]="Mandolin",e[e.Piano=10]="Piano",e[e.Synth=12]="Synth",e[e.Strings=11]="Strings",e[e.Brass=13]="Brass",e[e.Reed=14]="Reed",e[e.Woodwind=15]="Woodwind",e[e.Vocal=16]="Vocal",e[e.PitchedIdiophone=17]="PitchedIdiophone",e[e.Fx=21]="Fx",e[e.PercussionKit=18]="PercussionKit",e[e.Idiophone=19]="Idiophone",e[e.Membraphone=20]="Membraphone"}(vl||(vl={}));class El{constructor(e,t,s=null){if(this.icon=vl.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 Fl{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new fs;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;break;case i.Tenuto:a|=16}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 w.Slight:s.addElement("Vibrato").innerText="Slight";break;case w.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",t.ornament!==M.None&&(s.addElement("Ornament").innerText=M[t.ornament])}writeNoteProperties(e,t){const s=e.addElement("Properties");if(this.writeConcertPitch(s,t),this.writeTransposedPitch(s,t),t.isStringed&&(this.writeSimplePropertyNode(s,"String","String",(t.string-1).toString()),this.writeSimplePropertyNode(s,"Fret","Fret",t.fret.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString()),t.showStringNumber&&this.writeSimplePropertyNode(s,"ShowStringNumber","Enable",null)),t.isPiano&&(this.writeSimplePropertyNode(s,"Octave","Number",t.octave.toString()),this.writeSimplePropertyNode(s,"Tone","Step",t.tone.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString())),t.beat.tap&&this.writeSimplePropertyNode(s,"Tapped","Enable",null),t.harmonicType!==y.None){switch(t.harmonicType){case y.Natural:this.writeSimplePropertyNode(s,"HarmonicType","HType","Natural");break;case y.Artificial:this.writeSimplePropertyNode(s,"HarmonicType","HType","Artificial");break;case y.Pinch:this.writeSimplePropertyNode(s,"HarmonicType","HType","Pinch");break;case y.Tap:this.writeSimplePropertyNode(s,"HarmonicType","HType","Tap");break;case y.Semi:this.writeSimplePropertyNode(s,"HarmonicType","HType","Semi");break;case y.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 S.IntoFromAbove:i|=32;break;case S.IntoFromBelow:i|=16}switch(t.slideOutType){case _.Shift:i|=1;break;case _.Legato:i|=2;break;case _.OutDown:i|=4;break;case _.OutUp:i|=8;break;case _.PickSlideDown:i|=64;break;case _.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=Fe.defaultSteps[a],o=Fe.defaultAccidentals[a]};switch(h(),i){case b.Default:break;case b.ForceNone:case b.ForceNatural:o="";break;case b.ForceSharp:o="#";break;case b.ForceDoubleSharp:"#"===o&&(s-=2,h()),o="x";break;case b.ForceFlat:"#"===o&&(s+=1,h()),o="b";break;case b.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 te((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/te.MaxPosition*100}writeBeatNode(e,t,s){const i=e.addElement("Beat");if(i.attributes.set("id",t.id.toString()),i.addElement("Dynamic").innerText=g[t.dynamics],t.fade!==O.None&&(i.addElement("Fadding").innerText=O[t.fade]),t.isTremolo)switch(t.tremoloSpeed){case p.Eighth:i.addElement("Tremolo").innerText="1/2";break;case p.Sixteenth:i.addElement("Tremolo").innerText="1/4";break;case p.ThirtySecond:i.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&i.addElement("Chord").setCData(t.chordId),t.crescendo!==u.None&&(i.addElement("Hairpin").innerText=u[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 m.OnBeat:case m.BeforeBeat:i.addElement("GraceNotes").innerText=m[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 Ge.Up:i.addElement("TransposedPitchStemOrientation").innerText="Upward",i.addElement("UserTransposedPitchStemOrientation").innerText="Upward";break;case Ge.Down:i.addElement("TransposedPitchStemOrientation").innerText="Downward",i.addElement("UserTransposedPitchStemOrientation").innerText="Downward"}i.addElement("ConcertPitchStemOrientation").innerText="Undefined",t.slashed&&i.addElement("Slashed"),t.deadSlapped&&i.addElement("DeadSlapped"),t.notes.length>0&&(i.addElement("Notes").innerText=t.notes.map((e=>e.id)).join(" ")),t.golpe!==A.None&&(i.addElement("Golpe").innerText=A[t.golpe]),t.wahPedal!==R.None&&(i.addElement("Wah").innerText=R[t.wahPedal]),t.showTimer&&(i.addElement("Timer").innerText=(t.timer??0).toString()),this.writeBeatProperties(i,t),this.writeBeatXProperties(i,t),t.lyrics&&t.lyrics.length>0&&this.writeBeatLyrics(i,t.lyrics)}writeBeatLyrics(e,t){const s=e.addElement("Lyrics");for(const e of t){s.addElement("Line").setCData(e)}}writeBeatXProperties(e,t){const s=e.addElement("XProperties");switch(t.brushDuration>0&&this.writeSimpleXPropertyNode(s,"687935489","Int",t.brushDuration.toString()),t.beamingMode){case G.ForceSplitToNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","2");break;case G.ForceMergeWithNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","1");break;case G.ForceSplitOnSecondaryToNext:this.writeSimpleXPropertyNode(s,"1124204552","Int","1")}}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 E.Up:this.writeSimplePropertyNode(s,"PickStroke","Direction","Up");break;case E.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 w.Wide:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Wide");break;case w.Slight:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Slight")}if(t.isBarre)switch(this.writeSimplePropertyNode(s,"BarreFret","Fret",t.barreFret.toString()),t.barreShape){case V.Full:this.writeSimplePropertyNode(s,"BarreString","String","0");break;case V.Half:this.writeSimplePropertyNode(s,"BarreString","String","1")}if(t.rasgueado!=H.None){let e="";switch(t.rasgueado){case H.Ii:e="ii_1";break;case H.Mi:e="mi_1";break;case H.MiiTriplet:e="mii_1";break;case H.MiiAnapaest:e="mii_2";break;case H.PmpTriplet:e="pmp_1";break;case H.PmpAnapaest:e="pmp_2";break;case H.PeiTriplet:e="pei_1";break;case H.PeiAnapaest:e="pei_2";break;case H.PaiTriplet:e="pai_1";break;case H.PaiAnapaest:e="pai_2";break;case H.AmiTriplet:e="ami_1";break;case H.AmiAnapaest:e="ami_2";break;case H.Ppp:e="ppp_1";break;case H.Amii:e="amii_1";break;case H.Amip:e="amip_1";break;case H.Eami:e="eami_1";break;case H.Eamii:e="eamii_1";break;case H.Peami:e="peami_1"}this.writeSimplePropertyNode(s,"Rasgueado","Rasgueado",e)}}writeRhythm(e,t,s){const i=`${t.duration}_${t.dots}_${t.tupletNumerator}_${t.tupletDenominator}';`;let a;if(this._rhythmIdLookup.has(i))a=this._rhythmIdLookup.get(i);else{a=this._rhythmIdLookup.size.toString(),this._rhythmIdLookup.set(i,a);const e=s.addElement("Rhythm");if(e.attributes.set("id",a),t.hasTuplet){const s=e.addElement("PrimaryTuplet");s.attributes.set("num",t.tupletNumerator.toString()),s.attributes.set("den",t.tupletDenominator.toString())}t.dots>0&&e.addElement("AugmentationDot").attributes.set("count",t.dots.toString());let r="Quarter";switch(t.duration){case p.QuadrupleWhole:r="Long";break;case p.DoubleWhole:r="DoubleWhole";break;case p.Whole:r="Whole";break;case p.Half:r="Half";break;case p.Quarter:r="Quarter";break;case p.Eighth:r="Eighth";break;case p.Sixteenth:r="16th";break;case p.ThirtySecond:r="32nd";break;case p.SixtyFourth:r="64th";break;case p.OneHundredTwentyEighth:r="128th";break;case p.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 te((r.offset+n.offset)/2,(r.value+n.value)/2)}s.attributes.set("destinationOffset",this.toBendOffset(n.offset).toString()),s.attributes.set("destinationValue",this.toBendValue(n.value).toString()),s.attributes.set("middleOffset1",this.toBendOffset(i.offset).toString()),s.attributes.set("middleOffset2",this.toBendOffset(a.offset).toString()),s.attributes.set("middleValue",this.toBendValue(i.value).toString()),s.attributes.set("originOffset",this.toBendOffset(r.offset).toString()),s.attributes.set("originValue",this.toBendValue(r.value).toString())}writeScoreNode(e,t){const s=e.addElement("Score");s.addElement("Title").setCData(t.title),s.addElement("SubTitle").setCData(t.subTitle),s.addElement("Artist").setCData(t.artist),s.addElement("Album").setCData(t.album),s.addElement("Words").setCData(t.words),s.addElement("Music").setCData(t.music),s.addElement("WordsAndMusic").setCData(t.words===t.music?t.words:""),s.addElement("Copyright").setCData(t.copyright),s.addElement("Tabber").setCData(t.tab),s.addElement("Instructions").setCData(t.instructions),s.addElement("Notices").setCData(t.notices),s.addElement("FirstPageHeader").setCData(""),s.addElement("FirstPageFooter").setCData(""),s.addElement("PageHeader").setCData(""),s.addElement("PageFooter").setCData(""),s.addElement("ScoreSystemsDefaultLayout").setCData(t.defaultSystemsLayout.toString()),s.addElement("ScoreSystemsLayout").setCData(t.systemsLayout.join(" ")),s.addElement("ScoreZoomPolicy").innerText="Value",s.addElement("ScoreZoom").innerText="1",s.addElement("MultiVoice").innerText="1>"}writeMasterTrackNode(e,t){const s=e.addElement("MasterTrack");s.addElement("Tracks").innerText=t.tracks.map((e=>e.index)).join(" ");const i=s.addElement("Automations");if(t.masterBars.length>0&&t.masterBars[0].isAnacrusis&&s.addElement("Anacrusis"),0===t.masterBars[0].tempoAutomations.length){const e=i.addElement("Automation");e.addElement("Type").innerText="Tempo",e.addElement("Linear").innerText="false",e.addElement("Bar").innerText="0",e.addElement("Position").innerText="0",e.addElement("Visible").innerText="true",e.addElement("Value").innerText=`${t.tempo} 2`,t.tempoLabel&&(e.addElement("Text").innerText=t.tempoLabel)}for(const e of t.masterBars)for(const t of e.tempoAutomations){const s=i.addElement("Automation");s.addElement("Type").innerText="Tempo",s.addElement("Linear").innerText=t.isLinear?"true":"false",s.addElement("Bar").innerText=e.index.toString(),s.addElement("Position").innerText=t.ratioPosition.toString(),s.addElement("Visible").innerText="true",s.addElement("Value").innerText=`${t.value} 2`,t.text&&(s.addElement("Text").innerText=t.text)}}writeAudioTracksNode(e,t){e.addElement("AudioTracks")}writeTracksNode(e,t){const s=e.addElement("Tracks");for(const e of t.tracks)this.writeTrackNode(s,e)}writeTrackNode(e,t){const s=e.addElement("Track");s.attributes.set("id",t.index.toString()),s.addElement("Name").setCData(t.name),s.addElement("ShortName").setCData(t.shortName),s.addElement("Color").innerText=`${t.color.r} ${t.color.g} ${t.color.b}`,s.addElement("SystemsDefautLayout").innerText=t.defaultSystemsLayout.toString(),s.addElement("SystemsLayout").innerText=t.systemsLayout.join(" "),s.addElement("AutoBrush"),s.addElement("PalmMute").innerText="0",s.addElement("PlayingStyle").innerText=Y.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",s.addElement("UseOneChannelPerString"),s.addElement("IconId").innerText=Fl.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?Fl.DrumKitProgramInfo.icon:Fl.MidiProgramInfoLookup.has(e.program)?Fl.MidiProgramInfoLookup.get(e.program).icon:vl.SteelGuitar}writeSoundAndAutomation(e,t,s,i,a,r,n,o=0){const h=e.addElement("Sound");h.addElement("Name").setCData(s),h.addElement("Label").setCData(s),h.addElement("Path").setCData(i),h.addElement("Role").setCData(a);const l=h.addElement("MIDI");l.addElement("LSB").innerText="0",l.addElement("MSB").innerText="0",l.addElement("Program").innerText=n.toString();const d=t.addElement("Automation");d.addElement("Type").innerText="Sound",d.addElement("Linear").innerText="false",d.addElement("Bar").innerText=r.toString(),d.addElement("Position").innerText=o.toString(),d.addElement("Visible").innerText="true",d.addElement("Value").setCData(`${i};${s};${a}`)}writeSoundsAndAutomations(e,t){const s=e.addElement("Sounds"),i=e.addElement("Automations");if(t.staves.length>0&&t.staves[0].bars.length>0){const e=`Track_${t.index}_Initial`,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 d of h.beats){const h=d.getAutomation(a.Instrument),c=0===l.index&&0===d.index;if(h){const a=c?e:`ProgramChange_${d.id}`,u=c?r:`Midi/${h.value}`,p=c?n:"User";c||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),c&&(o=!0)}}}for(const e of t.staves)for(const t of e.bars)for(const e of t.sustainPedals)if(e.pedalType!==h.Hold){const s=i.addElement("Automation");switch(s.addElement("Type").innerText="SustainPedal",s.addElement("Linear").innerText="false",s.addElement("Bar").innerText=t.index.toString(),s.addElement("Position").innerText=e.ratioPosition.toString(),s.addElement("Visible").innerText="true",e.pedalType){case h.Down:s.addElement("Value").innerText="0 1";break;case h.Up:s.addElement("Value").innerText="0 3"}}}writeMidiConnectionNode(e,t){const s=e.addElement("MidiConnection");s.addElement("Port").innerText=t.playbackInfo.port.toString(),s.addElement("PrimaryChannel").innerText=t.playbackInfo.primaryChannel.toString(),s.addElement("SecondaryChannel").innerText=t.playbackInfo.secondaryChannel.toString(),s.addElement("ForeOneChannelPerString").innerText="false"}writeRseNode(e,t){const s=e.addElement("RSE").addElement("ChannelStrip");s.attributes.set("version","E56");s.addElement("Parameters").innerText=`0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1 0.5 ${t.playbackInfo.balance/16} ${t.playbackInfo.volume/16} 0.5 0.5 0.5`}writeStavesNode(e,t){const s=e.addElement("Staves");for(const e of t.staves)this.writeStaffNode(s,e)}writeStaffNode(e,t){const s=e.addElement("Staff").addElement("Properties");if(this.writeSimplePropertyNode(s,"CapoFret","Fret",t.capo.toString()),this.writeSimplePropertyNode(s,"FretCount","Fret","24"),t.tuning.length>0){const e=s.addElement("Property");switch(e.attributes.set("name","Tuning"),e.addElement("Pitches").innerText=t.tuning.slice().reverse().join(" "),e.addElement("Label").setCData(t.tuningName),e.addElement("LabelVisible").innerText=t.tuningName?"true":"false",e.addElement("Flat"),t.tuning.length){case 3:e.addElement("Instrument").innerText="Shamisen";break;case 4:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":42==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Cello":43==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Contrabass":40==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Violin":41==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Viola":e.addElement("Instrument").innerText="Bass";break;case 5:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":e.addElement("Instrument").innerText="Bass";break;case 6:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;case 7:t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;default:e.addElement("Instrument").innerText="Guitar"}}this.writeSimplePropertyNode(s,"PartialCapoFret","Fret","0"),this.writeSimplePropertyNode(s,"PartialCapoStringFlags","Bitset",t.tuning.map((e=>"0")).join("")),this.writeSimplePropertyNode(s,"TuningFlat","Enable",null),this.writeDiagramCollection(s,t,"DiagramCollection"),this.writeDiagramCollection(s,t,"DiagramWorkingSet")}writeDiagramCollection(e,t,s){const i=e.addElement("Property");i.attributes.set("name",s);const a=i.addElement("Items"),r=t.chords;if(r)for(const[e,t]of r){const s=a.addElement("Item");s.attributes.set("id",e),s.attributes.set("name",t.name);const i=s.addElement("Diagram");i.attributes.set("stringCount",t.strings.length.toString()),i.attributes.set("fretCount","5"),i.attributes.set("baseFret",(t.firstFret-1).toString()),i.attributes.set("barStates",t.strings.map((e=>"1")).join(" "));const r=[],n=new Map;for(let e=0;e<t.strings.length;e++){let s=t.strings[e];if(-1!==s){const a=i.addElement("Fret"),o=t.strings.length-1-e;a.attributes.set("string",o.toString()),a.attributes.set("fret",(s-t.firstFret+1).toString()),n.has(s)||(n.set(s,[]),r.push(s)),n.get(s).push(o)}}r.sort();const o=i.addElement("Fingering");if(t.barreFrets.length>0){const e=[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 d=i.addElement("Property");d.attributes.set("name","ShowFingering"),d.attributes.set("type","bool"),d.attributes.set("value",t.showFingering?"true":"false");const c=i.addElement("Chord"),u=c.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=c.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=c.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const m=c.addElement("Degree");m.attributes.set("interval","Fifth"),m.attributes.set("alteration","Perfect"),m.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,s,i){const a=e.addElement("Property");a.attributes.set("name",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeSimpleXPropertyNode(e,t,s,i){const a=e.addElement("XProperty");a.attributes.set("id",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeLyricsNode(e,t){const s=e.addElement("Lyrics");s.attributes.set("dispatched","true");let i=[];for(const e of t.staves[0].bars)for(const t of e.voices)if(!t.isEmpty)for(const s of t.beats)if(s.lyrics)for(let t=0;t<s.lyrics.length;t++){for(;t>=i.length;){const t=new ke;t.startBar=e.index,t.text="[Empty]",i.push(t)}const a=i[t];a.text="[Empty]"==a.text?s.lyrics[t]:a.text+" "+s.lyrics[t].split(" ").join("+")}for(let e=0;e<i.length;e++){const t=s.addElement("Line");t.addElement("Text").setCData(i[e].text),t.addElement("Offset").innerText=i[e].startBar.toString()}}writeTransposeNode(e,t){const s=e.addElement("Transpose"),i=Math.floor(t.staves[0].displayTranspositionPitch/12),a=t.staves[0].displayTranspositionPitch-12*i;s.addElement("Chromatic").innerText=a.toString(),s.addElement("Octave").innerText=i.toString()}writeInstrumentSetNode(e,t){const s=e.addElement("InstrumentSet"),i=t.staves[0];if(s.addElement("LineCount").innerText=i.standardNotationLineCount.toString(),t.percussionArticulations.length>0||i.isPercussion){const e=t.percussionArticulations.length>0?t.percussionArticulations:Array.from(ue.instrumentArticulations.values());s.addElement("Name").innerText=Fl.DrumKitProgramInfo.instrumentSetName,s.addElement("Type").innerText=Fl.DrumKitProgramInfo.instrumentSetType;let i="",r=new us,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 L.Top:e.addElement("TechniquePlacement").innerText="below";break;case L.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case L.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=Fl.MidiProgramInfoLookup.has(t.playbackInfo.program)?Fl.MidiProgramInfoLookup.get(t.playbackInfo.program):Fl.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===F.None)return"";let t=F[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=P[t.keySignatureType],i.addElement("Sharps").innerText="Sharps",s.addElement("Time").innerText=`${t.timeSignatureNumerator}/${t.timeSignatureDenominator}`,t.isFreeTime&&s.addElement("FreeTime");let a=[];for(const e of t.score.tracks)for(const s of e.staves)a.push(s.bars[t.index].id.toString());if(s.addElement("Bars").innerText=a.join(" "),t.isDoubleBar&&s.addElement("DoubleBar"),t.isSectionStart){const e=s.addElement("Section");e.addElement("Letter").setCData(t.section.marker),e.addElement("Text").setCData(t.section.text)}if(t.isRepeatStart||t.isRepeatEnd){const e=s.addElement("Repeat");e.attributes.set("start",t.isRepeatStart?"true":"false"),e.attributes.set("end",t.isRepeatEnd?"true":"false"),t.isRepeatEnd&&e.attributes.set("count",t.repeatCount.toString())}if(t.alternateEndings>0){let e=t.alternateEndings;const i=[];let a=0;for(;e>0;)1==(e>>a&1)&&(i.push(a+1),e&=~(1<<a)),a++;s.addElement("AlternateEndings").innerText=i.join(" ")}if(t.tripletFeel!==C.NoTripletFeel&&(s.addElement("TripletFeel").innerText=C[t.tripletFeel]),t.directions&&t.directions.size>0){const e=s.addElement("Directions");for(const s of t.directions)switch(s){case Ve.TargetFine:e.addElement("Target").innerText="Fine";break;case Ve.TargetSegno:e.addElement("Target").innerText="Segno";break;case Ve.TargetSegnoSegno:e.addElement("Target").innerText="SegnoSegno";break;case Ve.TargetCoda:e.addElement("Target").innerText="Coda";break;case Ve.TargetDoubleCoda:e.addElement("Target").innerText="DoubleCoda";break;case Ve.JumpDaCapo:e.addElement("Jump").innerText="DaCapo";break;case Ve.JumpDaCapoAlCoda:e.addElement("Jump").innerText="DaCapoAlCoda";break;case Ve.JumpDaCapoAlDoubleCoda:e.addElement("Jump").innerText="DaCapoAlDoubleCoda";break;case Ve.JumpDaCapoAlFine:e.addElement("Jump").innerText="DaCapoAlFine";break;case Ve.JumpDalSegno:e.addElement("Jump").innerText="DaSegno";break;case Ve.JumpDalSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoAlCoda";break;case Ve.JumpDalSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoAlDoubleCoda";break;case Ve.JumpDalSegnoAlFine:e.addElement("Jump").innerText="DaSegnoAlFine";break;case Ve.JumpDalSegnoSegno:e.addElement("Jump").innerText="DaSegnoSegno";break;case Ve.JumpDalSegnoSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlCoda";break;case Ve.JumpDalSegnoSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlDoubleCoda";break;case Ve.JumpDalSegnoSegnoAlFine:e.addElement("Jump").innerText="DaSegnoSegnoAlFine";break;case Ve.JumpDaCoda:e.addElement("Jump").innerText="DaCoda";break;case Ve.JumpDaDoubleCoda:e.addElement("Jump").innerText="DaDoubleCoda"}}this.writeFermatas(s,t)}writeFermatas(e,t){const s=t.fermata?.size??0;if(0!==s&&s>0){const s=e.addElement("Fermatas");for(const[e,i]of t.fermata)this.writeFermata(s,e,i)}}writeFermata(e,t,s){let i=-1,a=1;if(t>0)for(;a<10&&(i=t/ee.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=He[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(" ")}}Fl.MidiProgramInfoLookup=new Map([[0,new El(vl.Piano,"Acoustic Piano")],[1,new El(vl.Piano,"Acoustic Piano")],[2,new El(vl.Piano,"Electric Piano")],[3,new El(vl.Piano,"Acoustic Piano")],[4,new El(vl.Piano,"Electric Piano")],[5,new El(vl.Piano,"Electric Piano")],[6,new El(vl.Piano,"Harpsichord")],[7,new El(vl.Piano,"Harpsichord")],[8,new El(vl.PitchedIdiophone,"Celesta")],[9,new El(vl.PitchedIdiophone,"Vibraphone")],[10,new El(vl.PitchedIdiophone,"Vibraphone")],[11,new El(vl.PitchedIdiophone,"Vibraphone")],[12,new El(vl.PitchedIdiophone,"Xylophone")],[13,new El(vl.PitchedIdiophone,"Xylophone")],[14,new El(vl.PitchedIdiophone,"Vibraphone")],[15,new El(vl.Banjo,"Banjo")],[16,new El(vl.Piano,"Electric Organ")],[17,new El(vl.Piano,"Electric Organ")],[18,new El(vl.Piano,"Electric Organ")],[19,new El(vl.Piano,"Electric Organ")],[20,new El(vl.Piano,"Electric Organ")],[21,new El(vl.Piano,"Electric Organ")],[22,new El(vl.Woodwind,"Recorder")],[23,new El(vl.Piano,"Electric Organ")],[24,new El(vl.ClassicalGuitar,"Nylon Guitar")],[25,new El(vl.SteelGuitar,"Steel Guitar")],[26,new El(vl.SteelGuitar,"Electric Guitar")],[27,new El(vl.ElectricGuitar,"Electric Guitar")],[28,new El(vl.ElectricGuitar,"Electric Guitar")],[29,new El(vl.ElectricGuitar,"Electric Guitar")],[30,new El(vl.SteelGuitar,"Electric Guitar")],[31,new El(vl.SteelGuitar,"Electric Guitar")],[32,new El(vl.Bass,"Acoustic Bass")],[33,new El(vl.Bass,"Electric Bass")],[34,new El(vl.Bass,"Electric Bass")],[35,new El(vl.Bass,"Acoustic Bass")],[36,new El(vl.Bass,"Electric Bass")],[37,new El(vl.Bass,"Electric Bass")],[38,new El(vl.Synth,"Synth Bass")],[39,new El(vl.Synth,"Synth Bass")],[40,new El(vl.Strings,"Violin")],[41,new El(vl.Strings,"Viola")],[42,new El(vl.Strings,"Cello")],[43,new El(vl.Strings,"Contrabass")],[44,new El(vl.Strings,"Violin")],[45,new El(vl.Strings,"Violin")],[46,new El(vl.Piano,"Harp")],[47,new El(vl.Membraphone,"Timpani")],[48,new El(vl.Strings,"Violin")],[49,new El(vl.Strings,"Violin")],[50,new El(vl.Strings,"Violin")],[51,new El(vl.Strings,"Violin")],[52,new El(vl.Vocal,"Voice")],[53,new El(vl.Vocal,"Voice")],[54,new El(vl.Vocal,"Voice")],[55,new El(vl.Synth,"Pad Synthesizer")],[56,new El(vl.Brass,"Trumpet")],[57,new El(vl.Brass,"Trombone")],[58,new El(vl.Brass,"Tuba")],[59,new El(vl.Brass,"Trumpet")],[60,new El(vl.Brass,"French Horn")],[61,new El(vl.Brass,"Trumpet")],[62,new El(vl.Brass,"Trumpet")],[63,new El(vl.Brass,"Trumpet")],[64,new El(vl.Reed,"Saxophone")],[65,new El(vl.Reed,"Saxophone")],[66,new El(vl.Reed,"Saxophone")],[67,new El(vl.Reed,"Saxophone")],[68,new El(vl.Reed,"Oboe")],[69,new El(vl.Reed,"English Horn")],[70,new El(vl.Reed,"Bassoon")],[71,new El(vl.Reed,"Clarinet")],[72,new El(vl.Reed,"Piccolo")],[73,new El(vl.Woodwind,"Flute")],[74,new El(vl.Woodwind,"Recorder")],[75,new El(vl.Woodwind,"Flute")],[76,new El(vl.Woodwind,"Recorder")],[77,new El(vl.Woodwind,"Flute")],[78,new El(vl.Woodwind,"Recorder")],[79,new El(vl.Woodwind,"Flute")],[80,new El(vl.Synth,"Lead Synthesizer")],[81,new El(vl.Synth,"Lead Synthesizer")],[82,new El(vl.Synth,"Lead Synthesizer")],[83,new El(vl.Synth,"Lead Synthesizer")],[84,new El(vl.Synth,"Lead Synthesizer")],[85,new El(vl.Synth,"Lead Synthesizer")],[86,new El(vl.Synth,"Lead Synthesizer")],[87,new El(vl.Synth,"Lead Synthesizer")],[88,new El(vl.Synth,"Pad Synthesizer")],[89,new El(vl.Synth,"Pad Synthesizer")],[90,new El(vl.Synth,"Pad Synthesizer")],[91,new El(vl.Synth,"Pad Synthesizer")],[92,new El(vl.Synth,"Pad Synthesizer")],[93,new El(vl.Synth,"Pad Synthesizer")],[94,new El(vl.Synth,"Pad Synthesizer")],[95,new El(vl.Synth,"Pad Synthesizer")],[96,new El(vl.Fx,"Pad Synthesizer")],[97,new El(vl.Fx,"Pad Synthesizer")],[98,new El(vl.Fx,"Pad Synthesizer")],[99,new El(vl.Fx,"Pad Synthesizer")],[100,new El(vl.Fx,"Lead Synthesizer")],[101,new El(vl.Fx,"Lead Synthesizer")],[102,new El(vl.Fx,"Lead Synthesizer")],[103,new El(vl.Fx,"Trumpet")],[104,new El(vl.ElectricGuitar,"Banjo")],[105,new El(vl.Banjo,"Banjo")],[106,new El(vl.Ukulele,"Ukulele")],[107,new El(vl.Banjo,"Banjo")],[108,new El(vl.PitchedIdiophone,"Xylophone")],[109,new El(vl.Reed,"Bassoon")],[110,new El(vl.Strings,"Violin")],[111,new El(vl.Woodwind,"Flute")],[112,new El(vl.PitchedIdiophone,"Xylophone")],[113,new El(vl.Idiophone,"Celesta")],[114,new El(vl.PitchedIdiophone,"Vibraphone")],[115,new El(vl.Idiophone,"Xylophone")],[116,new El(vl.Membraphone,"Xylophone")],[117,new El(vl.Membraphone,"Xylophone")],[118,new El(vl.Membraphone,"Xylophone")],[119,new El(vl.Idiophone,"Celesta")],[120,new El(vl.Fx,"Steel Guitar")],[121,new El(vl.Fx,"Recorder")],[122,new El(vl.Fx,"Recorder")],[123,new El(vl.Fx,"Recorder")],[124,new El(vl.Fx,"Recorder")],[125,new El(vl.Fx,"Recorder")],[126,new El(vl.Fx,"Recorder")],[127,new El(vl.Fx,"Timpani")]]),Fl.DrumKitProgramInfo=new El(vl.PercussionKit,"Drums","drumKit");class Dl{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=Dl.CrcInit,this.reset()}update(e,t,s){for(let i=0;i<s;i++)this._checkValue=Dl.Crc32Lookup[255&(this._checkValue^e[t+i])]^this._checkValue>>>8}reset(){this._checkValue=Dl.CrcInit}}Dl.Crc32Lookup=Dl.buildCrc32Lookup(),Dl.CrcInit=4294967295;class Ll{}Ll.MAX_WBITS=15,Ll.WSIZE=1<<Ll.MAX_WBITS,Ll.WMASK=Ll.WSIZE-1,Ll.MIN_MATCH=3,Ll.MAX_MATCH=258,Ll.DEFAULT_MEM_LEVEL=8,Ll.PENDING_BUF_SIZE=1<<Ll.DEFAULT_MEM_LEVEL+8,Ll.HASH_BITS=Ll.DEFAULT_MEM_LEVEL+7,Ll.HASH_SIZE=1<<Ll.HASH_BITS,Ll.HASH_SHIFT=(Ll.HASH_BITS+Ll.MIN_MATCH-1)/Ll.MIN_MATCH,Ll.HASH_MASK=Ll.HASH_SIZE-1,Ll.MIN_LOOKAHEAD=Ll.MAX_MATCH+Ll.MIN_MATCH+1,Ll.MAX_DIST=Ll.WSIZE-Ll.MIN_LOOKAHEAD;class Ml{constructor(e,t,s,i){this.length=null,this.numCodes=0,this.codes=null,this.huffman=e,this.minNumCodes=s,this.maxLength=i,this.freqs=new Int16Array(t),this.bitLengthCounts=new Int32Array(i)}reset(){for(let e=0;e<this.freqs.length;e++)this.freqs[e]=0;this.codes=null,this.length=null}buildTree(){let e=this.freqs.length,t=new Int32Array(e),s=0,i=0;for(let a=0;a<e;a++){let e=this.freqs[a];if(0!==e){let r=s++;for(;r>0;){let s=Math.floor((r-1)/2);if(!(this.freqs[t[s]]>e))break;t[r]=t[s],r=s}t[r]=a,i=a}}for(;s<2;){let e=i<2?++i:0;t[s++]=e}this.numCodes=Math.max(i+1,this.minNumCodes);let a=s,r=new Int32Array(4*s-2),n=new Int32Array(2*s-1),o=a;for(let e=0;e<s;e++){let s=t[e];r[2*e]=s,r[2*e+1]=-1,n[e]=this.freqs[s]<<8,t[e]=e}do{let e=t[0],i=t[--s],a=0,h=1;for(;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*h+1;let l=n[i];for(;h=a,a>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i;let d=t[0];i=o++,r[2*i]=e,r[2*i+1]=d;let c=Math.min(255&n[e],255&n[d]);for(l=n[e]+n[d]-c+1,n[i]=l,a=0,h=1;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*a+1;for(;h=a,h>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i}while(s>1);this.buildLength(r)}buildLength(e){this.length=new Uint8Array(this.freqs.length);let t=Math.floor(e.length/2),s=Math.floor((t+1)/2),i=0;for(let e=0;e<this.maxLength;e++)this.bitLengthCounts[e]=0;let a=new Int32Array(t);a[t-1]=0;for(let s=t-1;s>=0;s--)if(-1!=e[2*s+1]){let t=a[s]+1;t>this.maxLength&&(t=this.maxLength,i++),a[e[2*s]]=t,a[e[2*s+1]]=t}else{let t=a[s];this.bitLengthCounts[t-1]++,this.length[e[2*s]]=a[s]}if(0==i)return;let r=this.maxLength-1;do{for(;0==this.bitLengthCounts[--r];);do{this.bitLengthCounts[r]--,this.bitLengthCounts[++r]++,i-=1<<this.maxLength-1-r}while(i>0&&r<this.maxLength-1)}while(i>0);this.bitLengthCounts[this.maxLength-1]+=i,this.bitLengthCounts[this.maxLength-2]-=i;let n=2*s;for(let t=this.maxLength;0!=t;t--){let s=this.bitLengthCounts[t-1];for(;s>0;){let i=2*e[n++];-1==e[i+1]&&(this.length[e[i]]=t,s--)}}}getEncodedLength(){let e=0;for(let t=0;t<this.freqs.length;t++)e+=this.freqs[t]*this.length[t];return e}calcBLFreq(e){let t,s,i,a=-1,r=0;for(;r<this.numCodes;){i=1;let n=this.length[r];for(0==n?(t=138,s=3):(t=6,s=3,a!=n&&(e.freqs[n]++,i=0)),a=n,r++;r<this.numCodes&&a==this.length[r]&&(r++,!(++i>=t)););i<s?e.freqs[a]+=i:0!=a?e.freqs[Ml.Repeat3To6]++:i<=10?e.freqs[Ml.Repeat3To10]++:e.freqs[Ml.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]=Il.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(Ml.Repeat3To6),this.huffman.pending.writeBits(i-3,2)):i<=10?(e.writeSymbol(Ml.Repeat3To10),this.huffman.pending.writeBits(i-3,3)):(e.writeSymbol(Ml.Repeat11To138),this.huffman.pending.writeBits(i-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}Ml.Repeat3To6=16,Ml.Repeat3To10=17,Ml.Repeat11To138=18;class Il{static staticInit(){let e=0;for(;e<144;)Il.staticLCodes[e]=Il.bitReverse(48+e<<8),Il.staticLLength[e++]=8;for(;e<256;)Il.staticLCodes[e]=Il.bitReverse(256+e<<7),Il.staticLLength[e++]=9;for(;e<280;)Il.staticLCodes[e]=Il.bitReverse(-256+e<<9),Il.staticLLength[e++]=7;for(;e<Il.LITERAL_NUM;)Il.staticLCodes[e]=Il.bitReverse(-88+e<<8),Il.staticLLength[e++]=8;for(e=0;e<Il.DIST_NUM;e++)Il.staticDCodes[e]=Il.bitReverse(e<<11),Il.staticDLength[e]=5}static bitReverse(e){return Il.bit4Reverse[15&e]<<12|Il.bit4Reverse[e>>4&15]<<8|Il.bit4Reverse[e>>8&15]<<4|Il.bit4Reverse[e>>12]}constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new Ml(this,Il.LITERAL_NUM,257,15),this.distTree=new Ml(this,Il.DIST_NUM,1,15),this.blTree=new Ml(this,Il.BITLEN_NUM,4,7),this.d_buf=new Int16Array(Il.BUFSIZE),this.l_buf=new Uint8Array(Il.BUFSIZE)}isFull(){return this.last_lit>=Il.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((Il.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[Il.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[Il.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<Il.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*Il.staticLLength[e];for(let e=0;e<Il.DIST_NUM;e++)n+=this.distTree.freqs[e]*Il.staticDLength[e];r>=n&&(r=n),t>=0&&s+4<r>>3?this.flushStoredBlock(e,t,s,i):r==n?(this.pending.writeBits((Il.STATIC_TREES<<1)+(i?1:0),3),this.literalTree.setStaticCodes(Il.staticLCodes,Il.staticLLength),this.distTree.setStaticCodes(Il.staticDCodes,Il.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((Il.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[Il.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=Il.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=Il.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(Il.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;let s=Il.Lcode(t-3);this.literalTree.freqs[s]++,s>=265&&s<285&&(this.extra_bits+=Math.floor((s-261)/4));let i=Il.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}}Il.BUFSIZE=1<<Ll.DEFAULT_MEM_LEVEL+6,Il.LITERAL_NUM=286,Il.STORED_BLOCK=0,Il.STATIC_TREES=1,Il.DYN_TREES=2,Il.DIST_NUM=30,Il.staticLCodes=new Int16Array(Il.LITERAL_NUM),Il.staticLLength=new Uint8Array(Il.LITERAL_NUM),Il.staticDCodes=new Int16Array(Il.DIST_NUM),Il.staticDLength=new Uint8Array(Il.DIST_NUM),Il.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Il.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),Il.BITLEN_NUM=19,Il.EOF_SYMBOL=256,Il.staticInit();class Al{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 Il(e),this.inputCrc=new Dl,this.window=new Uint8Array(2*Ll.WSIZE),this.head=new Int16Array(Ll.HASH_SIZE),this.prev=new Int16Array(Ll.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=Ll.MIN_MATCH-1;for(let e=0;e<Ll.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<Ll.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<Ll.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<Ll.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=Ll.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*Ll.WSIZE-Ll.MIN_LOOKAHEAD&&this.slideWindow();let e=this.matchStart,s=this.matchLen;if(this.lookahead>=Ll.MIN_MATCH){let e=this.insertString();0!=e&&this.strstart-e<=Ll.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen==Ll.MIN_MATCH&&this.strstart-this.matchStart>Al.TooFar&&(this.matchLen=Ll.MIN_MATCH-1)}if(s>=Ll.MIN_MATCH&&this.matchLen<=s){this.huffman.tallyDist(this.strstart-1-e,s),s-=2;do{this.strstart++,this.lookahead--,this.lookahead>=Ll.MIN_MATCH&&this.insertString()}while(--s>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=Ll.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(Ll.MAX_MATCH,this.lookahead)-1,a=Math.max(s-Ll.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,Ll.MIN_MATCH-1),s+this.matchLen>i)return!1;let l=r[s+this.matchLen-1],d=r[s+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,s=this.strstart,r[t+this.matchLen]==d&&r[t+this.matchLen-1]==l&&r[t]==r[s]&&r[++t]==r[++s]){switch((i-s)%8){case 1:if(r[++s]==r[++t])break;break;case 2:if(r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 3:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 4:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 5:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 6:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 7:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break}if(r[s]==r[t])do{if(s==i){++s,++t;break}}while(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]);if(s-this.strstart>this.matchLen){if(this.matchStart=e,this.matchLen=s-this.strstart,this.matchLen>=h)break;l=r[s-1],d=r[s]}e=65535&n[e&Ll.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=Ll.MIN_MATCH}insertString(){let e,t=(this.insertHashIndex<<Ll.HASH_SHIFT^this.window[this.strstart+(Ll.MIN_MATCH-1)])&Ll.HASH_MASK;return e=this.head[t],this.prev[this.strstart&Ll.WMASK]=e,this.head[t]=this.strstart,this.insertHashIndex=t,65535&e}fillWindow(){if(this.strstart>=Ll.WSIZE+Ll.MAX_DIST&&this.slideWindow(),this.lookahead<Ll.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*Ll.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>=Ll.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(Ll.WSIZE,Ll.WSIZE+Ll.WSIZE),0),this.matchStart-=Ll.WSIZE,this.strstart-=Ll.WSIZE,this.blockStart-=Ll.WSIZE;for(let e=0;e<Ll.HASH_SIZE;++e){let t=65535&this.head[e];this.head[e]=t>=Ll.WSIZE?t-Ll.WSIZE:0}for(let e=0;e<Ll.WSIZE;e++){let t=65535&this.prev[e];this.prev[e]=t>=Ll.WSIZE?t-Ll.WSIZE:0}}}Al.TooFar=4096;class Ol{get isFlushed(){return 0===this._end}constructor(e){this._start=0,this._end=0,this._bits=0,this.bitCount=0,this._buffer=new Uint8Array(e)}reset(){this._start=0,this._end=0,this.bitCount=0}writeShortMSB(e){this._buffer[this._end++]=e>>8&255,this._buffer[this._end++]=255&e}writeShort(e){this._buffer[this._end++]=e,this._buffer[this._end++]=e>>8}writeBlock(e,t,s){this._buffer.set(e.subarray(t,t+s),this._end),this._end+=s}flush(e,t,s){return this.bitCount>=8&&(this._buffer[this._end++]=255&this._bits,this._bits>>=8,this.bitCount-=8),s>this._end-this._start?(s=this._end-this._start,e.set(this._buffer.subarray(this._start,this._start+s),t),this._start=0,this._end=0):(e.set(this._buffer.subarray(this._start,this._start+s),t),this._start+=s),s}writeBits(e,t){this._bits|=e<<this.bitCount,this.bitCount+=t,this.bitCount>=16&&(this._buffer[this._end++]=255&this._bits,this._buffer[this._end++]=this._bits>>8&255,this._bits>>=16,this.bitCount-=16)}alignToByte(){this.bitCount>0&&(this._buffer[this._end++]=255&this._bits,this.bitCount>8&&(this._buffer[this._end++]=this._bits>>8&255)),this._bits=0,this.bitCount=0}}class Rl{get inputCrc(){return this._engine.inputCrc.value}constructor(){this._state=0,this._pending=new Ol(Ll.PENDING_BUF_SIZE),this._engine=new Al(this._pending),this.reset()}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state==Rl.FinishedState&&this._pending.isFlushed}reset(){this._state=Rl.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==Rl.FinishedState)break;if(!this._engine.deflate(!!(this._state&Rl.IsFlushing),!!(this._state&Rl.IsFinishing)))switch(this._state){case Rl.BusyState:return i-s;case Rl.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=Rl.BusyState;break;case Rl.FinishingState:this._pending.alignToByte(),this._state=Rl.FinishedState}}return i-s}finish(){this._state|=Rl.IsFlushing|Rl.IsFinishing}}Rl.IsFlushing=4,Rl.IsFinishing=8,Rl.BusyState=16,Rl.FlushingState=20,Rl.FinishingState=28,Rl.FinishedState=30;class Vl{constructor(e,t,s,i,a){this.entry=e,this.crc32=t,this.localHeaderOffset=s,this.compressionMode=i,this.compressedSize=a}}class Hl{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new Rl,this._data=e}writeEntry(e){const t=qs.CompressionMethodDeflate,s=Oe.empty(),i=this.compress(s,e.data,t),a=s.toArray(),r=new Vl(e,i,this._data.bytesWritten,t,s.length);this._centralDirectoryHeaders.push(r),Ae.writeInt32LE(this._data,qs.LocalFileHeaderSignature),Ae.writeUInt16LE(this._data,10),Ae.writeUInt16LE(this._data,2048),Ae.writeUInt16LE(this._data,t),Ae.writeInt16LE(this._data,0),Ae.writeInt16LE(this._data,0),Ae.writeInt32LE(this._data,i),Ae.writeInt32LE(this._data,a.length),Ae.writeInt32LE(this._data,e.data.length),Ae.writeInt16LE(this._data,e.fullName.length),Ae.writeInt16LE(this._data,0);const n=Ae.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,s){if(s!=qs.CompressionMethodDeflate){const s=new Dl;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){Ae.writeInt32LE(this._data,qs.EndOfCentralDirSignature),Ae.writeInt16LE(this._data,0),Ae.writeInt16LE(this._data,0),Ae.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Ae.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Ae.writeInt32LE(this._data,t-e),Ae.writeInt32LE(this._data,e),Ae.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){Ae.writeInt32LE(this._data,qs.CentralFileHeaderSignature),Ae.writeUInt16LE(this._data,10),Ae.writeUInt16LE(this._data,10),Ae.writeUInt16LE(this._data,2048),Ae.writeUInt16LE(this._data,e.compressionMode),Ae.writeInt16LE(this._data,0),Ae.writeInt16LE(this._data,0),Ae.writeInt32LE(this._data,e.crc32),Ae.writeInt32LE(this._data,e.compressedSize),Ae.writeInt32LE(this._data,e.entry.data.length),Ae.writeInt16LE(this._data,e.entry.fullName.length),Ae.writeInt16LE(this._data,0),Ae.writeInt16LE(this._data,0),Ae.writeInt16LE(this._data,0),Ae.writeInt16LE(this._data,0),Ae.writeInt32LE(this._data,0),Ae.writeInt32LE(this._data,e.localHeaderOffset);const t=Ae.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}var Gl=Object.freeze({__proto__:null,Gp7Exporter:class extends Cl{get name(){return"Guitar Pro 7"}constructor(){super()}writeScore(e){re.debug(this.name,"Writing data entries");const t=(new Fl).writeXml(e),s=cs.writeForScore(e),i=Bs.writeForScore(e),a=$s.writeForScore(e);re.debug(this.name,"Writing ZIP entries");let r=new Hl(this.data);r.writeEntry(new qs("VERSION",Ae.stringToBytes("7.0"))),r.writeEntry(new qs("Content/",new Uint8Array(0))),r.writeEntry(new qs("Content/BinaryStylesheet",s)),r.writeEntry(new qs("Content/PartConfiguration",i)),r.writeEntry(new qs("Content/LayoutConfiguration",a)),r.writeEntry(new qs("Content/score.gpif",Ae.stringToBytes(t))),r.end()}},ScoreExporter:Cl}),Wl=Object.freeze({__proto__:null,AlphaSynthMidiFileHandler:Ma,AlphaTabMetronomeEvent:ct,AlphaTabRestEvent:ut,BeatTickLookup:Ra,ControlChangeEvent:ft,get ControllerType(){return Os},EndOfTrackEvent:wt,MasterBarTickLookup:Ha,MidiEvent:ht,get MidiEventType(){return je},MidiFile:ot,get MidiFileFormat(){return qe},MidiFileGenerator:Ja,MidiTickLookup:Wa,MidiTickLookupFindBeatResult:Ga,NoteBendEvent:_t,NoteEvent:pt,NoteOffEvent:mt,NoteOnEvent:gt,PitchBendEvent:St,ProgramChangeEvent:yt,TempoChangeEvent:bt,TimeSignatureEvent:lt}),zl=Object.freeze({__proto__:null,BarBounds:xa,BeatBounds:Na,Bounds:ds,BoundsLookup:Ea,MasterBarBounds:va,NoteBounds:Pa,RenderFinishedEventArgs:Ta,ScoreRenderer:Fa,StaffSystemBounds:Ca}),Ul=Object.freeze({__proto__:null,ActiveBeatsChangedEventArgs:tr,AlphaSynth:Sa,AlphaSynthAudioWorkletOutput:yr,AlphaSynthScriptProcessorOutput:cr,AlphaSynthWebAudioOutputBase:dr,AlphaSynthWebWorkerApi:pr,CircularSampleBuffer:lr,MidiEventsPlayedEventArgs:ya,PlaybackRange:Ya,PlaybackRangeChangedEventArgs:ba,get PlayerState(){return Es},PlayerStateChangedEventArgs:di,PositionChangedEventArgs:ci}),Xl=Object.freeze({__proto__:null});export{_r as AlphaTabApi,j as AlphaTabError,s as AlphaTabErrorType,ae as ConsoleLogger,xl as CoreSettings,kt as DisplaySettings,Tl as Environment,ar as FileLoadError,k as FingeringMode,Pe as FormatError,Tt as ImporterSettings,Bl as LayoutEngineFactory,e as LayoutMode,N as LogLevel,re as Logger,x as NotationElement,T as NotationMode,se as NotationSettings,$e as PlayerOutputMode,vt as PlayerSettings,ur as ProgressEventArgs,kl as RenderEngineFactory,Bt as RenderingResources,er as ResizeEventArgs,Qe as ScrollMode,Ot as Settings,t as StaveProfile,Ke as SystemsLayoutMode,B as TabRhythmMode,xt as VibratoPlaybackSettings,Rs as WebPlatform,Gl as exporter,Pl as importer,Xl as json,Nl as meta,Wl as midi,ns as model,Jn as platform,zl as rendering,Ul as synth};
|
|
2
2
|
//# sourceMappingURL=alphaTab.core.min.mjs.map
|