@coderline/alphatab 1.3.0-alpha.148 → 1.3.0-alpha.154

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * alphaTab v1.3.0-alpha.148 (develop, build 148)
2
+ * alphaTab v1.3.0-alpha.154 (develop, build 154)
3
3
  *
4
4
  * Copyright © 2022, Daniel Kuschny and Contributors, All rights reserved.
5
5
  *
@@ -14,4 +14,4 @@
14
14
  * Copyright (C) 2012 Steve Folta (https://github.com/stevefolta/SFZero)
15
15
  */
16
16
 
17
- var e,t,s,i,a,r,n,o,h,l,c,d,u,p,g,f,m,y,b,S,w,_,B,T,k,v,x,N,P,E,C,F,L,M,I,D,R,A,O,G,V,H,W,z,U,X,Y,q,J,Q,j,K,$,Z,ee,te,se,ie,ae,re,ne,oe,he,le,ce;!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 de{static getValue(e){return de._values||(de._values=new Map),e=e.toLowerCase().split(" ").join(""),de._values.has(e)?de._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}}de._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 ue{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 pe extends Error{constructor(e,t="",s){super(null!=t?t:""),this.type=e,this.inner=null!=s?s:null,Object.setPrototypeOf(this,pe.prototype)}}class ge extends pe{constructor(e=null,t=null){super(s.Format,null!=e?e:"Unsupported format"),this.inner=t,Object.setPrototypeOf(this,ge.prototype)}}!function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy"}(i||(i={})),function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(a||(a={}));class fe{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 fe;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 fe;return i.type=a.Instrument,i.isLinear=e,i.ratioPosition=t,i.value=s,i}}!function(e){e[e.Neutral=0]="Neutral",e[e.C3=1]="C3",e[e.C4=2]="C4",e[e.F4=3]="F4",e[e.G2=4]="G2"}(r||(r={})),function(e){e[e._15ma=0]="_15ma",e[e._8va=1]="_8va",e[e.Regular=2]="Regular",e[e._8vb=3]="_8vb",e[e._15mb=4]="_15mb"}(n||(n={})),function(e){e[e.None=0]="None",e[e.Simple=1]="Simple",e[e.FirstOfDouble=2]="FirstOfDouble",e[e.SecondOfDouble=3]="SecondOfDouble"}(o||(o={}));class me{constructor(){this.id=me._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}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){this.isMultiVoice=!1;for(let s=0,i=this.voices.length;s<i;s++){let i=this.voices[s];i.finish(e,t),s>0&&!i.isEmpty&&(this.isMultiVoice=!0)}}calculateDuration(){let e=0;for(let t of this.voices){let s=t.calculateDuration();s>e&&(e=s)}return e}}me._globalBarId=0;class ye{static ticksToMillis(e,t){return e*(6e4/(t*ye.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*ye.QuarterTime))|0}static toTicks(e){return ye.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),ye.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 ye.MinVelocity+e*ye.VelocityIncrement}}ye.QuarterTime=960,ye.MinVelocity=15,ye.VelocityIncrement=16;class be{constructor(e=0,t=0){this.offset=e,this.value=t}}be.MaxPosition=60,be.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(h||(h={})),function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Bend=2]="Bend",e[e.Release=3]="Release",e[e.BendRelease=4]="BendRelease",e[e.Hold=5]="Hold",e[e.Prebend=6]="Prebend",e[e.PrebendBend=7]="PrebendBend",e[e.PrebendRelease=8]="PrebendRelease"}(l||(l={})),function(e){e[e.None=0]="None",e[e.BrushUp=1]="BrushUp",e[e.BrushDown=2]="BrushDown",e[e.ArpeggioUp=3]="ArpeggioUp",e[e.ArpeggioDown=4]="ArpeggioDown"}(c||(c={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(d||(d={})),function(e){e[e.QuadrupleWhole=-4]="QuadrupleWhole",e[e.DoubleWhole=-2]="DoubleWhole",e[e.Whole=1]="Whole",e[e.Half=2]="Half",e[e.Quarter=4]="Quarter",e[e.Eighth=8]="Eighth",e[e.Sixteenth=16]="Sixteenth",e[e.ThirtySecond=32]="ThirtySecond",e[e.SixtyFourth=64]="SixtyFourth",e[e.OneHundredTwentyEighth=128]="OneHundredTwentyEighth",e[e.TwoHundredFiftySixth=256]="TwoHundredFiftySixth"}(u||(u={})),function(e){e[e.PPP=0]="PPP",e[e.PP=1]="PP",e[e.P=2]="P",e[e.MP=3]="MP",e[e.MF=4]="MF",e[e.F=5]="F",e[e.FF=6]="FF",e[e.FFF=7]="FFF"}(p||(p={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(g||(g={})),function(e){e[e.Unknown=-2]="Unknown",e[e.NoOrDead=-1]="NoOrDead",e[e.Thumb=0]="Thumb",e[e.IndexFinger=1]="IndexFinger",e[e.MiddleFinger=2]="MiddleFinger",e[e.AnnularFinger=3]="AnnularFinger",e[e.LittleFinger=4]="LittleFinger"}(f||(f={})),function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Artificial=2]="Artificial",e[e.Pinch=3]="Pinch",e[e.Tap=4]="Tap",e[e.Semi=5]="Semi",e[e.Feedback=6]="Feedback"}(m||(m={})),function(e){e[e.Default=0]="Default",e[e.ForceNone=1]="ForceNone",e[e.ForceNatural=2]="ForceNatural",e[e.ForceSharp=3]="ForceSharp",e[e.ForceDoubleSharp=4]="ForceDoubleSharp",e[e.ForceFlat=5]="ForceFlat",e[e.ForceDoubleFlat=6]="ForceDoubleFlat"}(y||(y={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(b||(b={})),function(e){e[e.None=0]="None",e[e.Shift=1]="Shift",e[e.Legato=2]="Legato",e[e.OutUp=3]="OutUp",e[e.OutDown=4]="OutDown",e[e.PickSlideDown=5]="PickSlideDown",e[e.PickSlideUp=6]="PickSlideUp"}(S||(S={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(w||(w={})),function(e){e[e.Hidden=0]="Hidden",e[e.ShowWithBeams=1]="ShowWithBeams",e[e.ShowWithBars=2]="ShowWithBars"}(_||(_={})),function(e){e[e.ScoreDefault=0]="ScoreDefault",e[e.ScoreForcePiano=1]="ScoreForcePiano",e[e.SingleNoteEffectBand=2]="SingleNoteEffectBand",e[e.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano"}(B||(B={})),function(e){e[e.GuitarPro=0]="GuitarPro",e[e.SongBook=1]="SongBook"}(T||(T={})),function(e){e[e.ScoreTitle=0]="ScoreTitle",e[e.ScoreSubTitle=1]="ScoreSubTitle",e[e.ScoreArtist=2]="ScoreArtist",e[e.ScoreAlbum=3]="ScoreAlbum",e[e.ScoreWords=4]="ScoreWords",e[e.ScoreMusic=5]="ScoreMusic",e[e.ScoreWordsAndMusic=6]="ScoreWordsAndMusic",e[e.ScoreCopyright=7]="ScoreCopyright",e[e.GuitarTuning=8]="GuitarTuning",e[e.TrackNames=9]="TrackNames",e[e.ChordDiagrams=10]="ChordDiagrams",e[e.ParenthesisOnTiedBends=11]="ParenthesisOnTiedBends",e[e.TabNotesOnTiedBends=12]="TabNotesOnTiedBends",e[e.ZerosOnDiveWhammys=13]="ZerosOnDiveWhammys",e[e.EffectAlternateEndings=14]="EffectAlternateEndings",e[e.EffectCapo=15]="EffectCapo",e[e.EffectChordNames=16]="EffectChordNames",e[e.EffectCrescendo=17]="EffectCrescendo",e[e.EffectDynamics=18]="EffectDynamics",e[e.EffectFadeIn=19]="EffectFadeIn",e[e.EffectFermata=20]="EffectFermata",e[e.EffectFingering=21]="EffectFingering",e[e.EffectHarmonics=22]="EffectHarmonics",e[e.EffectLetRing=23]="EffectLetRing",e[e.EffectLyrics=24]="EffectLyrics",e[e.EffectMarker=25]="EffectMarker",e[e.EffectOttavia=26]="EffectOttavia",e[e.EffectPalmMute=27]="EffectPalmMute",e[e.EffectPickSlide=28]="EffectPickSlide",e[e.EffectPickStroke=29]="EffectPickStroke",e[e.EffectSlightBeatVibrato=30]="EffectSlightBeatVibrato",e[e.EffectSlightNoteVibrato=31]="EffectSlightNoteVibrato",e[e.EffectTap=32]="EffectTap",e[e.EffectTempo=33]="EffectTempo",e[e.EffectText=34]="EffectText",e[e.EffectTrill=35]="EffectTrill",e[e.EffectTripletFeel=36]="EffectTripletFeel",e[e.EffectWhammyBar=37]="EffectWhammyBar",e[e.EffectWideBeatVibrato=38]="EffectWideBeatVibrato",e[e.EffectWideNoteVibrato=39]="EffectWideNoteVibrato",e[e.EffectLeftHandTap=40]="EffectLeftHandTap"}(k||(k={}));class Se{constructor(){this.notationMode=T.GuitarPro,this.fingeringMode=B.ScoreDefault,this.elements=new Map,this.rhythmMode=_.Hidden,this.rhythmHeight=15,this.transpositionPitches=[],this.displayTranspositionPitches=[],this.smallGraceTabNotes=!0,this.extendBendArrowsOnTiedNotes=!0,this.extendLineEffectsToBeatEnd=!1,this.slurHeight=5}isNotationElementVisible(e){return this.elements.has(e)?this.elements.get(e):!Se.defaultElements.has(e)||Se.defaultElements.get(e)}}Se.defaultElements=new Map([[k.ZerosOnDiveWhammys,!1]]);class we{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}!function(e){e[e.None=0]="None",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warning=3]="Warning",e[e.Error=4]="Error"}(v||(v={}));class _e{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...s){console.debug(_e.format(e,t),...s)}warning(e,t,...s){console.warn(_e.format(e,t),...s)}info(e,t,...s){console.info(_e.format(e,t),...s)}error(e,t,...s){console.error(_e.format(e,t),...s)}}_e.logLevel=v.Info;class Be{static shouldLog(e){return Be.logLevel!==v.None&&e>=Be.logLevel}static debug(e,t,...s){Be.shouldLog(v.Debug)&&Be.log.debug(e,t,...s)}static warning(e,t,...s){Be.shouldLog(v.Warning)&&Be.log.warning(e,t,...s)}static info(e,t,...s){Be.shouldLog(v.Info)&&Be.log.info(e,t,...s)}static error(e,t,...s){Be.shouldLog(v.Error)&&Be.log.error(e,t,...s)}}Be.logLevel=v.Info,Be.log=new _e;class Te{constructor(){this.note=null,this.noteValue=0,this.octave=0}get realValue(){return 12*this.octave+this.noteValue}}class ke{static getIndex(e){return e<0?0:0|Math.log2(e)}static keySignatureIsFlat(e){return e<0}static keySignatureIsNatural(e){return 0===e}static keySignatureIsSharp(e){return e>0}static applyPitchOffsets(e,t){for(let s=0;s<t.tracks.length;s++){if(s<e.notation.displayTranspositionPitches.length)for(let i of t.tracks[s].staves)i.displayTranspositionPitch=-e.notation.displayTranspositionPitches[s];if(s<e.notation.transpositionPitches.length)for(let i of t.tracks[s].staves)i.transpositionPitch=-e.notation.transpositionPitches[s]}}static fingerToString(e,t,s,i){if(e.notation.fingeringMode===B.ScoreForcePiano||e.notation.fingeringMode===B.SingleNoteEffectBandForcePiano||de.isPiano(t.voice.bar.staff.track.playbackInfo.program))switch(s){case f.Unknown:case f.NoOrDead:return null;case f.Thumb:return"1";case f.IndexFinger:return"2";case f.MiddleFinger:return"3";case f.AnnularFinger:return"4";case f.LittleFinger:return"5";default:return null}if(i)switch(s){case f.Unknown:case f.NoOrDead:return"0";case f.Thumb:return"T";case f.IndexFinger:return"1";case f.MiddleFinger:return"2";case f.AnnularFinger:return"3";case f.LittleFinger:return"4";default:return null}switch(s){case f.Unknown:case f.NoOrDead:return null;case f.Thumb:return"p";case f.IndexFinger:return"i";case f.MiddleFinger:return"m";case f.AnnularFinger:return"a";case f.LittleFinger:return"c";default:return null}}static isTuning(e){return!!ke.parseTuning(e)}static parseTuning(e){let t="",s="";for(let i=0;i<e.length;i++){let a=e.charCodeAt(i);if(a>=48&&a<=57){if(!t)return null;s+=String.fromCharCode(a)}else{if(!(a>=65&&a<=90||a>=97&&a<=122||35===a))return null;t+=String.fromCharCode(a)}}if(!s||!t)return null;let i=new Te;return i.octave=parseInt(s)+1,i.note=t.toLowerCase(),i.noteValue=ke.getToneForText(i.note),i}static getTuningForText(e){let t=ke.parseTuning(e);return t?t.realValue:-1}static getToneForText(e){let t=0;switch(e.toLowerCase()){case"c":t=0;break;case"c#":case"db":t=1;break;case"d":t=2;break;case"d#":case"eb":t=3;break;case"e":t=4;break;case"f":t=5;break;case"f#":case"gb":t=6;break;case"g":t=7;break;case"g#":case"ab":t=8;break;case"a":t=9;break;case"a#":case"bb":t=10;break;case"b":t=11;break;default:return 0}return t}static newGuid(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)}static isAlmostEqualTo(e,t){return Math.abs(e-t)<1e-5}static toHexString(e,t=0){let s="";do{s=String.fromCharCode("0123456789ABCDEF".charCodeAt(15&e))+s,e>>=4}while(e>0);for(;s.length<t;)s="0"+s;return s}}!function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(x||(x={})),function(e){e[e.None=-1]="None",e[e.GClef=57424]="GClef",e[e.CClef=57436]="CClef",e[e.FClef=57442]="FClef",e[e.UnpitchedPercussionClef1=57449]="UnpitchedPercussionClef1",e[e.SixStringTabClef=57453]="SixStringTabClef",e[e.FourStringTabClef=57454]="FourStringTabClef",e[e.TimeSig0=57472]="TimeSig0",e[e.TimeSig1=57473]="TimeSig1",e[e.TimeSig2=57474]="TimeSig2",e[e.TimeSig3=57475]="TimeSig3",e[e.TimeSig4=57476]="TimeSig4",e[e.TimeSig5=57477]="TimeSig5",e[e.TimeSig6=57478]="TimeSig6",e[e.TimeSig7=57479]="TimeSig7",e[e.TimeSig8=57480]="TimeSig8",e[e.TimeSig9=57481]="TimeSig9",e[e.TimeSigCommon=57482]="TimeSigCommon",e[e.TimeSigCutCommon=57483]="TimeSigCutCommon",e[e.NoteheadDoubleWholeSquare=57505]="NoteheadDoubleWholeSquare",e[e.NoteheadDoubleWhole=57504]="NoteheadDoubleWhole",e[e.NoteheadWhole=57506]="NoteheadWhole",e[e.NoteheadHalf=57507]="NoteheadHalf",e[e.NoteheadBlack=57508]="NoteheadBlack",e[e.NoteheadNull=57509]="NoteheadNull",e[e.NoteheadXOrnate=57514]="NoteheadXOrnate",e[e.NoteheadTriangleUpWhole=57531]="NoteheadTriangleUpWhole",e[e.NoteheadTriangleUpHalf=57532]="NoteheadTriangleUpHalf",e[e.NoteheadTriangleUpBlack=57534]="NoteheadTriangleUpBlack",e[e.NoteheadDiamondBlackWide=57564]="NoteheadDiamondBlackWide",e[e.NoteheadDiamondWhite=57565]="NoteheadDiamondWhite",e[e.NoteheadDiamondWhiteWide=57566]="NoteheadDiamondWhiteWide",e[e.NoteheadCircleX=57523]="NoteheadCircleX",e[e.NoteheadXWhole=57511]="NoteheadXWhole",e[e.NoteheadXHalf=57512]="NoteheadXHalf",e[e.NoteheadXBlack=57513]="NoteheadXBlack",e[e.NoteheadParenthesis=57550]="NoteheadParenthesis",e[e.NoteheadSlashedBlack2=57552]="NoteheadSlashedBlack2",e[e.NoteheadCircleSlash=57591]="NoteheadCircleSlash",e[e.NoteheadHeavyX=57592]="NoteheadHeavyX",e[e.NoteheadHeavyXHat=57593]="NoteheadHeavyXHat",e[e.NoteQuarterUp=57813]="NoteQuarterUp",e[e.NoteEighthUp=57815]="NoteEighthUp",e[e.Tremolo3=57890]="Tremolo3",e[e.Tremolo2=57889]="Tremolo2",e[e.Tremolo1=57888]="Tremolo1",e[e.FlagEighthUp=57920]="FlagEighthUp",e[e.FlagEighthDown=57921]="FlagEighthDown",e[e.FlagSixteenthUp=57922]="FlagSixteenthUp",e[e.FlagSixteenthDown=57923]="FlagSixteenthDown",e[e.FlagThirtySecondUp=57924]="FlagThirtySecondUp",e[e.FlagThirtySecondDown=57925]="FlagThirtySecondDown",e[e.FlagSixtyFourthUp=57926]="FlagSixtyFourthUp",e[e.FlagSixtyFourthDown=57927]="FlagSixtyFourthDown",e[e.FlagOneHundredTwentyEighthUp=57928]="FlagOneHundredTwentyEighthUp",e[e.FlagOneHundredTwentyEighthDown=57929]="FlagOneHundredTwentyEighthDown",e[e.FlagTwoHundredFiftySixthUp=57930]="FlagTwoHundredFiftySixthUp",e[e.FlagTwoHundredFiftySixthDown=57931]="FlagTwoHundredFiftySixthDown",e[e.AccidentalFlat=57952]="AccidentalFlat",e[e.AccidentalNatural=57953]="AccidentalNatural",e[e.AccidentalSharp=57954]="AccidentalSharp",e[e.AccidentalDoubleSharp=57955]="AccidentalDoubleSharp",e[e.AccidentalDoubleFlat=57956]="AccidentalDoubleFlat",e[e.AccidentalQuarterToneFlatArrowUp=57968]="AccidentalQuarterToneFlatArrowUp",e[e.AccidentalQuarterToneSharpArrowUp=57972]="AccidentalQuarterToneSharpArrowUp",e[e.AccidentalQuarterToneNaturalArrowUp=57970]="AccidentalQuarterToneNaturalArrowUp",e[e.ArticAccentAbove=58528]="ArticAccentAbove",e[e.ArticStaccatoAbove=58530]="ArticStaccatoAbove",e[e.ArticMarcatoAbove=58540]="ArticMarcatoAbove",e[e.FermataAbove=58560]="FermataAbove",e[e.FermataShortAbove=58564]="FermataShortAbove",e[e.FermataLongAbove=58566]="FermataLongAbove",e[e.RestLonga=58593]="RestLonga",e[e.RestDoubleWhole=58594]="RestDoubleWhole",e[e.RestWhole=58595]="RestWhole",e[e.RestHalf=58596]="RestHalf",e[e.RestQuarter=58597]="RestQuarter",e[e.RestEighth=58598]="RestEighth",e[e.RestSixteenth=58599]="RestSixteenth",e[e.RestThirtySecond=58600]="RestThirtySecond",e[e.RestSixtyFourth=58601]="RestSixtyFourth",e[e.RestOneHundredTwentyEighth=58602]="RestOneHundredTwentyEighth",e[e.RestTwoHundredFiftySixth=58603]="RestTwoHundredFiftySixth",e[e.Repeat1Bar=58624]="Repeat1Bar",e[e.Repeat2Bars=58625]="Repeat2Bars",e[e.Ottava=58640]="Ottava",e[e.OttavaAlta=58641]="OttavaAlta",e[e.OttavaBassaVb=58652]="OttavaBassaVb",e[e.Quindicesima=58644]="Quindicesima",e[e.QuindicesimaAlta=58645]="QuindicesimaAlta",e[e.DynamicPPP=58666]="DynamicPPP",e[e.DynamicPP=58667]="DynamicPP",e[e.DynamicPiano=58656]="DynamicPiano",e[e.DynamicMP=58668]="DynamicMP",e[e.DynamicMF=58669]="DynamicMF",e[e.DynamicForte=58658]="DynamicForte",e[e.DynamicFF=58671]="DynamicFF",e[e.DynamicFFF=58672]="DynamicFFF",e[e.OrnamentTrill=58726]="OrnamentTrill",e[e.StringsDownBow=58896]="StringsDownBow",e[e.StringsUpBow=58898]="StringsUpBow",e[e.PictEdgeOfCymbal=59177]="PictEdgeOfCymbal",e[e.GuitarString0=59443]="GuitarString0",e[e.GuitarString1=59444]="GuitarString1",e[e.GuitarString2=59445]="GuitarString2",e[e.GuitarString3=59446]="GuitarString3",e[e.GuitarString4=59447]="GuitarString4",e[e.GuitarString5=59448]="GuitarString5",e[e.GuitarString6=59449]="GuitarString6",e[e.GuitarString7=59450]="GuitarString7",e[e.GuitarString8=59451]="GuitarString8",e[e.GuitarString9=59452]="GuitarString9",e[e.GuitarGolpe=59458]="GuitarGolpe",e[e.FretboardX=59481]="FretboardX",e[e.FretboardO=59482]="FretboardO",e[e.WiggleTrill=60068]="WiggleTrill",e[e.WiggleVibratoMediumFast=60126]="WiggleVibratoMediumFast",e[e.OctaveBaselineM=60565]="OctaveBaselineM",e[e.OctaveBaselineB=60563]="OctaveBaselineB"}(N||(N={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(P||(P={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(E||(E={}));class ve{constructor(e="",t=0,s=0,i=N.None,a=N.None,r=N.None,n=N.None,o=E.Middle){this.elementType=e,this.outputMidiNumber=s,this.staffLine=t,this.noteHeadDefault=i,this.noteHeadHalf=a!==N.None?a:i,this.noteHeadWhole=r!==N.None?r:i,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case u.Whole:return this.noteHeadWhole;case u.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class xe{static articulationFromElementVariation(e,t){return e<xe.gp6ElementAndVariationToArticulation.length?(t>=xe.gp6ElementAndVariationToArticulation.length&&(t=0),xe.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]:xe.getArticulationByValue(t)}static getElementAndVariation(e){const t=xe.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<xe.gp6ElementAndVariationToArticulation.length;e++){const s=xe.gp6ElementAndVariationToArticulation[e];for(let i=0;i<s.length;i++){const a=xe.getArticulationByValue(s[i]);if((null==a?void 0:a.outputMidiNumber)===t.outputMidiNumber)return[e,i]}}return[-1,-1]}static getArticulationByValue(e){return xe.instrumentArticulations.has(e)?xe.instrumentArticulations.get(e):null}}xe.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]],xe.instrumentArticulations=new Map([[38,new ve("snare",3,38,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[37,new ve("snare",3,37,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[91,new ve("snare",3,38,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite)],[42,new ve("hiHat",-1,42,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[92,new ve("hiHat",-1,46,N.NoteheadCircleSlash,N.NoteheadCircleSlash,N.NoteheadCircleSlash)],[46,new ve("hiHat",-1,46,N.NoteheadCircleX,N.NoteheadCircleX,N.NoteheadCircleX)],[44,new ve("hiHat",9,44,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[35,new ve("kickDrum",8,35,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[36,new ve("kickDrum",7,36,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[50,new ve("tom",1,50,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[48,new ve("tom",2,48,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[47,new ve("tom",4,47,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[45,new ve("tom",5,45,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[43,new ve("tom",6,43,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[93,new ve("ride",0,51,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.PictEdgeOfCymbal,E.Bottom)],[51,new ve("ride",0,51,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[53,new ve("ride",0,53,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite)],[94,new ve("ride",0,51,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.ArticStaccatoAbove,E.Top)],[55,new ve("splash",-2,55,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[95,new ve("splash",-2,55,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.ArticStaccatoAbove,E.Bottom)],[52,new ve("china",-3,52,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat)],[96,new ve("china",-3,52,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat)],[49,new ve("crash",-2,49,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX)],[97,new ve("crash",-2,49,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX,N.ArticStaccatoAbove,E.Bottom)],[57,new ve("crash",-1,57,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX)],[98,new ve("crash",-1,57,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX,N.ArticStaccatoAbove,E.Bottom)],[99,new ve("cowbell",1,56,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpHalf,N.NoteheadTriangleUpWhole)],[100,new ve("cowbell",1,56,N.NoteheadXBlack,N.NoteheadXHalf,N.NoteheadXWhole)],[56,new ve("cowbell",0,56,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpHalf,N.NoteheadTriangleUpWhole)],[101,new ve("cowbell",0,56,N.NoteheadXBlack,N.NoteheadXHalf,N.NoteheadXWhole)],[102,new ve("cowbell",-1,56,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpHalf,N.NoteheadTriangleUpWhole)],[103,new ve("cowbell",-1,56,N.NoteheadXBlack,N.NoteheadXHalf,N.NoteheadXWhole)],[77,new ve("woodblock",-9,77,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack)],[76,new ve("woodblock",-10,76,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack)],[60,new ve("bongo",-4,60,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[104,new ve("bongo",-5,60,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,E.Middle)],[105,new ve("bongo",-6,60,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[61,new ve("bongo",-7,61,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[106,new ve("bongo",-8,61,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,E.Middle)],[107,new ve("bongo",-16,61,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[66,new ve("timbale",10,66,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[65,new ve("timbale",9,65,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[68,new ve("agogo",12,68,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[67,new ve("agogo",11,67,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[64,new ve("conga",17,64,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[108,new ve("conga",16,64,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[109,new ve("conga",15,64,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,E.Middle)],[63,new ve("conga",14,63,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[110,new ve("conga",13,63,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[62,new ve("conga",19,62,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,E.Middle)],[72,new ve("whistle",-11,72,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[71,new ve("whistle",-17,71,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[73,new ve("guiro",38,73,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[74,new ve("guiro",37,74,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[86,new ve("surdo",36,86,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[87,new ve("surdo",35,87,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadParenthesis,E.Middle)],[54,new ve("tambourine",3,54,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack)],[111,new ve("tambourine",2,54,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.StringsUpBow,E.Bottom)],[112,new ve("tambourine",1,54,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.StringsDownBow,E.Bottom)],[113,new ve("tambourine",-7,54,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[79,new ve("cuica",30,79,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[78,new ve("cuica",29,78,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[58,new ve("vibraslap",28,58,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[81,new ve("triangle",27,81,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[80,new ve("triangle",26,80,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadParenthesis,E.Middle)],[114,new ve("grancassa",25,43,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[115,new ve("piatti",18,49,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[116,new ve("piatti",24,49,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[69,new ve("cabasa",23,69,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[117,new ve("cabasa",22,69,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,E.Bottom)],[85,new ve("castanets",21,85,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[75,new ve("claves",20,75,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[70,new ve("maraca",-12,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[118,new ve("maraca",-13,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,E.Bottom)],[119,new ve("maraca",-14,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[120,new ve("maraca",-15,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,E.Bottom)],[82,new ve("shaker",-23,54,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[122,new ve("shaker",-24,54,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,E.Bottom)],[84,new ve("bellTree",-18,53,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[123,new ve("bellTree",-19,53,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,E.Bottom)],[83,new ve("jingleBell",-20,53,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[124,new ve("unpitched",-21,62,N.NoteheadNull,N.NoteheadNull,N.NoteheadNull,N.GuitarGolpe,E.Top)],[125,new ve("unpitched",-22,62,N.NoteheadNull,N.NoteheadNull,N.NoteheadNull,N.GuitarGolpe,E.Bottom)],[39,new ve("handClap",3,39,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[40,new ve("snare",3,40,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[31,new ve("snare",3,40,N.NoteheadSlashedBlack2,N.NoteheadSlashedBlack2,N.NoteheadSlashedBlack2)],[41,new ve("tom",5,41,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[59,new ve("ride",2,59,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.PictEdgeOfCymbal,E.Bottom)],[126,new ve("ride",2,59,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[127,new ve("ride",2,59,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite)],[29,new ve("ride",2,59,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.ArticStaccatoAbove,E.Top)],[30,new ve("crash",-3,49,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[33,new ve("snare",3,37,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[34,new ve("snare",3,38,N.NoteheadBlack,N.NoteheadBlack,N.NoteheadBlack)]]);class Ne{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1}}class Pe{constructor(){this.id=Pe.GlobalNoteId++,this.index=0,this.accentuated=i.None,this.bendType=l.None,this.bendStyle=h.Default,this.bendOrigin=null,this.isContinuedBend=!1,this.bendPoints=null,this.maxBendPoint=null,this.fret=-1,this.string=-1,this.octave=-1,this.tone=-1,this.percussionArticulation=-1,this.isVisible=!0,this.isLeftHandTapped=!1,this.isHammerPullOrigin=!1,this.hammerPullOrigin=null,this.hammerPullDestination=null,this.isSlurDestination=!1,this.slurOrigin=null,this.slurDestination=null,this.harmonicType=m.None,this.harmonicValue=0,this.isGhost=!1,this.isLetRing=!1,this.letRingDestination=null,this.isPalmMute=!1,this.palmMuteDestination=null,this.isDead=!1,this.isStaccato=!1,this.slideInType=b.None,this.slideOutType=S.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=w.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=f.Unknown,this.rightHandFinger=f.Unknown,this.isFingering=!1,this.trillValue=-1,this.trillSpeed=u.ThirtySecond,this.durationPercent=1,this.accidentalMode=y.Default,this.dynamics=p.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this._noteIdBag=null}get hasBend(){return null!==this.bendPoints&&this.bendType!==l.None}get isStringed(){return this.string>=0}get isPiano(){return!this.isStringed&&this.octave>=0&&this.tone>=0}get isPercussion(){return!this.isStringed&&this.percussionArticulation>=0}get element(){return this.isPercussion?xe.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?xe.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==m.None}get isTieOrigin(){return null!==this.tieDestination}get trillFret(){return this.trillValue-this.stringTuning}get isTrill(){return this.trillValue>=0}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get stringTuning(){return this.beat.voice.bar.staff.capo+Pe.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(){let e=this.realValueWithoutHarmonic;return this.isStringed&&(this.harmonicType===m.Natural?e=this.harmonicPitch+this.stringTuning-this.beat.voice.bar.staff.transpositionPitch:e+=this.harmonicPitch),e}get realValueWithoutHarmonic(){return this.isPercussion?this.percussionArticulation:this.isStringed?this.fret+this.stringTuning-this.beat.voice.bar.staff.transpositionPitch:this.isPiano?12*this.octave+this.tone-this.beat.voice.bar.staff.transpositionPitch:0}get harmonicPitch(){if(this.harmonicType===m.None||!this.isStringed)return 0;let e=this.harmonicValue;return ke.isAlmostEqualTo(e,2.4)?36:ke.isAlmostEqualTo(e,2.7)?34:e<3?0:e<=3.5?31:e<=4?28:e<=5?24:e<=6?34:e<=7?19:e<=8.5?36:e<=9?28:e<=10?34:e<=11?0:e<=12?12:e<14?0:e<=15?34:e<=16?28:e<=17?36:e<=18?0:e<=19?19:e<=21?0:e<=22?36:e<=24?24:0}get initialBendValue(){return this.hasBend?Math.floor(this.bendPoints[0].value/2):this.bendOrigin?Math.floor(this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value/2):this.isTieDestination&&this.tieOrigin.bendOrigin?Math.floor(this.tieOrigin.bendOrigin.bendPoints[this.tieOrigin.bendOrigin.bendPoints.length-1].value/2):this.beat.hasWhammyBar?Math.floor(this.beat.whammyBarPoints[0].value/2):this.beat.isContinuedWhammy?Math.floor(this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value/2):0}get displayValue(){return this.displayValueWithoutBend+this.initialBendValue}get displayValueWithoutBend(){let e=this.realValue;switch(this.harmonicType!==m.Natural&&this.harmonicType!==m.None&&(e-=this.harmonicPitch),this.beat.ottava){case n._15ma:e-=24;break;case n._8va:e-=12;break;case n.Regular:break;case n._8vb:e+=12;break;case n._15mb:e+=24}switch(this.beat.voice.bar.clefOttava){case n._15ma:e-=24;break;case n._8va:e-=12;break;case n.Regular:break;case n._8vb:e+=12;break;case n._15mb:e+=24}return e-this.beat.voice.bar.staff.displayTranspositionPitch}get hasQuarterToneOffset(){return this.hasBend?this.bendPoints[0].value%2!=0:this.bendOrigin?this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value%2!=0:this.beat.hasWhammyBar?this.beat.whammyBarPoints[0].value%2!=0:!!this.beat.isContinuedWhammy&&this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value%2!=0}addBendPoint(e){let t=this.bendPoints;null===t&&(t=[],this.bendPoints=t),t.push(e),(!this.maxBendPoint||e.value>this.maxBendPoint.value)&&(this.maxBendPoint=e),this.bendType===l.None&&(this.bendType=l.Custom)}finish(e,t){let s=new we((()=>Pe.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=Pe.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case S.Shift:case S.Legato:this.slideTarget=s.value,this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=S.None}let a=null;this.isHammerPullOrigin&&this.hammerPullDestination?a=this.hammerPullDestination:this.slideOutType===S.Legato&&this.slideTarget&&(a=this.slideTarget),a&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===x.None?(this.effectSlurOrigin.effectSlurDestination=a,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=a,this.effectSlurDestination.effectSlurOrigin=this));const r=this.bendPoints;if(null!=r&&r.length>0&&this.bendType===l.Custom){let e=this.isTieDestination&&this.tieOrigin.hasBend;if(this.isContinuedBend=e,4===r.length){let t=r[0],s=r[1],i=r[2],a=r[3];s.value===i.value?a.value>t.value?s.value>a.value?this.bendType=l.BendRelease:!e&&t.value>0?(this.bendType=l.PrebendBend,r.splice(2,1),r.splice(1,1)):(this.bendType=l.Bend,r.splice(2,1),r.splice(1,1)):a.value<t.value?e?(this.bendType=l.Release,r.splice(2,1),r.splice(1,1)):(this.bendType=l.PrebendRelease,r.splice(2,1),r.splice(1,1)):s.value>t.value?this.bendType=l.BendRelease:t.value>0&&!e?(this.bendType=l.Prebend,r.splice(2,1),r.splice(1,1)):(this.bendType=l.Hold,r.splice(2,1),r.splice(1,1)):Be.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===r.length){let t=r[0],s=r[1];s.value>t.value?!e&&t.value>0?this.bendType=l.PrebendBend:this.bendType=l.Bend:s.value<t.value?this.bendType=e?l.Release:l.PrebendRelease:this.bendType=l.Hold}}else null!==r&&0!==r.length||(this.bendType=l.None);this.initialBendValue>0&&(this.accidentalMode=y.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+Pe.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+Pe.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-Pe.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){if(null!=this._noteIdBag){let t;e.has(Pe.NoteIdLookupKey)?t=e.get(Pe.NoteIdLookupKey):(t=new Map,e.set(Pe.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=Pe.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 Ne),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Ne),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Ne),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Ne),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Ne),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Ne),this._noteIdBag.hammerPullDestinationNoteId=t,!0}return!1}}Pe.GlobalNoteId=0,Pe.MaxOffsetForSameLineSearch=3,Pe.NoteIdLookupKey="NoteIdLookup";class Ee{constructor(e){this._isEqualLengthTuplet=!0,this.totalDuration=0,this.beats=[],this.isFull=!1,this.voice=e}check(e){if(0===this.beats.length)return this.beats.push(e),this.totalDuration+=e.playbackDuration,!0;if(e.graceType!==g.None)return!0;if(e.voice!==this.voice||this.isFull||e.tupletNumerator!==this.beats[0].tupletNumerator||e.tupletDenominator!==this.beats[0].tupletDenominator)return!1;if(e.playbackDuration!==this.beats[0].playbackDuration&&(this._isEqualLengthTuplet=!1),this.beats.push(e),this.totalDuration+=e.playbackDuration,this._isEqualLengthTuplet)this.beats.length===this.beats[0].tupletNumerator&&(this.isFull=!0);else{let e=this.beats[0].tupletNumerator/this.beats[0].tupletDenominator|0;for(let t of Ee.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}Ee.HalfTicks=1920,Ee.QuarterTicks=960,Ee.EighthTicks=480,Ee.SixteenthTicks=240,Ee.ThirtySecondTicks=120,Ee.SixtyFourthTicks=60,Ee.OneHundredTwentyEighthTicks=30,Ee.TwoHundredFiftySixthTicks=15,Ee.AllTicks=[Ee.HalfTicks,Ee.QuarterTicks,Ee.EighthTicks,Ee.SixteenthTicks,Ee.ThirtySecondTicks,Ee.SixtyFourthTicks,Ee.OneHundredTwentyEighthTicks,Ee.TwoHundredFiftySixthTicks],function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Dive=2]="Dive",e[e.Dip=3]="Dip",e[e.Hold=4]="Hold",e[e.Predive=5]="Predive",e[e.PrediveDive=6]="PrediveDive"}(C||(C={}));class Ce{static clone(e){const t=new be;return t.offset=e.offset,t.value=e.value,t}}class Fe{static clone(e){const t=new Pe;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(Ce.clone(s))}return t.fret=e.fret,t.string=e.string,t.octave=e.octave,t.tone=e.tone,t.percussionArticulation=e.percussionArticulation,t.isVisible=e.isVisible,t.isLeftHandTapped=e.isLeftHandTapped,t.isHammerPullOrigin=e.isHammerPullOrigin,t.isSlurDestination=e.isSlurDestination,t.harmonicType=e.harmonicType,t.harmonicValue=e.harmonicValue,t.isGhost=e.isGhost,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.isDead=e.isDead,t.isStaccato=e.isStaccato,t.slideInType=e.slideInType,t.slideOutType=e.slideOutType,t.vibrato=e.vibrato,t.isTieDestination=e.isTieDestination,t.leftHandFinger=e.leftHandFinger,t.rightHandFinger=e.rightHandFinger,t.isFingering=e.isFingering,t.trillValue=e.trillValue,t.trillSpeed=e.trillSpeed,t.durationPercent=e.durationPercent,t.accidentalMode=e.accidentalMode,t.dynamics=e.dynamics,t}}class Le{static clone(e){const t=new fe;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class Me{static clone(e){const t=new De;t.index=e.index,t.notes=[];for(const s of e.notes)t.addNote(Fe.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(Le.clone(s));if(t.dots=e.dots,t.fadeIn=e.fadeIn,t.lyrics=e.lyrics?e.lyrics.slice():null,t.hasRasgueado=e.hasRasgueado,t.pop=e.pop,t.slap=e.slap,t.tap=e.tap,t.text=e.text,t.brushType=e.brushType,t.brushDuration=e.brushDuration,t.tupletDenominator=e.tupletDenominator,t.tupletNumerator=e.tupletNumerator,t.isContinuedWhammy=e.isContinuedWhammy,t.whammyBarType=e.whammyBarType,e.whammyBarPoints){t.whammyBarPoints=[];for(const s of e.whammyBarPoints)t.addWhammyBarPoint(Ce.clone(s))}return t.vibrato=e.vibrato,t.chordId=e.chordId,t.graceType=e.graceType,t.pickStroke=e.pickStroke,t.tremoloSpeed=e.tremoloSpeed,t.crescendo=e.crescendo,t.displayStart=e.displayStart,t.playbackStart=e.playbackStart,t.displayDuration=e.displayDuration,t.playbackDuration=e.playbackDuration,t.dynamics=e.dynamics,t.invertBeamDirection=e.invertBeamDirection,t.preferredBeamDirection=e.preferredBeamDirection,t.isEffectSlurOrigin=e.isEffectSlurOrigin,t.beamingMode=e.beamingMode,t}}class Ie{constructor(){this.beats=[],this.id="empty",this.isComplete=!1}addBeat(e){e.graceIndex=this.beats.length,e.graceGroup=this,this.beats.push(e)}finish(){this.beats.length>0&&(this.id=this.beats[0].absoluteDisplayStart+"_"+this.beats[0].voice.index)}}!function(e){e[e.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext"}(F||(F={}));class De{constructor(){this.id=De._globalBeatId++,this.index=0,this.previousBeat=null,this.nextBeat=null,this.notes=[],this.noteStringLookup=new Map,this.noteValueLookup=new Map,this.isEmpty=!1,this.whammyStyle=h.Default,this.ottava=n.Regular,this.fermata=null,this.isLegatoOrigin=!1,this.minNote=null,this.maxNote=null,this.maxStringNote=null,this.minStringNote=null,this.duration=u.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fadeIn=!1,this.lyrics=null,this.hasRasgueado=!1,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.brushType=c.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=C.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=w.None,this.chordId=null,this.graceType=g.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=x.None,this.tremoloSpeed=null,this.crescendo=d.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.dynamics=p.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=F.Auto}get isLastOfVoice(){return this.index===this.voice.beats.length-1}get isLegatoDestination(){return!!this.previousBeat&&this.previousBeat.isLegatoOrigin}get isRest(){return this.isEmpty||0===this.notes.length}get isFullBarRest(){return this.isRest&&1===this.voice.beats.length&&this.duration===u.Whole}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==C.None}get hasChord(){return!!this.chordId}get chord(){return this.chordId?this.voice.bar.staff.getChord(this.chordId):null}get isTremolo(){return!!this.tremoloSpeed}get absoluteDisplayStart(){return this.voice.bar.masterBar.start+this.displayStart}get absolutePlaybackStart(){return this.voice.bar.masterBar.start+this.playbackStart}get isEffectSlurDestination(){return!!this.effectSlurOrigin}addWhammyBarPoint(e){let t=this.whammyBarPoints;null===t&&(t=[],this.whammyBarPoints=t),t.push(e),(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e),(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e),this.whammyBarType===C.None&&(this.whammyBarType=C.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)}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=ye.toTicks(this.duration);return 2===this.dots?e=ye.applyDot(e,!0):1===this.dots&&(e=ye.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=ye.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){let e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case g.BeforeBeat:case g.OnBeat:switch(this.duration){case u.Sixteenth:this.playbackDuration=ye.toTicks(u.SixtyFourth);break;case u.ThirtySecond:this.playbackDuration=ye.toTicks(u.OneHundredTwentyEighth);break;default:this.playbackDuration=ye.toTicks(u.ThirtySecond)}this.displayDuration=0;break;case g.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;let t=this.previousBeat;t&&t.graceType===g.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){let e=this.previousBeat,t=e?e.tupletGroup:null;(this.hasTuplet||this.graceType!==g.None&&t)&&(e&&t&&t.check(this)||(t=new Ee(this.voice),t.check(this)),this.tupletGroup=t)}finish(e,t){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(fe.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case g.OnBeat:case g.BeforeBeat:let e=this.graceGroup.beats.length;this.duration=1===e?u.Eighth:2===e?u.Sixteenth:u.ThirtySecond}let s=e?e.notation.notationMode:T.GuitarPro,i="grad"===this.text||"grad."===this.text;i&&s===T.SongBook&&(this.text="");let r=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let n=0,o=!1;for(let a=0,c=this.notes.length;a<c;a++){let c=this.notes[a];if(c.dynamics=this.dynamics,c.finish(e,t),c.isLetRing&&(this.isLetRing=!0),c.isPalmMute&&(this.isPalmMute=!0),s===T.SongBook&&c.hasBend&&this.graceType!==g.BendGrace){if(!c.isTieOrigin)switch(c.bendType){case l.Bend:case l.PrebendRelease:case l.PrebendBend:r=!0}i||c.bendStyle===h.Gradual?(i=!0,c.bendStyle=h.Gradual,r=!1):c.bendStyle=h.Fast}c.isVisible&&(n++,(!this.minNote||c.realValue<this.minNote.realValue)&&(this.minNote=c),(!this.maxNote||c.realValue>this.maxNote.realValue)&&(this.maxNote=c),(!this.minStringNote||c.string<this.minStringNote.string)&&(this.minStringNote=c),(!this.maxStringNote||c.string>this.maxStringNote.string)&&(this.maxStringNote=c),c.hasEffectSlur&&(o=!0))}if(o&&(this.effectSlurOrigin?(this.effectSlurOrigin.effectSlurDestination=this.nextBeat,this.effectSlurOrigin.effectSlurDestination&&(this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin),this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=this.nextBeat,this.effectSlurDestination&&(this.effectSlurDestination.effectSlurOrigin=this))),this.notes.length>0&&0===n&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&e&&e.notation.notationMode===T.GuitarPro&&(this.previousBeat.isLetRing&&(this.isLetRing=!0),this.previousBeat.isPalmMute&&(this.isPalmMute=!0));else{let e=this.previousBeat;for(;e&&e.isRest;)this.isLetRing||(e.isLetRing=!1),this.isPalmMute||(e.isPalmMute=!1),e=e.previousBeat}const c=this.whammyBarPoints;if(null!==c&&c.length>0&&this.whammyBarType===C.Custom){s===T.SongBook&&(this.whammyStyle=i?h.Gradual:h.Fast);let e=!!this.previousBeat&&this.previousBeat.hasWhammyBar;if(this.isContinuedWhammy=e,4===c.length){let t=c[0],i=c[1],a=c[2],r=c[3];i.value===a.value?t.value<i.value&&i.value<r.value||t.value>i.value&&i.value>r.value?(0===t.value||e?this.whammyBarType=C.Dive:this.whammyBarType=C.PrediveDive,c.splice(2,1),c.splice(1,1)):t.value>i.value&&i.value<r.value||t.value<i.value&&i.value>r.value?(this.whammyBarType=C.Dip,i.offset!==a.offset&&s!==T.SongBook||c.splice(2,1)):t.value===i.value&&i.value===r.value?(0===t.value||e?this.whammyBarType=C.Hold:this.whammyBarType=C.Predive,c.splice(2,1),c.splice(1,1)):Be.warning("Model","Unsupported whammy type detected, fallback to custom",null):Be.warning("Model","Unsupported whammy type detected, fallback to custom",null)}}if(this.updateDurations(),r){let e=Me.clone(this);e.id=De._globalBeatId++,e.pickStroke=x.None;for(let t=0,s=e.notes.length;t<s;t++){let s=e.notes[t],i=this.notes[t];if(s.bendType=l.None,s.maxBendPoint=null,s.bendPoints=null,s.bendStyle=h.Default,s.id=Pe.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=Pe.findTieOrigin(i);if(e&&e.hasBend){s.bendType=l.Hold;let e=i.bendPoints[i.bendPoints.length-1];s.addBendPoint(new be(0,e.value)),s.addBendPoint(new be(be.MaxPosition,e.value))}}s.isTieDestination=!0}this.graceType=g.BendGrace,this.graceGroup=new Ie,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new Ie,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){for(const t of this.notes)this.noteValueLookup.set(t.realValue,t),t.chain(e)}}De._globalBeatId=0;class Re{constructor(){this.name="",this.firstFret=1,this.strings=[],this.barreFrets=[],this.showName=!0,this.showDiagram=!0,this.showFingering=!0}}!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"}(L||(L={}));class Ae{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=L.Begin,r=L.Begin,n=!1,o=0;for(;t<e.length;){let s=e.charCodeAt(t);switch(a){case L.IgnoreSpaces:switch(s){case Ae.CharCodeLF:case Ae.CharCodeCR:case Ae.CharCodeTab:break;case Ae.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case L.Begin:switch(s){case Ae.CharCodeBrackedOpen:a=L.Comment;break;default:o=t,a=L.Text;continue}break;case L.Comment:switch(s){case Ae.CharCodeBrackedClose:a=L.Begin}break;case L.Text:switch(s){case Ae.CharCodeDash:a=L.Dash;break;case Ae.CharCodeCR:case Ae.CharCodeLF:case Ae.CharCodeSpace:let s=e.substr(o,t-o);this.addChunk(s,i),a=L.IgnoreSpaces,r=L.Begin}break;case L.Dash:switch(s){case Ae.CharCodeDash:break;default:let s=e.substr(o,t-o);this.addChunk(s,i),n=!0,a=L.IgnoreSpaces,r=L.Begin;continue}}t+=1}a===L.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}}Ae.CharCodeLF=10,Ae.CharCodeTab=9,Ae.CharCodeCR=13,Ae.CharCodeSpace=32,Ae.CharCodeBrackedClose=93,Ae.CharCodeBrackedOpen=91,Ae.CharCodeDash=45,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"}(M||(M={})),function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(I||(I={})),function(e){e[e.NoTripletFeel=0]="NoTripletFeel",e[e.Triplet16th=1]="Triplet16th",e[e.Triplet8th=2]="Triplet8th",e[e.Dotted16th=3]="Dotted16th",e[e.Dotted8th=4]="Dotted8th",e[e.Scottish16th=5]="Scottish16th",e[e.Scottish8th=6]="Scottish8th"}(D||(D={}));class Oe{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=M.C,this.keySignatureType=I.Major,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.tripletFeel=D.NoTripletFeel,this.section=null,this.tempoAutomation=null,this.fermata=null,this.start=0,this.isAnacrusis=!1}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}calculateDuration(e=!0){if(this.isAnacrusis&&e){let e=0;for(let t of this.score.tracks)for(let s of t.staves){let t=this.index<s.bars.length?s.bars[this.index].calculateDuration():0;t>e&&(e=t)}return e}return this.timeSignatureNumerator*ye.valueToTicks(this.timeSignatureDenominator)}addFermata(e,t){let s=this.fermata;null===s&&(s=new Map,this.fermata=s),s.set(e,t)}getFermata(e){const t=this.fermata;return null===t?null:t.has(e.playbackStart)?t.get(e.playbackStart):null}}Oe.MaxAlternateEndings=8;class Ge{constructor(){this.hideDynamics=!1}}class Ve{constructor(){this.masterBars=[],this.openings=[],this.closings=[],this.isOpened=!1,this.isClosed=!1}addMasterBar(e){0===this.openings.length&&this.openings.push(e),this.masterBars.push(e),e.repeatGroup=this,e.isRepeatEnd?(this.closings.push(e),this.isClosed=!0,this.isOpened||(this.masterBars[0].isRepeatStart=!0,this.isOpened=!0)):this.isClosed&&(this.isClosed=!1,this.openings.push(e))}}class He{constructor(){this._currentRepeatGroup=new Ve,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.stylesheet=new Ge}rebuildRepeatGroups(){let e=new Ve;for(let t of this.masterBars)(t.isRepeatStart||this._currentRepeatGroup.isClosed&&t.alternateEndings<=0)&&(e=new Ve),e.addMasterBar(t)}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())),(e.isRepeatStart||this._currentRepeatGroup.isClosed&&e.alternateEndings<=0)&&(this._currentRepeatGroup=new Ve),this._currentRepeatGroup.addMasterBar(e),this.masterBars.push(e)}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 We{constructor(){this.marker="",this.text=""}}class ze extends pe{constructor(e){super(s.Format,e),Object.setPrototypeOf(this,ze.prototype)}}class Ue{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="#"+ke.toHexString(this.r,2)+ke.toHexString(this.g,2)+ke.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 Ue(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){switch(typeof e){case"number":{const t=new Ue(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 Ue(17*parseInt(t.substring(1,1),16),17*parseInt(t.substring(2,1),16),17*parseInt(t.substring(3,1),16));if(5===t.length)return new Ue(17*parseInt(t.substring(1,1),16),17*parseInt(t.substring(2,1),16),17*parseInt(t.substring(3,1),16),17*parseInt(t.substring(4,1),16));if(7===t.length)return new Ue(parseInt(t.substring(1,2),16),parseInt(t.substring(3,2),16),parseInt(t.substring(5,2),16));if(9===t.length)return new Ue(parseInt(t.substring(1,2),16),parseInt(t.substring(3,2),16),parseInt(t.substring(5,2),16),parseInt(t.substring(7,2),16))}else if(t.startsWith("rgba")||t.startsWith("rgb")){const e=t.indexOf("("),s=t.lastIndexOf(")");if(-1===e||-1===s)throw new ze("No values specified for rgb/rgba function");const i=t.substring(e+1,s).split(",");if(3===i.length)return new Ue(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]));if(4===i.length)return new Ue(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]),255*parseFloat(i[3]))}return null}}throw new ze("Unsupported format for color")}static toJson(e){return e.raw}}Ue.BlackRgb="#000000";class Xe{constructor(){this.volume=15,this.balance=8,this.port=1,this.program=0,this.primaryChannel=0,this.secondaryChannel=0,this.isMute=!1,this.isSolo=!1}}class Ye{constructor(e="",t=null,s=!1){this.isStandard=s,this.name=e,this.tunings=null!=t?t:[]}static getTextForTuning(e,t){let s=Ye.getTextPartsForTuning(e);return t?s.join(""):s[0]}static getTextPartsForTuning(e,t=-1){return[["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"][e%12],((e/12|0)+t).toString()]}static getDefaultTuningFor(e){return Ye._defaultTunings.has(e)?Ye._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return Ye._sevenStrings;case 6:return Ye._sixStrings;case 5:return Ye._fiveStrings;case 4:return Ye._fourStrings}return[]}static initialize(){Ye._defaultTunings.set(7,new Ye("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),Ye._sevenStrings.push(Ye._defaultTunings.get(7)),Ye._defaultTunings.set(6,new Ye("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),Ye._sixStrings.push(Ye._defaultTunings.get(6)),Ye._sixStrings.push(new Ye("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),Ye._sixStrings.push(new Ye("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),Ye._sixStrings.push(new Ye("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),Ye._sixStrings.push(new Ye("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),Ye._sixStrings.push(new Ye("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),Ye._sixStrings.push(new Ye("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),Ye._defaultTunings.set(5,new Ye("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),Ye._fiveStrings.push(Ye._defaultTunings.get(5)),Ye._fiveStrings.push(new Ye("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),Ye._fiveStrings.push(new Ye("Banjo Open D Tuning",[62,57,54,50,69],!1)),Ye._fiveStrings.push(new Ye("Banjo Open G Tuning",[62,59,55,50,67],!1)),Ye._fiveStrings.push(new Ye("Banjo G Minor Tuning",[62,58,55,50,67],!1)),Ye._fiveStrings.push(new Ye("Banjo G Modal Tuning",[62,57,55,50,67],!1)),Ye._defaultTunings.set(4,new Ye("Bass Standard Tuning",[43,38,33,28],!0)),Ye._fourStrings.push(Ye._defaultTunings.get(4)),Ye._fourStrings.push(new Ye("Bass Tune down ½ step",[42,37,32,27],!1)),Ye._fourStrings.push(new Ye("Bass Tune down 1 step",[41,36,31,26],!1)),Ye._fourStrings.push(new Ye("Bass Tune down 2 step",[39,34,29,24],!1)),Ye._fourStrings.push(new Ye("Bass Dropped D Tuning",[43,38,33,26],!1)),Ye._fourStrings.push(new Ye("Ukulele C Tuning",[45,40,36,43],!1)),Ye._fourStrings.push(new Ye("Ukulele G Tuning",[52,47,43,38],!1)),Ye._fourStrings.push(new Ye("Mandolin Standard Tuning",[64,57,50,43],!1)),Ye._fourStrings.push(new Ye("Mandolin or Violin Tuning",[76,69,62,55],!1)),Ye._fourStrings.push(new Ye("Viola Tuning",[69,62,55,48],!1)),Ye._fourStrings.push(new Ye("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){let t=Ye.getPresetsFor(e.length);for(let s=0,i=t.length;s<i;s++){let i=t[s],a=!0;for(let t=0,s=e.length;t<s;t++)if(e[t]!==i.tunings[t]){a=!1;break}if(a)return i}return null}finish(){const e=Ye.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}Ye._sevenStrings=[],Ye._sixStrings=[],Ye._fiveStrings=[],Ye._fourStrings=[],Ye._defaultTunings=new Map,Ye.defaultAccidentals=["","#","","#","","","#","","#","","#",""],Ye.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],Ye.initialize();class qe{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new Ye("",[],!1),this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=5}get tuning(){return this.stringTuning.tunings}get tuningName(){return this.stringTuning.name}get isStringed(){return this.stringTuning.tunings.length>0}finish(e,t){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){var t,s;return null!==(s=null===(t=this.chords)||void 0===t?void 0:t.has(e))&&void 0!==s&&s}getChord(e){var t,s;return null!==(s=null===(t=this.chords)||void 0===t?void 0:t.get(e))&&void 0!==s?s:null}addBar(e){let t=this.bars;e.staff=this,e.index=t.length,t.length>0&&(e.previousBar=t[t.length-1],e.previousBar.nextBar=e),t.push(e)}}class Je{constructor(){this.index=0,this.staves=[],this.playbackInfo=new Xe,this.color=new Ue(200,0,0,255),this.name="",this.shortName="",this.percussionArticulations=[]}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new qe)}addStaff(e){e.index=this.staves.length,e.track=this,this.staves.push(e)}finish(e,t){this.shortName||(this.shortName=this.name,this.shortName.length>Je.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,Je.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[s]=i.chunks[t],a=a.nextBeat)}}}}}Je.ShortNameMaxLength=10;class Qe{constructor(){this.id=Qe._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){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){this._beatLookup=new Map;let s=null;for(let e=0;e<this.beats.length;e++){let i=this.beats[e];i.index=e,this.chain(i,t),i.graceType===g.None?(i.graceGroup=s,s&&(s.isComplete=!0),s=null):(s||(s=new Ie),s.addBeat(i))}let i=0,a=0;for(let s=0;s<this.beats.length;s++){let r=this.beats[s];if(r.index=s,r.finish(e,t),r.graceType===g.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==g.BendGrace){let s=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case g.BeforeBeat:e.previousBeat?(e.previousBeat.playbackDuration-=s,a=e.previousBeat.voice==this?e.previousBeat.playbackStart+e.previousBeat.playbackDuration:-s):a=-s;for(const e of r.graceGroup.beats)this._beatLookup.delete(e.playbackStart),e.playbackStart=a,this._beatLookup.set(e.playbackStart,r),a+=e.playbackDuration;break;case g.OnBeat:r.playbackDuration-=s,a=t.voice===this?t.playbackStart+t.playbackDuration:-s}}}r.displayStart=i,r.playbackStart=a,r.fermata?this.bar.masterBar.addFermata(r.playbackStart,r.fermata):r.fermata=this.bar.masterBar.getFermata(r),this._beatLookup.set(r.playbackStart,r)}else r.displayStart=i,r.playbackStart=a;r.finishTuplet(),r.graceGroup&&r.graceGroup.finish(),i+=r.displayDuration,a+=r.playbackDuration}}calculateDuration(){if(this.isEmpty||0===this.beats.length)return 0;let e=this.beats[this.beats.length-1],t=this.beats[0];return e.playbackStart+e.playbackDuration-t.playbackStart}}Qe._globalBarId=0;class je{static float64ToBytes(e){return je._dataView.setFloat64(0,e,!0),this._conversionByteArray}static bytesToFloat64(e){throw je._conversionByteArray.set(e,0),je._dataView.getFloat64(0,!0)}static uint16ToInt16(e){return je._dataView.setUint16(0,e,!0),je._dataView.getInt16(0,!0)}static int16ToUint32(e){return je._dataView.setInt16(0,e,!0),je._dataView.getUint32(0,!0)}static int32ToUint16(e){return je._dataView.setInt32(0,e,!0),je._dataView.getUint16(0,!0)}static int32ToInt16(e){return je._dataView.setInt32(0,e,!0),je._dataView.getInt16(0,!0)}static int32ToUint32(e){return je._dataView.setInt32(0,e,!0),je._dataView.getUint32(0,!0)}static uint8ToInt8(e){return je._dataView.setUint8(0,e),je._dataView.getInt8(0)}}je._conversionBuffer=new ArrayBuffer(8),je._conversionByteArray=new Uint8Array(je._conversionBuffer),je._dataView=new DataView(je._conversionBuffer);class Ke{static readInt32BE(e){return e.readByte()<<24|e.readByte()<<16|e.readByte()<<8|e.readByte()}static readInt32LE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static readUInt32LE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static decodeUInt32LE(e,t){let s=e[t],i=e[t+1],a=e[t+2];return e[t+3]<<24|a<<16|i<<8|s}static readUInt16LE(e){let t=e.readByte(),s=e.readByte();return je.int32ToUint16(s<<8|t)}static readInt16LE(e){let t=e.readByte(),s=e.readByte();return je.int32ToInt16(s<<8|t)}static readUInt32BE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte(),a=e.readByte();return je.int32ToUint32(t<<24|s<<16|i<<8|a)}static readUInt16BE(e){let t=e.readByte(),s=e.readByte();return je.int32ToInt16(t<<8|s)}static readInt16BE(e){let t=e.readByte(),s=e.readByte();return je.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),Ke.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==(8388608&s)&&(s|=255<<24),s}static readInt16(e,t){return je.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){let s=Ke.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(t>>0&255)}static writeInt32LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255),e.writeByte(t>>16&255),e.writeByte(t>>24&255)}static writeUInt16LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255)}static writeInt16LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255)}}class $e{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return $e.withCapacity(0)}static withCapacity(e){let t=new $e;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){let t=new $e;return t._buffer=e,t.length=e.length,t}static fromString(e){let t=Ke.stringToBytes(e);return $e.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}}!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",e[e.Property=15]="Property"}(R||(R={}));class Ze extends pe{constructor(e){super(s.AlphaTex,e),this.position=0,this.nonTerm="",this.expected=R.No,this.symbol=R.No,this.symbolData=null,Object.setPrototypeOf(this,Ze.prototype)}static symbolError(e,t,s,i,a=null){let r;r=a?`MalFormed AlphaTex: @${e}: Error on block ${t}, invalid value: ${a}`:`MalFormed AlphaTex: @${e}: Error on block ${t}, expected a ${R[s]} found a ${R[i]}: '${a}'`;let n=new Ze(r);return n.position=e,n.nonTerm=t,n.expected=s,n.symbol=i,n.symbolData=a,n}static errorMessage(e,t){let s=new Ze(t="MalFormed AlphaTex: @"+e+": "+t);return s.position=e,s}}class et extends ue{constructor(){super(),this._trackChannel=0,this._input="",this._ch=0,this._curChPos=0,this._sy=R.No,this._syData="",this._allowNegatives=!1,this._allowTuning=!1,this._currentDuration=u.QuadrupleWhole,this._currentDynamics=p.PPP,this._currentTuplet=0,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=$e.empty(),this._input=e,this.settings=t}readScore(){try{if(this.data.length>0&&(this._input=Ke.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this.createDefaultScore(),this._curChPos=0,this._currentDuration=u.Quarter,this._currentDynamics=p.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===R.LowerThan)throw new ge("Unknown start sign <");this.score(),this.consolidate(),this._score.finish(this.settings),this._score.rebuildRepeatGroups();for(const[e,t]of this._lyrics)this._score.tracks[e].applyLyrics(t);return this._score}catch(e){throw e instanceof Ze?new ge(e.message):e}}consolidate(){for(let e of this._score.tracks)for(let t of e.staves)for(;t.bars.length<this._score.masterBars.length;){let e=this.newBar(t),s=new De;s.isEmpty=!0,e.voices[0].addBeat(s)}}error(e,t,s=!0){let i;throw i=s?Ze.symbolError(this._curChPos,e,t,this._sy,null):Ze.symbolError(this._curChPos,e,t,t,this._syData),this.logErrors&&Be.error(this.name,i.message),i}errorMessage(e){let t=Ze.errorMessage(this._curChPos,e);throw this.logErrors&&Be.error(this.name,t.message),t}createDefaultScore(){this._score=new He,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new Je,this._currentTrack.ensureStaveCount(1),this._currentTrack.playbackInfo.program=25,this._currentTrack.playbackInfo.primaryChannel=this._trackChannel++,this._currentTrack.playbackInfo.secondaryChannel=this._trackChannel++,this._currentStaff=this._currentTrack.staves[0],this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=Ye.getDefaultTuningFor(6).tunings,this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=p.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":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;default:return r.G2}}parseClefFromInt(e){switch(e){case 43:return r.G2;case 65:return r.F4;case 48:return r.C3;case 60:return r.C4;default:return r.G2}}parseTripletFeelFromString(e){switch(e.toLowerCase()){case"no":case"none":return D.NoTripletFeel;case"t16":case"triplet-16th":return D.Triplet16th;case"t8":case"triplet-8th":return D.Triplet8th;case"d16":case"dotted-16th":return D.Dotted16th;case"d8":case"dotted-8th":return D.Dotted8th;case"s16":case"scottish-16th":return D.Scottish16th;case"s8":case"scottish-8th":return D.Scottish8th;default:return D.NoTripletFeel}}parseTripletFeelFromInt(e){switch(e){case 0:return D.NoTripletFeel;case 1:return D.Triplet16th;case 2:return D.Triplet8th;case 3:return D.Dotted16th;case 4:return D.Dotted8th;case 5:return D.Scottish16th;case 6:return D.Scottish8th;default:return D.NoTripletFeel}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":return-7;case"gb":return-6;case"db":return-5;case"ab":return-4;case"eb":return-3;case"bb":return-2;case"f":return-1;case"c":return 0;case"g":return 1;case"d":return 2;case"a":return 3;case"e":return 4;case"b":return 5;case"f#":return 6;case"c#":return 7;default:return 0}}nextChar(){return this._curChPos<this._input.length?this._ch=this._input.charCodeAt(this._curChPos++):this._ch=0,this._ch}newSy(){this._sy=R.No;do{if(this._ch===et.Eof)this._sy=R.Eof;else if(32===this._ch||11===this._ch||13===this._ch||10===this._ch||9===this._ch)this._ch=this.nextChar();else if(47===this._ch)if(this._ch=this.nextChar(),47===this._ch)for(;13!==this._ch&&10!==this._ch&&this._ch!==et.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;0!==this._ch;)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("symbol",R.String,!1);else if(34===this._ch||39===this._ch){let e=this._ch;this._ch=this.nextChar();let t="";for(this._sy=R.String;this._ch!==e&&this._ch!==et.Eof;)t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)if(this._allowNegatives&&this.isDigit(this._ch)){let e=this.readNumber();this._sy=R.Number,this._syData=e}else this._sy=R.String,this._syData=this.readName();else if(46===this._ch)this._sy=R.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=R.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=R.LParensis,this._ch=this.nextChar();else if(92===this._ch){this._ch=this.nextChar();let e=this.readName();this._sy=R.MetaCommand,this._syData=e}else if(41===this._ch)this._sy=R.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=R.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=R.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=R.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=R.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=R.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch)){let e=this.readNumber();this._sy=R.Number,this._syData=e}else if(et.isLetter(this._ch)){let e=this.readName(),t=this._allowTuning?ke.parseTuning(e):null;t?(this._sy=R.Tuning,this._syData=t):(this._sy=R.String,this._syData=e)}else this.error("symbol",R.String,!1)}while(this._sy===R.No);return this._sy}static isLetter(e){return!et.isTerminal(e)&&(e>=33&&e<=47||e>=58&&e<=126||e>128)}static isTerminal(e){return 46===e||123===e||125===e||91===e||93===e||40===e||41===e||124===e||39===e||34===e||92===e}isDigit(e){return e>=48&&e<=57||45===e&&this._allowNegatives}readName(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(et.isLetter(this._ch)||this.isDigit(this._ch)||35===this._ch);return e}readNumber(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(this.isDigit(this._ch));return parseInt(e)}score(){if(this._sy===R.Eof)throw new ge("Unexpected end of file");const e=this.metaData(),t=this.bars();if(!e&&!t)throw new ge("No alphaTex data found")}metaData(){let e=!1,t=!0;for(;this._sy===R.MetaCommand&&t;){switch(this._syData.toLowerCase()){case"title":this._sy=this.newSy(),this._sy===R.String?this._score.title=this._syData:this.error("title",R.String,!0),this._sy=this.newSy(),e=!0;break;case"subtitle":this._sy=this.newSy(),this._sy===R.String?this._score.subTitle=this._syData:this.error("subtitle",R.String,!0),this._sy=this.newSy(),e=!0;break;case"artist":this._sy=this.newSy(),this._sy===R.String?this._score.artist=this._syData:this.error("artist",R.String,!0),this._sy=this.newSy(),e=!0;break;case"album":this._sy=this.newSy(),this._sy===R.String?this._score.album=this._syData:this.error("album",R.String,!0),this._sy=this.newSy(),e=!0;break;case"words":this._sy=this.newSy(),this._sy===R.String?this._score.words=this._syData:this.error("words",R.String,!0),this._sy=this.newSy(),e=!0;break;case"music":this._sy=this.newSy(),this._sy===R.String?this._score.music=this._syData:this.error("music",R.String,!0),this._sy=this.newSy(),e=!0;break;case"copyright":this._sy=this.newSy(),this._sy===R.String?this._score.copyright=this._syData:this.error("copyright",R.String,!0),this._sy=this.newSy(),e=!0;break;case"tempo":this._sy=this.newSy(),this._sy===R.Number?this._score.tempo=this._syData:this.error("tempo",R.Number,!0),this._sy=this.newSy(),e=!0;break;default:this.handleStaffMeta()?e=!0:e?this.error("metaDataTags",R.String,!1):t=!1}}return e?(this._sy!==R.Dot&&this.error("song",R.Dot,!0),this._sy=this.newSy()):this._sy===R.Dot&&(this._sy=this.newSy()),e}handleStaffMeta(){var e,t;switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===R.Number?this._currentStaff.capo=this._syData:this.error("capo",R.Number,!0),this._sy=this.newSy(),!0;case"tuning":this._sy=this.newSy();let s=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case R.String:let e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?(this._currentStaff.stringTuning.tunings=[],this._currentStaff.displayTranspositionPitch=0):this.error("tuning",R.Tuning,!0),this._sy=this.newSy();break;case R.Tuning:let t=[];do{let e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===R.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",R.Tuning,!0)}return s!==this._currentStaff.tuning.length&&(null!==(t=null===(e=this._currentStaff.chords)||void 0===e?void 0:e.size)&&void 0!==t?t:0)>0&&this.errorMessage("Tuning must be defined before any chord"),!0;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===R.Number){let e=this._syData;e>=0&&e<=128?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",R.Number,!1)}else if(this._sy===R.String){let e=this._syData.toLowerCase();this._currentTrack.playbackInfo.program=de.getValue(e)}else this.error("instrument",R.Number,!0);return this._sy=this.newSy(),!0;case"lyrics":this._sy=this.newSy();let i=new Ae;return i.startBar=0,i.text="",this._sy===R.Number&&(i.startBar=this._syData,this._sy=this.newSy()),this._sy===R.String?(i.text=this._syData,this._sy=this.newSy()):this.error("lyrics",R.String,!0),this._lyrics.get(this._currentTrack.index).push(i),!0;case"chord":this._sy=this.newSy();let a=new Re;this.chordProperties(a),this._sy===R.String?(a.name=this._syData,this._sy=this.newSy()):this.error("chord-name",R.Number,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===R.Number?a.strings.push(this._syData):this._sy===R.String&&"x"===this._syData.toLowerCase()&&a.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,a.name),a),!0;default:return!1}}chordProperties(e){if(this._sy===R.LBrace){for(this._sy=this.newSy();this._sy===R.String;)switch(this._syData.toLowerCase()){case"firstfret":switch(this._sy=this.newSy(),this._sy){case R.Number:e.firstFret=this._syData;break;default:this.error("chord-firstfret",R.Number,!0)}this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case R.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case R.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",R.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case R.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case R.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",R.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case R.String:e.showName="false"!==this._syData.toLowerCase();break;case R.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",R.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===R.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",R.String,!1)}this._sy!==R.RBrace&&this.error("chord-properties",R.RBrace,!0),this._sy=this.newSy()}}bars(){let e=this.bar();for(;this._sy!==R.Eof;)if(this._sy===R.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==R.MetaCommand)break;this.bar()}return e}trackStaffMeta(){let e=!1;if(this._sy===R.MetaCommand){e=!0;let t=this._syData.toLowerCase();"track"===t&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===R.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===R.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy())),this._sy===R.MetaCommand&&(t=this._syData.toLowerCase(),"staff"===t&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0&&(this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this._currentStaff=this._currentTrack.staves[this._currentTrack.staves.length-1],this._currentDynamics=p.F),this.staffProperties()))}return e}staffProperties(){if(this._sy!==R.LBrace)return;this._sy=this.newSy();let e=!1,t=!1;for(;this._sy===R.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy();break;case"tabs":t=!0,this._sy=this.newSy();break;default:this.error("staff-properties",R.String,!1)}(e||t)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t),this._sy!==R.RBrace&&this.error("staff-properties",R.RBrace,!0),this._sy=this.newSy()}bar(){const e=this.trackStaffMeta();let t=this.newBar(this._currentStaff);if(this._currentStaff.bars.length>this._score.masterBars.length){let e=new Oe;this._score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.timeSignatureDenominator=e.previousMasterBar.timeSignatureDenominator,e.timeSignatureNumerator=e.previousMasterBar.timeSignatureNumerator,e.tripletFeel=e.previousMasterBar.tripletFeel)}const s=this.barMeta(t);if(!this._staffTuningApplied&&!this._staffHasExplicitTuning){const e=this._currentTrack.playbackInfo.program;this._currentStaff.displayTranspositionPitch=0,this._currentStaff.stringTuning.tunings=[],15==e||e>=24&&e<=31?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=Ye.getDefaultTuningFor(6).tunings):e>=32&&e<=39?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):40==e||44==e||45==e||48==e||49==e||50==e||51==e?this._currentStaff.stringTuning.tunings=[52,57,50,43]:41==e?this._currentStaff.stringTuning.tunings=[57,50,43,36]:42==e?this._currentStaff.stringTuning.tunings=[45,38,31,24]:43==e?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):105==e?this._currentStaff.stringTuning.tunings=[50,47,43,38,55]:106==e?this._currentStaff.stringTuning.tunings=[57,52,45]:107==e?this._currentStaff.stringTuning.tunings=[52,45,38,31]:110==e&&(this._currentStaff.stringTuning.tunings=[64,57,50,43]),this._staffTuningApplied=!0}let i=!1,a=t.voices[0];for(;this._sy!==R.Pipe&&this._sy!==R.Eof&&this.beat(a);)i=!0;if(0===a.beats.length){let e=new De;e.isEmpty=!0,a.addBeat(e)}return e||s||i}newBar(e){let t=new me;e.addBar(t),t.index>0&&(t.clef=t.previousBar.clef);let s=new Qe;return t.addVoice(s),t}beat(e){this.beatDuration();let t=new De;if(e.addBeat(t),this._sy===R.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==R.RParensis&&this._sy!==R.Eof&&this.note(t););this._sy!==R.RParensis&&this.error("note-list",R.RParensis,!0),this._sy=this.newSy()}else if(this._sy===R.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===R.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==R.Number&&this.error("duration",R.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||this.applyTuplet(t,this._currentTuplet);let s=1;this._sy===R.Multiply&&(this._sy=this.newSy(),this._sy!==R.Number?this.error("multiplier",R.Number,!0):s=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let i=0;i<s-1;i++)e.addBeat(Me.clone(t));return!0}beatDuration(){if(this._sy===R.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==R.Number&&this.error("duration",R.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===R.LBrace)){for(this._sy=this.newSy();this._sy===R.String;){switch(this._syData.toLowerCase()){case"tu":this._sy=this.newSy(),this._sy!==R.Number&&this.error("duration-tuplet",R.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();break;default:this.error("beat-duration",R.String,!1)}}this._sy!==R.RBrace&&this.error("beat-duration",R.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===R.LBrace){for(this._sy=this.newSy();this._sy===R.String;)this._syData=this._syData.toLowerCase(),this.applyBeatEffect(e)||this.error("beat-effects",R.String,!1);this._sy!==R.RBrace&&this.error("beat-effects",R.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){let t=this._syData.toLowerCase();if("f"===t)return e.fadeIn=!0,this._sy=this.newSy(),!0;if("v"===t)return e.vibrato=w.Slight,this._sy=this.newSy(),!0;if("s"===t)return e.slap=!0,this._sy=this.newSy(),!0;if("p"===t)return e.pop=!0,this._sy=this.newSy(),!0;if("tt"===t)return e.tap=!0,this._sy=this.newSy(),!0;if("dd"===t)return e.dots=2,this._sy=this.newSy(),!0;if("d"===t)return e.dots=1,this._sy=this.newSy(),!0;if("su"===t)return e.pickStroke=x.Up,this._sy=this.newSy(),!0;if("sd"===t)return e.pickStroke=x.Down,this._sy=this.newSy(),!0;if("tu"===t)return this._sy=this.newSy(),this._sy!==R.Number?(this.error("tuplet",R.Number,!0),!1):(this.applyTuplet(e,this._syData),this._sy=this.newSy(),!0);if("tb"===t||"tbe"===t){let s="tbe"===t;if(this._sy=this.newSy(),this._sy!==R.LParensis)return this.error("tremolobar-effect",R.LParensis,!0),!1;for(this._allowNegatives=!0,this._sy=this.newSy();this._sy!==R.RParensis&&this._sy!==R.Eof;){let t=0,i=0;if(s){if(this._sy!==R.Number)return this.error("tremolobar-effect",R.Number,!0),!1;if(t=this._syData,this._sy=this.newSy(),this._sy!==R.Number)return this.error("tremolobar-effect",R.Number,!0),!1;i=this._syData}else{if(this._sy!==R.Number)return this.error("tremolobar-effect",R.Number,!0),!1;t=0,i=this._syData}e.addWhammyBarPoint(new be(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++}}return this._allowNegatives=!1,this._sy!==R.RParensis?(this.error("tremolobar-effect",R.RParensis,!0),!1):(this._sy=this.newSy(),!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 Re;e.showDiagram=!1,e.name=t,this._currentStaff.addChord(s,e)}return e.chordId=s,this._sy=this.newSy(),!0}if("gr"===t)return this._sy=this.newSy(),"ob"===this._syData.toLowerCase()?(e.graceType=g.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=g.BendGrace,this._sy=this.newSy()):e.graceType=g.BeforeBeat,!0;if("dy"===t){switch(this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=p.PPP;break;case"pp":e.dynamics=p.PP;break;case"p":e.dynamics=p.P;break;case"mp":e.dynamics=p.MP;break;case"mf":e.dynamics=p.MF;break;case"f":e.dynamics=p.F;break;case"ff":e.dynamics=p.FF;break;case"fff":e.dynamics=p.FFF}return this._currentDynamics=e.dynamics,this.newSy(),!0}if("cre"===t)return e.crescendo=d.Crescendo,this.newSy(),!0;if("dec"===t)return e.crescendo=d.Decrescendo,this.newSy(),!0;if("tp"===t){this._sy=this.newSy();let t=u.Eighth;if(this._sy===R.Number){switch(this._syData){case 8:t=u.Eighth;break;case 16:t=u.Sixteenth;break;case 32:t=u.ThirtySecond;break;default:t=u.Eighth}this._sy=this.newSy()}return e.tremoloSpeed=t,!0}return!1}getChordId(e,t){return t.toLowerCase()+e.index+e.track.index}applyTuplet(e,t){switch(t){case 3:e.tupletNumerator=3,e.tupletDenominator=2;break;case 5:e.tupletNumerator=5,e.tupletDenominator=4;break;case 6:e.tupletNumerator=6,e.tupletDenominator=4;break;case 7:e.tupletNumerator=7,e.tupletDenominator=4;break;case 9:e.tupletNumerator=9,e.tupletDenominator=8;break;case 10:e.tupletNumerator=10,e.tupletDenominator=8;break;case 11:e.tupletNumerator=11,e.tupletDenominator=8;break;case 12:e.tupletNumerator=12,e.tupletDenominator=8;break;default:e.tupletNumerator=1,e.tupletDenominator=1}}isNoteText(e){return"x"===e||"-"===e||"r"===e}note(e){let t=!1,s=!1,i=-1,a=-1,r=-1;switch(this._sy){case R.Number:i=this._syData;break;case R.String:t="x"===this._syData,s="-"===this._syData,s||t?i=0:this.error("note-fret",R.Number,!0);break;case R.Tuning:let e=this._syData;a=e.octave,r=e.noteValue;break;default:return!1}this._sy=this.newSy();let n=-1===a&&this._currentStaff.tuning.length>0,o=-1;n&&(this._sy!==R.Dot&&this.error("note",R.Dot,!0),this._sy=this.newSy(),this._sy!==R.Number&&this.error("note-string",R.Number,!0),o=this._syData,(o<1||o>this._currentStaff.tuning.length)&&this.error("note-string",R.Number,!1),this._sy=this.newSy());let h=new Pe;return n?(h.string=this._currentStaff.tuning.length-(o-1),h.isDead=t,h.isTieDestination=s,s||(h.fret=i)):(h.octave=a,h.tone=r,h.isTieDestination=s),e.addNote(h),this.noteEffects(h),!0}noteEffects(e){if(this._sy===R.LBrace){for(this._sy=this.newSy();this._sy===R.String;){let t=this._syData.toLowerCase();if(this._syData=t,"b"===t||"be"===t){let t="be"===this._syData;for(this._sy=this.newSy(),this._sy!==R.LParensis&&this.error("bend-effect",R.LParensis,!0),this._sy=this.newSy();this._sy!==R.RParensis&&this._sy!==R.Eof;){let s=0,i=0;t?(this._sy!==R.Number&&this.error("bend-effect-value",R.Number,!0),s=this._syData,this._sy=this.newSy(),this._sy!==R.Number&&this.error("bend-effect-value",R.Number,!0),i=this._syData):(this._sy!==R.Number&&this.error("bend-effect-value",R.Number,!0),i=this._syData),e.addBendPoint(new be(s,i)),this._sy=this.newSy()}const s=e.bendPoints;if(null!=s){for(;s.length>60;)s.splice(s.length-1,1);if(t)s.sort(((e,t)=>e.offset-t.offset));else{let e=s.length,t=60/(e-1)|0,i=0;for(;i<e;)s[i].offset=Math.min(60,i*t),i++}}this._sy!==R.RParensis&&this.error("bend-effect",R.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=m.Natural,this._sy=this.newSy();else if("ah"===t)e.harmonicType=m.Artificial,this._sy=this.newSy();else if("th"===t)e.harmonicType=m.Tap,this._sy=this.newSy();else if("ph"===t)e.harmonicType=m.Pinch,this._sy=this.newSy();else if("sh"===t)e.harmonicType=m.Semi,this._sy=this.newSy();else if("tr"===t){this._sy=this.newSy(),this._sy!==R.Number&&this.error("trill-effect",R.Number,!0);let t=this._syData;this._sy=this.newSy();let s=u.Sixteenth;if(this._sy===R.Number){switch(this._syData){case 16:s=u.Sixteenth;break;case 32:s=u.ThirtySecond;break;case 64:s=u.SixtyFourth;break;default:s=u.Sixteenth}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=S.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=S.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=b.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=b.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=S.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=S.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=S.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=S.PickSlideUp;else if("h"===t)this._sy=this.newSy(),e.isHammerPullOrigin=!0;else if("lht"===t)this._sy=this.newSy(),e.isLeftHandTapped=!0;else if("g"===t)this._sy=this.newSy(),e.isGhost=!0;else if("ac"===t)this._sy=this.newSy(),e.accentuated=i.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=i.Heavy;else if("pm"===t)this._sy=this.newSy(),e.isPalmMute=!0;else if("st"===t)this._sy=this.newSy(),e.isStaccato=!0;else if("lr"===t)this._sy=this.newSy(),e.isLetRing=!0;else if("x"===t)this._sy=this.newSy(),e.fret=0,e.isDead=!0;else if("-"===t||"t"===t)this._sy=this.newSy(),e.isTieDestination=!0;else if("lf"===t){this._sy=this.newSy();let t=f.Thumb;this._sy===R.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===R.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else this.applyBeatEffect(e.beat)||this.error(t,R.String,!1)}this._sy!==R.RBrace&&this.error("note-effect",R.RBrace,!1),this._sy=this.newSy()}}toFinger(e){switch(e){case 1:return f.Thumb;case 2:return f.IndexFinger;case 3:return f.MiddleFinger;case 4:return f.AnnularFinger;case 5:return f.LittleFinger}return f.Thumb}parseDuration(e){switch(e){case-4:return u.QuadrupleWhole;case-2:return u.DoubleWhole;case 1:return u.Whole;case 2:return u.Half;case 4:return u.Quarter;case 8:return u.Eighth;case 16:return u.Sixteenth;case 32:return u.ThirtySecond;case 64:return u.SixtyFourth;case 128:return u.OneHundredTwentyEighth;default:return u.Quarter}}barMeta(e){let t=!1,s=e.masterBar;for(;this._sy===R.MetaCommand;){t=!0;let i=this._syData.toLowerCase();if("ts"===i)this._sy=this.newSy(),this._sy!==R.Number&&this.error("timesignature-numerator",R.Number,!0),s.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==R.Number&&this.error("timesignature-denominator",R.Number,!0),s.timeSignatureDenominator=this._syData,this._sy=this.newSy();else if("ro"===i)s.isRepeatStart=!0,this._sy=this.newSy();else if("rc"===i)this._sy=this.newSy(),this._sy!==R.Number&&this.error("repeatclose",R.Number,!0),s.repeatCount=this._syData,this._sy=this.newSy();else if("ks"===i)this._sy=this.newSy(),this._sy!==R.String&&this.error("keysignature",R.String,!0),s.keySignature=this.parseKeySignature(this._syData.toLowerCase()),this._sy=this.newSy();else if("clef"===i){switch(this._sy=this.newSy(),this._sy){case R.String:e.clef=this.parseClefFromString(this._syData.toLowerCase());break;case R.Number:e.clef=this.parseClefFromInt(this._syData);break;case R.Tuning:let t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",R.String,!0)}this._sy=this.newSy()}else if("tempo"===i){this._sy=this.newSy(),this._sy!==R.Number&&this.error("tempo",R.Number,!0);let e=new fe;e.isLinear=!1,e.type=a.Tempo,e.value=this._syData,s.tempoAutomation=e,this._sy=this.newSy()}else if("section"===i){this._sy=this.newSy(),this._sy!==R.String&&this.error("section",R.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==R.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());let i=new We;i.marker=t,i.text=e,s.section=i}else if("tf"===i){switch(this._allowTuning=!1,this._sy=this.newSy(),this._allowTuning=!0,this._sy){case R.String:s.tripletFeel=this.parseTripletFeelFromString(this._syData.toLowerCase());break;case R.Number:s.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",R.String,!0)}this._sy=this.newSy()}else"ac"===i?(s.isAnacrusis=!0,this._sy=this.newSy()):0===e.index&&this.handleStaffMeta()||this.error("measure-effects",R.String,!1)}if(0===s.index&&!s.tempoAutomation){let e=new fe;e.isLinear=!1,e.type=a.Tempo,e.value=this._score.tempo,s.tempoAutomation=e}return t}}et.Eof=0;class tt extends ue{constructor(){super(),this._versionNumber=0,this._globalTripletFeel=D.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._beatTextChunksByTrack=new Map}get name(){return"Guitar Pro 3-5"}readScore(){return this.readVersion(),this._score=new He,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=st.gpReadBool(this.data)?D.Triplet8th:D.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=st.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=Ke.readInt32LE(this.data),this._versionNumber>=510&&st.gpReadBool(this.data),Ke.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.data.skip(38),this.data.skip(4)),this._barCount=Ke.readInt32LE(this.data),this._trackCount=Ke.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0&&(this._score.masterBars[0].tempoAutomation=fe.buildTempoAutomation(!1,0,this._score.tempo,2),this._score.masterBars[0].tempoAutomation.text=this._score.tempoLabel),this._score.finish(this.settings),this._lyrics&&this._lyricsTrack>=0&&this._score.tracks[this._lyricsTrack].applyLyrics(this._lyrics),this._score}readVersion(){let e=st.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(tt.VersionString))throw new ge("Unsupported format");e=e.substr(tt.VersionString.length+1);let t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*parseInt(e.substr(0,t))+parseInt(e.substr(t+1)),Be.debug(this.name,"Guitar Pro version "+e+" detected")}readScoreInformation(){var e;this._score.title=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?st.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding);let t=Ke.readInt32LE(this.data),s="";for(let i=0;i<t;i++)i>0&&(s+="\r\n"),s+=null===(e=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding))||void 0===e?void 0:e.toString();this._score.notices=s}readLyrics(){this._lyrics=[],this._lyricsTrack=Ke.readInt32LE(this.data)-1;for(let e=0;e<5;e++){let e=new Ae;e.startBar=Ke.readInt32LE(this.data)-1,e.text=st.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(30);for(let e=0;e<10;e++)st.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){let t=new Xe;t.primaryChannel=e,t.secondaryChannel=e,t.program=Ke.readInt32LE(this.data),t.volume=this.data.readByte(),t.balance=this.data.readByte(),this.data.skip(6),this._playbackInfos.push(t)}}readMasterBars(){for(let e=0;e<this._barCount;e++)this.readMasterBar()}readMasterBar(){let e=null;this._score.masterBars.length>0&&(e=this._score.masterBars[this._score.masterBars.length-1]);let t=new Oe,s=this.data.readByte();if(0!=(1&s)?t.timeSignatureNumerator=this.data.readByte():e&&(t.timeSignatureNumerator=e.timeSignatureNumerator),0!=(2&s)?t.timeSignatureDenominator=this.data.readByte():e&&(t.timeSignatureDenominator=e.timeSignatureDenominator),t.isRepeatStart=0!=(4&s),0!=(8&s)&&(t.repeatCount=this.data.readByte()+(this._versionNumber>=500?0:1)),0!=(16&s))if(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&&0==(i&t)&&(a|=t)}t.alternateEndings=a}else t.alternateEndings=this.data.readByte();if(0!=(32&s)){let e=new We;e.text=st.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",st.gpReadColor(this.data,!1),t.section=e}if(0!=(64&s)?(t.keySignature=Ke.readSInt8(this.data),t.keySignatureType=this.data.readByte()):e&&(t.keySignature=e.keySignature,t.keySignatureType=e.keySignatureType),this._versionNumber>=500&&0!=(3&s)&&this.data.skip(4),this._versionNumber>=500&&0==(16&s)&&(t.alternateEndings=this.data.readByte()),this._versionNumber>=500){switch(this.data.readByte()){case 1:t.tripletFeel=D.Triplet8th;break;case 2:t.tripletFeel=D.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=0!=(128&s),this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){let e=new Je;e.ensureStaveCount(1),this._score.addTrack(e);let t=e.staves[0],s=this.data.readByte();e.name=st.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),0!=(1&s)&&(t.isPercussion=!0);let i=Ke.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){let t=Ke.readInt32LE(this.data);i>e&&a.push(t)}t.stringTuning.tunings=a;let r=Ke.readInt32LE(this.data),n=Ke.readInt32LE(this.data)-1,o=Ke.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=0!=(16&s),i.isMute=0!=(32&s),i.secondaryChannel=o,de.isGuitar(i.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=i}t.capo=Ke.readInt32LE(this.data),e.color=st.gpReadColor(this.data,!1),this._versionNumber>=500&&(this.data.readByte(),this.data.readByte(),this.data.skip(43)),this._versionNumber>=510&&(this.data.skip(4),st.gpReadStringIntByte(this.data,this.settings.importer.encoding),st.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 me,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=Ke.readInt32LE(this.data);if(0===s)return;let i=new Qe;t.addVoice(i);for(let a=0;a<s;a++)this.readBeat(e,t,i)}readBeat(e,t,s){let i=new De,a=this.data.readByte();if(0!=(1&a)&&(i.dots=1),0!=(64&a)){let e=this.data.readByte();i.isEmpty=0==(2&e)}switch(s.addBeat(i),Ke.readSInt8(this.data)){case-2:i.duration=u.Whole;break;case-1:i.duration=u.Half;break;case 0:i.duration=u.Quarter;break;case 1:i.duration=u.Eighth;break;case 2:i.duration=u.Sixteenth;break;case 3:i.duration=u.ThirtySecond;break;case 4:i.duration=u.SixtyFourth;break;default:i.duration=u.Quarter}if(0!=(32&a))switch(i.tupletNumerator=Ke.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}0!=(2&a)&&this.readChord(i);let r=this.settings.importer.beatTextAsLyrics&&e.index!==this._lyricsTrack;if(0!=(4&a)){const t=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const s=new Ae;s.text=t.trim(),s.finish(!0);const i=[];for(let e=s.chunks.length-1;e>=0;e--)i.push(s.chunks[e]);this._beatTextChunksByTrack.set(e.index,i)}else i.text=t}let n=m.None;0!=(8&a)&&(n=this.readBeatEffects(i)),0!=(16&a)&&this.readMixTableChange(i);let o=this.data.readByte();for(let a=6;a>=0;a--)if(0!=(o&1<<a)&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,s,i,6-a);n!==m.None&&(r.harmonicType=n,r.harmonicType===m.Natural&&(r.harmonicValue=this.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){this.data.readByte(),0!=(8&this.data.readByte())&&this.data.readByte()}r&&!i.isRest&&this._beatTextChunksByTrack.has(e.index)&&this._beatTextChunksByTrack.get(e.index).length>0&&(i.lyrics=[this._beatTextChunksByTrack.get(e.index).pop()])}readChord(e){let t=new Re,s=ke.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=st.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Ke.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Ke.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=st.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Ke.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Ke.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=st.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=Ke.readInt32LE(this.data);for(let s=0;s<6;s++){let i=Ke.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=st.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=Ke.readInt32LE(this.data),t.firstFret>0)for(let i=0;i<s;i++){let s=Ke.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}}t.name&&(e.chordId=s,e.voice.bar.staff.addChord(e.chordId,t))}readBeatEffects(e){let t=this.data.readByte(),s=0;if(this._versionNumber>=400&&(s=this.data.readByte()),e.fadeIn=0!=(16&t),(this._versionNumber<400&&0!=(1&t)||0!=(2&t))&&(e.vibrato=w.Slight),e.hasRasgueado=0!=(1&s),0!=(32&t)&&this._versionNumber>=400){switch(Ke.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}}else if(0!=(32&t)){switch(Ke.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(0!=(4&s)&&this.readTremoloBarEffect(e),0!=(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=tt.toStrokeValue(t)):s>0&&(e.brushType=c.BrushDown,e.brushDuration=tt.toStrokeValue(s))}if(0!=(2&s))switch(Ke.readSInt8(this.data)){case 0:e.pickStroke=x.None;break;case 1:e.pickStroke=x.Up;break;case 2:e.pickStroke=x.Down}if(this._versionNumber<400){if(0!=(4&t))return m.Natural;if(0!=(8&t))return m.Artificial}return m.None}readTremoloBarEffect(e){this.data.readByte(),Ke.readInt32LE(this.data);let t=Ke.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new be(0,0);t.offset=Ke.readInt32LE(this.data),t.value=Ke.readInt32LE(this.data)/tt.BendStep|0,st.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 it;t.instrument=Ke.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=Ke.readSInt8(this.data),t.balance=Ke.readSInt8(this.data);let s=Ke.readSInt8(this.data),i=Ke.readSInt8(this.data),r=Ke.readSInt8(this.data),n=Ke.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=st.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=Ke.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=Ke.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500&&this.data.readByte(),this._versionNumber>=510&&(st.gpReadStringIntByte(this.data,this.settings.importer.encoding),st.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){let s=new fe;s.isLinear=!0,s.type=a.Volume,s.value=t.volume,e.automations.push(s)}if(t.balance>=0){let s=new fe;s.isLinear=!0,s.type=a.Balance,s.value=t.balance,e.automations.push(s)}if(t.instrument>=0){let s=new fe;s.isLinear=!0,s.type=a.Instrument,s.value=t.instrument,e.automations.push(s)}if(t.tempo>=0){let s=new fe;s.isLinear=!0,s.type=a.Tempo,s.value=t.tempo,e.automations.push(s),e.voice.bar.masterBar.tempoAutomation=s}}readNote(e,t,s,a,r){let n=new Pe;n.string=t.staff.tuning.length-r;let o=this.data.readByte();if(0!=(2&o)?n.accentuated=i.Heavy:0!=(64&o)&&(n.accentuated=i.Normal),n.isGhost=0!=(4&o),0!=(32&o)){let e=this.data.readByte();3===e?n.isDead=!0:2===e&&(n.isTieDestination=!0)}if(0!=(1&o)&&this._versionNumber<500&&(this.data.readByte(),this.data.readByte()),0!=(16&o)){let e=Ke.readSInt8(this.data);n.dynamics=this.toDynamicValue(e),a.dynamics=n.dynamics}0!=(32&o)&&(n.fret=Ke.readSInt8(this.data)),0!=(128&o)&&(n.leftHandFinger=Ke.readSInt8(this.data),n.rightHandFinger=Ke.readSInt8(this.data),n.isFingering=!0);let h=!1;if(this._versionNumber>=500){0!=(1&o)&&(n.durationPercent=st.gpReadDouble(this.data)),h=0!=(2&this.data.readByte())}if(a.addNote(n),0!=(8&o)&&this.readNoteEffects(e,s,a,n),t.staff.isPercussion&&(n.percussionArticulation=n.fret,n.string=-1,n.fret=-1),h){const e=Ye.defaultAccidentals[n.realValueWithoutHarmonic%12];"#"===e?n.accidentalMode=y.ForceFlat:"b"===e&&(n.accidentalMode=y.ForceSharp)}return n}toDynamicValue(e){switch(e){case 1:return p.PPP;case 2:return p.PP;case 3:return p.P;case 4:return p.MP;case 5:return p.MF;case 6:return p.F;case 7:return p.FF;case 8:return p.FFF;default:return p.F}}readNoteEffects(e,t,s,i){let a=this.data.readByte(),r=0;this._versionNumber>=400&&(r=this.data.readByte()),0!=(1&a)&&this.readBend(i),0!=(16&a)&&this.readGrace(t,i),0!=(4&r)&&this.readTremoloPicking(s),0!=(8&r)?this.readSlide(i):this._versionNumber<400&&0!=(4&a)&&(i.slideOutType=S.Shift),0!=(16&r)&&this.readArtificialHarmonic(i),0!=(32&r)&&this.readTrill(i),i.isLetRing=0!=(8&a),i.isHammerPullOrigin=0!=(2&a),0!=(64&r)&&(i.vibrato=w.Slight),i.isPalmMute=0!=(2&r),i.isStaccato=0!=(1&r)}readBend(e){this.data.readByte(),Ke.readInt32LE(this.data);let t=Ke.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new be(0,0);t.offset=Ke.readInt32LE(this.data),t.value=Ke.readInt32LE(this.data)/tt.BendStep|0,st.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){let s=new De,i=new Pe;switch(i.string=t.string,i.fret=Ke.readSInt8(this.data),s.duration=u.ThirtySecond,s.dynamics=this.toDynamicValue(Ke.readSInt8(this.data)),Ke.readSInt8(this.data)){case 0:break;case 1:i.slideOutType=S.Legato,i.slideTarget=t;break;case 2:break;case 3:i.isHammerPullOrigin=!0}if(i.dynamics=s.dynamics,this.data.skip(1),this._versionNumber<500)s.graceType=g.BeforeBeat;else{let e=this.data.readByte();i.isDead=0!=(1&e),s.graceType=0!=(2&e)?g.OnBeat:g.BeforeBeat}e.addGraceBeat(s),s.addNote(i)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=u.Eighth;break;case 2:e.tremoloSpeed=u.Sixteenth;break;case 3:e.tremoloSpeed=u.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){let t=Ke.readSInt8(this.data);0!=(1&t)?e.slideOutType=S.Shift:0!=(2&t)?e.slideOutType=S.Legato:0!=(4&t)?e.slideOutType=S.OutDown:0!=(8&t)&&(e.slideOutType=S.OutUp),0!=(16&t)?e.slideInType=b.IntoFromBelow:0!=(32&t)&&(e.slideInType=b.IntoFromAbove)}else{switch(Ke.readSInt8(this.data)){case 1:e.slideOutType=S.Shift;break;case 2:e.slideOutType=S.Legato;break;case 3:e.slideOutType=S.OutDown;break;case 4:e.slideOutType=S.OutUp;break;case-1:e.slideInType=b.IntoFromBelow;break;case-2:e.slideInType=b.IntoFromAbove}}}readArtificialHarmonic(e){let t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=m.Natural,e.harmonicValue=this.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=m.Artificial;break;case 3:e.harmonicType=m.Tap,e.harmonicValue=this.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=m.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=m.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=m.Natural;break;case 3:e.harmonicType=m.Tap;break;case 4:e.harmonicType=m.Pinch;break;case 5:e.harmonicType=m.Semi;break;case 15:case 17:case 22:e.harmonicType=m.Artificial}}deltaFretToHarmonicValue(e){switch(e){case 2:return 2.4;case 3:return 3.2;case 4:case 5:case 7:case 9:case 12:case 16:case 17:case 19:case 24:return e;case 8:return 8.2;case 10:return 9.6;case 14:case 15:return 14.7;case 21:case 22:return 21.7;default:return 12}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=u.Sixteenth;break;case 2:e.trillSpeed=u.ThirtySecond;break;case 3:e.trillSpeed=u.SixtyFourth}}}tt.VersionString="FICHIER GUITAR PRO ",tt.BendStep=25;class st{static gpReadDouble(e){let t=new Uint8Array(8);return e.read(t,0,t.length),new Float64Array(t.buffer)[0]}static gpReadFloat(e){let t=new Uint8Array(4);return t[3]=e.readByte(),t[2]=e.readByte(),t[2]=e.readByte(),t[1]=e.readByte(),new Float32Array(t.buffer)[0]}static gpReadColor(e,t=!1){let s=e.readByte(),i=e.readByte(),a=e.readByte(),r=255;return t?r=e.readByte():e.skip(1),new Ue(s,i,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),st.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return st.gpReadString(e,Ke.readInt32LE(e),t)}static gpReadStringIntByte(e,t){let s=Ke.readInt32LE(e)-1;return e.readByte(),st.gpReadString(e,s,t)}static gpReadString(e,t,s){let i=new Uint8Array(t);return e.read(i,0,i.length),Ke.toString(i,s)}static gpWriteString(e,t){const s=Ke.stringToBytes(t);e.writeByte(t.length),e.write(s,0,s.length)}static gpReadStringByteLength(e,t,s){let i=e.readByte(),a=st.gpReadString(e,i,s);return i<t&&e.skip(t-i),a}}class it{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class at{constructor(){this.x=0,this.y=0,this.w=0,this.h=0}}!function(e){e[e.Boolean=0]="Boolean",e[e.Integer=1]="Integer",e[e.Float=2]="Float",e[e.String=3]="String",e[e.Point=4]="Point",e[e.Size=5]="Size",e[e.Rectangle=6]="Rectangle",e[e.Color=7]="Color"}(A||(A={}));class rt{constructor(e){this.raw=new Map;let t=$e.fromBuffer(e),s=Ke.readInt32BE(t);for(let e=0;e<s;e++){let e=st.gpReadString(t,t.readByte(),"utf-8");switch(t.readByte()){case A.Boolean:let s=1===t.readByte();this.addValue(e,s);break;case A.Integer:let i=Ke.readInt32BE(t);this.addValue(e,i);break;case A.Float:let a=st.gpReadFloat(t);this.addValue(e,a);break;case A.String:let r=st.gpReadString(t,Ke.readInt16BE(t),"utf-8");this.addValue(e,r);break;case A.Point:let n=Ke.readInt32BE(t),o=Ke.readInt32BE(t);this.addValue(e,new be(n,o));break;case A.Size:let h=Ke.readInt32BE(t),l=Ke.readInt32BE(t);this.addValue(e,new be(h,l));break;case A.Rectangle:let c=new at;c.x=Ke.readInt32BE(t),c.y=Ke.readInt32BE(t),c.w=Ke.readInt32BE(t),c.h=Ke.readInt32BE(t),this.addValue(e,c);break;case A.Color:let d=st.gpReadColor(t,!0);this.addValue(e,d)}}}apply(e){for(const[t,s]of this.raw)switch(t){case"StandardNotation/hideDynamics":e.stylesheet.hideDynamics=s}}addValue(e,t){this.raw.set(e,t)}static writeForScore(e){const t=$e.withCapacity(128);return Ke.writeInt32BE(t,1),rt.writeBooleanEntry(t,"StandardNotation/hideDynamics",e.stylesheet.hideDynamics),t.toArray()}static writeBooleanEntry(e,t,s){st.gpWriteString(e,t),e.writeByte(A.Boolean),e.writeByte(s?1:0)}}!function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(O||(O={}));class nt{constructor(){this.type=O.Short,this.length=0}}!function(e){e[e.None=0]="None",e[e.Element=1]="Element",e[e.Text=2]="Text",e[e.CDATA=3]="CDATA",e[e.Document=4]="Document",e[e.DocumentType=5]="DocumentType"}(G||(G={}));class ot{constructor(){this.nodeType=G.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!==G.Element&&e.nodeType!==G.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===G.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===G.Element&&t.localName===e)return t;return null}addElement(e){const t=new ot;return t.nodeType=G.Element,t.localName=e,this.addChild(t),t}get innerText(){var e,t;if(this.nodeType===G.Element||this.nodeType===G.Document){if(this.firstElement&&this.firstElement.nodeType===G.CDATA)return this.firstElement.innerText;let t="";for(let s of this.childNodes)t+=null===(e=s.innerText)||void 0===e?void 0:e.toString();return t.trim()}return null!==(t=this.value)&&void 0!==t?t:""}set innerText(e){const t=new ot;t.nodeType=G.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new ot;t.nodeType=G.CDATA,t.value=e,this.childNodes=[t]}}class ht extends pe{constructor(e,t,i){super(s.Format,e),this.pos=0,this.xml=t,this.pos=i,Object.setPrototypeOf(this,ht.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"}(V||(V={}));class lt{static parse(e,t,s){var i;let a=e.charCodeAt(t),r=V.Begin,n=V.Begin,o=0,h="",l=V.Begin,c=null,d=null,u=0,p=0;for(;t<e.length;){switch(a=e.charCodeAt(t),r){case V.IgnoreSpaces:switch(a){case lt.CharCodeLF:case lt.CharCodeCR:case lt.CharCodeTab:case lt.CharCodeSpace:break;default:r=n;continue}break;case V.Begin:switch(a){case lt.CharCodeLowerThan:r=V.IgnoreSpaces,n=V.BeginNode;break;default:o=t,r=V.Pcdata;continue}break;case V.Pcdata:if(a===lt.CharCodeLowerThan){h+=e.substr(o,t-o);let i=new ot;i.nodeType=G.Text,i.value=h,h="",s.addChild(i),r=V.IgnoreSpaces,n=V.BeginNode}else a===lt.CharCodeAmp&&(h+=e.substr(o,t-o),r=V.Escape,l=V.Pcdata,o=t+1);break;case V.Cdata:if(a===lt.CharCodeBrackedClose&&e.charCodeAt(t+1)===lt.CharCodeBrackedClose&&e.charCodeAt(t+2)===lt.CharCodeGreaterThan){let i=new ot;i.nodeType=G.CDATA,i.value=e.substr(o,t-o),s.addChild(i),t+=2,r=V.Begin}break;case V.BeginNode:switch(a){case lt.CharCodeExclamation:if(e.charCodeAt(t+1)===lt.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new ht("Expected <![CDATA[",e,t);t+=5,r=V.Cdata,o=t+1}else if(e.charCodeAt(t+1)===lt.CharCodeUpperD||e.charCodeAt(t+1)===lt.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new ht("Expected <!DOCTYPE",e,t);t+=8,r=V.Doctype,o=t+1}else{if(e.charCodeAt(t+1)!==lt.CharCodeMinus||e.charCodeAt(t+2)!==lt.CharCodeMinus)throw new ht("Expected \x3c!--",e,t);t+=2,r=V.Comment,o=t+1}break;case lt.CharCodeQuestion:r=V.Header,o=t;break;case lt.CharCodeSlash:if(!s)throw new ht("Expected node name",e,t);o=t+1,r=V.IgnoreSpaces,n=V.Close;break;default:r=V.TagName,o=t;continue}break;case V.TagName:if(!lt.isValidChar(a)){if(t===o)throw new ht("Expected node name",e,t);c=new ot,c.nodeType=G.Element,c.localName=e.substr(o,t-o),s.addChild(c),r=V.IgnoreSpaces,n=V.Body;continue}break;case V.Body:switch(a){case lt.CharCodeSlash:r=V.WaitEnd;break;case lt.CharCodeGreaterThan:r=V.Childs;break;default:r=V.AttribName,o=t;continue}break;case V.AttribName:if(!lt.isValidChar(a)){if(o===t)throw new ht("Expected attribute name",e,t);if(d=e.substr(o,t-o),c.attributes.has(d))throw new ht(`Duplicate attribute [${d}]`,e,t);r=V.IgnoreSpaces,n=V.Equals;continue}break;case V.Equals:switch(a){case lt.CharCodeEquals:r=V.IgnoreSpaces,n=V.AttvalBegin;break;default:throw new ht("Expected =",e,t)}break;case V.AttvalBegin:switch(a){case lt.CharCodeDoubleQuote:case lt.CharCodeSingleQuote:h="",r=V.AttribVal,o=t+1,p=a}break;case V.AttribVal:switch(a){case lt.CharCodeAmp:h+=e.substr(o,t-o),r=V.Escape,l=V.AttribVal,o=t+1;break;default:if(a===p){h+=e.substr(o,t-o);let s=h;h="",c.attributes.set(d,s),r=V.IgnoreSpaces,n=V.Body}}break;case V.Childs:o=t=lt.parse(e,t,c),r=V.Begin;break;case V.WaitEnd:switch(a){case lt.CharCodeGreaterThan:r=V.Begin;break;default:throw new ht("Expected >",e,t)}break;case V.WaitEndRet:switch(a){case lt.CharCodeGreaterThan:return t;default:throw new ht("Expected >",e,t)}case V.Close:if(!lt.isValidChar(a)){if(o===t)throw new ht("Expected node name",e,t);if(e.substr(o,t-o)!==s.localName)throw new ht("Expected </"+s.localName+">",e,t);r=V.IgnoreSpaces,n=V.WaitEndRet;continue}break;case V.Comment:a===lt.CharCodeMinus&&e.charCodeAt(t+1)===lt.CharCodeMinus&&e.charCodeAt(t+2)===lt.CharCodeGreaterThan&&(t+=2,r=V.Begin);break;case V.Doctype:if(a===lt.CharCodeBrackedOpen)u++;else if(a===lt.CharCodeBrackedClose)u--;else if(a===lt.CharCodeGreaterThan&&0===u){let i=new ot;i.nodeType=G.DocumentType,i.value=e.substr(o,t-o),s.addChild(i),r=V.Begin}break;case V.Header:a===lt.CharCodeQuestion&&e.charCodeAt(t+1)===lt.CharCodeGreaterThan&&(t++,r=V.Begin);break;case V.Escape:if(a===lt.CharCodeSemi){let s=e.substr(o,t-o);if(s.charCodeAt(0)===lt.CharCodeSharp){let e=s.charCodeAt(1)===lt.CharCodeLowerX?parseInt("0"+s.substr(1,s.length-1)):parseInt(s.substr(1,s.length-1));h+=String.fromCharCode(e)}else lt.Escapes.has(s)?h+=lt.Escapes.get(s):h+=null===(i="&"+s+";")||void 0===i?void 0:i.toString();o=t+1,r=l}else lt.isValidChar(a)||a===lt.CharCodeSharp||(h+="&",h+=e.substr(o,t-o),o=--t+1,r=l)}t++}if(r===V.Begin&&(o=t,r=V.Pcdata),r===V.Pcdata){if(t!==o){h+=e.substr(o,t-o);let i=new ot;i.nodeType=G.Text,i.value=h,s.addChild(i)}return t}if(r===V.Escape&&l===V.Pcdata){h+="&",h+=e.substr(o,t-o);let i=new ot;return i.nodeType=G.Text,i.value=h,s.addChild(i),t}throw new ht("Unexpected end",e,t)}static isValidChar(e){return e>=lt.CharCodeLowerA&&e<=lt.CharCodeLowerZ||e>=lt.CharCodeUpperA&&e<=lt.CharCodeUpperZ||e>=lt.CharCode0&&e<=lt.CharCode9||e===lt.CharCodeColon||e===lt.CharCodeDot||e===lt.CharCodeUnderscore||e===lt.CharCodeMinus}}lt.CharCodeLF=10,lt.CharCodeTab=9,lt.CharCodeCR=13,lt.CharCodeSpace=32,lt.CharCodeLowerThan=60,lt.CharCodeAmp=38,lt.CharCodeBrackedClose=93,lt.CharCodeBrackedOpen=91,lt.CharCodeGreaterThan=62,lt.CharCodeExclamation=33,lt.CharCodeUpperD=68,lt.CharCodeLowerD=100,lt.CharCodeMinus=45,lt.CharCodeQuestion=63,lt.CharCodeSlash=47,lt.CharCodeEquals=61,lt.CharCodeDoubleQuote=34,lt.CharCodeSingleQuote=39,lt.CharCodeSharp=35,lt.CharCodeLowerX=120,lt.CharCodeLowerA=97,lt.CharCodeLowerZ=122,lt.CharCodeUpperA=65,lt.CharCodeUpperZ=90,lt.CharCode0=48,lt.CharCode9=57,lt.CharCodeColon=58,lt.CharCodeDot=46,lt.CharCodeUnderscore=95,lt.CharCodeSemi=59,lt.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class ct{constructor(e,t){this._result=[],this._indention=e,this._xmlHeader=t,this._currentIndention="",this._isStartOfLine=!0}static write(e,t,s){const i=new ct(t,s);return i.writeNode(e),i.toString()}writeNode(e){switch(e.nodeType){case G.None:break;case G.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===G.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case G.Text:e.value&&this.write(e.value);break;case G.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case G.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case G.DocumentType:this.write(`<!DOCTYPE ${e.value}>`)}}unindend(){this._currentIndention=this._currentIndention.substr(0,this._currentIndention.length-this._indention.length)}indent(){this._currentIndention+=this._indention}writeAttributeValue(e){for(let t=0;t<e.length;t++){const s=e.charAt(t);switch(s){case"<":this._result.push("&lt;");break;case">":this._result.push("&gt;");break;case"&":this._result.push("&amp;");break;case"'":this._result.push("&apos;");break;case'"':this._result.push("&quot;");break;default:this._result.push(s)}}}write(e){this._isStartOfLine&&this._result.push(this._currentIndention),this._result.push(e),this._isStartOfLine=!1}writeLine(e=null){e&&this.write(e),this._indention.length>0&&!this._isStartOfLine&&(this._result.push("\n"),this._isStartOfLine=!0)}toString(){return this._result.join("").trimRight()}}class dt extends ot{constructor(){super(),this.nodeType=G.Document}parse(e){lt.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return ct.write(this,e,t)}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(H||(H={}));class ut{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=u.Quarter}}class pt{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return this.path+";"+this.name+";"+this.role}}class gt{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1}parseXml(e,t){this._masterTrackAutomations=new Map,this._automationsPerTrackIdAndBarIndex=new Map,this._tracksMapping=[],this._tracksById=new Map,this._masterBars=[],this._barsOfMasterBar=[],this._voicesOfBar=new Map,this._barsById=new Map,this._voiceById=new Map,this._beatsOfVoice=new Map,this._beatById=new Map,this._rhythmOfBeat=new Map,this._rhythmById=new Map,this._notesOfBeat=new Map,this._noteById=new Map,this._tappedNotes=new Map,this._lyricsByTrack=new Map,this._soundsByTrack=new Map,this._skipApplyLyrics=!1;let s=new dt;try{s.parse(e)}catch(e){throw new ge("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 ge("Root node of XML was not GPIF");this.score=new He;for(let e of t.childNodes)if(e.nodeType===G.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===G.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}}parseMasterTrackNode(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null);break;case"Tracks":this._tracksMapping=t.innerText.split(" ");break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,s){for(let i of e.childNodes)if(i.nodeType===G.Element)switch(i.localName){case"Automation":this.parseAutomation(i,t,s)}}parseAutomation(e,t,s){let i=null,a=!1,r=-1,n=0,o=0,h=null,l=0,c=null;for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Type":i=t.innerText;break;case"Linear":a="true"===t.innerText.toLowerCase();break;case"Bar":r=parseInt(t.innerText);break;case"Position":n=parseFloat(t.innerText);break;case"Value":if(t.firstElement&&t.firstElement.nodeType===G.CDATA)h=t.innerText;else{let e=t.innerText.split(" ");1===e.length?(o=parseFloat(e[0]),l=1):(o=parseFloat(e[0]),l=parseInt(e[1]))}break;case"Text":c=t.innerText}if(!i)return;let d=null;switch(i){case"Tempo":d=fe.buildTempoAutomation(a,n,o,l);break;case"Sound":h&&s&&s.has(h)&&(d=fe.buildInstrumentAutomation(a,n,s.get(h).program))}d&&(c&&(d.text=c),r>=0&&(t.has(r)||t.set(r,[]),t.get(r).push(d)))}parseTracksNode(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Track":this.parseTrack(t)}}parseTrack(e){this._articulationByName=new Map;let t=new Je;t.ensureStaveCount(1),t.staves[0].showStandardNotation=!0;let s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===G.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 Ue(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"Lyrics":this.parseLyrics(s,i);break;case"Properties":this.parseTrackProperties(t,i);break;case"GeneralMidi":case"MidiConnection":case"MIDISettings":this.parseGeneralMidi(t,i);break;case"Sounds":this.parseSounds(s,t,i);break;case"PlaybackState":let r=i.innerText;t.playbackInfo.isSolo="Solo"===r,t.playbackInfo.isMute="Mute"===r;break;case"PartSounding":this.parsePartSounding(t,i);break;case"Staves":this.parseStaves(t,i);break;case"Transpose":this.parseTranspose(t,i);break;case"RSE":this.parseRSE(t,i);break;case"Automations":this.parseTrackAutomations(s,i)}this._tracksById.set(s,t)}parseTrackAutomations(e,t){const s=new Map;this._automationsPerTrackIdAndBarIndex.set(e,s),this.parseAutomations(t,s,this._soundsByTrack.get(e))}parseNotationPatch(e,t){for(let s of t.childNodes)if(s.nodeType===G.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===G.Element)switch(s.localName){case"Type":switch(s.innerText){case"drumKit":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===G.Element)switch(s.localName){case"Element":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===G.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===G.Element)switch(i.localName){case"Articulation":this.parseArticulation(e,i,s)}}parseArticulation(e,t,s){const i=new ve;i.outputMidiNumber=-1,i.elementType=s;let a="";for(let e of t.childNodes)if(e.nodeType===G.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":i.techniqueSymbolPlacement=E.Bottom;break;case"inside":i.techniqueSymbolPlacement=E.Middle;break;case"above":i.techniqueSymbolPlacement=E.Bottom;break;case"below":i.techniqueSymbolPlacement=E.Top}break;case"Noteheads":const s=t.split(" ");s.length>=1&&(i.noteHeadDefault=this.parseNoteHead(s[0])),s.length>=2&&(i.noteHeadHalf=this.parseNoteHead(s[1])),s.length>=3&&(i.noteHeadWhole=this.parseNoteHead(s[2])),i.noteHeadHalf==N.None&&(i.noteHeadHalf=i.noteHeadDefault),i.noteHeadWhole==N.None&&(i.noteHeadWhole=i.noteHeadDefault);break;case"StaffLine":t.length>0&&(i.staffLine=parseInt(t))}}-1!==i.outputMidiNumber?(e.percussionArticulations.push(i),a.length>0&&this._articulationByName.set(a,i)):a.length>0&&this._articulationByName.has(a)&&(this._articulationByName.get(a).staffLine=i.staffLine)}parseTechniqueSymbol(e){switch(e){case"pictEdgeOfCymbal":return N.PictEdgeOfCymbal;case"articStaccatoAbove":return N.ArticStaccatoAbove;case"noteheadParenthesis":return N.NoteheadParenthesis;case"stringsUpBow":return N.StringsUpBow;case"stringsDownBow":return N.StringsDownBow;case"guitarGolpe":return N.GuitarGolpe;default:return N.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return N.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return N.NoteheadDoubleWhole;case"noteheadWhole":return N.NoteheadWhole;case"noteheadHalf":return N.NoteheadHalf;case"noteheadBlack":return N.NoteheadBlack;case"noteheadNull":return N.NoteheadNull;case"noteheadXOrnate":return N.NoteheadXOrnate;case"noteheadTriangleUpWhole":return N.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return N.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return N.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return N.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return N.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return N.NoteheadDiamondWhiteWide;case"noteheadCircleX":return N.NoteheadCircleX;case"noteheadXWhole":return N.NoteheadXWhole;case"noteheadXHalf":return N.NoteheadXHalf;case"noteheadXBlack":return N.NoteheadXBlack;case"noteheadParenthesis":return N.NoteheadParenthesis;case"noteheadSlashedBlack2":return N.NoteheadSlashedBlack2;case"noteheadCircleSlash":return N.NoteheadCircleSlash;case"noteheadHeavyX":return N.NoteheadHeavyX;case"noteheadHeavyXHat":return N.NoteheadHeavyXHat;default:return Be.warning("GPIF","Unknown notehead symbol",e),N.None}}parseStaves(e,t){let s=0;for(let i of t.childNodes)if(i.nodeType===G.Element)switch(i.localName){case"Staff":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===G.Element)switch(s.localName){case"Properties":this.parseStaffProperties(e,s)}}parseStaffProperties(e,t){for(let s of t.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"Property":this.parseStaffProperty(e,s)}}parseStaffProperty(e,t){switch(t.getAttribute("name")){case"Tuning":for(let s of t.childNodes)if(s.nodeType===G.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===G.Element)switch(e.localName){case"Line":s.push(this.parseLyricsLine(e))}this._lyricsByTrack.set(e,s)}parseLyricsLine(e){let t=new Ae;for(let s of e.childNodes)if(s.nodeType===G.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===G.Element)switch(t.localName){case"Item":this.parseDiagramItemForTrack(e,t)}}parseDiagramCollectionForStaff(e,t){let s=t.findChildElement("Items");for(let t of s.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Item":this.parseDiagramItemForStaff(e,t)}}parseDiagramItemForTrack(e,t){let s=new Re,i=t.getAttribute("id");for(let t of e.staves)t.addChord(i,s);this.parseDiagramItemForChord(s,t)}parseDiagramItemForStaff(e,t){let s=new Re,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"),i=parseInt(s.getAttribute("stringCount")),a=parseInt(s.getAttribute("baseFret"));e.firstFret=a+1;for(let t=0;t<i;t++)e.strings.push(-1);for(let t of s.childNodes)if(t.nodeType===G.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===G.Element)switch(s.localName){case"Position":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===G.Element)switch(s.localName){case"Property":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===G.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===G.Element)switch(i.localName){case"Sound":this.parseSound(e,t,i)}}parseSound(e,t,s){const i=new pt;for(let e of s.childNodes)if(e.nodeType===G.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===G.Element)switch(s.localName){case"Program":e.program=parseInt(s.innerText)}}parsePartSounding(e,t){for(let s of t.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"TranspositionPitch":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===G.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===G.Element)switch(s.localName){case"ChannelStrip":this.parseChannelStrip(e,s)}}parseChannelStrip(e,t){for(let s of t.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"Parameters":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===G.Element)switch(t.localName){case"MasterBar":this.parseMasterBar(t)}}parseMasterBar(e){let t=new Oe;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"Time":let e=s.innerText.split("/");t.timeSignatureNumerator=parseInt(e[0]),t.timeSignatureDenominator=parseInt(e[1]);break;case"DoubleBar":t.isDoubleBar=!0;break;case"Section":t.section=new We,t.section.marker=s.findChildElement("Letter").innerText,t.section.text=s.findChildElement("Text").innerText;break;case"Repeat":"true"===s.getAttribute("start").toLowerCase()&&(t.isRepeatStart=!0),"true"===s.getAttribute("end").toLowerCase()&&s.getAttribute("count")&&(t.repeatCount=parseInt(s.getAttribute("count")));break;case"AlternateEndings":let i=s.innerText.split(" "),a=0;for(let e=0;e<i.length;e++)a|=1<<-1+parseInt(i[e]);t.alternateEndings=a;break;case"Bars":this._barsOfMasterBar.push(s.innerText.split(" "));break;case"TripletFeel":switch(s.innerText){case"NoTripletFeel":t.tripletFeel=D.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=D.Triplet8th;break;case"Triplet16th":t.tripletFeel=D.Triplet16th;break;case"Dotted8th":t.tripletFeel=D.Dotted8th;break;case"Dotted16th":t.tripletFeel=D.Dotted16th;break;case"Scottish8th":t.tripletFeel=D.Scottish8th;break;case"Scottish16th":t.tripletFeel=D.Scottish16th}break;case"Key":t.keySignature=parseInt(s.findChildElement("AccidentalCount").innerText);let r=s.findChildElement("Mode");if(r)switch(r.innerText.toLowerCase()){case"major":t.keySignatureType=I.Major;break;case"minor":t.keySignatureType=I.Minor}break;case"Fermatas":this.parseFermatas(t,s)}this._masterBars.push(t)}parseFermatas(e,t){for(let s of t.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"Fermata":this.parseFermata(e,s)}}parseFermata(e,t){let s=0,i=new nt;for(let e of t.childNodes)if(e.nodeType===G.Element)switch(e.localName){case"Type":switch(e.innerText){case"Short":i.type=O.Short;break;case"Medium":i.type=O.Medium;break;case"Long":i.type=O.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])*ye.QuarterTime|0}}e.addFermata(s,i)}parseBars(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Bar":this.parseBar(t)}}parseBar(e){let t=new me,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===G.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}}this._barsById.set(s,t)}parseVoices(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Voice":this.parseVoice(t)}}parseVoice(e){let t=new Qe,s=e.getAttribute("id");for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Beats":this._beatsOfVoice.set(s,t.innerText.split(" "))}this._voiceById.set(s,t)}parseBeats(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Beat":this.parseBeat(t)}}parseBeat(e){let t=new De,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===G.Element)switch(i.localName){case"Notes":this._notesOfBeat.set(s,i.innerText.split(" "));break;case"Rhythm":this._rhythmOfBeat.set(s,i.getAttribute("ref"));break;case"Fadding":"FadeIn"===i.innerText&&(t.fadeIn=!0);break;case"Tremolo":switch(i.innerText){case"1/2":t.tremoloSpeed=u.Eighth;break;case"1/4":t.tremoloSpeed=u.Sixteenth;break;case"1/8":t.tremoloSpeed=u.ThirtySecond}break;case"Chord":t.chordId=i.innerText;break;case"Hairpin":switch(i.innerText){case"Crescendo":t.crescendo=d.Crescendo;break;case"Decrescendo":t.crescendo=d.Decrescendo}break;case"Arpeggio":"Up"===i.innerText?t.brushType=c.ArpeggioUp:t.brushType=c.ArpeggioDown;break;case"Properties":this.parseBeatProperties(i,t);break;case"XProperties":this.parseBeatXProperties(i,t);break;case"FreeText":t.text=i.innerText;break;case"TransposedPitchStemOrientation":switch(i.innerText){case"Upward":t.preferredBeamDirection=H.Up;break;case"Downward":t.preferredBeamDirection=H.Down}break;case"Dynamic":switch(i.innerText){case"PPP":t.dynamics=p.PPP;break;case"PP":t.dynamics=p.PP;break;case"P":t.dynamics=p.P;break;case"MP":t.dynamics=p.MP;break;case"MF":t.dynamics=p.MF;break;case"F":t.dynamics=p.F;break;case"FF":t.dynamics=p.FF;break;case"FFF":t.dynamics=p.FFF}break;case"GraceNotes":switch(i.innerText){case"OnBeat":t.graceType=g.OnBeat;break;case"BeforeBeat":t.graceType=g.BeforeBeat}break;case"Legato":"true"===i.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":let e=new be(0,0);e.value=this.toBendValue(parseFloat(i.getAttribute("originValue"))),e.offset=this.toBendOffset(parseFloat(i.getAttribute("originOffset"))),t.addWhammyBarPoint(e);let a=new be(0,0);a.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),a.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);let r=new be(0,0);r.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),r.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);let o=new be(0,0);o.value=this.toBendValue(parseFloat(i.getAttribute("destinationValue"))),o.offset=this.toBendOffset(parseFloat(i.getAttribute("destinationOffset"))),t.addWhammyBarPoint(o);break;case"Ottavia":switch(i.innerText){case"8va":t.ottava=n._8va;break;case"8vb":t.ottava=n._8vb;break;case"15ma":t.ottava=n._15ma;break;case"15mb":t.ottava=n._15mb}break;case"Lyrics":t.lyrics=this.parseBeatLyrics(i),this._skipApplyLyrics=!0}this._beatById.set(s,t)}parseBeatLyrics(e){const t=[];for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"Line":t.push(s.innerText)}return t}parseBeatXProperties(e,t){for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"XProperty":let e=0;switch(s.getAttribute("id")){case"1124204545":e=parseInt(s.findChildElement("Int").innerText),t.invertBeamDirection=1===e;break;case"687935489":e=parseInt(s.findChildElement("Int").innerText),t.brushDuration=e}}}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===G.Element)switch(h.localName){case"Property":switch(h.getAttribute("name")){case"Brush":"Up"===h.findChildElement("Direction").innerText?t.brushType=c.BrushUp:t.brushType=c.BrushDown;break;case"PickStroke":"Up"===h.findChildElement("Direction").innerText?t.pickStroke=x.Up:t.pickStroke=x.Down;break;case"Slapped":h.findChildElement("Enable")&&(t.slap=!0);break;case"Popped":h.findChildElement("Enable")&&(t.pop=!0);break;case"VibratoWTremBar":switch(h.findChildElement("Strength").innerText){case"Wide":t.vibrato=w.Wide;break;case"Slight":t.vibrato=w.Slight}break;case"WhammyBar":s=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":i||(i=new be(0,0)),i.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":i||(i=new be(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 be(be.MaxPosition,0)),o.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new be(0,0)),o.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText))}}s&&(i||(i=new be(0,0)),o||(o=new be(be.MaxPosition,0)),t.addWhammyBarPoint(i),r&&a&&t.addWhammyBarPoint(new be(r,a)),n&&a&&t.addWhammyBarPoint(new be(n,a)),r||n||!a||t.addWhammyBarPoint(new be(be.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Note":this.parseNote(t)}}parseNote(e){let t=new Pe,s=e.getAttribute("id");for(let a of e.childNodes)if(a.nodeType===G.Element)switch(a.localName){case"Properties":this.parseNoteProperties(a,t,s);break;case"AntiAccent":"normal"===a.innerText.toLowerCase()&&(t.isGhost=!0);break;case"LetRing":t.isLetRing=!0;break;case"Trill":t.trillValue=parseInt(a.innerText),t.trillSpeed=u.Sixteenth;break;case"Accent":let e=parseInt(a.innerText);0!=(1&e)&&(t.isStaccato=!0),0!=(4&e)&&(t.accentuated=i.Heavy),0!=(8&e)&&(t.accentuated=i.Normal);break;case"Tie":"true"===a.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(a.innerText){case"Slight":t.vibrato=w.Slight;break;case"Wide":t.vibrato=w.Wide}break;case"LeftFingering":switch(t.isFingering=!0,a.innerText){case"P":t.leftHandFinger=f.Thumb;break;case"I":t.leftHandFinger=f.IndexFinger;break;case"M":t.leftHandFinger=f.MiddleFinger;break;case"A":t.leftHandFinger=f.AnnularFinger;break;case"C":t.leftHandFinger=f.LittleFinger}break;case"RightFingering":switch(t.isFingering=!0,a.innerText){case"P":t.rightHandFinger=f.Thumb;break;case"I":t.rightHandFinger=f.IndexFinger;break;case"M":t.rightHandFinger=f.MiddleFinger;break;case"A":t.rightHandFinger=f.AnnularFinger;break;case"C":t.rightHandFinger=f.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=parseInt(a.innerText)}this._noteById.set(s,t)}parseNoteProperties(e,t,s){let i=!1,a=null,r=null,n=null,o=null,h=null,l=-1,c=-1;for(let d of e.childNodes)if(d.nodeType===G.Element)switch(d.localName){case"Property":switch(d.getAttribute("name")){case"String":t.string=parseInt(d.findChildElement("String").innerText)+1;break;case"Fret":t.fret=parseInt(d.findChildElement("Fret").innerText);break;case"Element":l=parseInt(d.findChildElement("Element").innerText);break;case"Variation":c=parseInt(d.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(s,!0);break;case"HarmonicType":let e=d.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=m.None;break;case"Natural":t.harmonicType=m.Natural;break;case"Artificial":t.harmonicType=m.Artificial;break;case"Pinch":t.harmonicType=m.Pinch;break;case"Tap":t.harmonicType=m.Tap;break;case"Semi":t.harmonicType=m.Semi;break;case"Feedback":t.harmonicType=m.Feedback}break;case"HarmonicFret":let u=d.findChildElement("HFret");u&&(t.harmonicValue=parseFloat(u.innerText));break;case"Muted":d.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":d.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=parseInt(d.findChildElement("Number").innerText),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=parseInt(d.findChildElement("Step").innerText);break;case"ConcertPitch":this.parseConcertPitch(d,t);break;case"Bended":i=!0;break;case"BendOriginValue":a||(a=new be(0,0)),a.value=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new be(0,0)),a.offset=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleValue":r=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleOffset1":n=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleOffset2":o=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationValue":h||(h=new be(be.MaxPosition,0)),h.value=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new be(0,0)),h.offset=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"HopoOrigin":d.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":let p=parseInt(d.findChildElement("Flags").innerText);0!=(1&p)?t.slideOutType=S.Shift:0!=(2&p)?t.slideOutType=S.Legato:0!=(4&p)?t.slideOutType=S.OutDown:0!=(8&p)&&(t.slideOutType=S.OutUp),0!=(16&p)?t.slideInType=b.IntoFromBelow:0!=(32&p)&&(t.slideInType=b.IntoFromAbove),0!=(64&p)?t.slideOutType=S.PickSlideDown:0!=(128&p)&&(t.slideOutType=S.PickSlideUp)}}i&&(a||(a=new be(0,0)),h||(h=new be(be.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new be(n,r)),o&&r&&t.addBendPoint(new be(o,r)),n||o||!r||t.addBendPoint(new be(be.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==c&&(t.percussionArticulation=xe.articulationFromElementVariation(l,c))}parseConcertPitch(e,t){const s=e.findChildElement("Pitch");if(s)for(let e of s.childNodes)if(e.nodeType===G.Element)switch(e.localName){case"Accidental":switch(e.innerText){case"x":t.accidentalMode=y.ForceDoubleSharp;break;case"#":t.accidentalMode=y.ForceSharp;break;case"b":t.accidentalMode=y.ForceFlat;break;case"bb":t.accidentalMode=y.ForceDoubleFlat}}}toBendValue(e){return e*gt.BendPointValueFactor|0}toBendOffset(e){return e*gt.BendPointPositionFactor}parseRhythms(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Rhythm":this.parseRhythm(t)}}parseRhythm(e){let t=new ut,s=e.getAttribute("id");t.id=s;for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"NoteValue":switch(s.innerText){case"Long":t.value=u.QuadrupleWhole;break;case"DoubleWhole":t.value=u.DoubleWhole;break;case"Whole":t.value=u.Whole;break;case"Half":t.value=u.Half;break;case"Quarter":t.value=u.Quarter;break;case"Eighth":t.value=u.Eighth;break;case"16th":t.value=u.Sixteenth;break;case"32nd":t.value=u.ThirtySecond;break;case"64th":t.value=u.SixtyFourth;break;case"128th":t.value=u.OneHundredTwentyEighth;break;case"256th":t.value=u.TwoHundredFiftySixth}break;case"PrimaryTuplet":t.tupletNumerator=parseInt(s.getAttribute("num")),t.tupletDenominator=parseInt(s.getAttribute("den"));break;case"AugmentationDot":t.dots=parseInt(s.getAttribute("count"))}this._rhythmById.set(s,t)}buildModel(){for(let e=0,t=this._masterBars.length;e<t;e++){let t=this._masterBars[e];this.score.addMasterBar(t)}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e);this.score.addTrack(t)}for(let e of this._barsOfMasterBar){let t=0;for(let s=0,i=0;s<e.length&&i<this.score.tracks.length;s++){let a=e[s];if(a!==gt.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!==gt.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!==gt.InvalidId){let t=Me.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!==gt.InvalidId){const e=Fe.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 Qe;e.addVoice(t);let s=new De;s.isEmpty=!0,s.duration=u.Quarter,t.addBeat(s)}t===s.staves.length-1?(i++,t=0):t++}else i++}}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e),s=!1;for(const e of t.staves)if(e.isPercussion){s=!0;break}if(s||(t.percussionArticulations=[]),this._automationsPerTrackIdAndBarIndex.has(e)){const s=this._automationsPerTrackIdAndBarIndex.get(e);for(const[e,i]of s)if(t.staves.length>0&&e<t.staves[0].bars.length){const s=t.staves[0].bars[e];if(s.voices.length>0&&s.voices[0].beats.length>0){const e=s.voices[0].beats[0];for(const t of i)e.automations.push(t)}}}}for(const[e,t]of this._masterTrackAutomations){let s=this.score.masterBars[e];for(let i=0,r=t.length;i<r;i++){let r=t[i];r.type===a.Tempo&&(0===e&&(this.score.tempo=0|r.value,r.text&&(this.score.tempoLabel=r.text)),s.tempoAutomation=r)}}}}gt.InvalidId="-1",gt.BendPointPositionFactor=be.MaxPosition/100,gt.BendPointValueFactor=.04;class ft{constructor(){this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class mt{constructor(){this.isMultiRest=!1,this.tracks=[]}}class yt{constructor(e){this.parts=[],this.zoomLevel=0,this.layout=0;let t=$e.fromBuffer(e),s=Ke.readInt32BE(t);for(let e=0;e<s;e++){let e=new mt;this.parts.push(e),e.isMultiRest=st.gpReadBool(t);let s=Ke.readInt32BE(t);for(let i=0;i<s;i++){let s=t.readByte();0===s&&(s=1);let i=new ft;i.showStandardNotation=0!=(1&s),i.showTablature=0!=(2&s),i.showSlash=0!=(4&s),e.tracks.push(i)}}}apply(e){let t=0,s=0;for(let i of this.parts)for(let a of i.tracks){if(s<e.tracks.length){let i=e.tracks[s];if(t<i.staves.length){let e=i.staves[t];e.showTablature=a.showTablature,e.showStandardNotation=a.showStandardNotation}}s++,s>=e.tracks.length&&(t++,s=0)}}static writeForScore(e){const t=$e.withCapacity(128),s=[new mt];for(const t of e.tracks)for(const e of t.staves){const t=new ft;if(t.showStandardNotation=e.showStandardNotation,t.showTablature=e.showTablature,0===e.index)s[0].tracks.push(t);else{let e=new mt;e.tracks.push(t),s.push(e)}}Ke.writeInt32BE(t,s.length);for(const e of s){t.writeByte(e.isMultiRest?1:0),Ke.writeInt32BE(t,e.tracks.length);for(const s of e.tracks){let e=0;s.showStandardNotation&&(e|=1),s.showTablature&&(e|=2),s.showSlash&&(e|=4),t.writeByte(e)}}return t.toArray()}}class bt{}class St extends bt{constructor(e){super(),this.n=e}}class wt extends bt{constructor(e,t){super(),this.left=e,this.right=t}}class _t extends bt{constructor(e,t){super(),this.n=e,this.table=t}}class Bt{static make(e,t,s,i){let a=[],r=[];if(i>32)throw new ze("Invalid huffman");for(let e=0;e<i;e++)a.push(0),r.push(0);for(let r=0;r<s;r++){let s=e[r+t];if(s>=i)throw new ze("Invalid huffman");a[s]++}let n=0;for(let e=1;e<i-1;e++)n=n+a[e]<<1,r[e]=n;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 Bt.treeCompress(new wt(Bt.treeMake(o,i,0,1),Bt.treeMake(o,i,1,1)))}static treeMake(e,t,s,i){if(i>t)throw new ze("Invalid huffman");let a=s<<5|i;return e.has(a)?new St(e.get(a)):(s<<=1,i+=1,new wt(Bt.treeMake(e,t,s,i),Bt.treeMake(e,t,1|s,i)))}static treeCompress(e){let t=Bt.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof wt)return new wt(Bt.treeCompress(e.left),Bt.treeCompress(e.right));throw new ze("assert")}let s=1<<t,i=[];for(let e=0;e<s;e++)i.push(new St(-1));return Bt.treeWalk(i,0,0,t,e),new _t(t,i)}static treeWalk(e,t,s,i,a){a instanceof wt&&i>0?(Bt.treeWalk(e,t,s+1,i-1,a.left),Bt.treeWalk(e,t|1<<s,s+1,i-1,a.right)):e[t]=Bt.treeCompress(a)}static treeDepth(e){if(e instanceof St)return 0;if(e instanceof _t)throw new ze("assert");if(e instanceof wt){let t=Bt.treeDepth(e.left),s=Bt.treeDepth(e.right);return 1+(t<s?t:s)}return 0}}!function(e){e[e.Head=0]="Head",e[e.Block=1]="Block",e[e.CData=2]="CData",e[e.Flat=3]="Flat",e[e.Crc=4]="Crc",e[e.Dist=5]="Dist",e[e.DistOne=6]="DistOne",e[e.Done=7]="Done"}(W||(W={}));class Tt{constructor(){this.buffer=new Uint8Array(Tt.BufferSize),this.pos=0}slide(){let e=new Uint8Array(Tt.BufferSize);this.pos-=Tt.Size,e.set(this.buffer.subarray(Tt.Size,Tt.Size+this.pos),0),this.buffer=e}addBytes(e,t,s){this.pos+s>Tt.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+s),this.pos),this.pos+=s}addByte(e){this.pos===Tt.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}Tt.Size=32768,Tt.BufferSize=65536;class kt{constructor(e){this._nbits=0,this._bits=0,this._state=W.Block,this._isFinal=!1,this._huffman=kt._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new Tt,this._input=e;for(let e=0;e<19;e++)this._lengths.push(-1)}static buildFixedHuffman(){let e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return Bt.make(e,0,288,10)}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 W.Head:let e=this._input.readByte();if(8!==(15&e))throw new ze("Invalid data");let t=this._input.readByte(),s=0!=(32&t);if(((e<<8)+t)%31!=0)throw new ze("Invalid data");if(s)throw new ze("Unsupported dictionary");return this._state=W.Block,!0;case W.Crc:return this._state=W.Done,!0;case W.Done:return!1;case W.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:if(this._len=Ke.readUInt16LE(this._input),Ke.readUInt16LE(this._input)!==65535-this._len)throw new ze("Invalid data");this._state=W.Flat;let e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=kt._fixedHuffman,this._huffdist=null,this._state=W.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[kt.CodeLengthsPos[e]]=this.getBits(3);for(let e=i;e<19;e++)this._lengths[kt.CodeLengthsPos[e]]=0;this._huffman=Bt.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=Bt.make(a,t,s,16),this._huffman=Bt.make(a,0,t,16),this._state=W.CData,!0;default:throw new ze("Invalid data")}case W.Flat:{let e=this._len<this._needed?this._len:this._needed,t=Ke.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?W.Crc:W.Block),this._needed>0}case W.DistOne:{let e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=W.CData),this._needed>0}case W.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=W.CData),this._needed>0;case W.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?W.Crc:W.Block,!0;{i=i-257&255;let e=kt.LenExtraBitsTbl[i];if(-1===e)throw new ze("Invalid data");this._len=kt.LenBaseValTbl[i]+this.getBits(e);let t=this._huffdist,s=t?this.applyHuffman(t):this.getRevBits(5);if(e=kt.DistExtraBitsTbl[s],-1===e)throw new ze("Invalid data");if(this._dist=kt.DistBaseValTbl[s]+this.getBits(e),this._dist>this._window.available())throw new ze("Invalid data");return this._state=1===this._dist?W.DistOne:W.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==(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 ze("Invalid data");for(;s<r;)e[s]=i,s++;break;case 17:if(s+=3+this.getBits(3),s>t)throw new ze("Invalid data");break;case 18:if(s+=11+this.getBits(7),s>t)throw new ze("Invalid data");break;default:throw new ze("Invalid data")}}}applyHuffman(e){if(e instanceof St)return e.n;if(e instanceof wt)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof _t)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new ze("Invalid data")}}kt.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],kt.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],kt.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],kt.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],kt.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],kt._fixedHuffman=kt.buildFixedHuffman();class vt{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}}vt.OptionalDataDescriptorSignature=134695760,vt.CompressionMethodDeflate=8,vt.LocalFileHeaderSignature=67324752,vt.CentralFileHeaderSignature=33639248,vt.EndOfCentralDirSignature=101010256;class xt{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(Ke.readInt32LE(e)!==vt.LocalFileHeaderSignature)return null;Ke.readUInt16LE(e);let t=Ke.readUInt16LE(e),s=Ke.readUInt16LE(e),i=0!==s;if(i&&s!==vt.CompressionMethodDeflate)return null;Ke.readInt16LE(this._readable),Ke.readInt16LE(this._readable),Ke.readInt32LE(e),Ke.readInt32LE(e);let a,r=Ke.readInt32LE(e),n=Ke.readInt16LE(e),o=Ke.readInt16LE(e),h=Ke.toString(Ke.readByteArray(e,n),"utf-8");if(e.skip(o),i){let e=$e.empty(),t=new kt(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=Ke.readByteArray(this._readable,r);if(0!=(8&t)){Ke.readInt32LE(this._readable)===vt.OptionalDataDescriptorSignature&&Ke.readInt32LE(this._readable),Ke.readInt32LE(this._readable),Ke.readInt32LE(this._readable)}return new vt(h,a)}}class Nt extends ue{get name(){return"Guitar Pro 7"}constructor(){super()}readScore(){Be.debug(this.name,"Loading ZIP entries");let e,t=new xt(this.data);try{e=t.read()}catch(e){throw new ge("No Zip archive",e)}Be.debug(this.name,"Zip entries loaded");let s=null,i=null,a=null;for(let t of e)switch(t.fileName){case"score.gpif":s=Ke.toString(t.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=t.data;break;case"PartConfiguration":a=t.data}if(!s)throw new ge("No score.gpif found in zip archive");Be.debug(this.name,"Start Parsing score.gpif");let r=new gt;r.parseXml(s,this.settings),Be.debug(this.name,"score.gpif parsed");let n=r.score;if(i){Be.debug(this.name,"Start Parsing BinaryStylesheet"),new rt(i).apply(n),Be.debug(this.name,"BinaryStylesheet parsed")}if(a){Be.debug(this.name,"Start Parsing Part Configuration"),new yt(a).apply(n),Be.debug(this.name,"Part Configuration parsed")}return n}}class Pt extends pe{constructor(){super(s.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,Pt.prototype)}}class Et{constructor(e){this._currentByte=0,this._position=Et.ByteSize,this._source=e}readByte(){return this.readBits(8)}readBytes(e){const t=new Uint8Array(e);for(let s=0;s<e;s++)t[s]=255&this.readByte();return t}readBits(e){let t=0,s=e-1;for(;s>=0;)t|=this.readBit()<<s,s--;return t}readBitsReversed(e){let t=0;for(let s=0;s<e;s++)t|=this.readBit()<<s;return t}readBit(){if(this._position>=8){if(this._currentByte=this._source.readByte(),-1===this._currentByte)throw new Pt;this._position=0}const e=this._currentByte>>Et.ByteSize-this._position-1&1;return this._position++,e}readAll(){let e=$e.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof Pt))throw e}return e.toArray()}}Et.ByteSize=8;class Ct{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class Ft{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){let t=new Et(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){let s,i=$e.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 Pt))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 ge("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 Ct;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?$e.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]}}Ft.HeaderBcFs="BCFS",Ft.HeaderBcFz="BCFZ",Ft.ScoreGpif="score.gpif",Ft.BinaryStylesheet="BinaryStylesheet",Ft.PartConfiguration="PartConfiguration";class Lt extends ue{get name(){return"Guitar Pro 6"}constructor(){super()}readScore(){Be.debug(this.name,"Loading GPX filesystem");let e=new Ft;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration"),e.load(this.data),Be.debug(this.name,"GPX filesystem loaded");let t=null,s=null,i=null;for(let a of e.files)switch(a.fileName){case"score.gpif":t=Ke.toString(a.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=a.data;break;case"PartConfiguration":i=a.data}if(!t)throw new ge("No score.gpif found in GPX");Be.debug(this.name,"Start Parsing score.gpif");let a=new gt;a.parseXml(t,this.settings),Be.debug(this.name,"score.gpif parsed");let r=a.score;if(s){Be.debug(this.name,"Start Parsing BinaryStylesheet"),new rt(s).apply(r),Be.debug(this.name,"BinaryStylesheet parsed")}if(i){Be.debug(this.name,"Start Parsing Part Configuration"),new yt(i).apply(r),Be.debug(this.name,"Part Configuration parsed")}return r}}class Mt extends ue{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}get name(){return"MusicXML"}readScore(){this._trackById=new Map,this._partGroups=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._slurStarts=new Map;let e=Ke.toString(this.data.readAll(),this.settings.importer.encoding),t=new dt;try{t.parse(e)}catch(e){throw new ge("Unsupported format")}return this._score=new He,this._score.tempo=120,this.parseDom(t),this.settings.importer.mergePartGroupsInMusicXml&&this.mergePartGroups(),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}mergePartGroups(){let e=!1;for(const t of this._partGroups.values())t.length>1&&(this.mergeGroup(t),e=!0);if(e)for(let e=0;e<this._score.tracks.length;e++)this._score.tracks[e].index=e}mergeGroup(e){let t=e[0];for(let s=1;s<e.length;s++){let i=e[s];for(let e of i.staves)t.addStaff(e);let a=this._score.tracks.indexOf(i);this._score.tracks.splice(a,1)}}parseDom(e){let t=e.firstElement;if(!t)throw new ge("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":break;default:throw new ge("Unsupported format")}}parsePartwise(e){for(let t of e.childNodes)if(t.nodeType===G.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===G.Element)switch(t.localName){case"work-title":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===G.Element)switch(t.localName){case"measure":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 me;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)}if(r){let s=!1;for(let i of e.childNodes)if(i.nodeType===G.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);break;case"sound":break;case"barline":this.parseBarline(i,r)}}return!0}ensureVoices(e){for(;e.voices.length<this._maxVoices;){let t=new Qe;e.addVoice(t);let s=new De;s.isEmpty=!0,s.chordId=this._currentChord,t.addBeat(s)}}getOrCreateBeat(e,t,s){let i=0,a=e.getElementsByTagName("voice",!1);a.length>0&&(i=parseInt(a[0].innerText)-1);let r=this._previousBeatWasPulled;this._previousBeatWasPulled=!1;let n,o,h=e.getElementsByTagName("staff",!1),l=1;if(h.length>0){l=parseInt(h[0].innerText),(this._isBeamContinue||r)&&this._previousBeat.voice.bar.staff.index!==l-1&&(l=this._previousBeat.voice.bar.staff.index+1,this._previousBeatWasPulled=!0);let e=t[0].staff.track.index+"-"+l;this._voiceOfStaff.has(e)||this._voiceOfStaff.set(e,i)}l--,n=l<0?t[0]:l>=t.length?t[t.length-1]:t[l];let c=this.getOrCreateVoice(n,i);return s&&c.beats.length>0||1===c.beats.length&&c.isEmpty?o=c.beats[c.beats.length-1]:(o=new De,o.isEmpty=!1,c.addBeat(o)),this._isBeamContinue=!1,this._previousBeat=o,o}parseForward(e,t){let s=this.getOrCreateBeat(e,t,!1),i=parseInt(e.findChildElement("duration").innerText)*u.Quarter/this._divisionsPerQuarterNote,a=[u.SixtyFourth,u.ThirtySecond,u.Sixteenth,u.Eighth,u.Quarter,u.Half,u.Whole];for(let e of a)if(i>=e){s.duration=e,i-=e;break}s.isEmpty=!1}parseStaffDetails(e,t){for(let s of e.childNodes)if(s.nodeType===G.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===G.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=ke.getTuningForText(i+a)+r;for(let e of t.staves)e.tuning[e.tuning.length-s]=n}parseHarmony(e,t){let s=null,i="";for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"root":for(let e of t.childNodes)if(e.nodeType===G.Element)switch(e.localName){case"root-step":s=e.innerText;break;case"root-alter":switch(parseInt(t.innerText)){case-2:i=" bb";break;case-1:i=" b";break;case 0:i="";break;case 1:i=" #";break;case 2:i=" ##"}}}let a=new Re;a.name=s+i,this._currentChord=ke.newGuid();for(let e of t.staves)e.addChord(this._currentChord,a)}parseBarline(e,t){for(let s of e.childNodes)if(s.nodeType===G.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 Pe;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===G.Element)switch(t.localName){case"grace":i.graceType=g.BeforeBeat,i.duration=u.ThirtySecond;break;case"duration":if(i.isRest&&!r){switch(parseInt(t.innerText)){case 1:i.duration=u.Whole;break;case 2:i.duration=u.Half;break;case 4:i.duration=u.Quarter;break;case 8:i.duration=u.Eighth;break;case 16:i.duration=u.Sixteenth;break;case 32:i.duration=u.ThirtySecond;break;case 64:i.duration=u.SixtyFourth;break;default:i.duration=u.Quarter}}break;case"tie":this.parseTied(t,a);break;case"cue":case"instrument":break;case"type":i.duration=this.getDuration(t.innerText),i.graceType!==g.None&&i.duration<u.Sixteenth&&(i.duration=u.Eighth);break;case"dot":i.dots++;break;case"accidental":this.parseAccidental(t,a);break;case"time-modification":this.parseTimeModification(t,i);break;case"stem":break;case"notehead":"yes"===t.getAttribute("parentheses")&&(a.isGhost=!0);break;case"beam":"continue"===t.innerText&&(this._isBeamContinue=!0);break;case"notations":this.parseNotations(t,i,a);break;case"lyric":this.parseLyric(t,i);break;case"pitch":this.parsePitch(t,a);break;case"unpitched":this.parseUnpitched(t,a);break;case"rest":r="yes"===t.getAttribute("measure"),i.isEmpty=!1,i.notes=[],i.duration=u.Whole}if(a.isStringed)for(let e=0;e<i.notes.length;e++)if(i.notes[e].string===a.string&&i.notes[e]!==a){i.removeNote(a);break}}getDuration(e){switch(e){case"256th":case"128th":case"64th":return u.SixtyFourth;case"32nd":return u.ThirtySecond;case"16th":return u.Sixteenth;case"eighth":return u.Eighth;case"quarter":return u.Quarter;case"half":return u.Half;case"long":case"breve":case"whole":return u.Whole}return u.Quarter}parseLyric(e,t){for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"text":t.text?t.text+=" "+s.innerText:t.text=s.innerText}}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=y.ForceSharp;break;case"natural":t.accidentalMode=y.ForceNatural;break;case"flat":t.accidentalMode=y.ForceFlat}}parseTied(e,t){"start"===e.getAttribute("type")?this._tieStartIds.has(t.id)||(this._tieStartIds.set(t.id,!0),this._tieStarts.push(t)):"stop"===e.getAttribute("type")&&this._tieStarts.length>0&&!t.isTieDestination&&(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===G.Element)switch(i.localName){case"articulations":this.parseArticulations(i,s);break;case"tied":this.parseTied(i,s);break;case"slide":case"glissando":"start"===i.getAttribute("type")&&(s.slideOutType=S.Shift);break;case"dynamics":this.parseDynamics(i,t);break;case"technical":this.parseTechnical(i,s);break;case"ornaments":this.parseOrnaments(i,s);break;case"slur":let e=i.getAttribute("number");switch(e||(e="1"),i.getAttribute("type")){case"start":this._slurStarts.set(e,s);break;case"stop":if(this._slurStarts.has(e)){s.isSlurDestination=!0,this._slurStarts.get(e).slurDestination=s,s.slurOrigin=s}}}}parseOrnaments(e,t){for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"tremolo":switch(parseInt(s.innerText)){case 1:t.beat.tremoloSpeed=u.Eighth;break;case 2:t.beat.tremoloSpeed=u.Sixteenth;break;case 3:t.beat.tremoloSpeed=u.ThirtySecond}}}parseTechnical(e,t){for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"string":t.string=parseInt(s.innerText),-2147483648!==t.string&&(t.string=t.beat.voice.bar.staff.tuning.length-t.string+1);break;case"fret":t.fret=parseInt(s.innerText);break;case"down-bow":t.beat.pickStroke=x.Down;break;case"up-bow":t.beat.pickStroke=x.Up}-2147483648!==t.string&&-2147483648!==t.fret||(t.string=-1,t.fret=-1)}parseArticulations(e,t){for(let s of e.childNodes)switch(s.localName){case"accent":t.accentuated=i.Normal;break;case"strong-accent":t.accentuated=i.Heavy;break;case"staccato":case"detached-legato":t.isStaccato=!0}}parseDynamics(e,t){for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"p":t.dynamics=p.P;break;case"pp":t.dynamics=p.PP;break;case"ppp":t.dynamics=p.PPP;break;case"f":t.dynamics=p.F;break;case"ff":t.dynamics=p.FF;break;case"fff":t.dynamics=p.FFF;break;case"mp":t.dynamics=p.MP;break;case"mf":t.dynamics=p.MF}}parseTimeModification(e,t){for(let s of e.childNodes)if(s.nodeType===G.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===G.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+ke.getToneForText(s)+i;t.octave=r/12|0,t.tone=r-12*t.octave}parsePitch(e,t){let s="",i=0,a=0;for(let t of e.childNodes)if(t.nodeType===G.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+ke.getToneForText(s)+(0|i);t.octave=r/12|0,t.tone=r-12*t.octave}getOrCreateVoice(e,t){if(t<e.voices.length)return e.voices[t];for(let s=e.voices.length;s<=t;s++)e.addVoice(new Qe);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===G.Element)switch(s.localName){case"sound":let e=s.getAttribute("tempo");if(e){let s=new fe;s.isLinear=!0,s.type=a.Tempo,s.value=parseInt(e),t.tempoAutomation=s}break;case"direction-type":let i=s.firstElement;switch(i.localName){case"words":this._currentDirection=i.innerText;break;case"metronome":this.parseMetronome(i,t)}}}parseMetronome(e,t){let s=u.Quarter,i=120;for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"beat-unit":s=this.getDuration(t.innerText);break;case"per-minute":i=parseInt(t.innerText)}let r=new fe;r.type=a.Tempo,r.value=i*(s/4|0),t.tempoAutomation=r}parseAttributes(e,t,s,i){let a=0,r=!1;for(let n of e.childNodes)if(n.nodeType===G.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===G.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===G.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":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;break;default:t.clef=r.G2}}parseTime(e,t){"common"===e.getAttribute("symbol")&&(t.timeSignatureCommon=!0);let s=!1,i=!1;for(let a of e.childNodes)if(a.nodeType===G.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===G.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:M.C,t.keySignatureType="minor"===i?I.Minor:I.Major}getOrCreateMasterBar(e){if(e<this._score.masterBars.length)return this._score.masterBars[e];for(let t=this._score.masterBars.length;t<=e;t++){let e=new Oe;if(this._score.masterBars.length>0){let t=this._score.masterBars[this._score.masterBars.length-1];e.timeSignatureDenominator=t.timeSignatureDenominator,e.timeSignatureNumerator=t.timeSignatureNumerator,e.keySignature=t.keySignature,e.keySignatureType=t.keySignatureType}this._score.addMasterBar(e)}return this._score.masterBars[e]}parseIdentification(e){for(let t of e.childNodes)if(t.nodeType===G.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===G.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 Je;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===G.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===G.Element)switch(s.localName){case"midi-channel":t.playbackInfo.primaryChannel=parseInt(s.innerText);break;case"midi-program":t.playbackInfo.program=parseInt(s.innerText);break;case"volume":t.playbackInfo.volume=Math.floor(parseInt(s.innerText)/100*16);break;case"pan":t.playbackInfo.balance=Math.max(0,Math.min(16,Math.floor((parseInt(s.innerText)+90)/180*16)))}}}!function(e){e[e.PerNotePitchBend=96]="PerNotePitchBend",e[e.NoteOff=128]="NoteOff",e[e.NoteOn=144]="NoteOn",e[e.NoteAftertouch=160]="NoteAftertouch",e[e.Controller=176]="Controller",e[e.ProgramChange=192]="ProgramChange",e[e.ChannelAftertouch=208]="ChannelAftertouch",e[e.PitchBend=224]="PitchBend",e[e.SystemExclusive=240]="SystemExclusive",e[e.SystemExclusive2=247]="SystemExclusive2",e[e.Meta=255]="Meta"}(z||(z={}));class It{constructor(e,t,s,i,a){this.track=e,this.tick=t,this.message=s|i<<8|a<<16}get channel(){return 15&this.message}get command(){return 240&this.message}get data1(){return(65280&this.message)>>8}set data1(e){this.message&=-65281,this.message|=e<<8}get data2(){return(16711680&this.message)>>16}set data2(e){this.message&=-16711681,this.message|=e<<16}writeTo(e){let t=new Uint8Array([this.message>>24&255,this.message>>16&255,this.message>>8&255,255&this.message]);e.write(t,0,t.length)}}!function(e){e[e.SequenceNumber=0]="SequenceNumber",e[e.TextEvent=1]="TextEvent",e[e.CopyrightNotice=2]="CopyrightNotice",e[e.SequenceOrTrackName=3]="SequenceOrTrackName",e[e.InstrumentName=4]="InstrumentName",e[e.LyricText=5]="LyricText",e[e.MarkerText=6]="MarkerText",e[e.CuePoint=7]="CuePoint",e[e.PatchName=8]="PatchName",e[e.PortName=9]="PortName",e[e.MidiChannel=32]="MidiChannel",e[e.MidiPort=33]="MidiPort",e[e.EndOfTrack=47]="EndOfTrack",e[e.Tempo=81]="Tempo",e[e.SmpteOffset=84]="SmpteOffset",e[e.TimeSignature=88]="TimeSignature",e[e.KeySignature=89]="KeySignature",e[e.SequencerSpecific=127]="SequencerSpecific"}(U||(U={}));class Dt extends It{get channel(){return-1}get command(){return 255&this.message}get metaStatus(){return this.data1}constructor(e,t,s,i,a){super(e,t,s,i,a)}}!function(e){e[e.SystemExclusive=240]="SystemExclusive",e[e.MtcQuarterFrame=241]="MtcQuarterFrame",e[e.SongPosition=242]="SongPosition",e[e.SongSelect=243]="SongSelect",e[e.TuneRequest=246]="TuneRequest",e[e.SystemExclusive2=247]="SystemExclusive2"}(X||(X={}));class Rt extends It{get channel(){return-1}get command(){return 255&this.message}constructor(e,t,s,i,a){super(e,t,s,i,a)}}!function(e){e[e.MetronomeTick=0]="MetronomeTick",e[e.Rest=1]="Rest"}(Y||(Y={}));class At extends Rt{constructor(e,t,s,i,a){super(e,t,s,255&i,i>>8&255),this.data=a}get isMetronome(){return this.manufacturerId==At.AlphaTabManufacturerId&&this.data[0]==Y.MetronomeTick}get metronomeNumerator(){return this.isMetronome?this.data[1]:-1}get metronomeDurationInTicks(){return this.isMetronome?Ke.decodeUInt32LE(this.data,2):-1}get metronomeDurationInMilliseconds(){return this.isMetronome?Ke.decodeUInt32LE(this.data,6):-1}get isRest(){return this.manufacturerId==At.AlphaTabManufacturerId&&this.data[0]==Y.Rest}get manufacturerId(){return this.message>>8}writeTo(e){e.writeByte(240);let t=this.data.length+2;e.writeByte(this.manufacturerId);let s=new Uint8Array([t>>24&255,t>>16&255,t>>8&255,255&t]);e.write(s,0,s.length),e.writeByte(247)}static encodeMetronome(e,t,s){const i=$e.withCapacity(10);return i.writeByte(Y.MetronomeTick),i.writeByte(e),Ke.writeInt32LE(i,t),Ke.writeInt32LE(i,s),i.toArray()}}At.AlphaTabManufacturerId=125;class Ot{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event instanceof At&&this.event.isMetronome}static newMetronomeEvent(e,t,s,i,a){const r=new At(0,t,z.SystemExclusive2,At.AlphaTabManufacturerId,At.encodeMetronome(s,i,a));return new Ot(e,r)}}class Gt{}Gt.DefaultChannelCount=17,Gt.MetronomeChannel=Gt.DefaultChannelCount-1,Gt.AudioChannels=2,Gt.MinVolume=0,Gt.MinProgram=0,Gt.MaxProgram=127,Gt.MinPlaybackSpeed=.125,Gt.MaxPlaybackSpeed=8,Gt.MaxPitchWheel=16384,Gt.MaxPitchWheel20=4294967296,Gt.DefaultPitchWheel=Gt.MaxPitchWheel/2,Gt.MicroBufferCount=32,Gt.MicroBufferSize=64;class Vt{constructor(e,t,s){this.bpm=e,this.ticks=t,this.time=s}}class Ht{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=ye.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class Wt{constructor(e){this._oneTimeState=null,this._countInState=null,this.isLooping=!1,this.playbackSpeed=1,this._synthesizer=e,this._mainState=new Ht,this._currentState=this._mainState}get isPlayingOneTimeMidi(){return this._currentState==this._oneTimeState}get isPlayingCountIn(){return this._currentState==this._countInState}get playbackRange(){return this._currentState.playbackRange}set playbackRange(e){this._currentState.playbackRange=e,e&&(this._currentState.playbackRangeStartTime=this.tickPositionToTimePositionWithSpeed(e.startTick,1),this._currentState.playbackRangeEndTime=this.tickPositionToTimePositionWithSpeed(e.endTick,1))}get currentTime(){return this._currentState.currentTime}get endTick(){return this._currentState.endTick}get endTime(){return this._currentState.endTime/this.playbackSpeed}seek(e){if(e*=this.playbackSpeed,this.playbackRange&&(e<this._currentState.playbackRangeStartTime?e=this._currentState.playbackRangeStartTime:e>this._currentState.playbackRangeEndTime&&(e=this._currentState.playbackRangeEndTime)),e>this._currentState.currentTime)this.silentProcess(e-this._currentState.currentTime);else if(e<this._currentState.currentTime){this._currentState.currentTime=0,this._currentState.eventIndex=0;let t=this._synthesizer.metronomeVolume;this._synthesizer.noteOffAll(!0),this._synthesizer.resetSoft(),this._synthesizer.setupMetronomeChannel(t),this.silentProcess(e)}}silentProcess(e){if(e<=0)return;let t=Date.now(),s=this._currentState.currentTime+e;for(;this._currentState.currentTime<s;)this.fillMidiEventQueueLimited(s-this._currentState.currentTime)&&this._synthesizer.synthesizeSilent(Gt.MicroBufferSize);this._currentState.currentTime=s;let i=Date.now()-t;Be.debug("Sequencer","Silent seek finished in "+i+"ms")}loadOneTimeMidi(e){this._oneTimeState=this.createStateFromFile(e),this._currentState=this._oneTimeState}loadMidi(e){this._mainState=this.createStateFromFile(e),this._currentState=this._mainState}createStateFromFile(e){const t=new Ht;t.tempoChanges=[],t.division=e.division,t.eventIndex=0,t.currentTime=0,t.synthData=[];let s=120,i=0,a=0,r=0,n=0,o=0,h=0,l=0,c=0;for(let d of e.events){let u=new Ot(t.synthData.length,d);t.synthData.push(u);let p=d.tick-c;if(i+=p,a+=p*(6e4/(s*e.division)),u.time=a,c=d.tick,n>0)for(;h<i;){let e=Ot.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(d.command===z.Meta&&d.data1===U.Tempo){s=6e7/d.value,t.tempoChanges.push(new Vt(s,i,a)),o=n*(6e4/(s*e.division))}else if(d.command===z.Meta&&d.data1===U.TimeSignature){let i=d,a=Math.pow(2,i.data[1]);r=i.data[0],n=t.division*(4/a)|0,o=n*(6e4/(s*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=i.data[0],t.firstTimeSignatureDenominator=a)}else if(d.command===z.ProgramChange){let e=d.channel;t.firstProgramEventPerChannel.has(e)||t.firstProgramEventPerChannel.set(e,u)}}return t.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),t.endTime=a,t.endTick=i,t}fillMidiEventQueue(){return this.fillMidiEventQueueLimited(-1)}fillMidiEventQueueLimited(e){let t=Gt.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}tickPositionToTimePosition(e){return this.tickPositionToTimePositionWithSpeed(e,this.playbackSpeed)}timePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(e,this.playbackSpeed)}tickPositionToTimePositionWithSpeed(e,t){let s=0,i=120,a=0;for(const t of this._currentState.tempoChanges){if(e<t.ticks)break;s=t.time,i=t.bpm,a=t.ticks}return s+=(e-=a)*(6e4/(i*this._currentState.division)),s/t}timePositionToTickPositionWithSpeed(e,t){e*=t;let s=0,i=120,a=0;for(const t of this._currentState.tempoChanges){if(e<t.time)break;s=t.ticks,i=t.bpm,a=t.time}return s+=(e-=a)/(6e4/(i*this._currentState.division))|0,s+1}get internalEndTime(){return this.playbackRange?this._currentState.playbackRangeEndTime:this._currentState.endTime}get isFinished(){return this._currentState.currentTime>=this.internalEndTime}stop(){this.playbackRange?this.playbackRange&&(this._currentState.currentTime=this.playbackRange.startTick,this._currentState.eventIndex=0):(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 Ht;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 Vt(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=Ot.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"}(q||(q={}));class zt{constructor(e,t){this.state=e,this.stopped=t}}class Ut{constructor(e,t,s,i,a){this.currentTime=e,this.endTime=t,this.currentTick=s,this.endTick=i,this.isSeek=a}}class Xt{constructor(){this.id="",this.size=0}static load(e,t,s){if(e&&Xt.HeaderSize>e.size)return!1;if(s.position+Xt.HeaderSize>=s.length)return!1;if(t.id=Ke.read8BitStringLength(s,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=Ke.readUInt32LE(s),e&&Xt.HeaderSize+t.size>e.size)return!1;e&&(e.size-=Xt.HeaderSize+t.size);let i="RIFF"===t.id,a="LIST"===t.id;return(!i||!e)&&(!i&&!a||(t.id=Ke.read8BitStringLength(s,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}Xt.HeaderSize=8;class Yt{constructor(){this.phdrs=[],this.pbags=[],this.pmods=[],this.pgens=[],this.insts=[],this.ibags=[],this.imods=[],this.igens=[],this.sHdrs=[],this.fontSamples=new Float32Array(0)}load(e){const t=new Xt,s=new Xt;if(!Xt.load(null,t,e)||"sfbk"!==t.id)throw new ze("Soundfont is not a valid Soundfont2 file");for(;Xt.load(t,s,e);){let t=new Xt;if("pdta"===s.id)for(;Xt.load(s,t,e);)switch(t.id){case"phdr":for(let s=0,i=t.size/Zt.SizeInFile|0;s<i;s++)this.phdrs.push(new Zt(e));break;case"pbag":for(let s=0,i=t.size/Kt.SizeInFile|0;s<i;s++)this.pbags.push(new Kt(e));break;case"pmod":for(let s=0,i=t.size/es.SizeInFile|0;s<i;s++)this.pmods.push(new es(e));break;case"pgen":for(let s=0,i=t.size/$t.SizeInFile|0;s<i;s++)this.pgens.push(new $t(e));break;case"inst":for(let s=0,i=t.size/jt.SizeInFile|0;s<i;s++)this.insts.push(new jt(e));break;case"ibag":for(let s=0,i=t.size/qt.SizeInFile|0;s<i;s++)this.ibags.push(new qt(e));break;case"imod":for(let s=0,i=t.size/Jt.SizeInFile|0;s<i;s++)this.imods.push(new Jt(e));break;case"igen":for(let s=0,i=t.size/Qt.SizeInFile|0;s<i;s++)this.igens.push(new Qt(e));break;case"shdr":for(let s=0,i=t.size/ts.SizeInFile|0;s<i;s++)this.sHdrs.push(new ts(e));break;default:e.position+=t.size}else if("sdta"===s.id)for(;Xt.load(s,t,e);)switch(t.id){case"smpl":this.fontSamples=Yt.loadSamples(t,e);break;default:e.position+=t.size}else e.position+=s.size}}static loadSamples(e,t){let s=e.size/2|0;const i=new Float32Array(s);let a=0;const r=new Uint8Array(2048);for(;s>0;){let e=Math.min(s,r.length/2|0);t.read(r,0,2*e);for(let t=0;t<e;t++){const e=je.int32ToInt16(r[2*t+1]<<8|r[2*t]);i[a+t]=e/32767}s-=e,a+=e}return i}}class qt{constructor(e){this.instGenNdx=Ke.readUInt16LE(e),this.instModNdx=Ke.readUInt16LE(e)}}qt.SizeInFile=4;class Jt{constructor(e){this.modSrcOper=Ke.readUInt16LE(e),this.modDestOper=Ke.readUInt16LE(e),this.modAmount=Ke.readInt16LE(e),this.modAmtSrcOper=Ke.readUInt16LE(e),this.modTransOper=Ke.readUInt16LE(e)}}Jt.SizeInFile=10;class Qt{constructor(e){this.genOper=Ke.readUInt16LE(e),this.genAmount=new ss(e)}}Qt.SizeInFile=4;class jt{constructor(e){this.instName=Ke.read8BitStringLength(e,20),this.instBagNdx=Ke.readUInt16LE(e)}}jt.SizeInFile=22;class Kt{constructor(e){this.genNdx=Ke.readUInt16LE(e),this.modNdx=Ke.readUInt16LE(e)}}Kt.SizeInFile=4;class $t{constructor(e){this.genOper=Ke.readUInt16LE(e),this.genAmount=new ss(e)}}$t.SizeInFile=4,$t.GenInstrument=41,$t.GenKeyRange=43,$t.GenVelRange=44,$t.GenSampleId=53;class Zt{constructor(e){this.presetName=Ke.read8BitStringLength(e,20),this.preset=Ke.readUInt16LE(e),this.bank=Ke.readUInt16LE(e),this.presetBagNdx=Ke.readUInt16LE(e),this.library=Ke.readUInt32LE(e),this.genre=Ke.readUInt32LE(e),this.morphology=Ke.readUInt32LE(e)}}Zt.SizeInFile=38;class es{constructor(e){this.modSrcOper=Ke.readUInt16LE(e),this.modDestOper=Ke.readUInt16LE(e),this.modAmount=Ke.readUInt16LE(e),this.modAmtSrcOper=Ke.readUInt16LE(e),this.modTransOper=Ke.readUInt16LE(e)}}es.SizeInFile=10;class ts{constructor(e){this.sampleName=Ke.read8BitStringLength(e,20),this.start=Ke.readUInt32LE(e),this.end=Ke.readUInt32LE(e),this.startLoop=Ke.readUInt32LE(e),this.endLoop=Ke.readUInt32LE(e),this.sampleRate=Ke.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=Ke.readSInt8(e),this.sampleLink=Ke.readUInt16LE(e),this.sampleType=Ke.readUInt16LE(e)}}ts.SizeInFile=46;class ss{constructor(e){this.wordAmount=Ke.readUInt16LE(e)}get shortAmount(){return je.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}}class is{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 as{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"}(J||(J={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(Q||(Q={}));class rs{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null,this.fontSamples=null}}class ns{static timecents2Secs(e){return Math.pow(2,e/1200)}static decibelsToGain(e){return e>-100?Math.pow(10,.05*e):0}static gainToDecibels(e){return e<=1e-5?-100:20*Math.log10(e)}static cents2Hertz(e){return 8.176*Math.pow(2,e/1200)}static clamp(e,t,s){return e<=t?t:e>=s?s:e}}class os{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:ns.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:ns.timecents2Secs(this.attack),this.release=this.release<-11950?0:ns.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:ns.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:ns.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?ns.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"}(j||(j={}));class hs{constructor(e){this.loopMode=J.None,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv=new os,this.modEnv=new os,this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,e&&(this.loopMode=e.loopMode,this.sampleRate=e.sampleRate,this.loKey=e.loKey,this.hiKey=e.hiKey,this.loVel=e.loVel,this.hiVel=e.hiVel,this.group=e.group,this.offset=e.offset,this.end=e.end,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this.transpose=e.transpose,this.tune=e.tune,this.pitchKeyCenter=e.pitchKeyCenter,this.pitchKeyTrack=e.pitchKeyTrack,this.attenuation=e.attenuation,this.pan=e.pan,this.ampEnv=new os(e.ampEnv),this.modEnv=new os(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=J.None,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv.clear(),this.modEnv.clear(),this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,this.hiKey=127,this.hiVel=127,this.pitchKeyCenter=60,e||(this.pitchKeyTrack=100,this.pitchKeyCenter=-1,this.ampEnv.delay=-12e3,this.ampEnv.attack=-12e3,this.ampEnv.hold=-12e3,this.ampEnv.decay=-12e3,this.ampEnv.release=-12e3,this.modEnv.delay=-12e3,this.modEnv.attack=-12e3,this.modEnv.hold=-12e3,this.modEnv.decay=-12e3,this.modEnv.release=-12e3,this.initialFilterFc=13500,this.delayModLFO=-12e3,this.delayVibLFO=-12e3)}operator(e,t){switch(e){case j.StartAddrsOffset:this.offset+=je.int16ToUint32(t.shortAmount);break;case j.EndAddrsOffset:this.end+=je.int16ToUint32(t.shortAmount);break;case j.StartloopAddrsOffset:this.loopStart+=je.int16ToUint32(t.shortAmount);break;case j.EndloopAddrsOffset:this.loopEnd+=je.int16ToUint32(t.shortAmount);break;case j.StartAddrsCoarseOffset:this.offset+=32768*je.int16ToUint32(t.shortAmount);break;case j.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case j.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case j.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case j.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case j.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case j.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case j.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case j.EndAddrsCoarseOffset:this.end+=32768*je.int16ToUint32(t.shortAmount);break;case j.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case j.Pan:this.pan=t.shortAmount/1e3;break;case j.DelayModLFO:this.delayModLFO=t.shortAmount;break;case j.FreqModLFO:this.freqModLFO=t.shortAmount;break;case j.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case j.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case j.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case j.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case j.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case j.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case j.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case j.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case j.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case j.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case j.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case j.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case j.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case j.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case j.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case j.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case j.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case j.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case j.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case j.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case j.StartloopAddrsCoarseOffset:this.loopStart+=32768*je.int16ToUint32(t.shortAmount);break;case j.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case j.EndloopAddrsCoarseOffset:this.loopEnd+=32768*je.int16ToUint32(t.shortAmount);break;case j.CoarseTune:this.transpose+=t.shortAmount;break;case j.FineTune:this.tune+=t.shortAmount;break;case j.SampleModes:this.loopMode=3==(3&t.wordAmount)?J.Sustain:1==(3&t.wordAmount)?J.Continuous:J.None;break;case j.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case j.ExclusiveClass:this.group=t.wordAmount;break;case j.OverridingRootKey:this.pitchKeyCenter=t.shortAmount}}}!function(e){e[e.None=0]="None",e[e.Delay=1]="Delay",e[e.Attack=2]="Attack",e[e.Hold=3]="Hold",e[e.Decay=4]="Decay",e[e.Sustain=5]="Sustain",e[e.Release=6]="Release",e[e.Done=7]="Done"}(K||(K={}));class ls{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=K.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case K.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=K.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=K.Delay;break;case K.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=K.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=K.Attack;break;case K.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=K.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=K.Hold;break;case K.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=K.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=K.Decay;break;case K.Decay:return this.segment=K.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case K.Sustain:if(this.segment=K.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?ls.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=K.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,s,i,a){this.parameters=new os(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:ns.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:ns.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|s,this.isAmpEnv=i,this.nextSegment(K.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)}}ls.FastReleaseTime=.01;class cs{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,s){this.samplesUntil=e*s|0,this.delta=4*ns.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 ds{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 us{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 ls,this.modEnv=new ls,this.lowPass=new ds,this.modLfo=new cs,this.vibLfo=new cs,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/(ns.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(K.Sustain,e),this.modEnv.nextSegment(K.Sustain,e),this.region.loopMode===J.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(K.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(K.Sustain,e)}render(e,t,s,i,a){if(!this.region)return;let r=this.region;let n=e.presets[this.playingPreset].fontSamples,o=0,h=e.outputMode===Q.StereoUnweaved?i:-1,l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,c=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),d=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,f=r.end,m=g+1,y=this.sourceSamplePosition,b=new ds(this.lowPass),S=0!==r.modLfoToFilterFc||0!==r.modEnvToFilterFc,w=0,_=0,B=0,T=0,k=0!==r.modLfoToPitch||0!==r.modEnvToPitch||0!==r.vibLfoToPitch,v=0,x=0,N=0,P=0,E=0!==r.modLfoToVolume,C=0,F=0;for(S?(w=e.outSampleRate,_=r.initialFilterFc,B=r.modLfoToFilterFc,T=r.modEnvToFilterFc):(w=0,_=0,B=0,T=0),k?(v=0,x=r.modLfoToPitch,N=r.vibLfoToPitch,P=r.modEnvToPitch):(v=ns.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,x=0,N=0,P=0),E?F=.1*r.modLfoToVolume:(C=ns.decibelsToGain(this.noteGainDb),F=0);i>0;){let r,L,M=0,I=i>us.RenderEffectSampleBlock?us.RenderEffectSampleBlock:i;if(i-=I,S){let e=_+this.modLfo.level*B+this.modEnv.level*T;b.active=e<=13500,b.active&&b.setup(ns.cents2Hertz(e)/w)}switch(k&&(v=ns.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*x+this.vibLfo.level*N+this.modEnv.level*P))*this.pitchOutputFactor),E&&(C=ns.decibelsToGain(this.noteGainDb+this.modLfo.level*F)),r=C*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(I,e.outSampleRate),l&&this.modEnv.process(I,e.outSampleRate),c&&this.modLfo.process(I),d&&this.vibLfo.process(I),e.outputMode){case Q.StereoInterleaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;I-- >0&&y<f;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*L,o++,t[s+o]+=r*M,o++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case Q.StereoUnweaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;I-- >0&&y<f;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*L,o++,t[s+h]+=r*M,h++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case Q.Mono:for(;I-- >0&&y<f;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,h=n[e]*(1-a)+n[i]*a;b.active&&(h=b.process(h)),t[s+o]=h*r,o++,y+=v,y>=m&&u&&(y-=g-p+1)}}if(y>=f||this.ampEnv.segment===K.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}us.RenderEffectSampleBlock=Gt.MicroBufferSize;class ps{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}}class gs{constructor(e){this._midiEventQueue=new ps,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=Q.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._isAnySolo=!1}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(Gt.MetronomeChannel,33),this.channelNoteOn(Gt.MetronomeChannel,33,95/127)):e.event&&this.processMidiMessage(e.event),a.push(e)}for(const a of this._voices)if(-1!==a.playingPreset){const r=a.playingChannel,n=this._mutedChannels.has(r)||i&&r!=Gt.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,s,n):a.kill()}return a}processMidiMessage(e){const t=e.command,s=e.channel,i=e.data1,a=e.data2;switch(t){case z.NoteOff:this.channelNoteOff(s,i);break;case z.NoteOn:this.channelNoteOn(s,i,a/127);break;case z.NoteAftertouch:break;case z.Controller:this.channelMidiControl(s,i,a);break;case z.ProgramChange:this.channelSetPresetNumber(s,i,9===s);break;case z.ChannelAftertouch:break;case z.PitchBend:this.channelSetPitchWheel(s,i|a<<7);break;case z.PerNotePitchBend:const t=e;let r=t.pitch;r=r*Gt.MaxPitchWheel/Gt.MaxPitchWheel20,this.channelSetPerNotePitchWheel(s,t.noteKey,r);break;case z.Meta:switch(e.data1){case U.Tempo:this.currentTempo=6e7/e.value;break;case U.TimeSignature:this.timeSignatureNumerator=e.data[0],this.timeSignatureDenominator=Math.pow(2,e.data[1])}}}get metronomeVolume(){return this.channelGetMixVolume(Gt.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Gt.MetronomeChannel,e),e>0&&(this.channelSetVolume(Gt.MetronomeChannel,1),this.channelSetPresetNumber(Gt.MetronomeChannel,0,!0))}get masterVolume(){return ns.decibelsToGain(this.globalGainDb)}set masterVolume(e){var t=ns.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<K.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(){var e,t;return null!==(t=null===(e=this.presets)||void 0===e?void 0:e.length)&&void 0!==t?t:0}reset(){for(let e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<K.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 us;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-ns.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!==J.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(ns.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>=K.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>=K.Release)||r.end(this.outSampleRate)}bankNoteOff(e,t,s){const i=this.getPresetIndex(e,t);return-1!==i&&(this.noteOff(i,s),!0)}noteOffAll(e){for(const t of this._voices)-1!==t.playingPreset&&t.ampEnv.segment<K.Release&&(e?t.endQuick(this.outSampleRate):t.end(this.outSampleRate))}get activeVoiceCount(){let e=0;for(const t of this._voices)-1!==t.playingPreset&&e++;return e}channelInit(e){if(this._channels&&e<this._channels.channelList.length)return this._channels.channelList[e];this._channels||(this._channels=new as);for(let t=this._channels.channelList.length;t<=e;t++){let e=new is;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._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,s))}channelNoteOff(e,t){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>=K.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>=K.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<K.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<K.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=je.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=je.int32ToUint16(t)}channelSetBankPreset(e,t,s){const i=this.channelInit(e),a=this.getPresetIndex(t,s);return-1!==a&&(i.presetIndex=je.int32ToUint16(a),i.bank=je.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=ns.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=je.int32ToUint16(t),this.channelApplyPitch(e,s))}channelSetPerNotePitchWheel(e,t,s){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 5:case 96:case 97:case 64:case 65:case 66:case 122:case 124:case 125:case 126:case 127:return;case 38:return i.midiData=je.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 7:return i.midiVolume=je.int32ToUint16(127&i.midiVolume|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case 39:return i.midiVolume=je.int32ToUint16(16256&i.midiVolume|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case 11:return i.midiExpression=je.int32ToUint16(127&i.midiExpression|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case 43:return i.midiExpression=je.int32ToUint16(16256&i.midiExpression|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case 10:return i.midiPan=je.int32ToUint16(127&i.midiPan|s<<7),void this.channelSetPan(e,i.midiPan/16383);case 42:return i.midiPan=je.int32ToUint16(16256&i.midiPan|s),void this.channelSetPan(e,i.midiPan/16383);case 6:return i.midiData=je.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&&6===t&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case 0:return void(i.bank=je.int32ToUint16(32768|s));case 32:return void(i.bank=je.int32ToUint16((0!=(32768&i.bank)?(127&i.bank)<<7:0)|s));case 101:return void(i.midiRpn=je.int32ToUint16(127&(65535===i.midiRpn?0:i.midiRpn)|s<<7));case 100:return void(i.midiRpn=je.int32ToUint16(16256&(65535===i.midiRpn?0:i.midiRpn)|s));case 98:case 99:return void(i.midiRpn=65535);case 120:return void this.channelSoundsOffAll(e);case 123:return void this.channelNoteOffAll(e);case 121: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?ns.decibelsToGain(this._channels.channelList[e].gainDb):1}channelGetPitchWheel(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchWheel:8192}channelGetPitchRange(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchRange:2}channelGetTuning(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].tuning:0}resetPresets(){this.presets=[]}loadPresets(e,t){const s=[];for(let t=0;t<e.phdrs.length-1;t++){const i=e.phdrs[t];let a=0;const r=new rs;s.push(r),r.name=i.presetName,r.bank=i.bank,r.presetNumber=i.preset,r.fontSamples=e.fontSamples;let n=0;for(let s=i.presetBagNdx;s<e.phdrs[t+1].presetBagNdx;s++){let t=0,i=127,a=0,r=127;for(let o=e.pbags[s].genNdx;o<e.pbags[s+1].genNdx;o++){let s=e.pgens[o];if(s.genOper!==$t.GenKeyRange)if(s.genOper!==$t.GenVelRange){if(s.genOper===$t.GenInstrument&&!(s.genAmount.wordAmount>=e.insts.length))for(let o=e.insts[s.genAmount.wordAmount].instBagNdx;o<e.insts[s.genAmount.wordAmount+1].instBagNdx;o++){let s=0,h=127,l=0,c=127;for(let d=e.ibags[o].instGenNdx;d<e.ibags[o+1].instGenNdx;d++){let o=e.igens[d];o.genOper!==$t.GenKeyRange?o.genOper!==$t.GenVelRange?53===o.genOper&&h>=t&&s<=i&&c>=a&&l<=r&&n++:(l=o.genAmount.lowByteAmount,c=o.genAmount.highByteAmount):(s=o.genAmount.lowByteAmount,h=o.genAmount.highByteAmount)}}}else a=s.genAmount.lowByteAmount,r=s.genAmount.highByteAmount;else t=s.genAmount.lowByteAmount,i=s.genAmount.highByteAmount}}r.regions=new Array(n);let o=new hs;o.clear(!0);for(let s=i.presetBagNdx;s<e.phdrs[t+1].presetBagNdx;s++){const t=e.pbags[s],n=new hs(o);let h=!1;for(let i=t.genNdx;i<e.pbags[s+1].genNdx;i++){const t=e.pgens[i];if(t.genOper===$t.GenInstrument){let s=t.genAmount.wordAmount;if(s>=e.insts.length)continue;let i=new hs;i.clear(!1);let o=e.insts[s];for(let t=o.instBagNdx;t<e.insts[s+1].instBagNdx;t++){let s=e.ibags[t],h=new hs(i),l=!1;for(let i=s.instGenNdx;i<e.ibags[t+1].instGenNdx;i++){let t=e.igens[i];if(t.genOper===$t.GenSampleId){if(h.hiKey<n.loKey||h.loKey>n.hiKey)continue;if(h.hiVel<n.loVel||h.loVel>n.hiVel)continue;n.loKey>h.loKey&&(h.loKey=n.loKey),n.hiKey<h.hiKey&&(h.hiKey=n.hiKey),n.loVel>h.loVel&&(h.loVel=n.loVel),n.hiVel<h.hiVel&&(h.hiVel=n.hiVel),h.offset+=n.offset,h.end+=n.end,h.loopStart+=n.loopStart,h.loopEnd+=n.loopEnd,h.transpose+=n.transpose,h.tune+=n.tune,h.pitchKeyTrack+=n.pitchKeyTrack,h.attenuation+=n.attenuation,h.pan+=n.pan,h.ampEnv.delay+=n.ampEnv.delay,h.ampEnv.attack+=n.ampEnv.attack,h.ampEnv.hold+=n.ampEnv.hold,h.ampEnv.decay+=n.ampEnv.decay,h.ampEnv.sustain+=n.ampEnv.sustain,h.ampEnv.release+=n.ampEnv.release,h.modEnv.delay+=n.modEnv.delay,h.modEnv.attack+=n.modEnv.attack,h.modEnv.hold+=n.modEnv.hold,h.modEnv.decay+=n.modEnv.decay,h.modEnv.sustain+=n.modEnv.sustain,h.modEnv.release+=n.modEnv.release,h.initialFilterQ+=n.initialFilterQ,h.initialFilterFc+=n.initialFilterFc,h.modEnvToPitch+=n.modEnvToPitch,h.modEnvToFilterFc+=n.modEnvToFilterFc,h.delayModLFO+=n.delayModLFO,h.freqModLFO+=n.freqModLFO,h.modLfoToPitch+=n.modLfoToPitch,h.modLfoToFilterFc+=n.modLfoToFilterFc,h.modLfoToVolume+=n.modLfoToVolume,h.delayVibLFO+=n.delayVibLFO,h.freqVibLFO+=n.freqVibLFO,h.vibLfoToPitch+=n.vibLfoToPitch,h.ampEnv.envToSecs(!0),h.modEnv.envToSecs(!1),h.delayModLFO=h.delayModLFO<-11950?0:ns.timecents2Secs(h.delayModLFO),h.delayVibLFO=h.delayVibLFO<-11950?0:ns.timecents2Secs(h.delayVibLFO),h.pan<-.5?h.pan=-.5:h.pan>.5&&(h.pan=.5),(h.initialFilterQ<1500||h.initialFilterQ>13500)&&(h.initialFilterQ=0);let s=e.sHdrs[t.genAmount.wordAmount];h.offset+=s.start,h.end+=s.end,h.loopStart+=s.startLoop,h.loopEnd+=s.endLoop,s.endLoop>0&&(h.loopEnd-=1),-1===h.pitchKeyCenter&&(h.pitchKeyCenter=s.originalPitch),h.tune+=s.pitchCorrection,h.sampleRate=s.sampleRate,0!==h.end&&h.end<r.fontSamples.length?h.end++:h.end=r.fontSamples.length,r.regions[a]=new hs(h),a++,l=!0}else h.operator(t.genOper,t.genAmount)}s!==e.ibags[o.instBagNdx]||l||(i=new hs(h))}h=!0}else n.operator(t.genOper,t.genAmount)}t!==e.pbags[i.presetBagNdx]||h||(o=n)}}if(t&&this.presets)for(const e of s)this.presets.push(e);else this.presets=s}}class fs{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 ms{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 ys{constructor(e){this.events=e}}class bs{constructor(e){this._isSoundFontLoaded=!1,this._isMidiLoaded=!1,this._tickPosition=0,this._timePosition=0,this._metronomeVolume=0,this._countInVolume=0,this._playedEventsQueue=new ps,this._midiEventsPlayedFilter=new Set,this.isReady=!1,this.state=q.Paused,this.ready=new fs,this.readyForPlayback=new fs,this.finished=new fs,this.soundFontLoaded=new fs,this.soundFontLoadFailed=new ms,this.midiLoaded=new ms,this.midiLoadFailed=new ms,this.stateChanged=new ms,this.positionChanged=new ms,this.midiEventsPlayed=new ms,Be.debug("AlphaSynth","Initializing player"),this.state=q.Paused,Be.debug("AlphaSynth","Creating output"),this.output=e,Be.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new gs(this.output.sampleRate),this._sequencer=new Wt(this._synthesizer),Be.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{let e=new Float32Array(Gt.MicroBufferSize*Gt.MicroBufferCount*Gt.AudioChannels),t=0;for(let s=0;s<Gt.MicroBufferCount;s++){this._sequencer.fillMidiEventQueue();const s=this._synthesizer.synthesize(e,t,Gt.MicroBufferSize);t+=Gt.MicroBufferSize*Gt.AudioChannels;for(const e of s)this._midiEventsPlayedFilter.has(e.event.command)&&this._playedEventsQueue.enqueue(e);if(this._sequencer.isFinished)break}t<e.length&&(e=e.subarray(0,t)),this.output.addSamples(e)})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open()}get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return Be.logLevel}set logLevel(e){Be.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Gt.MinVolume),this._synthesizer.masterVolume=e,this.onAudioSettingsUpdate()}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Gt.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e,this.onAudioSettingsUpdate()}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Gt.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=ns.clamp(e,Gt.MinPlaybackSpeed,Gt.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.tickPositionToTimePosition(e)}get timePosition(){return this._timePosition}set timePosition(e){Be.debug("AlphaSynth",`Seeking to position ${e}ms`),this._sequencer.seek(e),this.updateTimePosition(e,!0),this.output.resetSamples()}get playbackRange(){return this._sequencer.playbackRange}set playbackRange(e){this._sequencer.playbackRange=e,e&&(this.tickPosition=e.startTick)}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){Be.debug("AlphaSynth","Destroying player"),this.stop(),this.output.destroy()}play(){return!(this.state!==q.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(Be.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.tickPosition=0),this.output.play(),!0)}playInternal(){Be.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.state=q.Playing,this.stateChanged.trigger(new zt(this.state,!1))}pause(){this.state!==q.Paused&&this._isMidiLoaded&&(Be.debug("AlphaSynth","Pausing playback"),this.state=q.Paused,this.stateChanged.trigger(new zt(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===q.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(Be.debug("AlphaSynth","Stopping playback"),this.state=q.Paused,this.output.pause(),this._sequencer.stop(),this._synthesizer.noteOffAll(!0),this.tickPosition=this._sequencer.playbackRange?this._sequencer.playbackRange.startTick:0,this.stateChanged.trigger(new zt(this.state,!0)))}playOneTimeMidiFile(e){this.pause(),this._sequencer.loadOneTimeMidi(e),this._sequencer.stop(),this._synthesizer.noteOffAll(!0),this.tickPosition=0,this.output.play()}resetSoundFonts(){this.stop(),this._synthesizer.resetPresets(),this._isSoundFontLoaded=!1,this.soundFontLoaded.trigger()}loadSoundFont(e,t){this.pause();let s=$e.fromBuffer(e);try{Be.debug("AlphaSynth","Loading soundfont from bytes");let e=new Yt;e.load(s),this._synthesizer.loadPresets(e,t),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),Be.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){Be.error("AlphaSynth","Could not load soundfont from bytes "+e),this.soundFontLoadFailed.trigger(e)}}checkReadyForPlayback(){this.isReadyForPlayback&&(this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.readyForPlayback.trigger())}loadMidiFile(e){this.stop();try{Be.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new Ut(0,this._sequencer.endTime,0,this._sequencer.endTick,!1)),Be.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){Be.error("AlphaSynth","Could not load midi from model "+e),this.midiLoadFailed.trigger(e)}}setChannelMute(e,t){this._synthesizer.channelSetMute(e,t),this.onAudioSettingsUpdate()}resetChannelStates(){this._synthesizer.resetChannelStates()}setChannelSolo(e,t){this._synthesizer.channelSetSolo(e,t),this.onAudioSettingsUpdate()}setChannelVolume(e,t){t=Math.max(t,Gt.MinVolume),this._synthesizer.channelSetMixVolume(e,t),this.onAudioSettingsUpdate()}onAudioSettingsUpdate(){this.timePosition=this.timePosition}onSamplesPlayed(e){let t=e/this._synthesizer.outSampleRate*1e3;this.updateTimePosition(this._timePosition+t,!1),this.checkForFinish()}checkForFinish(){let e=0,t=0;this.playbackRange?(e=this.playbackRange.startTick,t=this.playbackRange.endTick):t=this._sequencer.endTick,this._tickPosition>=t&&(Be.debug("AlphaSynth","Finished playback"),this._sequencer.isPlayingCountIn?(this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal()):this._sequencer.isPlayingOneTimeMidi?(this._sequencer.resetOneTimeMidi(),this.state=q.Paused,this.output.pause(),this._synthesizer.noteOffAll(!1)):(this.finished.trigger(),this.isLooping?this.tickPosition=e:this.stop()))}updateTimePosition(e,t){const s=e;this._timePosition=s;const i=this._sequencer.timePositionToTickPosition(s);this._tickPosition=i;const a=this._sequencer.endTime,r=this._sequencer.endTick;if(this._sequencer.isPlayingOneTimeMidi||this._sequencer.isPlayingCountIn||(Be.debug("AlphaSynth",`Position changed: (time: ${s}/${a}, tick: ${i}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount}`),this.positionChanged.trigger(new Ut(s,a,i,r,t))),t)this._playedEventsQueue.clear();else{const e=new ps;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<s;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new ys(e.toArray()))}}}class Ss{constructor(){this.division=ye.QuarterTime,this.events=[]}addEvent(e){if(0===this.events.length)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)}}toBinary(){let e=$e.empty();return this.writeTo(e),e.toArray()}writeTo(e){let t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),t=new Uint8Array([0,0,0,6]),e.write(t,0,t.length),t=new Uint8Array([0,0]),e.write(t,0,t.length);let s=1;t=new Uint8Array([s>>8&255,255&s]),e.write(t,0,t.length),s=this.division,t=new Uint8Array([s>>8&255,255&s]),e.write(t,0,t.length);let i=$e.empty(),a=0;for(let e of this.events){let t=e.tick-a;Ss.writeVariableInt(i,t),e.writeTo(i),a=e.tick}t=new Uint8Array([77,84,114,107]),e.write(t,0,t.length);let r=i.toArray(),n=r.length;t=new Uint8Array([n>>24&255,n>>16&255,n>>8&255,255&n]),e.write(t,0,t.length),e.write(r,0,r.length)}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])}}class ws extends Dt{constructor(e,t,s,i,a){super(e,t,s,i,0),this.data=a}writeTo(e){e.writeByte(255),e.writeByte(this.metaStatus);let t=this.data.length;Ss.writeVariableInt(e,t),e.write(this.data,0,this.data.length)}}class _s extends Dt{constructor(e,t,s,i,a){super(e,t,s,i,0),this.value=a}writeTo(e){e.writeByte(255),e.writeByte(this.metaStatus),Ss.writeVariableInt(e,3);let t=new Uint8Array([this.value>>16&255,this.value>>8&255,255&this.value]);e.write(t,0,t.length)}}class Bs{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 pe(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)}}class Ts{constructor(e,t,s){this.text=e,this.startPos=t,this.endPos=s}}class ks{constructor(e){this.style="normal",this.variant="normal",this.weight="normal",this.stretch="normal",this.lineHeight="normal",this.size="1rem",this.families=[],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 Ts(e.substring(s,i),s,i)),s=i+1}return t}parse(){var e;if(this.reset(),1===this._tokens.length)switch(null===(e=this._currentToken)||void 0===e?void 0:e.text){case"caption":case"icon":case"menu":case"message-box":case"small-caption":case"status-bar":case"inherit":return}this.fontStyleVariantWeight(),this.fontSizeLineHeight(),this.fontFamily()}fontFamily(){if(!this._currentToken)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()}}!function(e){e[e.Plain=0]="Plain",e[e.Italic=1]="Italic"}($||($={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(Z||(Z={}));class vs{constructor(e,t,s=$.Plain,i=Z.Regular){this._cssScale=0,this._family=e,this._size=t,this._style=s,this._weight=i,this._css=this.toCssString()}reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._family}set family(e){this._family=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===Z.Bold}get isItalic(){return this.style===$.Italic}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+="'",t+=this.family,t+="'",this._css=t,this._cssScale=e}return this._css}static fromJson(e){switch(typeof e){case"undefined":return null;case"object":{const t=e;let s=t.get("family"),i=t.get("size"),a=Bs.parseEnum(t.get("style"),$),r=Bs.parseEnum(t.get("weight"),Z);return new vs(s,i,a,r)}case"string":{const t=new ks(e);t.parse();let s=t.families[0];(s.startsWith("'")&&s.endsWith("'")||s.startsWith('"')&&s.endsWith('"'))&&(s=s.substr(1,s.length-2));let 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=$.Plain;"italic"===t.style&&(r=$.Italic);let n=Z.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=Z.Bold}return new vs(s,a,r,n)}default:return null}}static toJson(e){const t=new Map;return t.set("family",e.family),t.set("size",e.size),t.set("style",e.style),t.set("weight",e.weight),t}}class xs{constructor(){this.copyrightFont=new vs(xs.sansFont,12,$.Plain,Z.Bold),this.titleFont=new vs(xs.serifFont,32,$.Plain),this.subTitleFont=new vs(xs.serifFont,20,$.Plain),this.wordsFont=new vs(xs.serifFont,15,$.Plain),this.effectFont=new vs(xs.serifFont,12,$.Italic),this.fretboardNumberFont=new vs(xs.sansFont,11,$.Plain),this.tablatureFont=new vs(xs.sansFont,13,$.Plain),this.graceFont=new vs(xs.sansFont,11,$.Plain),this.staffLineColor=new Ue(165,165,165,255),this.barSeparatorColor=new Ue(34,34,17,255),this.barNumberFont=new vs(xs.sansFont,11,$.Plain),this.barNumberColor=new Ue(200,0,0,255),this.fingeringFont=new vs(xs.serifFont,14,$.Plain),this.markerFont=new vs(xs.serifFont,14,$.Plain,Z.Bold),this.mainGlyphColor=new Ue(0,0,0,255),this.secondaryGlyphColor=new Ue(0,0,0,100),this.scoreInfoColor=new Ue(0,0,0,255)}}xs.sansFont="Arial",xs.serifFont="Georgia";class Ns{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.resources=new xs,this.padding=null}}class Ps{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"}(ee||(ee={}));class Es{constructor(){this.noteWideLength=480,this.noteWideAmplitude=2,this.noteSlightLength=480,this.noteSlightAmplitude=2,this.beatWideLength=240,this.beatWideAmplitude=3,this.beatSlightLength=240,this.beatSlightAmplitude=3}}class Cs{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}class Fs{constructor(){this.soundFont=null,this.scrollElement="html,body",this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=ee.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new Es,this.slide=new Cs,this.playTripletFeel=!0}}class Ls{static fromJson(e,t){t&&Bs.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=Bs.parseEnum(s,v),!0;case"useworkers":return e.useWorkers=s,!0;case"includenotebounds":return e.includeNoteBounds=s,!0}return!1}}class Ms{static fromJson(e,t){t&&Bs.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",vs.toJson(e.copyrightFont)),t.set("titlefont",vs.toJson(e.titleFont)),t.set("subtitlefont",vs.toJson(e.subTitleFont)),t.set("wordsfont",vs.toJson(e.wordsFont)),t.set("effectfont",vs.toJson(e.effectFont)),t.set("fretboardnumberfont",vs.toJson(e.fretboardNumberFont)),t.set("tablaturefont",vs.toJson(e.tablatureFont)),t.set("gracefont",vs.toJson(e.graceFont)),t.set("stafflinecolor",Ue.toJson(e.staffLineColor)),t.set("barseparatorcolor",Ue.toJson(e.barSeparatorColor)),t.set("barnumberfont",vs.toJson(e.barNumberFont)),t.set("barnumbercolor",Ue.toJson(e.barNumberColor)),t.set("fingeringfont",vs.toJson(e.fingeringFont)),t.set("markerfont",vs.toJson(e.markerFont)),t.set("mainglyphcolor",Ue.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",Ue.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",Ue.toJson(e.scoreInfoColor)),t}static setProperty(e,t,s){switch(t){case"copyrightfont":return e.copyrightFont=vs.fromJson(s),!0;case"titlefont":return e.titleFont=vs.fromJson(s),!0;case"subtitlefont":return e.subTitleFont=vs.fromJson(s),!0;case"wordsfont":return e.wordsFont=vs.fromJson(s),!0;case"effectfont":return e.effectFont=vs.fromJson(s),!0;case"fretboardnumberfont":return e.fretboardNumberFont=vs.fromJson(s),!0;case"tablaturefont":return e.tablatureFont=vs.fromJson(s),!0;case"gracefont":return e.graceFont=vs.fromJson(s),!0;case"stafflinecolor":return e.staffLineColor=Ue.fromJson(s),!0;case"barseparatorcolor":return e.barSeparatorColor=Ue.fromJson(s),!0;case"barnumberfont":return e.barNumberFont=vs.fromJson(s),!0;case"barnumbercolor":return e.barNumberColor=Ue.fromJson(s),!0;case"fingeringfont":return e.fingeringFont=vs.fromJson(s),!0;case"markerfont":return e.markerFont=vs.fromJson(s),!0;case"mainglyphcolor":return e.mainGlyphColor=Ue.fromJson(s),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=Ue.fromJson(s),!0;case"scoreinfocolor":return e.scoreInfoColor=Ue.fromJson(s),!0}return!1}}class Is{static fromJson(e,t){t&&Bs.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("resources",Ms.toJson(e.resources)),t.set("padding",e.padding),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=Bs.parseEnum(a,e),!0;case"staveprofile":return s.staveProfile=Bs.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"padding":return s.padding=a,!0}if(["resources"].indexOf(i)>=0)return Ms.fromJson(s.resources,a),!0;for(const e of["resources"])if(0===i.indexOf(e)&&Ms.setProperty(s.resources,i.substring(e.length),a))return!0;return!1}}class Ds{static fromJson(e,t){t&&Bs.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=Bs.parseEnum(s,T),!0;case"fingeringmode":return e.fingeringMode=Bs.parseEnum(s,B),!0;case"elements":return e.elements=new Map,Bs.forEach(s,((t,s)=>{e.elements.set(Bs.parseEnum(s,k),t)})),!0;case"rhythmmode":return e.rhythmMode=Bs.parseEnum(s,_),!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 Rs{static fromJson(e,t){t&&Bs.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 As{static fromJson(e,t){t&&Bs.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 Os{static fromJson(e,t){t&&Bs.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 Gs{static fromJson(e,t){t&&Bs.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("scrollelement",e.scrollElement),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",As.toJson(e.vibrato)),t.set("slide",Os.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t}static setProperty(e,t,s){switch(t){case"soundfont":return e.soundFont=s,!0;case"scrollelement":return e.scrollElement=s,!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=Bs.parseEnum(s,ee),!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}if(["vibrato"].indexOf(t)>=0)return As.fromJson(e.vibrato,s),!0;for(const i of["vibrato"])if(0===t.indexOf(i)&&As.setProperty(e.vibrato,t.substring(i.length),s))return!0;if(["slide"].indexOf(t)>=0)return Os.fromJson(e.slide,s),!0;for(const i of["slide"])if(0===t.indexOf(i)&&Os.setProperty(e.slide,t.substring(i.length),s))return!0;return!1}}class Vs{static fromJson(e,t){t&&Bs.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",Ls.toJson(e.core)),t.set("display",Is.toJson(e.display)),t.set("notation",Ds.toJson(e.notation)),t.set("importer",Rs.toJson(e.importer)),t.set("player",Gs.toJson(e.player)),t}static setProperty(e,t,s){if(["core",""].indexOf(t)>=0)return Ls.fromJson(e.core,s),!0;for(const i of["core",""])if(0===t.indexOf(i)&&Ls.setProperty(e.core,t.substring(i.length),s))return!0;if(["display",""].indexOf(t)>=0)return Is.fromJson(e.display,s),!0;for(const i of["display",""])if(0===t.indexOf(i)&&Is.setProperty(e.display,t.substring(i.length),s))return!0;if(["notation"].indexOf(t)>=0)return Ds.fromJson(e.notation,s),!0;for(const i of["notation"])if(0===t.indexOf(i)&&Ds.setProperty(e.notation,t.substring(i.length),s))return!0;if(["importer"].indexOf(t)>=0)return Rs.fromJson(e.importer,s),!0;for(const i of["importer"])if(0===t.indexOf(i)&&Rs.setProperty(e.importer,t.substring(i.length),s))return!0;if(["player"].indexOf(t)>=0)return Gs.fromJson(e.player,s),!0;for(const i of["player"])if(0===t.indexOf(i)&&Gs.setProperty(e.player,t.substring(i.length),s))return!0;return!1}}class Hs{constructor(){this.core=new lo,this.display=new Ns,this.notation=new Se,this.importer=new Ps,this.player=new Fs}setSongBookModeSettings(){this.notation.notationMode=T.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=B.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(k.ParenthesisOnTiedBends,!1),this.notation.elements.set(k.TabNotesOnTiedBends,!1),this.notation.elements.set(k.ZerosOnDiveWhammys,!0)}static get songBook(){let e=new Hs;return e.setSongBookModeSettings(),e}fillFromJson(e){Vs.fromJson(this,e)}}class Ws extends It{constructor(e,t,s,i,a){super(e,t,s,0,0),this.noteKey=i,this.pitch=a}writeTo(e){let t=new Uint8Array([64,255&this.message,255&this.noteKey,0,this.pitch>>24&255,this.pitch>>16&255,this.pitch>>8&255,255&this.pitch]);e.write(t,0,t.length)}}class zs{static fromJson(e,t){t&&Bs.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 Us{static fromJson(e,t){t&&Bs.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=Bs.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 Xs{static fromJson(e,t){t&&Bs.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=Bs.parseEnum(s,O),!0;case"length":return e.length=s,!0}return!1}}class Ys{static fromJson(e,t){t&&Bs.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("alternateendings",e.alternateEndings),t.set("keysignature",e.keySignature),t.set("keysignaturetype",e.keySignatureType),t.set("isdoublebar",e.isDoubleBar),t.set("isrepeatstart",e.isRepeatStart),t.set("repeatcount",e.repeatCount),t.set("timesignaturenumerator",e.timeSignatureNumerator),t.set("timesignaturedenominator",e.timeSignatureDenominator),t.set("timesignaturecommon",e.timeSignatureCommon),t.set("tripletfeel",e.tripletFeel),t.set("section",zs.toJson(e.section)),t.set("tempoautomation",Us.toJson(e.tempoAutomation)),null!==e.fermata){const s=new Map;t.set("fermata",s);for(const[t,i]of e.fermata)s.set(t.toString(),Xs.toJson(i))}return t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t}static setProperty(e,t,s){switch(t){case"alternateendings":return e.alternateEndings=s,!0;case"keysignature":return e.keySignature=Bs.parseEnum(s,M),!0;case"keysignaturetype":return e.keySignatureType=Bs.parseEnum(s,I),!0;case"isdoublebar":return e.isDoubleBar=s,!0;case"isrepeatstart":return e.isRepeatStart=s,!0;case"repeatcount":return e.repeatCount=s,!0;case"timesignaturenumerator":return e.timeSignatureNumerator=s,!0;case"timesignaturedenominator":return e.timeSignatureDenominator=s,!0;case"timesignaturecommon":return e.timeSignatureCommon=s,!0;case"tripletfeel":return e.tripletFeel=Bs.parseEnum(s,D),!0;case"fermata":return e.fermata=new Map,Bs.forEach(s,((t,s)=>{const i=new nt;Xs.fromJson(i,t),e.addFermata(parseInt(s),i)})),!0;case"start":return e.start=s,!0;case"isanacrusis":return e.isAnacrusis=s,!0}return["section"].indexOf(t)>=0?(s?(e.section=new We,zs.fromJson(e.section,s)):e.section=null,!0):["tempoautomation"].indexOf(t)>=0&&(s?(e.tempoAutomation=new fe,Us.fromJson(e.tempoAutomation,s)):e.tempoAutomation=null,!0)}}class qs{static fromJson(e,t){t&&Bs.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 Js{static fromJson(e,t){t&&Bs.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){var t;if(!e)return null;const s=new Map;return s.set("id",e.id),s.set("accentuated",e.accentuated),s.set("bendtype",e.bendType),s.set("bendstyle",e.bendStyle),s.set("iscontinuedbend",e.isContinuedBend),null!==e.bendPoints&&s.set("bendpoints",null===(t=e.bendPoints)||void 0===t?void 0:t.map((e=>qs.toJson(e)))),s.set("fret",e.fret),s.set("string",e.string),s.set("octave",e.octave),s.set("tone",e.tone),s.set("percussionarticulation",e.percussionArticulation),s.set("isvisible",e.isVisible),s.set("islefthandtapped",e.isLeftHandTapped),s.set("ishammerpullorigin",e.isHammerPullOrigin),s.set("isslurdestination",e.isSlurDestination),s.set("harmonictype",e.harmonicType),s.set("harmonicvalue",e.harmonicValue),s.set("isghost",e.isGhost),s.set("isletring",e.isLetRing),s.set("ispalmmute",e.isPalmMute),s.set("isdead",e.isDead),s.set("isstaccato",e.isStaccato),s.set("slideintype",e.slideInType),s.set("slideouttype",e.slideOutType),s.set("vibrato",e.vibrato),s.set("istiedestination",e.isTieDestination),s.set("lefthandfinger",e.leftHandFinger),s.set("righthandfinger",e.rightHandFinger),s.set("isfingering",e.isFingering),s.set("trillvalue",e.trillValue),s.set("trillspeed",e.trillSpeed),s.set("durationpercent",e.durationPercent),s.set("accidentalmode",e.accidentalMode),s.set("dynamics",e.dynamics),e.toJson(s),s}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"accentuated":return e.accentuated=Bs.parseEnum(s,i),!0;case"bendtype":return e.bendType=Bs.parseEnum(s,l),!0;case"bendstyle":return e.bendStyle=Bs.parseEnum(s,h),!0;case"iscontinuedbend":return e.isContinuedBend=s,!0;case"bendpoints":if(s){e.bendPoints=[];for(const t of s){const s=new be;qs.fromJson(s,t),e.addBendPoint(s)}}return!0;case"fret":return e.fret=s,!0;case"string":return e.string=s,!0;case"octave":return e.octave=s,!0;case"tone":return e.tone=s,!0;case"percussionarticulation":return e.percussionArticulation=s,!0;case"isvisible":return e.isVisible=s,!0;case"islefthandtapped":return e.isLeftHandTapped=s,!0;case"ishammerpullorigin":return e.isHammerPullOrigin=s,!0;case"isslurdestination":return e.isSlurDestination=s,!0;case"harmonictype":return e.harmonicType=Bs.parseEnum(s,m),!0;case"harmonicvalue":return e.harmonicValue=s,!0;case"isghost":return e.isGhost=s,!0;case"isletring":return e.isLetRing=s,!0;case"ispalmmute":return e.isPalmMute=s,!0;case"isdead":return e.isDead=s,!0;case"isstaccato":return e.isStaccato=s,!0;case"slideintype":return e.slideInType=Bs.parseEnum(s,b),!0;case"slideouttype":return e.slideOutType=Bs.parseEnum(s,S),!0;case"vibrato":return e.vibrato=Bs.parseEnum(s,w),!0;case"istiedestination":return e.isTieDestination=s,!0;case"lefthandfinger":return e.leftHandFinger=Bs.parseEnum(s,f),!0;case"righthandfinger":return e.rightHandFinger=Bs.parseEnum(s,f),!0;case"isfingering":return e.isFingering=s,!0;case"trillvalue":return e.trillValue=s,!0;case"trillspeed":return e.trillSpeed=Bs.parseEnum(s,u),!0;case"durationpercent":return e.durationPercent=s,!0;case"accidentalmode":return e.accidentalMode=Bs.parseEnum(s,y),!0;case"dynamics":return e.dynamics=Bs.parseEnum(s,p),!0}return e.setProperty(t,s)}}class Qs{static fromJson(e,t){t&&Bs.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){var t;if(!e)return null;const s=new Map;return s.set("id",e.id),s.set("notes",e.notes.map((e=>Js.toJson(e)))),s.set("isempty",e.isEmpty),s.set("whammystyle",e.whammyStyle),s.set("ottava",e.ottava),s.set("islegatoorigin",e.isLegatoOrigin),s.set("duration",e.duration),s.set("automations",e.automations.map((e=>Us.toJson(e)))),s.set("dots",e.dots),s.set("fadein",e.fadeIn),s.set("lyrics",e.lyrics),s.set("hasrasgueado",e.hasRasgueado),s.set("pop",e.pop),s.set("slap",e.slap),s.set("tap",e.tap),s.set("text",e.text),s.set("brushtype",e.brushType),s.set("brushduration",e.brushDuration),s.set("tupletdenominator",e.tupletDenominator),s.set("tupletnumerator",e.tupletNumerator),s.set("iscontinuedwhammy",e.isContinuedWhammy),s.set("whammybartype",e.whammyBarType),null!==e.whammyBarPoints&&s.set("whammybarpoints",null===(t=e.whammyBarPoints)||void 0===t?void 0:t.map((e=>qs.toJson(e)))),s.set("vibrato",e.vibrato),s.set("chordid",e.chordId),s.set("gracetype",e.graceType),s.set("pickstroke",e.pickStroke),s.set("tremolospeed",e.tremoloSpeed),s.set("crescendo",e.crescendo),s.set("displaystart",e.displayStart),s.set("playbackstart",e.playbackStart),s.set("displayduration",e.displayDuration),s.set("playbackduration",e.playbackDuration),s.set("dynamics",e.dynamics),s.set("invertbeamdirection",e.invertBeamDirection),s.set("preferredbeamdirection",e.preferredBeamDirection),s.set("beamingmode",e.beamingMode),s}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 Pe;Js.fromJson(s,t),e.addNote(s)}return!0;case"isempty":return e.isEmpty=s,!0;case"whammystyle":return e.whammyStyle=Bs.parseEnum(s,h),!0;case"ottava":return e.ottava=Bs.parseEnum(s,n),!0;case"islegatoorigin":return e.isLegatoOrigin=s,!0;case"duration":return e.duration=Bs.parseEnum(s,u),!0;case"automations":e.automations=[];for(const t of s){const s=new fe;Us.fromJson(s,t),e.automations.push(s)}return!0;case"dots":return e.dots=s,!0;case"fadein":return e.fadeIn=s,!0;case"lyrics":return e.lyrics=s,!0;case"hasrasgueado":return e.hasRasgueado=s,!0;case"pop":return e.pop=s,!0;case"slap":return e.slap=s,!0;case"tap":return e.tap=s,!0;case"text":return e.text=s,!0;case"brushtype":return e.brushType=Bs.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=Bs.parseEnum(s,C),!0;case"whammybarpoints":if(s){e.whammyBarPoints=[];for(const t of s){const s=new be;qs.fromJson(s,t),e.addWhammyBarPoint(s)}}return!0;case"vibrato":return e.vibrato=Bs.parseEnum(s,w),!0;case"chordid":return e.chordId=s,!0;case"gracetype":return e.graceType=Bs.parseEnum(s,g),!0;case"pickstroke":return e.pickStroke=Bs.parseEnum(s,x),!0;case"tremolospeed":return e.tremoloSpeed=Bs.parseEnum(s,u),!0;case"crescendo":return e.crescendo=Bs.parseEnum(s,d),!0;case"displaystart":return e.displayStart=s,!0;case"playbackstart":return e.playbackStart=s,!0;case"displayduration":return e.displayDuration=s,!0;case"playbackduration":return e.playbackDuration=s,!0;case"dynamics":return e.dynamics=Bs.parseEnum(s,p),!0;case"invertbeamdirection":return e.invertBeamDirection=s,!0;case"preferredbeamdirection":return e.preferredBeamDirection=Bs.parseEnum(s,H),!0;case"beamingmode":return e.beamingMode=Bs.parseEnum(s,F),!0}return!1}}class js{static fromJson(e,t){t&&Bs.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=>Qs.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 De;Qs.fromJson(s,t),e.addBeat(s)}return!0;case"isempty":return e.isEmpty=s,!0}return!1}}class Ks{static fromJson(e,t){t&&Bs.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=>js.toJson(e)))),t.set("similemark",e.simileMark),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"clef":return e.clef=Bs.parseEnum(s,r),!0;case"clefottava":return e.clefOttava=Bs.parseEnum(s,n),!0;case"voices":e.voices=[];for(const t of s){const s=new Qe;js.fromJson(s,t),e.addVoice(s)}return!0;case"similemark":return e.simileMark=Bs.parseEnum(s,o),!0}return!1}}class $s{static fromJson(e,t){t&&Bs.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 Zs{static fromJson(e,t){t&&Bs.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 ei{static fromJson(e,t){t&&Bs.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=>Ks.toJson(e)))),null!==e.chords){const s=new Map;t.set("chords",s);for(const[t,i]of e.chords)s.set(t.toString(),$s.toJson(i))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",Zs.toJson(e.stringTuning)),t.set("showtablature",e.showTablature),t.set("showstandardnotation",e.showStandardNotation),t.set("ispercussion",e.isPercussion),t.set("standardnotationlinecount",e.standardNotationLineCount),t}static setProperty(e,t,s){switch(t){case"bars":e.bars=[];for(const t of s){const s=new me;Ks.fromJson(s,t),e.addBar(s)}return!0;case"chords":return e.chords=new Map,Bs.forEach(s,((t,s)=>{const i=new Re;$s.fromJson(i,t),e.addChord(s,i)})),!0;case"capo":return e.capo=s,!0;case"transpositionpitch":return e.transpositionPitch=s,!0;case"displaytranspositionpitch":return e.displayTranspositionPitch=s,!0;case"showtablature":return e.showTablature=s,!0;case"showstandardnotation":return e.showStandardNotation=s,!0;case"ispercussion":return e.isPercussion=s,!0;case"standardnotationlinecount":return e.standardNotationLineCount=s,!0}return["stringtuning"].indexOf(t)>=0&&(Zs.fromJson(e.stringTuning,s),!0)}}class ti{static fromJson(e,t){t&&Bs.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 si{static fromJson(e,t){t&&Bs.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=Bs.parseEnum(s,N),!0;case"noteheadhalf":return e.noteHeadHalf=Bs.parseEnum(s,N),!0;case"noteheadwhole":return e.noteHeadWhole=Bs.parseEnum(s,N),!0;case"techniquesymbol":return e.techniqueSymbol=Bs.parseEnum(s,N),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=Bs.parseEnum(s,E),!0;case"outputmidinumber":return e.outputMidiNumber=s,!0}return!1}}class ii{static fromJson(e,t){t&&Bs.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=>ei.toJson(e)))),t.set("playbackinfo",ti.toJson(e.playbackInfo)),t.set("color",Ue.toJson(e.color)),t.set("name",e.name),t.set("shortname",e.shortName),t.set("percussionarticulations",e.percussionArticulations.map((e=>si.toJson(e)))),t}static setProperty(e,t,s){switch(t){case"staves":e.staves=[];for(const t of s){const s=new qe;ei.fromJson(s,t),e.addStaff(s)}return!0;case"color":return e.color=Ue.fromJson(s),!0;case"name":return e.name=s,!0;case"shortname":return e.shortName=s,!0;case"percussionarticulations":e.percussionArticulations=[];for(const t of s){const s=new ve;si.fromJson(s,t),e.percussionArticulations.push(s)}return!0}return["playbackinfo"].indexOf(t)>=0&&(ti.fromJson(e.playbackInfo,s),!0)}}class ai{static fromJson(e,t){t&&Bs.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("hidedynamics",e.hideDynamics),t}static setProperty(e,t,s){switch(t){case"hidedynamics":return e.hideDynamics=s,!0}return!1}}class ri{static fromJson(e,t){t&&Bs.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=>Ys.toJson(e)))),t.set("tracks",e.tracks.map((e=>ii.toJson(e)))),t.set("stylesheet",ai.toJson(e.stylesheet)),t}static setProperty(e,t,s){switch(t){case"album":return e.album=s,!0;case"artist":return e.artist=s,!0;case"copyright":return e.copyright=s,!0;case"instructions":return e.instructions=s,!0;case"music":return e.music=s,!0;case"notices":return e.notices=s,!0;case"subtitle":return e.subTitle=s,!0;case"title":return e.title=s,!0;case"words":return e.words=s,!0;case"tab":return e.tab=s,!0;case"tempo":return e.tempo=s,!0;case"tempolabel":return e.tempoLabel=s,!0;case"masterbars":e.masterBars=[];for(const t of s){const s=new Oe;Ys.fromJson(s,t),e.addMasterBar(s)}return!0;case"tracks":e.tracks=[];for(const t of s){const s=new Je;ii.fromJson(s,t),e.addTrack(s)}return!0}return["stylesheet"].indexOf(t)>=0&&(ai.fromJson(e.stylesheet,s),!0)}}class ni{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=ni.scoreToJsObject(e);return JSON.stringify(t,ni.jsonReplacer)}static jsonToScore(e,t){return ni.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return ri.toJson(e)}static jsObjectToScore(e,t){let s=new He;return ri.fromJson(s,e),s.finish(null!=t?t:new Hs),s}static settingsToJson(e){let t=ni.settingsToJsObject(e);return JSON.stringify(t,ni.jsonReplacer)}static jsonToSettings(e){return ni.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return Vs.toJson(e)}static jsObjectToSettings(e){let t=new Hs;return Vs.fromJson(t,e),t}static jsObjectToMidiFile(e){let t=new Ss;t.division=e.division;let s=e.events;for(let e of s){let s=ni.jsObjectToMidiEvent(e);t.events.push(s)}return t}static jsObjectToMidiEvent(e){let t,s=e.track,i=e.tick,a=e.message;switch(e.type){case"SystemExclusiveEvent":t=new At(s,i,0,0,e.data),t.message=a;break;case"MetaDataEvent":t=new ws(s,i,0,0,e.data),t.message=a;break;case"MetaNumberEvent":t=new _s(s,i,0,0,e.value),t.message=a;break;case"Midi20PerNotePitchBendEvent":t=new Ws(s,i,0,e.noteKey,e.pitch),t.message=a;break;default:t=new It(s,i,0,0,0),t.message=a}return t}static midiFileToJsObject(e){let t={};t.division=e.division;let s=[];t.events=s;for(let t of e.events)s.push(ni.midiEventToJsObject(t));return t}static midiEventToJsObject(e){let t={};return t.track=e.track,t.tick=e.tick,t.message=e.message,e instanceof At?(t.type="SystemExclusiveEvent",t.data=e.data):e instanceof ws?(t.type="MetaDataEvent",t.data=e.data):e instanceof _s?(t.type="MetaNumberEvent",t.value=e.value):e instanceof Ws&&(t.type="Midi20PerNotePitchBendEvent",t.noteKey=e.noteKey,t.pitch=e.pitch),t}}class oi{constructor(){this.ready=new fs,this.samplesPlayed=new ms,this.sampleRequest=new fs}get sampleRate(){return oi.preferredSampleRate}open(){Be.debug("AlphaSynth","Initializing webworker worker"),this._worker=ho.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 oi.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case oi.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(){}}oi.CmdOutputPrefix="alphaSynth.output.",oi.CmdOutputAddSamples=oi.CmdOutputPrefix+"addSamples",oi.CmdOutputPlay=oi.CmdOutputPrefix+"play",oi.CmdOutputPause=oi.CmdOutputPrefix+"pause",oi.CmdOutputResetSamples=oi.CmdOutputPrefix+"resetSamples",oi.CmdOutputSampleRequest=oi.CmdOutputPrefix+"sampleRequest",oi.CmdOutputSamplesPlayed=oi.CmdOutputPrefix+"samplesPlayed",oi.preferredSampleRate=0;class hi{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new bs(new oi),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._main.postMessage({cmd:"alphaSynth.ready"})}static init(){let e=ho.globalThis;e.addEventListener("message",(t=>{let s=t.data;switch(s.cmd){case"alphaSynth.initialize":oi.preferredSampleRate=s.sampleRate,Be.logLevel=s.logLevel,ho.globalThis.alphaSynthWebWorker=new hi(e)}}))}handleMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":Be.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(ni.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(ni.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);break;case"alphaSynth.setChannelSolo":this._player.setChannelSolo(t.channel,t.solo);break;case"alphaSynth.setChannelVolume":this._player.setChannelVolume(t.channel,t.volume);break;case"alphaSynth.resetChannelStates":this._player.resetChannelStates();break;case"alphaSynth.destroy":this._player.destroy(),this._main.postMessage({cmd:"alphaSynth.destroyed"})}}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(ni.midiEventToJsObject)})}}class li{static generateFontLookup(e){if(!li.FontSizeLookupTables.has(e))if(ho.isRunningInWorker)li.FontSizeLookupTables.set(e,new Uint8Array([8]));else{let t=document.createElement("canvas").getContext("2d");t.font="11px "+e;let s=[];for(let e=32;e<255;e++){let i=String.fromCharCode(e);s.push(t.measureText(i).width)}let i=new Uint8Array(s);li.FontSizeLookupTables.set(e,i)}}static measureString(e,t,s,i,a){let r;li.FontSizeLookupTables.has(t)||li.generateFontLookup(t),r=li.FontSizeLookupTables.get(t);let n=1;i===$.Italic&&(n*=1.2),a===Z.Bold&&(n*=1.2);let o=0;for(let t=0;t<e.length;t++){let i=Math.min(r.length-1,e.charCodeAt(t)-32);i>=0&&(o+=r[i]*s/11)}return o*n}}li.Georgia=new Uint8Array([3,4,5,7,7,9,8,2,4,4,5,7,3,4,3,5,7,5,6,6,6,6,6,6,7,6,3,3,7,7,7,5,10,7,7,7,8,7,7,8,9,4,6,8,7,10,8,8,7,8,8,6,7,8,7,11,8,7,7,4,5,4,7,7,6,6,6,5,6,5,4,6,6,3,3,6,3,10,6,6,6,6,5,5,4,6,5,8,6,5,5,5,4,5,7,6,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,3,4,6,7,6,7,4,6,6,10,6,6,7,0,10,7,5,7,6,6,6,6,6,3,6,6,6,6,12,12,12,5,7,7,7,7,7,7,11,7,7,7,7,7,4,4,4,4,8,8,8,8,8,8,8,7,8,8,8,8,8,7,7,6,6,6,6,6,6,6,8,5,5,5,5,5,3,3,3,3,6,6,6,6,6,6,6,7,6,6,6,6,6,5,6]),li.Arial=new Uint8Array([3,3,4,6,6,10,7,2,4,4,4,6,3,4,3,3,6,6,6,6,6,6,6,6,6,6,3,3,6,6,6,6,11,7,7,8,8,7,7,9,8,3,6,7,6,9,8,9,7,9,8,7,7,8,7,10,7,7,7,3,3,3,5,6,4,6,6,6,6,6,3,6,6,2,2,6,2,9,6,6,6,6,4,6,3,6,6,8,6,6,6,4,3,4,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,4,6,6,6,6,3,6,4,8,4,6,6,0,8,6,4,6,4,4,4,6,6,4,4,4,4,6,9,9,9,7,7,7,7,7,7,7,11,8,7,7,7,7,3,3,3,3,8,8,9,9,9,9,9,6,9,8,8,8,8,7,7,7,6,6,6,6,6,6,10,6,6,6,6,6,3,3,3,3,6,6,6,6,6,6,6,6,7,6,6,6,6,6,6]),li.FontSizeLookupTables=new Map([["Arial",li.Arial],["'Arial'",li.Arial],['"Arial"',li.Arial],["Georgia",li.Georgia],["'Georgia'",li.Georgia],['"Georgia"',li.Georgia]]),li.ControlChars=32;class ci{constructor(){this.id=ke.newGuid(),this.x=0,this.y=0,this.width=0,this.height=0,this.totalWidth=0,this.totalHeight=0,this.firstMasterBarIndex=0,this.lastMasterBarIndex=0,this.renderResult=null}}class di{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}}class ui{constructor(){this.notes=null}addNote(e){this.notes||(this.notes=[]),e.beatBounds=this,this.notes.push(e)}findNoteAtPos(e,t){const s=this.notes;if(!s)return null;for(let i of s){let s=i.noteHeadBounds.y+i.noteHeadBounds.h,a=i.noteHeadBounds.x+i.noteHeadBounds.w;if(i.noteHeadBounds.x>=e&&i.noteHeadBounds.y>=t&&e<=a&&t<=s)return i.note}return null}}class pi{constructor(){this.index=0,this.isFirstOfLine=!1,this.bars=[],this.staveGroupBounds=null}addBar(e){e.masterBarBounds=this,this.bars.push(e)}findBeatAtPos(e,t){let s=null;for(let t of this.bars){let i=t.findBeatAtPos(e);i&&(!s||s.realBounds.x<i.realBounds.x)&&(s=i)}return s?s.beat:null}finish(){this.bars.sort(((e,t)=>e.realBounds.y<t.realBounds.y?-1:e.realBounds.y>t.realBounds.y?1:e.realBounds.x<t.realBounds.x?-1:e.realBounds.x>t.realBounds.x?1:0))}addBeat(e){this.staveGroupBounds.boundsLookup.addBeat(e)}}class gi{}class fi{constructor(){this.index=0,this.bars=[]}finish(){for(let e of this.bars)e.finish()}addBar(e){this.boundsLookup.addMasterBar(e),e.staveGroupBounds=this,this.bars.push(e)}findBarAtPos(e){let t=null;for(let s of this.bars)if(!t||s.realBounds.x<e)t=s;else if(e>s.realBounds.x+s.realBounds.w)break;return t}}class mi{constructor(){this._beatLookup=new Map,this._masterBarLookup=new Map,this._currentStaveGroup=null,this.staveGroups=[],this.isFinished=!1}toJson(){let e={},t=[];e.staveGroups=t;for(let e of this.staveGroups){let s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.bars=[];for(let t of e.bars){let e={};e.lineAlignedBounds=this.boundsToJson(t.lineAlignedBounds),e.visualBounds=this.boundsToJson(t.visualBounds),e.realBounds=this.boundsToJson(t.realBounds),e.index=t.index,e.bars=[];for(let s of t.bars){let t={};t.visualBounds=this.boundsToJson(s.visualBounds),t.realBounds=this.boundsToJson(s.realBounds),t.beats=[];for(let e of s.beats){let s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds);let i=s;if(i.beatIndex=e.beat.index,i.voiceIndex=e.beat.voice.index,i.barIndex=e.beat.voice.bar.index,i.staffIndex=e.beat.voice.bar.staff.index,i.trackIndex=e.beat.voice.bar.staff.track.index,e.notes){let t=s.notes=[];for(let s of e.notes){let e={};e.index=s.note.index,e.noteHeadBounds=this.boundsToJson(s.noteHeadBounds),t.push(e)}}t.beats.push(s)}e.bars.push(t)}s.bars.push(e)}t.push(s)}return e}static fromJson(e,t){let s=new mi,i=e.staveGroups;for(let e of i){let i=new fi;i.visualBounds=e.visualBounds,i.realBounds=e.realBounds,s.addStaveGroup(i);for(let s of e.bars){let e=new pi;e.index=s.index,e.isFirstOfLine=s.isFirstOfLine,e.lineAlignedBounds=s.lineAlignedBounds,e.visualBounds=s.visualBounds,e.realBounds=s.realBounds,i.addBar(e);for(let i of s.bars){let s=new di;s.visualBounds=i.visualBounds,s.realBounds=i.realBounds,e.addBar(s);for(let e of i.beats){let i=new ui;i.visualBounds=e.visualBounds,i.realBounds=e.realBounds;let a=e;if(i.beat=t.tracks[a.trackIndex].staves[a.staffIndex].bars[a.barIndex].voices[a.voiceIndex].beats[a.beatIndex],e.notes){i.notes=[];for(let t of e.notes){let e=new gi,s=t;e.note=i.beat.notes[s.index],e.noteHeadBounds=t.noteHeadBounds,i.addNote(e)}}s.addBeat(i)}}}}return s}boundsToJson(e){let t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(){for(let e of this.staveGroups)e.finish();this.isFinished=!0}addNote(e){this.findBeat(e.note.beat).addNote(e)}addStaveGroup(e){e.index=this.staveGroups.length,e.boundsLookup=this,this.staveGroups.push(e),this._currentStaveGroup=e}addMasterBar(e){e.staveGroupBounds?this._masterBarLookup.set(e.index,e):(e.staveGroupBounds=this._currentStaveGroup,this._masterBarLookup.set(e.index,e),this._currentStaveGroup.addBar(e))}addBeat(e){this._beatLookup.set(e.beat.id,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){let t=e.id;return this._beatLookup.has(t)?this._beatLookup.get(t):null}getBeatAtPos(e,t){let s=0,i=this.staveGroups.length-1,a=-1;for(;s<=i;){let e=(i+s)/2|0,r=this.staveGroups[e];if(t>=r.realBounds.y&&t<=r.realBounds.y+r.realBounds.h){a=e;break}t<r.realBounds.y?i=e-1:s=e+1}if(-1===a)return null;let r=this.staveGroups[a].findBarAtPos(e);return r?r.findBeatAtPos(e,t):null}getNoteAtPos(e,t,s){let i=this.findBeat(e);return i?i.findNoteAtPos(t,s):null}}class yi{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 ms,this.renderFinished=new ms,this.partialRenderFinished=new ms,this.partialLayoutFinished=new ms,this.postRenderFinished=new fs,this.error=new ms,this.settings=t,this.recreateCanvas(),this.recreateLayout()}destroy(){this.score=null,this.canvas=null,this.layout=null,this.boundsLookup=null,this.tracks=null}recreateCanvas(){return this._currentRenderEngine!==this.settings.core.engine&&(this.canvas=ho.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=ho.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?(Be.debug("Rendering","Request render of lazy partial "+e),t.renderLazyPartial(e)):Be.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 mi,this.recreateCanvas(),this.canvas.lineWidth=this.settings.display.scale,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){Be.debug("Rendering","Rendering "+this.tracks.length+" tracks");for(let e=0;e<this.tracks.length;e++){let t=this.tracks[e];Be.debug("Rendering","Track "+e+": "+t.name)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),Be.debug("Rendering","Rendering finished")}else Be.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),Be.debug("Rendering","Clearing finished");else Be.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(Be.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(Be.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new mi,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):Be.warning("Rendering","Current layout does not support dynamic resizing, nothing was done",null),Be.debug("Rendering","Resize finished")}layoutAndRender(){Be.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(){const e=new ci;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}class bi{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){ho.globalThis.alphaTabWebWorker=new bi(ho.globalThis)}handleMessage(e){let t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":let e=ni.jsObjectToSettings(t.settings);Be.logLevel=e.core.logLevel,this._renderer=new yi(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((()=>{var e,t;this._main.postMessage({cmd:"alphaTab.postRenderFinished",boundsLookup:null!==(t=null===(e=this._renderer.boundsLookup)||void 0===e?void 0:e.toJson())&&void 0!==t?t: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:ni.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(s,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(e){li.FontSizeLookupTables||(li.FontSizeLookupTables=new Map);for(let t in e)li.FontSizeLookupTables.set(t,e[t])}}updateSettings(e){Vs.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){Be.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class Si{constructor(){this._canvas=null,this._color=new Ue(0,0,0,255),this._font=new vs("Arial",10,$.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 vs(s,parseFloat(t.fontSize),$.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"}onRenderFinished(){return null}beginRender(e,t){this._canvas=document.createElement("canvas"),this._canvas.width=e*ho.HighDpiFactor|0,this._canvas.height=t*ho.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(ho.HighDpiFactor,ho.HighDpiFactor),this._context.lineWidth=this._lineWidth}endRender(){let e=this._canvas;return this._canvas=null,e}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._context.strokeStyle=e.rgba,this._context.fillStyle=e.rgba)}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._context&&(this._context.lineWidth=e)}fillRect(e,t,s,i){s>0&&this._context.fillRect(0|e,0|t,s,i)}strokeRect(e,t,s,i){this._context.strokeRect(0|e,0|t,s,i)}beginPath(){this._context.beginPath()}closePath(){this._context.closePath()}moveTo(e,t){this._context.moveTo(e,t)}lineTo(e,t){this._context.lineTo(e,t)}quadraticCurveTo(e,t,s,i){this._context.quadraticCurveTo(e,t,s,i)}bezierCurveTo(e,t,s,i,a,r){this._context.bezierCurveTo(e,t,s,i,a,r)}fillCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.fill()}strokeCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.stroke()}fill(){this._context.fill(),this._context.beginPath()}stroke(){this._context.stroke(),this._context.beginPath()}get font(){return this._font}set font(e){this._font=e,this._context&&(this._context.font=e.toCssString(this.settings.display.scale)),this._measureContext.font=e.toCssString(this.settings.display.scale)}get textAlign(){switch(this._context.textAlign){case"left":return P.Left;case"center":return P.Center;case"right":return P.Right;default:return P.Left}}set textAlign(e){switch(e){case P.Left:this._context.textAlign="left";break;case P.Center:this._context.textAlign="center";break;case P.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":return E.Top;case"middle":return E.Middle;case"bottom":return E.Bottom;default:return E.Top}}set textBaseline(e){switch(e){case E.Top:this._context.textBaseline="hanging";break;case E.Middle:this._context.textBaseline="middle";break;case E.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,s){this._context.fillText(e,t,s)}measureText(e){return this._measureContext.measureText(e).width}fillMusicFontSymbol(e,t,s,i,a=!1){i!==N.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a=!1){let r="";for(let e of i)e!==N.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a=!1){let r=this._context.textAlign,n=this._context.textBaseline,o=this._context.font;this._context.font=this._musicFont.toCssString(s),this._context.textBaseline="middle",this._context.textAlign=a?"center":"left",this._context.fillText(i,e,t),this._context.textBaseline=n,this._context.font=o,this._context.textAlign=r}beginRotate(e,t,s){this._context.save(),this._context.translate(e,t),this._context.rotate(s*Math.PI/180)}endRotate(){this._context.restore()}}class wi{constructor(e){this._midiFile=e}addTimeSignature(e,t,s){let i=0;for(;(s>>=1)>0;)i++;const a=new ws(0,e,255,U.TimeSignature,new Uint8Array([255&t,255&i,48,8]));this._midiFile.addEvent(a)}addRest(e,t,s){const i=new At(e,t,X.SystemExclusive,At.AlphaTabManufacturerId,new Uint8Array([Y.Rest]));this._midiFile.addEvent(i)}addNote(e,t,s,i,a,r){const n=ye.dynamicToVelocity(a),o=new It(e,t,this.makeCommand(z.NoteOn,r),wi.fixValue(i),wi.fixValue(n));this._midiFile.addEvent(o);const h=new It(e,t+s,this.makeCommand(z.NoteOff,r),wi.fixValue(i),wi.fixValue(n));this._midiFile.addEvent(h)}makeCommand(e,t){return 240&e|15&t}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,s,i,a){const r=new It(e,t,this.makeCommand(z.Controller,s),wi.fixValue(i),wi.fixValue(a));this._midiFile.addEvent(r)}addProgramChange(e,t,s,i){const a=new It(e,t,this.makeCommand(z.ProgramChange,s),wi.fixValue(i),0);this._midiFile.addEvent(a)}addTempo(e,t){const s=6e7/t|0,i=new _s(0,e,255,U.Tempo,s);this._midiFile.addEvent(i)}addBend(e,t,s,i){i=i>=Gt.MaxPitchWheel?Gt.MaxPitchWheel:Math.floor(i);const a=new It(e,t,this.makeCommand(z.PitchBend,s),127&i,i>>7&127);this._midiFile.addEvent(a)}addNoteBend(e,t,s,i,a){a=(a=a>=Gt.MaxPitchWheel?Gt.MaxPitchWheel:Math.floor(a))*Gt.MaxPitchWheel20/Gt.MaxPitchWheel;const r=new Ws(e,t,this.makeCommand(z.PerNotePitchBend,s),i,a);this._midiFile.addEvent(r)}finishTrack(e,t){const s=new ws(e,t,255,U.EndOfTrack,new Uint8Array(0));this._midiFile.addEvent(s)}}class _i{constructor(){this._highlightedBeats=new Map,this.index=0,this.start=0,this.end=0,this.isEmptyBar=!1,this.beatsToHighlight=[]}highlightBeat(e){this._highlightedBeats.has(e.id)||(this._highlightedBeats.set(e.id,!0),this.beatsToHighlight.push(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.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.ResetControllers=121]="ResetControllers",e[e.AllNotesOff=123]="AllNotesOff"}(te||(te={}));class Bi{constructor(e){this._repeatStartIndex=0,this._repeatNumber=0,this._repeatOpen=!1,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}get finished(){return this.index>=this._score.masterBars.length}processCurrent(){const e=this._score.masterBars[this.index],t=e.alternateEndings;e.repeatGroup.isClosed||e.repeatGroup.openings[e.repeatGroup.openings.length-1]!==e||(this._repeatNumber=0,this._repeatOpen=!1),!e.isRepeatStart&&0!==e.index||0!==this._repeatNumber?e.isRepeatStart&&(this.shouldPlay=!0):(this._repeatStartIndex=this.index,this._repeatOpen=!0),this._repeatOpen&&t>0&&(0==(t&1<<this._repeatNumber)?this.shouldPlay=!1:this.shouldPlay=!0),this.shouldPlay&&(this.currentTick+=e.calculateDuration())}moveNext(){const e=this._score.masterBars[this.index].repeatCount-1;this._repeatOpen&&e>0?this._repeatNumber<e?(this.index=this._repeatStartIndex,this._repeatNumber++):(this._repeatNumber=0,this._repeatOpen=!1,this.shouldPlay=!0,this.index++):this.index++}}class Ti{constructor(){this.start=0,this.end=0,this.tempo=0,this.beats=[],this.nextMasterBar=null}finish(){this.beats.sort(((e,t)=>e.start-t.start))}addBeat(e){e.masterBar=this,e.index=this.beats.length,this.beats.push(e)}}class ki{constructor(){this.duration=0,this.nextBeatLookup=null}get currentBeat(){return this.currentBeatLookup.beat}get nextBeat(){var e,t;return null!==(t=null===(e=this.nextBeatLookup)||void 0===e?void 0:e.beat)&&void 0!==t?t:null}}class vi{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[]}finish(){let e=null,t=[];for(let s of this.masterBars){s.finish(),e&&(e.nextMasterBar=s);for(const e of s.beats){const s=[];for(let i of t)i.end>e.start&&(s.push(i),e.highlightBeat(i.beat),e.start<=i.start&&i.highlightBeat(e.beat));s.push(e),t=s}e=s}}findBeat(e,t,s=null){const i=new Map;for(const t of e)i.set(t.index,!0);let a=null;return s&&(a=this.findBeatFast(i,s,t)),a||(a=this.findBeatSlow(i,t)),a}findBeatFast(e,t,s){return s>=t.currentBeatLookup.start&&s<t.currentBeatLookup.end?t:t.nextBeatLookup&&s>=t.nextBeatLookup.start&&s<t.nextBeatLookup.end?this.createResult(t.nextBeatLookup,e):null}findBeatSlow(e,t){const s=this.findMasterBar(t);if(!s)return null;let i=null,a=s.beats;for(let s=0;s<a.length;s++){let r=a[s];if(e.has(r.beat.voice.bar.staff.track.index))if(r.start<=t&&t<r.end)(!i||i.start<r.start)&&(i=a[s]);else if(r.end>t)break}return i?this.createResult(i,e):null}createResult(e,t){const s=this.findNextBeat(e,t),i=new ki;return i.currentBeatLookup=e,i.nextBeatLookup=s,i.duration=s?ye.ticksToMillis(s.start-e.start,e.masterBar.tempo):ye.ticksToMillis(e.end-e.start,e.masterBar.tempo),i.beatsToHighlight=e.beatsToHighlight,i}findNextBeat(e,t){const s=e.masterBar;let i=s.beats,a=null;for(let s=e.index+1;s<i.length;s++){const r=i[s];if(r.start>e.start&&t.has(r.beat.voice.bar.staff.track.index)){a=r;break}}if(!a&&s.nextMasterBar){i=s.nextMasterBar.beats;for(let e=0;e<i.length;e++){const s=i[e];if(t.has(s.beat.voice.bar.staff.track.index)){a=s;break}}}return a}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 Ti;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}addMasterBar(e){this.masterBars.push(e),this._currentMasterBar=e,this.masterBarLookup.has(e.masterBar.index)||this.masterBarLookup.set(e.masterBar.index,e)}addBeat(e){var t;null===(t=this._currentMasterBar)||void 0===t||t.addBeat(e)}}class xi{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Ni{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class Pi{constructor(e,t,s){this._currentTempo=0,this._currentBarRepeatLookup=null,this._programsPerChannel=new Map,this.tickLookup=new vi,this._currentTripletFeel=null,this._score=e,this._settings=t||new Hs,this._currentTempo=this._score.tempo,this._handler=s}generate(){for(const e of this._score.tracks)this.generateTrack(e);Be.debug("Midi","Begin midi generation");const e=new Bi(this._score);let t=null;for(;!e.finished;){const s=e.index,i=this._score.masterBars[s],a=e.currentTick;if(e.processCurrent(),e.shouldPlay){this.generateMasterBar(i,t,a);for(const e of this._score.tracks)for(const t of e.staves)s<t.bars.length&&this.generateBar(t.bars[s],a)}e.moveNext(),t=i}for(const t of this._score.tracks)this._handler.finishTrack(t.index,e.currentTick);this.tickLookup.finish(),Be.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))}generateChannel(e,t,s){let i=Pi.toChannelShort(s.volume),a=Pi.toChannelShort(s.balance);this._handler.addControlChange(e.index,0,t,te.VolumeCoarse,i),this._handler.addControlChange(e.index,0,t,te.PanCoarse,a),this._handler.addControlChange(e.index,0,t,te.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,te.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,te.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,te.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,te.DataEntryCoarse,Pi.PitchBendRangeInSemitones),this.addProgramChange(e,0,t,s.program)}static toChannelShort(e){const t=Math.max(-32768,Math.min(32767,8*e-1));return Math.max(t,-1)+1}generateMasterBar(e,t,s){t&&t.timeSignatureDenominator===e.timeSignatureDenominator&&t.timeSignatureNumerator===e.timeSignatureNumerator||this._handler.addTimeSignature(s,e.timeSignatureNumerator,e.timeSignatureDenominator),t?e.tempoAutomation&&(this._handler.addTempo(s,e.tempoAutomation.value),this._currentTempo=e.tempoAutomation.value):(this._handler.addTempo(s,e.score.tempo),this._currentTempo=e.score.tempo);const i=new Ti;i.masterBar=e,i.start=s,i.tempo=this._currentTempo,i.end=i.start+e.calculateDuration(),this.tickLookup.addMasterBar(i)}generateBar(e,t){let s=this.getPlaybackBar(e);this._currentBarRepeatLookup=null;for(const i of s.voices)this.generateVoice(i,t,e)}getPlaybackBar(e){switch(e.simileMark){case o.Simple:e.previousBar&&(e=this.getPlaybackBar(e.previousBar));break;case o.FirstOfDouble:case o.SecondOfDouble:e.previousBar&&e.previousBar.previousBar&&(e=this.getPlaybackBar(e.previousBar.previousBar))}return e}generateVoice(e,t,s){if(!e.isEmpty||e.bar.isEmpty&&0===e.index)for(const i of e.beats)this.generateBeat(i,t,s)}generateBeat(e,t,s){let i=e.playbackStart,a=e.playbackDuration;e.voice.bar.isEmpty?a=e.voice.bar.masterBar.calculateDuration():e.voice.bar.masterBar.tripletFeel!==D.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(i-=this._currentTripletFeel.secondBeatStartOffset,a=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=Pi.calculateTripletFeelInfo(i,a,e),this._currentTripletFeel&&(a=this._currentTripletFeel.firstBeatDuration)));const r=new _i;r.start=t+i;const n=e.nextBeat?e.nextBeat.absolutePlaybackStart-e.absolutePlaybackStart:a;r.end=t+i,r.highlightBeat(e),r.end+=n>a?n:a,s===e.voice.bar?(r.beat=e,this.tickLookup.addBeat(r)):(r.isEmptyBar=!0,r.beat=s.voices[0].beats[0],this._currentBarRepeatLookup?this._currentBarRepeatLookup.end=r.end:(this._currentBarRepeatLookup=r,this.tickLookup.addBeat(this._currentBarRepeatLookup)));const o=e.voice.bar.staff.track;for(const s of e.automations)this.generateAutomation(e,s,t);if(e.isRest)this._handler.addRest(o.index,t+i,o.playbackInfo.primaryChannel);else{let s=this.getBrushInfo(e);for(const r of e.notes)this.generateNote(r,t+i,a,s)}if(e.vibrato!==w.None){let s=240,a=3;switch(e.vibrato){case w.Slight:s=this._settings.player.vibrato.beatSlightLength,a=this._settings.player.vibrato.beatSlightAmplitude;break;case w.Wide:s=this._settings.player.vibrato.beatWideLength,a=this._settings.player.vibrato.beatWideAmplitude}this.generateVibratorWithParams(t+i,e.playbackDuration,s,a,((t,s)=>{this._handler.addBend(e.voice.bar.staff.track.index,t,o.playbackInfo.secondaryChannel,s)}))}}static calculateTripletFeelInfo(e,t,s){let i;switch(s.voice.bar.masterBar.tripletFeel){case D.Triplet8th:case D.Dotted8th:case D.Scottish8th:i=u.Eighth;break;case D.Triplet16th:case D.Dotted16th:case D.Scottish16th:i=u.Sixteenth;break;default:return null}const a=ye.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 Ni;switch(s.voice.bar.masterBar.tripletFeel){case D.Triplet8th:r.firstBeatDuration=ye.applyTuplet(ye.toTicks(u.Quarter),3,2),r.secondBeatDuration=ye.applyTuplet(ye.toTicks(u.Eighth),3,2);break;case D.Dotted8th:r.firstBeatDuration=ye.applyDot(ye.toTicks(u.Eighth),!1),r.secondBeatDuration=ye.toTicks(u.Sixteenth);break;case D.Scottish8th:r.firstBeatDuration=ye.toTicks(u.Sixteenth),r.secondBeatDuration=ye.applyDot(ye.toTicks(u.Eighth),!1);break;case D.Triplet16th:r.firstBeatDuration=ye.applyTuplet(ye.toTicks(u.Eighth),3,2),r.secondBeatDuration=ye.applyTuplet(ye.toTicks(u.Sixteenth),3,2);break;case D.Dotted16th:r.firstBeatDuration=ye.applyDot(ye.toTicks(u.Sixteenth),!1),r.secondBeatDuration=ye.toTicks(u.ThirtySecond);break;case D.Scottish16th:r.firstBeatDuration=ye.toTicks(u.ThirtySecond),r.secondBeatDuration=ye.applyDot(ye.toTicks(u.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateNote(e,t,s,i){const a=e.beat.voice.bar.staff.track,r=e.beat.voice.bar.staff;let n=e.realValue;if(e.isPercussion){const t=xe.getArticulation(e);t&&(n=t.outputMidiNumber)}const o=e.isStringed&&e.string<=i.length?i[e.string-1]:0,h=t+o,l=this.getNoteDuration(e,s);l.untilTieOrSlideEnd-=o,l.noteOnly-=o,l.letRingEnd-=o;const c=Pi.getDynamicValue(e),d=e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==w.None?a.playbackInfo.secondaryChannel:a.playbackInfo.primaryChannel;let u=0;if(u=e.hasBend?Pi.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?Pi.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===S.Legato?-1:Pi.getPitchWheel(0),u>=0&&this._handler.addNoteBend(a.index,h,d,n,u),e.beat.fadeIn&&this.generateFadeIn(e,h,l),!e.isTrill||r.isPercussion){if(e.beat.isTremolo)this.generateTremoloPicking(e,h,l,n,c,d);else if(e.hasBend?this.generateBend(e,h,l,n,d):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,h,l,d):e.slideInType!==b.None||e.slideOutType!==S.None?this.generateSlide(e,h,l,n,c,d):e.vibrato!==w.None&&this.generateVibrato(e,h,l,n,d),!(e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===S.Legato)){let e=Math.max(l.untilTieOrSlideEnd,l.letRingEnd);this._handler.addNote(a.index,h,e,n,c,d)}}else this.generateTrill(e,h,l,n,c,d)}getNoteDuration(e,t){const s=new xi;if(s.noteOnly=t,s.untilTieOrSlideEnd=t,s.letRingEnd=t,e.isDead)return s.noteOnly=this.applyStaticDuration(Pi.DefaultDurationDead,t),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(e.isPalmMute)return s.noteOnly=this.applyStaticDuration(Pi.DefaultDurationPalmMute,t),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(e.isStaccato)return s.noteOnly=t/2|0,s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(e.isTieOrigin){const i=e.tieDestination;if(i)if(e.isTieDestination){const e=this.getNoteDuration(i,i.beat.playbackDuration);s.untilTieOrSlideEnd=t+e.untilTieOrSlideEnd}else{const t=e.beat.absolutePlaybackStart,a=this.getNoteDuration(i,i.beat.playbackDuration),r=i.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-t}}else if(e.slideOutType===S.Legato){const t=e.slideTarget;if(t){const i=e.beat.absolutePlaybackStart,a=this.getNoteDuration(t,t.beat.playbackDuration),r=t.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-i}}if(e.isLetRing&&this._settings.notation.notationMode===T.GuitarPro){let i=e.beat,a=0;const r=e.beat.voice.bar.masterBar.calculateDuration();for(;i.nextBeat;){let t=i.nextBeat;if(t.isRest)break;if(e.isStringed&&t.hasNoteOnString(e.string))break;if(i=i.nextBeat,a=i.absolutePlaybackStart-e.beat.absolutePlaybackStart+i.playbackDuration,a>r){a=r;break}}i===e.beat?s.letRingEnd=t:s.letRingEnd=a}else s.letRingEnd=s.untilTieOrSlideEnd;return s}applyStaticDuration(e,t){const s=this._currentTempo*e/be.MaxPosition|0;return Math.min(s,t)}static getDynamicValue(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 t<0&&(t=0),t}generateFadeIn(e,t,s){const i=e.beat.voice.bar.staff.track,a=Pi.toChannelShort(i.playbackInfo.volume)/s.noteOnly,r=s.noteOnly/120|0,n=t+s.noteOnly;for(let e=r-1;e>=0;e--){const s=n-120*e,o=(s-t)*a;e===r-1&&(this._handler.addControlChange(i.index,t,i.playbackInfo.primaryChannel,te.VolumeCoarse,o),this._handler.addControlChange(i.index,t,i.playbackInfo.secondaryChannel,te.VolumeCoarse,o)),this._handler.addControlChange(i.index,s,i.playbackInfo.primaryChannel,te.VolumeCoarse,o),this._handler.addControlChange(i.index,s,i.playbackInfo.secondaryChannel,te.VolumeCoarse,o)}}generateVibrato(e,t,s,i,a){let r=0,n=0;switch(e.vibrato){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;this.generateVibratorWithParams(t,s.noteOnly,r,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)}))}generateVibratorWithParams(e,t,s,i,a){const r=s/2|0,n=(e+=s)+t;for(;e<n;){let t=0;const o=e+s<n?s:n-e;for(;t<o;){let s=i*Math.sin(t*Math.PI/r);a(e+t|0,Pi.getPitchWheel(s)),t+=16}e+=s}}static getPitchWheel(e){return Gt.DefaultPitchWheel+e/2*Pi.PitchValuePerSemitone}generateSlide(e,t,s,i,a,r){let n=e.slideOutType===S.Legato?s.noteOnly:s.untilTieOrSlideEnd,o=[],h=e.beat.voice.bar.staff.track;const l=this._settings.player.slide.simpleSlidePitchOffset,c=Math.floor(be.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),d=Math.floor(be.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case b.IntoFromAbove:o.push(new be(0,l)),o.push(new be(c,0));break;case b.IntoFromBelow:o.push(new be(0,-l)),o.push(new be(c,0))}switch(e.slideOutType){case S.Legato:case S.Shift:o.push(new be(d,0));const t=2*(e.slideTarget.realValue-e.realValue);o.push(new be(be.MaxPosition,t));break;case S.OutDown:o.push(new be(be.MaxPosition-c,0)),o.push(new be(be.MaxPosition,-l));break;case S.OutUp:o.push(new be(be.MaxPosition-c,0)),o.push(new be(be.MaxPosition,l))}this.generateWhammyOrBend(t,n,o,((e,t)=>{this._handler.addNoteBend(h.index,e,r,i,t)}))}generateBend(e,t,s,i,a){let r=e.bendPoints,n=e.beat.voice.bar.staff.track;const o=(e,t)=>{this._handler.addNoteBend(n.index,e,a,i,t)};let c,d=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend;)t=t.tieDestination;c=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==g.None){switch(e.tieDestination.bendType){case l.Bend:case l.BendRelease:case l.PrebendBend:d=e.tieDestination.bendPoints[1].value;break;case l.Prebend:case l.PrebendRelease:d=e.tieDestination.bendPoints[0].value}c=Math.max(s.noteOnly,ye.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo))}else c=s.noteOnly;r[0].value>0&&!e.isContinuedBend&&t>0&&t--;const u=Math.min(c,ye.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));let p=[];switch(e.bendType){case l.Custom:p=r;break;case l.Bend:case l.Release:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),p.push(new be(be.MaxPosition,d));break;case h.Fast:return(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),void(e.beat.graceType===g.BendGrace?this.generateSongBookWhammyOrBend(t,c,!0,[e.bendPoints[0].value,d],u,o):this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,d],u,o))}break;case l.BendRelease:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),p.push(new be(be.MaxPosition/2|0,e.bendPoints[1].value)),p.push(new be(be.MaxPosition,e.bendPoints[2].value));break;case h.Fast:return void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],u,o)}break;case l.Hold:case l.Prebend:p=r;break;case l.PrebendBend:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),p.push(new be(be.MaxPosition,e.bendPoints[1].value));break;case h.Fast:return o(t,0|Pi.getPitchWheel(e.bendPoints[0].value)),(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,d],u,o)}break;case l.PrebendRelease:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),p.push(new be(be.MaxPosition,e.bendPoints[1].value));break;case h.Fast:return o(t,0|Pi.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,e.bendPoints[1].value],u,o)}}this.generateWhammyOrBend(t,c,p,o)}generateSongBookWhammyOrBend(e,t,s,i,a,r){const n=s?e:e+t-a,o=a/(i.length-1);for(let e=0;e<i.length-1;e++){const t=Pi.getPitchWheel(i[e]),s=Pi.getPitchWheel(i[e+1]),a=n+o*e;this.generateBendValues(a,o,t,s,r)}}generateWhammy(e,t,s,i){const a=e.whammyBarPoints,r=e.voice.bar.staff.track,n=s.noteOnly;a[0].value>0&&!e.isContinuedWhammy&&t--;const o=(e,t)=>{this._handler.addBend(r.index,e,i,t)};let l=[];switch(e.whammyBarType){case C.Custom:l=a;break;case C.Dive:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new be(0,a[0].value)),l.push(new be(be.MaxPosition,a[1].value));break;case h.Fast:const e=Math.min(n,ye.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],e,o)}break;case C.Dip:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new be(0,a[0].value)),l.push(new be(be.MaxPosition/2|0,a[1].value)),l.push(new be(be.MaxPosition,a[2].value));break;case h.Fast:const e=Math.min(n,ye.millisToTicks(this._settings.player.songBookDipDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!0,[a[0].value,a[1].value,a[2].value],e,o)}break;case C.Hold:case C.Predive:l=a;break;case C.PrediveDive:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new be(0,a[0].value)),l.push(new be(be.MaxPosition/2|0,a[0].value)),l.push(new be(be.MaxPosition,a[1].value));break;case h.Fast:const e=Pi.getPitchWheel(a[0].value);this._handler.addBend(r.index,t,i,0|e);const s=Math.min(n,ye.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],s,o)}}this.generateWhammyOrBend(t,n,l,o)}generateWhammyOrBend(e,t,s,i){const a=t/be.MaxPosition;for(let t=0;t<s.length-1;t++){const r=s[t],n=s[t+1],o=Pi.getPitchWheel(r.value),h=Pi.getPitchWheel(n.value),l=a*(n.offset-r.offset),c=e+a*r.offset;this.generateBendValues(c,l,o,h,i)}}generateBendValues(e,t,s,i,a){const r=ye.ticksToMillis(t,this._currentTempo),n=Math.abs(i-s)/Pi.PitchValuePerSemitone,o=Math.max(Pi.MinBreakpointsPerSemitone*n,r/Pi.MillisecondsPerBreakpoint),h=t/o,l=(i-s)/o;for(let t=0;t<o;t++)a(0|e,Math.round(s)),s+=l,e+=h;s<i&&a(0|e,i)}generateTrill(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=ye.toTicks(e.trillSpeed),l=!0,c=t,d=t+s.untilTieOrSlideEnd;for(;c+10<d;)c+h>=d&&(h=d-c),this._handler.addNote(n.index,c,h,l?o:i,a,r),l=!l,c+=h}generateTremoloPicking(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track;let o=ye.toTicks(e.beat.tremoloSpeed),h=t;const l=t+s.untilTieOrSlideEnd;for(;h+10<l;)h+o>=l&&(o=l-h),this._handler.addNote(n.index,h,o,i,a,r),h+=o}getBrushInfo(e){const t=new Int32Array(e.voice.bar.staff.tuning.length);if(e.brushType!==c.None){let s=0,i=0;for(const t of e.notes)t.isTieDestination||(s|=1<<t.string-1,i++);if(e.notes.length>0){let a=0;const r=e.brushDuration/(i-1)|0;for(let i=0;i<e.voice.bar.staff.tuning.length;i++){let n=e.brushType===c.ArpeggioDown||e.brushType===c.BrushDown?i:t.length-1-i;0!=(s&1<<n)&&(t[n]=a,a+=r)}}}return t}generateAutomation(e,t,s){switch(t.type){case a.Instrument:this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,255&(0|t.value)),this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,255&(0|t.value));break;case a.Balance:let i=Pi.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,te.PanCoarse,i),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,te.PanCoarse,i);break;case a.Volume:let r=Pi.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,te.VolumeCoarse,r),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,te.VolumeCoarse,r)}}prepareSingleBeat(e){let t=-1,s=-1,i=e;for(;i&&(-1===t||-1===s);){for(const i of e.automations)switch(i.type){case a.Instrument:s=i.value;break;case a.Tempo:t=i.value}i=i.previousBeat}const r=e.voice.bar.staff.track,n=e.voice.bar.masterBar;-1===t&&(t=n.score.tempo),-1===s&&(s=r.playbackInfo.program);const o=r.playbackInfo.volume;this.generateTrack(r),this._handler.addTimeSignature(0,n.timeSignatureNumerator,n.timeSignatureDenominator),this._handler.addTempo(0,t);let h=Pi.toChannelShort(o);this._handler.addControlChange(0,0,r.playbackInfo.primaryChannel,te.VolumeCoarse,h),this._handler.addControlChange(0,0,r.playbackInfo.secondaryChannel,te.VolumeCoarse,h)}generateSingleBeat(e){this.prepareSingleBeat(e),this.generateBeat(e,-e.playbackStart,e.voice.bar)}generateSingleNote(e){this.prepareSingleBeat(e.beat),this.generateNote(e,-e.beat.playbackStart,e.beat.playbackDuration,new Int32Array(e.beat.voice.bar.staff.tuning.length))}}Pi.DefaultDurationDead=30,Pi.DefaultDurationPalmMute=80,Pi.PitchBendRangeInSemitones=16,Pi.PitchValuePerSemitone=Gt.DefaultPitchWheel/Pi.PitchBendRangeInSemitones,Pi.MinBreakpointsPerSemitone=6,Pi.MillisecondsPerBreakpoint=150;class Ei{constructor(){this.startTick=0,this.endTick=0}}class Ci{constructor(e,t){this.width=0,this.height=0,this.x=e,this.y=t}get scale(){return this.renderer.scale}doLayout(){}paint(e,t,s){}}class Fi extends Ci{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Li extends Fi{constructor(e,t,s,i){super(e,t),this.glyphScale=0,this.glyphScale=s,this.symbol=i}paint(e,t,s){s.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale*this.scale,this.symbol,!1)}}class Mi extends Li{constructor(e,t,s,i){super(e,t,i?Mi.GraceScale:1,Mi.getSymbol(s)),this._isGrace=i,this._duration=s}paint(e,t,s){let i=this._isGrace?this.scale:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale*this.scale,this.symbol,!1)}doLayout(){let e=(this._isGrace?Mi.GraceScale:1)*this.scale;switch(this._duration){case u.QuadrupleWhole:this.width=14*e;break;case u.DoubleWhole:case u.Whole:this.width=14*(this._isGrace?Mi.GraceScale:1)*this.scale;break;default:this.width=Mi.QuarterNoteHeadWidth*(this._isGrace?Mi.GraceScale:1)*this.scale}this.height=Mi.NoteHeadHeight*e}static getSymbol(e){switch(e){case u.QuadrupleWhole:return N.NoteheadDoubleWholeSquare;case u.DoubleWhole:return N.NoteheadDoubleWhole;case u.Whole:return N.NoteheadWhole;case u.Half:return N.NoteheadHalf;default:return N.NoteheadBlack}}}Mi.GraceScale=.75,Mi.NoteHeadHeight=8,Mi.QuarterNoteHeadWidth=9;class Ii extends Li{constructor(e,t,s,i,a){super(e,t,a?Mi.GraceScale:1,Ii.getSymbol(s,i,a))}doLayout(){this.width=0}static getSymbol(e,t,s){if(s&&(e=u.Eighth),t===H.Up)switch(e){case u.Eighth:return N.FlagEighthUp;case u.Sixteenth:return N.FlagSixteenthUp;case u.ThirtySecond:return N.FlagThirtySecondUp;case u.SixtyFourth:return N.FlagSixtyFourthUp;case u.OneHundredTwentyEighth:return N.FlagOneHundredTwentyEighthUp;case u.TwoHundredFiftySixth:return N.FlagTwoHundredFiftySixthUp;default:return N.FlagEighthUp}switch(e){case u.Eighth:return N.FlagEighthDown;case u.Sixteenth:return N.FlagSixteenthDown;case u.ThirtySecond:return N.FlagThirtySecondDown;case u.SixtyFourth:return N.FlagSixtyFourthDown;case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:return N.FlagOneHundredTwentyEighthDown;default:return N.FlagEighthDown}}}Ii.FlagWidth=11;class Di extends Ci{constructor(e,t){super(0,0),this.ties=[],this.minWidth=0,this.beat=e,this.ties=[],this.voiceContainer=t}get onTimeX(){return this.onNotes.x+this.onNotes.centerX}registerLayoutingInfo(e){let t=this.preNotes.computedWidth+this.onNotes.centerX;this.beat.graceGroup&&!this.beat.graceGroup.isComplete&&(t+=Di.GraceBeatPadding*this.renderer.scale);let s=this.onNotes.computedWidth-this.onNotes.centerX;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);(i&&i.hasFlag||this.beat.graceType!==g.None)&&(s+=Ii.FlagWidth*this.scale*(this.beat.graceType!==g.None?Mi.GraceScale:1));for(const e of this.ties)s+=e.width;this.beat.graceType!==g.None&&(s+=Di.GraceBeatPadding*this.renderer.scale),e.addBeatSpring(this.beat,t,s),e.setPreBeatSize(this.beat,this.preNotes.computedWidth),e.setOnBeatSize(this.beat,this.onNotes.computedWidth),e.setBeatCenterX(this.beat,this.onNotes.centerX)}applyLayoutingInfo(e){let t=e.getBeatCenterX(this.beat)-this.onNotes.centerX;this.beat.graceGroup&&!this.beat.graceGroup.isComplete&&(t+=Di.GraceBeatPadding*this.renderer.scale),this.preNotes.x=t,this.preNotes.width=e.getPreBeatSize(this.beat),this.onNotes.width=e.getOnBeatSize(this.beat),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.updateBeamingHelper(),this.updateWidth()}doLayout(){this.preNotes.x=0,this.preNotes.renderer=this.renderer,this.preNotes.container=this,this.preNotes.doLayout(),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.renderer=this.renderer,this.onNotes.container=this,this.onNotes.doLayout();let e=this.beat.notes.length-1;for(;e>=0;)this.createTies(this.beat.notes[e--]);this.updateWidth()}updateWidth(){if(this.minWidth=this.preNotes.width+this.onNotes.width,!this.beat.isRest)if(1===this.onNotes.beamingHelper.beats.length)this.beat.duration>=u.Eighth&&(this.minWidth+=20*this.scale);else switch(this.beat.duration){case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:this.minWidth+=10*this.scale}let e=0;for(let t of this.ties)t.width>e&&(e=t.width);this.minWidth+=e,this.width=this.minWidth}scaleToWidth(e){for(let e of this.ties)e.doLayout();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(Di.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 ui;a.beat=this.beat,a.visualBounds=new at,a.visualBounds.x=t+this.x+this.onNotes.x,a.visualBounds.y=e.visualBounds.y,a.visualBounds.w=this.onNotes.width,a.visualBounds.h=e.visualBounds.h,a.realBounds=new at,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,i&&(a.visualBounds.x=t+this.x,a.realBounds.x=a.visualBounds.x),e.addBeat(a),this.renderer.settings.core.includeNoteBounds&&this.onNotes.buildBoundingsLookup(a,t+this.x,s+this.y)}}Di.GraceBeatPadding=3;class Ri{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new lo}causeIssue(){return this.settings=null,!0}}class Ai{constructor(e){this.bounds=null,this.beat=e}}class Oi extends pe{constructor(e,t){super(s.General,e),this.xhr=t,Object.setPrototypeOf(this,Oi.prototype)}}class Gi{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=Gi.loadScoreFromBytes(s,i);t(r)}catch(e){s(e)}else 0===a.status?s(new Oi("You are offline!!\n Please Check Your Network.",a)):404===a.status?s(new Oi("Requested URL not found.",a)):500===a.status?s(new Oi("Internel Server Error.",a)):"parsererror"===a.statusText?s(new Oi("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?s(new Oi("Request Time out.",a)):s(new Oi("Unknow Error: "+a.responseText,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Hs);let s=ho.buildImporters();Be.debug("ScoreLoader","Loading score from "+e.length+" bytes using "+s.length+" importers",null);let i=null,a=$e.fromBuffer(e);for(let e of s){a.reset();try{Be.debug("ScoreLoader","Importing using importer "+e.name),e.init(a,t),i=e.readScore(),Be.debug("ScoreLoader","Score imported using "+e.name);break}catch(t){if(!(t instanceof ge))throw Be.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;Be.debug("ScoreLoader",e.name+" does not support the file")}}if(i)return i;throw Be.error("ScoreLoader","No compatible importer found for file"),new ge("No compatible importer found for file")}}class Vi{constructor(e){this.mouseEvent=e}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()}}class Hi{constructor(e){this._resizeListeners=0,this._lastBounds=new at,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new Vi(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new Vi(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new Vi(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&Hi.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,Hi.resizeObserver.value.unobserve(this.element))}}}get width(){return this.element.offsetWidth}set width(e){this.element.style.width=e+"px"}get scrollLeft(){return this.element.scrollLeft}set scrollLeft(e){this.element.scrollTop=e}get scrollTop(){return this.element.scrollLeft}set scrollTop(e){this.element.scrollTop=e}get height(){return this.element.offsetHeight}set height(e){this.element.style.height=e>=0?e+"px":"100%"}get isVisible(){return!!this.element.offsetWidth||!!this.element.offsetHeight||!!this.element.getClientRects().length}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=""}}Hi.resizeObserver=new we((()=>new ResizeObserver((e=>{for(const t of e){let e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class Wi{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new ms,this._family=e}checkForFontAvailability(){if(ho.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0,t=window.setInterval((()=>{e++,Be.warning("Rendering",`Could not load font '${this._family}' within ${5*e} seconds`,null)}),5e3);Be.debug("Font","Start checking for font availablility: "+this._family),Be.debug("Font",`[${this._family}] Font API available`);let s=()=>{document.fonts.load("1em "+this._family).then((()=>(Be.debug("Font",`[${this._family}] Font API signaled loaded`),document.fonts.check("1em "+this._family)?(Be.debug("Rendering",`[${this._family}] Font API signaled available`),this.isFontLoaded=!0,window.clearInterval(t),this.fontLoaded.trigger(this._family)):(Be.debug("Font",`[${this._family}] Font API loaded reported, but font not available, checking later again`,null),window.setTimeout((()=>{s()}),250)),!0)))};s()}}class zi{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 Ui{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new fs,this.samplesPlayed=new ms,this.sampleRequest=new fs}get sampleRate(){return this._context?this._context.sampleRate:Ui.PreferredSampleRate}activate(){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(Be.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{var e,t;Be.debug("WebAudio",`Audio Context resume success: state=${null===(e=this._context)||void 0===e?void 0:e.state}, sampleRate:${null===(t=this._context)||void 0===t?void 0:t.sampleRate}`)}),(e=>{var t,s;Be.debug("WebAudio",`Audio Context resume failed: state=${null===(t=this._context)||void 0===t?void 0:t.state}, sampleRate:${null===(s=this._context)||void 0===s?void 0:s.sampleRate}, reason=${e}`)})))}patchIosSampleRate(){let e=navigator.userAgent;if(-1!==e.indexOf("iPhone")||0!==e.indexOf("iPad")){let e=this.createAudioContext(),t=e.createBuffer(1,1,Ui.PreferredSampleRate),s=e.createBufferSource();s.buffer=t,s.connect(e.destination),s.start(0),s.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in ho.globalThis)return new AudioContext;if("webkitAudioContext"in ho.globalThis)return new webkitAudioContext;throw new pe(s.General,"AudioContext not found")}open(){this.patchIosSampleRate(),this._context=this.createAudioContext();let e=this._context;if("suspended"===e.state){let t=()=>{e.resume(),ho.globalThis.setTimeout((()=>{"running"===e.state&&(document.body.removeEventListener("touchend",t,!1),document.body.removeEventListener("click",t,!1))}),0)};document.body.addEventListener("touchend",t,!1),document.body.addEventListener("click",t,!1)}}play(){let e=this._context;this.activate(),this._buffer=e.createBuffer(2,Ui.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(){var e;this.pause(),null===(e=this._context)||void 0===e||e.close()}onSamplesPlayed(e){this.samplesPlayed.trigger(e)}onSampleRequest(){this.sampleRequest.trigger()}onReady(){this.ready.trigger()}}Ui.BufferSize=4096,Ui.PreferredSampleRate=44100,Ui.TotalBufferTimeInMilliseconds=5e3;class Xi extends Ui{constructor(){super(...arguments),this._audioNode=null,this._bufferCount=0,this._requestedBufferCount=0,this._outputBuffer=new Float32Array(0)}open(){super.open(),this._bufferCount=Math.floor(Ui.TotalBufferTimeInMilliseconds*this.sampleRate/1e3/Ui.BufferSize),this._circularBuffer=new zi(Ui.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*Ui.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*Ui.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),this._circularBuffer.read(a,0,Math.min(a.length,this._circularBuffer.count));let r=0;for(let e=0;e<t.length;e++)t[e]=a[r++],s[e]=a[r++];this.onSamplesPlayed(t.length),this.requestBuffers()}}class Yi{constructor(e,t){this.loaded=e,this.total=t}}class qi{constructor(e,t,s){this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=q.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 fs,this.readyForPlayback=new fs,this.finished=new fs,this.soundFontLoaded=new fs,this.soundFontLoadFailed=new ms,this.midiLoaded=new ms,this.midiLoadFailed=new ms,this.stateChanged=new ms,this.positionChanged=new ms,this.midiEventsPlayed=new ms,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=q.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();try{this._synth=ho.createAlphaTabWorker(t)}catch(e){try{this._synth=new Worker(t)}catch(e){return void Be.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:s}),this.masterVolume=1,this.playbackSpeed=1,this.metronomeVolume=0}get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return Be.logLevel}set logLevel(e){Be.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Gt.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Gt.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Gt.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=ns.clamp(e,Gt.MinPlaybackSpeed,Gt.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})}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:ni.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,s){Be.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=>{Be.error("AlphaSynth","Loading failed: "+e.message),this.soundFontLoadFailed.trigger(new Oi(e.message,i))},i.onprogress=e=>{Be.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),s(new Yi(e.loaded,e.total))},i.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:ni.midiFileToJsObject(e)})}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,Gt.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 Ut(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new ys(t.events.map(ni.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new zt(t.state,t.stopped));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 Ut(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 Ji{constructor(e,t){if(this._width=0,this.boundsLookup=null,this.preRender=new ms,this.partialRenderFinished=new ms,this.partialLayoutFinished=new ms,this.renderFinished=new ms,this.postRenderFinished=new fs,this.error=new ms,this._api=e,t.core.scriptFile){try{this._worker=ho.createAlphaTabWorker(t.core.scriptFile)}catch(e){try{this._worker=new Worker(t.core.scriptFile)}catch(t){return void Be.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))}else Be.error("Rendering","Could not detect alphaTab script file, cannot initialize renderer")}destroy(){this._worker.terminate()}updateSettings(e){this._worker.postMessage({cmd:"alphaTab.updateSettings",settings:this.serializeSettingsForWorker(e)})}serializeSettingsForWorker(e){const t=ni.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=mi.fromJson(t.boundsLookup,this._api.score),this.postRenderFinished.trigger();break;case"alphaTab.error":this.error.trigger(t.error)}}renderScore(e,t){let s=null==e?null:ni.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:s,trackIndexes:t,fontSizes:li.FontSizeLookupTables})}}class Qi{constructor(e,t,s,i){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=s,this.selectionWrapper=i}}!function(e){e[e.Browser=0]="Browser",e[e.NodeJs=1]="NodeJs",e[e.BrowserModule=2]="BrowserModule"}(se||(se={}));class ji{static init(){var e;ji._isRegistered||(ji._isRegistered=!0,registerProcessor("alphatab",((e=class e extends AudioWorkletProcessor{constructor(...t){super(...t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,Be.info("WebAudio","creating processor"),this._bufferCount=Math.floor(e.TotalBufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new zi(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){let t=e.data;switch(t.cmd){case oi.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case oi.CmdOutputResetSamples:this._circularBuffer.clear()}}process(e,t,s){if(1!==t.length&&2!==t[0].length)return!1;let i=t[0][0],a=t[0][1];if(!i||!a)return!0;let r=i.length+a.length,n=this._outputBuffer;n.length!==r&&(n=new Float32Array(r),this._outputBuffer=n),this._circularBuffer.read(n,0,Math.min(n.length,this._circularBuffer.count));let o=0;for(let e=0;e<i.length;e++)i[e]=n[o++],a[e]=n[o++];return this.port.postMessage({cmd:oi.CmdOutputSamplesPlayed,samples:i.length}),this.requestBuffers(),!0}requestBuffers(){const t=this._bufferCount/2|0;let s=t*e.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*e.BufferSize<s){for(let e=0;e<t;e++)this.port.postMessage({cmd:oi.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e.TotalBufferTimeInMilliseconds=5e3,e)))}}ji._isRegistered=!1;class Ki extends Ui{constructor(){super(...arguments),this._worklet=null}open(){super.open(),this.onReady()}play(){super.play();let e=this._context;e.audioWorklet.addModule(ho.scriptFile).then((()=>{this._worklet=new AudioWorkletNode(e,"alphatab",{numberOfOutputs:1,outputChannelCount:[2]}),this._worklet.port.onmessage=this.handleMessage.bind(this),this._source.connect(this._worklet),this._source.start(0),this._worklet.connect(e.destination)}),(e=>{Be.error("WebAudio","Audio Worklet creation failed: reason="+e)}))}handleMessage(e){let t=e.data;switch(t.cmd){case oi.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case oi.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){var t;null===(t=this._worklet)||void 0===t||t.port.postMessage({cmd:oi.CmdOutputAddSamples,samples:e})}resetSamples(){var e;null===(e=this._worklet)||void 0===e||e.port.postMessage({cmd:oi.CmdOutputResetSamples})}}!function(e){e[e.LayoutDone=0]="LayoutDone",e[e.RenderRequested=1]="RenderRequested",e[e.RenderDone=2]="RenderDone",e[e.Detached=3]="Detached"}(ie||(ie={}));class $i{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 fs,this.canRenderChanged=new fs,this._highlightedElements=[],this._scrollContainer=null,ho.webPlatform!==se.Browser&&ho.webPlatform!==se.BrowserModule)throw new pe(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 Hi(e),this.areWorkersSupported="Worker"in window,ho.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(e)}get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(ho.bravuraFontChecker.checkForFontAvailability(),!ho.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(Be.debug("Font","All fonts loaded: "+this._fontCheckers.size),!0)}onFontLoaded(e){li.generateFontLookup(e),this.areAllFontsLoaded()&&this.canRenderChanged.trigger()}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)?this._api.renderer.renderResult(s.layoutResultId):e.replaceChildren():s.resultState===ie.Detached&&(e.replaceChildren(...s.renderedResult),s.resultState=ie.RenderDone):s.resultState===ie.RenderDone&&(s.resultState=ie.Detached,s.replaceChildren())}}}createWorkerRenderer(){return new Ji(this._api,this._api.settings)}initialize(e,t){let s;this._api=e,s=t instanceof Hs?t:ni.jsObjectToSettings(t);let i=this.getDataAttributes();Vs.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.family)){let t=new Wi(e.family);this._fontCheckers.set(e.family,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 Hi(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 He)return t(e),!0;if(e instanceof ArrayBuffer){let s=new Uint8Array(e);return t(Gi.loadScoreFromBytes(s,this._api.settings)),!0}return e instanceof Uint8Array?(t(Gi.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(Gi.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=()=>{var e;this._api.renderer.width=0|this.rootContainer.width,this._api.renderer.updateSettings(this._api.settings),this._contents?(this._api.tex(this._contents,null!==(e=this._initialTrackIndexes)&&void 0!==e?e:void 0),this._initialTrackIndexes=null):this._file&&Gi.loadScoreAsync(this._file,(e=>{var t;this._api.renderScore(e,null!==(t=this._initialTrackIndexes)&&void 0!==t?t: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;ho.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=ie.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=ie.LayoutDone,delete s.renderedResultId,delete s.renderedResult,this._resultIdToElementLookup.set(e.id,s);for(let t=e.firstMasterBarIndex;t<=e.lastMasterBarIndex;t++)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.lastChild)}createWorkerPlayer(){let e=ho.scriptFile;if(!e)return Be.error("Player","alphaTab script file could not be detected, player cannot initialize"),null;let t=null,s="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window?(Be.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),t=new qi(new Ki,e,this._api.settings.core.logLevel)):s&&(Be.debug("Player","Will use webworkers for synthesizing and web audio api for playback"),t=new qi(new Xi,e,this._api.settings.core.logLevel)),t?t.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):Be.error("Player","Player requires webworkers and web audio api, browser unsupported",null),t}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const s=this._barToElementLookup.get(t);if(s){let t=s.getElementsByClassName(e);for(let e=0;e<t.length;e++)t.item(e).classList.add("at-highlight"),this._highlightedElements.push(t.item(e))}}removeHighlights(){const e=this._highlightedElements;if(e){for(const t of e)t.classList.remove("at-highlight");this._highlightedElements=[]}}destroyCursors(){let e=this._api.container.element,t=e.querySelector(".at-cursors");e.removeChild(t)}createCursors(){let e=this._api.container.element,t=document.createElement("div");t.classList.add("at-cursors");let s=document.createElement("div");s.classList.add("at-selection");let i=document.createElement("div");i.classList.add("at-cursor-bar");let a=document.createElement("div");return a.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",i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.willChange="transform",i.style.width="1px",i.style.height="1px",a.style.position="absolute",a.style.transition="all 0s linear",a.style.left="0",a.style.top="0",a.style.willChange="transform",a.style.width="3px",a.style.height="1px",e.insertBefore(t,e.firstChild),t.appendChild(s),t.appendChild(i),t.appendChild(a),new Qi(new Hi(t),new Hi(i),new Hi(a),new Hi(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 at;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 Hi(e),this._scrollContainer}createSelectionElement(){let e=document.createElement("div");return e.style.position="absolute",e.style.width="1px",e.style.height="1px",new Hi(e)}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 Zi extends class{constructor(e,t){this._startTime=0,this._trackIndexes=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=q.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=q.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new ms,this._beatMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new ms,this.beatMouseMove=new ms,this.beatMouseUp=new ms,this.scoreLoaded=new ms,this.resize=new ms,this.renderStarted=new ms,this.renderFinished=new ms,this.postRenderFinished=new fs,this.error=new ms,this.playerReady=new fs,this.playerFinished=new fs,this.soundFontLoaded=new fs,this.midiLoad=new ms,this.midiLoaded=new ms,this.playerStateChanged=new ms,this.playerPositionChanged=new ms,this.midiEventsPlayed=new ms,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),Be.logLevel=this.settings.core.logLevel,this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&ho.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new yi(this.settings),this.container.resize.on(ho.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));let s=new Ri;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;Be.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(){this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?this.setupPlayer():this.destroyPlayer()}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 pe(s.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(t,e)}}internalRenderTracks(e,t){if(e!==this.score){ke.applyPitchOffsets(this.settings,e),this.score=e,this.tracks=t,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this.onScoreLoaded(e),this.loadMidiForScore(),this.render()}else{this.tracks=t,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this.render()}}triggerResize(){if(this.container.isVisible){let e=new Ri;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 Be.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{Be.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)),this.uiFacade.beginAppendRenderResults(e)}updateRenderResult(e){e&&e.renderResult&&this.uiFacade.beginUpdateRenderResults(e)}tex(e,t){try{let s=new et;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 isReadyForPlayback(){return!!this.player&&this.player.isReadyForPlayback}get playerState(){return this.player?this.player.state:q.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.destroyCursors())}setupPlayer(){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.finished.on(this.onPlayerFinished.bind(this)),this.settings.player.enableCursor?this.setupCursors():this.destroyCursors()))}loadMidiForScore(){if(!this.player||!this.score||!this.player.isReady)return;Be.debug("AlphaTab","Generating Midi");let e=new Ss,t=new wi(e),s=new Pi(this.score,this.settings,t);s.generate(),this._tickCache=s.tickLookup,this.onMidiLoad(e),this.player.loadMidiFile(e)}changeTrackVolume(e,t){if(this.player)for(let s of e)this.player.setChannelVolume(s.playbackInfo.primaryChannel,t),this.player.setChannelVolume(s.playbackInfo.secondaryChannel,t)}changeTrackSolo(e,t){if(this.player)for(let s of e)this.player.setChannelSolo(s.playbackInfo.primaryChannel,t),this.player.setChannelSolo(s.playbackInfo.secondaryChannel,t)}changeTrackMute(e,t){if(this.player)for(let s of e)this.player.setChannelMute(s.playbackInfo.primaryChannel,t),this.player.setChannelMute(s.playbackInfo.secondaryChannel,t)}play(){return!!this.player&&this.player.play()}pause(){this.player&&this.player.pause()}playPause(){this.player&&this.player.playPause()}stop(){this.player&&this.player.stop()}playBeat(e){if(!this.player)return;let t=new Ss,s=new wi(t);new Pi(e.voice.bar.staff.track.score,this.settings,s).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;let t=new Ss,s=new wi(t);new Pi(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,this._previousTick=0,this._playerState=q.Paused)}setupCursors(){let e=this.uiFacade.createCursors();e&&(this._cursorWrapper=e.cursorWrapper,this._barCursor=e.barCursor,this._beatCursor=e.beatCursor,this._selectionWrapper=e.selectionWrapper,this._previousTick=0,this._playerState=q.Paused,this.renderer.postRenderFinished.on((()=>{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===q.Paused){let e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getMasterBarStart(e.currentBeat.voice.bar.masterBar)+e.currentBeat.playbackStart)}}))))}cursorUpdateTick(e,t,s=!1){let i=this._tickCache;if(i){let a=this.tracks;if(a.length>0){let r=i.findBeat(a,e,this._currentBeat);r&&this.cursorUpdateBeat(r,t,s)}}}cursorUpdateBeat(e,t,s){const i=e.currentBeat,a=e.nextBeat,r=e.duration,n=e.beatsToHighlight;if(!i)return;let o=this.renderer.boundsLookup;if(!o)return;let h=this._currentBeat,l=this._previousCursorCache,c=this._previousStateForCursor;if(i===(null==h?void 0:h.currentBeat)&&o===l&&c===this._playerState)return;let d=o.findBeat(i);d&&(this._currentBeat=e,this._previousCursorCache=o,this._previousStateForCursor=this._playerState,this.uiFacade.beginInvoke((()=>{this.internalCursorUpdateBeat(i,a,r,t,n,o,d,s)})))}scrollToCursor(){const e=this._currentBarBounds;e&&this.internalScrollToCursor(e)}internalScrollToCursor(e){let t=this.uiFacade.getScrollContainer(),s=ho.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 ee.Continuous:let i=this.uiFacade.getOffset(t,this.container);this.uiFacade.scrollToY(t,i.y+s,this.settings.player.scrollSpeed);break;case ee.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 ee.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 ee.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){let h=this._barCursor,l=this._beatCursor,c=n.barBounds.masterBarBounds,d=c.visualBounds;this._currentBarBounds=c,h.setBounds(d.x,d.y,d.w,d.h),this.settings.player.enableAnimatedBeatCursor&&l.stopAnimation(),l.setBounds(n.visualBounds.x,d.y,1,d.h),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let u=!1;if(this._playerState===q.Playing&&!i){if(this.settings.player.enableElementHighlighting&&a)for(let t of a){let s=Di.getGroupId(t);this.uiFacade.highlightElements(s,e.voice.bar.index)}if(this.settings.player.enableAnimatedBeatCursor){let i=c.visualBounds.x+c.visualBounds.w;if(t&&(t.voice.bar.index===e.voice.bar.index&&t.index>e.index||t.voice.bar.index===e.voice.bar.index+1)){let e=r.findBeat(t);e&&e.barBounds.masterBarBounds.staveGroupBounds===c.staveGroupBounds&&(i=e.visualBounds.x)}this.uiFacade.beginInvoke((()=>{l.transitionToX(s/this.playbackSpeed,i)}))}o=!i,u=!0}o&&!this._beatMouseDown&&this.settings.player.scrollMode!==ee.Off&&this.internalScrollToCursor(c),u&&this.onPlayedBeatChanged(e)}onPlayedBeatChanged(e){this._isDestroyed||(this.playedBeatChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playedBeatChanged",e))}onBeatMouseDown(e,t){this._isDestroyed||(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&(this._selectionStart=new Ai(t),this._selectionEnd=null),this._beatMouseDown=!0,this.beatMouseDown.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseDown",t,e))}onBeatMouseMove(e,t){this._isDestroyed||(this.settings.player.enableUserInteraction&&(this._selectionEnd&&this._selectionEnd.beat===t||(this._selectionEnd=new Ai(t),this.cursorSelectRange(this._selectionStart,this._selectionEnd))),this.beatMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseMove",t,e))}onBeatMouseUp(e,t){if(!this._isDestroyed){if(this.settings.player.enableUserInteraction){if(this._selectionEnd){let e=this._selectionStart.beat.absolutePlaybackStart;if(this._selectionStart.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===q.Paused&&this.cursorUpdateTick(this._selectionStart.beat.absolutePlaybackStart,!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 Ei;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}}updateSelectionCursor(e){if(this._tickCache)if(e){const t=this._tickCache.findBeat(this.tracks,e.startTick),s=this._tickCache.findBeat(this.tracks,e.endTick);if(t&&s){const e=new Ai(t.currentBeat),i=new Ai(s.currentBeat);this.cursorSelectRange(e,i)}}else this.cursorSelectRange(null,null)}setupClickHandling(){this.canvasElement.mouseDown.on((e=>{var t,s;if(!e.isLeftMouseButton)return;this.settings.player.enableUserInteraction&&e.preventDefault();let i=e.getX(this.canvasElement),a=e.getY(this.canvasElement),r=null!==(s=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(i,a))&&void 0!==s?s:null;r&&this.onBeatMouseDown(e,r)})),this.canvasElement.mouseMove.on((e=>{var t,s;if(!this._beatMouseDown)return;let i=e.getX(this.canvasElement),a=e.getY(this.canvasElement),r=null!==(s=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(i,a))&&void 0!==s?s:null;r&&this.onBeatMouseMove(e,r)})),this.canvasElement.mouseUp.on((e=>{var t,s;if(!this._beatMouseDown)return;this.settings.player.enableUserInteraction&&e.preventDefault();let i=e.getX(this.canvasElement),a=e.getY(this.canvasElement),r=null!==(s=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(i,a))&&void 0!==s?s:null;this.onBeatMouseUp(e,r)})),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=e.beat.absolutePlaybackStart;if(t.beat.absolutePlaybackStart<a){let s=e;e=t,t=s}let r=e.bounds.realBounds.x,n=t.bounds.realBounds.x+t.bounds.realBounds.w;if(t.beat.index===t.beat.voice.beats.length-1&&(n=t.bounds.barBounds.masterBarBounds.realBounds.x+t.bounds.barBounds.masterBarBounds.realBounds.w),e.bounds.barBounds.masterBarBounds.staveGroupBounds!==t.bounds.barBounds.masterBarBounds.staveGroupBounds){let a=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x,o=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x+e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.w,h=this.uiFacade.createSelectionElement();h.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,o-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(h);let l=e.bounds.barBounds.masterBarBounds.staveGroupBounds.index+1,c=t.bounds.barBounds.masterBarBounds.staveGroupBounds.index;for(let e=l;e<c;e++){let t=s.staveGroups[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),i.appendChild(r)}let d=this.uiFacade.createSelectionElement();d.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(d)}else{let t=this.uiFacade.createSelectionElement();t.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,n-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(t)}}onScoreLoaded(e){this._isDestroyed||(this.scoreLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"scoreLoaded",e))}onResize(e){this._isDestroyed||(this.resize.trigger(e),this.uiFacade.triggerEvent(this.container,"resize",e))}onRenderStarted(e){this._isDestroyed||(this.renderStarted.trigger(e),this.uiFacade.triggerEvent(this.container,"renderStarted",e))}onRenderFinished(e){this._isDestroyed||(this.renderFinished.trigger(e),this.uiFacade.triggerEvent(this.container,"renderFinished",e))}onPostRenderFinished(){this._isDestroyed||(this.postRenderFinished.trigger(),this.uiFacade.triggerEvent(this.container,"postRenderFinished",null))}onError(e){this._isDestroyed||(Be.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))}}{constructor(e,t){super(new $i(e),t),this.soundFontLoad=new ms}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("<!DOCTYPE html><html></head><body></body></html>"),i.document.body.appendChild(a);let r=void 0!==window.screenLeft?window.screenLeft:window.left,n=void 0!==window.screenTop?window.screenTop:window.top,o="innerWidth"in window?window.innerWidth:"clientWidth"in document.documentElement?document.documentElement.clientWidth:window.screen.width,h="innerHeight"in window?window.innerHeight:"clientHeight"in document.documentElement?document.documentElement.clientHeight:window.screen.height,l=a.offsetWidth+50,c=window.innerHeight,d=(o/2|0)-(l/2|0)+r,u=(h/2|0)-(c/2|0)+n;i.resizeTo(l,c),i.moveTo(d,u),i.focus();let p=ni.jsObjectToSettings(ni.settingsToJsObject(this.settings));p.core.enableLazyLoading=!1,p.core.useWorkers=!1,p.display.scale=.8,p.display.stretchForce=.8,Vs.fromJson(p,s);let g=new Zi(a,p);g.renderer.postRenderFinished.on((()=>{g.canvasElement.height=-1,i.print()})),g.renderTracks(this.tracks)}downloadMidi(){if(!this.score)return;let e=new Ss,t=new wi(e);new Pi(this.score,this.settings,t).generate();let s=e.toBinary(),i=this.score.title?this.score.title+".mid":"File.mid",a=document.createElement("a");a.download=i;let r=new Blob([s],{type:"audio/midi"}),n=URL.createObjectURL(r);a.href=n,a.style.display="none",document.body.appendChild(a),a.click(),document.body.removeChild(a)}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 ea{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 Be.error("Api","Method '"+t+"' does not exist on jQuery.alphaTab"),null}init(e,t,s){if(!t){t=new Zi(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 ta{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.color=new Ue(255,255,255,255),this.lineWidth=1,this.font=new vs("Arial",10,$.Plain),this.textAlign=P.Left,this.textBaseline=E.Top}beginRender(e,t){this.buffer=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${0|e}px" height="${0|t}px" class="at-surface-svg">\n`,this._currentPath="",this._currentPathIsEmpty=!0,this.textBaseline=E.Top}beginGroup(e){this.buffer+=`<g class="${e}">`}endGroup(){this.buffer+="</g>"}endRender(){return this.buffer+="</svg>",this.buffer}fillRect(e,t,s,i){s>0&&(this.buffer+=`<rect x="${0|e}" y="${0|t}" width="${s}" height="${i}" fill="${this.color.rgba}" />\n`)}strokeRect(e,t,s,i){this.buffer+=`<rect x="${0|e}" y="${0|t}" width="${s}" height="${i}" stroke="${this.color.rgba}"`,1!==this.lineWidth&&(this.buffer+=` stroke-width="${this.lineWidth}"`),this.buffer+=' fill="transparent" />\n'}beginPath(){}closePath(){this._currentPath+=" z"}moveTo(e,t){this._currentPath+=` M${e},${t}`}lineTo(e,t){this._currentPathIsEmpty=!1,this._currentPath+=` L${e},${t}`}quadraticCurveTo(e,t,s,i){this._currentPathIsEmpty=!1,this._currentPath+=` Q${e},${t},${s},${i}`}bezierCurveTo(e,t,s,i,a,r){this._currentPathIsEmpty=!1,this._currentPath+=` C${e},${t},${s},${i},${a},${r}`}fillCircle(e,t,s){this._currentPathIsEmpty=!1,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.fill()}strokeCircle(e,t,s){this._currentPathIsEmpty=!1,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.stroke()}fill(){this._currentPathIsEmpty||(this.buffer+=`<path d="${this._currentPath}"`,"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),this.buffer+=' style="stroke: none"/>'),this._currentPath="",this._currentPathIsEmpty=!0}stroke(){if(!this._currentPathIsEmpty){let e=`<path d="${this._currentPath}" stroke="${this.color.rgba}"`;1!==this.lineWidth&&(e+=` stroke-width="${this.lineWidth}"`),e+=' style="fill: none" />',this.buffer+=e}this._currentPath="",this._currentPathIsEmpty=!0}fillText(e,t,s){if(""===e)return;let i=`<text x="${0|t}" y="${0|s}" style="stroke: none; font:${this.font.toCssString(this.settings.display.scale)}" ${this.getSvgBaseLine()}`;"#000000"!==this.color.rgba&&(i+=` fill="${this.color.rgba}"`),this.textAlign!==P.Left&&(i+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),i+=`>${ta.escapeText(e)}</text>`,this.buffer+=i}static escapeText(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}getSvgTextAlignment(e){switch(e){case P.Left:return"start";case P.Center:return"middle";case P.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case E.Top:return'dominant-baseline="hanging"';case E.Bottom:return'dominant-baseline="bottom"';default:return""}}measureText(e){return e?li.measureString(e,this.font.family,this.font.size,this.font.style,this.font.weight):0}onRenderFinished(){return null}beginRotate(e,t,s){this.buffer+='<g transform="translate('+e+" ,"+t+") rotate( "+s+')">'}endRotate(){this.buffer+="</g>"}}class sa extends ta{constructor(){super()}fillMusicFontSymbol(e,t,s,i,a){i!==N.None&&this.fillMusicFontSymbolText(e,t,s,`&#${i};`,a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(let e of i)e!==N.None&&(r+=`&#${e};`);this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){this.buffer+=`<g transform="translate(${e} ${t})" class="at" ><text`,this.buffer+=1!==s?` style="font-size: ${100*s}%; stroke:none"`:' style="stroke:none"',"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),a&&(this.buffer+=' text-anchor="'+this.getSvgTextAlignment(P.Center)+'"'),this.buffer+=`>${i}</text></g>`}}class ia{constructor(){this.isInAccolade=!0,this.isRelevantForBoundsLookup=!0,this.hideOnMultiTrack=!1,this.hideOnPercussionTrack=!1}canCreate(e,t){return!this.hideOnPercussionTrack||!t.isPercussion}}!function(e){e[e.PreNotes=0]="PreNotes",e[e.OnNotes=1]="OnNotes",e[e.MiddleNotes=2]="MiddleNotes",e[e.Stem=3]="Stem",e[e.PostNotes=4]="PostNotes",e[e.EndBeat=5]="EndBeat"}(ae||(ae={}));class aa extends Ci{constructor(e,t){super(e,t),this.glyphs=null}get isEmpty(){return!this.glyphs||0===this.glyphs.length}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);let e=0;for(let t=0,s=this.glyphs.length;t<s;t++){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 ra extends aa{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 na extends aa{constructor(e,t,s){super(e,t),this.voice=s,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){const t=this.renderer.scale;let s=this.renderer.layoutingInfo.spaceToForce(e/t);this.scaleToForce(s)}scaleToForce(e){const t=this.renderer.scale;this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e)*t;let s=this.renderer.layoutingInfo.buildOnTimePositions(e),i=this.beatGlyphs;for(let e=0,a=i.length;e<a;e++){let r=i[e];switch(r.beat.graceType){case g.None:r.x=s.get(r.beat.absoluteDisplayStart)*t-r.onTimeX;break;default:const a=r.beat.graceGroup.beats[0].absoluteDisplayStart,n=r.beat.graceGroup.id;if(r.beat.graceGroup.isComplete&&s.has(a)){r.x=s.get(a)*t-r.onTimeX;let e=this.renderer.layoutingInfo.allGraceRods.get(n),i=this.renderer.layoutingInfo.springs.get(a).preBeatWidth;r.x-=i,r.x-=e[r.beat.graceIndex].postSpringWidth,r.x+=e[r.beat.graceIndex].graceBeatWidth;const o=e[r.beat.graceGroup.beats.length-1];r.x-=o.graceBeatWidth}else{let t=this.renderer.layoutingInfo.incompleteGraceRods.get(n);const s=t[r.beat.graceIndex].postSpringWidth-t[r.beat.graceIndex].preSpringWidth;e>0?0===r.beat.graceIndex?r.x=i[e-1].x+i[e-1].width:r.x=i[e-1].x+t[r.beat.graceIndex-1].postSpringWidth-t[r.beat.graceIndex-1].preSpringWidth-s:r.x=-s}}if(e>0){let t=r.x-i[e-1].x;i[e-1].scaleToWidth(t)}if(e===a-1){let e=this.width-i[i.length-1].x;r.scaleToWidth(e)}}}registerLayoutingInfo(e){e.updateVoiceSize(this.width);let t=this.beatGlyphs;for(let s of t)s.registerLayoutingInfo(e)}applyLayoutingInfo(e){let t=this.beatGlyphs;for(let s of t)s.applyLayoutingInfo(e);this.scaleToForce(Math.max(this.renderer.settings.display.stretchForce,e.minStretchForce))}addGlyph(e){let t=e;e.x=0===this.beatGlyphs.length?0:this.beatGlyphs[this.beatGlyphs.length-1].x+this.beatGlyphs[this.beatGlyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.beatGlyphs.push(t),this.width=e.x+e.width,t.beat.hasTuplet&&t.beat.tupletGroup.beats[0].id===t.beat.id&&this.tupletGroups.push(t.beat.tupletGroup)}doLayout(){}paint(e,t,s){s.color=0===this.voice.index?this.renderer.resources.mainGlyphColor:this.renderer.resources.secondaryGlyphColor;for(let i=0,a=this.beatGlyphs.length;i<a;i++)this.beatGlyphs[i].paint(e+this.x,t+this.y,s)}}na.KeySizeBeat="Beat",function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Sharp=2]="Sharp",e[e.Flat=3]="Flat",e[e.NaturalQuarterNoteUp=4]="NaturalQuarterNoteUp",e[e.SharpQuarterNoteUp=5]="SharpQuarterNoteUp",e[e.FlatQuarterNoteUp=6]="FlatQuarterNoteUp",e[e.DoubleSharp=7]="DoubleSharp",e[e.DoubleFlat=8]="DoubleFlat"}(re||(re={}));class oa{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class ha{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){var s,i;return t<e.staff.track.percussionArticulations.length?e.staff.track.percussionArticulations[t].staffLine:null!==(i=null===(s=xe.getArticulationByValue(t))||void 0===s?void 0:s.staffLine)&&void 0!==i?i:0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case y.ForceDoubleFlat:t+=2;break;case y.ForceDoubleSharp:t-=2;break;case y.ForceFlat:t+=1;break;case y.ForceSharp:t-=1}return t}applyAccidental(e){const t=ha.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=ha.getNoteValue(t);if(e.staff.isPercussion)s=ha.getPercussionLine(e,i);else{const a=t?t.accidentalMode:y.Default;s=ha.calculateNoteLine(e,i,a)}return s}getAccidental(e,t,s,i,a=null){let r=re.None,n=0;if(this._bar.staff.isPercussion)n=ha.getPercussionLine(this._bar,e);else{const s=a?a.accidentalMode:y.Default;n=ha.calculateNoteLine(this._bar,e,s);let i=this._bar.masterBar.keySignature+7,o=e%12,h=i<7?re.Flat:re.Sharp,l=ha.KeySignatureLookup[i][o],c=ha.AccidentalNotes[o];if(t)switch(r=c?h:re.Natural,r){case re.Natural:r=re.NaturalQuarterNoteUp;break;case re.Sharp:r=re.SharpQuarterNoteUp;break;case re.Flat:r=re.FlatQuarterNoteUp}else{switch(s){case y.ForceSharp:r=re.Sharp;break;case y.ForceDoubleSharp:r=re.DoubleSharp;break;case y.ForceFlat:r=re.Flat;break;case y.ForceDoubleFlat:r=re.DoubleFlat;break;default:c?r=h:l&&(r=re.Natural)}let e=!1;if(a&&a.isTieDestination&&0===a.beat.index){const t=this._barRenderer.previousRenderer;if(t){t.accidentalHelper.getNoteLine(a.tieOrigin)===n&&(e=!0)}}e?r=re.None:r!==re.None?(this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===r&&(r=re.None):l&&r===h&&(r=re.None),r!==re.None&&this._registeredAccidentals.set(n,r)):this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===re.Natural?r=re.None:(r=re.Natural,this._registeredAccidentals.set(n,r)):this._registeredAccidentals.delete(n)}}return a?(this._appliedScoreLines.set(a.id,n),this._notesByValue.set(e,a)):this._appliedScoreLinesByValue.set(e,n),(-1e3===this.minLine||this.minLine<n)&&(this.minLine=n,this.minLineBeat=s),(-1e3===this.maxLine||this.maxLine>n)&&(this.maxLine=n,this.maxLineBeat=s),i||this.registerLine(s,n),r}registerLine(e,t){let s;this._beatLines.has(e.id)?s=this._beatLines.get(e.id):(s=new oa,this._beatLines.set(e.id,s)),(-1e3===s.minLine||t<s.minLine)&&(s.minLine=t),(-1e3===s.minLine||t>s.maxLine)&&(s.maxLine=t)}getMaxLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).maxLine:0}getMinLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).minLine:0}static calculateNoteLine(e,t,s){let i=t,a=e.masterBar.keySignature,r=e.clef,n=i%12,o=(i/12|0)-1,h=ha.OctaveSteps[r];return h-=o*ha.StepsPerOctave,h-=(ke.keySignatureIsSharp(a)||ke.keySignatureIsNatural(a)?ha.SharpNoteSteps:ha.FlatNoteSteps)[n],h}getNoteLine(e){return this._appliedScoreLines.get(e.id)}getNoteLineForValue(e,t=!1){return this._appliedScoreLinesByValue.has(e)?this._appliedScoreLinesByValue.get(e):t&&this._notesByValue.has(e)?this.getNoteLine(this._notesByValue.get(e)):0}}ha.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]],ha.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],ha.StepsPerOctave=7,ha.OctaveSteps=[38,32,30,26,38],ha.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],ha.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class la{constructor(){this.staffId="",this.up=0,this.down=0}}class ca{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 da{constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=u.QuadrupleWhole,this.fingeringCount=0,this.hasTuplet=!1,this._firstBeatLowestNoteCompareValue=-1,this._firstBeatHighestNoteCompareValue=-1,this._lastBeatLowestNoteCompareValue=-1,this._lastBeatHighestNoteCompareValue=-1,this.lowestNoteInHelper=null,this._lowestNoteCompareValueInHelper=-1,this.highestNoteInHelper=null,this._highestNoteCompareValueInHelper=-1,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isGrace=!1,this.minRestLine=null,this.beatOfMinRestLine=null,this.maxRestLine=null,this.beatOfMaxRestLine=null,this.direction=H.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}get hasLine(){return 1===this.beats.length&&this.beats[0].duration>u.Whole}get hasFlag(){return 1===this.beats.length&&!this.beats[0].isRest&&(this.beats[0].duration>u.Quarter||this.beats[0].graceType!==g.None)}getBeatLineX(e){return this.hasBeatLineX(e)?this.direction===H.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 la),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(H.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==g.None)&&(e=this.invert(H.Up)):e=H.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){let t=this._renderer.getNoteY(this.highestNoteInHelper,ne.Center),s=this._renderer.getNoteY(this.lowestNoteInHelper,ne.Center);if(null===e){const i=(t+s)/2;e=this.invert(this._renderer.middleYPosition<i?H.Up:H.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(H.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:return[2,2];case u.Whole:return[0,1];case u.Half:return[1,0];case u.Quarter:return[3,3];case u.Eighth:return[2,2];case u.Sixteenth:return[2,4];case u.ThirtySecond:return[4,4];case u.SixtyFourth:return[4,6];case u.OneHundredTwentyEighth:return[6,6];case u.TwoHundredFiftySixth:return[6,8]}return[0,0]}applyRest(e,t){if(this._lastNonRestBeat&&e.index>=this._lastNonRestBeat.index||this._firstNonRestBeat&&e.index<=this._firstNonRestBeat.index)return;let s=t,i=t;const a=da.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){if(!this.invertBeamDirection)return e;switch(e){case H.Down:return H.Up;default:return H.Down}}checkBeat(e){e.invertBeamDirection&&(this.invertBeamDirection=!0),this.voice||(this.voice=e.voice);let t=!1;if(0===this.beats.length)t=!0;else switch(this.beats[this.beats.length-1].beamingMode){case F.Auto:t=da.canJoin(this.beats[this.beats.length-1],e);break;case F.ForceSplitToNext:t=!1;break;case F.ForceMergeWithNext:t=!0}if(t){if(null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.isRest)0===this.beats.length&&this.beats.push(e);else{this.isRestBeamHelper&&(this.beats=[]),this.beats.push(e),e.graceType!==g.None&&(this.isGrace=!0),e.hasTuplet&&(this.hasTuplet=!0);let t=0;for(let s=0;s<e.notes.length;s++){let i=e.notes[s];i.leftHandFinger===f.Unknown&&i.rightHandFinger===f.Unknown||t++}t>this.fingeringCount&&(this.fingeringCount=t),this.checkNote(e.minNote),this.checkNote(e.maxNote),this.shortestDuration<e.duration&&(this.shortestDuration=e.duration),this._firstNonRestBeat||(this._firstNonRestBeat=e),this._lastNonRestBeat=e}e.hasTuplet&&(this.hasTuplet=!0)}return t}checkNote(e){if(!e)return;let t,s;this.voice&&e.isPercussion?(t=-ha.getPercussionLine(this.voice.bar,ha.getNoteValue(e)),s=t):(t=ha.getNoteValue(e),s=t,e.harmonicType!==m.None&&e.harmonicType!==m.Natural&&(s=e.realValue-this._staff.displayTranspositionPitch)),1===this.beats.length&&this.beats[0]===e.beat&&((-1===this._firstBeatLowestNoteCompareValue||t<this._firstBeatLowestNoteCompareValue)&&(this._firstBeatLowestNoteCompareValue=t),(-1===this._firstBeatHighestNoteCompareValue||s>this._firstBeatHighestNoteCompareValue)&&(this._firstBeatHighestNoteCompareValue=s)),(-1===this._lastBeatLowestNoteCompareValue||t<this._lastBeatLowestNoteCompareValue)&&(this._lastBeatLowestNoteCompareValue=t),(-1===this._lastBeatHighestNoteCompareValue||s>this._lastBeatHighestNoteCompareValue)&&(this._lastBeatHighestNoteCompareValue=s),(!this.lowestNoteInHelper||t<this._lowestNoteCompareValueInHelper)&&(this.lowestNoteInHelper=e,this._lowestNoteCompareValueInHelper=t),(!this.highestNoteInHelper||s>this._highestNoteCompareValueInHelper)&&(this.highestNoteInHelper=e,this._highestNoteCompareValueInHelper=s)}static canJoin(e,t){if(!e||!t||e.graceType!==t.graceType||e.graceType===g.BendGrace||t.graceType===g.BendGrace)return!1;if(e.graceType!==g.None&&t.graceType!==g.None)return!0;let s=e.voice.bar;if(s!==t.voice.bar)return!1;let i=e.playbackStart,a=t.playbackStart;if(!da.canJoinDuration(e.duration)||!da.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=ye.QuarterTime;switch(s.masterBar.timeSignatureDenominator){case 8:s.masterBar.timeSignatureNumerator%3==0&&(r+=ye.QuarterTime/2|0)}return(0|(r+i)/r)===(0|(r+a)/r)}static canJoinDuration(e){switch(e){case u.Whole:case u.Half:case u.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,s){return ke.getIndex(e.duration)-2-s>0&&ke.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 ua{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class pa{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new ua(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 ga{constructor(){this.reservedLayoutAreasByDisplayTime=new Map,this.restDurationsByDisplayTime=new Map}getBeatMinMaxY(){let e=-1e3,t=-1e3;for(const s of this.reservedLayoutAreasByDisplayTime.values())-1e3===e?(e=s.topY,t=s.bottomY):(e>s.topY&&(e=s.topY),t<s.bottomY&&(t=s.bottomY));return-1e3===e?[0,0]:[e,t]}reserveBeatSlot(e,t,s){t!=s&&(this.reservedLayoutAreasByDisplayTime.has(e.displayStart)||this.reservedLayoutAreasByDisplayTime.set(e.displayStart,new pa(e)),this.reservedLayoutAreasByDisplayTime.get(e.displayStart).addSlot(t,s),e.isRest&&this.registerRest(e))}registerRest(e){this.restDurationsByDisplayTime.has(e.displayStart)||this.restDurationsByDisplayTime.set(e.displayStart,new Map),this.restDurationsByDisplayTime.get(e.displayStart).has(e.playbackDuration)||this.restDurationsByDisplayTime.get(e.displayStart).set(e.playbackDuration,e.id)}applyRestCollisionOffset(e,t,s){if(e.voice.index>0&&this.reservedLayoutAreasByDisplayTime.has(e.playbackStart)){const i=da.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 fa{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this._renderer=e,this.collisionHelper=new ga}initialize(){var e=this._renderer,t=this._renderer.bar;let s=null,i=null;for(let a=0,r=t.voices.length;a<r;a++){let r=t.voices[a];this.beamHelpers.push([]),this.beamHelperLookup.push(new Map);for(let a=0,n=r.beats.length;a<n;a++){let n,o=r.beats[a];o.graceType!==g.None?n=i:(n=s,i=null),n&&n.checkBeat(o)||(n&&n.finish(),n=new da(t.staff,e),n.checkBeat(o),o.graceType!==g.None?i=n:s=n,this.beamHelpers[r.index].push(n)),this.beamHelperLookup[r.index].set(o.index,n)}s&&s.finish(),i&&i.finish(),s=null,i=null}}getBeamingHelperForBeat(e){return this.beamHelperLookup[e.voice.index].get(e.index)}}!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"}(ne||(ne={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(oe||(oe={}));class ma{constructor(e,t){this._preBeatGlyphs=new ra,this._voiceContainers=new Map,this._postBeatGlyphs=new ra,this.x=0,this.y=0,this.width=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 fa(this))}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}get middleYPosition(){return 0}registerOverflowTop(e){e>this.topOverflow&&(this.topOverflow=e)}registerOverflowBottom(e){e>this.bottomOverflow&&(this.bottomOverflow=e)}scaleToWidth(e){let t=e-this._preBeatGlyphs.width-this._postBeatGlyphs.width;for(const e of this._voiceContainers.values())e.scaleToWidth(t);this._postBeatGlyphs.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width+t,this.width=e}get resources(){return this.settings.display.resources}get settings(){return this.scoreRenderer.settings}get scale(){return this.settings.display.scale}get 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);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)}return this._postBeatGlyphs.x=Math.floor(e),this._postBeatGlyphs.width=this.layoutingInfo.postBeatSize,this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),!0}finalizeRenderer(){this.isFinalized=!0}doLayout(){if(this.bar){this.helpers.initialize(),this._preBeatGlyphs=new ra,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new ra,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 na(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()}}hasVoiceContainer(e){return!e.isEmpty||0===e.index}updateSizes(){this.staff.registerStaffTop(this.topPadding),this.staff.registerStaffBottom(this.height-this.bottomPadding);let e=this._voiceContainers,t=this.beatGlyphsStart,s=t;for(const i of e.values()){i.x=t,i.doLayout();let e=i.x+i.width;s<e&&(s=e)}this._postBeatGlyphs.x=Math.floor(s),this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.height+=this.layoutingInfo.height*this.scale}addPreBeatGlyph(e){e.renderer=this,this._preBeatGlyphs.addGlyph(e)}addBeatGlyph(e){e.renderer=this,e.preNotes.renderer=this,e.onNotes.renderer=this,e.onNotes.beamingHelper=this.helpers.beamHelperLookup[e.beat.voice.index].get(e.beat.index),this.getVoiceContainer(e.beat.voice).addGlyph(e)}getVoiceContainer(e){return this._voiceContainers.has(e.index)?this._voiceContainers.get(e.index):void 0}getBeatContainer(e){var t,s;return null===(s=null===(t=this.getVoiceContainer(e.voice))||void 0===t?void 0:t.beatGlyphs)||void 0===s?void 0:s[e.index]}getPreNotesGlyphForBeat(e){var t;return null===(t=this.getBeatContainer(e))||void 0===t?void 0:t.preNotes}getOnNotesGlyphForBeat(e){var t;return null===(t=this.getBeatContainer(e))||void 0===t?void 0:t.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 di;i.bar=this.bar,i.visualBounds=new at,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 at,i.realBounds.x=t+this.x,i.realBounds.y=s+this.y,i.realBounds.w=this.width,i.realBounds.h=this.height,e.addBar(i);for(const[e,a]of this._voiceContainers){let r=this.bar.isEmpty&&0===e;if(!a.voice.isEmpty||r)for(let e=0,n=a.beatGlyphs.length;e<n;e++){a.beatGlyphs[e].buildBoundingsLookup(i,t+this.x+a.x,s+this.y+a.y,r)}}}addPostBeatGlyph(e){this._postBeatGlyphs.addGlyph(e)}createPreBeatGlyphs(){this._wasFirstOfLine=this.isFirstOfLine}createBeatGlyphs(){for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];this.hasVoiceContainer(t)&&this.createVoiceGlyphs(this.bar.voices[e])}}createVoiceGlyphs(e){}createPostBeatGlyphs(){}get beatGlyphsStart(){return this._preBeatGlyphs.x+this._preBeatGlyphs.width}get postBeatGlyphsStart(){return this._postBeatGlyphs.x}getBeatX(e,t=ae.PreNotes){let s=this.getBeatContainer(e);if(s)switch(t){case ae.PreNotes:return s.voiceContainer.x+s.x;case ae.OnNotes:return s.voiceContainer.x+s.x+s.onNotes.x;case ae.MiddleNotes:return s.voiceContainer.x+s.x+s.onTimeX;case ae.Stem:const t=s.onNotes.beamingHelper?s.onNotes.beamingHelper.getBeatLineX(e):s.onNotes.x+s.onNotes.width/2;return s.voiceContainer.x+t;case ae.PostNotes:return s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.width;case ae.EndBeat:return s.voiceContainer.x+s.x+s.width}return 0}getNoteX(e,t){let s=this.getBeatContainer(e.beat);return s?s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.getNoteX(e,t):0}getNoteY(e,t){let s=this.getOnNotesGlyphForBeat(e.beat);return s?s.getNoteY(e,t):NaN}reLayout(){(this._wasFirstOfLine&&!this.isFirstOfLine||!this._wasFirstOfLine&&this.isFirstOfLine)&&(this._preBeatGlyphs=new ra,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()),this.updateSizes(),this.registerLayoutingInfo()}paintSimileMark(e,t,s){switch(this.bar.simileMark){case o.Simple:s.fillMusicFontSymbol(e+this.x+(this.width-20*this.scale)/2,t+this.y+this.height/2,1,N.Repeat1Bar,!1);break;case o.SecondOfDouble:s.fillMusicFontSymbol(e+this.x-28*this.scale/2,t+this.y+this.height/2,1,N.Repeat2Bars,!1)}}completeBeamingHelper(e){}}ma.LineSpacing=8,ma.StemWidth=.12*ma.LineSpacing,ma.StaffLineThickness=.13*ma.LineSpacing,ma.BeamThickness=.5*ma.LineSpacing,ma.BeamSpacing=.25*ma.LineSpacing,function(e){e[e.SinglePreBeat=0]="SinglePreBeat",e[e.SingleOnBeat=1]="SingleOnBeat",e[e.SingleOnBeatToEnd=2]="SingleOnBeatToEnd",e[e.GroupedOnBeat=3]="GroupedOnBeat",e[e.GroupedOnBeatToEnd=4]="GroupedOnBeatToEnd",e[e.FullBar=5]="FullBar"}(he||(he={}));class ya extends Ci{constructor(e,t){super(0,0),this._uniqueEffectGlyphs=[],this._effectGlyphs=[],this.isEmpty=!0,this.previousBand=null,this.isLinkedToPrevious=!1,this.firstBeat=null,this.lastBeat=null,this.height=0,this.slot=null,this.voice=e,this.info=t}doLayout(){super.doLayout();for(let e=0;e<this.renderer.bar.voices.length;e++)this._effectGlyphs.push(new Map),this._uniqueEffectGlyphs.push([])}createGlyph(e){if(e.voice===this.voice&&this.info.shouldCreateGlyph(this.renderer.settings,e)&&(!this.info.hideOnMultiTrack||0===this.renderer.staff.trackIndex)){if(this.isEmpty=!1,this.firstBeat&&!e.isBefore(this.firstBeat)||(this.firstBeat=e),!this.lastBeat||e.isAfter(this.lastBeat))switch(this.lastBeat=e,this.info.sizingMode){case he.SingleOnBeatToEnd:case he.GroupedOnBeatToEnd:this.lastBeat.nextBeat&&(this.lastBeat=this.lastBeat.nextBeat)}let t=this.createOrResizeGlyph(this.info.sizingMode,e);t.height>this.height&&(this.height=t.height)}}createOrResizeGlyph(e,t){let s;switch(e){case he.FullBar: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 he.SinglePreBeat:case he.SingleOnBeat:case he.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 he.GroupedOnBeat:case he.GroupedOnBeatToEnd:let i=e===he.GroupedOnBeat?he.SingleOnBeat:he.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 i=this.renderer.previousRenderer.getBand(this.voice,this.info.effectId)._effectGlyphs[t.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(he.SingleOnBeat,t)}}paint(e,t,s){super.paint(e,t,s);for(let i=0,a=this._uniqueEffectGlyphs.length;i<a;i++){let a=this._uniqueEffectGlyphs[i];for(let i=0,r=a.length;i<r;i++){a[i].paint(e+this.x,t+this.y,s)}}}alignGlyphs(){for(let e=0;e<this._effectGlyphs.length;e++)for(const t of this._effectGlyphs[e].keys())this.alignGlyph(this.info.sizingMode,this.renderer.bar.voices[e].beats[t])}alignGlyph(e,t){let s,i=this._effectGlyphs[t.voice.index].get(t.index),a=this.renderer.getBeatContainer(t);switch(e){case he.SinglePreBeat:s=a.preNotes,i.x=this.renderer.beatGlyphsStart+s.x+a.x,i.width=s.width;break;case he.SingleOnBeat:case he.GroupedOnBeat:s=a.onNotes,i.x=this.renderer.beatGlyphsStart+s.x+a.x,i.width=s.width;break;case he.SingleOnBeatToEnd:case he.GroupedOnBeatToEnd:s=a.onNotes,i.x=this.renderer.beatGlyphsStart+s.x+a.x,a.beat.isLastOfVoice?i.width=this.renderer.width-i.x:i.width=a.width-a.preNotes.width-a.preNotes.x;break;case he.FullBar:i.width=this.renderer.width}}}class ba{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class Sa{constructor(){this.bands=[],this.shared=new ba}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 wa{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 Sa;return this.slots.push(t),t}register(e){let t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class _a extends aa{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 Ba extends _a{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,s){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class Ta extends ma{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(){super.finalizeRenderer(),this.updateHeight()}updateHeight(){if(!this.sizingInfo)return;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}this.height=e}applyLayoutingInfo(){if(!super.applyLayoutingInfo())return!1;if(this.index>0){let e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new wa;for(let e of this._bands)e.alignGlyphs(),e.isEmpty||this.sizingInfo.register(e);return this.updateHeight(),!0}scaleToWidth(e){super.scaleToWidth(e);for(let e of this._bands)e.alignGlyphs()}createBeatGlyphs(){this._bands=[],this._bandLookup=new Map;for(let e of this.bar.voices)if(this.hasVoiceContainer(e))for(let t of this._infos){let s=new ya(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 Di(t,this.getVoiceContainer(e));s.preNotes=new _a,s.onNotes=new Ba,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 ka extends ia{constructor(e,t){super(),this._infos=t,this._staffId=e,this.isInAccolade=!1,this.isRelevantForBoundsLookup=!1}get staffId(){return this._staffId}create(e,t){return new Ta(e,t,this._infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class va extends Fi{constructor(e,t,s){super(e,t),this._endingsString="",this._endings=[];for(let e=0;e<Oe.MaxAlternateEndings;e++)0!=(s&1<<e)&&this._endings.push(e)}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(va.Padding*this.scale+2);let e="";for(let t=0,s=this._endings.length;t<s;t++)e+=this._endings[t]+1,e+=". ";this._endingsString=e}paint(e,t,s){super.paint(e,t,s);let i=s.textBaseline;if(s.textBaseline=E.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+va.Padding*this.scale,t+this.y*this.scale)}s.textBaseline=i}}va.Padding=3;class xa{get effectId(){return this.notationElement.toString()}}class Na extends xa{get notationElement(){return k.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return he.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){return new va(0,0,t.voice.bar.masterBar.alternateEndings)}canExpand(e,t){return!0}}class Pa extends Fi{constructor(e,t,s,i,a=P.Left){super(e,t),this._lines=s.split("\n"),this.font=i,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,s){let i=s.color;s.color=i,s.font=this.font;let a=s.textAlign;s.textAlign=this.textAlign;let r=t+this.y;for(let t of this._lines)s.fillText(t,e+this.x,r),r+=this.font.size;s.textAlign=a}}class Ea extends xa{get notationElement(){return k.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Pa(0,0,"Capo. fret "+t.voice.bar.staff.capo,e.resources.effectFont,P.Left)}canExpand(e,t){return!1}}class Ca extends xa{get notationElement(){return k.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Pa(0,0,t.chord.name,e.resources.effectFont,P.Center)}canExpand(e,t){return!1}}class Fa extends Fi{constructor(e){super(),this.forceGroupedRendering=!1,this.endOnBarLine=!1,this.endPosition=e}get isLinkedWithPrevious(){return!!this.previousGlyph&&this.previousGlyph.renderer.staff.staveGroup===this.renderer.staff.staveGroup}get isLinkedWithNext(){return!!this.nextGlyph&&this.nextGlyph.renderer.isFinalized&&this.nextGlyph.renderer.staff.staveGroup===this.renderer.staff.staveGroup}paint(e,t,s){if(this.isLinkedWithPrevious)return;if(!this.isLinkedWithNext&&!this.forceGroupedRendering)return void this.paintNonGrouped(e,t,s);let i;if(!this.isLinkedWithNext&&this.forceGroupedRendering)i=this;else for(i=this.nextGlyph;i.isLinkedWithNext;)i=i.nextGlyph;let a=i.renderer,r=i.beat,n=this.endPosition,o=e-this.renderer.x,h=this.calculateEndX(a,r,o,n);this.paintGrouped(e,t,h,s)}calculateEndX(e,t,s,i){return t?s+e.x+e.getBeatX(t,i):s+e.x+this.x+this.width}paintNonGrouped(e,t,s){let i=e-this.renderer.x,a=this.calculateEndX(this.renderer,this.beat,i,this.endPosition);this.paintGrouped(e,t,a,s)}}class La extends Fa{constructor(e,t,s){super(ae.EndBeat),this._crescendo=d.None,this._crescendo=s,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17*this.scale}paintGrouped(e,t,s,i){let a=e+this.x,r=this.height*this.scale;i.beginPath(),this._crescendo===d.Crescendo?(s-=La.Padding*this.scale,i.moveTo(s,t+this.y),i.lineTo(a,t+this.y+r/2),i.lineTo(s,t+this.y+r)):(s-=La.Padding*this.scale,i.moveTo(a,t+this.y),i.lineTo(s,t+this.y+r/2),i.lineTo(a,t+this.y+r)),i.stroke()}}La.Padding=Mi.QuarterNoteHeadWidth/2|0;class Ma extends xa{get notationElement(){return k.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==d.None}createNewGlyph(e,t){return new La(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class Ia extends Li{constructor(e,t,s){super(e,t,.6,Ia.getSymbol(s))}doLayout(){super.doLayout(),this.height=17*this.scale,this.y+=this.height/2}static getSymbol(e){switch(e){case p.PPP:return N.DynamicPPP;case p.PP:return N.DynamicPP;case p.P:return N.DynamicPiano;case p.MP:return N.DynamicMP;case p.MF:return N.DynamicMF;case p.F:return N.DynamicForte;case p.FF:return N.DynamicFF;case p.FFF:return N.DynamicFFF;default:return N.None}}}class Da extends xa{get notationElement(){return k.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return this.internalShouldCreateGlyph(t)}internalShouldCreateGlyph(e){if(e.voice.bar.staff.track.score.stylesheet.hideDynamics||e.isEmpty||e.voice.isEmpty||e.isRest||e.graceType!==g.None)return!1;let t=this.getPreviousDynamicsBeat(e),s=0===e.voice.index&&!t||e.dynamics!==(null==t?void 0:t.dynamics);if(s&&e.voice.index>0)for(let t of e.voice.bar.voices)if(t.index<e.voice.index){let i=t.getBeatAtPlaybackStart(e.playbackStart);i&&e.dynamics===i.dynamics&&this.internalShouldCreateGlyph(i)&&(s=!1)}return s}getPreviousDynamicsBeat(e){let t=e.previousBeat;for(;null!=t;){if(!t.isRest&&t.graceType===g.None)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new Ia(0,0,t.dynamics)}canExpand(e,t){return!0}}class Ra extends Fi{doLayout(){super.doLayout(),this.height=17*this.scale}paint(e,t,s){let i=6*this.scale,a=Math.max(this.width,14*this.scale),r=this.height/2;s.beginPath(),s.moveTo(e+this.x,t+this.y+r),s.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r-i),s.moveTo(e+this.x,t+this.y+r),s.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r+i),s.stroke()}}class Aa extends xa{get notationElement(){return k.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.fadeIn}createNewGlyph(e,t){return new Ra}canExpand(e,t){return!0}}class Oa extends Li{constructor(e,t,s){super(e,t,1,Oa.getSymbol(s))}static getSymbol(e){switch(e){case O.Short:return N.FermataShortAbove;case O.Medium:return N.FermataAbove;case O.Long:return N.FermataLongAbove;default:return N.None}}doLayout(){this.width=23*this.scale,this.height=12*this.scale}paint(e,t,s){super.paint(e-this.width/2,t+this.height,s)}}class Ga extends xa{get notationElement(){return k.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new Oa(0,0,t.fermata.type)}canExpand(e,t){return!0}}class Va extends xa{get notationElement(){return k.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return!(0!==t.voice.index||t.isRest||e.notation.fingeringMode!==B.SingleNoteEffectBand&&e.notation.fingeringMode!==B.SingleNoteEffectBandForcePiano)&&(1===t.notes.length&&t.notes[0].isFingering)}createNewGlyph(e,t){var s;let i=f.Unknown,a=!1,r=t.notes[0];r.leftHandFinger!==f.Unknown?(i=r.leftHandFinger,a=!0):r.rightHandFinger!==f.Unknown&&(i=r.rightHandFinger);let n=null!==(s=ke.fingerToString(e.settings,t,i,a))&&void 0!==s?s:"";return new Pa(0,0,n,e.resources.fingeringFont,P.Left)}canExpand(e,t){return!0}}class Ha extends xa{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 Wa extends Fa{constructor(e){super(ae.OnNotes),this._label=e}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=ae.EndBeat,this.forceGroupedRendering=!0),super.doLayout(),this.height=this.renderer.resources.effectFont.size}paintNonGrouped(e,t,s){let i=this.renderer.resources;s.font=i.effectFont;let a=s.textAlign;s.textAlign=P.Center,s.fillText(this._label,e+this.x,t+this.y),s.textAlign=a}paintGrouped(e,t,s,i){this.paintNonGrouped(e,t,i);let a=3*this.scale,r=i.measureText(this._label),n=e+this.x+r/2+a,o=t+this.y+4*this.scale,h=8*this.scale;if(s>n){let e=n;for(;e<s;)i.beginPath(),i.moveTo(e,0|o),i.lineTo(Math.min(e+h,s),0|o),e+=h+a,i.stroke();i.beginPath(),i.moveTo(s,o-5*this.scale|0),i.lineTo(s,o+5*this.scale|0),i.stroke()}}}Wa.LineSpacing=3,Wa.LineTopPadding=4,Wa.LineTopOffset=5,Wa.LineSize=8;class za extends Ha{constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case m.None:this._effectId="harmonics-none";break;case m.Natural:this._effectId="harmonics-natural";break;case m.Artificial:this._effectId="harmonics-artificial";break;case m.Pinch:this._effectId="harmonics-pinch";break;case m.Tap:this._effectId="harmonics-tap";break;case m.Semi:this._effectId="harmonics-semi";break;case m.Feedback:this._effectId="harmonics-feedback";break;default:this._effectId=""}}get effectId(){return this._effectId}get notationElement(){return k.EffectHarmonics}shouldCreateGlyphForNote(e){return!(!e.isHarmonic||e.harmonicType!==this._harmonicType)&&(e.beat!==this._beat&&(this._beat=e.beat),!0)}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new Wa(za.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case m.Natural:return"N.H.";case m.Artificial:return"A.H.";case m.Pinch:return"P.H.";case m.Tap:return"T.H.";case m.Semi:return"S.H.";case m.Feedback:return"Fdbk."}return""}}class Ua extends xa{get notationElement(){return k.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new Wa("LetRing")}canExpand(e,t){return!0}}class Xa extends Fi{constructor(e,t,s,i,a=P.Center){super(e,t),this._lines=s,this.font=i,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,s){s.font=this.font;let i=s.textAlign;s.textAlign=this.textAlign;for(let i=0;i<this._lines.length;i++)this._lines[i]&&s.fillText(this._lines[i],e+this.x,t+this.y+i*this.font.size);s.textAlign=i}}class Ya extends xa{get notationElement(){return k.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new Xa(0,0,t.lyrics,e.resources.effectFont,P.Center)}canExpand(e,t){return!0}}class qa extends xa{get notationElement(){return k.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return he.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 Pa(0,0,t.voice.bar.masterBar.section.marker?"["+t.voice.bar.masterBar.section.marker+"] "+t.voice.bar.masterBar.section.text:t.voice.bar.masterBar.section.text,e.resources.markerFont,P.Left)}canExpand(e,t){return!0}}class Ja extends Fa{constructor(e,t){super(ae.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=13*this.scale}paintNonGrouped(e,t,s){this.paintOttava(e,t,s)}paintOttava(e,t,s){let i=0;switch(this._ottava){case n._15ma:i=37*this.scale,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,N.QuindicesimaAlta,!1);break;case n._8va:i=26*this.scale,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,N.OttavaAlta,!1);break;case n._8vb:i=23*this.scale,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,N.OttavaBassaVb,!1);break;case n._15mb:i=36*this.scale,s.fillMusicFontSymbols(e+this.x-i/2,t+this.y+this.height,.8,[N.Quindicesima,N.OctaveBaselineM,N.OctaveBaselineB],!1)}return i/2}paintGrouped(e,t,s,i){let a=this.paintOttava(e,t,i),r=3*this.scale,n=e+this.x+a+r,o=t+this.y;o+=this._aboveStaff?2*this.scale:this.height-2*this.scale;let h=8*this.scale;if(s>n){let e=n;for(;e<s;)i.beginPath(),i.moveTo(e,0|o),i.lineTo(Math.min(e+h,s),0|o),e+=h+r,i.stroke();i.beginPath(),this._aboveStaff?(i.moveTo(s,o),i.lineTo(s,t+this.y+this.height)):(i.moveTo(s,o),i.lineTo(s,t+this.y)),i.stroke()}}}class Qa extends xa{constructor(e){super(),this._aboveStaff=e}get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return k.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeat}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 Ja(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class ja extends Ha{get notationElement(){return k.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new Wa("P.M.")}constructor(){super()}}class Ka extends Ha{get notationElement(){return k.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===S.PickSlideDown||e.slideOutType===S.PickSlideUp}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new Wa("P.S.")}constructor(){super()}}class $a extends Li{constructor(e,t,s){super(e,t,Mi.GraceScale,$a.getSymbol(s))}doLayout(){this.width=9*this.scale,this.height=13*this.scale}paint(e,t,s){super.paint(e,t+this.height,s)}static getSymbol(e){switch(e){case x.Up:return N.StringsUpBow;case x.Down:return N.StringsDownBow;default:return N.None}}}class Za extends xa{get notationElement(){return k.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==x.None}createNewGlyph(e,t){return new $a(0,0,t.pickStroke)}canExpand(e,t){return!0}}class er extends Fa{constructor(e){super(ae.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case w.Slight:this._stepSize=12*this.scale;break;case w.Wide:this._stepSize=23*this.scale}this.height=18*this.scale}paintGrouped(e,t,s,i){let a=e+this.x,r=s-a,n=Math.max(1,r/this._stepSize);i.beginPath(),i.moveTo(a,t+this.y);for(let e=0;e<n;e++)i.lineTo(a+this._stepSize/2,t+this.y+this.height),i.lineTo(a+this._stepSize,t+this.y),a+=this._stepSize;i.stroke()}}class tr extends xa{get notationElement(){return k.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===w.Slight}createNewGlyph(e,t){return new er(w.Slight)}canExpand(e,t){return!0}}class sr extends Fa{constructor(e,t,s,i=1.2,a=!1){super(ae.EndBeat),this._scale=0,this._symbol=N.None,this._symbolSize=0,this._type=s,this._scale=i,this.x=e,this.y=t,this._partialWaves=a}doLayout(){super.doLayout();let e=0;switch(this._type){case w.Slight:this._symbol=N.WiggleTrill,this._symbolSize=9*this._scale,e=6*this._scale;break;case w.Wide:this._symbol=N.WiggleVibratoMediumFast,this._symbolSize=10*this._scale,e=10*this._scale}this.height=e*this.scale}paintGrouped(e,t,s,i){let a=s-(e+this.x),r=this._symbolSize*this.scale,n=a/r;this._partialWaves||(n=Math.floor(n)),n<1&&(n=1);let o=0;for(let s=0;s<n;s++)i.fillMusicFontSymbol(e+this.x+o,t+this.y+2*this.height,this._scale*this.scale,this._symbol,!1),o+=r}}class ir extends Ha{get notationElement(){return k.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===w.Slight||e.isTieDestination&&e.tieOrigin.vibrato===w.Slight}get sizingMode(){return he.GroupedOnBeatToEnd}createNewGlyph(e,t){return new sr(0,0,w.Slight,1.2)}constructor(){super()}}class ar extends xa{get notationElement(){return k.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){let s=e.resources;return t.slap?new Pa(0,0,"S",s.effectFont,P.Left):t.pop?new Pa(0,0,"P",s.effectFont,P.Left):new Pa(0,0,"T",s.effectFont,P.Left)}canExpand(e,t){return!0}}class rr extends Fi{constructor(e,t,s){super(e,t),this._tempo=0,this._tempo=s}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,s){let i=this.renderer.resources;s.font=i.markerFont,s.fillMusicFontSymbol(e+this.x,t+this.y+.8*this.height,this.scale*Mi.GraceScale,N.NoteQuarterUp,!1),s.fillText("= "+this._tempo.toString(),e+this.x+this.height/2,t+this.y+s.font.size/2)}}class nr extends xa{get notationElement(){return k.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return he.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&(!!t.voice.bar.masterBar.tempoAutomation||0===t.voice.bar.index)}createNewGlyph(e,t){let s=0;return s=t.voice.bar.masterBar.tempoAutomation?t.voice.bar.masterBar.tempoAutomation.value:t.voice.bar.staff.track.score.tempo,new rr(0,0,s)}canExpand(e,t){return!0}}class or extends xa{get notationElement(){return k.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Pa(0,0,t.text,e.resources.effectFont,P.Left)}canExpand(e,t){return!0}}class hr extends Fi{constructor(e,t){super(e,t)}doLayout(){super.doLayout(),this.height=20*this.scale}paint(e,t,s){let i=this.renderer.resources;s.font=i.markerFont;let a=s.measureText("tr");s.fillText("tr",e+this.x,t+this.y+s.font.size/2);let r=a+3*this.scale,n=this.width-r,o=11*this.scale*1.2,h=Math.max(1,(n-r)/o),l=r,c=t+this.y+this.height;for(let t=0;t<h;t++)s.fillMusicFontSymbol(e+this.x+l,c,1.2,N.WiggleTrill,!1),l+=o}}class lr extends Ha{get notationElement(){return k.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return he.SingleOnBeat}createNewGlyph(e,t){return new hr(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(le||(le={}));class cr extends Fi{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,s){e+=this.x;let i=(t+=this.y)+this.height*Mi.GraceScale;s.font=this.renderer.resources.effectFont,s.fillText("(",e,t+.3*this.height);let a=e+10*this.scale,r=e+40*this.scale;switch(this._tripletFeel){case D.NoTripletFeel:this.renderBarNote(a,i,cr.NoteScale,s,[le.Full]),this.renderBarNote(r,i,cr.NoteScale,s,[le.Full]);break;case D.Triplet8th:this.renderBarNote(a,i,cr.NoteScale,s,[le.Full]),s.fillMusicFontSymbol(r,i,cr.NoteScale,N.NoteQuarterUp,!1),s.fillMusicFontSymbol(r+cr.NoteSeparation*this.scale,i,cr.NoteScale,N.NoteEighthUp,!1),this.renderTriplet(r,t,s);break;case D.Triplet16th:this.renderBarNote(a,i,cr.NoteScale,s,[le.Full,le.Full]),this.renderBarNote(r,i,cr.NoteScale,s,[le.Full,le.PartialRight]),this.renderTriplet(r,t,s);break;case D.Dotted8th:this.renderBarNote(a,i,cr.NoteScale,s,[le.Full]),this.renderBarNote(r,i,cr.NoteScale,s,[le.Full,le.PartialRight]),s.fillCircle(r+9*this.scale,i,this.scale);break;case D.Dotted16th:this.renderBarNote(a,i,cr.NoteScale,s,[le.Full,le.Full]),this.renderBarNote(r,i,cr.NoteScale,s,[le.Full,le.Full,le.PartialRight]),s.fillCircle(r+9*this.scale,i,this.scale);break;case D.Scottish8th:this.renderBarNote(a,i,cr.NoteScale,s,[le.Full]),this.renderBarNote(r,i,cr.NoteScale,s,[le.Full,le.PartialLeft]),s.fillCircle(r+cr.NoteSeparation*this.scale+8*this.scale,i,this.scale);break;case D.Scottish16th:this.renderBarNote(a,i,cr.NoteScale,s,[le.Full,le.Full]),this.renderBarNote(r,i,cr.NoteScale,s,[le.Full,le.Full,le.PartialLeft]),s.fillCircle(r+cr.NoteSeparation*this.scale+8*this.scale,i,this.scale)}s.fillText("=",e+30*this.scale,t+5*this.scale),s.fillText(")",e+65*this.scale,t+.3*this.height)}renderBarNote(e,t,s,i,a){i.fillMusicFontSymbol(e,t,s,N.NoteQuarterUp,!1);let r=cr.NoteSeparation/2*this.scale;for(let s=0;s<a.length;s++)switch(a[s]){case le.Full:i.fillRect(e+4*this.scale,t-cr.NoteHeight*this.scale+cr.BarSeparation*this.scale*s,cr.NoteSeparation*this.scale,cr.BarHeight*this.scale);break;case le.PartialLeft:i.fillRect(e+4*this.scale,t-cr.NoteHeight*this.scale+cr.BarSeparation*this.scale*s,r,cr.BarHeight*this.scale);break;case le.PartialRight:i.fillRect(e+4*this.scale+r,t-cr.NoteHeight*this.scale+cr.BarSeparation*this.scale*s,r,cr.BarHeight*this.scale)}i.fillMusicFontSymbol(e+cr.NoteSeparation*this.scale,t,s,N.NoteQuarterUp,!1)}renderTriplet(e,t,s){t+=2*this.scale;let i=this.renderer.resources.effectFont;s.font=new vs(i.family,.8*i.size,i.style);let a=e+cr.NoteSeparation*this.scale+3*this.scale;s.beginPath(),s.moveTo(e,t+3*this.scale),s.lineTo(e,t),s.lineTo(e+5*this.scale,t),s.moveTo(a+5*this.scale,t+3*this.scale),s.lineTo(a+5*this.scale,t),s.lineTo(a,t),s.stroke(),s.fillText("3",e+7*this.scale,t-10*this.scale),s.font=i}}cr.NoteScale=.4,cr.NoteHeight=12,cr.NoteSeparation=12,cr.BarHeight=2,cr.BarSeparation=3;class dr extends xa{get notationElement(){return k.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return he.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==D.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new cr(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class ur extends xa{get notationElement(){return k.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new Wa("w/bar")}canExpand(e,t){return!0}}class pr extends xa{get notationElement(){return k.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===w.Wide}createNewGlyph(e,t){return new er(w.Wide)}canExpand(e,t){return!0}}class gr extends Ha{get notationElement(){return k.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===w.Wide||e.isTieDestination&&e.tieOrigin.vibrato===w.Wide}get sizingMode(){return he.GroupedOnBeatToEnd}createNewGlyph(e,t){return new sr(0,0,w.Wide,1.2)}}class fr extends Fi{constructor(e,t,s){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=s}doLayout(){super.doLayout();const e=this.scale;let t=this.renderer.resources;this._textRow=1.5*t.effectFont.size*e,this._fretRow=1.5*t.effectFont.size*e,this._chord.firstFret>1?this._firstFretSpacing=fr.FretSpacing*e:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+(fr.Frets-1)*fr.FretSpacing*e+2*fr.Padding*e,this.width=this._firstFretSpacing+(this._chord.staff.tuning.length-1)*fr.StringSpacing*e+2*fr.Padding*e}paint(e,t,s){e+=this.x+fr.Padding*this.scale+this._firstFretSpacing,t+=this.y;let i=this.width-2*fr.Padding*this.scale+this.scale-this._firstFretSpacing,a=fr.StringSpacing*this.scale,r=fr.FretSpacing*this.scale,n=this.renderer.resources,o=fr.CircleRadius*this.scale,h=s.textAlign,l=s.textBaseline;s.font=n.effectFont,s.textAlign=P.Center,s.textBaseline=E.Top,this._chord.showName&&s.fillText(this._chord.name,e+this.width/2,t+n.effectFont.size/2),t+=this._textRow,e+=a/2,s.font=n.fretboardNumberFont,s.textBaseline=E.Middle;for(let i=0;i<this._chord.staff.tuning.length;i++){let r=e+i*a,n=t+this._fretRow/2,o=this._chord.strings[this._chord.staff.tuning.length-i-1];o<0?s.fillMusicFontSymbol(r,n,this.scale,N.FretboardX,!0):0===o?s.fillMusicFontSymbol(r,n,this.scale,N.FretboardO,!0):(o-=this._chord.firstFret-1,s.fillText(o.toString(),r,n))}t+=this._fretRow;for(let i=0;i<this._chord.staff.tuning.length;i++){let n=e+i*a;s.fillRect(n,t,1,r*fr.Frets+this.scale)}this._chord.firstFret>1&&(s.textAlign=P.Left,s.fillText(this._chord.firstFret.toString(),e-this._firstFretSpacing,t+r/2)),s.fillRect(e,t-this.scale,i,2*this.scale);for(let a=0;a<=fr.Frets;a++){let n=t+a*r;s.fillRect(e,n,i,this.scale)}let c=new Map;for(let e of this._chord.barreFrets){let t=[-1,-1];c.set(e-this._chord.firstFret,t)}for(let i=0;i<this._chord.strings.length;i++){let n=this._chord.strings[i];if(n>0){if(n-=this._chord.firstFret,c.has(n)){let e=c.get(n);(-1===e[0]||i<e[0])&&(e[0]=i),(-1===e[1]||i>e[1])&&(e[1]=i)}let h=t+n*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-i-1)*a;s.fillCircle(l,h,o)}}for(const[i,n]of c){let h=t+i*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-n[1]-1)*a,c=e+(this._chord.strings.length-n[0]-1)*a;s.fillRect(l,h-o,c-l,2*o)}s.textAlign=h,s.textBaseline=l}}fr.Padding=5,fr.Frets=5,fr.CircleRadius=2.5,fr.StringSpacing=10,fr.FretSpacing=12;class mr extends aa{constructor(e,t,s=P.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=s}doLayout(){let e=0;switch(this._align){case P.Left:e=0;break;case P.Center:e=(this.width-this._glyphWidth)/2;break;case P.Right:e=this.width-this._glyphWidth}for(let t of this.glyphs)t.x=e,e+=t.width}addGlyphToRow(e){this.glyphs.push(e),this._glyphWidth+=e.width,e.height>this.height&&(this.height=e.height)}}class yr extends aa{constructor(e,t,s=P.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=s}doLayout(){let e=0,t=0,s=2*yr.Padding*this.scale;this._rows=[];let i=new mr(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 mr(e,t,this._align),i.width=this.width,i.addGlyphToRow(a),e+=a.width);i.isEmpty||(i.doLayout(),this._rows.push(i),t+=i.height+s),this.height=t+s}paint(e,t,s){for(let i of this._rows)i.paint(e+this.x,t+this.y+yr.Padding*this.scale,s)}}yr.Padding=3;class br extends yr{constructor(e,t){super(e,t)}addChord(e){if(e.strings.length>0){let t=new fr(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}}class Sr{constructor(e,t,s){this._sharedLayoutData=new Map,this.barRenderers=[],this.x=0,this.y=0,this.height=0,this.index=0,this.staffIndex=0,this.trackIndex=0,this.staveTop=0,this.topSpacing=20,this.bottomSpacing=5,this.staveBottom=0,this.isFirstInAccolade=!1,this.isLastInAccolade=!1,this._factory=s,this.trackIndex=e,this.modelStaff=t}get staveId(){return this._factory.staffId}getSharedLayoutData(e,t){return this._sharedLayoutData.has(e)?this._sharedLayoutData.get(e):t}setSharedLayoutData(e,t){this._sharedLayoutData.set(e,t)}get isInAccolade(){return this._factory.isInAccolade}get isRelevantForBoundsLookup(){return this._factory.isRelevantForBoundsLookup}registerStaffTop(e){this.staveTop=e}registerStaffBottom(e){this.staveBottom=e}addBarRenderer(e){e.staff=this,e.index=this.barRenderers.length,e.reLayout(),this.barRenderers.push(e),this.staveGroup.layout.registerBarRenderer(this.staveId,e)}addBar(e,t){let s;s=e?this._factory.create(this.staveGroup.layout.renderer,e):new ma(this.staveGroup.layout.renderer,e),s.staff=this,s.index=this.barRenderers.length,s.layoutingInfo=t,s.doLayout(),s.registerLayoutingInfo(),this.barRenderers.push(s),e&&this.staveGroup.layout.registerBarRenderer(this.staveId,s)}revertLastBar(){let e=this.barRenderers[this.barRenderers.length-1];return this.barRenderers.splice(this.barRenderers.length-1,1),this.staveGroup.layout.unregisterBarRenderer(this.staveId,e),e}scaleToWidth(e){this._sharedLayoutData=new Map;let t=(e-this.staveGroup.width)/this.barRenderers.length;for(let e=0,s=this.barRenderers.length;e<s;e++)this.barRenderers[e].scaleToWidth(this.barRenderers[e].width+t)}get topOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){let s=this.barRenderers[t];s.topOverflow>e&&(e=s.topOverflow)}return e}get bottomOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){let s=this.barRenderers[t];s.bottomOverflow>e&&(e=s.bottomOverflow)}return e}finalizeStaff(){let e=0;this.height=0;let t=this.topOverflow,s=this.bottomOverflow;for(let s=0;s<this.barRenderers.length;s++)this.barRenderers[s].x=e,this.barRenderers[s].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[s].height),this.barRenderers[s].finalizeRenderer(),e+=this.barRenderers[s].width;this.height>0&&(this.height+=this.topSpacing+t+s+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 wr{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 _r{constructor(){this._timeSortedSprings=[],this._xMin=0,this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,this.version=0,this.preBeatSizes=new Map,this.onBeatSizes=new Map,this.onBeatCenterX=new Map,this.preBeatSize=0,this.postBeatSize=0,this.voiceSize=0,this.minStretchForce=0,this.totalSpringConstant=0,this.incompleteGraceRods=new Map,this.allGraceRods=new Map,this.springs=new Map,this.height=0}updateVoiceSize(e){e>this.voiceSize&&(this.voiceSize=e,this.version++)}setPreBeatSize(e,t){(!this.preBeatSizes.has(e.index)||this.preBeatSizes.get(e.index)<t)&&(this.preBeatSizes.set(e.index,t),this.version++)}getPreBeatSize(e){return this.preBeatSizes.has(e.index)?this.preBeatSizes.get(e.index):0}setOnBeatSize(e,t){(!this.onBeatSizes.has(e.index)||this.onBeatSizes.get(e.index)<t)&&(this.onBeatSizes.set(e.index,t),this.version++)}getOnBeatSize(e){return this.onBeatSizes.has(e.index)?this.onBeatSizes.get(e.index):0}getBeatCenterX(e){return this.onBeatCenterX.has(e.index)?this.onBeatCenterX.get(e.index):0}setBeatCenterX(e,t){(!this.onBeatCenterX.has(e.index)||this.onBeatCenterX.get(e.index)<t)&&(this.onBeatCenterX.set(e.index,t),this.version++)}updateMinStretchForce(e){this.minStretchForce<e&&(this.minStretchForce=e)}addSpring(e,t,s,i,a){let r;if(this.version++,this.springs.has(e))r=this.springs.get(e),r.postSpringWidth<a&&(r.postSpringWidth=a),r.graceBeatWidth<s&&(r.graceBeatWidth=s),r.preBeatWidth<i&&(r.preBeatWidth=i),t<r.smallestDuration&&(r.smallestDuration=t),t>r.longestDuration&&(r.longestDuration=t),r.allDurations.add(t);else{if(r=new wr,r.timePosition=e,r.allDurations.add(t),this._timeSortedSprings.length>0){let e=this._timeSortedSprings[this._timeSortedSprings.length-1];for(const t of e.allDurations)e.timePosition}r.longestDuration=t,r.postSpringWidth=a,r.graceBeatWidth=s,r.preBeatWidth=i,this.springs.set(e,r);let n=this._timeSortedSprings,o=n.length-1;for(;o>0&&n[o].timePosition>e;)o--;this._timeSortedSprings.splice(o+1,0,r)}return(-1===this._minTime||this._minTime>e)&&(this._minTime=e),r}addBeatSpring(e,t,s){let i=e.absoluteDisplayStart;if(e.graceType!==g.None){const a=e.graceGroup.id;this.allGraceRods.has(a)||this.allGraceRods.set(a,new Array(e.graceGroup.beats.length)),e.graceGroup.isComplete||this.incompleteGraceRods.has(a)||this.incompleteGraceRods.set(a,new Array(e.graceGroup.beats.length));let r=this.allGraceRods.get(a)[e.graceIndex];if(r)r.postSpringWidth<s&&(r.postSpringWidth=s),r.preBeatWidth<t&&(r.preBeatWidth=t);else{const r=new wr;r.timePosition=i,r.postSpringWidth=s,r.preBeatWidth=t,e.graceGroup.isComplete||(this.incompleteGraceRods.get(a)[e.graceIndex]=r),this.allGraceRods.get(a)[e.graceIndex]=r}}else{let a=0;if(e.graceGroup&&this.allGraceRods.has(e.graceGroup.id))for(const t of this.allGraceRods.get(e.graceGroup.id))a+=t.springWidth;this.addSpring(i,e.displayDuration,a,t,s)}}finish(){for(const[e,t]of this.allGraceRods){let s=0;if(this.incompleteGraceRods.has(e))for(const e of t)s+=e.preBeatWidth,e.graceBeatWidth=s,s+=e.postSpringWidth;else for(let e=t.length-1;e>=0;e--)t[e].graceBeatWidth=s,s-=t[e].preBeatWidth+t[e].postSpringWidth}this._incompleteGraceRodsWidth=0;for(const e of this.incompleteGraceRods.values())for(const t of e)this._incompleteGraceRodsWidth+=t.preBeatWidth+t.postSpringWidth;this.calculateSpringConstants(),this.version++}calculateSpringConstants(){this._xMin=0;let e=this.springs;for(const t of e.values())t.springWidth<this._xMin&&(this._xMin=t.springWidth);let t=0,s=this._timeSortedSprings;if(0===s.length)return this.totalSpringConstant=-1,void(this.minStretchForce=-1);for(let e=0;e<s.length;e++){let i=s[e],a=0;if(e===s.length-1)a=i.longestDuration;else{let t=s[e+1];a=Math.abs(t.timePosition-i.timePosition)}i.springConstant=this.calculateSpringConstant(i,a),t+=1/i.springConstant}this.totalSpringConstant=1/t,this.minStretchForce=0;for(let e=0;e<s.length;e++){let t=s[e],i=0;if(e===s.length-1)i=t.postSpringWidth;else{let a=s[e+1];i=t.postSpringWidth+a.preSpringWidth}0===e&&(i+=t.preSpringWidth);let a=i*t.springConstant;this.updateMinStretchForce(a)}}paint(e,t,s){}calculateSpringConstant(e,t){return t<=0&&(t=ye.toTicks(u.SixtyFourth)),0===e.smallestDuration&&(e.smallestDuration=t),e.smallestDuration/t*(1/((1+.85*Math.log2(t/_r.MinDuration))*_r.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(ke.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}}_r.MinDuration=30,_r.MinDurationWidth=7;class Br{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.renderers=[]}}class Tr{constructor(e,t){this.staves=[],this.stavesRelevantForBoundsLookup=[],this.firstStaffInAccolade=null,this.lastStaffInAccolade=null,this.staveGroup=e,this.track=t}addStaff(e){this.staves.push(e),e.isRelevantForBoundsLookup&&this.stavesRelevantForBoundsLookup.push(e)}}class kr{constructor(){this._allStaves=[],this._firstStaffInAccolade=null,this._lastStaffInAccolade=null,this._accoladeSpacingCalculated=!1,this.x=0,this.y=0,this.index=0,this.accoladeSpacing=0,this.isFull=!1,this.width=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[]}get firstBarIndex(){return this.masterBarsRenderers[0].masterBar.index}get lastBarIndex(){return this.masterBarsRenderers[this.masterBarsRenderers.length-1].masterBar.index}addMasterBarRenderers(e,t){if(0===e.length)return null;this.masterBarsRenderers.push(t),this.calculateAccoladeSpacing(e),t.layoutingInfo.preBeatSize=0;let s=0;for(let e=0,i=this.staves.length;e<i;e++){let i=this.staves[e];for(let e=0,a=i.staves.length;e<a;e++){let a=i.staves[e],r=t.renderers[s++];a.addBarRenderer(r)}}return this.updateWidth(),t}addBars(e,t){if(0===e.length)return null;let s=new Br;s.layoutingInfo=new _r,s.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(s),this.calculateAccoladeSpacing(e);let i=s.layoutingInfo;for(let e of this.staves)for(let a of e.staves){let r=e.track.staves[a.modelStaff.index].bars[t];a.addBar(r,i);let n=a.barRenderers[a.barRenderers.length-1];s.renderers.push(n),n.isLinkedToPrevious&&(s.isLinkedToPrevious=!0),n.canWrap||(s.canWrap=!1)}return i.finish(),s.width=this.updateWidth(),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;for(let e=0,s=this._allStaves.length;e<s;e++){let s=this._allStaves[e].revertLastBar();t=Math.max(t,s.width)}return this.width-=t,e}return null}updateWidth(){let e=0;for(let t=0,s=this._allStaves.length;t<s;t++){let s=this._allStaves[t];s.barRenderers[s.barRenderers.length-1].applyLayoutingInfo(),s.barRenderers[s.barRenderers.length-1].width>e&&(e=s.barRenderers[s.barRenderers.length-1].width)}return this.width+=e,e}calculateAccoladeSpacing(e){if(!this._accoladeSpacingCalculated&&0===this.index)if(this._accoladeSpacingCalculated=!0,this.layout.renderer.settings.notation.isNotationElementVisible(k.TrackNames)){let t=this.layout.renderer.canvas,s=this.layout.renderer.settings.display.resources.effectFont;t.font=s;for(let s of e)this.accoladeSpacing=Math.ceil(Math.max(this.accoladeSpacing,t.measureText(s.shortName)));this.accoladeSpacing*=this.layout.scale,this.accoladeSpacing+=2*kr.AccoladeLabelSpacing*this.layout.scale,this.width+=this.accoladeSpacing}else this.accoladeSpacing=0}getStaveTrackGroup(e){for(let t=0,s=this.staves.length;t<s;t++){let s=this.staves[t];if(s.track===e)return s}return null}addStaff(e,t){let s=this.getStaveTrackGroup(e);s||(s=new Tr(this,e),this.staves.push(s)),t.staveTrackGroup=s,t.staveGroup=this,t.index=this._allStaves.length,this._allStaves.push(t),s.addStaff(t),t.isInAccolade&&(this._firstStaffInAccolade||(this._firstStaffInAccolade=t,t.isFirstInAccolade=!0),s.firstStaffInAccolade||(s.firstStaffInAccolade=t),this._lastStaffInAccolade||(this._lastStaffInAccolade=t,t.isLastInAccolade=!0),this._lastStaffInAccolade&&(this._lastStaffInAccolade.isLastInAccolade=!1),this._lastStaffInAccolade=t,this._lastStaffInAccolade.isLastInAccolade=!0,s.lastStaffInAccolade=t)}get height(){return this._allStaves[this._allStaves.length-1].y+this._allStaves[this._allStaves.length-1].height}scaleToWidth(e){for(let t=0,s=this._allStaves.length;t<s;t++)this._allStaves[t].scaleToWidth(e);this.width=e}paint(e,t,s){this.paintPartial(e+this.x,t+this.y,s,0,this.masterBarsRenderers.length)}paintPartial(e,t,s,i,a){for(let r=0,n=this._allStaves.length;r<n;r++)this._allStaves[r].paint(e,t,s,i,a);let r=this.layout.renderer.settings.display.resources;if(this.staves.length>0&&0===i){if(s.color=r.barSeparatorColor,this._firstStaffInAccolade&&this._lastStaffInAccolade){let i=t+this._firstStaffInAccolade.y+this._firstStaffInAccolade.staveTop+this._firstStaffInAccolade.topSpacing+this._firstStaffInAccolade.topOverflow,a=t+this._lastStaffInAccolade.y+this._lastStaffInAccolade.topSpacing+this._lastStaffInAccolade.topOverflow+this._lastStaffInAccolade.staveBottom,r=e+this._firstStaffInAccolade.x;s.beginPath(),s.moveTo(r,i),s.lineTo(r,a),s.stroke()}s.font=r.effectFont;for(let i=0,a=this.staves.length;i<a;i++){let a=this.staves[i];if(a.firstStaffInAccolade&&a.lastStaffInAccolade){let i=t+a.firstStaffInAccolade.y+a.firstStaffInAccolade.staveTop+a.firstStaffInAccolade.topSpacing+a.firstStaffInAccolade.topOverflow,r=t+a.lastStaffInAccolade.y+a.lastStaffInAccolade.topSpacing+a.lastStaffInAccolade.topOverflow+a.lastStaffInAccolade.staveBottom,n=e+a.firstStaffInAccolade.x,o=3*this.layout.renderer.settings.display.scale,h=o,l=i-4*o,c=r+4*o;0===this.index&&this.layout.renderer.settings.notation.isNotationElementVisible(k.TrackNames)&&s.fillText(a.track.shortName,e+kr.AccoladeLabelSpacing*this.layout.scale,i),s.fillRect(n-h-o,l,o,c-l);let d=n-h-o,u=n+2*o;s.beginPath(),s.moveTo(d,l),s.bezierCurveTo(d,l,d,l,u,l-o),s.bezierCurveTo(n,l+o,d,l+o,d,l+o),s.closePath(),s.fill(),s.beginPath(),s.moveTo(d,c),s.bezierCurveTo(d,c,n,c,u,c+o),s.bezierCurveTo(n,c-o,d,c-o,d,c-o),s.closePath(),s.fill()}}}}finalizeGroup(){let e=0;for(let t of this._allStaves)t.x=this.accoladeSpacing,t.y=e,t.finalizeStaff(),e+=t.height}buildBoundingsLookup(e,t){if(this.layout.renderer.boundsLookup.isFinished)return;if(!this._firstStaffInAccolade||!this._lastStaffInAccolade)return;let s=this._allStaves[this._allStaves.length-1],i=t+this.y+this._firstStaffInAccolade.y,a=t+this.y+this._lastStaffInAccolade.y+this._lastStaffInAccolade.height,r=t+this.y+this._allStaves[0].y,n=t+this.y+s.y+s.height,o=t+this.y+this._firstStaffInAccolade.y+this._firstStaffInAccolade.topSpacing+this._firstStaffInAccolade.topOverflow+(this._firstStaffInAccolade.barRenderers.length>0?this._firstStaffInAccolade.barRenderers[0].topPadding:0),h=a-i,l=t+this.y+s.y+s.height-s.bottomSpacing-s.bottomOverflow-(s.barRenderers.length>0?s.barRenderers[0].bottomPadding:0)-o,c=n-r,d=this.x+this._firstStaffInAccolade.x,u=new fi;u.visualBounds=new at,u.visualBounds.x=e,u.visualBounds.y=t+this.y,u.visualBounds.w=this.width,u.visualBounds.h=this.height,u.realBounds=new at,u.realBounds.x=e,u.realBounds.y=t+this.y,u.realBounds.w=this.width,u.realBounds.h=this.height,this.layout.renderer.boundsLookup.addStaveGroup(u);let p=new Map;for(let e=0;e<this.staves.length;e++)for(let s of this.staves[e].stavesRelevantForBoundsLookup)for(let e of s.barRenderers){let a;p.has(e.bar.masterBar.index)?a=p.get(e.bar.masterBar.index):(a=new pi,a.index=e.bar.masterBar.index,a.isFirstOfLine=e.isFirstOfLine,a.realBounds=new at,a.realBounds.x=d+e.x,a.realBounds.y=r,a.realBounds.w=e.width,a.realBounds.h=c,a.visualBounds=new at,a.visualBounds.x=d+e.x,a.visualBounds.y=i,a.visualBounds.w=e.width,a.visualBounds.h=h,a.lineAlignedBounds=new at,a.lineAlignedBounds.x=d+e.x,a.lineAlignedBounds.y=o,a.lineAlignedBounds.w=e.width,a.lineAlignedBounds.h=l,this.layout.renderer.boundsLookup.addMasterBar(a),p.set(a.index,a)),e.buildBoundingsLookup(a,d,t+this.y+s.y)}}getBarX(e){if(!this._firstStaffInAccolade||0===this.layout.renderer.tracks.length)return 0;let t=this.layout.renderer.tracks[0].staves[0].bars[e];return this.layout.getRendererForBar(this._firstStaffInAccolade.staveId,t).x}}kr.AccoladeLabelSpacing=10;class vr extends aa{constructor(e,t,s,i){super(e,t),this._tuning=s,this._trackLabel=i,this.glyphs=[]}doLayout(){if(!(this.glyphs.length>0)){this.createGlyphs(this._tuning);for(const e of this.glyphs)e.renderer=this.renderer,e.doLayout()}}createGlyphs(e){const t=this.renderer.scale,s=this.renderer.resources;this.height=0;const i=15*t;this._trackLabel.length>0&&(this.addGlyph(new Pa(0,this.height,this._trackLabel,s.effectFont,P.Left)),this.height+=i),this.addGlyph(new Pa(0,this.height,e.name,s.effectFont,P.Left));const a=64*t;if(this.renderer.scoreRenderer.canvas.font=s.effectFont,this.width=Math.max(this.renderer.scoreRenderer.canvas.measureText(this._trackLabel)*t,Math.max(this.renderer.scoreRenderer.canvas.measureText(e.name)*t,2*a)),this.height+=i,!e.isStandard){const r=.7,n=vr.CircleNumberHeight*r*t;let o=0|Math.ceil(e.tunings.length/2),h=0,l=this.height;for(let c=0,d=e.tunings.length;c<d;c++){const d=N.GuitarString0+(c+1);this.addGlyph(new Li(h,l+n/1.2,r,d));const u="= "+Ye.getTextForTuning(e.tunings[c],!1);this.addGlyph(new Pa(h+n+1*t,l,u,s.effectFont,P.Left)),l+=i,c===o-1&&(l=this.height,h+=a)}this.height+=o*i}this.width+=15*t}}vr.CircleNumberHeight=20;class xr extends yr{constructor(e,t){super(e,t,P.Left)}addTuning(e,t){if(e.tunings.length>0){let s=new vr(0,0,e,t);s.renderer=this.renderer,s.doLayout(),this.glyphs.push(s)}}}class Nr{constructor(e,t){this.args=e,this.renderCallback=t}}class Pr{constructor(e){this._barRendererLookup=new Map,this.width=0,this.height=0,this.scoreInfoGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t)),this.firstBarIndex=t;let s=this.renderer.settings.display.barCount;s<0&&(s=e.masterBars.length),s=t+s-1,s=Math.min(e.masterBars.length-1,Math.max(0,s)),this.lastBarIndex=s,this.createScoreInfoGlyphs(),this.doLayoutAndRender()}registerPartial(e,t){this.renderer.partialLayoutFinished.trigger(e),this.renderer.settings.core.enableLazyLoading?this._lazyPartials.set(e.id,new Nr(e,t)):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(){Be.debug("ScoreLayout","Creating score info glyphs");let e=this.renderer.settings.notation,t=this.renderer.score,s=this.renderer.settings.display.resources;this.scoreInfoGlyphs=new Map,t.title&&e.isNotationElementVisible(k.ScoreTitle)&&this.scoreInfoGlyphs.set(k.ScoreTitle,new Pa(0,0,t.title,s.titleFont,P.Center)),t.subTitle&&e.isNotationElementVisible(k.ScoreSubTitle)&&this.scoreInfoGlyphs.set(k.ScoreSubTitle,new Pa(0,0,t.subTitle,s.subTitleFont,P.Center)),t.artist&&e.isNotationElementVisible(k.ScoreArtist)&&this.scoreInfoGlyphs.set(k.ScoreArtist,new Pa(0,0,t.artist,s.subTitleFont,P.Center)),t.album&&e.isNotationElementVisible(k.ScoreAlbum)&&this.scoreInfoGlyphs.set(k.ScoreAlbum,new Pa(0,0,t.album,s.subTitleFont,P.Center)),t.music&&t.music===t.words&&e.isNotationElementVisible(k.ScoreWordsAndMusic)?this.scoreInfoGlyphs.set(k.ScoreWordsAndMusic,new Pa(0,0,"Music and Words by "+t.words,s.wordsFont,P.Center)):(t.music&&e.isNotationElementVisible(k.ScoreMusic)&&this.scoreInfoGlyphs.set(k.ScoreMusic,new Pa(0,0,"Music by "+t.music,s.wordsFont,P.Right)),t.words&&e.isNotationElementVisible(k.ScoreWords)&&this.scoreInfoGlyphs.set(k.ScoreWords,new Pa(0,0,"Words by "+t.words,s.wordsFont,P.Left)));const i=new ma(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);if(e.isNotationElementVisible(k.GuitarTuning)){let e=[];for(let t of this.renderer.tracks)for(let s of t.staves)if(!s.isPercussion&&s.isStringed&&s.tuning.length>0&&s.showTablature){e.push(s);break}if(e.length>0){this.tuningGlyph=new xr(0,0),this.tuningGlyph.renderer=i;for(const t of e)this.tuningGlyph.addTuning(t.stringTuning,e.length>1?t.track.name:"")}}if(e.isNotationElementVisible(k.ChordDiagrams)){this.chordDiagrams=new br(0,0),this.chordDiagrams.renderer=i;let e=new Map;for(let t of this.renderer.tracks)for(let s of t.staves){const t=s.chords;if(t)for(const[s,i]of t)e.has(s)||i.showDiagram&&(e.set(s,i),this.chordDiagrams.addChord(i))}}}get scale(){return this.renderer.settings.display.scale}createEmptyStaveGroup(){let e=new kr;e.layout=this;for(let s=0;s<this.renderer.tracks.length;s++){let i=this.renderer.tracks[s],a=!1;for(let e of i.staves)if(e.showStandardNotation){a=!0;break}for(let r=0;r<i.staves.length;r++){let n,o=i.staves[r];if(o.isPercussion)n=t.Score;else if(this.renderer.settings.display.staveProfile!==t.Default)n=this.renderer.settings.display.staveProfile;else if(o.showTablature&&o.showStandardNotation)n=t.ScoreTab;else if(o.showTablature)n=a?t.TabMixed:t.Tab;else{if(!o.showStandardNotation)continue;n=t.Score}let h=ho.staveProfiles.get(n);for(let t of h)t.canCreate(i,o)&&e.addStaff(i,new Sr(s,o,t))}}return e}registerBarRenderer(e,t){this._barRendererLookup.has(e)||this._barRendererLookup.set(e,new Map),this._barRendererLookup.get(e).set(t.bar.id,t)}unregisterBarRenderer(e,t){if(this._barRendererLookup.has(e)){this._barRendererLookup.get(e).delete(t.bar.id)}}getRendererForBar(e,t){let s=t.id;return this._barRendererLookup.has(e)&&this._barRendererLookup.get(e).has(s)?this._barRendererLookup.get(e).get(s):null}layoutAndRenderAnnotation(e){let t="rendered by alphaTab",s=this.renderer.settings.display.resources,i=12*this.renderer.settings.display.scale,a=Math.floor(2*i);const r=new ci,n=new vs(s.copyrightFont.family,i,$.Plain,Z.Bold);this.renderer.canvas.font=n;const o=ho.getLayoutEngineFactory(this.renderer.settings.display.layoutMode).vertical;return r.width=this.renderer.canvas.measureText(t),r.height=a,r.x=o?(this.width-r.width)/2:this.firstBarX,r.y=e,r.totalWidth=this.width,r.totalHeight=e+a,r.firstMasterBarIndex=-1,r.lastMasterBarIndex=-1,this.registerPartial(r,(e=>{e.color=s.mainGlyphColor,e.font=n,e.textAlign=P.Left,e.fillText(t,0,i)})),e+a}}class Er{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class Cr extends Pr{constructor(e){super(e),this._group=null,this._pagePadding=null}get name(){return"HorizontalScreen"}get supportsResize(){return!1}get firstBarX(){let e=this._pagePadding[0];return this._group&&(e+=this._group.accoladeSpacing),e}doResize(){}doLayoutAndRender(){this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=Cr.PagePadding),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t));let s=t,i=this.renderer.settings.display.barCount;i<=0&&(i=e.masterBars.length),i=t+i-1,i=Math.min(e.masterBars.length-1,Math.max(0,i)),this._group=this.createEmptyStaveGroup(),this._group.isLast=!0,this._group.x=this._pagePadding[0],this._group.y=this._pagePadding[1];let a=this.renderer.settings.display.barCountPerPartial,r=[],n=new Er,o=0;for(;s<=i;){let t=this._group.addBars(this.renderer.tracks,s);if(t)if(0===n.masterBars.length&&t.isLinkedToPrevious&&r.length>0){let i=r[r.length-1];i.masterBars.push(e.masterBars[s]),i.width+=t.width,o+=t.width,n.x+=o}else n.masterBars.push(e.masterBars[s]),n.width+=t.width,n.masterBars.length>=a&&(0===r.length&&(n.width+=this._group.accoladeSpacing+this._pagePadding[0]),o+=n.width,r.push(n),Be.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null),n=new Er,n.x=o);s++}n.masterBars.length>0&&(0===r.length&&(n.width+=this._group.accoladeSpacing+this._pagePadding[0]),r.push(n),Be.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null)),this._group.finalizeGroup(),this.height=Math.floor(this._group.y+this._group.height),this.width=this._group.x+this._group.width+this._pagePadding[2],s=0;let h=0;for(let e=0;e<r.length;e++){const t=r[e],i=new ci;i.x=h,i.y=0,i.totalWidth=this.width,i.totalHeight=this.height,i.width=t.width,i.height=this.height,i.firstMasterBarIndex=t.masterBars[0].index,i.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,h+=t.width;const a=s,n=e;this._group.buildBoundingsLookup(this._group.x,this._group.y),this.registerPartial(i,(e=>{e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=P.Left;let s=this._group.getBarX(t.masterBars[0].index)+this._group.accoladeSpacing;0===n&&(s-=this._group.x+this._group.accoladeSpacing),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=P.Left,Be.debug(this.name,"Rendering partial from bar "+t.masterBars[0].index+" to "+t.masterBars[t.masterBars.length-1].index,null),this._group.paintPartial(-s,this._group.y,e,a,t.masterBars.length)})),s+=t.masterBars.length}this.height=this.layoutAndRenderAnnotation(this.height)+this._pagePadding[3]}}Cr.PagePadding=[20,20,20,20],Cr.GroupSpacing=20;class Fr extends Pr{constructor(e){super(e),this._groups=[],this._allMasterBarRenderers=[],this._barsFromPreviousGroup=[],this._pagePadding=null}get name(){return"PageView"}doLayoutAndRender(){this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=Fr.PagePadding),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let e=0;this.width=this.renderer.width,this._allMasterBarRenderers=[],e=this.layoutAndRenderScoreInfo(e,-1),e=this.layoutAndRenderTunings(e,-1),e=this.layoutAndRenderChordDiagrams(e,-1),e=this.layoutAndRenderScore(e),e=this.layoutAndRenderAnnotation(e),this.height=e+this._pagePadding[3]}get supportsResize(){return!0}get firstBarX(){let e=this._pagePadding[0];return this._groups.length>0&&(e+=this._groups[0].accoladeSpacing),e}doResize(){let e=0;this.width=this.renderer.width;let t=this.height;e=this.layoutAndRenderScoreInfo(e,t),e=this.layoutAndRenderTunings(e,t),e=this.layoutAndRenderChordDiagrams(e,t),e=this.resizeAndRenderScore(e,t),e=this.layoutAndRenderAnnotation(e),this.height=e+this._pagePadding[3]}layoutAndRenderTunings(e,t=-1){if(!this.tuningGlyph)return e;let s=this.renderer.settings.display.resources;this.tuningGlyph.x=this._pagePadding[0],this.tuningGlyph.width=this.width,this.tuningGlyph.doLayout();let i=this.tuningGlyph.height+11*this.scale;const a=new ci;return a.x=0,a.y=e,a.width=this.width,a.height=i,a.totalWidth=this.width,a.totalHeight=t<0?e+a.height:t,a.firstMasterBarIndex=-1,a.lastMasterBarIndex=-1,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=P.Center,this.tuningGlyph.paint(0,0,e)})),e+i}layoutAndRenderChordDiagrams(e,t=-1){if(!this.chordDiagrams)return e;const s=this.renderer.settings.display.resources;this.chordDiagrams.width=this.width,this.chordDiagrams.doLayout();const i=Math.floor(this.chordDiagrams.height),a=new ci;return a.x=0,a.y=e,a.width=this.width,a.height=i,a.totalWidth=this.width,a.totalHeight=t<0?e+i:t,a.firstMasterBarIndex=-1,a.lastMasterBarIndex=-1,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=P.Center,this.chordDiagrams.paint(0,0,e)})),e+i}layoutAndRenderScoreInfo(e,t=-1){Be.debug(this.name,"Layouting score info");const s=new ci;s.x=0,s.y=e;let i=this._pagePadding[1],a=this.scale,r=this.renderer.settings.display.resources,n=[k.ScoreTitle,k.ScoreSubTitle,k.ScoreArtist,k.ScoreAlbum,k.ScoreWordsAndMusic];for(let e=0;e<n.length;e++)if(this.scoreInfoGlyphs.has(n[e])){let t=this.scoreInfoGlyphs.get(n[e]);t.x=this.width/2,t.y=i,t.textAlign=P.Center,i+=t.font.size*a}let o=!1,h=0;if(this.scoreInfoGlyphs.has(k.ScoreMusic)){let e=this.scoreInfoGlyphs.get(k.ScoreMusic);e.x=this.width-this._pagePadding[2],e.y=i,e.textAlign=P.Right,o=!0,h=e.font.size*a}if(this.scoreInfoGlyphs.has(k.ScoreWords)){let e=this.scoreInfoGlyphs.get(k.ScoreWords);e.x=this._pagePadding[0],e.y=i,e.textAlign=P.Left,o=!0,h=e.font.size*a}return o&&(i+=h),i=Math.floor(i+17*this.scale),s.width=this.width,s.height=i,s.totalWidth=this.width,s.totalHeight=t<0?e+s.height:t,s.firstMasterBarIndex=-1,s.lastMasterBarIndex=-1,this.registerPartial(s,(e=>{e.color=r.scoreInfoColor,e.textAlign=P.Center;for(const t of this.scoreInfoGlyphs.values())t.paint(0,0,e)})),e+i}resizeAndRenderScore(e,t){if(-1!==this.renderer.settings.display.barsPerRow)for(let s=0;s<this._groups.length;s++){let i=this._groups[s];this.fitGroup(i),i.finalizeGroup(),e+=this.paintGroup(i,t)}else{this._groups=[];let s=0,i=this.maxWidth,a=this.createEmptyStaveGroup();for(a.index=this._groups.length,a.x=this._pagePadding[0],a.y=e;s<this._allMasterBarRenderers.length;){let r=this._allMasterBarRenderers[s];if(a.width+r.width<=i||0===a.masterBarsRenderers.length)a.addMasterBarRenderers(this.renderer.tracks,r),s++;else{for(;r&&!r.canWrap&&a.masterBarsRenderers.length>1;)r=a.revertLastBar(),s--;a.isFull=!0,a.isLast=this.lastBarIndex===a.lastBarIndex,this._groups.push(a),this.fitGroup(a),a.finalizeGroup(),e+=this.paintGroup(a,t),a=this.createEmptyStaveGroup(),a.index=this._groups.length,a.x=this._pagePadding[0],a.y=e}}a.isLast=this.lastBarIndex===a.lastBarIndex,this.fitGroup(a),a.finalizeGroup(),e+=this.paintGroup(a,t)}return e}layoutAndRenderScore(e){let t=this.firstBarIndex,s=this.lastBarIndex;for(this._groups=[];t<=s;){let i=this.createStaveGroup(t,s);this._groups.push(i),i.x=this._pagePadding[0],i.y=e,t=i.lastBarIndex+1,this.fitGroup(i),i.finalizeGroup(),Be.debug(this.name,"Rendering partial from bar "+i.firstBarIndex+" to "+i.lastBarIndex,null),e+=this.paintGroup(i,e)}return e}paintGroup(e,t){let s=Math.floor(e.height+20*this.scale);const i=new ci;return i.x=0,i.y=e.y,i.totalWidth=this.width,i.totalHeight=t,i.width=this.width,i.height=s,i.firstMasterBarIndex=e.firstBarIndex,i.lastMasterBarIndex=e.lastBarIndex,e.buildBoundingsLookup(0,0),this.registerPartial(i,(t=>{this.renderer.canvas.color=this.renderer.settings.display.resources.mainGlyphColor,this.renderer.canvas.textAlign=P.Left,e.paint(0,-i.y,t)})),t+=s,s}fitGroup(e){(e.isFull||e.width>this.maxWidth)&&e.scaleToWidth(this.maxWidth)}createStaveGroup(e,t){let s=this.createEmptyStaveGroup();s.index=this._groups.length;let i=this.renderer.settings.display.barsPerRow,a=this.maxWidth,r=t+1,n=e;for(;n<r;){if(this._barsFromPreviousGroup.length>0)for(let e of this._barsFromPreviousGroup)s.addMasterBarRenderers(this.renderer.tracks,e),n=e.masterBar.index;else{let e=s.addBars(this.renderer.tracks,n);e&&this._allMasterBarRenderers.push(e)}this._barsFromPreviousGroup=[];let e=!1;if((-1===i&&s.width>=a&&0!==s.masterBarsRenderers.length||s.masterBarsRenderers.length===i+1)&&(e=!0),e){let e=s.revertLastBar();if(e)for(this._barsFromPreviousGroup.push(e);e&&!e.canWrap&&s.masterBarsRenderers.length>1;)e=s.revertLastBar(),e&&this._barsFromPreviousGroup.push(e);return s.isFull=!0,s.isLast=!1,this._barsFromPreviousGroup.reverse(),s}s.x=0,n++}return s.isLast=t===s.lastBarIndex,s}get maxWidth(){return this.renderer.width-this._pagePadding[0]-this._pagePadding[2]}}Fr.PagePadding=[40,40,40,40],Fr.GroupSpacing=20;class Lr extends Li{constructor(e,t,s,i=!1){super(e,t,i?Mi.GraceScale:1,Lr.getMusicSymbol(s)),this._isGrace=i,this._accidentalType=s}static getMusicSymbol(e){switch(e){case re.Natural:return N.AccidentalNatural;case re.Sharp:return N.AccidentalSharp;case re.Flat:return N.AccidentalFlat;case re.NaturalQuarterNoteUp:return N.AccidentalQuarterToneNaturalArrowUp;case re.SharpQuarterNoteUp:return N.AccidentalQuarterToneSharpArrowUp;case re.FlatQuarterNoteUp:return N.AccidentalQuarterToneFlatArrowUp;case re.DoubleSharp:return N.AccidentalDoubleSharp;case re.DoubleFlat:return N.AccidentalDoubleFlat}return N.None}doLayout(){switch(this._accidentalType){case re.DoubleFlat:this.width=18;break;default:this.width=8}this.width=this.width*(this._isGrace?Mi.GraceScale:1)*this.scale}}class Mr extends Ci{constructor(e,t,s){super(e,t),this._number=0,this._number=s}doLayout(){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.barNumberFont,this.width=this.renderer.scoreRenderer.canvas.measureText(this._number.toString())+5*this.scale}paint(e,t,s){if(!this.renderer.staff.isFirstInAccolade)return;let i=this.renderer.resources,a=s.color;s.color=i.barNumberColor,s.font=i.barNumberFont,s.fillText(this._number.toString(),e+this.x,t+this.y),s.color=a}}class Ir extends Ci{constructor(e,t){super(e,t)}doLayout(){this.renderer.isLast?this.width=15*this.scale:this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart?this.width=2*this.scale:(this.width=2*this.scale,this.renderer.bar.masterBar.isDoubleBar&&(this.width+=2*this.scale))}paint(e,t,s){let i=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x,o=r-a;this.renderer.isLast?(s.fillRect(n+this.width-i-i,a,this.scale,o),s.fillRect(n+this.width-i,a,i,o)):this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart||(s.fillRect(n+this.width-this.scale,a,this.scale,o),this.renderer.bar.masterBar.isDoubleBar&&s.fillRect(n+this.width-5*this.scale,a,this.scale,o))}}class Dr extends Li{constructor(e,t,s,i){super(e,t,1,Dr.getSymbol(s)),this._clef=s,this._clefOttava=i}doLayout(){switch(this._clef){case r.Neutral:this.width=15*this.scale;break;case r.C3:case r.C4:case r.F4:case r.G2:this.width=28*this.scale}}static getSymbol(e){switch(e){case r.Neutral:return N.UnpitchedPercussionClef1;case r.C3:case r.C4:return N.CClef;case r.F4:return N.FClef;case r.G2:return N.GClef;default:return N.None}}paint(e,t,s){let i;super.paint(e,t,s);let a=!1;switch(this._clefOttava){case n._15ma:i=new Li(-4*this.scale,0,.5,N.Quindicesima),a=!0;break;case n._8va:i=new Li(-2*this.scale,0,.5,N.Ottava),a=!0;break;case n._8vb:i=new Li(-6*this.scale,0,.5,N.Ottava);break;case n._15mb:i=new Li(-8*this.scale,0,.5,N.Quindicesima);break;default:return}let o=0,h=0;switch(this._clef){case r.Neutral:o=a?-12:15,h=0;break;case r.C3:case r.C4:o=a?-19:27,h=0;break;case r.F4:o=a?-9:27,h=-4;break;case r.G2:o=a?-37:30,h=0;break;default:return}i.renderer=this.renderer,i.doLayout();let l=this.width/2;i.paint(e+this.x+l+h*this.scale,t+this.y+o*this.scale,s)}}class Rr extends Ci{constructor(e,t){super(e,t)}doLayout(){this.width=11*this.scale}paint(e,t,s){let i=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x,o=r-a,h=1.5*this.scale,l=(a+r)/2;s.fillCircle(n,l-3*h,h),s.fillCircle(n,l+3*h,h),n+=4*this.scale,s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke(),n+=3*this.scale+.5,s.fillRect(n,a,i,o)}}class Ar extends Ci{constructor(e,t,s){super(e,t),this._count=0,this._count=0,this._count=s}doLayout(){this.width=0}paint(e,t,s){let i=this.renderer.resources,a=s.textAlign;s.font=i.barNumberFont,s.textAlign=P.Right;let r="x"+this._count,n=s.measureText(r)/1.5;s.fillText(r,e+this.x-n,t+this.y),s.textAlign=a}}class Or extends Ci{constructor(e,t,s,i){super(e,t),this._dotOffset=0,this._circleSize=0,this._dotOffset=0,this._circleSize=0,this._dotOffset=i,this._circleSize=s}doLayout(){this.width=13*this.scale}paint(e,t,s){let i=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x+.5,o=r-a;s.fillRect(n,a,i,o),n+=2*i-.5,s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke(),n+=3*this.scale;let h=this._circleSize*this.scale,l=(a+r)/2;s.fillCircle(n,l-h*this._dotOffset,h),s.fillCircle(n,l+h*this._dotOffset,h)}}class Gr extends Li{constructor(e,t,s){super(e,t,1,Gr.getSymbol(s))}static getSymbol(e){switch(e){case i.None:return N.None;case i.Normal:return N.ArticAccentAbove;case i.Heavy:return N.ArticMarcatoAbove;default:return N.None}}doLayout(){this.width=9*this.scale,this.height=9*this.scale}paint(e,t,s){super.paint(e-2*this.scale,t+this.height,s)}}class Vr extends Ci{constructor(e,t,s){super(e,t),this._size=0,this._size=s}doLayout(){this.width=this._size+3*this.scale}paint(e,t,s){s.fillCircle(e+this.x,t+this.y,this._size)}}class Hr extends Li{constructor(e,t,s){super(e,t,s?Mi.GraceScale:1,N.NoteheadXOrnate),this._isGrace=s}doLayout(){this.width=9*(this._isGrace?Mi.GraceScale:1)*this.scale,this.height=Mi.NoteHeadHeight*this.scale}}class Wr extends Li{constructor(e,t,s,i){super(e,t,i?Mi.GraceScale:1,Wr.getSymbol(s)),this._isGrace=i}static getSymbol(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:case u.Whole:case u.Half:return N.NoteheadDiamondWhiteWide;default:return N.NoteheadDiamondBlackWide}}doLayout(){this.width=9*(this._isGrace?Mi.GraceScale:1)*this.scale,this.height=Mi.NoteHeadHeight*this.scale}}class zr extends Ci{constructor(e,t,s){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=H.Up,this.startBeat=e,this.endBeat=t,this.forEnd=s}doLayout(){this.width=0}paint(e,t,s){if(!this.endBeat)return;let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar);this.startNoteRenderer=i;let a=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.endBeat.voice.bar);this.endNoteRenderer=a;let r=0,n=0,o=0,h=0,l=!1;this.tieDirection=i?this.getBeamDirection(this.startBeat,i):this.getBeamDirection(this.endBeat,a),!this.forEnd&&i?(i!==a?(r=e+i.x+this.getStartX(),o=t+i.y+this.getStartY()+this.yOffset,a&&i.staff===a.staff?(n=e+a.x+this.getEndX(),h=t+a.y+this.getEndY()+this.yOffset):(n=e+i.x+i.width,h=o)):(r=e+i.x+this.getStartX(),n=e+a.x+this.getEndX(),o=t+i.y+this.getStartY()+this.yOffset,h=t+a.y+this.getEndY()+this.yOffset),l=!0):i&&i.staff===a.staff||(r=e+a.x,n=e+a.x+this.getEndX(),o=t+a.y+this.getEndY()+this.yOffset,h=o,l=!0),l&&(this.shouldDrawBendSlur()?zr.drawBendSlur(s,r,o,n,h,this.tieDirection===H.Down,this.scale):zr.paintTie(s,this.scale,r,o,n,h,this.tieDirection===H.Down,this.getTieHeight(r,o,n,h),4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,s,i){return 22}getBeamDirection(e,t){return H.Down}getStartY(){return 0}getEndY(){return 0}getStartX(){return 0}getEndX(){return 0}static paintTie(e,t,s,i,a,r,n=!1,o=22,h=4){if(s===a&&i===r)return;if(a<s){let e=s;s=a,a=e,e=i,i=r,r=e}o*=t,h*=t;let l=r-i,c=a-s,d=Math.sqrt(l*l+c*c);n?l*=-1:c*=-1,l/=d,c/=d;let u=(a+s)/2,p=(r+i)/2,g=u+o*l,f=p+o*c,m=u+(o-h)*l,y=p+(o-h)*c;e.beginPath(),e.moveTo(s,i),e.quadraticCurveTo(g,f,a,r),e.quadraticCurveTo(m,y,s,i),e.closePath(),e.fill()}static drawBendSlur(e,t,s,i,a,r,n,o){let h=a-s,l=i-t,c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;let d=(i+t)/2,u=(a+s)/2,p=zr.BendSlurHeight*n;i-t<20&&(p/=2);let g=d+p*h,f=u+p*l;if(e.beginPath(),e.moveTo(t,s),e.lineTo(g,f),e.lineTo(i,a),e.stroke(),o){let t=e.measureText(o),s=r?0:-e.font.size;e.fillText(o,g-t/2,f+s)}}}zr.BendSlurHeight=11;class Ur extends Ci{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=Ur.Size*this.scale}paint(e,t,s){this._isOpen?zr.paintTie(s,this.scale,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):zr.paintTie(s,this.scale,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3)}}Ur.Size=6;class Xr{constructor(e,t){this.line=0,this.line=e,this.isGhost=t}}class Yr extends Ci{constructor(e){super(0,0),this._infos=[],this._glyphs=[],this.isEmpty=!0,this._isOpen=e}addParenthesis(e){let t=this.renderer,s=t.getNoteLine(e),i=e.isGhost||this.isTiedBend(e)&&t.settings.notation.isNotationElementVisible(k.ParenthesisOnTiedBends);this.addParenthesisOnLine(s,i)}addParenthesisOnLine(e,t){let s=new Xr(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 Ur(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 qr{constructor(e,t){this.line=0,this.glyph=e,this.line=t}}class Jr extends Ci{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new fs,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){let s=new qr(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===H.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===H.Down?-e:0,r+=this._noteHeadPadding,this.upLineX=r,this.downLineX=0),this.displacedX=e,this.width=r}paint(e,t,s){e+=this.x,t+=this.y;let i=this.renderer,a=3*this.scale,r=this.width-this.noteStartX+2*a;if(this.hasTopOverflow){let n=s.color;s.color=i.resources.staffLineColor;let o=-2;for(;o>=this.minNote.line;){let n=t+i.getScoreY(o);s.fillRect(e-a+this.noteStartX,n,r,this.scale),o-=2}s.color=n}if(this.hasBottomOverflow){let n=s.color;s.color=i.resources.staffLineColor;let o=10;for(;o<=this.maxNote.line;){let n=t+i.getScoreY(o);s.fillRect(e-a+this.noteStartX,n,r,this.scale),o+=2}s.color=n}let n=this._infos,o=e+this._noteHeadPadding;for(let e of n)e.glyph.renderer=this.renderer,e.glyph.paint(o,t,s)}}class Qr extends Li{constructor(e,t,s){super(e,t,1,Qr.getSymbol(s))}doLayout(){this.width=12*this.scale}static getSymbol(e){switch(e){case u.ThirtySecond:return N.Tremolo3;case u.Sixteenth:return N.Tremolo2;case u.Eighth:return N.Tremolo1;default:return N.None}}}class jr extends Jr{constructor(){super(),this._noteGlyphLookup=new Map,this._notes=[],this._tremoloPicking=null,this.aboveBeatEffects=new Map,this.belowBeatEffects=new Map}get direction(){return this.beamingHelper.direction}getNoteX(e,t){if(this._noteGlyphLookup.has(e.id)){let s=this._noteGlyphLookup.get(e.id),i=this.x+s.x+this._noteHeadPadding;switch(t){case oe.Left:break;case oe.Center:i+=s.width/2;break;case oe.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 ne.TopWithStem:i-=this.renderer.getStemSize(this.beamingHelper);break;case ne.Top:i-=s.height/2;break;case ne.Center:break;case ne.Bottom:i+=s.height/2;break;case ne.BottomWithStem:i+=this.renderer.getStemSize(this.beamingHelper)}return i}return 0}addNoteGlyph(e,t,s){super.add(e,s),this._noteGlyphLookup.set(t.id,e),this._notes.push(t)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.upLineX,e+this.x+this.downLineX)}doLayout(){super.doLayout();let e=this.direction;for(const e of this.aboveBeatEffects.values())e.renderer=this.renderer,e.doLayout();for(const e of this.belowBeatEffects.values())e.renderer=this.renderer,e.doLayout();if(this.beat.isTremolo){let t=0,s=e===H.Up?this.minNote:this.maxNote,i=e===H.Up?this.displacedX:0,a=this.beat.tremoloSpeed;switch(a){case u.ThirtySecond:t=e===H.Up?-15:15;break;case u.Sixteenth:t=e===H.Up?-12:15;break;case u.Eighth:t=e===H.Up?-10:10;break;default:t=e===H.Up?-10:15}this._tremoloPicking=new Qr(i,s.glyph.y+t*this.scale,a),this._tremoloPicking.renderer=this.renderer,this._tremoloPicking.doLayout()}}buildBoundingsLookup(e,t,s){for(let i of this._notes)if(this._noteGlyphLookup.has(i.id)){let a=this._noteGlyphLookup.get(i.id),r=new gi;r.note=i,r.noteHeadBounds=new at,r.noteHeadBounds.x=t+this.x+this._noteHeadPadding+a.x,r.noteHeadBounds.y=s+this.y+a.y-a.height/2,r.noteHeadBounds.w=a.width,r.noteHeadBounds.h=a.height,e.addNote(r)}}paint(e,t,s){let i=this.renderer,a=0,r=0,n=1,o=-n;this.beamingHelper.direction===H.Up?(r=i.getScoreY(this.minNote.line),a=i.getScoreY(this.maxNote.line-2)):(r=i.getScoreY(this.maxNote.line-1),a=i.getScoreY(this.minNote.line+1),o*=-1,n*=-1);for(const i of this.aboveBeatEffects.values())a+=o*i.height,i.paint(e+this.x+2*this.scale,t+this.y+a,s);for(const i of this.belowBeatEffects.values())r+=n*i.height,i.paint(e+this.x+2*this.scale,t+this.y+r,s);super.paint(e,t,s),this._tremoloPicking&&this._tremoloPicking.paint(e,t,s)}}class Kr extends Li{constructor(e,t,s){super(e,t,1,Kr.getSymbol(s)),this._duration=s}static getSymbol(e){switch(e){case u.QuadrupleWhole:return N.RestLonga;case u.DoubleWhole:return N.RestDoubleWhole;case u.Whole:return N.RestWhole;case u.Half:return N.RestHalf;case u.Quarter:return N.RestQuarter;case u.Eighth:return N.RestEighth;case u.Sixteenth:return N.RestSixteenth;case u.ThirtySecond:return N.RestThirtySecond;case u.SixtyFourth:return N.RestSixtyFourth;case u.OneHundredTwentyEighth:return N.RestOneHundredTwentyEighth;case u.TwoHundredFiftySixth:return N.RestTwoHundredFiftySixth;default:return N.None}}static getSize(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:case u.Whole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:return 9;case u.ThirtySecond:return 12;case u.SixtyFourth:return 14;case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:return 20}return 10}doLayout(){this.width=Kr.getSize(this._duration)*this.scale}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class $r{constructor(){this.x=0,this.y=-3e3,this.width=0}}class Zr extends aa{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 $r);let t=21*this.scale;for(let s=0,i=this.glyphs.length;s<i;s++){let i=this.glyphs[s];i.renderer=this.renderer,i.doLayout();let a=0;for(;e[a].y>i.y;)a++,a===e.length&&e.push(new $r);i.x=a,e[a].y=i.y+t,e[a].width<i.width&&(e[a].width=i.width)}this.width=0;for(const t of e)this.width+=t.width,t.x=this.width;for(let t=0,s=this.glyphs.length;t<s;t++){let s=this.glyphs[t];const i=e[s.x];s.x=this.width-i.x}}}class en extends Jr{constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new Zr,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new Yr(!0),this._postNoteParenthesis=new Yr(!1))}get direction(){return H.Up}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 Mi(0,0,u.Quarter,!0),a=s.accidentalHelper.applyAccidentalForValue(this._beat,e,t,!0),r=s.accidentalHelper.getNoteLineForValue(e,!1);if(i.y=s.getScoreY(r),this._showParenthesis&&(this._preNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.addParenthesisOnLine(r,!0),this._postNoteParenthesis.addParenthesisOnLine(r,!0)),a!==re.None){let e=new Lr(0,i.y,a,!0);e.renderer=this.renderer,this._accidentals.renderer=this.renderer,this._accidentals.addGlyph(e)}this._noteValueLookup.set(e,i),this.add(i,r),this.isEmpty=!1}doLayout(){let e=0;this._showParenthesis&&(this._preNoteParenthesis.x=e,this._preNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.doLayout(),e+=this._preNoteParenthesis.width+en.ElementPadding*this.scale),this._accidentals.isEmpty||(e+=this._accidentals.width+en.ElementPadding*this.scale,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+en.ElementPadding*this.scale),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+en.ElementPadding*this.scale,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+en.ElementPadding*this.scale)}paint(e,t,s){this._accidentals.isEmpty||this._accidentals.paint(e+this.x,t+this.y,s),this._showParenthesis&&(this._preNoteParenthesis.paint(e+this.x,t+this.y,s),this._postNoteParenthesis.paint(e+this.x,t+this.y,s)),super.paint(e,t,s)}}en.ElementPadding=2;class tn extends Ci{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,s,i,a,r,n,o){zr.drawBendSlur(e,t,s,i,a,r,n,o)}doLayout(){super.doLayout(),this.width=0;for(let e of this.BendNoteHeads)e.doLayout(),this.width+=e.width+10*this.scale}getTieDirection(e,t){switch(t.getBeatDirection(e)){case H.Up:return H.Down;default:return H.Up}}}tn.EndPadding=8;class sn extends be{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class an extends Ci{constructor(){super(0,0),this._notes=[],this._renderPoints=new Map,this._preBendMinValue=-1,this._bendMiddleMinValue=-1,this._bendEndMinValue=-1,this._bendEndContinuedMinValue=-1,this._releaseMinValue=-1,this._releaseContinuedMinValue=-1,this._maxBendValue=-1}addBends(e){this._notes.push(e);let t=this.createRenderingPoints(e);this._renderPoints.set(e.id,t),(-1===this._maxBendValue||this._maxBendValue<e.maxBendPoint.value)&&(this._maxBendValue=e.maxBendPoint.value);let s=0;switch(e.bendType){case l.Bend:s=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||s<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=s):(-1===this._bendEndMinValue||s<this._bendEndMinValue)&&(this._bendEndMinValue=s);break;case l.Release:s=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s);break;case l.BendRelease:s=t[1].value,(-1===this._bendMiddleMinValue||s<this._bendMiddleMinValue)&&(this._bendMiddleMinValue=s),s=t[2].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s);break;case l.Prebend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s);break;case l.PrebendBend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s),s=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||s<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=s):(-1===this._bendEndMinValue||s<this._bendEndMinValue)&&(this._bendEndMinValue=s);break;case l.PrebendRelease:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s),s=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s)}}doLayout(){super.doLayout();let e=this._maxBendValue*an.BendValueHeight*this.scale;this.renderer.registerOverflowTop(e);let t=0;for(let e of this._notes){let s=this._renderPoints.get(e.id);switch(e.bendType){case l.Bend:s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case l.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t);break;case l.BendRelease:s[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[2].lineValue=t);break;case l.Prebend:s[0].lineValue=this._preBendMinValue;break;case l.PrebendBend:s[0].lineValue=this._preBendMinValue,s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case l.PrebendRelease:s[0].lineValue=this._preBendMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t)}}this.width=0,this._notes.sort(((e,t)=>e.isStringed?e.string-t.string:e.realValue-t.realValue))}createRenderingPoints(e){let t=[];switch(e.bendType){case l.Custom:for(let s of e.bendPoints)t.push(new sn(s.offset,s.value));break;case l.BendRelease:t.push(new sn(0,e.bendPoints[0].value)),t.push(new sn(be.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new sn(be.MaxPosition,e.bendPoints[3].value));break;case l.Bend:case l.Hold:case l.Prebend:case l.PrebendBend:case l.PrebendRelease:case l.Release:t.push(new sn(0,e.bendPoints[0].value)),t.push(new sn(be.MaxPosition,e.bendPoints[1].value))}return t}paint(e,t,s){let i=s.color;this._notes.length>1&&(s.color=this.renderer.resources.secondaryGlyphColor);for(let a of this._notes){let r=this._renderPoints.get(a.id),n=this.renderer,o=a,c=!1,d=null,u=!1,p=a.bendStyle===h.Gradual?"grad.":"",g=null;for(;o.isTieOrigin;){let e=o.tieDestination;if(d=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,e.beat.voice.bar),!d||n.staff!==d.staff)break;if(o=e,c=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes){u=!0;break}}g=o.beat,d=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,g.voice.bar),g.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(g=null);let f=0,m=0,y=t+n.y;f=e+n.x,r[0].value>0||a.isContinuedBend?f+=n.getBeatX(a.beat,ae.MiddleNotes):f+=n.getNoteX(a,oe.Right),m=!g||g.isLastOfVoice&&!u?e+d.x+d.postBeatGlyphsStart:u||!g.nextBeat?e+d.x+d.getBeatX(g,ae.MiddleNotes):a.bendType===l.Hold?e+d.x+d.getBeatX(g.nextBeat,ae.OnNotes):e+d.x+d.getBeatX(g.nextBeat,ae.PreNotes),c||(m-=an.ArrowSize*this.scale);let b=(m-f)/be.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 sn(0,0),t,f,y,b,p,s),a.bendType!==l.Prebend?(0===e&&(f+=2*this.scale),this.paintBend(a,t,i,f,y,b,p,s)):a.isTieOrigin&&a.tieDestination.hasBend&&(i=new sn(be.MaxPosition,t.value),i.lineValue=t.lineValue,this.paintBend(a,t,i,f,y,b,p,s))}s.color=i}}paintBend(e,t,s,i,a,r,n,o){let h=this.renderer,l=this.renderer.resources,c=h.lineOffset/2,d=i+r*t.offset,u=an.BendValueHeight*this.scale,p=a-u*t.lineValue;0===t.value?s.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,ne.Top):p+=h.getNoteY(e,ne.Center):p+=c;let g=i+r*s.offset,f=a-u*s.lineValue;0===s.lineValue?f+=h.getNoteY(e,ne.Center):f+=c;let m=0,y=an.ArrowSize*this.scale;if(s.value>t.value?(f+y>p&&(f=p-y),o.beginPath(),o.moveTo(g,f),o.lineTo(g-.5*y,f+y),o.lineTo(g+.5*y,f+y),o.closePath(),o.fill(),m=y):s.value!==t.value&&(f<p&&(f=p+y),o.beginPath(),o.moveTo(g,f),o.lineTo(g-.5*y,f-y),o.lineTo(g+.5*y,f-y),o.closePath(),o.fill(),m=-y),o.stroke(),t.value===s.value){if(t.lineValue>0){let e=g,t=an.DashSize*this.scale,s=d+t;if((e-d)/(2*t)<1)o.moveTo(e,p),o.lineTo(d,p);else for(;e>s;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>d?(o.moveTo(d,p),o.bezierCurveTo((d+g)/2,p,g,p,g,f+m),o.stroke()):(o.moveTo(d,p),o.lineTo(g,f),o.stroke());if(n&&t.offset<s.offset){o.font=l.graceFont;let e=o.measureText(n),t=0,s=0;if(p>f){let i=Math.abs(p-f);t=i>1.3*o.font.size?p-i/2:p,s=(d+g-e)/2}else t=p,s=g-e;o.fillText(n,s,t)}if(0!==s.value&&t.value!==s.value){let e=s.value,i=s.value>t.value;e=Math.abs(e);let r="";if(4===e)r="full",e-=4;else if(e>=4||e<=-4){let t=e/4|0;r+=t,e-=4*t}if(e>0&&(r+=an.getFractionSign(e)),""!==r){f=a-u*s.value;let e=f;i||(e=p+1*Math.abs(f-p)/3),o.font=l.tablatureFont;let t=o.measureText(r),n=e-.5*l.tablatureFont.size-2*this.scale,h=g-t/2;o.fillText(r,h,n)}}}static getFractionSign(e){switch(e){case 1:return"¼";case 2:return"½";case 3:return"¾";default:return e+"/ 4"}}}an.ArrowSize=6,an.DashSize=3,an.BendValueHeight=6;class rn extends Ci{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===C.Custom)return e.whammyBarPoints;let t=[];switch(e.whammyBarType){case C.Dive:case C.Hold:case C.PrediveDive:case C.Predive:t.push(new be(0,e.whammyBarPoints[0].value)),t.push(new be(be.MaxPosition,e.whammyBarPoints[1].value));break;case C.Dip:t.push(new be(0,e.whammyBarPoints[0].value)),t.push(new be(be.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new be(be.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===C.Dip;let e=null,t=null,s=this._beat;for(;s&&s.hasWhammyBar;)(!e||e.value>s.minWhammyPoint.value)&&(e=s.minWhammyPoint),(!t||t.value<s.maxWhammyPoint.value)&&(t=s.maxWhammyPoint),s=s.nextBeat;let i=t.value>0?Math.abs(this.getOffset(t.value)):0;(i>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys))&&(i+=2*this.renderer.resources.tablatureFont.size);let a=e.value<0?Math.abs(this.getOffset(e.value)):0;this.renderer.registerOverflowTop(i+a),i>this.renderer.staff.getSharedLayoutData(rn.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(rn.TopOffsetSharedDataKey,i)}getOffset(e){if(0===e)return 0;let t=rn.PerHalfSize*this.scale+Math.log2(Math.abs(e)/2)*rn.PerHalfSize*this.scale;return e<0&&(t=-t),t}paint(e,t,s){let i=this.renderer,a=this._beat.nextBeat,r=null,n=ae.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===C.Dip?ae.PreNotes:ae.MiddleNotes:(a=null,r=null));let o=0,l=0;this._isSimpleDip?(o=e+i.x+i.getBeatX(this._beat,ae.OnNotes)-2*this.scale,l=e+i.x+i.getBeatX(this._beat,ae.PostNotes)+2*this.scale):(o=e+i.x+i.getBeatX(this._beat,ae.MiddleNotes),l=r?e+r.x+r.getBeatX(a,n):e+i.x+i.width-2*this.scale);let c=s.textAlign;if(s.textAlign=P.Center,this._renderPoints.length>=2){let e=(l-o)/be.MaxPosition;s.beginPath();let i=t+this.renderer.staff.getSharedLayoutData(rn.TopOffsetSharedDataKey,0),a=this._beat.whammyStyle===h.Gradual?"grad.":"";for(let t=0,r=this._renderPoints.length-1;t<r;t++){let n=this._renderPoints[t],h=this._renderPoints[t+1],l=t<r-2?this._renderPoints[t+2]:null,c=0===t;0!==t||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new be(0,0),n,h,o,i,e,s),c=!1),this.paintWhammy(c,n,h,l,o,i,e,s,a),a=""}s.stroke()}s.textAlign=c}paintWhammy(e,t,s,i,a,r,n,o,h){let l=a+n*t.offset,c=a+n*s.offset,d=r-this.getOffset(t.value),u=r-this.getOffset(s.value);if(t.offset===s.offset){let e=rn.DashSize*this.scale;if(Math.abs(u-d)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(d,u),s=Math.min(d,u);for(;t>s;)o.moveTo(l,s),o.lineTo(l,s+e),s+=2*e}o.stroke()}else if(t.value===s.value){let e=rn.DashSize*this.scale;if(Math.abs(c-l)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(l,c),s=Math.min(l,c);for(;t>s;)o.moveTo(t,d),o.lineTo(t-e,d),t-=2*e}o.stroke()}else o.moveTo(l,d),o.lineTo(c,u);let p=this.renderer.resources;if(e&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let e=d;e-=p.tablatureFont.size+2*this.scale,this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2*this.scale,o.fillText(h,l,e))}let g=Math.abs(s.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys)&&!this._isSimpleDip)&&t.value!==s.value){let e="";if(s.value<0&&(e+="-"),g>=4){let t=g/4|0;e+=t,g-=4*t}else 0===g&&(e+="0");g>0&&(e+=an.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(d,u)-p.tablatureFont.size-2*this.scale:(a=t.offset===s.offset?Math.min(d,u):u,a-=p.tablatureFont.size+2*this.scale,i&&i.value>s.value&&(a-=2*this.scale));let r=c;o.fillText(e,r,a)}}}rn.TopOffsetSharedDataKey="tab.whammy.topoffset",rn.PerHalfSize=6,rn.DashSize=3;class nn extends tn{constructor(e){super(0,0),this._beat=e}doLayout(){let e=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case C.None:case C.Custom:case C.Hold:return;case C.Dive:case C.PrediveDive:{let e=new en(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 C.Dip:if(e===T.SongBook){let e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+nn.SimpleDipHeight*this.scale+nn.SimpleDipPadding*this.scale}else{let e=new en(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 en(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)}break;case C.Predive:}super.doLayout()}paint(e,t,s){let i=this._beat;switch(i.whammyBarType){case C.None:case C.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,ae.MiddleNotes),o=this.getTieDirection(i,r),l=1===this._beat.notes.length?o:H.Up,c=s.textAlign;for(let c=0;c<i.notes.length;c++){let d=i.notes[c],u=t+r.y;c>0&&c>=(this._beat.notes.length/2|0)&&(l=H.Down),l===H.Down?u+=r.getNoteY(d,ne.Bottom):u+=r.getNoteY(d,ne.Top);let p=e+r.x;i.isLastOfVoice?p+=r.width:p+=r.getBeatX(i,ae.EndBeat),p-=8*this.scale;let g=i.whammyStyle===h.Gradual&&0===c?"grad.":"",f=null;d.isTieOrigin&&(f=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,d.tieDestination.beat.voice.bar),f&&f.staff===r.staff?p=e+f.x+f.getBeatX(d.tieDestination.beat,ae.MiddleNotes):f=null);let m=Mi.NoteHeadHeight*this.scale*Mi.GraceScale*.5;l===H.Up&&(m=-m);let y=i.whammyBarPoints.length>0?this.getBendNoteValue(d,i.whammyBarPoints[i.whammyBarPoints.length-1]):0,b=0,S=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(y)?(b=this.BendNoteHeads[0].getNoteValueY(y)+m,S=!0):f&&(d.isTieOrigin&&d.tieDestination.beat.hasWhammyBar||d.beat.isContinuedWhammy)?(b=t+f.y+f.getNoteY(d.tieDestination,ne.Top),S=!0,l===H.Down&&(b+=Mi.NoteHeadHeight*this.scale)):d.isTieOrigin&&(b=f?t+f.y+f.getNoteY(d.tieDestination,ne.Top):u,l===H.Down&&(b+=Mi.NoteHeadHeight*this.scale)),i.whammyBarType){case C.Hold:d.isTieOrigin&&zr.paintTie(s,this.scale,n,u,p,b,o===H.Down,22,4);break;case C.Dive:0===c&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.BendNoteHeads[0].containsNoteValue(y)&&(b+=this.BendNoteHeads[0].y)),S?this.drawBendSlur(s,n,u,p,b,l===H.Down,this.scale,g):d.isTieOrigin&&zr.paintTie(s,this.scale,n,u,p,b,o===H.Down,22,4);break;case C.Dip:if(a===T.SongBook){if(0===c){let i=e+r.x+r.getBeatX(this._beat,ae.OnNotes)-2*this.scale,a=e+r.x+r.getBeatX(this._beat,ae.PostNotes)+2*this.scale,n=(i+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();s.font=this.renderer.resources.tablatureFont,s.fillText(o,n,t+this.y);let h=t+this.y+s.font.size+2*this.scale,l=h+nn.SimpleDipHeight*this.scale;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(s.moveTo(i,l),s.lineTo(n,h),s.lineTo(a,l)):(s.moveTo(i,h),s.lineTo(n,l),s.lineTo(a,h)),s.stroke()}d.isTieOrigin&&zr.paintTie(s,this.scale,n,u,p,b,o===H.Down,22,4)}else{let e=(n+p)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s);let a=this.getBendNoteValue(d,i.whammyBarPoints[1]),o=this.BendNoteHeads[0].getNoteValueY(a)+m;this.drawBendSlur(s,n,u,e,o,l===H.Down,this.scale,g),this.BendNoteHeads[1].x=p-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=t+r.y,this.BendNoteHeads[1].paint(0,0,s),b=this.BendNoteHeads[1].getNoteValueY(y)+m,this.drawBendSlur(s,e,o,p,b,l===H.Down,this.scale,g)}break;case C.PrediveDive:case C.Predive:let h=e+r.x+r.getBeatX(d.beat,ae.PreNotes);h+=r.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let f=t+r.y+r.getScoreY(r.accidentalHelper.getNoteLineForValue(d.displayValue-(d.beat.whammyBarPoints[0].value/2|0),!1))+m;this.drawBendSlur(s,h,f,n,u,l===H.Down,this.scale,g),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.drawBendSlur(s,n,u,p,b,l===H.Down,this.scale,g))}}s.textAlign=c}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}nn.SimpleDipHeight=2*rn.PerHalfSize,nn.SimpleDipPadding=2;class on extends Ci{constructor(e,t,s){super(e,t),this.width=s}}class hn extends Li{constructor(e,t,s,i,a){super(e,t,a?Mi.GraceScale:1,s.getSymbol(i)),this._isGrace=a,this._articulation=s}paint(e,t,s){let i=this._isGrace?this.scale:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale*this.scale,this.symbol,!1),this._articulation.techniqueSymbol!==N.None&&this._articulation.techniqueSymbolPlacement===E.Middle&&s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale*this.scale,this._articulation.techniqueSymbol,!1)}doLayout(){let e=(this._isGrace?Mi.GraceScale:1)*this.scale;switch(this.symbol){case N.NoteheadWhole:this.width=14;break;case N.NoteheadCircleX:case N.NoteheadDiamondWhite:this.width=9;break;case N.NoteheadHeavyXHat:case N.NoteheadHeavyX:this.width=13;break;default:this.width=10}this.width=this.width*(this._isGrace?Mi.GraceScale:1)*this.scale,this.height=Mi.NoteHeadHeight*e}}class ln extends Li{constructor(e,t){super(e,t,Mi.GraceScale,N.ArticStaccatoAbove)}doLayout(){this.width=Mi.QuarterNoteHeadWidth*this.scale,this.height=7*this.scale}paint(e,t,s){super.paint(e+3*this.scale,t+5*this.scale,s)}}class cn extends Li{constructor(e,t){super(e,t,.5,N.PictEdgeOfCymbal)}doLayout(){this.width=22*this.scale,this.height=15*this.scale}paint(e,t,s){super.paint(e-3*this.scale,t+this.height,s)}}class dn extends Li{constructor(e,t){super(e,t,Mi.GraceScale,N.GuitarGolpe)}doLayout(){this.width=9*this.scale,this.height=10*this.scale}paint(e,t,s){super.paint(e,t+this.height,s)}}class un extends Ba{constructor(){super(...arguments),this._collisionOffset=-1e3,this._skipPaint=!1,this.noteHeads=null,this.restGlyph=null}getNoteX(e,t){return this.noteHeads?this.noteHeads.getNoteX(e,t):0}buildBoundingsLookup(e,t,s){this.noteHeads&&this.noteHeads.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteY(e,t){return this.noteHeads?this.noteHeads.getNoteY(e,t):0}updateBeamingHelper(){if(this.noteHeads)this.noteHeads.updateBeamingHelper(this.container.x+this.x);else if(this.restGlyph&&(this.restGlyph.updateBeamingHelper(this.container.x+this.x),this.renderer.bar.isMultiVoice&&-1e3===this._collisionOffset)){this._collisionOffset=this.renderer.helpers.collisionHelper.applyRestCollisionOffset(this.container.beat,this.restGlyph.y,this.renderer.getScoreHeight(1)),this.y+=this._collisionOffset;const e=this.renderer.helpers.collisionHelper.restDurationsByDisplayTime;e.has(this.container.beat.playbackStart)&&e.get(this.container.beat.playbackStart).has(this.container.beat.playbackDuration)&&e.get(this.container.beat.playbackStart).get(this.container.beat.playbackDuration)!==this.container.beat.id&&(this._skipPaint=!0)}}paint(e,t,s){this._skipPaint||super.paint(e,t,s)}doLayout(){let e=this.renderer;if(!this.container.beat.isEmpty)if(this.container.beat.isRest){let t=2*Math.ceil((this.renderer.bar.staff.standardNotationLineCount-1)/2);this.container.beat.duration===u.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const s=new Kr(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=da.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 on(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++){let e=new aa(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addGlyph(e)}}}else{const t=new jr;this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper;let s=new Yr(!1);s.renderer=this.renderer;for(let e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),s.addParenthesis(e));if(this.addGlyph(t),s.isEmpty||(this.addGlyph(new on(0,0,4*(this.container.beat.graceType!==g.None?Mi.GraceScale:1)*this.scale)),this.addGlyph(s)),this.container.beat.hasWhammyBar){let e=new nn(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addGlyph(new on(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++){let t=new aa(0,0);t.renderer=this.renderer;for(let s of this.container.beat.notes)this.createBeatDot(e.getNoteLine(s),t);this.addGlyph(t)}}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.container.beat.isRest?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.centerX=this.noteHeads.x+this.noteHeads.width/2}createBeatDot(e,t){let s=this.renderer;t.addGlyph(new Vr(0,s.getScoreY(e),1.5*this.scale))}createNoteHeadGlyph(e){let t=this.container.beat.graceType!==g.None;if(e.beat.voice.bar.staff.isPercussion){const s=xe.getArticulation(e);if(s)return new hn(0,0,s,e.beat.duration,t);Be.warning("Rendering","No articulation found for percussion instrument "+e.percussionArticulation)}return e.isDead?new Hr(0,0,t):e.beat.graceType===g.BendGrace?new Mi(0,0,u.Quarter,!0):e.harmonicType===m.Natural?new Wr(0,0,e.beat.duration,t):new Mi(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===g.BendGrace&&!e.hasBend)return;let t=this.renderer,s=this.createNoteHeadGlyph(e),a=t.getNoteLine(e);if(s.y=t.getScoreY(a),this.noteHeads.addNoteGlyph(s,e,a),e.harmonicType!==m.None&&e.harmonicType!==m.Natural){let i=e.displayValue+e.harmonicPitch;s=new Wr(0,0,e.beat.duration,this.container.beat.graceType!==g.None),a=t.accidentalHelper.getNoteLineForValue(i,!1),s.y=t.getScoreY(a),this.noteHeads.addNoteGlyph(s,e,a)}if(e.isStaccato&&!this.noteHeads.aboveBeatEffects.has("Staccato")&&this.noteHeads.belowBeatEffects.set("Staccato",new ln(0,0)),e.accentuated!==i.Normal||this.noteHeads.aboveBeatEffects.has("Accent")||this.noteHeads.belowBeatEffects.set("Accent",new Gr(0,0,i.Normal)),e.accentuated!==i.Heavy||this.noteHeads.aboveBeatEffects.has("HAccent")||this.noteHeads.belowBeatEffects.set("HAccent",new Gr(0,0,i.Heavy)),e.isPercussion){const t=xe.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==E.Middle){const e=t.techniqueSymbolPlacement===E.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case N.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new cn(0,0));break;case N.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new ln(0,0));break;case N.StringsUpBow:e.set("StringsUpBow",new $a(0,0,x.Up));break;case N.StringsDownBow:e.set("StringsDownBow",new $a(0,0,x.Down));break;case N.GuitarGolpe:e.set("GuitarGolpe",new dn(0,0))}}}}}class pn extends Ci{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10*this.scale}paint(e,t,s){let i=this.renderer,a=i.lineOffset,r=t+this.y+(i.getNoteY(this._beat.maxNote,ne.Bottom)-a),n=t+this.y+i.getNoteY(this._beat.minNote,ne.Top)+a,o=e+this.x+this.width/2,h=8*this.scale;if(this._beat.brushType!==c.None){let t=new sr(0,0,w.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let i=-t.height/2;if(this._beat.brushType===c.ArpeggioUp){let a=r+h,l=n-h;t.width=Math.abs(l-a),s.beginRotate(e+this.x+5*this.scale,l,-90),t.paint(0,i,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 a=r+h,l=n;t.width=Math.abs(l-a),s.beginRotate(e+this.x+5*this.scale,a,90),t.paint(0,i,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 gn extends _a{constructor(){super(),this._prebends=null,this.accidentals=null}get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}doLayout(){if(!this.container.beat.isRest){let e=new Zr;e.renderer=this.renderer;let t=new Yr(!0);t.renderer=this.renderer;const s=new en(this.container.beat,!0);this._prebends=s,s.renderer=this.renderer;for(let i of this.container.beat.notes)if(i.isVisible){if(i.hasBend)switch(i.bendType){case l.PrebendBend:case l.Prebend:case l.PrebendRelease:s.addGlyph(i.displayValue-(i.bendPoints[0].value/2|0),!1)}else if(i.beat.hasWhammyBar)switch(i.beat.whammyBarType){case C.PrediveDive:case C.Predive:this._prebends.addGlyph(i.displayValue-(i.beat.whammyBarPoints[0].value/2|0),!1)}this.createAccidentalGlyph(i,e),t.addParenthesis(i)}s.isEmpty||(this.addGlyph(s),this.addGlyph(new on(0,0,4*(this.container.beat.graceType!==g.None?Mi.GraceScale:1)*this.scale))),this.container.beat.brushType!==c.None&&(this.addGlyph(new pn(this.container.beat)),this.addGlyph(new on(0,0,4*this.scale))),t.isEmpty||(this.addGlyph(t),this.addGlyph(new on(0,0,4*(this.container.beat.graceType!==g.None?Mi.GraceScale:1)*this.scale))),e.isEmpty||(this.accidentals=e,this.addGlyph(new on(0,0,2*(this.container.beat.graceType!==g.None?Mi.GraceScale:1)*this.scale)),this.addGlyph(e),this.addGlyph(new on(0,0,2*(this.container.beat.graceType!==g.None?Mi.GraceScale:1)*this.scale)))}super.doLayout()}createAccidentalGlyph(e,t){let s=this.renderer,i=s.accidentalHelper.applyAccidental(e),a=s.getNoteLine(e),r=this.container.beat.graceType!==g.None;if(i!==re.None){let e=new Lr(0,s.getScoreY(a),i,r);e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==m.None&&e.harmonicType!==m.Natural){let n=e.displayValue+e.harmonicPitch;i=s.accidentalHelper.applyAccidentalForValue(e.beat,n,r,!1),a=s.accidentalHelper.getNoteLineForValue(n,!1);let o=new Lr(0,s.getScoreY(a),i,r);o.renderer=this.renderer,t.addGlyph(o)}}}class fn extends Li{constructor(e,t,s,i){super(e,t,i,fn.getSymbol(s)),this._digit=0,this._scale=0,this._digit=s,this._scale=i}doLayout(){this.width=this.getDigitWidth(this._digit)*this.scale*this._scale}getDigitWidth(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:return 14;case 1:return 10;default:return 0}}static getSymbol(e){switch(e){case 0:return N.TimeSig0;case 1:return N.TimeSig1;case 2:return N.TimeSig2;case 3:return N.TimeSig3;case 4:return N.TimeSig4;case 5:return N.TimeSig5;case 6:return N.TimeSig6;case 7:return N.TimeSig7;case 8:return N.TimeSig8;case 9:return N.TimeSig9;default:return N.None}}}class mn extends aa{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 fn(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}}}mn.numberHeight=18;class yn extends aa{constructor(e,t,s,i,a){super(e,t),this._numerator=0,this._denominator=0,this._numerator=s,this._denominator=i,this._isCommon=a}doLayout(){if(this._isCommon&&2===this._numerator&&2===this._denominator){let e=new Li(0,0,this.commonScale,N.TimeSigCutCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){let e=new Li(0,0,this.commonScale,N.TimeSigCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else{const e=mn.numberHeight*this.scale;let t=new mn(0,-e/2,this._numerator,this.numberScale),s=new mn(0,e/2,this._denominator,this.numberScale);this.addGlyph(t),this.addGlyph(s),super.doLayout();for(let e=0,t=this.glyphs.length;e<t;e++){let t=this.glyphs[e];t.x=(this.width-t.width)/2}}}}class bn extends yn{get commonScale(){return 1}get numberScale(){return 1}}class Sn extends tn{constructor(e){super(0,0),this._notes=[],this._endNoteGlyph=null,this._middleNoteGlyph=null,this._beat=e}addBends(e){if(this._notes.push(e),!e.isTieOrigin)switch(e.bendType){case l.Bend:case l.PrebendRelease:case l.PrebendBend:{let t=this._endNoteGlyph;t||(t=new en(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let s=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,s),s.value%2!=0)}break;case l.Release:if(!e.isTieOrigin){let t=this._endNoteGlyph;t||(t=new en(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let s=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,s),s.value%2!=0)}break;case l.BendRelease:{let t=this._middleNoteGlyph;t||(t=new en(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 en(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,ae.MiddleNotes),r=e+i.x;this._beat.isLastOfVoice?r+=i.postBeatGlyphsStart:r+=i.getBeatX(this._beat.nextBeat,ae.PreNotes),r-=8*this.scale;let n=(a+r)/2;this._middleNoteGlyph&&(this._middleNoteGlyph.x=n-this._middleNoteGlyph.noteHeadOffset,this._middleNoteGlyph.y=t+i.y,this._middleNoteGlyph.paint(0,0,s)),this._endNoteGlyph&&(this._endNoteGlyph.x=r-this._endNoteGlyph.noteHeadOffset,this._endNoteGlyph.y=t+i.y,this._endNoteGlyph.paint(0,0,s)),this._notes.sort(((e,t)=>t.displayValue-e.displayValue));let o=this._beat.graceType===g.BendGrace?this._beat.nextBeat:this._beat,c=1===this._notes.length?this.getTieDirection(o,i):H.Up;for(let o=0;o<this._notes.length;o++){let d=this._notes[o];o>0&&o>=(this._notes.length/2|0)&&(c=H.Down);let u=t+i.y+i.getNoteY(d,ne.Top),p=Mi.NoteHeadHeight*this.scale*Mi.GraceScale*.5;c===H.Down&&(u+=Mi.NoteHeadHeight*this.scale);let g=d.bendStyle===h.Gradual?"grad.":"";if(d.isTieOrigin){let r=d.tieDestination,n=r?this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.beat.voice.bar):null;if(n&&n.staff===i.staff){let i=e+n.x+n.getBeatX(r.beat,ae.MiddleNotes),o=t+n.y+n.getNoteY(r,ne.Top);c===H.Down&&(o+=Mi.NoteHeadHeight*this.scale),d.bendType===l.Hold||d.bendType===l.Prebend?zr.paintTie(s,this.scale,a,u,i,o,c===H.Down,22,4):this.drawBendSlur(s,a,u,i,o,c===H.Down,this.scale,g)}else{let r=e+i.x+i.width,n=d.tieDestination.realValue;i.accidentalHelper.applyAccidentalForValue(d.beat,n,!1,!0);let o=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(n,!1));d.bendType===l.Hold||d.bendType===l.Prebend?zr.paintTie(s,this.scale,a,u,r,o,c===H.Down,22,4):this.drawBendSlur(s,a,u,r,o,c===H.Down,this.scale,g)}switch(d.bendType){case l.Prebend:case l.PrebendBend:case l.PrebendRelease:let r=e+i.x+i.getBeatX(d.beat,ae.PreNotes);r+=i.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let n=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(d.displayValue-(d.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,r,n,a,u,c===H.Down,this.scale)}}else{c===H.Up&&(p=-p);let o=0,h=0;switch(d.bendType){case l.Bend:o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,h,c===H.Down,this.scale,g);break;case l.BendRelease:let f=this.getBendNoteValue(d,d.bendPoints[1]),m=this._middleNoteGlyph.getNoteValueY(f)+p;this.drawBendSlur(s,a,u,n,m,c===H.Down,this.scale,g),o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,n,m,r,h,c===H.Down,this.scale,g);break;case l.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,h,c===H.Down,this.scale,g));break;case l.Prebend:case l.PrebendBend:case l.PrebendRelease:let y=e+i.x+i.getBeatX(d.beat,ae.PreNotes);y+=i.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let b=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(d.displayValue-(d.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,y,b,a,u,c===H.Down,this.scale),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,h,c===H.Down,this.scale,g))}}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class wn extends zr{constructor(e,t,s=!1){super(e,t,s)}doLayout(){super.doLayout()}getBeamDirection(e,t){if(e.isRest)return H.Up;switch(t.getBeatDirection(e)){case H.Up:return H.Down;default:return H.Up}}getStartY(){if(this.startBeat.isRest)return this.startNoteRenderer.getScoreY(9);switch(this.tieDirection){case H.Up:return this.startNoteRenderer.getNoteY(this.startBeat.maxNote,ne.Top);default:return this.startNoteRenderer.getNoteY(this.startBeat.minNote,ne.Bottom)}}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)switch(this.tieDirection){case H.Up:return e.getScoreY(9);default:return e.getScoreY(0)}const t=this.startNoteRenderer.getBeatDirection(this.startBeat),s=e.getBeatDirection(this.endBeat);if(t!==s&&this.startBeat.graceType===g.None)if(s===this.tieDirection)switch(this.tieDirection){case H.Up:return e.getNoteY(this.endBeat.maxNote,ne.TopWithStem);default:return e.getNoteY(this.endBeat.minNote,ne.BottomWithStem)}else switch(this.tieDirection){case H.Up:return e.getNoteY(this.endBeat.maxNote,ne.BottomWithStem);default:return e.getNoteY(this.endBeat.minNote,ne.TopWithStem)}switch(this.tieDirection){case H.Up:return e.getNoteY(this.endBeat.maxNote,ne.Top);default:return e.getNoteY(this.endBeat.minNote,ne.Bottom)}}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,ae.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>u.Whole&&e===this.tieDirection?ae.Stem:ae.MiddleNotes)}}class _n extends Ci{constructor(e,t,s,i){super(0,0),this._outType=t,this._inType=e,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.drawSlideOut(e,t,s)}paintSlideIn(e,t,s){let i=this.renderer,a=12*this.scale,r=e+i.x+i.getNoteX(this._startNote,oe.Left)-2*this.scale,n=t+i.y+i.getNoteY(this._startNote,ne.Center),o=r-a,h=t+i.y;switch(this._inType){case b.IntoFromBelow:h+=i.getNoteY(this._startNote,ne.Bottom);break;case b.IntoFromAbove:h+=i.getNoteY(this._startNote,ne.Top);break;default:return}let l=this.getAccidentalsWidth(i,this._startNote.beat);o-=l,r-=l,this.paintSlideLine(s,!1,o,r,h,n)}getAccidentalsWidth(e,t){let s=e.getPreNotesGlyphForBeat(t);return s&&s.accidentals?s.accidentals.width:0}drawSlideOut(e,t,s){let i=this.renderer,a=12*this.scale,r=3*this.scale,n=1*this.scale,o=2*this.scale,h=0,l=0,c=0,d=0,u=!1;switch(this._outType){case S.Shift:case S.Legato:if(h=e+i.x+i.getBeatX(this._startNote.beat,ae.PostNotes)+r,l=t+i.y+i.getNoteY(this._startNote,ne.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?(c=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,ae.PreNotes)-n,d=t+s.y+s.getNoteY(this._startNote.slideTarget,ne.Center)):(c=e+i.x+this._parent.x,d=l),this._startNote.slideTarget.realValue>this._startNote.realValue?(l+=o,d-=o):(l-=o,d+=o)}else c=e+i.x+this._parent.x,d=l;break;case S.OutUp:h=e+i.x+i.getNoteX(this._startNote,oe.Right),l=t+i.y+i.getNoteY(this._startNote,ne.Center),c=h+a,d=t+i.y+i.getNoteY(this._startNote,ne.Top);break;case S.OutDown:h=e+i.x+i.getNoteX(this._startNote,oe.Right),l=t+i.y+i.getNoteY(this._startNote,ne.Center),c=h+a,d=t+i.y+i.getNoteY(this._startNote,ne.Bottom);break;case S.PickSlideUp:h=e+i.x+i.getNoteX(this._startNote,oe.Right)+r,l=t+i.y+i.getNoteY(this._startNote,ne.Center),d=t+i.y+i.getNoteY(this._startNote,ne.Top),c=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(c=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,ae.PreNotes)),u=!0;break;case S.PickSlideDown:h=e+i.x+i.getNoteX(this._startNote,oe.Right)+r,l=t+i.y+i.getNoteY(this._startNote,ne.Center),d=t+i.y+i.getNoteY(this._startNote,ne.Bottom),c=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(c=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,ae.PreNotes)),u=!0;break;default:return}this.paintSlideLine(s,u,h,c,l,d)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new sr(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 Bn extends wn{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(){if(this.isStartCentered())switch(this.tieDirection){case H.Up:return this.startNoteRenderer.getNoteY(this._startNote,ne.Top);default:return this.startNoteRenderer.getNoteY(this._startNote,ne.Bottom)}return this.startNoteRenderer.getNoteY(this._startNote,ne.Center)}getEndY(){if(!this.isEndCentered())return this.endNoteRenderer.getNoteY(this._endNote,ne.Center);if(this.isEndOnStem())switch(this.tieDirection){case H.Up:return this.endNoteRenderer.getNoteY(this._endNote,ne.TopWithStem);default:return this.endNoteRenderer.getNoteY(this._endNote,ne.BottomWithStem)}else switch(this.tieDirection){case H.Up:return this.endNoteRenderer.getNoteY(this._endNote,ne.Top);default:return this.endNoteRenderer.getNoteY(this._endNote,ne.Bottom)}}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===H.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===H.Down}isEndCentered(){return this._startNote.beat.graceType===g.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===H.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===H.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===g.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,ae.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,oe.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,ae.Stem):this.endNoteRenderer.getNoteX(this._endNote,oe.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,ae.PreNotes)}}class Tn extends zr{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){switch(t.getBeatDirection(e)){case H.Up:return H.Down;default:return H.Up}}getStartY(){if(this.startBeat.isRest)return this.startNoteRenderer.getScoreY(9);switch(this.tieDirection){case H.Up:return this.startNoteRenderer.getNoteY(this.startNote,ne.Top);default:return this.startNoteRenderer.getNoteY(this.startNote,ne.Bottom)}}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)switch(this.tieDirection){case H.Up:return e.getScoreY(9);default:return e.getScoreY(0)}switch(this.tieDirection){case H.Up:return e.getNoteY(this.endNote,ne.Top);default:return e.getNoteY(this.endNote,ne.Bottom)}}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,ae.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,ae.PreNotes)}}class kn extends Di{constructor(e,t){super(e,t),this._bend=null,this._effectSlur=null,this._effectEndSlur=null}doLayout(){if(this._effectSlur=null,this._effectEndSlur=null,super.doLayout(),this.beat.isLegatoOrigin){if(!this.beat.previousBeat||!this.beat.previousBeat.isLegatoOrigin){let e=this.beat.nextBeat;for(;e.nextBeat&&e.nextBeat.isLegatoDestination;)e=e.nextBeat;this.ties.push(new wn(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.ties.push(new wn(e,this.beat,!0))}this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(e.isVisible){if(e.isTieOrigin&&!e.hasBend&&!e.beat.hasWhammyBar&&e.beat.graceType!==g.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){let t=new Tn(e,e.tieDestination,!1);this.ties.push(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){let t=new Tn(e.tieOrigin,e,!0);this.ties.push(t)}if(e.slideInType!==b.None||e.slideOutType!==S.None){let t=new _n(e.slideInType,e.slideOutType,e,this);this.ties.push(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){let t=new Bn(e,e.slurDestination,!1);this.ties.push(t)}if(e.isSlurDestination){let t=new Bn(e.slurOrigin,e,!0);this.ties.push(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new Bn(e,e.effectSlurDestination,!1);this._effectSlur=t,this.ties.push(t)}if(!this._effectEndSlur&&e.beat.isEffectSlurDestination&&e.beat.effectSlurOrigin){let t=this.onNotes.beamingHelper.direction,s=t===H.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,i=t===H.Up?e.beat.minNote:e.beat.maxNote;const a=new Bn(s,i,!0);this._effectEndSlur=a,this.ties.push(a)}if(e.hasBend){if(!this._bend){const t=new Sn(e.beat);this._bend=t,t.renderer=this.renderer,this.ties.push(t)}this._bend.addBends(e)}}}}class vn extends ma{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._firstLineY=0,this._startSpacing=!1,this.accidentalHelper=new ha(this)}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}get lineOffset(){return(ma.LineSpacing+1)*this.scale}updateSizes(){let e=this.resources,t=e.tablatureFont.size/2+.2*e.tablatureFont.size;this.topPadding=t*this.scale,this.bottomPadding=t*this.scale,this.height=4*this.lineOffset+this.topPadding+this.bottomPadding,this.updateFirstLineY(),super.updateSizes()}updateFirstLineY(){let e=4*this.lineOffset,t=(this.bar.staff.standardNotationLineCount-1)*this.lineOffset;this._firstLineY=(e-t)/2}doLayout(){if(this.updateFirstLineY(),super.doLayout(),!this.bar.isEmpty&&this.accidentalHelper.maxLineBeat){let e=this.getScoreY(-2),t=this.getScoreY(6),s=this.simpleWhammyOverflow;this.registerOverflowTop(s);let i=this.getScoreY(this.accidentalHelper.maxLine),a=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);a.direction===H.Up&&(i-=this.getStemSize(a),i-=a.fingeringCount*this.resources.graceFont.size,a.hasTuplet&&(i-=2*this.resources.effectFont.size)),a.hasTuplet&&(i-=1.5*this.resources.effectFont.size),i<e&&this.registerOverflowTop(Math.abs(i)+s);let r=this.getScoreY(this.accidentalHelper.minLine),n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);n.direction===H.Down&&(r+=this.getStemSize(n),r+=n.fingeringCount*this.resources.graceFont.size),r>t&&this.registerOverflowBottom(Math.abs(r)-t)}}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s),this.paintTuplets(e,t,s)}paintTuplets(e,t,s){for(let i of this.bar.voices)if(this.hasVoiceContainer(i)){let a=this.getVoiceContainer(i);for(let i of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,i)}}paintBeams(e,t,s){for(let i=0,a=this.helpers.beamHelpers.length;i<a;i++){let a=this.helpers.beamHelpers[i];for(let i=0,r=a.length;i<r;i++){let r=a[i];this.paintBeamHelper(e+this.beatGlyphsStart,t,s,r)}}}paintBeamHelper(e,t,s,i){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(1===i.beats.length?this.paintFlag(e,t,s,i):this.paintBar(e,t,s,i))}paintTupletHelper(e,t,s,i){let a,r=this.resources,n=s.textAlign,o=s.textBaseline;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=P.Center,s.textBaseline=E.Middle;let h=i.beats[0].tupletNumerator,l=i.beats[0].tupletDenominator;a=2===h&&3===l?"2":3===h&&2===l?"3":4===h&&6===l?"4":5===h&&4===l?"5":6===h&&4===l?"6":7===h&&4===l?"7":9===h&&8===l?"9":10===h&&8===l?"10":11===h&&8===l?"11":12===h&&8===l?"12":13===h&&8===l?"13":h+":"+l;let c=10*this.scale,d=5*this.scale;if(1!==i.beats.length&&i.isFull){let n=i.beats[0],o=i.beats[i.beats.length-1],h=null,l=null;for(let e=0;e<i.beats.length;e++)if(!i.beats[e].isRest){h=i.beats[e];break}for(let e=i.beats.length-1;e>=0;e--)if(!i.beats[e].isRest){l=i.beats[e];break}let u=!1;h||(h=n,u=!0),l||(l=o);let p=this.helpers.beamHelperLookup[i.voice.index].get(n.index),g=this.helpers.beamHelperLookup[i.voice.index].get(o.index),f=p.getBeatLineX(n),m=g.getBeatLineX(o),y=this.helpers.beamHelperLookup[i.voice.index].get(h.index),b=this.helpers.beamHelperLookup[i.voice.index].get(l.index),S=p.direction,w=this.calculateBeamYWithDirection(y,f,S),_=this.calculateBeamYWithDirection(b,m,S);u&&(w=Math.max(w,_),_=w),s.font=r.effectFont;let B=s.measureText(a),T=3*this.scale,k=(f+m)/2,v=k-B/2-T,x=k+B/2+T,N=(_-w)/(m-f),P=w-N*f,E=N*v+P,C=N*k+P,F=N*x+P;S===H.Down&&(c*=-1,d*=-1),s.beginPath(),s.moveTo(e+this.x+f,t+this.y+w-c|0),s.lineTo(e+this.x+f,t+this.y+w-c-d|0),s.lineTo(e+this.x+v,t+this.y+E-c-d|0),s.stroke(),s.beginPath(),s.moveTo(e+this.x+x,t+this.y+F-c-d|0),s.lineTo(e+this.x+m,t+this.y+_-c-d|0),s.lineTo(e+this.x+m,t+this.y+_-c|0),s.stroke(),s.fillText(a,e+this.x+k,t+this.y+C-c-d)}else for(let n=0,o=i.beats.length;n<o;n++){let o=i.beats[n],h=this.helpers.beamHelperLookup[i.voice.index].get(o.index);if(!h)continue;let l=h.direction,u=h.getBeatLineX(o),p=this.calculateBeamYWithDirection(h,u,l);l===H.Down&&(c*=-1,d*=-1),s.font=r.effectFont,s.fillText(a,e+this.x+u,t+this.y+p-c-d)}s.textAlign=n,s.textBaseline=o}getStemSize(e){let t=1===e.beats.length?this.getFlagStemSize(e.shortestDuration):this.getBarStemSize(e.shortestDuration);return e.isGrace&&(t*=Mi.GraceScale),t}getBarStemSize(e){let t=0;switch(e){case u.QuadrupleWhole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:t=6;break;case u.ThirtySecond:t=8;break;case u.SixtyFourth:case u.OneHundredTwentyEighth:t=9;break;case u.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}getFlagStemSize(e){let t=0;switch(e){case u.QuadrupleWhole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:case u.ThirtySecond:case u.SixtyFourth:case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:t=6;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){let s=super.getNoteY(e,t);if(isNaN(s)){const t=ha.computeLineWithoutAccidentals(this.bar,e);s=this.getScoreY(t)}return s}calculateBeamY(e,t){return this.calculateBeamYWithDirection(e,t,e.direction)}applyLayoutingInfo(){const e=super.applyLayoutingInfo();if(e&&this.bar.isMultiVoice){let e=this.getScoreY(-2),t=this.getScoreY(6),s=this.helpers.collisionHelper.getBeatMinMaxY();s[0]<e&&this.registerOverflowTop(Math.abs(s[0])),s[1]>t&&this.registerOverflowBottom(Math.abs(s[1])-t)}return e}calculateBeamYWithDirection(e,t,s){let i=this.getStemSize(e);if(!e.drawingInfos.has(s)){let t=new ca;e.drawingInfos.set(s,t);const a=e.beats[0],r=e.beats[e.beats.length-1];let n=e.isRestBeamHelper;t.startBeat=a,t.startX=e.getBeatLineX(a),t.startY=n?s===H.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===H.Up?this.getScoreY(this.accidentalHelper.getMinLine(a))-i:this.getScoreY(this.accidentalHelper.getMaxLine(a))+i,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?s===H.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===H.Up?this.getScoreY(this.accidentalHelper.getMinLine(r))-i:this.getScoreY(this.accidentalHelper.getMaxLine(r))+i;let o=10*this.scale;if(s===H.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),s===H.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),s===H.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),s===H.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(s===H.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=ke.getIndex(e.shortestDuration)-2;let a=e.isGrace?Mi.GraceScale:1,r=i*(ma.BeamSpacing+ma.BeamThickness)*this.scale*a;if(r+=ma.BeamSpacing,s===H.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===H.Down&&null!==e.maxRestLine){const s=this.getScoreY(e.maxRestLine)+r-t.calcY(e.getBeatLineX(e.beatOfMaxRestLine));s>0&&(t.startY+=s,t.endY+=s)}}}}return e.drawingInfos.get(s).calcY(t)}paintBar(e,t,s,i){for(let a=0,r=i.beats.length;a<r;a++){let r=i.beats[a],n=r.graceType!==g.None?Mi.GraceScale:1,o=i.getBeatLineX(r),h=i.direction,l=t+this.y;l+=h===H.Up?this.getScoreY(this.accidentalHelper.getMaxLine(r)):this.getScoreY(this.accidentalHelper.getMinLine(r));let c=t+this.y;c+=this.calculateBeamY(i,o),s.lineWidth=ma.StemWidth*this.scale,s.beginPath(),s.moveTo(e+this.x+o,l),s.lineTo(e+this.x+o,c),s.stroke(),s.lineWidth=this.scale;let d=c;h===H.Down?d+=2*s.font.size:0!==a&&(d-=1.5*s.font.size),this.paintFingering(s,r,e+this.x+o,h,d);let u=6*this.scale*n,p=(ma.BeamSpacing+ma.BeamThickness)*this.scale*n,f=ma.BeamThickness*this.scale*n,m=ke.getIndex(r.duration)-2,y=t+this.y;h===H.Down&&(p=-p,f=-f);for(let t=0;t<m;t++){let n=0,h=0,l=0,c=0,d=y+t*p;if(a<i.beats.length-1){if(da.isFullBarJoin(r,i.beats[a+1],t))n=o,h=i.getBeatLineX(i.beats[a+1]);else{if(0!==a&&da.isFullBarJoin(i.beats[a-1],r,t))continue;n=o,h=n+u}l=d+this.calculateBeamY(i,n),c=d+this.calculateBeamY(i,h),vn.paintSingleBar(s,e+this.x+n,l,e+this.x+h,c,f)}else a>0&&!da.isFullBarJoin(r,i.beats[a-1],t)&&(n=o-u,h=o,l=d+this.calculateBeamY(i,n),c=d+this.calculateBeamY(i,h),vn.paintSingleBar(s,e+this.x+n,l,e+this.x+h,c,f))}}}static paintSingleBar(e,t,s,i,a,r){e.beginPath(),e.moveTo(t,s),e.lineTo(i,a),e.lineTo(i,a+r),e.lineTo(t,s+r),e.closePath(),e.fill()}paintFlag(e,t,s,i){let a=i.beats[0];if(a.graceType===g.BendGrace||a.graceType!==g.None&&this.settings.notation.notationMode===T.SongBook)return;let r=a.graceType!==g.None,n=r?Mi.GraceScale:1,o=this.getFlagStemSize(i.shortestDuration),h=i.getBeatLineX(a),l=i.direction,c=this.getScoreY(this.accidentalHelper.getMinLine(a)),d=this.getScoreY(this.accidentalHelper.getMaxLine(a)),u=0,p=0;if(l===H.Down?(d+=o*n,u=d,p=t+this.y+d):(c-=o*n,u=c,p=t+this.y+c),this.paintFingering(s,a,e+this.x+h,l,p),i.hasLine){if(s.lineWidth=ma.StemWidth*this.scale,s.beginPath(),s.moveTo(e+this.x+h,t+this.y+c),s.lineTo(e+this.x+h,t+this.y+d),s.stroke(),s.lineWidth=this.scale,a.graceType===g.BeforeBeat){let i=15*this.scale,a=12*this.scale;s.beginPath(),l===H.Down?(s.moveTo(e+this.x+h-a/2,t+this.y+d-i),s.lineTo(e+this.x+h+a/2,t+this.y+d)):(s.moveTo(e+this.x+h-a/2,t+this.y+c+i),s.lineTo(e+this.x+h+a/2,t+this.y+c)),s.stroke()}if(i.hasFlag){let i=new Ii(h-this.scale/2,u,a.duration,l,r);i.renderer=this,i.doLayout(),i.paint(e+this.x,t+this.y,s)}}}paintFingering(e,t,s,i,a){let r=this.settings;if(r.notation.fingeringMode!==B.ScoreDefault&&r.notation.fingeringMode!==B.ScoreForcePiano)return;i===H.Up?s-=10*this.scale:s+=3*this.scale;let n=t.notes.slice(0);n.sort(((e,t)=>e.realValue-t.realValue));for(let i=0;i<n.length;i++){let o=n[i],h=null;o.leftHandFinger!==f.Unknown?h=ke.fingerToString(r,t,o.leftHandFinger,!0):o.rightHandFinger!==f.Unknown&&(h=ke.fingerToString(r,t,o.rightHandFinger,!1)),h&&(e.fillText(h,s,a),a-=0|e.font.size)}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Or(0,0,1.5,3)),this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let e=0;switch(this.bar.clef){case r.Neutral:e=this.bar.staff.standardNotationLineCount-1;break;case r.F4:e=2;break;case r.C3:e=4;break;case r.C4:e=2;break;case r.G2:e=6}this.createStartSpacing(),this.addPreBeatGlyph(new Dr(0,this.getScoreY(e)+.5*ma.StaffLineThickness,this.bar.clef,this.bar.clefOttava))}(0===this.index&&this.bar.masterBar.keySignature!==M.C||this.bar.previousBar&&this.bar.masterBar.keySignature!==this.bar.previousBar.masterBar.keySignature)&&(this.createStartSpacing(),this.createKeySignatureGlyphs()),(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new Mr(0,this.getScoreHeight(-.5),this.bar.index+1))}createBeatGlyphs(){for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];this.hasVoiceContainer(t)&&this.createVoiceGlyphs(t)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new Rr(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Ar(0,this.getScoreHeight(-.5),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new Ir(0,0))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new on(0,0,2*this.scale)),this._startSpacing=!0)}createKeySignatureGlyphs(){let e=0,t=this.bar.masterBar.keySignature,s=this.bar.previousBar?this.bar.previousBar.masterBar.keySignature:0;switch(this.bar.clef){case r.Neutral:e=0;break;case r.G2:e=1;break;case r.F4:e=2;break;case r.C3:e=-1;break;case r.C4:e=1}let i=new Map,a=[];if(ke.keySignatureIsSharp(t))for(let s=0;s<Math.abs(t);s++){let t=vn.SharpKsSteps[s]+e;a.push(new Lr(0,this.getScoreY(t),re.Sharp,!1)),i.set(t,!0)}else for(let s=0;s<Math.abs(t);s++){let t=vn.FlatKsSteps[s]+e;a.push(new Lr(0,this.getScoreY(t),re.Flat,!1)),i.set(t,!0)}let n=Math.abs(s),o=ke.keySignatureIsSharp(s)?vn.SharpKsSteps:vn.FlatKsSteps;for(let t=0;t<n;t++){let s=o[t]+e;i.has(s)||this.addPreBeatGlyph(new Lr(0,this.getScoreY(o[t]+e),re.Natural,!1))}for(let e of a)this.addPreBeatGlyph(e)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new on(0,0,5*this.scale));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new bn(0,this.getScoreY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,s=e.beats.length;t<s;t++){let s=e.beats[t],i=new kn(s,this.getVoiceContainer(e));i.preNotes=new gn,i.onNotes=new un,this.addBeatGlyph(i)}}getNoteLine(e){return this.accidentalHelper.getNoteLine(e)}getScoreY(e){return this._firstLineY+this.lineOffset+this.getScoreHeight(e)}getScoreHeight(e){return this.lineOffset/2*e}paintBackground(e,t,s){super.paintBackground(e,t,s);let i=this.resources;s.color=i.staffLineColor;for(let i=0;i<this.bar.staff.standardNotationLineCount;i++){const a=t+this.y+this.getScoreY(2*i);s.fillRect(e+this.x,0|a,this.width,this.scale*ma.StaffLineThickness)}s.color=i.mainGlyphColor,this.paintSimileMark(e,t,s)}completeBeamingHelper(e){if(this.bar.isMultiVoice&&e.highestNoteInHelper&&e.lowestNoteInHelper){let t=this.getNoteY(e.highestNoteInHelper,ne.Center),s=this.getNoteY(e.lowestNoteInHelper,ne.Center),i=this.getStemSize(e);e.hasTuplet&&(i+=2*this.resources.effectFont.size),e.direction==H.Up?t-=i:s+=i;for(const i of e.beats)this.helpers.collisionHelper.reserveBeatSlot(i,t,s)}}}vn.StaffId="score",vn.SharpKsSteps=[-1,2,-2,1,4,0,3],vn.FlatKsSteps=[3,0,4,1,5,2,6];class xn extends ia{get staffId(){return vn.StaffId}create(e,t){return new vn(e,t)}constructor(){super()}}class Nn extends Ci{constructor(e,t,s,i){super(0,0),this._inType=e,this._outType=t,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.paintSlideOut(e,t,s)}paintSlideIn(e,t,s){let i=this.renderer,a=12*this.scale,r=3*this.scale,n=0,o=0,h=0,l=0;switch(this._inType){case b.IntoFromBelow:h=e+i.x+i.getNoteX(this._startNote,oe.Left),l=t+i.y+i.getNoteY(this._startNote,ne.Center),n=h-a,o=t+i.y+i.getNoteY(this._startNote,ne.Center)+r;break;case b.IntoFromAbove:h=e+i.x+i.getNoteX(this._startNote,oe.Left),l=t+i.y+i.getNoteY(this._startNote,ne.Center),n=h-a,o=t+i.y+i.getNoteY(this._startNote,ne.Center)-r;break;default:return}this.paintSlideLine(s,!1,n,h,o,l)}paintSlideOut(e,t,s){let i=this.renderer,a=12*this.scale,r=3*this.scale,n=0,o=0,h=0,l=0,c=!1;const d=2*this.scale;switch(this._outType){case S.Shift:case S.Legato:if(n=e+i.x+i.getBeatX(this._startNote.beat,ae.PostNotes),o=t+i.y+i.getNoteY(this._startNote,ne.Center),this._startNote.slideTarget){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(h=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,ae.OnNotes)-d,l=t+s.y+s.getNoteY(this._startNote.slideTarget,ne.Center)):(h=e+i.x+this._parent.x,l=o),this._startNote.slideTarget.fret>this._startNote.fret?(o+=r,l-=r):(o-=r,l+=r)}else h=e+i.x+this._parent.x,l=o;break;case S.OutUp:n=e+i.x+i.getNoteX(this._startNote,oe.Right),o=t+i.y+i.getNoteY(this._startNote,ne.Center),h=n+a-d,l=t+i.y+i.getNoteY(this._startNote,ne.Center)-r;break;case S.OutDown:n=e+i.x+i.getNoteX(this._startNote,oe.Right),o=t+i.y+i.getNoteY(this._startNote,ne.Center),h=n+a-d,l=t+i.y+i.getNoteY(this._startNote,ne.Center)+r;break;case S.PickSlideDown:n=e+i.x+i.getNoteX(this._startNote,oe.Right),o=t+i.y+i.getNoteY(this._startNote,ne.Center),h=e+i.x+i.getBeatX(this._startNote.beat,ae.EndBeat),l=o+3*r,c=!0;break;case S.PickSlideUp:n=e+i.x+i.getNoteX(this._startNote,oe.Right),o=t+i.y+i.getNoteY(this._startNote,ne.Center),h=e+i.x+i.getBeatX(this._startNote.beat,ae.EndBeat),l=o-3*r,c=!0;break;default:return}this.paintSlideLine(s,c,n,h,o,l)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new sr(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 Pn extends zr{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?H.Up:Pn.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?H.Up:H.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,ne.Center):this.tieDirection===H.Up?this.startNoteRenderer.getNoteY(this.startNote,ne.Top):this.startNoteRenderer.getNoteY(this.startNote,ne.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20*this.scale:this.startNoteRenderer.getNoteX(this.startNote,oe.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,oe.Left):this.endNoteRenderer.getNoteX(this.endNote,oe.Center)}}class En extends Pn{constructor(e,t,s,i=!1){super(e,t,i),this._direction=Pn.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!==Pn.getBeamDirectionForNote(e))return!1;switch(this._direction){case H.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 H.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 Cn extends Di{constructor(e,t){super(e,t),this._bend=null,this._effectSlurs=[]}doLayout(){this._effectSlurs=[],super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(!e.isVisible)return;let t=this.renderer;if(e.isTieOrigin&&t.showTiedNotes&&e.tieDestination.isVisible){let t=new Pn(e,e.tieDestination,!1);this.ties.push(t)}if(e.isTieDestination&&t.showTiedNotes){let t=new Pn(e.tieOrigin,e,!0);this.ties.push(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new Pn(e,e,!1);this.ties.push(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 En(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.ties.push(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 En(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.ties.push(t)}}if(e.slideInType!==b.None||e.slideOutType!==S.None){let t=new Nn(e.slideInType,e.slideOutType,e,this);this.ties.push(t)}if(e.hasBend){if(!this._bend){const e=new an;this._bend=e,e.renderer=this.renderer,this.ties.push(e)}this._bend.addBends(e)}}}class Fn extends Ci{constructor(e,t,s){super(e,t),this._noteString=null,this._trillNoteString=null,this._trillNoteStringWidth=0,this.isEmpty=!1,this.noteStringWidth=0,this._note=s}doLayout(){let e=this._note,t=e.fret-e.beat.voice.bar.staff.transpositionPitch;if(e.harmonicType===m.Natural&&0!==e.harmonicValue&&(t=e.harmonicValue-e.beat.voice.bar.staff.transpositionPitch),e.isTieDestination)0===e.beat.index&&this.renderer.settings.notation.notationMode==T.GuitarPro||(e.bendType===l.Bend||e.bendType===l.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(k.TabNotesOnTiedBends)?this._noteString="("+(e.tieOrigin.fret-e.beat.voice.bar.staff.transpositionPitch).toString()+")":this._noteString="";else if(this._noteString=e.isDead?"x":t.toString(),e.isGhost)this._noteString="("+this._noteString+")";else if(e.harmonicType===m.Natural){let e=this._noteString.indexOf(String.fromCharCode(46));e>=0&&(this._noteString=this._noteString.substr(0,e+2)),this._noteString="<"+this._noteString+">"}if(e.isTrill)this._trillNoteString="("+(e.trillFret-e.beat.voice.bar.staff.transpositionPitch).toString()+")";else if(ke.isAlmostEqualTo(e.harmonicValue,0))this._trillNoteString="";else switch(e.harmonicType){case m.Artificial:case m.Pinch:case m.Tap:case m.Semi:case m.Feedback:let s=(t+e.harmonicValue).toString(),i=s.indexOf(String.fromCharCode(46));i>=0&&(s=s.substr(0,i+2)),this._trillNoteString="<"+s+">";break;default:this._trillNoteString=""}if(this.isEmpty=!this._noteString,!this.isEmpty){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.tablatureFont,this.noteStringWidth=this.renderer.scoreRenderer.canvas.measureText(this._noteString)*this.scale,this.width=this.noteStringWidth,this.height=this.renderer.scoreRenderer.canvas.font.size,!!this._trillNoteString&&(this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,this._trillNoteStringWidth=3*this.scale+this.renderer.scoreRenderer.canvas.measureText(this._trillNoteString),this.width+=this._trillNoteStringWidth)}}paint(e,t,s){if(this.isEmpty)return;let i=this.noteStringWidth+this._trillNoteStringWidth,a=e+this.x+(this.width-i)/2,r=this.renderer.scoreRenderer.canvas.font;this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,s.fillText(this._trillNoteString,a+this.noteStringWidth+3*this.scale,t+this.y),this.renderer.scoreRenderer.canvas.font=r,s.fillText(this._noteString,a,t+this.y)}buildBoundingsLookup(e,t,s){let i=new gi;i.note=this._note,i.noteHeadBounds=new at,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,this.renderer.scoreRenderer.boundsLookup.addNote(i)}}class Ln extends Ci{constructor(e,t,s){super(e,t),this._notes=[],this.minStringNote=null,this.beatEffects=new Map,this.notesPerString=new Map,this.noteStringWidth=0,this._isGrace=s}buildBoundingsLookup(e,t,s){for(const i of this._notes)i.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteX(e,t){if(this.notesPerString.has(e.string)){let s=this.notesPerString.get(e.string),i=this.x+s.x;switch(t){case oe.Left:break;case oe.Center:i+=s.noteStringWidth/2;break;case oe.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 ne.Top:case ne.TopWithStem:i-=s.height/2+2*this.scale;break;case ne.Center:break;case ne.Bottom:case ne.BottomWithStem:i+=s.height/2}return i}return 0}doLayout(){let e=0,t=0;for(let s=0,i=this._notes.length;s<i;s++){let i=this._notes[s];i.renderer=this.renderer,i.doLayout(),i.width>e&&(e=i.width),i.noteStringWidth>t&&(t=i.noteStringWidth)}this.noteStringWidth=t;let s=this.renderer.resources.tablatureFont.size,i=this.getNoteY(this.minStringNote,ne.Center)+s/2,a=7*this.scale;for(const e of this.beatEffects.values())e.y+=i,e.x+=this.width/2,e.renderer=this.renderer,i+=a,e.doLayout();this.width=e}addNoteGlyph(e,t){this._notes.push(e),this.notesPerString.set(t.string,e),(!this.minStringNote||t.string<this.minStringNote.string)&&(this.minStringNote=t)}paint(e,t,s){e+=this.x,t+=this.y;let i=this.renderer.resources,a=s.textBaseline;s.textBaseline=E.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 Mn extends Li{constructor(e,t,s,i){super(e,t,1,Kr.getSymbol(i)),this._isVisibleRest=s,this._duration=i}doLayout(){this._isVisibleRest?this.width=Kr.getSize(this._duration)*this.scale:this.width=10*this.scale}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){this._isVisibleRest&&super.paint(e,t,s)}}class In extends Ba{constructor(){super(...arguments),this.noteNumbers=null,this.restGlyph=null}getNoteX(e,t){return this.noteNumbers?this.noteNumbers.getNoteX(e,t):0}getNoteY(e,t){return this.noteNumbers?this.noteNumbers.getNoteY(e,t):0}buildBoundingsLookup(e,t,s){this.noteNumbers&&this.noteNumbers.buildBoundingsLookup(e,t+this.x,s+this.y)}doLayout(){let e=this.renderer;if(this.container.beat.isRest){let t=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),s=e.getTabY(t);const i=new Mn(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 on(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new Vr(0,s,1.5*this.scale))}}else{let t=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==g.None;const s=new Ln(0,0,t);this.noteNumbers=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper;for(let e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);if(this.addGlyph(s),this.container.beat.hasWhammyBar){let e=new rn(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!this.noteNumbers.beatEffects.has("tremolo")){let e=0,t=this.container.beat.tremoloSpeed;switch(t){case u.ThirtySecond:e=10;break;case u.Sixteenth:e=5;break;case u.Eighth:e=0}this.noteNumbers.beatEffects.set("tremolo",new Qr(5*this.scale,e*this.scale,t))}if(this.container.beat.dots>0&&e.settings.notation.rhythmMode!==_.Hidden){this.addGlyph(new on(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++)this.addGlyph(new Vr(0,e.lineOffset*e.bar.staff.tuning.length+e.settings.notation.rhythmHeight*e.scale,1.5*this.scale))}}if(!this.glyphs)return;let t=0;for(let e=0,s=this.glyphs.length;e<s;e++){let s=this.glyphs[e];s.x=t,s.renderer=this.renderer,s.doLayout(),t+=s.width}this.width=t,this.computedWidth=t,this.container.beat.isEmpty?this.centerX=this.width/2:this.container.beat.isRest?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.centerX=this.noteNumbers.x+this.noteNumbers.noteStringWidth/2}updateBeamingHelper(){this.container.beat.isRest?this.restGlyph.updateBeamingHelper(this.container.x+this.x):this.noteNumbers.updateBeamingHelper(this.container.x+this.x)}createNoteGlyph(e){let t=this.renderer,s=new Fn(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 Dn extends Ci{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10*this.scale}paint(e,t,s){let i=this.renderer,a=t+this.x+i.getNoteY(this._beat.maxNote,ne.Top),r=t+this.y+i.getNoteY(this._beat.minNote,ne.Bottom),n=e+this.x+this.width/2|0,o=8*this.scale;if(this._beat.brushType!==c.None){if(this._beat.brushType===c.BrushUp||this._beat.brushType===c.BrushDown)s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke();else if(this._beat.brushType===c.ArpeggioUp){let t=new sr(0,0,w.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let i=a,n=r-o;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4*this.scale,n,-90),t.paint(0,-t.height/2,s),s.endRotate()}else if(this._beat.brushType===c.ArpeggioDown){let t=new sr(0,0,w.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let i=a+o,n=r;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4*this.scale,i,90),t.paint(0,-t.height/2,s),s.endRotate()}this._beat.brushType===c.BrushUp||this._beat.brushType===c.ArpeggioUp?(s.beginPath(),s.moveTo(n,r),s.lineTo(n+o/2,r-o),s.lineTo(n-o/2,r-o),s.closePath(),s.fill()):(s.beginPath(),s.moveTo(n,a),s.lineTo(n+o/2,a+o),s.lineTo(n-o/2,a+o),s.closePath(),s.fill())}}}class Rn extends _a{doLayout(){this.container.beat.brushType===c.None||this.container.beat.isRest||(this.addGlyph(new Dn(this.container.beat)),this.addGlyph(new on(0,0,4*this.scale))),super.doLayout()}constructor(){super()}}class An extends Ci{constructor(e,t){super(e,t)}doLayout(){this.width=28*this.scale}paint(e,t,s){let i=this.renderer.bar.staff.tuning.length,a=i<=4?N.FourStringTabClef:N.SixStringTabClef,r=i<=4?i/4.5:i/6.5;s.fillMusicFontSymbol(e+this.x+5*this.scale,t+this.y,r*this.scale,a,!1)}}class On extends yn{get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?Mi.GraceScale:1}}class Gn extends ma{constructor(e,t){super(e,t),this._firstLineY=0,this._tupletSize=0,this.showTimeSignature=!1,this.showRests=!1,this.showTiedNotes=!1,this._startSpacing=!1}get lineOffset(){return(Gn.TabLineSpacing+1)*this.scale}updateSizes(){let e=this.resources,t=(e.tablatureFont.size/2+.2*e.tablatureFont.size)*this.scale;this.topPadding=t,this.bottomPadding=t,this.height=this.lineOffset*(this.bar.staff.tuning.length-1)+2*t,this.settings.notation.rhythmMode!==_.Hidden&&(this.height+=this.settings.notation.rhythmHeight*this.settings.display.scale,this.bottomPadding+=this.settings.notation.rhythmHeight*this.settings.display.scale),this.updateFirstLineY(),super.updateSizes()}updateFirstLineY(){let e=this.resources;this._firstLineY=(e.tablatureFont.size/2+.2*e.tablatureFont.size)*this.scale}doLayout(){if(this.updateFirstLineY(),super.doLayout(),this.settings.notation.rhythmMode!==_.Hidden){let e=!1;for(let t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}e&&(this._tupletSize=.8*this.resources.effectFont.size,this.registerOverflowBottom(this._tupletSize))}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Or(0,0,1.5,3)),this.isFirstOfLine){let e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new An(5*this.scale,this.getTabY(e)))}this.showTimeSignature&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new Mr(0,this.getTabHeight(-.5),this.bar.index+1))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new on(0,0,2*this.scale)),this._startSpacing=!0)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new on(0,0,5*this.scale));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new On(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,s=e.beats.length;t<s;t++){let s=e.beats[t],i=new Cn(s,this.getVoiceContainer(e));i.preNotes=new Rn,i.onNotes=new In,this.addBeatGlyph(i)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new Rr(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Ar(0,this.getTabY(-1),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new Ir(0,0))}getTabY(e){return this._firstLineY+this.getTabHeight(e)}getTabHeight(e){return this.lineOffset*e}get middleYPosition(){return this.getTabY(this.bar.staff.tuning.length-1)}paintBackground(e,t,s){super.paintBackground(e,t,s);let i=this.resources;s.color=i.staffLineColor;let a=this.scale,r=[];for(let e=0,t=this.bar.staff.tuning.length;e<t;e++)r.push([]);for(let e of this.bar.voices)if(this.hasVoiceContainer(e)){let t=this.getVoiceContainer(e);for(let e of t.beatGlyphs){let s=e.onNotes,i=s.noteNumbers;if(i)for(const[n,o]of i.notesPerString)o.isEmpty||r[this.bar.staff.tuning.length-n].push(new Float32Array([t.x+e.x+s.x+i.x,i.width+a]))}}for(let e of r)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));for(let i=0,a=this.bar.staff.tuning.length;i<a;i++){const a=this.getTabY(i);let n=0;for(let o of r[i])s.fillRect(e+this.x+n,t+this.y+a|0,o[0]-n,this.scale*ma.StaffLineThickness),n=o[0]+o[1];s.fillRect(e+this.x+n,t+this.y+a|0,this.width-n,this.scale*ma.StaffLineThickness)}s.color=i.mainGlyphColor,this.paintSimileMark(e,t,s)}paint(e,t,s){super.paint(e,t,s),this.settings.notation.rhythmMode!==_.Hidden&&(this.paintBeams(e,t,s),this.paintTuplets(e,t,s))}paintBeams(e,t,s){for(let i=0,a=this.helpers.beamHelpers.length;i<a;i++){let a=this.helpers.beamHelpers[i];for(let i=0,r=a.length;i<r;i++){let r=a[i];this.paintBeamHelper(e+this.beatGlyphsStart,t,s,r)}}}paintTuplets(e,t,s){for(let i of this.bar.voices)if(this.hasVoiceContainer(i)){let a=this.getVoiceContainer(i);for(let i of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,i)}}paintBeamHelper(e,t,s,i){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(1===i.beats.length||this.settings.notation.rhythmMode===_.ShowWithBeams?this.paintFooter(e,t,s,i):this.paintBar(e,t,s,i))}paintBar(e,t,s,i){for(let a=0,r=i.beats.length;a<r;a++){let r=i.beats[a];if(i.hasBeatLineX(r)){let n=i.getBeatLineX(r),o=t+this.y,h=t+this.y+this.height-this._tupletSize,l=this.getOnNotesGlyphForBeat(r);l.noteNumbers&&r.duration!==u.Half?o+=l.noteNumbers.getNoteY(l.noteNumbers.minStringNote,ne.Bottom)+this.lineOffset/2:o+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(r,t+this.y,e+this.x+n,o,h,s);let c=6*this.scale,d=-6*this.scale,p=3*this.scale,g=ke.getIndex(r.duration)-2,f=h;for(let t=0;t<g;t++){let o=0,h=0,l=0,u=0,g=f+t*d;if(1===i.beats.length)o=n,h=n+c,l=g,u=g,Gn.paintSingleBar(s,e+this.x+o,l,e+this.x+h,u,p);else if(a<i.beats.length-1){if(da.isFullBarJoin(r,i.beats[a+1],t))o=n,h=i.getBeatLineX(i.beats[a+1]);else{if(0!==a&&da.isFullBarJoin(i.beats[a-1],r,t))continue;o=n,h=o+c}l=g,u=g,Gn.paintSingleBar(s,e+this.x+o,l,e+this.x+h,u,p)}else a>0&&!da.isFullBarJoin(r,i.beats[a-1],t)&&(o=n-c,h=n,l=g,u=g,Gn.paintSingleBar(s,e+this.x+o,l,e+this.x+h,u,p))}}}}paintTupletHelper(e,t,s,i){let a,r=this.resources,n=s.textAlign,o=s.textBaseline;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=P.Center,s.textBaseline=E.Middle;let h=i.beats[0].tupletNumerator,l=i.beats[0].tupletDenominator;if(a=2===h&&3===l?"2":3===h&&2===l?"3":4===h&&6===l?"4":5===h&&4===l?"5":6===h&&4===l?"6":7===h&&4===l?"7":9===h&&8===l?"9":10===h&&8===l?"10":11===h&&8===l?"11":12===h&&8===l?"12":13===h&&8===l?"13":h+":"+l,1!==i.beats.length&&i.isFull){let n=i.beats[0],o=i.beats[i.beats.length-1],h=this.helpers.beamHelperLookup[i.voice.index].get(n.index),l=this.helpers.beamHelperLookup[i.voice.index].get(o.index);if(h&&l){let i=h.getBeatLineX(n),c=l.getBeatLineX(o);s.font=r.effectFont;let d=s.measureText(a),u=3*this.scale,p=(i+c)/2,g=p-d/2-u,f=p+d/2+u,m=t+this.y+this.height-this._tupletSize+.5*r.effectFont.size,y=.25*-r.effectFont.size,b=-5*this.scale;s.beginPath(),s.moveTo(e+this.x+i,m-y|0),s.lineTo(e+this.x+i,m-y-b|0),s.lineTo(e+this.x+g,m-y-b|0),s.stroke(),s.beginPath(),s.moveTo(e+this.x+f,m-y-b|0),s.lineTo(e+this.x+c,m-y-b|0),s.lineTo(e+this.x+c,m-y|0),s.stroke(),s.fillText(a,e+this.x+p,m-y-b)}}else for(let n=0,o=i.beats.length;n<o;n++){let o=i.beats[n],h=this.helpers.beamHelperLookup[i.voice.index].get(o.index);if(!h)continue;let l=h.getBeatLineX(o),c=t+this.y+this.height-this._tupletSize+.5*r.effectFont.size;s.font=r.effectFont,s.fillText(a,e+this.x+l,c)}s.textAlign=n,s.textBaseline=o}static paintSingleBar(e,t,s,i,a,r){e.beginPath(),e.moveTo(t,s),e.lineTo(i,a),e.lineTo(i,a-r),e.lineTo(t,s-r),e.closePath(),e.fill()}paintBeamingStem(e,t,s,i,a,r){r.beginPath();let n=[];this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.has(e.displayStart)&&(n=this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.get(e.displayStart).slots.slice(),n.sort(((e,t)=>e.topY-t.topY)));let o=a;for(;o>i;){r.moveTo(s,o);let e=i;if(!(n.length>0&&n[n.length-1].bottomY>e)){r.lineTo(s,e);break}{const i=n.pop();e=t+i.bottomY,r.lineTo(s,e),o=t+i.topY}}r.stroke()}paintFooter(e,t,s,i){for(let a of i.beats){if(a.graceType!==g.None||a.duration===u.Whole||a.duration===u.DoubleWhole||a.duration===u.QuadrupleWhole)return;let r=i.getBeatLineX(a),n=t+this.y,o=t+this.y+this.height-this._tupletSize,h=this.getOnNotesGlyphForBeat(a);if(h.noteNumbers&&a.duration!==u.Half?n+=h.noteNumbers.getNoteY(h.noteNumbers.minStringNote,ne.Bottom):n+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(a,t+this.y,e+this.x+r,n,o,s),a.duration>u.Quarter){let t=new Ii(0,0,a.duration,H.Down,!1);t.renderer=this,t.doLayout(),t.paint(e+this.x+r,o,s)}}}}Gn.StaffId="tab",Gn.TabLineSpacing=10;class Vn extends ia{constructor(e,t,s){super(),this._showTimeSignature=e,this._showRests=t,this._showTiedNotes=s,this.hideOnPercussionTrack=!0}get staffId(){return Gn.StaffId}canCreate(e,t){return t.tuning.length>0&&super.canCreate(e,t)}create(e,t){let s=new Gn(e,t);return s.showRests=this._showRests,s.showTimeSignature=this._showTimeSignature,s.showTiedNotes=this._showTiedNotes,s}}class Hn extends Fi{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+Hn.Padding*this.scale}paint(e,t,s){let i=this.renderer.resources;s.font=i.effectFont;let a=s.textAlign;s.textAlign=P.Center,s.fillText("T",e+this.x,t+this.y+s.font.size/2),s.textAlign=a,s.strokeCircle(e+this.x,t+this.y+s.font.size/2+(Hn.Padding-1)*this.scale,s.font.size/1.6)}}Hn.Padding=4;class Wn extends Ha{get notationElement(){return k.EffectTap}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new Hn}}class zn{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"}(ce||(ce={}));class Un extends zn{constructor(){super(...arguments),this.align=P.Left,this.frame=ce.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class Xn extends zn{constructor(){super(...arguments),this.chord=new Re}}class Yn extends zn{}class qn extends zn{}class Jn extends zn{constructor(){super(...arguments),this.number=0}}class Qn extends zn{constructor(){super(...arguments),this.decrescendo=!1}}class jn extends zn{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class Kn extends zn{constructor(){super(...arguments),this.octave=1}}class $n extends zn{}class Zn{constructor(){this.defaultClef=r.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class eo{constructor(){this.from=0,this.to=0,this.curly=!1}}class to{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class so{constructor(){this._trackChannel=0,this._beamingMode=F.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new Oe,this._voiceStates=new Map}parseXml(e,t){this._galleryObjects=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._voiceCounts=new Map,this._slurs=new Map,this._crescendo=new Map,this._isFirstSystem=!0;let s=new dt;try{s.parse(e)}catch(e){throw new ge("Could not parse XML",e)}this.parseDom(s),this.consolidate(),this.score.finish(t)}consolidate(){let e=this.score.tempo;for(const t of this.score.tracks){const s=this._voiceCounts.get(t.index);for(const i of t.staves){for(;i.bars.length<this.score.masterBars.length;)this.addNewBar(i);for(const t of i.bars){for(;t.voices.length<s;)t.addVoice(new Qe);for(const e of t.voices)if(0===e.beats.length){const t=new De;t.isEmpty=!0,e.addBeat(t)}const i=t.masterBar;i.tempoAutomation&&(i.tempoAutomation.value!==e?e=i.tempoAutomation.value:i.tempoAutomation=null)}}}so.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),so.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?d.Decrescendo:d.Crescendo}))}static applyEffectRange(e,t){for(const[s,i]of e){const e=i.noteRange;let a=s;for(let s=0;s<e;s++)if(t(i,a),a.index+1<a.voice.beats.length)a=a.voice.beats[a.index+1];else{if(!(a.voice.bar.index+1<a.voice.bar.staff.bars.length))break;a=a.voice.bar.staff.bars[a.voice.bar.index+1].voices[a.voice.index].beats[0]}}}parseDom(e){let t=e.firstElement;if(!t)throw new ge("No valid XML");if("score"!==t.localName)throw new ge('Root node of XML was not "score"');this.score=new He,this.score.tempo=120;for(let e of t.childNodes)if(e.nodeType===G.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===G.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 Je,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===G.Element)switch(t.localName){case"bracket":this.parseBracket(t)}}parseBracket(e){const t=new eo;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===G.Element)switch(t.localName){case"staffLayout":this.parseStaffLayout(t)}}parseStaffLayout(e){const t=new Zn;t.description=e.getAttribute("description");for(let s of e.childNodes)if(s.nodeType===G.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===G.Element)switch(t.localName){case"system":this.parseSystem(t)}}parseSystem(e){e.attributes.has("tempo")&&0===this.score.masterBars.length&&(this.score.tempo=parseInt(e.attributes.get("tempo"))),"0"===e.getAttribute("beamGrouping")&&(this._beamingMode=F.ForceSplitToNext);for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"staves":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===G.Element)switch(i.localName){case"staff":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===G.Element)switch(r.localName){case"voices":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===G.Element)switch(n.localName){case"voice":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 me;if(e.bars.length>0?(t.clef=e.bars[e.bars.length-1].clef,t.clefOttava=e.bars[e.bars.length-1].clefOttava):t.clef=this._currentStaffLayout.defaultClef,e.addBar(t),e.bars.length>this.score.masterBars.length){let e=new Oe;this.score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.tripletFeel=e.previousMasterBar.tripletFeel),e.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,e.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,e.timeSignatureCommon=this._timeSignature.timeSignatureCommon}return t}newBar(e,t){this._currentVoiceState.currentBarIndex++,this._currentBar=this.getOrCreateBar(e,this._currentVoiceState.currentBarIndex),this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1),this._currentVoiceState.currentBarComplete=!1,this._currentVoiceState.currentPosition=0,this.ensureVoice(e,t)}parseVoice(e,t,s,i,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 to,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=H.Up;break;case"down":this._currentVoiceState.voiceStemDir=H.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const h=n.findChildElement("noteObjects");if(s.attributes.has("tempo")&&(this._currentBar.masterBar.tempoAutomation=new fe,this._currentBar.masterBar.tempoAutomation.isLinear=!0,this._currentBar.masterBar.tempoAutomation.type=a.Tempo,this._currentBar.masterBar.tempoAutomation.value=parseInt(s.attributes.get("tempo"))),h)for(let e of h.childNodes)if(e.nodeType===G.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;case"dashed":default:this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0}break;case"chord":let s=new De;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 Qe);(!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 Pe;for(let a of t.childNodes)if(a.nodeType===G.Element)switch(a.localName){case"stem":switch(a.getAttribute("dir")){case"up":e.preferredBeamDirection=H.Up;break;case"down":e.preferredBeamDirection=H.Down}break;case"articulation":switch(a.getAttribute("type")){case"staccato":s.isStaccato=!0;break;case"normalAccent":s.accentuated=i.Normal;break;case"strongAccent":s.accentuated=i.Heavy}break;case"lyric":this.parseLyric(e,a);break;case"drawObjects":this.parseBeatDrawObject(e,a);break;case"heads":this.parseHeads(e,s,a);break;case"beam":switch(a.getAttribute("group")){case"force":e.beamingMode=F.ForceMergeWithNext;break;case"divide":e.beamingMode=F.ForceSplitToNext}}}parseHeads(e,t,s){for(let i of s.childNodes)if(i.nodeType===G.Element)switch(i.localName){case"head":this.parseHead(e,t,i)}}parseHead(e,t,s){const i=new Pe,a=ke.parseTuning(s.getAttribute("pitch"));i.octave=a.octave-1,i.tone=a.noteValue,i.isStaccato=t.isStaccato,i.accentuated=t.accentuated,e.addNote(i);for(let e of s.childNodes)if(e.nodeType===G.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===G.Element)switch(s.localName){case"drawObj":const t=this.parseDrawObj(s);if(t)if(t instanceof Un)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new nt,e.fermata.type=O.Medium):"f"===t.text?e.dynamics=p.F:"j"===t.text&&(e.dynamics=p.MF):this._isFirstSystem&&""===this.score.title&&t.align===P.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===P.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===P.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof Xn);else if(t instanceof qn)e.vibrato=w.Slight;else if(t instanceof Qn)e.crescendo=t.decrescendo?d.Decrescendo:d.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof Yn){const s=t;this._slurs.set(e,s)}else t instanceof jn&&this.applyVolta(t)}}parseBarDrawObject(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"drawObj":const e=this.parseDrawObj(t);e&&e instanceof jn&&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===G.Element)switch(s.localName){case"verse":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 De;return s.beamingMode=this._beamingMode,this.parseDuration(e,s,t),s}if(1===parseInt(s)){let e=new De;return e.beamingMode=this._beamingMode,e.duration=u.Whole,e}return Be.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return u.DoubleWhole;case"1/1":return u.Whole;case"1/2":return u.Half;case"1/4":return u.Quarter;case"1/8":return u.Eighth;case"1/16":return u.Sixteenth;case"1/32":return u.ThirtySecond;case"1/64":return u.SixtyFourth;case"1/128":return u.OneHundredTwentyEighth;default:return Be.warning("Importer","Unsupported duration"),u.Quarter}}parseDuration(e,t,s){const i=s.getAttribute("base");t.duration=this.parseDurationValue(i),s.attributes.has("dots")&&(t.dots=parseInt(s.attributes.get("dots")));const a=s.findChildElement("tuplet");if(a){t.tupletNumerator=parseInt(a.getAttribute("count"));const e="true"===a.getAttribute("tripartite")?3:1,s="true"===a.getAttribute("prolong")?0:1;let i=0;for(;e*Math.pow(2,i+s)<t.tupletNumerator;)i++;t.tupletDenominator=e*Math.pow(2,i)}}parsePageObjects(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"drawObj":const e=this.parseDrawObj(t);if(e&&e instanceof Un)switch(e.align){case P.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case P.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"drawObj":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===G.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 $n}parseOctaveClef(e){const t=new Kn;return e.attributes.has("octave")&&(t.octave=parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new jn;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 Qn;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new Jn;return e.attributes.has("number")&&(t.number=parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new qn}parseSlur(e){return new Yn}parseGuitar(e){const t=new Xn,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 Un;switch(e.attributes.has("x")&&(t.x=parseFloat(e.attributes.get("x"))),e.attributes.has("x")&&(t.y=parseFloat(e.attributes.get("y"))),e.getAttribute("align")){case"left":t.align=P.Left;break;case"center":t.align=P.Center;break;case"right":t.align=P.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=ce.Rectangle;break;case"ellipse":t.frame=ce.Ellipse;break;case"circle":t.frame=ce.Circle;break;case"none":t.frame=ce.None}if(e.firstElement){for(let s of e.childNodes)if(s.nodeType===G.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===G.Element)switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class io extends ue{get name(){return"Capella"}constructor(){super()}readScore(){Be.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new xt(this.data).read(),Be.debug(this.name,"Zip entries loaded"),e.length>0)for(let s of e)switch(s.fileName){case"score.xml":t=Ke.toString(s.data,this.settings.importer.encoding)}else this.data.reset(),t=Ke.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new ge("No valid capella file");Be.debug(this.name,"Start Parsing score.xml");try{let e=new so;return e.parseXml(t,this.settings),Be.debug(this.name,"score.xml parsed"),e.score}catch(e){throw new ge("Failed to parse CapXML",e)}}}class ao{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:[]});this._callback(e,this)}}class ro{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)}}class no{constructor(e,t){this.vertical=e,this.createLayout=t}}class oo{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class ho{static createStyleElement(e,t){let s=e.getElementById("alphaTabStyle");if(!s){if(!t)return void Be.error("AlphaTab","Font directory could not be detected, cannot create style element");s=e.createElement("style"),s.id="alphaTabStyle";let i=`\n @font-face {\n font-family: 'alphaTab';\n src: url('${t}Bravura.eot');\n src: url('${t}Bravura.eot?#iefix') format('embedded-opentype')\n , url('${t}Bravura.woff') format('woff')\n , url('${t}Bravura.otf') format('opentype')\n , url('${t}Bravura.svg#Bravura') format('svg');\n font-weight: normal;\n font-style: normal;\n }\n .at-surface * {\n cursor: default;\n vertical-align: top;\n overflow: visible;\n }\n .at-surface-svg text {\n dominant-baseline: central;\n } \n .at {\n font-family: 'alphaTab';\n speak: none;\n font-style: normal;\n font-weight: normal;\n font-variant: normal;\n text-transform: none;\n line-height: 1;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n font-size: ${ho.MusicFontSize}px;\n overflow: visible !important;\n }`;s.innerHTML=i,e.getElementsByTagName("head").item(0).appendChild(s),ho.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===ho._globalThis){try{ho._globalThis=globalThis}catch(e){}void 0===ho._globalThis&&(ho._globalThis=self),void 0===ho._globalThis&&(ho._globalThis=global),void 0===ho._globalThis&&(ho._globalThis=window),void 0===ho._globalThis&&(ho._globalThis=Function("return this")())}return this._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in ho.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in ho.globalThis}static createAlphaTabWorker(e){if(ho.webPlatform===se.BrowserModule){let t=new Blob([`import * as alphaTab from '${e}'`],{type:"text/javascript"});return new Worker(URL.createObjectURL(t),{type:"module"})}{let t=new Blob([`importScripts('${e}')`]);return new Worker(URL.createObjectURL(t))}}static throttle(e,t){let s=0;return()=>{ho.globalThis.clearTimeout(s),s=ho.globalThis.setTimeout(e,t)}}static detectScriptFile(){try{const e=import.meta.url;if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in ho.globalThis&&document.currentScript?document.currentScript.src:null}static registerJQueryPlugin(){if(!ho.isRunningInWorker&&ho.globalThis&&"jQuery"in ho.globalThis){let e=ho.globalThis.jQuery,t=new ea;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:ea.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&ho.renderEngines.has(e)?ho.renderEngines.get(e):ho.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&ho.layoutEngines.has(t)?ho.layoutEngines.get(t):ho.layoutEngines.get(e.Page)}static buildImporters(){return[new tt,new Lt,new Nt,new Mt,new io,new et]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new oo(!0,(()=>new sa))),e.set("default",e.get("svg")),ho.createPlatformSpecificRenderEngines(e),e}static createPlatformSpecificRenderEngines(e){e.set("html5",new oo(!1,(()=>new Si)))}static createDefaultStaveProfiles(){const e=new Map;e.set(t.ScoreTab,[new ka("score-effects",[new nr,new dr,new qa,new or,new Ca,new Ga,new ur,new lr,new Qa(!0),new pr,new tr,new gr,new ir,new Wn,new Na]),new xn,new ka("tab-effects",[new Ma,new Qa(!1),new Da,new Ya,new lr,new pr,new tr,new gr,new ir,new ar,new Aa,new za(m.Natural),new za(m.Artificial),new za(m.Pinch),new za(m.Tap),new za(m.Semi),new za(m.Feedback),new Ua,new Ea,new Va,new ja,new Za,new Ka,new Wn]),new Vn(!1,!1,!1)]),e.set(t.Score,[new ka("score-effects",[new nr,new dr,new qa,new or,new Ca,new Ga,new ur,new lr,new Qa(!0),new pr,new tr,new gr,new ir,new Aa,new Ua,new ja,new Za,new Ka,new Wn,new Na]),new xn,new ka("score-bottom-effects",[new Ma,new Qa(!1),new Da,new Ya])]);let s=[new nr,new dr,new qa,new or,new Ca,new Ga,new lr,new pr,new tr,new gr,new ir,new ar,new Aa,new za(m.Artificial),new za(m.Pinch),new za(m.Tap),new za(m.Semi),new za(m.Feedback),new Ua,new Ea,new Va,new ja,new Za,new Ka,new Wn,new Na];return e.set(t.Tab,[new ka("tab-effects",s),new Vn(!0,!0,!0),new ka("tab-bottom-effects",[new Ya])]),e.set(t.TabMixed,[new ka("tab-effects",s),new Vn(!1,!1,!1),new ka("tab-bottom-effects",[new Ya])]),e}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.Page,new no(!0,(e=>new Fr(e)))),t.set(e.Horizontal,new no(!1,(e=>new Cr(e)))),t}static platformInit(){ho.isRunningInAudioWorklet?ji.init():ho.isRunningInWorker?(bi.init(),hi.init()):ho.webPlatform!==se.Browser&&ho.webPlatform!==se.BrowserModule||(ho.registerJQueryPlugin(),ho.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in ho.globalThis||(ho.globalThis.ResizeObserver=ao),"IntersectionObserver"in ho.globalThis||(ho.globalThis.IntersectionObserver=ro))}static detectWebPlatform(){try{if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return se.NodeJs}catch(e){}try{if(import.meta.url)return se.BrowserModule}catch(e){}return se.Browser}}ho.MusicFontSize=34,ho.HighDpiFactor=1,ho._globalThis=void 0,ho.webPlatform=ho.detectWebPlatform(),ho.scriptFile=ho.detectScriptFile(),ho.bravuraFontChecker=new Wi("alphaTab"),ho.renderEngines=ho.createDefaultRenderEngines(),ho.layoutEngines=ho.createDefaultLayoutEngines(),ho.staveProfiles=ho.createDefaultStaveProfiles(),ho.platformInit();class lo{constructor(){if(this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=v.Info,this.useWorkers=!0,this.includeNoteBounds=!1,!ho.isRunningInWorker&&ho.globalThis.ALPHATAB_ROOT?(this.scriptFile=ho.globalThis.ALPHATAB_ROOT,this.scriptFile=lo.ensureFullUrl(this.scriptFile),this.scriptFile=lo.appendScriptName(this.scriptFile)):this.scriptFile=ho.scriptFile,!ho.isRunningInWorker&&ho.globalThis.ALPHATAB_FONT)this.fontDirectory=ho.globalThis.ALPHATAB_FONT,this.fontDirectory=lo.ensureFullUrl(this.fontDirectory);else if(this.fontDirectory=this.scriptFile,this.fontDirectory){let e=this.fontDirectory.lastIndexOf(String.fromCharCode(47));e>=0&&(this.fontDirectory=this.fontDirectory.substr(0,e)+"/font/")}}static ensureFullUrl(e){var t,s,i;if(!e)return"";if(!e.startsWith("http")&&!e.startsWith("https")&&!e.startsWith("file")){let a="",r=ho.globalThis.location;if(a+=null===(t=r.protocol)||void 0===t?void 0:t.toString(),a+="//".toString(),r.hostname&&(a+=null===(s=r.hostname)||void 0===s?void 0:s.toString()),r.port&&(a+=":".toString(),a+=null===(i=r.port)||void 0===i?void 0:i.toString()),!e.startsWith("/")){let e=r.pathname.split("/").slice(0,-1).join("/");e.length>0&&(e.startsWith("/")||(a+="/".toString()),a+=null==e?void 0:e.toString())}return e.startsWith("/")||(a+="/".toString()),a+=null==e?void 0:e.toString(),a}return e}static appendScriptName(e){return e&&!e.endsWith(".js")&&(e.endsWith("/")||(e+="/"),e+="alphaTab.js"),e}}class co{}co.version="1.3.0-alpha.148",co.date="2022-01-20T21:02:02.590Z";var uo,po=Object.freeze({__proto__:null,ScoreImporter:ue,ScoreLoader:Gi,UnsupportedFormatError:ge});class go{init(e,t){this.data=e,this.settings=t}export(e,t=null){const s=$e.withCapacity(1024);return this.init(s,null!=t?t:new Hs),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"}(uo||(uo={}));class fo{constructor(e,t,s=null){if(this.icon=uo.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 mo{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new dt;return this._rhythmIdLookup=new Map,this.writeDom(t,e),t.toFormattedString("",!0)}writeDom(e,t){const s=e.addElement("GPIF");s.addElement("GPVersion").innerText="7";const i=s.addElement("GPRevision");i.innerText="7",i.attributes.set("required","12021"),i.attributes.set("recommended","12023"),i.innerText="12025",s.addElement("Encoding").addElement("EncodingDescription").innerText="GP7",this.writeScoreNode(s,t),this.writeMasterTrackNode(s,t),this.writeAudioTracksNode(s,t),this.writeTracksNode(s,t),this.writeMasterBarsNode(s,t);const a=s.addElement("Bars"),r=s.addElement("Voices"),n=s.addElement("Beats"),o=s.addElement("Notes"),h=s.addElement("Rhythms");for(const e of t.tracks)for(const t of e.staves)for(const e of t.bars){this.writeBarNode(a,e);for(const t of e.voices){this.writeVoiceNode(r,t);for(const e of t.beats){this.writeBeatNode(n,e,h);for(const t of e.notes)this.writeNoteNode(o,t)}}}}writeNoteNode(e,t){const s=e.addElement("Note");s.attributes.set("id",t.id.toString()),this.writeNoteProperties(s,t),t.isGhost&&(s.addElement("AntiAccent").innerText="normal"),t.isLetRing&&s.addElement("LetRing"),t.isTrill&&(s.addElement("Trill").innerText=t.trillValue.toString());let a=0;switch(t.isStaccato&&(a|=1),t.accentuated){case i.Normal:a|=8;break;case i.Heavy:a|=4}if(a>0&&(s.addElement("Accent").innerText=a.toString()),t.isTieOrigin||t.isTieDestination){const e=s.addElement("Tie");e.attributes.set("origin",t.isTieOrigin?"true":"false"),e.attributes.set("destination",t.isTieDestination?"true":"false")}switch(t.vibrato){case 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"}writeNoteProperties(e,t){const s=e.addElement("Properties");if(this.writeConcertPitch(s,t),this.writeTransposedPitch(s,t),t.isStringed&&(this.writeSimplePropertyNode(s,"String","String",(t.string-1).toString()),this.writeSimplePropertyNode(s,"Fret","Fret",t.fret.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString())),t.isPiano&&(this.writeSimplePropertyNode(s,"Octave","Number",t.octave.toString()),this.writeSimplePropertyNode(s,"Tone","Step",t.tone.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString())),t.beat.tap&&this.writeSimplePropertyNode(s,"Tapped","Enable",null),t.harmonicType!==m.None){switch(t.harmonicType){case m.Natural:this.writeSimplePropertyNode(s,"HarmonicType","HType","Natural");break;case m.Artificial:this.writeSimplePropertyNode(s,"HarmonicType","HType","Artificial");break;case m.Pinch:this.writeSimplePropertyNode(s,"HarmonicType","HType","Pinch");break;case m.Tap:this.writeSimplePropertyNode(s,"HarmonicType","HType","Tap");break;case m.Semi:this.writeSimplePropertyNode(s,"HarmonicType","HType","Semi");break;case m.Feedback:this.writeSimplePropertyNode(s,"HarmonicType","HType","Feedback")}0!==t.harmonicValue&&this.writeSimplePropertyNode(s,"HarmonicFret","HFret",t.harmonicValue.toString())}t.isDead&&this.writeSimplePropertyNode(s,"Muted","Enable",null),t.isPalmMute&&this.writeSimplePropertyNode(s,"PalmMuted","Enable",null),t.hasBend&&this.writeBend(s,t),t.isHammerPullOrigin&&this.writeSimplePropertyNode(s,"HopoOrigin","Enable",null),t.isHammerPullDestination&&this.writeSimplePropertyNode(s,"HopoDestination","Enable",null),t.isLeftHandTapped&&this.writeSimplePropertyNode(s,"LeftHandTapped","Enable",null);let i=0;switch(t.slideInType){case b.IntoFromAbove:i|=32;break;case b.IntoFromBelow:i|=16}switch(t.slideOutType){case S.Shift:i|=1;break;case S.Legato:i|=2;break;case S.OutDown:i|=4;break;case S.OutUp:i|=8;break;case S.PickSlideDown:i|=64;break;case S.PickSlideUp:i|=128}i>0&&this.writeSimplePropertyNode(s,"Slide","Flags",i.toString())}writeTransposedPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"TransposedPitch",t.displayValueWithoutBend,t.accidentalMode)}writeConcertPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"ConcertPitch",t.realValueWithoutHarmonic,t.accidentalMode)}writePitchForValue(e,t,s,i){let a=0,r=0,n="",o="";const h=()=>{a=s%12,r=s/12|0,n=Ye.defaultSteps[a],o=Ye.defaultAccidentals[a]};switch(h(),i){case y.Default:break;case y.ForceNone:case y.ForceNatural:o="";break;case y.ForceSharp:o="#";break;case y.ForceDoubleSharp:"#"===o&&(s-=2,h()),o="x";break;case y.ForceFlat:"#"===o&&(s+=1,h()),o="b";break;case y.ForceDoubleFlat:"#"===o&&(s+=2,h()),o="bb"}this.writePitch(e,t,n,r.toString(),o)}writePitch(e,t,s,i,a){const r=e.addElement("Property");r.attributes.set("name",t);const n=r.addElement("Pitch");n.addElement("Step").innerText=s,n.addElement("Accidental").innerText=a,n.addElement("Octave").innerText=i}writeBend(e,t){t.hasBend&&t.bendPoints.length<=4&&this.writeStandardBend(e,t.bendPoints)}writeStandardBend(e,t){this.writeSimplePropertyNode(e,"Bended","Enable",null);var s,i,a=t[0],r=t[t.length-1];switch(t.length){case 4:s=t[1],i=t[2];break;case 3:s=t[1],i=t[1];break;default:i=s=new be((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/be.MaxPosition*100}writeBeatNode(e,t,s){const i=e.addElement("Beat");if(i.attributes.set("id",t.id.toString()),i.addElement("Dynamic").innerText=p[t.dynamics],t.fadeIn&&(i.addElement("Fadding").innerText="FadeIn"),t.isTremolo)switch(t.tremoloSpeed){case u.Eighth:i.addElement("Tremolo").innerText="1/2";break;case u.Sixteenth:i.addElement("Tremolo").innerText="1/4";break;case u.ThirtySecond:i.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&i.addElement("Chord").setCData(t.chordId),t.crescendo!==d.None&&(i.addElement("Hairpin").innerText=d[t.crescendo]),t.brushType){case c.ArpeggioUp:i.addElement("Arpeggio").innerText="Up";break;case c.ArpeggioDown:i.addElement("Arpeggio").innerText="Down"}switch(t.text&&i.addElement("FreeText").setCData(t.text),t.graceType){case g.OnBeat:case g.BeforeBeat:i.addElement("GraceNotes").innerText=g[t.graceType]}if(t.ottava!==n.Regular&&(i.addElement("Ottavia").innerText=n[t.ottava].substr(1)),t.hasWhammyBar&&this.writeWhammyNode(i,t),t.isLegatoOrigin||t.isLegatoDestination){const e=i.addElement("Legato");e.attributes.set("origin",t.isLegatoOrigin?"true":"false"),e.attributes.set("destination",t.isLegatoDestination?"true":"false")}if(this.writeRhythm(i,t,s),null!==t.preferredBeamDirection)switch(t.preferredBeamDirection){case H.Up:i.addElement("TransposedPitchStemOrientation").innerText="Upward";break;case H.Down:i.addElement("TransposedPitchStemOrientation").innerText="Downward"}i.addElement("ConcertPitchStemOrientation").innerText="Undefined",t.isRest||(i.addElement("Notes").innerText=t.notes.map((e=>e.id)).join(" ")),this.writeBeatProperties(i,t),this.writeBeatXProperties(i,t),t.lyrics&&t.lyrics.length>0&&this.writeBeatLyrics(i,t.lyrics)}writeBeatLyrics(e,t){const s=e.addElement("Lyrics");for(const e of t){s.addElement("Line").setCData(e)}}writeBeatXProperties(e,t){const s=e.addElement("XProperties");t.brushDuration>0&&this.writeSimpleXPropertyNode(s,"687935489","Int",t.brushDuration.toString())}writeBeatProperties(e,t){const s=e.addElement("Properties");switch(t.brushType){case c.BrushUp:this.writeSimplePropertyNode(s,"Brush","Direction","Up");break;case c.BrushDown:this.writeSimplePropertyNode(s,"Brush","Direction","Down")}switch(t.pickStroke){case x.Up:this.writeSimplePropertyNode(s,"PickStroke","Direction","Up");break;case x.Down:this.writeSimplePropertyNode(s,"PickStroke","Direction","Down")}switch(t.slap&&this.writeSimplePropertyNode(s,"Slapped","Enable",null),t.pop&&this.writeSimplePropertyNode(s,"Popped","Enable",null),t.vibrato){case w.Wide:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Wide");break;case w.Slight:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Slight")}}writeRhythm(e,t,s){const i=`${t.duration}_${t.dots}_${t.tupletNumerator}_${t.tupletDenominator}';`;let a;if(this._rhythmIdLookup.has(i))a=this._rhythmIdLookup.get(i);else{a=this._rhythmIdLookup.size.toString(),this._rhythmIdLookup.set(i,a);const e=s.addElement("Rhythm");if(e.attributes.set("id",a),t.hasTuplet){const s=e.addElement("PrimaryTuplet");s.attributes.set("num",t.tupletNumerator.toString()),s.attributes.set("den",t.tupletDenominator.toString())}t.dots>0&&e.addElement("AugmentationDot").attributes.set("count",t.dots.toString());let r="Quarter";switch(t.duration){case u.QuadrupleWhole:r="Long";break;case u.DoubleWhole:r="DoubleWhole";break;case u.Whole:r="Whole";break;case u.Half:r="Half";break;case u.Quarter:r="Quarter";break;case u.Eighth:r="Eighth";break;case u.Sixteenth:r="16th";break;case u.ThirtySecond:r="32nd";break;case u.SixtyFourth:r="64th";break;case u.OneHundredTwentyEighth:r="128th";break;case u.TwoHundredFiftySixth:r="256th"}e.addElement("NoteValue").innerText=r}e.addElement("Rhythm").attributes.set("ref",a)}writeWhammyNode(e,t){t.hasWhammyBar&&t.whammyBarPoints.length<=4&&this.writeStandardWhammy(e,t.whammyBarPoints)}writeStandardWhammy(e,t){const s=e.addElement("Whammy");var i,a,r=t[0],n=t[t.length-1];switch(t.length){case 4:i=t[1],a=t[2];break;case 3:i=t[1],a=t[1];break;default:a=i=new be((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("4"),s.addElement("ScoreSystemsLayout").setCData("4"),s.addElement("ScoreZoomPolicy").innerText="Value",s.addElement("ScoreZoom").innerText="1",s.addElement("MultiVoice").innerText="1>"}writeMasterTrackNode(e,t){const s=e.addElement("MasterTrack");s.addElement("Tracks").innerText=t.tracks.map((e=>e.index)).join(" ");const i=s.addElement("Automations");t.masterBars.length>0&&t.masterBars[0].isAnacrusis&&s.addElement("Anacrusis");const a=i.addElement("Automation");a.addElement("Type").innerText="Tempo",a.addElement("Linear").innerText="false",a.addElement("Bar").innerText="0",a.addElement("Position").innerText="0",a.addElement("Visible").innerText="true",a.addElement("Value").innerText=t.tempo+" 2",t.tempoLabel&&(a.addElement("Text").innerText=t.tempoLabel);for(const e of t.masterBars)if(e.index>0&&e.tempoAutomation){const t=i.addElement("Automation");t.addElement("Type").innerText="Tempo",t.addElement("Linear").innerText=e.tempoAutomation.isLinear?"true":"false",t.addElement("Bar").innerText=e.index.toString(),t.addElement("Position").innerText=e.tempoAutomation.ratioPosition.toString(),t.addElement("Visible").innerText="true",t.addElement("Value").innerText=e.tempoAutomation.value+" 2",e.tempoAutomation.text&&(t.addElement("Text").innerText=e.tempoAutomation.text)}}writeAudioTracksNode(e,t){e.addElement("AudioTracks")}writeTracksNode(e,t){const s=e.addElement("Tracks");for(const e of t.tracks)this.writeTrackNode(s,e)}writeTrackNode(e,t){const s=e.addElement("Track");s.attributes.set("id",t.index.toString()),s.addElement("Name").setCData(t.name),s.addElement("ShortName").setCData(t.shortName),s.addElement("Color").innerText=`${t.color.r} ${t.color.g} ${t.color.b}`,s.addElement("SystemsDefautLayout").innerText="3",s.addElement("SystemsLayout").innerText="1",s.addElement("AutoBrush"),s.addElement("PalmMute").innerText="0",s.addElement("PlayingStyle").innerText=de.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",s.addElement("UseOneChannelPerString"),s.addElement("IconId").innerText=mo.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?mo.DrumKitProgramInfo.icon:mo.MidiProgramInfoLookup.has(e.program)?mo.MidiProgramInfoLookup.get(e.program).icon:uo.SteelGuitar}writeSoundAndAutomation(e,t,s,i,a,r,n,o=0){const h=e.addElement("Sound");h.addElement("Name").setCData(s),h.addElement("Label").setCData(s),h.addElement("Path").setCData(i),h.addElement("Role").setCData(a);const l=h.addElement("MIDI");l.addElement("LSB").innerText="0",l.addElement("MSB").innerText="0",l.addElement("Program").innerText=n.toString();const c=t.addElement("Automation");c.addElement("Type").innerText="Sound",c.addElement("Linear").innerText="false",c.addElement("Bar").innerText=r.toString(),c.addElement("Position").innerText=o.toString(),c.addElement("Visible").innerText="true",c.addElement("Value").setCData(`${i};${s};${a}`)}writeSoundsAndAutomations(e,t){const s=e.addElement("Sounds"),i=e.addElement("Automations");if(t.staves.length>0&&t.staves[0].bars.length>0){const e=`Track_${t.index}_Initial`,r="Midi/"+t.playbackInfo.program,n="Factory";let o=!1;for(const h of t.staves)for(const l of h.bars)for(const h of l.voices)for(const c of h.beats){const h=c.getAutomation(a.Instrument),d=0===l.index&&0===c.index;if(h){const a=d?e:"ProgramChange_"+c.id,u=d?r:"Midi/"+h.value,p=d?n:"User";d||o||(this.writeSoundAndAutomation(s,i,e,r,n,t.staves[0].bars[0].index,t.playbackInfo.program),o=!0),this.writeSoundAndAutomation(s,i,a,u,p,l.index,h.value,h.ratioPosition),d&&(o=!0)}}}}writeMidiConnectionNode(e,t){const s=e.addElement("MidiConnection");s.addElement("Port").innerText=t.playbackInfo.port.toString(),s.addElement("PrimaryChannel").innerText=t.playbackInfo.primaryChannel.toString(),s.addElement("SecondaryChannel").innerText=t.playbackInfo.secondaryChannel.toString(),s.addElement("ForeOneChannelPerString").innerText="false"}writeRseNode(e,t){const s=e.addElement("RSE").addElement("ChannelStrip");s.attributes.set("version","E56");s.addElement("Parameters").innerText=`0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1 0.5 ${t.playbackInfo.balance/16} ${t.playbackInfo.volume/16} 0.5 0.5 0.5`}writeStavesNode(e,t){const s=e.addElement("Staves");for(const e of t.staves)this.writeStaffNode(s,e)}writeStaffNode(e,t){const s=e.addElement("Staff").addElement("Properties");if(this.writeSimplePropertyNode(s,"CapoFret","Fret",t.capo.toString()),this.writeSimplePropertyNode(s,"FretCount","Fret","24"),t.tuning.length>0){const e=s.addElement("Property");switch(e.attributes.set("name","Tuning"),e.addElement("Pitches").innerText=t.tuning.slice().reverse().join(" "),e.addElement("Label").setCData(t.tuningName),e.addElement("LabelVisible").innerText=t.tuningName?"true":"false",e.addElement("Flat"),t.tuning.length){case 3:e.addElement("Instrument").innerText="Shamisen";break;case 4:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":42==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Cello":43==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Contrabass":40==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Violin":41==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Viola":e.addElement("Instrument").innerText="Bass";break;case 5:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":e.addElement("Instrument").innerText="Bass";break;case 6:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;case 7:t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;default:e.addElement("Instrument").innerText="Guitar"}}this.writeSimplePropertyNode(s,"PartialCapoFret","Fret","0"),this.writeSimplePropertyNode(s,"PartialCapoStringFlags","Bitset",t.tuning.map((e=>"0")).join("")),this.writeSimplePropertyNode(s,"TuningFlat","Enable",null),this.writeDiagramCollection(s,t,"DiagramCollection"),this.writeDiagramCollection(s,t,"DiagramWorkingSet")}writeDiagramCollection(e,t,s){const i=e.addElement("Property");i.attributes.set("name",s);const a=i.addElement("Items"),r=t.chords;if(r)for(const[e,t]of r){const s=a.addElement("Item");s.attributes.set("id",e),s.attributes.set("name",t.name);const i=s.addElement("Diagram");i.attributes.set("stringCount",t.strings.length.toString()),i.attributes.set("fretCount","5"),i.attributes.set("baseFret",(t.firstFret-1).toString()),i.attributes.set("barStates",t.strings.map((e=>"1")).join(" "));const r=[],n=new Map;for(let e=0;e<t.strings.length;e++){let s=t.strings[e];if(-1!==s){const a=i.addElement("Fret"),o=t.strings.length-1-e;a.attributes.set("string",o.toString()),a.attributes.set("fret",(s-t.firstFret+1).toString()),n.has(s)||(n.set(s,[]),r.push(s)),n.get(s).push(o)}}r.sort();const o=i.addElement("Fingering");if(t.barreFrets.length>0){const e=[f.LittleFinger,f.AnnularFinger,f.MiddleFinger,f.IndexFinger];for(const s of r){const i=n.get(s);if(i.length>1&&t.barreFrets.indexOf(s)>=0){const a=e.length>0?e.pop():f.IndexFinger;for(const e of i){const i=o.addElement("Position");switch(a){case f.LittleFinger:i.attributes.set("finger","Pinky");break;case f.AnnularFinger:i.attributes.set("finger","Ring");break;case f.MiddleFinger:i.attributes.set("finger","Middle");break;case f.IndexFinger:i.attributes.set("finger","Index")}i.attributes.set("fret",(s-t.firstFret+1).toString()),i.attributes.set("string",e.toString())}}}}const h=i.addElement("Property");h.attributes.set("name","ShowName"),h.attributes.set("type","bool"),h.attributes.set("value",t.showName?"true":"false");const l=i.addElement("Property");l.attributes.set("name","ShowDiagram"),l.attributes.set("type","bool"),l.attributes.set("value",t.showDiagram?"true":"false");const c=i.addElement("Property");c.attributes.set("name","ShowFingering"),c.attributes.set("type","bool"),c.attributes.set("value",t.showFingering?"true":"false");const d=i.addElement("Chord"),u=d.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=d.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=d.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const m=d.addElement("Degree");m.attributes.set("interval","Fifth"),m.attributes.set("alteration","Perfect"),m.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,s,i){const a=e.addElement("Property");a.attributes.set("name",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeSimpleXPropertyNode(e,t,s,i){const a=e.addElement("XProperty");a.attributes.set("id",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeLyricsNode(e,t){const s=e.addElement("Lyrics");s.attributes.set("dispatched","true");let i=[];for(const e of t.staves[0].bars)for(const t of e.voices)if(!t.isEmpty)for(const s of t.beats)if(s.lyrics)for(let t=0;t<s.lyrics.length;t++){for(;t>=i.length;){const t=new Ae;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(xe.instrumentArticulations.values());s.addElement("Name").innerText=mo.DrumKitProgramInfo.instrumentSetName,s.addElement("Type").innerText=mo.DrumKitProgramInfo.instrumentSetType;let i="",r=new ot,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 E.Top:e.addElement("TechniquePlacement").innerText="below";break;case E.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case E.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=mo.MidiProgramInfoLookup.has(t.playbackInfo.program)?mo.MidiProgramInfoLookup.get(t.playbackInfo.program):mo.MidiProgramInfoLookup.get(0);s.addElement("Name").innerText=e.instrumentSetName,s.addElement("Type").innerText=e.instrumentSetType;const i=s.addElement("Elements").addElement("Element");i.addElement("Pitched").innerText="Pitched",i.addElement("Type").innerText="pitched",i.addElement("SoundbankName").innerText="";const a=i.addElement("Articulations").addElement("Articulation");a.addElement("Name").innerText="",a.addElement("StaffLine").innerText="0",a.addElement("Noteheads").innerText="noteheadBlack noteheadHalf noteheadWhole",a.addElement("TechniquePlacement").innerText="outside",a.addElement("TechniqueSymbol").innerText="",a.addElement("InputMidiNumbers").innerText="",a.addElement("OutputRSESound").innerText="",a.addElement("OutputMidiNumber").innerText="0"}}mapMusicSymbol(e){if(e===N.None)return"";let t=N[e];return t.substring(0,1).toLowerCase()+t.substring(1)}writeMasterBarsNode(e,t){const s=e.addElement("MasterBars");for(const e of t.masterBars)this.writeMasterBarNode(s,e)}writeMasterBarNode(e,t){const s=e.addElement("MasterBar"),i=s.addElement("Key");i.addElement("AccidentalCount").innerText=t.keySignature.toString(),i.addElement("Mode").innerText=I[t.keySignatureType],i.addElement("Sharps").innerText="Sharps",s.addElement("Time").innerText=`${t.timeSignatureNumerator}/${t.timeSignatureDenominator}`;let a=[];for(const e of t.score.tracks)for(const s of e.staves)a.push(s.bars[t.index].id.toString());if(s.addElement("Bars").innerText=a.join(" "),t.isDoubleBar&&s.addElement("DoubleBar"),t.isSectionStart){const e=s.addElement("Section");e.addElement("Letter").setCData(t.section.marker),e.addElement("Text").setCData(t.section.text)}if(t.isRepeatStart||t.isRepeatEnd){const e=s.addElement("Repeat");e.attributes.set("start",t.isRepeatStart?"true":"false"),e.attributes.set("end",t.isRepeatEnd?"true":"false"),t.isRepeatEnd&&e.attributes.set("count",t.repeatCount.toString())}if(t.alternateEndings>0){let e=t.alternateEndings;const i=[];let a=0;for(;e>0;)1==(e>>a&1)&&(i.push(a+1),e&=~(1<<a)),a++;s.addElement("AlternateEndings").innerText=i.join(" ")}t.tripletFeel!==D.NoTripletFeel&&(s.addElement("TripletFeel").innerText=D[t.tripletFeel]),this.writeFermatas(s,t)}writeFermatas(e,t){var s,i;const a=null!==(i=null===(s=t.fermata)||void 0===s?void 0:s.size)&&void 0!==i?i:0;if(0!==a&&a>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/ye.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=O[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(" ")}}mo.MidiProgramInfoLookup=new Map([[0,new fo(uo.Piano,"Acoustic Piano")],[1,new fo(uo.Piano,"Acoustic Piano")],[2,new fo(uo.Piano,"Electric Piano")],[3,new fo(uo.Piano,"Acoustic Piano")],[4,new fo(uo.Piano,"Electric Piano")],[5,new fo(uo.Piano,"Electric Piano")],[6,new fo(uo.Piano,"Harpsichord")],[7,new fo(uo.Piano,"Harpsichord")],[8,new fo(uo.PitchedIdiophone,"Celesta")],[9,new fo(uo.PitchedIdiophone,"Vibraphone")],[10,new fo(uo.PitchedIdiophone,"Vibraphone")],[11,new fo(uo.PitchedIdiophone,"Vibraphone")],[12,new fo(uo.PitchedIdiophone,"Xylophone")],[13,new fo(uo.PitchedIdiophone,"Xylophone")],[14,new fo(uo.PitchedIdiophone,"Vibraphone")],[15,new fo(uo.Banjo,"Banjo")],[16,new fo(uo.Piano,"Electric Organ")],[17,new fo(uo.Piano,"Electric Organ")],[18,new fo(uo.Piano,"Electric Organ")],[19,new fo(uo.Piano,"Electric Organ")],[20,new fo(uo.Piano,"Electric Organ")],[21,new fo(uo.Piano,"Electric Organ")],[22,new fo(uo.Woodwind,"Recorder")],[23,new fo(uo.Piano,"Electric Organ")],[24,new fo(uo.ClassicalGuitar,"Nylon Guitar")],[25,new fo(uo.SteelGuitar,"Steel Guitar")],[26,new fo(uo.SteelGuitar,"Electric Guitar")],[27,new fo(uo.ElectricGuitar,"Electric Guitar")],[28,new fo(uo.ElectricGuitar,"Electric Guitar")],[29,new fo(uo.ElectricGuitar,"Electric Guitar")],[30,new fo(uo.SteelGuitar,"Electric Guitar")],[31,new fo(uo.SteelGuitar,"Electric Guitar")],[32,new fo(uo.Bass,"Acoustic Bass")],[33,new fo(uo.Bass,"Electric Bass")],[34,new fo(uo.Bass,"Electric Bass")],[35,new fo(uo.Bass,"Acoustic Bass")],[36,new fo(uo.Bass,"Electric Bass")],[37,new fo(uo.Bass,"Electric Bass")],[38,new fo(uo.Synth,"Synth Bass")],[39,new fo(uo.Synth,"Synth Bass")],[40,new fo(uo.Strings,"Violin")],[41,new fo(uo.Strings,"Viola")],[42,new fo(uo.Strings,"Cello")],[43,new fo(uo.Strings,"Contrabass")],[44,new fo(uo.Strings,"Violin")],[45,new fo(uo.Strings,"Violin")],[46,new fo(uo.Piano,"Harp")],[47,new fo(uo.Membraphone,"Timpani")],[48,new fo(uo.Strings,"Violin")],[49,new fo(uo.Strings,"Violin")],[50,new fo(uo.Strings,"Violin")],[51,new fo(uo.Strings,"Violin")],[52,new fo(uo.Vocal,"Voice")],[53,new fo(uo.Vocal,"Voice")],[54,new fo(uo.Vocal,"Voice")],[55,new fo(uo.Synth,"Pad Synthesizer")],[56,new fo(uo.Brass,"Trumpet")],[57,new fo(uo.Brass,"Trombone")],[58,new fo(uo.Brass,"Tuba")],[59,new fo(uo.Brass,"Trumpet")],[60,new fo(uo.Brass,"French Horn")],[61,new fo(uo.Brass,"Trumpet")],[62,new fo(uo.Brass,"Trumpet")],[63,new fo(uo.Brass,"Trumpet")],[64,new fo(uo.Reed,"Saxophone")],[65,new fo(uo.Reed,"Saxophone")],[66,new fo(uo.Reed,"Saxophone")],[67,new fo(uo.Reed,"Saxophone")],[68,new fo(uo.Reed,"Oboe")],[69,new fo(uo.Reed,"English Horn")],[70,new fo(uo.Reed,"Bassoon")],[71,new fo(uo.Reed,"Clarinet")],[72,new fo(uo.Reed,"Piccolo")],[73,new fo(uo.Woodwind,"Flute")],[74,new fo(uo.Woodwind,"Recorder")],[75,new fo(uo.Woodwind,"Flute")],[76,new fo(uo.Woodwind,"Recorder")],[77,new fo(uo.Woodwind,"Flute")],[78,new fo(uo.Woodwind,"Recorder")],[79,new fo(uo.Woodwind,"Flute")],[80,new fo(uo.Synth,"Lead Synthesizer")],[81,new fo(uo.Synth,"Lead Synthesizer")],[82,new fo(uo.Synth,"Lead Synthesizer")],[83,new fo(uo.Synth,"Lead Synthesizer")],[84,new fo(uo.Synth,"Lead Synthesizer")],[85,new fo(uo.Synth,"Lead Synthesizer")],[86,new fo(uo.Synth,"Lead Synthesizer")],[87,new fo(uo.Synth,"Lead Synthesizer")],[88,new fo(uo.Synth,"Pad Synthesizer")],[89,new fo(uo.Synth,"Pad Synthesizer")],[90,new fo(uo.Synth,"Pad Synthesizer")],[91,new fo(uo.Synth,"Pad Synthesizer")],[92,new fo(uo.Synth,"Pad Synthesizer")],[93,new fo(uo.Synth,"Pad Synthesizer")],[94,new fo(uo.Synth,"Pad Synthesizer")],[95,new fo(uo.Synth,"Pad Synthesizer")],[96,new fo(uo.Fx,"Pad Synthesizer")],[97,new fo(uo.Fx,"Pad Synthesizer")],[98,new fo(uo.Fx,"Pad Synthesizer")],[99,new fo(uo.Fx,"Pad Synthesizer")],[100,new fo(uo.Fx,"Lead Synthesizer")],[101,new fo(uo.Fx,"Lead Synthesizer")],[102,new fo(uo.Fx,"Lead Synthesizer")],[103,new fo(uo.Fx,"Trumpet")],[104,new fo(uo.ElectricGuitar,"Banjo")],[105,new fo(uo.Banjo,"Banjo")],[106,new fo(uo.Ukulele,"Ukulele")],[107,new fo(uo.Banjo,"Banjo")],[108,new fo(uo.PitchedIdiophone,"Xylophone")],[109,new fo(uo.Reed,"Bassoon")],[110,new fo(uo.Strings,"Violin")],[111,new fo(uo.Woodwind,"Flute")],[112,new fo(uo.PitchedIdiophone,"Xylophone")],[113,new fo(uo.Idiophone,"Celesta")],[114,new fo(uo.PitchedIdiophone,"Vibraphone")],[115,new fo(uo.Idiophone,"Xylophone")],[116,new fo(uo.Membraphone,"Xylophone")],[117,new fo(uo.Membraphone,"Xylophone")],[118,new fo(uo.Membraphone,"Xylophone")],[119,new fo(uo.Idiophone,"Celesta")],[120,new fo(uo.Fx,"Steel Guitar")],[121,new fo(uo.Fx,"Recorder")],[122,new fo(uo.Fx,"Recorder")],[123,new fo(uo.Fx,"Recorder")],[124,new fo(uo.Fx,"Recorder")],[125,new fo(uo.Fx,"Recorder")],[126,new fo(uo.Fx,"Recorder")],[127,new fo(uo.Fx,"Timpani")]]),mo.DrumKitProgramInfo=new fo(uo.PercussionKit,"Drums","drumKit");class yo{constructor(){this._checkValue=yo.CrcInit,this.reset()}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==(1&s)?s>>>1^3988292384:s>>>1;e[t]=s}return e}get value(){return~this._checkValue}update(e,t,s){for(let i=0;i<s;i++)this._checkValue=yo.Crc32Lookup[255&(this._checkValue^e[t+i])]^this._checkValue>>>8}reset(){this._checkValue=yo.CrcInit}}yo.Crc32Lookup=yo.buildCrc32Lookup(),yo.CrcInit=4294967295;class bo{}bo.MAX_WBITS=15,bo.WSIZE=1<<bo.MAX_WBITS,bo.WMASK=bo.WSIZE-1,bo.MIN_MATCH=3,bo.MAX_MATCH=258,bo.DEFAULT_MEM_LEVEL=8,bo.PENDING_BUF_SIZE=1<<bo.DEFAULT_MEM_LEVEL+8,bo.HASH_BITS=bo.DEFAULT_MEM_LEVEL+7,bo.HASH_SIZE=1<<bo.HASH_BITS,bo.HASH_SHIFT=(bo.HASH_BITS+bo.MIN_MATCH-1)/bo.MIN_MATCH,bo.HASH_MASK=bo.HASH_SIZE-1,bo.MIN_LOOKAHEAD=bo.MAX_MATCH+bo.MIN_MATCH+1,bo.MAX_DIST=bo.WSIZE-bo.MIN_LOOKAHEAD;class So{constructor(e,t,s,i){this.length=null,this.numCodes=0,this.codes=null,this.huffman=e,this.minNumCodes=s,this.maxLength=i,this.freqs=new Int16Array(t),this.bitLengthCounts=new Int32Array(i)}reset(){for(let e=0;e<this.freqs.length;e++)this.freqs[e]=0;this.codes=null,this.length=null}buildTree(){let e=this.freqs.length,t=new Int32Array(e),s=0,i=0;for(let a=0;a<e;a++){let e=this.freqs[a];if(0!==e){let r=s++;for(;r>0;){let s=Math.floor((r-1)/2);if(!(this.freqs[t[s]]>e))break;t[r]=t[s],r=s}t[r]=a,i=a}}for(;s<2;){let e=i<2?++i:0;t[s++]=e}this.numCodes=Math.max(i+1,this.minNumCodes);let a=s,r=new Int32Array(4*s-2),n=new Int32Array(2*s-1),o=a;for(let e=0;e<s;e++){let s=t[e];r[2*e]=s,r[2*e+1]=-1,n[e]=this.freqs[s]<<8,t[e]=e}do{let e=t[0],i=t[--s],a=0,h=1;for(;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*h+1;let l=n[i];for(;h=a,a>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i;let c=t[0];i=o++,r[2*i]=e,r[2*i+1]=c;let d=Math.min(255&n[e],255&n[c]);for(l=n[e]+n[c]-d+1,n[i]=l,a=0,h=1;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*a+1;for(;h=a,h>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i}while(s>1);this.buildLength(r)}buildLength(e){this.length=new Uint8Array(this.freqs.length);let t=Math.floor(e.length/2),s=Math.floor((t+1)/2),i=0;for(let e=0;e<this.maxLength;e++)this.bitLengthCounts[e]=0;let a=new Int32Array(t);a[t-1]=0;for(let s=t-1;s>=0;s--)if(-1!=e[2*s+1]){let t=a[s]+1;t>this.maxLength&&(t=this.maxLength,i++),a[e[2*s]]=t,a[e[2*s+1]]=t}else{let t=a[s];this.bitLengthCounts[t-1]++,this.length[e[2*s]]=a[s]}if(0==i)return;let r=this.maxLength-1;do{for(;0==this.bitLengthCounts[--r];);do{this.bitLengthCounts[r]--,this.bitLengthCounts[++r]++,i-=1<<this.maxLength-1-r}while(i>0&&r<this.maxLength-1)}while(i>0);this.bitLengthCounts[this.maxLength-1]+=i,this.bitLengthCounts[this.maxLength-2]-=i;let n=2*s;for(let t=this.maxLength;0!=t;t--){let s=this.bitLengthCounts[t-1];for(;s>0;){let i=2*e[n++];-1==e[i+1]&&(this.length[e[i]]=t,s--)}}}getEncodedLength(){let e=0;for(let t=0;t<this.freqs.length;t++)e+=this.freqs[t]*this.length[t];return e}calcBLFreq(e){let t,s,i,a=-1,r=0;for(;r<this.numCodes;){i=1;let n=this.length[r];for(0==n?(t=138,s=3):(t=6,s=3,a!=n&&(e.freqs[n]++,i=0)),a=n,r++;r<this.numCodes&&a==this.length[r]&&(r++,!(++i>=t)););i<s?e.freqs[a]+=i:0!=a?e.freqs[So.Repeat3To6]++:i<=10?e.freqs[So.Repeat3To10]++:e.freqs[So.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]=wo.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(So.Repeat3To6),this.huffman.pending.writeBits(i-3,2)):i<=10?(e.writeSymbol(So.Repeat3To10),this.huffman.pending.writeBits(i-3,3)):(e.writeSymbol(So.Repeat11To138),this.huffman.pending.writeBits(i-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}So.Repeat3To6=16,So.Repeat3To10=17,So.Repeat11To138=18;class wo{constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new So(this,wo.LITERAL_NUM,257,15),this.distTree=new So(this,wo.DIST_NUM,1,15),this.blTree=new So(this,wo.BITLEN_NUM,4,7),this.d_buf=new Int16Array(wo.BUFSIZE),this.l_buf=new Uint8Array(wo.BUFSIZE)}static staticInit(){let e=0;for(;e<144;)wo.staticLCodes[e]=wo.bitReverse(48+e<<8),wo.staticLLength[e++]=8;for(;e<256;)wo.staticLCodes[e]=wo.bitReverse(256+e<<7),wo.staticLLength[e++]=9;for(;e<280;)wo.staticLCodes[e]=wo.bitReverse(-256+e<<9),wo.staticLLength[e++]=7;for(;e<wo.LITERAL_NUM;)wo.staticLCodes[e]=wo.bitReverse(-88+e<<8),wo.staticLLength[e++]=8;for(e=0;e<wo.DIST_NUM;e++)wo.staticDCodes[e]=wo.bitReverse(e<<11),wo.staticDLength[e]=5}static bitReverse(e){return wo.bit4Reverse[15&e]<<12|wo.bit4Reverse[e>>4&15]<<8|wo.bit4Reverse[e>>8&15]<<4|wo.bit4Reverse[e>>12]}isFull(){return this.last_lit>=wo.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((wo.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[wo.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[wo.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<wo.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*wo.staticLLength[e];for(let e=0;e<wo.DIST_NUM;e++)n+=this.distTree.freqs[e]*wo.staticDLength[e];r>=n&&(r=n),t>=0&&s+4<r>>3?this.flushStoredBlock(e,t,s,i):r==n?(this.pending.writeBits((wo.STATIC_TREES<<1)+(i?1:0),3),this.literalTree.setStaticCodes(wo.staticLCodes,wo.staticLLength),this.distTree.setStaticCodes(wo.staticDCodes,wo.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((wo.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[wo.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=wo.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=wo.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(wo.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;let s=wo.Lcode(t-3);this.literalTree.freqs[s]++,s>=265&&s<285&&(this.extra_bits+=Math.floor((s-261)/4));let i=wo.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}}wo.BUFSIZE=1<<bo.DEFAULT_MEM_LEVEL+6,wo.LITERAL_NUM=286,wo.STORED_BLOCK=0,wo.STATIC_TREES=1,wo.DYN_TREES=2,wo.DIST_NUM=30,wo.staticLCodes=new Int16Array(wo.LITERAL_NUM),wo.staticLLength=new Uint8Array(wo.LITERAL_NUM),wo.staticDCodes=new Int16Array(wo.DIST_NUM),wo.staticDLength=new Uint8Array(wo.DIST_NUM),wo.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],wo.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),wo.BITLEN_NUM=19,wo.EOF_SYMBOL=256,wo.staticInit();class _o{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 wo(e),this.inputCrc=new yo,this.window=new Uint8Array(2*bo.WSIZE),this.head=new Int16Array(bo.HASH_SIZE),this.prev=new Int16Array(bo.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=bo.MIN_MATCH-1;for(let e=0;e<bo.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<bo.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<bo.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<bo.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=bo.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*bo.WSIZE-bo.MIN_LOOKAHEAD&&this.slideWindow();let e=this.matchStart,s=this.matchLen;if(this.lookahead>=bo.MIN_MATCH){let e=this.insertString();0!=e&&this.strstart-e<=bo.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen==bo.MIN_MATCH&&this.strstart-this.matchStart>_o.TooFar&&(this.matchLen=bo.MIN_MATCH-1)}if(s>=bo.MIN_MATCH&&this.matchLen<=s){this.huffman.tallyDist(this.strstart-1-e,s),s-=2;do{this.strstart++,this.lookahead--,this.lookahead>=bo.MIN_MATCH&&this.insertString()}while(--s>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=bo.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(bo.MAX_MATCH,this.lookahead)-1,a=Math.max(s-bo.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,bo.MIN_MATCH-1),s+this.matchLen>i)return!1;let l=r[s+this.matchLen-1],c=r[s+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,s=this.strstart,r[t+this.matchLen]==c&&r[t+this.matchLen-1]==l&&r[t]==r[s]&&r[++t]==r[++s]){switch((i-s)%8){case 1:if(r[++s]==r[++t])break;break;case 2:if(r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 3:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 4:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 5:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 6:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 7:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break}if(r[s]==r[t])do{if(s==i){++s,++t;break}}while(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]);if(s-this.strstart>this.matchLen){if(this.matchStart=e,this.matchLen=s-this.strstart,this.matchLen>=h)break;l=r[s-1],c=r[s]}e=65535&n[e&bo.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=bo.MIN_MATCH}insertString(){let e,t=(this.insertHashIndex<<bo.HASH_SHIFT^this.window[this.strstart+(bo.MIN_MATCH-1)])&bo.HASH_MASK;return e=this.head[t],this.prev[this.strstart&bo.WMASK]=e,this.head[t]=this.strstart,this.insertHashIndex=t,65535&e}fillWindow(){if(this.strstart>=bo.WSIZE+bo.MAX_DIST&&this.slideWindow(),this.lookahead<bo.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*bo.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>=bo.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(bo.WSIZE,bo.WSIZE+bo.WSIZE),0),this.matchStart-=bo.WSIZE,this.strstart-=bo.WSIZE,this.blockStart-=bo.WSIZE;for(let e=0;e<bo.HASH_SIZE;++e){let t=65535&this.head[e];this.head[e]=t>=bo.WSIZE?t-bo.WSIZE:0}for(let e=0;e<bo.WSIZE;e++){let t=65535&this.prev[e];this.prev[e]=t>=bo.WSIZE?t-bo.WSIZE:0}}}_o.TooFar=4096;class Bo{constructor(e){this._start=0,this._end=0,this._bits=0,this.bitCount=0,this._buffer=new Uint8Array(e)}get isFlushed(){return 0===this._end}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 To{constructor(){this._state=0,this._pending=new Bo(bo.PENDING_BUF_SIZE),this._engine=new _o(this._pending),this.reset()}get inputCrc(){return this._engine.inputCrc.value}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state==To.FinishedState&&this._pending.isFlushed}reset(){this._state=To.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==To.FinishedState)break;if(!this._engine.deflate(0!=(this._state&To.IsFlushing),0!=(this._state&To.IsFinishing)))switch(this._state){case To.BusyState:return i-s;case To.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=To.BusyState;break;case To.FinishingState:this._pending.alignToByte(),this._state=To.FinishedState}}return i-s}finish(){this._state|=To.IsFlushing|To.IsFinishing}}To.IsFlushing=4,To.IsFinishing=8,To.BusyState=16,To.FlushingState=20,To.FinishingState=28,To.FinishedState=30;class ko{constructor(e,t,s,i,a){this.entry=e,this.crc32=t,this.localHeaderOffset=s,this.compressionMode=i,this.compressedSize=a}}class vo{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new To,this._data=e}writeEntry(e){const t=vt.CompressionMethodDeflate,s=$e.empty(),i=this.compress(s,e.data,t),a=s.toArray(),r=new ko(e,i,this._data.bytesWritten,t,s.length);this._centralDirectoryHeaders.push(r),Ke.writeInt32LE(this._data,vt.LocalFileHeaderSignature),Ke.writeUInt16LE(this._data,10),Ke.writeUInt16LE(this._data,2048),Ke.writeUInt16LE(this._data,t),Ke.writeInt16LE(this._data,0),Ke.writeInt16LE(this._data,0),Ke.writeInt32LE(this._data,i),Ke.writeInt32LE(this._data,a.length),Ke.writeInt32LE(this._data,e.data.length),Ke.writeInt16LE(this._data,e.fullName.length),Ke.writeInt16LE(this._data,0);const n=Ke.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,s){if(s!=vt.CompressionMethodDeflate){const s=new yo;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){Ke.writeInt32LE(this._data,vt.EndOfCentralDirSignature),Ke.writeInt16LE(this._data,0),Ke.writeInt16LE(this._data,0),Ke.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Ke.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Ke.writeInt32LE(this._data,t-e),Ke.writeInt32LE(this._data,e),Ke.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){Ke.writeInt32LE(this._data,vt.CentralFileHeaderSignature),Ke.writeUInt16LE(this._data,10),Ke.writeUInt16LE(this._data,10),Ke.writeUInt16LE(this._data,2048),Ke.writeUInt16LE(this._data,e.compressionMode),Ke.writeInt16LE(this._data,0),Ke.writeInt16LE(this._data,0),Ke.writeInt32LE(this._data,e.crc32),Ke.writeInt32LE(this._data,e.compressedSize),Ke.writeInt32LE(this._data,e.entry.data.length),Ke.writeInt16LE(this._data,e.entry.fullName.length),Ke.writeInt16LE(this._data,0),Ke.writeInt16LE(this._data,0),Ke.writeInt16LE(this._data,0),Ke.writeInt16LE(this._data,0),Ke.writeInt32LE(this._data,0),Ke.writeInt32LE(this._data,e.localHeaderOffset);const t=Ke.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}var xo=Object.freeze({__proto__:null,ScoreExporter:go,Gp7Exporter:class extends go{get name(){return"Guitar Pro 7"}constructor(){super()}writeScore(e){Be.debug(this.name,"Writing data entries");const t=(new mo).writeXml(e),s=rt.writeForScore(e),i=yt.writeForScore(e);Be.debug(this.name,"Writing ZIP entries");let a=new vo(this.data);a.writeEntry(new vt("VERSION",Ke.stringToBytes("7.0"))),a.writeEntry(new vt("Content/",new Uint8Array(0))),a.writeEntry(new vt("Content/BinaryStylesheet",s)),a.writeEntry(new vt("Content/PartConfiguration",i)),a.writeEntry(new vt("Content/score.gpif",Ke.stringToBytes(t))),a.end()}}}),No=Object.freeze({__proto__:null,BeatTickLookup:_i,MasterBarTickLookup:Ti,MidiTickLookup:vi,MidiTickLookupFindBeatResult:ki,MidiFile:Ss,get ControllerType(){return te},MetaDataEvent:ws,MetaEvent:Dt,get MetaEventType(){return U},MetaNumberEvent:_s,MidiEvent:It,get MidiEventType(){return z},Midi20PerNotePitchBendEvent:Ws,SystemCommonEvent:Rt,get SystemCommonType(){return X},SystemExclusiveEvent:At,MidiFileGenerator:Pi,AlphaSynthMidiFileHandler:wi}),Po=Object.freeze({__proto__:null,get AccentuationType(){return i},get AccidentalType(){return re},get AutomationType(){return a},Automation:fe,Bar:me,Beat:De,BendPoint:be,get BendStyle(){return h},get BendType(){return l},get BrushType(){return c},Chord:Re,get Clef(){return r},Color:Ue,get CrescendoType(){return d},get Duration(){return u},get DynamicValue(){return p},get FermataType(){return O},Fermata:nt,get Fingers(){return f},get FontStyle(){return $},Font:vs,get GraceType(){return g},get HarmonicType(){return m},InstrumentArticulation:ve,JsonConverter:ni,get KeySignature(){return M},get KeySignatureType(){return I},Lyrics:Ae,MasterBar:Oe,get MusicFontSymbol(){return N},Note:Pe,get NoteAccidentalMode(){return y},get Ottavia(){return n},get PickStroke(){return x},PlaybackInformation:Xe,RenderStylesheet:Ge,RepeatGroup:Ve,Score:He,Section:We,get SimileMark(){return o},get SlideInType(){return b},get SlideOutType(){return S},Staff:qe,Track:Je,get TripletFeel(){return D},Tuning:Ye,TupletGroup:Ee,get VibratoType(){return w},Voice:Qe,get WhammyType(){return C}}),Eo=Object.freeze({__proto__:null,RenderFinishedEventArgs:ci,ScoreRenderer:yi,BarBounds:di,BeatBounds:ui,Bounds:at,BoundsLookup:mi,MasterBarBounds:pi,NoteBounds:gi,StaveGroupBounds:fi}),Co=Object.freeze({__proto__:null,AlphaSynth:bs,PlaybackRange:Ei,get PlayerState(){return q},PlayerStateChangedEventArgs:zt,PositionChangedEventArgs:Ut,AlphaSynthWebWorkerApi:qi});export{Zi as AlphaTabApi,pe as AlphaTabError,s as AlphaTabErrorType,lo as CoreSettings,Ns as DisplaySettings,Oi as FileLoadError,B as FingeringMode,ze as FormatError,Ps as ImporterSettings,e as LayoutMode,v as LogLevel,Be as Logger,T as NotationMode,Se as NotationSettings,Fs as PlayerSettings,Yi as ProgressEventArgs,xs as RenderingResources,Ri as ResizeEventArgs,ee as ScrollMode,Hs as Settings,t as StaveProfile,_ as TabRhythmMode,Es as VibratoPlaybackSettings,xo as exporter,po as importer,co as meta,No as midi,Po as model,Eo as rendering,Co as synth};
17
+ var e,t,s,i,a,r,n,o,h,l,c,d,u,p,g,f,m,y,b,S,w,_,B,T,k,v,x,N,P,E,C,F,L,M,I,D,R,A,O,G,V,H,W,z,U,X,Y,q,J,Q,j,K,$,Z,ee,te,se,ie,ae,re,ne,oe,he,le,ce;!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 de{static getValue(e){return de._values||(de._values=new Map),e=e.toLowerCase().split(" ").join(""),de._values.has(e)?de._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}}de._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 ue{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 pe extends Error{constructor(e,t="",s){super(null!=t?t:""),this.type=e,this.inner=null!=s?s:null,Object.setPrototypeOf(this,pe.prototype)}}class ge extends pe{constructor(e=null,t=null){super(s.Format,null!=e?e:"Unsupported format"),this.inner=t,Object.setPrototypeOf(this,ge.prototype)}}!function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy"}(i||(i={})),function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(a||(a={}));class fe{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 fe;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 fe;return i.type=a.Instrument,i.isLinear=e,i.ratioPosition=t,i.value=s,i}}!function(e){e[e.Neutral=0]="Neutral",e[e.C3=1]="C3",e[e.C4=2]="C4",e[e.F4=3]="F4",e[e.G2=4]="G2"}(r||(r={})),function(e){e[e._15ma=0]="_15ma",e[e._8va=1]="_8va",e[e.Regular=2]="Regular",e[e._8vb=3]="_8vb",e[e._15mb=4]="_15mb"}(n||(n={})),function(e){e[e.None=0]="None",e[e.Simple=1]="Simple",e[e.FirstOfDouble=2]="FirstOfDouble",e[e.SecondOfDouble=3]="SecondOfDouble"}(o||(o={}));class me{constructor(){this.id=me._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}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){this.isMultiVoice=!1;for(let s=0,i=this.voices.length;s<i;s++){let i=this.voices[s];i.finish(e,t),s>0&&!i.isEmpty&&(this.isMultiVoice=!0)}}calculateDuration(){let e=0;for(let t of this.voices){let s=t.calculateDuration();s>e&&(e=s)}return e}}me._globalBarId=0;class ye{static ticksToMillis(e,t){return e*(6e4/(t*ye.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*ye.QuarterTime))|0}static toTicks(e){return ye.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),ye.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 ye.MinVelocity+e*ye.VelocityIncrement}}ye.QuarterTime=960,ye.MinVelocity=15,ye.VelocityIncrement=16;class be{constructor(e=0,t=0){this.offset=e,this.value=t}}be.MaxPosition=60,be.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(h||(h={})),function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Bend=2]="Bend",e[e.Release=3]="Release",e[e.BendRelease=4]="BendRelease",e[e.Hold=5]="Hold",e[e.Prebend=6]="Prebend",e[e.PrebendBend=7]="PrebendBend",e[e.PrebendRelease=8]="PrebendRelease"}(l||(l={})),function(e){e[e.None=0]="None",e[e.BrushUp=1]="BrushUp",e[e.BrushDown=2]="BrushDown",e[e.ArpeggioUp=3]="ArpeggioUp",e[e.ArpeggioDown=4]="ArpeggioDown"}(c||(c={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(d||(d={})),function(e){e[e.QuadrupleWhole=-4]="QuadrupleWhole",e[e.DoubleWhole=-2]="DoubleWhole",e[e.Whole=1]="Whole",e[e.Half=2]="Half",e[e.Quarter=4]="Quarter",e[e.Eighth=8]="Eighth",e[e.Sixteenth=16]="Sixteenth",e[e.ThirtySecond=32]="ThirtySecond",e[e.SixtyFourth=64]="SixtyFourth",e[e.OneHundredTwentyEighth=128]="OneHundredTwentyEighth",e[e.TwoHundredFiftySixth=256]="TwoHundredFiftySixth"}(u||(u={})),function(e){e[e.PPP=0]="PPP",e[e.PP=1]="PP",e[e.P=2]="P",e[e.MP=3]="MP",e[e.MF=4]="MF",e[e.F=5]="F",e[e.FF=6]="FF",e[e.FFF=7]="FFF"}(p||(p={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(g||(g={})),function(e){e[e.Unknown=-2]="Unknown",e[e.NoOrDead=-1]="NoOrDead",e[e.Thumb=0]="Thumb",e[e.IndexFinger=1]="IndexFinger",e[e.MiddleFinger=2]="MiddleFinger",e[e.AnnularFinger=3]="AnnularFinger",e[e.LittleFinger=4]="LittleFinger"}(f||(f={})),function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Artificial=2]="Artificial",e[e.Pinch=3]="Pinch",e[e.Tap=4]="Tap",e[e.Semi=5]="Semi",e[e.Feedback=6]="Feedback"}(m||(m={})),function(e){e[e.Default=0]="Default",e[e.ForceNone=1]="ForceNone",e[e.ForceNatural=2]="ForceNatural",e[e.ForceSharp=3]="ForceSharp",e[e.ForceDoubleSharp=4]="ForceDoubleSharp",e[e.ForceFlat=5]="ForceFlat",e[e.ForceDoubleFlat=6]="ForceDoubleFlat"}(y||(y={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(b||(b={})),function(e){e[e.None=0]="None",e[e.Shift=1]="Shift",e[e.Legato=2]="Legato",e[e.OutUp=3]="OutUp",e[e.OutDown=4]="OutDown",e[e.PickSlideDown=5]="PickSlideDown",e[e.PickSlideUp=6]="PickSlideUp"}(S||(S={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(w||(w={})),function(e){e[e.Hidden=0]="Hidden",e[e.ShowWithBeams=1]="ShowWithBeams",e[e.ShowWithBars=2]="ShowWithBars"}(_||(_={})),function(e){e[e.ScoreDefault=0]="ScoreDefault",e[e.ScoreForcePiano=1]="ScoreForcePiano",e[e.SingleNoteEffectBand=2]="SingleNoteEffectBand",e[e.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano"}(B||(B={})),function(e){e[e.GuitarPro=0]="GuitarPro",e[e.SongBook=1]="SongBook"}(T||(T={})),function(e){e[e.ScoreTitle=0]="ScoreTitle",e[e.ScoreSubTitle=1]="ScoreSubTitle",e[e.ScoreArtist=2]="ScoreArtist",e[e.ScoreAlbum=3]="ScoreAlbum",e[e.ScoreWords=4]="ScoreWords",e[e.ScoreMusic=5]="ScoreMusic",e[e.ScoreWordsAndMusic=6]="ScoreWordsAndMusic",e[e.ScoreCopyright=7]="ScoreCopyright",e[e.GuitarTuning=8]="GuitarTuning",e[e.TrackNames=9]="TrackNames",e[e.ChordDiagrams=10]="ChordDiagrams",e[e.ParenthesisOnTiedBends=11]="ParenthesisOnTiedBends",e[e.TabNotesOnTiedBends=12]="TabNotesOnTiedBends",e[e.ZerosOnDiveWhammys=13]="ZerosOnDiveWhammys",e[e.EffectAlternateEndings=14]="EffectAlternateEndings",e[e.EffectCapo=15]="EffectCapo",e[e.EffectChordNames=16]="EffectChordNames",e[e.EffectCrescendo=17]="EffectCrescendo",e[e.EffectDynamics=18]="EffectDynamics",e[e.EffectFadeIn=19]="EffectFadeIn",e[e.EffectFermata=20]="EffectFermata",e[e.EffectFingering=21]="EffectFingering",e[e.EffectHarmonics=22]="EffectHarmonics",e[e.EffectLetRing=23]="EffectLetRing",e[e.EffectLyrics=24]="EffectLyrics",e[e.EffectMarker=25]="EffectMarker",e[e.EffectOttavia=26]="EffectOttavia",e[e.EffectPalmMute=27]="EffectPalmMute",e[e.EffectPickSlide=28]="EffectPickSlide",e[e.EffectPickStroke=29]="EffectPickStroke",e[e.EffectSlightBeatVibrato=30]="EffectSlightBeatVibrato",e[e.EffectSlightNoteVibrato=31]="EffectSlightNoteVibrato",e[e.EffectTap=32]="EffectTap",e[e.EffectTempo=33]="EffectTempo",e[e.EffectText=34]="EffectText",e[e.EffectTrill=35]="EffectTrill",e[e.EffectTripletFeel=36]="EffectTripletFeel",e[e.EffectWhammyBar=37]="EffectWhammyBar",e[e.EffectWideBeatVibrato=38]="EffectWideBeatVibrato",e[e.EffectWideNoteVibrato=39]="EffectWideNoteVibrato",e[e.EffectLeftHandTap=40]="EffectLeftHandTap"}(k||(k={}));class Se{constructor(){this.notationMode=T.GuitarPro,this.fingeringMode=B.ScoreDefault,this.elements=new Map,this.rhythmMode=_.Hidden,this.rhythmHeight=15,this.transpositionPitches=[],this.displayTranspositionPitches=[],this.smallGraceTabNotes=!0,this.extendBendArrowsOnTiedNotes=!0,this.extendLineEffectsToBeatEnd=!1,this.slurHeight=5}isNotationElementVisible(e){return this.elements.has(e)?this.elements.get(e):!Se.defaultElements.has(e)||Se.defaultElements.get(e)}}Se.defaultElements=new Map([[k.ZerosOnDiveWhammys,!1]]);class we{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}!function(e){e[e.None=0]="None",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warning=3]="Warning",e[e.Error=4]="Error"}(v||(v={}));class _e{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...s){console.debug(_e.format(e,t),...s)}warning(e,t,...s){console.warn(_e.format(e,t),...s)}info(e,t,...s){console.info(_e.format(e,t),...s)}error(e,t,...s){console.error(_e.format(e,t),...s)}}_e.logLevel=v.Info;class Be{static shouldLog(e){return Be.logLevel!==v.None&&e>=Be.logLevel}static debug(e,t,...s){Be.shouldLog(v.Debug)&&Be.log.debug(e,t,...s)}static warning(e,t,...s){Be.shouldLog(v.Warning)&&Be.log.warning(e,t,...s)}static info(e,t,...s){Be.shouldLog(v.Info)&&Be.log.info(e,t,...s)}static error(e,t,...s){Be.shouldLog(v.Error)&&Be.log.error(e,t,...s)}}Be.logLevel=v.Info,Be.log=new _e;class Te{constructor(){this.note=null,this.noteValue=0,this.octave=0}get realValue(){return 12*this.octave+this.noteValue}}class ke{static getIndex(e){return e<0?0:0|Math.log2(e)}static keySignatureIsFlat(e){return e<0}static keySignatureIsNatural(e){return 0===e}static keySignatureIsSharp(e){return e>0}static applyPitchOffsets(e,t){for(let s=0;s<t.tracks.length;s++){if(s<e.notation.displayTranspositionPitches.length)for(let i of t.tracks[s].staves)i.displayTranspositionPitch=-e.notation.displayTranspositionPitches[s];if(s<e.notation.transpositionPitches.length)for(let i of t.tracks[s].staves)i.transpositionPitch=-e.notation.transpositionPitches[s]}}static fingerToString(e,t,s,i){if(e.notation.fingeringMode===B.ScoreForcePiano||e.notation.fingeringMode===B.SingleNoteEffectBandForcePiano||de.isPiano(t.voice.bar.staff.track.playbackInfo.program))switch(s){case f.Unknown:case f.NoOrDead:return null;case f.Thumb:return"1";case f.IndexFinger:return"2";case f.MiddleFinger:return"3";case f.AnnularFinger:return"4";case f.LittleFinger:return"5";default:return null}if(i)switch(s){case f.Unknown:case f.NoOrDead:return"0";case f.Thumb:return"T";case f.IndexFinger:return"1";case f.MiddleFinger:return"2";case f.AnnularFinger:return"3";case f.LittleFinger:return"4";default:return null}switch(s){case f.Unknown:case f.NoOrDead:return null;case f.Thumb:return"p";case f.IndexFinger:return"i";case f.MiddleFinger:return"m";case f.AnnularFinger:return"a";case f.LittleFinger:return"c";default:return null}}static isTuning(e){return!!ke.parseTuning(e)}static parseTuning(e){let t="",s="";for(let i=0;i<e.length;i++){let a=e.charCodeAt(i);if(a>=48&&a<=57){if(!t)return null;s+=String.fromCharCode(a)}else{if(!(a>=65&&a<=90||a>=97&&a<=122||35===a))return null;t+=String.fromCharCode(a)}}if(!s||!t)return null;let i=new Te;return i.octave=parseInt(s)+1,i.note=t.toLowerCase(),i.noteValue=ke.getToneForText(i.note),i}static getTuningForText(e){let t=ke.parseTuning(e);return t?t.realValue:-1}static getToneForText(e){let t=0;switch(e.toLowerCase()){case"c":t=0;break;case"c#":case"db":t=1;break;case"d":t=2;break;case"d#":case"eb":t=3;break;case"e":t=4;break;case"f":t=5;break;case"f#":case"gb":t=6;break;case"g":t=7;break;case"g#":case"ab":t=8;break;case"a":t=9;break;case"a#":case"bb":t=10;break;case"b":t=11;break;default:return 0}return t}static newGuid(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)}static isAlmostEqualTo(e,t){return Math.abs(e-t)<1e-5}static toHexString(e,t=0){let s="";do{s=String.fromCharCode("0123456789ABCDEF".charCodeAt(15&e))+s,e>>=4}while(e>0);for(;s.length<t;)s="0"+s;return s}}!function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(x||(x={})),function(e){e[e.None=-1]="None",e[e.GClef=57424]="GClef",e[e.CClef=57436]="CClef",e[e.FClef=57442]="FClef",e[e.UnpitchedPercussionClef1=57449]="UnpitchedPercussionClef1",e[e.SixStringTabClef=57453]="SixStringTabClef",e[e.FourStringTabClef=57454]="FourStringTabClef",e[e.TimeSig0=57472]="TimeSig0",e[e.TimeSig1=57473]="TimeSig1",e[e.TimeSig2=57474]="TimeSig2",e[e.TimeSig3=57475]="TimeSig3",e[e.TimeSig4=57476]="TimeSig4",e[e.TimeSig5=57477]="TimeSig5",e[e.TimeSig6=57478]="TimeSig6",e[e.TimeSig7=57479]="TimeSig7",e[e.TimeSig8=57480]="TimeSig8",e[e.TimeSig9=57481]="TimeSig9",e[e.TimeSigCommon=57482]="TimeSigCommon",e[e.TimeSigCutCommon=57483]="TimeSigCutCommon",e[e.NoteheadDoubleWholeSquare=57505]="NoteheadDoubleWholeSquare",e[e.NoteheadDoubleWhole=57504]="NoteheadDoubleWhole",e[e.NoteheadWhole=57506]="NoteheadWhole",e[e.NoteheadHalf=57507]="NoteheadHalf",e[e.NoteheadBlack=57508]="NoteheadBlack",e[e.NoteheadNull=57509]="NoteheadNull",e[e.NoteheadXOrnate=57514]="NoteheadXOrnate",e[e.NoteheadTriangleUpWhole=57531]="NoteheadTriangleUpWhole",e[e.NoteheadTriangleUpHalf=57532]="NoteheadTriangleUpHalf",e[e.NoteheadTriangleUpBlack=57534]="NoteheadTriangleUpBlack",e[e.NoteheadDiamondBlackWide=57564]="NoteheadDiamondBlackWide",e[e.NoteheadDiamondWhite=57565]="NoteheadDiamondWhite",e[e.NoteheadDiamondWhiteWide=57566]="NoteheadDiamondWhiteWide",e[e.NoteheadCircleX=57523]="NoteheadCircleX",e[e.NoteheadXWhole=57511]="NoteheadXWhole",e[e.NoteheadXHalf=57512]="NoteheadXHalf",e[e.NoteheadXBlack=57513]="NoteheadXBlack",e[e.NoteheadParenthesis=57550]="NoteheadParenthesis",e[e.NoteheadSlashedBlack2=57552]="NoteheadSlashedBlack2",e[e.NoteheadCircleSlash=57591]="NoteheadCircleSlash",e[e.NoteheadHeavyX=57592]="NoteheadHeavyX",e[e.NoteheadHeavyXHat=57593]="NoteheadHeavyXHat",e[e.NoteQuarterUp=57813]="NoteQuarterUp",e[e.NoteEighthUp=57815]="NoteEighthUp",e[e.Tremolo3=57890]="Tremolo3",e[e.Tremolo2=57889]="Tremolo2",e[e.Tremolo1=57888]="Tremolo1",e[e.FlagEighthUp=57920]="FlagEighthUp",e[e.FlagEighthDown=57921]="FlagEighthDown",e[e.FlagSixteenthUp=57922]="FlagSixteenthUp",e[e.FlagSixteenthDown=57923]="FlagSixteenthDown",e[e.FlagThirtySecondUp=57924]="FlagThirtySecondUp",e[e.FlagThirtySecondDown=57925]="FlagThirtySecondDown",e[e.FlagSixtyFourthUp=57926]="FlagSixtyFourthUp",e[e.FlagSixtyFourthDown=57927]="FlagSixtyFourthDown",e[e.FlagOneHundredTwentyEighthUp=57928]="FlagOneHundredTwentyEighthUp",e[e.FlagOneHundredTwentyEighthDown=57929]="FlagOneHundredTwentyEighthDown",e[e.FlagTwoHundredFiftySixthUp=57930]="FlagTwoHundredFiftySixthUp",e[e.FlagTwoHundredFiftySixthDown=57931]="FlagTwoHundredFiftySixthDown",e[e.AccidentalFlat=57952]="AccidentalFlat",e[e.AccidentalNatural=57953]="AccidentalNatural",e[e.AccidentalSharp=57954]="AccidentalSharp",e[e.AccidentalDoubleSharp=57955]="AccidentalDoubleSharp",e[e.AccidentalDoubleFlat=57956]="AccidentalDoubleFlat",e[e.AccidentalQuarterToneFlatArrowUp=57968]="AccidentalQuarterToneFlatArrowUp",e[e.AccidentalQuarterToneSharpArrowUp=57972]="AccidentalQuarterToneSharpArrowUp",e[e.AccidentalQuarterToneNaturalArrowUp=57970]="AccidentalQuarterToneNaturalArrowUp",e[e.ArticAccentAbove=58528]="ArticAccentAbove",e[e.ArticStaccatoAbove=58530]="ArticStaccatoAbove",e[e.ArticMarcatoAbove=58540]="ArticMarcatoAbove",e[e.FermataAbove=58560]="FermataAbove",e[e.FermataShortAbove=58564]="FermataShortAbove",e[e.FermataLongAbove=58566]="FermataLongAbove",e[e.RestLonga=58593]="RestLonga",e[e.RestDoubleWhole=58594]="RestDoubleWhole",e[e.RestWhole=58595]="RestWhole",e[e.RestHalf=58596]="RestHalf",e[e.RestQuarter=58597]="RestQuarter",e[e.RestEighth=58598]="RestEighth",e[e.RestSixteenth=58599]="RestSixteenth",e[e.RestThirtySecond=58600]="RestThirtySecond",e[e.RestSixtyFourth=58601]="RestSixtyFourth",e[e.RestOneHundredTwentyEighth=58602]="RestOneHundredTwentyEighth",e[e.RestTwoHundredFiftySixth=58603]="RestTwoHundredFiftySixth",e[e.Repeat1Bar=58624]="Repeat1Bar",e[e.Repeat2Bars=58625]="Repeat2Bars",e[e.Ottava=58640]="Ottava",e[e.OttavaAlta=58641]="OttavaAlta",e[e.OttavaBassaVb=58652]="OttavaBassaVb",e[e.Quindicesima=58644]="Quindicesima",e[e.QuindicesimaAlta=58645]="QuindicesimaAlta",e[e.DynamicPPP=58666]="DynamicPPP",e[e.DynamicPP=58667]="DynamicPP",e[e.DynamicPiano=58656]="DynamicPiano",e[e.DynamicMP=58668]="DynamicMP",e[e.DynamicMF=58669]="DynamicMF",e[e.DynamicForte=58658]="DynamicForte",e[e.DynamicFF=58671]="DynamicFF",e[e.DynamicFFF=58672]="DynamicFFF",e[e.OrnamentTrill=58726]="OrnamentTrill",e[e.StringsDownBow=58896]="StringsDownBow",e[e.StringsUpBow=58898]="StringsUpBow",e[e.PictEdgeOfCymbal=59177]="PictEdgeOfCymbal",e[e.GuitarString0=59443]="GuitarString0",e[e.GuitarString1=59444]="GuitarString1",e[e.GuitarString2=59445]="GuitarString2",e[e.GuitarString3=59446]="GuitarString3",e[e.GuitarString4=59447]="GuitarString4",e[e.GuitarString5=59448]="GuitarString5",e[e.GuitarString6=59449]="GuitarString6",e[e.GuitarString7=59450]="GuitarString7",e[e.GuitarString8=59451]="GuitarString8",e[e.GuitarString9=59452]="GuitarString9",e[e.GuitarGolpe=59458]="GuitarGolpe",e[e.FretboardX=59481]="FretboardX",e[e.FretboardO=59482]="FretboardO",e[e.WiggleTrill=60068]="WiggleTrill",e[e.WiggleVibratoMediumFast=60126]="WiggleVibratoMediumFast",e[e.OctaveBaselineM=60565]="OctaveBaselineM",e[e.OctaveBaselineB=60563]="OctaveBaselineB"}(N||(N={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(P||(P={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(E||(E={}));class ve{constructor(e="",t=0,s=0,i=N.None,a=N.None,r=N.None,n=N.None,o=E.Middle){this.elementType=e,this.outputMidiNumber=s,this.staffLine=t,this.noteHeadDefault=i,this.noteHeadHalf=a!==N.None?a:i,this.noteHeadWhole=r!==N.None?r:i,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case u.Whole:return this.noteHeadWhole;case u.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class xe{static articulationFromElementVariation(e,t){return e<xe.gp6ElementAndVariationToArticulation.length?(t>=xe.gp6ElementAndVariationToArticulation.length&&(t=0),xe.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]:xe.getArticulationByValue(t)}static getElementAndVariation(e){const t=xe.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<xe.gp6ElementAndVariationToArticulation.length;e++){const s=xe.gp6ElementAndVariationToArticulation[e];for(let i=0;i<s.length;i++){const a=xe.getArticulationByValue(s[i]);if((null==a?void 0:a.outputMidiNumber)===t.outputMidiNumber)return[e,i]}}return[-1,-1]}static getArticulationByValue(e){return xe.instrumentArticulations.has(e)?xe.instrumentArticulations.get(e):null}}xe.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]],xe.instrumentArticulations=new Map([[38,new ve("snare",3,38,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[37,new ve("snare",3,37,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[91,new ve("snare",3,38,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite)],[42,new ve("hiHat",-1,42,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[92,new ve("hiHat",-1,46,N.NoteheadCircleSlash,N.NoteheadCircleSlash,N.NoteheadCircleSlash)],[46,new ve("hiHat",-1,46,N.NoteheadCircleX,N.NoteheadCircleX,N.NoteheadCircleX)],[44,new ve("hiHat",9,44,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[35,new ve("kickDrum",8,35,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[36,new ve("kickDrum",7,36,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[50,new ve("tom",1,50,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[48,new ve("tom",2,48,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[47,new ve("tom",4,47,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[45,new ve("tom",5,45,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[43,new ve("tom",6,43,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[93,new ve("ride",0,51,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.PictEdgeOfCymbal,E.Bottom)],[51,new ve("ride",0,51,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[53,new ve("ride",0,53,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite)],[94,new ve("ride",0,51,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.ArticStaccatoAbove,E.Top)],[55,new ve("splash",-2,55,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[95,new ve("splash",-2,55,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.ArticStaccatoAbove,E.Bottom)],[52,new ve("china",-3,52,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat)],[96,new ve("china",-3,52,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat,N.NoteheadHeavyXHat)],[49,new ve("crash",-2,49,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX)],[97,new ve("crash",-2,49,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX,N.ArticStaccatoAbove,E.Bottom)],[57,new ve("crash",-1,57,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX)],[98,new ve("crash",-1,57,N.NoteheadHeavyX,N.NoteheadHeavyX,N.NoteheadHeavyX,N.ArticStaccatoAbove,E.Bottom)],[99,new ve("cowbell",1,56,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpHalf,N.NoteheadTriangleUpWhole)],[100,new ve("cowbell",1,56,N.NoteheadXBlack,N.NoteheadXHalf,N.NoteheadXWhole)],[56,new ve("cowbell",0,56,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpHalf,N.NoteheadTriangleUpWhole)],[101,new ve("cowbell",0,56,N.NoteheadXBlack,N.NoteheadXHalf,N.NoteheadXWhole)],[102,new ve("cowbell",-1,56,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpHalf,N.NoteheadTriangleUpWhole)],[103,new ve("cowbell",-1,56,N.NoteheadXBlack,N.NoteheadXHalf,N.NoteheadXWhole)],[77,new ve("woodblock",-9,77,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack)],[76,new ve("woodblock",-10,76,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack)],[60,new ve("bongo",-4,60,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[104,new ve("bongo",-5,60,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,E.Middle)],[105,new ve("bongo",-6,60,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[61,new ve("bongo",-7,61,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[106,new ve("bongo",-8,61,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,E.Middle)],[107,new ve("bongo",-16,61,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[66,new ve("timbale",10,66,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[65,new ve("timbale",9,65,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[68,new ve("agogo",12,68,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[67,new ve("agogo",11,67,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[64,new ve("conga",17,64,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[108,new ve("conga",16,64,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[109,new ve("conga",15,64,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,E.Middle)],[63,new ve("conga",14,63,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[110,new ve("conga",13,63,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[62,new ve("conga",19,62,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.NoteheadParenthesis,E.Middle)],[72,new ve("whistle",-11,72,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[71,new ve("whistle",-17,71,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[73,new ve("guiro",38,73,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[74,new ve("guiro",37,74,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[86,new ve("surdo",36,86,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[87,new ve("surdo",35,87,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadParenthesis,E.Middle)],[54,new ve("tambourine",3,54,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack)],[111,new ve("tambourine",2,54,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.StringsUpBow,E.Bottom)],[112,new ve("tambourine",1,54,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.NoteheadTriangleUpBlack,N.StringsDownBow,E.Bottom)],[113,new ve("tambourine",-7,54,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[79,new ve("cuica",30,79,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[78,new ve("cuica",29,78,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[58,new ve("vibraslap",28,58,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[81,new ve("triangle",27,81,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[80,new ve("triangle",26,80,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadParenthesis,E.Middle)],[114,new ve("grancassa",25,43,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[115,new ve("piatti",18,49,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[116,new ve("piatti",24,49,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[69,new ve("cabasa",23,69,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[117,new ve("cabasa",22,69,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,E.Bottom)],[85,new ve("castanets",21,85,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[75,new ve("claves",20,75,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[70,new ve("maraca",-12,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[118,new ve("maraca",-13,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,E.Bottom)],[119,new ve("maraca",-14,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[120,new ve("maraca",-15,70,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,E.Bottom)],[82,new ve("shaker",-23,54,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[122,new ve("shaker",-24,54,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,E.Bottom)],[84,new ve("bellTree",-18,53,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[123,new ve("bellTree",-19,53,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole,N.StringsUpBow,E.Bottom)],[83,new ve("jingleBell",-20,53,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[124,new ve("unpitched",-21,62,N.NoteheadNull,N.NoteheadNull,N.NoteheadNull,N.GuitarGolpe,E.Top)],[125,new ve("unpitched",-22,62,N.NoteheadNull,N.NoteheadNull,N.NoteheadNull,N.GuitarGolpe,E.Bottom)],[39,new ve("handClap",3,39,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[40,new ve("snare",3,40,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[31,new ve("snare",3,40,N.NoteheadSlashedBlack2,N.NoteheadSlashedBlack2,N.NoteheadSlashedBlack2)],[41,new ve("tom",5,41,N.NoteheadBlack,N.NoteheadHalf,N.NoteheadWhole)],[59,new ve("ride",2,59,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.PictEdgeOfCymbal,E.Bottom)],[126,new ve("ride",2,59,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[127,new ve("ride",2,59,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite,N.NoteheadDiamondWhite)],[29,new ve("ride",2,59,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack,N.ArticStaccatoAbove,E.Top)],[30,new ve("crash",-3,49,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[33,new ve("snare",3,37,N.NoteheadXBlack,N.NoteheadXBlack,N.NoteheadXBlack)],[34,new ve("snare",3,38,N.NoteheadBlack,N.NoteheadBlack,N.NoteheadBlack)]]);class Ne{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1}}class Pe{constructor(){this.id=Pe.GlobalNoteId++,this.index=0,this.accentuated=i.None,this.bendType=l.None,this.bendStyle=h.Default,this.bendOrigin=null,this.isContinuedBend=!1,this.bendPoints=null,this.maxBendPoint=null,this.fret=-1,this.string=-1,this.octave=-1,this.tone=-1,this.percussionArticulation=-1,this.isVisible=!0,this.isLeftHandTapped=!1,this.isHammerPullOrigin=!1,this.hammerPullOrigin=null,this.hammerPullDestination=null,this.isSlurDestination=!1,this.slurOrigin=null,this.slurDestination=null,this.harmonicType=m.None,this.harmonicValue=0,this.isGhost=!1,this.isLetRing=!1,this.letRingDestination=null,this.isPalmMute=!1,this.palmMuteDestination=null,this.isDead=!1,this.isStaccato=!1,this.slideInType=b.None,this.slideOutType=S.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=w.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=f.Unknown,this.rightHandFinger=f.Unknown,this.isFingering=!1,this.trillValue=-1,this.trillSpeed=u.ThirtySecond,this.durationPercent=1,this.accidentalMode=y.Default,this.dynamics=p.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this._noteIdBag=null}get hasBend(){return null!==this.bendPoints&&this.bendType!==l.None}get isStringed(){return this.string>=0}get isPiano(){return!this.isStringed&&this.octave>=0&&this.tone>=0}get isPercussion(){return!this.isStringed&&this.percussionArticulation>=0}get element(){return this.isPercussion?xe.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?xe.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==m.None}get isTieOrigin(){return null!==this.tieDestination}get trillFret(){return this.trillValue-this.stringTuning}get isTrill(){return this.trillValue>=0}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get stringTuning(){return this.beat.voice.bar.staff.capo+Pe.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(){let e=this.realValueWithoutHarmonic;return this.isStringed&&(this.harmonicType===m.Natural?e=this.harmonicPitch+this.stringTuning-this.beat.voice.bar.staff.transpositionPitch:e+=this.harmonicPitch),e}get realValueWithoutHarmonic(){return this.isPercussion?this.percussionArticulation:this.isStringed?this.fret+this.stringTuning-this.beat.voice.bar.staff.transpositionPitch:this.isPiano?12*this.octave+this.tone-this.beat.voice.bar.staff.transpositionPitch:0}get harmonicPitch(){if(this.harmonicType===m.None||!this.isStringed)return 0;let e=this.harmonicValue;return ke.isAlmostEqualTo(e,2.4)?36:ke.isAlmostEqualTo(e,2.7)?34:e<3?0:e<=3.5?31:e<=4?28:e<=5?24:e<=6?34:e<=7?19:e<=8.5?36:e<=9?28:e<=10?34:e<=11?0:e<=12?12:e<14?0:e<=15?34:e<=16?28:e<=17?36:e<=18?0:e<=19?19:e<=21?0:e<=22?36:e<=24?24:0}get initialBendValue(){return this.hasBend?Math.floor(this.bendPoints[0].value/2):this.bendOrigin?Math.floor(this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value/2):this.isTieDestination&&this.tieOrigin.bendOrigin?Math.floor(this.tieOrigin.bendOrigin.bendPoints[this.tieOrigin.bendOrigin.bendPoints.length-1].value/2):this.beat.hasWhammyBar?Math.floor(this.beat.whammyBarPoints[0].value/2):this.beat.isContinuedWhammy?Math.floor(this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value/2):0}get displayValue(){return this.displayValueWithoutBend+this.initialBendValue}get displayValueWithoutBend(){let e=this.realValue;switch(this.harmonicType!==m.Natural&&this.harmonicType!==m.None&&(e-=this.harmonicPitch),this.beat.ottava){case n._15ma:e-=24;break;case n._8va:e-=12;break;case n.Regular:break;case n._8vb:e+=12;break;case n._15mb:e+=24}switch(this.beat.voice.bar.clefOttava){case n._15ma:e-=24;break;case n._8va:e-=12;break;case n.Regular:break;case n._8vb:e+=12;break;case n._15mb:e+=24}return e-this.beat.voice.bar.staff.displayTranspositionPitch}get hasQuarterToneOffset(){return this.hasBend?this.bendPoints[0].value%2!=0:this.bendOrigin?this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value%2!=0:this.beat.hasWhammyBar?this.beat.whammyBarPoints[0].value%2!=0:!!this.beat.isContinuedWhammy&&this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value%2!=0}addBendPoint(e){let t=this.bendPoints;null===t&&(t=[],this.bendPoints=t),t.push(e),(!this.maxBendPoint||e.value>this.maxBendPoint.value)&&(this.maxBendPoint=e),this.bendType===l.None&&(this.bendType=l.Custom)}finish(e,t){let s=new we((()=>Pe.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=Pe.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case S.Shift:case S.Legato:this.slideTarget=s.value,this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=S.None}let a=null;this.isHammerPullOrigin&&this.hammerPullDestination?a=this.hammerPullDestination:this.slideOutType===S.Legato&&this.slideTarget&&(a=this.slideTarget),a&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===x.None?(this.effectSlurOrigin.effectSlurDestination=a,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=a,this.effectSlurDestination.effectSlurOrigin=this));const r=this.bendPoints;if(null!=r&&r.length>0&&this.bendType===l.Custom){let e=this.isTieDestination&&this.tieOrigin.hasBend;if(this.isContinuedBend=e,4===r.length){let t=r[0],s=r[1],i=r[2],a=r[3];s.value===i.value?a.value>t.value?s.value>a.value?this.bendType=l.BendRelease:!e&&t.value>0?(this.bendType=l.PrebendBend,r.splice(2,1),r.splice(1,1)):(this.bendType=l.Bend,r.splice(2,1),r.splice(1,1)):a.value<t.value?e?(this.bendType=l.Release,r.splice(2,1),r.splice(1,1)):(this.bendType=l.PrebendRelease,r.splice(2,1),r.splice(1,1)):s.value>t.value?this.bendType=l.BendRelease:t.value>0&&!e?(this.bendType=l.Prebend,r.splice(2,1),r.splice(1,1)):(this.bendType=l.Hold,r.splice(2,1),r.splice(1,1)):Be.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===r.length){let t=r[0],s=r[1];s.value>t.value?!e&&t.value>0?this.bendType=l.PrebendBend:this.bendType=l.Bend:s.value<t.value?this.bendType=e?l.Release:l.PrebendRelease:this.bendType=l.Hold}}else null!==r&&0!==r.length||(this.bendType=l.None);this.initialBendValue>0&&(this.accidentalMode=y.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+Pe.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+Pe.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-Pe.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){if(null!=this._noteIdBag){let t;e.has(Pe.NoteIdLookupKey)?t=e.get(Pe.NoteIdLookupKey):(t=new Map,e.set(Pe.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=Pe.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 Ne),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Ne),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Ne),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Ne),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Ne),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Ne),this._noteIdBag.hammerPullDestinationNoteId=t,!0}return!1}}Pe.GlobalNoteId=0,Pe.MaxOffsetForSameLineSearch=3,Pe.NoteIdLookupKey="NoteIdLookup";class Ee{constructor(e){this._isEqualLengthTuplet=!0,this.totalDuration=0,this.beats=[],this.isFull=!1,this.voice=e}check(e){if(0===this.beats.length)return this.beats.push(e),this.totalDuration+=e.playbackDuration,!0;if(e.graceType!==g.None)return!0;if(e.voice!==this.voice||this.isFull||e.tupletNumerator!==this.beats[0].tupletNumerator||e.tupletDenominator!==this.beats[0].tupletDenominator)return!1;if(e.playbackDuration!==this.beats[0].playbackDuration&&(this._isEqualLengthTuplet=!1),this.beats.push(e),this.totalDuration+=e.playbackDuration,this._isEqualLengthTuplet)this.beats.length===this.beats[0].tupletNumerator&&(this.isFull=!0);else{let e=this.beats[0].tupletNumerator/this.beats[0].tupletDenominator|0;for(let t of Ee.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}Ee.HalfTicks=1920,Ee.QuarterTicks=960,Ee.EighthTicks=480,Ee.SixteenthTicks=240,Ee.ThirtySecondTicks=120,Ee.SixtyFourthTicks=60,Ee.OneHundredTwentyEighthTicks=30,Ee.TwoHundredFiftySixthTicks=15,Ee.AllTicks=[Ee.HalfTicks,Ee.QuarterTicks,Ee.EighthTicks,Ee.SixteenthTicks,Ee.ThirtySecondTicks,Ee.SixtyFourthTicks,Ee.OneHundredTwentyEighthTicks,Ee.TwoHundredFiftySixthTicks],function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Dive=2]="Dive",e[e.Dip=3]="Dip",e[e.Hold=4]="Hold",e[e.Predive=5]="Predive",e[e.PrediveDive=6]="PrediveDive"}(C||(C={}));class Ce{static clone(e){const t=new be;return t.offset=e.offset,t.value=e.value,t}}class Fe{static clone(e){const t=new Pe;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(Ce.clone(s))}return t.fret=e.fret,t.string=e.string,t.octave=e.octave,t.tone=e.tone,t.percussionArticulation=e.percussionArticulation,t.isVisible=e.isVisible,t.isLeftHandTapped=e.isLeftHandTapped,t.isHammerPullOrigin=e.isHammerPullOrigin,t.isSlurDestination=e.isSlurDestination,t.harmonicType=e.harmonicType,t.harmonicValue=e.harmonicValue,t.isGhost=e.isGhost,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.isDead=e.isDead,t.isStaccato=e.isStaccato,t.slideInType=e.slideInType,t.slideOutType=e.slideOutType,t.vibrato=e.vibrato,t.isTieDestination=e.isTieDestination,t.leftHandFinger=e.leftHandFinger,t.rightHandFinger=e.rightHandFinger,t.isFingering=e.isFingering,t.trillValue=e.trillValue,t.trillSpeed=e.trillSpeed,t.durationPercent=e.durationPercent,t.accidentalMode=e.accidentalMode,t.dynamics=e.dynamics,t}}class Le{static clone(e){const t=new fe;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class Me{static clone(e){const t=new De;t.index=e.index,t.notes=[];for(const s of e.notes)t.addNote(Fe.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(Le.clone(s));if(t.dots=e.dots,t.fadeIn=e.fadeIn,t.lyrics=e.lyrics?e.lyrics.slice():null,t.hasRasgueado=e.hasRasgueado,t.pop=e.pop,t.slap=e.slap,t.tap=e.tap,t.text=e.text,t.brushType=e.brushType,t.brushDuration=e.brushDuration,t.tupletDenominator=e.tupletDenominator,t.tupletNumerator=e.tupletNumerator,t.isContinuedWhammy=e.isContinuedWhammy,t.whammyBarType=e.whammyBarType,e.whammyBarPoints){t.whammyBarPoints=[];for(const s of e.whammyBarPoints)t.addWhammyBarPoint(Ce.clone(s))}return t.vibrato=e.vibrato,t.chordId=e.chordId,t.graceType=e.graceType,t.pickStroke=e.pickStroke,t.tremoloSpeed=e.tremoloSpeed,t.crescendo=e.crescendo,t.displayStart=e.displayStart,t.playbackStart=e.playbackStart,t.displayDuration=e.displayDuration,t.playbackDuration=e.playbackDuration,t.dynamics=e.dynamics,t.invertBeamDirection=e.invertBeamDirection,t.preferredBeamDirection=e.preferredBeamDirection,t.isEffectSlurOrigin=e.isEffectSlurOrigin,t.beamingMode=e.beamingMode,t}}class Ie{constructor(){this.beats=[],this.id="empty",this.isComplete=!1}addBeat(e){e.graceIndex=this.beats.length,e.graceGroup=this,this.beats.push(e)}finish(){this.beats.length>0&&(this.id=this.beats[0].absoluteDisplayStart+"_"+this.beats[0].voice.index)}}!function(e){e[e.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext"}(F||(F={}));class De{constructor(){this.id=De._globalBeatId++,this.index=0,this.previousBeat=null,this.nextBeat=null,this.notes=[],this.noteStringLookup=new Map,this.noteValueLookup=new Map,this.isEmpty=!1,this.whammyStyle=h.Default,this.ottava=n.Regular,this.fermata=null,this.isLegatoOrigin=!1,this.minNote=null,this.maxNote=null,this.maxStringNote=null,this.minStringNote=null,this.duration=u.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fadeIn=!1,this.lyrics=null,this.hasRasgueado=!1,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.brushType=c.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=C.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=w.None,this.chordId=null,this.graceType=g.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=x.None,this.tremoloSpeed=null,this.crescendo=d.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.dynamics=p.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=F.Auto}get isLastOfVoice(){return this.index===this.voice.beats.length-1}get isLegatoDestination(){return!!this.previousBeat&&this.previousBeat.isLegatoOrigin}get isRest(){return this.isEmpty||0===this.notes.length}get isFullBarRest(){return this.isRest&&1===this.voice.beats.length&&this.duration===u.Whole}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==C.None}get hasChord(){return!!this.chordId}get chord(){return this.chordId?this.voice.bar.staff.getChord(this.chordId):null}get isTremolo(){return!!this.tremoloSpeed}get absoluteDisplayStart(){return this.voice.bar.masterBar.start+this.displayStart}get absolutePlaybackStart(){return this.voice.bar.masterBar.start+this.playbackStart}get isEffectSlurDestination(){return!!this.effectSlurOrigin}addWhammyBarPoint(e){let t=this.whammyBarPoints;null===t&&(t=[],this.whammyBarPoints=t),t.push(e),(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e),(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e),this.whammyBarType===C.None&&(this.whammyBarType=C.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)}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=ye.toTicks(this.duration);return 2===this.dots?e=ye.applyDot(e,!0):1===this.dots&&(e=ye.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=ye.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){let e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case g.BeforeBeat:case g.OnBeat:switch(this.duration){case u.Sixteenth:this.playbackDuration=ye.toTicks(u.SixtyFourth);break;case u.ThirtySecond:this.playbackDuration=ye.toTicks(u.OneHundredTwentyEighth);break;default:this.playbackDuration=ye.toTicks(u.ThirtySecond)}this.displayDuration=0;break;case g.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;let t=this.previousBeat;t&&t.graceType===g.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){let e=this.previousBeat,t=e?e.tupletGroup:null;(this.hasTuplet||this.graceType!==g.None&&t)&&(e&&t&&t.check(this)||(t=new Ee(this.voice),t.check(this)),this.tupletGroup=t)}finish(e,t){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(fe.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case g.OnBeat:case g.BeforeBeat:let e=this.graceGroup.beats.length;this.duration=1===e?u.Eighth:2===e?u.Sixteenth:u.ThirtySecond}let s=e?e.notation.notationMode:T.GuitarPro,i="grad"===this.text||"grad."===this.text;i&&s===T.SongBook&&(this.text="");let r=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let n=0,o=!1;for(let a=0,c=this.notes.length;a<c;a++){let c=this.notes[a];if(c.dynamics=this.dynamics,c.finish(e,t),c.isLetRing&&(this.isLetRing=!0),c.isPalmMute&&(this.isPalmMute=!0),s===T.SongBook&&c.hasBend&&this.graceType!==g.BendGrace){if(!c.isTieOrigin)switch(c.bendType){case l.Bend:case l.PrebendRelease:case l.PrebendBend:r=!0}i||c.bendStyle===h.Gradual?(i=!0,c.bendStyle=h.Gradual,r=!1):c.bendStyle=h.Fast}c.isVisible&&(n++,(!this.minNote||c.realValue<this.minNote.realValue)&&(this.minNote=c),(!this.maxNote||c.realValue>this.maxNote.realValue)&&(this.maxNote=c),(!this.minStringNote||c.string<this.minStringNote.string)&&(this.minStringNote=c),(!this.maxStringNote||c.string>this.maxStringNote.string)&&(this.maxStringNote=c),c.hasEffectSlur&&(o=!0))}if(o&&(this.effectSlurOrigin?(this.effectSlurOrigin.effectSlurDestination=this.nextBeat,this.effectSlurOrigin.effectSlurDestination&&(this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin),this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=this.nextBeat,this.effectSlurDestination&&(this.effectSlurDestination.effectSlurOrigin=this))),this.notes.length>0&&0===n&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&e&&e.notation.notationMode===T.GuitarPro&&(this.previousBeat.isLetRing&&(this.isLetRing=!0),this.previousBeat.isPalmMute&&(this.isPalmMute=!0));else{let e=this.previousBeat;for(;e&&e.isRest;)this.isLetRing||(e.isLetRing=!1),this.isPalmMute||(e.isPalmMute=!1),e=e.previousBeat}const c=this.whammyBarPoints;if(null!==c&&c.length>0&&this.whammyBarType===C.Custom){s===T.SongBook&&(this.whammyStyle=i?h.Gradual:h.Fast);let e=!!this.previousBeat&&this.previousBeat.hasWhammyBar;if(this.isContinuedWhammy=e,4===c.length){let t=c[0],i=c[1],a=c[2],r=c[3];i.value===a.value?t.value<i.value&&i.value<r.value||t.value>i.value&&i.value>r.value?(0===t.value||e?this.whammyBarType=C.Dive:this.whammyBarType=C.PrediveDive,c.splice(2,1),c.splice(1,1)):t.value>i.value&&i.value<r.value||t.value<i.value&&i.value>r.value?(this.whammyBarType=C.Dip,i.offset!==a.offset&&s!==T.SongBook||c.splice(2,1)):t.value===i.value&&i.value===r.value?(0===t.value||e?this.whammyBarType=C.Hold:this.whammyBarType=C.Predive,c.splice(2,1),c.splice(1,1)):Be.warning("Model","Unsupported whammy type detected, fallback to custom",null):Be.warning("Model","Unsupported whammy type detected, fallback to custom",null)}}if(this.updateDurations(),r){let e=Me.clone(this);e.id=De._globalBeatId++,e.pickStroke=x.None;for(let t=0,s=e.notes.length;t<s;t++){let s=e.notes[t],i=this.notes[t];if(s.bendType=l.None,s.maxBendPoint=null,s.bendPoints=null,s.bendStyle=h.Default,s.id=Pe.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=Pe.findTieOrigin(i);if(e&&e.hasBend){s.bendType=l.Hold;let e=i.bendPoints[i.bendPoints.length-1];s.addBendPoint(new be(0,e.value)),s.addBendPoint(new be(be.MaxPosition,e.value))}}s.isTieDestination=!0}this.graceType=g.BendGrace,this.graceGroup=new Ie,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new Ie,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){for(const t of this.notes)this.noteValueLookup.set(t.realValue,t),t.chain(e)}}De._globalBeatId=0;class Re{constructor(){this.name="",this.firstFret=1,this.strings=[],this.barreFrets=[],this.showName=!0,this.showDiagram=!0,this.showFingering=!0}}!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"}(L||(L={}));class Ae{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=L.Begin,r=L.Begin,n=!1,o=0;for(;t<e.length;){let s=e.charCodeAt(t);switch(a){case L.IgnoreSpaces:switch(s){case Ae.CharCodeLF:case Ae.CharCodeCR:case Ae.CharCodeTab:break;case Ae.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case L.Begin:switch(s){case Ae.CharCodeBrackedOpen:a=L.Comment;break;default:o=t,a=L.Text;continue}break;case L.Comment:switch(s){case Ae.CharCodeBrackedClose:a=L.Begin}break;case L.Text:switch(s){case Ae.CharCodeDash:a=L.Dash;break;case Ae.CharCodeCR:case Ae.CharCodeLF:case Ae.CharCodeSpace:let s=e.substr(o,t-o);this.addChunk(s,i),a=L.IgnoreSpaces,r=L.Begin}break;case L.Dash:switch(s){case Ae.CharCodeDash:break;default:let s=e.substr(o,t-o);this.addChunk(s,i),n=!0,a=L.IgnoreSpaces,r=L.Begin;continue}}t+=1}a===L.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}}Ae.CharCodeLF=10,Ae.CharCodeTab=9,Ae.CharCodeCR=13,Ae.CharCodeSpace=32,Ae.CharCodeBrackedClose=93,Ae.CharCodeBrackedOpen=91,Ae.CharCodeDash=45,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"}(M||(M={})),function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(I||(I={})),function(e){e[e.NoTripletFeel=0]="NoTripletFeel",e[e.Triplet16th=1]="Triplet16th",e[e.Triplet8th=2]="Triplet8th",e[e.Dotted16th=3]="Dotted16th",e[e.Dotted8th=4]="Dotted8th",e[e.Scottish16th=5]="Scottish16th",e[e.Scottish8th=6]="Scottish8th"}(D||(D={}));class Oe{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=M.C,this.keySignatureType=I.Major,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.tripletFeel=D.NoTripletFeel,this.section=null,this.tempoAutomation=null,this.fermata=null,this.start=0,this.isAnacrusis=!1}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}calculateDuration(e=!0){if(this.isAnacrusis&&e){let e=0;for(let t of this.score.tracks)for(let s of t.staves){let t=this.index<s.bars.length?s.bars[this.index].calculateDuration():0;t>e&&(e=t)}return e}return this.timeSignatureNumerator*ye.valueToTicks(this.timeSignatureDenominator)}addFermata(e,t){let s=this.fermata;null===s&&(s=new Map,this.fermata=s),s.set(e,t)}getFermata(e){const t=this.fermata;return null===t?null:t.has(e.playbackStart)?t.get(e.playbackStart):null}}Oe.MaxAlternateEndings=8;class Ge{constructor(){this.hideDynamics=!1}}class Ve{constructor(){this.masterBars=[],this.openings=[],this.closings=[],this.isOpened=!1,this.isClosed=!1}addMasterBar(e){0===this.openings.length&&this.openings.push(e),this.masterBars.push(e),e.repeatGroup=this,e.isRepeatEnd?(this.closings.push(e),this.isClosed=!0,this.isOpened||(this.masterBars[0].isRepeatStart=!0,this.isOpened=!0)):this.isClosed&&(this.isClosed=!1,this.openings.push(e))}}class He{constructor(){this._currentRepeatGroup=new Ve,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.stylesheet=new Ge}rebuildRepeatGroups(){let e=new Ve;for(let t of this.masterBars)(t.isRepeatStart||this._currentRepeatGroup.isClosed&&t.alternateEndings<=0)&&(e=new Ve),e.addMasterBar(t)}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())),(e.isRepeatStart||this._currentRepeatGroup.isClosed&&e.alternateEndings<=0)&&(this._currentRepeatGroup=new Ve),this._currentRepeatGroup.addMasterBar(e),this.masterBars.push(e)}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 We{constructor(){this.marker="",this.text=""}}class ze extends pe{constructor(e){super(s.Format,e),Object.setPrototypeOf(this,ze.prototype)}}class Ue{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="#"+ke.toHexString(this.r,2)+ke.toHexString(this.g,2)+ke.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 Ue(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){switch(typeof e){case"number":{const t=new Ue(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 Ue(17*parseInt(t.substring(1,1),16),17*parseInt(t.substring(2,1),16),17*parseInt(t.substring(3,1),16));if(5===t.length)return new Ue(17*parseInt(t.substring(1,1),16),17*parseInt(t.substring(2,1),16),17*parseInt(t.substring(3,1),16),17*parseInt(t.substring(4,1),16));if(7===t.length)return new Ue(parseInt(t.substring(1,2),16),parseInt(t.substring(3,2),16),parseInt(t.substring(5,2),16));if(9===t.length)return new Ue(parseInt(t.substring(1,2),16),parseInt(t.substring(3,2),16),parseInt(t.substring(5,2),16),parseInt(t.substring(7,2),16))}else if(t.startsWith("rgba")||t.startsWith("rgb")){const e=t.indexOf("("),s=t.lastIndexOf(")");if(-1===e||-1===s)throw new ze("No values specified for rgb/rgba function");const i=t.substring(e+1,s).split(",");if(3===i.length)return new Ue(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]));if(4===i.length)return new Ue(parseInt(i[0]),parseInt(i[1]),parseInt(i[2]),255*parseFloat(i[3]))}return null}}throw new ze("Unsupported format for color")}static toJson(e){return e.raw}}Ue.BlackRgb="#000000";class Xe{constructor(){this.volume=15,this.balance=8,this.port=1,this.program=0,this.primaryChannel=0,this.secondaryChannel=0,this.isMute=!1,this.isSolo=!1}}class Ye{constructor(e="",t=null,s=!1){this.isStandard=s,this.name=e,this.tunings=null!=t?t:[]}static getTextForTuning(e,t){let s=Ye.getTextPartsForTuning(e);return t?s.join(""):s[0]}static getTextPartsForTuning(e,t=-1){return[["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"][e%12],((e/12|0)+t).toString()]}static getDefaultTuningFor(e){return Ye._defaultTunings.has(e)?Ye._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return Ye._sevenStrings;case 6:return Ye._sixStrings;case 5:return Ye._fiveStrings;case 4:return Ye._fourStrings}return[]}static initialize(){Ye._defaultTunings.set(7,new Ye("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),Ye._sevenStrings.push(Ye._defaultTunings.get(7)),Ye._defaultTunings.set(6,new Ye("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),Ye._sixStrings.push(Ye._defaultTunings.get(6)),Ye._sixStrings.push(new Ye("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),Ye._sixStrings.push(new Ye("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),Ye._sixStrings.push(new Ye("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),Ye._sixStrings.push(new Ye("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),Ye._sixStrings.push(new Ye("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),Ye._sixStrings.push(new Ye("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),Ye._defaultTunings.set(5,new Ye("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),Ye._fiveStrings.push(Ye._defaultTunings.get(5)),Ye._fiveStrings.push(new Ye("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),Ye._fiveStrings.push(new Ye("Banjo Open D Tuning",[62,57,54,50,69],!1)),Ye._fiveStrings.push(new Ye("Banjo Open G Tuning",[62,59,55,50,67],!1)),Ye._fiveStrings.push(new Ye("Banjo G Minor Tuning",[62,58,55,50,67],!1)),Ye._fiveStrings.push(new Ye("Banjo G Modal Tuning",[62,57,55,50,67],!1)),Ye._defaultTunings.set(4,new Ye("Bass Standard Tuning",[43,38,33,28],!0)),Ye._fourStrings.push(Ye._defaultTunings.get(4)),Ye._fourStrings.push(new Ye("Bass Tune down ½ step",[42,37,32,27],!1)),Ye._fourStrings.push(new Ye("Bass Tune down 1 step",[41,36,31,26],!1)),Ye._fourStrings.push(new Ye("Bass Tune down 2 step",[39,34,29,24],!1)),Ye._fourStrings.push(new Ye("Bass Dropped D Tuning",[43,38,33,26],!1)),Ye._fourStrings.push(new Ye("Ukulele C Tuning",[45,40,36,43],!1)),Ye._fourStrings.push(new Ye("Ukulele G Tuning",[52,47,43,38],!1)),Ye._fourStrings.push(new Ye("Mandolin Standard Tuning",[64,57,50,43],!1)),Ye._fourStrings.push(new Ye("Mandolin or Violin Tuning",[76,69,62,55],!1)),Ye._fourStrings.push(new Ye("Viola Tuning",[69,62,55,48],!1)),Ye._fourStrings.push(new Ye("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){let t=Ye.getPresetsFor(e.length);for(let s=0,i=t.length;s<i;s++){let i=t[s],a=!0;for(let t=0,s=e.length;t<s;t++)if(e[t]!==i.tunings[t]){a=!1;break}if(a)return i}return null}finish(){const e=Ye.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}Ye._sevenStrings=[],Ye._sixStrings=[],Ye._fiveStrings=[],Ye._fourStrings=[],Ye._defaultTunings=new Map,Ye.defaultAccidentals=["","#","","#","","","#","","#","","#",""],Ye.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],Ye.initialize();class qe{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new Ye("",[],!1),this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=5}get tuning(){return this.stringTuning.tunings}get tuningName(){return this.stringTuning.name}get isStringed(){return this.stringTuning.tunings.length>0}finish(e,t){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){var t,s;return null!==(s=null===(t=this.chords)||void 0===t?void 0:t.has(e))&&void 0!==s&&s}getChord(e){var t,s;return null!==(s=null===(t=this.chords)||void 0===t?void 0:t.get(e))&&void 0!==s?s:null}addBar(e){let t=this.bars;e.staff=this,e.index=t.length,t.length>0&&(e.previousBar=t[t.length-1],e.previousBar.nextBar=e),t.push(e)}}class Je{constructor(){this.index=0,this.staves=[],this.playbackInfo=new Xe,this.color=new Ue(200,0,0,255),this.name="",this.shortName="",this.percussionArticulations=[]}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new qe)}addStaff(e){e.index=this.staves.length,e.track=this,this.staves.push(e)}finish(e,t){this.shortName||(this.shortName=this.name,this.shortName.length>Je.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,Je.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[s]=i.chunks[t],a=a.nextBeat)}}}}}Je.ShortNameMaxLength=10;class Qe{constructor(){this.id=Qe._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){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){this._beatLookup=new Map;let s=null;for(let e=0;e<this.beats.length;e++){let i=this.beats[e];i.index=e,this.chain(i,t),i.graceType===g.None?(i.graceGroup=s,s&&(s.isComplete=!0),s=null):(s||(s=new Ie),s.addBeat(i))}let i=0,a=0;for(let s=0;s<this.beats.length;s++){let r=this.beats[s];if(r.index=s,r.finish(e,t),r.graceType===g.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==g.BendGrace){let s=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case g.BeforeBeat:e.previousBeat?(e.previousBeat.playbackDuration-=s,a=e.previousBeat.voice==this?e.previousBeat.playbackStart+e.previousBeat.playbackDuration:-s):a=-s;for(const e of r.graceGroup.beats)this._beatLookup.delete(e.playbackStart),e.playbackStart=a,this._beatLookup.set(e.playbackStart,r),a+=e.playbackDuration;break;case g.OnBeat:r.playbackDuration-=s,a=t.voice===this?t.playbackStart+t.playbackDuration:-s}}}r.displayStart=i,r.playbackStart=a,r.fermata?this.bar.masterBar.addFermata(r.playbackStart,r.fermata):r.fermata=this.bar.masterBar.getFermata(r),this._beatLookup.set(r.playbackStart,r)}else r.displayStart=i,r.playbackStart=a;r.finishTuplet(),r.graceGroup&&r.graceGroup.finish(),i+=r.displayDuration,a+=r.playbackDuration}}calculateDuration(){if(this.isEmpty||0===this.beats.length)return 0;let e=this.beats[this.beats.length-1],t=this.beats[0];return e.playbackStart+e.playbackDuration-t.playbackStart}}Qe._globalBarId=0;class je{static float64ToBytes(e){return je._dataView.setFloat64(0,e,!0),this._conversionByteArray}static bytesToFloat64(e){throw je._conversionByteArray.set(e,0),je._dataView.getFloat64(0,!0)}static uint16ToInt16(e){return je._dataView.setUint16(0,e,!0),je._dataView.getInt16(0,!0)}static int16ToUint32(e){return je._dataView.setInt16(0,e,!0),je._dataView.getUint32(0,!0)}static int32ToUint16(e){return je._dataView.setInt32(0,e,!0),je._dataView.getUint16(0,!0)}static int32ToInt16(e){return je._dataView.setInt32(0,e,!0),je._dataView.getInt16(0,!0)}static int32ToUint32(e){return je._dataView.setInt32(0,e,!0),je._dataView.getUint32(0,!0)}static uint8ToInt8(e){return je._dataView.setUint8(0,e),je._dataView.getInt8(0)}}je._conversionBuffer=new ArrayBuffer(8),je._conversionByteArray=new Uint8Array(je._conversionBuffer),je._dataView=new DataView(je._conversionBuffer);class Ke{static readInt32BE(e){return e.readByte()<<24|e.readByte()<<16|e.readByte()<<8|e.readByte()}static readInt32LE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static readUInt32LE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static decodeUInt32LE(e,t){let s=e[t],i=e[t+1],a=e[t+2];return e[t+3]<<24|a<<16|i<<8|s}static readUInt16LE(e){let t=e.readByte(),s=e.readByte();return je.int32ToUint16(s<<8|t)}static readInt16LE(e){let t=e.readByte(),s=e.readByte();return je.int32ToInt16(s<<8|t)}static readUInt32BE(e){let t=e.readByte(),s=e.readByte(),i=e.readByte(),a=e.readByte();return je.int32ToUint32(t<<24|s<<16|i<<8|a)}static readUInt16BE(e){let t=e.readByte(),s=e.readByte();return je.int32ToInt16(t<<8|s)}static readInt16BE(e){let t=e.readByte(),s=e.readByte();return je.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),Ke.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==(8388608&s)&&(s|=255<<24),s}static readInt16(e,t){return je.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){let s=Ke.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(t>>0&255)}static writeInt32LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255),e.writeByte(t>>16&255),e.writeByte(t>>24&255)}static writeUInt16LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255)}static writeInt16LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255)}}class $e{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return $e.withCapacity(0)}static withCapacity(e){let t=new $e;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){let t=new $e;return t._buffer=e,t.length=e.length,t}static fromString(e){let t=Ke.stringToBytes(e);return $e.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}}!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",e[e.Property=15]="Property"}(R||(R={}));class Ze extends pe{constructor(e){super(s.AlphaTex,e),this.position=0,this.nonTerm="",this.expected=R.No,this.symbol=R.No,this.symbolData=null,Object.setPrototypeOf(this,Ze.prototype)}static symbolError(e,t,s,i,a=null){let r;r=a?`MalFormed AlphaTex: @${e}: Error on block ${t}, invalid value: ${a}`:`MalFormed AlphaTex: @${e}: Error on block ${t}, expected a ${R[s]} found a ${R[i]}: '${a}'`;let n=new Ze(r);return n.position=e,n.nonTerm=t,n.expected=s,n.symbol=i,n.symbolData=a,n}static errorMessage(e,t){let s=new Ze(t="MalFormed AlphaTex: @"+e+": "+t);return s.position=e,s}}class et extends ue{constructor(){super(),this._trackChannel=0,this._input="",this._ch=0,this._curChPos=0,this._sy=R.No,this._syData="",this._allowNegatives=!1,this._allowTuning=!1,this._currentDuration=u.QuadrupleWhole,this._currentDynamics=p.PPP,this._currentTuplet=0,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=$e.empty(),this._input=e,this.settings=t}readScore(){try{if(this.data.length>0&&(this._input=Ke.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this.createDefaultScore(),this._curChPos=0,this._currentDuration=u.Quarter,this._currentDynamics=p.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===R.LowerThan)throw new ge("Unknown start sign <");this.score(),this.consolidate(),this._score.finish(this.settings),this._score.rebuildRepeatGroups();for(const[e,t]of this._lyrics)this._score.tracks[e].applyLyrics(t);return this._score}catch(e){throw e instanceof Ze?new ge(e.message):e}}consolidate(){for(let e of this._score.tracks)for(let t of e.staves)for(;t.bars.length<this._score.masterBars.length;){let e=this.newBar(t),s=new De;s.isEmpty=!0,e.voices[0].addBeat(s)}}error(e,t,s=!0){let i;throw i=s?Ze.symbolError(this._curChPos,e,t,this._sy,null):Ze.symbolError(this._curChPos,e,t,t,this._syData),this.logErrors&&Be.error(this.name,i.message),i}errorMessage(e){let t=Ze.errorMessage(this._curChPos,e);throw this.logErrors&&Be.error(this.name,t.message),t}createDefaultScore(){this._score=new He,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new Je,this._currentTrack.ensureStaveCount(1),this._currentTrack.playbackInfo.program=25,this._currentTrack.playbackInfo.primaryChannel=this._trackChannel++,this._currentTrack.playbackInfo.secondaryChannel=this._trackChannel++,this._currentStaff=this._currentTrack.staves[0],this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=Ye.getDefaultTuningFor(6).tunings,this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=p.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":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;default:return r.G2}}parseClefFromInt(e){switch(e){case 43:return r.G2;case 65:return r.F4;case 48:return r.C3;case 60:return r.C4;default:return r.G2}}parseTripletFeelFromString(e){switch(e.toLowerCase()){case"no":case"none":return D.NoTripletFeel;case"t16":case"triplet-16th":return D.Triplet16th;case"t8":case"triplet-8th":return D.Triplet8th;case"d16":case"dotted-16th":return D.Dotted16th;case"d8":case"dotted-8th":return D.Dotted8th;case"s16":case"scottish-16th":return D.Scottish16th;case"s8":case"scottish-8th":return D.Scottish8th;default:return D.NoTripletFeel}}parseTripletFeelFromInt(e){switch(e){case 0:return D.NoTripletFeel;case 1:return D.Triplet16th;case 2:return D.Triplet8th;case 3:return D.Dotted16th;case 4:return D.Dotted8th;case 5:return D.Scottish16th;case 6:return D.Scottish8th;default:return D.NoTripletFeel}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":return-7;case"gb":return-6;case"db":return-5;case"ab":return-4;case"eb":return-3;case"bb":return-2;case"f":return-1;case"c":return 0;case"g":return 1;case"d":return 2;case"a":return 3;case"e":return 4;case"b":return 5;case"f#":return 6;case"c#":return 7;default:return 0}}nextChar(){return this._curChPos<this._input.length?this._ch=this._input.charCodeAt(this._curChPos++):this._ch=0,this._ch}newSy(){this._sy=R.No;do{if(this._ch===et.Eof)this._sy=R.Eof;else if(32===this._ch||11===this._ch||13===this._ch||10===this._ch||9===this._ch)this._ch=this.nextChar();else if(47===this._ch)if(this._ch=this.nextChar(),47===this._ch)for(;13!==this._ch&&10!==this._ch&&this._ch!==et.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;0!==this._ch;)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("symbol",R.String,!1);else if(34===this._ch||39===this._ch){let e=this._ch;this._ch=this.nextChar();let t="";for(this._sy=R.String;this._ch!==e&&this._ch!==et.Eof;)t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)if(this._allowNegatives&&this.isDigit(this._ch)){let e=this.readNumber();this._sy=R.Number,this._syData=e}else this._sy=R.String,this._syData=this.readName();else if(46===this._ch)this._sy=R.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=R.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=R.LParensis,this._ch=this.nextChar();else if(92===this._ch){this._ch=this.nextChar();let e=this.readName();this._sy=R.MetaCommand,this._syData=e}else if(41===this._ch)this._sy=R.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=R.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=R.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=R.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=R.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=R.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch)){let e=this.readNumber();this._sy=R.Number,this._syData=e}else if(et.isLetter(this._ch)){let e=this.readName(),t=this._allowTuning?ke.parseTuning(e):null;t?(this._sy=R.Tuning,this._syData=t):(this._sy=R.String,this._syData=e)}else this.error("symbol",R.String,!1)}while(this._sy===R.No);return this._sy}static isLetter(e){return!et.isTerminal(e)&&(e>=33&&e<=47||e>=58&&e<=126||e>128)}static isTerminal(e){return 46===e||123===e||125===e||91===e||93===e||40===e||41===e||124===e||39===e||34===e||92===e}isDigit(e){return e>=48&&e<=57||45===e&&this._allowNegatives}readName(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(et.isLetter(this._ch)||this.isDigit(this._ch)||35===this._ch);return e}readNumber(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(this.isDigit(this._ch));return parseInt(e)}score(){if(this._sy===R.Eof)throw new ge("Unexpected end of file");const e=this.metaData(),t=this.bars();if(!e&&!t)throw new ge("No alphaTex data found")}metaData(){let e=!1,t=!0;for(;this._sy===R.MetaCommand&&t;){switch(this._syData.toLowerCase()){case"title":this._sy=this.newSy(),this._sy===R.String?this._score.title=this._syData:this.error("title",R.String,!0),this._sy=this.newSy(),e=!0;break;case"subtitle":this._sy=this.newSy(),this._sy===R.String?this._score.subTitle=this._syData:this.error("subtitle",R.String,!0),this._sy=this.newSy(),e=!0;break;case"artist":this._sy=this.newSy(),this._sy===R.String?this._score.artist=this._syData:this.error("artist",R.String,!0),this._sy=this.newSy(),e=!0;break;case"album":this._sy=this.newSy(),this._sy===R.String?this._score.album=this._syData:this.error("album",R.String,!0),this._sy=this.newSy(),e=!0;break;case"words":this._sy=this.newSy(),this._sy===R.String?this._score.words=this._syData:this.error("words",R.String,!0),this._sy=this.newSy(),e=!0;break;case"music":this._sy=this.newSy(),this._sy===R.String?this._score.music=this._syData:this.error("music",R.String,!0),this._sy=this.newSy(),e=!0;break;case"copyright":this._sy=this.newSy(),this._sy===R.String?this._score.copyright=this._syData:this.error("copyright",R.String,!0),this._sy=this.newSy(),e=!0;break;case"tempo":this._sy=this.newSy(),this._sy===R.Number?this._score.tempo=this._syData:this.error("tempo",R.Number,!0),this._sy=this.newSy(),e=!0;break;default:this.handleStaffMeta()?e=!0:e?this.error("metaDataTags",R.String,!1):t=!1}}return e?(this._sy!==R.Dot&&this.error("song",R.Dot,!0),this._sy=this.newSy()):this._sy===R.Dot&&(this._sy=this.newSy()),e}handleStaffMeta(){var e,t;switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===R.Number?this._currentStaff.capo=this._syData:this.error("capo",R.Number,!0),this._sy=this.newSy(),!0;case"tuning":this._sy=this.newSy();let s=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case R.String:let e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?(this._currentStaff.stringTuning.tunings=[],this._currentStaff.displayTranspositionPitch=0):this.error("tuning",R.Tuning,!0),this._sy=this.newSy();break;case R.Tuning:let t=[];do{let e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===R.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",R.Tuning,!0)}return s!==this._currentStaff.tuning.length&&(null!==(t=null===(e=this._currentStaff.chords)||void 0===e?void 0:e.size)&&void 0!==t?t:0)>0&&this.errorMessage("Tuning must be defined before any chord"),!0;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===R.Number){let e=this._syData;e>=0&&e<=128?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",R.Number,!1)}else if(this._sy===R.String){let e=this._syData.toLowerCase();this._currentTrack.playbackInfo.program=de.getValue(e)}else this.error("instrument",R.Number,!0);return this._sy=this.newSy(),!0;case"lyrics":this._sy=this.newSy();let i=new Ae;return i.startBar=0,i.text="",this._sy===R.Number&&(i.startBar=this._syData,this._sy=this.newSy()),this._sy===R.String?(i.text=this._syData,this._sy=this.newSy()):this.error("lyrics",R.String,!0),this._lyrics.get(this._currentTrack.index).push(i),!0;case"chord":this._sy=this.newSy();let a=new Re;this.chordProperties(a),this._sy===R.String?(a.name=this._syData,this._sy=this.newSy()):this.error("chord-name",R.Number,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===R.Number?a.strings.push(this._syData):this._sy===R.String&&"x"===this._syData.toLowerCase()&&a.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,a.name),a),!0;default:return!1}}chordProperties(e){if(this._sy===R.LBrace){for(this._sy=this.newSy();this._sy===R.String;)switch(this._syData.toLowerCase()){case"firstfret":switch(this._sy=this.newSy(),this._sy){case R.Number:e.firstFret=this._syData;break;default:this.error("chord-firstfret",R.Number,!0)}this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case R.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case R.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",R.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case R.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case R.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",R.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case R.String:e.showName="false"!==this._syData.toLowerCase();break;case R.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",R.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===R.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",R.String,!1)}this._sy!==R.RBrace&&this.error("chord-properties",R.RBrace,!0),this._sy=this.newSy()}}bars(){let e=this.bar();for(;this._sy!==R.Eof;)if(this._sy===R.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==R.MetaCommand)break;this.bar()}return e}trackStaffMeta(){let e=!1;if(this._sy===R.MetaCommand){e=!0;let t=this._syData.toLowerCase();"track"===t&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===R.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===R.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy())),this._sy===R.MetaCommand&&(t=this._syData.toLowerCase(),"staff"===t&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0&&(this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this._currentStaff=this._currentTrack.staves[this._currentTrack.staves.length-1],this._currentDynamics=p.F),this.staffProperties()))}return e}staffProperties(){if(this._sy!==R.LBrace)return;this._sy=this.newSy();let e=!1,t=!1;for(;this._sy===R.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy();break;case"tabs":t=!0,this._sy=this.newSy();break;default:this.error("staff-properties",R.String,!1)}(e||t)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t),this._sy!==R.RBrace&&this.error("staff-properties",R.RBrace,!0),this._sy=this.newSy()}bar(){const e=this.trackStaffMeta();let t=this.newBar(this._currentStaff);if(this._currentStaff.bars.length>this._score.masterBars.length){let e=new Oe;this._score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.timeSignatureDenominator=e.previousMasterBar.timeSignatureDenominator,e.timeSignatureNumerator=e.previousMasterBar.timeSignatureNumerator,e.tripletFeel=e.previousMasterBar.tripletFeel)}const s=this.barMeta(t);if(!this._staffTuningApplied&&!this._staffHasExplicitTuning){const e=this._currentTrack.playbackInfo.program;this._currentStaff.displayTranspositionPitch=0,this._currentStaff.stringTuning.tunings=[],15==e||e>=24&&e<=31?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=Ye.getDefaultTuningFor(6).tunings):e>=32&&e<=39?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):40==e||44==e||45==e||48==e||49==e||50==e||51==e?this._currentStaff.stringTuning.tunings=[52,57,50,43]:41==e?this._currentStaff.stringTuning.tunings=[57,50,43,36]:42==e?this._currentStaff.stringTuning.tunings=[45,38,31,24]:43==e?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):105==e?this._currentStaff.stringTuning.tunings=[50,47,43,38,55]:106==e?this._currentStaff.stringTuning.tunings=[57,52,45]:107==e?this._currentStaff.stringTuning.tunings=[52,45,38,31]:110==e&&(this._currentStaff.stringTuning.tunings=[64,57,50,43]),this._staffTuningApplied=!0}let i=!1,a=t.voices[0];for(;this._sy!==R.Pipe&&this._sy!==R.Eof&&this.beat(a);)i=!0;if(0===a.beats.length){let e=new De;e.isEmpty=!0,a.addBeat(e)}return e||s||i}newBar(e){let t=new me;e.addBar(t),t.index>0&&(t.clef=t.previousBar.clef);let s=new Qe;return t.addVoice(s),t}beat(e){this.beatDuration();let t=new De;if(e.addBeat(t),this._sy===R.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==R.RParensis&&this._sy!==R.Eof&&this.note(t););this._sy!==R.RParensis&&this.error("note-list",R.RParensis,!0),this._sy=this.newSy()}else if(this._sy===R.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===R.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==R.Number&&this.error("duration",R.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||this.applyTuplet(t,this._currentTuplet);let s=1;this._sy===R.Multiply&&(this._sy=this.newSy(),this._sy!==R.Number?this.error("multiplier",R.Number,!0):s=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let i=0;i<s-1;i++)e.addBeat(Me.clone(t));return!0}beatDuration(){if(this._sy===R.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==R.Number&&this.error("duration",R.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===R.LBrace)){for(this._sy=this.newSy();this._sy===R.String;){switch(this._syData.toLowerCase()){case"tu":this._sy=this.newSy(),this._sy!==R.Number&&this.error("duration-tuplet",R.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();break;default:this.error("beat-duration",R.String,!1)}}this._sy!==R.RBrace&&this.error("beat-duration",R.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===R.LBrace){for(this._sy=this.newSy();this._sy===R.String;)this._syData=this._syData.toLowerCase(),this.applyBeatEffect(e)||this.error("beat-effects",R.String,!1);this._sy!==R.RBrace&&this.error("beat-effects",R.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){let t=this._syData.toLowerCase();if("f"===t)return e.fadeIn=!0,this._sy=this.newSy(),!0;if("v"===t)return e.vibrato=w.Slight,this._sy=this.newSy(),!0;if("s"===t)return e.slap=!0,this._sy=this.newSy(),!0;if("p"===t)return e.pop=!0,this._sy=this.newSy(),!0;if("tt"===t)return e.tap=!0,this._sy=this.newSy(),!0;if("dd"===t)return e.dots=2,this._sy=this.newSy(),!0;if("d"===t)return e.dots=1,this._sy=this.newSy(),!0;if("su"===t)return e.pickStroke=x.Up,this._sy=this.newSy(),!0;if("sd"===t)return e.pickStroke=x.Down,this._sy=this.newSy(),!0;if("tu"===t)return this._sy=this.newSy(),this._sy!==R.Number?(this.error("tuplet",R.Number,!0),!1):(this.applyTuplet(e,this._syData),this._sy=this.newSy(),!0);if("tb"===t||"tbe"===t){let s="tbe"===t;if(this._sy=this.newSy(),this._sy!==R.LParensis)return this.error("tremolobar-effect",R.LParensis,!0),!1;for(this._allowNegatives=!0,this._sy=this.newSy();this._sy!==R.RParensis&&this._sy!==R.Eof;){let t=0,i=0;if(s){if(this._sy!==R.Number)return this.error("tremolobar-effect",R.Number,!0),!1;if(t=this._syData,this._sy=this.newSy(),this._sy!==R.Number)return this.error("tremolobar-effect",R.Number,!0),!1;i=this._syData}else{if(this._sy!==R.Number)return this.error("tremolobar-effect",R.Number,!0),!1;t=0,i=this._syData}e.addWhammyBarPoint(new be(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++}}return this._allowNegatives=!1,this._sy!==R.RParensis?(this.error("tremolobar-effect",R.RParensis,!0),!1):(this._sy=this.newSy(),!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 Re;e.showDiagram=!1,e.name=t,this._currentStaff.addChord(s,e)}return e.chordId=s,this._sy=this.newSy(),!0}if("gr"===t)return this._sy=this.newSy(),"ob"===this._syData.toLowerCase()?(e.graceType=g.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=g.BendGrace,this._sy=this.newSy()):e.graceType=g.BeforeBeat,!0;if("dy"===t){switch(this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=p.PPP;break;case"pp":e.dynamics=p.PP;break;case"p":e.dynamics=p.P;break;case"mp":e.dynamics=p.MP;break;case"mf":e.dynamics=p.MF;break;case"f":e.dynamics=p.F;break;case"ff":e.dynamics=p.FF;break;case"fff":e.dynamics=p.FFF}return this._currentDynamics=e.dynamics,this.newSy(),!0}if("cre"===t)return e.crescendo=d.Crescendo,this.newSy(),!0;if("dec"===t)return e.crescendo=d.Decrescendo,this.newSy(),!0;if("tp"===t){this._sy=this.newSy();let t=u.Eighth;if(this._sy===R.Number){switch(this._syData){case 8:t=u.Eighth;break;case 16:t=u.Sixteenth;break;case 32:t=u.ThirtySecond;break;default:t=u.Eighth}this._sy=this.newSy()}return e.tremoloSpeed=t,!0}return!1}getChordId(e,t){return t.toLowerCase()+e.index+e.track.index}applyTuplet(e,t){switch(t){case 3:e.tupletNumerator=3,e.tupletDenominator=2;break;case 5:e.tupletNumerator=5,e.tupletDenominator=4;break;case 6:e.tupletNumerator=6,e.tupletDenominator=4;break;case 7:e.tupletNumerator=7,e.tupletDenominator=4;break;case 9:e.tupletNumerator=9,e.tupletDenominator=8;break;case 10:e.tupletNumerator=10,e.tupletDenominator=8;break;case 11:e.tupletNumerator=11,e.tupletDenominator=8;break;case 12:e.tupletNumerator=12,e.tupletDenominator=8;break;default:e.tupletNumerator=1,e.tupletDenominator=1}}isNoteText(e){return"x"===e||"-"===e||"r"===e}note(e){let t=!1,s=!1,i=-1,a=-1,r=-1;switch(this._sy){case R.Number:i=this._syData;break;case R.String:t="x"===this._syData,s="-"===this._syData,s||t?i=0:this.error("note-fret",R.Number,!0);break;case R.Tuning:let e=this._syData;a=e.octave,r=e.noteValue;break;default:return!1}this._sy=this.newSy();let n=-1===a&&this._currentStaff.tuning.length>0,o=-1;n&&(this._sy!==R.Dot&&this.error("note",R.Dot,!0),this._sy=this.newSy(),this._sy!==R.Number&&this.error("note-string",R.Number,!0),o=this._syData,(o<1||o>this._currentStaff.tuning.length)&&this.error("note-string",R.Number,!1),this._sy=this.newSy());let h=new Pe;return n?(h.string=this._currentStaff.tuning.length-(o-1),h.isDead=t,h.isTieDestination=s,s||(h.fret=i)):(h.octave=a,h.tone=r,h.isTieDestination=s),e.addNote(h),this.noteEffects(h),!0}noteEffects(e){if(this._sy===R.LBrace){for(this._sy=this.newSy();this._sy===R.String;){let t=this._syData.toLowerCase();if(this._syData=t,"b"===t||"be"===t){let t="be"===this._syData;for(this._sy=this.newSy(),this._sy!==R.LParensis&&this.error("bend-effect",R.LParensis,!0),this._sy=this.newSy();this._sy!==R.RParensis&&this._sy!==R.Eof;){let s=0,i=0;t?(this._sy!==R.Number&&this.error("bend-effect-value",R.Number,!0),s=this._syData,this._sy=this.newSy(),this._sy!==R.Number&&this.error("bend-effect-value",R.Number,!0),i=this._syData):(this._sy!==R.Number&&this.error("bend-effect-value",R.Number,!0),i=this._syData),e.addBendPoint(new be(s,i)),this._sy=this.newSy()}const s=e.bendPoints;if(null!=s){for(;s.length>60;)s.splice(s.length-1,1);if(t)s.sort(((e,t)=>e.offset-t.offset));else{let e=s.length,t=60/(e-1)|0,i=0;for(;i<e;)s[i].offset=Math.min(60,i*t),i++}}this._sy!==R.RParensis&&this.error("bend-effect",R.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=m.Natural,this._sy=this.newSy();else if("ah"===t)e.harmonicType=m.Artificial,this._sy=this.newSy();else if("th"===t)e.harmonicType=m.Tap,this._sy=this.newSy();else if("ph"===t)e.harmonicType=m.Pinch,this._sy=this.newSy();else if("sh"===t)e.harmonicType=m.Semi,this._sy=this.newSy();else if("tr"===t){this._sy=this.newSy(),this._sy!==R.Number&&this.error("trill-effect",R.Number,!0);let t=this._syData;this._sy=this.newSy();let s=u.Sixteenth;if(this._sy===R.Number){switch(this._syData){case 16:s=u.Sixteenth;break;case 32:s=u.ThirtySecond;break;case 64:s=u.SixtyFourth;break;default:s=u.Sixteenth}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=S.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=S.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=b.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=b.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=S.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=S.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=S.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=S.PickSlideUp;else if("h"===t)this._sy=this.newSy(),e.isHammerPullOrigin=!0;else if("lht"===t)this._sy=this.newSy(),e.isLeftHandTapped=!0;else if("g"===t)this._sy=this.newSy(),e.isGhost=!0;else if("ac"===t)this._sy=this.newSy(),e.accentuated=i.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=i.Heavy;else if("pm"===t)this._sy=this.newSy(),e.isPalmMute=!0;else if("st"===t)this._sy=this.newSy(),e.isStaccato=!0;else if("lr"===t)this._sy=this.newSy(),e.isLetRing=!0;else if("x"===t)this._sy=this.newSy(),e.fret=0,e.isDead=!0;else if("-"===t||"t"===t)this._sy=this.newSy(),e.isTieDestination=!0;else if("lf"===t){this._sy=this.newSy();let t=f.Thumb;this._sy===R.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===R.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else this.applyBeatEffect(e.beat)||this.error(t,R.String,!1)}this._sy!==R.RBrace&&this.error("note-effect",R.RBrace,!1),this._sy=this.newSy()}}toFinger(e){switch(e){case 1:return f.Thumb;case 2:return f.IndexFinger;case 3:return f.MiddleFinger;case 4:return f.AnnularFinger;case 5:return f.LittleFinger}return f.Thumb}parseDuration(e){switch(e){case-4:return u.QuadrupleWhole;case-2:return u.DoubleWhole;case 1:return u.Whole;case 2:return u.Half;case 4:return u.Quarter;case 8:return u.Eighth;case 16:return u.Sixteenth;case 32:return u.ThirtySecond;case 64:return u.SixtyFourth;case 128:return u.OneHundredTwentyEighth;default:return u.Quarter}}barMeta(e){let t=!1,s=e.masterBar;for(;this._sy===R.MetaCommand;){t=!0;let i=this._syData.toLowerCase();if("ts"===i)this._sy=this.newSy(),this._sy!==R.Number&&this.error("timesignature-numerator",R.Number,!0),s.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==R.Number&&this.error("timesignature-denominator",R.Number,!0),s.timeSignatureDenominator=this._syData,this._sy=this.newSy();else if("ro"===i)s.isRepeatStart=!0,this._sy=this.newSy();else if("rc"===i)this._sy=this.newSy(),this._sy!==R.Number&&this.error("repeatclose",R.Number,!0),s.repeatCount=this._syData,this._sy=this.newSy();else if("ks"===i)this._sy=this.newSy(),this._sy!==R.String&&this.error("keysignature",R.String,!0),s.keySignature=this.parseKeySignature(this._syData.toLowerCase()),this._sy=this.newSy();else if("clef"===i){switch(this._sy=this.newSy(),this._sy){case R.String:e.clef=this.parseClefFromString(this._syData.toLowerCase());break;case R.Number:e.clef=this.parseClefFromInt(this._syData);break;case R.Tuning:let t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",R.String,!0)}this._sy=this.newSy()}else if("tempo"===i){this._sy=this.newSy(),this._sy!==R.Number&&this.error("tempo",R.Number,!0);let e=new fe;e.isLinear=!1,e.type=a.Tempo,e.value=this._syData,s.tempoAutomation=e,this._sy=this.newSy()}else if("section"===i){this._sy=this.newSy(),this._sy!==R.String&&this.error("section",R.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==R.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());let i=new We;i.marker=t,i.text=e,s.section=i}else if("tf"===i){switch(this._allowTuning=!1,this._sy=this.newSy(),this._allowTuning=!0,this._sy){case R.String:s.tripletFeel=this.parseTripletFeelFromString(this._syData.toLowerCase());break;case R.Number:s.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",R.String,!0)}this._sy=this.newSy()}else"ac"===i?(s.isAnacrusis=!0,this._sy=this.newSy()):0===e.index&&this.handleStaffMeta()||this.error("measure-effects",R.String,!1)}if(0===s.index&&!s.tempoAutomation){let e=new fe;e.isLinear=!1,e.type=a.Tempo,e.value=this._score.tempo,s.tempoAutomation=e}return t}}et.Eof=0;class tt extends ue{constructor(){super(),this._versionNumber=0,this._globalTripletFeel=D.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._beatTextChunksByTrack=new Map}get name(){return"Guitar Pro 3-5"}readScore(){return this.readVersion(),this._score=new He,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=st.gpReadBool(this.data)?D.Triplet8th:D.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=st.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=Ke.readInt32LE(this.data),this._versionNumber>=510&&st.gpReadBool(this.data),Ke.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.data.skip(38),this.data.skip(4)),this._barCount=Ke.readInt32LE(this.data),this._trackCount=Ke.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0&&(this._score.masterBars[0].tempoAutomation=fe.buildTempoAutomation(!1,0,this._score.tempo,2),this._score.masterBars[0].tempoAutomation.text=this._score.tempoLabel),this._score.finish(this.settings),this._lyrics&&this._lyricsTrack>=0&&this._score.tracks[this._lyricsTrack].applyLyrics(this._lyrics),this._score}readVersion(){let e=st.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(tt.VersionString))throw new ge("Unsupported format");e=e.substr(tt.VersionString.length+1);let t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*parseInt(e.substr(0,t))+parseInt(e.substr(t+1)),Be.debug(this.name,"Guitar Pro version "+e+" detected")}readScoreInformation(){var e;this._score.title=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?st.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding);let t=Ke.readInt32LE(this.data),s="";for(let i=0;i<t;i++)i>0&&(s+="\r\n"),s+=null===(e=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding))||void 0===e?void 0:e.toString();this._score.notices=s}readLyrics(){this._lyrics=[],this._lyricsTrack=Ke.readInt32LE(this.data)-1;for(let e=0;e<5;e++){let e=new Ae;e.startBar=Ke.readInt32LE(this.data)-1,e.text=st.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(30);for(let e=0;e<10;e++)st.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){let t=new Xe;t.primaryChannel=e,t.secondaryChannel=e,t.program=Ke.readInt32LE(this.data),t.volume=this.data.readByte(),t.balance=this.data.readByte(),this.data.skip(6),this._playbackInfos.push(t)}}readMasterBars(){for(let e=0;e<this._barCount;e++)this.readMasterBar()}readMasterBar(){let e=null;this._score.masterBars.length>0&&(e=this._score.masterBars[this._score.masterBars.length-1]);let t=new Oe,s=this.data.readByte();if(0!=(1&s)?t.timeSignatureNumerator=this.data.readByte():e&&(t.timeSignatureNumerator=e.timeSignatureNumerator),0!=(2&s)?t.timeSignatureDenominator=this.data.readByte():e&&(t.timeSignatureDenominator=e.timeSignatureDenominator),t.isRepeatStart=0!=(4&s),0!=(8&s)&&(t.repeatCount=this.data.readByte()+(this._versionNumber>=500?0:1)),0!=(16&s))if(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&&0==(i&t)&&(a|=t)}t.alternateEndings=a}else t.alternateEndings=this.data.readByte();if(0!=(32&s)){let e=new We;e.text=st.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",st.gpReadColor(this.data,!1),t.section=e}if(0!=(64&s)?(t.keySignature=Ke.readSInt8(this.data),t.keySignatureType=this.data.readByte()):e&&(t.keySignature=e.keySignature,t.keySignatureType=e.keySignatureType),this._versionNumber>=500&&0!=(3&s)&&this.data.skip(4),this._versionNumber>=500&&0==(16&s)&&(t.alternateEndings=this.data.readByte()),this._versionNumber>=500){switch(this.data.readByte()){case 1:t.tripletFeel=D.Triplet8th;break;case 2:t.tripletFeel=D.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=0!=(128&s),this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){let e=new Je;e.ensureStaveCount(1),this._score.addTrack(e);let t=e.staves[0],s=this.data.readByte();e.name=st.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),0!=(1&s)&&(t.isPercussion=!0);let i=Ke.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){let t=Ke.readInt32LE(this.data);i>e&&a.push(t)}t.stringTuning.tunings=a;let r=Ke.readInt32LE(this.data),n=Ke.readInt32LE(this.data)-1,o=Ke.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=0!=(16&s),i.isMute=0!=(32&s),i.secondaryChannel=o,de.isGuitar(i.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=i}t.capo=Ke.readInt32LE(this.data),e.color=st.gpReadColor(this.data,!1),this._versionNumber>=500&&(this.data.readByte(),this.data.readByte(),this.data.skip(43)),this._versionNumber>=510&&(this.data.skip(4),st.gpReadStringIntByte(this.data,this.settings.importer.encoding),st.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 me,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=Ke.readInt32LE(this.data);if(0===s)return;let i=new Qe;t.addVoice(i);for(let a=0;a<s;a++)this.readBeat(e,t,i)}readBeat(e,t,s){let i=new De,a=this.data.readByte();if(0!=(1&a)&&(i.dots=1),0!=(64&a)){let e=this.data.readByte();i.isEmpty=0==(2&e)}switch(s.addBeat(i),Ke.readSInt8(this.data)){case-2:i.duration=u.Whole;break;case-1:i.duration=u.Half;break;case 0:i.duration=u.Quarter;break;case 1:i.duration=u.Eighth;break;case 2:i.duration=u.Sixteenth;break;case 3:i.duration=u.ThirtySecond;break;case 4:i.duration=u.SixtyFourth;break;default:i.duration=u.Quarter}if(0!=(32&a))switch(i.tupletNumerator=Ke.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}0!=(2&a)&&this.readChord(i);let r=this.settings.importer.beatTextAsLyrics&&e.index!==this._lyricsTrack;if(0!=(4&a)){const t=st.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const s=new Ae;s.text=t.trim(),s.finish(!0);const i=[];for(let e=s.chunks.length-1;e>=0;e--)i.push(s.chunks[e]);this._beatTextChunksByTrack.set(e.index,i)}else i.text=t}let n=m.None;0!=(8&a)&&(n=this.readBeatEffects(i)),0!=(16&a)&&this.readMixTableChange(i);let o=this.data.readByte();for(let a=6;a>=0;a--)if(0!=(o&1<<a)&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,s,i,6-a);n!==m.None&&(r.harmonicType=n,r.harmonicType===m.Natural&&(r.harmonicValue=this.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){this.data.readByte(),0!=(8&this.data.readByte())&&this.data.readByte()}r&&!i.isRest&&this._beatTextChunksByTrack.has(e.index)&&this._beatTextChunksByTrack.get(e.index).length>0&&(i.lyrics=[this._beatTextChunksByTrack.get(e.index).pop()])}readChord(e){let t=new Re,s=ke.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=st.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Ke.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Ke.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=st.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Ke.readInt32LE(this.data);for(let s=0;s<7;s++){let i=Ke.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=st.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=Ke.readInt32LE(this.data);for(let s=0;s<6;s++){let i=Ke.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=st.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=Ke.readInt32LE(this.data),t.firstFret>0)for(let i=0;i<s;i++){let s=Ke.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}}t.name&&(e.chordId=s,e.voice.bar.staff.addChord(e.chordId,t))}readBeatEffects(e){let t=this.data.readByte(),s=0;if(this._versionNumber>=400&&(s=this.data.readByte()),e.fadeIn=0!=(16&t),(this._versionNumber<400&&0!=(1&t)||0!=(2&t))&&(e.vibrato=w.Slight),e.hasRasgueado=0!=(1&s),0!=(32&t)&&this._versionNumber>=400){switch(Ke.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}}else if(0!=(32&t)){switch(Ke.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(0!=(4&s)&&this.readTremoloBarEffect(e),0!=(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=tt.toStrokeValue(t)):s>0&&(e.brushType=c.BrushDown,e.brushDuration=tt.toStrokeValue(s))}if(0!=(2&s))switch(Ke.readSInt8(this.data)){case 0:e.pickStroke=x.None;break;case 1:e.pickStroke=x.Up;break;case 2:e.pickStroke=x.Down}if(this._versionNumber<400){if(0!=(4&t))return m.Natural;if(0!=(8&t))return m.Artificial}return m.None}readTremoloBarEffect(e){this.data.readByte(),Ke.readInt32LE(this.data);let t=Ke.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new be(0,0);t.offset=Ke.readInt32LE(this.data),t.value=Ke.readInt32LE(this.data)/tt.BendStep|0,st.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 it;t.instrument=Ke.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=Ke.readSInt8(this.data),t.balance=Ke.readSInt8(this.data);let s=Ke.readSInt8(this.data),i=Ke.readSInt8(this.data),r=Ke.readSInt8(this.data),n=Ke.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=st.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=Ke.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=Ke.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500&&this.data.readByte(),this._versionNumber>=510&&(st.gpReadStringIntByte(this.data,this.settings.importer.encoding),st.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){let s=new fe;s.isLinear=!0,s.type=a.Volume,s.value=t.volume,e.automations.push(s)}if(t.balance>=0){let s=new fe;s.isLinear=!0,s.type=a.Balance,s.value=t.balance,e.automations.push(s)}if(t.instrument>=0){let s=new fe;s.isLinear=!0,s.type=a.Instrument,s.value=t.instrument,e.automations.push(s)}if(t.tempo>=0){let s=new fe;s.isLinear=!0,s.type=a.Tempo,s.value=t.tempo,e.automations.push(s),e.voice.bar.masterBar.tempoAutomation=s}}readNote(e,t,s,a,r){let n=new Pe;n.string=t.staff.tuning.length-r;let o=this.data.readByte();if(0!=(2&o)?n.accentuated=i.Heavy:0!=(64&o)&&(n.accentuated=i.Normal),n.isGhost=0!=(4&o),0!=(32&o)){let e=this.data.readByte();3===e?n.isDead=!0:2===e&&(n.isTieDestination=!0)}if(0!=(1&o)&&this._versionNumber<500&&(this.data.readByte(),this.data.readByte()),0!=(16&o)){let e=Ke.readSInt8(this.data);n.dynamics=this.toDynamicValue(e),a.dynamics=n.dynamics}0!=(32&o)&&(n.fret=Ke.readSInt8(this.data)),0!=(128&o)&&(n.leftHandFinger=Ke.readSInt8(this.data),n.rightHandFinger=Ke.readSInt8(this.data),n.isFingering=!0);let h=!1;if(this._versionNumber>=500){0!=(1&o)&&(n.durationPercent=st.gpReadDouble(this.data)),h=0!=(2&this.data.readByte())}if(a.addNote(n),0!=(8&o)&&this.readNoteEffects(e,s,a,n),t.staff.isPercussion&&(n.percussionArticulation=n.fret,n.string=-1,n.fret=-1),h){const e=Ye.defaultAccidentals[n.realValueWithoutHarmonic%12];"#"===e?n.accidentalMode=y.ForceFlat:"b"===e&&(n.accidentalMode=y.ForceSharp)}return n}toDynamicValue(e){switch(e){case 1:return p.PPP;case 2:return p.PP;case 3:return p.P;case 4:return p.MP;case 5:return p.MF;case 6:return p.F;case 7:return p.FF;case 8:return p.FFF;default:return p.F}}readNoteEffects(e,t,s,i){let a=this.data.readByte(),r=0;this._versionNumber>=400&&(r=this.data.readByte()),0!=(1&a)&&this.readBend(i),0!=(16&a)&&this.readGrace(t,i),0!=(4&r)&&this.readTremoloPicking(s),0!=(8&r)?this.readSlide(i):this._versionNumber<400&&0!=(4&a)&&(i.slideOutType=S.Shift),0!=(16&r)&&this.readArtificialHarmonic(i),0!=(32&r)&&this.readTrill(i),i.isLetRing=0!=(8&a),i.isHammerPullOrigin=0!=(2&a),0!=(64&r)&&(i.vibrato=w.Slight),i.isPalmMute=0!=(2&r),i.isStaccato=0!=(1&r)}readBend(e){this.data.readByte(),Ke.readInt32LE(this.data);let t=Ke.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){let t=new be(0,0);t.offset=Ke.readInt32LE(this.data),t.value=Ke.readInt32LE(this.data)/tt.BendStep|0,st.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){let s=new De,i=new Pe;switch(i.string=t.string,i.fret=Ke.readSInt8(this.data),s.duration=u.ThirtySecond,s.dynamics=this.toDynamicValue(Ke.readSInt8(this.data)),Ke.readSInt8(this.data)){case 0:break;case 1:i.slideOutType=S.Legato,i.slideTarget=t;break;case 2:break;case 3:i.isHammerPullOrigin=!0}if(i.dynamics=s.dynamics,this.data.skip(1),this._versionNumber<500)s.graceType=g.BeforeBeat;else{let e=this.data.readByte();i.isDead=0!=(1&e),s.graceType=0!=(2&e)?g.OnBeat:g.BeforeBeat}e.addGraceBeat(s),s.addNote(i)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=u.Eighth;break;case 2:e.tremoloSpeed=u.Sixteenth;break;case 3:e.tremoloSpeed=u.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){let t=Ke.readSInt8(this.data);0!=(1&t)?e.slideOutType=S.Shift:0!=(2&t)?e.slideOutType=S.Legato:0!=(4&t)?e.slideOutType=S.OutDown:0!=(8&t)&&(e.slideOutType=S.OutUp),0!=(16&t)?e.slideInType=b.IntoFromBelow:0!=(32&t)&&(e.slideInType=b.IntoFromAbove)}else{switch(Ke.readSInt8(this.data)){case 1:e.slideOutType=S.Shift;break;case 2:e.slideOutType=S.Legato;break;case 3:e.slideOutType=S.OutDown;break;case 4:e.slideOutType=S.OutUp;break;case-1:e.slideInType=b.IntoFromBelow;break;case-2:e.slideInType=b.IntoFromAbove}}}readArtificialHarmonic(e){let t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=m.Natural,e.harmonicValue=this.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=m.Artificial;break;case 3:e.harmonicType=m.Tap,e.harmonicValue=this.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=m.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=m.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=m.Natural;break;case 3:e.harmonicType=m.Tap;break;case 4:e.harmonicType=m.Pinch;break;case 5:e.harmonicType=m.Semi;break;case 15:case 17:case 22:e.harmonicType=m.Artificial}}deltaFretToHarmonicValue(e){switch(e){case 2:return 2.4;case 3:return 3.2;case 4:case 5:case 7:case 9:case 12:case 16:case 17:case 19:case 24:return e;case 8:return 8.2;case 10:return 9.6;case 14:case 15:return 14.7;case 21:case 22:return 21.7;default:return 12}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=u.Sixteenth;break;case 2:e.trillSpeed=u.ThirtySecond;break;case 3:e.trillSpeed=u.SixtyFourth}}}tt.VersionString="FICHIER GUITAR PRO ",tt.BendStep=25;class st{static gpReadDouble(e){let t=new Uint8Array(8);return e.read(t,0,t.length),new Float64Array(t.buffer)[0]}static gpReadFloat(e){let t=new Uint8Array(4);return t[3]=e.readByte(),t[2]=e.readByte(),t[2]=e.readByte(),t[1]=e.readByte(),new Float32Array(t.buffer)[0]}static gpReadColor(e,t=!1){let s=e.readByte(),i=e.readByte(),a=e.readByte(),r=255;return t?r=e.readByte():e.skip(1),new Ue(s,i,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),st.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return st.gpReadString(e,Ke.readInt32LE(e),t)}static gpReadStringIntByte(e,t){let s=Ke.readInt32LE(e)-1;return e.readByte(),st.gpReadString(e,s,t)}static gpReadString(e,t,s){let i=new Uint8Array(t);return e.read(i,0,i.length),Ke.toString(i,s)}static gpWriteString(e,t){const s=Ke.stringToBytes(t);e.writeByte(t.length),e.write(s,0,s.length)}static gpReadStringByteLength(e,t,s){let i=e.readByte(),a=st.gpReadString(e,i,s);return i<t&&e.skip(t-i),a}}class it{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class at{constructor(){this.x=0,this.y=0,this.w=0,this.h=0}}!function(e){e[e.Boolean=0]="Boolean",e[e.Integer=1]="Integer",e[e.Float=2]="Float",e[e.String=3]="String",e[e.Point=4]="Point",e[e.Size=5]="Size",e[e.Rectangle=6]="Rectangle",e[e.Color=7]="Color"}(A||(A={}));class rt{constructor(e){this.raw=new Map;let t=$e.fromBuffer(e),s=Ke.readInt32BE(t);for(let e=0;e<s;e++){let e=st.gpReadString(t,t.readByte(),"utf-8");switch(t.readByte()){case A.Boolean:let s=1===t.readByte();this.addValue(e,s);break;case A.Integer:let i=Ke.readInt32BE(t);this.addValue(e,i);break;case A.Float:let a=st.gpReadFloat(t);this.addValue(e,a);break;case A.String:let r=st.gpReadString(t,Ke.readInt16BE(t),"utf-8");this.addValue(e,r);break;case A.Point:let n=Ke.readInt32BE(t),o=Ke.readInt32BE(t);this.addValue(e,new be(n,o));break;case A.Size:let h=Ke.readInt32BE(t),l=Ke.readInt32BE(t);this.addValue(e,new be(h,l));break;case A.Rectangle:let c=new at;c.x=Ke.readInt32BE(t),c.y=Ke.readInt32BE(t),c.w=Ke.readInt32BE(t),c.h=Ke.readInt32BE(t),this.addValue(e,c);break;case A.Color:let d=st.gpReadColor(t,!0);this.addValue(e,d)}}}apply(e){for(const[t,s]of this.raw)switch(t){case"StandardNotation/hideDynamics":e.stylesheet.hideDynamics=s}}addValue(e,t){this.raw.set(e,t)}static writeForScore(e){const t=$e.withCapacity(128);return Ke.writeInt32BE(t,1),rt.writeBooleanEntry(t,"StandardNotation/hideDynamics",e.stylesheet.hideDynamics),t.toArray()}static writeBooleanEntry(e,t,s){st.gpWriteString(e,t),e.writeByte(A.Boolean),e.writeByte(s?1:0)}}!function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(O||(O={}));class nt{constructor(){this.type=O.Short,this.length=0}}!function(e){e[e.None=0]="None",e[e.Element=1]="Element",e[e.Text=2]="Text",e[e.CDATA=3]="CDATA",e[e.Document=4]="Document",e[e.DocumentType=5]="DocumentType"}(G||(G={}));class ot{constructor(){this.nodeType=G.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!==G.Element&&e.nodeType!==G.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===G.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===G.Element&&t.localName===e)return t;return null}addElement(e){const t=new ot;return t.nodeType=G.Element,t.localName=e,this.addChild(t),t}get innerText(){var e,t;if(this.nodeType===G.Element||this.nodeType===G.Document){if(this.firstElement&&this.firstElement.nodeType===G.CDATA)return this.firstElement.innerText;let t="";for(let s of this.childNodes)t+=null===(e=s.innerText)||void 0===e?void 0:e.toString();return t.trim()}return null!==(t=this.value)&&void 0!==t?t:""}set innerText(e){const t=new ot;t.nodeType=G.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new ot;t.nodeType=G.CDATA,t.value=e,this.childNodes=[t]}}class ht extends pe{constructor(e,t,i){super(s.Format,e),this.pos=0,this.xml=t,this.pos=i,Object.setPrototypeOf(this,ht.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"}(V||(V={}));class lt{static parse(e,t,s){var i;let a=e.charCodeAt(t),r=V.Begin,n=V.Begin,o=0,h="",l=V.Begin,c=null,d=null,u=0,p=0;for(;t<e.length;){switch(a=e.charCodeAt(t),r){case V.IgnoreSpaces:switch(a){case lt.CharCodeLF:case lt.CharCodeCR:case lt.CharCodeTab:case lt.CharCodeSpace:break;default:r=n;continue}break;case V.Begin:switch(a){case lt.CharCodeLowerThan:r=V.IgnoreSpaces,n=V.BeginNode;break;default:o=t,r=V.Pcdata;continue}break;case V.Pcdata:if(a===lt.CharCodeLowerThan){h+=e.substr(o,t-o);let i=new ot;i.nodeType=G.Text,i.value=h,h="",s.addChild(i),r=V.IgnoreSpaces,n=V.BeginNode}else a===lt.CharCodeAmp&&(h+=e.substr(o,t-o),r=V.Escape,l=V.Pcdata,o=t+1);break;case V.Cdata:if(a===lt.CharCodeBrackedClose&&e.charCodeAt(t+1)===lt.CharCodeBrackedClose&&e.charCodeAt(t+2)===lt.CharCodeGreaterThan){let i=new ot;i.nodeType=G.CDATA,i.value=e.substr(o,t-o),s.addChild(i),t+=2,r=V.Begin}break;case V.BeginNode:switch(a){case lt.CharCodeExclamation:if(e.charCodeAt(t+1)===lt.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new ht("Expected <![CDATA[",e,t);t+=5,r=V.Cdata,o=t+1}else if(e.charCodeAt(t+1)===lt.CharCodeUpperD||e.charCodeAt(t+1)===lt.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new ht("Expected <!DOCTYPE",e,t);t+=8,r=V.Doctype,o=t+1}else{if(e.charCodeAt(t+1)!==lt.CharCodeMinus||e.charCodeAt(t+2)!==lt.CharCodeMinus)throw new ht("Expected \x3c!--",e,t);t+=2,r=V.Comment,o=t+1}break;case lt.CharCodeQuestion:r=V.Header,o=t;break;case lt.CharCodeSlash:if(!s)throw new ht("Expected node name",e,t);o=t+1,r=V.IgnoreSpaces,n=V.Close;break;default:r=V.TagName,o=t;continue}break;case V.TagName:if(!lt.isValidChar(a)){if(t===o)throw new ht("Expected node name",e,t);c=new ot,c.nodeType=G.Element,c.localName=e.substr(o,t-o),s.addChild(c),r=V.IgnoreSpaces,n=V.Body;continue}break;case V.Body:switch(a){case lt.CharCodeSlash:r=V.WaitEnd;break;case lt.CharCodeGreaterThan:r=V.Childs;break;default:r=V.AttribName,o=t;continue}break;case V.AttribName:if(!lt.isValidChar(a)){if(o===t)throw new ht("Expected attribute name",e,t);if(d=e.substr(o,t-o),c.attributes.has(d))throw new ht(`Duplicate attribute [${d}]`,e,t);r=V.IgnoreSpaces,n=V.Equals;continue}break;case V.Equals:switch(a){case lt.CharCodeEquals:r=V.IgnoreSpaces,n=V.AttvalBegin;break;default:throw new ht("Expected =",e,t)}break;case V.AttvalBegin:switch(a){case lt.CharCodeDoubleQuote:case lt.CharCodeSingleQuote:h="",r=V.AttribVal,o=t+1,p=a}break;case V.AttribVal:switch(a){case lt.CharCodeAmp:h+=e.substr(o,t-o),r=V.Escape,l=V.AttribVal,o=t+1;break;default:if(a===p){h+=e.substr(o,t-o);let s=h;h="",c.attributes.set(d,s),r=V.IgnoreSpaces,n=V.Body}}break;case V.Childs:o=t=lt.parse(e,t,c),r=V.Begin;break;case V.WaitEnd:switch(a){case lt.CharCodeGreaterThan:r=V.Begin;break;default:throw new ht("Expected >",e,t)}break;case V.WaitEndRet:switch(a){case lt.CharCodeGreaterThan:return t;default:throw new ht("Expected >",e,t)}case V.Close:if(!lt.isValidChar(a)){if(o===t)throw new ht("Expected node name",e,t);if(e.substr(o,t-o)!==s.localName)throw new ht("Expected </"+s.localName+">",e,t);r=V.IgnoreSpaces,n=V.WaitEndRet;continue}break;case V.Comment:a===lt.CharCodeMinus&&e.charCodeAt(t+1)===lt.CharCodeMinus&&e.charCodeAt(t+2)===lt.CharCodeGreaterThan&&(t+=2,r=V.Begin);break;case V.Doctype:if(a===lt.CharCodeBrackedOpen)u++;else if(a===lt.CharCodeBrackedClose)u--;else if(a===lt.CharCodeGreaterThan&&0===u){let i=new ot;i.nodeType=G.DocumentType,i.value=e.substr(o,t-o),s.addChild(i),r=V.Begin}break;case V.Header:a===lt.CharCodeQuestion&&e.charCodeAt(t+1)===lt.CharCodeGreaterThan&&(t++,r=V.Begin);break;case V.Escape:if(a===lt.CharCodeSemi){let s=e.substr(o,t-o);if(s.charCodeAt(0)===lt.CharCodeSharp){let e=s.charCodeAt(1)===lt.CharCodeLowerX?parseInt("0"+s.substr(1,s.length-1)):parseInt(s.substr(1,s.length-1));h+=String.fromCharCode(e)}else lt.Escapes.has(s)?h+=lt.Escapes.get(s):h+=null===(i="&"+s+";")||void 0===i?void 0:i.toString();o=t+1,r=l}else lt.isValidChar(a)||a===lt.CharCodeSharp||(h+="&",h+=e.substr(o,t-o),o=--t+1,r=l)}t++}if(r===V.Begin&&(o=t,r=V.Pcdata),r===V.Pcdata){if(t!==o){h+=e.substr(o,t-o);let i=new ot;i.nodeType=G.Text,i.value=h,s.addChild(i)}return t}if(r===V.Escape&&l===V.Pcdata){h+="&",h+=e.substr(o,t-o);let i=new ot;return i.nodeType=G.Text,i.value=h,s.addChild(i),t}throw new ht("Unexpected end",e,t)}static isValidChar(e){return e>=lt.CharCodeLowerA&&e<=lt.CharCodeLowerZ||e>=lt.CharCodeUpperA&&e<=lt.CharCodeUpperZ||e>=lt.CharCode0&&e<=lt.CharCode9||e===lt.CharCodeColon||e===lt.CharCodeDot||e===lt.CharCodeUnderscore||e===lt.CharCodeMinus}}lt.CharCodeLF=10,lt.CharCodeTab=9,lt.CharCodeCR=13,lt.CharCodeSpace=32,lt.CharCodeLowerThan=60,lt.CharCodeAmp=38,lt.CharCodeBrackedClose=93,lt.CharCodeBrackedOpen=91,lt.CharCodeGreaterThan=62,lt.CharCodeExclamation=33,lt.CharCodeUpperD=68,lt.CharCodeLowerD=100,lt.CharCodeMinus=45,lt.CharCodeQuestion=63,lt.CharCodeSlash=47,lt.CharCodeEquals=61,lt.CharCodeDoubleQuote=34,lt.CharCodeSingleQuote=39,lt.CharCodeSharp=35,lt.CharCodeLowerX=120,lt.CharCodeLowerA=97,lt.CharCodeLowerZ=122,lt.CharCodeUpperA=65,lt.CharCodeUpperZ=90,lt.CharCode0=48,lt.CharCode9=57,lt.CharCodeColon=58,lt.CharCodeDot=46,lt.CharCodeUnderscore=95,lt.CharCodeSemi=59,lt.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class ct{constructor(e,t){this._result=[],this._indention=e,this._xmlHeader=t,this._currentIndention="",this._isStartOfLine=!0}static write(e,t,s){const i=new ct(t,s);return i.writeNode(e),i.toString()}writeNode(e){switch(e.nodeType){case G.None:break;case G.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===G.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case G.Text:e.value&&this.write(e.value);break;case G.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case G.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case G.DocumentType:this.write(`<!DOCTYPE ${e.value}>`)}}unindend(){this._currentIndention=this._currentIndention.substr(0,this._currentIndention.length-this._indention.length)}indent(){this._currentIndention+=this._indention}writeAttributeValue(e){for(let t=0;t<e.length;t++){const s=e.charAt(t);switch(s){case"<":this._result.push("&lt;");break;case">":this._result.push("&gt;");break;case"&":this._result.push("&amp;");break;case"'":this._result.push("&apos;");break;case'"':this._result.push("&quot;");break;default:this._result.push(s)}}}write(e){this._isStartOfLine&&this._result.push(this._currentIndention),this._result.push(e),this._isStartOfLine=!1}writeLine(e=null){e&&this.write(e),this._indention.length>0&&!this._isStartOfLine&&(this._result.push("\n"),this._isStartOfLine=!0)}toString(){return this._result.join("").trimRight()}}class dt extends ot{constructor(){super(),this.nodeType=G.Document}parse(e){lt.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return ct.write(this,e,t)}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(H||(H={}));class ut{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=u.Quarter}}class pt{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return this.path+";"+this.name+";"+this.role}}class gt{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1}parseXml(e,t){this._masterTrackAutomations=new Map,this._automationsPerTrackIdAndBarIndex=new Map,this._tracksMapping=[],this._tracksById=new Map,this._masterBars=[],this._barsOfMasterBar=[],this._voicesOfBar=new Map,this._barsById=new Map,this._voiceById=new Map,this._beatsOfVoice=new Map,this._beatById=new Map,this._rhythmOfBeat=new Map,this._rhythmById=new Map,this._notesOfBeat=new Map,this._noteById=new Map,this._tappedNotes=new Map,this._lyricsByTrack=new Map,this._soundsByTrack=new Map,this._skipApplyLyrics=!1;let s=new dt;try{s.parse(e)}catch(e){throw new ge("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 ge("Root node of XML was not GPIF");this.score=new He;for(let e of t.childNodes)if(e.nodeType===G.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===G.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}}parseMasterTrackNode(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null);break;case"Tracks":this._tracksMapping=t.innerText.split(" ");break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,s){for(let i of e.childNodes)if(i.nodeType===G.Element)switch(i.localName){case"Automation":this.parseAutomation(i,t,s)}}parseAutomation(e,t,s){let i=null,a=!1,r=-1,n=0,o=0,h=null,l=0,c=null;for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Type":i=t.innerText;break;case"Linear":a="true"===t.innerText.toLowerCase();break;case"Bar":r=parseInt(t.innerText);break;case"Position":n=parseFloat(t.innerText);break;case"Value":if(t.firstElement&&t.firstElement.nodeType===G.CDATA)h=t.innerText;else{let e=t.innerText.split(" ");1===e.length?(o=parseFloat(e[0]),l=1):(o=parseFloat(e[0]),l=parseInt(e[1]))}break;case"Text":c=t.innerText}if(!i)return;let d=null;switch(i){case"Tempo":d=fe.buildTempoAutomation(a,n,o,l);break;case"Sound":h&&s&&s.has(h)&&(d=fe.buildInstrumentAutomation(a,n,s.get(h).program))}d&&(c&&(d.text=c),r>=0&&(t.has(r)||t.set(r,[]),t.get(r).push(d)))}parseTracksNode(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Track":this.parseTrack(t)}}parseTrack(e){this._articulationByName=new Map;let t=new Je;t.ensureStaveCount(1),t.staves[0].showStandardNotation=!0;let s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===G.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 Ue(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"Lyrics":this.parseLyrics(s,i);break;case"Properties":this.parseTrackProperties(t,i);break;case"GeneralMidi":case"MidiConnection":case"MIDISettings":this.parseGeneralMidi(t,i);break;case"Sounds":this.parseSounds(s,t,i);break;case"PlaybackState":let r=i.innerText;t.playbackInfo.isSolo="Solo"===r,t.playbackInfo.isMute="Mute"===r;break;case"PartSounding":this.parsePartSounding(t,i);break;case"Staves":this.parseStaves(t,i);break;case"Transpose":this.parseTranspose(t,i);break;case"RSE":this.parseRSE(t,i);break;case"Automations":this.parseTrackAutomations(s,i)}this._tracksById.set(s,t)}parseTrackAutomations(e,t){const s=new Map;this._automationsPerTrackIdAndBarIndex.set(e,s),this.parseAutomations(t,s,this._soundsByTrack.get(e))}parseNotationPatch(e,t){for(let s of t.childNodes)if(s.nodeType===G.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===G.Element)switch(s.localName){case"Type":switch(s.innerText){case"drumKit":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===G.Element)switch(s.localName){case"Element":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===G.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===G.Element)switch(i.localName){case"Articulation":this.parseArticulation(e,i,s)}}parseArticulation(e,t,s){const i=new ve;i.outputMidiNumber=-1,i.elementType=s;let a="";for(let e of t.childNodes)if(e.nodeType===G.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":i.techniqueSymbolPlacement=E.Bottom;break;case"inside":i.techniqueSymbolPlacement=E.Middle;break;case"above":i.techniqueSymbolPlacement=E.Bottom;break;case"below":i.techniqueSymbolPlacement=E.Top}break;case"Noteheads":const s=t.split(" ");s.length>=1&&(i.noteHeadDefault=this.parseNoteHead(s[0])),s.length>=2&&(i.noteHeadHalf=this.parseNoteHead(s[1])),s.length>=3&&(i.noteHeadWhole=this.parseNoteHead(s[2])),i.noteHeadHalf==N.None&&(i.noteHeadHalf=i.noteHeadDefault),i.noteHeadWhole==N.None&&(i.noteHeadWhole=i.noteHeadDefault);break;case"StaffLine":t.length>0&&(i.staffLine=parseInt(t))}}-1!==i.outputMidiNumber?(e.percussionArticulations.push(i),a.length>0&&this._articulationByName.set(a,i)):a.length>0&&this._articulationByName.has(a)&&(this._articulationByName.get(a).staffLine=i.staffLine)}parseTechniqueSymbol(e){switch(e){case"pictEdgeOfCymbal":return N.PictEdgeOfCymbal;case"articStaccatoAbove":return N.ArticStaccatoAbove;case"noteheadParenthesis":return N.NoteheadParenthesis;case"stringsUpBow":return N.StringsUpBow;case"stringsDownBow":return N.StringsDownBow;case"guitarGolpe":return N.GuitarGolpe;default:return N.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return N.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return N.NoteheadDoubleWhole;case"noteheadWhole":return N.NoteheadWhole;case"noteheadHalf":return N.NoteheadHalf;case"noteheadBlack":return N.NoteheadBlack;case"noteheadNull":return N.NoteheadNull;case"noteheadXOrnate":return N.NoteheadXOrnate;case"noteheadTriangleUpWhole":return N.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return N.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return N.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return N.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return N.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return N.NoteheadDiamondWhiteWide;case"noteheadCircleX":return N.NoteheadCircleX;case"noteheadXWhole":return N.NoteheadXWhole;case"noteheadXHalf":return N.NoteheadXHalf;case"noteheadXBlack":return N.NoteheadXBlack;case"noteheadParenthesis":return N.NoteheadParenthesis;case"noteheadSlashedBlack2":return N.NoteheadSlashedBlack2;case"noteheadCircleSlash":return N.NoteheadCircleSlash;case"noteheadHeavyX":return N.NoteheadHeavyX;case"noteheadHeavyXHat":return N.NoteheadHeavyXHat;default:return Be.warning("GPIF","Unknown notehead symbol",e),N.None}}parseStaves(e,t){let s=0;for(let i of t.childNodes)if(i.nodeType===G.Element)switch(i.localName){case"Staff":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===G.Element)switch(s.localName){case"Properties":this.parseStaffProperties(e,s)}}parseStaffProperties(e,t){for(let s of t.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"Property":this.parseStaffProperty(e,s)}}parseStaffProperty(e,t){switch(t.getAttribute("name")){case"Tuning":for(let s of t.childNodes)if(s.nodeType===G.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===G.Element)switch(e.localName){case"Line":s.push(this.parseLyricsLine(e))}this._lyricsByTrack.set(e,s)}parseLyricsLine(e){let t=new Ae;for(let s of e.childNodes)if(s.nodeType===G.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===G.Element)switch(t.localName){case"Item":this.parseDiagramItemForTrack(e,t)}}parseDiagramCollectionForStaff(e,t){let s=t.findChildElement("Items");for(let t of s.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Item":this.parseDiagramItemForStaff(e,t)}}parseDiagramItemForTrack(e,t){let s=new Re,i=t.getAttribute("id");for(let t of e.staves)t.addChord(i,s);this.parseDiagramItemForChord(s,t)}parseDiagramItemForStaff(e,t){let s=new Re,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"),i=parseInt(s.getAttribute("stringCount")),a=parseInt(s.getAttribute("baseFret"));e.firstFret=a+1;for(let t=0;t<i;t++)e.strings.push(-1);for(let t of s.childNodes)if(t.nodeType===G.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===G.Element)switch(s.localName){case"Position":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===G.Element)switch(s.localName){case"Property":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===G.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===G.Element)switch(i.localName){case"Sound":this.parseSound(e,t,i)}}parseSound(e,t,s){const i=new pt;for(let e of s.childNodes)if(e.nodeType===G.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===G.Element)switch(s.localName){case"Program":e.program=parseInt(s.innerText)}}parsePartSounding(e,t){for(let s of t.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"TranspositionPitch":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===G.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===G.Element)switch(s.localName){case"ChannelStrip":this.parseChannelStrip(e,s)}}parseChannelStrip(e,t){for(let s of t.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"Parameters":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===G.Element)switch(t.localName){case"MasterBar":this.parseMasterBar(t)}}parseMasterBar(e){let t=new Oe;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"Time":let e=s.innerText.split("/");t.timeSignatureNumerator=parseInt(e[0]),t.timeSignatureDenominator=parseInt(e[1]);break;case"DoubleBar":t.isDoubleBar=!0;break;case"Section":t.section=new We,t.section.marker=s.findChildElement("Letter").innerText,t.section.text=s.findChildElement("Text").innerText;break;case"Repeat":"true"===s.getAttribute("start").toLowerCase()&&(t.isRepeatStart=!0),"true"===s.getAttribute("end").toLowerCase()&&s.getAttribute("count")&&(t.repeatCount=parseInt(s.getAttribute("count")));break;case"AlternateEndings":let i=s.innerText.split(" "),a=0;for(let e=0;e<i.length;e++)a|=1<<-1+parseInt(i[e]);t.alternateEndings=a;break;case"Bars":this._barsOfMasterBar.push(s.innerText.split(" "));break;case"TripletFeel":switch(s.innerText){case"NoTripletFeel":t.tripletFeel=D.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=D.Triplet8th;break;case"Triplet16th":t.tripletFeel=D.Triplet16th;break;case"Dotted8th":t.tripletFeel=D.Dotted8th;break;case"Dotted16th":t.tripletFeel=D.Dotted16th;break;case"Scottish8th":t.tripletFeel=D.Scottish8th;break;case"Scottish16th":t.tripletFeel=D.Scottish16th}break;case"Key":t.keySignature=parseInt(s.findChildElement("AccidentalCount").innerText);let r=s.findChildElement("Mode");if(r)switch(r.innerText.toLowerCase()){case"major":t.keySignatureType=I.Major;break;case"minor":t.keySignatureType=I.Minor}break;case"Fermatas":this.parseFermatas(t,s)}this._masterBars.push(t)}parseFermatas(e,t){for(let s of t.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"Fermata":this.parseFermata(e,s)}}parseFermata(e,t){let s=0,i=new nt;for(let e of t.childNodes)if(e.nodeType===G.Element)switch(e.localName){case"Type":switch(e.innerText){case"Short":i.type=O.Short;break;case"Medium":i.type=O.Medium;break;case"Long":i.type=O.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])*ye.QuarterTime|0}}e.addFermata(s,i)}parseBars(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Bar":this.parseBar(t)}}parseBar(e){let t=new me,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===G.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}}this._barsById.set(s,t)}parseVoices(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Voice":this.parseVoice(t)}}parseVoice(e){let t=new Qe,s=e.getAttribute("id");for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Beats":this._beatsOfVoice.set(s,t.innerText.split(" "))}this._voiceById.set(s,t)}parseBeats(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Beat":this.parseBeat(t)}}parseBeat(e){let t=new De,s=e.getAttribute("id");for(let i of e.childNodes)if(i.nodeType===G.Element)switch(i.localName){case"Notes":this._notesOfBeat.set(s,i.innerText.split(" "));break;case"Rhythm":this._rhythmOfBeat.set(s,i.getAttribute("ref"));break;case"Fadding":"FadeIn"===i.innerText&&(t.fadeIn=!0);break;case"Tremolo":switch(i.innerText){case"1/2":t.tremoloSpeed=u.Eighth;break;case"1/4":t.tremoloSpeed=u.Sixteenth;break;case"1/8":t.tremoloSpeed=u.ThirtySecond}break;case"Chord":t.chordId=i.innerText;break;case"Hairpin":switch(i.innerText){case"Crescendo":t.crescendo=d.Crescendo;break;case"Decrescendo":t.crescendo=d.Decrescendo}break;case"Arpeggio":"Up"===i.innerText?t.brushType=c.ArpeggioUp:t.brushType=c.ArpeggioDown;break;case"Properties":this.parseBeatProperties(i,t);break;case"XProperties":this.parseBeatXProperties(i,t);break;case"FreeText":t.text=i.innerText;break;case"TransposedPitchStemOrientation":switch(i.innerText){case"Upward":t.preferredBeamDirection=H.Up;break;case"Downward":t.preferredBeamDirection=H.Down}break;case"Dynamic":switch(i.innerText){case"PPP":t.dynamics=p.PPP;break;case"PP":t.dynamics=p.PP;break;case"P":t.dynamics=p.P;break;case"MP":t.dynamics=p.MP;break;case"MF":t.dynamics=p.MF;break;case"F":t.dynamics=p.F;break;case"FF":t.dynamics=p.FF;break;case"FFF":t.dynamics=p.FFF}break;case"GraceNotes":switch(i.innerText){case"OnBeat":t.graceType=g.OnBeat;break;case"BeforeBeat":t.graceType=g.BeforeBeat}break;case"Legato":"true"===i.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":let e=new be(0,0);e.value=this.toBendValue(parseFloat(i.getAttribute("originValue"))),e.offset=this.toBendOffset(parseFloat(i.getAttribute("originOffset"))),t.addWhammyBarPoint(e);let a=new be(0,0);a.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),a.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);let r=new be(0,0);r.value=this.toBendValue(parseFloat(i.getAttribute("middleValue"))),r.offset=this.toBendOffset(parseFloat(i.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);let o=new be(0,0);o.value=this.toBendValue(parseFloat(i.getAttribute("destinationValue"))),o.offset=this.toBendOffset(parseFloat(i.getAttribute("destinationOffset"))),t.addWhammyBarPoint(o);break;case"Ottavia":switch(i.innerText){case"8va":t.ottava=n._8va;break;case"8vb":t.ottava=n._8vb;break;case"15ma":t.ottava=n._15ma;break;case"15mb":t.ottava=n._15mb}break;case"Lyrics":t.lyrics=this.parseBeatLyrics(i),this._skipApplyLyrics=!0}this._beatById.set(s,t)}parseBeatLyrics(e){const t=[];for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"Line":t.push(s.innerText)}return t}parseBeatXProperties(e,t){for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"XProperty":let e=0;switch(s.getAttribute("id")){case"1124204545":e=parseInt(s.findChildElement("Int").innerText),t.invertBeamDirection=1===e;break;case"687935489":e=parseInt(s.findChildElement("Int").innerText),t.brushDuration=e}}}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===G.Element)switch(h.localName){case"Property":switch(h.getAttribute("name")){case"Brush":"Up"===h.findChildElement("Direction").innerText?t.brushType=c.BrushUp:t.brushType=c.BrushDown;break;case"PickStroke":"Up"===h.findChildElement("Direction").innerText?t.pickStroke=x.Up:t.pickStroke=x.Down;break;case"Slapped":h.findChildElement("Enable")&&(t.slap=!0);break;case"Popped":h.findChildElement("Enable")&&(t.pop=!0);break;case"VibratoWTremBar":switch(h.findChildElement("Strength").innerText){case"Wide":t.vibrato=w.Wide;break;case"Slight":t.vibrato=w.Slight}break;case"WhammyBar":s=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":i||(i=new be(0,0)),i.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":i||(i=new be(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 be(be.MaxPosition,0)),o.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new be(0,0)),o.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText))}}s&&(i||(i=new be(0,0)),o||(o=new be(be.MaxPosition,0)),t.addWhammyBarPoint(i),r&&a&&t.addWhammyBarPoint(new be(r,a)),n&&a&&t.addWhammyBarPoint(new be(n,a)),r||n||!a||t.addWhammyBarPoint(new be(be.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Note":this.parseNote(t)}}parseNote(e){let t=new Pe,s=e.getAttribute("id");for(let a of e.childNodes)if(a.nodeType===G.Element)switch(a.localName){case"Properties":this.parseNoteProperties(a,t,s);break;case"AntiAccent":"normal"===a.innerText.toLowerCase()&&(t.isGhost=!0);break;case"LetRing":t.isLetRing=!0;break;case"Trill":t.trillValue=parseInt(a.innerText),t.trillSpeed=u.Sixteenth;break;case"Accent":let e=parseInt(a.innerText);0!=(1&e)&&(t.isStaccato=!0),0!=(4&e)&&(t.accentuated=i.Heavy),0!=(8&e)&&(t.accentuated=i.Normal);break;case"Tie":"true"===a.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(a.innerText){case"Slight":t.vibrato=w.Slight;break;case"Wide":t.vibrato=w.Wide}break;case"LeftFingering":switch(t.isFingering=!0,a.innerText){case"P":t.leftHandFinger=f.Thumb;break;case"I":t.leftHandFinger=f.IndexFinger;break;case"M":t.leftHandFinger=f.MiddleFinger;break;case"A":t.leftHandFinger=f.AnnularFinger;break;case"C":t.leftHandFinger=f.LittleFinger}break;case"RightFingering":switch(t.isFingering=!0,a.innerText){case"P":t.rightHandFinger=f.Thumb;break;case"I":t.rightHandFinger=f.IndexFinger;break;case"M":t.rightHandFinger=f.MiddleFinger;break;case"A":t.rightHandFinger=f.AnnularFinger;break;case"C":t.rightHandFinger=f.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=parseInt(a.innerText)}this._noteById.set(s,t)}parseNoteProperties(e,t,s){let i=!1,a=null,r=null,n=null,o=null,h=null,l=-1,c=-1;for(let d of e.childNodes)if(d.nodeType===G.Element)switch(d.localName){case"Property":switch(d.getAttribute("name")){case"String":t.string=parseInt(d.findChildElement("String").innerText)+1;break;case"Fret":t.fret=parseInt(d.findChildElement("Fret").innerText);break;case"Element":l=parseInt(d.findChildElement("Element").innerText);break;case"Variation":c=parseInt(d.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(s,!0);break;case"HarmonicType":let e=d.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=m.None;break;case"Natural":t.harmonicType=m.Natural;break;case"Artificial":t.harmonicType=m.Artificial;break;case"Pinch":t.harmonicType=m.Pinch;break;case"Tap":t.harmonicType=m.Tap;break;case"Semi":t.harmonicType=m.Semi;break;case"Feedback":t.harmonicType=m.Feedback}break;case"HarmonicFret":let u=d.findChildElement("HFret");u&&(t.harmonicValue=parseFloat(u.innerText));break;case"Muted":d.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":d.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=parseInt(d.findChildElement("Number").innerText),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=parseInt(d.findChildElement("Step").innerText);break;case"ConcertPitch":this.parseConcertPitch(d,t);break;case"Bended":i=!0;break;case"BendOriginValue":a||(a=new be(0,0)),a.value=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new be(0,0)),a.offset=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleValue":r=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleOffset1":n=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleOffset2":o=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationValue":h||(h=new be(be.MaxPosition,0)),h.value=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new be(0,0)),h.offset=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"HopoOrigin":d.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":let p=parseInt(d.findChildElement("Flags").innerText);0!=(1&p)?t.slideOutType=S.Shift:0!=(2&p)?t.slideOutType=S.Legato:0!=(4&p)?t.slideOutType=S.OutDown:0!=(8&p)&&(t.slideOutType=S.OutUp),0!=(16&p)?t.slideInType=b.IntoFromBelow:0!=(32&p)&&(t.slideInType=b.IntoFromAbove),0!=(64&p)?t.slideOutType=S.PickSlideDown:0!=(128&p)&&(t.slideOutType=S.PickSlideUp)}}i&&(a||(a=new be(0,0)),h||(h=new be(be.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new be(n,r)),o&&r&&t.addBendPoint(new be(o,r)),n||o||!r||t.addBendPoint(new be(be.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==c&&(t.percussionArticulation=xe.articulationFromElementVariation(l,c))}parseConcertPitch(e,t){const s=e.findChildElement("Pitch");if(s)for(let e of s.childNodes)if(e.nodeType===G.Element)switch(e.localName){case"Accidental":switch(e.innerText){case"x":t.accidentalMode=y.ForceDoubleSharp;break;case"#":t.accidentalMode=y.ForceSharp;break;case"b":t.accidentalMode=y.ForceFlat;break;case"bb":t.accidentalMode=y.ForceDoubleFlat}}}toBendValue(e){return e*gt.BendPointValueFactor|0}toBendOffset(e){return e*gt.BendPointPositionFactor}parseRhythms(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Rhythm":this.parseRhythm(t)}}parseRhythm(e){let t=new ut,s=e.getAttribute("id");t.id=s;for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"NoteValue":switch(s.innerText){case"Long":t.value=u.QuadrupleWhole;break;case"DoubleWhole":t.value=u.DoubleWhole;break;case"Whole":t.value=u.Whole;break;case"Half":t.value=u.Half;break;case"Quarter":t.value=u.Quarter;break;case"Eighth":t.value=u.Eighth;break;case"16th":t.value=u.Sixteenth;break;case"32nd":t.value=u.ThirtySecond;break;case"64th":t.value=u.SixtyFourth;break;case"128th":t.value=u.OneHundredTwentyEighth;break;case"256th":t.value=u.TwoHundredFiftySixth}break;case"PrimaryTuplet":t.tupletNumerator=parseInt(s.getAttribute("num")),t.tupletDenominator=parseInt(s.getAttribute("den"));break;case"AugmentationDot":t.dots=parseInt(s.getAttribute("count"))}this._rhythmById.set(s,t)}buildModel(){for(let e=0,t=this._masterBars.length;e<t;e++){let t=this._masterBars[e];this.score.addMasterBar(t)}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e);this.score.addTrack(t)}for(let e of this._barsOfMasterBar){let t=0;for(let s=0,i=0;s<e.length&&i<this.score.tracks.length;s++){let a=e[s];if(a!==gt.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!==gt.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!==gt.InvalidId){let t=Me.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!==gt.InvalidId){const e=Fe.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 Qe;e.addVoice(t);let s=new De;s.isEmpty=!0,s.duration=u.Quarter,t.addBeat(s)}t===s.staves.length-1?(i++,t=0):t++}else i++}}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e),s=!1;for(const e of t.staves)if(e.isPercussion){s=!0;break}if(s||(t.percussionArticulations=[]),this._automationsPerTrackIdAndBarIndex.has(e)){const s=this._automationsPerTrackIdAndBarIndex.get(e);for(const[e,i]of s)if(t.staves.length>0&&e<t.staves[0].bars.length){const s=t.staves[0].bars[e];if(s.voices.length>0&&s.voices[0].beats.length>0){const e=s.voices[0].beats[0];for(const t of i)e.automations.push(t)}}}}for(const[e,t]of this._masterTrackAutomations){let s=this.score.masterBars[e];for(let i=0,r=t.length;i<r;i++){let r=t[i];r.type===a.Tempo&&(0===e&&(this.score.tempo=0|r.value,r.text&&(this.score.tempoLabel=r.text)),s.tempoAutomation=r)}}}}gt.InvalidId="-1",gt.BendPointPositionFactor=be.MaxPosition/100,gt.BendPointValueFactor=.04;class ft{constructor(){this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class mt{constructor(){this.isMultiRest=!1,this.tracks=[]}}class yt{constructor(e){this.parts=[],this.zoomLevel=0,this.layout=0;let t=$e.fromBuffer(e),s=Ke.readInt32BE(t);for(let e=0;e<s;e++){let e=new mt;this.parts.push(e),e.isMultiRest=st.gpReadBool(t);let s=Ke.readInt32BE(t);for(let i=0;i<s;i++){let s=t.readByte();0===s&&(s=1);let i=new ft;i.showStandardNotation=0!=(1&s),i.showTablature=0!=(2&s),i.showSlash=0!=(4&s),e.tracks.push(i)}}}apply(e){let t=0,s=0;for(let i of this.parts)for(let a of i.tracks){if(s<e.tracks.length){let i=e.tracks[s];if(t<i.staves.length){let e=i.staves[t];e.showTablature=a.showTablature,e.showStandardNotation=a.showStandardNotation}}s++,s>=e.tracks.length&&(t++,s=0)}}static writeForScore(e){const t=$e.withCapacity(128),s=[new mt];for(const t of e.tracks)for(const e of t.staves){const t=new ft;if(t.showStandardNotation=e.showStandardNotation,t.showTablature=e.showTablature,0===e.index)s[0].tracks.push(t);else{let e=new mt;e.tracks.push(t),s.push(e)}}Ke.writeInt32BE(t,s.length);for(const e of s){t.writeByte(e.isMultiRest?1:0),Ke.writeInt32BE(t,e.tracks.length);for(const s of e.tracks){let e=0;s.showStandardNotation&&(e|=1),s.showTablature&&(e|=2),s.showSlash&&(e|=4),t.writeByte(e)}}return t.toArray()}}class bt{}class St extends bt{constructor(e){super(),this.n=e}}class wt extends bt{constructor(e,t){super(),this.left=e,this.right=t}}class _t extends bt{constructor(e,t){super(),this.n=e,this.table=t}}class Bt{static make(e,t,s,i){let a=[],r=[];if(i>32)throw new ze("Invalid huffman");for(let e=0;e<i;e++)a.push(0),r.push(0);for(let r=0;r<s;r++){let s=e[r+t];if(s>=i)throw new ze("Invalid huffman");a[s]++}let n=0;for(let e=1;e<i-1;e++)n=n+a[e]<<1,r[e]=n;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 Bt.treeCompress(new wt(Bt.treeMake(o,i,0,1),Bt.treeMake(o,i,1,1)))}static treeMake(e,t,s,i){if(i>t)throw new ze("Invalid huffman");let a=s<<5|i;return e.has(a)?new St(e.get(a)):(s<<=1,i+=1,new wt(Bt.treeMake(e,t,s,i),Bt.treeMake(e,t,1|s,i)))}static treeCompress(e){let t=Bt.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof wt)return new wt(Bt.treeCompress(e.left),Bt.treeCompress(e.right));throw new ze("assert")}let s=1<<t,i=[];for(let e=0;e<s;e++)i.push(new St(-1));return Bt.treeWalk(i,0,0,t,e),new _t(t,i)}static treeWalk(e,t,s,i,a){a instanceof wt&&i>0?(Bt.treeWalk(e,t,s+1,i-1,a.left),Bt.treeWalk(e,t|1<<s,s+1,i-1,a.right)):e[t]=Bt.treeCompress(a)}static treeDepth(e){if(e instanceof St)return 0;if(e instanceof _t)throw new ze("assert");if(e instanceof wt){let t=Bt.treeDepth(e.left),s=Bt.treeDepth(e.right);return 1+(t<s?t:s)}return 0}}!function(e){e[e.Head=0]="Head",e[e.Block=1]="Block",e[e.CData=2]="CData",e[e.Flat=3]="Flat",e[e.Crc=4]="Crc",e[e.Dist=5]="Dist",e[e.DistOne=6]="DistOne",e[e.Done=7]="Done"}(W||(W={}));class Tt{constructor(){this.buffer=new Uint8Array(Tt.BufferSize),this.pos=0}slide(){let e=new Uint8Array(Tt.BufferSize);this.pos-=Tt.Size,e.set(this.buffer.subarray(Tt.Size,Tt.Size+this.pos),0),this.buffer=e}addBytes(e,t,s){this.pos+s>Tt.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+s),this.pos),this.pos+=s}addByte(e){this.pos===Tt.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}Tt.Size=32768,Tt.BufferSize=65536;class kt{constructor(e){this._nbits=0,this._bits=0,this._state=W.Block,this._isFinal=!1,this._huffman=kt._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new Tt,this._input=e;for(let e=0;e<19;e++)this._lengths.push(-1)}static buildFixedHuffman(){let e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return Bt.make(e,0,288,10)}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 W.Head:let e=this._input.readByte();if(8!==(15&e))throw new ze("Invalid data");let t=this._input.readByte(),s=0!=(32&t);if(((e<<8)+t)%31!=0)throw new ze("Invalid data");if(s)throw new ze("Unsupported dictionary");return this._state=W.Block,!0;case W.Crc:return this._state=W.Done,!0;case W.Done:return!1;case W.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:if(this._len=Ke.readUInt16LE(this._input),Ke.readUInt16LE(this._input)!==65535-this._len)throw new ze("Invalid data");this._state=W.Flat;let e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=kt._fixedHuffman,this._huffdist=null,this._state=W.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[kt.CodeLengthsPos[e]]=this.getBits(3);for(let e=i;e<19;e++)this._lengths[kt.CodeLengthsPos[e]]=0;this._huffman=Bt.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=Bt.make(a,t,s,16),this._huffman=Bt.make(a,0,t,16),this._state=W.CData,!0;default:throw new ze("Invalid data")}case W.Flat:{let e=this._len<this._needed?this._len:this._needed,t=Ke.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?W.Crc:W.Block),this._needed>0}case W.DistOne:{let e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=W.CData),this._needed>0}case W.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=W.CData),this._needed>0;case W.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?W.Crc:W.Block,!0;{i=i-257&255;let e=kt.LenExtraBitsTbl[i];if(-1===e)throw new ze("Invalid data");this._len=kt.LenBaseValTbl[i]+this.getBits(e);let t=this._huffdist,s=t?this.applyHuffman(t):this.getRevBits(5);if(e=kt.DistExtraBitsTbl[s],-1===e)throw new ze("Invalid data");if(this._dist=kt.DistBaseValTbl[s]+this.getBits(e),this._dist>this._window.available())throw new ze("Invalid data");return this._state=1===this._dist?W.DistOne:W.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==(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 ze("Invalid data");for(;s<r;)e[s]=i,s++;break;case 17:if(s+=3+this.getBits(3),s>t)throw new ze("Invalid data");break;case 18:if(s+=11+this.getBits(7),s>t)throw new ze("Invalid data");break;default:throw new ze("Invalid data")}}}applyHuffman(e){if(e instanceof St)return e.n;if(e instanceof wt)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof _t)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new ze("Invalid data")}}kt.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],kt.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],kt.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],kt.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],kt.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],kt._fixedHuffman=kt.buildFixedHuffman();class vt{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}}vt.OptionalDataDescriptorSignature=134695760,vt.CompressionMethodDeflate=8,vt.LocalFileHeaderSignature=67324752,vt.CentralFileHeaderSignature=33639248,vt.EndOfCentralDirSignature=101010256;class xt{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(Ke.readInt32LE(e)!==vt.LocalFileHeaderSignature)return null;Ke.readUInt16LE(e);let t=Ke.readUInt16LE(e),s=Ke.readUInt16LE(e),i=0!==s;if(i&&s!==vt.CompressionMethodDeflate)return null;Ke.readInt16LE(this._readable),Ke.readInt16LE(this._readable),Ke.readInt32LE(e),Ke.readInt32LE(e);let a,r=Ke.readInt32LE(e),n=Ke.readInt16LE(e),o=Ke.readInt16LE(e),h=Ke.toString(Ke.readByteArray(e,n),"utf-8");if(e.skip(o),i){let e=$e.empty(),t=new kt(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=Ke.readByteArray(this._readable,r);if(0!=(8&t)){Ke.readInt32LE(this._readable)===vt.OptionalDataDescriptorSignature&&Ke.readInt32LE(this._readable),Ke.readInt32LE(this._readable),Ke.readInt32LE(this._readable)}return new vt(h,a)}}class Nt extends ue{get name(){return"Guitar Pro 7"}constructor(){super()}readScore(){Be.debug(this.name,"Loading ZIP entries");let e,t=new xt(this.data);try{e=t.read()}catch(e){throw new ge("No Zip archive",e)}Be.debug(this.name,"Zip entries loaded");let s=null,i=null,a=null;for(let t of e)switch(t.fileName){case"score.gpif":s=Ke.toString(t.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=t.data;break;case"PartConfiguration":a=t.data}if(!s)throw new ge("No score.gpif found in zip archive");Be.debug(this.name,"Start Parsing score.gpif");let r=new gt;r.parseXml(s,this.settings),Be.debug(this.name,"score.gpif parsed");let n=r.score;if(i){Be.debug(this.name,"Start Parsing BinaryStylesheet"),new rt(i).apply(n),Be.debug(this.name,"BinaryStylesheet parsed")}if(a){Be.debug(this.name,"Start Parsing Part Configuration"),new yt(a).apply(n),Be.debug(this.name,"Part Configuration parsed")}return n}}class Pt extends pe{constructor(){super(s.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,Pt.prototype)}}class Et{constructor(e){this._currentByte=0,this._position=Et.ByteSize,this._source=e}readByte(){return this.readBits(8)}readBytes(e){const t=new Uint8Array(e);for(let s=0;s<e;s++)t[s]=255&this.readByte();return t}readBits(e){let t=0,s=e-1;for(;s>=0;)t|=this.readBit()<<s,s--;return t}readBitsReversed(e){let t=0;for(let s=0;s<e;s++)t|=this.readBit()<<s;return t}readBit(){if(this._position>=8){if(this._currentByte=this._source.readByte(),-1===this._currentByte)throw new Pt;this._position=0}const e=this._currentByte>>Et.ByteSize-this._position-1&1;return this._position++,e}readAll(){let e=$e.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof Pt))throw e}return e.toArray()}}Et.ByteSize=8;class Ct{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class Ft{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){let t=new Et(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){let s,i=$e.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 Pt))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 ge("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 Ct;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?$e.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]}}Ft.HeaderBcFs="BCFS",Ft.HeaderBcFz="BCFZ",Ft.ScoreGpif="score.gpif",Ft.BinaryStylesheet="BinaryStylesheet",Ft.PartConfiguration="PartConfiguration";class Lt extends ue{get name(){return"Guitar Pro 6"}constructor(){super()}readScore(){Be.debug(this.name,"Loading GPX filesystem");let e=new Ft;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration"),e.load(this.data),Be.debug(this.name,"GPX filesystem loaded");let t=null,s=null,i=null;for(let a of e.files)switch(a.fileName){case"score.gpif":t=Ke.toString(a.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=a.data;break;case"PartConfiguration":i=a.data}if(!t)throw new ge("No score.gpif found in GPX");Be.debug(this.name,"Start Parsing score.gpif");let a=new gt;a.parseXml(t,this.settings),Be.debug(this.name,"score.gpif parsed");let r=a.score;if(s){Be.debug(this.name,"Start Parsing BinaryStylesheet"),new rt(s).apply(r),Be.debug(this.name,"BinaryStylesheet parsed")}if(i){Be.debug(this.name,"Start Parsing Part Configuration"),new yt(i).apply(r),Be.debug(this.name,"Part Configuration parsed")}return r}}class Mt extends ue{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}get name(){return"MusicXML"}readScore(){this._trackById=new Map,this._partGroups=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._slurStarts=new Map;let e=Ke.toString(this.data.readAll(),this.settings.importer.encoding),t=new dt;try{t.parse(e)}catch(e){throw new ge("Unsupported format")}return this._score=new He,this._score.tempo=120,this.parseDom(t),this.settings.importer.mergePartGroupsInMusicXml&&this.mergePartGroups(),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}mergePartGroups(){let e=!1;for(const t of this._partGroups.values())t.length>1&&(this.mergeGroup(t),e=!0);if(e)for(let e=0;e<this._score.tracks.length;e++)this._score.tracks[e].index=e}mergeGroup(e){let t=e[0];for(let s=1;s<e.length;s++){let i=e[s];for(let e of i.staves)t.addStaff(e);let a=this._score.tracks.indexOf(i);this._score.tracks.splice(a,1)}}parseDom(e){let t=e.firstElement;if(!t)throw new ge("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":break;default:throw new ge("Unsupported format")}}parsePartwise(e){for(let t of e.childNodes)if(t.nodeType===G.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===G.Element)switch(t.localName){case"work-title":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===G.Element)switch(t.localName){case"measure":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 me;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)}if(r){let s=!1;for(let i of e.childNodes)if(i.nodeType===G.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);break;case"sound":break;case"barline":this.parseBarline(i,r)}}return!0}ensureVoices(e){for(;e.voices.length<this._maxVoices;){let t=new Qe;e.addVoice(t);let s=new De;s.isEmpty=!0,s.chordId=this._currentChord,t.addBeat(s)}}getOrCreateBeat(e,t,s){let i=0,a=e.getElementsByTagName("voice",!1);a.length>0&&(i=parseInt(a[0].innerText)-1);let r=this._previousBeatWasPulled;this._previousBeatWasPulled=!1;let n,o,h=e.getElementsByTagName("staff",!1),l=1;if(h.length>0){l=parseInt(h[0].innerText),(this._isBeamContinue||r)&&this._previousBeat.voice.bar.staff.index!==l-1&&(l=this._previousBeat.voice.bar.staff.index+1,this._previousBeatWasPulled=!0);let e=t[0].staff.track.index+"-"+l;this._voiceOfStaff.has(e)||this._voiceOfStaff.set(e,i)}l--,n=l<0?t[0]:l>=t.length?t[t.length-1]:t[l];let c=this.getOrCreateVoice(n,i);return s&&c.beats.length>0||1===c.beats.length&&c.isEmpty?o=c.beats[c.beats.length-1]:(o=new De,o.isEmpty=!1,c.addBeat(o)),this._isBeamContinue=!1,this._previousBeat=o,o}parseForward(e,t){let s=this.getOrCreateBeat(e,t,!1),i=parseInt(e.findChildElement("duration").innerText)*u.Quarter/this._divisionsPerQuarterNote,a=[u.SixtyFourth,u.ThirtySecond,u.Sixteenth,u.Eighth,u.Quarter,u.Half,u.Whole];for(let e of a)if(i>=e){s.duration=e,i-=e;break}s.isEmpty=!1}parseStaffDetails(e,t){for(let s of e.childNodes)if(s.nodeType===G.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===G.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=ke.getTuningForText(i+a)+r;for(let e of t.staves)e.tuning[e.tuning.length-s]=n}parseHarmony(e,t){let s=null,i="";for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"root":for(let e of t.childNodes)if(e.nodeType===G.Element)switch(e.localName){case"root-step":s=e.innerText;break;case"root-alter":switch(parseInt(t.innerText)){case-2:i=" bb";break;case-1:i=" b";break;case 0:i="";break;case 1:i=" #";break;case 2:i=" ##"}}}let a=new Re;a.name=s+i,this._currentChord=ke.newGuid();for(let e of t.staves)e.addChord(this._currentChord,a)}parseBarline(e,t){for(let s of e.childNodes)if(s.nodeType===G.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 Pe;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===G.Element)switch(t.localName){case"grace":i.graceType=g.BeforeBeat,i.duration=u.ThirtySecond;break;case"duration":if(i.isRest&&!r){switch(parseInt(t.innerText)){case 1:i.duration=u.Whole;break;case 2:i.duration=u.Half;break;case 4:i.duration=u.Quarter;break;case 8:i.duration=u.Eighth;break;case 16:i.duration=u.Sixteenth;break;case 32:i.duration=u.ThirtySecond;break;case 64:i.duration=u.SixtyFourth;break;default:i.duration=u.Quarter}}break;case"tie":this.parseTied(t,a);break;case"cue":case"instrument":break;case"type":i.duration=this.getDuration(t.innerText),i.graceType!==g.None&&i.duration<u.Sixteenth&&(i.duration=u.Eighth);break;case"dot":i.dots++;break;case"accidental":this.parseAccidental(t,a);break;case"time-modification":this.parseTimeModification(t,i);break;case"stem":break;case"notehead":"yes"===t.getAttribute("parentheses")&&(a.isGhost=!0);break;case"beam":"continue"===t.innerText&&(this._isBeamContinue=!0);break;case"notations":this.parseNotations(t,i,a);break;case"lyric":this.parseLyric(t,i);break;case"pitch":this.parsePitch(t,a);break;case"unpitched":this.parseUnpitched(t,a);break;case"rest":r="yes"===t.getAttribute("measure"),i.isEmpty=!1,i.notes=[],i.duration=u.Whole}if(a.isStringed)for(let e=0;e<i.notes.length;e++)if(i.notes[e].string===a.string&&i.notes[e]!==a){i.removeNote(a);break}}getDuration(e){switch(e){case"256th":case"128th":case"64th":return u.SixtyFourth;case"32nd":return u.ThirtySecond;case"16th":return u.Sixteenth;case"eighth":return u.Eighth;case"quarter":return u.Quarter;case"half":return u.Half;case"long":case"breve":case"whole":return u.Whole}return u.Quarter}parseLyric(e,t){for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"text":t.text?t.text+=" "+s.innerText:t.text=s.innerText}}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=y.ForceSharp;break;case"natural":t.accidentalMode=y.ForceNatural;break;case"flat":t.accidentalMode=y.ForceFlat}}parseTied(e,t){"start"===e.getAttribute("type")?this._tieStartIds.has(t.id)||(this._tieStartIds.set(t.id,!0),this._tieStarts.push(t)):"stop"===e.getAttribute("type")&&this._tieStarts.length>0&&!t.isTieDestination&&(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===G.Element)switch(i.localName){case"articulations":this.parseArticulations(i,s);break;case"tied":this.parseTied(i,s);break;case"slide":case"glissando":"start"===i.getAttribute("type")&&(s.slideOutType=S.Shift);break;case"dynamics":this.parseDynamics(i,t);break;case"technical":this.parseTechnical(i,s);break;case"ornaments":this.parseOrnaments(i,s);break;case"slur":let e=i.getAttribute("number");switch(e||(e="1"),i.getAttribute("type")){case"start":this._slurStarts.set(e,s);break;case"stop":if(this._slurStarts.has(e)){s.isSlurDestination=!0,this._slurStarts.get(e).slurDestination=s,s.slurOrigin=s}}}}parseOrnaments(e,t){for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"tremolo":switch(parseInt(s.innerText)){case 1:t.beat.tremoloSpeed=u.Eighth;break;case 2:t.beat.tremoloSpeed=u.Sixteenth;break;case 3:t.beat.tremoloSpeed=u.ThirtySecond}}}parseTechnical(e,t){for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"string":t.string=parseInt(s.innerText),-2147483648!==t.string&&(t.string=t.beat.voice.bar.staff.tuning.length-t.string+1);break;case"fret":t.fret=parseInt(s.innerText);break;case"down-bow":t.beat.pickStroke=x.Down;break;case"up-bow":t.beat.pickStroke=x.Up}-2147483648!==t.string&&-2147483648!==t.fret||(t.string=-1,t.fret=-1)}parseArticulations(e,t){for(let s of e.childNodes)switch(s.localName){case"accent":t.accentuated=i.Normal;break;case"strong-accent":t.accentuated=i.Heavy;break;case"staccato":case"detached-legato":t.isStaccato=!0}}parseDynamics(e,t){for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"p":t.dynamics=p.P;break;case"pp":t.dynamics=p.PP;break;case"ppp":t.dynamics=p.PPP;break;case"f":t.dynamics=p.F;break;case"ff":t.dynamics=p.FF;break;case"fff":t.dynamics=p.FFF;break;case"mp":t.dynamics=p.MP;break;case"mf":t.dynamics=p.MF}}parseTimeModification(e,t){for(let s of e.childNodes)if(s.nodeType===G.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===G.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+ke.getToneForText(s)+i;t.octave=r/12|0,t.tone=r-12*t.octave}parsePitch(e,t){let s="",i=0,a=0;for(let t of e.childNodes)if(t.nodeType===G.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+ke.getToneForText(s)+(0|i);t.octave=r/12|0,t.tone=r-12*t.octave}getOrCreateVoice(e,t){if(t<e.voices.length)return e.voices[t];for(let s=e.voices.length;s<=t;s++)e.addVoice(new Qe);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===G.Element)switch(s.localName){case"sound":let e=s.getAttribute("tempo");if(e){let s=new fe;s.isLinear=!0,s.type=a.Tempo,s.value=parseInt(e),t.tempoAutomation=s}break;case"direction-type":let i=s.firstElement;switch(i.localName){case"words":this._currentDirection=i.innerText;break;case"metronome":this.parseMetronome(i,t)}}}parseMetronome(e,t){let s=u.Quarter,i=120;for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"beat-unit":s=this.getDuration(t.innerText);break;case"per-minute":i=parseInt(t.innerText)}let r=new fe;r.type=a.Tempo,r.value=i*(s/4|0),t.tempoAutomation=r}parseAttributes(e,t,s,i){let a=0,r=!1;for(let n of e.childNodes)if(n.nodeType===G.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===G.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===G.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":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;break;default:t.clef=r.G2}}parseTime(e,t){"common"===e.getAttribute("symbol")&&(t.timeSignatureCommon=!0);let s=!1,i=!1;for(let a of e.childNodes)if(a.nodeType===G.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===G.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:M.C,t.keySignatureType="minor"===i?I.Minor:I.Major}getOrCreateMasterBar(e){if(e<this._score.masterBars.length)return this._score.masterBars[e];for(let t=this._score.masterBars.length;t<=e;t++){let e=new Oe;if(this._score.masterBars.length>0){let t=this._score.masterBars[this._score.masterBars.length-1];e.timeSignatureDenominator=t.timeSignatureDenominator,e.timeSignatureNumerator=t.timeSignatureNumerator,e.keySignature=t.keySignature,e.keySignatureType=t.keySignatureType}this._score.addMasterBar(e)}return this._score.masterBars[e]}parseIdentification(e){for(let t of e.childNodes)if(t.nodeType===G.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===G.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 Je;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===G.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===G.Element)switch(s.localName){case"midi-channel":t.playbackInfo.primaryChannel=parseInt(s.innerText);break;case"midi-program":t.playbackInfo.program=parseInt(s.innerText);break;case"volume":t.playbackInfo.volume=Math.floor(parseInt(s.innerText)/100*16);break;case"pan":t.playbackInfo.balance=Math.max(0,Math.min(16,Math.floor((parseInt(s.innerText)+90)/180*16)))}}}!function(e){e[e.PerNotePitchBend=96]="PerNotePitchBend",e[e.NoteOff=128]="NoteOff",e[e.NoteOn=144]="NoteOn",e[e.NoteAftertouch=160]="NoteAftertouch",e[e.Controller=176]="Controller",e[e.ProgramChange=192]="ProgramChange",e[e.ChannelAftertouch=208]="ChannelAftertouch",e[e.PitchBend=224]="PitchBend",e[e.SystemExclusive=240]="SystemExclusive",e[e.SystemExclusive2=247]="SystemExclusive2",e[e.Meta=255]="Meta"}(z||(z={}));class It{constructor(e,t,s,i,a){this.track=e,this.tick=t,this.message=s|i<<8|a<<16}get channel(){return 15&this.message}get command(){return 240&this.message}get data1(){return(65280&this.message)>>8}set data1(e){this.message&=-65281,this.message|=e<<8}get data2(){return(16711680&this.message)>>16}set data2(e){this.message&=-16711681,this.message|=e<<16}writeTo(e){let t=new Uint8Array([this.message>>24&255,this.message>>16&255,this.message>>8&255,255&this.message]);e.write(t,0,t.length)}}!function(e){e[e.SequenceNumber=0]="SequenceNumber",e[e.TextEvent=1]="TextEvent",e[e.CopyrightNotice=2]="CopyrightNotice",e[e.SequenceOrTrackName=3]="SequenceOrTrackName",e[e.InstrumentName=4]="InstrumentName",e[e.LyricText=5]="LyricText",e[e.MarkerText=6]="MarkerText",e[e.CuePoint=7]="CuePoint",e[e.PatchName=8]="PatchName",e[e.PortName=9]="PortName",e[e.MidiChannel=32]="MidiChannel",e[e.MidiPort=33]="MidiPort",e[e.EndOfTrack=47]="EndOfTrack",e[e.Tempo=81]="Tempo",e[e.SmpteOffset=84]="SmpteOffset",e[e.TimeSignature=88]="TimeSignature",e[e.KeySignature=89]="KeySignature",e[e.SequencerSpecific=127]="SequencerSpecific"}(U||(U={}));class Dt extends It{get channel(){return-1}get command(){return 255&this.message}get metaStatus(){return this.data1}constructor(e,t,s,i,a){super(e,t,s,i,a)}}!function(e){e[e.SystemExclusive=240]="SystemExclusive",e[e.MtcQuarterFrame=241]="MtcQuarterFrame",e[e.SongPosition=242]="SongPosition",e[e.SongSelect=243]="SongSelect",e[e.TuneRequest=246]="TuneRequest",e[e.SystemExclusive2=247]="SystemExclusive2"}(X||(X={}));class Rt extends It{get channel(){return-1}get command(){return 255&this.message}constructor(e,t,s,i,a){super(e,t,s,i,a)}}!function(e){e[e.MetronomeTick=0]="MetronomeTick",e[e.Rest=1]="Rest"}(Y||(Y={}));class At extends Rt{constructor(e,t,s,i,a){super(e,t,s,255&i,i>>8&255),this.data=a}get isMetronome(){return this.manufacturerId==At.AlphaTabManufacturerId&&this.data[0]==Y.MetronomeTick}get metronomeNumerator(){return this.isMetronome?this.data[1]:-1}get metronomeDurationInTicks(){return this.isMetronome?Ke.decodeUInt32LE(this.data,2):-1}get metronomeDurationInMilliseconds(){return this.isMetronome?Ke.decodeUInt32LE(this.data,6):-1}get isRest(){return this.manufacturerId==At.AlphaTabManufacturerId&&this.data[0]==Y.Rest}get manufacturerId(){return this.message>>8}writeTo(e){e.writeByte(240);let t=this.data.length+2;e.writeByte(this.manufacturerId);let s=new Uint8Array([t>>24&255,t>>16&255,t>>8&255,255&t]);e.write(s,0,s.length),e.writeByte(247)}static encodeMetronome(e,t,s){const i=$e.withCapacity(10);return i.writeByte(Y.MetronomeTick),i.writeByte(e),Ke.writeInt32LE(i,t),Ke.writeInt32LE(i,s),i.toArray()}}At.AlphaTabManufacturerId=125;class Ot{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event instanceof At&&this.event.isMetronome}static newMetronomeEvent(e,t,s,i,a){const r=new At(0,t,z.SystemExclusive2,At.AlphaTabManufacturerId,At.encodeMetronome(s,i,a));return new Ot(e,r)}}class Gt{}Gt.DefaultChannelCount=17,Gt.MetronomeChannel=Gt.DefaultChannelCount-1,Gt.AudioChannels=2,Gt.MinVolume=0,Gt.MinProgram=0,Gt.MaxProgram=127,Gt.MinPlaybackSpeed=.125,Gt.MaxPlaybackSpeed=8,Gt.MaxPitchWheel=16384,Gt.MaxPitchWheel20=4294967296,Gt.DefaultPitchWheel=Gt.MaxPitchWheel/2,Gt.MicroBufferCount=32,Gt.MicroBufferSize=64;class Vt{constructor(e,t,s){this.bpm=e,this.ticks=t,this.time=s}}class Ht{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=ye.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class Wt{constructor(e){this._oneTimeState=null,this._countInState=null,this.isLooping=!1,this.playbackSpeed=1,this._synthesizer=e,this._mainState=new Ht,this._currentState=this._mainState}get isPlayingOneTimeMidi(){return this._currentState==this._oneTimeState}get isPlayingCountIn(){return this._currentState==this._countInState}get playbackRange(){return this._currentState.playbackRange}set playbackRange(e){this._currentState.playbackRange=e,e&&(this._currentState.playbackRangeStartTime=this.tickPositionToTimePositionWithSpeed(e.startTick,1),this._currentState.playbackRangeEndTime=this.tickPositionToTimePositionWithSpeed(e.endTick,1))}get currentTime(){return this._currentState.currentTime}get endTick(){return this._currentState.endTick}get endTime(){return this._currentState.endTime/this.playbackSpeed}seek(e){if(e*=this.playbackSpeed,this.playbackRange&&(e<this._currentState.playbackRangeStartTime?e=this._currentState.playbackRangeStartTime:e>this._currentState.playbackRangeEndTime&&(e=this._currentState.playbackRangeEndTime)),e>this._currentState.currentTime)this.silentProcess(e-this._currentState.currentTime);else if(e<this._currentState.currentTime){this._currentState.currentTime=0,this._currentState.eventIndex=0;let t=this._synthesizer.metronomeVolume;this._synthesizer.noteOffAll(!0),this._synthesizer.resetSoft(),this._synthesizer.setupMetronomeChannel(t),this.silentProcess(e)}}silentProcess(e){if(e<=0)return;let t=Date.now(),s=this._currentState.currentTime+e;for(;this._currentState.currentTime<s;)this.fillMidiEventQueueLimited(s-this._currentState.currentTime)&&this._synthesizer.synthesizeSilent(Gt.MicroBufferSize);this._currentState.currentTime=s;let i=Date.now()-t;Be.debug("Sequencer","Silent seek finished in "+i+"ms")}loadOneTimeMidi(e){this._oneTimeState=this.createStateFromFile(e),this._currentState=this._oneTimeState}loadMidi(e){this._mainState=this.createStateFromFile(e),this._currentState=this._mainState}createStateFromFile(e){const t=new Ht;t.tempoChanges=[],t.division=e.division,t.eventIndex=0,t.currentTime=0,t.synthData=[];let s=120,i=0,a=0,r=0,n=0,o=0,h=0,l=0,c=0;for(let d of e.events){let u=new Ot(t.synthData.length,d);t.synthData.push(u);let p=d.tick-c;if(i+=p,a+=p*(6e4/(s*e.division)),u.time=a,c=d.tick,n>0)for(;h<i;){let e=Ot.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(d.command===z.Meta&&d.data1===U.Tempo){s=6e7/d.value,t.tempoChanges.push(new Vt(s,i,a)),o=n*(6e4/(s*e.division))}else if(d.command===z.Meta&&d.data1===U.TimeSignature){let i=d,a=Math.pow(2,i.data[1]);r=i.data[0],n=t.division*(4/a)|0,o=n*(6e4/(s*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=i.data[0],t.firstTimeSignatureDenominator=a)}else if(d.command===z.ProgramChange){let e=d.channel;t.firstProgramEventPerChannel.has(e)||t.firstProgramEventPerChannel.set(e,u)}}return t.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),t.endTime=a,t.endTick=i,t}fillMidiEventQueue(){return this.fillMidiEventQueueLimited(-1)}fillMidiEventQueueLimited(e){let t=Gt.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}tickPositionToTimePosition(e){return this.tickPositionToTimePositionWithSpeed(e,this.playbackSpeed)}timePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(e,this.playbackSpeed)}tickPositionToTimePositionWithSpeed(e,t){let s=0,i=120,a=0;for(const t of this._currentState.tempoChanges){if(e<t.ticks)break;s=t.time,i=t.bpm,a=t.ticks}return s+=(e-=a)*(6e4/(i*this._currentState.division)),s/t}timePositionToTickPositionWithSpeed(e,t){e*=t;let s=0,i=120,a=0;for(const t of this._currentState.tempoChanges){if(e<t.time)break;s=t.ticks,i=t.bpm,a=t.time}return s+=(e-=a)/(6e4/(i*this._currentState.division))|0,s+1}get internalEndTime(){return this.playbackRange?this._currentState.playbackRangeEndTime:this._currentState.endTime}get isFinished(){return this._currentState.currentTime>=this.internalEndTime}stop(){this.playbackRange?this.playbackRange&&(this._currentState.currentTime=this.playbackRange.startTick,this._currentState.eventIndex=0):(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 Ht;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 Vt(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=Ot.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"}(q||(q={}));class zt{constructor(e,t){this.state=e,this.stopped=t}}class Ut{constructor(e,t,s,i,a){this.currentTime=e,this.endTime=t,this.currentTick=s,this.endTick=i,this.isSeek=a}}class Xt{constructor(){this.id="",this.size=0}static load(e,t,s){if(e&&Xt.HeaderSize>e.size)return!1;if(s.position+Xt.HeaderSize>=s.length)return!1;if(t.id=Ke.read8BitStringLength(s,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=Ke.readUInt32LE(s),e&&Xt.HeaderSize+t.size>e.size)return!1;e&&(e.size-=Xt.HeaderSize+t.size);let i="RIFF"===t.id,a="LIST"===t.id;return(!i||!e)&&(!i&&!a||(t.id=Ke.read8BitStringLength(s,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}Xt.HeaderSize=8;class Yt{constructor(){this.phdrs=[],this.pbags=[],this.pmods=[],this.pgens=[],this.insts=[],this.ibags=[],this.imods=[],this.igens=[],this.sHdrs=[],this.fontSamples=new Float32Array(0)}load(e){const t=new Xt,s=new Xt;if(!Xt.load(null,t,e)||"sfbk"!==t.id)throw new ze("Soundfont is not a valid Soundfont2 file");for(;Xt.load(t,s,e);){let t=new Xt;if("pdta"===s.id)for(;Xt.load(s,t,e);)switch(t.id){case"phdr":for(let s=0,i=t.size/Zt.SizeInFile|0;s<i;s++)this.phdrs.push(new Zt(e));break;case"pbag":for(let s=0,i=t.size/Kt.SizeInFile|0;s<i;s++)this.pbags.push(new Kt(e));break;case"pmod":for(let s=0,i=t.size/es.SizeInFile|0;s<i;s++)this.pmods.push(new es(e));break;case"pgen":for(let s=0,i=t.size/$t.SizeInFile|0;s<i;s++)this.pgens.push(new $t(e));break;case"inst":for(let s=0,i=t.size/jt.SizeInFile|0;s<i;s++)this.insts.push(new jt(e));break;case"ibag":for(let s=0,i=t.size/qt.SizeInFile|0;s<i;s++)this.ibags.push(new qt(e));break;case"imod":for(let s=0,i=t.size/Jt.SizeInFile|0;s<i;s++)this.imods.push(new Jt(e));break;case"igen":for(let s=0,i=t.size/Qt.SizeInFile|0;s<i;s++)this.igens.push(new Qt(e));break;case"shdr":for(let s=0,i=t.size/ts.SizeInFile|0;s<i;s++)this.sHdrs.push(new ts(e));break;default:e.position+=t.size}else if("sdta"===s.id)for(;Xt.load(s,t,e);)switch(t.id){case"smpl":this.fontSamples=Yt.loadSamples(t,e);break;default:e.position+=t.size}else e.position+=s.size}}static loadSamples(e,t){let s=e.size/2|0;const i=new Float32Array(s);let a=0;const r=new Uint8Array(2048);for(;s>0;){let e=Math.min(s,r.length/2|0);t.read(r,0,2*e);for(let t=0;t<e;t++){const e=je.int32ToInt16(r[2*t+1]<<8|r[2*t]);i[a+t]=e/32767}s-=e,a+=e}return i}}class qt{constructor(e){this.instGenNdx=Ke.readUInt16LE(e),this.instModNdx=Ke.readUInt16LE(e)}}qt.SizeInFile=4;class Jt{constructor(e){this.modSrcOper=Ke.readUInt16LE(e),this.modDestOper=Ke.readUInt16LE(e),this.modAmount=Ke.readInt16LE(e),this.modAmtSrcOper=Ke.readUInt16LE(e),this.modTransOper=Ke.readUInt16LE(e)}}Jt.SizeInFile=10;class Qt{constructor(e){this.genOper=Ke.readUInt16LE(e),this.genAmount=new ss(e)}}Qt.SizeInFile=4;class jt{constructor(e){this.instName=Ke.read8BitStringLength(e,20),this.instBagNdx=Ke.readUInt16LE(e)}}jt.SizeInFile=22;class Kt{constructor(e){this.genNdx=Ke.readUInt16LE(e),this.modNdx=Ke.readUInt16LE(e)}}Kt.SizeInFile=4;class $t{constructor(e){this.genOper=Ke.readUInt16LE(e),this.genAmount=new ss(e)}}$t.SizeInFile=4,$t.GenInstrument=41,$t.GenKeyRange=43,$t.GenVelRange=44,$t.GenSampleId=53;class Zt{constructor(e){this.presetName=Ke.read8BitStringLength(e,20),this.preset=Ke.readUInt16LE(e),this.bank=Ke.readUInt16LE(e),this.presetBagNdx=Ke.readUInt16LE(e),this.library=Ke.readUInt32LE(e),this.genre=Ke.readUInt32LE(e),this.morphology=Ke.readUInt32LE(e)}}Zt.SizeInFile=38;class es{constructor(e){this.modSrcOper=Ke.readUInt16LE(e),this.modDestOper=Ke.readUInt16LE(e),this.modAmount=Ke.readUInt16LE(e),this.modAmtSrcOper=Ke.readUInt16LE(e),this.modTransOper=Ke.readUInt16LE(e)}}es.SizeInFile=10;class ts{constructor(e){this.sampleName=Ke.read8BitStringLength(e,20),this.start=Ke.readUInt32LE(e),this.end=Ke.readUInt32LE(e),this.startLoop=Ke.readUInt32LE(e),this.endLoop=Ke.readUInt32LE(e),this.sampleRate=Ke.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=Ke.readSInt8(e),this.sampleLink=Ke.readUInt16LE(e),this.sampleType=Ke.readUInt16LE(e)}}ts.SizeInFile=46;class ss{constructor(e){this.wordAmount=Ke.readUInt16LE(e)}get shortAmount(){return je.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}}class is{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 as{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"}(J||(J={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(Q||(Q={}));class rs{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null,this.fontSamples=null}}class ns{static timecents2Secs(e){return Math.pow(2,e/1200)}static decibelsToGain(e){return e>-100?Math.pow(10,.05*e):0}static gainToDecibels(e){return e<=1e-5?-100:20*Math.log10(e)}static cents2Hertz(e){return 8.176*Math.pow(2,e/1200)}static clamp(e,t,s){return e<=t?t:e>=s?s:e}}class os{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:ns.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:ns.timecents2Secs(this.attack),this.release=this.release<-11950?0:ns.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:ns.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:ns.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?ns.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"}(j||(j={}));class hs{constructor(e){this.loopMode=J.None,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv=new os,this.modEnv=new os,this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,e&&(this.loopMode=e.loopMode,this.sampleRate=e.sampleRate,this.loKey=e.loKey,this.hiKey=e.hiKey,this.loVel=e.loVel,this.hiVel=e.hiVel,this.group=e.group,this.offset=e.offset,this.end=e.end,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this.transpose=e.transpose,this.tune=e.tune,this.pitchKeyCenter=e.pitchKeyCenter,this.pitchKeyTrack=e.pitchKeyTrack,this.attenuation=e.attenuation,this.pan=e.pan,this.ampEnv=new os(e.ampEnv),this.modEnv=new os(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=J.None,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv.clear(),this.modEnv.clear(),this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,this.hiKey=127,this.hiVel=127,this.pitchKeyCenter=60,e||(this.pitchKeyTrack=100,this.pitchKeyCenter=-1,this.ampEnv.delay=-12e3,this.ampEnv.attack=-12e3,this.ampEnv.hold=-12e3,this.ampEnv.decay=-12e3,this.ampEnv.release=-12e3,this.modEnv.delay=-12e3,this.modEnv.attack=-12e3,this.modEnv.hold=-12e3,this.modEnv.decay=-12e3,this.modEnv.release=-12e3,this.initialFilterFc=13500,this.delayModLFO=-12e3,this.delayVibLFO=-12e3)}operator(e,t){switch(e){case j.StartAddrsOffset:this.offset+=je.int16ToUint32(t.shortAmount);break;case j.EndAddrsOffset:this.end+=je.int16ToUint32(t.shortAmount);break;case j.StartloopAddrsOffset:this.loopStart+=je.int16ToUint32(t.shortAmount);break;case j.EndloopAddrsOffset:this.loopEnd+=je.int16ToUint32(t.shortAmount);break;case j.StartAddrsCoarseOffset:this.offset+=32768*je.int16ToUint32(t.shortAmount);break;case j.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case j.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case j.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case j.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case j.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case j.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case j.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case j.EndAddrsCoarseOffset:this.end+=32768*je.int16ToUint32(t.shortAmount);break;case j.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case j.Pan:this.pan=t.shortAmount/1e3;break;case j.DelayModLFO:this.delayModLFO=t.shortAmount;break;case j.FreqModLFO:this.freqModLFO=t.shortAmount;break;case j.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case j.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case j.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case j.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case j.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case j.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case j.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case j.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case j.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case j.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case j.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case j.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case j.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case j.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case j.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case j.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case j.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case j.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case j.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case j.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case j.StartloopAddrsCoarseOffset:this.loopStart+=32768*je.int16ToUint32(t.shortAmount);break;case j.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case j.EndloopAddrsCoarseOffset:this.loopEnd+=32768*je.int16ToUint32(t.shortAmount);break;case j.CoarseTune:this.transpose+=t.shortAmount;break;case j.FineTune:this.tune+=t.shortAmount;break;case j.SampleModes:this.loopMode=3==(3&t.wordAmount)?J.Sustain:1==(3&t.wordAmount)?J.Continuous:J.None;break;case j.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case j.ExclusiveClass:this.group=t.wordAmount;break;case j.OverridingRootKey:this.pitchKeyCenter=t.shortAmount}}}!function(e){e[e.None=0]="None",e[e.Delay=1]="Delay",e[e.Attack=2]="Attack",e[e.Hold=3]="Hold",e[e.Decay=4]="Decay",e[e.Sustain=5]="Sustain",e[e.Release=6]="Release",e[e.Done=7]="Done"}(K||(K={}));class ls{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=K.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case K.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=K.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=K.Delay;break;case K.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=K.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=K.Attack;break;case K.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=K.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=K.Hold;break;case K.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=K.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=K.Decay;break;case K.Decay:return this.segment=K.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case K.Sustain:if(this.segment=K.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?ls.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=K.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,s,i,a){this.parameters=new os(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:ns.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:ns.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|s,this.isAmpEnv=i,this.nextSegment(K.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)}}ls.FastReleaseTime=.01;class cs{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,s){this.samplesUntil=e*s|0,this.delta=4*ns.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 ds{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 us{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 ls,this.modEnv=new ls,this.lowPass=new ds,this.modLfo=new cs,this.vibLfo=new cs,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/(ns.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(K.Sustain,e),this.modEnv.nextSegment(K.Sustain,e),this.region.loopMode===J.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(K.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(K.Sustain,e)}render(e,t,s,i,a){if(!this.region)return;let r=this.region;let n=e.presets[this.playingPreset].fontSamples,o=0,h=e.outputMode===Q.StereoUnweaved?i:-1,l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,c=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),d=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,f=r.end,m=g+1,y=this.sourceSamplePosition,b=new ds(this.lowPass),S=0!==r.modLfoToFilterFc||0!==r.modEnvToFilterFc,w=0,_=0,B=0,T=0,k=0!==r.modLfoToPitch||0!==r.modEnvToPitch||0!==r.vibLfoToPitch,v=0,x=0,N=0,P=0,E=0!==r.modLfoToVolume,C=0,F=0;for(S?(w=e.outSampleRate,_=r.initialFilterFc,B=r.modLfoToFilterFc,T=r.modEnvToFilterFc):(w=0,_=0,B=0,T=0),k?(v=0,x=r.modLfoToPitch,N=r.vibLfoToPitch,P=r.modEnvToPitch):(v=ns.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,x=0,N=0,P=0),E?F=.1*r.modLfoToVolume:(C=ns.decibelsToGain(this.noteGainDb),F=0);i>0;){let r,L,M=0,I=i>us.RenderEffectSampleBlock?us.RenderEffectSampleBlock:i;if(i-=I,S){let e=_+this.modLfo.level*B+this.modEnv.level*T;b.active=e<=13500,b.active&&b.setup(ns.cents2Hertz(e)/w)}switch(k&&(v=ns.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*x+this.vibLfo.level*N+this.modEnv.level*P))*this.pitchOutputFactor),E&&(C=ns.decibelsToGain(this.noteGainDb+this.modLfo.level*F)),r=C*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(I,e.outSampleRate),l&&this.modEnv.process(I,e.outSampleRate),c&&this.modLfo.process(I),d&&this.vibLfo.process(I),e.outputMode){case Q.StereoInterleaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;I-- >0&&y<f;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*L,o++,t[s+o]+=r*M,o++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case Q.StereoUnweaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;I-- >0&&y<f;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*L,o++,t[s+h]+=r*M,h++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case Q.Mono:for(;I-- >0&&y<f;){let e=0|y,i=e>=g&&u?p:e+1,a=y-e,h=n[e]*(1-a)+n[i]*a;b.active&&(h=b.process(h)),t[s+o]=h*r,o++,y+=v,y>=m&&u&&(y-=g-p+1)}}if(y>=f||this.ampEnv.segment===K.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}us.RenderEffectSampleBlock=Gt.MicroBufferSize;class ps{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}}class gs{constructor(e){this._midiEventQueue=new ps,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=Q.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._isAnySolo=!1}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(Gt.MetronomeChannel,33),this.channelNoteOn(Gt.MetronomeChannel,33,95/127)):e.event&&this.processMidiMessage(e.event),a.push(e)}for(const a of this._voices)if(-1!==a.playingPreset){const r=a.playingChannel,n=this._mutedChannels.has(r)||i&&r!=Gt.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,s,n):a.kill()}return a}processMidiMessage(e){const t=e.command,s=e.channel,i=e.data1,a=e.data2;switch(t){case z.NoteOff:this.channelNoteOff(s,i);break;case z.NoteOn:this.channelNoteOn(s,i,a/127);break;case z.NoteAftertouch:break;case z.Controller:this.channelMidiControl(s,i,a);break;case z.ProgramChange:this.channelSetPresetNumber(s,i,9===s);break;case z.ChannelAftertouch:break;case z.PitchBend:this.channelSetPitchWheel(s,i|a<<7);break;case z.PerNotePitchBend:const t=e;let r=t.pitch;r=r*Gt.MaxPitchWheel/Gt.MaxPitchWheel20,this.channelSetPerNotePitchWheel(s,t.noteKey,r);break;case z.Meta:switch(e.data1){case U.Tempo:this.currentTempo=6e7/e.value;break;case U.TimeSignature:this.timeSignatureNumerator=e.data[0],this.timeSignatureDenominator=Math.pow(2,e.data[1])}}}get metronomeVolume(){return this.channelGetMixVolume(Gt.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Gt.MetronomeChannel,e),e>0&&(this.channelSetVolume(Gt.MetronomeChannel,1),this.channelSetPresetNumber(Gt.MetronomeChannel,0,!0))}get masterVolume(){return ns.decibelsToGain(this.globalGainDb)}set masterVolume(e){var t=ns.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<K.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(){var e,t;return null!==(t=null===(e=this.presets)||void 0===e?void 0:e.length)&&void 0!==t?t:0}reset(){for(let e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<K.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 us;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-ns.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!==J.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(ns.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>=K.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>=K.Release)||r.end(this.outSampleRate)}bankNoteOff(e,t,s){const i=this.getPresetIndex(e,t);return-1!==i&&(this.noteOff(i,s),!0)}noteOffAll(e){for(const t of this._voices)-1!==t.playingPreset&&t.ampEnv.segment<K.Release&&(e?t.endQuick(this.outSampleRate):t.end(this.outSampleRate))}get activeVoiceCount(){let e=0;for(const t of this._voices)-1!==t.playingPreset&&e++;return e}channelInit(e){if(this._channels&&e<this._channels.channelList.length)return this._channels.channelList[e];this._channels||(this._channels=new as);for(let t=this._channels.channelList.length;t<=e;t++){let e=new is;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._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,s))}channelNoteOff(e,t){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>=K.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>=K.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<K.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<K.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=je.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=je.int32ToUint16(t)}channelSetBankPreset(e,t,s){const i=this.channelInit(e),a=this.getPresetIndex(t,s);return-1!==a&&(i.presetIndex=je.int32ToUint16(a),i.bank=je.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=ns.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=je.int32ToUint16(t),this.channelApplyPitch(e,s))}channelSetPerNotePitchWheel(e,t,s){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 5:case 96:case 97:case 64:case 65:case 66:case 122:case 124:case 125:case 126:case 127:return;case 38:return i.midiData=je.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 7:return i.midiVolume=je.int32ToUint16(127&i.midiVolume|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case 39:return i.midiVolume=je.int32ToUint16(16256&i.midiVolume|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case 11:return i.midiExpression=je.int32ToUint16(127&i.midiExpression|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case 43:return i.midiExpression=je.int32ToUint16(16256&i.midiExpression|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case 10:return i.midiPan=je.int32ToUint16(127&i.midiPan|s<<7),void this.channelSetPan(e,i.midiPan/16383);case 42:return i.midiPan=je.int32ToUint16(16256&i.midiPan|s),void this.channelSetPan(e,i.midiPan/16383);case 6:return i.midiData=je.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&&6===t&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case 0:return void(i.bank=je.int32ToUint16(32768|s));case 32:return void(i.bank=je.int32ToUint16((0!=(32768&i.bank)?(127&i.bank)<<7:0)|s));case 101:return void(i.midiRpn=je.int32ToUint16(127&(65535===i.midiRpn?0:i.midiRpn)|s<<7));case 100:return void(i.midiRpn=je.int32ToUint16(16256&(65535===i.midiRpn?0:i.midiRpn)|s));case 98:case 99:return void(i.midiRpn=65535);case 120:return void this.channelSoundsOffAll(e);case 123:return void this.channelNoteOffAll(e);case 121: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?ns.decibelsToGain(this._channels.channelList[e].gainDb):1}channelGetPitchWheel(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchWheel:8192}channelGetPitchRange(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchRange:2}channelGetTuning(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].tuning:0}resetPresets(){this.presets=[]}loadPresets(e,t){const s=[];for(let t=0;t<e.phdrs.length-1;t++){const i=e.phdrs[t];let a=0;const r=new rs;s.push(r),r.name=i.presetName,r.bank=i.bank,r.presetNumber=i.preset,r.fontSamples=e.fontSamples;let n=0;for(let s=i.presetBagNdx;s<e.phdrs[t+1].presetBagNdx;s++){let t=0,i=127,a=0,r=127;for(let o=e.pbags[s].genNdx;o<e.pbags[s+1].genNdx;o++){let s=e.pgens[o];if(s.genOper!==$t.GenKeyRange)if(s.genOper!==$t.GenVelRange){if(s.genOper===$t.GenInstrument&&!(s.genAmount.wordAmount>=e.insts.length))for(let o=e.insts[s.genAmount.wordAmount].instBagNdx;o<e.insts[s.genAmount.wordAmount+1].instBagNdx;o++){let s=0,h=127,l=0,c=127;for(let d=e.ibags[o].instGenNdx;d<e.ibags[o+1].instGenNdx;d++){let o=e.igens[d];o.genOper!==$t.GenKeyRange?o.genOper!==$t.GenVelRange?53===o.genOper&&h>=t&&s<=i&&c>=a&&l<=r&&n++:(l=o.genAmount.lowByteAmount,c=o.genAmount.highByteAmount):(s=o.genAmount.lowByteAmount,h=o.genAmount.highByteAmount)}}}else a=s.genAmount.lowByteAmount,r=s.genAmount.highByteAmount;else t=s.genAmount.lowByteAmount,i=s.genAmount.highByteAmount}}r.regions=new Array(n);let o=new hs;o.clear(!0);for(let s=i.presetBagNdx;s<e.phdrs[t+1].presetBagNdx;s++){const t=e.pbags[s],n=new hs(o);let h=!1;for(let i=t.genNdx;i<e.pbags[s+1].genNdx;i++){const t=e.pgens[i];if(t.genOper===$t.GenInstrument){let s=t.genAmount.wordAmount;if(s>=e.insts.length)continue;let i=new hs;i.clear(!1);let o=e.insts[s];for(let t=o.instBagNdx;t<e.insts[s+1].instBagNdx;t++){let s=e.ibags[t],h=new hs(i),l=!1;for(let i=s.instGenNdx;i<e.ibags[t+1].instGenNdx;i++){let t=e.igens[i];if(t.genOper===$t.GenSampleId){if(h.hiKey<n.loKey||h.loKey>n.hiKey)continue;if(h.hiVel<n.loVel||h.loVel>n.hiVel)continue;n.loKey>h.loKey&&(h.loKey=n.loKey),n.hiKey<h.hiKey&&(h.hiKey=n.hiKey),n.loVel>h.loVel&&(h.loVel=n.loVel),n.hiVel<h.hiVel&&(h.hiVel=n.hiVel),h.offset+=n.offset,h.end+=n.end,h.loopStart+=n.loopStart,h.loopEnd+=n.loopEnd,h.transpose+=n.transpose,h.tune+=n.tune,h.pitchKeyTrack+=n.pitchKeyTrack,h.attenuation+=n.attenuation,h.pan+=n.pan,h.ampEnv.delay+=n.ampEnv.delay,h.ampEnv.attack+=n.ampEnv.attack,h.ampEnv.hold+=n.ampEnv.hold,h.ampEnv.decay+=n.ampEnv.decay,h.ampEnv.sustain+=n.ampEnv.sustain,h.ampEnv.release+=n.ampEnv.release,h.modEnv.delay+=n.modEnv.delay,h.modEnv.attack+=n.modEnv.attack,h.modEnv.hold+=n.modEnv.hold,h.modEnv.decay+=n.modEnv.decay,h.modEnv.sustain+=n.modEnv.sustain,h.modEnv.release+=n.modEnv.release,h.initialFilterQ+=n.initialFilterQ,h.initialFilterFc+=n.initialFilterFc,h.modEnvToPitch+=n.modEnvToPitch,h.modEnvToFilterFc+=n.modEnvToFilterFc,h.delayModLFO+=n.delayModLFO,h.freqModLFO+=n.freqModLFO,h.modLfoToPitch+=n.modLfoToPitch,h.modLfoToFilterFc+=n.modLfoToFilterFc,h.modLfoToVolume+=n.modLfoToVolume,h.delayVibLFO+=n.delayVibLFO,h.freqVibLFO+=n.freqVibLFO,h.vibLfoToPitch+=n.vibLfoToPitch,h.ampEnv.envToSecs(!0),h.modEnv.envToSecs(!1),h.delayModLFO=h.delayModLFO<-11950?0:ns.timecents2Secs(h.delayModLFO),h.delayVibLFO=h.delayVibLFO<-11950?0:ns.timecents2Secs(h.delayVibLFO),h.pan<-.5?h.pan=-.5:h.pan>.5&&(h.pan=.5),(h.initialFilterQ<1500||h.initialFilterQ>13500)&&(h.initialFilterQ=0);let s=e.sHdrs[t.genAmount.wordAmount];h.offset+=s.start,h.end+=s.end,h.loopStart+=s.startLoop,h.loopEnd+=s.endLoop,s.endLoop>0&&(h.loopEnd-=1),-1===h.pitchKeyCenter&&(h.pitchKeyCenter=s.originalPitch),h.tune+=s.pitchCorrection,h.sampleRate=s.sampleRate,0!==h.end&&h.end<r.fontSamples.length?h.end++:h.end=r.fontSamples.length,r.regions[a]=new hs(h),a++,l=!0}else h.operator(t.genOper,t.genAmount)}s!==e.ibags[o.instBagNdx]||l||(i=new hs(h))}h=!0}else n.operator(t.genOper,t.genAmount)}t!==e.pbags[i.presetBagNdx]||h||(o=n)}}if(t&&this.presets)for(const e of s)this.presets.push(e);else this.presets=s}}class fs{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 ms{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 ys{constructor(e){this.events=e}}class bs{constructor(e){this._isSoundFontLoaded=!1,this._isMidiLoaded=!1,this._tickPosition=0,this._timePosition=0,this._metronomeVolume=0,this._countInVolume=0,this._playedEventsQueue=new ps,this._midiEventsPlayedFilter=new Set,this.isReady=!1,this.state=q.Paused,this.ready=new fs,this.readyForPlayback=new fs,this.finished=new fs,this.soundFontLoaded=new fs,this.soundFontLoadFailed=new ms,this.midiLoaded=new ms,this.midiLoadFailed=new ms,this.stateChanged=new ms,this.positionChanged=new ms,this.midiEventsPlayed=new ms,Be.debug("AlphaSynth","Initializing player"),this.state=q.Paused,Be.debug("AlphaSynth","Creating output"),this.output=e,Be.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new gs(this.output.sampleRate),this._sequencer=new Wt(this._synthesizer),Be.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{let e=new Float32Array(Gt.MicroBufferSize*Gt.MicroBufferCount*Gt.AudioChannels),t=0;for(let s=0;s<Gt.MicroBufferCount;s++){this._sequencer.fillMidiEventQueue();const s=this._synthesizer.synthesize(e,t,Gt.MicroBufferSize);t+=Gt.MicroBufferSize*Gt.AudioChannels;for(const e of s)this._midiEventsPlayedFilter.has(e.event.command)&&this._playedEventsQueue.enqueue(e);if(this._sequencer.isFinished)break}t<e.length&&(e=e.subarray(0,t)),this.output.addSamples(e)})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open()}get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return Be.logLevel}set logLevel(e){Be.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Gt.MinVolume),this._synthesizer.masterVolume=e,this.onAudioSettingsUpdate()}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Gt.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e,this.onAudioSettingsUpdate()}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Gt.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=ns.clamp(e,Gt.MinPlaybackSpeed,Gt.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.tickPositionToTimePosition(e)}get timePosition(){return this._timePosition}set timePosition(e){Be.debug("AlphaSynth",`Seeking to position ${e}ms`),this._sequencer.seek(e),this.updateTimePosition(e,!0),this.output.resetSamples()}get playbackRange(){return this._sequencer.playbackRange}set playbackRange(e){this._sequencer.playbackRange=e,e&&(this.tickPosition=e.startTick)}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){Be.debug("AlphaSynth","Destroying player"),this.stop(),this.output.destroy()}play(){return!(this.state!==q.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(Be.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.tickPosition=0),this.output.play(),!0)}playInternal(){Be.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.state=q.Playing,this.stateChanged.trigger(new zt(this.state,!1))}pause(){this.state!==q.Paused&&this._isMidiLoaded&&(Be.debug("AlphaSynth","Pausing playback"),this.state=q.Paused,this.stateChanged.trigger(new zt(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===q.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(Be.debug("AlphaSynth","Stopping playback"),this.state=q.Paused,this.output.pause(),this._sequencer.stop(),this._synthesizer.noteOffAll(!0),this.tickPosition=this._sequencer.playbackRange?this._sequencer.playbackRange.startTick:0,this.stateChanged.trigger(new zt(this.state,!0)))}playOneTimeMidiFile(e){this.pause(),this._sequencer.loadOneTimeMidi(e),this._sequencer.stop(),this._synthesizer.noteOffAll(!0),this.tickPosition=0,this.output.play()}resetSoundFonts(){this.stop(),this._synthesizer.resetPresets(),this._isSoundFontLoaded=!1,this.soundFontLoaded.trigger()}loadSoundFont(e,t){this.pause();let s=$e.fromBuffer(e);try{Be.debug("AlphaSynth","Loading soundfont from bytes");let e=new Yt;e.load(s),this._synthesizer.loadPresets(e,t),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),Be.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){Be.error("AlphaSynth","Could not load soundfont from bytes "+e),this.soundFontLoadFailed.trigger(e)}}checkReadyForPlayback(){this.isReadyForPlayback&&(this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.readyForPlayback.trigger())}loadMidiFile(e){this.stop();try{Be.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new Ut(0,this._sequencer.endTime,0,this._sequencer.endTick,!1)),Be.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){Be.error("AlphaSynth","Could not load midi from model "+e),this.midiLoadFailed.trigger(e)}}setChannelMute(e,t){this._synthesizer.channelSetMute(e,t),this.onAudioSettingsUpdate()}resetChannelStates(){this._synthesizer.resetChannelStates()}setChannelSolo(e,t){this._synthesizer.channelSetSolo(e,t),this.onAudioSettingsUpdate()}setChannelVolume(e,t){t=Math.max(t,Gt.MinVolume),this._synthesizer.channelSetMixVolume(e,t),this.onAudioSettingsUpdate()}onAudioSettingsUpdate(){this.timePosition=this.timePosition}onSamplesPlayed(e){let t=e/this._synthesizer.outSampleRate*1e3;this.updateTimePosition(this._timePosition+t,!1),this.checkForFinish()}checkForFinish(){let e=0,t=0;this.playbackRange?(e=this.playbackRange.startTick,t=this.playbackRange.endTick):t=this._sequencer.endTick,this._tickPosition>=t&&(Be.debug("AlphaSynth","Finished playback"),this._sequencer.isPlayingCountIn?(this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal()):this._sequencer.isPlayingOneTimeMidi?(this._sequencer.resetOneTimeMidi(),this.state=q.Paused,this.output.pause(),this._synthesizer.noteOffAll(!1)):(this.finished.trigger(),this.isLooping?this.tickPosition=e:this.stop()))}updateTimePosition(e,t){const s=e;this._timePosition=s;const i=this._sequencer.timePositionToTickPosition(s);this._tickPosition=i;const a=this._sequencer.endTime,r=this._sequencer.endTick;if(this._sequencer.isPlayingOneTimeMidi||this._sequencer.isPlayingCountIn||(Be.debug("AlphaSynth",`Position changed: (time: ${s}/${a}, tick: ${i}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount}`),this.positionChanged.trigger(new Ut(s,a,i,r,t))),t)this._playedEventsQueue.clear();else{const e=new ps;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<s;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new ys(e.toArray()))}}}class Ss{constructor(){this.division=ye.QuarterTime,this.events=[]}addEvent(e){if(0===this.events.length)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)}}toBinary(){let e=$e.empty();return this.writeTo(e),e.toArray()}writeTo(e){let t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),t=new Uint8Array([0,0,0,6]),e.write(t,0,t.length),t=new Uint8Array([0,0]),e.write(t,0,t.length);let s=1;t=new Uint8Array([s>>8&255,255&s]),e.write(t,0,t.length),s=this.division,t=new Uint8Array([s>>8&255,255&s]),e.write(t,0,t.length);let i=$e.empty(),a=0;for(let e of this.events){let t=e.tick-a;Ss.writeVariableInt(i,t),e.writeTo(i),a=e.tick}t=new Uint8Array([77,84,114,107]),e.write(t,0,t.length);let r=i.toArray(),n=r.length;t=new Uint8Array([n>>24&255,n>>16&255,n>>8&255,255&n]),e.write(t,0,t.length),e.write(r,0,r.length)}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])}}class ws extends Dt{constructor(e,t,s,i,a){super(e,t,s,i,0),this.data=a}writeTo(e){e.writeByte(255),e.writeByte(this.metaStatus);let t=this.data.length;Ss.writeVariableInt(e,t),e.write(this.data,0,this.data.length)}}class _s extends Dt{constructor(e,t,s,i,a){super(e,t,s,i,0),this.value=a}writeTo(e){e.writeByte(255),e.writeByte(this.metaStatus),Ss.writeVariableInt(e,3);let t=new Uint8Array([this.value>>16&255,this.value>>8&255,255&this.value]);e.write(t,0,t.length)}}class Bs{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 pe(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)}}class Ts{constructor(e,t,s){this.text=e,this.startPos=t,this.endPos=s}}class ks{constructor(e){this.style="normal",this.variant="normal",this.weight="normal",this.stretch="normal",this.lineHeight="normal",this.size="1rem",this.families=[],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 Ts(e.substring(s,i),s,i)),s=i+1}return t}parse(){var e;if(this.reset(),1===this._tokens.length)switch(null===(e=this._currentToken)||void 0===e?void 0:e.text){case"caption":case"icon":case"menu":case"message-box":case"small-caption":case"status-bar":case"inherit":return}this.fontStyleVariantWeight(),this.fontSizeLineHeight(),this.fontFamily()}fontFamily(){if(!this._currentToken)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()}}!function(e){e[e.Plain=0]="Plain",e[e.Italic=1]="Italic"}($||($={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(Z||(Z={}));class vs{constructor(e,t,s=$.Plain,i=Z.Regular){this._cssScale=0,this._family=e,this._size=t,this._style=s,this._weight=i,this._css=this.toCssString()}reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._family}set family(e){this._family=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===Z.Bold}get isItalic(){return this.style===$.Italic}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+="'",t+=this.family,t+="'",this._css=t,this._cssScale=e}return this._css}static fromJson(e){switch(typeof e){case"undefined":return null;case"object":{const t=e;let s=t.get("family"),i=t.get("size"),a=Bs.parseEnum(t.get("style"),$),r=Bs.parseEnum(t.get("weight"),Z);return new vs(s,i,a,r)}case"string":{const t=new ks(e);t.parse();let s=t.families[0];(s.startsWith("'")&&s.endsWith("'")||s.startsWith('"')&&s.endsWith('"'))&&(s=s.substr(1,s.length-2));let 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=$.Plain;"italic"===t.style&&(r=$.Italic);let n=Z.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=Z.Bold}return new vs(s,a,r,n)}default:return null}}static toJson(e){const t=new Map;return t.set("family",e.family),t.set("size",e.size),t.set("style",e.style),t.set("weight",e.weight),t}}class xs{constructor(){this.copyrightFont=new vs(xs.sansFont,12,$.Plain,Z.Bold),this.titleFont=new vs(xs.serifFont,32,$.Plain),this.subTitleFont=new vs(xs.serifFont,20,$.Plain),this.wordsFont=new vs(xs.serifFont,15,$.Plain),this.effectFont=new vs(xs.serifFont,12,$.Italic),this.fretboardNumberFont=new vs(xs.sansFont,11,$.Plain),this.tablatureFont=new vs(xs.sansFont,13,$.Plain),this.graceFont=new vs(xs.sansFont,11,$.Plain),this.staffLineColor=new Ue(165,165,165,255),this.barSeparatorColor=new Ue(34,34,17,255),this.barNumberFont=new vs(xs.sansFont,11,$.Plain),this.barNumberColor=new Ue(200,0,0,255),this.fingeringFont=new vs(xs.serifFont,14,$.Plain),this.markerFont=new vs(xs.serifFont,14,$.Plain,Z.Bold),this.mainGlyphColor=new Ue(0,0,0,255),this.secondaryGlyphColor=new Ue(0,0,0,100),this.scoreInfoColor=new Ue(0,0,0,255)}}xs.sansFont="Arial",xs.serifFont="Georgia";class Ns{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.resources=new xs,this.padding=null}}class Ps{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"}(ee||(ee={}));class Es{constructor(){this.noteWideLength=480,this.noteWideAmplitude=2,this.noteSlightLength=480,this.noteSlightAmplitude=2,this.beatWideLength=240,this.beatWideAmplitude=3,this.beatSlightLength=240,this.beatSlightAmplitude=3}}class Cs{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}class Fs{constructor(){this.soundFont=null,this.scrollElement="html,body",this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=ee.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new Es,this.slide=new Cs,this.playTripletFeel=!0}}class Ls{static fromJson(e,t){t&&Bs.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=Bs.parseEnum(s,v),!0;case"useworkers":return e.useWorkers=s,!0;case"includenotebounds":return e.includeNoteBounds=s,!0}return!1}}class Ms{static fromJson(e,t){t&&Bs.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",vs.toJson(e.copyrightFont)),t.set("titlefont",vs.toJson(e.titleFont)),t.set("subtitlefont",vs.toJson(e.subTitleFont)),t.set("wordsfont",vs.toJson(e.wordsFont)),t.set("effectfont",vs.toJson(e.effectFont)),t.set("fretboardnumberfont",vs.toJson(e.fretboardNumberFont)),t.set("tablaturefont",vs.toJson(e.tablatureFont)),t.set("gracefont",vs.toJson(e.graceFont)),t.set("stafflinecolor",Ue.toJson(e.staffLineColor)),t.set("barseparatorcolor",Ue.toJson(e.barSeparatorColor)),t.set("barnumberfont",vs.toJson(e.barNumberFont)),t.set("barnumbercolor",Ue.toJson(e.barNumberColor)),t.set("fingeringfont",vs.toJson(e.fingeringFont)),t.set("markerfont",vs.toJson(e.markerFont)),t.set("mainglyphcolor",Ue.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",Ue.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",Ue.toJson(e.scoreInfoColor)),t}static setProperty(e,t,s){switch(t){case"copyrightfont":return e.copyrightFont=vs.fromJson(s),!0;case"titlefont":return e.titleFont=vs.fromJson(s),!0;case"subtitlefont":return e.subTitleFont=vs.fromJson(s),!0;case"wordsfont":return e.wordsFont=vs.fromJson(s),!0;case"effectfont":return e.effectFont=vs.fromJson(s),!0;case"fretboardnumberfont":return e.fretboardNumberFont=vs.fromJson(s),!0;case"tablaturefont":return e.tablatureFont=vs.fromJson(s),!0;case"gracefont":return e.graceFont=vs.fromJson(s),!0;case"stafflinecolor":return e.staffLineColor=Ue.fromJson(s),!0;case"barseparatorcolor":return e.barSeparatorColor=Ue.fromJson(s),!0;case"barnumberfont":return e.barNumberFont=vs.fromJson(s),!0;case"barnumbercolor":return e.barNumberColor=Ue.fromJson(s),!0;case"fingeringfont":return e.fingeringFont=vs.fromJson(s),!0;case"markerfont":return e.markerFont=vs.fromJson(s),!0;case"mainglyphcolor":return e.mainGlyphColor=Ue.fromJson(s),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=Ue.fromJson(s),!0;case"scoreinfocolor":return e.scoreInfoColor=Ue.fromJson(s),!0}return!1}}class Is{static fromJson(e,t){t&&Bs.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("resources",Ms.toJson(e.resources)),t.set("padding",e.padding),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=Bs.parseEnum(a,e),!0;case"staveprofile":return s.staveProfile=Bs.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"padding":return s.padding=a,!0}if(["resources"].indexOf(i)>=0)return Ms.fromJson(s.resources,a),!0;for(const e of["resources"])if(0===i.indexOf(e)&&Ms.setProperty(s.resources,i.substring(e.length),a))return!0;return!1}}class Ds{static fromJson(e,t){t&&Bs.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=Bs.parseEnum(s,T),!0;case"fingeringmode":return e.fingeringMode=Bs.parseEnum(s,B),!0;case"elements":return e.elements=new Map,Bs.forEach(s,((t,s)=>{e.elements.set(Bs.parseEnum(s,k),t)})),!0;case"rhythmmode":return e.rhythmMode=Bs.parseEnum(s,_),!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 Rs{static fromJson(e,t){t&&Bs.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 As{static fromJson(e,t){t&&Bs.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 Os{static fromJson(e,t){t&&Bs.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 Gs{static fromJson(e,t){t&&Bs.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("scrollelement",e.scrollElement),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",As.toJson(e.vibrato)),t.set("slide",Os.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t}static setProperty(e,t,s){switch(t){case"soundfont":return e.soundFont=s,!0;case"scrollelement":return e.scrollElement=s,!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=Bs.parseEnum(s,ee),!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}if(["vibrato"].indexOf(t)>=0)return As.fromJson(e.vibrato,s),!0;for(const i of["vibrato"])if(0===t.indexOf(i)&&As.setProperty(e.vibrato,t.substring(i.length),s))return!0;if(["slide"].indexOf(t)>=0)return Os.fromJson(e.slide,s),!0;for(const i of["slide"])if(0===t.indexOf(i)&&Os.setProperty(e.slide,t.substring(i.length),s))return!0;return!1}}class Vs{static fromJson(e,t){t&&Bs.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",Ls.toJson(e.core)),t.set("display",Is.toJson(e.display)),t.set("notation",Ds.toJson(e.notation)),t.set("importer",Rs.toJson(e.importer)),t.set("player",Gs.toJson(e.player)),t}static setProperty(e,t,s){if(["core",""].indexOf(t)>=0)return Ls.fromJson(e.core,s),!0;for(const i of["core",""])if(0===t.indexOf(i)&&Ls.setProperty(e.core,t.substring(i.length),s))return!0;if(["display",""].indexOf(t)>=0)return Is.fromJson(e.display,s),!0;for(const i of["display",""])if(0===t.indexOf(i)&&Is.setProperty(e.display,t.substring(i.length),s))return!0;if(["notation"].indexOf(t)>=0)return Ds.fromJson(e.notation,s),!0;for(const i of["notation"])if(0===t.indexOf(i)&&Ds.setProperty(e.notation,t.substring(i.length),s))return!0;if(["importer"].indexOf(t)>=0)return Rs.fromJson(e.importer,s),!0;for(const i of["importer"])if(0===t.indexOf(i)&&Rs.setProperty(e.importer,t.substring(i.length),s))return!0;if(["player"].indexOf(t)>=0)return Gs.fromJson(e.player,s),!0;for(const i of["player"])if(0===t.indexOf(i)&&Gs.setProperty(e.player,t.substring(i.length),s))return!0;return!1}}class Hs{constructor(){this.core=new lo,this.display=new Ns,this.notation=new Se,this.importer=new Ps,this.player=new Fs}setSongBookModeSettings(){this.notation.notationMode=T.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=B.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(k.ParenthesisOnTiedBends,!1),this.notation.elements.set(k.TabNotesOnTiedBends,!1),this.notation.elements.set(k.ZerosOnDiveWhammys,!0)}static get songBook(){let e=new Hs;return e.setSongBookModeSettings(),e}fillFromJson(e){Vs.fromJson(this,e)}}class Ws extends It{constructor(e,t,s,i,a){super(e,t,s,0,0),this.noteKey=i,this.pitch=a}writeTo(e){let t=new Uint8Array([64,255&this.message,255&this.noteKey,0,this.pitch>>24&255,this.pitch>>16&255,this.pitch>>8&255,255&this.pitch]);e.write(t,0,t.length)}}class zs{static fromJson(e,t){t&&Bs.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 Us{static fromJson(e,t){t&&Bs.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=Bs.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 Xs{static fromJson(e,t){t&&Bs.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=Bs.parseEnum(s,O),!0;case"length":return e.length=s,!0}return!1}}class Ys{static fromJson(e,t){t&&Bs.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("alternateendings",e.alternateEndings),t.set("keysignature",e.keySignature),t.set("keysignaturetype",e.keySignatureType),t.set("isdoublebar",e.isDoubleBar),t.set("isrepeatstart",e.isRepeatStart),t.set("repeatcount",e.repeatCount),t.set("timesignaturenumerator",e.timeSignatureNumerator),t.set("timesignaturedenominator",e.timeSignatureDenominator),t.set("timesignaturecommon",e.timeSignatureCommon),t.set("tripletfeel",e.tripletFeel),t.set("section",zs.toJson(e.section)),t.set("tempoautomation",Us.toJson(e.tempoAutomation)),null!==e.fermata){const s=new Map;t.set("fermata",s);for(const[t,i]of e.fermata)s.set(t.toString(),Xs.toJson(i))}return t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t}static setProperty(e,t,s){switch(t){case"alternateendings":return e.alternateEndings=s,!0;case"keysignature":return e.keySignature=Bs.parseEnum(s,M),!0;case"keysignaturetype":return e.keySignatureType=Bs.parseEnum(s,I),!0;case"isdoublebar":return e.isDoubleBar=s,!0;case"isrepeatstart":return e.isRepeatStart=s,!0;case"repeatcount":return e.repeatCount=s,!0;case"timesignaturenumerator":return e.timeSignatureNumerator=s,!0;case"timesignaturedenominator":return e.timeSignatureDenominator=s,!0;case"timesignaturecommon":return e.timeSignatureCommon=s,!0;case"tripletfeel":return e.tripletFeel=Bs.parseEnum(s,D),!0;case"fermata":return e.fermata=new Map,Bs.forEach(s,((t,s)=>{const i=new nt;Xs.fromJson(i,t),e.addFermata(parseInt(s),i)})),!0;case"start":return e.start=s,!0;case"isanacrusis":return e.isAnacrusis=s,!0}return["section"].indexOf(t)>=0?(s?(e.section=new We,zs.fromJson(e.section,s)):e.section=null,!0):["tempoautomation"].indexOf(t)>=0&&(s?(e.tempoAutomation=new fe,Us.fromJson(e.tempoAutomation,s)):e.tempoAutomation=null,!0)}}class qs{static fromJson(e,t){t&&Bs.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 Js{static fromJson(e,t){t&&Bs.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){var t;if(!e)return null;const s=new Map;return s.set("id",e.id),s.set("accentuated",e.accentuated),s.set("bendtype",e.bendType),s.set("bendstyle",e.bendStyle),s.set("iscontinuedbend",e.isContinuedBend),null!==e.bendPoints&&s.set("bendpoints",null===(t=e.bendPoints)||void 0===t?void 0:t.map((e=>qs.toJson(e)))),s.set("fret",e.fret),s.set("string",e.string),s.set("octave",e.octave),s.set("tone",e.tone),s.set("percussionarticulation",e.percussionArticulation),s.set("isvisible",e.isVisible),s.set("islefthandtapped",e.isLeftHandTapped),s.set("ishammerpullorigin",e.isHammerPullOrigin),s.set("isslurdestination",e.isSlurDestination),s.set("harmonictype",e.harmonicType),s.set("harmonicvalue",e.harmonicValue),s.set("isghost",e.isGhost),s.set("isletring",e.isLetRing),s.set("ispalmmute",e.isPalmMute),s.set("isdead",e.isDead),s.set("isstaccato",e.isStaccato),s.set("slideintype",e.slideInType),s.set("slideouttype",e.slideOutType),s.set("vibrato",e.vibrato),s.set("istiedestination",e.isTieDestination),s.set("lefthandfinger",e.leftHandFinger),s.set("righthandfinger",e.rightHandFinger),s.set("isfingering",e.isFingering),s.set("trillvalue",e.trillValue),s.set("trillspeed",e.trillSpeed),s.set("durationpercent",e.durationPercent),s.set("accidentalmode",e.accidentalMode),s.set("dynamics",e.dynamics),e.toJson(s),s}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"accentuated":return e.accentuated=Bs.parseEnum(s,i),!0;case"bendtype":return e.bendType=Bs.parseEnum(s,l),!0;case"bendstyle":return e.bendStyle=Bs.parseEnum(s,h),!0;case"iscontinuedbend":return e.isContinuedBend=s,!0;case"bendpoints":if(s){e.bendPoints=[];for(const t of s){const s=new be;qs.fromJson(s,t),e.addBendPoint(s)}}return!0;case"fret":return e.fret=s,!0;case"string":return e.string=s,!0;case"octave":return e.octave=s,!0;case"tone":return e.tone=s,!0;case"percussionarticulation":return e.percussionArticulation=s,!0;case"isvisible":return e.isVisible=s,!0;case"islefthandtapped":return e.isLeftHandTapped=s,!0;case"ishammerpullorigin":return e.isHammerPullOrigin=s,!0;case"isslurdestination":return e.isSlurDestination=s,!0;case"harmonictype":return e.harmonicType=Bs.parseEnum(s,m),!0;case"harmonicvalue":return e.harmonicValue=s,!0;case"isghost":return e.isGhost=s,!0;case"isletring":return e.isLetRing=s,!0;case"ispalmmute":return e.isPalmMute=s,!0;case"isdead":return e.isDead=s,!0;case"isstaccato":return e.isStaccato=s,!0;case"slideintype":return e.slideInType=Bs.parseEnum(s,b),!0;case"slideouttype":return e.slideOutType=Bs.parseEnum(s,S),!0;case"vibrato":return e.vibrato=Bs.parseEnum(s,w),!0;case"istiedestination":return e.isTieDestination=s,!0;case"lefthandfinger":return e.leftHandFinger=Bs.parseEnum(s,f),!0;case"righthandfinger":return e.rightHandFinger=Bs.parseEnum(s,f),!0;case"isfingering":return e.isFingering=s,!0;case"trillvalue":return e.trillValue=s,!0;case"trillspeed":return e.trillSpeed=Bs.parseEnum(s,u),!0;case"durationpercent":return e.durationPercent=s,!0;case"accidentalmode":return e.accidentalMode=Bs.parseEnum(s,y),!0;case"dynamics":return e.dynamics=Bs.parseEnum(s,p),!0}return e.setProperty(t,s)}}class Qs{static fromJson(e,t){t&&Bs.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){var t;if(!e)return null;const s=new Map;return s.set("id",e.id),s.set("notes",e.notes.map((e=>Js.toJson(e)))),s.set("isempty",e.isEmpty),s.set("whammystyle",e.whammyStyle),s.set("ottava",e.ottava),s.set("islegatoorigin",e.isLegatoOrigin),s.set("duration",e.duration),s.set("automations",e.automations.map((e=>Us.toJson(e)))),s.set("dots",e.dots),s.set("fadein",e.fadeIn),s.set("lyrics",e.lyrics),s.set("hasrasgueado",e.hasRasgueado),s.set("pop",e.pop),s.set("slap",e.slap),s.set("tap",e.tap),s.set("text",e.text),s.set("brushtype",e.brushType),s.set("brushduration",e.brushDuration),s.set("tupletdenominator",e.tupletDenominator),s.set("tupletnumerator",e.tupletNumerator),s.set("iscontinuedwhammy",e.isContinuedWhammy),s.set("whammybartype",e.whammyBarType),null!==e.whammyBarPoints&&s.set("whammybarpoints",null===(t=e.whammyBarPoints)||void 0===t?void 0:t.map((e=>qs.toJson(e)))),s.set("vibrato",e.vibrato),s.set("chordid",e.chordId),s.set("gracetype",e.graceType),s.set("pickstroke",e.pickStroke),s.set("tremolospeed",e.tremoloSpeed),s.set("crescendo",e.crescendo),s.set("displaystart",e.displayStart),s.set("playbackstart",e.playbackStart),s.set("displayduration",e.displayDuration),s.set("playbackduration",e.playbackDuration),s.set("dynamics",e.dynamics),s.set("invertbeamdirection",e.invertBeamDirection),s.set("preferredbeamdirection",e.preferredBeamDirection),s.set("beamingmode",e.beamingMode),s}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 Pe;Js.fromJson(s,t),e.addNote(s)}return!0;case"isempty":return e.isEmpty=s,!0;case"whammystyle":return e.whammyStyle=Bs.parseEnum(s,h),!0;case"ottava":return e.ottava=Bs.parseEnum(s,n),!0;case"islegatoorigin":return e.isLegatoOrigin=s,!0;case"duration":return e.duration=Bs.parseEnum(s,u),!0;case"automations":e.automations=[];for(const t of s){const s=new fe;Us.fromJson(s,t),e.automations.push(s)}return!0;case"dots":return e.dots=s,!0;case"fadein":return e.fadeIn=s,!0;case"lyrics":return e.lyrics=s,!0;case"hasrasgueado":return e.hasRasgueado=s,!0;case"pop":return e.pop=s,!0;case"slap":return e.slap=s,!0;case"tap":return e.tap=s,!0;case"text":return e.text=s,!0;case"brushtype":return e.brushType=Bs.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=Bs.parseEnum(s,C),!0;case"whammybarpoints":if(s){e.whammyBarPoints=[];for(const t of s){const s=new be;qs.fromJson(s,t),e.addWhammyBarPoint(s)}}return!0;case"vibrato":return e.vibrato=Bs.parseEnum(s,w),!0;case"chordid":return e.chordId=s,!0;case"gracetype":return e.graceType=Bs.parseEnum(s,g),!0;case"pickstroke":return e.pickStroke=Bs.parseEnum(s,x),!0;case"tremolospeed":return e.tremoloSpeed=Bs.parseEnum(s,u),!0;case"crescendo":return e.crescendo=Bs.parseEnum(s,d),!0;case"displaystart":return e.displayStart=s,!0;case"playbackstart":return e.playbackStart=s,!0;case"displayduration":return e.displayDuration=s,!0;case"playbackduration":return e.playbackDuration=s,!0;case"dynamics":return e.dynamics=Bs.parseEnum(s,p),!0;case"invertbeamdirection":return e.invertBeamDirection=s,!0;case"preferredbeamdirection":return e.preferredBeamDirection=Bs.parseEnum(s,H),!0;case"beamingmode":return e.beamingMode=Bs.parseEnum(s,F),!0}return!1}}class js{static fromJson(e,t){t&&Bs.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=>Qs.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 De;Qs.fromJson(s,t),e.addBeat(s)}return!0;case"isempty":return e.isEmpty=s,!0}return!1}}class Ks{static fromJson(e,t){t&&Bs.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=>js.toJson(e)))),t.set("similemark",e.simileMark),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"clef":return e.clef=Bs.parseEnum(s,r),!0;case"clefottava":return e.clefOttava=Bs.parseEnum(s,n),!0;case"voices":e.voices=[];for(const t of s){const s=new Qe;js.fromJson(s,t),e.addVoice(s)}return!0;case"similemark":return e.simileMark=Bs.parseEnum(s,o),!0}return!1}}class $s{static fromJson(e,t){t&&Bs.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 Zs{static fromJson(e,t){t&&Bs.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 ei{static fromJson(e,t){t&&Bs.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=>Ks.toJson(e)))),null!==e.chords){const s=new Map;t.set("chords",s);for(const[t,i]of e.chords)s.set(t.toString(),$s.toJson(i))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",Zs.toJson(e.stringTuning)),t.set("showtablature",e.showTablature),t.set("showstandardnotation",e.showStandardNotation),t.set("ispercussion",e.isPercussion),t.set("standardnotationlinecount",e.standardNotationLineCount),t}static setProperty(e,t,s){switch(t){case"bars":e.bars=[];for(const t of s){const s=new me;Ks.fromJson(s,t),e.addBar(s)}return!0;case"chords":return e.chords=new Map,Bs.forEach(s,((t,s)=>{const i=new Re;$s.fromJson(i,t),e.addChord(s,i)})),!0;case"capo":return e.capo=s,!0;case"transpositionpitch":return e.transpositionPitch=s,!0;case"displaytranspositionpitch":return e.displayTranspositionPitch=s,!0;case"showtablature":return e.showTablature=s,!0;case"showstandardnotation":return e.showStandardNotation=s,!0;case"ispercussion":return e.isPercussion=s,!0;case"standardnotationlinecount":return e.standardNotationLineCount=s,!0}return["stringtuning"].indexOf(t)>=0&&(Zs.fromJson(e.stringTuning,s),!0)}}class ti{static fromJson(e,t){t&&Bs.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 si{static fromJson(e,t){t&&Bs.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=Bs.parseEnum(s,N),!0;case"noteheadhalf":return e.noteHeadHalf=Bs.parseEnum(s,N),!0;case"noteheadwhole":return e.noteHeadWhole=Bs.parseEnum(s,N),!0;case"techniquesymbol":return e.techniqueSymbol=Bs.parseEnum(s,N),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=Bs.parseEnum(s,E),!0;case"outputmidinumber":return e.outputMidiNumber=s,!0}return!1}}class ii{static fromJson(e,t){t&&Bs.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=>ei.toJson(e)))),t.set("playbackinfo",ti.toJson(e.playbackInfo)),t.set("color",Ue.toJson(e.color)),t.set("name",e.name),t.set("shortname",e.shortName),t.set("percussionarticulations",e.percussionArticulations.map((e=>si.toJson(e)))),t}static setProperty(e,t,s){switch(t){case"staves":e.staves=[];for(const t of s){const s=new qe;ei.fromJson(s,t),e.addStaff(s)}return!0;case"color":return e.color=Ue.fromJson(s),!0;case"name":return e.name=s,!0;case"shortname":return e.shortName=s,!0;case"percussionarticulations":e.percussionArticulations=[];for(const t of s){const s=new ve;si.fromJson(s,t),e.percussionArticulations.push(s)}return!0}return["playbackinfo"].indexOf(t)>=0&&(ti.fromJson(e.playbackInfo,s),!0)}}class ai{static fromJson(e,t){t&&Bs.forEach(t,((t,s)=>this.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("hidedynamics",e.hideDynamics),t}static setProperty(e,t,s){switch(t){case"hidedynamics":return e.hideDynamics=s,!0}return!1}}class ri{static fromJson(e,t){t&&Bs.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=>Ys.toJson(e)))),t.set("tracks",e.tracks.map((e=>ii.toJson(e)))),t.set("stylesheet",ai.toJson(e.stylesheet)),t}static setProperty(e,t,s){switch(t){case"album":return e.album=s,!0;case"artist":return e.artist=s,!0;case"copyright":return e.copyright=s,!0;case"instructions":return e.instructions=s,!0;case"music":return e.music=s,!0;case"notices":return e.notices=s,!0;case"subtitle":return e.subTitle=s,!0;case"title":return e.title=s,!0;case"words":return e.words=s,!0;case"tab":return e.tab=s,!0;case"tempo":return e.tempo=s,!0;case"tempolabel":return e.tempoLabel=s,!0;case"masterbars":e.masterBars=[];for(const t of s){const s=new Oe;Ys.fromJson(s,t),e.addMasterBar(s)}return!0;case"tracks":e.tracks=[];for(const t of s){const s=new Je;ii.fromJson(s,t),e.addTrack(s)}return!0}return["stylesheet"].indexOf(t)>=0&&(ai.fromJson(e.stylesheet,s),!0)}}class ni{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=ni.scoreToJsObject(e);return JSON.stringify(t,ni.jsonReplacer)}static jsonToScore(e,t){return ni.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return ri.toJson(e)}static jsObjectToScore(e,t){let s=new He;return ri.fromJson(s,e),s.finish(null!=t?t:new Hs),s}static settingsToJson(e){let t=ni.settingsToJsObject(e);return JSON.stringify(t,ni.jsonReplacer)}static jsonToSettings(e){return ni.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return Vs.toJson(e)}static jsObjectToSettings(e){let t=new Hs;return Vs.fromJson(t,e),t}static jsObjectToMidiFile(e){let t=new Ss;t.division=e.division;let s=e.events;for(let e of s){let s=ni.jsObjectToMidiEvent(e);t.events.push(s)}return t}static jsObjectToMidiEvent(e){let t,s=e.track,i=e.tick,a=e.message;switch(e.type){case"SystemExclusiveEvent":t=new At(s,i,0,0,e.data),t.message=a;break;case"MetaDataEvent":t=new ws(s,i,0,0,e.data),t.message=a;break;case"MetaNumberEvent":t=new _s(s,i,0,0,e.value),t.message=a;break;case"Midi20PerNotePitchBendEvent":t=new Ws(s,i,0,e.noteKey,e.pitch),t.message=a;break;default:t=new It(s,i,0,0,0),t.message=a}return t}static midiFileToJsObject(e){let t={};t.division=e.division;let s=[];t.events=s;for(let t of e.events)s.push(ni.midiEventToJsObject(t));return t}static midiEventToJsObject(e){let t={};return t.track=e.track,t.tick=e.tick,t.message=e.message,e instanceof At?(t.type="SystemExclusiveEvent",t.data=e.data):e instanceof ws?(t.type="MetaDataEvent",t.data=e.data):e instanceof _s?(t.type="MetaNumberEvent",t.value=e.value):e instanceof Ws&&(t.type="Midi20PerNotePitchBendEvent",t.noteKey=e.noteKey,t.pitch=e.pitch),t}}class oi{constructor(){this.ready=new fs,this.samplesPlayed=new ms,this.sampleRequest=new fs}get sampleRate(){return oi.preferredSampleRate}open(){Be.debug("AlphaSynth","Initializing webworker worker"),this._worker=ho.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 oi.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case oi.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(){}}oi.CmdOutputPrefix="alphaSynth.output.",oi.CmdOutputAddSamples=oi.CmdOutputPrefix+"addSamples",oi.CmdOutputPlay=oi.CmdOutputPrefix+"play",oi.CmdOutputPause=oi.CmdOutputPrefix+"pause",oi.CmdOutputResetSamples=oi.CmdOutputPrefix+"resetSamples",oi.CmdOutputSampleRequest=oi.CmdOutputPrefix+"sampleRequest",oi.CmdOutputSamplesPlayed=oi.CmdOutputPrefix+"samplesPlayed",oi.preferredSampleRate=0;class hi{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new bs(new oi),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._main.postMessage({cmd:"alphaSynth.ready"})}static init(){let e=ho.globalThis;e.addEventListener("message",(t=>{let s=t.data;switch(s.cmd){case"alphaSynth.initialize":oi.preferredSampleRate=s.sampleRate,Be.logLevel=s.logLevel,ho.globalThis.alphaSynthWebWorker=new hi(e)}}))}handleMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":Be.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(ni.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(ni.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);break;case"alphaSynth.setChannelSolo":this._player.setChannelSolo(t.channel,t.solo);break;case"alphaSynth.setChannelVolume":this._player.setChannelVolume(t.channel,t.volume);break;case"alphaSynth.resetChannelStates":this._player.resetChannelStates();break;case"alphaSynth.destroy":this._player.destroy(),this._main.postMessage({cmd:"alphaSynth.destroyed"})}}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(ni.midiEventToJsObject)})}}class li{static generateFontLookup(e){if(!li.FontSizeLookupTables.has(e))if(ho.isRunningInWorker)li.FontSizeLookupTables.set(e,new Uint8Array([8]));else{let t=document.createElement("canvas").getContext("2d");t.font="11px "+e;let s=[];for(let e=32;e<255;e++){let i=String.fromCharCode(e);s.push(t.measureText(i).width)}let i=new Uint8Array(s);li.FontSizeLookupTables.set(e,i)}}static measureString(e,t,s,i,a){let r;li.FontSizeLookupTables.has(t)||li.generateFontLookup(t),r=li.FontSizeLookupTables.get(t);let n=1;i===$.Italic&&(n*=1.2),a===Z.Bold&&(n*=1.2);let o=0;for(let t=0;t<e.length;t++){let i=Math.min(r.length-1,e.charCodeAt(t)-32);i>=0&&(o+=r[i]*s/11)}return o*n}}li.Georgia=new Uint8Array([3,4,5,7,7,9,8,2,4,4,5,7,3,4,3,5,7,5,6,6,6,6,6,6,7,6,3,3,7,7,7,5,10,7,7,7,8,7,7,8,9,4,6,8,7,10,8,8,7,8,8,6,7,8,7,11,8,7,7,4,5,4,7,7,6,6,6,5,6,5,4,6,6,3,3,6,3,10,6,6,6,6,5,5,4,6,5,8,6,5,5,5,4,5,7,6,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,3,4,6,7,6,7,4,6,6,10,6,6,7,0,10,7,5,7,6,6,6,6,6,3,6,6,6,6,12,12,12,5,7,7,7,7,7,7,11,7,7,7,7,7,4,4,4,4,8,8,8,8,8,8,8,7,8,8,8,8,8,7,7,6,6,6,6,6,6,6,8,5,5,5,5,5,3,3,3,3,6,6,6,6,6,6,6,7,6,6,6,6,6,5,6]),li.Arial=new Uint8Array([3,3,4,6,6,10,7,2,4,4,4,6,3,4,3,3,6,6,6,6,6,6,6,6,6,6,3,3,6,6,6,6,11,7,7,8,8,7,7,9,8,3,6,7,6,9,8,9,7,9,8,7,7,8,7,10,7,7,7,3,3,3,5,6,4,6,6,6,6,6,3,6,6,2,2,6,2,9,6,6,6,6,4,6,3,6,6,8,6,6,6,4,3,4,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,4,6,6,6,6,3,6,4,8,4,6,6,0,8,6,4,6,4,4,4,6,6,4,4,4,4,6,9,9,9,7,7,7,7,7,7,7,11,8,7,7,7,7,3,3,3,3,8,8,9,9,9,9,9,6,9,8,8,8,8,7,7,7,6,6,6,6,6,6,10,6,6,6,6,6,3,3,3,3,6,6,6,6,6,6,6,6,7,6,6,6,6,6,6]),li.FontSizeLookupTables=new Map([["Arial",li.Arial],["'Arial'",li.Arial],['"Arial"',li.Arial],["Georgia",li.Georgia],["'Georgia'",li.Georgia],['"Georgia"',li.Georgia]]),li.ControlChars=32;class ci{constructor(){this.id=ke.newGuid(),this.x=0,this.y=0,this.width=0,this.height=0,this.totalWidth=0,this.totalHeight=0,this.firstMasterBarIndex=0,this.lastMasterBarIndex=0,this.renderResult=null}}class di{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}}class ui{constructor(){this.notes=null}addNote(e){this.notes||(this.notes=[]),e.beatBounds=this,this.notes.push(e)}findNoteAtPos(e,t){const s=this.notes;if(!s)return null;for(let i of s){let s=i.noteHeadBounds.y+i.noteHeadBounds.h,a=i.noteHeadBounds.x+i.noteHeadBounds.w;if(i.noteHeadBounds.x>=e&&i.noteHeadBounds.y>=t&&e<=a&&t<=s)return i.note}return null}}class pi{constructor(){this.index=0,this.isFirstOfLine=!1,this.bars=[],this.staveGroupBounds=null}addBar(e){e.masterBarBounds=this,this.bars.push(e)}findBeatAtPos(e,t){let s=null;for(let t of this.bars){let i=t.findBeatAtPos(e);i&&(!s||s.realBounds.x<i.realBounds.x)&&(s=i)}return s?s.beat:null}finish(){this.bars.sort(((e,t)=>e.realBounds.y<t.realBounds.y?-1:e.realBounds.y>t.realBounds.y?1:e.realBounds.x<t.realBounds.x?-1:e.realBounds.x>t.realBounds.x?1:0))}addBeat(e){this.staveGroupBounds.boundsLookup.addBeat(e)}}class gi{}class fi{constructor(){this.index=0,this.bars=[]}finish(){for(let e of this.bars)e.finish()}addBar(e){this.boundsLookup.addMasterBar(e),e.staveGroupBounds=this,this.bars.push(e)}findBarAtPos(e){let t=null;for(let s of this.bars)if(!t||s.realBounds.x<e)t=s;else if(e>s.realBounds.x+s.realBounds.w)break;return t}}class mi{constructor(){this._beatLookup=new Map,this._masterBarLookup=new Map,this._currentStaveGroup=null,this.staveGroups=[],this.isFinished=!1}toJson(){let e={},t=[];e.staveGroups=t;for(let e of this.staveGroups){let s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.bars=[];for(let t of e.bars){let e={};e.lineAlignedBounds=this.boundsToJson(t.lineAlignedBounds),e.visualBounds=this.boundsToJson(t.visualBounds),e.realBounds=this.boundsToJson(t.realBounds),e.index=t.index,e.bars=[];for(let s of t.bars){let t={};t.visualBounds=this.boundsToJson(s.visualBounds),t.realBounds=this.boundsToJson(s.realBounds),t.beats=[];for(let e of s.beats){let s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds);let i=s;if(i.beatIndex=e.beat.index,i.voiceIndex=e.beat.voice.index,i.barIndex=e.beat.voice.bar.index,i.staffIndex=e.beat.voice.bar.staff.index,i.trackIndex=e.beat.voice.bar.staff.track.index,e.notes){let t=s.notes=[];for(let s of e.notes){let e={};e.index=s.note.index,e.noteHeadBounds=this.boundsToJson(s.noteHeadBounds),t.push(e)}}t.beats.push(s)}e.bars.push(t)}s.bars.push(e)}t.push(s)}return e}static fromJson(e,t){let s=new mi,i=e.staveGroups;for(let e of i){let i=new fi;i.visualBounds=e.visualBounds,i.realBounds=e.realBounds,s.addStaveGroup(i);for(let s of e.bars){let e=new pi;e.index=s.index,e.isFirstOfLine=s.isFirstOfLine,e.lineAlignedBounds=s.lineAlignedBounds,e.visualBounds=s.visualBounds,e.realBounds=s.realBounds,i.addBar(e);for(let i of s.bars){let s=new di;s.visualBounds=i.visualBounds,s.realBounds=i.realBounds,e.addBar(s);for(let e of i.beats){let i=new ui;i.visualBounds=e.visualBounds,i.realBounds=e.realBounds;let a=e;if(i.beat=t.tracks[a.trackIndex].staves[a.staffIndex].bars[a.barIndex].voices[a.voiceIndex].beats[a.beatIndex],e.notes){i.notes=[];for(let t of e.notes){let e=new gi,s=t;e.note=i.beat.notes[s.index],e.noteHeadBounds=t.noteHeadBounds,i.addNote(e)}}s.addBeat(i)}}}}return s}boundsToJson(e){let t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(){for(let e of this.staveGroups)e.finish();this.isFinished=!0}addNote(e){this.findBeat(e.note.beat).addNote(e)}addStaveGroup(e){e.index=this.staveGroups.length,e.boundsLookup=this,this.staveGroups.push(e),this._currentStaveGroup=e}addMasterBar(e){e.staveGroupBounds?this._masterBarLookup.set(e.index,e):(e.staveGroupBounds=this._currentStaveGroup,this._masterBarLookup.set(e.index,e),this._currentStaveGroup.addBar(e))}addBeat(e){this._beatLookup.set(e.beat.id,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){let t=e.id;return this._beatLookup.has(t)?this._beatLookup.get(t):null}getBeatAtPos(e,t){let s=0,i=this.staveGroups.length-1,a=-1;for(;s<=i;){let e=(i+s)/2|0,r=this.staveGroups[e];if(t>=r.realBounds.y&&t<=r.realBounds.y+r.realBounds.h){a=e;break}t<r.realBounds.y?i=e-1:s=e+1}if(-1===a)return null;let r=this.staveGroups[a].findBarAtPos(e);return r?r.findBeatAtPos(e,t):null}getNoteAtPos(e,t,s){let i=this.findBeat(e);return i?i.findNoteAtPos(t,s):null}}class yi{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 ms,this.renderFinished=new ms,this.partialRenderFinished=new ms,this.partialLayoutFinished=new ms,this.postRenderFinished=new fs,this.error=new ms,this.settings=t,this.recreateCanvas(),this.recreateLayout()}destroy(){this.score=null,this.canvas=null,this.layout=null,this.boundsLookup=null,this.tracks=null}recreateCanvas(){return this._currentRenderEngine!==this.settings.core.engine&&(this.canvas=ho.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=ho.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?(Be.debug("Rendering","Request render of lazy partial "+e),t.renderLazyPartial(e)):Be.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 mi,this.recreateCanvas(),this.canvas.lineWidth=this.settings.display.scale,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){Be.debug("Rendering","Rendering "+this.tracks.length+" tracks");for(let e=0;e<this.tracks.length;e++){let t=this.tracks[e];Be.debug("Rendering","Track "+e+": "+t.name)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),Be.debug("Rendering","Rendering finished")}else Be.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),Be.debug("Rendering","Clearing finished");else Be.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(Be.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(Be.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new mi,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):Be.warning("Rendering","Current layout does not support dynamic resizing, nothing was done",null),Be.debug("Rendering","Resize finished")}layoutAndRender(){Be.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(){const e=new ci;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}class bi{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){ho.globalThis.alphaTabWebWorker=new bi(ho.globalThis)}handleMessage(e){let t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":let e=ni.jsObjectToSettings(t.settings);Be.logLevel=e.core.logLevel,this._renderer=new yi(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((()=>{var e,t;this._main.postMessage({cmd:"alphaTab.postRenderFinished",boundsLookup:null!==(t=null===(e=this._renderer.boundsLookup)||void 0===e?void 0:e.toJson())&&void 0!==t?t: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:ni.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(s,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(e){li.FontSizeLookupTables||(li.FontSizeLookupTables=new Map);for(let t in e)li.FontSizeLookupTables.set(t,e[t])}}updateSettings(e){Vs.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){Be.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class Si{constructor(){this._canvas=null,this._color=new Ue(0,0,0,255),this._font=new vs("Arial",10,$.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 vs(s,parseFloat(t.fontSize),$.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"}onRenderFinished(){return null}beginRender(e,t){this._canvas=document.createElement("canvas"),this._canvas.width=e*ho.HighDpiFactor|0,this._canvas.height=t*ho.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(ho.HighDpiFactor,ho.HighDpiFactor),this._context.lineWidth=this._lineWidth}endRender(){let e=this._canvas;return this._canvas=null,e}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._context.strokeStyle=e.rgba,this._context.fillStyle=e.rgba)}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._context&&(this._context.lineWidth=e)}fillRect(e,t,s,i){s>0&&this._context.fillRect(0|e,0|t,s,i)}strokeRect(e,t,s,i){this._context.strokeRect(0|e,0|t,s,i)}beginPath(){this._context.beginPath()}closePath(){this._context.closePath()}moveTo(e,t){this._context.moveTo(e,t)}lineTo(e,t){this._context.lineTo(e,t)}quadraticCurveTo(e,t,s,i){this._context.quadraticCurveTo(e,t,s,i)}bezierCurveTo(e,t,s,i,a,r){this._context.bezierCurveTo(e,t,s,i,a,r)}fillCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.fill()}strokeCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.stroke()}fill(){this._context.fill(),this._context.beginPath()}stroke(){this._context.stroke(),this._context.beginPath()}get font(){return this._font}set font(e){this._font=e,this._context&&(this._context.font=e.toCssString(this.settings.display.scale)),this._measureContext.font=e.toCssString(this.settings.display.scale)}get textAlign(){switch(this._context.textAlign){case"left":return P.Left;case"center":return P.Center;case"right":return P.Right;default:return P.Left}}set textAlign(e){switch(e){case P.Left:this._context.textAlign="left";break;case P.Center:this._context.textAlign="center";break;case P.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":return E.Top;case"middle":return E.Middle;case"bottom":return E.Bottom;default:return E.Top}}set textBaseline(e){switch(e){case E.Top:this._context.textBaseline="hanging";break;case E.Middle:this._context.textBaseline="middle";break;case E.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,s){this._context.fillText(e,t,s)}measureText(e){return this._measureContext.measureText(e).width}fillMusicFontSymbol(e,t,s,i,a=!1){i!==N.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a=!1){let r="";for(let e of i)e!==N.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a=!1){let r=this._context.textAlign,n=this._context.textBaseline,o=this._context.font;this._context.font=this._musicFont.toCssString(s),this._context.textBaseline="middle",this._context.textAlign=a?"center":"left",this._context.fillText(i,e,t),this._context.textBaseline=n,this._context.font=o,this._context.textAlign=r}beginRotate(e,t,s){this._context.save(),this._context.translate(e,t),this._context.rotate(s*Math.PI/180)}endRotate(){this._context.restore()}}class wi{constructor(e){this._midiFile=e}addTimeSignature(e,t,s){let i=0;for(;(s>>=1)>0;)i++;const a=new ws(0,e,255,U.TimeSignature,new Uint8Array([255&t,255&i,48,8]));this._midiFile.addEvent(a)}addRest(e,t,s){const i=new At(e,t,X.SystemExclusive,At.AlphaTabManufacturerId,new Uint8Array([Y.Rest]));this._midiFile.addEvent(i)}addNote(e,t,s,i,a,r){const n=ye.dynamicToVelocity(a),o=new It(e,t,this.makeCommand(z.NoteOn,r),wi.fixValue(i),wi.fixValue(n));this._midiFile.addEvent(o);const h=new It(e,t+s,this.makeCommand(z.NoteOff,r),wi.fixValue(i),wi.fixValue(n));this._midiFile.addEvent(h)}makeCommand(e,t){return 240&e|15&t}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,s,i,a){const r=new It(e,t,this.makeCommand(z.Controller,s),wi.fixValue(i),wi.fixValue(a));this._midiFile.addEvent(r)}addProgramChange(e,t,s,i){const a=new It(e,t,this.makeCommand(z.ProgramChange,s),wi.fixValue(i),0);this._midiFile.addEvent(a)}addTempo(e,t){const s=6e7/t|0,i=new _s(0,e,255,U.Tempo,s);this._midiFile.addEvent(i)}addBend(e,t,s,i){i=i>=Gt.MaxPitchWheel?Gt.MaxPitchWheel:Math.floor(i);const a=new It(e,t,this.makeCommand(z.PitchBend,s),127&i,i>>7&127);this._midiFile.addEvent(a)}addNoteBend(e,t,s,i,a){a=(a=a>=Gt.MaxPitchWheel?Gt.MaxPitchWheel:Math.floor(a))*Gt.MaxPitchWheel20/Gt.MaxPitchWheel;const r=new Ws(e,t,this.makeCommand(z.PerNotePitchBend,s),i,a);this._midiFile.addEvent(r)}finishTrack(e,t){const s=new ws(e,t,255,U.EndOfTrack,new Uint8Array(0));this._midiFile.addEvent(s)}}class _i{constructor(){this._highlightedBeats=new Map,this.index=0,this.start=0,this.end=0,this.isEmptyBar=!1,this.beatsToHighlight=[]}highlightBeat(e){this._highlightedBeats.has(e.id)||(this._highlightedBeats.set(e.id,!0),this.beatsToHighlight.push(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.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.ResetControllers=121]="ResetControllers",e[e.AllNotesOff=123]="AllNotesOff"}(te||(te={}));class Bi{constructor(e){this._repeatStartIndex=0,this._repeatNumber=0,this._repeatOpen=!1,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}get finished(){return this.index>=this._score.masterBars.length}processCurrent(){const e=this._score.masterBars[this.index],t=e.alternateEndings;e.repeatGroup.isClosed||e.repeatGroup.openings[e.repeatGroup.openings.length-1]!==e||(this._repeatNumber=0,this._repeatOpen=!1),!e.isRepeatStart&&0!==e.index||0!==this._repeatNumber?e.isRepeatStart&&(this.shouldPlay=!0):(this._repeatStartIndex=this.index,this._repeatOpen=!0),this._repeatOpen&&t>0&&(0==(t&1<<this._repeatNumber)?this.shouldPlay=!1:this.shouldPlay=!0),this.shouldPlay&&(this.currentTick+=e.calculateDuration())}moveNext(){const e=this._score.masterBars[this.index].repeatCount-1;this._repeatOpen&&e>0?this._repeatNumber<e?(this.index=this._repeatStartIndex,this._repeatNumber++):(this._repeatNumber=0,this._repeatOpen=!1,this.shouldPlay=!0,this.index++):this.index++}}class Ti{constructor(){this.start=0,this.end=0,this.tempo=0,this.beats=[],this.nextMasterBar=null}finish(){this.beats.sort(((e,t)=>e.start-t.start))}addBeat(e){e.masterBar=this,e.index=this.beats.length,this.beats.push(e)}}class ki{constructor(){this.duration=0,this.nextBeatLookup=null}get currentBeat(){return this.currentBeatLookup.beat}get nextBeat(){var e,t;return null!==(t=null===(e=this.nextBeatLookup)||void 0===e?void 0:e.beat)&&void 0!==t?t:null}}class vi{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[]}finish(){let e=null,t=[];for(let s of this.masterBars){s.finish(),e&&(e.nextMasterBar=s);for(const e of s.beats){const s=[];for(let i of t)i.end>e.start&&(s.push(i),e.highlightBeat(i.beat),e.start<=i.start&&i.highlightBeat(e.beat));s.push(e),t=s}e=s}}findBeat(e,t,s=null){const i=new Map;for(const t of e)i.set(t.index,!0);let a=null;return s&&(a=this.findBeatFast(i,s,t)),a||(a=this.findBeatSlow(i,t)),a}findBeatFast(e,t,s){return s>=t.currentBeatLookup.start&&s<t.currentBeatLookup.end?t:t.nextBeatLookup&&s>=t.nextBeatLookup.start&&s<t.nextBeatLookup.end?this.createResult(t.nextBeatLookup,e):null}findBeatSlow(e,t){const s=this.findMasterBar(t);if(!s)return null;let i=null,a=s.beats;for(let s=0;s<a.length;s++){let r=a[s];if(e.has(r.beat.voice.bar.staff.track.index))if(r.start<=t&&t<r.end)(!i||i.start<r.start)&&(i=a[s]);else if(r.end>t)break}return i?this.createResult(i,e):null}createResult(e,t){const s=this.findNextBeat(e,t),i=new ki;return i.currentBeatLookup=e,i.nextBeatLookup=s,i.duration=s?ye.ticksToMillis(s.start-e.start,e.masterBar.tempo):ye.ticksToMillis(e.end-e.start,e.masterBar.tempo),i.beatsToHighlight=e.beatsToHighlight,i}findNextBeat(e,t){const s=e.masterBar;let i=s.beats,a=null;for(let s=e.index+1;s<i.length;s++){const r=i[s];if(r.start>e.start&&t.has(r.beat.voice.bar.staff.track.index)){a=r;break}}if(!a&&s.nextMasterBar){i=s.nextMasterBar.beats;for(let e=0;e<i.length;e++){const s=i[e];if(t.has(s.beat.voice.bar.staff.track.index)){a=s;break}}}return a}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 Ti;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}addMasterBar(e){this.masterBars.push(e),this._currentMasterBar=e,this.masterBarLookup.has(e.masterBar.index)||this.masterBarLookup.set(e.masterBar.index,e)}addBeat(e){var t;null===(t=this._currentMasterBar)||void 0===t||t.addBeat(e)}}class xi{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Ni{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class Pi{constructor(e,t,s){this._currentTempo=0,this._currentBarRepeatLookup=null,this._programsPerChannel=new Map,this.tickLookup=new vi,this._currentTripletFeel=null,this._score=e,this._settings=t||new Hs,this._currentTempo=this._score.tempo,this._handler=s}generate(){for(const e of this._score.tracks)this.generateTrack(e);Be.debug("Midi","Begin midi generation");const e=new Bi(this._score);let t=null;for(;!e.finished;){const s=e.index,i=this._score.masterBars[s],a=e.currentTick;if(e.processCurrent(),e.shouldPlay){this.generateMasterBar(i,t,a);for(const e of this._score.tracks)for(const t of e.staves)s<t.bars.length&&this.generateBar(t.bars[s],a)}e.moveNext(),t=i}for(const t of this._score.tracks)this._handler.finishTrack(t.index,e.currentTick);this.tickLookup.finish(),Be.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))}generateChannel(e,t,s){let i=Pi.toChannelShort(s.volume),a=Pi.toChannelShort(s.balance);this._handler.addControlChange(e.index,0,t,te.VolumeCoarse,i),this._handler.addControlChange(e.index,0,t,te.PanCoarse,a),this._handler.addControlChange(e.index,0,t,te.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,te.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,te.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,te.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,te.DataEntryCoarse,Pi.PitchBendRangeInSemitones),this.addProgramChange(e,0,t,s.program)}static toChannelShort(e){const t=Math.max(-32768,Math.min(32767,8*e-1));return Math.max(t,-1)+1}generateMasterBar(e,t,s){t&&t.timeSignatureDenominator===e.timeSignatureDenominator&&t.timeSignatureNumerator===e.timeSignatureNumerator||this._handler.addTimeSignature(s,e.timeSignatureNumerator,e.timeSignatureDenominator),t?e.tempoAutomation&&(this._handler.addTempo(s,e.tempoAutomation.value),this._currentTempo=e.tempoAutomation.value):(this._handler.addTempo(s,e.score.tempo),this._currentTempo=e.score.tempo);const i=new Ti;i.masterBar=e,i.start=s,i.tempo=this._currentTempo,i.end=i.start+e.calculateDuration(),this.tickLookup.addMasterBar(i)}generateBar(e,t){let s=this.getPlaybackBar(e);this._currentBarRepeatLookup=null;for(const i of s.voices)this.generateVoice(i,t,e)}getPlaybackBar(e){switch(e.simileMark){case o.Simple:e.previousBar&&(e=this.getPlaybackBar(e.previousBar));break;case o.FirstOfDouble:case o.SecondOfDouble:e.previousBar&&e.previousBar.previousBar&&(e=this.getPlaybackBar(e.previousBar.previousBar))}return e}generateVoice(e,t,s){if(!e.isEmpty||e.bar.isEmpty&&0===e.index)for(const i of e.beats)this.generateBeat(i,t,s)}generateBeat(e,t,s){let i=e.playbackStart,a=e.playbackDuration;e.voice.bar.isEmpty?a=e.voice.bar.masterBar.calculateDuration():e.voice.bar.masterBar.tripletFeel!==D.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(i-=this._currentTripletFeel.secondBeatStartOffset,a=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=Pi.calculateTripletFeelInfo(i,a,e),this._currentTripletFeel&&(a=this._currentTripletFeel.firstBeatDuration)));const r=new _i;r.start=t+i;const n=e.nextBeat?e.nextBeat.absolutePlaybackStart-e.absolutePlaybackStart:a;r.end=t+i,r.highlightBeat(e),r.end+=n>a?n:a,s===e.voice.bar?(r.beat=e,this.tickLookup.addBeat(r)):(r.isEmptyBar=!0,r.beat=s.voices[0].beats[0],this._currentBarRepeatLookup?this._currentBarRepeatLookup.end=r.end:(this._currentBarRepeatLookup=r,this.tickLookup.addBeat(this._currentBarRepeatLookup)));const o=e.voice.bar.staff.track;for(const s of e.automations)this.generateAutomation(e,s,t);if(e.isRest)this._handler.addRest(o.index,t+i,o.playbackInfo.primaryChannel);else{let s=this.getBrushInfo(e);for(const r of e.notes)this.generateNote(r,t+i,a,s)}if(e.vibrato!==w.None){let s=240,a=3;switch(e.vibrato){case w.Slight:s=this._settings.player.vibrato.beatSlightLength,a=this._settings.player.vibrato.beatSlightAmplitude;break;case w.Wide:s=this._settings.player.vibrato.beatWideLength,a=this._settings.player.vibrato.beatWideAmplitude}this.generateVibratorWithParams(t+i,e.playbackDuration,s,a,((t,s)=>{this._handler.addBend(e.voice.bar.staff.track.index,t,o.playbackInfo.secondaryChannel,s)}))}}static calculateTripletFeelInfo(e,t,s){let i;switch(s.voice.bar.masterBar.tripletFeel){case D.Triplet8th:case D.Dotted8th:case D.Scottish8th:i=u.Eighth;break;case D.Triplet16th:case D.Dotted16th:case D.Scottish16th:i=u.Sixteenth;break;default:return null}const a=ye.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 Ni;switch(s.voice.bar.masterBar.tripletFeel){case D.Triplet8th:r.firstBeatDuration=ye.applyTuplet(ye.toTicks(u.Quarter),3,2),r.secondBeatDuration=ye.applyTuplet(ye.toTicks(u.Eighth),3,2);break;case D.Dotted8th:r.firstBeatDuration=ye.applyDot(ye.toTicks(u.Eighth),!1),r.secondBeatDuration=ye.toTicks(u.Sixteenth);break;case D.Scottish8th:r.firstBeatDuration=ye.toTicks(u.Sixteenth),r.secondBeatDuration=ye.applyDot(ye.toTicks(u.Eighth),!1);break;case D.Triplet16th:r.firstBeatDuration=ye.applyTuplet(ye.toTicks(u.Eighth),3,2),r.secondBeatDuration=ye.applyTuplet(ye.toTicks(u.Sixteenth),3,2);break;case D.Dotted16th:r.firstBeatDuration=ye.applyDot(ye.toTicks(u.Sixteenth),!1),r.secondBeatDuration=ye.toTicks(u.ThirtySecond);break;case D.Scottish16th:r.firstBeatDuration=ye.toTicks(u.ThirtySecond),r.secondBeatDuration=ye.applyDot(ye.toTicks(u.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateNote(e,t,s,i){const a=e.beat.voice.bar.staff.track,r=e.beat.voice.bar.staff;let n=e.realValue;if(e.isPercussion){const t=xe.getArticulation(e);t&&(n=t.outputMidiNumber)}const o=e.isStringed&&e.string<=i.length?i[e.string-1]:0,h=t+o,l=this.getNoteDuration(e,s);l.untilTieOrSlideEnd-=o,l.noteOnly-=o,l.letRingEnd-=o;const c=Pi.getDynamicValue(e),d=e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==w.None?a.playbackInfo.secondaryChannel:a.playbackInfo.primaryChannel;let u=0;if(u=e.hasBend?Pi.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?Pi.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===S.Legato?-1:Pi.getPitchWheel(0),u>=0&&this._handler.addNoteBend(a.index,h,d,n,u),e.beat.fadeIn&&this.generateFadeIn(e,h,l),!e.isTrill||r.isPercussion){if(e.beat.isTremolo)this.generateTremoloPicking(e,h,l,n,c,d);else if(e.hasBend?this.generateBend(e,h,l,n,d):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,h,l,d):e.slideInType!==b.None||e.slideOutType!==S.None?this.generateSlide(e,h,l,n,c,d):e.vibrato!==w.None&&this.generateVibrato(e,h,l,n,d),!(e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===S.Legato)){let e=Math.max(l.untilTieOrSlideEnd,l.letRingEnd);this._handler.addNote(a.index,h,e,n,c,d)}}else this.generateTrill(e,h,l,n,c,d)}getNoteDuration(e,t){const s=new xi;if(s.noteOnly=t,s.untilTieOrSlideEnd=t,s.letRingEnd=t,e.isDead)return s.noteOnly=this.applyStaticDuration(Pi.DefaultDurationDead,t),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(e.isPalmMute)return s.noteOnly=this.applyStaticDuration(Pi.DefaultDurationPalmMute,t),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(e.isStaccato)return s.noteOnly=t/2|0,s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(e.isTieOrigin){const i=e.tieDestination;if(i)if(e.isTieDestination){const e=this.getNoteDuration(i,i.beat.playbackDuration);s.untilTieOrSlideEnd=t+e.untilTieOrSlideEnd}else{const t=e.beat.absolutePlaybackStart,a=this.getNoteDuration(i,i.beat.playbackDuration),r=i.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-t}}else if(e.slideOutType===S.Legato){const t=e.slideTarget;if(t){const i=e.beat.absolutePlaybackStart,a=this.getNoteDuration(t,t.beat.playbackDuration),r=t.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-i}}if(e.isLetRing&&this._settings.notation.notationMode===T.GuitarPro){let i=e.beat,a=0;const r=e.beat.voice.bar.masterBar.calculateDuration();for(;i.nextBeat;){let t=i.nextBeat;if(t.isRest)break;if(e.isStringed&&t.hasNoteOnString(e.string))break;if(i=i.nextBeat,a=i.absolutePlaybackStart-e.beat.absolutePlaybackStart+i.playbackDuration,a>r){a=r;break}}i===e.beat?s.letRingEnd=t:s.letRingEnd=a}else s.letRingEnd=s.untilTieOrSlideEnd;return s}applyStaticDuration(e,t){const s=this._currentTempo*e/be.MaxPosition|0;return Math.min(s,t)}static getDynamicValue(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 t<0&&(t=0),t}generateFadeIn(e,t,s){const i=e.beat.voice.bar.staff.track,a=Pi.toChannelShort(i.playbackInfo.volume)/s.noteOnly,r=s.noteOnly/120|0,n=t+s.noteOnly;for(let e=r-1;e>=0;e--){const s=n-120*e,o=(s-t)*a;e===r-1&&(this._handler.addControlChange(i.index,t,i.playbackInfo.primaryChannel,te.VolumeCoarse,o),this._handler.addControlChange(i.index,t,i.playbackInfo.secondaryChannel,te.VolumeCoarse,o)),this._handler.addControlChange(i.index,s,i.playbackInfo.primaryChannel,te.VolumeCoarse,o),this._handler.addControlChange(i.index,s,i.playbackInfo.secondaryChannel,te.VolumeCoarse,o)}}generateVibrato(e,t,s,i,a){let r=0,n=0;switch(e.vibrato){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;this.generateVibratorWithParams(t,s.noteOnly,r,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)}))}generateVibratorWithParams(e,t,s,i,a){const r=s/2|0,n=(e+=s)+t;for(;e<n;){let t=0;const o=e+s<n?s:n-e;for(;t<o;){let s=i*Math.sin(t*Math.PI/r);a(e+t|0,Pi.getPitchWheel(s)),t+=16}e+=s}}static getPitchWheel(e){return Gt.DefaultPitchWheel+e/2*Pi.PitchValuePerSemitone}generateSlide(e,t,s,i,a,r){let n=e.slideOutType===S.Legato?s.noteOnly:s.untilTieOrSlideEnd,o=[],h=e.beat.voice.bar.staff.track;const l=this._settings.player.slide.simpleSlidePitchOffset,c=Math.floor(be.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),d=Math.floor(be.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case b.IntoFromAbove:o.push(new be(0,l)),o.push(new be(c,0));break;case b.IntoFromBelow:o.push(new be(0,-l)),o.push(new be(c,0))}switch(e.slideOutType){case S.Legato:case S.Shift:o.push(new be(d,0));const t=2*(e.slideTarget.realValue-e.realValue);o.push(new be(be.MaxPosition,t));break;case S.OutDown:o.push(new be(be.MaxPosition-c,0)),o.push(new be(be.MaxPosition,-l));break;case S.OutUp:o.push(new be(be.MaxPosition-c,0)),o.push(new be(be.MaxPosition,l))}this.generateWhammyOrBend(t,n,o,((e,t)=>{this._handler.addNoteBend(h.index,e,r,i,t)}))}generateBend(e,t,s,i,a){let r=e.bendPoints,n=e.beat.voice.bar.staff.track;const o=(e,t)=>{this._handler.addNoteBend(n.index,e,a,i,t)};let c,d=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend;)t=t.tieDestination;c=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==g.None){switch(e.tieDestination.bendType){case l.Bend:case l.BendRelease:case l.PrebendBend:d=e.tieDestination.bendPoints[1].value;break;case l.Prebend:case l.PrebendRelease:d=e.tieDestination.bendPoints[0].value}c=Math.max(s.noteOnly,ye.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo))}else c=s.noteOnly;r[0].value>0&&!e.isContinuedBend&&t>0&&t--;const u=Math.min(c,ye.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));let p=[];switch(e.bendType){case l.Custom:p=r;break;case l.Bend:case l.Release:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),p.push(new be(be.MaxPosition,d));break;case h.Fast:return(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),void(e.beat.graceType===g.BendGrace?this.generateSongBookWhammyOrBend(t,c,!0,[e.bendPoints[0].value,d],u,o):this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,d],u,o))}break;case l.BendRelease:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),p.push(new be(be.MaxPosition/2|0,e.bendPoints[1].value)),p.push(new be(be.MaxPosition,e.bendPoints[2].value));break;case h.Fast:return void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],u,o)}break;case l.Hold:case l.Prebend:p=r;break;case l.PrebendBend:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),p.push(new be(be.MaxPosition,e.bendPoints[1].value));break;case h.Fast:return o(t,0|Pi.getPitchWheel(e.bendPoints[0].value)),(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,d],u,o)}break;case l.PrebendRelease:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),p.push(new be(be.MaxPosition,e.bendPoints[1].value));break;case h.Fast:return o(t,0|Pi.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,c,!1,[e.bendPoints[0].value,e.bendPoints[1].value],u,o)}}this.generateWhammyOrBend(t,c,p,o)}generateSongBookWhammyOrBend(e,t,s,i,a,r){const n=s?e:e+t-a,o=a/(i.length-1);for(let e=0;e<i.length-1;e++){const t=Pi.getPitchWheel(i[e]),s=Pi.getPitchWheel(i[e+1]),a=n+o*e;this.generateBendValues(a,o,t,s,r)}}generateWhammy(e,t,s,i){const a=e.whammyBarPoints,r=e.voice.bar.staff.track,n=s.noteOnly;a[0].value>0&&!e.isContinuedWhammy&&t--;const o=(e,t)=>{this._handler.addBend(r.index,e,i,t)};let l=[];switch(e.whammyBarType){case C.Custom:l=a;break;case C.Dive:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new be(0,a[0].value)),l.push(new be(be.MaxPosition,a[1].value));break;case h.Fast:const e=Math.min(n,ye.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],e,o)}break;case C.Dip:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new be(0,a[0].value)),l.push(new be(be.MaxPosition/2|0,a[1].value)),l.push(new be(be.MaxPosition,a[2].value));break;case h.Fast:const e=Math.min(n,ye.millisToTicks(this._settings.player.songBookDipDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!0,[a[0].value,a[1].value,a[2].value],e,o)}break;case C.Hold:case C.Predive:l=a;break;case C.PrediveDive:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new be(0,a[0].value)),l.push(new be(be.MaxPosition/2|0,a[0].value)),l.push(new be(be.MaxPosition,a[1].value));break;case h.Fast:const e=Pi.getPitchWheel(a[0].value);this._handler.addBend(r.index,t,i,0|e);const s=Math.min(n,ye.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],s,o)}}this.generateWhammyOrBend(t,n,l,o)}generateWhammyOrBend(e,t,s,i){const a=t/be.MaxPosition;for(let t=0;t<s.length-1;t++){const r=s[t],n=s[t+1],o=Pi.getPitchWheel(r.value),h=Pi.getPitchWheel(n.value),l=a*(n.offset-r.offset),c=e+a*r.offset;this.generateBendValues(c,l,o,h,i)}}generateBendValues(e,t,s,i,a){const r=ye.ticksToMillis(t,this._currentTempo),n=Math.abs(i-s)/Pi.PitchValuePerSemitone,o=Math.max(Pi.MinBreakpointsPerSemitone*n,r/Pi.MillisecondsPerBreakpoint),h=t/o,l=(i-s)/o;for(let t=0;t<o;t++)a(0|e,Math.round(s)),s+=l,e+=h;s<i&&a(0|e,i)}generateTrill(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=ye.toTicks(e.trillSpeed),l=!0,c=t,d=t+s.untilTieOrSlideEnd;for(;c+10<d;)c+h>=d&&(h=d-c),this._handler.addNote(n.index,c,h,l?o:i,a,r),l=!l,c+=h}generateTremoloPicking(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track;let o=ye.toTicks(e.beat.tremoloSpeed),h=t;const l=t+s.untilTieOrSlideEnd;for(;h+10<l;)h+o>=l&&(o=l-h),this._handler.addNote(n.index,h,o,i,a,r),h+=o}getBrushInfo(e){const t=new Int32Array(e.voice.bar.staff.tuning.length);if(e.brushType!==c.None){let s=0,i=0;for(const t of e.notes)t.isTieDestination||(s|=1<<t.string-1,i++);if(e.notes.length>0){let a=0;const r=e.brushDuration/(i-1)|0;for(let i=0;i<e.voice.bar.staff.tuning.length;i++){let n=e.brushType===c.ArpeggioDown||e.brushType===c.BrushDown?i:t.length-1-i;0!=(s&1<<n)&&(t[n]=a,a+=r)}}}return t}generateAutomation(e,t,s){switch(t.type){case a.Instrument:this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,255&(0|t.value)),this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,255&(0|t.value));break;case a.Balance:let i=Pi.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,te.PanCoarse,i),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,te.PanCoarse,i);break;case a.Volume:let r=Pi.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,te.VolumeCoarse,r),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,te.VolumeCoarse,r)}}prepareSingleBeat(e){let t=-1,s=-1,i=e;for(;i&&(-1===t||-1===s);){for(const i of e.automations)switch(i.type){case a.Instrument:s=i.value;break;case a.Tempo:t=i.value}i=i.previousBeat}const r=e.voice.bar.staff.track,n=e.voice.bar.masterBar;-1===t&&(t=n.score.tempo),-1===s&&(s=r.playbackInfo.program);const o=r.playbackInfo.volume;this.generateTrack(r),this._handler.addTimeSignature(0,n.timeSignatureNumerator,n.timeSignatureDenominator),this._handler.addTempo(0,t);let h=Pi.toChannelShort(o);this._handler.addControlChange(0,0,r.playbackInfo.primaryChannel,te.VolumeCoarse,h),this._handler.addControlChange(0,0,r.playbackInfo.secondaryChannel,te.VolumeCoarse,h)}generateSingleBeat(e){this.prepareSingleBeat(e),this.generateBeat(e,-e.playbackStart,e.voice.bar)}generateSingleNote(e){this.prepareSingleBeat(e.beat),this.generateNote(e,-e.beat.playbackStart,e.beat.playbackDuration,new Int32Array(e.beat.voice.bar.staff.tuning.length))}}Pi.DefaultDurationDead=30,Pi.DefaultDurationPalmMute=80,Pi.PitchBendRangeInSemitones=16,Pi.PitchValuePerSemitone=Gt.DefaultPitchWheel/Pi.PitchBendRangeInSemitones,Pi.MinBreakpointsPerSemitone=6,Pi.MillisecondsPerBreakpoint=150;class Ei{constructor(){this.startTick=0,this.endTick=0}}class Ci{constructor(e,t){this.width=0,this.height=0,this.x=e,this.y=t}get scale(){return this.renderer.scale}doLayout(){}paint(e,t,s){}}class Fi extends Ci{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Li extends Fi{constructor(e,t,s,i){super(e,t),this.glyphScale=0,this.glyphScale=s,this.symbol=i}paint(e,t,s){s.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale*this.scale,this.symbol,!1)}}class Mi extends Li{constructor(e,t,s,i){super(e,t,i?Mi.GraceScale:1,Mi.getSymbol(s)),this._isGrace=i,this._duration=s}paint(e,t,s){let i=this._isGrace?this.scale:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale*this.scale,this.symbol,!1)}doLayout(){let e=(this._isGrace?Mi.GraceScale:1)*this.scale;switch(this._duration){case u.QuadrupleWhole:this.width=14*e;break;case u.DoubleWhole:case u.Whole:this.width=14*(this._isGrace?Mi.GraceScale:1)*this.scale;break;default:this.width=Mi.QuarterNoteHeadWidth*(this._isGrace?Mi.GraceScale:1)*this.scale}this.height=Mi.NoteHeadHeight*e}static getSymbol(e){switch(e){case u.QuadrupleWhole:return N.NoteheadDoubleWholeSquare;case u.DoubleWhole:return N.NoteheadDoubleWhole;case u.Whole:return N.NoteheadWhole;case u.Half:return N.NoteheadHalf;default:return N.NoteheadBlack}}}Mi.GraceScale=.75,Mi.NoteHeadHeight=8,Mi.QuarterNoteHeadWidth=9;class Ii extends Li{constructor(e,t,s,i,a){super(e,t,a?Mi.GraceScale:1,Ii.getSymbol(s,i,a))}doLayout(){this.width=0}static getSymbol(e,t,s){if(s&&(e=u.Eighth),t===H.Up)switch(e){case u.Eighth:return N.FlagEighthUp;case u.Sixteenth:return N.FlagSixteenthUp;case u.ThirtySecond:return N.FlagThirtySecondUp;case u.SixtyFourth:return N.FlagSixtyFourthUp;case u.OneHundredTwentyEighth:return N.FlagOneHundredTwentyEighthUp;case u.TwoHundredFiftySixth:return N.FlagTwoHundredFiftySixthUp;default:return N.FlagEighthUp}switch(e){case u.Eighth:return N.FlagEighthDown;case u.Sixteenth:return N.FlagSixteenthDown;case u.ThirtySecond:return N.FlagThirtySecondDown;case u.SixtyFourth:return N.FlagSixtyFourthDown;case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:return N.FlagOneHundredTwentyEighthDown;default:return N.FlagEighthDown}}}Ii.FlagWidth=11;class Di extends Ci{constructor(e,t){super(0,0),this.ties=[],this.minWidth=0,this.beat=e,this.ties=[],this.voiceContainer=t}get onTimeX(){return this.onNotes.x+this.onNotes.centerX}registerLayoutingInfo(e){let t=this.preNotes.computedWidth+this.onNotes.centerX;this.beat.graceGroup&&!this.beat.graceGroup.isComplete&&(t+=Di.GraceBeatPadding*this.renderer.scale);let s=this.onNotes.computedWidth-this.onNotes.centerX;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);(i&&i.hasFlag||this.beat.graceType!==g.None)&&(s+=Ii.FlagWidth*this.scale*(this.beat.graceType!==g.None?Mi.GraceScale:1));for(const e of this.ties)s+=e.width;this.beat.graceType!==g.None&&(s+=Di.GraceBeatPadding*this.renderer.scale),e.addBeatSpring(this.beat,t,s),e.setPreBeatSize(this.beat,this.preNotes.computedWidth),e.setOnBeatSize(this.beat,this.onNotes.computedWidth),e.setBeatCenterX(this.beat,this.onNotes.centerX)}applyLayoutingInfo(e){let t=e.getBeatCenterX(this.beat)-this.onNotes.centerX;this.beat.graceGroup&&!this.beat.graceGroup.isComplete&&(t+=Di.GraceBeatPadding*this.renderer.scale),this.preNotes.x=t,this.preNotes.width=e.getPreBeatSize(this.beat),this.onNotes.width=e.getOnBeatSize(this.beat),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.updateBeamingHelper(),this.updateWidth()}doLayout(){this.preNotes.x=0,this.preNotes.renderer=this.renderer,this.preNotes.container=this,this.preNotes.doLayout(),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.renderer=this.renderer,this.onNotes.container=this,this.onNotes.doLayout();let e=this.beat.notes.length-1;for(;e>=0;)this.createTies(this.beat.notes[e--]);this.updateWidth()}updateWidth(){if(this.minWidth=this.preNotes.width+this.onNotes.width,!this.beat.isRest)if(1===this.onNotes.beamingHelper.beats.length)this.beat.duration>=u.Eighth&&(this.minWidth+=20*this.scale);else switch(this.beat.duration){case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:this.minWidth+=10*this.scale}let e=0;for(let t of this.ties)t.width>e&&(e=t.width);this.minWidth+=e,this.width=this.minWidth}scaleToWidth(e){for(let e of this.ties)e.doLayout();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(Di.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 ui;a.beat=this.beat,a.visualBounds=new at,a.visualBounds.x=t+this.x+this.onNotes.x,a.visualBounds.y=e.visualBounds.y,a.visualBounds.w=this.onNotes.width,a.visualBounds.h=e.visualBounds.h,a.realBounds=new at,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,i&&(a.visualBounds.x=t+this.x,a.realBounds.x=a.visualBounds.x),e.addBeat(a),this.renderer.settings.core.includeNoteBounds&&this.onNotes.buildBoundingsLookup(a,t+this.x,s+this.y)}}Di.GraceBeatPadding=3;class Ri{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new lo}causeIssue(){return this.settings=null,!0}}class Ai{constructor(e){this.bounds=null,this.beat=e}}class Oi extends pe{constructor(e,t){super(s.General,e),this.xhr=t,Object.setPrototypeOf(this,Oi.prototype)}}class Gi{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=Gi.loadScoreFromBytes(s,i);t(r)}catch(e){s(e)}else 0===a.status?s(new Oi("You are offline!!\n Please Check Your Network.",a)):404===a.status?s(new Oi("Requested URL not found.",a)):500===a.status?s(new Oi("Internel Server Error.",a)):"parsererror"===a.statusText?s(new Oi("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?s(new Oi("Request Time out.",a)):s(new Oi("Unknow Error: "+a.responseText,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Hs);let s=ho.buildImporters();Be.debug("ScoreLoader","Loading score from "+e.length+" bytes using "+s.length+" importers",null);let i=null,a=$e.fromBuffer(e);for(let e of s){a.reset();try{Be.debug("ScoreLoader","Importing using importer "+e.name),e.init(a,t),i=e.readScore(),Be.debug("ScoreLoader","Score imported using "+e.name);break}catch(t){if(!(t instanceof ge))throw Be.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;Be.debug("ScoreLoader",e.name+" does not support the file")}}if(i)return i;throw Be.error("ScoreLoader","No compatible importer found for file"),new ge("No compatible importer found for file")}}class Vi{constructor(e){this.mouseEvent=e}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()}}class Hi{constructor(e){this._resizeListeners=0,this._lastBounds=new at,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new Vi(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new Vi(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new Vi(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&Hi.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,Hi.resizeObserver.value.unobserve(this.element))}}}get width(){return this.element.offsetWidth}set width(e){this.element.style.width=e+"px"}get scrollLeft(){return this.element.scrollLeft}set scrollLeft(e){this.element.scrollTop=e}get scrollTop(){return this.element.scrollLeft}set scrollTop(e){this.element.scrollTop=e}get height(){return this.element.offsetHeight}set height(e){this.element.style.height=e>=0?e+"px":"100%"}get isVisible(){return!!this.element.offsetWidth||!!this.element.offsetHeight||!!this.element.getClientRects().length}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=""}}Hi.resizeObserver=new we((()=>new ResizeObserver((e=>{for(const t of e){let e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class Wi{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new ms,this._family=e}checkForFontAvailability(){if(ho.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0,t=window.setInterval((()=>{e++,Be.warning("Rendering",`Could not load font '${this._family}' within ${5*e} seconds`,null)}),5e3);Be.debug("Font","Start checking for font availablility: "+this._family),Be.debug("Font",`[${this._family}] Font API available`);let s=()=>{document.fonts.load("1em "+this._family).then((()=>(Be.debug("Font",`[${this._family}] Font API signaled loaded`),document.fonts.check("1em "+this._family)?(Be.debug("Rendering",`[${this._family}] Font API signaled available`),this.isFontLoaded=!0,window.clearInterval(t),this.fontLoaded.trigger(this._family)):(Be.debug("Font",`[${this._family}] Font API loaded reported, but font not available, checking later again`,null),window.setTimeout((()=>{s()}),250)),!0)))};s()}}class zi{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 Ui{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new fs,this.samplesPlayed=new ms,this.sampleRequest=new fs}get sampleRate(){return this._context?this._context.sampleRate:Ui.PreferredSampleRate}activate(){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(Be.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{var e,t;Be.debug("WebAudio",`Audio Context resume success: state=${null===(e=this._context)||void 0===e?void 0:e.state}, sampleRate:${null===(t=this._context)||void 0===t?void 0:t.sampleRate}`)}),(e=>{var t,s;Be.debug("WebAudio",`Audio Context resume failed: state=${null===(t=this._context)||void 0===t?void 0:t.state}, sampleRate:${null===(s=this._context)||void 0===s?void 0:s.sampleRate}, reason=${e}`)})))}patchIosSampleRate(){let e=navigator.userAgent;if(-1!==e.indexOf("iPhone")||0!==e.indexOf("iPad")){let e=this.createAudioContext(),t=e.createBuffer(1,1,Ui.PreferredSampleRate),s=e.createBufferSource();s.buffer=t,s.connect(e.destination),s.start(0),s.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in ho.globalThis)return new AudioContext;if("webkitAudioContext"in ho.globalThis)return new webkitAudioContext;throw new pe(s.General,"AudioContext not found")}open(){this.patchIosSampleRate(),this._context=this.createAudioContext();let e=this._context;if("suspended"===e.state){let t=()=>{e.resume(),ho.globalThis.setTimeout((()=>{"running"===e.state&&(document.body.removeEventListener("touchend",t,!1),document.body.removeEventListener("click",t,!1))}),0)};document.body.addEventListener("touchend",t,!1),document.body.addEventListener("click",t,!1)}}play(){let e=this._context;this.activate(),this._buffer=e.createBuffer(2,Ui.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(){var e;this.pause(),null===(e=this._context)||void 0===e||e.close()}onSamplesPlayed(e){this.samplesPlayed.trigger(e)}onSampleRequest(){this.sampleRequest.trigger()}onReady(){this.ready.trigger()}}Ui.BufferSize=4096,Ui.PreferredSampleRate=44100,Ui.TotalBufferTimeInMilliseconds=5e3;class Xi extends Ui{constructor(){super(...arguments),this._audioNode=null,this._bufferCount=0,this._requestedBufferCount=0,this._outputBuffer=new Float32Array(0)}open(){super.open(),this._bufferCount=Math.floor(Ui.TotalBufferTimeInMilliseconds*this.sampleRate/1e3/Ui.BufferSize),this._circularBuffer=new zi(Ui.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*Ui.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*Ui.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),this._circularBuffer.read(a,0,Math.min(a.length,this._circularBuffer.count));let r=0;for(let e=0;e<t.length;e++)t[e]=a[r++],s[e]=a[r++];this.onSamplesPlayed(t.length),this.requestBuffers()}}class Yi{constructor(e,t){this.loaded=e,this.total=t}}class qi{constructor(e,t,s){this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=q.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 fs,this.readyForPlayback=new fs,this.finished=new fs,this.soundFontLoaded=new fs,this.soundFontLoadFailed=new ms,this.midiLoaded=new ms,this.midiLoadFailed=new ms,this.stateChanged=new ms,this.positionChanged=new ms,this.midiEventsPlayed=new ms,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=q.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();try{this._synth=ho.createAlphaTabWorker(t)}catch(e){try{this._synth=new Worker(t)}catch(e){return void Be.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:s}),this.masterVolume=1,this.playbackSpeed=1,this.metronomeVolume=0}get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return Be.logLevel}set logLevel(e){Be.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Gt.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Gt.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Gt.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=ns.clamp(e,Gt.MinPlaybackSpeed,Gt.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})}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:ni.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,s){Be.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=>{Be.error("AlphaSynth","Loading failed: "+e.message),this.soundFontLoadFailed.trigger(new Oi(e.message,i))},i.onprogress=e=>{Be.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),s(new Yi(e.loaded,e.total))},i.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:ni.midiFileToJsObject(e)})}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,Gt.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 Ut(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new ys(t.events.map(ni.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new zt(t.state,t.stopped));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 Ut(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 Ji{constructor(e,t){if(this._width=0,this.boundsLookup=null,this.preRender=new ms,this.partialRenderFinished=new ms,this.partialLayoutFinished=new ms,this.renderFinished=new ms,this.postRenderFinished=new fs,this.error=new ms,this._api=e,t.core.scriptFile){try{this._worker=ho.createAlphaTabWorker(t.core.scriptFile)}catch(e){try{this._worker=new Worker(t.core.scriptFile)}catch(t){return void Be.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))}else Be.error("Rendering","Could not detect alphaTab script file, cannot initialize renderer")}destroy(){this._worker.terminate()}updateSettings(e){this._worker.postMessage({cmd:"alphaTab.updateSettings",settings:this.serializeSettingsForWorker(e)})}serializeSettingsForWorker(e){const t=ni.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=mi.fromJson(t.boundsLookup,this._api.score),this.postRenderFinished.trigger();break;case"alphaTab.error":this.error.trigger(t.error)}}renderScore(e,t){let s=null==e?null:ni.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:s,trackIndexes:t,fontSizes:li.FontSizeLookupTables})}}class Qi{constructor(e,t,s,i){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=s,this.selectionWrapper=i}}!function(e){e[e.Browser=0]="Browser",e[e.NodeJs=1]="NodeJs",e[e.BrowserModule=2]="BrowserModule"}(se||(se={}));class ji{static init(){var e;ji._isRegistered||(ji._isRegistered=!0,registerProcessor("alphatab",((e=class e extends AudioWorkletProcessor{constructor(...t){super(...t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,Be.info("WebAudio","creating processor"),this._bufferCount=Math.floor(e.TotalBufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new zi(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){let t=e.data;switch(t.cmd){case oi.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case oi.CmdOutputResetSamples:this._circularBuffer.clear()}}process(e,t,s){if(1!==t.length&&2!==t[0].length)return!1;let i=t[0][0],a=t[0][1];if(!i||!a)return!0;let r=i.length+a.length,n=this._outputBuffer;n.length!==r&&(n=new Float32Array(r),this._outputBuffer=n),this._circularBuffer.read(n,0,Math.min(n.length,this._circularBuffer.count));let o=0;for(let e=0;e<i.length;e++)i[e]=n[o++],a[e]=n[o++];return this.port.postMessage({cmd:oi.CmdOutputSamplesPlayed,samples:i.length}),this.requestBuffers(),!0}requestBuffers(){const t=this._bufferCount/2|0;let s=t*e.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*e.BufferSize<s){for(let e=0;e<t;e++)this.port.postMessage({cmd:oi.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e.TotalBufferTimeInMilliseconds=5e3,e)))}}ji._isRegistered=!1;class Ki extends Ui{constructor(){super(...arguments),this._worklet=null}open(){super.open(),this.onReady()}play(){super.play();let e=this._context;e.audioWorklet.addModule(ho.scriptFile).then((()=>{this._worklet=new AudioWorkletNode(e,"alphatab",{numberOfOutputs:1,outputChannelCount:[2]}),this._worklet.port.onmessage=this.handleMessage.bind(this),this._source.connect(this._worklet),this._source.start(0),this._worklet.connect(e.destination)}),(e=>{Be.error("WebAudio","Audio Worklet creation failed: reason="+e)}))}handleMessage(e){let t=e.data;switch(t.cmd){case oi.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case oi.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){var t;null===(t=this._worklet)||void 0===t||t.port.postMessage({cmd:oi.CmdOutputAddSamples,samples:e})}resetSamples(){var e;null===(e=this._worklet)||void 0===e||e.port.postMessage({cmd:oi.CmdOutputResetSamples})}}!function(e){e[e.LayoutDone=0]="LayoutDone",e[e.RenderRequested=1]="RenderRequested",e[e.RenderDone=2]="RenderDone",e[e.Detached=3]="Detached"}(ie||(ie={}));class $i{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 fs,this.canRenderChanged=new fs,this._highlightedElements=[],this._scrollContainer=null,ho.webPlatform!==se.Browser&&ho.webPlatform!==se.BrowserModule)throw new pe(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 Hi(e),this.areWorkersSupported="Worker"in window,ho.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(e)}get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(ho.bravuraFontChecker.checkForFontAvailability(),!ho.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(Be.debug("Font","All fonts loaded: "+this._fontCheckers.size),!0)}onFontLoaded(e){li.generateFontLookup(e),this.areAllFontsLoaded()&&this.canRenderChanged.trigger()}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)?this._api.renderer.renderResult(s.layoutResultId):e.replaceChildren():s.resultState===ie.Detached&&(e.replaceChildren(...s.renderedResult),s.resultState=ie.RenderDone):s.resultState===ie.RenderDone&&(s.resultState=ie.Detached,s.replaceChildren())}}}createWorkerRenderer(){return new Ji(this._api,this._api.settings)}initialize(e,t){let s;this._api=e,s=t instanceof Hs?t:ni.jsObjectToSettings(t);let i=this.getDataAttributes();Vs.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.family)){let t=new Wi(e.family);this._fontCheckers.set(e.family,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 Hi(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 He)return t(e),!0;if(e instanceof ArrayBuffer){let s=new Uint8Array(e);return t(Gi.loadScoreFromBytes(s,this._api.settings)),!0}return e instanceof Uint8Array?(t(Gi.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(Gi.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=()=>{var e;this._api.renderer.width=0|this.rootContainer.width,this._api.renderer.updateSettings(this._api.settings),this._contents?(this._api.tex(this._contents,null!==(e=this._initialTrackIndexes)&&void 0!==e?e:void 0),this._initialTrackIndexes=null):this._file&&Gi.loadScoreAsync(this._file,(e=>{var t;this._api.renderScore(e,null!==(t=this._initialTrackIndexes)&&void 0!==t?t: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;ho.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=ie.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=ie.LayoutDone,delete s.renderedResultId,delete s.renderedResult,this._resultIdToElementLookup.set(e.id,s);for(let t=e.firstMasterBarIndex;t<=e.lastMasterBarIndex;t++)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.lastChild)}createWorkerPlayer(){let e=ho.scriptFile;if(!e)return Be.error("Player","alphaTab script file could not be detected, player cannot initialize"),null;let t=null,s="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window?(Be.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),t=new qi(new Ki,e,this._api.settings.core.logLevel)):s&&(Be.debug("Player","Will use webworkers for synthesizing and web audio api for playback"),t=new qi(new Xi,e,this._api.settings.core.logLevel)),t?t.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):Be.error("Player","Player requires webworkers and web audio api, browser unsupported",null),t}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const s=this._barToElementLookup.get(t);if(s){let t=s.getElementsByClassName(e);for(let e=0;e<t.length;e++)t.item(e).classList.add("at-highlight"),this._highlightedElements.push(t.item(e))}}removeHighlights(){const e=this._highlightedElements;if(e){for(const t of e)t.classList.remove("at-highlight");this._highlightedElements=[]}}destroyCursors(){let e=this._api.container.element,t=e.querySelector(".at-cursors");e.removeChild(t)}createCursors(){let e=this._api.container.element,t=document.createElement("div");t.classList.add("at-cursors");let s=document.createElement("div");s.classList.add("at-selection");let i=document.createElement("div");i.classList.add("at-cursor-bar");let a=document.createElement("div");return a.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",i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.willChange="transform",i.style.width="1px",i.style.height="1px",a.style.position="absolute",a.style.transition="all 0s linear",a.style.left="0",a.style.top="0",a.style.willChange="transform",a.style.width="3px",a.style.height="1px",e.insertBefore(t,e.firstChild),t.appendChild(s),t.appendChild(i),t.appendChild(a),new Qi(new Hi(t),new Hi(i),new Hi(a),new Hi(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 at;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 Hi(e),this._scrollContainer}createSelectionElement(){let e=document.createElement("div");return e.style.position="absolute",e.style.width="1px",e.style.height="1px",new Hi(e)}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 Zi extends class{constructor(e,t){this._startTime=0,this._trackIndexes=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=q.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=q.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new ms,this._beatMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new ms,this.beatMouseMove=new ms,this.beatMouseUp=new ms,this.scoreLoaded=new ms,this.resize=new ms,this.renderStarted=new ms,this.renderFinished=new ms,this.postRenderFinished=new fs,this.error=new ms,this.playerReady=new fs,this.playerFinished=new fs,this.soundFontLoaded=new fs,this.midiLoad=new ms,this.midiLoaded=new ms,this.playerStateChanged=new ms,this.playerPositionChanged=new ms,this.midiEventsPlayed=new ms,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),Be.logLevel=this.settings.core.logLevel,this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&ho.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new yi(this.settings),this.container.resize.on(ho.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));let s=new Ri;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;Be.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(){this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?this.setupPlayer():this.destroyPlayer()}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 pe(s.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(t,e)}}internalRenderTracks(e,t){if(e!==this.score){ke.applyPitchOffsets(this.settings,e),this.score=e,this.tracks=t,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this.onScoreLoaded(e),this.loadMidiForScore(),this.render()}else{this.tracks=t,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this.render()}}triggerResize(){if(this.container.isVisible){let e=new Ri;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 Be.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{Be.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)),this.uiFacade.beginAppendRenderResults(e)}updateRenderResult(e){e&&e.renderResult&&this.uiFacade.beginUpdateRenderResults(e)}tex(e,t){try{let s=new et;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 isReadyForPlayback(){return!!this.player&&this.player.isReadyForPlayback}get playerState(){return this.player?this.player.state:q.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.destroyCursors())}setupPlayer(){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.finished.on(this.onPlayerFinished.bind(this)),this.settings.player.enableCursor?this.setupCursors():this.destroyCursors()))}loadMidiForScore(){if(!this.player||!this.score||!this.player.isReady)return;Be.debug("AlphaTab","Generating Midi");let e=new Ss,t=new wi(e),s=new Pi(this.score,this.settings,t);s.generate(),this._tickCache=s.tickLookup,this.onMidiLoad(e),this.player.loadMidiFile(e)}changeTrackVolume(e,t){if(this.player)for(let s of e)this.player.setChannelVolume(s.playbackInfo.primaryChannel,t),this.player.setChannelVolume(s.playbackInfo.secondaryChannel,t)}changeTrackSolo(e,t){if(this.player)for(let s of e)this.player.setChannelSolo(s.playbackInfo.primaryChannel,t),this.player.setChannelSolo(s.playbackInfo.secondaryChannel,t)}changeTrackMute(e,t){if(this.player)for(let s of e)this.player.setChannelMute(s.playbackInfo.primaryChannel,t),this.player.setChannelMute(s.playbackInfo.secondaryChannel,t)}play(){return!!this.player&&this.player.play()}pause(){this.player&&this.player.pause()}playPause(){this.player&&this.player.playPause()}stop(){this.player&&this.player.stop()}playBeat(e){if(!this.player)return;let t=new Ss,s=new wi(t);new Pi(e.voice.bar.staff.track.score,this.settings,s).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;let t=new Ss,s=new wi(t);new Pi(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,this._previousTick=0,this._playerState=q.Paused)}setupCursors(){let e=this.uiFacade.createCursors();e&&(this._cursorWrapper=e.cursorWrapper,this._barCursor=e.barCursor,this._beatCursor=e.beatCursor,this._selectionWrapper=e.selectionWrapper,this._previousTick=0,this._playerState=q.Paused,this.renderer.postRenderFinished.on((()=>{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===q.Paused){let e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getMasterBarStart(e.currentBeat.voice.bar.masterBar)+e.currentBeat.playbackStart)}}))))}cursorUpdateTick(e,t,s=!1){let i=this._tickCache;if(i){let a=this.tracks;if(a.length>0){let r=i.findBeat(a,e,this._currentBeat);r&&this.cursorUpdateBeat(r,t,s)}}}cursorUpdateBeat(e,t,s){const i=e.currentBeat,a=e.nextBeat,r=e.duration,n=e.beatsToHighlight;if(!i)return;let o=this.renderer.boundsLookup;if(!o)return;let h=this._currentBeat,l=this._previousCursorCache,c=this._previousStateForCursor;if(i===(null==h?void 0:h.currentBeat)&&o===l&&c===this._playerState)return;let d=o.findBeat(i);d&&(this._currentBeat=e,this._previousCursorCache=o,this._previousStateForCursor=this._playerState,this.uiFacade.beginInvoke((()=>{this.internalCursorUpdateBeat(i,a,r,t,n,o,d,s)})))}scrollToCursor(){const e=this._currentBarBounds;e&&this.internalScrollToCursor(e)}internalScrollToCursor(e){let t=this.uiFacade.getScrollContainer(),s=ho.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 ee.Continuous:let i=this.uiFacade.getOffset(t,this.container);this.uiFacade.scrollToY(t,i.y+s,this.settings.player.scrollSpeed);break;case ee.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 ee.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 ee.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){let h=this._barCursor,l=this._beatCursor,c=n.barBounds.masterBarBounds,d=c.visualBounds;this._currentBarBounds=c,h.setBounds(d.x,d.y,d.w,d.h),this.settings.player.enableAnimatedBeatCursor&&l.stopAnimation(),l.setBounds(n.visualBounds.x,d.y,1,d.h),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let u=!1;if(this._playerState===q.Playing&&!i){if(this.settings.player.enableElementHighlighting&&a)for(let t of a){let s=Di.getGroupId(t);this.uiFacade.highlightElements(s,e.voice.bar.index)}if(this.settings.player.enableAnimatedBeatCursor){let i=c.visualBounds.x+c.visualBounds.w;if(t&&(t.voice.bar.index===e.voice.bar.index&&t.index>e.index||t.voice.bar.index===e.voice.bar.index+1)){let e=r.findBeat(t);e&&e.barBounds.masterBarBounds.staveGroupBounds===c.staveGroupBounds&&(i=e.visualBounds.x)}this.uiFacade.beginInvoke((()=>{l.transitionToX(s/this.playbackSpeed,i)}))}o=!i,u=!0}o&&!this._beatMouseDown&&this.settings.player.scrollMode!==ee.Off&&this.internalScrollToCursor(c),u&&this.onPlayedBeatChanged(e)}onPlayedBeatChanged(e){this._isDestroyed||(this.playedBeatChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playedBeatChanged",e))}onBeatMouseDown(e,t){this._isDestroyed||(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&(this._selectionStart=new Ai(t),this._selectionEnd=null),this._beatMouseDown=!0,this.beatMouseDown.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseDown",t,e))}onBeatMouseMove(e,t){this._isDestroyed||(this.settings.player.enableUserInteraction&&(this._selectionEnd&&this._selectionEnd.beat===t||(this._selectionEnd=new Ai(t),this.cursorSelectRange(this._selectionStart,this._selectionEnd))),this.beatMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseMove",t,e))}onBeatMouseUp(e,t){if(!this._isDestroyed){if(this.settings.player.enableUserInteraction){if(this._selectionEnd){let e=this._selectionStart.beat.absolutePlaybackStart;if(this._selectionStart.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===q.Paused&&this.cursorUpdateTick(this._selectionStart.beat.absolutePlaybackStart,!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 Ei;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}}updateSelectionCursor(e){if(this._tickCache)if(e){const t=this._tickCache.findBeat(this.tracks,e.startTick),s=this._tickCache.findBeat(this.tracks,e.endTick);if(t&&s){const e=new Ai(t.currentBeat),i=new Ai(s.currentBeat);this.cursorSelectRange(e,i)}}else this.cursorSelectRange(null,null)}setupClickHandling(){this.canvasElement.mouseDown.on((e=>{var t,s;if(!e.isLeftMouseButton)return;this.settings.player.enableUserInteraction&&e.preventDefault();let i=e.getX(this.canvasElement),a=e.getY(this.canvasElement),r=null!==(s=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(i,a))&&void 0!==s?s:null;r&&this.onBeatMouseDown(e,r)})),this.canvasElement.mouseMove.on((e=>{var t,s;if(!this._beatMouseDown)return;let i=e.getX(this.canvasElement),a=e.getY(this.canvasElement),r=null!==(s=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(i,a))&&void 0!==s?s:null;r&&this.onBeatMouseMove(e,r)})),this.canvasElement.mouseUp.on((e=>{var t,s;if(!this._beatMouseDown)return;this.settings.player.enableUserInteraction&&e.preventDefault();let i=e.getX(this.canvasElement),a=e.getY(this.canvasElement),r=null!==(s=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(i,a))&&void 0!==s?s:null;this.onBeatMouseUp(e,r)})),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=e.beat.absolutePlaybackStart;if(t.beat.absolutePlaybackStart<a){let s=e;e=t,t=s}let r=e.bounds.realBounds.x,n=t.bounds.realBounds.x+t.bounds.realBounds.w;if(t.beat.index===t.beat.voice.beats.length-1&&(n=t.bounds.barBounds.masterBarBounds.realBounds.x+t.bounds.barBounds.masterBarBounds.realBounds.w),e.bounds.barBounds.masterBarBounds.staveGroupBounds!==t.bounds.barBounds.masterBarBounds.staveGroupBounds){let a=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x,o=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x+e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.w,h=this.uiFacade.createSelectionElement();h.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,o-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(h);let l=e.bounds.barBounds.masterBarBounds.staveGroupBounds.index+1,c=t.bounds.barBounds.masterBarBounds.staveGroupBounds.index;for(let e=l;e<c;e++){let t=s.staveGroups[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),i.appendChild(r)}let d=this.uiFacade.createSelectionElement();d.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(d)}else{let t=this.uiFacade.createSelectionElement();t.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,n-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(t)}}onScoreLoaded(e){this._isDestroyed||(this.scoreLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"scoreLoaded",e))}onResize(e){this._isDestroyed||(this.resize.trigger(e),this.uiFacade.triggerEvent(this.container,"resize",e))}onRenderStarted(e){this._isDestroyed||(this.renderStarted.trigger(e),this.uiFacade.triggerEvent(this.container,"renderStarted",e))}onRenderFinished(e){this._isDestroyed||(this.renderFinished.trigger(e),this.uiFacade.triggerEvent(this.container,"renderFinished",e))}onPostRenderFinished(){this._isDestroyed||(this.postRenderFinished.trigger(),this.uiFacade.triggerEvent(this.container,"postRenderFinished",null))}onError(e){this._isDestroyed||(Be.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))}}{constructor(e,t){super(new $i(e),t),this.soundFontLoad=new ms}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("<!DOCTYPE html><html></head><body></body></html>"),i.document.body.appendChild(a);let r=void 0!==window.screenLeft?window.screenLeft:window.left,n=void 0!==window.screenTop?window.screenTop:window.top,o="innerWidth"in window?window.innerWidth:"clientWidth"in document.documentElement?document.documentElement.clientWidth:window.screen.width,h="innerHeight"in window?window.innerHeight:"clientHeight"in document.documentElement?document.documentElement.clientHeight:window.screen.height,l=a.offsetWidth+50,c=window.innerHeight,d=(o/2|0)-(l/2|0)+r,u=(h/2|0)-(c/2|0)+n;i.resizeTo(l,c),i.moveTo(d,u),i.focus();let p=ni.jsObjectToSettings(ni.settingsToJsObject(this.settings));p.core.enableLazyLoading=!1,p.core.useWorkers=!1,p.display.scale=.8,p.display.stretchForce=.8,Vs.fromJson(p,s);let g=new Zi(a,p);g.renderer.postRenderFinished.on((()=>{g.canvasElement.height=-1,i.print()})),g.renderTracks(this.tracks)}downloadMidi(){if(!this.score)return;let e=new Ss,t=new wi(e);new Pi(this.score,this.settings,t).generate();let s=e.toBinary(),i=this.score.title?this.score.title+".mid":"File.mid",a=document.createElement("a");a.download=i;let r=new Blob([s],{type:"audio/midi"}),n=URL.createObjectURL(r);a.href=n,a.style.display="none",document.body.appendChild(a),a.click(),document.body.removeChild(a)}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 ea{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 Be.error("Api","Method '"+t+"' does not exist on jQuery.alphaTab"),null}init(e,t,s){if(!t){t=new Zi(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 ta{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.color=new Ue(255,255,255,255),this.lineWidth=1,this.font=new vs("Arial",10,$.Plain),this.textAlign=P.Left,this.textBaseline=E.Top}beginRender(e,t){this.buffer=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${0|e}px" height="${0|t}px" class="at-surface-svg">\n`,this._currentPath="",this._currentPathIsEmpty=!0,this.textBaseline=E.Top}beginGroup(e){this.buffer+=`<g class="${e}">`}endGroup(){this.buffer+="</g>"}endRender(){return this.buffer+="</svg>",this.buffer}fillRect(e,t,s,i){s>0&&(this.buffer+=`<rect x="${0|e}" y="${0|t}" width="${s}" height="${i}" fill="${this.color.rgba}" />\n`)}strokeRect(e,t,s,i){this.buffer+=`<rect x="${0|e}" y="${0|t}" width="${s}" height="${i}" stroke="${this.color.rgba}"`,1!==this.lineWidth&&(this.buffer+=` stroke-width="${this.lineWidth}"`),this.buffer+=' fill="transparent" />\n'}beginPath(){}closePath(){this._currentPath+=" z"}moveTo(e,t){this._currentPath+=` M${e},${t}`}lineTo(e,t){this._currentPathIsEmpty=!1,this._currentPath+=` L${e},${t}`}quadraticCurveTo(e,t,s,i){this._currentPathIsEmpty=!1,this._currentPath+=` Q${e},${t},${s},${i}`}bezierCurveTo(e,t,s,i,a,r){this._currentPathIsEmpty=!1,this._currentPath+=` C${e},${t},${s},${i},${a},${r}`}fillCircle(e,t,s){this._currentPathIsEmpty=!1,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.fill()}strokeCircle(e,t,s){this._currentPathIsEmpty=!1,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.stroke()}fill(){this._currentPathIsEmpty||(this.buffer+=`<path d="${this._currentPath}"`,"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),this.buffer+=' style="stroke: none"/>'),this._currentPath="",this._currentPathIsEmpty=!0}stroke(){if(!this._currentPathIsEmpty){let e=`<path d="${this._currentPath}" stroke="${this.color.rgba}"`;1!==this.lineWidth&&(e+=` stroke-width="${this.lineWidth}"`),e+=' style="fill: none" />',this.buffer+=e}this._currentPath="",this._currentPathIsEmpty=!0}fillText(e,t,s){if(""===e)return;let i=`<text x="${0|t}" y="${0|s}" style="stroke: none; font:${this.font.toCssString(this.settings.display.scale)}" ${this.getSvgBaseLine()}`;"#000000"!==this.color.rgba&&(i+=` fill="${this.color.rgba}"`),this.textAlign!==P.Left&&(i+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),i+=`>${ta.escapeText(e)}</text>`,this.buffer+=i}static escapeText(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}getSvgTextAlignment(e){switch(e){case P.Left:return"start";case P.Center:return"middle";case P.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case E.Top:return'dominant-baseline="hanging"';case E.Bottom:return'dominant-baseline="bottom"';default:return""}}measureText(e){return e?li.measureString(e,this.font.family,this.font.size,this.font.style,this.font.weight):0}onRenderFinished(){return null}beginRotate(e,t,s){this.buffer+='<g transform="translate('+e+" ,"+t+") rotate( "+s+')">'}endRotate(){this.buffer+="</g>"}}class sa extends ta{constructor(){super()}fillMusicFontSymbol(e,t,s,i,a){i!==N.None&&this.fillMusicFontSymbolText(e,t,s,`&#${i};`,a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(let e of i)e!==N.None&&(r+=`&#${e};`);this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){this.buffer+=`<g transform="translate(${e} ${t})" class="at" ><text`,this.buffer+=1!==s?` style="font-size: ${100*s}%; stroke:none"`:' style="stroke:none"',"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),a&&(this.buffer+=' text-anchor="'+this.getSvgTextAlignment(P.Center)+'"'),this.buffer+=`>${i}</text></g>`}}class ia{constructor(){this.isInAccolade=!0,this.isRelevantForBoundsLookup=!0,this.hideOnMultiTrack=!1,this.hideOnPercussionTrack=!1}canCreate(e,t){return!this.hideOnPercussionTrack||!t.isPercussion}}!function(e){e[e.PreNotes=0]="PreNotes",e[e.OnNotes=1]="OnNotes",e[e.MiddleNotes=2]="MiddleNotes",e[e.Stem=3]="Stem",e[e.PostNotes=4]="PostNotes",e[e.EndBeat=5]="EndBeat"}(ae||(ae={}));class aa extends Ci{constructor(e,t){super(e,t),this.glyphs=null}get isEmpty(){return!this.glyphs||0===this.glyphs.length}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);let e=0;for(let t=0,s=this.glyphs.length;t<s;t++){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 ra extends aa{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 na extends aa{constructor(e,t,s){super(e,t),this.voice=s,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){const t=this.renderer.scale;let s=this.renderer.layoutingInfo.spaceToForce(e/t);this.scaleToForce(s)}scaleToForce(e){const t=this.renderer.scale;this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e)*t;let s=this.renderer.layoutingInfo.buildOnTimePositions(e),i=this.beatGlyphs;for(let e=0,a=i.length;e<a;e++){let r=i[e];switch(r.beat.graceType){case g.None:r.x=s.get(r.beat.absoluteDisplayStart)*t-r.onTimeX;break;default:const a=r.beat.graceGroup.beats[0].absoluteDisplayStart,n=r.beat.graceGroup.id;if(r.beat.graceGroup.isComplete&&s.has(a)){r.x=s.get(a)*t-r.onTimeX;let e=this.renderer.layoutingInfo.allGraceRods.get(n),i=this.renderer.layoutingInfo.springs.get(a).preBeatWidth;r.x-=i,r.x-=e[r.beat.graceIndex].postSpringWidth,r.x+=e[r.beat.graceIndex].graceBeatWidth;const o=e[r.beat.graceGroup.beats.length-1];r.x-=o.graceBeatWidth}else{let t=this.renderer.layoutingInfo.incompleteGraceRods.get(n);const s=t[r.beat.graceIndex].postSpringWidth-t[r.beat.graceIndex].preSpringWidth;e>0?0===r.beat.graceIndex?r.x=i[e-1].x+i[e-1].width:r.x=i[e-1].x+t[r.beat.graceIndex-1].postSpringWidth-t[r.beat.graceIndex-1].preSpringWidth-s:r.x=-s}}if(e>0){let t=r.x-i[e-1].x;i[e-1].scaleToWidth(t)}if(e===a-1){let e=this.width-i[i.length-1].x;r.scaleToWidth(e)}}}registerLayoutingInfo(e){e.updateVoiceSize(this.width);let t=this.beatGlyphs;for(let s of t)s.registerLayoutingInfo(e)}applyLayoutingInfo(e){let t=this.beatGlyphs;for(let s of t)s.applyLayoutingInfo(e);this.scaleToForce(Math.max(this.renderer.settings.display.stretchForce,e.minStretchForce))}addGlyph(e){let t=e;e.x=0===this.beatGlyphs.length?0:this.beatGlyphs[this.beatGlyphs.length-1].x+this.beatGlyphs[this.beatGlyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.beatGlyphs.push(t),this.width=e.x+e.width,t.beat.hasTuplet&&t.beat.tupletGroup.beats[0].id===t.beat.id&&this.tupletGroups.push(t.beat.tupletGroup)}doLayout(){}paint(e,t,s){s.color=0===this.voice.index?this.renderer.resources.mainGlyphColor:this.renderer.resources.secondaryGlyphColor;for(let i=0,a=this.beatGlyphs.length;i<a;i++)this.beatGlyphs[i].paint(e+this.x,t+this.y,s)}}na.KeySizeBeat="Beat",function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Sharp=2]="Sharp",e[e.Flat=3]="Flat",e[e.NaturalQuarterNoteUp=4]="NaturalQuarterNoteUp",e[e.SharpQuarterNoteUp=5]="SharpQuarterNoteUp",e[e.FlatQuarterNoteUp=6]="FlatQuarterNoteUp",e[e.DoubleSharp=7]="DoubleSharp",e[e.DoubleFlat=8]="DoubleFlat"}(re||(re={}));class oa{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class ha{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){var s,i;return t<e.staff.track.percussionArticulations.length?e.staff.track.percussionArticulations[t].staffLine:null!==(i=null===(s=xe.getArticulationByValue(t))||void 0===s?void 0:s.staffLine)&&void 0!==i?i:0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case y.ForceDoubleFlat:t+=2;break;case y.ForceDoubleSharp:t-=2;break;case y.ForceFlat:t+=1;break;case y.ForceSharp:t-=1}return t}applyAccidental(e){const t=ha.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=ha.getNoteValue(t);if(e.staff.isPercussion)s=ha.getPercussionLine(e,i);else{const a=t?t.accidentalMode:y.Default;s=ha.calculateNoteLine(e,i,a)}return s}getAccidental(e,t,s,i,a=null){let r=re.None,n=0;if(this._bar.staff.isPercussion)n=ha.getPercussionLine(this._bar,e);else{const s=a?a.accidentalMode:y.Default;n=ha.calculateNoteLine(this._bar,e,s);let i=this._bar.masterBar.keySignature+7,o=e%12,h=i<7?re.Flat:re.Sharp,l=ha.KeySignatureLookup[i][o],c=ha.AccidentalNotes[o];if(t)switch(r=c?h:re.Natural,r){case re.Natural:r=re.NaturalQuarterNoteUp;break;case re.Sharp:r=re.SharpQuarterNoteUp;break;case re.Flat:r=re.FlatQuarterNoteUp}else{switch(s){case y.ForceSharp:r=re.Sharp;break;case y.ForceDoubleSharp:r=re.DoubleSharp;break;case y.ForceFlat:r=re.Flat;break;case y.ForceDoubleFlat:r=re.DoubleFlat;break;default:c?r=h:l&&(r=re.Natural)}let e=!1;if(a&&a.isTieDestination&&0===a.beat.index){const t=this._barRenderer.previousRenderer;if(t){t.accidentalHelper.getNoteLine(a.tieOrigin)===n&&(e=!0)}}e?r=re.None:r!==re.None?(this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===r&&(r=re.None):l&&r===h&&(r=re.None),r!==re.None&&this._registeredAccidentals.set(n,r)):this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===re.Natural?r=re.None:(r=re.Natural,this._registeredAccidentals.set(n,r)):this._registeredAccidentals.delete(n)}}return a?(this._appliedScoreLines.set(a.id,n),this._notesByValue.set(e,a)):this._appliedScoreLinesByValue.set(e,n),(-1e3===this.minLine||this.minLine<n)&&(this.minLine=n,this.minLineBeat=s),(-1e3===this.maxLine||this.maxLine>n)&&(this.maxLine=n,this.maxLineBeat=s),i||this.registerLine(s,n),r}registerLine(e,t){let s;this._beatLines.has(e.id)?s=this._beatLines.get(e.id):(s=new oa,this._beatLines.set(e.id,s)),(-1e3===s.minLine||t<s.minLine)&&(s.minLine=t),(-1e3===s.minLine||t>s.maxLine)&&(s.maxLine=t)}getMaxLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).maxLine:0}getMinLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).minLine:0}static calculateNoteLine(e,t,s){let i=t,a=e.masterBar.keySignature,r=e.clef,n=i%12,o=(i/12|0)-1,h=ha.OctaveSteps[r];return h-=o*ha.StepsPerOctave,h-=(ke.keySignatureIsSharp(a)||ke.keySignatureIsNatural(a)?ha.SharpNoteSteps:ha.FlatNoteSteps)[n],h}getNoteLine(e){return this._appliedScoreLines.get(e.id)}getNoteLineForValue(e,t=!1){return this._appliedScoreLinesByValue.has(e)?this._appliedScoreLinesByValue.get(e):t&&this._notesByValue.has(e)?this.getNoteLine(this._notesByValue.get(e)):0}}ha.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]],ha.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],ha.StepsPerOctave=7,ha.OctaveSteps=[38,32,30,26,38],ha.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],ha.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class la{constructor(){this.staffId="",this.up=0,this.down=0}}class ca{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 da{constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=u.QuadrupleWhole,this.fingeringCount=0,this.hasTuplet=!1,this._firstBeatLowestNoteCompareValue=-1,this._firstBeatHighestNoteCompareValue=-1,this._lastBeatLowestNoteCompareValue=-1,this._lastBeatHighestNoteCompareValue=-1,this.lowestNoteInHelper=null,this._lowestNoteCompareValueInHelper=-1,this.highestNoteInHelper=null,this._highestNoteCompareValueInHelper=-1,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isGrace=!1,this.minRestLine=null,this.beatOfMinRestLine=null,this.maxRestLine=null,this.beatOfMaxRestLine=null,this.direction=H.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}get hasLine(){return 1===this.beats.length&&this.beats[0].duration>u.Whole}get hasFlag(){return 1===this.beats.length&&!this.beats[0].isRest&&(this.beats[0].duration>u.Quarter||this.beats[0].graceType!==g.None)}getBeatLineX(e){return this.hasBeatLineX(e)?this.direction===H.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 la),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(H.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==g.None)&&(e=this.invert(H.Up)):e=H.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){let t=this._renderer.getNoteY(this.highestNoteInHelper,ne.Center),s=this._renderer.getNoteY(this.lowestNoteInHelper,ne.Center);if(null===e){const i=(t+s)/2;e=this.invert(this._renderer.middleYPosition<i?H.Up:H.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(H.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:return[2,2];case u.Whole:return[0,1];case u.Half:return[1,0];case u.Quarter:return[3,3];case u.Eighth:return[2,2];case u.Sixteenth:return[2,4];case u.ThirtySecond:return[4,4];case u.SixtyFourth:return[4,6];case u.OneHundredTwentyEighth:return[6,6];case u.TwoHundredFiftySixth:return[6,8]}return[0,0]}applyRest(e,t){if(this._lastNonRestBeat&&e.index>=this._lastNonRestBeat.index||this._firstNonRestBeat&&e.index<=this._firstNonRestBeat.index)return;let s=t,i=t;const a=da.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){if(!this.invertBeamDirection)return e;switch(e){case H.Down:return H.Up;default:return H.Down}}checkBeat(e){e.invertBeamDirection&&(this.invertBeamDirection=!0),this.voice||(this.voice=e.voice);let t=!1;if(0===this.beats.length)t=!0;else switch(this.beats[this.beats.length-1].beamingMode){case F.Auto:t=da.canJoin(this.beats[this.beats.length-1],e);break;case F.ForceSplitToNext:t=!1;break;case F.ForceMergeWithNext:t=!0}if(t){if(null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.isRest)0===this.beats.length&&this.beats.push(e);else{this.isRestBeamHelper&&(this.beats=[]),this.beats.push(e),e.graceType!==g.None&&(this.isGrace=!0),e.hasTuplet&&(this.hasTuplet=!0);let t=0;for(let s=0;s<e.notes.length;s++){let i=e.notes[s];i.leftHandFinger===f.Unknown&&i.rightHandFinger===f.Unknown||t++}t>this.fingeringCount&&(this.fingeringCount=t),this.checkNote(e.minNote),this.checkNote(e.maxNote),this.shortestDuration<e.duration&&(this.shortestDuration=e.duration),this._firstNonRestBeat||(this._firstNonRestBeat=e),this._lastNonRestBeat=e}e.hasTuplet&&(this.hasTuplet=!0)}return t}checkNote(e){if(!e)return;let t,s;this.voice&&e.isPercussion?(t=-ha.getPercussionLine(this.voice.bar,ha.getNoteValue(e)),s=t):(t=ha.getNoteValue(e),s=t,e.harmonicType!==m.None&&e.harmonicType!==m.Natural&&(s=e.realValue-this._staff.displayTranspositionPitch)),1===this.beats.length&&this.beats[0]===e.beat&&((-1===this._firstBeatLowestNoteCompareValue||t<this._firstBeatLowestNoteCompareValue)&&(this._firstBeatLowestNoteCompareValue=t),(-1===this._firstBeatHighestNoteCompareValue||s>this._firstBeatHighestNoteCompareValue)&&(this._firstBeatHighestNoteCompareValue=s)),(-1===this._lastBeatLowestNoteCompareValue||t<this._lastBeatLowestNoteCompareValue)&&(this._lastBeatLowestNoteCompareValue=t),(-1===this._lastBeatHighestNoteCompareValue||s>this._lastBeatHighestNoteCompareValue)&&(this._lastBeatHighestNoteCompareValue=s),(!this.lowestNoteInHelper||t<this._lowestNoteCompareValueInHelper)&&(this.lowestNoteInHelper=e,this._lowestNoteCompareValueInHelper=t),(!this.highestNoteInHelper||s>this._highestNoteCompareValueInHelper)&&(this.highestNoteInHelper=e,this._highestNoteCompareValueInHelper=s)}static canJoin(e,t){if(!e||!t||e.graceType!==t.graceType||e.graceType===g.BendGrace||t.graceType===g.BendGrace)return!1;if(e.graceType!==g.None&&t.graceType!==g.None)return!0;let s=e.voice.bar;if(s!==t.voice.bar)return!1;let i=e.playbackStart,a=t.playbackStart;if(!da.canJoinDuration(e.duration)||!da.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=ye.QuarterTime;switch(s.masterBar.timeSignatureDenominator){case 8:s.masterBar.timeSignatureNumerator%3==0&&(r+=ye.QuarterTime/2|0)}return(0|(r+i)/r)===(0|(r+a)/r)}static canJoinDuration(e){switch(e){case u.Whole:case u.Half:case u.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,s){return ke.getIndex(e.duration)-2-s>0&&ke.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 ua{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class pa{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new ua(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 ga{constructor(){this.reservedLayoutAreasByDisplayTime=new Map,this.restDurationsByDisplayTime=new Map}getBeatMinMaxY(){let e=-1e3,t=-1e3;for(const s of this.reservedLayoutAreasByDisplayTime.values())-1e3===e?(e=s.topY,t=s.bottomY):(e>s.topY&&(e=s.topY),t<s.bottomY&&(t=s.bottomY));return-1e3===e?[0,0]:[e,t]}reserveBeatSlot(e,t,s){t!=s&&(this.reservedLayoutAreasByDisplayTime.has(e.displayStart)||this.reservedLayoutAreasByDisplayTime.set(e.displayStart,new pa(e)),this.reservedLayoutAreasByDisplayTime.get(e.displayStart).addSlot(t,s),e.isRest&&this.registerRest(e))}registerRest(e){this.restDurationsByDisplayTime.has(e.displayStart)||this.restDurationsByDisplayTime.set(e.displayStart,new Map),this.restDurationsByDisplayTime.get(e.displayStart).has(e.playbackDuration)||this.restDurationsByDisplayTime.get(e.displayStart).set(e.playbackDuration,e.id)}applyRestCollisionOffset(e,t,s){if(e.voice.index>0&&this.reservedLayoutAreasByDisplayTime.has(e.playbackStart)){const i=da.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 fa{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this._renderer=e,this.collisionHelper=new ga}initialize(){var e=this._renderer,t=this._renderer.bar;let s=null,i=null;for(let a=0,r=t.voices.length;a<r;a++){let r=t.voices[a];this.beamHelpers.push([]),this.beamHelperLookup.push(new Map);for(let a=0,n=r.beats.length;a<n;a++){let n,o=r.beats[a];o.graceType!==g.None?n=i:(n=s,i=null),n&&n.checkBeat(o)||(n&&n.finish(),n=new da(t.staff,e),n.checkBeat(o),o.graceType!==g.None?i=n:s=n,this.beamHelpers[r.index].push(n)),this.beamHelperLookup[r.index].set(o.index,n)}s&&s.finish(),i&&i.finish(),s=null,i=null}}getBeamingHelperForBeat(e){return this.beamHelperLookup[e.voice.index].get(e.index)}}!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"}(ne||(ne={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(oe||(oe={}));class ma{constructor(e,t){this._preBeatGlyphs=new ra,this._voiceContainers=new Map,this._postBeatGlyphs=new ra,this.x=0,this.y=0,this.width=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 fa(this))}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}get middleYPosition(){return 0}registerOverflowTop(e){e>this.topOverflow&&(this.topOverflow=e)}registerOverflowBottom(e){e>this.bottomOverflow&&(this.bottomOverflow=e)}scaleToWidth(e){let t=e-this._preBeatGlyphs.width-this._postBeatGlyphs.width;for(const e of this._voiceContainers.values())e.scaleToWidth(t);this._postBeatGlyphs.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width+t,this.width=e}get resources(){return this.settings.display.resources}get settings(){return this.scoreRenderer.settings}get scale(){return this.settings.display.scale}get 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);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)}return this._postBeatGlyphs.x=Math.floor(e),this._postBeatGlyphs.width=this.layoutingInfo.postBeatSize,this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),!0}finalizeRenderer(){this.isFinalized=!0}doLayout(){if(this.bar){this.helpers.initialize(),this._preBeatGlyphs=new ra,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new ra,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 na(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()}}hasVoiceContainer(e){return!e.isEmpty||0===e.index}updateSizes(){this.staff.registerStaffTop(this.topPadding),this.staff.registerStaffBottom(this.height-this.bottomPadding);let e=this._voiceContainers,t=this.beatGlyphsStart,s=t;for(const i of e.values()){i.x=t,i.doLayout();let e=i.x+i.width;s<e&&(s=e)}this._postBeatGlyphs.x=Math.floor(s),this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.height+=this.layoutingInfo.height*this.scale}addPreBeatGlyph(e){e.renderer=this,this._preBeatGlyphs.addGlyph(e)}addBeatGlyph(e){e.renderer=this,e.preNotes.renderer=this,e.onNotes.renderer=this,e.onNotes.beamingHelper=this.helpers.beamHelperLookup[e.beat.voice.index].get(e.beat.index),this.getVoiceContainer(e.beat.voice).addGlyph(e)}getVoiceContainer(e){return this._voiceContainers.has(e.index)?this._voiceContainers.get(e.index):void 0}getBeatContainer(e){var t,s;return null===(s=null===(t=this.getVoiceContainer(e.voice))||void 0===t?void 0:t.beatGlyphs)||void 0===s?void 0:s[e.index]}getPreNotesGlyphForBeat(e){var t;return null===(t=this.getBeatContainer(e))||void 0===t?void 0:t.preNotes}getOnNotesGlyphForBeat(e){var t;return null===(t=this.getBeatContainer(e))||void 0===t?void 0:t.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 di;i.bar=this.bar,i.visualBounds=new at,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 at,i.realBounds.x=t+this.x,i.realBounds.y=s+this.y,i.realBounds.w=this.width,i.realBounds.h=this.height,e.addBar(i);for(const[e,a]of this._voiceContainers){let r=this.bar.isEmpty&&0===e;if(!a.voice.isEmpty||r)for(let e=0,n=a.beatGlyphs.length;e<n;e++){a.beatGlyphs[e].buildBoundingsLookup(i,t+this.x+a.x,s+this.y+a.y,r)}}}addPostBeatGlyph(e){this._postBeatGlyphs.addGlyph(e)}createPreBeatGlyphs(){this._wasFirstOfLine=this.isFirstOfLine}createBeatGlyphs(){for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];this.hasVoiceContainer(t)&&this.createVoiceGlyphs(this.bar.voices[e])}}createVoiceGlyphs(e){}createPostBeatGlyphs(){}get beatGlyphsStart(){return this._preBeatGlyphs.x+this._preBeatGlyphs.width}get postBeatGlyphsStart(){return this._postBeatGlyphs.x}getBeatX(e,t=ae.PreNotes){let s=this.getBeatContainer(e);if(s)switch(t){case ae.PreNotes:return s.voiceContainer.x+s.x;case ae.OnNotes:return s.voiceContainer.x+s.x+s.onNotes.x;case ae.MiddleNotes:return s.voiceContainer.x+s.x+s.onTimeX;case ae.Stem:const t=s.onNotes.beamingHelper?s.onNotes.beamingHelper.getBeatLineX(e):s.onNotes.x+s.onNotes.width/2;return s.voiceContainer.x+t;case ae.PostNotes:return s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.width;case ae.EndBeat:return s.voiceContainer.x+s.x+s.width}return 0}getNoteX(e,t){let s=this.getBeatContainer(e.beat);return s?s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.getNoteX(e,t):0}getNoteY(e,t){let s=this.getOnNotesGlyphForBeat(e.beat);return s?s.getNoteY(e,t):NaN}reLayout(){(this._wasFirstOfLine&&!this.isFirstOfLine||!this._wasFirstOfLine&&this.isFirstOfLine)&&(this._preBeatGlyphs=new ra,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()),this.updateSizes(),this.registerLayoutingInfo()}paintSimileMark(e,t,s){switch(this.bar.simileMark){case o.Simple:s.fillMusicFontSymbol(e+this.x+(this.width-20*this.scale)/2,t+this.y+this.height/2,1,N.Repeat1Bar,!1);break;case o.SecondOfDouble:s.fillMusicFontSymbol(e+this.x-28*this.scale/2,t+this.y+this.height/2,1,N.Repeat2Bars,!1)}}completeBeamingHelper(e){}}ma.LineSpacing=8,ma.StemWidth=.12*ma.LineSpacing,ma.StaffLineThickness=.13*ma.LineSpacing,ma.BeamThickness=.5*ma.LineSpacing,ma.BeamSpacing=.25*ma.LineSpacing,function(e){e[e.SinglePreBeat=0]="SinglePreBeat",e[e.SingleOnBeat=1]="SingleOnBeat",e[e.SingleOnBeatToEnd=2]="SingleOnBeatToEnd",e[e.GroupedOnBeat=3]="GroupedOnBeat",e[e.GroupedOnBeatToEnd=4]="GroupedOnBeatToEnd",e[e.FullBar=5]="FullBar"}(he||(he={}));class ya extends Ci{constructor(e,t){super(0,0),this._uniqueEffectGlyphs=[],this._effectGlyphs=[],this.isEmpty=!0,this.previousBand=null,this.isLinkedToPrevious=!1,this.firstBeat=null,this.lastBeat=null,this.height=0,this.slot=null,this.voice=e,this.info=t}doLayout(){super.doLayout();for(let e=0;e<this.renderer.bar.voices.length;e++)this._effectGlyphs.push(new Map),this._uniqueEffectGlyphs.push([])}createGlyph(e){if(e.voice===this.voice&&this.info.shouldCreateGlyph(this.renderer.settings,e)&&(!this.info.hideOnMultiTrack||0===this.renderer.staff.trackIndex)){if(this.isEmpty=!1,this.firstBeat&&!e.isBefore(this.firstBeat)||(this.firstBeat=e),!this.lastBeat||e.isAfter(this.lastBeat))switch(this.lastBeat=e,this.info.sizingMode){case he.SingleOnBeatToEnd:case he.GroupedOnBeatToEnd:this.lastBeat.nextBeat&&(this.lastBeat=this.lastBeat.nextBeat)}let t=this.createOrResizeGlyph(this.info.sizingMode,e);t.height>this.height&&(this.height=t.height)}}createOrResizeGlyph(e,t){let s;switch(e){case he.FullBar: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 he.SinglePreBeat:case he.SingleOnBeat:case he.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 he.GroupedOnBeat:case he.GroupedOnBeatToEnd:let i=e===he.GroupedOnBeat?he.SingleOnBeat:he.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 i=this.renderer.previousRenderer.getBand(this.voice,this.info.effectId)._effectGlyphs[t.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(he.SingleOnBeat,t)}}paint(e,t,s){super.paint(e,t,s);for(let i=0,a=this._uniqueEffectGlyphs.length;i<a;i++){let a=this._uniqueEffectGlyphs[i];for(let i=0,r=a.length;i<r;i++){a[i].paint(e+this.x,t+this.y,s)}}}alignGlyphs(){for(let e=0;e<this._effectGlyphs.length;e++)for(const t of this._effectGlyphs[e].keys())this.alignGlyph(this.info.sizingMode,this.renderer.bar.voices[e].beats[t])}alignGlyph(e,t){let s,i=this._effectGlyphs[t.voice.index].get(t.index),a=this.renderer.getBeatContainer(t);switch(e){case he.SinglePreBeat:s=a.preNotes,i.x=this.renderer.beatGlyphsStart+s.x+a.x,i.width=s.width;break;case he.SingleOnBeat:case he.GroupedOnBeat:s=a.onNotes,i.x=this.renderer.beatGlyphsStart+s.x+a.x,i.width=s.width;break;case he.SingleOnBeatToEnd:case he.GroupedOnBeatToEnd:s=a.onNotes,i.x=this.renderer.beatGlyphsStart+s.x+a.x,a.beat.isLastOfVoice?i.width=this.renderer.width-i.x:i.width=a.width-a.preNotes.width-a.preNotes.x;break;case he.FullBar:i.width=this.renderer.width}}}class ba{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class Sa{constructor(){this.bands=[],this.shared=new ba}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 wa{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 Sa;return this.slots.push(t),t}register(e){let t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class _a extends aa{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 Ba extends _a{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,s){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class Ta extends ma{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(){super.finalizeRenderer(),this.updateHeight()}updateHeight(){if(!this.sizingInfo)return;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}this.height=e}applyLayoutingInfo(){if(!super.applyLayoutingInfo())return!1;if(this.index>0){let e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new wa;for(let e of this._bands)e.alignGlyphs(),e.isEmpty||this.sizingInfo.register(e);return this.updateHeight(),!0}scaleToWidth(e){super.scaleToWidth(e);for(let e of this._bands)e.alignGlyphs()}createBeatGlyphs(){this._bands=[],this._bandLookup=new Map;for(let e of this.bar.voices)if(this.hasVoiceContainer(e))for(let t of this._infos){let s=new ya(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 Di(t,this.getVoiceContainer(e));s.preNotes=new _a,s.onNotes=new Ba,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 ka extends ia{constructor(e,t){super(),this._infos=t,this._staffId=e,this.isInAccolade=!1,this.isRelevantForBoundsLookup=!1}get staffId(){return this._staffId}create(e,t){return new Ta(e,t,this._infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class va extends Fi{constructor(e,t,s){super(e,t),this._endingsString="",this._endings=[];for(let e=0;e<Oe.MaxAlternateEndings;e++)0!=(s&1<<e)&&this._endings.push(e)}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(va.Padding*this.scale+2);let e="";for(let t=0,s=this._endings.length;t<s;t++)e+=this._endings[t]+1,e+=". ";this._endingsString=e}paint(e,t,s){super.paint(e,t,s);let i=s.textBaseline;if(s.textBaseline=E.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+va.Padding*this.scale,t+this.y*this.scale)}s.textBaseline=i}}va.Padding=3;class xa{get effectId(){return this.notationElement.toString()}}class Na extends xa{get notationElement(){return k.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return he.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){return new va(0,0,t.voice.bar.masterBar.alternateEndings)}canExpand(e,t){return!0}}class Pa extends Fi{constructor(e,t,s,i,a=P.Left){super(e,t),this._lines=s.split("\n"),this.font=i,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,s){let i=s.color;s.color=i,s.font=this.font;let a=s.textAlign;s.textAlign=this.textAlign;let r=t+this.y;for(let t of this._lines)s.fillText(t,e+this.x,r),r+=this.font.size;s.textAlign=a}}class Ea extends xa{get notationElement(){return k.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Pa(0,0,"Capo. fret "+t.voice.bar.staff.capo,e.resources.effectFont,P.Left)}canExpand(e,t){return!1}}class Ca extends xa{get notationElement(){return k.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Pa(0,0,t.chord.name,e.resources.effectFont,P.Center)}canExpand(e,t){return!1}}class Fa extends Fi{constructor(e){super(),this.forceGroupedRendering=!1,this.endOnBarLine=!1,this.endPosition=e}get isLinkedWithPrevious(){return!!this.previousGlyph&&this.previousGlyph.renderer.staff.staveGroup===this.renderer.staff.staveGroup}get isLinkedWithNext(){return!!this.nextGlyph&&this.nextGlyph.renderer.isFinalized&&this.nextGlyph.renderer.staff.staveGroup===this.renderer.staff.staveGroup}paint(e,t,s){if(this.isLinkedWithPrevious)return;if(!this.isLinkedWithNext&&!this.forceGroupedRendering)return void this.paintNonGrouped(e,t,s);let i;if(!this.isLinkedWithNext&&this.forceGroupedRendering)i=this;else for(i=this.nextGlyph;i.isLinkedWithNext;)i=i.nextGlyph;let a=i.renderer,r=i.beat,n=this.endPosition,o=e-this.renderer.x,h=this.calculateEndX(a,r,o,n);this.paintGrouped(e,t,h,s)}calculateEndX(e,t,s,i){return t?s+e.x+e.getBeatX(t,i):s+e.x+this.x+this.width}paintNonGrouped(e,t,s){let i=e-this.renderer.x,a=this.calculateEndX(this.renderer,this.beat,i,this.endPosition);this.paintGrouped(e,t,a,s)}}class La extends Fa{constructor(e,t,s){super(ae.EndBeat),this._crescendo=d.None,this._crescendo=s,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17*this.scale}paintGrouped(e,t,s,i){let a=e+this.x,r=this.height*this.scale;i.beginPath(),this._crescendo===d.Crescendo?(s-=La.Padding*this.scale,i.moveTo(s,t+this.y),i.lineTo(a,t+this.y+r/2),i.lineTo(s,t+this.y+r)):(s-=La.Padding*this.scale,i.moveTo(a,t+this.y),i.lineTo(s,t+this.y+r/2),i.lineTo(a,t+this.y+r)),i.stroke()}}La.Padding=Mi.QuarterNoteHeadWidth/2|0;class Ma extends xa{get notationElement(){return k.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==d.None}createNewGlyph(e,t){return new La(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class Ia extends Li{constructor(e,t,s){super(e,t,.6,Ia.getSymbol(s))}doLayout(){super.doLayout(),this.height=17*this.scale,this.y+=this.height/2}static getSymbol(e){switch(e){case p.PPP:return N.DynamicPPP;case p.PP:return N.DynamicPP;case p.P:return N.DynamicPiano;case p.MP:return N.DynamicMP;case p.MF:return N.DynamicMF;case p.F:return N.DynamicForte;case p.FF:return N.DynamicFF;case p.FFF:return N.DynamicFFF;default:return N.None}}}class Da extends xa{get notationElement(){return k.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return this.internalShouldCreateGlyph(t)}internalShouldCreateGlyph(e){if(e.voice.bar.staff.track.score.stylesheet.hideDynamics||e.isEmpty||e.voice.isEmpty||e.isRest||e.graceType!==g.None)return!1;let t=this.getPreviousDynamicsBeat(e),s=0===e.voice.index&&!t||e.dynamics!==(null==t?void 0:t.dynamics);if(s&&e.voice.index>0)for(let t of e.voice.bar.voices)if(t.index<e.voice.index){let i=t.getBeatAtPlaybackStart(e.playbackStart);i&&e.dynamics===i.dynamics&&this.internalShouldCreateGlyph(i)&&(s=!1)}return s}getPreviousDynamicsBeat(e){let t=e.previousBeat;for(;null!=t;){if(!t.isRest&&t.graceType===g.None)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new Ia(0,0,t.dynamics)}canExpand(e,t){return!0}}class Ra extends Fi{doLayout(){super.doLayout(),this.height=17*this.scale}paint(e,t,s){let i=6*this.scale,a=Math.max(this.width,14*this.scale),r=this.height/2;s.beginPath(),s.moveTo(e+this.x,t+this.y+r),s.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r-i),s.moveTo(e+this.x,t+this.y+r),s.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r+i),s.stroke()}}class Aa extends xa{get notationElement(){return k.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.fadeIn}createNewGlyph(e,t){return new Ra}canExpand(e,t){return!0}}class Oa extends Li{constructor(e,t,s){super(e,t,1,Oa.getSymbol(s))}static getSymbol(e){switch(e){case O.Short:return N.FermataShortAbove;case O.Medium:return N.FermataAbove;case O.Long:return N.FermataLongAbove;default:return N.None}}doLayout(){this.width=23*this.scale,this.height=12*this.scale}paint(e,t,s){super.paint(e-this.width/2,t+this.height,s)}}class Ga extends xa{get notationElement(){return k.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new Oa(0,0,t.fermata.type)}canExpand(e,t){return!0}}class Va extends xa{get notationElement(){return k.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return!(0!==t.voice.index||t.isRest||e.notation.fingeringMode!==B.SingleNoteEffectBand&&e.notation.fingeringMode!==B.SingleNoteEffectBandForcePiano)&&(1===t.notes.length&&t.notes[0].isFingering)}createNewGlyph(e,t){var s;let i=f.Unknown,a=!1,r=t.notes[0];r.leftHandFinger!==f.Unknown?(i=r.leftHandFinger,a=!0):r.rightHandFinger!==f.Unknown&&(i=r.rightHandFinger);let n=null!==(s=ke.fingerToString(e.settings,t,i,a))&&void 0!==s?s:"";return new Pa(0,0,n,e.resources.fingeringFont,P.Left)}canExpand(e,t){return!0}}class Ha extends xa{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 Wa extends Fa{constructor(e){super(ae.OnNotes),this._label=e}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=ae.EndBeat,this.forceGroupedRendering=!0),super.doLayout(),this.height=this.renderer.resources.effectFont.size}paintNonGrouped(e,t,s){let i=this.renderer.resources;s.font=i.effectFont;let a=s.textAlign;s.textAlign=P.Center,s.fillText(this._label,e+this.x,t+this.y),s.textAlign=a}paintGrouped(e,t,s,i){this.paintNonGrouped(e,t,i);let a=3*this.scale,r=i.measureText(this._label),n=e+this.x+r/2+a,o=t+this.y+4*this.scale,h=8*this.scale;if(s>n){let e=n;for(;e<s;)i.beginPath(),i.moveTo(e,0|o),i.lineTo(Math.min(e+h,s),0|o),e+=h+a,i.stroke();i.beginPath(),i.moveTo(s,o-5*this.scale|0),i.lineTo(s,o+5*this.scale|0),i.stroke()}}}Wa.LineSpacing=3,Wa.LineTopPadding=4,Wa.LineTopOffset=5,Wa.LineSize=8;class za extends Ha{constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case m.None:this._effectId="harmonics-none";break;case m.Natural:this._effectId="harmonics-natural";break;case m.Artificial:this._effectId="harmonics-artificial";break;case m.Pinch:this._effectId="harmonics-pinch";break;case m.Tap:this._effectId="harmonics-tap";break;case m.Semi:this._effectId="harmonics-semi";break;case m.Feedback:this._effectId="harmonics-feedback";break;default:this._effectId=""}}get effectId(){return this._effectId}get notationElement(){return k.EffectHarmonics}shouldCreateGlyphForNote(e){return!(!e.isHarmonic||e.harmonicType!==this._harmonicType)&&(e.beat!==this._beat&&(this._beat=e.beat),!0)}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new Wa(za.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case m.Natural:return"N.H.";case m.Artificial:return"A.H.";case m.Pinch:return"P.H.";case m.Tap:return"T.H.";case m.Semi:return"S.H.";case m.Feedback:return"Fdbk."}return""}}class Ua extends xa{get notationElement(){return k.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new Wa("LetRing")}canExpand(e,t){return!0}}class Xa extends Fi{constructor(e,t,s,i,a=P.Center){super(e,t),this._lines=s,this.font=i,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,s){s.font=this.font;let i=s.textAlign;s.textAlign=this.textAlign;for(let i=0;i<this._lines.length;i++)this._lines[i]&&s.fillText(this._lines[i],e+this.x,t+this.y+i*this.font.size);s.textAlign=i}}class Ya extends xa{get notationElement(){return k.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new Xa(0,0,t.lyrics,e.resources.effectFont,P.Center)}canExpand(e,t){return!0}}class qa extends xa{get notationElement(){return k.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return he.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 Pa(0,0,t.voice.bar.masterBar.section.marker?"["+t.voice.bar.masterBar.section.marker+"] "+t.voice.bar.masterBar.section.text:t.voice.bar.masterBar.section.text,e.resources.markerFont,P.Left)}canExpand(e,t){return!0}}class Ja extends Fa{constructor(e,t){super(ae.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=13*this.scale}paintNonGrouped(e,t,s){this.paintOttava(e,t,s)}paintOttava(e,t,s){let i=0;switch(this._ottava){case n._15ma:i=37*this.scale,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,N.QuindicesimaAlta,!1);break;case n._8va:i=26*this.scale,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,N.OttavaAlta,!1);break;case n._8vb:i=23*this.scale,s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,N.OttavaBassaVb,!1);break;case n._15mb:i=36*this.scale,s.fillMusicFontSymbols(e+this.x-i/2,t+this.y+this.height,.8,[N.Quindicesima,N.OctaveBaselineM,N.OctaveBaselineB],!1)}return i/2}paintGrouped(e,t,s,i){let a=this.paintOttava(e,t,i),r=3*this.scale,n=e+this.x+a+r,o=t+this.y;o+=this._aboveStaff?2*this.scale:this.height-2*this.scale;let h=8*this.scale;if(s>n){let e=n;for(;e<s;)i.beginPath(),i.moveTo(e,0|o),i.lineTo(Math.min(e+h,s),0|o),e+=h+r,i.stroke();i.beginPath(),this._aboveStaff?(i.moveTo(s,o),i.lineTo(s,t+this.y+this.height)):(i.moveTo(s,o),i.lineTo(s,t+this.y)),i.stroke()}}}class Qa extends xa{constructor(e){super(),this._aboveStaff=e}get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return k.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeat}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 Ja(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class ja extends Ha{get notationElement(){return k.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new Wa("P.M.")}constructor(){super()}}class Ka extends Ha{get notationElement(){return k.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===S.PickSlideDown||e.slideOutType===S.PickSlideUp}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new Wa("P.S.")}constructor(){super()}}class $a extends Li{constructor(e,t,s){super(e,t,Mi.GraceScale,$a.getSymbol(s))}doLayout(){this.width=9*this.scale,this.height=13*this.scale}paint(e,t,s){super.paint(e,t+this.height,s)}static getSymbol(e){switch(e){case x.Up:return N.StringsUpBow;case x.Down:return N.StringsDownBow;default:return N.None}}}class Za extends xa{get notationElement(){return k.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==x.None}createNewGlyph(e,t){return new $a(0,0,t.pickStroke)}canExpand(e,t){return!0}}class er extends Fa{constructor(e){super(ae.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case w.Slight:this._stepSize=12*this.scale;break;case w.Wide:this._stepSize=23*this.scale}this.height=18*this.scale}paintGrouped(e,t,s,i){let a=e+this.x,r=s-a,n=Math.max(1,r/this._stepSize);i.beginPath(),i.moveTo(a,t+this.y);for(let e=0;e<n;e++)i.lineTo(a+this._stepSize/2,t+this.y+this.height),i.lineTo(a+this._stepSize,t+this.y),a+=this._stepSize;i.stroke()}}class tr extends xa{get notationElement(){return k.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===w.Slight}createNewGlyph(e,t){return new er(w.Slight)}canExpand(e,t){return!0}}class sr extends Fa{constructor(e,t,s,i=1.2,a=!1){super(ae.EndBeat),this._scale=0,this._symbol=N.None,this._symbolSize=0,this._type=s,this._scale=i,this.x=e,this.y=t,this._partialWaves=a}doLayout(){super.doLayout();let e=0;switch(this._type){case w.Slight:this._symbol=N.WiggleTrill,this._symbolSize=9*this._scale,e=6*this._scale;break;case w.Wide:this._symbol=N.WiggleVibratoMediumFast,this._symbolSize=10*this._scale,e=10*this._scale}this.height=e*this.scale}paintGrouped(e,t,s,i){let a=s-(e+this.x),r=this._symbolSize*this.scale,n=a/r;this._partialWaves||(n=Math.floor(n)),n<1&&(n=1);let o=0;for(let s=0;s<n;s++)i.fillMusicFontSymbol(e+this.x+o,t+this.y+2*this.height,this._scale*this.scale,this._symbol,!1),o+=r}}class ir extends Ha{get notationElement(){return k.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===w.Slight||e.isTieDestination&&e.tieOrigin.vibrato===w.Slight}get sizingMode(){return he.GroupedOnBeatToEnd}createNewGlyph(e,t){return new sr(0,0,w.Slight,1.2)}constructor(){super()}}class ar extends xa{get notationElement(){return k.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){let s=e.resources;return t.slap?new Pa(0,0,"S",s.effectFont,P.Left):t.pop?new Pa(0,0,"P",s.effectFont,P.Left):new Pa(0,0,"T",s.effectFont,P.Left)}canExpand(e,t){return!0}}class rr extends Fi{constructor(e,t,s){super(e,t),this._tempo=0,this._tempo=s}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,s){let i=this.renderer.resources;s.font=i.markerFont,s.fillMusicFontSymbol(e+this.x,t+this.y+.8*this.height,this.scale*Mi.GraceScale,N.NoteQuarterUp,!1),s.fillText("= "+this._tempo.toString(),e+this.x+this.height/2,t+this.y+s.font.size/2)}}class nr extends xa{get notationElement(){return k.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return he.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&(!!t.voice.bar.masterBar.tempoAutomation||0===t.voice.bar.index)}createNewGlyph(e,t){let s=0;return s=t.voice.bar.masterBar.tempoAutomation?t.voice.bar.masterBar.tempoAutomation.value:t.voice.bar.staff.track.score.tempo,new rr(0,0,s)}canExpand(e,t){return!0}}class or extends xa{get notationElement(){return k.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Pa(0,0,t.text,e.resources.effectFont,P.Left)}canExpand(e,t){return!0}}class hr extends Fi{constructor(e,t){super(e,t)}doLayout(){super.doLayout(),this.height=20*this.scale}paint(e,t,s){let i=this.renderer.resources;s.font=i.markerFont;let a=s.measureText("tr");s.fillText("tr",e+this.x,t+this.y+s.font.size/2);let r=a+3*this.scale,n=this.width-r,o=11*this.scale*1.2,h=Math.max(1,(n-r)/o),l=r,c=t+this.y+this.height;for(let t=0;t<h;t++)s.fillMusicFontSymbol(e+this.x+l,c,1.2,N.WiggleTrill,!1),l+=o}}class lr extends Ha{get notationElement(){return k.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return he.SingleOnBeat}createNewGlyph(e,t){return new hr(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(le||(le={}));class cr extends Fi{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,s){e+=this.x;let i=(t+=this.y)+this.height*Mi.GraceScale;s.font=this.renderer.resources.effectFont,s.fillText("(",e,t+.3*this.height);let a=e+10*this.scale,r=e+40*this.scale;switch(this._tripletFeel){case D.NoTripletFeel:this.renderBarNote(a,i,cr.NoteScale,s,[le.Full]),this.renderBarNote(r,i,cr.NoteScale,s,[le.Full]);break;case D.Triplet8th:this.renderBarNote(a,i,cr.NoteScale,s,[le.Full]),s.fillMusicFontSymbol(r,i,cr.NoteScale,N.NoteQuarterUp,!1),s.fillMusicFontSymbol(r+cr.NoteSeparation*this.scale,i,cr.NoteScale,N.NoteEighthUp,!1),this.renderTriplet(r,t,s);break;case D.Triplet16th:this.renderBarNote(a,i,cr.NoteScale,s,[le.Full,le.Full]),this.renderBarNote(r,i,cr.NoteScale,s,[le.Full,le.PartialRight]),this.renderTriplet(r,t,s);break;case D.Dotted8th:this.renderBarNote(a,i,cr.NoteScale,s,[le.Full]),this.renderBarNote(r,i,cr.NoteScale,s,[le.Full,le.PartialRight]),s.fillCircle(r+9*this.scale,i,this.scale);break;case D.Dotted16th:this.renderBarNote(a,i,cr.NoteScale,s,[le.Full,le.Full]),this.renderBarNote(r,i,cr.NoteScale,s,[le.Full,le.Full,le.PartialRight]),s.fillCircle(r+9*this.scale,i,this.scale);break;case D.Scottish8th:this.renderBarNote(a,i,cr.NoteScale,s,[le.Full]),this.renderBarNote(r,i,cr.NoteScale,s,[le.Full,le.PartialLeft]),s.fillCircle(r+cr.NoteSeparation*this.scale+8*this.scale,i,this.scale);break;case D.Scottish16th:this.renderBarNote(a,i,cr.NoteScale,s,[le.Full,le.Full]),this.renderBarNote(r,i,cr.NoteScale,s,[le.Full,le.Full,le.PartialLeft]),s.fillCircle(r+cr.NoteSeparation*this.scale+8*this.scale,i,this.scale)}s.fillText("=",e+30*this.scale,t+5*this.scale),s.fillText(")",e+65*this.scale,t+.3*this.height)}renderBarNote(e,t,s,i,a){i.fillMusicFontSymbol(e,t,s,N.NoteQuarterUp,!1);let r=cr.NoteSeparation/2*this.scale;for(let s=0;s<a.length;s++)switch(a[s]){case le.Full:i.fillRect(e+4*this.scale,t-cr.NoteHeight*this.scale+cr.BarSeparation*this.scale*s,cr.NoteSeparation*this.scale,cr.BarHeight*this.scale);break;case le.PartialLeft:i.fillRect(e+4*this.scale,t-cr.NoteHeight*this.scale+cr.BarSeparation*this.scale*s,r,cr.BarHeight*this.scale);break;case le.PartialRight:i.fillRect(e+4*this.scale+r,t-cr.NoteHeight*this.scale+cr.BarSeparation*this.scale*s,r,cr.BarHeight*this.scale)}i.fillMusicFontSymbol(e+cr.NoteSeparation*this.scale,t,s,N.NoteQuarterUp,!1)}renderTriplet(e,t,s){t+=2*this.scale;let i=this.renderer.resources.effectFont;s.font=new vs(i.family,.8*i.size,i.style);let a=e+cr.NoteSeparation*this.scale+3*this.scale;s.beginPath(),s.moveTo(e,t+3*this.scale),s.lineTo(e,t),s.lineTo(e+5*this.scale,t),s.moveTo(a+5*this.scale,t+3*this.scale),s.lineTo(a+5*this.scale,t),s.lineTo(a,t),s.stroke(),s.fillText("3",e+7*this.scale,t-10*this.scale),s.font=i}}cr.NoteScale=.4,cr.NoteHeight=12,cr.NoteSeparation=12,cr.BarHeight=2,cr.BarSeparation=3;class dr extends xa{get notationElement(){return k.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return he.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==D.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new cr(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class ur extends xa{get notationElement(){return k.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new Wa("w/bar")}canExpand(e,t){return!0}}class pr extends xa{get notationElement(){return k.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===w.Wide}createNewGlyph(e,t){return new er(w.Wide)}canExpand(e,t){return!0}}class gr extends Ha{get notationElement(){return k.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===w.Wide||e.isTieDestination&&e.tieOrigin.vibrato===w.Wide}get sizingMode(){return he.GroupedOnBeatToEnd}createNewGlyph(e,t){return new sr(0,0,w.Wide,1.2)}}class fr extends Fi{constructor(e,t,s){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=s}doLayout(){super.doLayout();const e=this.scale;let t=this.renderer.resources;this._textRow=1.5*t.effectFont.size*e,this._fretRow=1.5*t.effectFont.size*e,this._chord.firstFret>1?this._firstFretSpacing=fr.FretSpacing*e:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+(fr.Frets-1)*fr.FretSpacing*e+2*fr.Padding*e,this.width=this._firstFretSpacing+(this._chord.staff.tuning.length-1)*fr.StringSpacing*e+2*fr.Padding*e}paint(e,t,s){e+=this.x+fr.Padding*this.scale+this._firstFretSpacing,t+=this.y;let i=this.width-2*fr.Padding*this.scale+this.scale-this._firstFretSpacing,a=fr.StringSpacing*this.scale,r=fr.FretSpacing*this.scale,n=this.renderer.resources,o=fr.CircleRadius*this.scale,h=s.textAlign,l=s.textBaseline;s.font=n.effectFont,s.textAlign=P.Center,s.textBaseline=E.Top,this._chord.showName&&s.fillText(this._chord.name,e+this.width/2,t+n.effectFont.size/2),t+=this._textRow,e+=a/2,s.font=n.fretboardNumberFont,s.textBaseline=E.Middle;for(let i=0;i<this._chord.staff.tuning.length;i++){let r=e+i*a,n=t+this._fretRow/2,o=this._chord.strings[this._chord.staff.tuning.length-i-1];o<0?s.fillMusicFontSymbol(r,n,this.scale,N.FretboardX,!0):0===o?s.fillMusicFontSymbol(r,n,this.scale,N.FretboardO,!0):(o-=this._chord.firstFret-1,s.fillText(o.toString(),r,n))}t+=this._fretRow;for(let i=0;i<this._chord.staff.tuning.length;i++){let n=e+i*a;s.fillRect(n,t,1,r*fr.Frets+this.scale)}this._chord.firstFret>1&&(s.textAlign=P.Left,s.fillText(this._chord.firstFret.toString(),e-this._firstFretSpacing,t+r/2)),s.fillRect(e,t-this.scale,i,2*this.scale);for(let a=0;a<=fr.Frets;a++){let n=t+a*r;s.fillRect(e,n,i,this.scale)}let c=new Map;for(let e of this._chord.barreFrets){let t=[-1,-1];c.set(e-this._chord.firstFret,t)}for(let i=0;i<this._chord.strings.length;i++){let n=this._chord.strings[i];if(n>0){if(n-=this._chord.firstFret,c.has(n)){let e=c.get(n);(-1===e[0]||i<e[0])&&(e[0]=i),(-1===e[1]||i>e[1])&&(e[1]=i)}let h=t+n*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-i-1)*a;s.fillCircle(l,h,o)}}for(const[i,n]of c){let h=t+i*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-n[1]-1)*a,c=e+(this._chord.strings.length-n[0]-1)*a;s.fillRect(l,h-o,c-l,2*o)}s.textAlign=h,s.textBaseline=l}}fr.Padding=5,fr.Frets=5,fr.CircleRadius=2.5,fr.StringSpacing=10,fr.FretSpacing=12;class mr extends aa{constructor(e,t,s=P.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=s}doLayout(){let e=0;switch(this._align){case P.Left:e=0;break;case P.Center:e=(this.width-this._glyphWidth)/2;break;case P.Right:e=this.width-this._glyphWidth}for(let t of this.glyphs)t.x=e,e+=t.width}addGlyphToRow(e){this.glyphs.push(e),this._glyphWidth+=e.width,e.height>this.height&&(this.height=e.height)}}class yr extends aa{constructor(e,t,s=P.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=s}doLayout(){let e=0,t=0,s=2*yr.Padding*this.scale;this._rows=[];let i=new mr(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 mr(e,t,this._align),i.width=this.width,i.addGlyphToRow(a),e+=a.width);i.isEmpty||(i.doLayout(),this._rows.push(i),t+=i.height+s),this.height=t+s}paint(e,t,s){for(let i of this._rows)i.paint(e+this.x,t+this.y+yr.Padding*this.scale,s)}}yr.Padding=3;class br extends yr{constructor(e,t){super(e,t)}addChord(e){if(e.strings.length>0){let t=new fr(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}}class Sr{constructor(e,t,s){this._sharedLayoutData=new Map,this.barRenderers=[],this.x=0,this.y=0,this.height=0,this.index=0,this.staffIndex=0,this.trackIndex=0,this.staveTop=0,this.topSpacing=20,this.bottomSpacing=5,this.staveBottom=0,this.isFirstInAccolade=!1,this.isLastInAccolade=!1,this._factory=s,this.trackIndex=e,this.modelStaff=t}get staveId(){return this._factory.staffId}getSharedLayoutData(e,t){return this._sharedLayoutData.has(e)?this._sharedLayoutData.get(e):t}setSharedLayoutData(e,t){this._sharedLayoutData.set(e,t)}get isInAccolade(){return this._factory.isInAccolade}get isRelevantForBoundsLookup(){return this._factory.isRelevantForBoundsLookup}registerStaffTop(e){this.staveTop=e}registerStaffBottom(e){this.staveBottom=e}addBarRenderer(e){e.staff=this,e.index=this.barRenderers.length,e.reLayout(),this.barRenderers.push(e),this.staveGroup.layout.registerBarRenderer(this.staveId,e)}addBar(e,t){let s;s=e?this._factory.create(this.staveGroup.layout.renderer,e):new ma(this.staveGroup.layout.renderer,e),s.staff=this,s.index=this.barRenderers.length,s.layoutingInfo=t,s.doLayout(),s.registerLayoutingInfo(),this.barRenderers.push(s),e&&this.staveGroup.layout.registerBarRenderer(this.staveId,s)}revertLastBar(){let e=this.barRenderers[this.barRenderers.length-1];return this.barRenderers.splice(this.barRenderers.length-1,1),this.staveGroup.layout.unregisterBarRenderer(this.staveId,e),e}scaleToWidth(e){this._sharedLayoutData=new Map;let t=(e-this.staveGroup.width)/this.barRenderers.length;for(let e=0,s=this.barRenderers.length;e<s;e++)this.barRenderers[e].scaleToWidth(this.barRenderers[e].width+t)}get topOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){let s=this.barRenderers[t];s.topOverflow>e&&(e=s.topOverflow)}return e}get bottomOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){let s=this.barRenderers[t];s.bottomOverflow>e&&(e=s.bottomOverflow)}return e}finalizeStaff(){let e=0;this.height=0;let t=this.topOverflow,s=this.bottomOverflow;for(let s=0;s<this.barRenderers.length;s++)this.barRenderers[s].x=e,this.barRenderers[s].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[s].height),this.barRenderers[s].finalizeRenderer(),e+=this.barRenderers[s].width;this.height>0&&(this.height+=this.topSpacing+t+s+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 wr{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 _r{constructor(){this._timeSortedSprings=[],this._xMin=0,this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,this.version=0,this.preBeatSizes=new Map,this.onBeatSizes=new Map,this.onBeatCenterX=new Map,this.preBeatSize=0,this.postBeatSize=0,this.voiceSize=0,this.minStretchForce=0,this.totalSpringConstant=0,this.incompleteGraceRods=new Map,this.allGraceRods=new Map,this.springs=new Map,this.height=0}updateVoiceSize(e){e>this.voiceSize&&(this.voiceSize=e,this.version++)}setPreBeatSize(e,t){(!this.preBeatSizes.has(e.index)||this.preBeatSizes.get(e.index)<t)&&(this.preBeatSizes.set(e.index,t),this.version++)}getPreBeatSize(e){return this.preBeatSizes.has(e.index)?this.preBeatSizes.get(e.index):0}setOnBeatSize(e,t){(!this.onBeatSizes.has(e.index)||this.onBeatSizes.get(e.index)<t)&&(this.onBeatSizes.set(e.index,t),this.version++)}getOnBeatSize(e){return this.onBeatSizes.has(e.index)?this.onBeatSizes.get(e.index):0}getBeatCenterX(e){return this.onBeatCenterX.has(e.index)?this.onBeatCenterX.get(e.index):0}setBeatCenterX(e,t){(!this.onBeatCenterX.has(e.index)||this.onBeatCenterX.get(e.index)<t)&&(this.onBeatCenterX.set(e.index,t),this.version++)}updateMinStretchForce(e){this.minStretchForce<e&&(this.minStretchForce=e)}addSpring(e,t,s,i,a){let r;if(this.version++,this.springs.has(e))r=this.springs.get(e),r.postSpringWidth<a&&(r.postSpringWidth=a),r.graceBeatWidth<s&&(r.graceBeatWidth=s),r.preBeatWidth<i&&(r.preBeatWidth=i),t<r.smallestDuration&&(r.smallestDuration=t),t>r.longestDuration&&(r.longestDuration=t),r.allDurations.add(t);else{if(r=new wr,r.timePosition=e,r.allDurations.add(t),this._timeSortedSprings.length>0){let e=this._timeSortedSprings[this._timeSortedSprings.length-1];for(const t of e.allDurations)e.timePosition}r.longestDuration=t,r.postSpringWidth=a,r.graceBeatWidth=s,r.preBeatWidth=i,this.springs.set(e,r);let n=this._timeSortedSprings,o=n.length-1;for(;o>0&&n[o].timePosition>e;)o--;this._timeSortedSprings.splice(o+1,0,r)}return(-1===this._minTime||this._minTime>e)&&(this._minTime=e),r}addBeatSpring(e,t,s){let i=e.absoluteDisplayStart;if(e.graceType!==g.None){const a=e.graceGroup.id;this.allGraceRods.has(a)||this.allGraceRods.set(a,new Array(e.graceGroup.beats.length)),e.graceGroup.isComplete||this.incompleteGraceRods.has(a)||this.incompleteGraceRods.set(a,new Array(e.graceGroup.beats.length));let r=this.allGraceRods.get(a)[e.graceIndex];if(r)r.postSpringWidth<s&&(r.postSpringWidth=s),r.preBeatWidth<t&&(r.preBeatWidth=t);else{const r=new wr;r.timePosition=i,r.postSpringWidth=s,r.preBeatWidth=t,e.graceGroup.isComplete||(this.incompleteGraceRods.get(a)[e.graceIndex]=r),this.allGraceRods.get(a)[e.graceIndex]=r}}else{let a=0;if(e.graceGroup&&this.allGraceRods.has(e.graceGroup.id))for(const t of this.allGraceRods.get(e.graceGroup.id))a+=t.springWidth;this.addSpring(i,e.displayDuration,a,t,s)}}finish(){for(const[e,t]of this.allGraceRods){let s=0;if(this.incompleteGraceRods.has(e))for(const e of t)s+=e.preBeatWidth,e.graceBeatWidth=s,s+=e.postSpringWidth;else for(let e=t.length-1;e>=0;e--)t[e].graceBeatWidth=s,s-=t[e].preBeatWidth+t[e].postSpringWidth}this._incompleteGraceRodsWidth=0;for(const e of this.incompleteGraceRods.values())for(const t of e)this._incompleteGraceRodsWidth+=t.preBeatWidth+t.postSpringWidth;this.calculateSpringConstants(),this.version++}calculateSpringConstants(){this._xMin=0;let e=this.springs;for(const t of e.values())t.springWidth<this._xMin&&(this._xMin=t.springWidth);let t=0,s=this._timeSortedSprings;if(0===s.length)return this.totalSpringConstant=-1,void(this.minStretchForce=-1);for(let e=0;e<s.length;e++){let i=s[e],a=0;if(e===s.length-1)a=i.longestDuration;else{let t=s[e+1];a=Math.abs(t.timePosition-i.timePosition)}i.springConstant=this.calculateSpringConstant(i,a),t+=1/i.springConstant}this.totalSpringConstant=1/t,this.minStretchForce=0;for(let e=0;e<s.length;e++){let t=s[e],i=0;if(e===s.length-1)i=t.postSpringWidth;else{let a=s[e+1];i=t.postSpringWidth+a.preSpringWidth}0===e&&(i+=t.preSpringWidth);let a=i*t.springConstant;this.updateMinStretchForce(a)}}paint(e,t,s){}calculateSpringConstant(e,t){return t<=0&&(t=ye.toTicks(u.SixtyFourth)),0===e.smallestDuration&&(e.smallestDuration=t),e.smallestDuration/t*(1/((1+.85*Math.log2(t/_r.MinDuration))*_r.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(ke.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}}_r.MinDuration=30,_r.MinDurationWidth=7;class Br{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.renderers=[]}}class Tr{constructor(e,t){this.staves=[],this.stavesRelevantForBoundsLookup=[],this.firstStaffInAccolade=null,this.lastStaffInAccolade=null,this.staveGroup=e,this.track=t}addStaff(e){this.staves.push(e),e.isRelevantForBoundsLookup&&this.stavesRelevantForBoundsLookup.push(e)}}class kr{constructor(){this._allStaves=[],this._firstStaffInAccolade=null,this._lastStaffInAccolade=null,this._accoladeSpacingCalculated=!1,this.x=0,this.y=0,this.index=0,this.accoladeSpacing=0,this.isFull=!1,this.width=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[]}get firstBarIndex(){return this.masterBarsRenderers[0].masterBar.index}get lastBarIndex(){return this.masterBarsRenderers[this.masterBarsRenderers.length-1].masterBar.index}addMasterBarRenderers(e,t){if(0===e.length)return null;this.masterBarsRenderers.push(t),this.calculateAccoladeSpacing(e),t.layoutingInfo.preBeatSize=0;let s=0;for(let e=0,i=this.staves.length;e<i;e++){let i=this.staves[e];for(let e=0,a=i.staves.length;e<a;e++){let a=i.staves[e],r=t.renderers[s++];a.addBarRenderer(r)}}return this.updateWidth(),t}addBars(e,t){if(0===e.length)return null;let s=new Br;s.layoutingInfo=new _r,s.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(s),this.calculateAccoladeSpacing(e);let i=s.layoutingInfo;for(let e of this.staves)for(let a of e.staves){let r=e.track.staves[a.modelStaff.index].bars[t];a.addBar(r,i);let n=a.barRenderers[a.barRenderers.length-1];s.renderers.push(n),n.isLinkedToPrevious&&(s.isLinkedToPrevious=!0),n.canWrap||(s.canWrap=!1)}return i.finish(),s.width=this.updateWidth(),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;for(let e=0,s=this._allStaves.length;e<s;e++){let s=this._allStaves[e].revertLastBar();t=Math.max(t,s.width)}return this.width-=t,e}return null}updateWidth(){let e=0;for(let t=0,s=this._allStaves.length;t<s;t++){let s=this._allStaves[t];s.barRenderers[s.barRenderers.length-1].applyLayoutingInfo(),s.barRenderers[s.barRenderers.length-1].width>e&&(e=s.barRenderers[s.barRenderers.length-1].width)}return this.width+=e,e}calculateAccoladeSpacing(e){if(!this._accoladeSpacingCalculated&&0===this.index)if(this._accoladeSpacingCalculated=!0,this.layout.renderer.settings.notation.isNotationElementVisible(k.TrackNames)){let t=this.layout.renderer.canvas,s=this.layout.renderer.settings.display.resources.effectFont;t.font=s;for(let s of e)this.accoladeSpacing=Math.ceil(Math.max(this.accoladeSpacing,t.measureText(s.shortName)));this.accoladeSpacing*=this.layout.scale,this.accoladeSpacing+=2*kr.AccoladeLabelSpacing*this.layout.scale,this.width+=this.accoladeSpacing}else this.accoladeSpacing=0}getStaveTrackGroup(e){for(let t=0,s=this.staves.length;t<s;t++){let s=this.staves[t];if(s.track===e)return s}return null}addStaff(e,t){let s=this.getStaveTrackGroup(e);s||(s=new Tr(this,e),this.staves.push(s)),t.staveTrackGroup=s,t.staveGroup=this,t.index=this._allStaves.length,this._allStaves.push(t),s.addStaff(t),t.isInAccolade&&(this._firstStaffInAccolade||(this._firstStaffInAccolade=t,t.isFirstInAccolade=!0),s.firstStaffInAccolade||(s.firstStaffInAccolade=t),this._lastStaffInAccolade||(this._lastStaffInAccolade=t,t.isLastInAccolade=!0),this._lastStaffInAccolade&&(this._lastStaffInAccolade.isLastInAccolade=!1),this._lastStaffInAccolade=t,this._lastStaffInAccolade.isLastInAccolade=!0,s.lastStaffInAccolade=t)}get height(){return this._allStaves[this._allStaves.length-1].y+this._allStaves[this._allStaves.length-1].height}scaleToWidth(e){for(let t=0,s=this._allStaves.length;t<s;t++)this._allStaves[t].scaleToWidth(e);this.width=e}paint(e,t,s){this.paintPartial(e+this.x,t+this.y,s,0,this.masterBarsRenderers.length)}paintPartial(e,t,s,i,a){for(let r=0,n=this._allStaves.length;r<n;r++)this._allStaves[r].paint(e,t,s,i,a);let r=this.layout.renderer.settings.display.resources;if(this.staves.length>0&&0===i){if(s.color=r.barSeparatorColor,this._firstStaffInAccolade&&this._lastStaffInAccolade){let i=t+this._firstStaffInAccolade.y+this._firstStaffInAccolade.staveTop+this._firstStaffInAccolade.topSpacing+this._firstStaffInAccolade.topOverflow,a=t+this._lastStaffInAccolade.y+this._lastStaffInAccolade.topSpacing+this._lastStaffInAccolade.topOverflow+this._lastStaffInAccolade.staveBottom,r=e+this._firstStaffInAccolade.x;s.beginPath(),s.moveTo(r,i),s.lineTo(r,a),s.stroke()}s.font=r.effectFont;for(let i=0,a=this.staves.length;i<a;i++){let a=this.staves[i];if(a.firstStaffInAccolade&&a.lastStaffInAccolade){let i=t+a.firstStaffInAccolade.y+a.firstStaffInAccolade.staveTop+a.firstStaffInAccolade.topSpacing+a.firstStaffInAccolade.topOverflow,r=t+a.lastStaffInAccolade.y+a.lastStaffInAccolade.topSpacing+a.lastStaffInAccolade.topOverflow+a.lastStaffInAccolade.staveBottom,n=e+a.firstStaffInAccolade.x,o=3*this.layout.renderer.settings.display.scale,h=o,l=i-4*o,c=r+4*o;0===this.index&&this.layout.renderer.settings.notation.isNotationElementVisible(k.TrackNames)&&s.fillText(a.track.shortName,e+kr.AccoladeLabelSpacing*this.layout.scale,i),s.fillRect(n-h-o,l,o,c-l);let d=n-h-o,u=n+2*o;s.beginPath(),s.moveTo(d,l),s.bezierCurveTo(d,l,d,l,u,l-o),s.bezierCurveTo(n,l+o,d,l+o,d,l+o),s.closePath(),s.fill(),s.beginPath(),s.moveTo(d,c),s.bezierCurveTo(d,c,n,c,u,c+o),s.bezierCurveTo(n,c-o,d,c-o,d,c-o),s.closePath(),s.fill()}}}}finalizeGroup(){let e=0;for(let t of this._allStaves)t.x=this.accoladeSpacing,t.y=e,t.finalizeStaff(),e+=t.height}buildBoundingsLookup(e,t){if(this.layout.renderer.boundsLookup.isFinished)return;if(!this._firstStaffInAccolade||!this._lastStaffInAccolade)return;let s=this._allStaves[this._allStaves.length-1],i=t+this.y+this._firstStaffInAccolade.y,a=t+this.y+this._lastStaffInAccolade.y+this._lastStaffInAccolade.height,r=t+this.y+this._allStaves[0].y,n=t+this.y+s.y+s.height,o=t+this.y+this._firstStaffInAccolade.y+this._firstStaffInAccolade.topSpacing+this._firstStaffInAccolade.topOverflow+(this._firstStaffInAccolade.barRenderers.length>0?this._firstStaffInAccolade.barRenderers[0].topPadding:0),h=a-i,l=t+this.y+s.y+s.height-s.bottomSpacing-s.bottomOverflow-(s.barRenderers.length>0?s.barRenderers[0].bottomPadding:0)-o,c=n-r,d=this.x+this._firstStaffInAccolade.x,u=new fi;u.visualBounds=new at,u.visualBounds.x=e,u.visualBounds.y=t+this.y,u.visualBounds.w=this.width,u.visualBounds.h=this.height,u.realBounds=new at,u.realBounds.x=e,u.realBounds.y=t+this.y,u.realBounds.w=this.width,u.realBounds.h=this.height,this.layout.renderer.boundsLookup.addStaveGroup(u);let p=new Map;for(let e=0;e<this.staves.length;e++)for(let s of this.staves[e].stavesRelevantForBoundsLookup)for(let e of s.barRenderers){let a;p.has(e.bar.masterBar.index)?a=p.get(e.bar.masterBar.index):(a=new pi,a.index=e.bar.masterBar.index,a.isFirstOfLine=e.isFirstOfLine,a.realBounds=new at,a.realBounds.x=d+e.x,a.realBounds.y=r,a.realBounds.w=e.width,a.realBounds.h=c,a.visualBounds=new at,a.visualBounds.x=d+e.x,a.visualBounds.y=i,a.visualBounds.w=e.width,a.visualBounds.h=h,a.lineAlignedBounds=new at,a.lineAlignedBounds.x=d+e.x,a.lineAlignedBounds.y=o,a.lineAlignedBounds.w=e.width,a.lineAlignedBounds.h=l,this.layout.renderer.boundsLookup.addMasterBar(a),p.set(a.index,a)),e.buildBoundingsLookup(a,d,t+this.y+s.y)}}getBarX(e){if(!this._firstStaffInAccolade||0===this.layout.renderer.tracks.length)return 0;let t=this.layout.renderer.tracks[0].staves[0].bars[e];return this.layout.getRendererForBar(this._firstStaffInAccolade.staveId,t).x}}kr.AccoladeLabelSpacing=10;class vr extends aa{constructor(e,t,s,i){super(e,t),this._tuning=s,this._trackLabel=i,this.glyphs=[]}doLayout(){if(!(this.glyphs.length>0)){this.createGlyphs(this._tuning);for(const e of this.glyphs)e.renderer=this.renderer,e.doLayout()}}createGlyphs(e){const t=this.renderer.scale,s=this.renderer.resources;this.height=0;const i=15*t;this._trackLabel.length>0&&(this.addGlyph(new Pa(0,this.height,this._trackLabel,s.effectFont,P.Left)),this.height+=i),this.addGlyph(new Pa(0,this.height,e.name,s.effectFont,P.Left));const a=64*t;if(this.renderer.scoreRenderer.canvas.font=s.effectFont,this.width=Math.max(this.renderer.scoreRenderer.canvas.measureText(this._trackLabel)*t,Math.max(this.renderer.scoreRenderer.canvas.measureText(e.name)*t,2*a)),this.height+=i,!e.isStandard){const r=.7,n=vr.CircleNumberHeight*r*t;let o=0|Math.ceil(e.tunings.length/2),h=0,l=this.height;for(let c=0,d=e.tunings.length;c<d;c++){const d=N.GuitarString0+(c+1);this.addGlyph(new Li(h,l+n/1.2,r,d));const u="= "+Ye.getTextForTuning(e.tunings[c],!1);this.addGlyph(new Pa(h+n+1*t,l,u,s.effectFont,P.Left)),l+=i,c===o-1&&(l=this.height,h+=a)}this.height+=o*i}this.width+=15*t}}vr.CircleNumberHeight=20;class xr extends yr{constructor(e,t){super(e,t,P.Left)}addTuning(e,t){if(e.tunings.length>0){let s=new vr(0,0,e,t);s.renderer=this.renderer,s.doLayout(),this.glyphs.push(s)}}}class Nr{constructor(e,t){this.args=e,this.renderCallback=t}}class Pr{constructor(e){this._barRendererLookup=new Map,this.width=0,this.height=0,this.scoreInfoGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t)),this.firstBarIndex=t;let s=this.renderer.settings.display.barCount;s<0&&(s=e.masterBars.length),s=t+s-1,s=Math.min(e.masterBars.length-1,Math.max(0,s)),this.lastBarIndex=s,this.createScoreInfoGlyphs(),this.doLayoutAndRender()}registerPartial(e,t){this.renderer.partialLayoutFinished.trigger(e),this.renderer.settings.core.enableLazyLoading?this._lazyPartials.set(e.id,new Nr(e,t)):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(){Be.debug("ScoreLayout","Creating score info glyphs");let e=this.renderer.settings.notation,t=this.renderer.score,s=this.renderer.settings.display.resources;this.scoreInfoGlyphs=new Map,t.title&&e.isNotationElementVisible(k.ScoreTitle)&&this.scoreInfoGlyphs.set(k.ScoreTitle,new Pa(0,0,t.title,s.titleFont,P.Center)),t.subTitle&&e.isNotationElementVisible(k.ScoreSubTitle)&&this.scoreInfoGlyphs.set(k.ScoreSubTitle,new Pa(0,0,t.subTitle,s.subTitleFont,P.Center)),t.artist&&e.isNotationElementVisible(k.ScoreArtist)&&this.scoreInfoGlyphs.set(k.ScoreArtist,new Pa(0,0,t.artist,s.subTitleFont,P.Center)),t.album&&e.isNotationElementVisible(k.ScoreAlbum)&&this.scoreInfoGlyphs.set(k.ScoreAlbum,new Pa(0,0,t.album,s.subTitleFont,P.Center)),t.music&&t.music===t.words&&e.isNotationElementVisible(k.ScoreWordsAndMusic)?this.scoreInfoGlyphs.set(k.ScoreWordsAndMusic,new Pa(0,0,"Music and Words by "+t.words,s.wordsFont,P.Center)):(t.music&&e.isNotationElementVisible(k.ScoreMusic)&&this.scoreInfoGlyphs.set(k.ScoreMusic,new Pa(0,0,"Music by "+t.music,s.wordsFont,P.Right)),t.words&&e.isNotationElementVisible(k.ScoreWords)&&this.scoreInfoGlyphs.set(k.ScoreWords,new Pa(0,0,"Words by "+t.words,s.wordsFont,P.Left)));const i=new ma(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);if(e.isNotationElementVisible(k.GuitarTuning)){let e=[];for(let t of this.renderer.tracks)for(let s of t.staves)if(!s.isPercussion&&s.isStringed&&s.tuning.length>0&&s.showTablature){e.push(s);break}if(e.length>0){this.tuningGlyph=new xr(0,0),this.tuningGlyph.renderer=i;for(const t of e)this.tuningGlyph.addTuning(t.stringTuning,e.length>1?t.track.name:"")}}if(e.isNotationElementVisible(k.ChordDiagrams)){this.chordDiagrams=new br(0,0),this.chordDiagrams.renderer=i;let e=new Map;for(let t of this.renderer.tracks)for(let s of t.staves){const t=s.chords;if(t)for(const[s,i]of t)e.has(s)||i.showDiagram&&(e.set(s,i),this.chordDiagrams.addChord(i))}}}get scale(){return this.renderer.settings.display.scale}createEmptyStaveGroup(){let e=new kr;e.layout=this;for(let s=0;s<this.renderer.tracks.length;s++){let i=this.renderer.tracks[s],a=!1;for(let e of i.staves)if(e.showStandardNotation){a=!0;break}for(let r=0;r<i.staves.length;r++){let n,o=i.staves[r];if(o.isPercussion)n=t.Score;else if(this.renderer.settings.display.staveProfile!==t.Default)n=this.renderer.settings.display.staveProfile;else if(o.showTablature&&o.showStandardNotation)n=t.ScoreTab;else if(o.showTablature)n=a?t.TabMixed:t.Tab;else{if(!o.showStandardNotation)continue;n=t.Score}let h=ho.staveProfiles.get(n);for(let t of h)t.canCreate(i,o)&&e.addStaff(i,new Sr(s,o,t))}}return e}registerBarRenderer(e,t){this._barRendererLookup.has(e)||this._barRendererLookup.set(e,new Map),this._barRendererLookup.get(e).set(t.bar.id,t)}unregisterBarRenderer(e,t){if(this._barRendererLookup.has(e)){this._barRendererLookup.get(e).delete(t.bar.id)}}getRendererForBar(e,t){let s=t.id;return this._barRendererLookup.has(e)&&this._barRendererLookup.get(e).has(s)?this._barRendererLookup.get(e).get(s):null}layoutAndRenderAnnotation(e){let t="rendered by alphaTab",s=this.renderer.settings.display.resources,i=12*this.renderer.settings.display.scale,a=Math.floor(2*i);const r=new ci,n=new vs(s.copyrightFont.family,i,$.Plain,Z.Bold);this.renderer.canvas.font=n;const o=ho.getLayoutEngineFactory(this.renderer.settings.display.layoutMode).vertical;return r.width=this.renderer.canvas.measureText(t),r.height=a,r.x=o?(this.width-r.width)/2:this.firstBarX,r.y=e,r.totalWidth=this.width,r.totalHeight=e+a,r.firstMasterBarIndex=-1,r.lastMasterBarIndex=-1,this.registerPartial(r,(e=>{e.color=s.mainGlyphColor,e.font=n,e.textAlign=P.Left,e.fillText(t,0,i)})),e+a}}class Er{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class Cr extends Pr{constructor(e){super(e),this._group=null,this._pagePadding=null}get name(){return"HorizontalScreen"}get supportsResize(){return!1}get firstBarX(){let e=this._pagePadding[0];return this._group&&(e+=this._group.accoladeSpacing),e}doResize(){}doLayoutAndRender(){this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=Cr.PagePadding),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t));let s=t,i=this.renderer.settings.display.barCount;i<=0&&(i=e.masterBars.length),i=t+i-1,i=Math.min(e.masterBars.length-1,Math.max(0,i)),this._group=this.createEmptyStaveGroup(),this._group.isLast=!0,this._group.x=this._pagePadding[0],this._group.y=this._pagePadding[1];let a=this.renderer.settings.display.barCountPerPartial,r=[],n=new Er,o=0;for(;s<=i;){let t=this._group.addBars(this.renderer.tracks,s);if(t)if(0===n.masterBars.length&&t.isLinkedToPrevious&&r.length>0){let i=r[r.length-1];i.masterBars.push(e.masterBars[s]),i.width+=t.width,o+=t.width,n.x+=o}else n.masterBars.push(e.masterBars[s]),n.width+=t.width,n.masterBars.length>=a&&(0===r.length&&(n.width+=this._group.accoladeSpacing+this._pagePadding[0]),o+=n.width,r.push(n),Be.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null),n=new Er,n.x=o);s++}n.masterBars.length>0&&(0===r.length&&(n.width+=this._group.accoladeSpacing+this._pagePadding[0]),r.push(n),Be.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null)),this._group.finalizeGroup(),this.height=Math.floor(this._group.y+this._group.height),this.width=this._group.x+this._group.width+this._pagePadding[2],s=0;let h=0;for(let e=0;e<r.length;e++){const t=r[e],i=new ci;i.x=h,i.y=0,i.totalWidth=this.width,i.totalHeight=this.height,i.width=t.width,i.height=this.height,i.firstMasterBarIndex=t.masterBars[0].index,i.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,h+=t.width;const a=s,n=e;this._group.buildBoundingsLookup(this._group.x,this._group.y),this.registerPartial(i,(e=>{e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=P.Left;let s=this._group.getBarX(t.masterBars[0].index)+this._group.accoladeSpacing;0===n&&(s-=this._group.x+this._group.accoladeSpacing),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=P.Left,Be.debug(this.name,"Rendering partial from bar "+t.masterBars[0].index+" to "+t.masterBars[t.masterBars.length-1].index,null),this._group.paintPartial(-s,this._group.y,e,a,t.masterBars.length)})),s+=t.masterBars.length}this.height=this.layoutAndRenderAnnotation(this.height)+this._pagePadding[3]}}Cr.PagePadding=[20,20,20,20],Cr.GroupSpacing=20;class Fr extends Pr{constructor(e){super(e),this._groups=[],this._allMasterBarRenderers=[],this._barsFromPreviousGroup=[],this._pagePadding=null}get name(){return"PageView"}doLayoutAndRender(){this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=Fr.PagePadding),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let e=0;this.width=this.renderer.width,this._allMasterBarRenderers=[],e=this.layoutAndRenderScoreInfo(e,-1),e=this.layoutAndRenderTunings(e,-1),e=this.layoutAndRenderChordDiagrams(e,-1),e=this.layoutAndRenderScore(e),e=this.layoutAndRenderAnnotation(e),this.height=e+this._pagePadding[3]}get supportsResize(){return!0}get firstBarX(){let e=this._pagePadding[0];return this._groups.length>0&&(e+=this._groups[0].accoladeSpacing),e}doResize(){let e=0;this.width=this.renderer.width;let t=this.height;e=this.layoutAndRenderScoreInfo(e,t),e=this.layoutAndRenderTunings(e,t),e=this.layoutAndRenderChordDiagrams(e,t),e=this.resizeAndRenderScore(e,t),e=this.layoutAndRenderAnnotation(e),this.height=e+this._pagePadding[3]}layoutAndRenderTunings(e,t=-1){if(!this.tuningGlyph)return e;let s=this.renderer.settings.display.resources;this.tuningGlyph.x=this._pagePadding[0],this.tuningGlyph.width=this.width,this.tuningGlyph.doLayout();let i=this.tuningGlyph.height+11*this.scale;const a=new ci;return a.x=0,a.y=e,a.width=this.width,a.height=i,a.totalWidth=this.width,a.totalHeight=t<0?e+a.height:t,a.firstMasterBarIndex=-1,a.lastMasterBarIndex=-1,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=P.Center,this.tuningGlyph.paint(0,0,e)})),e+i}layoutAndRenderChordDiagrams(e,t=-1){if(!this.chordDiagrams)return e;const s=this.renderer.settings.display.resources;this.chordDiagrams.width=this.width,this.chordDiagrams.doLayout();const i=Math.floor(this.chordDiagrams.height),a=new ci;return a.x=0,a.y=e,a.width=this.width,a.height=i,a.totalWidth=this.width,a.totalHeight=t<0?e+i:t,a.firstMasterBarIndex=-1,a.lastMasterBarIndex=-1,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=P.Center,this.chordDiagrams.paint(0,0,e)})),e+i}layoutAndRenderScoreInfo(e,t=-1){Be.debug(this.name,"Layouting score info");const s=new ci;s.x=0,s.y=e;let i=this._pagePadding[1],a=this.scale,r=this.renderer.settings.display.resources,n=[k.ScoreTitle,k.ScoreSubTitle,k.ScoreArtist,k.ScoreAlbum,k.ScoreWordsAndMusic];for(let e=0;e<n.length;e++)if(this.scoreInfoGlyphs.has(n[e])){let t=this.scoreInfoGlyphs.get(n[e]);t.x=this.width/2,t.y=i,t.textAlign=P.Center,i+=t.font.size*a}let o=!1,h=0;if(this.scoreInfoGlyphs.has(k.ScoreMusic)){let e=this.scoreInfoGlyphs.get(k.ScoreMusic);e.x=this.width-this._pagePadding[2],e.y=i,e.textAlign=P.Right,o=!0,h=e.font.size*a}if(this.scoreInfoGlyphs.has(k.ScoreWords)){let e=this.scoreInfoGlyphs.get(k.ScoreWords);e.x=this._pagePadding[0],e.y=i,e.textAlign=P.Left,o=!0,h=e.font.size*a}return o&&(i+=h),i=Math.floor(i+17*this.scale),s.width=this.width,s.height=i,s.totalWidth=this.width,s.totalHeight=t<0?e+s.height:t,s.firstMasterBarIndex=-1,s.lastMasterBarIndex=-1,this.registerPartial(s,(e=>{e.color=r.scoreInfoColor,e.textAlign=P.Center;for(const t of this.scoreInfoGlyphs.values())t.paint(0,0,e)})),e+i}resizeAndRenderScore(e,t){if(-1!==this.renderer.settings.display.barsPerRow)for(let s=0;s<this._groups.length;s++){let i=this._groups[s];this.fitGroup(i),i.finalizeGroup(),e+=this.paintGroup(i,t)}else{this._groups=[];let s=0,i=this.maxWidth,a=this.createEmptyStaveGroup();for(a.index=this._groups.length,a.x=this._pagePadding[0],a.y=e;s<this._allMasterBarRenderers.length;){let r=this._allMasterBarRenderers[s];if(a.width+r.width<=i||0===a.masterBarsRenderers.length)a.addMasterBarRenderers(this.renderer.tracks,r),s++;else{for(;r&&!r.canWrap&&a.masterBarsRenderers.length>1;)r=a.revertLastBar(),s--;a.isFull=!0,a.isLast=this.lastBarIndex===a.lastBarIndex,this._groups.push(a),this.fitGroup(a),a.finalizeGroup(),e+=this.paintGroup(a,t),a=this.createEmptyStaveGroup(),a.index=this._groups.length,a.x=this._pagePadding[0],a.y=e}}a.isLast=this.lastBarIndex===a.lastBarIndex,this.fitGroup(a),a.finalizeGroup(),e+=this.paintGroup(a,t)}return e}layoutAndRenderScore(e){let t=this.firstBarIndex,s=this.lastBarIndex;for(this._groups=[];t<=s;){let i=this.createStaveGroup(t,s);this._groups.push(i),i.x=this._pagePadding[0],i.y=e,t=i.lastBarIndex+1,this.fitGroup(i),i.finalizeGroup(),Be.debug(this.name,"Rendering partial from bar "+i.firstBarIndex+" to "+i.lastBarIndex,null),e+=this.paintGroup(i,e)}return e}paintGroup(e,t){let s=Math.floor(e.height+20*this.scale);const i=new ci;return i.x=0,i.y=e.y,i.totalWidth=this.width,i.totalHeight=t,i.width=this.width,i.height=s,i.firstMasterBarIndex=e.firstBarIndex,i.lastMasterBarIndex=e.lastBarIndex,e.buildBoundingsLookup(0,0),this.registerPartial(i,(t=>{this.renderer.canvas.color=this.renderer.settings.display.resources.mainGlyphColor,this.renderer.canvas.textAlign=P.Left,e.paint(0,-i.y,t)})),t+=s,s}fitGroup(e){(e.isFull||e.width>this.maxWidth)&&e.scaleToWidth(this.maxWidth)}createStaveGroup(e,t){let s=this.createEmptyStaveGroup();s.index=this._groups.length;let i=this.renderer.settings.display.barsPerRow,a=this.maxWidth,r=t+1,n=e;for(;n<r;){if(this._barsFromPreviousGroup.length>0)for(let e of this._barsFromPreviousGroup)s.addMasterBarRenderers(this.renderer.tracks,e),n=e.masterBar.index;else{let e=s.addBars(this.renderer.tracks,n);e&&this._allMasterBarRenderers.push(e)}this._barsFromPreviousGroup=[];let e=!1;if((-1===i&&s.width>=a&&0!==s.masterBarsRenderers.length||s.masterBarsRenderers.length===i+1)&&(e=!0),e){let e=s.revertLastBar();if(e)for(this._barsFromPreviousGroup.push(e);e&&!e.canWrap&&s.masterBarsRenderers.length>1;)e=s.revertLastBar(),e&&this._barsFromPreviousGroup.push(e);return s.isFull=!0,s.isLast=!1,this._barsFromPreviousGroup.reverse(),s}s.x=0,n++}return s.isLast=t===s.lastBarIndex,s}get maxWidth(){return this.renderer.width-this._pagePadding[0]-this._pagePadding[2]}}Fr.PagePadding=[40,40,40,40],Fr.GroupSpacing=20;class Lr extends Li{constructor(e,t,s,i=!1){super(e,t,i?Mi.GraceScale:1,Lr.getMusicSymbol(s)),this._isGrace=i,this._accidentalType=s}static getMusicSymbol(e){switch(e){case re.Natural:return N.AccidentalNatural;case re.Sharp:return N.AccidentalSharp;case re.Flat:return N.AccidentalFlat;case re.NaturalQuarterNoteUp:return N.AccidentalQuarterToneNaturalArrowUp;case re.SharpQuarterNoteUp:return N.AccidentalQuarterToneSharpArrowUp;case re.FlatQuarterNoteUp:return N.AccidentalQuarterToneFlatArrowUp;case re.DoubleSharp:return N.AccidentalDoubleSharp;case re.DoubleFlat:return N.AccidentalDoubleFlat}return N.None}doLayout(){switch(this._accidentalType){case re.DoubleFlat:this.width=18;break;default:this.width=8}this.width=this.width*(this._isGrace?Mi.GraceScale:1)*this.scale}}class Mr extends Ci{constructor(e,t,s){super(e,t),this._number=0,this._number=s}doLayout(){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.barNumberFont,this.width=this.renderer.scoreRenderer.canvas.measureText(this._number.toString())+5*this.scale}paint(e,t,s){if(!this.renderer.staff.isFirstInAccolade)return;let i=this.renderer.resources,a=s.color;s.color=i.barNumberColor,s.font=i.barNumberFont,s.fillText(this._number.toString(),e+this.x,t+this.y),s.color=a}}class Ir extends Ci{constructor(e,t){super(e,t)}doLayout(){this.renderer.isLast?this.width=15*this.scale:this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart?this.width=2*this.scale:(this.width=2*this.scale,this.renderer.bar.masterBar.isDoubleBar&&(this.width+=2*this.scale))}paint(e,t,s){let i=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x,o=r-a;this.renderer.isLast?(s.fillRect(n+this.width-i-i,a,this.scale,o),s.fillRect(n+this.width-i,a,i,o)):this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart||(s.fillRect(n+this.width-this.scale,a,this.scale,o),this.renderer.bar.masterBar.isDoubleBar&&s.fillRect(n+this.width-5*this.scale,a,this.scale,o))}}class Dr extends Li{constructor(e,t,s,i){super(e,t,1,Dr.getSymbol(s)),this._clef=s,this._clefOttava=i}doLayout(){switch(this._clef){case r.Neutral:this.width=15*this.scale;break;case r.C3:case r.C4:case r.F4:case r.G2:this.width=28*this.scale}}static getSymbol(e){switch(e){case r.Neutral:return N.UnpitchedPercussionClef1;case r.C3:case r.C4:return N.CClef;case r.F4:return N.FClef;case r.G2:return N.GClef;default:return N.None}}paint(e,t,s){let i;super.paint(e,t,s);let a=!1;switch(this._clefOttava){case n._15ma:i=new Li(-4*this.scale,0,.5,N.Quindicesima),a=!0;break;case n._8va:i=new Li(-2*this.scale,0,.5,N.Ottava),a=!0;break;case n._8vb:i=new Li(-6*this.scale,0,.5,N.Ottava);break;case n._15mb:i=new Li(-8*this.scale,0,.5,N.Quindicesima);break;default:return}let o=0,h=0;switch(this._clef){case r.Neutral:o=a?-12:15,h=0;break;case r.C3:case r.C4:o=a?-19:27,h=0;break;case r.F4:o=a?-9:27,h=-4;break;case r.G2:o=a?-37:30,h=0;break;default:return}i.renderer=this.renderer,i.doLayout();let l=this.width/2;i.paint(e+this.x+l+h*this.scale,t+this.y+o*this.scale,s)}}class Rr extends Ci{constructor(e,t){super(e,t)}doLayout(){this.width=11*this.scale}paint(e,t,s){let i=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x,o=r-a,h=1.5*this.scale,l=(a+r)/2;s.fillCircle(n,l-3*h,h),s.fillCircle(n,l+3*h,h),n+=4*this.scale,s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke(),n+=3*this.scale+.5,s.fillRect(n,a,i,o)}}class Ar extends Ci{constructor(e,t,s){super(e,t),this._count=0,this._count=0,this._count=s}doLayout(){this.width=0}paint(e,t,s){let i=this.renderer.resources,a=s.textAlign;s.font=i.barNumberFont,s.textAlign=P.Right;let r="x"+this._count,n=s.measureText(r)/1.5;s.fillText(r,e+this.x-n,t+this.y),s.textAlign=a}}class Or extends Ci{constructor(e,t,s,i){super(e,t),this._dotOffset=0,this._circleSize=0,this._dotOffset=0,this._circleSize=0,this._dotOffset=i,this._circleSize=s}doLayout(){this.width=13*this.scale}paint(e,t,s){let i=4*this.scale,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding,n=e+this.x+.5,o=r-a;s.fillRect(n,a,i,o),n+=2*i-.5,s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke(),n+=3*this.scale;let h=this._circleSize*this.scale,l=(a+r)/2;s.fillCircle(n,l-h*this._dotOffset,h),s.fillCircle(n,l+h*this._dotOffset,h)}}class Gr extends Li{constructor(e,t,s){super(e,t,1,Gr.getSymbol(s))}static getSymbol(e){switch(e){case i.None:return N.None;case i.Normal:return N.ArticAccentAbove;case i.Heavy:return N.ArticMarcatoAbove;default:return N.None}}doLayout(){this.width=9*this.scale,this.height=9*this.scale}paint(e,t,s){super.paint(e-2*this.scale,t+this.height,s)}}class Vr extends Ci{constructor(e,t,s){super(e,t),this._size=0,this._size=s}doLayout(){this.width=this._size+3*this.scale}paint(e,t,s){s.fillCircle(e+this.x,t+this.y,this._size)}}class Hr extends Li{constructor(e,t,s){super(e,t,s?Mi.GraceScale:1,N.NoteheadXOrnate),this._isGrace=s}doLayout(){this.width=9*(this._isGrace?Mi.GraceScale:1)*this.scale,this.height=Mi.NoteHeadHeight*this.scale}}class Wr extends Li{constructor(e,t,s,i){super(e,t,i?Mi.GraceScale:1,Wr.getSymbol(s)),this._isGrace=i}static getSymbol(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:case u.Whole:case u.Half:return N.NoteheadDiamondWhiteWide;default:return N.NoteheadDiamondBlackWide}}doLayout(){this.width=9*(this._isGrace?Mi.GraceScale:1)*this.scale,this.height=Mi.NoteHeadHeight*this.scale}}class zr extends Ci{constructor(e,t,s){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=H.Up,this.startBeat=e,this.endBeat=t,this.forEnd=s}doLayout(){this.width=0}paint(e,t,s){if(!this.endBeat)return;let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar);this.startNoteRenderer=i;let a=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.endBeat.voice.bar);this.endNoteRenderer=a;let r=0,n=0,o=0,h=0,l=!1;this.tieDirection=i?this.getBeamDirection(this.startBeat,i):this.getBeamDirection(this.endBeat,a),!this.forEnd&&i?(i!==a?(r=e+i.x+this.getStartX(),o=t+i.y+this.getStartY()+this.yOffset,a&&i.staff===a.staff?(n=e+a.x+this.getEndX(),h=t+a.y+this.getEndY()+this.yOffset):(n=e+i.x+i.width,h=o)):(r=e+i.x+this.getStartX(),n=e+a.x+this.getEndX(),o=t+i.y+this.getStartY()+this.yOffset,h=t+a.y+this.getEndY()+this.yOffset),l=!0):i&&i.staff===a.staff||(r=e+a.x,n=e+a.x+this.getEndX(),o=t+a.y+this.getEndY()+this.yOffset,h=o,l=!0),l&&(this.shouldDrawBendSlur()?zr.drawBendSlur(s,r,o,n,h,this.tieDirection===H.Down,this.scale):zr.paintTie(s,this.scale,r,o,n,h,this.tieDirection===H.Down,this.getTieHeight(r,o,n,h),4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,s,i){return 22}getBeamDirection(e,t){return H.Down}getStartY(){return 0}getEndY(){return 0}getStartX(){return 0}getEndX(){return 0}static paintTie(e,t,s,i,a,r,n=!1,o=22,h=4){if(s===a&&i===r)return;if(a<s){let e=s;s=a,a=e,e=i,i=r,r=e}o*=t,h*=t;let l=r-i,c=a-s,d=Math.sqrt(l*l+c*c);n?l*=-1:c*=-1,l/=d,c/=d;let u=(a+s)/2,p=(r+i)/2,g=u+o*l,f=p+o*c,m=u+(o-h)*l,y=p+(o-h)*c;e.beginPath(),e.moveTo(s,i),e.quadraticCurveTo(g,f,a,r),e.quadraticCurveTo(m,y,s,i),e.closePath(),e.fill()}static drawBendSlur(e,t,s,i,a,r,n,o){let h=a-s,l=i-t,c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;let d=(i+t)/2,u=(a+s)/2,p=zr.BendSlurHeight*n;i-t<20&&(p/=2);let g=d+p*h,f=u+p*l;if(e.beginPath(),e.moveTo(t,s),e.lineTo(g,f),e.lineTo(i,a),e.stroke(),o){let t=e.measureText(o),s=r?0:-e.font.size;e.fillText(o,g-t/2,f+s)}}}zr.BendSlurHeight=11;class Ur extends Ci{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=Ur.Size*this.scale}paint(e,t,s){this._isOpen?zr.paintTie(s,this.scale,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):zr.paintTie(s,this.scale,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3)}}Ur.Size=6;class Xr{constructor(e,t){this.line=0,this.line=e,this.isGhost=t}}class Yr extends Ci{constructor(e){super(0,0),this._infos=[],this._glyphs=[],this.isEmpty=!0,this._isOpen=e}addParenthesis(e){let t=this.renderer,s=t.getNoteLine(e),i=e.isGhost||this.isTiedBend(e)&&t.settings.notation.isNotationElementVisible(k.ParenthesisOnTiedBends);this.addParenthesisOnLine(s,i)}addParenthesisOnLine(e,t){let s=new Xr(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 Ur(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 qr{constructor(e,t){this.line=0,this.glyph=e,this.line=t}}class Jr extends Ci{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new fs,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){let s=new qr(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===H.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===H.Down?-e:0,r+=this._noteHeadPadding,this.upLineX=r,this.downLineX=0),this.displacedX=e,this.width=r}paint(e,t,s){e+=this.x,t+=this.y;let i=this.renderer,a=3*this.scale,r=this.width-this.noteStartX+2*a;if(this.hasTopOverflow){let n=s.color;s.color=i.resources.staffLineColor;let o=-2;for(;o>=this.minNote.line;){let n=t+i.getScoreY(o);s.fillRect(e-a+this.noteStartX,n,r,this.scale),o-=2}s.color=n}if(this.hasBottomOverflow){let n=s.color;s.color=i.resources.staffLineColor;let o=10;for(;o<=this.maxNote.line;){let n=t+i.getScoreY(o);s.fillRect(e-a+this.noteStartX,n,r,this.scale),o+=2}s.color=n}let n=this._infos,o=e+this._noteHeadPadding;for(let e of n)e.glyph.renderer=this.renderer,e.glyph.paint(o,t,s)}}class Qr extends Li{constructor(e,t,s){super(e,t,1,Qr.getSymbol(s))}doLayout(){this.width=12*this.scale}static getSymbol(e){switch(e){case u.ThirtySecond:return N.Tremolo3;case u.Sixteenth:return N.Tremolo2;case u.Eighth:return N.Tremolo1;default:return N.None}}}class jr extends Jr{constructor(){super(),this._noteGlyphLookup=new Map,this._notes=[],this._tremoloPicking=null,this.aboveBeatEffects=new Map,this.belowBeatEffects=new Map}get direction(){return this.beamingHelper.direction}getNoteX(e,t){if(this._noteGlyphLookup.has(e.id)){let s=this._noteGlyphLookup.get(e.id),i=this.x+s.x+this._noteHeadPadding;switch(t){case oe.Left:break;case oe.Center:i+=s.width/2;break;case oe.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 ne.TopWithStem:i-=this.renderer.getStemSize(this.beamingHelper);break;case ne.Top:i-=s.height/2;break;case ne.Center:break;case ne.Bottom:i+=s.height/2;break;case ne.BottomWithStem:i+=this.renderer.getStemSize(this.beamingHelper)}return i}return 0}addNoteGlyph(e,t,s){super.add(e,s),this._noteGlyphLookup.set(t.id,e),this._notes.push(t)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.upLineX,e+this.x+this.downLineX)}doLayout(){super.doLayout();let e=this.direction;for(const e of this.aboveBeatEffects.values())e.renderer=this.renderer,e.doLayout();for(const e of this.belowBeatEffects.values())e.renderer=this.renderer,e.doLayout();if(this.beat.isTremolo){let t=0,s=e===H.Up?this.minNote:this.maxNote,i=e===H.Up?this.displacedX:0,a=this.beat.tremoloSpeed;switch(a){case u.ThirtySecond:t=e===H.Up?-15:15;break;case u.Sixteenth:t=e===H.Up?-12:15;break;case u.Eighth:t=e===H.Up?-10:10;break;default:t=e===H.Up?-10:15}this._tremoloPicking=new Qr(i,s.glyph.y+t*this.scale,a),this._tremoloPicking.renderer=this.renderer,this._tremoloPicking.doLayout()}}buildBoundingsLookup(e,t,s){for(let i of this._notes)if(this._noteGlyphLookup.has(i.id)){let a=this._noteGlyphLookup.get(i.id),r=new gi;r.note=i,r.noteHeadBounds=new at,r.noteHeadBounds.x=t+this.x+this._noteHeadPadding+a.x,r.noteHeadBounds.y=s+this.y+a.y-a.height/2,r.noteHeadBounds.w=a.width,r.noteHeadBounds.h=a.height,e.addNote(r)}}paint(e,t,s){let i=this.renderer,a=0,r=0,n=1,o=-n;this.beamingHelper.direction===H.Up?(r=i.getScoreY(this.minNote.line),a=i.getScoreY(this.maxNote.line-2)):(r=i.getScoreY(this.maxNote.line-1),a=i.getScoreY(this.minNote.line+1),o*=-1,n*=-1);for(const i of this.aboveBeatEffects.values())a+=o*i.height,i.paint(e+this.x+2*this.scale,t+this.y+a,s);for(const i of this.belowBeatEffects.values())r+=n*i.height,i.paint(e+this.x+2*this.scale,t+this.y+r,s);super.paint(e,t,s),this._tremoloPicking&&this._tremoloPicking.paint(e,t,s)}}class Kr extends Li{constructor(e,t,s){super(e,t,1,Kr.getSymbol(s)),this._duration=s}static getSymbol(e){switch(e){case u.QuadrupleWhole:return N.RestLonga;case u.DoubleWhole:return N.RestDoubleWhole;case u.Whole:return N.RestWhole;case u.Half:return N.RestHalf;case u.Quarter:return N.RestQuarter;case u.Eighth:return N.RestEighth;case u.Sixteenth:return N.RestSixteenth;case u.ThirtySecond:return N.RestThirtySecond;case u.SixtyFourth:return N.RestSixtyFourth;case u.OneHundredTwentyEighth:return N.RestOneHundredTwentyEighth;case u.TwoHundredFiftySixth:return N.RestTwoHundredFiftySixth;default:return N.None}}static getSize(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:case u.Whole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:return 9;case u.ThirtySecond:return 12;case u.SixtyFourth:return 14;case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:return 20}return 10}doLayout(){this.width=Kr.getSize(this._duration)*this.scale}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class $r{constructor(){this.x=0,this.y=-3e3,this.width=0}}class Zr extends aa{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 $r);let t=21*this.scale;for(let s=0,i=this.glyphs.length;s<i;s++){let i=this.glyphs[s];i.renderer=this.renderer,i.doLayout();let a=0;for(;e[a].y>i.y;)a++,a===e.length&&e.push(new $r);i.x=a,e[a].y=i.y+t,e[a].width<i.width&&(e[a].width=i.width)}this.width=0;for(const t of e)this.width+=t.width,t.x=this.width;for(let t=0,s=this.glyphs.length;t<s;t++){let s=this.glyphs[t];const i=e[s.x];s.x=this.width-i.x}}}class en extends Jr{constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new Zr,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new Yr(!0),this._postNoteParenthesis=new Yr(!1))}get direction(){return H.Up}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 Mi(0,0,u.Quarter,!0),a=s.accidentalHelper.applyAccidentalForValue(this._beat,e,t,!0),r=s.accidentalHelper.getNoteLineForValue(e,!1);if(i.y=s.getScoreY(r),this._showParenthesis&&(this._preNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.addParenthesisOnLine(r,!0),this._postNoteParenthesis.addParenthesisOnLine(r,!0)),a!==re.None){let e=new Lr(0,i.y,a,!0);e.renderer=this.renderer,this._accidentals.renderer=this.renderer,this._accidentals.addGlyph(e)}this._noteValueLookup.set(e,i),this.add(i,r),this.isEmpty=!1}doLayout(){let e=0;this._showParenthesis&&(this._preNoteParenthesis.x=e,this._preNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.doLayout(),e+=this._preNoteParenthesis.width+en.ElementPadding*this.scale),this._accidentals.isEmpty||(e+=this._accidentals.width+en.ElementPadding*this.scale,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+en.ElementPadding*this.scale),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+en.ElementPadding*this.scale,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+en.ElementPadding*this.scale)}paint(e,t,s){this._accidentals.isEmpty||this._accidentals.paint(e+this.x,t+this.y,s),this._showParenthesis&&(this._preNoteParenthesis.paint(e+this.x,t+this.y,s),this._postNoteParenthesis.paint(e+this.x,t+this.y,s)),super.paint(e,t,s)}}en.ElementPadding=2;class tn extends Ci{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,s,i,a,r,n,o){zr.drawBendSlur(e,t,s,i,a,r,n,o)}doLayout(){super.doLayout(),this.width=0;for(let e of this.BendNoteHeads)e.doLayout(),this.width+=e.width+10*this.scale}getTieDirection(e,t){switch(t.getBeatDirection(e)){case H.Up:return H.Down;default:return H.Up}}}tn.EndPadding=8;class sn extends be{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class an extends Ci{constructor(){super(0,0),this._notes=[],this._renderPoints=new Map,this._preBendMinValue=-1,this._bendMiddleMinValue=-1,this._bendEndMinValue=-1,this._bendEndContinuedMinValue=-1,this._releaseMinValue=-1,this._releaseContinuedMinValue=-1,this._maxBendValue=-1}addBends(e){this._notes.push(e);let t=this.createRenderingPoints(e);this._renderPoints.set(e.id,t),(-1===this._maxBendValue||this._maxBendValue<e.maxBendPoint.value)&&(this._maxBendValue=e.maxBendPoint.value);let s=0;switch(e.bendType){case l.Bend:s=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||s<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=s):(-1===this._bendEndMinValue||s<this._bendEndMinValue)&&(this._bendEndMinValue=s);break;case l.Release:s=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s);break;case l.BendRelease:s=t[1].value,(-1===this._bendMiddleMinValue||s<this._bendMiddleMinValue)&&(this._bendMiddleMinValue=s),s=t[2].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s);break;case l.Prebend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s);break;case l.PrebendBend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s),s=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||s<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=s):(-1===this._bendEndMinValue||s<this._bendEndMinValue)&&(this._bendEndMinValue=s);break;case l.PrebendRelease:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s),s=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s)}}doLayout(){super.doLayout();let e=this._maxBendValue*an.BendValueHeight*this.scale;this.renderer.registerOverflowTop(e);let t=0;for(let e of this._notes){let s=this._renderPoints.get(e.id);switch(e.bendType){case l.Bend:s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case l.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t);break;case l.BendRelease:s[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[2].lineValue=t);break;case l.Prebend:s[0].lineValue=this._preBendMinValue;break;case l.PrebendBend:s[0].lineValue=this._preBendMinValue,s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case l.PrebendRelease:s[0].lineValue=this._preBendMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t)}}this.width=0,this._notes.sort(((e,t)=>e.isStringed?e.string-t.string:e.realValue-t.realValue))}createRenderingPoints(e){let t=[];switch(e.bendType){case l.Custom:for(let s of e.bendPoints)t.push(new sn(s.offset,s.value));break;case l.BendRelease:t.push(new sn(0,e.bendPoints[0].value)),t.push(new sn(be.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new sn(be.MaxPosition,e.bendPoints[3].value));break;case l.Bend:case l.Hold:case l.Prebend:case l.PrebendBend:case l.PrebendRelease:case l.Release:t.push(new sn(0,e.bendPoints[0].value)),t.push(new sn(be.MaxPosition,e.bendPoints[1].value))}return t}paint(e,t,s){let i=s.color;this._notes.length>1&&(s.color=this.renderer.resources.secondaryGlyphColor);for(let a of this._notes){let r=this._renderPoints.get(a.id),n=this.renderer,o=a,c=!1,d=null,u=!1,p=a.bendStyle===h.Gradual?"grad.":"",g=null;for(;o.isTieOrigin;){let e=o.tieDestination;if(d=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,e.beat.voice.bar),!d||n.staff!==d.staff)break;if(o=e,c=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes){u=!0;break}}g=o.beat,d=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,g.voice.bar),g.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(g=null);let f=0,m=0,y=t+n.y;f=e+n.x,r[0].value>0||a.isContinuedBend?f+=n.getBeatX(a.beat,ae.MiddleNotes):f+=n.getNoteX(a,oe.Right),m=!g||g.isLastOfVoice&&!u?e+d.x+d.postBeatGlyphsStart:u||!g.nextBeat?e+d.x+d.getBeatX(g,ae.MiddleNotes):a.bendType===l.Hold?e+d.x+d.getBeatX(g.nextBeat,ae.OnNotes):e+d.x+d.getBeatX(g.nextBeat,ae.PreNotes),c||(m-=an.ArrowSize*this.scale);let b=(m-f)/be.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 sn(0,0),t,f,y,b,p,s),a.bendType!==l.Prebend?(0===e&&(f+=2*this.scale),this.paintBend(a,t,i,f,y,b,p,s)):a.isTieOrigin&&a.tieDestination.hasBend&&(i=new sn(be.MaxPosition,t.value),i.lineValue=t.lineValue,this.paintBend(a,t,i,f,y,b,p,s))}s.color=i}}paintBend(e,t,s,i,a,r,n,o){let h=this.renderer,l=this.renderer.resources,c=h.lineOffset/2,d=i+r*t.offset,u=an.BendValueHeight*this.scale,p=a-u*t.lineValue;0===t.value?s.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,ne.Top):p+=h.getNoteY(e,ne.Center):p+=c;let g=i+r*s.offset,f=a-u*s.lineValue;0===s.lineValue?f+=h.getNoteY(e,ne.Center):f+=c;let m=0,y=an.ArrowSize*this.scale;if(s.value>t.value?(f+y>p&&(f=p-y),o.beginPath(),o.moveTo(g,f),o.lineTo(g-.5*y,f+y),o.lineTo(g+.5*y,f+y),o.closePath(),o.fill(),m=y):s.value!==t.value&&(f<p&&(f=p+y),o.beginPath(),o.moveTo(g,f),o.lineTo(g-.5*y,f-y),o.lineTo(g+.5*y,f-y),o.closePath(),o.fill(),m=-y),o.stroke(),t.value===s.value){if(t.lineValue>0){let e=g,t=an.DashSize*this.scale,s=d+t;if((e-d)/(2*t)<1)o.moveTo(e,p),o.lineTo(d,p);else for(;e>s;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>d?(o.moveTo(d,p),o.bezierCurveTo((d+g)/2,p,g,p,g,f+m),o.stroke()):(o.moveTo(d,p),o.lineTo(g,f),o.stroke());if(n&&t.offset<s.offset){o.font=l.graceFont;let e=o.measureText(n),t=0,s=0;if(p>f){let i=Math.abs(p-f);t=i>1.3*o.font.size?p-i/2:p,s=(d+g-e)/2}else t=p,s=g-e;o.fillText(n,s,t)}if(0!==s.value&&t.value!==s.value){let e=s.value,i=s.value>t.value;e=Math.abs(e);let r="";if(4===e)r="full",e-=4;else if(e>=4||e<=-4){let t=e/4|0;r+=t,e-=4*t}if(e>0&&(r+=an.getFractionSign(e)),""!==r){f=a-u*s.value;let e=f;i||(e=p+1*Math.abs(f-p)/3),o.font=l.tablatureFont;let t=o.measureText(r),n=e-.5*l.tablatureFont.size-2*this.scale,h=g-t/2;o.fillText(r,h,n)}}}static getFractionSign(e){switch(e){case 1:return"¼";case 2:return"½";case 3:return"¾";default:return e+"/ 4"}}}an.ArrowSize=6,an.DashSize=3,an.BendValueHeight=6;class rn extends Ci{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===C.Custom)return e.whammyBarPoints;let t=[];switch(e.whammyBarType){case C.Dive:case C.Hold:case C.PrediveDive:case C.Predive:t.push(new be(0,e.whammyBarPoints[0].value)),t.push(new be(be.MaxPosition,e.whammyBarPoints[1].value));break;case C.Dip:t.push(new be(0,e.whammyBarPoints[0].value)),t.push(new be(be.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new be(be.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===C.Dip;let e=null,t=null,s=this._beat;for(;s&&s.hasWhammyBar;)(!e||e.value>s.minWhammyPoint.value)&&(e=s.minWhammyPoint),(!t||t.value<s.maxWhammyPoint.value)&&(t=s.maxWhammyPoint),s=s.nextBeat;let i=t.value>0?Math.abs(this.getOffset(t.value)):0;(i>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys))&&(i+=2*this.renderer.resources.tablatureFont.size);let a=e.value<0?Math.abs(this.getOffset(e.value)):0;this.renderer.registerOverflowTop(i+a),i>this.renderer.staff.getSharedLayoutData(rn.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(rn.TopOffsetSharedDataKey,i)}getOffset(e){if(0===e)return 0;let t=rn.PerHalfSize*this.scale+Math.log2(Math.abs(e)/2)*rn.PerHalfSize*this.scale;return e<0&&(t=-t),t}paint(e,t,s){let i=this.renderer,a=this._beat.nextBeat,r=null,n=ae.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===C.Dip?ae.PreNotes:ae.MiddleNotes:(a=null,r=null));let o=0,l=0;this._isSimpleDip?(o=e+i.x+i.getBeatX(this._beat,ae.OnNotes)-2*this.scale,l=e+i.x+i.getBeatX(this._beat,ae.PostNotes)+2*this.scale):(o=e+i.x+i.getBeatX(this._beat,ae.MiddleNotes),l=r?e+r.x+r.getBeatX(a,n):e+i.x+i.width-2*this.scale);let c=s.textAlign;if(s.textAlign=P.Center,this._renderPoints.length>=2){let e=(l-o)/be.MaxPosition;s.beginPath();let i=t+this.renderer.staff.getSharedLayoutData(rn.TopOffsetSharedDataKey,0),a=this._beat.whammyStyle===h.Gradual?"grad.":"";for(let t=0,r=this._renderPoints.length-1;t<r;t++){let n=this._renderPoints[t],h=this._renderPoints[t+1],l=t<r-2?this._renderPoints[t+2]:null,c=0===t;0!==t||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new be(0,0),n,h,o,i,e,s),c=!1),this.paintWhammy(c,n,h,l,o,i,e,s,a),a=""}s.stroke()}s.textAlign=c}paintWhammy(e,t,s,i,a,r,n,o,h){let l=a+n*t.offset,c=a+n*s.offset,d=r-this.getOffset(t.value),u=r-this.getOffset(s.value);if(t.offset===s.offset){let e=rn.DashSize*this.scale;if(Math.abs(u-d)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(d,u),s=Math.min(d,u);for(;t>s;)o.moveTo(l,s),o.lineTo(l,s+e),s+=2*e}o.stroke()}else if(t.value===s.value){let e=rn.DashSize*this.scale;if(Math.abs(c-l)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(l,c),s=Math.min(l,c);for(;t>s;)o.moveTo(t,d),o.lineTo(t-e,d),t-=2*e}o.stroke()}else o.moveTo(l,d),o.lineTo(c,u);let p=this.renderer.resources;if(e&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let e=d;e-=p.tablatureFont.size+2*this.scale,this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2*this.scale,o.fillText(h,l,e))}let g=Math.abs(s.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys)&&!this._isSimpleDip)&&t.value!==s.value){let e="";if(s.value<0&&(e+="-"),g>=4){let t=g/4|0;e+=t,g-=4*t}else 0===g&&(e+="0");g>0&&(e+=an.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(d,u)-p.tablatureFont.size-2*this.scale:(a=t.offset===s.offset?Math.min(d,u):u,a-=p.tablatureFont.size+2*this.scale,i&&i.value>s.value&&(a-=2*this.scale));let r=c;o.fillText(e,r,a)}}}rn.TopOffsetSharedDataKey="tab.whammy.topoffset",rn.PerHalfSize=6,rn.DashSize=3;class nn extends tn{constructor(e){super(0,0),this._beat=e}doLayout(){let e=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case C.None:case C.Custom:case C.Hold:return;case C.Dive:case C.PrediveDive:{let e=new en(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 C.Dip:if(e===T.SongBook){let e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+nn.SimpleDipHeight*this.scale+nn.SimpleDipPadding*this.scale}else{let e=new en(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 en(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)}break;case C.Predive:}super.doLayout()}paint(e,t,s){let i=this._beat;switch(i.whammyBarType){case C.None:case C.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,ae.MiddleNotes),o=this.getTieDirection(i,r),l=1===this._beat.notes.length?o:H.Up,c=s.textAlign;for(let c=0;c<i.notes.length;c++){let d=i.notes[c],u=t+r.y;c>0&&c>=(this._beat.notes.length/2|0)&&(l=H.Down),l===H.Down?u+=r.getNoteY(d,ne.Bottom):u+=r.getNoteY(d,ne.Top);let p=e+r.x;i.isLastOfVoice?p+=r.width:p+=r.getBeatX(i,ae.EndBeat),p-=8*this.scale;let g=i.whammyStyle===h.Gradual&&0===c?"grad.":"",f=null;d.isTieOrigin&&(f=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,d.tieDestination.beat.voice.bar),f&&f.staff===r.staff?p=e+f.x+f.getBeatX(d.tieDestination.beat,ae.MiddleNotes):f=null);let m=Mi.NoteHeadHeight*this.scale*Mi.GraceScale*.5;l===H.Up&&(m=-m);let y=i.whammyBarPoints.length>0?this.getBendNoteValue(d,i.whammyBarPoints[i.whammyBarPoints.length-1]):0,b=0,S=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(y)?(b=this.BendNoteHeads[0].getNoteValueY(y)+m,S=!0):f&&(d.isTieOrigin&&d.tieDestination.beat.hasWhammyBar||d.beat.isContinuedWhammy)?(b=t+f.y+f.getNoteY(d.tieDestination,ne.Top),S=!0,l===H.Down&&(b+=Mi.NoteHeadHeight*this.scale)):d.isTieOrigin&&(b=f?t+f.y+f.getNoteY(d.tieDestination,ne.Top):u,l===H.Down&&(b+=Mi.NoteHeadHeight*this.scale)),i.whammyBarType){case C.Hold:d.isTieOrigin&&zr.paintTie(s,this.scale,n,u,p,b,o===H.Down,22,4);break;case C.Dive:0===c&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.BendNoteHeads[0].containsNoteValue(y)&&(b+=this.BendNoteHeads[0].y)),S?this.drawBendSlur(s,n,u,p,b,l===H.Down,this.scale,g):d.isTieOrigin&&zr.paintTie(s,this.scale,n,u,p,b,o===H.Down,22,4);break;case C.Dip:if(a===T.SongBook){if(0===c){let i=e+r.x+r.getBeatX(this._beat,ae.OnNotes)-2*this.scale,a=e+r.x+r.getBeatX(this._beat,ae.PostNotes)+2*this.scale,n=(i+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();s.font=this.renderer.resources.tablatureFont,s.fillText(o,n,t+this.y);let h=t+this.y+s.font.size+2*this.scale,l=h+nn.SimpleDipHeight*this.scale;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(s.moveTo(i,l),s.lineTo(n,h),s.lineTo(a,l)):(s.moveTo(i,h),s.lineTo(n,l),s.lineTo(a,h)),s.stroke()}d.isTieOrigin&&zr.paintTie(s,this.scale,n,u,p,b,o===H.Down,22,4)}else{let e=(n+p)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s);let a=this.getBendNoteValue(d,i.whammyBarPoints[1]),o=this.BendNoteHeads[0].getNoteValueY(a)+m;this.drawBendSlur(s,n,u,e,o,l===H.Down,this.scale,g),this.BendNoteHeads[1].x=p-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=t+r.y,this.BendNoteHeads[1].paint(0,0,s),b=this.BendNoteHeads[1].getNoteValueY(y)+m,this.drawBendSlur(s,e,o,p,b,l===H.Down,this.scale,g)}break;case C.PrediveDive:case C.Predive:let h=e+r.x+r.getBeatX(d.beat,ae.PreNotes);h+=r.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let f=t+r.y+r.getScoreY(r.accidentalHelper.getNoteLineForValue(d.displayValue-(d.beat.whammyBarPoints[0].value/2|0),!1))+m;this.drawBendSlur(s,h,f,n,u,l===H.Down,this.scale,g),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.drawBendSlur(s,n,u,p,b,l===H.Down,this.scale,g))}}s.textAlign=c}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}nn.SimpleDipHeight=2*rn.PerHalfSize,nn.SimpleDipPadding=2;class on extends Ci{constructor(e,t,s){super(e,t),this.width=s}}class hn extends Li{constructor(e,t,s,i,a){super(e,t,a?Mi.GraceScale:1,s.getSymbol(i)),this._isGrace=a,this._articulation=s}paint(e,t,s){let i=this._isGrace?this.scale:0;s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale*this.scale,this.symbol,!1),this._articulation.techniqueSymbol!==N.None&&this._articulation.techniqueSymbolPlacement===E.Middle&&s.fillMusicFontSymbol(e+this.x,t+this.y+i,this.glyphScale*this.scale,this._articulation.techniqueSymbol,!1)}doLayout(){let e=(this._isGrace?Mi.GraceScale:1)*this.scale;switch(this.symbol){case N.NoteheadWhole:this.width=14;break;case N.NoteheadCircleX:case N.NoteheadDiamondWhite:this.width=9;break;case N.NoteheadHeavyXHat:case N.NoteheadHeavyX:this.width=13;break;default:this.width=10}this.width=this.width*(this._isGrace?Mi.GraceScale:1)*this.scale,this.height=Mi.NoteHeadHeight*e}}class ln extends Li{constructor(e,t){super(e,t,Mi.GraceScale,N.ArticStaccatoAbove)}doLayout(){this.width=Mi.QuarterNoteHeadWidth*this.scale,this.height=7*this.scale}paint(e,t,s){super.paint(e+3*this.scale,t+5*this.scale,s)}}class cn extends Li{constructor(e,t){super(e,t,.5,N.PictEdgeOfCymbal)}doLayout(){this.width=22*this.scale,this.height=15*this.scale}paint(e,t,s){super.paint(e-3*this.scale,t+this.height,s)}}class dn extends Li{constructor(e,t){super(e,t,Mi.GraceScale,N.GuitarGolpe)}doLayout(){this.width=9*this.scale,this.height=10*this.scale}paint(e,t,s){super.paint(e,t+this.height,s)}}class un extends Ba{constructor(){super(...arguments),this._collisionOffset=-1e3,this._skipPaint=!1,this.noteHeads=null,this.restGlyph=null}getNoteX(e,t){return this.noteHeads?this.noteHeads.getNoteX(e,t):0}buildBoundingsLookup(e,t,s){this.noteHeads&&this.noteHeads.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteY(e,t){return this.noteHeads?this.noteHeads.getNoteY(e,t):0}updateBeamingHelper(){if(this.noteHeads)this.noteHeads.updateBeamingHelper(this.container.x+this.x);else if(this.restGlyph&&(this.restGlyph.updateBeamingHelper(this.container.x+this.x),this.renderer.bar.isMultiVoice&&-1e3===this._collisionOffset)){this._collisionOffset=this.renderer.helpers.collisionHelper.applyRestCollisionOffset(this.container.beat,this.restGlyph.y,this.renderer.getScoreHeight(1)),this.y+=this._collisionOffset;const e=this.renderer.helpers.collisionHelper.restDurationsByDisplayTime;e.has(this.container.beat.playbackStart)&&e.get(this.container.beat.playbackStart).has(this.container.beat.playbackDuration)&&e.get(this.container.beat.playbackStart).get(this.container.beat.playbackDuration)!==this.container.beat.id&&(this._skipPaint=!0)}}paint(e,t,s){this._skipPaint||super.paint(e,t,s)}doLayout(){let e=this.renderer;if(!this.container.beat.isEmpty)if(this.container.beat.isRest){let t=2*Math.ceil((this.renderer.bar.staff.standardNotationLineCount-1)/2);this.container.beat.duration===u.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const s=new Kr(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=da.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 on(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++){let e=new aa(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addGlyph(e)}}}else{const t=new jr;this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper;let s=new Yr(!1);s.renderer=this.renderer;for(let e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),s.addParenthesis(e));if(this.addGlyph(t),s.isEmpty||(this.addGlyph(new on(0,0,4*(this.container.beat.graceType!==g.None?Mi.GraceScale:1)*this.scale)),this.addGlyph(s)),this.container.beat.hasWhammyBar){let e=new nn(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addGlyph(new on(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++){let t=new aa(0,0);t.renderer=this.renderer;for(let s of this.container.beat.notes)this.createBeatDot(e.getNoteLine(s),t);this.addGlyph(t)}}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.container.beat.isRest?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.centerX=this.noteHeads.x+this.noteHeads.width/2}createBeatDot(e,t){let s=this.renderer;t.addGlyph(new Vr(0,s.getScoreY(e),1.5*this.scale))}createNoteHeadGlyph(e){let t=this.container.beat.graceType!==g.None;if(e.beat.voice.bar.staff.isPercussion){const s=xe.getArticulation(e);if(s)return new hn(0,0,s,e.beat.duration,t);Be.warning("Rendering","No articulation found for percussion instrument "+e.percussionArticulation)}return e.isDead?new Hr(0,0,t):e.beat.graceType===g.BendGrace?new Mi(0,0,u.Quarter,!0):e.harmonicType===m.Natural?new Wr(0,0,e.beat.duration,t):new Mi(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===g.BendGrace&&!e.hasBend)return;let t=this.renderer,s=this.createNoteHeadGlyph(e),a=t.getNoteLine(e);if(s.y=t.getScoreY(a),this.noteHeads.addNoteGlyph(s,e,a),e.harmonicType!==m.None&&e.harmonicType!==m.Natural){let i=e.displayValue+e.harmonicPitch;s=new Wr(0,0,e.beat.duration,this.container.beat.graceType!==g.None),a=t.accidentalHelper.getNoteLineForValue(i,!1),s.y=t.getScoreY(a),this.noteHeads.addNoteGlyph(s,e,a)}if(e.isStaccato&&!this.noteHeads.aboveBeatEffects.has("Staccato")&&this.noteHeads.belowBeatEffects.set("Staccato",new ln(0,0)),e.accentuated!==i.Normal||this.noteHeads.aboveBeatEffects.has("Accent")||this.noteHeads.belowBeatEffects.set("Accent",new Gr(0,0,i.Normal)),e.accentuated!==i.Heavy||this.noteHeads.aboveBeatEffects.has("HAccent")||this.noteHeads.belowBeatEffects.set("HAccent",new Gr(0,0,i.Heavy)),e.isPercussion){const t=xe.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==E.Middle){const e=t.techniqueSymbolPlacement===E.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case N.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new cn(0,0));break;case N.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new ln(0,0));break;case N.StringsUpBow:e.set("StringsUpBow",new $a(0,0,x.Up));break;case N.StringsDownBow:e.set("StringsDownBow",new $a(0,0,x.Down));break;case N.GuitarGolpe:e.set("GuitarGolpe",new dn(0,0))}}}}}class pn extends Ci{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10*this.scale}paint(e,t,s){let i=this.renderer,a=i.lineOffset,r=t+this.y+(i.getNoteY(this._beat.maxNote,ne.Bottom)-a),n=t+this.y+i.getNoteY(this._beat.minNote,ne.Top)+a,o=e+this.x+this.width/2,h=8*this.scale;if(this._beat.brushType!==c.None){let t=new sr(0,0,w.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let i=-t.height/2;if(this._beat.brushType===c.ArpeggioUp){let a=r+h,l=n-h;t.width=Math.abs(l-a),s.beginRotate(e+this.x+5*this.scale,l,-90),t.paint(0,i,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 a=r+h,l=n;t.width=Math.abs(l-a),s.beginRotate(e+this.x+5*this.scale,a,90),t.paint(0,i,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 gn extends _a{constructor(){super(),this._prebends=null,this.accidentals=null}get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}doLayout(){if(!this.container.beat.isRest){let e=new Zr;e.renderer=this.renderer;let t=new Yr(!0);t.renderer=this.renderer;const s=new en(this.container.beat,!0);this._prebends=s,s.renderer=this.renderer;for(let i of this.container.beat.notes)if(i.isVisible){if(i.hasBend)switch(i.bendType){case l.PrebendBend:case l.Prebend:case l.PrebendRelease:s.addGlyph(i.displayValue-(i.bendPoints[0].value/2|0),!1)}else if(i.beat.hasWhammyBar)switch(i.beat.whammyBarType){case C.PrediveDive:case C.Predive:this._prebends.addGlyph(i.displayValue-(i.beat.whammyBarPoints[0].value/2|0),!1)}this.createAccidentalGlyph(i,e),t.addParenthesis(i)}s.isEmpty||(this.addGlyph(s),this.addGlyph(new on(0,0,4*(this.container.beat.graceType!==g.None?Mi.GraceScale:1)*this.scale))),this.container.beat.brushType!==c.None&&(this.addGlyph(new pn(this.container.beat)),this.addGlyph(new on(0,0,4*this.scale))),t.isEmpty||(this.addGlyph(t),this.addGlyph(new on(0,0,4*(this.container.beat.graceType!==g.None?Mi.GraceScale:1)*this.scale))),e.isEmpty||(this.accidentals=e,this.addGlyph(new on(0,0,2*(this.container.beat.graceType!==g.None?Mi.GraceScale:1)*this.scale)),this.addGlyph(e),this.addGlyph(new on(0,0,2*(this.container.beat.graceType!==g.None?Mi.GraceScale:1)*this.scale)))}super.doLayout()}createAccidentalGlyph(e,t){let s=this.renderer,i=s.accidentalHelper.applyAccidental(e),a=s.getNoteLine(e),r=this.container.beat.graceType!==g.None;if(i!==re.None){let e=new Lr(0,s.getScoreY(a),i,r);e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==m.None&&e.harmonicType!==m.Natural){let n=e.displayValue+e.harmonicPitch;i=s.accidentalHelper.applyAccidentalForValue(e.beat,n,r,!1),a=s.accidentalHelper.getNoteLineForValue(n,!1);let o=new Lr(0,s.getScoreY(a),i,r);o.renderer=this.renderer,t.addGlyph(o)}}}class fn extends Li{constructor(e,t,s,i){super(e,t,i,fn.getSymbol(s)),this._digit=0,this._scale=0,this._digit=s,this._scale=i}doLayout(){this.width=this.getDigitWidth(this._digit)*this.scale*this._scale}getDigitWidth(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:return 14;case 1:return 10;default:return 0}}static getSymbol(e){switch(e){case 0:return N.TimeSig0;case 1:return N.TimeSig1;case 2:return N.TimeSig2;case 3:return N.TimeSig3;case 4:return N.TimeSig4;case 5:return N.TimeSig5;case 6:return N.TimeSig6;case 7:return N.TimeSig7;case 8:return N.TimeSig8;case 9:return N.TimeSig9;default:return N.None}}}class mn extends aa{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 fn(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}}}mn.numberHeight=18;class yn extends aa{constructor(e,t,s,i,a){super(e,t),this._numerator=0,this._denominator=0,this._numerator=s,this._denominator=i,this._isCommon=a}doLayout(){if(this._isCommon&&2===this._numerator&&2===this._denominator){let e=new Li(0,0,this.commonScale,N.TimeSigCutCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){let e=new Li(0,0,this.commonScale,N.TimeSigCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else{const e=mn.numberHeight*this.scale;let t=new mn(0,-e/2,this._numerator,this.numberScale),s=new mn(0,e/2,this._denominator,this.numberScale);this.addGlyph(t),this.addGlyph(s),super.doLayout();for(let e=0,t=this.glyphs.length;e<t;e++){let t=this.glyphs[e];t.x=(this.width-t.width)/2}}}}class bn extends yn{get commonScale(){return 1}get numberScale(){return 1}}class Sn extends tn{constructor(e){super(0,0),this._notes=[],this._endNoteGlyph=null,this._middleNoteGlyph=null,this._beat=e}addBends(e){if(this._notes.push(e),!e.isTieOrigin)switch(e.bendType){case l.Bend:case l.PrebendRelease:case l.PrebendBend:{let t=this._endNoteGlyph;t||(t=new en(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let s=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,s),s.value%2!=0)}break;case l.Release:if(!e.isTieOrigin){let t=this._endNoteGlyph;t||(t=new en(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let s=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,s),s.value%2!=0)}break;case l.BendRelease:{let t=this._middleNoteGlyph;t||(t=new en(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 en(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,ae.MiddleNotes),r=e+i.x;this._beat.isLastOfVoice?r+=i.postBeatGlyphsStart:r+=i.getBeatX(this._beat.nextBeat,ae.PreNotes),r-=8*this.scale;let n=(a+r)/2;this._middleNoteGlyph&&(this._middleNoteGlyph.x=n-this._middleNoteGlyph.noteHeadOffset,this._middleNoteGlyph.y=t+i.y,this._middleNoteGlyph.paint(0,0,s)),this._endNoteGlyph&&(this._endNoteGlyph.x=r-this._endNoteGlyph.noteHeadOffset,this._endNoteGlyph.y=t+i.y,this._endNoteGlyph.paint(0,0,s)),this._notes.sort(((e,t)=>t.displayValue-e.displayValue));let o=this._beat.graceType===g.BendGrace?this._beat.nextBeat:this._beat,c=1===this._notes.length?this.getTieDirection(o,i):H.Up;for(let o=0;o<this._notes.length;o++){let d=this._notes[o];o>0&&o>=(this._notes.length/2|0)&&(c=H.Down);let u=t+i.y+i.getNoteY(d,ne.Top),p=Mi.NoteHeadHeight*this.scale*Mi.GraceScale*.5;c===H.Down&&(u+=Mi.NoteHeadHeight*this.scale);let g=d.bendStyle===h.Gradual?"grad.":"";if(d.isTieOrigin){let r=d.tieDestination,n=r?this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.beat.voice.bar):null;if(n&&n.staff===i.staff){let i=e+n.x+n.getBeatX(r.beat,ae.MiddleNotes),o=t+n.y+n.getNoteY(r,ne.Top);c===H.Down&&(o+=Mi.NoteHeadHeight*this.scale),d.bendType===l.Hold||d.bendType===l.Prebend?zr.paintTie(s,this.scale,a,u,i,o,c===H.Down,22,4):this.drawBendSlur(s,a,u,i,o,c===H.Down,this.scale,g)}else{let r=e+i.x+i.width,n=d.tieDestination.realValue;i.accidentalHelper.applyAccidentalForValue(d.beat,n,!1,!0);let o=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(n,!1));d.bendType===l.Hold||d.bendType===l.Prebend?zr.paintTie(s,this.scale,a,u,r,o,c===H.Down,22,4):this.drawBendSlur(s,a,u,r,o,c===H.Down,this.scale,g)}switch(d.bendType){case l.Prebend:case l.PrebendBend:case l.PrebendRelease:let r=e+i.x+i.getBeatX(d.beat,ae.PreNotes);r+=i.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let n=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(d.displayValue-(d.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,r,n,a,u,c===H.Down,this.scale)}}else{c===H.Up&&(p=-p);let o=0,h=0;switch(d.bendType){case l.Bend:o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,h,c===H.Down,this.scale,g);break;case l.BendRelease:let f=this.getBendNoteValue(d,d.bendPoints[1]),m=this._middleNoteGlyph.getNoteValueY(f)+p;this.drawBendSlur(s,a,u,n,m,c===H.Down,this.scale,g),o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(s,n,m,r,h,c===H.Down,this.scale,g);break;case l.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,h,c===H.Down,this.scale,g));break;case l.Prebend:case l.PrebendBend:case l.PrebendRelease:let y=e+i.x+i.getBeatX(d.beat,ae.PreNotes);y+=i.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let b=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(d.displayValue-(d.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(s,y,b,a,u,c===H.Down,this.scale),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),h=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(s,a,u,r,h,c===H.Down,this.scale,g))}}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class wn extends zr{constructor(e,t,s=!1){super(e,t,s)}doLayout(){super.doLayout()}getBeamDirection(e,t){if(e.isRest)return H.Up;switch(t.getBeatDirection(e)){case H.Up:return H.Down;default:return H.Up}}getStartY(){if(this.startBeat.isRest)return this.startNoteRenderer.getScoreY(9);switch(this.tieDirection){case H.Up:return this.startNoteRenderer.getNoteY(this.startBeat.maxNote,ne.Top);default:return this.startNoteRenderer.getNoteY(this.startBeat.minNote,ne.Bottom)}}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)switch(this.tieDirection){case H.Up:return e.getScoreY(9);default:return e.getScoreY(0)}const t=this.startNoteRenderer.getBeatDirection(this.startBeat),s=e.getBeatDirection(this.endBeat);if(t!==s&&this.startBeat.graceType===g.None)if(s===this.tieDirection)switch(this.tieDirection){case H.Up:return e.getNoteY(this.endBeat.maxNote,ne.TopWithStem);default:return e.getNoteY(this.endBeat.minNote,ne.BottomWithStem)}else switch(this.tieDirection){case H.Up:return e.getNoteY(this.endBeat.maxNote,ne.BottomWithStem);default:return e.getNoteY(this.endBeat.minNote,ne.TopWithStem)}switch(this.tieDirection){case H.Up:return e.getNoteY(this.endBeat.maxNote,ne.Top);default:return e.getNoteY(this.endBeat.minNote,ne.Bottom)}}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,ae.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>u.Whole&&e===this.tieDirection?ae.Stem:ae.MiddleNotes)}}class _n extends Ci{constructor(e,t,s,i){super(0,0),this._outType=t,this._inType=e,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.drawSlideOut(e,t,s)}paintSlideIn(e,t,s){let i=this.renderer,a=12*this.scale,r=e+i.x+i.getNoteX(this._startNote,oe.Left)-2*this.scale,n=t+i.y+i.getNoteY(this._startNote,ne.Center),o=r-a,h=t+i.y;switch(this._inType){case b.IntoFromBelow:h+=i.getNoteY(this._startNote,ne.Bottom);break;case b.IntoFromAbove:h+=i.getNoteY(this._startNote,ne.Top);break;default:return}let l=this.getAccidentalsWidth(i,this._startNote.beat);o-=l,r-=l,this.paintSlideLine(s,!1,o,r,h,n)}getAccidentalsWidth(e,t){let s=e.getPreNotesGlyphForBeat(t);return s&&s.accidentals?s.accidentals.width:0}drawSlideOut(e,t,s){let i=this.renderer,a=12*this.scale,r=3*this.scale,n=1*this.scale,o=2*this.scale,h=0,l=0,c=0,d=0,u=!1;switch(this._outType){case S.Shift:case S.Legato:if(h=e+i.x+i.getBeatX(this._startNote.beat,ae.PostNotes)+r,l=t+i.y+i.getNoteY(this._startNote,ne.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?(c=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,ae.PreNotes)-n,d=t+s.y+s.getNoteY(this._startNote.slideTarget,ne.Center)):(c=e+i.x+this._parent.x,d=l),this._startNote.slideTarget.realValue>this._startNote.realValue?(l+=o,d-=o):(l-=o,d+=o)}else c=e+i.x+this._parent.x,d=l;break;case S.OutUp:h=e+i.x+i.getNoteX(this._startNote,oe.Right),l=t+i.y+i.getNoteY(this._startNote,ne.Center),c=h+a,d=t+i.y+i.getNoteY(this._startNote,ne.Top);break;case S.OutDown:h=e+i.x+i.getNoteX(this._startNote,oe.Right),l=t+i.y+i.getNoteY(this._startNote,ne.Center),c=h+a,d=t+i.y+i.getNoteY(this._startNote,ne.Bottom);break;case S.PickSlideUp:h=e+i.x+i.getNoteX(this._startNote,oe.Right)+r,l=t+i.y+i.getNoteY(this._startNote,ne.Center),d=t+i.y+i.getNoteY(this._startNote,ne.Top),c=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(c=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,ae.PreNotes)),u=!0;break;case S.PickSlideDown:h=e+i.x+i.getNoteX(this._startNote,oe.Right)+r,l=t+i.y+i.getNoteY(this._startNote,ne.Center),d=t+i.y+i.getNoteY(this._startNote,ne.Bottom),c=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(c=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,ae.PreNotes)),u=!0;break;default:return}this.paintSlideLine(s,u,h,c,l,d)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new sr(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 Bn extends wn{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(){if(this.isStartCentered())switch(this.tieDirection){case H.Up:return this.startNoteRenderer.getNoteY(this._startNote,ne.Top);default:return this.startNoteRenderer.getNoteY(this._startNote,ne.Bottom)}return this.startNoteRenderer.getNoteY(this._startNote,ne.Center)}getEndY(){if(!this.isEndCentered())return this.endNoteRenderer.getNoteY(this._endNote,ne.Center);if(this.isEndOnStem())switch(this.tieDirection){case H.Up:return this.endNoteRenderer.getNoteY(this._endNote,ne.TopWithStem);default:return this.endNoteRenderer.getNoteY(this._endNote,ne.BottomWithStem)}else switch(this.tieDirection){case H.Up:return this.endNoteRenderer.getNoteY(this._endNote,ne.Top);default:return this.endNoteRenderer.getNoteY(this._endNote,ne.Bottom)}}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===H.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===H.Down}isEndCentered(){return this._startNote.beat.graceType===g.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===H.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===H.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===g.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,ae.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,oe.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,ae.Stem):this.endNoteRenderer.getNoteX(this._endNote,oe.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,ae.PreNotes)}}class Tn extends zr{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){switch(t.getBeatDirection(e)){case H.Up:return H.Down;default:return H.Up}}getStartY(){if(this.startBeat.isRest)return this.startNoteRenderer.getScoreY(9);switch(this.tieDirection){case H.Up:return this.startNoteRenderer.getNoteY(this.startNote,ne.Top);default:return this.startNoteRenderer.getNoteY(this.startNote,ne.Bottom)}}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)switch(this.tieDirection){case H.Up:return e.getScoreY(9);default:return e.getScoreY(0)}switch(this.tieDirection){case H.Up:return e.getNoteY(this.endNote,ne.Top);default:return e.getNoteY(this.endNote,ne.Bottom)}}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,ae.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,ae.PreNotes)}}class kn extends Di{constructor(e,t){super(e,t),this._bend=null,this._effectSlur=null,this._effectEndSlur=null}doLayout(){if(this._effectSlur=null,this._effectEndSlur=null,super.doLayout(),this.beat.isLegatoOrigin){if(!this.beat.previousBeat||!this.beat.previousBeat.isLegatoOrigin){let e=this.beat.nextBeat;for(;e.nextBeat&&e.nextBeat.isLegatoDestination;)e=e.nextBeat;this.ties.push(new wn(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.ties.push(new wn(e,this.beat,!0))}this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(e.isVisible){if(e.isTieOrigin&&!e.hasBend&&!e.beat.hasWhammyBar&&e.beat.graceType!==g.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){let t=new Tn(e,e.tieDestination,!1);this.ties.push(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){let t=new Tn(e.tieOrigin,e,!0);this.ties.push(t)}if(e.slideInType!==b.None||e.slideOutType!==S.None){let t=new _n(e.slideInType,e.slideOutType,e,this);this.ties.push(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){let t=new Bn(e,e.slurDestination,!1);this.ties.push(t)}if(e.isSlurDestination){let t=new Bn(e.slurOrigin,e,!0);this.ties.push(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new Bn(e,e.effectSlurDestination,!1);this._effectSlur=t,this.ties.push(t)}if(!this._effectEndSlur&&e.beat.isEffectSlurDestination&&e.beat.effectSlurOrigin){let t=this.onNotes.beamingHelper.direction,s=t===H.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,i=t===H.Up?e.beat.minNote:e.beat.maxNote;const a=new Bn(s,i,!0);this._effectEndSlur=a,this.ties.push(a)}if(e.hasBend){if(!this._bend){const t=new Sn(e.beat);this._bend=t,t.renderer=this.renderer,this.ties.push(t)}this._bend.addBends(e)}}}}class vn extends ma{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._firstLineY=0,this._startSpacing=!1,this.accidentalHelper=new ha(this)}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}get lineOffset(){return(ma.LineSpacing+1)*this.scale}updateSizes(){let e=this.resources,t=e.tablatureFont.size/2+.2*e.tablatureFont.size;this.topPadding=t*this.scale,this.bottomPadding=t*this.scale,this.height=4*this.lineOffset+this.topPadding+this.bottomPadding,this.updateFirstLineY(),super.updateSizes()}updateFirstLineY(){let e=4*this.lineOffset,t=(this.bar.staff.standardNotationLineCount-1)*this.lineOffset;this._firstLineY=(e-t)/2}doLayout(){if(this.updateFirstLineY(),super.doLayout(),!this.bar.isEmpty&&this.accidentalHelper.maxLineBeat){let e=this.getScoreY(-2),t=this.getScoreY(6),s=this.simpleWhammyOverflow;this.registerOverflowTop(s);let i=this.getScoreY(this.accidentalHelper.maxLine),a=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);a.direction===H.Up&&(i-=this.getStemSize(a),i-=a.fingeringCount*this.resources.graceFont.size,a.hasTuplet&&(i-=2*this.resources.effectFont.size)),a.hasTuplet&&(i-=1.5*this.resources.effectFont.size),i<e&&this.registerOverflowTop(Math.abs(i)+s);let r=this.getScoreY(this.accidentalHelper.minLine),n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);n.direction===H.Down&&(r+=this.getStemSize(n),r+=n.fingeringCount*this.resources.graceFont.size),r>t&&this.registerOverflowBottom(Math.abs(r)-t)}}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s),this.paintTuplets(e,t,s)}paintTuplets(e,t,s){for(let i of this.bar.voices)if(this.hasVoiceContainer(i)){let a=this.getVoiceContainer(i);for(let i of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,i)}}paintBeams(e,t,s){for(let i=0,a=this.helpers.beamHelpers.length;i<a;i++){let a=this.helpers.beamHelpers[i];for(let i=0,r=a.length;i<r;i++){let r=a[i];this.paintBeamHelper(e+this.beatGlyphsStart,t,s,r)}}}paintBeamHelper(e,t,s,i){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(1===i.beats.length?this.paintFlag(e,t,s,i):this.paintBar(e,t,s,i))}paintTupletHelper(e,t,s,i){let a,r=this.resources,n=s.textAlign,o=s.textBaseline;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=P.Center,s.textBaseline=E.Middle;let h=i.beats[0].tupletNumerator,l=i.beats[0].tupletDenominator;a=2===h&&3===l?"2":3===h&&2===l?"3":4===h&&6===l?"4":5===h&&4===l?"5":6===h&&4===l?"6":7===h&&4===l?"7":9===h&&8===l?"9":10===h&&8===l?"10":11===h&&8===l?"11":12===h&&8===l?"12":13===h&&8===l?"13":h+":"+l;let c=10*this.scale,d=5*this.scale;if(1!==i.beats.length&&i.isFull){let n=i.beats[0],o=i.beats[i.beats.length-1],h=null,l=null;for(let e=0;e<i.beats.length;e++)if(!i.beats[e].isRest){h=i.beats[e];break}for(let e=i.beats.length-1;e>=0;e--)if(!i.beats[e].isRest){l=i.beats[e];break}let u=!1;h||(h=n,u=!0),l||(l=o);let p=this.helpers.beamHelperLookup[i.voice.index].get(n.index),g=this.helpers.beamHelperLookup[i.voice.index].get(o.index),f=p.getBeatLineX(n),m=g.getBeatLineX(o),y=this.helpers.beamHelperLookup[i.voice.index].get(h.index),b=this.helpers.beamHelperLookup[i.voice.index].get(l.index),S=p.direction,w=this.calculateBeamYWithDirection(y,f,S),_=this.calculateBeamYWithDirection(b,m,S);u&&(w=Math.max(w,_),_=w),s.font=r.effectFont;let B=s.measureText(a),T=3*this.scale,k=(f+m)/2,v=k-B/2-T,x=k+B/2+T,N=(_-w)/(m-f),P=w-N*f,E=N*v+P,C=N*k+P,F=N*x+P;S===H.Down&&(c*=-1,d*=-1),s.beginPath(),s.moveTo(e+this.x+f,t+this.y+w-c|0),s.lineTo(e+this.x+f,t+this.y+w-c-d|0),s.lineTo(e+this.x+v,t+this.y+E-c-d|0),s.stroke(),s.beginPath(),s.moveTo(e+this.x+x,t+this.y+F-c-d|0),s.lineTo(e+this.x+m,t+this.y+_-c-d|0),s.lineTo(e+this.x+m,t+this.y+_-c|0),s.stroke(),s.fillText(a,e+this.x+k,t+this.y+C-c-d)}else for(let n=0,o=i.beats.length;n<o;n++){let o=i.beats[n],h=this.helpers.beamHelperLookup[i.voice.index].get(o.index);if(!h)continue;let l=h.direction,u=h.getBeatLineX(o),p=this.calculateBeamYWithDirection(h,u,l);l===H.Down&&(c*=-1,d*=-1),s.font=r.effectFont,s.fillText(a,e+this.x+u,t+this.y+p-c-d)}s.textAlign=n,s.textBaseline=o}getStemSize(e){let t=1===e.beats.length?this.getFlagStemSize(e.shortestDuration):this.getBarStemSize(e.shortestDuration);return e.isGrace&&(t*=Mi.GraceScale),t}getBarStemSize(e){let t=0;switch(e){case u.QuadrupleWhole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:t=6;break;case u.ThirtySecond:t=8;break;case u.SixtyFourth:case u.OneHundredTwentyEighth:t=9;break;case u.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}getFlagStemSize(e){let t=0;switch(e){case u.QuadrupleWhole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:case u.ThirtySecond:case u.SixtyFourth:case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:t=6;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){let s=super.getNoteY(e,t);if(isNaN(s)){const t=ha.computeLineWithoutAccidentals(this.bar,e);s=this.getScoreY(t)}return s}calculateBeamY(e,t){return this.calculateBeamYWithDirection(e,t,e.direction)}applyLayoutingInfo(){const e=super.applyLayoutingInfo();if(e&&this.bar.isMultiVoice){let e=this.getScoreY(-2),t=this.getScoreY(6),s=this.helpers.collisionHelper.getBeatMinMaxY();s[0]<e&&this.registerOverflowTop(Math.abs(s[0])),s[1]>t&&this.registerOverflowBottom(Math.abs(s[1])-t)}return e}calculateBeamYWithDirection(e,t,s){let i=this.getStemSize(e);if(!e.drawingInfos.has(s)){let t=new ca;e.drawingInfos.set(s,t);const a=e.beats[0],r=e.beats[e.beats.length-1];let n=e.isRestBeamHelper;t.startBeat=a,t.startX=e.getBeatLineX(a),t.startY=n?s===H.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===H.Up?this.getScoreY(this.accidentalHelper.getMinLine(a))-i:this.getScoreY(this.accidentalHelper.getMaxLine(a))+i,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?s===H.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===H.Up?this.getScoreY(this.accidentalHelper.getMinLine(r))-i:this.getScoreY(this.accidentalHelper.getMaxLine(r))+i;let o=10*this.scale;if(s===H.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),s===H.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),s===H.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),s===H.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(s===H.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=ke.getIndex(e.shortestDuration)-2;let a=e.isGrace?Mi.GraceScale:1,r=i*(ma.BeamSpacing+ma.BeamThickness)*this.scale*a;if(r+=ma.BeamSpacing,s===H.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===H.Down&&null!==e.maxRestLine){const s=this.getScoreY(e.maxRestLine)+r-t.calcY(e.getBeatLineX(e.beatOfMaxRestLine));s>0&&(t.startY+=s,t.endY+=s)}}}}return e.drawingInfos.get(s).calcY(t)}paintBar(e,t,s,i){for(let a=0,r=i.beats.length;a<r;a++){let r=i.beats[a],n=r.graceType!==g.None?Mi.GraceScale:1,o=i.getBeatLineX(r),h=i.direction,l=t+this.y;l+=h===H.Up?this.getScoreY(this.accidentalHelper.getMaxLine(r)):this.getScoreY(this.accidentalHelper.getMinLine(r));let c=t+this.y;c+=this.calculateBeamY(i,o),s.lineWidth=ma.StemWidth*this.scale,s.beginPath(),s.moveTo(e+this.x+o,l),s.lineTo(e+this.x+o,c),s.stroke(),s.lineWidth=this.scale;let d=c;h===H.Down?d+=2*s.font.size:0!==a&&(d-=1.5*s.font.size),this.paintFingering(s,r,e+this.x+o,h,d);let u=6*this.scale*n,p=(ma.BeamSpacing+ma.BeamThickness)*this.scale*n,f=ma.BeamThickness*this.scale*n,m=ke.getIndex(r.duration)-2,y=t+this.y;h===H.Down&&(p=-p,f=-f);for(let t=0;t<m;t++){let n=0,h=0,l=0,c=0,d=y+t*p;if(a<i.beats.length-1){if(da.isFullBarJoin(r,i.beats[a+1],t))n=o,h=i.getBeatLineX(i.beats[a+1]);else{if(0!==a&&da.isFullBarJoin(i.beats[a-1],r,t))continue;n=o,h=n+u}l=d+this.calculateBeamY(i,n),c=d+this.calculateBeamY(i,h),vn.paintSingleBar(s,e+this.x+n,l,e+this.x+h,c,f)}else a>0&&!da.isFullBarJoin(r,i.beats[a-1],t)&&(n=o-u,h=o,l=d+this.calculateBeamY(i,n),c=d+this.calculateBeamY(i,h),vn.paintSingleBar(s,e+this.x+n,l,e+this.x+h,c,f))}}}static paintSingleBar(e,t,s,i,a,r){e.beginPath(),e.moveTo(t,s),e.lineTo(i,a),e.lineTo(i,a+r),e.lineTo(t,s+r),e.closePath(),e.fill()}paintFlag(e,t,s,i){let a=i.beats[0];if(a.graceType===g.BendGrace||a.graceType!==g.None&&this.settings.notation.notationMode===T.SongBook)return;let r=a.graceType!==g.None,n=r?Mi.GraceScale:1,o=this.getFlagStemSize(i.shortestDuration),h=i.getBeatLineX(a),l=i.direction,c=this.getScoreY(this.accidentalHelper.getMinLine(a)),d=this.getScoreY(this.accidentalHelper.getMaxLine(a)),u=0,p=0;if(l===H.Down?(d+=o*n,u=d,p=t+this.y+d):(c-=o*n,u=c,p=t+this.y+c),this.paintFingering(s,a,e+this.x+h,l,p),i.hasLine){if(s.lineWidth=ma.StemWidth*this.scale,s.beginPath(),s.moveTo(e+this.x+h,t+this.y+c),s.lineTo(e+this.x+h,t+this.y+d),s.stroke(),s.lineWidth=this.scale,a.graceType===g.BeforeBeat){let i=15*this.scale,a=12*this.scale;s.beginPath(),l===H.Down?(s.moveTo(e+this.x+h-a/2,t+this.y+d-i),s.lineTo(e+this.x+h+a/2,t+this.y+d)):(s.moveTo(e+this.x+h-a/2,t+this.y+c+i),s.lineTo(e+this.x+h+a/2,t+this.y+c)),s.stroke()}if(i.hasFlag){let i=new Ii(h-this.scale/2,u,a.duration,l,r);i.renderer=this,i.doLayout(),i.paint(e+this.x,t+this.y,s)}}}paintFingering(e,t,s,i,a){let r=this.settings;if(r.notation.fingeringMode!==B.ScoreDefault&&r.notation.fingeringMode!==B.ScoreForcePiano)return;i===H.Up?s-=10*this.scale:s+=3*this.scale;let n=t.notes.slice(0);n.sort(((e,t)=>e.realValue-t.realValue));for(let i=0;i<n.length;i++){let o=n[i],h=null;o.leftHandFinger!==f.Unknown?h=ke.fingerToString(r,t,o.leftHandFinger,!0):o.rightHandFinger!==f.Unknown&&(h=ke.fingerToString(r,t,o.rightHandFinger,!1)),h&&(e.fillText(h,s,a),a-=0|e.font.size)}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Or(0,0,1.5,3)),this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let e=0;switch(this.bar.clef){case r.Neutral:e=this.bar.staff.standardNotationLineCount-1;break;case r.F4:e=2;break;case r.C3:e=4;break;case r.C4:e=2;break;case r.G2:e=6}this.createStartSpacing(),this.addPreBeatGlyph(new Dr(0,this.getScoreY(e)+.5*ma.StaffLineThickness,this.bar.clef,this.bar.clefOttava))}(0===this.index&&this.bar.masterBar.keySignature!==M.C||this.bar.previousBar&&this.bar.masterBar.keySignature!==this.bar.previousBar.masterBar.keySignature)&&(this.createStartSpacing(),this.createKeySignatureGlyphs()),(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new Mr(0,this.getScoreHeight(-.5),this.bar.index+1))}createBeatGlyphs(){for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];this.hasVoiceContainer(t)&&this.createVoiceGlyphs(t)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new Rr(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Ar(0,this.getScoreHeight(-.5),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new Ir(0,0))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new on(0,0,2*this.scale)),this._startSpacing=!0)}createKeySignatureGlyphs(){let e=0,t=this.bar.masterBar.keySignature,s=this.bar.previousBar?this.bar.previousBar.masterBar.keySignature:0;switch(this.bar.clef){case r.Neutral:e=0;break;case r.G2:e=1;break;case r.F4:e=2;break;case r.C3:e=-1;break;case r.C4:e=1}let i=new Map,a=[];if(ke.keySignatureIsSharp(t))for(let s=0;s<Math.abs(t);s++){let t=vn.SharpKsSteps[s]+e;a.push(new Lr(0,this.getScoreY(t),re.Sharp,!1)),i.set(t,!0)}else for(let s=0;s<Math.abs(t);s++){let t=vn.FlatKsSteps[s]+e;a.push(new Lr(0,this.getScoreY(t),re.Flat,!1)),i.set(t,!0)}let n=Math.abs(s),o=ke.keySignatureIsSharp(s)?vn.SharpKsSteps:vn.FlatKsSteps;for(let t=0;t<n;t++){let s=o[t]+e;i.has(s)||this.addPreBeatGlyph(new Lr(0,this.getScoreY(o[t]+e),re.Natural,!1))}for(let e of a)this.addPreBeatGlyph(e)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new on(0,0,5*this.scale));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new bn(0,this.getScoreY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,s=e.beats.length;t<s;t++){let s=e.beats[t],i=new kn(s,this.getVoiceContainer(e));i.preNotes=new gn,i.onNotes=new un,this.addBeatGlyph(i)}}getNoteLine(e){return this.accidentalHelper.getNoteLine(e)}getScoreY(e){return this._firstLineY+this.lineOffset+this.getScoreHeight(e)}getScoreHeight(e){return this.lineOffset/2*e}paintBackground(e,t,s){super.paintBackground(e,t,s);let i=this.resources;s.color=i.staffLineColor;for(let i=0;i<this.bar.staff.standardNotationLineCount;i++){const a=t+this.y+this.getScoreY(2*i);s.fillRect(e+this.x,0|a,this.width,this.scale*ma.StaffLineThickness)}s.color=i.mainGlyphColor,this.paintSimileMark(e,t,s)}completeBeamingHelper(e){if(this.bar.isMultiVoice&&e.highestNoteInHelper&&e.lowestNoteInHelper){let t=this.getNoteY(e.highestNoteInHelper,ne.Center),s=this.getNoteY(e.lowestNoteInHelper,ne.Center),i=this.getStemSize(e);e.hasTuplet&&(i+=2*this.resources.effectFont.size),e.direction==H.Up?t-=i:s+=i;for(const i of e.beats)this.helpers.collisionHelper.reserveBeatSlot(i,t,s)}}}vn.StaffId="score",vn.SharpKsSteps=[-1,2,-2,1,4,0,3],vn.FlatKsSteps=[3,0,4,1,5,2,6];class xn extends ia{get staffId(){return vn.StaffId}create(e,t){return new vn(e,t)}constructor(){super()}}class Nn extends Ci{constructor(e,t,s,i){super(0,0),this._inType=e,this._outType=t,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.paintSlideOut(e,t,s)}paintSlideIn(e,t,s){let i=this.renderer,a=12*this.scale,r=3*this.scale,n=0,o=0,h=0,l=0;switch(this._inType){case b.IntoFromBelow:h=e+i.x+i.getNoteX(this._startNote,oe.Left),l=t+i.y+i.getNoteY(this._startNote,ne.Center),n=h-a,o=t+i.y+i.getNoteY(this._startNote,ne.Center)+r;break;case b.IntoFromAbove:h=e+i.x+i.getNoteX(this._startNote,oe.Left),l=t+i.y+i.getNoteY(this._startNote,ne.Center),n=h-a,o=t+i.y+i.getNoteY(this._startNote,ne.Center)-r;break;default:return}this.paintSlideLine(s,!1,n,h,o,l)}paintSlideOut(e,t,s){let i=this.renderer,a=12*this.scale,r=3*this.scale,n=0,o=0,h=0,l=0,c=!1;const d=2*this.scale;switch(this._outType){case S.Shift:case S.Legato:if(n=e+i.x+i.getBeatX(this._startNote.beat,ae.PostNotes),o=t+i.y+i.getNoteY(this._startNote,ne.Center),this._startNote.slideTarget){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(h=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,ae.OnNotes)-d,l=t+s.y+s.getNoteY(this._startNote.slideTarget,ne.Center)):(h=e+i.x+this._parent.x,l=o),this._startNote.slideTarget.fret>this._startNote.fret?(o+=r,l-=r):(o-=r,l+=r)}else h=e+i.x+this._parent.x,l=o;break;case S.OutUp:n=e+i.x+i.getNoteX(this._startNote,oe.Right),o=t+i.y+i.getNoteY(this._startNote,ne.Center),h=n+a-d,l=t+i.y+i.getNoteY(this._startNote,ne.Center)-r;break;case S.OutDown:n=e+i.x+i.getNoteX(this._startNote,oe.Right),o=t+i.y+i.getNoteY(this._startNote,ne.Center),h=n+a-d,l=t+i.y+i.getNoteY(this._startNote,ne.Center)+r;break;case S.PickSlideDown:n=e+i.x+i.getNoteX(this._startNote,oe.Right),o=t+i.y+i.getNoteY(this._startNote,ne.Center),h=e+i.x+i.getBeatX(this._startNote.beat,ae.EndBeat),l=o+3*r,c=!0;break;case S.PickSlideUp:n=e+i.x+i.getNoteX(this._startNote,oe.Right),o=t+i.y+i.getNoteY(this._startNote,ne.Center),h=e+i.x+i.getBeatX(this._startNote.beat,ae.EndBeat),l=o-3*r,c=!0;break;default:return}this.paintSlideLine(s,c,n,h,o,l)}paintSlideLine(e,t,s,i,a,r){if(t){let t=new sr(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 Pn extends zr{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?H.Up:Pn.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?H.Up:H.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,ne.Center):this.tieDirection===H.Up?this.startNoteRenderer.getNoteY(this.startNote,ne.Top):this.startNoteRenderer.getNoteY(this.startNote,ne.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20*this.scale:this.startNoteRenderer.getNoteX(this.startNote,oe.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,oe.Left):this.endNoteRenderer.getNoteX(this.endNote,oe.Center)}}class En extends Pn{constructor(e,t,s,i=!1){super(e,t,i),this._direction=Pn.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!==Pn.getBeamDirectionForNote(e))return!1;switch(this._direction){case H.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 H.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 Cn extends Di{constructor(e,t){super(e,t),this._bend=null,this._effectSlurs=[]}doLayout(){this._effectSlurs=[],super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(!e.isVisible)return;let t=this.renderer;if(e.isTieOrigin&&t.showTiedNotes&&e.tieDestination.isVisible){let t=new Pn(e,e.tieDestination,!1);this.ties.push(t)}if(e.isTieDestination&&t.showTiedNotes){let t=new Pn(e.tieOrigin,e,!0);this.ties.push(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new Pn(e,e,!1);this.ties.push(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 En(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.ties.push(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 En(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.ties.push(t)}}if(e.slideInType!==b.None||e.slideOutType!==S.None){let t=new Nn(e.slideInType,e.slideOutType,e,this);this.ties.push(t)}if(e.hasBend){if(!this._bend){const e=new an;this._bend=e,e.renderer=this.renderer,this.ties.push(e)}this._bend.addBends(e)}}}class Fn extends Ci{constructor(e,t,s){super(e,t),this._noteString=null,this._trillNoteString=null,this._trillNoteStringWidth=0,this.isEmpty=!1,this.noteStringWidth=0,this._note=s}doLayout(){let e=this._note,t=e.fret-e.beat.voice.bar.staff.transpositionPitch;if(e.harmonicType===m.Natural&&0!==e.harmonicValue&&(t=e.harmonicValue-e.beat.voice.bar.staff.transpositionPitch),e.isTieDestination)0===e.beat.index&&this.renderer.settings.notation.notationMode==T.GuitarPro||(e.bendType===l.Bend||e.bendType===l.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(k.TabNotesOnTiedBends)?this._noteString="("+(e.tieOrigin.fret-e.beat.voice.bar.staff.transpositionPitch).toString()+")":this._noteString="";else if(this._noteString=e.isDead?"x":t.toString(),e.isGhost)this._noteString="("+this._noteString+")";else if(e.harmonicType===m.Natural){let e=this._noteString.indexOf(String.fromCharCode(46));e>=0&&(this._noteString=this._noteString.substr(0,e+2)),this._noteString="<"+this._noteString+">"}if(e.isTrill)this._trillNoteString="("+(e.trillFret-e.beat.voice.bar.staff.transpositionPitch).toString()+")";else if(ke.isAlmostEqualTo(e.harmonicValue,0))this._trillNoteString="";else switch(e.harmonicType){case m.Artificial:case m.Pinch:case m.Tap:case m.Semi:case m.Feedback:let s=(t+e.harmonicValue).toString(),i=s.indexOf(String.fromCharCode(46));i>=0&&(s=s.substr(0,i+2)),this._trillNoteString="<"+s+">";break;default:this._trillNoteString=""}if(this.isEmpty=!this._noteString,!this.isEmpty){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.tablatureFont,this.noteStringWidth=this.renderer.scoreRenderer.canvas.measureText(this._noteString)*this.scale,this.width=this.noteStringWidth,this.height=this.renderer.scoreRenderer.canvas.font.size,!!this._trillNoteString&&(this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,this._trillNoteStringWidth=3*this.scale+this.renderer.scoreRenderer.canvas.measureText(this._trillNoteString),this.width+=this._trillNoteStringWidth)}}paint(e,t,s){if(this.isEmpty)return;let i=this.noteStringWidth+this._trillNoteStringWidth,a=e+this.x+(this.width-i)/2,r=this.renderer.scoreRenderer.canvas.font;this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,s.fillText(this._trillNoteString,a+this.noteStringWidth+3*this.scale,t+this.y),this.renderer.scoreRenderer.canvas.font=r,s.fillText(this._noteString,a,t+this.y)}buildBoundingsLookup(e,t,s){let i=new gi;i.note=this._note,i.noteHeadBounds=new at,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,this.renderer.scoreRenderer.boundsLookup.addNote(i)}}class Ln extends Ci{constructor(e,t,s){super(e,t),this._notes=[],this.minStringNote=null,this.beatEffects=new Map,this.notesPerString=new Map,this.noteStringWidth=0,this._isGrace=s}buildBoundingsLookup(e,t,s){for(const i of this._notes)i.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteX(e,t){if(this.notesPerString.has(e.string)){let s=this.notesPerString.get(e.string),i=this.x+s.x;switch(t){case oe.Left:break;case oe.Center:i+=s.noteStringWidth/2;break;case oe.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 ne.Top:case ne.TopWithStem:i-=s.height/2+2*this.scale;break;case ne.Center:break;case ne.Bottom:case ne.BottomWithStem:i+=s.height/2}return i}return 0}doLayout(){let e=0,t=0;for(let s=0,i=this._notes.length;s<i;s++){let i=this._notes[s];i.renderer=this.renderer,i.doLayout(),i.width>e&&(e=i.width),i.noteStringWidth>t&&(t=i.noteStringWidth)}this.noteStringWidth=t;let s=this.renderer.resources.tablatureFont.size,i=this.getNoteY(this.minStringNote,ne.Center)+s/2,a=7*this.scale;for(const e of this.beatEffects.values())e.y+=i,e.x+=this.width/2,e.renderer=this.renderer,i+=a,e.doLayout();this.width=e}addNoteGlyph(e,t){this._notes.push(e),this.notesPerString.set(t.string,e),(!this.minStringNote||t.string<this.minStringNote.string)&&(this.minStringNote=t)}paint(e,t,s){e+=this.x,t+=this.y;let i=this.renderer.resources,a=s.textBaseline;s.textBaseline=E.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 Mn extends Li{constructor(e,t,s,i){super(e,t,1,Kr.getSymbol(i)),this._isVisibleRest=s,this._duration=i}doLayout(){this._isVisibleRest?this.width=Kr.getSize(this._duration)*this.scale:this.width=10*this.scale}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){this._isVisibleRest&&super.paint(e,t,s)}}class In extends Ba{constructor(){super(...arguments),this.noteNumbers=null,this.restGlyph=null}getNoteX(e,t){return this.noteNumbers?this.noteNumbers.getNoteX(e,t):0}getNoteY(e,t){return this.noteNumbers?this.noteNumbers.getNoteY(e,t):0}buildBoundingsLookup(e,t,s){this.noteNumbers&&this.noteNumbers.buildBoundingsLookup(e,t+this.x,s+this.y)}doLayout(){let e=this.renderer;if(this.container.beat.isRest){let t=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),s=e.getTabY(t);const i=new Mn(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 on(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new Vr(0,s,1.5*this.scale))}}else{let t=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==g.None;const s=new Ln(0,0,t);this.noteNumbers=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper;for(let e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);if(this.addGlyph(s),this.container.beat.hasWhammyBar){let e=new rn(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!this.noteNumbers.beatEffects.has("tremolo")){let e=0,t=this.container.beat.tremoloSpeed;switch(t){case u.ThirtySecond:e=10;break;case u.Sixteenth:e=5;break;case u.Eighth:e=0}this.noteNumbers.beatEffects.set("tremolo",new Qr(5*this.scale,e*this.scale,t))}if(this.container.beat.dots>0&&e.settings.notation.rhythmMode!==_.Hidden){this.addGlyph(new on(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++)this.addGlyph(new Vr(0,e.lineOffset*e.bar.staff.tuning.length+e.settings.notation.rhythmHeight*e.scale,1.5*this.scale))}}if(!this.glyphs)return;let t=0;for(let e=0,s=this.glyphs.length;e<s;e++){let s=this.glyphs[e];s.x=t,s.renderer=this.renderer,s.doLayout(),t+=s.width}this.width=t,this.computedWidth=t,this.container.beat.isEmpty?this.centerX=this.width/2:this.container.beat.isRest?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.centerX=this.noteNumbers.x+this.noteNumbers.noteStringWidth/2}updateBeamingHelper(){this.container.beat.isRest?this.restGlyph.updateBeamingHelper(this.container.x+this.x):this.noteNumbers.updateBeamingHelper(this.container.x+this.x)}createNoteGlyph(e){let t=this.renderer,s=new Fn(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 Dn extends Ci{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10*this.scale}paint(e,t,s){let i=this.renderer,a=t+this.x+i.getNoteY(this._beat.maxNote,ne.Top),r=t+this.y+i.getNoteY(this._beat.minNote,ne.Bottom),n=e+this.x+this.width/2|0,o=8*this.scale;if(this._beat.brushType!==c.None){if(this._beat.brushType===c.BrushUp||this._beat.brushType===c.BrushDown)s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke();else if(this._beat.brushType===c.ArpeggioUp){let t=new sr(0,0,w.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let i=a,n=r-o;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4*this.scale,n,-90),t.paint(0,-t.height/2,s),s.endRotate()}else if(this._beat.brushType===c.ArpeggioDown){let t=new sr(0,0,w.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let i=a+o,n=r;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4*this.scale,i,90),t.paint(0,-t.height/2,s),s.endRotate()}this._beat.brushType===c.BrushUp||this._beat.brushType===c.ArpeggioUp?(s.beginPath(),s.moveTo(n,r),s.lineTo(n+o/2,r-o),s.lineTo(n-o/2,r-o),s.closePath(),s.fill()):(s.beginPath(),s.moveTo(n,a),s.lineTo(n+o/2,a+o),s.lineTo(n-o/2,a+o),s.closePath(),s.fill())}}}class Rn extends _a{doLayout(){this.container.beat.brushType===c.None||this.container.beat.isRest||(this.addGlyph(new Dn(this.container.beat)),this.addGlyph(new on(0,0,4*this.scale))),super.doLayout()}constructor(){super()}}class An extends Ci{constructor(e,t){super(e,t)}doLayout(){this.width=28*this.scale}paint(e,t,s){let i=this.renderer.bar.staff.tuning.length,a=i<=4?N.FourStringTabClef:N.SixStringTabClef,r=i<=4?i/4.5:i/6.5;s.fillMusicFontSymbol(e+this.x+5*this.scale,t+this.y,r*this.scale,a,!1)}}class On extends yn{get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?Mi.GraceScale:1}}class Gn extends ma{constructor(e,t){super(e,t),this._firstLineY=0,this._tupletSize=0,this.showTimeSignature=!1,this.showRests=!1,this.showTiedNotes=!1,this._startSpacing=!1}get lineOffset(){return(Gn.TabLineSpacing+1)*this.scale}updateSizes(){let e=this.resources,t=(e.tablatureFont.size/2+.2*e.tablatureFont.size)*this.scale;this.topPadding=t,this.bottomPadding=t,this.height=this.lineOffset*(this.bar.staff.tuning.length-1)+2*t,this.settings.notation.rhythmMode!==_.Hidden&&(this.height+=this.settings.notation.rhythmHeight*this.settings.display.scale,this.bottomPadding+=this.settings.notation.rhythmHeight*this.settings.display.scale),this.updateFirstLineY(),super.updateSizes()}updateFirstLineY(){let e=this.resources;this._firstLineY=(e.tablatureFont.size/2+.2*e.tablatureFont.size)*this.scale}doLayout(){if(this.updateFirstLineY(),super.doLayout(),this.settings.notation.rhythmMode!==_.Hidden){let e=!1;for(let t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}e&&(this._tupletSize=.8*this.resources.effectFont.size,this.registerOverflowBottom(this._tupletSize))}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Or(0,0,1.5,3)),this.isFirstOfLine){let e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new An(5*this.scale,this.getTabY(e)))}this.showTimeSignature&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new Mr(0,this.getTabHeight(-.5),this.bar.index+1))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new on(0,0,2*this.scale)),this._startSpacing=!0)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new on(0,0,5*this.scale));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new On(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,s=e.beats.length;t<s;t++){let s=e.beats[t],i=new Cn(s,this.getVoiceContainer(e));i.preNotes=new Rn,i.onNotes=new In,this.addBeatGlyph(i)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new Rr(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Ar(0,this.getTabY(-1),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new Ir(0,0))}getTabY(e){return this._firstLineY+this.getTabHeight(e)}getTabHeight(e){return this.lineOffset*e}get middleYPosition(){return this.getTabY(this.bar.staff.tuning.length-1)}paintBackground(e,t,s){super.paintBackground(e,t,s);let i=this.resources;s.color=i.staffLineColor;let a=this.scale,r=[];for(let e=0,t=this.bar.staff.tuning.length;e<t;e++)r.push([]);for(let e of this.bar.voices)if(this.hasVoiceContainer(e)){let t=this.getVoiceContainer(e);for(let e of t.beatGlyphs){let s=e.onNotes,i=s.noteNumbers;if(i)for(const[n,o]of i.notesPerString)o.isEmpty||r[this.bar.staff.tuning.length-n].push(new Float32Array([t.x+e.x+s.x+i.x,i.width+a]))}}for(let e of r)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));for(let i=0,a=this.bar.staff.tuning.length;i<a;i++){const a=this.getTabY(i);let n=0;for(let o of r[i])s.fillRect(e+this.x+n,t+this.y+a|0,o[0]-n,this.scale*ma.StaffLineThickness),n=o[0]+o[1];s.fillRect(e+this.x+n,t+this.y+a|0,this.width-n,this.scale*ma.StaffLineThickness)}s.color=i.mainGlyphColor,this.paintSimileMark(e,t,s)}paint(e,t,s){super.paint(e,t,s),this.settings.notation.rhythmMode!==_.Hidden&&(this.paintBeams(e,t,s),this.paintTuplets(e,t,s))}paintBeams(e,t,s){for(let i=0,a=this.helpers.beamHelpers.length;i<a;i++){let a=this.helpers.beamHelpers[i];for(let i=0,r=a.length;i<r;i++){let r=a[i];this.paintBeamHelper(e+this.beatGlyphsStart,t,s,r)}}}paintTuplets(e,t,s){for(let i of this.bar.voices)if(this.hasVoiceContainer(i)){let a=this.getVoiceContainer(i);for(let i of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,i)}}paintBeamHelper(e,t,s,i){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(1===i.beats.length||this.settings.notation.rhythmMode===_.ShowWithBeams?this.paintFooter(e,t,s,i):this.paintBar(e,t,s,i))}paintBar(e,t,s,i){for(let a=0,r=i.beats.length;a<r;a++){let r=i.beats[a];if(i.hasBeatLineX(r)){let n=i.getBeatLineX(r),o=t+this.y,h=t+this.y+this.height-this._tupletSize,l=this.getOnNotesGlyphForBeat(r);l.noteNumbers&&r.duration!==u.Half?o+=l.noteNumbers.getNoteY(l.noteNumbers.minStringNote,ne.Bottom)+this.lineOffset/2:o+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(r,t+this.y,e+this.x+n,o,h,s);let c=6*this.scale,d=-6*this.scale,p=3*this.scale,g=ke.getIndex(r.duration)-2,f=h;for(let t=0;t<g;t++){let o=0,h=0,l=0,u=0,g=f+t*d;if(1===i.beats.length)o=n,h=n+c,l=g,u=g,Gn.paintSingleBar(s,e+this.x+o,l,e+this.x+h,u,p);else if(a<i.beats.length-1){if(da.isFullBarJoin(r,i.beats[a+1],t))o=n,h=i.getBeatLineX(i.beats[a+1]);else{if(0!==a&&da.isFullBarJoin(i.beats[a-1],r,t))continue;o=n,h=o+c}l=g,u=g,Gn.paintSingleBar(s,e+this.x+o,l,e+this.x+h,u,p)}else a>0&&!da.isFullBarJoin(r,i.beats[a-1],t)&&(o=n-c,h=n,l=g,u=g,Gn.paintSingleBar(s,e+this.x+o,l,e+this.x+h,u,p))}}}}paintTupletHelper(e,t,s,i){let a,r=this.resources,n=s.textAlign,o=s.textBaseline;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=P.Center,s.textBaseline=E.Middle;let h=i.beats[0].tupletNumerator,l=i.beats[0].tupletDenominator;if(a=2===h&&3===l?"2":3===h&&2===l?"3":4===h&&6===l?"4":5===h&&4===l?"5":6===h&&4===l?"6":7===h&&4===l?"7":9===h&&8===l?"9":10===h&&8===l?"10":11===h&&8===l?"11":12===h&&8===l?"12":13===h&&8===l?"13":h+":"+l,1!==i.beats.length&&i.isFull){let n=i.beats[0],o=i.beats[i.beats.length-1],h=this.helpers.beamHelperLookup[i.voice.index].get(n.index),l=this.helpers.beamHelperLookup[i.voice.index].get(o.index);if(h&&l){let i=h.getBeatLineX(n),c=l.getBeatLineX(o);s.font=r.effectFont;let d=s.measureText(a),u=3*this.scale,p=(i+c)/2,g=p-d/2-u,f=p+d/2+u,m=t+this.y+this.height-this._tupletSize+.5*r.effectFont.size,y=.25*-r.effectFont.size,b=-5*this.scale;s.beginPath(),s.moveTo(e+this.x+i,m-y|0),s.lineTo(e+this.x+i,m-y-b|0),s.lineTo(e+this.x+g,m-y-b|0),s.stroke(),s.beginPath(),s.moveTo(e+this.x+f,m-y-b|0),s.lineTo(e+this.x+c,m-y-b|0),s.lineTo(e+this.x+c,m-y|0),s.stroke(),s.fillText(a,e+this.x+p,m-y-b)}}else for(let n=0,o=i.beats.length;n<o;n++){let o=i.beats[n],h=this.helpers.beamHelperLookup[i.voice.index].get(o.index);if(!h)continue;let l=h.getBeatLineX(o),c=t+this.y+this.height-this._tupletSize+.5*r.effectFont.size;s.font=r.effectFont,s.fillText(a,e+this.x+l,c)}s.textAlign=n,s.textBaseline=o}static paintSingleBar(e,t,s,i,a,r){e.beginPath(),e.moveTo(t,s),e.lineTo(i,a),e.lineTo(i,a-r),e.lineTo(t,s-r),e.closePath(),e.fill()}paintBeamingStem(e,t,s,i,a,r){r.beginPath();let n=[];this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.has(e.displayStart)&&(n=this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.get(e.displayStart).slots.slice(),n.sort(((e,t)=>e.topY-t.topY)));let o=a;for(;o>i;){r.moveTo(s,o);let e=i;if(!(n.length>0&&n[n.length-1].bottomY>e)){r.lineTo(s,e);break}{const i=n.pop();e=t+i.bottomY,r.lineTo(s,e),o=t+i.topY}}r.stroke()}paintFooter(e,t,s,i){for(let a of i.beats){if(a.graceType!==g.None||a.duration===u.Whole||a.duration===u.DoubleWhole||a.duration===u.QuadrupleWhole)return;let r=i.getBeatLineX(a),n=t+this.y,o=t+this.y+this.height-this._tupletSize,h=this.getOnNotesGlyphForBeat(a);if(h.noteNumbers&&a.duration!==u.Half?n+=h.noteNumbers.getNoteY(h.noteNumbers.minStringNote,ne.Bottom):n+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(a,t+this.y,e+this.x+r,n,o,s),a.duration>u.Quarter){let t=new Ii(0,0,a.duration,H.Down,!1);t.renderer=this,t.doLayout(),t.paint(e+this.x+r,o,s)}}}}Gn.StaffId="tab",Gn.TabLineSpacing=10;class Vn extends ia{constructor(e,t,s){super(),this._showTimeSignature=e,this._showRests=t,this._showTiedNotes=s,this.hideOnPercussionTrack=!0}get staffId(){return Gn.StaffId}canCreate(e,t){return t.tuning.length>0&&super.canCreate(e,t)}create(e,t){let s=new Gn(e,t);return s.showRests=this._showRests,s.showTimeSignature=this._showTimeSignature,s.showTiedNotes=this._showTiedNotes,s}}class Hn extends Fi{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+Hn.Padding*this.scale}paint(e,t,s){let i=this.renderer.resources;s.font=i.effectFont;let a=s.textAlign;s.textAlign=P.Center,s.fillText("T",e+this.x,t+this.y+s.font.size/2),s.textAlign=a,s.strokeCircle(e+this.x,t+this.y+s.font.size/2+(Hn.Padding-1)*this.scale,s.font.size/1.6)}}Hn.Padding=4;class Wn extends Ha{get notationElement(){return k.EffectTap}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new Hn}}class zn{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"}(ce||(ce={}));class Un extends zn{constructor(){super(...arguments),this.align=P.Left,this.frame=ce.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class Xn extends zn{constructor(){super(...arguments),this.chord=new Re}}class Yn extends zn{}class qn extends zn{}class Jn extends zn{constructor(){super(...arguments),this.number=0}}class Qn extends zn{constructor(){super(...arguments),this.decrescendo=!1}}class jn extends zn{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class Kn extends zn{constructor(){super(...arguments),this.octave=1}}class $n extends zn{}class Zn{constructor(){this.defaultClef=r.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class eo{constructor(){this.from=0,this.to=0,this.curly=!1}}class to{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class so{constructor(){this._trackChannel=0,this._beamingMode=F.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new Oe,this._voiceStates=new Map}parseXml(e,t){this._galleryObjects=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._voiceCounts=new Map,this._slurs=new Map,this._crescendo=new Map,this._isFirstSystem=!0;let s=new dt;try{s.parse(e)}catch(e){throw new ge("Could not parse XML",e)}this.parseDom(s),this.consolidate(),this.score.finish(t)}consolidate(){let e=this.score.tempo;for(const t of this.score.tracks){const s=this._voiceCounts.get(t.index);for(const i of t.staves){for(;i.bars.length<this.score.masterBars.length;)this.addNewBar(i);for(const t of i.bars){for(;t.voices.length<s;)t.addVoice(new Qe);for(const e of t.voices)if(0===e.beats.length){const t=new De;t.isEmpty=!0,e.addBeat(t)}const i=t.masterBar;i.tempoAutomation&&(i.tempoAutomation.value!==e?e=i.tempoAutomation.value:i.tempoAutomation=null)}}}so.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),so.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?d.Decrescendo:d.Crescendo}))}static applyEffectRange(e,t){for(const[s,i]of e){const e=i.noteRange;let a=s;for(let s=0;s<e;s++)if(t(i,a),a.index+1<a.voice.beats.length)a=a.voice.beats[a.index+1];else{if(!(a.voice.bar.index+1<a.voice.bar.staff.bars.length))break;a=a.voice.bar.staff.bars[a.voice.bar.index+1].voices[a.voice.index].beats[0]}}}parseDom(e){let t=e.firstElement;if(!t)throw new ge("No valid XML");if("score"!==t.localName)throw new ge('Root node of XML was not "score"');this.score=new He,this.score.tempo=120;for(let e of t.childNodes)if(e.nodeType===G.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===G.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 Je,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===G.Element)switch(t.localName){case"bracket":this.parseBracket(t)}}parseBracket(e){const t=new eo;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===G.Element)switch(t.localName){case"staffLayout":this.parseStaffLayout(t)}}parseStaffLayout(e){const t=new Zn;t.description=e.getAttribute("description");for(let s of e.childNodes)if(s.nodeType===G.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===G.Element)switch(t.localName){case"system":this.parseSystem(t)}}parseSystem(e){e.attributes.has("tempo")&&0===this.score.masterBars.length&&(this.score.tempo=parseInt(e.attributes.get("tempo"))),"0"===e.getAttribute("beamGrouping")&&(this._beamingMode=F.ForceSplitToNext);for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"staves":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===G.Element)switch(i.localName){case"staff":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===G.Element)switch(r.localName){case"voices":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===G.Element)switch(n.localName){case"voice":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 me;if(e.bars.length>0?(t.clef=e.bars[e.bars.length-1].clef,t.clefOttava=e.bars[e.bars.length-1].clefOttava):t.clef=this._currentStaffLayout.defaultClef,e.addBar(t),e.bars.length>this.score.masterBars.length){let e=new Oe;this.score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.tripletFeel=e.previousMasterBar.tripletFeel),e.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,e.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,e.timeSignatureCommon=this._timeSignature.timeSignatureCommon}return t}newBar(e,t){this._currentVoiceState.currentBarIndex++,this._currentBar=this.getOrCreateBar(e,this._currentVoiceState.currentBarIndex),this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1),this._currentVoiceState.currentBarComplete=!1,this._currentVoiceState.currentPosition=0,this.ensureVoice(e,t)}parseVoice(e,t,s,i,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 to,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=H.Up;break;case"down":this._currentVoiceState.voiceStemDir=H.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const h=n.findChildElement("noteObjects");if(s.attributes.has("tempo")&&(this._currentBar.masterBar.tempoAutomation=new fe,this._currentBar.masterBar.tempoAutomation.isLinear=!0,this._currentBar.masterBar.tempoAutomation.type=a.Tempo,this._currentBar.masterBar.tempoAutomation.value=parseInt(s.attributes.get("tempo"))),h)for(let e of h.childNodes)if(e.nodeType===G.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;case"dashed":default:this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0}break;case"chord":let s=new De;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 Qe);(!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 Pe;for(let a of t.childNodes)if(a.nodeType===G.Element)switch(a.localName){case"stem":switch(a.getAttribute("dir")){case"up":e.preferredBeamDirection=H.Up;break;case"down":e.preferredBeamDirection=H.Down}break;case"articulation":switch(a.getAttribute("type")){case"staccato":s.isStaccato=!0;break;case"normalAccent":s.accentuated=i.Normal;break;case"strongAccent":s.accentuated=i.Heavy}break;case"lyric":this.parseLyric(e,a);break;case"drawObjects":this.parseBeatDrawObject(e,a);break;case"heads":this.parseHeads(e,s,a);break;case"beam":switch(a.getAttribute("group")){case"force":e.beamingMode=F.ForceMergeWithNext;break;case"divide":e.beamingMode=F.ForceSplitToNext}}}parseHeads(e,t,s){for(let i of s.childNodes)if(i.nodeType===G.Element)switch(i.localName){case"head":this.parseHead(e,t,i)}}parseHead(e,t,s){const i=new Pe,a=ke.parseTuning(s.getAttribute("pitch"));i.octave=a.octave-1,i.tone=a.noteValue,i.isStaccato=t.isStaccato,i.accentuated=t.accentuated,e.addNote(i);for(let e of s.childNodes)if(e.nodeType===G.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===G.Element)switch(s.localName){case"drawObj":const t=this.parseDrawObj(s);if(t)if(t instanceof Un)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new nt,e.fermata.type=O.Medium):"f"===t.text?e.dynamics=p.F:"j"===t.text&&(e.dynamics=p.MF):this._isFirstSystem&&""===this.score.title&&t.align===P.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===P.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===P.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof Xn);else if(t instanceof qn)e.vibrato=w.Slight;else if(t instanceof Qn)e.crescendo=t.decrescendo?d.Decrescendo:d.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof Yn){const s=t;this._slurs.set(e,s)}else t instanceof jn&&this.applyVolta(t)}}parseBarDrawObject(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"drawObj":const e=this.parseDrawObj(t);e&&e instanceof jn&&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===G.Element)switch(s.localName){case"verse":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 De;return s.beamingMode=this._beamingMode,this.parseDuration(e,s,t),s}if(1===parseInt(s)){let e=new De;return e.beamingMode=this._beamingMode,e.duration=u.Whole,e}return Be.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return u.DoubleWhole;case"1/1":return u.Whole;case"1/2":return u.Half;case"1/4":return u.Quarter;case"1/8":return u.Eighth;case"1/16":return u.Sixteenth;case"1/32":return u.ThirtySecond;case"1/64":return u.SixtyFourth;case"1/128":return u.OneHundredTwentyEighth;default:return Be.warning("Importer","Unsupported duration"),u.Quarter}}parseDuration(e,t,s){const i=s.getAttribute("base");t.duration=this.parseDurationValue(i),s.attributes.has("dots")&&(t.dots=parseInt(s.attributes.get("dots")));const a=s.findChildElement("tuplet");if(a){t.tupletNumerator=parseInt(a.getAttribute("count"));const e="true"===a.getAttribute("tripartite")?3:1,s="true"===a.getAttribute("prolong")?0:1;let i=0;for(;e*Math.pow(2,i+s)<t.tupletNumerator;)i++;t.tupletDenominator=e*Math.pow(2,i)}}parsePageObjects(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"drawObj":const e=this.parseDrawObj(t);if(e&&e instanceof Un)switch(e.align){case P.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case P.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"drawObj":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===G.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 $n}parseOctaveClef(e){const t=new Kn;return e.attributes.has("octave")&&(t.octave=parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new jn;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 Qn;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new Jn;return e.attributes.has("number")&&(t.number=parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new qn}parseSlur(e){return new Yn}parseGuitar(e){const t=new Xn,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 Un;switch(e.attributes.has("x")&&(t.x=parseFloat(e.attributes.get("x"))),e.attributes.has("x")&&(t.y=parseFloat(e.attributes.get("y"))),e.getAttribute("align")){case"left":t.align=P.Left;break;case"center":t.align=P.Center;break;case"right":t.align=P.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=ce.Rectangle;break;case"ellipse":t.frame=ce.Ellipse;break;case"circle":t.frame=ce.Circle;break;case"none":t.frame=ce.None}if(e.firstElement){for(let s of e.childNodes)if(s.nodeType===G.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===G.Element)switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class io extends ue{get name(){return"Capella"}constructor(){super()}readScore(){Be.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new xt(this.data).read(),Be.debug(this.name,"Zip entries loaded"),e.length>0)for(let s of e)switch(s.fileName){case"score.xml":t=Ke.toString(s.data,this.settings.importer.encoding)}else this.data.reset(),t=Ke.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new ge("No valid capella file");Be.debug(this.name,"Start Parsing score.xml");try{let e=new so;return e.parseXml(t,this.settings),Be.debug(this.name,"score.xml parsed"),e.score}catch(e){throw new ge("Failed to parse CapXML",e)}}}class ao{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:[]});this._callback(e,this)}}class ro{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)}}class no{constructor(e,t){this.vertical=e,this.createLayout=t}}class oo{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class ho{static createStyleElement(e,t){let s=e.getElementById("alphaTabStyle");if(!s){if(!t)return void Be.error("AlphaTab","Font directory could not be detected, cannot create style element");s=e.createElement("style"),s.id="alphaTabStyle";let i=`\n @font-face {\n font-family: 'alphaTab';\n src: url('${t}Bravura.eot');\n src: url('${t}Bravura.eot?#iefix') format('embedded-opentype')\n , url('${t}Bravura.woff') format('woff')\n , url('${t}Bravura.otf') format('opentype')\n , url('${t}Bravura.svg#Bravura') format('svg');\n font-weight: normal;\n font-style: normal;\n }\n .at-surface * {\n cursor: default;\n vertical-align: top;\n overflow: visible;\n }\n .at-surface-svg text {\n dominant-baseline: central;\n } \n .at {\n font-family: 'alphaTab';\n speak: none;\n font-style: normal;\n font-weight: normal;\n font-variant: normal;\n text-transform: none;\n line-height: 1;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n font-size: ${ho.MusicFontSize}px;\n overflow: visible !important;\n }`;s.innerHTML=i,e.getElementsByTagName("head").item(0).appendChild(s),ho.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===ho._globalThis){try{ho._globalThis=globalThis}catch(e){}void 0===ho._globalThis&&(ho._globalThis=self),void 0===ho._globalThis&&(ho._globalThis=global),void 0===ho._globalThis&&(ho._globalThis=window),void 0===ho._globalThis&&(ho._globalThis=Function("return this")())}return this._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in ho.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in ho.globalThis}static createAlphaTabWorker(e){if(ho.webPlatform===se.BrowserModule){let t=new Blob([`import * as alphaTab from '${e}'`],{type:"text/javascript"});return new Worker(URL.createObjectURL(t),{type:"module"})}{let t=new Blob([`importScripts('${e}')`]);return new Worker(URL.createObjectURL(t))}}static throttle(e,t){let s=0;return()=>{ho.globalThis.clearTimeout(s),s=ho.globalThis.setTimeout(e,t)}}static detectScriptFile(){try{const e=import.meta.url;if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in ho.globalThis&&document.currentScript?document.currentScript.src:null}static registerJQueryPlugin(){if(!ho.isRunningInWorker&&ho.globalThis&&"jQuery"in ho.globalThis){let e=ho.globalThis.jQuery,t=new ea;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:ea.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&ho.renderEngines.has(e)?ho.renderEngines.get(e):ho.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&ho.layoutEngines.has(t)?ho.layoutEngines.get(t):ho.layoutEngines.get(e.Page)}static buildImporters(){return[new tt,new Lt,new Nt,new Mt,new io,new et]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new oo(!0,(()=>new sa))),e.set("default",e.get("svg")),ho.createPlatformSpecificRenderEngines(e),e}static createPlatformSpecificRenderEngines(e){e.set("html5",new oo(!1,(()=>new Si)))}static createDefaultStaveProfiles(){const e=new Map;e.set(t.ScoreTab,[new ka("score-effects",[new nr,new dr,new qa,new or,new Ca,new Ga,new ur,new lr,new Qa(!0),new pr,new tr,new gr,new ir,new Wn,new Na]),new xn,new ka("tab-effects",[new Ma,new Qa(!1),new Da,new Ya,new lr,new pr,new tr,new gr,new ir,new ar,new Aa,new za(m.Natural),new za(m.Artificial),new za(m.Pinch),new za(m.Tap),new za(m.Semi),new za(m.Feedback),new Ua,new Ea,new Va,new ja,new Za,new Ka,new Wn]),new Vn(!1,!1,!1)]),e.set(t.Score,[new ka("score-effects",[new nr,new dr,new qa,new or,new Ca,new Ga,new ur,new lr,new Qa(!0),new pr,new tr,new gr,new ir,new Aa,new Ua,new ja,new Za,new Ka,new Wn,new Na]),new xn,new ka("score-bottom-effects",[new Ma,new Qa(!1),new Da,new Ya])]);let s=[new nr,new dr,new qa,new or,new Ca,new Ga,new lr,new pr,new tr,new gr,new ir,new ar,new Aa,new za(m.Artificial),new za(m.Pinch),new za(m.Tap),new za(m.Semi),new za(m.Feedback),new Ua,new Ea,new Va,new ja,new Za,new Ka,new Wn,new Na];return e.set(t.Tab,[new ka("tab-effects",s),new Vn(!0,!0,!0),new ka("tab-bottom-effects",[new Ya])]),e.set(t.TabMixed,[new ka("tab-effects",s),new Vn(!1,!1,!1),new ka("tab-bottom-effects",[new Ya])]),e}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.Page,new no(!0,(e=>new Fr(e)))),t.set(e.Horizontal,new no(!1,(e=>new Cr(e)))),t}static platformInit(){ho.isRunningInAudioWorklet?ji.init():ho.isRunningInWorker?(bi.init(),hi.init()):ho.webPlatform!==se.Browser&&ho.webPlatform!==se.BrowserModule||(ho.registerJQueryPlugin(),ho.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in ho.globalThis||(ho.globalThis.ResizeObserver=ao),"IntersectionObserver"in ho.globalThis||(ho.globalThis.IntersectionObserver=ro))}static detectWebPlatform(){try{if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return se.NodeJs}catch(e){}try{const e=import.meta.url;if(e&&"string"==typeof e)return se.BrowserModule}catch(e){}return se.Browser}}ho.MusicFontSize=34,ho.HighDpiFactor=1,ho._globalThis=void 0,ho.webPlatform=ho.detectWebPlatform(),ho.scriptFile=ho.detectScriptFile(),ho.bravuraFontChecker=new Wi("alphaTab"),ho.renderEngines=ho.createDefaultRenderEngines(),ho.layoutEngines=ho.createDefaultLayoutEngines(),ho.staveProfiles=ho.createDefaultStaveProfiles(),ho.platformInit();class lo{constructor(){if(this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=v.Info,this.useWorkers=!0,this.includeNoteBounds=!1,!ho.isRunningInWorker&&ho.globalThis.ALPHATAB_ROOT?(this.scriptFile=ho.globalThis.ALPHATAB_ROOT,this.scriptFile=lo.ensureFullUrl(this.scriptFile),this.scriptFile=lo.appendScriptName(this.scriptFile)):this.scriptFile=ho.scriptFile,!ho.isRunningInWorker&&ho.globalThis.ALPHATAB_FONT)this.fontDirectory=ho.globalThis.ALPHATAB_FONT,this.fontDirectory=lo.ensureFullUrl(this.fontDirectory);else if(this.fontDirectory=this.scriptFile,this.fontDirectory){let e=this.fontDirectory.lastIndexOf(String.fromCharCode(47));e>=0&&(this.fontDirectory=this.fontDirectory.substr(0,e)+"/font/")}}static ensureFullUrl(e){var t,s,i;if(!e)return"";if(!e.startsWith("http")&&!e.startsWith("https")&&!e.startsWith("file")){let a="",r=ho.globalThis.location;if(a+=null===(t=r.protocol)||void 0===t?void 0:t.toString(),a+="//".toString(),r.hostname&&(a+=null===(s=r.hostname)||void 0===s?void 0:s.toString()),r.port&&(a+=":".toString(),a+=null===(i=r.port)||void 0===i?void 0:i.toString()),!e.startsWith("/")){let e=r.pathname.split("/").slice(0,-1).join("/");e.length>0&&(e.startsWith("/")||(a+="/".toString()),a+=null==e?void 0:e.toString())}return e.startsWith("/")||(a+="/".toString()),a+=null==e?void 0:e.toString(),a}return e}static appendScriptName(e){return e&&!e.endsWith(".js")&&(e.endsWith("/")||(e+="/"),e+="alphaTab.js"),e}}class co{}co.version="1.3.0-alpha.154",co.date="2022-01-26T00:39:04.884Z";var uo,po=Object.freeze({__proto__:null,ScoreImporter:ue,ScoreLoader:Gi,UnsupportedFormatError:ge});class go{init(e,t){this.data=e,this.settings=t}export(e,t=null){const s=$e.withCapacity(1024);return this.init(s,null!=t?t:new Hs),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"}(uo||(uo={}));class fo{constructor(e,t,s=null){if(this.icon=uo.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 mo{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new dt;return this._rhythmIdLookup=new Map,this.writeDom(t,e),t.toFormattedString("",!0)}writeDom(e,t){const s=e.addElement("GPIF");s.addElement("GPVersion").innerText="7";const i=s.addElement("GPRevision");i.innerText="7",i.attributes.set("required","12021"),i.attributes.set("recommended","12023"),i.innerText="12025",s.addElement("Encoding").addElement("EncodingDescription").innerText="GP7",this.writeScoreNode(s,t),this.writeMasterTrackNode(s,t),this.writeAudioTracksNode(s,t),this.writeTracksNode(s,t),this.writeMasterBarsNode(s,t);const a=s.addElement("Bars"),r=s.addElement("Voices"),n=s.addElement("Beats"),o=s.addElement("Notes"),h=s.addElement("Rhythms");for(const e of t.tracks)for(const t of e.staves)for(const e of t.bars){this.writeBarNode(a,e);for(const t of e.voices){this.writeVoiceNode(r,t);for(const e of t.beats){this.writeBeatNode(n,e,h);for(const t of e.notes)this.writeNoteNode(o,t)}}}}writeNoteNode(e,t){const s=e.addElement("Note");s.attributes.set("id",t.id.toString()),this.writeNoteProperties(s,t),t.isGhost&&(s.addElement("AntiAccent").innerText="normal"),t.isLetRing&&s.addElement("LetRing"),t.isTrill&&(s.addElement("Trill").innerText=t.trillValue.toString());let a=0;switch(t.isStaccato&&(a|=1),t.accentuated){case i.Normal:a|=8;break;case i.Heavy:a|=4}if(a>0&&(s.addElement("Accent").innerText=a.toString()),t.isTieOrigin||t.isTieDestination){const e=s.addElement("Tie");e.attributes.set("origin",t.isTieOrigin?"true":"false"),e.attributes.set("destination",t.isTieDestination?"true":"false")}switch(t.vibrato){case 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"}writeNoteProperties(e,t){const s=e.addElement("Properties");if(this.writeConcertPitch(s,t),this.writeTransposedPitch(s,t),t.isStringed&&(this.writeSimplePropertyNode(s,"String","String",(t.string-1).toString()),this.writeSimplePropertyNode(s,"Fret","Fret",t.fret.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString())),t.isPiano&&(this.writeSimplePropertyNode(s,"Octave","Number",t.octave.toString()),this.writeSimplePropertyNode(s,"Tone","Step",t.tone.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString())),t.beat.tap&&this.writeSimplePropertyNode(s,"Tapped","Enable",null),t.harmonicType!==m.None){switch(t.harmonicType){case m.Natural:this.writeSimplePropertyNode(s,"HarmonicType","HType","Natural");break;case m.Artificial:this.writeSimplePropertyNode(s,"HarmonicType","HType","Artificial");break;case m.Pinch:this.writeSimplePropertyNode(s,"HarmonicType","HType","Pinch");break;case m.Tap:this.writeSimplePropertyNode(s,"HarmonicType","HType","Tap");break;case m.Semi:this.writeSimplePropertyNode(s,"HarmonicType","HType","Semi");break;case m.Feedback:this.writeSimplePropertyNode(s,"HarmonicType","HType","Feedback")}0!==t.harmonicValue&&this.writeSimplePropertyNode(s,"HarmonicFret","HFret",t.harmonicValue.toString())}t.isDead&&this.writeSimplePropertyNode(s,"Muted","Enable",null),t.isPalmMute&&this.writeSimplePropertyNode(s,"PalmMuted","Enable",null),t.hasBend&&this.writeBend(s,t),t.isHammerPullOrigin&&this.writeSimplePropertyNode(s,"HopoOrigin","Enable",null),t.isHammerPullDestination&&this.writeSimplePropertyNode(s,"HopoDestination","Enable",null),t.isLeftHandTapped&&this.writeSimplePropertyNode(s,"LeftHandTapped","Enable",null);let i=0;switch(t.slideInType){case b.IntoFromAbove:i|=32;break;case b.IntoFromBelow:i|=16}switch(t.slideOutType){case S.Shift:i|=1;break;case S.Legato:i|=2;break;case S.OutDown:i|=4;break;case S.OutUp:i|=8;break;case S.PickSlideDown:i|=64;break;case S.PickSlideUp:i|=128}i>0&&this.writeSimplePropertyNode(s,"Slide","Flags",i.toString())}writeTransposedPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"TransposedPitch",t.displayValueWithoutBend,t.accidentalMode)}writeConcertPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"ConcertPitch",t.realValueWithoutHarmonic,t.accidentalMode)}writePitchForValue(e,t,s,i){let a=0,r=0,n="",o="";const h=()=>{a=s%12,r=s/12|0,n=Ye.defaultSteps[a],o=Ye.defaultAccidentals[a]};switch(h(),i){case y.Default:break;case y.ForceNone:case y.ForceNatural:o="";break;case y.ForceSharp:o="#";break;case y.ForceDoubleSharp:"#"===o&&(s-=2,h()),o="x";break;case y.ForceFlat:"#"===o&&(s+=1,h()),o="b";break;case y.ForceDoubleFlat:"#"===o&&(s+=2,h()),o="bb"}this.writePitch(e,t,n,r.toString(),o)}writePitch(e,t,s,i,a){const r=e.addElement("Property");r.attributes.set("name",t);const n=r.addElement("Pitch");n.addElement("Step").innerText=s,n.addElement("Accidental").innerText=a,n.addElement("Octave").innerText=i}writeBend(e,t){t.hasBend&&t.bendPoints.length<=4&&this.writeStandardBend(e,t.bendPoints)}writeStandardBend(e,t){this.writeSimplePropertyNode(e,"Bended","Enable",null);var s,i,a=t[0],r=t[t.length-1];switch(t.length){case 4:s=t[1],i=t[2];break;case 3:s=t[1],i=t[1];break;default:i=s=new be((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/be.MaxPosition*100}writeBeatNode(e,t,s){const i=e.addElement("Beat");if(i.attributes.set("id",t.id.toString()),i.addElement("Dynamic").innerText=p[t.dynamics],t.fadeIn&&(i.addElement("Fadding").innerText="FadeIn"),t.isTremolo)switch(t.tremoloSpeed){case u.Eighth:i.addElement("Tremolo").innerText="1/2";break;case u.Sixteenth:i.addElement("Tremolo").innerText="1/4";break;case u.ThirtySecond:i.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&i.addElement("Chord").setCData(t.chordId),t.crescendo!==d.None&&(i.addElement("Hairpin").innerText=d[t.crescendo]),t.brushType){case c.ArpeggioUp:i.addElement("Arpeggio").innerText="Up";break;case c.ArpeggioDown:i.addElement("Arpeggio").innerText="Down"}switch(t.text&&i.addElement("FreeText").setCData(t.text),t.graceType){case g.OnBeat:case g.BeforeBeat:i.addElement("GraceNotes").innerText=g[t.graceType]}if(t.ottava!==n.Regular&&(i.addElement("Ottavia").innerText=n[t.ottava].substr(1)),t.hasWhammyBar&&this.writeWhammyNode(i,t),t.isLegatoOrigin||t.isLegatoDestination){const e=i.addElement("Legato");e.attributes.set("origin",t.isLegatoOrigin?"true":"false"),e.attributes.set("destination",t.isLegatoDestination?"true":"false")}if(this.writeRhythm(i,t,s),null!==t.preferredBeamDirection)switch(t.preferredBeamDirection){case H.Up:i.addElement("TransposedPitchStemOrientation").innerText="Upward";break;case H.Down:i.addElement("TransposedPitchStemOrientation").innerText="Downward"}i.addElement("ConcertPitchStemOrientation").innerText="Undefined",t.isRest||(i.addElement("Notes").innerText=t.notes.map((e=>e.id)).join(" ")),this.writeBeatProperties(i,t),this.writeBeatXProperties(i,t),t.lyrics&&t.lyrics.length>0&&this.writeBeatLyrics(i,t.lyrics)}writeBeatLyrics(e,t){const s=e.addElement("Lyrics");for(const e of t){s.addElement("Line").setCData(e)}}writeBeatXProperties(e,t){const s=e.addElement("XProperties");t.brushDuration>0&&this.writeSimpleXPropertyNode(s,"687935489","Int",t.brushDuration.toString())}writeBeatProperties(e,t){const s=e.addElement("Properties");switch(t.brushType){case c.BrushUp:this.writeSimplePropertyNode(s,"Brush","Direction","Up");break;case c.BrushDown:this.writeSimplePropertyNode(s,"Brush","Direction","Down")}switch(t.pickStroke){case x.Up:this.writeSimplePropertyNode(s,"PickStroke","Direction","Up");break;case x.Down:this.writeSimplePropertyNode(s,"PickStroke","Direction","Down")}switch(t.slap&&this.writeSimplePropertyNode(s,"Slapped","Enable",null),t.pop&&this.writeSimplePropertyNode(s,"Popped","Enable",null),t.vibrato){case w.Wide:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Wide");break;case w.Slight:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Slight")}}writeRhythm(e,t,s){const i=`${t.duration}_${t.dots}_${t.tupletNumerator}_${t.tupletDenominator}';`;let a;if(this._rhythmIdLookup.has(i))a=this._rhythmIdLookup.get(i);else{a=this._rhythmIdLookup.size.toString(),this._rhythmIdLookup.set(i,a);const e=s.addElement("Rhythm");if(e.attributes.set("id",a),t.hasTuplet){const s=e.addElement("PrimaryTuplet");s.attributes.set("num",t.tupletNumerator.toString()),s.attributes.set("den",t.tupletDenominator.toString())}t.dots>0&&e.addElement("AugmentationDot").attributes.set("count",t.dots.toString());let r="Quarter";switch(t.duration){case u.QuadrupleWhole:r="Long";break;case u.DoubleWhole:r="DoubleWhole";break;case u.Whole:r="Whole";break;case u.Half:r="Half";break;case u.Quarter:r="Quarter";break;case u.Eighth:r="Eighth";break;case u.Sixteenth:r="16th";break;case u.ThirtySecond:r="32nd";break;case u.SixtyFourth:r="64th";break;case u.OneHundredTwentyEighth:r="128th";break;case u.TwoHundredFiftySixth:r="256th"}e.addElement("NoteValue").innerText=r}e.addElement("Rhythm").attributes.set("ref",a)}writeWhammyNode(e,t){t.hasWhammyBar&&t.whammyBarPoints.length<=4&&this.writeStandardWhammy(e,t.whammyBarPoints)}writeStandardWhammy(e,t){const s=e.addElement("Whammy");var i,a,r=t[0],n=t[t.length-1];switch(t.length){case 4:i=t[1],a=t[2];break;case 3:i=t[1],a=t[1];break;default:a=i=new be((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("4"),s.addElement("ScoreSystemsLayout").setCData("4"),s.addElement("ScoreZoomPolicy").innerText="Value",s.addElement("ScoreZoom").innerText="1",s.addElement("MultiVoice").innerText="1>"}writeMasterTrackNode(e,t){const s=e.addElement("MasterTrack");s.addElement("Tracks").innerText=t.tracks.map((e=>e.index)).join(" ");const i=s.addElement("Automations");t.masterBars.length>0&&t.masterBars[0].isAnacrusis&&s.addElement("Anacrusis");const a=i.addElement("Automation");a.addElement("Type").innerText="Tempo",a.addElement("Linear").innerText="false",a.addElement("Bar").innerText="0",a.addElement("Position").innerText="0",a.addElement("Visible").innerText="true",a.addElement("Value").innerText=t.tempo+" 2",t.tempoLabel&&(a.addElement("Text").innerText=t.tempoLabel);for(const e of t.masterBars)if(e.index>0&&e.tempoAutomation){const t=i.addElement("Automation");t.addElement("Type").innerText="Tempo",t.addElement("Linear").innerText=e.tempoAutomation.isLinear?"true":"false",t.addElement("Bar").innerText=e.index.toString(),t.addElement("Position").innerText=e.tempoAutomation.ratioPosition.toString(),t.addElement("Visible").innerText="true",t.addElement("Value").innerText=e.tempoAutomation.value+" 2",e.tempoAutomation.text&&(t.addElement("Text").innerText=e.tempoAutomation.text)}}writeAudioTracksNode(e,t){e.addElement("AudioTracks")}writeTracksNode(e,t){const s=e.addElement("Tracks");for(const e of t.tracks)this.writeTrackNode(s,e)}writeTrackNode(e,t){const s=e.addElement("Track");s.attributes.set("id",t.index.toString()),s.addElement("Name").setCData(t.name),s.addElement("ShortName").setCData(t.shortName),s.addElement("Color").innerText=`${t.color.r} ${t.color.g} ${t.color.b}`,s.addElement("SystemsDefautLayout").innerText="3",s.addElement("SystemsLayout").innerText="1",s.addElement("AutoBrush"),s.addElement("PalmMute").innerText="0",s.addElement("PlayingStyle").innerText=de.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",s.addElement("UseOneChannelPerString"),s.addElement("IconId").innerText=mo.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?mo.DrumKitProgramInfo.icon:mo.MidiProgramInfoLookup.has(e.program)?mo.MidiProgramInfoLookup.get(e.program).icon:uo.SteelGuitar}writeSoundAndAutomation(e,t,s,i,a,r,n,o=0){const h=e.addElement("Sound");h.addElement("Name").setCData(s),h.addElement("Label").setCData(s),h.addElement("Path").setCData(i),h.addElement("Role").setCData(a);const l=h.addElement("MIDI");l.addElement("LSB").innerText="0",l.addElement("MSB").innerText="0",l.addElement("Program").innerText=n.toString();const c=t.addElement("Automation");c.addElement("Type").innerText="Sound",c.addElement("Linear").innerText="false",c.addElement("Bar").innerText=r.toString(),c.addElement("Position").innerText=o.toString(),c.addElement("Visible").innerText="true",c.addElement("Value").setCData(`${i};${s};${a}`)}writeSoundsAndAutomations(e,t){const s=e.addElement("Sounds"),i=e.addElement("Automations");if(t.staves.length>0&&t.staves[0].bars.length>0){const e=`Track_${t.index}_Initial`,r="Midi/"+t.playbackInfo.program,n="Factory";let o=!1;for(const h of t.staves)for(const l of h.bars)for(const h of l.voices)for(const c of h.beats){const h=c.getAutomation(a.Instrument),d=0===l.index&&0===c.index;if(h){const a=d?e:"ProgramChange_"+c.id,u=d?r:"Midi/"+h.value,p=d?n:"User";d||o||(this.writeSoundAndAutomation(s,i,e,r,n,t.staves[0].bars[0].index,t.playbackInfo.program),o=!0),this.writeSoundAndAutomation(s,i,a,u,p,l.index,h.value,h.ratioPosition),d&&(o=!0)}}}}writeMidiConnectionNode(e,t){const s=e.addElement("MidiConnection");s.addElement("Port").innerText=t.playbackInfo.port.toString(),s.addElement("PrimaryChannel").innerText=t.playbackInfo.primaryChannel.toString(),s.addElement("SecondaryChannel").innerText=t.playbackInfo.secondaryChannel.toString(),s.addElement("ForeOneChannelPerString").innerText="false"}writeRseNode(e,t){const s=e.addElement("RSE").addElement("ChannelStrip");s.attributes.set("version","E56");s.addElement("Parameters").innerText=`0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1 0.5 ${t.playbackInfo.balance/16} ${t.playbackInfo.volume/16} 0.5 0.5 0.5`}writeStavesNode(e,t){const s=e.addElement("Staves");for(const e of t.staves)this.writeStaffNode(s,e)}writeStaffNode(e,t){const s=e.addElement("Staff").addElement("Properties");if(this.writeSimplePropertyNode(s,"CapoFret","Fret",t.capo.toString()),this.writeSimplePropertyNode(s,"FretCount","Fret","24"),t.tuning.length>0){const e=s.addElement("Property");switch(e.attributes.set("name","Tuning"),e.addElement("Pitches").innerText=t.tuning.slice().reverse().join(" "),e.addElement("Label").setCData(t.tuningName),e.addElement("LabelVisible").innerText=t.tuningName?"true":"false",e.addElement("Flat"),t.tuning.length){case 3:e.addElement("Instrument").innerText="Shamisen";break;case 4:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":42==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Cello":43==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Contrabass":40==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Violin":41==t.track.playbackInfo.program?e.addElement("Instrument").innerText="Viola":e.addElement("Instrument").innerText="Bass";break;case 5:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":e.addElement("Instrument").innerText="Bass";break;case 6:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;case 7:t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;default:e.addElement("Instrument").innerText="Guitar"}}this.writeSimplePropertyNode(s,"PartialCapoFret","Fret","0"),this.writeSimplePropertyNode(s,"PartialCapoStringFlags","Bitset",t.tuning.map((e=>"0")).join("")),this.writeSimplePropertyNode(s,"TuningFlat","Enable",null),this.writeDiagramCollection(s,t,"DiagramCollection"),this.writeDiagramCollection(s,t,"DiagramWorkingSet")}writeDiagramCollection(e,t,s){const i=e.addElement("Property");i.attributes.set("name",s);const a=i.addElement("Items"),r=t.chords;if(r)for(const[e,t]of r){const s=a.addElement("Item");s.attributes.set("id",e),s.attributes.set("name",t.name);const i=s.addElement("Diagram");i.attributes.set("stringCount",t.strings.length.toString()),i.attributes.set("fretCount","5"),i.attributes.set("baseFret",(t.firstFret-1).toString()),i.attributes.set("barStates",t.strings.map((e=>"1")).join(" "));const r=[],n=new Map;for(let e=0;e<t.strings.length;e++){let s=t.strings[e];if(-1!==s){const a=i.addElement("Fret"),o=t.strings.length-1-e;a.attributes.set("string",o.toString()),a.attributes.set("fret",(s-t.firstFret+1).toString()),n.has(s)||(n.set(s,[]),r.push(s)),n.get(s).push(o)}}r.sort();const o=i.addElement("Fingering");if(t.barreFrets.length>0){const e=[f.LittleFinger,f.AnnularFinger,f.MiddleFinger,f.IndexFinger];for(const s of r){const i=n.get(s);if(i.length>1&&t.barreFrets.indexOf(s)>=0){const a=e.length>0?e.pop():f.IndexFinger;for(const e of i){const i=o.addElement("Position");switch(a){case f.LittleFinger:i.attributes.set("finger","Pinky");break;case f.AnnularFinger:i.attributes.set("finger","Ring");break;case f.MiddleFinger:i.attributes.set("finger","Middle");break;case f.IndexFinger:i.attributes.set("finger","Index")}i.attributes.set("fret",(s-t.firstFret+1).toString()),i.attributes.set("string",e.toString())}}}}const h=i.addElement("Property");h.attributes.set("name","ShowName"),h.attributes.set("type","bool"),h.attributes.set("value",t.showName?"true":"false");const l=i.addElement("Property");l.attributes.set("name","ShowDiagram"),l.attributes.set("type","bool"),l.attributes.set("value",t.showDiagram?"true":"false");const c=i.addElement("Property");c.attributes.set("name","ShowFingering"),c.attributes.set("type","bool"),c.attributes.set("value",t.showFingering?"true":"false");const d=i.addElement("Chord"),u=d.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=d.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=d.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const m=d.addElement("Degree");m.attributes.set("interval","Fifth"),m.attributes.set("alteration","Perfect"),m.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,s,i){const a=e.addElement("Property");a.attributes.set("name",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeSimpleXPropertyNode(e,t,s,i){const a=e.addElement("XProperty");a.attributes.set("id",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeLyricsNode(e,t){const s=e.addElement("Lyrics");s.attributes.set("dispatched","true");let i=[];for(const e of t.staves[0].bars)for(const t of e.voices)if(!t.isEmpty)for(const s of t.beats)if(s.lyrics)for(let t=0;t<s.lyrics.length;t++){for(;t>=i.length;){const t=new Ae;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(xe.instrumentArticulations.values());s.addElement("Name").innerText=mo.DrumKitProgramInfo.instrumentSetName,s.addElement("Type").innerText=mo.DrumKitProgramInfo.instrumentSetType;let i="",r=new ot,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 E.Top:e.addElement("TechniquePlacement").innerText="below";break;case E.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case E.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=mo.MidiProgramInfoLookup.has(t.playbackInfo.program)?mo.MidiProgramInfoLookup.get(t.playbackInfo.program):mo.MidiProgramInfoLookup.get(0);s.addElement("Name").innerText=e.instrumentSetName,s.addElement("Type").innerText=e.instrumentSetType;const i=s.addElement("Elements").addElement("Element");i.addElement("Pitched").innerText="Pitched",i.addElement("Type").innerText="pitched",i.addElement("SoundbankName").innerText="";const a=i.addElement("Articulations").addElement("Articulation");a.addElement("Name").innerText="",a.addElement("StaffLine").innerText="0",a.addElement("Noteheads").innerText="noteheadBlack noteheadHalf noteheadWhole",a.addElement("TechniquePlacement").innerText="outside",a.addElement("TechniqueSymbol").innerText="",a.addElement("InputMidiNumbers").innerText="",a.addElement("OutputRSESound").innerText="",a.addElement("OutputMidiNumber").innerText="0"}}mapMusicSymbol(e){if(e===N.None)return"";let t=N[e];return t.substring(0,1).toLowerCase()+t.substring(1)}writeMasterBarsNode(e,t){const s=e.addElement("MasterBars");for(const e of t.masterBars)this.writeMasterBarNode(s,e)}writeMasterBarNode(e,t){const s=e.addElement("MasterBar"),i=s.addElement("Key");i.addElement("AccidentalCount").innerText=t.keySignature.toString(),i.addElement("Mode").innerText=I[t.keySignatureType],i.addElement("Sharps").innerText="Sharps",s.addElement("Time").innerText=`${t.timeSignatureNumerator}/${t.timeSignatureDenominator}`;let a=[];for(const e of t.score.tracks)for(const s of e.staves)a.push(s.bars[t.index].id.toString());if(s.addElement("Bars").innerText=a.join(" "),t.isDoubleBar&&s.addElement("DoubleBar"),t.isSectionStart){const e=s.addElement("Section");e.addElement("Letter").setCData(t.section.marker),e.addElement("Text").setCData(t.section.text)}if(t.isRepeatStart||t.isRepeatEnd){const e=s.addElement("Repeat");e.attributes.set("start",t.isRepeatStart?"true":"false"),e.attributes.set("end",t.isRepeatEnd?"true":"false"),t.isRepeatEnd&&e.attributes.set("count",t.repeatCount.toString())}if(t.alternateEndings>0){let e=t.alternateEndings;const i=[];let a=0;for(;e>0;)1==(e>>a&1)&&(i.push(a+1),e&=~(1<<a)),a++;s.addElement("AlternateEndings").innerText=i.join(" ")}t.tripletFeel!==D.NoTripletFeel&&(s.addElement("TripletFeel").innerText=D[t.tripletFeel]),this.writeFermatas(s,t)}writeFermatas(e,t){var s,i;const a=null!==(i=null===(s=t.fermata)||void 0===s?void 0:s.size)&&void 0!==i?i:0;if(0!==a&&a>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/ye.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=O[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(" ")}}mo.MidiProgramInfoLookup=new Map([[0,new fo(uo.Piano,"Acoustic Piano")],[1,new fo(uo.Piano,"Acoustic Piano")],[2,new fo(uo.Piano,"Electric Piano")],[3,new fo(uo.Piano,"Acoustic Piano")],[4,new fo(uo.Piano,"Electric Piano")],[5,new fo(uo.Piano,"Electric Piano")],[6,new fo(uo.Piano,"Harpsichord")],[7,new fo(uo.Piano,"Harpsichord")],[8,new fo(uo.PitchedIdiophone,"Celesta")],[9,new fo(uo.PitchedIdiophone,"Vibraphone")],[10,new fo(uo.PitchedIdiophone,"Vibraphone")],[11,new fo(uo.PitchedIdiophone,"Vibraphone")],[12,new fo(uo.PitchedIdiophone,"Xylophone")],[13,new fo(uo.PitchedIdiophone,"Xylophone")],[14,new fo(uo.PitchedIdiophone,"Vibraphone")],[15,new fo(uo.Banjo,"Banjo")],[16,new fo(uo.Piano,"Electric Organ")],[17,new fo(uo.Piano,"Electric Organ")],[18,new fo(uo.Piano,"Electric Organ")],[19,new fo(uo.Piano,"Electric Organ")],[20,new fo(uo.Piano,"Electric Organ")],[21,new fo(uo.Piano,"Electric Organ")],[22,new fo(uo.Woodwind,"Recorder")],[23,new fo(uo.Piano,"Electric Organ")],[24,new fo(uo.ClassicalGuitar,"Nylon Guitar")],[25,new fo(uo.SteelGuitar,"Steel Guitar")],[26,new fo(uo.SteelGuitar,"Electric Guitar")],[27,new fo(uo.ElectricGuitar,"Electric Guitar")],[28,new fo(uo.ElectricGuitar,"Electric Guitar")],[29,new fo(uo.ElectricGuitar,"Electric Guitar")],[30,new fo(uo.SteelGuitar,"Electric Guitar")],[31,new fo(uo.SteelGuitar,"Electric Guitar")],[32,new fo(uo.Bass,"Acoustic Bass")],[33,new fo(uo.Bass,"Electric Bass")],[34,new fo(uo.Bass,"Electric Bass")],[35,new fo(uo.Bass,"Acoustic Bass")],[36,new fo(uo.Bass,"Electric Bass")],[37,new fo(uo.Bass,"Electric Bass")],[38,new fo(uo.Synth,"Synth Bass")],[39,new fo(uo.Synth,"Synth Bass")],[40,new fo(uo.Strings,"Violin")],[41,new fo(uo.Strings,"Viola")],[42,new fo(uo.Strings,"Cello")],[43,new fo(uo.Strings,"Contrabass")],[44,new fo(uo.Strings,"Violin")],[45,new fo(uo.Strings,"Violin")],[46,new fo(uo.Piano,"Harp")],[47,new fo(uo.Membraphone,"Timpani")],[48,new fo(uo.Strings,"Violin")],[49,new fo(uo.Strings,"Violin")],[50,new fo(uo.Strings,"Violin")],[51,new fo(uo.Strings,"Violin")],[52,new fo(uo.Vocal,"Voice")],[53,new fo(uo.Vocal,"Voice")],[54,new fo(uo.Vocal,"Voice")],[55,new fo(uo.Synth,"Pad Synthesizer")],[56,new fo(uo.Brass,"Trumpet")],[57,new fo(uo.Brass,"Trombone")],[58,new fo(uo.Brass,"Tuba")],[59,new fo(uo.Brass,"Trumpet")],[60,new fo(uo.Brass,"French Horn")],[61,new fo(uo.Brass,"Trumpet")],[62,new fo(uo.Brass,"Trumpet")],[63,new fo(uo.Brass,"Trumpet")],[64,new fo(uo.Reed,"Saxophone")],[65,new fo(uo.Reed,"Saxophone")],[66,new fo(uo.Reed,"Saxophone")],[67,new fo(uo.Reed,"Saxophone")],[68,new fo(uo.Reed,"Oboe")],[69,new fo(uo.Reed,"English Horn")],[70,new fo(uo.Reed,"Bassoon")],[71,new fo(uo.Reed,"Clarinet")],[72,new fo(uo.Reed,"Piccolo")],[73,new fo(uo.Woodwind,"Flute")],[74,new fo(uo.Woodwind,"Recorder")],[75,new fo(uo.Woodwind,"Flute")],[76,new fo(uo.Woodwind,"Recorder")],[77,new fo(uo.Woodwind,"Flute")],[78,new fo(uo.Woodwind,"Recorder")],[79,new fo(uo.Woodwind,"Flute")],[80,new fo(uo.Synth,"Lead Synthesizer")],[81,new fo(uo.Synth,"Lead Synthesizer")],[82,new fo(uo.Synth,"Lead Synthesizer")],[83,new fo(uo.Synth,"Lead Synthesizer")],[84,new fo(uo.Synth,"Lead Synthesizer")],[85,new fo(uo.Synth,"Lead Synthesizer")],[86,new fo(uo.Synth,"Lead Synthesizer")],[87,new fo(uo.Synth,"Lead Synthesizer")],[88,new fo(uo.Synth,"Pad Synthesizer")],[89,new fo(uo.Synth,"Pad Synthesizer")],[90,new fo(uo.Synth,"Pad Synthesizer")],[91,new fo(uo.Synth,"Pad Synthesizer")],[92,new fo(uo.Synth,"Pad Synthesizer")],[93,new fo(uo.Synth,"Pad Synthesizer")],[94,new fo(uo.Synth,"Pad Synthesizer")],[95,new fo(uo.Synth,"Pad Synthesizer")],[96,new fo(uo.Fx,"Pad Synthesizer")],[97,new fo(uo.Fx,"Pad Synthesizer")],[98,new fo(uo.Fx,"Pad Synthesizer")],[99,new fo(uo.Fx,"Pad Synthesizer")],[100,new fo(uo.Fx,"Lead Synthesizer")],[101,new fo(uo.Fx,"Lead Synthesizer")],[102,new fo(uo.Fx,"Lead Synthesizer")],[103,new fo(uo.Fx,"Trumpet")],[104,new fo(uo.ElectricGuitar,"Banjo")],[105,new fo(uo.Banjo,"Banjo")],[106,new fo(uo.Ukulele,"Ukulele")],[107,new fo(uo.Banjo,"Banjo")],[108,new fo(uo.PitchedIdiophone,"Xylophone")],[109,new fo(uo.Reed,"Bassoon")],[110,new fo(uo.Strings,"Violin")],[111,new fo(uo.Woodwind,"Flute")],[112,new fo(uo.PitchedIdiophone,"Xylophone")],[113,new fo(uo.Idiophone,"Celesta")],[114,new fo(uo.PitchedIdiophone,"Vibraphone")],[115,new fo(uo.Idiophone,"Xylophone")],[116,new fo(uo.Membraphone,"Xylophone")],[117,new fo(uo.Membraphone,"Xylophone")],[118,new fo(uo.Membraphone,"Xylophone")],[119,new fo(uo.Idiophone,"Celesta")],[120,new fo(uo.Fx,"Steel Guitar")],[121,new fo(uo.Fx,"Recorder")],[122,new fo(uo.Fx,"Recorder")],[123,new fo(uo.Fx,"Recorder")],[124,new fo(uo.Fx,"Recorder")],[125,new fo(uo.Fx,"Recorder")],[126,new fo(uo.Fx,"Recorder")],[127,new fo(uo.Fx,"Timpani")]]),mo.DrumKitProgramInfo=new fo(uo.PercussionKit,"Drums","drumKit");class yo{constructor(){this._checkValue=yo.CrcInit,this.reset()}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==(1&s)?s>>>1^3988292384:s>>>1;e[t]=s}return e}get value(){return~this._checkValue}update(e,t,s){for(let i=0;i<s;i++)this._checkValue=yo.Crc32Lookup[255&(this._checkValue^e[t+i])]^this._checkValue>>>8}reset(){this._checkValue=yo.CrcInit}}yo.Crc32Lookup=yo.buildCrc32Lookup(),yo.CrcInit=4294967295;class bo{}bo.MAX_WBITS=15,bo.WSIZE=1<<bo.MAX_WBITS,bo.WMASK=bo.WSIZE-1,bo.MIN_MATCH=3,bo.MAX_MATCH=258,bo.DEFAULT_MEM_LEVEL=8,bo.PENDING_BUF_SIZE=1<<bo.DEFAULT_MEM_LEVEL+8,bo.HASH_BITS=bo.DEFAULT_MEM_LEVEL+7,bo.HASH_SIZE=1<<bo.HASH_BITS,bo.HASH_SHIFT=(bo.HASH_BITS+bo.MIN_MATCH-1)/bo.MIN_MATCH,bo.HASH_MASK=bo.HASH_SIZE-1,bo.MIN_LOOKAHEAD=bo.MAX_MATCH+bo.MIN_MATCH+1,bo.MAX_DIST=bo.WSIZE-bo.MIN_LOOKAHEAD;class So{constructor(e,t,s,i){this.length=null,this.numCodes=0,this.codes=null,this.huffman=e,this.minNumCodes=s,this.maxLength=i,this.freqs=new Int16Array(t),this.bitLengthCounts=new Int32Array(i)}reset(){for(let e=0;e<this.freqs.length;e++)this.freqs[e]=0;this.codes=null,this.length=null}buildTree(){let e=this.freqs.length,t=new Int32Array(e),s=0,i=0;for(let a=0;a<e;a++){let e=this.freqs[a];if(0!==e){let r=s++;for(;r>0;){let s=Math.floor((r-1)/2);if(!(this.freqs[t[s]]>e))break;t[r]=t[s],r=s}t[r]=a,i=a}}for(;s<2;){let e=i<2?++i:0;t[s++]=e}this.numCodes=Math.max(i+1,this.minNumCodes);let a=s,r=new Int32Array(4*s-2),n=new Int32Array(2*s-1),o=a;for(let e=0;e<s;e++){let s=t[e];r[2*e]=s,r[2*e+1]=-1,n[e]=this.freqs[s]<<8,t[e]=e}do{let e=t[0],i=t[--s],a=0,h=1;for(;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*h+1;let l=n[i];for(;h=a,a>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i;let c=t[0];i=o++,r[2*i]=e,r[2*i+1]=c;let d=Math.min(255&n[e],255&n[c]);for(l=n[e]+n[c]-d+1,n[i]=l,a=0,h=1;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*a+1;for(;h=a,h>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i}while(s>1);this.buildLength(r)}buildLength(e){this.length=new Uint8Array(this.freqs.length);let t=Math.floor(e.length/2),s=Math.floor((t+1)/2),i=0;for(let e=0;e<this.maxLength;e++)this.bitLengthCounts[e]=0;let a=new Int32Array(t);a[t-1]=0;for(let s=t-1;s>=0;s--)if(-1!=e[2*s+1]){let t=a[s]+1;t>this.maxLength&&(t=this.maxLength,i++),a[e[2*s]]=t,a[e[2*s+1]]=t}else{let t=a[s];this.bitLengthCounts[t-1]++,this.length[e[2*s]]=a[s]}if(0==i)return;let r=this.maxLength-1;do{for(;0==this.bitLengthCounts[--r];);do{this.bitLengthCounts[r]--,this.bitLengthCounts[++r]++,i-=1<<this.maxLength-1-r}while(i>0&&r<this.maxLength-1)}while(i>0);this.bitLengthCounts[this.maxLength-1]+=i,this.bitLengthCounts[this.maxLength-2]-=i;let n=2*s;for(let t=this.maxLength;0!=t;t--){let s=this.bitLengthCounts[t-1];for(;s>0;){let i=2*e[n++];-1==e[i+1]&&(this.length[e[i]]=t,s--)}}}getEncodedLength(){let e=0;for(let t=0;t<this.freqs.length;t++)e+=this.freqs[t]*this.length[t];return e}calcBLFreq(e){let t,s,i,a=-1,r=0;for(;r<this.numCodes;){i=1;let n=this.length[r];for(0==n?(t=138,s=3):(t=6,s=3,a!=n&&(e.freqs[n]++,i=0)),a=n,r++;r<this.numCodes&&a==this.length[r]&&(r++,!(++i>=t)););i<s?e.freqs[a]+=i:0!=a?e.freqs[So.Repeat3To6]++:i<=10?e.freqs[So.Repeat3To10]++:e.freqs[So.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]=wo.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(So.Repeat3To6),this.huffman.pending.writeBits(i-3,2)):i<=10?(e.writeSymbol(So.Repeat3To10),this.huffman.pending.writeBits(i-3,3)):(e.writeSymbol(So.Repeat11To138),this.huffman.pending.writeBits(i-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}So.Repeat3To6=16,So.Repeat3To10=17,So.Repeat11To138=18;class wo{constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new So(this,wo.LITERAL_NUM,257,15),this.distTree=new So(this,wo.DIST_NUM,1,15),this.blTree=new So(this,wo.BITLEN_NUM,4,7),this.d_buf=new Int16Array(wo.BUFSIZE),this.l_buf=new Uint8Array(wo.BUFSIZE)}static staticInit(){let e=0;for(;e<144;)wo.staticLCodes[e]=wo.bitReverse(48+e<<8),wo.staticLLength[e++]=8;for(;e<256;)wo.staticLCodes[e]=wo.bitReverse(256+e<<7),wo.staticLLength[e++]=9;for(;e<280;)wo.staticLCodes[e]=wo.bitReverse(-256+e<<9),wo.staticLLength[e++]=7;for(;e<wo.LITERAL_NUM;)wo.staticLCodes[e]=wo.bitReverse(-88+e<<8),wo.staticLLength[e++]=8;for(e=0;e<wo.DIST_NUM;e++)wo.staticDCodes[e]=wo.bitReverse(e<<11),wo.staticDLength[e]=5}static bitReverse(e){return wo.bit4Reverse[15&e]<<12|wo.bit4Reverse[e>>4&15]<<8|wo.bit4Reverse[e>>8&15]<<4|wo.bit4Reverse[e>>12]}isFull(){return this.last_lit>=wo.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((wo.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[wo.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[wo.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<wo.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*wo.staticLLength[e];for(let e=0;e<wo.DIST_NUM;e++)n+=this.distTree.freqs[e]*wo.staticDLength[e];r>=n&&(r=n),t>=0&&s+4<r>>3?this.flushStoredBlock(e,t,s,i):r==n?(this.pending.writeBits((wo.STATIC_TREES<<1)+(i?1:0),3),this.literalTree.setStaticCodes(wo.staticLCodes,wo.staticLLength),this.distTree.setStaticCodes(wo.staticDCodes,wo.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((wo.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[wo.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=wo.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=wo.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(wo.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;let s=wo.Lcode(t-3);this.literalTree.freqs[s]++,s>=265&&s<285&&(this.extra_bits+=Math.floor((s-261)/4));let i=wo.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}}wo.BUFSIZE=1<<bo.DEFAULT_MEM_LEVEL+6,wo.LITERAL_NUM=286,wo.STORED_BLOCK=0,wo.STATIC_TREES=1,wo.DYN_TREES=2,wo.DIST_NUM=30,wo.staticLCodes=new Int16Array(wo.LITERAL_NUM),wo.staticLLength=new Uint8Array(wo.LITERAL_NUM),wo.staticDCodes=new Int16Array(wo.DIST_NUM),wo.staticDLength=new Uint8Array(wo.DIST_NUM),wo.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],wo.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),wo.BITLEN_NUM=19,wo.EOF_SYMBOL=256,wo.staticInit();class _o{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 wo(e),this.inputCrc=new yo,this.window=new Uint8Array(2*bo.WSIZE),this.head=new Int16Array(bo.HASH_SIZE),this.prev=new Int16Array(bo.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=bo.MIN_MATCH-1;for(let e=0;e<bo.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<bo.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<bo.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<bo.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=bo.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*bo.WSIZE-bo.MIN_LOOKAHEAD&&this.slideWindow();let e=this.matchStart,s=this.matchLen;if(this.lookahead>=bo.MIN_MATCH){let e=this.insertString();0!=e&&this.strstart-e<=bo.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen==bo.MIN_MATCH&&this.strstart-this.matchStart>_o.TooFar&&(this.matchLen=bo.MIN_MATCH-1)}if(s>=bo.MIN_MATCH&&this.matchLen<=s){this.huffman.tallyDist(this.strstart-1-e,s),s-=2;do{this.strstart++,this.lookahead--,this.lookahead>=bo.MIN_MATCH&&this.insertString()}while(--s>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=bo.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(bo.MAX_MATCH,this.lookahead)-1,a=Math.max(s-bo.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,bo.MIN_MATCH-1),s+this.matchLen>i)return!1;let l=r[s+this.matchLen-1],c=r[s+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,s=this.strstart,r[t+this.matchLen]==c&&r[t+this.matchLen-1]==l&&r[t]==r[s]&&r[++t]==r[++s]){switch((i-s)%8){case 1:if(r[++s]==r[++t])break;break;case 2:if(r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 3:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 4:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 5:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 6:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break;break;case 7:if(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t])break}if(r[s]==r[t])do{if(s==i){++s,++t;break}}while(r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]&&r[++s]==r[++t]);if(s-this.strstart>this.matchLen){if(this.matchStart=e,this.matchLen=s-this.strstart,this.matchLen>=h)break;l=r[s-1],c=r[s]}e=65535&n[e&bo.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=bo.MIN_MATCH}insertString(){let e,t=(this.insertHashIndex<<bo.HASH_SHIFT^this.window[this.strstart+(bo.MIN_MATCH-1)])&bo.HASH_MASK;return e=this.head[t],this.prev[this.strstart&bo.WMASK]=e,this.head[t]=this.strstart,this.insertHashIndex=t,65535&e}fillWindow(){if(this.strstart>=bo.WSIZE+bo.MAX_DIST&&this.slideWindow(),this.lookahead<bo.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*bo.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>=bo.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(bo.WSIZE,bo.WSIZE+bo.WSIZE),0),this.matchStart-=bo.WSIZE,this.strstart-=bo.WSIZE,this.blockStart-=bo.WSIZE;for(let e=0;e<bo.HASH_SIZE;++e){let t=65535&this.head[e];this.head[e]=t>=bo.WSIZE?t-bo.WSIZE:0}for(let e=0;e<bo.WSIZE;e++){let t=65535&this.prev[e];this.prev[e]=t>=bo.WSIZE?t-bo.WSIZE:0}}}_o.TooFar=4096;class Bo{constructor(e){this._start=0,this._end=0,this._bits=0,this.bitCount=0,this._buffer=new Uint8Array(e)}get isFlushed(){return 0===this._end}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 To{constructor(){this._state=0,this._pending=new Bo(bo.PENDING_BUF_SIZE),this._engine=new _o(this._pending),this.reset()}get inputCrc(){return this._engine.inputCrc.value}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state==To.FinishedState&&this._pending.isFlushed}reset(){this._state=To.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==To.FinishedState)break;if(!this._engine.deflate(0!=(this._state&To.IsFlushing),0!=(this._state&To.IsFinishing)))switch(this._state){case To.BusyState:return i-s;case To.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=To.BusyState;break;case To.FinishingState:this._pending.alignToByte(),this._state=To.FinishedState}}return i-s}finish(){this._state|=To.IsFlushing|To.IsFinishing}}To.IsFlushing=4,To.IsFinishing=8,To.BusyState=16,To.FlushingState=20,To.FinishingState=28,To.FinishedState=30;class ko{constructor(e,t,s,i,a){this.entry=e,this.crc32=t,this.localHeaderOffset=s,this.compressionMode=i,this.compressedSize=a}}class vo{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new To,this._data=e}writeEntry(e){const t=vt.CompressionMethodDeflate,s=$e.empty(),i=this.compress(s,e.data,t),a=s.toArray(),r=new ko(e,i,this._data.bytesWritten,t,s.length);this._centralDirectoryHeaders.push(r),Ke.writeInt32LE(this._data,vt.LocalFileHeaderSignature),Ke.writeUInt16LE(this._data,10),Ke.writeUInt16LE(this._data,2048),Ke.writeUInt16LE(this._data,t),Ke.writeInt16LE(this._data,0),Ke.writeInt16LE(this._data,0),Ke.writeInt32LE(this._data,i),Ke.writeInt32LE(this._data,a.length),Ke.writeInt32LE(this._data,e.data.length),Ke.writeInt16LE(this._data,e.fullName.length),Ke.writeInt16LE(this._data,0);const n=Ke.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,s){if(s!=vt.CompressionMethodDeflate){const s=new yo;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){Ke.writeInt32LE(this._data,vt.EndOfCentralDirSignature),Ke.writeInt16LE(this._data,0),Ke.writeInt16LE(this._data,0),Ke.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Ke.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Ke.writeInt32LE(this._data,t-e),Ke.writeInt32LE(this._data,e),Ke.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){Ke.writeInt32LE(this._data,vt.CentralFileHeaderSignature),Ke.writeUInt16LE(this._data,10),Ke.writeUInt16LE(this._data,10),Ke.writeUInt16LE(this._data,2048),Ke.writeUInt16LE(this._data,e.compressionMode),Ke.writeInt16LE(this._data,0),Ke.writeInt16LE(this._data,0),Ke.writeInt32LE(this._data,e.crc32),Ke.writeInt32LE(this._data,e.compressedSize),Ke.writeInt32LE(this._data,e.entry.data.length),Ke.writeInt16LE(this._data,e.entry.fullName.length),Ke.writeInt16LE(this._data,0),Ke.writeInt16LE(this._data,0),Ke.writeInt16LE(this._data,0),Ke.writeInt16LE(this._data,0),Ke.writeInt32LE(this._data,0),Ke.writeInt32LE(this._data,e.localHeaderOffset);const t=Ke.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}var xo=Object.freeze({__proto__:null,ScoreExporter:go,Gp7Exporter:class extends go{get name(){return"Guitar Pro 7"}constructor(){super()}writeScore(e){Be.debug(this.name,"Writing data entries");const t=(new mo).writeXml(e),s=rt.writeForScore(e),i=yt.writeForScore(e);Be.debug(this.name,"Writing ZIP entries");let a=new vo(this.data);a.writeEntry(new vt("VERSION",Ke.stringToBytes("7.0"))),a.writeEntry(new vt("Content/",new Uint8Array(0))),a.writeEntry(new vt("Content/BinaryStylesheet",s)),a.writeEntry(new vt("Content/PartConfiguration",i)),a.writeEntry(new vt("Content/score.gpif",Ke.stringToBytes(t))),a.end()}}}),No=Object.freeze({__proto__:null,BeatTickLookup:_i,MasterBarTickLookup:Ti,MidiTickLookup:vi,MidiTickLookupFindBeatResult:ki,MidiFile:Ss,get ControllerType(){return te},MetaDataEvent:ws,MetaEvent:Dt,get MetaEventType(){return U},MetaNumberEvent:_s,MidiEvent:It,get MidiEventType(){return z},Midi20PerNotePitchBendEvent:Ws,SystemCommonEvent:Rt,get SystemCommonType(){return X},SystemExclusiveEvent:At,MidiFileGenerator:Pi,AlphaSynthMidiFileHandler:wi}),Po=Object.freeze({__proto__:null,get AccentuationType(){return i},get AccidentalType(){return re},get AutomationType(){return a},Automation:fe,Bar:me,Beat:De,BendPoint:be,get BendStyle(){return h},get BendType(){return l},get BrushType(){return c},Chord:Re,get Clef(){return r},Color:Ue,get CrescendoType(){return d},get Duration(){return u},get DynamicValue(){return p},get FermataType(){return O},Fermata:nt,get Fingers(){return f},get FontStyle(){return $},Font:vs,get GraceType(){return g},get HarmonicType(){return m},InstrumentArticulation:ve,JsonConverter:ni,get KeySignature(){return M},get KeySignatureType(){return I},Lyrics:Ae,MasterBar:Oe,get MusicFontSymbol(){return N},Note:Pe,get NoteAccidentalMode(){return y},get Ottavia(){return n},get PickStroke(){return x},PlaybackInformation:Xe,RenderStylesheet:Ge,RepeatGroup:Ve,Score:He,Section:We,get SimileMark(){return o},get SlideInType(){return b},get SlideOutType(){return S},Staff:qe,Track:Je,get TripletFeel(){return D},Tuning:Ye,TupletGroup:Ee,get VibratoType(){return w},Voice:Qe,get WhammyType(){return C}}),Eo=Object.freeze({__proto__:null,RenderFinishedEventArgs:ci,ScoreRenderer:yi,BarBounds:di,BeatBounds:ui,Bounds:at,BoundsLookup:mi,MasterBarBounds:pi,NoteBounds:gi,StaveGroupBounds:fi}),Co=Object.freeze({__proto__:null,AlphaSynth:bs,PlaybackRange:Ei,get PlayerState(){return q},PlayerStateChangedEventArgs:zt,PositionChangedEventArgs:Ut,AlphaSynthWebWorkerApi:qi});export{Zi as AlphaTabApi,pe as AlphaTabError,s as AlphaTabErrorType,lo as CoreSettings,Ns as DisplaySettings,Oi as FileLoadError,B as FingeringMode,ze as FormatError,Ps as ImporterSettings,e as LayoutMode,v as LogLevel,Be as Logger,T as NotationMode,Se as NotationSettings,Fs as PlayerSettings,Yi as ProgressEventArgs,xs as RenderingResources,Ri as ResizeEventArgs,ee as ScrollMode,Hs as Settings,t as StaveProfile,_ as TabRhythmMode,Es as VibratoPlaybackSettings,xo as exporter,po as importer,co as meta,No as midi,Po as model,Eo as rendering,Co as synth};