@coderline/alphatab 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).alphaTab={})}(this,(function(e){"use strict";var t,i,s,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,A;e.LayoutMode=void 0,(t=e.LayoutMode||(e.LayoutMode={}))[t.Page=0]="Page",t[t.Horizontal=1]="Horizontal",e.StaveProfile=void 0,(i=e.StaveProfile||(e.StaveProfile={}))[i.Default=0]="Default",i[i.ScoreTab=1]="ScoreTab",i[i.Score=2]="Score",i[i.Tab=3]="Tab",i[i.TabMixed=4]="TabMixed";class R{static getValue(e){return R._values||(R._values=new Map),e=e.toLowerCase().replaceAll(" ",""),R._values.has(e)?R._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}}R._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 O{init(e,t){this.data=e,this.settings=t}}e.AlphaTabErrorType=void 0,(s=e.AlphaTabErrorType||(e.AlphaTabErrorType={}))[s.General=0]="General",s[s.Format=1]="Format",s[s.AlphaTex=2]="AlphaTex";class G extends Error{constructor(e,t="",i){super(t??"",{cause:i}),this.type=e,this.inner=i??null,Object.setPrototypeOf(this,G.prototype)}}class V extends G{constructor(t=null,i=null){super(e.AlphaTabErrorType.Format,t??"Unsupported format"),this.inner=i,Object.setPrototypeOf(this,V.prototype)}}!function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy"}(a||(a={})),function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(r||(r={}));class H{constructor(){this.isLinear=!1,this.type=r.Tempo,this.value=0,this.ratioPosition=0,this.text=""}static buildTempoAutomation(e,t,i,s){(s<1||s>5)&&(s=2);let a=new Float32Array([1,.5,1,1.5,2,3]),n=new H;return n.type=r.Tempo,n.isLinear=e,n.ratioPosition=t,n.value=i*a[s],n}static buildInstrumentAutomation(e,t,i){let s=new H;return s.type=r.Instrument,s.isLinear=e,s.ratioPosition=t,s.value=i,s}}!function(e){e[e.Neutral=0]="Neutral",e[e.C3=1]="C3",e[e.C4=2]="C4",e[e.F4=3]="F4",e[e.G2=4]="G2"}(n||(n={})),function(e){e[e._15ma=0]="_15ma",e[e._8va=1]="_8va",e[e.Regular=2]="Regular",e[e._8vb=3]="_8vb",e[e._15mb=4]="_15mb"}(o||(o={})),function(e){e[e.None=0]="None",e[e.Simple=1]="Simple",e[e.FirstOfDouble=2]="FirstOfDouble",e[e.SecondOfDouble=3]="SecondOfDouble"}(h||(h={}));class W{constructor(){this.id=W._globalBarId++,this.index=0,this.nextBar=null,this.previousBar=null,this.clef=n.G2,this.clefOttava=o.Regular,this.voices=[],this.simileMark=h.None,this.isMultiVoice=!1,this.displayScale=1,this.displayWidth=-1}get masterBar(){return this.staff.track.score.masterBars[this.index]}get isEmpty(){for(let e=0,t=this.voices.length;e<t;e++)if(!this.voices[e].isEmpty)return!1;return!0}addVoice(e){e.bar=this,e.index=this.voices.length,this.voices.push(e)}finish(e,t=null){this.isMultiVoice=!1;for(let i=0,s=this.voices.length;i<s;i++){let s=this.voices[i];s.finish(e,t),i>0&&!s.isEmpty&&(this.isMultiVoice=!0)}}calculateDuration(){let e=0;for(let t of this.voices){let i=t.calculateDuration();i>e&&(e=i)}return e}}W._globalBarId=0;class z{static ticksToMillis(e,t){return e*(6e4/(t*z.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*z.QuarterTime))|0}static toTicks(e){return z.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),z.QuarterTime*(4/t)|0}static applyDot(e,t){return t?e+3*(e/4|0):e+(e/2|0)}static applyTuplet(e,t,i){return e*i/t|0}static removeTuplet(e,t,i){return e*t/i|0}static dynamicToVelocity(e){return z.MinVelocity+e*z.VelocityIncrement}}z.QuarterTime=960,z.MinVelocity=15,z.VelocityIncrement=16;class U{constructor(e=0,t=0){this.offset=e,this.value=t}}U.MaxPosition=60,U.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(l||(l={})),function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Bend=2]="Bend",e[e.Release=3]="Release",e[e.BendRelease=4]="BendRelease",e[e.Hold=5]="Hold",e[e.Prebend=6]="Prebend",e[e.PrebendBend=7]="PrebendBend",e[e.PrebendRelease=8]="PrebendRelease"}(c||(c={})),function(e){e[e.None=0]="None",e[e.BrushUp=1]="BrushUp",e[e.BrushDown=2]="BrushDown",e[e.ArpeggioUp=3]="ArpeggioUp",e[e.ArpeggioDown=4]="ArpeggioDown"}(d||(d={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(u||(u={})),function(e){e[e.QuadrupleWhole=-4]="QuadrupleWhole",e[e.DoubleWhole=-2]="DoubleWhole",e[e.Whole=1]="Whole",e[e.Half=2]="Half",e[e.Quarter=4]="Quarter",e[e.Eighth=8]="Eighth",e[e.Sixteenth=16]="Sixteenth",e[e.ThirtySecond=32]="ThirtySecond",e[e.SixtyFourth=64]="SixtyFourth",e[e.OneHundredTwentyEighth=128]="OneHundredTwentyEighth",e[e.TwoHundredFiftySixth=256]="TwoHundredFiftySixth"}(p||(p={})),function(e){e[e.PPP=0]="PPP",e[e.PP=1]="PP",e[e.P=2]="P",e[e.MP=3]="MP",e[e.MF=4]="MF",e[e.F=5]="F",e[e.FF=6]="FF",e[e.FFF=7]="FFF"}(g||(g={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(f||(f={})),function(e){e[e.Unknown=-2]="Unknown",e[e.NoOrDead=-1]="NoOrDead",e[e.Thumb=0]="Thumb",e[e.IndexFinger=1]="IndexFinger",e[e.MiddleFinger=2]="MiddleFinger",e[e.AnnularFinger=3]="AnnularFinger",e[e.LittleFinger=4]="LittleFinger"}(m||(m={})),function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Artificial=2]="Artificial",e[e.Pinch=3]="Pinch",e[e.Tap=4]="Tap",e[e.Semi=5]="Semi",e[e.Feedback=6]="Feedback"}(y||(y={})),function(e){e[e.Default=0]="Default",e[e.ForceNone=1]="ForceNone",e[e.ForceNatural=2]="ForceNatural",e[e.ForceSharp=3]="ForceSharp",e[e.ForceDoubleSharp=4]="ForceDoubleSharp",e[e.ForceFlat=5]="ForceFlat",e[e.ForceDoubleFlat=6]="ForceDoubleFlat"}(b||(b={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(S||(S={})),function(e){e[e.None=0]="None",e[e.Shift=1]="Shift",e[e.Legato=2]="Legato",e[e.OutUp=3]="OutUp",e[e.OutDown=4]="OutDown",e[e.PickSlideDown=5]="PickSlideDown",e[e.PickSlideUp=6]="PickSlideUp"}(w||(w={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(_||(_={})),e.TabRhythmMode=void 0,(B=e.TabRhythmMode||(e.TabRhythmMode={}))[B.Hidden=0]="Hidden",B[B.ShowWithBeams=1]="ShowWithBeams",B[B.ShowWithBars=2]="ShowWithBars",e.FingeringMode=void 0,(T=e.FingeringMode||(e.FingeringMode={}))[T.ScoreDefault=0]="ScoreDefault",T[T.ScoreForcePiano=1]="ScoreForcePiano",T[T.SingleNoteEffectBand=2]="SingleNoteEffectBand",T[T.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano",e.NotationMode=void 0,(k=e.NotationMode||(e.NotationMode={}))[k.GuitarPro=0]="GuitarPro",k[k.SongBook=1]="SongBook",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"}(v||(v={}));class X{constructor(){this.notationMode=e.NotationMode.GuitarPro,this.fingeringMode=e.FingeringMode.ScoreDefault,this.elements=new Map,this.rhythmMode=e.TabRhythmMode.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):!X.defaultElements.has(e)||X.defaultElements.get(e)}}X.defaultElements=new Map([[v.ZerosOnDiveWhammys,!1]]);class Y{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}e.LogLevel=void 0,(x=e.LogLevel||(e.LogLevel={}))[x.None=0]="None",x[x.Debug=1]="Debug",x[x.Info=2]="Info",x[x.Warning=3]="Warning",x[x.Error=4]="Error";class q{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...i){console.debug(q.format(e,t),...i)}warning(e,t,...i){console.warn(q.format(e,t),...i)}info(e,t,...i){console.info(q.format(e,t),...i)}error(e,t,...i){console.error(q.format(e,t),...i)}}q.logLevel=e.LogLevel.Info;class J{static shouldLog(t){return J.logLevel!==e.LogLevel.None&&t>=J.logLevel}static debug(t,i,...s){J.shouldLog(e.LogLevel.Debug)&&J.log.debug(t,i,...s)}static warning(t,i,...s){J.shouldLog(e.LogLevel.Warning)&&J.log.warning(t,i,...s)}static info(t,i,...s){J.shouldLog(e.LogLevel.Info)&&J.log.info(t,i,...s)}static error(t,i,...s){J.shouldLog(e.LogLevel.Error)&&J.log.error(t,i,...s)}}J.logLevel=e.LogLevel.Info,J.log=new q;class j{constructor(){this.note=null,this.noteValue=0,this.octave=0}get realValue(){return 12*this.octave+this.noteValue}}class Q{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 i=0;i<t.tracks.length;i++){if(i<e.notation.displayTranspositionPitches.length)for(let s of t.tracks[i].staves)s.displayTranspositionPitch=-e.notation.displayTranspositionPitches[i];if(i<e.notation.transpositionPitches.length)for(let s of t.tracks[i].staves)s.transpositionPitch=-e.notation.transpositionPitches[i]}}static fingerToString(t,i,s,a){if(t.notation.fingeringMode===e.FingeringMode.ScoreForcePiano||t.notation.fingeringMode===e.FingeringMode.SingleNoteEffectBandForcePiano||R.isPiano(i.voice.bar.staff.track.playbackInfo.program))switch(s){case m.Unknown:case m.NoOrDead:return null;case m.Thumb:return"1";case m.IndexFinger:return"2";case m.MiddleFinger:return"3";case m.AnnularFinger:return"4";case m.LittleFinger:return"5";default:return null}if(a)switch(s){case m.Unknown:case m.NoOrDead:return"0";case m.Thumb:return"T";case m.IndexFinger:return"1";case m.MiddleFinger:return"2";case m.AnnularFinger:return"3";case m.LittleFinger:return"4";default:return null}switch(s){case m.Unknown:case m.NoOrDead:return null;case m.Thumb:return"p";case m.IndexFinger:return"i";case m.MiddleFinger:return"m";case m.AnnularFinger:return"a";case m.LittleFinger:return"c";default:return null}}static isTuning(e){return!!Q.parseTuning(e)}static parseTuning(e){let t="",i="";for(let s=0;s<e.length;s++){let a=e.charCodeAt(s);if(a>=48&&a<=57){if(!t)return null;i+=String.fromCharCode(a)}else{if(!(a>=65&&a<=90||a>=97&&a<=122||35===a))return null;t+=String.fromCharCode(a)}}if(!i||!t)return null;let s=new j;return s.octave=parseInt(i)+1,s.note=t.toLowerCase(),s.noteValue=Q.getToneForText(s.note),s}static getTuningForText(e){let t=Q.parseTuning(e);return t?t.realValue:-1}static getToneForText(e){switch(e.toLowerCase()){case"c":default:return 0;case"c#":case"db":return 1;case"d":return 2;case"d#":case"eb":return 3;case"e":return 4;case"f":return 5;case"f#":case"gb":return 6;case"g":return 7;case"g#":case"ab":return 8;case"a":return 9;case"a#":case"bb":return 10;case"b":return 11}}static newGuid(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)}static isAlmostEqualTo(e,t){return Math.abs(e-t)<1e-5}static toHexString(e,t=0){let i="";do{i=String.fromCharCode("0123456789ABCDEF".charCodeAt(15&e))+i,e>>=4}while(e>0);for(;i.length<t;)i="0"+i;return i}}!function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(N||(N={})),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"}(P||(P={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(E||(E={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(C||(C={}));class ${constructor(e="",t=0,i=0,s=P.None,a=P.None,r=P.None,n=P.None,o=C.Middle){this.elementType=e,this.outputMidiNumber=i,this.staffLine=t,this.noteHeadDefault=s,this.noteHeadHalf=a!==P.None?a:s,this.noteHeadWhole=r!==P.None?r:s,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case p.Whole:return this.noteHeadWhole;case p.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class K{static articulationFromElementVariation(e,t){return e<K.gp6ElementAndVariationToArticulation.length?(t>=K.gp6ElementAndVariationToArticulation.length&&(t=0),K.gp6ElementAndVariationToArticulation[e][t]):38}static getArticulation(e){const t=e.percussionArticulation,i=e.beat.voice.bar.staff.track.percussionArticulations;return t<i.length?i[t]:K.getArticulationByValue(t)}static getElementAndVariation(e){const t=K.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<K.gp6ElementAndVariationToArticulation.length;e++){const i=K.gp6ElementAndVariationToArticulation[e];for(let s=0;s<i.length;s++){const a=K.getArticulationByValue(i[s]);if(a?.outputMidiNumber===t.outputMidiNumber)return[e,s]}}return[-1,-1]}static getArticulationByValue(e){return K.instrumentArticulations.has(e)?K.instrumentArticulations.get(e):null}}K.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]],K.instrumentArticulations=new Map([[38,new $("snare",3,38,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[37,new $("snare",3,37,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[91,new $("snare",3,38,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite)],[42,new $("hiHat",-1,42,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[92,new $("hiHat",-1,46,P.NoteheadCircleSlash,P.NoteheadCircleSlash,P.NoteheadCircleSlash)],[46,new $("hiHat",-1,46,P.NoteheadCircleX,P.NoteheadCircleX,P.NoteheadCircleX)],[44,new $("hiHat",9,44,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[35,new $("kickDrum",8,35,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[36,new $("kickDrum",7,36,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[50,new $("tom",1,50,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[48,new $("tom",2,48,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[47,new $("tom",4,47,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[45,new $("tom",5,45,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[43,new $("tom",6,43,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[93,new $("ride",0,51,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.PictEdgeOfCymbal,C.Bottom)],[51,new $("ride",0,51,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[53,new $("ride",0,53,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite)],[94,new $("ride",0,51,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.ArticStaccatoAbove,C.Top)],[55,new $("splash",-2,55,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[95,new $("splash",-2,55,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.ArticStaccatoAbove,C.Bottom)],[52,new $("china",-3,52,P.NoteheadHeavyXHat,P.NoteheadHeavyXHat,P.NoteheadHeavyXHat)],[96,new $("china",-3,52,P.NoteheadHeavyXHat,P.NoteheadHeavyXHat,P.NoteheadHeavyXHat)],[49,new $("crash",-2,49,P.NoteheadHeavyX,P.NoteheadHeavyX,P.NoteheadHeavyX)],[97,new $("crash",-2,49,P.NoteheadHeavyX,P.NoteheadHeavyX,P.NoteheadHeavyX,P.ArticStaccatoAbove,C.Bottom)],[57,new $("crash",-1,57,P.NoteheadHeavyX,P.NoteheadHeavyX,P.NoteheadHeavyX)],[98,new $("crash",-1,57,P.NoteheadHeavyX,P.NoteheadHeavyX,P.NoteheadHeavyX,P.ArticStaccatoAbove,C.Bottom)],[99,new $("cowbell",1,56,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpHalf,P.NoteheadTriangleUpWhole)],[100,new $("cowbell",1,56,P.NoteheadXBlack,P.NoteheadXHalf,P.NoteheadXWhole)],[56,new $("cowbell",0,56,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpHalf,P.NoteheadTriangleUpWhole)],[101,new $("cowbell",0,56,P.NoteheadXBlack,P.NoteheadXHalf,P.NoteheadXWhole)],[102,new $("cowbell",-1,56,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpHalf,P.NoteheadTriangleUpWhole)],[103,new $("cowbell",-1,56,P.NoteheadXBlack,P.NoteheadXHalf,P.NoteheadXWhole)],[77,new $("woodblock",-9,77,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack)],[76,new $("woodblock",-10,76,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack)],[60,new $("bongo",-4,60,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[104,new $("bongo",-5,60,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.NoteheadParenthesis,C.Middle)],[105,new $("bongo",-6,60,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[61,new $("bongo",-7,61,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[106,new $("bongo",-8,61,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.NoteheadParenthesis,C.Middle)],[107,new $("bongo",-16,61,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[66,new $("timbale",10,66,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[65,new $("timbale",9,65,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[68,new $("agogo",12,68,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[67,new $("agogo",11,67,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[64,new $("conga",17,64,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[108,new $("conga",16,64,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[109,new $("conga",15,64,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.NoteheadParenthesis,C.Middle)],[63,new $("conga",14,63,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[110,new $("conga",13,63,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[62,new $("conga",19,62,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.NoteheadParenthesis,C.Middle)],[72,new $("whistle",-11,72,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[71,new $("whistle",-17,71,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[73,new $("guiro",38,73,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[74,new $("guiro",37,74,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[86,new $("surdo",36,86,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[87,new $("surdo",35,87,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadParenthesis,C.Middle)],[54,new $("tambourine",3,54,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack)],[111,new $("tambourine",2,54,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.StringsUpBow,C.Bottom)],[112,new $("tambourine",1,54,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.StringsDownBow,C.Bottom)],[113,new $("tambourine",-7,54,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[79,new $("cuica",30,79,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[78,new $("cuica",29,78,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[58,new $("vibraslap",28,58,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[81,new $("triangle",27,81,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[80,new $("triangle",26,80,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadParenthesis,C.Middle)],[114,new $("grancassa",25,43,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[115,new $("piatti",18,49,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[116,new $("piatti",24,49,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[69,new $("cabasa",23,69,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[117,new $("cabasa",22,69,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[85,new $("castanets",21,85,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[75,new $("claves",20,75,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[70,new $("maraca",-12,70,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[118,new $("maraca",-13,70,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[119,new $("maraca",-14,70,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[120,new $("maraca",-15,70,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[82,new $("shaker",-23,54,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[122,new $("shaker",-24,54,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[84,new $("bellTree",-18,53,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[123,new $("bellTree",-19,53,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[83,new $("jingleBell",-20,53,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[124,new $("unpitched",-21,62,P.NoteheadNull,P.NoteheadNull,P.NoteheadNull,P.GuitarGolpe,C.Top)],[125,new $("unpitched",-22,62,P.NoteheadNull,P.NoteheadNull,P.NoteheadNull,P.GuitarGolpe,C.Bottom)],[39,new $("handClap",3,39,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[40,new $("snare",3,40,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[31,new $("snare",3,40,P.NoteheadSlashedBlack2,P.NoteheadSlashedBlack2,P.NoteheadSlashedBlack2)],[41,new $("tom",5,41,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[59,new $("ride",2,59,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.PictEdgeOfCymbal,C.Bottom)],[126,new $("ride",2,59,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[127,new $("ride",2,59,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite)],[29,new $("ride",2,59,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.ArticStaccatoAbove,C.Top)],[30,new $("crash",-3,49,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[33,new $("snare",3,37,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[34,new $("snare",3,38,P.NoteheadBlack,P.NoteheadBlack,P.NoteheadBlack)]]);class Z{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1}}class ee{constructor(){this.id=ee.GlobalNoteId++,this.index=0,this.accentuated=a.None,this.bendType=c.None,this.bendStyle=l.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=y.None,this.harmonicValue=0,this.isGhost=!1,this.isLetRing=!1,this.letRingDestination=null,this.isPalmMute=!1,this.palmMuteDestination=null,this.isDead=!1,this.isStaccato=!1,this.slideInType=S.None,this.slideOutType=w.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=_.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=m.Unknown,this.rightHandFinger=m.Unknown,this.isFingering=!1,this.trillValue=-1,this.trillSpeed=p.ThirtySecond,this.durationPercent=1,this.accidentalMode=b.Default,this.dynamics=g.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this._noteIdBag=null}get hasBend(){return null!==this.bendPoints&&this.bendType!==c.None}get isStringed(){return this.string>=0}get isPiano(){return!this.isStringed&&this.octave>=0&&this.tone>=0}get isPercussion(){return!this.isStringed&&this.percussionArticulation>=0}get element(){return this.isPercussion?K.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?K.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==y.None}get isTieOrigin(){return null!==this.tieDestination}get 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+ee.getStringTuning(this.beat.voice.bar.staff,this.string)}static getStringTuning(e,t){return e.tuning.length>0?e.tuning[e.tuning.length-(t-1)-1]:0}get realValue(){return this.calculateRealValue(!0,!0)}get realValueWithoutHarmonic(){return this.calculateRealValue(!0,!1)}calculateRealValue(e,t){const i=e?this.beat.voice.bar.staff.transpositionPitch:0;if(t){let t=this.calculateRealValue(e,!1);return this.isStringed&&(this.harmonicType===y.Natural?t=this.harmonicPitch+this.stringTuning-i:t+=this.harmonicPitch),t}return this.isPercussion?this.percussionArticulation:this.isStringed?this.fret+this.stringTuning-i:this.isPiano?12*this.octave+this.tone-i:0}get harmonicPitch(){if(this.harmonicType===y.None||!this.isStringed)return 0;let e=this.harmonicValue;return Q.isAlmostEqualTo(e,2.4)?36:Q.isAlmostEqualTo(e,2.7)?34:e<3?0:e<=3.5?31:e<=4?28:e<=5?24:e<=6?34:e<=7?19:e<=8.5?36:e<=9?28:e<=10?34:e<=11?0:e<=12?12:e<14?0:e<=15?34:e<=16?28:e<=17?36:e<=18?0:e<=19?19:e<=21?0:e<=22?36:e<=24?24:0}get initialBendValue(){return this.hasBend?Math.floor(this.bendPoints[0].value/2):this.bendOrigin?Math.floor(this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value/2):this.isTieDestination&&this.tieOrigin.bendOrigin?Math.floor(this.tieOrigin.bendOrigin.bendPoints[this.tieOrigin.bendOrigin.bendPoints.length-1].value/2):this.beat.hasWhammyBar?Math.floor(this.beat.whammyBarPoints[0].value/2):this.beat.isContinuedWhammy?Math.floor(this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value/2):0}get displayValue(){return this.displayValueWithoutBend+this.initialBendValue}get displayValueWithoutBend(){let e=this.realValue;switch(this.harmonicType!==y.Natural&&this.harmonicType!==y.None&&(e-=this.harmonicPitch),this.beat.ottava){case o._15ma:e-=24;break;case o._8va:e-=12;break;case o.Regular:break;case o._8vb:e+=12;break;case o._15mb:e+=24}switch(this.beat.voice.bar.clefOttava){case o._15ma:e-=24;break;case o._8va:e-=12;break;case o.Regular:break;case o._8vb:e+=12;break;case o._15mb:e+=24}return e-this.beat.voice.bar.staff.displayTranspositionPitch}get hasQuarterToneOffset(){return this.hasBend?this.bendPoints[0].value%2!=0:this.bendOrigin?this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value%2!=0:this.beat.hasWhammyBar?this.beat.whammyBarPoints[0].value%2!=0:!!this.beat.isContinuedWhammy&&this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value%2!=0}addBendPoint(e){let t=this.bendPoints;null===t&&(t=[],this.bendPoints=t),t.push(e),(!this.maxBendPoint||e.value>this.maxBendPoint.value)&&(this.maxBendPoint=e),this.bendType===c.None&&(this.bendType=c.Custom)}finish(t,i=null){let s=new Y((()=>ee.nextNoteOnSameLine(this))),a=t&&t.notation.notationMode===e.NotationMode.SongBook;if(this.isTieDestination&&(this.chain(i),a&&this.tieOrigin&&this.tieOrigin.isLetRing&&(this.isLetRing=!0)),this.isLetRing&&(s.value&&s.value.isLetRing?this.letRingDestination=s.value:this.letRingDestination=this,a&&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=ee.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case w.Shift:case w.Legato:this.slideTarget=s.value,this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=w.None}let r=null;this.isHammerPullOrigin&&this.hammerPullDestination?r=this.hammerPullDestination:this.slideOutType===w.Legato&&this.slideTarget&&(r=this.slideTarget),r&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===N.None?(this.effectSlurOrigin.effectSlurDestination=r,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=r,this.effectSlurDestination.effectSlurOrigin=this));const n=this.bendPoints;if(null!=n&&n.length>0&&this.bendType===c.Custom){let e=this.isTieDestination&&this.tieOrigin.hasBend;if(this.isContinuedBend=e,4===n.length){let t=n[0],i=n[1],s=n[2],a=n[3];i.value===s.value?a.value>t.value?i.value>a.value?this.bendType=c.BendRelease:!e&&t.value>0?(this.bendType=c.PrebendBend,n.splice(2,1),n.splice(1,1)):(this.bendType=c.Bend,n.splice(2,1),n.splice(1,1)):a.value<t.value?e?(this.bendType=c.Release,n.splice(2,1),n.splice(1,1)):(this.bendType=c.PrebendRelease,n.splice(2,1),n.splice(1,1)):i.value>t.value?this.bendType=c.BendRelease:t.value>0&&!e?(this.bendType=c.Prebend,n.splice(2,1),n.splice(1,1)):(this.bendType=c.Hold,n.splice(2,1),n.splice(1,1)):J.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===n.length){let t=n[0],i=n[1];i.value>t.value?!e&&t.value>0?this.bendType=c.PrebendBend:this.bendType=c.Bend:i.value<t.value?this.bendType=e?c.Release:c.PrebendRelease:this.bendType=c.Hold}}else null!==n&&0!==n.length||(this.bendType=c.None);this.initialBendValue>0&&(this.accidentalMode=b.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+ee.MaxOffsetForSameLineSearch;){let i=t.getNoteOnString(e.string);if(i)return i;t=t.nextBeat}return null}static findHammerPullDestination(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+ee.MaxOffsetForSameLineSearch;){let i=t.getNoteOnString(e.string);if(i)return i;for(let s=e.string;s>0;s--)if(i=t.getNoteOnString(s),i){if(i.isLeftHandTapped)return i;break}for(let s=e.string;s<=e.beat.voice.bar.staff.tuning.length;s++)if(i=t.getNoteOnString(s),i){if(i.isLeftHandTapped)return i;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-ee.MaxOffsetForSameLineSearch;){if(e.isStringed){let i=t.getNoteOnString(e.string);if(i)return i}else if(-1===e.octave&&-1===e.tone){if(e.index<t.notes.length)return t.notes[e.index]}else{let i=t.getNoteWithRealValue(e.realValue);if(i)return i}t=t.previousBeat}return null}chain(e=null){if(null!==e)if(null!==this._noteIdBag){let t;e.has(ee.NoteIdLookupKey)?t=e.get(ee.NoteIdLookupKey):(t=new Map,e.set(ee.NoteIdLookupKey,t)),-1===this._noteIdBag.hammerPullDestinationNoteId&&-1===this._noteIdBag.tieDestinationNoteId&&-1===this._noteIdBag.slurDestinationNoteId||t.set(this.id,this),-1!==this._noteIdBag.hammerPullOriginNoteId&&(this.hammerPullOrigin=t.get(this._noteIdBag.hammerPullOriginNoteId),this.hammerPullOrigin.hammerPullDestination=this),-1!==this._noteIdBag.tieOriginNoteId&&(this.tieOrigin=t.get(this._noteIdBag.tieOriginNoteId),this.tieOrigin.tieDestination=this),-1!==this._noteIdBag.slurOriginNoteId&&(this.slurOrigin=t.get(this._noteIdBag.slurOriginNoteId),this.slurOrigin.slurDestination=this),this._noteIdBag=null}else{if(!this.isTieDestination&&null===this.tieOrigin)return;let e=this.tieOrigin??ee.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 Z),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Z),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Z),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Z),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Z),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Z),this._noteIdBag.hammerPullDestinationNoteId=t,!0}return!1}}ee.GlobalNoteId=0,ee.MaxOffsetForSameLineSearch=3,ee.NoteIdLookupKey="NoteIdLookup";class te{constructor(e){this._isEqualLengthTuplet=!0,this.totalDuration=0,this.beats=[],this.isFull=!1,this.voice=e}check(e){if(0===this.beats.length)return this.beats.push(e),this.totalDuration+=e.playbackDuration,!0;if(e.graceType!==f.None)return!0;if(e.voice!==this.voice||this.isFull||e.tupletNumerator!==this.beats[0].tupletNumerator||e.tupletDenominator!==this.beats[0].tupletDenominator)return!1;if(e.playbackDuration!==this.beats[0].playbackDuration&&(this._isEqualLengthTuplet=!1),this.beats.push(e),this.totalDuration+=e.playbackDuration,this._isEqualLengthTuplet)this.beats.length===this.beats[0].tupletNumerator&&(this.isFull=!0);else{let e=this.beats[0].tupletNumerator/this.beats[0].tupletDenominator|0;for(let t of te.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}te.HalfTicks=1920,te.QuarterTicks=960,te.EighthTicks=480,te.SixteenthTicks=240,te.ThirtySecondTicks=120,te.SixtyFourthTicks=60,te.OneHundredTwentyEighthTicks=30,te.TwoHundredFiftySixthTicks=15,te.AllTicks=[te.HalfTicks,te.QuarterTicks,te.EighthTicks,te.SixteenthTicks,te.ThirtySecondTicks,te.SixtyFourthTicks,te.OneHundredTwentyEighthTicks,te.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"}(F||(F={}));class ie{static clone(e){const t=new U;return t.offset=e.offset,t.value=e.value,t}}class se{static clone(e){const t=new ee;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 i of e.bendPoints)t.addBendPoint(ie.clone(i))}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 ae{static clone(e){const t=new H;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class re{static clone(e){const t=new oe;t.index=e.index,t.notes=[];for(const i of e.notes)t.addNote(se.clone(i));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 i of e.automations)t.automations.push(ae.clone(i));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 i of e.whammyBarPoints)t.addWhammyBarPoint(ie.clone(i))}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 ne{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"}(L||(L={}));class oe{constructor(){this.id=oe._globalBeatId++,this.index=0,this.previousBeat=null,this.nextBeat=null,this.notes=[],this.noteStringLookup=new Map,this.noteValueLookup=new Map,this.isEmpty=!1,this.whammyStyle=l.Default,this.ottava=o.Regular,this.fermata=null,this.isLegatoOrigin=!1,this.minNote=null,this.maxNote=null,this.maxStringNote=null,this.minStringNote=null,this.duration=p.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fadeIn=!1,this.lyrics=null,this.hasRasgueado=!1,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.brushType=d.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=F.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=_.None,this.chordId=null,this.graceType=f.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=N.None,this.tremoloSpeed=null,this.crescendo=u.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.dynamics=g.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=L.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===p.Whole}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==F.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===F.None&&(this.whammyBarType=F.Custom)}removeWhammyBarPoint(e){const t=this.whammyBarPoints;if(null===t||e<0||e>=t.length)return;t.splice(e,1);let i=t[e];if(i===this.maxWhammyPoint){this.maxWhammyPoint=null;for(let e of t)(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e)}if(i===this.minWhammyPoint){this.minWhammyPoint=null;for(let e of t)(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e)}}addNote(e){e.beat=this,e.index=this.notes.length,this.notes.push(e),e.isStringed&&this.noteStringLookup.set(e.string,e)}removeNote(e){let t=this.notes.indexOf(e);t>=0&&(this.notes.splice(t,1),e.isStringed&&this.noteStringLookup.delete(e.string))}getAutomation(e){for(let t=0,i=this.automations.length;t<i;t++){let i=this.automations[t];if(i.type===e)return i}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=z.toTicks(this.duration);return 2===this.dots?e=z.applyDot(e,!0):1===this.dots&&(e=z.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=z.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){let e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case f.BeforeBeat:case f.OnBeat:switch(this.duration){case p.Sixteenth:this.playbackDuration=z.toTicks(p.SixtyFourth);break;case p.ThirtySecond:this.playbackDuration=z.toTicks(p.OneHundredTwentyEighth);break;default:this.playbackDuration=z.toTicks(p.ThirtySecond)}this.displayDuration=0;break;case f.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;let t=this.previousBeat;t&&t.graceType===f.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){let e=this.previousBeat,t=e?e.tupletGroup:null;(this.hasTuplet||this.graceType!==f.None&&t)&&(e&&t&&t.check(this)||(t=new te(this.voice),t.check(this)),this.tupletGroup=t)}finish(t,i=null){switch(null===this.getAutomation(r.Instrument)&&0===this.index&&0===this.voice.index&&0===this.voice.bar.index&&0===this.voice.bar.staff.index&&this.automations.push(H.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case f.OnBeat:case f.BeforeBeat:let e=this.graceGroup.beats.length;this.duration=1===e?p.Eighth:2===e?p.Sixteenth:p.ThirtySecond}let s=t?t.notation.notationMode:e.NotationMode.GuitarPro,a="grad"===this.text||"grad."===this.text;a&&s===e.NotationMode.SongBook&&(this.text="");let n=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let o=0,h=!1;for(let r=0,d=this.notes.length;r<d;r++){let d=this.notes[r];if(d.dynamics=this.dynamics,d.finish(t,i),d.isLetRing&&(this.isLetRing=!0),d.isPalmMute&&(this.isPalmMute=!0),s===e.NotationMode.SongBook&&d.hasBend&&this.graceType!==f.BendGrace){if(!d.isTieOrigin)switch(d.bendType){case c.Bend:case c.PrebendRelease:case c.PrebendBend:n=!0}a||d.bendStyle===l.Gradual?(a=!0,d.bendStyle=l.Gradual,n=!1):d.bendStyle=l.Fast}d.isVisible&&(o++,(!this.minNote||d.realValue<this.minNote.realValue)&&(this.minNote=d),(!this.maxNote||d.realValue>this.maxNote.realValue)&&(this.maxNote=d),(!this.minStringNote||d.string<this.minStringNote.string)&&(this.minStringNote=d),(!this.maxStringNote||d.string>this.maxStringNote.string)&&(this.maxStringNote=d),d.hasEffectSlur&&(h=!0))}if(h&&(this.effectSlurOrigin?(this.effectSlurOrigin.effectSlurDestination=this.nextBeat,this.effectSlurOrigin.effectSlurDestination&&(this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin),this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=this.nextBeat,this.effectSlurDestination&&(this.effectSlurDestination.effectSlurOrigin=this))),this.notes.length>0&&0===o&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&t&&t.notation.notationMode===e.NotationMode.GuitarPro&&(this.previousBeat.isLetRing&&(this.isLetRing=!0),this.previousBeat.isPalmMute&&(this.isPalmMute=!0));else{let e=this.previousBeat;for(;e&&e.isRest;)this.isLetRing||(e.isLetRing=!1),this.isPalmMute||(e.isPalmMute=!1),e=e.previousBeat}const d=this.whammyBarPoints;if(null!==d&&d.length>0&&this.whammyBarType===F.Custom){s===e.NotationMode.SongBook&&(this.whammyStyle=a?l.Gradual:l.Fast);let t=!!this.previousBeat&&this.previousBeat.hasWhammyBar;if(this.isContinuedWhammy=t,4===d.length){let i=d[0],a=d[1],r=d[2],n=d[3];a.value===r.value&&(i.value<a.value&&a.value<n.value||i.value>a.value&&a.value>n.value?(0===i.value||t?this.whammyBarType=F.Dive:this.whammyBarType=F.PrediveDive,d.splice(2,1),d.splice(1,1)):i.value>a.value&&a.value<n.value||i.value<a.value&&a.value>n.value?(this.whammyBarType=F.Dip,a.offset!==r.offset&&s!==e.NotationMode.SongBook||d.splice(2,1)):i.value===a.value&&a.value===n.value&&(0===i.value||t?this.whammyBarType=F.Hold:this.whammyBarType=F.Predive,d.splice(2,1),d.splice(1,1)))}}if(this.updateDurations(),n){let e=re.clone(this);e.id=oe._globalBeatId++,e.pickStroke=N.None;for(let t=0,i=e.notes.length;t<i;t++){let i=e.notes[t],s=this.notes[t];if(i.bendType=c.None,i.maxBendPoint=null,i.bendPoints=null,i.bendStyle=l.Default,i.id=ee.GlobalNoteId++,s.isTieOrigin&&(i.tieDestination=s.tieDestination,s.tieDestination.tieOrigin=i),s.isTieDestination&&(i.tieOrigin=s.tieOrigin?s.tieOrigin:null,s.tieOrigin.tieDestination=i),s.hasBend&&s.isTieOrigin){let e=ee.findTieOrigin(s);if(e&&e.hasBend){i.bendType=c.Hold;let e=s.bendPoints[s.bendPoints.length-1];i.addBendPoint(new U(0,e.value)),i.addBendPoint(new U(U.MaxPosition,e.value))}}i.isTieDestination=!0}this.graceType=f.BendGrace,this.graceGroup=new ne,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new ne,e.graceGroup.addBeat(this),e.graceGroup.isComplete=!0,e.graceGroup.finish()}}isBefore(e){return this.voice.bar.index<e.voice.bar.index||e.voice.bar.index===this.voice.bar.index&&this.index<e.index}isAfter(e){return this.voice.bar.index>e.voice.bar.index||e.voice.bar.index===this.voice.bar.index&&this.index>e.index}hasNoteOnString(e){return this.noteStringLookup.has(e)}getNoteWithRealValue(e){return this.noteValueLookup.has(e)?this.noteValueLookup.get(e):null}chain(e=null){for(const t of this.notes)this.noteValueLookup.set(t.realValue,t),t.chain(e)}}oe._globalBeatId=0;class he{constructor(){this.name="",this.firstFret=1,this.strings=[],this.barreFrets=[],this.showName=!0,this.showDiagram=!0,this.showFingering=!0}get uniqueId(){return[this.name,this.firstFret.toString(),this.strings.join(","),this.barreFrets.join(","),this.showDiagram.toString(),this.showFingering.toString(),this.showName.toString()].join("|")}}!function(e){e[e.Cb=-7]="Cb",e[e.Gb=-6]="Gb",e[e.Db=-5]="Db",e[e.Ab=-4]="Ab",e[e.Eb=-3]="Eb",e[e.Bb=-2]="Bb",e[e.F=-1]="F",e[e.C=0]="C",e[e.G=1]="G",e[e.D=2]="D",e[e.A=3]="A",e[e.E=4]="E",e[e.B=5]="B",e[e.FSharp=6]="FSharp",e[e.CSharp=7]="CSharp"}(M||(M={})),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"}(I||(I={}));class le{constructor(){this.startBar=0,this.text=""}finish(e=!1){this.chunks=[],this.parse(this.text,0,this.chunks,e)}parse(e,t,i,s){if(!e)return;let a=I.Begin,r=I.Begin,n=!1,o=0;for(;t<e.length;){let i=e.charCodeAt(t);switch(a){case I.IgnoreSpaces:switch(i){case le.CharCodeLF:case le.CharCodeCR:case le.CharCodeTab:break;case le.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case I.Begin:if(i!==le.CharCodeBrackedOpen){o=t,a=I.Text;continue}a=I.Comment;break;case I.Comment:if(i===le.CharCodeBrackedClose)a=I.Begin;break;case I.Text:switch(i){case le.CharCodeDash:a=I.Dash;break;case le.CharCodeCR:case le.CharCodeLF:case le.CharCodeSpace:let i=e.substr(o,t-o);this.addChunk(i,s),a=I.IgnoreSpaces,r=I.Begin}break;case I.Dash:if(i!==le.CharCodeDash){let i=e.substr(o,t-o);this.addChunk(i,s),n=!0,a=I.IgnoreSpaces,r=I.Begin;continue}}t+=1}a===I.Text&&t!==o&&this.addChunk(e.substr(o,t-o),s)}addChunk(e,t){e=this.prepareChunk(e),(!t||e.length>0&&"-"!==e)&&this.chunks.push(e)}prepareChunk(e){let t=e.split("+").join(" "),i=t.length;for(;i>0&&"_"===t.charAt(i-1);)i--;return i!==t.length?t.substr(0,i):t}}le.CharCodeLF=10,le.CharCodeTab=9,le.CharCodeCR=13,le.CharCodeSpace=32,le.CharCodeBrackedClose=93,le.CharCodeBrackedOpen=91,le.CharCodeDash=45,function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(D||(D={})),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"}(A||(A={}));class ce{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=M.C,this.keySignatureType=D.Major,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.tripletFeel=A.NoTripletFeel,this.section=null,this.tempoAutomation=null,this.fermata=null,this.start=0,this.isAnacrusis=!1,this.displayScale=1,this.displayWidth=-1}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}calculateDuration(e=!0){if(this.isAnacrusis&&e){let e=0;for(let t of this.score.tracks)for(let i of t.staves){let t=this.index<i.bars.length?i.bars[this.index].calculateDuration():0;t>e&&(e=t)}return e}return this.timeSignatureNumerator*z.valueToTicks(this.timeSignatureDenominator)}addFermata(e,t){let i=this.fermata;null===i&&(i=new Map,this.fermata=i),i.set(e,t)}getFermata(e){const t=this.fermata;return null===t?null:t.has(e.playbackStart)?t.get(e.playbackStart):null}}ce.MaxAlternateEndings=8;class de{constructor(){this.hideDynamics=!1}}class ue{constructor(){this.masterBars=[],this.opening=null,this.closings=[],this.isClosed=!1}get openings(){const e=this.opening;return e?[e]:[]}get isOpened(){return!0===this.opening?.isRepeatStart}addMasterBar(e){null===this.opening&&(this.opening=e),this.masterBars.push(e),e.repeatGroup=this,e.isRepeatEnd&&(this.closings.push(e),this.isClosed=!0)}}class pe{constructor(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0,this.album="",this.artist="",this.copyright="",this.instructions="",this.music="",this.notices="",this.subTitle="",this.title="",this.words="",this.tab="",this.tempo=120,this.tempoLabel="",this.masterBars=[],this.tracks=[],this.defaultSystemsLayout=3,this.systemsLayout=[],this.stylesheet=new de}rebuildRepeatGroups(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0;for(const e of this.masterBars)this.addMasterBarToRepeatGroups(e)}addMasterBar(e){e.score=this,e.index=this.masterBars.length,0!==this.masterBars.length&&(e.previousMasterBar=this.masterBars[this.masterBars.length-1],e.previousMasterBar.nextMasterBar=e,e.start=e.previousMasterBar.start+(e.previousMasterBar.isAnacrusis?0:e.previousMasterBar.calculateDuration())),this.addMasterBarToRepeatGroups(e),this.masterBars.push(e)}addMasterBarToRepeatGroups(e){e.isRepeatStart?(this._currentRepeatGroup?.isClosed&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--),this._currentRepeatGroup=new ue,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new ue,this._openedRepeatGroups.push(this._currentRepeatGroup)),this._currentRepeatGroup.addMasterBar(e),e.isRepeatEnd&&this._properlyOpenedRepeatGroups>1&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--,this._currentRepeatGroup=this._openedRepeatGroups.length>0?this._openedRepeatGroups[this._openedRepeatGroups.length-1]:null)}addTrack(e){e.score=this,e.index=this.tracks.length,this.tracks.push(e)}finish(e){const t=new Map;for(let i=0,s=this.tracks.length;i<s;i++)this.tracks[i].finish(e,t)}}class ge{constructor(){this.marker="",this.text=""}}class fe extends G{constructor(t){super(e.AlphaTabErrorType.Format,t),Object.setPrototypeOf(this,fe.prototype)}}class me{constructor(e,t,i,s=255){this.raw=0,this.raw=(255&s)<<24|(255&e)<<16|(255&t)<<8|255&i,this.updateRgba()}updateRgba(){255===this.a?this.rgba="#"+Q.toHexString(this.r,2)+Q.toHexString(this.g,2)+Q.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 me(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){switch(typeof e){case"number":{const t=new me(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 me(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16));if(5===t.length)return new me(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16),17*parseInt(t[4],16));if(7===t.length)return new me(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16));if(9===t.length)return new me(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16),parseInt(t.substring(7,9),16))}else if(t.startsWith("rgba")||t.startsWith("rgb")){const e=t.indexOf("("),i=t.lastIndexOf(")");if(-1===e||-1===i)throw new fe("No values specified for rgb/rgba function");const s=t.substring(e+1,i).split(",");if(3===s.length)return new me(parseInt(s[0]),parseInt(s[1]),parseInt(s[2]));if(4===s.length)return new me(parseInt(s[0]),parseInt(s[1]),parseInt(s[2]),255*parseFloat(s[3]))}return null}}throw new fe("Unsupported format for color")}static toJson(e){return e.raw}}me.BlackRgb="#000000";class ye{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 be{static getTextForTuning(e,t){let i=be.getTextPartsForTuning(e);return t?i.join(""):i[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 be._defaultTunings.has(e)?be._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return be._sevenStrings;case 6:return be._sixStrings;case 5:return be._fiveStrings;case 4:return be._fourStrings}return[]}static initialize(){be._defaultTunings.set(7,new be("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),be._sevenStrings.push(be._defaultTunings.get(7)),be._defaultTunings.set(6,new be("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),be._sixStrings.push(be._defaultTunings.get(6)),be._sixStrings.push(new be("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),be._sixStrings.push(new be("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),be._sixStrings.push(new be("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),be._sixStrings.push(new be("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),be._sixStrings.push(new be("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),be._sixStrings.push(new be("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),be._sixStrings.push(new be("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),be._sixStrings.push(new be("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),be._sixStrings.push(new be("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),be._sixStrings.push(new be("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),be._sixStrings.push(new be("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),be._sixStrings.push(new be("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),be._sixStrings.push(new be("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),be._sixStrings.push(new be("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),be._sixStrings.push(new be("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),be._sixStrings.push(new be("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),be._sixStrings.push(new be("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),be._sixStrings.push(new be("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),be._sixStrings.push(new be("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),be._sixStrings.push(new be("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),be._sixStrings.push(new be("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),be._sixStrings.push(new be("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),be._sixStrings.push(new be("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),be._sixStrings.push(new be("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),be._sixStrings.push(new be("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),be._sixStrings.push(new be("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),be._sixStrings.push(new be("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),be._sixStrings.push(new be("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),be._sixStrings.push(new be("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),be._sixStrings.push(new be("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),be._defaultTunings.set(5,new be("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),be._fiveStrings.push(be._defaultTunings.get(5)),be._fiveStrings.push(new be("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),be._fiveStrings.push(new be("Banjo Open D Tuning",[62,57,54,50,69],!1)),be._fiveStrings.push(new be("Banjo Open G Tuning",[62,59,55,50,67],!1)),be._fiveStrings.push(new be("Banjo G Minor Tuning",[62,58,55,50,67],!1)),be._fiveStrings.push(new be("Banjo G Modal Tuning",[62,57,55,50,67],!1)),be._defaultTunings.set(4,new be("Bass Standard Tuning",[43,38,33,28],!0)),be._fourStrings.push(be._defaultTunings.get(4)),be._fourStrings.push(new be("Bass Tune down ½ step",[42,37,32,27],!1)),be._fourStrings.push(new be("Bass Tune down 1 step",[41,36,31,26],!1)),be._fourStrings.push(new be("Bass Tune down 2 step",[39,34,29,24],!1)),be._fourStrings.push(new be("Bass Dropped D Tuning",[43,38,33,26],!1)),be._fourStrings.push(new be("Ukulele C Tuning",[45,40,36,43],!1)),be._fourStrings.push(new be("Ukulele G Tuning",[52,47,43,38],!1)),be._fourStrings.push(new be("Mandolin Standard Tuning",[64,57,50,43],!1)),be._fourStrings.push(new be("Mandolin or Violin Tuning",[76,69,62,55],!1)),be._fourStrings.push(new be("Viola Tuning",[69,62,55,48],!1)),be._fourStrings.push(new be("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){let t=be.getPresetsFor(e.length);for(let i=0,s=t.length;i<s;i++){let s=t[i],a=!0;for(let t=0,i=e.length;t<i;t++)if(e[t]!==s.tunings[t]){a=!1;break}if(a)return s}return null}constructor(e="",t=null,i=!1){this.isStandard=i,this.name=e,this.tunings=t??[]}finish(){const e=be.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}be._sevenStrings=[],be._sixStrings=[],be._fiveStrings=[],be._fourStrings=[],be._defaultTunings=new Map,be.defaultAccidentals=["","#","","#","","","#","","#","","#",""],be.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],be.initialize();class Se{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new be("",[],!1),this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=5}get tuning(){return this.stringTuning.tunings}get tuningName(){return this.stringTuning.name}get isStringed(){return this.stringTuning.tunings.length>0}finish(e,t=null){this.stringTuning.finish();for(let i=0,s=this.bars.length;i<s;i++)this.bars[i].finish(e,t)}addChord(e,t){t.staff=this;let i=this.chords;null===i&&(i=new Map,this.chords=i),i.set(e,t)}hasChord(e){return this.chords?.has(e)??!1}getChord(e){return this.chords?.get(e)??null}addBar(e){let t=this.bars;e.staff=this,e.index=t.length,t.length>0&&(e.previousBar=t[t.length-1],e.previousBar.nextBar=e),t.push(e)}}class we{constructor(){this.index=0,this.staves=[],this.playbackInfo=new ye,this.color=new me(200,0,0,255),this.name="",this.shortName="",this.defaultSystemsLayout=3,this.systemsLayout=[],this.percussionArticulations=[]}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new Se)}addStaff(e){e.index=this.staves.length,e.track=this,this.staves.push(e)}finish(e,t=null){this.shortName||(this.shortName=this.name,this.shortName.length>we.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,we.ShortNameMaxLength)));for(let i=0,s=this.staves.length;i<s;i++)this.staves[i].finish(e,t)}applyLyrics(e){for(let t of e)t.finish();let t=this.staves[0];for(let i=0;i<e.length;i++){let s=e[i];if(s.startBar>=0&&s.startBar<t.bars.length){let a=t.bars[s.startBar].voices[0].beats[0];for(let t=0;t<s.chunks.length&&a;t++){for(;a&&(a.isEmpty||a.isRest);)a=a.nextBeat;a&&(a.lyrics||(a.lyrics=new Array(e.length),a.lyrics.fill("")),a.lyrics[i]=s.chunks[t],a=a.nextBeat)}}}}}we.ShortNameMaxLength=10;let _e=class e{constructor(){this.id=e._globalBarId++,this.index=0,this.beats=[],this.isEmpty=!0}insertBeat(e,t){t.nextBeat=e.nextBeat,t.nextBeat&&(t.nextBeat.previousBeat=t),t.previousBeat=e,t.voice=this,e.nextBeat=t,this.beats.splice(e.index+1,0,t)}addBeat(e){e.voice=this,e.index=this.beats.length,this.beats.push(e),e.isEmpty||(this.isEmpty=!1)}chain(e,t=null){if(this.bar){if(e.index<this.beats.length-1)e.nextBeat=this.beats[e.index+1],e.nextBeat.previousBeat=e;else if(e.isLastOfVoice&&e.voice.bar.nextBar){let t=this.bar.nextBar.voices[this.index];t.beats.length>0?(e.nextBeat=t.beats[0],e.nextBeat.previousBeat=e):e.nextBeat.previousBeat=e}e.chain(t)}}addGraceBeat(e){if(0===this.beats.length)return void this.addBeat(e);let t=this.beats[this.beats.length-1];this.beats.splice(this.beats.length-1,1),this.addBeat(e),this.addBeat(t),this.isEmpty=!1}getBeatAtPlaybackStart(e){return this._beatLookup.has(e)?this._beatLookup.get(e):null}finish(e,t=null){this._beatLookup=new Map;let i=null;for(let e=0;e<this.beats.length;e++){let s=this.beats[e];s.index=e,this.chain(s,t),s.graceType===f.None?(s.graceGroup=i,i&&(i.isComplete=!0),i=null):(i||(i=new ne),i.addBeat(s))}let s=0,a=0;for(let i=0;i<this.beats.length;i++){let r=this.beats[i];if(r.index=i,r.finish(e,t),r.graceType===f.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==f.BendGrace){let i=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case f.BeforeBeat:e.previousBeat?(e.previousBeat.playbackDuration-=i,a=e.previousBeat.voice==this?e.previousBeat.playbackStart+e.previousBeat.playbackDuration:-i):a=-i;for(const e of r.graceGroup.beats)this._beatLookup.delete(e.playbackStart),e.playbackStart=a,this._beatLookup.set(e.playbackStart,r),a+=e.playbackDuration;break;case f.OnBeat:r.playbackDuration-=i,a=t.voice===this?t.playbackStart+t.playbackDuration:-i}}}r.displayStart=s,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=s,r.playbackStart=a;r.finishTuplet(),r.graceGroup&&r.graceGroup.finish(),s+=r.displayDuration,a+=r.playbackDuration}}calculateDuration(){if(this.isEmpty||0===this.beats.length)return 0;let e=this.beats[this.beats.length-1],t=this.beats[0];return e.playbackStart+e.playbackDuration-t.playbackStart}};_e._globalBarId=0;class Be{static float64ToBytes(e){return Be._dataView.setFloat64(0,e,!0),this._conversionByteArray}static bytesToFloat64(e){throw Be._conversionByteArray.set(e,0),Be._dataView.getFloat64(0,!0)}static uint16ToInt16(e){return Be._dataView.setUint16(0,e,!0),Be._dataView.getInt16(0,!0)}static int16ToUint32(e){return Be._dataView.setInt16(0,e,!0),Be._dataView.getUint32(0,!0)}static int32ToUint16(e){return Be._dataView.setInt32(0,e,!0),Be._dataView.getUint16(0,!0)}static int32ToInt16(e){return Be._dataView.setInt32(0,e,!0),Be._dataView.getInt16(0,!0)}static int32ToUint32(e){return Be._dataView.setInt32(0,e,!0),Be._dataView.getUint32(0,!0)}static uint8ToInt8(e){return Be._dataView.setUint8(0,e),Be._dataView.getInt8(0)}}Be._conversionBuffer=new ArrayBuffer(8),Be._conversionByteArray=new Uint8Array(Be._conversionBuffer),Be._dataView=new DataView(Be._conversionBuffer);class Te{static readInt32BE(e){return e.readByte()<<24|e.readByte()<<16|e.readByte()<<8|e.readByte()}static readInt32LE(e){let t=e.readByte(),i=e.readByte(),s=e.readByte();return e.readByte()<<24|s<<16|i<<8|t}static readUInt32LE(e){let t=e.readByte(),i=e.readByte(),s=e.readByte();return e.readByte()<<24|s<<16|i<<8|t}static decodeUInt32LE(e,t){let i=e[t],s=e[t+1],a=e[t+2];return e[t+3]<<24|a<<16|s<<8|i}static readUInt16LE(e){let t=e.readByte(),i=e.readByte();return Be.int32ToUint16(i<<8|t)}static readInt16LE(e){let t=e.readByte(),i=e.readByte();return Be.int32ToInt16(i<<8|t)}static readUInt32BE(e){let t=e.readByte(),i=e.readByte(),s=e.readByte(),a=e.readByte();return Be.int32ToUint32(t<<24|i<<16|s<<8|a)}static readUInt16BE(e){let t=e.readByte(),i=e.readByte();return Be.int32ToInt16(t<<8|i)}static readInt16BE(e){let t=e.readByte(),i=e.readByte();return Be.int32ToInt16(t<<8|i)}static readByteArray(e,t){let i=new Uint8Array(t);return e.read(i,0,t),i}static read8BitChars(e,t){let i=new Uint8Array(t);return e.read(i,0,i.length),Te.toString(i,"utf-8")}static read8BitString(e){let t="",i=e.readByte();for(;0!==i;)t+=String.fromCharCode(i),i=e.readByte();return t}static read8BitStringLength(e,t){let i="",s=-1;for(let a=0;a<t;a++){let t=e.readByte();0===t&&-1===s&&(s=a),i+=String.fromCharCode(t)}let a=i;return s>=0?a.substr(0,s):a}static readSInt8(e){let t=e.readByte();return-256*((255&t)>>7)+(255&t)}static readInt24(e,t){let i=e[t]|e[t+1]<<8|e[t+2]<<16;return 8388608&~i||(i|=255<<24),i}static readInt16(e,t){return Be.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){let i=Te.detectEncoding(e);return i&&(t=i),t||(t="utf-8"),new TextDecoder(t).decode(e.buffer)}static detectEncoding(e){return e.length>2&&254===e[0]&&255===e[1]?"utf-16be":e.length>2&&255===e[0]&&254===e[1]?"utf-16le":e.length>4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3]?"utf-32be":e.length>4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3]?"utf-32le":null}static stringToBytes(e){return(new TextEncoder).encode(e)}static writeInt32BE(e,t){e.writeByte(t>>24&255),e.writeByte(t>>16&255),e.writeByte(t>>8&255),e.writeByte(255&t)}static writeInt32LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255),e.writeByte(t>>16&255),e.writeByte(t>>24&255)}static writeUInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16BE(e,t){e.writeByte(t>>8&255),e.writeByte(255&t)}}class ke{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return ke.withCapacity(0)}static withCapacity(e){let t=new ke;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){let t=new ke;return t._buffer=e,t.length=e.length,t}static fromString(e){let t=Te.stringToBytes(e);return ke.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,i){let s=this.length-this.position;return s>i&&(s=i),s<=0?0:(e.set(this._buffer.subarray(this.position,this.position+s),t),this.position+=s,s)}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,i){let s=this.position+i;this.ensureCapacity(s);let a=Math.min(i,e.length-t);this._buffer.set(e.subarray(t,t+a),this.position),s>this.length&&(this.length=s),this.position=s}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 i=new Uint8Array(t);this.length>0&&i.set(this._buffer.subarray(0,0+this.length),0),this._buffer=i}}readAll(){return this.toArray()}toArray(){let e=new Uint8Array(this.length);return e.set(this._buffer.subarray(0,0+this.length),0),e}copyTo(e){e.write(this._buffer,0,this.length)}}var ve,xe,Ne,Pe,Ee,Ce,Fe,Le,Me,Ie,De,Ae,Re,Oe,Ge,Ve,He,We,ze,Ue,Xe,Ye,qe,Je,je,Qe,$e,Ke,Ze,et;!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"}(ve||(ve={}));class tt extends G{constructor(t,i,s,a,r,n,o,h=null){super(e.AlphaTabErrorType.AlphaTex,t),this.position=i,this.line=s,this.col=a,this.nonTerm=r??"",this.expected=n??ve.No,this.symbol=o??ve.No,this.symbolData=h,Object.setPrototypeOf(this,tt.prototype)}static symbolError(e,t,i,s,a,r,n=null){let o=`MalFormed AlphaTex: @${e} (line ${t}, col ${i}): Error on block ${s}`;return a!==r?(o+=`, expected a ${ve[a]} found a ${ve[r]}`,null!==n&&(o+=`: '${n}'`)):o+=`, invalid value: '${n}'`,new tt(o,e,t,i,s,a,r,n)}static errorMessage(e,t,i,s){return new tt(e=`MalFormed AlphaTex: @${t} (line ${i}, col ${s}): ${e}`,t,i,s,null,null,null,null)}}class it extends O{constructor(){super(),this._trackChannel=0,this._input="",this._ch=it.Eof,this._curChPos=0,this._line=1,this._col=0,this._lastValidSpot=[0,1,0],this._sy=ve.No,this._syData="",this._allowNegatives=!1,this._allowFloat=!1,this._allowTuning=!1,this._currentDuration=p.QuadrupleWhole,this._currentDynamics=g.PPP,this._currentTuplet=0,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=ke.empty(),this._input=e,this.settings=t}readScore(){try{if(this.data.length>0&&(this._input=Te.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this.createDefaultScore(),this._curChPos=0,this._line=1,this._col=0,this.saveValidSpot(),this._currentDuration=p.Quarter,this._currentDynamics=g.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===ve.LowerThan)throw new V("Unknown start sign '<' (meant to import as XML?)");if(this._sy===ve.Eof)throw new V("Unexpected end of file");const e=this.metaData(),t=this.bars();if(!e&&!t)throw new V("No alphaTex data found");this.consolidate(),this._score.finish(this.settings),this._score.rebuildRepeatGroups();for(const[e,t]of this._lyrics)this._score.tracks[e].applyLyrics(t);return this._score}catch(e){throw e instanceof tt?new V(e.message,e):e}}consolidate(){for(let e of this._score.tracks)for(let t of e.staves)for(;t.bars.length<this._score.masterBars.length;){let e=this.newBar(t),i=new oe;i.isEmpty=!0,e.voices[0].addBeat(i)}}error(e,t,i=!0){let s,a=!1;i?(s=this._sy,s!==ve.String&&s!==ve.Number&&s!==ve.MetaCommand||(a=!0)):s=t;let r=tt.symbolError(this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2],e,t,s,a?this._syData:null);throw this.logErrors&&J.error(this.name,r.message),r}errorMessage(e){let t=tt.errorMessage(e,this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2]);throw this.logErrors&&J.error(this.name,t.message),t}createDefaultScore(){this._score=new pe,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new we,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=be.getDefaultTuningFor(6).tunings,this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=g.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":default:return n.G2;case"f4":case"bass":return n.F4;case"c3":case"tenor":return n.C3;case"c4":case"alto":return n.C4;case"n":case"neutral":return n.Neutral}}parseClefFromInt(e){switch(e){case 43:default:return n.G2;case 65:return n.F4;case 48:return n.C3;case 60:return n.C4}}parseTripletFeelFromString(e){switch(e.toLowerCase()){case"no":case"none":default:return A.NoTripletFeel;case"t16":case"triplet-16th":return A.Triplet16th;case"t8":case"triplet-8th":return A.Triplet8th;case"d16":case"dotted-16th":return A.Dotted16th;case"d8":case"dotted-8th":return A.Dotted8th;case"s16":case"scottish-16th":return A.Scottish16th;case"s8":case"scottish-8th":return A.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return A.NoTripletFeel;case 1:return A.Triplet16th;case 2:return A.Triplet8th;case 3:return A.Dotted16th;case 4:return A.Dotted8th;case 5:return A.Scottish16th;case 6:return A.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":return M.Cb;case"gb":case"gbmajor":case"d#minor":return M.Gb;case"db":case"dbmajor":case"bbminor":return M.Db;case"ab":case"abmajor":case"fminor":return M.Ab;case"eb":case"ebmajor":case"cminor":return M.Eb;case"bb":case"bbmajor":case"gminor":return M.Bb;case"f":case"fmajor":case"dminor":return M.F;case"c":case"cmajor":case"aminor":default:return M.C;case"g":case"gmajor":case"eminor":return M.G;case"d":case"dmajor":case"bminor":return M.D;case"a":case"amajor":case"f#minor":return M.A;case"e":case"emajor":case"c#minor":return M.E;case"b":case"bmajor":case"g#minor":return M.B;case"f#":case"f#major":case"ebminor":return M.FSharp;case"c#":case"c#major":return M.CSharp}}nextChar(){return this._curChPos<this._input.length?(this._ch=this._input.charCodeAt(this._curChPos++),10===this._ch?(this._line++,this._col=0):this._col++):this._ch=it.Eof,this._ch}saveValidSpot(){this._lastValidSpot=[this._curChPos,this._line,this._col]}newSy(){for(this.saveValidSpot(),this._sy=ve.No;this._sy===ve.No;)if(this._ch===it.Eof)this._sy=ve.Eof;else if(it.isWhiteSpace(this._ch))this._ch=this.nextChar(),this.saveValidSpot();else if(47===this._ch){if(this._ch=this.nextChar(),47===this._ch)for(;13!==this._ch&&10!==this._ch&&this._ch!==it.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;this._ch!==it.Eof;)if(42===this._ch){if(this._ch=this.nextChar(),47===this._ch){this._ch=this.nextChar();break}}else this._ch=this.nextChar();else this.error("comment",ve.String,!1);this.saveValidSpot()}else if(34===this._ch||39===this._ch){let e=this._ch;this._ch=this.nextChar();let t="";for(this._sy=ve.String;this._ch!==e&&this._ch!==it.Eof;)t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._ch===it.Eof&&this.errorMessage("String opened but never closed"),this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)this._allowNegatives?(this._sy=ve.Number,this._syData=this.readNumber()):(this._sy=ve.String,this._syData=this.readName());else if(46===this._ch)this._sy=ve.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=ve.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=ve.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=ve.MetaCommand,this._syData=this.readName();else if(41===this._ch)this._sy=ve.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=ve.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=ve.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=ve.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=ve.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=ve.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this._sy=ve.Number,this._syData=this.readNumber();else if(it.isNameLetter(this._ch)){let e=this.readName(),t=this._allowTuning?Q.parseTuning(e):null;t?(this._sy=ve.Tuning,this._syData=t):(this._sy=ve.String,this._syData=e)}else this.error("symbol",ve.String,!1);return this._sy}static isNameLetter(e){return!it.isTerminal(e)&&(33<=e&&e<=47||58<=e&&e<=126||128<=e)}static isTerminal(e){return 46===e||123===e||125===e||91===e||93===e||40===e||41===e||124===e||39===e||34===e||92===e}static isWhiteSpace(e){return 9===e||10===e||11===e||13===e||32===e}isDigit(e){return e>=48&&e<=57||this._allowNegatives&&45===e||this._allowFloat&&46===e}readName(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(it.isNameLetter(this._ch)||this.isDigit(this._ch));return e}readNumber(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(this.isDigit(this._ch));return this._allowFloat?parseFloat(e):parseInt(e)}metaData(){let e=!1,t=!0;for(;this._sy===ve.MetaCommand&&t;){let i=this._syData.toLowerCase();switch(i){case"title":case"subtitle":case"artist":case"album":case"words":case"music":case"copyright":this._sy=this.newSy(),this._sy!==ve.String&&this.error(i,ve.String,!0);let s=this._syData;switch(i){case"title":this._score.title=s;break;case"subtitle":this._score.subTitle=s;break;case"artist":this._score.artist=s;break;case"album":this._score.album=s;break;case"words":this._score.words=s;break;case"music":this._score.music=s;break;case"copyright":this._score.copyright=s}this._sy=this.newSy(),e=!0;break;case"tempo":this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy===ve.Number?this._score.tempo=this._syData:this.error("tempo",ve.Number,!0),this._sy=this.newSy(),e=!0;break;default:this.handleStaffMeta()?e=!0:e?this.error("metaDataTags",ve.String,!1):t=!1}}return e?(this._sy!==ve.Dot&&this.error("song",ve.Dot,!0),this._sy=this.newSy()):this._sy===ve.Dot&&(this._sy=this.newSy()),e}handleStaffMeta(){switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===ve.Number?this._currentStaff.capo=this._syData:this.error("capo",ve.Number,!0),this._sy=this.newSy(),!0;case"tuning":this._sy=this.newSy();let e=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case ve.String:let e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?(this._currentStaff.stringTuning.tunings=[],this._currentStaff.displayTranspositionPitch=0):this.error("tuning",ve.Tuning,!0),this._sy=this.newSy();break;case ve.Tuning:let t=[];do{let e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===ve.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",ve.Tuning,!0)}return e!==this._currentStaff.tuning.length&&(this._currentStaff.chords?.size??0)>0&&this.errorMessage("Tuning must be defined before any chord"),!0;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===ve.Number){let e=this._syData;e>=0&&e<=127?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",ve.Number,!1)}else if(this._sy===ve.String){let e=this._syData.toLowerCase();this._currentTrack.playbackInfo.program=R.getValue(e)}else this.error("instrument",ve.Number,!0);return this._sy=this.newSy(),!0;case"lyrics":this._sy=this.newSy();let t=new le;return t.startBar=0,t.text="",this._sy===ve.Number&&(t.startBar=this._syData,this._sy=this.newSy()),this._sy===ve.String?(t.text=this._syData,this._sy=this.newSy()):this.error("lyrics",ve.String,!0),this._lyrics.get(this._currentTrack.index).push(t),!0;case"chord":this._sy=this.newSy();let i=new he;this.chordProperties(i),this._sy===ve.String?(i.name=this._syData,this._sy=this.newSy()):this.error("chord-name",ve.Number,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===ve.Number?i.strings.push(this._syData):this._sy===ve.String&&"x"===this._syData.toLowerCase()&&i.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,i.name),i),!0;default:return!1}}chordProperties(e){if(this._sy===ve.LBrace){for(this._sy=this.newSy();this._sy===ve.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===ve.Number)e.firstFret=this._syData;else this.error("chord-firstfret",ve.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case ve.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case ve.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",ve.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case ve.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case ve.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",ve.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case ve.String:e.showName="false"!==this._syData.toLowerCase();break;case ve.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",ve.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===ve.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",ve.String,!1)}this._sy!==ve.RBrace&&this.error("chord-properties",ve.RBrace,!0),this._sy=this.newSy()}}bars(){let e=this.bar();for(;this._sy!==ve.Eof;)if(this._sy===ve.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==ve.MetaCommand)break;this.bar()}return e}trackStaffMeta(){return this._sy===ve.MetaCommand&&("track"===this._syData.toLowerCase()&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===ve.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===ve.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy())),this._sy===ve.MetaCommand&&"staff"===this._syData.toLowerCase()&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0&&(this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this._currentStaff=this._currentTrack.staves[this._currentTrack.staves.length-1],this._currentDynamics=g.F),this.staffProperties()),!0)}staffProperties(){if(this._sy!==ve.LBrace)return;this._sy=this.newSy();let e=!1,t=!1;for(;this._sy===ve.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",ve.String,!1)}(e||t)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t),this._sy!==ve.RBrace&&this.error("staff-properties",ve.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 ce;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 i=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=be.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 s=!1,a=t.voices[0];for(;this._sy!==ve.Pipe&&this._sy!==ve.Eof&&this.beat(a);)s=!0;if(0===a.beats.length){let e=new oe;e.isEmpty=!0,a.addBeat(e)}return e||i||s}newBar(e){let t=new W;e.addBar(t),t.index>0&&(t.clef=t.previousBar.clef);let i=new _e;return t.addVoice(i),t}beat(e){this.beatDuration();let t=new oe;if(e.addBeat(t),this._sy===ve.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==ve.RParensis&&this._sy!==ve.Eof&&this.note(t););this._sy!==ve.RParensis&&this.error("note-list",ve.RParensis,!0),this._sy=this.newSy()}else if(this._sy===ve.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===ve.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==ve.Number&&this.error("duration",ve.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||it.applyTuplet(t,this._currentTuplet);let i=1;this._sy===ve.Multiply&&(this._sy=this.newSy(),this._sy!==ve.Number?this.error("multiplier",ve.Number,!0):i=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let s=0;s<i-1;s++)e.addBeat(re.clone(t));return!0}beatDuration(){if(this._sy===ve.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==ve.Number&&this.error("duration",ve.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===ve.LBrace)){for(this._sy=this.newSy();this._sy===ve.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==ve.Number&&this.error("duration-tuplet",ve.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",ve.String,!1)}this._sy!==ve.RBrace&&this.error("beat-duration",ve.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===ve.LBrace){for(this._sy=this.newSy();this._sy===ve.String;)this.applyBeatEffect(e)||this.error("beat-effects",ve.String,!1);this._sy!==ve.RBrace&&this.error("beat-effects",ve.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){let t=this._syData.toLowerCase();if("f"===t)e.fadeIn=!0;else if("v"===t)e.vibrato=_.Slight;else if("s"===t)e.slap=!0;else if("p"===t)e.pop=!0;else if("tt"===t)e.tap=!0;else if("dd"===t)e.dots=2;else if("d"===t)e.dots=1;else if("su"===t)e.pickStroke=N.Up;else if("sd"===t)e.pickStroke=N.Down;else if("tu"===t){if(this._sy=this.newSy(),this._sy!==ve.Number)return this.error("tuplet",ve.Number,!0),!1;it.applyTuplet(e,this._syData)}else if("tb"===t||"tbe"===t){let i="tbe"===t;for(this._sy=this.newSy(),this._sy!==ve.LParensis&&this.error("tremolobar-effect",ve.LParensis,!0),this._allowNegatives=!0,this._sy=this.newSy();this._sy!==ve.RParensis&&this._sy!==ve.Eof;){let t=0,s=0;i?(this._sy!==ve.Number&&this.error("tremolobar-effect",ve.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==ve.Number&&this.error("tremolobar-effect",ve.Number,!0),s=this._syData):(this._sy!==ve.Number&&this.error("tremolobar-effect",ve.Number,!0),t=0,s=this._syData),e.addWhammyBarPoint(new U(t,s)),this._sy=this.newSy()}if(null!=e.whammyBarPoints){for(;e.whammyBarPoints.length>60;)e.removeWhammyBarPoint(e.whammyBarPoints.length-1);if(i)e.whammyBarPoints.sort(((e,t)=>e.offset-t.offset));else{let t=e.whammyBarPoints.length,i=60/t|0,s=0;for(;s<t;)e.whammyBarPoints[s].offset=Math.min(60,s*i),s++}}this._allowNegatives=!1,this._sy!==ve.RParensis&&this.error("tremolobar-effect",ve.RParensis,!0)}else{if("bu"===t||"bd"===t||"au"===t||"ad"===t){switch(t){case"bu":e.brushType=d.BrushUp;break;case"bd":e.brushType=d.BrushDown;break;case"au":e.brushType=d.ArpeggioUp;break;case"ad":e.brushType=d.ArpeggioDown}return this._sy=this.newSy(),this._sy===ve.Number?(e.brushDuration=this._syData,this._sy=this.newSy(),!0):(e.updateDurations(),"bu"===t||"bd"===t?e.brushDuration=e.playbackDuration/4/e.notes.length:"au"!==t&&"ad"!==t||(e.brushDuration=e.playbackDuration/e.notes.length),!0)}if("ch"===t){this._sy=this.newSy();let t=this._syData,i=this.getChordId(this._currentStaff,t);if(!this._currentStaff.hasChord(i)){let e=new he;e.showDiagram=!1,e.name=t,this._currentStaff.addChord(i,e)}e.chordId=i}else{if("gr"===t)return this._sy=this.newSy(),"ob"===this._syData.toLowerCase()?(e.graceType=f.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=f.BendGrace,this._sy=this.newSy()):e.graceType=f.BeforeBeat,!0;if("dy"===t){switch(this._sy=this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=g.PPP;break;case"pp":e.dynamics=g.PP;break;case"p":e.dynamics=g.P;break;case"mp":e.dynamics=g.MP;break;case"mf":e.dynamics=g.MF;break;case"f":e.dynamics=g.F;break;case"ff":e.dynamics=g.FF;break;case"fff":e.dynamics=g.FFF}this._currentDynamics=e.dynamics}else if("cre"===t)e.crescendo=u.Crescendo;else{if("dec"!==t){if("tp"===t){if(this._sy=this.newSy(),e.tremoloSpeed=p.Eighth,this._sy===ve.Number){switch(this._syData){case 8:default:e.tremoloSpeed=p.Eighth;break;case 16:e.tremoloSpeed=p.Sixteenth;break;case 32:e.tremoloSpeed=p.ThirtySecond}this._sy=this.newSy()}return!0}return!1}e.crescendo=u.Decrescendo}}}return this._sy=this.newSy(),!0}getChordId(e,t){return t.toLowerCase()+e.index+e.track.index}static applyTuplet(e,t){switch(t){case 3:e.tupletNumerator=3,e.tupletDenominator=2;break;case 5:e.tupletNumerator=5,e.tupletDenominator=4;break;case 6:e.tupletNumerator=6,e.tupletDenominator=4;break;case 7:e.tupletNumerator=7,e.tupletDenominator=4;break;case 9:e.tupletNumerator=9,e.tupletDenominator=8;break;case 10:e.tupletNumerator=10,e.tupletDenominator=8;break;case 11:e.tupletNumerator=11,e.tupletDenominator=8;break;case 12:e.tupletNumerator=12,e.tupletDenominator=8;break;default:e.tupletNumerator=1,e.tupletDenominator=1}}isNoteText(e){return"x"===e||"-"===e||"r"===e}note(e){let t=!1,i=!1,s=-1,a=-1,r=-1;switch(this._sy){case ve.Number:s=this._syData;break;case ve.String:t="x"===this._syData,i="-"===this._syData,i||t?s=0:this.error("note-fret",ve.Number,!0);break;case ve.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!==ve.Dot&&this.error("note",ve.Dot,!0),this._sy=this.newSy(),this._sy!==ve.Number&&this.error("note-string",ve.Number,!0),o=this._syData,(o<1||o>this._currentStaff.tuning.length)&&this.error("note-string",ve.Number,!1),this._sy=this.newSy());let h=new ee;return n?(h.string=this._currentStaff.tuning.length-(o-1),h.isDead=t,h.isTieDestination=i,i||(h.fret=s)):(h.octave=a,h.tone=r,h.isTieDestination=i),e.addNote(h),this.noteEffects(h),!0}noteEffects(e){if(this._sy===ve.LBrace){for(this._sy=this.newSy();this._sy===ve.String;){let t=this._syData.toLowerCase();if("b"===t||"be"===t){let i="be"===t;for(this._sy=this.newSy(),this._sy!==ve.LParensis&&this.error("bend-effect",ve.LParensis,!0),this._sy=this.newSy();this._sy!==ve.RParensis&&this._sy!==ve.Eof;){let t=0,s=0;i?(this._sy!==ve.Number&&this.error("bend-effect-value",ve.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==ve.Number&&this.error("bend-effect-value",ve.Number,!0),s=this._syData):(this._sy!==ve.Number&&this.error("bend-effect-value",ve.Number,!0),s=this._syData),e.addBendPoint(new U(t,s)),this._sy=this.newSy()}const s=e.bendPoints;if(null!=s){for(;s.length>60;)s.splice(s.length-1,1);if(i)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!==ve.RParensis&&this.error("bend-effect",ve.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=y.Natural,this._sy=this.newSy();else if("ah"===t)e.harmonicType=y.Artificial,this._sy=this.newSy();else if("th"===t)e.harmonicType=y.Tap,this._sy=this.newSy();else if("ph"===t)e.harmonicType=y.Pinch,this._sy=this.newSy();else if("sh"===t)e.harmonicType=y.Semi,this._sy=this.newSy();else if("tr"===t){this._sy=this.newSy(),this._sy!==ve.Number&&this.error("trill-effect",ve.Number,!0);let t=this._syData;this._sy=this.newSy();let i=p.Sixteenth;if(this._sy===ve.Number){switch(this._syData){case 16:default:i=p.Sixteenth;break;case 32:i=p.ThirtySecond;break;case 64:i=p.SixtyFourth}this._sy=this.newSy()}e.trillValue=t+e.stringTuning,e.trillSpeed=i}else if("v"===t)this._sy=this.newSy(),e.vibrato=_.Slight;else if("sl"===t)this._sy=this.newSy(),e.slideOutType=w.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=w.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=S.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=S.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=w.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=w.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=w.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=w.PickSlideUp;else if("h"===t)this._sy=this.newSy(),e.isHammerPullOrigin=!0;else if("lht"===t)this._sy=this.newSy(),e.isLeftHandTapped=!0;else if("g"===t)this._sy=this.newSy(),e.isGhost=!0;else if("ac"===t)this._sy=this.newSy(),e.accentuated=a.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=a.Heavy;else if("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=m.Thumb;this._sy===ve.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.leftHandFinger=t}else if("rf"===t){this._sy=this.newSy();let t=m.Thumb;this._sy===ve.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else this.applyBeatEffect(e.beat)||this.error(t,ve.String,!1)}this._sy!==ve.RBrace&&this.error("note-effect",ve.RBrace,!1),this._sy=this.newSy()}}toFinger(e){switch(e){case 1:return m.Thumb;case 2:return m.IndexFinger;case 3:return m.MiddleFinger;case 4:return m.AnnularFinger;case 5:return m.LittleFinger}return m.Thumb}parseDuration(e){switch(e){case-4:return p.QuadrupleWhole;case-2:return p.DoubleWhole;case 1:return p.Whole;case 2:return p.Half;case 4:return p.Quarter;case 8:return p.Eighth;case 16:return p.Sixteenth;case 32:return p.ThirtySecond;case 64:return p.SixtyFourth;case 128:return p.OneHundredTwentyEighth;case 256:return p.TwoHundredFiftySixth;default:return p.Quarter}}barMeta(e){let t=!1,i=e.masterBar;for(;this._sy===ve.MetaCommand;){t=!0;let s=this._syData.toLowerCase();if("ts"===s)this._sy=this.newSy(),this._sy!==ve.Number&&this.error("timesignature-numerator",ve.Number,!0),i.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==ve.Number&&this.error("timesignature-denominator",ve.Number,!0),i.timeSignatureDenominator=this._syData,this._sy=this.newSy();else if("ro"===s)i.isRepeatStart=!0,this._sy=this.newSy();else if("rc"===s)this._sy=this.newSy(),this._sy!==ve.Number&&this.error("repeatclose",ve.Number,!0),this._syData>2048&&this.error("repeatclose",ve.Number,!1),i.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===s)if(this._sy=this.newSy(),this._sy===ve.LParensis){for(this._sy=this.newSy(),this._sy!==ve.Number&&this.error("alternateending",ve.Number,!0),this.applyAlternateEnding(i);this._sy===ve.Number;)this.applyAlternateEnding(i);this._sy!==ve.RParensis&&this.error("alternateending-list",ve.RParensis,!0),this._sy=this.newSy()}else this._sy!==ve.Number&&this.error("alternateending",ve.Number,!0),this.applyAlternateEnding(i);else if("ks"===s)this._sy=this.newSy(),this._sy!==ve.String&&this.error("keysignature",ve.String,!0),i.keySignature=this.parseKeySignature(this._syData),this._sy=this.newSy();else if("clef"===s){switch(this._sy=this.newSy(),this._sy){case ve.String:e.clef=this.parseClefFromString(this._syData);break;case ve.Number:e.clef=this.parseClefFromInt(this._syData);break;case ve.Tuning:let t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",ve.String,!0)}this._sy=this.newSy()}else if("tempo"===s){this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==ve.Number&&this.error("tempo",ve.Number,!0);let e=new H;e.isLinear=!1,e.type=r.Tempo,e.value=this._syData,i.tempoAutomation=e,this._sy=this.newSy()}else if("section"===s){this._sy=this.newSy(),this._sy!==ve.String&&this.error("section",ve.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==ve.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());let s=new ge;s.marker=t,s.text=e,i.section=s}else if("tf"===s){switch(this._allowTuning=!1,this._sy=this.newSy(),this._allowTuning=!0,this._sy){case ve.String:i.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case ve.Number:i.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",ve.String,!0)}this._sy=this.newSy()}else"ac"===s?(i.isAnacrusis=!0,this._sy=this.newSy()):0===e.index&&this.handleStaffMeta()||this.error("measure-effects",ve.String,!1)}if(0===i.index&&!i.tempoAutomation){let e=new H;e.isLinear=!1,e.type=r.Tempo,e.value=this._score.tempo,i.tempoAutomation=e}return t}applyAlternateEnding(e){let t=this._syData;t<1&&this.error("alternateending",ve.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}}it.Eof=0;class st extends O{get name(){return"Guitar Pro 3-5"}constructor(){super(),this._versionNumber=0,this._globalTripletFeel=A.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._beatTextChunksByTrack=new Map}readScore(){return this.readVersion(),this._score=new pe,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=at.gpReadBool(this.data)?A.Triplet8th:A.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=at.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=Te.readInt32LE(this.data),this._versionNumber>=510&&at.gpReadBool(this.data),Te.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.data.skip(38),this.data.skip(4)),this._barCount=Te.readInt32LE(this.data),this._trackCount=Te.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0&&(this._score.masterBars[0].tempoAutomation=H.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=at.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(st.VersionString))throw new V("Unsupported format");e=e.substr(st.VersionString.length+1);let t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*parseInt(e.substr(0,t))+parseInt(e.substr(t+1)),J.debug(this.name,"Guitar Pro version "+e+" detected")}readScoreInformation(){this._score.title=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?at.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding);let e=Te.readInt32LE(this.data),t="";for(let i=0;i<e;i++)i>0&&(t+="\r\n"),t+=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding)?.toString();this._score.notices=t}readLyrics(){this._lyrics=[],this._lyricsTrack=Te.readInt32LE(this.data)-1;for(let e=0;e<5;e++){let e=new le;e.startBar=Te.readInt32LE(this.data)-1,e.text=at.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(30);for(let e=0;e<10;e++)at.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){let t=new ye;t.primaryChannel=e,t.secondaryChannel=e,t.program=Te.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 ce,i=this.data.readByte();if(1&i?t.timeSignatureNumerator=this.data.readByte():e&&(t.timeSignatureNumerator=e.timeSignatureNumerator),2&i?t.timeSignatureDenominator=this.data.readByte():e&&(t.timeSignatureDenominator=e.timeSignatureDenominator),t.isRepeatStart=!!(4&i),8&i&&(t.repeatCount=this.data.readByte()+(this._versionNumber>=500?0:1)),16&i&&this._versionNumber<500){let i=e,s=0;for(;i&&(!i.isRepeatEnd||i===e)&&!i.isRepeatStart;)s|=i.alternateEndings,i=i.previousMasterBar;let a=0,r=this.data.readByte();for(let e=0;e<8;e++){let t=1<<e;r>e&&!(s&t)&&(a|=t)}t.alternateEndings=a}if(32&i){let e=new ge;e.text=at.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",at.gpReadColor(this.data,!1),t.section=e}if(64&i?(t.keySignature=Te.readSInt8(this.data),t.keySignatureType=this.data.readByte()):e&&(t.keySignature=e.keySignature,t.keySignatureType=e.keySignatureType),this._versionNumber>=500&&3&i&&this.data.skip(4),this._versionNumber>=500&&(t.alternateEndings=this.data.readByte()),this._versionNumber>=500){switch(this.data.readByte()){case 1:t.tripletFeel=A.Triplet8th;break;case 2:t.tripletFeel=A.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=!!(128&i),this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){let e=new we;e.ensureStaveCount(1),this._score.addTrack(e);let t=e.staves[0],i=this.data.readByte();e.name=at.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),1&i&&(t.isPercussion=!0);let s=Te.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){let t=Te.readInt32LE(this.data);s>e&&a.push(t)}t.stringTuning.tunings=a;let r=Te.readInt32LE(this.data),n=Te.readInt32LE(this.data)-1,o=Te.readInt32LE(this.data)-1;if(this.data.skip(4),n>=0&&n<this._playbackInfos.length){let s=this._playbackInfos[n];s.port=r,s.isSolo=!!(16&i),s.isMute=!!(32&i),s.secondaryChannel=o,R.isGuitar(s.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=s}t.capo=Te.readInt32LE(this.data),e.color=at.gpReadColor(this.data,!1),this._versionNumber>=500&&(this.data.readByte(),this.data.readByte(),this.data.skip(43)),this._versionNumber>=510&&(this.data.skip(4),at.gpReadStringIntByte(this.data,this.settings.importer.encoding),at.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 W,i=e.staves[0];i.isPercussion&&(t.clef=n.Neutral),i.addBar(t);let s=1;this._versionNumber>=500&&(this.data.readByte(),s=2);for(let i=0;i<s;i++)this.readVoice(e,t)}readVoice(e,t){let i=Te.readInt32LE(this.data);if(0===i)return;let s=new _e;t.addVoice(s);for(let a=0;a<i;a++)this.readBeat(e,t,s)}readBeat(e,t,i){let s=new oe,a=this.data.readByte();if(1&a&&(s.dots=1),64&a){let e=this.data.readByte();s.isEmpty=!(2&e)}switch(i.addBeat(s),Te.readSInt8(this.data)){case-2:s.duration=p.Whole;break;case-1:s.duration=p.Half;break;case 0:s.duration=p.Quarter;break;case 1:s.duration=p.Eighth;break;case 2:s.duration=p.Sixteenth;break;case 3:s.duration=p.ThirtySecond;break;case 4:s.duration=p.SixtyFourth;break;default:s.duration=p.Quarter}if(32&a)switch(s.tupletNumerator=Te.readInt32LE(this.data),s.tupletNumerator){case 1:s.tupletDenominator=1;break;case 3:s.tupletDenominator=2;break;case 5:case 6:case 7:s.tupletDenominator=4;break;case 9:case 10:case 11:case 12:case 13:s.tupletDenominator=8;break;case 2:case 4:case 8:break;default:s.tupletNumerator=1,s.tupletDenominator=1}2&a&&this.readChord(s);let r=this.settings.importer.beatTextAsLyrics&&e.index!==this._lyricsTrack;if(4&a){const t=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const i=new le;i.text=t.trim(),i.finish(!0);const s=[];for(let e=i.chunks.length-1;e>=0;e--)s.push(i.chunks[e]);this._beatTextChunksByTrack.set(e.index,s)}else s.text=t}let n=y.None;8&a&&(n=this.readBeatEffects(s)),16&a&&this.readMixTableChange(s);let o=this.data.readByte();for(let a=6;a>=0;a--)if(o&1<<a&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,i,s,6-a);n!==y.None&&(r.harmonicType=n,r.harmonicType===y.Natural&&(r.harmonicValue=this.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){this.data.readByte(),8&this.data.readByte()&&this.data.readByte()}r&&!s.isRest&&this._beatTextChunksByTrack.has(e.index)&&this._beatTextChunksByTrack.get(e.index).length>0&&(s.lyrics=[this._beatTextChunksByTrack.get(e.index).pop()])}readChord(e){let t=new he,i=Q.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=at.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Te.readInt32LE(this.data);for(let i=0;i<7;i++){let s=Te.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}let i=this.data.readByte(),s=new Uint8Array(5);this.data.read(s,0,s.length);for(let e=0;e<i;e++)t.barreFrets.push(s[e]);this.data.skip(26)}else if(0!==this.data.readByte())if(this._versionNumber>=400){this.data.skip(16),t.name=at.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Te.readInt32LE(this.data);for(let i=0;i<7;i++){let s=Te.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}let i=this.data.readByte(),s=new Uint8Array(5);this.data.read(s,0,s.length);for(let e=0;e<i;e++)t.barreFrets.push(s[e]);this.data.skip(26)}else{this.data.skip(25),t.name=at.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=Te.readInt32LE(this.data);for(let i=0;i<6;i++){let s=Te.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}this.data.skip(36)}else{let i=this._versionNumber>=406?7:6;if(t.name=at.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=Te.readInt32LE(this.data),t.firstFret>0)for(let s=0;s<i;s++){let i=Te.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}}t.name&&(e.chordId=i,e.voice.bar.staff.addChord(e.chordId,t))}readBeatEffects(e){let t=this.data.readByte(),i=0;if(this._versionNumber>=400&&(i=this.data.readByte()),e.fadeIn=!!(16&t),(this._versionNumber<400&&1&t||2&t)&&(e.vibrato=_.Slight),e.hasRasgueado=!!(1&i),32&t&&this._versionNumber>=400){switch(Te.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}}else if(32&t){switch(Te.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}this.data.skip(4)}if(4&i&&this.readTremoloBarEffect(e),64&t){let t=0,i=0;this._versionNumber<500?(i=this.data.readByte(),t=this.data.readByte()):(t=this.data.readByte(),i=this.data.readByte()),t>0?(e.brushType=d.BrushUp,e.brushDuration=st.toStrokeValue(t)):i>0&&(e.brushType=d.BrushDown,e.brushDuration=st.toStrokeValue(i))}if(2&i)switch(Te.readSInt8(this.data)){case 0:e.pickStroke=N.None;break;case 1:e.pickStroke=N.Up;break;case 2:e.pickStroke=N.Down}if(this._versionNumber<400){if(4&t)return y.Natural;if(8&t)return y.Artificial}return y.None}readTremoloBarEffect(e){this.data.readByte(),Te.readInt32LE(this.data);let t=Te.readInt32LE(this.data);if(t>0)for(let i=0;i<t;i++){let t=new U(0,0);t.offset=Te.readInt32LE(this.data),t.value=Te.readInt32LE(this.data)/st.BendStep|0,at.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 rt;t.instrument=Te.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=Te.readSInt8(this.data),t.balance=Te.readSInt8(this.data);let i=Te.readSInt8(this.data),s=Te.readSInt8(this.data),a=Te.readSInt8(this.data),n=Te.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=at.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=Te.readInt32LE(this.data),t.volume>=0&&this.data.readByte(),t.balance>=0&&this.data.readByte(),i>=0&&this.data.readByte(),s>=0&&this.data.readByte(),a>=0&&this.data.readByte(),n>=0&&this.data.readByte(),t.tempo>=0&&(t.duration=Te.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500&&this.data.readByte(),this._versionNumber>=510&&(at.gpReadStringIntByte(this.data,this.settings.importer.encoding),at.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){let i=new H;i.isLinear=!0,i.type=r.Volume,i.value=t.volume,e.automations.push(i)}if(t.balance>=0){let i=new H;i.isLinear=!0,i.type=r.Balance,i.value=t.balance,e.automations.push(i)}if(t.instrument>=0){let i=new H;i.isLinear=!0,i.type=r.Instrument,i.value=t.instrument,e.automations.push(i)}if(t.tempo>=0){let i=new H;i.isLinear=!0,i.type=r.Tempo,i.value=t.tempo,e.automations.push(i),e.voice.bar.masterBar.tempoAutomation=i}}readNote(e,t,i,s,r){let n=new ee;n.string=t.staff.tuning.length-r;let o=this.data.readByte();if(2&o?n.accentuated=a.Heavy:64&o&&(n.accentuated=a.Normal),n.isGhost=!!(4&o),32&o){let e=this.data.readByte();3===e?n.isDead=!0:2===e&&(n.isTieDestination=!0)}if(1&o&&this._versionNumber<500&&(this.data.readByte(),this.data.readByte()),16&o){let e=Te.readSInt8(this.data);n.dynamics=this.toDynamicValue(e),s.dynamics=n.dynamics}32&o&&(n.fret=Te.readSInt8(this.data)),128&o&&(n.leftHandFinger=Te.readSInt8(this.data),n.rightHandFinger=Te.readSInt8(this.data),n.isFingering=!0);let h=!1;if(this._versionNumber>=500){1&o&&(n.durationPercent=at.gpReadDouble(this.data)),h=!!(2&this.data.readByte())}if(s.addNote(n),8&o&&this.readNoteEffects(e,i,s,n),t.staff.isPercussion&&(n.percussionArticulation=n.fret,n.string=-1,n.fret=-1),h){const e=be.defaultAccidentals[n.realValueWithoutHarmonic%12];"#"===e?n.accidentalMode=b.ForceFlat:"b"===e&&(n.accidentalMode=b.ForceSharp)}return n}toDynamicValue(e){switch(e){case 1:return g.PPP;case 2:return g.PP;case 3:return g.P;case 4:return g.MP;case 5:return g.MF;case 6:default:return g.F;case 7:return g.FF;case 8:return g.FFF}}readNoteEffects(e,t,i,s){let a=this.data.readByte(),r=0;this._versionNumber>=400&&(r=this.data.readByte()),1&a&&this.readBend(s),16&a&&this.readGrace(t,s),4&r&&this.readTremoloPicking(i),8&r?this.readSlide(s):this._versionNumber<400&&4&a&&(s.slideOutType=w.Shift),16&r&&this.readArtificialHarmonic(s),32&r&&this.readTrill(s),s.isLetRing=!!(8&a),s.isHammerPullOrigin=!!(2&a),64&r&&(s.vibrato=_.Slight),s.isPalmMute=!!(2&r),s.isStaccato=!!(1&r)}readBend(e){this.data.readByte(),Te.readInt32LE(this.data);let t=Te.readInt32LE(this.data);if(t>0)for(let i=0;i<t;i++){let t=new U(0,0);t.offset=Te.readInt32LE(this.data),t.value=Te.readInt32LE(this.data)/st.BendStep|0,at.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){let i=new oe,s=new ee;switch(s.string=t.string,s.fret=Te.readSInt8(this.data),i.duration=p.ThirtySecond,i.dynamics=this.toDynamicValue(Te.readSInt8(this.data)),Te.readSInt8(this.data)){case 0:case 2:break;case 1:s.slideOutType=w.Legato,s.slideTarget=t;break;case 3:s.isHammerPullOrigin=!0}if(s.dynamics=i.dynamics,this.data.skip(1),this._versionNumber<500)i.graceType=f.BeforeBeat;else{let e=this.data.readByte();s.isDead=!!(1&e),i.graceType=2&e?f.OnBeat:f.BeforeBeat}e.addGraceBeat(i),i.addNote(s)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=p.Eighth;break;case 2:e.tremoloSpeed=p.Sixteenth;break;case 3:e.tremoloSpeed=p.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){let t=Te.readSInt8(this.data);1&t?e.slideOutType=w.Shift:2&t?e.slideOutType=w.Legato:4&t?e.slideOutType=w.OutDown:8&t&&(e.slideOutType=w.OutUp),16&t?e.slideInType=S.IntoFromBelow:32&t&&(e.slideInType=S.IntoFromAbove)}else{switch(Te.readSInt8(this.data)){case 1:e.slideOutType=w.Shift;break;case 2:e.slideOutType=w.Legato;break;case 3:e.slideOutType=w.OutDown;break;case 4:e.slideOutType=w.OutUp;break;case-1:e.slideInType=S.IntoFromBelow;break;case-2:e.slideInType=S.IntoFromAbove}}}readArtificialHarmonic(e){let t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=y.Natural,e.harmonicValue=this.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=y.Artificial;break;case 3:e.harmonicType=y.Tap,e.harmonicValue=this.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=y.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=y.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=y.Natural;break;case 3:e.harmonicType=y.Tap;break;case 4:e.harmonicType=y.Pinch;break;case 5:e.harmonicType=y.Semi;break;case 15:case 17:case 22:e.harmonicType=y.Artificial}}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=p.Sixteenth;break;case 2:e.trillSpeed=p.ThirtySecond;break;case 3:e.trillSpeed=p.SixtyFourth}}}st.VersionString="FICHIER GUITAR PRO ",st.BendStep=25;class at{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 i=e.readByte(),s=e.readByte(),a=e.readByte(),r=255;return t?r=e.readByte():e.skip(1),new me(i,s,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),at.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return at.gpReadString(e,Te.readInt32LE(e),t)}static gpReadStringIntByte(e,t){let i=Te.readInt32LE(e)-1;return e.readByte(),at.gpReadString(e,i,t)}static gpReadString(e,t,i){let s=new Uint8Array(t);return e.read(s,0,s.length),Te.toString(s,i)}static gpWriteString(e,t){const i=Te.stringToBytes(t);e.writeByte(t.length),e.write(i,0,i.length)}static gpReadStringByteLength(e,t,i){let s=e.readByte(),a=at.gpReadString(e,s,i);return s<t&&e.skip(t-s),a}}class rt{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class nt{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"}(xe||(xe={}));class ot{constructor(e){this.raw=new Map;let t=ke.fromBuffer(e),i=Te.readInt32BE(t);for(let e=0;e<i;e++){let e=at.gpReadString(t,t.readByte(),"utf-8");switch(t.readByte()){case xe.Boolean:let i=1===t.readByte();this.addValue(e,i);break;case xe.Integer:let s=Te.readInt32BE(t);this.addValue(e,s);break;case xe.Float:let a=at.gpReadFloat(t);this.addValue(e,a);break;case xe.String:let r=at.gpReadString(t,Te.readInt16BE(t),"utf-8");this.addValue(e,r);break;case xe.Point:let n=Te.readInt32BE(t),o=Te.readInt32BE(t);this.addValue(e,new U(n,o));break;case xe.Size:let h=Te.readInt32BE(t),l=Te.readInt32BE(t);this.addValue(e,new U(h,l));break;case xe.Rectangle:let c=new nt;c.x=Te.readInt32BE(t),c.y=Te.readInt32BE(t),c.w=Te.readInt32BE(t),c.h=Te.readInt32BE(t),this.addValue(e,c);break;case xe.Color:let d=at.gpReadColor(t,!0);this.addValue(e,d)}}}apply(e){for(const[t,i]of this.raw)if("StandardNotation/hideDynamics"===t)e.stylesheet.hideDynamics=i}addValue(e,t){this.raw.set(e,t)}static writeForScore(e){const t=ke.withCapacity(128);return Te.writeInt32BE(t,1),ot.writeBooleanEntry(t,"StandardNotation/hideDynamics",e.stylesheet.hideDynamics),t.toArray()}static writeBooleanEntry(e,t,i){at.gpWriteString(e,t),e.writeByte(xe.Boolean),e.writeByte(i?1:0)}}!function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(Ne||(Ne={}));class ht{constructor(){this.type=Ne.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"}(Pe||(Pe={}));class lt{constructor(){this.nodeType=Pe.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!==Pe.Element&&e.nodeType!==Pe.CDATA||(this.firstElement=e)}getAttribute(e){return this.attributes.has(e)?this.attributes.get(e):""}getElementsByTagName(e,t=!1){let i=[];return this.searchElementsByTagName(this.childNodes,i,e,t),i}searchElementsByTagName(e,t,i,s=!1){for(let a of e)a&&a.nodeType===Pe.Element&&a.localName===i&&t.push(a),s&&this.searchElementsByTagName(a.childNodes,t,i,!0)}findChildElement(e){for(let t of this.childNodes)if(t&&t.nodeType===Pe.Element&&t.localName===e)return t;return null}addElement(e){const t=new lt;return t.nodeType=Pe.Element,t.localName=e,this.addChild(t),t}get innerText(){if(this.nodeType===Pe.Element||this.nodeType===Pe.Document){if(this.firstElement&&this.firstElement.nodeType===Pe.CDATA)return this.firstElement.innerText;let e="";for(let t of this.childNodes)e+=t.innerText?.toString();return e.trim()}return this.value??""}set innerText(e){const t=new lt;t.nodeType=Pe.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new lt;t.nodeType=Pe.CDATA,t.value=e,this.childNodes=[t]}}class ct extends G{constructor(t,i,s){super(e.AlphaTabErrorType.Format,t),this.pos=0,this.xml=i,this.pos=s,Object.setPrototypeOf(this,ct.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"}(Ee||(Ee={}));class dt{static parse(e,t,i){let s=e.charCodeAt(t),a=Ee.Begin,r=Ee.Begin,n=0,o="",h=Ee.Begin,l=null,c=null,d=0,u=0;for(;t<e.length;){switch(s=e.charCodeAt(t),a){case Ee.IgnoreSpaces:switch(s){case dt.CharCodeLF:case dt.CharCodeCR:case dt.CharCodeTab:case dt.CharCodeSpace:break;default:a=r;continue}break;case Ee.Begin:if(s!==dt.CharCodeLowerThan){n=t,a=Ee.Pcdata;continue}a=Ee.IgnoreSpaces,r=Ee.BeginNode;break;case Ee.Pcdata:if(s===dt.CharCodeLowerThan){o+=e.substr(n,t-n);let s=new lt;s.nodeType=Pe.Text,s.value=o,o="",i.addChild(s),a=Ee.IgnoreSpaces,r=Ee.BeginNode}else s===dt.CharCodeAmp&&(o+=e.substr(n,t-n),a=Ee.Escape,h=Ee.Pcdata,n=t+1);break;case Ee.Cdata:if(s===dt.CharCodeBrackedClose&&e.charCodeAt(t+1)===dt.CharCodeBrackedClose&&e.charCodeAt(t+2)===dt.CharCodeGreaterThan){let s=new lt;s.nodeType=Pe.CDATA,s.value=e.substr(n,t-n),i.addChild(s),t+=2,a=Ee.Begin}break;case Ee.BeginNode:switch(s){case dt.CharCodeExclamation:if(e.charCodeAt(t+1)===dt.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new ct("Expected <![CDATA[",e,t);t+=5,a=Ee.Cdata,n=t+1}else if(e.charCodeAt(t+1)===dt.CharCodeUpperD||e.charCodeAt(t+1)===dt.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new ct("Expected <!DOCTYPE",e,t);t+=8,a=Ee.Doctype,n=t+1}else{if(e.charCodeAt(t+1)!==dt.CharCodeMinus||e.charCodeAt(t+2)!==dt.CharCodeMinus)throw new ct("Expected \x3c!--",e,t);t+=2,a=Ee.Comment,n=t+1}break;case dt.CharCodeQuestion:a=Ee.Header,n=t;break;case dt.CharCodeSlash:if(!i)throw new ct("Expected node name",e,t);n=t+1,a=Ee.IgnoreSpaces,r=Ee.Close;break;default:a=Ee.TagName,n=t;continue}break;case Ee.TagName:if(!dt.isValidChar(s)){if(t===n)throw new ct("Expected node name",e,t);l=new lt,l.nodeType=Pe.Element,l.localName=e.substr(n,t-n),i.addChild(l),a=Ee.IgnoreSpaces,r=Ee.Body;continue}break;case Ee.Body:switch(s){case dt.CharCodeSlash:a=Ee.WaitEnd;break;case dt.CharCodeGreaterThan:a=Ee.Childs;break;default:a=Ee.AttribName,n=t;continue}break;case Ee.AttribName:if(!dt.isValidChar(s)){if(n===t)throw new ct("Expected attribute name",e,t);if(c=e.substr(n,t-n),l.attributes.has(c))throw new ct(`Duplicate attribute [${c}]`,e,t);a=Ee.IgnoreSpaces,r=Ee.Equals;continue}break;case Ee.Equals:if(s!==dt.CharCodeEquals)throw new ct("Expected =",e,t);a=Ee.IgnoreSpaces,r=Ee.AttvalBegin;break;case Ee.AttvalBegin:switch(s){case dt.CharCodeDoubleQuote:case dt.CharCodeSingleQuote:o="",a=Ee.AttribVal,n=t+1,u=s}break;case Ee.AttribVal:if(s===dt.CharCodeAmp)o+=e.substr(n,t-n),a=Ee.Escape,h=Ee.AttribVal,n=t+1;else if(s===u){o+=e.substr(n,t-n);let i=o;o="",l.attributes.set(c,i),a=Ee.IgnoreSpaces,r=Ee.Body}break;case Ee.Childs:n=t=dt.parse(e,t,l),a=Ee.Begin;break;case Ee.WaitEnd:if(s!==dt.CharCodeGreaterThan)throw new ct("Expected >",e,t);a=Ee.Begin;break;case Ee.WaitEndRet:if(s===dt.CharCodeGreaterThan)return t;throw new ct("Expected >",e,t);case Ee.Close:if(!dt.isValidChar(s)){if(n===t)throw new ct("Expected node name",e,t);if(e.substr(n,t-n)!==i.localName)throw new ct("Expected </"+i.localName+">",e,t);a=Ee.IgnoreSpaces,r=Ee.WaitEndRet;continue}break;case Ee.Comment:s===dt.CharCodeMinus&&e.charCodeAt(t+1)===dt.CharCodeMinus&&e.charCodeAt(t+2)===dt.CharCodeGreaterThan&&(t+=2,a=Ee.Begin);break;case Ee.Doctype:if(s===dt.CharCodeBrackedOpen)d++;else if(s===dt.CharCodeBrackedClose)d--;else if(s===dt.CharCodeGreaterThan&&0===d){let s=new lt;s.nodeType=Pe.DocumentType,s.value=e.substr(n,t-n),i.addChild(s),a=Ee.Begin}break;case Ee.Header:s===dt.CharCodeQuestion&&e.charCodeAt(t+1)===dt.CharCodeGreaterThan&&(t++,a=Ee.Begin);break;case Ee.Escape:if(s===dt.CharCodeSemi){let i=e.substr(n,t-n);if(i.charCodeAt(0)===dt.CharCodeSharp){let e=i.charCodeAt(1)===dt.CharCodeLowerX?parseInt("0"+i.substr(1,i.length-1)):parseInt(i.substr(1,i.length-1));o+=String.fromCharCode(e)}else dt.Escapes.has(i)?o+=dt.Escapes.get(i):o+=("&"+i+";")?.toString();n=t+1,a=h}else dt.isValidChar(s)||s===dt.CharCodeSharp||(o+="&",o+=e.substr(n,t-n),n=--t+1,a=h)}t++}if(a===Ee.Begin&&(n=t,a=Ee.Pcdata),a===Ee.Pcdata){if(t!==n){o+=e.substr(n,t-n);let s=new lt;s.nodeType=Pe.Text,s.value=o,i.addChild(s)}return t}if(a===Ee.Escape&&h===Ee.Pcdata){o+="&",o+=e.substr(n,t-n);let s=new lt;return s.nodeType=Pe.Text,s.value=o,i.addChild(s),t}throw new ct("Unexpected end",e,t)}static isValidChar(e){return e>=dt.CharCodeLowerA&&e<=dt.CharCodeLowerZ||e>=dt.CharCodeUpperA&&e<=dt.CharCodeUpperZ||e>=dt.CharCode0&&e<=dt.CharCode9||e===dt.CharCodeColon||e===dt.CharCodeDot||e===dt.CharCodeUnderscore||e===dt.CharCodeMinus}}dt.CharCodeLF=10,dt.CharCodeTab=9,dt.CharCodeCR=13,dt.CharCodeSpace=32,dt.CharCodeLowerThan=60,dt.CharCodeAmp=38,dt.CharCodeBrackedClose=93,dt.CharCodeBrackedOpen=91,dt.CharCodeGreaterThan=62,dt.CharCodeExclamation=33,dt.CharCodeUpperD=68,dt.CharCodeLowerD=100,dt.CharCodeMinus=45,dt.CharCodeQuestion=63,dt.CharCodeSlash=47,dt.CharCodeEquals=61,dt.CharCodeDoubleQuote=34,dt.CharCodeSingleQuote=39,dt.CharCodeSharp=35,dt.CharCodeLowerX=120,dt.CharCodeLowerA=97,dt.CharCodeLowerZ=122,dt.CharCodeUpperA=65,dt.CharCodeUpperZ=90,dt.CharCode0=48,dt.CharCode9=57,dt.CharCodeColon=58,dt.CharCodeDot=46,dt.CharCodeUnderscore=95,dt.CharCodeSemi=59,dt.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class ut{static write(e,t,i){const s=new ut(t,i);return s.writeNode(e),s.toString()}constructor(e,t){this._result=[],this._indention=e,this._xmlHeader=t,this._currentIndention="",this._isStartOfLine=!0}writeNode(e){switch(e.nodeType){case Pe.None:break;case Pe.Element:this._result.length>0&&this.writeLine(),this.write(`<${e.localName}`);for(const[t,i]of e.attributes)this.write(` ${t}="`),this.writeAttributeValue(i),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===Pe.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case Pe.Text:e.value&&this.write(e.value);break;case Pe.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case Pe.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case Pe.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 i=e.charAt(t);switch(i){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(i)}}}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 pt extends lt{constructor(){super(),this.nodeType=Pe.Document}parse(e){dt.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return ut.write(this,e,t)}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(Ce||(Ce={}));class gt{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=p.Quarter}}class ft{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return this.path+";"+this.name+";"+this.role}}class mt{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 i=new pt;try{i.parse(e)}catch(e){throw new V("Could not parse XML",e)}if(this.parseDom(i),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 V("Root node of XML was not GPIF");this.score=new pe;for(let e of t.childNodes)if(e.nodeType===Pe.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===Pe.Element)switch(t.localName){case"Title":this.score.title=t.firstChild.innerText;break;case"SubTitle":this.score.subTitle=t.firstChild.innerText;break;case"Artist":this.score.artist=t.firstChild.innerText;break;case"Album":this.score.album=t.firstChild.innerText;break;case"Words":this.score.words=t.firstChild.innerText;break;case"Music":this.score.music=t.firstChild.innerText;break;case"WordsAndMusic":if(t.firstChild&&""!==t.firstChild.innerText){let e=t.firstChild.innerText;e&&!this.score.words&&(this.score.words=e),e&&!this.score.music&&(this.score.music=e)}break;case"Copyright":this.score.copyright=t.firstChild.innerText;break;case"Tabber":this.score.tab=t.firstChild.innerText;break;case"Instructions":this.score.instructions=t.firstChild.innerText;break;case"Notices":this.score.notices=t.firstChild.innerText;break;case"ScoreSystemsDefaultLayout":this.score.defaultSystemsLayout=parseInt(t.innerText);break;case"ScoreSystemsLayout":this.score.systemsLayout=t.innerText.split(" ").map((e=>parseInt(e)))}}parseMasterTrackNode(e){for(let t of e.childNodes)if(t.nodeType===Pe.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,i){for(let s of e.childNodes)if(s.nodeType===Pe.Element&&"Automation"===s.localName)this.parseAutomation(s,t,i)}parseAutomation(e,t,i){let s=null,a=!1,r=-1,n=0,o=0,h=null,l=0,c=null;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"Type":s=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===Pe.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(!s)return;let d=null;switch(s){case"Tempo":d=H.buildTempoAutomation(a,n,o,l);break;case"Sound":h&&i&&i.has(h)&&(d=H.buildInstrumentAutomation(a,n,i.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===Pe.Element&&"Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;let t=new we;t.ensureStaveCount(1),t.staves[0].showStandardNotation=!0;let i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"Name":t.name=s.innerText;break;case"Color":let e=s.innerText.split(" ");if(e.length>=3){let i=parseInt(e[0]),s=parseInt(e[1]),a=parseInt(e[2]);t.color=new me(i,s,a,255)}break;case"Instrument":let a=s.getAttribute("ref");(a.endsWith("-gs")||a.endsWith("GrandStaff"))&&(t.ensureStaveCount(2),t.staves[1].showStandardNotation=!0);break;case"InstrumentSet":this.parseInstrumentSet(t,s);break;case"NotationPatch":this.parseNotationPatch(t,s);break;case"ShortName":t.shortName=s.innerText;break;case"SystemsDefautLayout":t.defaultSystemsLayout=parseInt(s.innerText);break;case"SystemsLayout":t.systemsLayout=s.innerText.split(" ").map((e=>parseInt(e)));break;case"Lyrics":this.parseLyrics(i,s);break;case"Properties":this.parseTrackProperties(t,s);break;case"GeneralMidi":case"MidiConnection":case"MIDISettings":this.parseGeneralMidi(t,s);break;case"Sounds":this.parseSounds(i,t,s);break;case"PlaybackState":let r=s.innerText;t.playbackInfo.isSolo="Solo"===r,t.playbackInfo.isMute="Mute"===r;break;case"PartSounding":this.parsePartSounding(t,s);break;case"Staves":this.parseStaves(t,s);break;case"Transpose":this.parseTranspose(t,s);break;case"RSE":this.parseRSE(t,s);break;case"Automations":this.parseTrackAutomations(i,s)}this._tracksById.set(i,t)}parseTrackAutomations(e,t){const i=new Map;this._automationsPerTrackIdAndBarIndex.set(e,i),this.parseAutomations(t,i,this._soundsByTrack.get(e))}parseNotationPatch(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"LineCount":const t=parseInt(i.innerText);for(let i of e.staves)i.standardNotationLineCount=t;break;case"Elements":this.parseElements(e,i)}}parseInstrumentSet(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"Type":if("drumKit"===i.innerText)for(let t of e.staves)t.isPercussion=!0;if("drumKit"===i.innerText)for(let t of e.staves)t.isPercussion=!0;break;case"Elements":this.parseElements(e,i);break;case"LineCount":const t=parseInt(i.innerText);for(let i of e.staves)i.standardNotationLineCount=t}}parseElements(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"Element"===i.localName)this.parseElement(e,i)}parseElement(e,t){const i=t.findChildElement("Type"),s=i?i.innerText:"";for(let i of t.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"Name":case"Articulations":this.parseArticulations(e,i,s)}}parseArticulations(e,t,i){for(let s of t.childNodes)if(s.nodeType===Pe.Element&&"Articulation"===s.localName)this.parseArticulation(e,s,i)}parseArticulation(e,t,i){const s=new $;s.outputMidiNumber=-1,s.elementType=i;let a="";for(let e of t.childNodes)if(e.nodeType===Pe.Element){const t=e.innerText;switch(e.localName){case"Name":a=e.innerText;break;case"OutputMidiNumber":t.length>0&&(s.outputMidiNumber=parseInt(t));break;case"TechniqueSymbol":s.techniqueSymbol=this.parseTechniqueSymbol(t);break;case"TechniquePlacement":switch(t){case"outside":case"above":s.techniqueSymbolPlacement=C.Bottom;break;case"inside":s.techniqueSymbolPlacement=C.Middle;break;case"below":s.techniqueSymbolPlacement=C.Top}break;case"Noteheads":const i=t.split(" ");i.length>=1&&(s.noteHeadDefault=this.parseNoteHead(i[0])),i.length>=2&&(s.noteHeadHalf=this.parseNoteHead(i[1])),i.length>=3&&(s.noteHeadWhole=this.parseNoteHead(i[2])),s.noteHeadHalf==P.None&&(s.noteHeadHalf=s.noteHeadDefault),s.noteHeadWhole==P.None&&(s.noteHeadWhole=s.noteHeadDefault);break;case"StaffLine":t.length>0&&(s.staffLine=parseInt(t))}}-1!==s.outputMidiNumber?(e.percussionArticulations.push(s),a.length>0&&this._articulationByName.set(a,s)):a.length>0&&this._articulationByName.has(a)&&(this._articulationByName.get(a).staffLine=s.staffLine)}parseTechniqueSymbol(e){switch(e){case"pictEdgeOfCymbal":return P.PictEdgeOfCymbal;case"articStaccatoAbove":return P.ArticStaccatoAbove;case"noteheadParenthesis":return P.NoteheadParenthesis;case"stringsUpBow":return P.StringsUpBow;case"stringsDownBow":return P.StringsDownBow;case"guitarGolpe":return P.GuitarGolpe;default:return P.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return P.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return P.NoteheadDoubleWhole;case"noteheadWhole":return P.NoteheadWhole;case"noteheadHalf":return P.NoteheadHalf;case"noteheadBlack":return P.NoteheadBlack;case"noteheadNull":return P.NoteheadNull;case"noteheadXOrnate":return P.NoteheadXOrnate;case"noteheadTriangleUpWhole":return P.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return P.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return P.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return P.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return P.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return P.NoteheadDiamondWhiteWide;case"noteheadCircleX":return P.NoteheadCircleX;case"noteheadXWhole":return P.NoteheadXWhole;case"noteheadXHalf":return P.NoteheadXHalf;case"noteheadXBlack":return P.NoteheadXBlack;case"noteheadParenthesis":return P.NoteheadParenthesis;case"noteheadSlashedBlack2":return P.NoteheadSlashedBlack2;case"noteheadCircleSlash":return P.NoteheadCircleSlash;case"noteheadHeavyX":return P.NoteheadHeavyX;case"noteheadHeavyXHat":return P.NoteheadHeavyXHat;default:return J.warning("GPIF","Unknown notehead symbol",e),P.None}}parseStaves(e,t){let i=0;for(let s of t.childNodes)if(s.nodeType===Pe.Element&&"Staff"===s.localName){e.ensureStaveCount(i+1);let t=e.staves[i];this.parseStaff(t,s),i++}}parseStaff(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"Properties"===i.localName)this.parseStaffProperties(e,i)}parseStaffProperties(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"Property"===i.localName)this.parseStaffProperty(e,i)}parseStaffProperty(e,t){switch(t.getAttribute("name")){case"Tuning":for(let i of t.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"Pitches":let s=t.findChildElement("Pitches").innerText.split(" "),a=new Array(s.length);for(let e=0;e<a.length;e++)a[a.length-1-e]=parseInt(s[e]);e.stringTuning.tunings=a;break;case"Label":e.stringTuning.name=i.innerText}e.isPercussion||(e.showTablature=!0);break;case"DiagramCollection":case"ChordCollection":this.parseDiagramCollectionForStaff(e,t);break;case"CapoFret":let i=parseInt(t.findChildElement("Fret").innerText);e.capo=i}}parseLyrics(e,t){let i=[];for(let e of t.childNodes)if(e.nodeType===Pe.Element&&"Line"===e.localName)i.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,i)}parseLyricsLine(e){let t=new le;for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"Offset":t.startBar=parseInt(i.innerText);break;case"Text":t.text=i.innerText}return t}parseDiagramCollectionForTrack(e,t){let i=t.findChildElement("Items");for(let t of i.childNodes)if(t.nodeType===Pe.Element&&"Item"===t.localName)this.parseDiagramItemForTrack(e,t)}parseDiagramCollectionForStaff(e,t){let i=t.findChildElement("Items");for(let t of i.childNodes)if(t.nodeType===Pe.Element&&"Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){let i=new he,s=t.getAttribute("id");for(let t of e.staves)t.addChord(s,i);this.parseDiagramItemForChord(i,t)}parseDiagramItemForStaff(e,t){let i=new he,s=t.getAttribute("id");e.addChord(s,i),this.parseDiagramItemForChord(i,t)}parseDiagramItemForChord(e,t){e.name=t.getAttribute("name");let i=t.findChildElement("Diagram");if(!i)return e.showDiagram=!1,void(e.showFingering=!1);let s=parseInt(i.getAttribute("stringCount")),a=parseInt(i.getAttribute("baseFret"));e.firstFret=a+1;for(let t=0;t<s;t++)e.strings.push(-1);for(let t of i.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"Fret":let i=parseInt(t.getAttribute("string"));e.strings[s-i-1]=a+parseInt(t.getAttribute("fret"));break;case"Fingering":let r=new Map;for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"Position"===i.localName){let t=m.Unknown,s=a+parseInt(i.getAttribute("fret"));switch(i.getAttribute("finger")){case"Index":t=m.IndexFinger;break;case"Middle":t=m.MiddleFinger;break;case"Rank":t=m.AnnularFinger;break;case"Pinky":t=m.LittleFinger;break;case"Thumb":t=m.Thumb}t!==m.Unknown&&(r.has(t)?e.barreFrets.push(s):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 i of t.childNodes)if(i.nodeType===Pe.Element&&"Property"===i.localName)this.parseTrackProperty(e,i)}parseTrackProperty(e,t){switch(t.getAttribute("name")){case"Tuning":let i=t.findChildElement("Pitches").innerText.split(" "),s=new Array(i.length);for(let e=0;e<s.length;e++)s[s.length-1-e]=parseInt(i[e]);for(let t of e.staves)t.stringTuning.tunings=s,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 i of t.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"Program":e.playbackInfo.program=parseInt(i.innerText);break;case"Port":e.playbackInfo.port=parseInt(i.innerText);break;case"PrimaryChannel":e.playbackInfo.primaryChannel=parseInt(i.innerText);break;case"SecondaryChannel":e.playbackInfo.secondaryChannel=parseInt(i.innerText)}if("Percussion"===t.getAttribute("table"))for(let t of e.staves)t.isPercussion=!0}parseSounds(e,t,i){for(let s of i.childNodes)if(s.nodeType===Pe.Element&&"Sound"===s.localName)this.parseSound(e,t,s)}parseSound(e,t,i){const s=new ft;for(let e of i.childNodes)if(e.nodeType===Pe.Element)switch(e.localName){case"Name":s.name=e.innerText;break;case"Path":s.path=e.innerText;break;case"Role":s.role=e.innerText;break;case"MIDI":this.parseSoundMidi(s,e)}"Factory"!==s.role&&0!==t.playbackInfo.program||(t.playbackInfo.program=s.program),this._soundsByTrack.has(e)||this._soundsByTrack.set(e,new Map),this._soundsByTrack.get(e).set(s.uniqueId,s)}parseSoundMidi(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"Program"===i.localName)e.program=parseInt(i.innerText)}parsePartSounding(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"TranspositionPitch"===i.localName)for(let t of e.staves)t.displayTranspositionPitch=parseInt(i.innerText)}parseTranspose(e,t){let i=0,s=0;for(let e of t.childNodes)if(e.nodeType===Pe.Element)switch(e.localName){case"Chromatic":s=parseInt(e.innerText);break;case"Octave":i=parseInt(e.innerText)}for(let t of e.staves)t.displayTranspositionPitch=12*i+s}parseRSE(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"ChannelStrip"===i.localName)this.parseChannelStrip(e,i)}parseChannelStrip(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"Parameters"===i.localName)this.parseChannelStripParameters(e,i)}parseChannelStripParameters(e,t){if(t.firstChild&&t.firstChild.value){let i=t.firstChild.value.split(" ");i.length>=12&&(e.playbackInfo.balance=Math.floor(16*parseFloat(i[11])),e.playbackInfo.volume=Math.floor(16*parseFloat(i[12])))}}parseMasterBarsNode(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){let t=new ce;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"Time":let e=i.innerText.split("/");t.timeSignatureNumerator=parseInt(e[0]),t.timeSignatureDenominator=parseInt(e[1]);break;case"DoubleBar":t.isDoubleBar=!0;break;case"Section":t.section=new ge,t.section.marker=i.findChildElement("Letter").innerText,t.section.text=i.findChildElement("Text").innerText;break;case"Repeat":"true"===i.getAttribute("start").toLowerCase()&&(t.isRepeatStart=!0),"true"===i.getAttribute("end").toLowerCase()&&i.getAttribute("count")&&(t.repeatCount=parseInt(i.getAttribute("count")));break;case"AlternateEndings":let s=i.innerText.split(" "),a=0;for(let e=0;e<s.length;e++)a|=1<<-1+parseInt(s[e]);t.alternateEndings=a;break;case"Bars":this._barsOfMasterBar.push(i.innerText.split(" "));break;case"TripletFeel":switch(i.innerText){case"NoTripletFeel":t.tripletFeel=A.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=A.Triplet8th;break;case"Triplet16th":t.tripletFeel=A.Triplet16th;break;case"Dotted8th":t.tripletFeel=A.Dotted8th;break;case"Dotted16th":t.tripletFeel=A.Dotted16th;break;case"Scottish8th":t.tripletFeel=A.Scottish8th;break;case"Scottish16th":t.tripletFeel=A.Scottish16th}break;case"Key":t.keySignature=parseInt(i.findChildElement("AccidentalCount").innerText);let r=i.findChildElement("Mode");if(r)switch(r.innerText.toLowerCase()){case"major":t.keySignatureType=D.Major;break;case"minor":t.keySignatureType=D.Minor}break;case"Fermatas":this.parseFermatas(t,i);break;case"XProperties":this.parseMasterBarXProperties(i,t)}this._masterBars.push(t)}parseFermatas(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"Fermata"===i.localName)this.parseFermata(e,i)}parseFermata(e,t){let i=0,s=new ht;for(let e of t.childNodes)if(e.nodeType===Pe.Element)switch(e.localName){case"Type":switch(e.innerText){case"Short":s.type=Ne.Short;break;case"Medium":s.type=Ne.Medium;break;case"Long":s.type=Ne.Long}break;case"Length":s.length=parseFloat(e.innerText);break;case"Offset":let t=e.innerText.split("/");if(2===t.length){i=parseInt(t[0])/parseInt(t[1])*z.QuarterTime|0}}e.addFermata(i,s)}parseBars(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"Bar"===t.localName)this.parseBar(t)}parseBar(e){let t=new W,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"Voices":this._voicesOfBar.set(i,s.innerText.split(" "));break;case"Clef":switch(s.innerText){case"Neutral":t.clef=n.Neutral;break;case"G2":t.clef=n.G2;break;case"F4":t.clef=n.F4;break;case"C4":t.clef=n.C4;break;case"C3":t.clef=n.C3}break;case"Ottavia":switch(s.innerText){case"8va":t.clefOttava=o._8va;break;case"15ma":t.clefOttava=o._15ma;break;case"8vb":t.clefOttava=o._8vb;break;case"15mb":t.clefOttava=o._15mb}break;case"SimileMark":switch(s.innerText){case"Simple":t.simileMark=h.Simple;break;case"FirstOfDouble":t.simileMark=h.FirstOfDouble;break;case"SecondOfDouble":t.simileMark=h.SecondOfDouble}break;case"XProperties":this.parseBarXProperties(s,t)}this._barsById.set(i,t)}parseVoices(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"Voice"===t.localName)this.parseVoice(t)}parseVoice(e){let t=new _e,i=e.getAttribute("id");for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"Beats"===t.localName)this._beatsOfVoice.set(i,t.innerText.split(" "));this._voiceById.set(i,t)}parseBeats(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"Beat"===t.localName)this.parseBeat(t)}parseBeat(e){let t=new oe,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"Notes":this._notesOfBeat.set(i,s.innerText.split(" "));break;case"Rhythm":this._rhythmOfBeat.set(i,s.getAttribute("ref"));break;case"Fadding":"FadeIn"===s.innerText&&(t.fadeIn=!0);break;case"Tremolo":switch(s.innerText){case"1/2":t.tremoloSpeed=p.Eighth;break;case"1/4":t.tremoloSpeed=p.Sixteenth;break;case"1/8":t.tremoloSpeed=p.ThirtySecond}break;case"Chord":t.chordId=s.innerText;break;case"Hairpin":switch(s.innerText){case"Crescendo":t.crescendo=u.Crescendo;break;case"Decrescendo":t.crescendo=u.Decrescendo}break;case"Arpeggio":"Up"===s.innerText?t.brushType=d.ArpeggioUp:t.brushType=d.ArpeggioDown;break;case"Properties":this.parseBeatProperties(s,t);break;case"XProperties":this.parseBeatXProperties(s,t);break;case"FreeText":t.text=s.innerText;break;case"TransposedPitchStemOrientation":switch(s.innerText){case"Upward":t.preferredBeamDirection=Ce.Up;break;case"Downward":t.preferredBeamDirection=Ce.Down}break;case"Dynamic":switch(s.innerText){case"PPP":t.dynamics=g.PPP;break;case"PP":t.dynamics=g.PP;break;case"P":t.dynamics=g.P;break;case"MP":t.dynamics=g.MP;break;case"MF":t.dynamics=g.MF;break;case"F":t.dynamics=g.F;break;case"FF":t.dynamics=g.FF;break;case"FFF":t.dynamics=g.FFF}break;case"GraceNotes":switch(s.innerText){case"OnBeat":t.graceType=f.OnBeat;break;case"BeforeBeat":t.graceType=f.BeforeBeat}break;case"Legato":"true"===s.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":let e=new U(0,0);e.value=this.toBendValue(parseFloat(s.getAttribute("originValue"))),e.offset=this.toBendOffset(parseFloat(s.getAttribute("originOffset"))),t.addWhammyBarPoint(e);let a=new U(0,0);a.value=this.toBendValue(parseFloat(s.getAttribute("middleValue"))),a.offset=this.toBendOffset(parseFloat(s.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);let r=new U(0,0);r.value=this.toBendValue(parseFloat(s.getAttribute("middleValue"))),r.offset=this.toBendOffset(parseFloat(s.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);let n=new U(0,0);n.value=this.toBendValue(parseFloat(s.getAttribute("destinationValue"))),n.offset=this.toBendOffset(parseFloat(s.getAttribute("destinationOffset"))),t.addWhammyBarPoint(n);break;case"Ottavia":switch(s.innerText){case"8va":t.ottava=o._8va;break;case"8vb":t.ottava=o._8vb;break;case"15ma":t.ottava=o._15ma;break;case"15mb":t.ottava=o._15mb}break;case"Lyrics":t.lyrics=this.parseBeatLyrics(s),this._skipApplyLyrics=!0}this._beatById.set(i,t)}parseBeatLyrics(e){const t=[];for(let i of e.childNodes)if(i.nodeType===Pe.Element&&"Line"===i.localName)t.push(i.innerText);return t}parseBeatXProperties(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element&&"XProperty"===i.localName){let e=0;switch(i.getAttribute("id")){case"1124204545":e=parseInt(i.findChildElement("Int").innerText),t.invertBeamDirection=1===e;break;case"687935489":e=parseInt(i.findChildElement("Int").innerText),t.brushDuration=e}}}parseBarXProperties(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element&&"XProperty"===i.localName){if("1124139520"===i.getAttribute("id")){const e=i.findChildElement("Double")??i.findChildElement("Float");t.displayScale=parseFloat(e.innerText)}}}parseMasterBarXProperties(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element&&"XProperty"===i.localName){if("1124073984"===i.getAttribute("id"))t.displayScale=parseFloat(i.findChildElement("Double").innerText)}}parseBeatProperties(e,t){let i=!1,s=null,a=null,r=null,n=null,o=null;for(let h of e.childNodes)if(h.nodeType===Pe.Element&&"Property"===h.localName){switch(h.getAttribute("name")){case"Brush":"Up"===h.findChildElement("Direction").innerText?t.brushType=d.BrushUp:t.brushType=d.BrushDown;break;case"PickStroke":"Up"===h.findChildElement("Direction").innerText?t.pickStroke=N.Up:t.pickStroke=N.Down;break;case"Slapped":h.findChildElement("Enable")&&(t.slap=!0);break;case"Popped":h.findChildElement("Enable")&&(t.pop=!0);break;case"VibratoWTremBar":switch(h.findChildElement("Strength").innerText){case"Wide":t.vibrato=_.Wide;break;case"Slight":t.vibrato=_.Slight}break;case"WhammyBar":i=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":s||(s=new U(0,0)),s.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":s||(s=new U(0,0)),s.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 U(U.MaxPosition,0)),o.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new U(0,0)),o.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText))}}i&&(s||(s=new U(0,0)),o||(o=new U(U.MaxPosition,0)),t.addWhammyBarPoint(s),r&&a&&t.addWhammyBarPoint(new U(r,a)),n&&a&&t.addWhammyBarPoint(new U(n,a)),r||n||!a||t.addWhammyBarPoint(new U(U.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"Note"===t.localName)this.parseNote(t)}parseNote(e){let t=new ee,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"Properties":this.parseNoteProperties(s,t,i);break;case"AntiAccent":"normal"===s.innerText.toLowerCase()&&(t.isGhost=!0);break;case"LetRing":t.isLetRing=!0;break;case"Trill":t.trillValue=parseInt(s.innerText),t.trillSpeed=p.Sixteenth;break;case"Accent":let e=parseInt(s.innerText);1&e&&(t.isStaccato=!0),4&e&&(t.accentuated=a.Heavy),8&e&&(t.accentuated=a.Normal);break;case"Tie":"true"===s.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(s.innerText){case"Slight":t.vibrato=_.Slight;break;case"Wide":t.vibrato=_.Wide}break;case"LeftFingering":switch(t.isFingering=!0,s.innerText){case"P":t.leftHandFinger=m.Thumb;break;case"I":t.leftHandFinger=m.IndexFinger;break;case"M":t.leftHandFinger=m.MiddleFinger;break;case"A":t.leftHandFinger=m.AnnularFinger;break;case"C":t.leftHandFinger=m.LittleFinger}break;case"RightFingering":switch(t.isFingering=!0,s.innerText){case"P":t.rightHandFinger=m.Thumb;break;case"I":t.rightHandFinger=m.IndexFinger;break;case"M":t.rightHandFinger=m.MiddleFinger;break;case"A":t.rightHandFinger=m.AnnularFinger;break;case"C":t.rightHandFinger=m.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=parseInt(s.innerText)}this._noteById.set(i,t)}parseNoteProperties(e,t,i){let s=!1,a=null,r=null,n=null,o=null,h=null,l=-1,c=-1;for(let d of e.childNodes)if(d.nodeType===Pe.Element&&"Property"===d.localName){switch(d.getAttribute("name")){case"String":t.string=parseInt(d.findChildElement("String").innerText)+1;break;case"Fret":t.fret=parseInt(d.findChildElement("Fret").innerText);break;case"Element":l=parseInt(d.findChildElement("Element").innerText);break;case"Variation":c=parseInt(d.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(i,!0);break;case"HarmonicType":let e=d.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=y.None;break;case"Natural":t.harmonicType=y.Natural;break;case"Artificial":t.harmonicType=y.Artificial;break;case"Pinch":t.harmonicType=y.Pinch;break;case"Tap":t.harmonicType=y.Tap;break;case"Semi":t.harmonicType=y.Semi;break;case"Feedback":t.harmonicType=y.Feedback}break;case"HarmonicFret":let u=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":s=!0;break;case"BendOriginValue":a||(a=new U(0,0)),a.value=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new U(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 U(U.MaxPosition,0)),h.value=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new U(0,0)),h.offset=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"HopoOrigin":d.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":let p=parseInt(d.findChildElement("Flags").innerText);1&p?t.slideOutType=w.Shift:2&p?t.slideOutType=w.Legato:4&p?t.slideOutType=w.OutDown:8&p&&(t.slideOutType=w.OutUp),16&p?t.slideInType=S.IntoFromBelow:32&p&&(t.slideInType=S.IntoFromAbove),64&p?t.slideOutType=w.PickSlideDown:128&p&&(t.slideOutType=w.PickSlideUp)}}s&&(a||(a=new U(0,0)),h||(h=new U(U.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new U(n,r)),o&&r&&t.addBendPoint(new U(o,r)),n||o||!r||t.addBendPoint(new U(U.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==c&&(t.percussionArticulation=K.articulationFromElementVariation(l,c))}parseConcertPitch(e,t){const i=e.findChildElement("Pitch");if(i)for(let e of i.childNodes)if(e.nodeType===Pe.Element&&"Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=b.ForceDoubleSharp;break;case"#":t.accidentalMode=b.ForceSharp;break;case"b":t.accidentalMode=b.ForceFlat;break;case"bb":t.accidentalMode=b.ForceDoubleFlat}}toBendValue(e){return e*mt.BendPointValueFactor|0}toBendOffset(e){return e*mt.BendPointPositionFactor}parseRhythms(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){let t=new gt,i=e.getAttribute("id");t.id=i;for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"NoteValue":switch(i.innerText){case"Long":t.value=p.QuadrupleWhole;break;case"DoubleWhole":t.value=p.DoubleWhole;break;case"Whole":t.value=p.Whole;break;case"Half":t.value=p.Half;break;case"Quarter":t.value=p.Quarter;break;case"Eighth":t.value=p.Eighth;break;case"16th":t.value=p.Sixteenth;break;case"32nd":t.value=p.ThirtySecond;break;case"64th":t.value=p.SixtyFourth;break;case"128th":t.value=p.OneHundredTwentyEighth;break;case"256th":t.value=p.TwoHundredFiftySixth}break;case"PrimaryTuplet":t.tupletNumerator=parseInt(i.getAttribute("num")),t.tupletDenominator=parseInt(i.getAttribute("den"));break;case"AugmentationDot":t.dots=parseInt(i.getAttribute("count"))}this._rhythmById.set(i,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 i=0,s=0;i<e.length&&s<this.score.tracks.length;i++){let a=e[i];if(a!==mt.InvalidId){let e=this._barsById.get(a),i=this.score.tracks[s],r=i.staves[t];if(r.addBar(e),this._voicesOfBar.has(a))for(let t of this._voicesOfBar.get(a))if(t!==mt.InvalidId){let i=this._voiceById.get(t);if(e.addVoice(i),this._beatsOfVoice.has(t))for(let e of this._beatsOfVoice.get(t))if(e!==mt.InvalidId){let t=re.clone(this._beatById.get(e));i.addBeat(t);let s=this._rhythmOfBeat.get(e),a=this._rhythmById.get(s);if(t.duration=a.value,t.dots=a.dots,t.tupletNumerator=a.tupletNumerator,t.tupletDenominator=a.tupletDenominator,this._notesOfBeat.has(e))for(let i of this._notesOfBeat.get(e))if(i!==mt.InvalidId){const e=se.clone(this._noteById.get(i));r.isPercussion?(e.fret=-1,e.string=-1):e.percussionArticulation=-1,t.addNote(e),this._tappedNotes.has(i)&&(t.tap=!0)}}}else{let t=new _e;e.addVoice(t);let i=new oe;i.isEmpty=!0,i.duration=p.Quarter,t.addBeat(i)}t===i.staves.length-1?(s++,t=0):t++}else s++}}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e),i=!1;for(const e of t.staves)if(e.isPercussion){i=!0;break}if(i||(t.percussionArticulations=[]),this._automationsPerTrackIdAndBarIndex.has(e)){const i=this._automationsPerTrackIdAndBarIndex.get(e);for(const[e,s]of i)if(t.staves.length>0&&e<t.staves[0].bars.length){const i=t.staves[0].bars[e];if(i.voices.length>0&&i.voices[0].beats.length>0){const e=i.voices[0].beats[0];for(const t of s)e.automations.push(t)}}}}for(const[e,t]of this._masterTrackAutomations){let i=this.score.masterBars[e];for(let s=0,a=t.length;s<a;s++){let a=t[s];a.type===r.Tempo&&(0===e&&(this.score.tempo=0|a.value,a.text&&(this.score.tempoLabel=a.text)),i.tempoAutomation=a)}}}}mt.InvalidId="-1",mt.BendPointPositionFactor=U.MaxPosition/100,mt.BendPointValueFactor=.04;class yt{constructor(){this.isMultiRest=!1,this.trackViewGroups=[]}}class bt{constructor(){this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class St{apply(e){if(this.scoreViews.length>0){let t=0;for(let i of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){const s=e.tracks[t];for(const e of s.staves)e.showTablature=i.showTablature,e.showStandardNotation=i.showStandardNotation}t++}}}constructor(e){this.scoreViews=[];let t=ke.fromBuffer(e);const i=Te.readInt32BE(t);for(let e=0;e<i;e++){const e=new yt;this.scoreViews.push(e),e.isMultiRest=at.gpReadBool(t);const i=Te.readInt32BE(t);for(let s=0;s<i;s++){let i=t.readByte();0===i&&(i=1);let s=new bt;s.showStandardNotation=!!(1&i),s.showTablature=!!(2&i),s.showSlash=!!(4&i),e.trackViewGroups.push(s)}}}static writeForScore(e){const t=ke.withCapacity(128),i=[new yt];for(const t of e.tracks){const e=new bt;e.showStandardNotation=t.staves[0].showStandardNotation,e.showTablature=t.staves[0].showTablature,i[0].trackViewGroups.push(e);const s=new yt;s.trackViewGroups.push(e),i.push(s)}Te.writeInt32BE(t,i.length);for(const e of i){t.writeByte(e.isMultiRest?1:0),Te.writeInt32BE(t,e.trackViewGroups.length);for(const i of e.trackViewGroups){let e=0;i.showStandardNotation&&(e|=1),i.showTablature&&(e|=2),i.showSlash&&(e|=4),t.writeByte(e)}}return Te.writeInt32BE(t,1),t.toArray()}}class wt{}class _t extends wt{constructor(e){super(),this.n=e}}class Bt extends wt{constructor(e,t){super(),this.left=e,this.right=t}}class Tt extends wt{constructor(e,t){super(),this.n=e,this.table=t}}class kt{static make(e,t,i,s){let a=[],r=[];if(s>32)throw new fe("Invalid huffman");for(let e=0;e<s;e++)a.push(0),r.push(0);for(let r=0;r<i;r++){let i=e[r+t];if(i>=s)throw new fe("Invalid huffman");a[i]++}let n=0;for(let e=1;e<s-1;e++)n=n+a[e]<<1,r[e]=n;let o=new Map;for(let s=0;s<i;s++){let i=e[s+t];if(0!==i){let e=r[i-1];r[i-1]=e+1,o.set(e<<5|i,s)}}return kt.treeCompress(new Bt(kt.treeMake(o,s,0,1),kt.treeMake(o,s,1,1)))}static treeMake(e,t,i,s){if(s>t)throw new fe("Invalid huffman");let a=i<<5|s;return e.has(a)?new _t(e.get(a)):(i<<=1,s+=1,new Bt(kt.treeMake(e,t,i,s),kt.treeMake(e,t,1|i,s)))}static treeCompress(e){let t=kt.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof Bt)return new Bt(kt.treeCompress(e.left),kt.treeCompress(e.right));throw new fe("assert")}let i=1<<t,s=[];for(let e=0;e<i;e++)s.push(new _t(-1));return kt.treeWalk(s,0,0,t,e),new Tt(t,s)}static treeWalk(e,t,i,s,a){a instanceof Bt&&s>0?(kt.treeWalk(e,t,i+1,s-1,a.left),kt.treeWalk(e,t|1<<i,i+1,s-1,a.right)):e[t]=kt.treeCompress(a)}static treeDepth(e){if(e instanceof _t)return 0;if(e instanceof Tt)throw new fe("assert");if(e instanceof Bt){let t=kt.treeDepth(e.left),i=kt.treeDepth(e.right);return 1+(t<i?t:i)}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"}(Fe||(Fe={}));class vt{constructor(){this.buffer=new Uint8Array(vt.BufferSize),this.pos=0}slide(){let e=new Uint8Array(vt.BufferSize);this.pos-=vt.Size,e.set(this.buffer.subarray(vt.Size,vt.Size+this.pos),0),this.buffer=e}addBytes(e,t,i){this.pos+i>vt.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+i),this.pos),this.pos+=i}addByte(e){this.pos===vt.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}vt.Size=32768,vt.BufferSize=65536;class xt{static buildFixedHuffman(){let e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return kt.make(e,0,288,10)}constructor(e){this._nbits=0,this._bits=0,this._state=Fe.Block,this._isFinal=!1,this._huffman=xt._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new vt,this._input=e;for(let e=0;e<19;e++)this._lengths.push(-1)}readBytes(e,t,i){if(this._needed=i,this._outpos=t,this._output=e,i>0)for(;this.inflateLoop(););return i-this._needed}inflateLoop(){switch(this._state){case Fe.Head:let e=this._input.readByte();if(8!==(15&e))throw new fe("Invalid data");let t=this._input.readByte(),i=!!(32&t);if(((e<<8)+t)%31!=0)throw new fe("Invalid data");if(i)throw new fe("Unsupported dictionary");return this._state=Fe.Block,!0;case Fe.Crc:return this._state=Fe.Done,!0;case Fe.Done:return!1;case Fe.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:if(this._len=Te.readUInt16LE(this._input),Te.readUInt16LE(this._input)!==65535-this._len)throw new fe("Invalid data");this._state=Fe.Flat;let e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=xt._fixedHuffman,this._huffdist=null,this._state=Fe.CData,!0;case 2:let t=this.getBits(5)+257,i=this.getBits(5)+1,s=this.getBits(4)+4;for(let e=0;e<s;e++)this._lengths[xt.CodeLengthsPos[e]]=this.getBits(3);for(let e=s;e<19;e++)this._lengths[xt.CodeLengthsPos[e]]=0;this._huffman=kt.make(this._lengths,0,19,8);let a=[];for(let e=0;e<t+i;e++)a.push(0);return this.inflateLengths(a,t+i),this._huffdist=kt.make(a,t,i,16),this._huffman=kt.make(a,0,t,16),this._state=Fe.CData,!0;default:throw new fe("Invalid data")}case Fe.Flat:{let e=this._len<this._needed?this._len:this._needed,t=Te.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?Fe.Crc:Fe.Block),this._needed>0}case Fe.DistOne:{let e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=Fe.CData),this._needed>0}case Fe.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=Fe.CData),this._needed>0;case Fe.CData:let s=this.applyHuffman(this._huffman);if(s<256)return this.addByte(s),this._needed>0;if(256===s)return this._state=this._isFinal?Fe.Crc:Fe.Block,!0;{s=s-257&255;let e=xt.LenExtraBitsTbl[s];if(-1===e)throw new fe("Invalid data");this._len=xt.LenBaseValTbl[s]+this.getBits(e);let t=this._huffdist,i=t?this.applyHuffman(t):this.getRevBits(5);if(e=xt.DistExtraBitsTbl[i],-1===e)throw new fe("Invalid data");if(this._dist=xt.DistBaseValTbl[i]+this.getBits(e),this._dist>this._window.available())throw new fe("Invalid data");return this._state=1===this._dist?Fe.DistOne:Fe.Dist,!0}}return!1}addDistOne(e){let t=this._window.getLastChar();for(let i=0;i<e;i++)this.addByte(t)}addByte(e){this._window.addByte(e),this._output[this._outpos]=e,this._needed--,this._outpos++}addDist(e,t){this.addBytes(this._window.buffer,this._window.pos-e,t)}getBit(){0===this._nbits&&(this._nbits=8,this._bits=this._input.readByte());let e=!(1&~this._bits);return this._nbits--,this._bits=this._bits>>1,e}getBits(e){for(;this._nbits<e;)this._bits=this._bits|this._input.readByte()<<this._nbits,this._nbits+=8;let t=this._bits&(1<<e)-1;return this._nbits-=e,this._bits=this._bits>>e,t}getRevBits(e){return 0===e?0:this.getBit()?1<<e-1|this.getRevBits(e-1):this.getRevBits(e-1)}resetBits(){this._bits=0,this._nbits=0}addBytes(e,t,i){this._window.addBytes(e,t,i),this._output.set(e.subarray(t,t+i),this._outpos),this._needed-=i,this._outpos+=i}inflateLengths(e,t){let i=0,s=0;for(;i<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:s=a,e[i]=a,i++;break;case 16:let r=i+3+this.getBits(2);if(r>t)throw new fe("Invalid data");for(;i<r;)e[i]=s,i++;break;case 17:if(i+=3+this.getBits(3),i>t)throw new fe("Invalid data");break;case 18:if(i+=11+this.getBits(7),i>t)throw new fe("Invalid data");break;default:throw new fe("Invalid data")}}}applyHuffman(e){if(e instanceof _t)return e.n;if(e instanceof Bt)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof Tt)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new fe("Invalid data")}}xt.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],xt.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],xt.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],xt.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],xt.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],xt._fixedHuffman=xt.buildFixedHuffman();class Nt{constructor(e,t){this.fullName=e;let i=e.lastIndexOf("/");this.fileName=-1===i||i===e.length-1?this.fullName:e.substr(i+1),this.data=t}}Nt.OptionalDataDescriptorSignature=134695760,Nt.CompressionMethodDeflate=8,Nt.LocalFileHeaderSignature=67324752,Nt.CentralFileHeaderSignature=33639248,Nt.EndOfCentralDirSignature=101010256;class Pt{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(Te.readInt32LE(e)!==Nt.LocalFileHeaderSignature)return null;Te.readUInt16LE(e);let t=Te.readUInt16LE(e),i=Te.readUInt16LE(e),s=0!==i;if(s&&i!==Nt.CompressionMethodDeflate)return null;Te.readInt16LE(this._readable),Te.readInt16LE(this._readable),Te.readInt32LE(e),Te.readInt32LE(e);let a,r=Te.readInt32LE(e),n=Te.readInt16LE(e),o=Te.readInt16LE(e),h=Te.toString(Te.readByteArray(e,n),"utf-8");if(e.skip(o),s){let e=ke.empty(),t=new xt(this._readable),i=new Uint8Array(65536);for(;;){let s=t.readBytes(i,0,i.length);if(e.write(i,0,s),s<i.length)break}a=e.toArray()}else a=Te.readByteArray(this._readable,r);if(8&t){Te.readInt32LE(this._readable)===Nt.OptionalDataDescriptorSignature&&Te.readInt32LE(this._readable),Te.readInt32LE(this._readable),Te.readInt32LE(this._readable)}return new Nt(h,a)}}class Et extends O{get name(){return"Guitar Pro 7"}constructor(){super()}readScore(){J.debug(this.name,"Loading ZIP entries");let e,t=new Pt(this.data);try{e=t.read()}catch(e){throw new V("No Zip archive",e)}J.debug(this.name,"Zip entries loaded");let i=null,s=null,a=null;for(let t of e)switch(t.fileName){case"score.gpif":i=Te.toString(t.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=t.data;break;case"PartConfiguration":a=t.data}if(!i)throw new V("No score.gpif found in zip archive");J.debug(this.name,"Start Parsing score.gpif");let r=new mt;r.parseXml(i,this.settings),J.debug(this.name,"score.gpif parsed");let n=r.score;if(s){J.debug(this.name,"Start Parsing BinaryStylesheet"),new ot(s).apply(n),J.debug(this.name,"BinaryStylesheet parsed")}if(a){J.debug(this.name,"Start Parsing Part Configuration"),new St(a).apply(n),J.debug(this.name,"Part Configuration parsed")}return n}}class Ct extends G{constructor(){super(e.AlphaTabErrorType.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,Ct.prototype)}}class Ft{constructor(e){this._currentByte=0,this._position=Ft.ByteSize,this._source=e}readByte(){return this.readBits(8)}readBytes(e){const t=new Uint8Array(e);for(let i=0;i<e;i++)t[i]=255&this.readByte();return t}readBits(e){let t=0,i=e-1;for(;i>=0;)t|=this.readBit()<<i,i--;return t}readBitsReversed(e){let t=0;for(let i=0;i<e;i++)t|=this.readBit()<<i;return t}readBit(){if(this._position>=8){if(this._currentByte=this._source.readByte(),-1===this._currentByte)throw new Ct;this._position=0}const e=this._currentByte>>Ft.ByteSize-this._position-1&1;return this._position++,e}readAll(){let e=ke.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof Ct))throw e}return e.toArray()}}Ft.ByteSize=8;class Lt{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class Mt{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){let t=new Ft(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){let i,s=ke.empty(),a=this.getInteger(e.readBytes(4),0);try{for(;s.length<a;){if(1===e.readBits(1)){let t=e.readBits(4),a=e.readBitsReversed(t),r=e.readBitsReversed(t),n=s.length-a,o=Math.min(a,r);i=s.getBuffer(),s.write(i,n,o)}else{let t=e.readBitsReversed(2);for(let i=0;i<t;i++)s.writeByte(e.readByte())}}}catch(e){if(!(e instanceof Ct))throw e}i=s.getBuffer();let r=t?4:0,n=s.length-r,o=new Uint8Array(n),h=n;return o.set(i.subarray(r,r+h),0),o}readBlock(e){let t=this.readHeader(e);if("BCFZ"===t)this.readUncompressedBlock(this.decompress(e,!0));else{if("BCFS"!==t)throw new V("Unsupported format");this.readUncompressedBlock(e.readAll())}}readUncompressedBlock(e){let t=4096,i=t;for(;i+3<e.length;){if(2===this.getInteger(e,i)){let s=new Lt;s.fileName=this.getString(e,i+4,127),s.fileSize=this.getInteger(e,i+140);let a=!this.fileFilter||this.fileFilter(s.fileName);a&&this.files.push(s);let r=i+148,n=0,o=0,h=a?ke.withCapacity(s.fileSize):null;for(;n=this.getInteger(e,r+4*o++),0!==n;)i=n*t,a&&h.write(e,i,t);if(a){s.data=new Uint8Array(Math.min(s.fileSize,h.length));let e=h.toArray();s.data.set(e.subarray(0,0+s.data.length),0)}}i+=t}}getString(e,t,i){let s="";for(let a=0;a<i;a++){let i=255&e[t+a];if(0===i)break;s+=String.fromCharCode(i)}return s}getInteger(e,t){return e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}}Mt.HeaderBcFs="BCFS",Mt.HeaderBcFz="BCFZ",Mt.ScoreGpif="score.gpif",Mt.BinaryStylesheet="BinaryStylesheet",Mt.PartConfiguration="PartConfiguration";class It extends O{get name(){return"Guitar Pro 6"}constructor(){super()}readScore(){J.debug(this.name,"Loading GPX filesystem");let e=new Mt;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration"),e.load(this.data),J.debug(this.name,"GPX filesystem loaded");let t=null,i=null,s=null;for(let a of e.files)switch(a.fileName){case"score.gpif":t=Te.toString(a.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=a.data;break;case"PartConfiguration":s=a.data}if(!t)throw new V("No score.gpif found in GPX");J.debug(this.name,"Start Parsing score.gpif");let a=new mt;a.parseXml(t,this.settings),J.debug(this.name,"score.gpif parsed");let r=a.score;if(i){J.debug(this.name,"Start Parsing BinaryStylesheet"),new ot(i).apply(r),J.debug(this.name,"BinaryStylesheet parsed")}if(s){J.debug(this.name,"Start Parsing Part Configuration"),new St(s).apply(r),J.debug(this.name,"Part Configuration parsed")}return r}}class Dt extends O{get name(){return"MusicXML"}constructor(){super(),this._currentPartGroup=null,this._trackFirstMeasureNumber=0,this._maxVoices=0,this._currentDirection=null,this._currentChord=null,this._divisionsPerQuarterNote=0,this._voiceOfStaff=new Map,this._isBeamContinue=!1,this._previousBeatWasPulled=!1,this._previousBeat=null}readScore(){this._trackById=new Map,this._partGroups=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._slurStarts=new Map;let e=Te.toString(this.data.readAll(),this.settings.importer.encoding),t=new pt;try{t.parse(e)}catch(e){throw new V("Unsupported format")}return this._score=new pe,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 i=1;i<e.length;i++){let s=e[i];for(let e of s.staves)t.addStaff(e);let a=this._score.tracks.indexOf(s);this._score.tracks.splice(a,1)}}parseDom(e){let t=e.firstElement;if(!t)throw new V("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":break;default:throw new V("Unsupported format")}}parsePartwise(e){for(let t of e.childNodes)if(t.nodeType===Pe.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===Pe.Element&&"work-title"===t.localName)this._score.title=t.innerText}parsePart(e){let t=e.getAttribute("id");if(!this._trackById.has(t)){if(1!==this._trackById.size)return;for(const[e,i]of this._trackById)0!==i.staves.length&&0!==i.staves[0].bars.length||(t=e);if(!this._trackById.has(t))return}let i=this._trackById.get(t),s=!0;this._maxVoices=0;for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"measure"===t.localName)this.parseMeasure(t,i,s)&&(s=!1);for(let e of i.staves)for(let t of e.bars)this.ensureVoices(t)}parseMeasure(e,t,i){if("yes"===e.getAttribute("implicit")&&0===e.getElementsByTagName("note",!1).length)return!1;let s=0;if(i)this._divisionsPerQuarterNote=0,this._trackFirstMeasureNumber=parseInt(e.getAttribute("number")),this._trackFirstMeasureNumber||(this._trackFirstMeasureNumber=0),s=0;else{if(s=parseInt(e.getAttribute("number")),!s)return!1;s-=this._trackFirstMeasureNumber}if(i){let i=e.getElementsByTagName("attributes",!1);if(i.length>0){let e=i[0].getElementsByTagName("staves",!1);if(e.length>0){let i=parseInt(e[0].innerText);t.ensureStaveCount(i)}}}let a=new Array(t.staves.length),r=null;for(let e=t.staves[0].bars.length;e<=s;e++)for(let e=0;e<t.staves.length;e++){let i=new W;if(a[e]=i,t.staves[e].bars.length>0){let s=t.staves[e].bars[t.staves[e].bars.length-1];i.clef=s.clef}r=this.getOrCreateMasterBar(s),t.staves[e].addBar(i),this.ensureVoices(i)}let n=new Map;if(r){let i=!1;for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"note":this.parseNoteBeat(s,a);break;case"forward":this.parseForward(s,a);break;case"direction":this.parseDirection(s,r);break;case"attributes":i||(this.parseAttributes(s,a,r,t),i=!0);break;case"harmony":this.parseHarmony(s,t,n);break;case"sound":break;case"barline":this.parseBarline(s,r)}}return!0}ensureVoices(e){for(;e.voices.length<this._maxVoices;){let t=new _e;e.addVoice(t);let i=new oe;i.isEmpty=!0,i.chordId=this._currentChord,t.addBeat(i)}}getOrCreateBeat(e,t,i){let s=0,a=e.getElementsByTagName("voice",!1);a.length>0&&(s=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,s)}l--,n=l<0?t[0]:l>=t.length?t[t.length-1]:t[l];let c=this.getOrCreateVoice(n,s);return i&&c.beats.length>0||1===c.beats.length&&c.isEmpty?o=c.beats[c.beats.length-1]:(o=new oe,o.isEmpty=!1,c.addBeat(o)),this._isBeamContinue=!1,this._previousBeat=o,o}parseForward(e,t){let i=this.getOrCreateBeat(e,t,!1),s=parseInt(e.findChildElement("duration").innerText)*p.Quarter/this._divisionsPerQuarterNote,a=[p.SixtyFourth,p.ThirtySecond,p.Sixteenth,p.Eighth,p.Quarter,p.Half,p.Whole];for(let e of a)if(s>=e){i.duration=e,s-=e;break}i.isEmpty=!1}parseStaffDetails(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"staff-lines":for(let e of t.staves)e.stringTuning.tunings=new Array(parseInt(i.innerText)).fill(0);break;case"staff-tuning":this.parseStaffTuning(i,t)}for(let e of t.staves)this.isEmptyTuning(e.tuning)&&(e.stringTuning.tunings=[])}parseStaffTuning(e,t){let i=parseInt(e.getAttribute("line")),s="C",a="",r=0;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"tuning-step":s=t.innerText;break;case"tuning-alter":r=parseInt(t.innerText);break;case"tuning-octave":a=t.innerText}let n=Q.getTuningForText(s+a)+r;for(let e of t.staves)e.tuning[e.tuning.length-i]=n}parseHarmony(e,t,i){let s=new he;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"root":s.name=this.parseHarmonyRoot(t);break;case"kind":s.name=s.name+this.parseHarmonyKind(t);break;case"frame":this.parseHarmonyFrame(t,s)}this._currentChord=Q.newGuid();const a=s.uniqueId;i.has(a)&&(s.showDiagram=!1);for(let e of t.staves)e.addChord(this._currentChord,s);i.set(a,s)}parseHarmonyRoot(e){let t="",i="";for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"root-step":t=s.innerText;break;case"root-alter":switch(parseInt(e.innerText)){case-2:i="bb";break;case-1:i="b";break;case 0:i="";break;case 1:i="#";break;case 2:i="##"}}return t+i}parseHarmonyKind(e){const t=e.getAttribute("text");let i="";if(t)i=t;else{switch(e.innerText){case"major":i="";break;case"minor":i="m";break;case"augmented":i="+";break;case"diminished":i="○";break;case"dominant":i="7";break;case"major-seventh":i="7M";break;case"minor-seventh":i="m7";break;case"diminished-seventh":i="○7";break;case"augmented-seventh":i="+7";break;case"half-diminished":i="⍉";break;case"major-minor":i="mMaj";break;case"major-sixth":i="maj6";break;case"minor-sixth":i="m6";break;case"dominant-ninth":i="9";break;case"major-ninth":i="maj9";break;case"minor-ninth":i="m9";break;case"dominant-11th":i="11";break;case"major-11th":i="maj11";break;case"minor-11th":i="m11";break;case"dominant-13th":i="13";break;case"major-13th":i="maj13";break;case"minor-13th":i="m13";break;case"suspended-second":i="sus2";break;case"suspended-fourth":i="sus4"}}return i}parseHarmonyFrame(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"frame-strings":const e=parseInt(i.innerText);t.strings=new Array(e);for(let i=0;i<e;i++)t.strings[i]=-1;break;case"first-fret":t.firstFret=parseInt(i.innerText);break;case"frame-note":let s=null,a=null;for(let e of i.childNodes)switch(e.localName){case"string":s=parseInt(e.innerText);break;case"fret":a=parseInt(e.innerText),s&&a>=0&&(t.strings[s-1]=a);break;case"barre":s&&a&&"start"===e.getAttribute("type")&&t.barreFrets.push(a)}}}parseBarline(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"repeat":this.parseRepeat(i,t);break;case"ending":this.parseEnding(i,t)}}parseEnding(e,t){let i=parseInt(e.getAttribute("number"));i>0&&(--i,t.alternateEndings=t.alternateEndings|1<<i&255)}parseRepeat(e,t){let i=e.getAttribute("direction"),s=parseInt(e.getAttribute("times"));(s<0||isNaN(s))&&(s=2),"backward"===i?t.repeatCount=s:"forward"===i&&(t.isRepeatStart=!0)}parseNoteBeat(e,t){let i=e.getElementsByTagName("chord",!1).length>0,s=this.getOrCreateBeat(e,t,i);!s.chordId&&this._currentChord&&(s.chordId=this._currentChord,this._currentChord=null),this._currentDirection&&(s.text=this._currentDirection,this._currentDirection=null);let a=new ee;s.voice.isEmpty=!1,s.isEmpty=!1,s.addNote(a),s.dots=0;let r=!1;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"grace":s.graceType=f.BeforeBeat,s.duration=p.ThirtySecond;break;case"duration":if(s.isRest&&!r){switch(parseInt(t.innerText)){case 1:s.duration=p.Whole;break;case 2:s.duration=p.Half;break;case 4:default:s.duration=p.Quarter;break;case 8:s.duration=p.Eighth;break;case 16:s.duration=p.Sixteenth;break;case 32:s.duration=p.ThirtySecond;break;case 64:s.duration=p.SixtyFourth}}break;case"tie":this.parseTied(t,a);break;case"cue":case"instrument":case"stem":break;case"type":s.duration=this.getDuration(t.innerText),s.graceType!==f.None&&s.duration<p.Sixteenth&&(s.duration=p.Eighth);break;case"dot":s.dots++;break;case"accidental":this.parseAccidental(t,a);break;case"time-modification":this.parseTimeModification(t,s);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,s,a);break;case"lyric":this.parseLyric(t,s);break;case"pitch":this.parsePitch(t,a);break;case"unpitched":this.parseUnpitched(t,a);break;case"rest":r="yes"===t.getAttribute("measure"),s.isEmpty=!1,s.notes=[],s.duration=p.Whole}if(a.isStringed)for(let e=0;e<s.notes.length;e++)if(s.notes[e].string===a.string&&s.notes[e]!==a){s.removeNote(a);break}}getDuration(e){switch(e){case"256th":case"128th":case"64th":return p.SixtyFourth;case"32nd":return p.ThirtySecond;case"16th":return p.Sixteenth;case"eighth":return p.Eighth;case"quarter":return p.Quarter;case"half":return p.Half;case"long":case"breve":case"whole":return p.Whole}return p.Quarter}parseLyric(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element&&"text"===i.localName)t.text?t.text+=" "+i.innerText:t.text=i.innerText}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=b.ForceSharp;break;case"natural":t.accidentalMode=b.ForceNatural;break;case"flat":t.accidentalMode=b.ForceFlat}}parseTied(e,t){if("start"===e.getAttribute("type"))this._tieStartIds.has(t.id)||(this._tieStartIds.set(t.id,!0),this._tieStarts.push(t));else if("stop"===e.getAttribute("type")&&this._tieStarts.length>0&&!t.isTieDestination){const e=this._tieStarts[0];e.beat.voice.index===t.beat.voice.index&&e.beat.voice.bar.staff.index===t.beat.voice.bar.staff.index&&e.beat.voice.bar.staff.track.index===t.beat.voice.bar.staff.track.index&&(t.isTieDestination=!0,t.tieOrigin=this._tieStarts[0]),this._tieStarts.splice(0,1),this._tieStartIds.delete(t.id)}}parseNotations(e,t,i){for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"articulations":this.parseArticulations(s,i);break;case"tied":this.parseTied(s,i);break;case"slide":case"glissando":"start"===s.getAttribute("type")&&(i.slideOutType=w.Shift);break;case"dynamics":this.parseDynamics(s,t);break;case"technical":this.parseTechnical(s,i);break;case"ornaments":this.parseOrnaments(s,i);break;case"slur":let e=s.getAttribute("number");switch(e||(e="1"),e=t.voice.bar.staff.index+"_"+e,s.getAttribute("type")){case"start":this._slurStarts.set(e,i);break;case"stop":if(this._slurStarts.has(e)){i.isSlurDestination=!0;let t=this._slurStarts.get(e);t.slurDestination=i,i.slurOrigin=t}}}}parseOrnaments(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element&&"tremolo"===i.localName){switch(parseInt(i.innerText)){case 1:t.beat.tremoloSpeed=p.Eighth;break;case 2:t.beat.tremoloSpeed=p.Sixteenth;break;case 3:t.beat.tremoloSpeed=p.ThirtySecond}}}parseTechnical(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"string":t.string=parseInt(i.innerText),-2147483648!==t.string&&(t.string=t.beat.voice.bar.staff.tuning.length-t.string+1);break;case"fret":t.fret=parseInt(i.innerText);break;case"down-bow":t.beat.pickStroke=N.Down;break;case"up-bow":t.beat.pickStroke=N.Up}-2147483648!==t.string&&-2147483648!==t.fret||(t.string=-1,t.fret=-1)}parseArticulations(e,t){for(let i of e.childNodes)switch(i.localName){case"accent":t.accentuated=a.Normal;break;case"strong-accent":t.accentuated=a.Heavy;break;case"staccato":case"detached-legato":t.isStaccato=!0}}parseDynamics(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"p":t.dynamics=g.P;break;case"pp":t.dynamics=g.PP;break;case"ppp":t.dynamics=g.PPP;break;case"f":t.dynamics=g.F;break;case"ff":t.dynamics=g.FF;break;case"fff":t.dynamics=g.FFF;break;case"mp":t.dynamics=g.MP;break;case"mf":t.dynamics=g.MF}}parseTimeModification(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"actual-notes":t.tupletNumerator=parseInt(i.innerText);break;case"normal-notes":t.tupletDenominator=parseInt(i.innerText)}}parseUnpitched(e,t){let i="",s=0,a=0;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"display-step":i=t.innerText;break;case"display-alter":s=parseInt(t.innerText);break;case"display-octave":a=parseInt(t.innerText)}let r=12*a+Q.getToneForText(i)+s;t.octave=r/12|0,t.tone=r-12*t.octave}parsePitch(e,t){let i="",s=0,a=0;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"step":i=t.innerText;break;case"alter":s=parseFloat(t.innerText),isNaN(s)&&(s=0);break;case"octave":a=parseInt(t.innerText)+1}let r=12*a+Q.getToneForText(i)+(0|s);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 i=e.voices.length;i<=t;i++)e.addVoice(new _e);return this._maxVoices=Math.max(this._maxVoices,e.voices.length),e.voices[t]}parseDirection(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"sound":let e=i.getAttribute("tempo");if(e){let i=new H;i.isLinear=!0,i.type=r.Tempo,i.value=parseInt(e),t.tempoAutomation=i,0===t.index&&(t.score.tempo=i.value)}break;case"direction-type":let s=i.firstElement;switch(s.localName){case"words":this._currentDirection=s.innerText;break;case"metronome":this.parseMetronome(s,t)}}}parseMetronome(e,t){let i=p.Quarter,s=120;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"beat-unit":i=this.getDuration(t.innerText);break;case"per-minute":s=parseInt(t.innerText)}let a=new H;a.type=r.Tempo,a.value=s*(i/4|0),t.tempoAutomation=a,0===t.index&&(t.score.tempo=a.value)}parseAttributes(e,t,i,s){let a=0,r=!1;for(let n of e.childNodes)if(n.nodeType===Pe.Element)switch(n.localName){case"divisions":this._divisionsPerQuarterNote=parseInt(n.innerText);break;case"key":this.parseKey(n,i);break;case"time":this.parseTime(n,i),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,s);break;case"transpose":this.parseTranspose(n,s)}r||(i.timeSignatureCommon=!0)}parseTranspose(e,t){let i=0;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"chromatic":i+=parseInt(t.innerText);break;case"octave-change":i+=12*parseInt(t.innerText)}for(let e of t.staves)e.transpositionPitch=i}parseClef(e,t){let i="s",s=0;for(let a of e.childNodes)if(a.nodeType===Pe.Element)switch(a.localName){case"sign":i=a.innerText.toLowerCase();break;case"line":s=parseInt(a.innerText);break;case"clef-octave-change":switch(parseInt(a.innerText)){case-2:t.clefOttava=o._15mb;break;case-1:t.clefOttava=o._8vb;break;case 1:t.clefOttava=o._8va;break;case 2:t.clefOttava=o._15mb}}switch(i){case"g":default:t.clef=n.G2;break;case"f":t.clef=n.F4;break;case"c":t.clef=3===s?n.C3:n.C4;break;case"percussion":t.clef=n.Neutral,t.staff.isPercussion=!0;break;case"tab":t.clef=n.G2,t.staff.showTablature=!0}}parseTime(e,t){"common"===e.getAttribute("symbol")&&(t.timeSignatureCommon=!0);let i=!1,s=!1;for(let a of e.childNodes)if(a.nodeType===Pe.Element){let e=a.innerText;switch(a.localName){case"beats":i||(-1===e.indexOf("+")?t.timeSignatureNumerator=parseInt(e):t.timeSignatureNumerator=4,i=!0);break;case"beat-type":s||(-1===e.indexOf("+")?t.timeSignatureDenominator=parseInt(e):t.timeSignatureDenominator=4,s=!0)}}}parseKey(e,t){let i=-2147483648,s="";for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"fifths":i=parseInt(t.innerText);break;case"key-step":case"key-alter":break;case"mode":s=t.innerText}t.keySignature=-7<=i&&i<=7?i:M.C,t.keySignatureType="minor"===s?D.Minor:D.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 ce;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===Pe.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===Pe.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"),i=new we;i.ensureStaveCount(1),i.staves[0].showStandardNotation=!0,this._trackById.set(t,i),this._score.addTrack(i),this._currentPartGroup&&this._partGroups.get(this._currentPartGroup).push(i);for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"part-name":i.name=t.innerText;break;case"part-abbreviation":i.shortName=t.innerText;break;case"midi-instrument":this.parseMidiInstrument(t,i)}this.isEmptyTuning(i.staves[0].tuning)&&(i.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 i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"midi-channel":t.playbackInfo.primaryChannel=parseInt(i.innerText);break;case"midi-program":t.playbackInfo.program=parseInt(i.innerText);break;case"volume":t.playbackInfo.volume=Math.floor(parseInt(i.innerText)/100*16);break;case"pan":t.playbackInfo.balance=Math.max(0,Math.min(16,Math.floor((parseInt(i.innerText)+90)/180*16)))}}}!function(e){e[e.SingleTrackMultiChannel=0]="SingleTrackMultiChannel",e[e.MultiTrack=1]="MultiTrack"}(Le||(Le={}));class At{constructor(){this.events=[]}addEvent(e){if(0===this.events.length||e.tick>=this.events[this.events.length-1].tick)this.events.push(e);else{let t=this.events.length;for(;t>0;){if(!(this.events[t-1].tick>e.tick))break;t--}this.events.splice(t,0,e)}}writeTo(e){let t=ke.empty(),i=0;for(let e of this.events){let s=e.tick-i;Rt.writeVariableInt(t,s),e.writeTo(t),i=e.tick}const s=new Uint8Array([77,84,114,107]);e.write(s,0,s.length);let a=t.toArray();Te.writeInt32BE(e,a.length),e.write(a,0,a.length)}}class Rt{constructor(){this.format=Le.SingleTrackMultiChannel,this.division=z.QuarterTime,this.tracks=[]}get events(){if(1==this.tracks.length)return this.tracks[0].events;{const e=[];for(const e of this.tracks)this.events.push(...e.events);return e.sort(((e,t)=>e.tick-t.tick)),e}}ensureTracks(e){for(;this.tracks.length<e;)this.tracks.push(new At)}addEvent(e){this.format==Le.SingleTrackMultiChannel?(this.ensureTracks(1),this.tracks[0].addEvent(e)):(this.ensureTracks(e.track+1),this.tracks[e.track].addEvent(e))}toBinary(){let e=ke.empty();return this.writeTo(e),e.toArray()}writeTo(e){let t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),Te.writeInt32BE(e,6),Te.writeInt16BE(e,this.format),Te.writeInt16BE(e,this.tracks.length),Te.writeInt16BE(e,this.division);for(const t of this.tracks)t.writeTo(e)}static writeVariableInt(e,t){let i=new Uint8Array(4),s=0;do{i[s++]=127&t,t>>=7}while(t>0);for(;s>0;)s--,s>0?e.writeByte(128|i[s]):e.writeByte(i[s])}}!function(e){e[e.TimeSignature=88]="TimeSignature",e[e.NoteOn=128]="NoteOn",e[e.NoteOff=144]="NoteOff",e[e.ControlChange=176]="ControlChange",e[e.ProgramChange=192]="ProgramChange",e[e.TempoChange=81]="TempoChange",e[e.PitchBend=224]="PitchBend",e[e.PerNotePitchBend=96]="PerNotePitchBend",e[e.EndOfTrack=47]="EndOfTrack",e[e.AlphaTabRest=241]="AlphaTabRest",e[e.AlphaTabMetronome=242]="AlphaTabMetronome",e[e.SystemExclusive=240]="SystemExclusive",e[e.SystemExclusive2=247]="SystemExclusive2",e[e.Meta=255]="Meta"}(Me||(Me={}));class Ot{constructor(e,t,i){this.track=e,this.tick=t,this.type=i}get command(){return this.type}get message(){return 0}get data1(){return 0}get data2(){return 0}}class Gt extends Ot{constructor(e,t,i,s,a,r){super(e,t,Me.TimeSignature),this.track=e,this.tick=t,this.numerator=i,this.denominatorIndex=s,this.midiClocksPerMetronomeClick=a,this.thirtySecondNodesInQuarter=r}writeTo(e){e.writeByte(255),e.writeByte(88),Rt.writeVariableInt(e,4),e.writeByte(255&this.numerator),e.writeByte(255&this.denominatorIndex),e.writeByte(255&this.midiClocksPerMetronomeClick),e.writeByte(255&this.thirtySecondNodesInQuarter)}}class Vt extends Ot{constructor(e,t,i){super(e,t,i)}writeTo(e){e.writeByte(240);const t=ke.withCapacity(16);t.writeByte(Vt.AlphaTabManufacturerId),this.writeEventData(t),t.writeByte(247),Rt.writeVariableInt(e,t.length),t.copyTo(e)}}Vt.AlphaTabManufacturerId=125,Vt.MetronomeEventId=0,Vt.RestEventId=1;class Ht extends Vt{constructor(e,t,i,s,a){super(e,t,Me.AlphaTabMetronome),this.isMetronome=!0,this.metronomeNumerator=i,this.metronomeDurationInMilliseconds=a,this.metronomeDurationInTicks=s}writeEventData(e){e.writeByte(Vt.MetronomeEventId),e.writeByte(this.metronomeNumerator),Te.writeInt32LE(e,this.metronomeDurationInTicks),Te.writeInt32LE(e,this.metronomeDurationInMilliseconds)}}class Wt extends Vt{constructor(e,t,i){super(e,t,Me.AlphaTabRest),this.channel=i}writeEventData(e){e.writeByte(Vt.RestEventId),e.writeByte(this.channel)}}class zt extends Ot{constructor(e,t,i,s,a,r){super(e,t,i),this.channel=s,this.noteKey=a,this.noteVelocity=r}get data1(){return this.noteKey}get data2(){return this.noteVelocity}}class Ut extends zt{constructor(e,t,i,s,a){super(e,t,Me.NoteOn,i,s,a)}writeTo(e){e.writeByte(15&this.channel|144),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class Xt extends zt{constructor(e,t,i,s,a){super(e,t,Me.NoteOff,i,s,a)}writeTo(e){e.writeByte(15&this.channel|128),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class Yt extends Ot{constructor(e,t,i,s,a){super(e,t,Me.ControlChange),this.channel=i,this.controller=s,this.value=a}writeTo(e){e.writeByte(15&this.channel|176),e.writeByte(255&this.controller),e.writeByte(255&this.value)}get data1(){return this.controller}get data2(){return this.value}}class qt extends Ot{constructor(e,t,i,s){super(e,t,Me.ProgramChange),this.channel=i,this.program=s}writeTo(e){e.writeByte(15&this.channel|192),e.writeByte(255&this.program)}get data1(){return this.program}}class Jt extends Ot{constructor(e,t){super(0,e,Me.TempoChange),this.microSecondsPerQuarterNote=t}writeTo(e){e.writeByte(255),e.writeByte(81),e.writeByte(3),e.writeByte(this.microSecondsPerQuarterNote>>16&255),e.writeByte(this.microSecondsPerQuarterNote>>8&255),e.writeByte(255&this.microSecondsPerQuarterNote)}}class jt extends Ot{constructor(e,t,i,s){super(e,t,Me.PitchBend),this.channel=i,this.value=s}writeTo(e){e.writeByte(15&this.channel|224),e.writeByte(127&this.value),e.writeByte(this.value>>7&127)}get data1(){return 127&this.value}get data2(){return this.value>>7&127}}class Qt extends Ot{constructor(e,t,i,s,a){super(e,t,Me.PerNotePitchBend),this.channel=i,this.noteKey=s,this.value=a}writeTo(t){throw new G(e.AlphaTabErrorType.General,"Note Bend (Midi2.0) events cannot be exported to SMF1.0")}}class $t extends Ot{constructor(e,t){super(e,t,Me.EndOfTrack)}writeTo(e){e.writeByte(255),e.writeByte(47),e.writeByte(0)}}class Kt{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event.type==Me.AlphaTabMetronome}static newMetronomeEvent(e,t,i,s,a){const r=new Ht(0,t,i,s,a);return new Kt(e,r)}}class Zt{}Zt.DefaultChannelCount=17,Zt.MetronomeChannel=Zt.DefaultChannelCount-1,Zt.AudioChannels=2,Zt.MinVolume=0,Zt.MinProgram=0,Zt.MaxProgram=127,Zt.MinPlaybackSpeed=.125,Zt.MaxPlaybackSpeed=8,Zt.MaxPitchWheel=16384,Zt.MaxPitchWheel20=4294967296,Zt.DefaultPitchWheel=Zt.MaxPitchWheel/2,Zt.MicroBufferCount=32,Zt.MicroBufferSize=64;class ei{constructor(e,t,i){this.bpm=e,this.ticks=t,this.time=i}}class ti{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=z.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class ii{get isPlayingMain(){return this._currentState==this._mainState}get isPlayingOneTimeMidi(){return this._currentState==this._oneTimeState}get isPlayingCountIn(){return this._currentState==this._countInState}constructor(e){this._oneTimeState=null,this._countInState=null,this.isLooping=!1,this.playbackSpeed=1,this._synthesizer=e,this._mainState=new ti,this._currentState=this._mainState}get mainPlaybackRange(){return this._mainState.playbackRange}set mainPlaybackRange(e){this._mainState.playbackRange=e,e&&(this._mainState.playbackRangeStartTime=this.tickPositionToTimePositionWithSpeed(this._mainState,e.startTick,1),this._mainState.playbackRangeEndTime=this.tickPositionToTimePositionWithSpeed(this._mainState,e.endTick,1))}get currentTime(){return this._currentState.currentTime/this.playbackSpeed}get currentEndTick(){return this._currentState.endTick}get currentEndTime(){return this._currentState.endTime/this.playbackSpeed}mainSeek(e){if(e*=this.playbackSpeed,this.mainPlaybackRange&&(e<this._mainState.playbackRangeStartTime?e=this._mainState.playbackRangeStartTime:e>this._mainState.playbackRangeEndTime&&(e=this._mainState.playbackRangeEndTime)),e>this._mainState.currentTime)this.mainSilentProcess(e-this._mainState.currentTime);else if(e<this._mainState.currentTime){if(this._mainState.currentTime=0,this._mainState.eventIndex=0,this.isPlayingMain){let e=this._synthesizer.metronomeVolume;this._synthesizer.noteOffAll(!0),this._synthesizer.resetSoft(),this._synthesizer.setupMetronomeChannel(e)}this.mainSilentProcess(e)}}mainSilentProcess(e){if(e<=0)return;let t=Date.now(),i=this._mainState.currentTime+e;if(this.isPlayingMain)for(;this._mainState.currentTime<i;)this.fillMidiEventQueueLimited(i-this._mainState.currentTime)&&this._synthesizer.synthesizeSilent(Zt.MicroBufferSize);this._mainState.currentTime=i;let s=Date.now()-t;J.debug("Sequencer","Silent seek finished in "+s+"ms (main)")}loadOneTimeMidi(e){this._oneTimeState=this.createStateFromFile(e),this._currentState=this._oneTimeState}loadMidi(e){this._mainState=this.createStateFromFile(e),this._currentState=this._mainState}createStateFromFile(e){const t=new ti;t.tempoChanges=[],t.division=e.division,t.eventIndex=0,t.currentTime=0,t.synthData=[];let i=120,s=0,a=0,r=0,n=0,o=0,h=0,l=0,c=0;for(let d of e.events){let u=new Kt(t.synthData.length,d);t.synthData.push(u);let p=d.tick-c;if(s+=p,a+=p*(6e4/(i*e.division)),u.time=a,c=d.tick,n>0)for(;h<s;){let e=Kt.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(d.type===Me.TempoChange){i=6e7/d.microSecondsPerQuarterNote,t.tempoChanges.push(new ei(i,s,a)),o=n*(6e4/(i*e.division))}else if(d.type===Me.TimeSignature){let s=d,a=Math.pow(2,s.denominatorIndex);r=s.numerator,n=t.division*(4/a)|0,o=n*(6e4/(i*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=s.numerator,t.firstTimeSignatureDenominator=a)}else if(d.type===Me.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=s,t}fillMidiEventQueue(){return this.fillMidiEventQueueLimited(-1)}fillMidiEventQueueLimited(e){let t=Zt.MicroBufferSize/this._synthesizer.outSampleRate*1e3*this.playbackSpeed,i=this.internalEndTime;e>0&&(e<t&&(t=e),i=Math.min(this.internalEndTime,this._currentState.currentTime+e));let s=!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<i;)this._synthesizer.dispatchEvent(this._currentState.synthData[this._currentState.eventIndex]),this._currentState.eventIndex++,s=!0;return s}mainTickPositionToTimePosition(e){return this.tickPositionToTimePositionWithSpeed(this._mainState,e,this.playbackSpeed)}mainTimePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(this._mainState,e,this.playbackSpeed)}currentTimePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(this._currentState,e,this.playbackSpeed)}tickPositionToTimePositionWithSpeed(e,t,i){let s=0,a=120,r=0;for(const i of e.tempoChanges){if(t<i.ticks)break;s=i.time,a=i.bpm,r=i.ticks}return s+=(t-=r)*(6e4/(a*e.division)),s/i}timePositionToTickPositionWithSpeed(e,t,i){t*=i;let s=0,a=120,r=0;for(const i of e.tempoChanges){if(t<i.time)break;s=i.ticks,a=i.bpm,r=i.time}return s+=(t-=r)/(6e4/(a*e.division))|0,s+1}get internalEndTime(){return this.isPlayingMain&&this.mainPlaybackRange?this._currentState.playbackRangeEndTime:this._currentState.endTime}get isFinished(){return this._currentState.currentTime>=this.internalEndTime}stop(){this.isPlayingMain&&this.mainPlaybackRange?this._currentState.currentTime=this.mainPlaybackRange.startTick:this._currentState.currentTime=0,this._currentState.eventIndex=0}resetOneTimeMidi(){this._oneTimeState=null,this._currentState=this._mainState}resetCountIn(){this._countInState=null,this._currentState=this._mainState}startCountIn(){this.generateCountInMidi(),this._currentState=this._countInState,this.stop(),this._synthesizer.noteOffAll(!0)}generateCountInMidi(){const e=new ti;e.division=this._mainState.division;let t=120,i=4,s=4;0===this._mainState.eventIndex?(t=this._mainState.tempoChanges[0].bpm,i=this._mainState.firstTimeSignatureNumerator,s=this._mainState.firstTimeSignatureDenominator):(t=this._synthesizer.currentTempo,i=this._synthesizer.timeSignatureNumerator,s=this._synthesizer.timeSignatureDenominator),e.tempoChanges.push(new ei(t,0,0));let a=e.division*(4/s)|0,r=a*(6e4/(t*this._mainState.division)),n=0,o=0;for(let t=0;t<i;t++){let i=Kt.newMetronomeEvent(e.synthData.length,n,t,a,r);e.synthData.push(i),i.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"}(Ie||(Ie={}));class si{constructor(e,t){this.state=e,this.stopped=t}}class ai{constructor(e,t,i,s,a){this.currentTime=e,this.endTime=t,this.currentTick=i,this.endTick=s,this.isSeek=a}}class ri{constructor(){this.id="",this.size=0}static load(e,t,i){if(e&&ri.HeaderSize>e.size)return!1;if(i.position+ri.HeaderSize>=i.length)return!1;if(t.id=Te.read8BitStringLength(i,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=Te.readUInt32LE(i),e&&ri.HeaderSize+t.size>e.size)return!1;e&&(e.size-=ri.HeaderSize+t.size);let s="RIFF"===t.id,a="LIST"===t.id;return(!s||!e)&&(!s&&!a||(t.id=Te.read8BitStringLength(i,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}ri.HeaderSize=8;class ni{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 ri,i=new ri;if(!ri.load(null,t,e)||"sfbk"!==t.id)throw new fe("Soundfont is not a valid Soundfont2 file");for(;ri.load(t,i,e);){let t=new ri;if("pdta"===i.id)for(;ri.load(i,t,e);)switch(t.id){case"phdr":for(let i=0,s=t.size/pi.SizeInFile|0;i<s;i++)this.phdrs.push(new pi(e));break;case"pbag":for(let i=0,s=t.size/di.SizeInFile|0;i<s;i++)this.pbags.push(new di(e));break;case"pmod":for(let i=0,s=t.size/gi.SizeInFile|0;i<s;i++)this.pmods.push(new gi(e));break;case"pgen":for(let i=0,s=t.size/ui.SizeInFile|0;i<s;i++)this.pgens.push(new ui(e));break;case"inst":for(let i=0,s=t.size/ci.SizeInFile|0;i<s;i++)this.insts.push(new ci(e));break;case"ibag":for(let i=0,s=t.size/oi.SizeInFile|0;i<s;i++)this.ibags.push(new oi(e));break;case"imod":for(let i=0,s=t.size/hi.SizeInFile|0;i<s;i++)this.imods.push(new hi(e));break;case"igen":for(let i=0,s=t.size/li.SizeInFile|0;i<s;i++)this.igens.push(new li(e));break;case"shdr":for(let i=0,s=t.size/fi.SizeInFile|0;i<s;i++)this.sHdrs.push(new fi(e));break;default:e.position+=t.size}else if("sdta"===i.id)for(;ri.load(i,t,e);)if("smpl"===t.id)this.fontSamples=ni.loadSamples(t,e);else e.position+=t.size;else e.position+=i.size}}static loadSamples(e,t){let i=e.size/2|0;const s=new Float32Array(i);let a=0;const r=new Uint8Array(16384);for(;i>0;){let e=Math.min(i,r.length/2|0);t.read(r,0,2*e);for(let t=0;t<e;t++){const e=Be.int32ToInt16(r[2*t+1]<<8|r[2*t]);s[a+t]=e/32767}i-=e,a+=e}return s}}class oi{constructor(e){this.instGenNdx=Te.readUInt16LE(e),this.instModNdx=Te.readUInt16LE(e)}}oi.SizeInFile=4;class hi{constructor(e){this.modSrcOper=Te.readUInt16LE(e),this.modDestOper=Te.readUInt16LE(e),this.modAmount=Te.readInt16LE(e),this.modAmtSrcOper=Te.readUInt16LE(e),this.modTransOper=Te.readUInt16LE(e)}}hi.SizeInFile=10;class li{constructor(e){this.genOper=Te.readUInt16LE(e),this.genAmount=new mi(e)}}li.SizeInFile=4;class ci{constructor(e){this.instName=Te.read8BitStringLength(e,20),this.instBagNdx=Te.readUInt16LE(e)}}ci.SizeInFile=22;class di{constructor(e){this.genNdx=Te.readUInt16LE(e),this.modNdx=Te.readUInt16LE(e)}}di.SizeInFile=4;class ui{constructor(e){this.genOper=Te.readUInt16LE(e),this.genAmount=new mi(e)}}ui.SizeInFile=4,ui.GenInstrument=41,ui.GenKeyRange=43,ui.GenVelRange=44,ui.GenSampleId=53;class pi{constructor(e){this.presetName=Te.read8BitStringLength(e,20),this.preset=Te.readUInt16LE(e),this.bank=Te.readUInt16LE(e),this.presetBagNdx=Te.readUInt16LE(e),this.library=Te.readUInt32LE(e),this.genre=Te.readUInt32LE(e),this.morphology=Te.readUInt32LE(e)}}pi.SizeInFile=38;class gi{constructor(e){this.modSrcOper=Te.readUInt16LE(e),this.modDestOper=Te.readUInt16LE(e),this.modAmount=Te.readUInt16LE(e),this.modAmtSrcOper=Te.readUInt16LE(e),this.modTransOper=Te.readUInt16LE(e)}}gi.SizeInFile=10;class fi{constructor(e){this.sampleName=Te.read8BitStringLength(e,20),this.start=Te.readUInt32LE(e),this.end=Te.readUInt32LE(e),this.startLoop=Te.readUInt32LE(e),this.endLoop=Te.readUInt32LE(e),this.sampleRate=Te.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=Te.readSInt8(e),this.sampleLink=Te.readUInt16LE(e),this.sampleType=Te.readUInt16LE(e)}}fi.SizeInFile=46;class mi{get shortAmount(){return Be.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}constructor(e){this.wordAmount=Te.readUInt16LE(e)}}class yi{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 bi{constructor(){this.activeChannel=0,this.channelList=[]}setupVoice(e,t){const i=this.channelList[this.activeChannel],s=t.region.pan+i.panOffset;t.playingChannel=this.activeChannel,t.mixVolume=i.mixVolume,t.noteGainDb+=i.gainDb,t.updatePitchRatio(i,e.outSampleRate),s<=-.5?(t.panFactorLeft=1,t.panFactorRight=0):s>=.5?(t.panFactorLeft=0,t.panFactorRight=1):(t.panFactorLeft=Math.sqrt(.5-s),t.panFactorRight=Math.sqrt(.5+s))}}!function(e){e[e.None=0]="None",e[e.Continuous=1]="Continuous",e[e.Sustain=2]="Sustain"}(De||(De={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(Ae||(Ae={}));class Si{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null,this.fontSamples=null}}class wi{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,i){return e<=t?t:e>=i?i:e}}class _i{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:wi.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:wi.timecents2Secs(this.attack),this.release=this.release<-11950?0:wi.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:wi.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:wi.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?wi.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"}(Re||(Re={}));class Bi{constructor(e){this.loopMode=De.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 _i,this.modEnv=new _i,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 _i(e.ampEnv),this.modEnv=new _i(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=De.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 Re.StartAddrsOffset:this.offset+=Be.int16ToUint32(t.shortAmount);break;case Re.EndAddrsOffset:this.end+=Be.int16ToUint32(t.shortAmount);break;case Re.StartloopAddrsOffset:this.loopStart+=Be.int16ToUint32(t.shortAmount);break;case Re.EndloopAddrsOffset:this.loopEnd+=Be.int16ToUint32(t.shortAmount);break;case Re.StartAddrsCoarseOffset:this.offset+=32768*Be.int16ToUint32(t.shortAmount);break;case Re.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case Re.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case Re.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case Re.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case Re.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case Re.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case Re.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case Re.EndAddrsCoarseOffset:this.end+=32768*Be.int16ToUint32(t.shortAmount);break;case Re.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case Re.Pan:this.pan=t.shortAmount/1e3;break;case Re.DelayModLFO:this.delayModLFO=t.shortAmount;break;case Re.FreqModLFO:this.freqModLFO=t.shortAmount;break;case Re.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case Re.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case Re.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case Re.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case Re.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case Re.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case Re.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case Re.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case Re.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case Re.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case Re.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case Re.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case Re.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case Re.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case Re.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case Re.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case Re.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case Re.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case Re.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case Re.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case Re.StartloopAddrsCoarseOffset:this.loopStart+=32768*Be.int16ToUint32(t.shortAmount);break;case Re.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case Re.EndloopAddrsCoarseOffset:this.loopEnd+=32768*Be.int16ToUint32(t.shortAmount);break;case Re.CoarseTune:this.transpose+=t.shortAmount;break;case Re.FineTune:this.tune+=t.shortAmount;break;case Re.SampleModes:this.loopMode=3&~t.wordAmount?1==(3&t.wordAmount)?De.Continuous:De.None:De.Sustain;break;case Re.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case Re.ExclusiveClass:this.group=t.wordAmount;break;case Re.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"}(Oe||(Oe={}));class Ti{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=Oe.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case Oe.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=Oe.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=Oe.Delay;break;case Oe.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=Oe.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=Oe.Attack;break;case Oe.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=Oe.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=Oe.Hold;break;case Oe.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=Oe.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=Oe.Decay;break;case Oe.Decay:return this.segment=Oe.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case Oe.Sustain:if(this.segment=Oe.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?Ti.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=Oe.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,i,s,a){this.parameters=new _i(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:wi.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:wi.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|i,this.isAmpEnv=s,this.nextSegment(Oe.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)}}Ti.FastReleaseTime=.01;class ki{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,i){this.samplesUntil=e*i|0,this.delta=4*wi.cents2Hertz(t)/i,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 vi{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),i=t*t,s=1/(1+t*this.qInv+i);this.a0=i*s,this.a1=2*this.a0,this.b1=2*(i-1)*s,this.b2=(1-t*this.qInv+i)*s}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 xi{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 Ti,this.modEnv=new Ti,this.lowPass=new vi,this.modLfo=new ki,this.vibLfo=new ki,this.mixVolume=0,this.mute=!1}updatePitchRatio(e,t){let i=e.pitchWheel;e.perNotePitchWheel.has(this.playingKey)&&(i+=e.perNotePitchWheel.get(this.playingKey)-8192);const s=8192===i?e.tuning:i/16383*e.pitchRange*2-e.pitchRange+e.tuning;this.calcPitchRatio(s,t)}calcPitchRatio(e,t){if(!this.region)return;const i=this.playingKey+this.region.transpose+this.region.tune/100;let s=this.region.pitchKeyCenter+(i-this.region.pitchKeyCenter)*(this.region.pitchKeyTrack/100);0!==e&&(s+=e),this.pitchInputTimecents=100*s,this.pitchOutputFactor=this.region.sampleRate/(wi.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(Oe.Sustain,e),this.modEnv.nextSegment(Oe.Sustain,e),this.region.loopMode===De.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(Oe.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(Oe.Sustain,e)}render(e,t,i,s,a){if(!this.region)return;let r=this.region;let n=e.presets[this.playingPreset].fontSamples,o=0,h=e.outputMode===Ae.StereoUnweaved?s:-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 vi(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=wi.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,x=0,N=0,P=0),E?F=.1*r.modLfoToVolume:(C=wi.decibelsToGain(this.noteGainDb),F=0);s>0;){let r,L,M=0,I=s>xi.RenderEffectSampleBlock?xi.RenderEffectSampleBlock:s;if(s-=I,S){let e=_+this.modLfo.level*B+this.modEnv.level*T;b.active=e<=13500,b.active&&b.setup(wi.cents2Hertz(e)/w)}switch(k&&(v=wi.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*x+this.vibLfo.level*N+this.modEnv.level*P))*this.pitchOutputFactor),E&&(C=wi.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 Ae.StereoInterleaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;I-- >0&&y<f;){let e=0|y,s=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[s]*a;b.active&&(r=b.process(r)),t[i+o]+=r*L,o++,t[i+o]+=r*M,o++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case Ae.StereoUnweaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;I-- >0&&y<f;){let e=0|y,s=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[s]*a;b.active&&(r=b.process(r)),t[i+o]+=r*L,o++,t[i+h]+=r*M,h++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case Ae.Mono:for(;I-- >0&&y<f;){let e=0|y,s=e>=g&&u?p:e+1,a=y-e,h=n[e]*(1-a)+n[s]*a;b.active&&(h=b.process(h)),t[i+o]=h*r,o++,y+=v,y>=m&&u&&(y-=g-p+1)}}if(y>=f||this.ampEnv.segment===Oe.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}xi.RenderEffectSampleBlock=Zt.MicroBufferSize;class Ni{constructor(){this._items=[],this._position=0,this.isEmpty=!0}clear(){this._items=[],this._position=0,this.isEmpty=!0}enqueue(e){this.isEmpty=!1,this._items.push(e)}peek(){return this._items[this._position]}dequeue(){const e=this._items[this._position];return this._position++,this._position>=this._items.length/2&&(this._items=this._items.slice(this._position),this._position=0),this.isEmpty=0==this._items.length,e}toArray(){const e=this._items.slice(this._position);return e.reverse(),e}}!function(e){e[e.BankSelectCoarse=0]="BankSelectCoarse",e[e.ModulationCoarse=1]="ModulationCoarse",e[e.DataEntryCoarse=6]="DataEntryCoarse",e[e.VolumeCoarse=7]="VolumeCoarse",e[e.PanCoarse=10]="PanCoarse",e[e.ExpressionControllerCoarse=11]="ExpressionControllerCoarse",e[e.BankSelectFine=32]="BankSelectFine",e[e.ModulationFine=33]="ModulationFine",e[e.DataEntryFine=38]="DataEntryFine",e[e.VolumeFine=39]="VolumeFine",e[e.PanFine=42]="PanFine",e[e.ExpressionControllerFine=43]="ExpressionControllerFine",e[e.HoldPedal=64]="HoldPedal",e[e.LegatoPedal=68]="LegatoPedal",e[e.NonRegisteredParameterFine=98]="NonRegisteredParameterFine",e[e.NonRegisteredParameterCourse=99]="NonRegisteredParameterCourse",e[e.RegisteredParameterFine=100]="RegisteredParameterFine",e[e.RegisteredParameterCourse=101]="RegisteredParameterCourse",e[e.AllSoundOff=120]="AllSoundOff",e[e.ResetControllers=121]="ResetControllers",e[e.AllNotesOff=123]="AllNotesOff"}(Ge||(Ge={}));class Pi{constructor(e){this._midiEventQueue=new Ni,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this._transpositionPitches=new Map,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=Ae.StereoInterleaved,this.outSampleRate=0,this.globalGainDb=0,this.outSampleRate=e}synthesize(e,t,i){return this.fillWorkingBuffer(e,t,i)}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 i=this.channelInit(e);for(let i of this._voices)i.playingChannel===e&&-1!==i.playingPreset&&(i.mixVolume=t);i.mixVolume=t}channelSetMute(e,t){t?this._mutedChannels.set(e,!0):this._mutedChannels.delete(e)}channelSetSolo(e,t){t?this._soloChannels.set(e,!0):this._soloChannels.delete(e),this._isAnySolo=this._soloChannels.size>0}resetChannelStates(){this._mutedChannels=new Map,this._soloChannels=new Map,this.applyTranspositionPitches(new Map),this._isAnySolo=!1}applyTranspositionPitches(e){const t=this._transpositionPitches;for(const i of this._voices)if(i.playingChannel>=0&&9!==i.playingChannel){let s=0;t.has(i.playingChannel)&&(s-=t.get(i.playingChannel)),e.has(i.playingChannel)&&(s+=e.get(i.playingChannel)),i.playingKey+=s,this._channels&&i.updatePitchRatio(this._channels.channelList[i.playingChannel],this.outSampleRate)}this._transpositionPitches=e}dispatchEvent(e){this._midiEventQueue.enqueue(e)}fillWorkingBuffer(e,t,i){const s=this._isAnySolo,a=[];for(;!this._midiEventQueue.isEmpty;){let e=this._midiEventQueue.dequeue();e.isMetronome&&this.metronomeVolume>0?(this.channelNoteOff(Zt.MetronomeChannel,33),this.channelNoteOn(Zt.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)||s&&r!=Zt.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,i,n):a.kill()}return a}processMidiMessage(e){J.debug("MIdi","Processing Midi message "+Me[e.type]+"/"+e.tick);switch(e.type){case Me.TimeSignature:const t=e;this.timeSignatureNumerator=t.numerator,this.timeSignatureDenominator=Math.pow(2,t.denominatorIndex);break;case Me.NoteOn:const i=e;this.channelNoteOn(i.channel,i.noteKey,i.noteVelocity/127);break;case Me.NoteOff:const s=e;this.channelNoteOff(s.channel,s.noteKey);break;case Me.ControlChange:const a=e;this.channelMidiControl(a.channel,a.controller,a.value);break;case Me.ProgramChange:const r=e;this.channelSetPresetNumber(r.channel,r.program,9===r.channel);break;case Me.TempoChange:const n=e;this.currentTempo=6e7/n.microSecondsPerQuarterNote;break;case Me.PitchBend:const o=e;this.channelSetPitchWheel(o.channel,o.value);break;case Me.PerNotePitchBend:const h=e;let l=h.value;l=l*Zt.MaxPitchWheel/Zt.MaxPitchWheel20,this.channelSetPerNotePitchWheel(h.channel,h.noteKey,l)}}get metronomeVolume(){return this.channelGetMixVolume(Zt.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Zt.MetronomeChannel,e),e>0&&(this.channelSetVolume(Zt.MetronomeChannel,1),this.channelSetPresetNumber(Zt.MetronomeChannel,0,!0))}get masterVolume(){return wi.decibelsToGain(this.globalGainDb)}set masterVolume(e){var t=wi.gainToDecibels(e);const i=t-this.globalGainDb;if(0!==i){for(const e of this._voices)-1!==e.playingPreset&&(e.noteGainDb+=i);this.globalGainDb=t}}resetSoft(){for(const e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<Oe.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);if(this._channels)for(const e of this._channels.channelList)e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.perNotePitchWheel.clear(),e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0}get presetCount(){return this.presets?.length??0}reset(){for(let e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<Oe.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);this._channels=null}setOutput(e,t,i){this.outputMode=e,this.outSampleRate=t>=1?t:44100,this.globalGainDb=i}noteOn(e,t,i){if(!this.presets)return;const s=127*i|0;if(e<0||e>=this.presets.length)return;if(i<=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||s<r.loVel||s>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 xi;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-wi.gainToDecibels(1/i),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!==De.None&&r.loopStart<r.loopEnd;n.loopStart=o?r.loopStart:0,n.loopEnd=o?r.loopEnd:0,n.ampEnv.setup(r.ampEnv,t,s,!0,this.outSampleRate),n.modEnv.setup(r.modEnv,t,s,!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(wi.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,i,s){let a=this.getPresetIndex(e,t);return-1!==a&&(this.noteOn(a,i,s),!0)}noteOff(e,t){let i=null,s=null,a=[];for(let r of this._voices)r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=Oe.Release||(!i||r.playIndex<i.playIndex?(i=r,s=r,a.push(r)):r.playIndex===i.playIndex&&(s=r,a.push(r)));if(i)for(const r of a)r!==i&&r!==s&&(r.playIndex!==i.playIndex||r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=Oe.Release)||r.end(this.outSampleRate)}bankNoteOff(e,t,i){const s=this.getPresetIndex(e,t);return-1!==s&&(this.noteOff(s,i),!0)}noteOffAll(e){for(const t of this._voices)-1!==t.playingPreset&&t.ampEnv.segment<Oe.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 bi);for(let t=this._channels.channelList.length;t<=e;t++){let e=new yi;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 i=this.presets.length-1;i>=0;i--){let s=this.presets[i];if(s.presetNumber===t&&s.bank===e)return i}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,i){!this._channels||e>this._channels.channelList.length||(this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,i))}channelNoteOff(e,t){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e));const i=[];let s=null,a=null;for(const r of this._voices)-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=Oe.Release||(!s||r.playIndex<s.playIndex?(s=r,a=r,i.push(r)):r.playIndex===s.playIndex&&(a=r,i.push(r)));if(this.channelInit(e).perNotePitchWheel.delete(t),s)for(const r of i)r!==s&&r!==a&&(r.playIndex!==s.playIndex||-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=Oe.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<Oe.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<Oe.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=Be.int32ToUint16(t)}channelSetPresetNumber(e,t,i=!1){const s=this.channelInit(e);let a=0;return i?(a=this.getPresetIndex(128|32767&s.bank,t),-1===a&&(a=this.getPresetIndex(128,t)),-1===a&&(a=this.getPresetIndex(128,0)),-1===a&&(a=this.getPresetIndex(2047&s.bank,t))):a=this.getPresetIndex(2047&s.bank,t),s.presetIndex=a,-1!==a}channelSetBank(e,t){this.channelInit(e).bank=Be.int32ToUint16(t)}channelSetBankPreset(e,t,i){const s=this.channelInit(e),a=this.getPresetIndex(t,i);return-1!==a&&(s.presetIndex=Be.int32ToUint16(a),s.bank=Be.int32ToUint16(t),!0)}channelSetPan(e,t){for(const i of this._voices)if(i.playingChannel===e&&-1!==i.playingPreset){let e=i.region.pan+t-.5;e<=-.5?(i.panFactorLeft=1,i.panFactorRight=0):e>=.5?(i.panFactorLeft=0,i.panFactorRight=1):(i.panFactorLeft=Math.sqrt(.5-e),i.panFactorRight=Math.sqrt(.5+e))}this.channelInit(e).panOffset=t-.5}channelSetVolume(e,t){const i=this.channelInit(e),s=wi.gainToDecibels(t),a=s-i.gainDb;if(0!==a){for(const t of this._voices)t.playingChannel===e&&-1!==t.playingPreset&&(t.noteGainDb+=a);i.gainDb=s}}channelSetPitchWheel(e,t){const i=this.channelInit(e);i.pitchWheel!==t&&(i.pitchWheel=Be.int32ToUint16(t),this.channelApplyPitch(e,i))}channelSetPerNotePitchWheel(e,t,i){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e));const s=this.channelInit(e);s.perNotePitchWheel.has(t)&&s.perNotePitchWheel.get(t)===i||(s.perNotePitchWheel.set(t,i),this.channelApplyPitch(e,s,t))}channelApplyPitch(e,t,i=-1){for(const s of this._voices)s.playingChannel!==e||-1===s.playingPreset||-1!=i&&s.playingKey!==i||s.updatePitchRatio(t,this.outSampleRate)}channelSetPitchRange(e,t){const i=this.channelInit(e);i.pitchRange!==t&&(i.pitchRange=t,8192!==i.pitchWheel&&this.channelApplyPitch(e,i))}channelSetTuning(e,t){const i=this.channelInit(e);i.tuning!==t&&(i.tuning=t,this.channelApplyPitch(e,i))}channelMidiControl(e,t,i){let s=this.channelInit(e);switch(t){case Ge.DataEntryFine:return s.midiData=Be.int32ToUint16(16256&s.midiData|i),void(0===s.midiRpn?this.channelSetPitchRange(e,(s.midiData>>7)+.01*(127&s.midiData)):1===s.midiRpn?this.channelSetTuning(e,(0|s.tuning)+(s.midiData-8192)/8192):2===s.midiRpn&&this.channelSetTuning(e,i-64+(s.tuning-(0|s.tuning))));case Ge.VolumeCoarse:return s.midiVolume=Be.int32ToUint16(127&s.midiVolume|i<<7),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case Ge.VolumeFine:return s.midiVolume=Be.int32ToUint16(16256&s.midiVolume|i),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case Ge.ExpressionControllerCoarse:return s.midiExpression=Be.int32ToUint16(127&s.midiExpression|i<<7),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case Ge.ExpressionControllerFine:return s.midiExpression=Be.int32ToUint16(16256&s.midiExpression|i),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case Ge.PanCoarse:return s.midiPan=Be.int32ToUint16(127&s.midiPan|i<<7),void this.channelSetPan(e,s.midiPan/16383);case Ge.PanFine:return s.midiPan=Be.int32ToUint16(16256&s.midiPan|i),void this.channelSetPan(e,s.midiPan/16383);case Ge.DataEntryCoarse:return s.midiData=Be.int32ToUint16(127&s.midiData|i<<7),void(0===s.midiRpn?this.channelSetPitchRange(e,(s.midiData>>7)+.01*(127&s.midiData)):1===s.midiRpn?this.channelSetTuning(e,(0|s.tuning)+(s.midiData-8192)/8192):2===s.midiRpn&&t===Ge.DataEntryCoarse&&this.channelSetTuning(e,i-64+(s.tuning-(0|s.tuning))));case Ge.BankSelectCoarse:return void(s.bank=Be.int32ToUint16(32768|i));case Ge.BankSelectFine:return void(s.bank=Be.int32ToUint16((32768&s.bank?(127&s.bank)<<7:0)|i));case Ge.RegisteredParameterCourse:return void(s.midiRpn=Be.int32ToUint16(127&(65535===s.midiRpn?0:s.midiRpn)|i<<7));case Ge.RegisteredParameterFine:return void(s.midiRpn=Be.int32ToUint16(16256&(65535===s.midiRpn?0:s.midiRpn)|i));case Ge.NonRegisteredParameterFine:case Ge.NonRegisteredParameterCourse:return void(s.midiRpn=65535);case Ge.AllSoundOff:return void this.channelSoundsOffAll(e);case Ge.AllNotesOff:return void this.channelNoteOffAll(e);case Ge.ResetControllers:return s.midiVolume=16383,s.midiExpression=16383,s.midiPan=8192,s.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?wi.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 i=[];for(let t=0;t<e.phdrs.length-1;t++){const s=e.phdrs[t];let a=0;const r=new Si;i.push(r),r.name=s.presetName,r.bank=s.bank,r.presetNumber=s.preset,r.fontSamples=e.fontSamples;let n=0;for(let i=s.presetBagNdx;i<e.phdrs[t+1].presetBagNdx;i++){let t=0,s=127,a=0,r=127;for(let o=e.pbags[i].genNdx;o<e.pbags[i+1].genNdx;o++){let i=e.pgens[o];if(i.genOper!==ui.GenKeyRange)if(i.genOper!==ui.GenVelRange){if(i.genOper===ui.GenInstrument&&!(i.genAmount.wordAmount>=e.insts.length))for(let o=e.insts[i.genAmount.wordAmount].instBagNdx;o<e.insts[i.genAmount.wordAmount+1].instBagNdx;o++){let i=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!==ui.GenKeyRange?o.genOper!==ui.GenVelRange?53===o.genOper&&h>=t&&i<=s&&c>=a&&l<=r&&n++:(l=o.genAmount.lowByteAmount,c=o.genAmount.highByteAmount):(i=o.genAmount.lowByteAmount,h=o.genAmount.highByteAmount)}}}else a=i.genAmount.lowByteAmount,r=i.genAmount.highByteAmount;else t=i.genAmount.lowByteAmount,s=i.genAmount.highByteAmount}}r.regions=new Array(n);let o=new Bi;o.clear(!0);for(let i=s.presetBagNdx;i<e.phdrs[t+1].presetBagNdx;i++){const t=e.pbags[i],n=new Bi(o);let h=!1;for(let s=t.genNdx;s<e.pbags[i+1].genNdx;s++){const t=e.pgens[s];if(t.genOper===ui.GenInstrument){let i=t.genAmount.wordAmount;if(i>=e.insts.length)continue;let s=new Bi;s.clear(!1);let o=e.insts[i];for(let t=o.instBagNdx;t<e.insts[i+1].instBagNdx;t++){let i=e.ibags[t],h=new Bi(s),l=!1;for(let s=i.instGenNdx;s<e.ibags[t+1].instGenNdx;s++){let t=e.igens[s];if(t.genOper===ui.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:wi.timecents2Secs(h.delayModLFO),h.delayVibLFO=h.delayVibLFO<-11950?0:wi.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 i=e.sHdrs[t.genAmount.wordAmount];h.offset+=i.start,h.end+=i.end,h.loopStart+=i.startLoop,h.loopEnd+=i.endLoop,i.endLoop>0&&(h.loopEnd-=1),-1===h.pitchKeyCenter&&(h.pitchKeyCenter=i.originalPitch),h.tune+=i.pitchCorrection,h.sampleRate=i.sampleRate,0!==h.end&&h.end<r.fontSamples.length?h.end++:h.end=r.fontSamples.length,r.regions[a]=new Bi(h),a++,l=!0}else h.operator(t.genOper,t.genAmount)}i!==e.ibags[o.instBagNdx]||l||(s=new Bi(h))}h=!0}else n.operator(t.genOper,t.genAmount)}t!==e.pbags[s.presetBagNdx]||h||(o=n)}}if(t&&this.presets)for(const e of i)this.presets.push(e);else this.presets=i}}class Ei{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 Ci{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 Fi{constructor(e){this.events=e}}class Li{constructor(e){this.playbackRange=e}}class Mi{get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return J.logLevel}set logLevel(e){J.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Zt.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Zt.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Zt.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=wi.clamp(e,Zt.MinPlaybackSpeed,Zt.MaxPlaybackSpeed);let t=this._sequencer.playbackSpeed;this._sequencer.playbackSpeed=e,this.timePosition=this.timePosition*(t/e)}get tickPosition(){return this._tickPosition}set tickPosition(e){this.timePosition=this._sequencer.mainTickPositionToTimePosition(e)}get timePosition(){return this._timePosition}set timePosition(e){J.debug("AlphaSynth",`Seeking to position ${e}ms (main)`),this._sequencer.mainSeek(e),this.updateTimePosition(e,!0),this._sequencer.isPlayingMain&&(this._notPlayedSamples=0,this.output.resetSamples())}get playbackRange(){return this._sequencer.mainPlaybackRange}set playbackRange(e){this._sequencer.mainPlaybackRange=e,e&&(this.tickPosition=e.startTick),this.playbackRangeChanged.trigger(new Li(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){J.debug("AlphaSynth","Destroying player"),this.stop(),this.output.destroy()}constructor(e,t){this._isSoundFontLoaded=!1,this._isMidiLoaded=!1,this._tickPosition=0,this._timePosition=0,this._metronomeVolume=0,this._countInVolume=0,this._playedEventsQueue=new Ni,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this.isReady=!1,this.state=Ie.Paused,this.ready=new Ei,this.readyForPlayback=new Ei,this.finished=new Ei,this.soundFontLoaded=new Ei,this.soundFontLoadFailed=new Ci,this.midiLoaded=new Ci,this.midiLoadFailed=new Ci,this.stateChanged=new Ci,this.positionChanged=new Ci,this.midiEventsPlayed=new Ci,this.playbackRangeChanged=new Ci,J.debug("AlphaSynth","Initializing player"),this.state=Ie.Paused,J.debug("AlphaSynth","Creating output"),this.output=e,J.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new Pi(this.output.sampleRate),this._sequencer=new ii(this._synthesizer),J.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this.state!=Ie.Playing||this._sequencer.isFinished){let e=new Float32Array(0);this.output.addSamples(e)}else{let e=new Float32Array(Zt.MicroBufferSize*Zt.MicroBufferCount*Zt.AudioChannels),t=0;for(let i=0;i<Zt.MicroBufferCount;i++){this._sequencer.fillMidiEventQueue();const i=this._synthesizer.synthesize(e,t,Zt.MicroBufferSize);t+=Zt.MicroBufferSize*Zt.AudioChannels;for(const e of i)this._midiEventsPlayedFilter.has(e.event.type)&&this._playedEventsQueue.enqueue(e);if(this._sequencer.isFinished)break}t<e.length&&(e=e.subarray(0,t)),this._notPlayedSamples+=e.length,this.output.addSamples(e)}})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open(t)}play(){return!(this.state!==Ie.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(J.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(J.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),J.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.state=Ie.Playing,this.stateChanged.trigger(new si(this.state,!1))}pause(){this.state!==Ie.Paused&&this._isMidiLoaded&&(J.debug("AlphaSynth","Pausing playback"),this.state=Ie.Paused,this.stateChanged.trigger(new si(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===Ie.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(J.debug("AlphaSynth","Stopping playback"),this.state=Ie.Paused,this.output.pause(),this._notPlayedSamples=0,this._sequencer.stop(),this._synthesizer.noteOffAll(!0),this.tickPosition=this._sequencer.mainPlaybackRange?this._sequencer.mainPlaybackRange.startTick:0,this.stateChanged.trigger(new si(this.state,!0)))}playOneTimeMidiFile(e){this._sequencer.isPlayingOneTimeMidi?this.stopOneTimeMidi():this.pause(),this._sequencer.loadOneTimeMidi(e),this._synthesizer.noteOffAll(!0),this.updateTimePosition(0,!0),this._notPlayedSamples=0,this.output.resetSamples(),this.output.play()}resetSoundFonts(){this.stop(),this._synthesizer.resetPresets(),this._isSoundFontLoaded=!1,this.soundFontLoaded.trigger()}loadSoundFont(e,t){this.pause();let i=ke.fromBuffer(e);try{J.debug("AlphaSynth","Loading soundfont from bytes");let e=new ni;e.load(i),this._synthesizer.loadPresets(e,t),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),J.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){J.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{J.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new ai(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),J.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){J.error("AlphaSynth","Could not load midi from model "+e),this.midiLoadFailed.trigger(e)}}applyTranspositionPitches(e){this._synthesizer.applyTranspositionPitches(e)}setChannelMute(e,t){this._synthesizer.channelSetMute(e,t)}resetChannelStates(){this._synthesizer.resetChannelStates()}setChannelSolo(e,t){this._synthesizer.channelSetSolo(e,t)}setChannelVolume(e,t){t=Math.max(t,Zt.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;let t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*Zt.AudioChannels,this.updateTimePosition(this._timePosition+t,!1),this.checkForFinish()}checkForFinish(){let e=0,t=0;this.playbackRange&&this._sequencer.isPlayingMain?(e=this.playbackRange.startTick,t=this.playbackRange.endTick):t=this._sequencer.currentEndTick,this._tickPosition>=t&&this._notPlayedSamples<=0&&(this._notPlayedSamples=0,this._sequencer.isPlayingCountIn?(J.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(J.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=Ie.Paused,this.stopOneTimeMidi()):(J.debug("AlphaSynth","Finished playback (main)"),this.finished.trigger(),this.isLooping?this.tickPosition=e:this.stop()))}stopOneTimeMidi(){this.output.pause(),this._synthesizer.noteOffAll(!0),this._sequencer.resetOneTimeMidi(),this.timePosition=this._sequencer.currentTime}updateTimePosition(e,t){const i=e;this._timePosition=i;const s=this._sequencer.currentTimePositionToTickPosition(i);this._tickPosition=s;const a=this._sequencer.currentEndTime,r=this._sequencer.currentEndTick,n=this._sequencer.isPlayingMain?"main":this._sequencer.isPlayingCountIn?"count-in":"one-time";if(J.debug("AlphaSynth",`Position changed: (time: ${i}/${a}, tick: ${s}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new ai(i,a,s,r,t)),t)this._playedEventsQueue.clear();else{const e=new Ni;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<i;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new Fi(e.toArray()))}}}class Ii{static parseEnum(t,i){switch(typeof t){case"string":const e=parseInt(t);return isNaN(e)?i[Object.keys(i).find((e=>e.toLowerCase()===t.toLowerCase()))]:e;case"number":return t;case"undefined":case"object":return null}throw new G(e.AlphaTabErrorType.Format,`Could not parse enum value '${t}'`)}static forEach(e,t){if(e instanceof Map)e.forEach(t);else if("object"==typeof e)for(const i in e)t(e[i],i)}static getValue(e,t){return e instanceof Map?e.get(t):"object"==typeof e?e[t]:null}}class Di{constructor(e,t,i){this.text=e,this.startPos=t,this.endPos=i}}class Ai{constructor(e){this.style="normal",this.variant="normal",this.weight="normal",this.stretch="normal",this.lineHeight="normal",this.size="1rem",this.families=[],this.parseOnlyFamilies=!1,this._currentTokenIndex=-1,this._input="",this._currentToken=null,this._input=e,this._tokens=this.splitToTokens(e)}splitToTokens(e){const t=[];let i=0;for(;i<e.length;){let s=i;for(;s<e.length&&" "!==e.charAt(s);)s++;s>i&&t.push(new Di(e.substring(i,s),i,s)),i=s+1}return t}parse(){if(this.reset(),1===this._tokens.length)switch(this._currentToken?.text){case"caption":case"icon":case"menu":case"message-box":case"small-caption":case"status-bar":case"inherit":return}this.parseOnlyFamilies||(this.fontStyleVariantWeight(),this.fontSizeLineHeight()),this.fontFamily()}static parseFamilies(e){const t=new Ai(e);return t.parseOnlyFamilies=!0,t.parse(),t.families}fontFamily(){if(!this._currentToken){if(this.parseOnlyFamilies)return;throw new Error("Missing font list")}const e=this._input.substr(this._currentToken.startPos).trim();let t=0;for(;t<e.length;){let i=e.charAt(t);if(" "===i||","==i)t++;else if('"'===i||"'"===i){const s=this.findEndOfQuote(e,t+1,i);this.families.push(e.substring(t+1,s).split("\\"+i).join(i)),t=s+1}else{const i=this.findEndOfQuote(e,t+1,",");this.families.push(e.substring(t,i).trim()),t=i+1}}}findEndOfQuote(e,t,i){let s=!1;for(;t<e.length;){const a=e.charAt(t);if(!s&&a===i)return t;s=!s&&"\\"===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,i=!1,s=3,a=[];for(;;){if(!this._currentToken)return;let r=this._currentToken.text;switch(r){case"normal":case"inherit":a.push(r),s--,this.nextToken();break;case"italic":case"oblique":this.style=r,e=!0,s--,this.nextToken();break;case"small-caps":this.variant=r,t=!0,s--,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,i=!0,s--,this.nextToken();break;default:return}if(0===s)break}for(;a.length>0;){const s=a.pop();i?t?e||(this.style=s):this.variant=s:this.weight=s}}reset(){this._currentTokenIndex=-1,this.nextToken()}static quoteFont(e){if(-1===e.indexOf(" "))return e;return`"${e.replaceAll('"','\\"')}"`}}!function(e){e[e.Plain=0]="Plain",e[e.Italic=1]="Italic"}(Ve||(Ve={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(He||(He={}));class Ri{reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=Ai.parseFamilies(e)}get families(){return this._families}set families(e){this._families=e,this.reset()}get size(){return this._size}set size(e){this._size=e,this.reset()}get style(){return this._style}set style(e){this._style=e,this.reset()}get weight(){return this._weight}set weight(e){this._weight=e,this.reset()}get isBold(){return this.weight===He.Bold}get isItalic(){return this.style===Ve.Italic}constructor(e,t,i=Ve.Plain,s=He.Regular){this._cssScale=0,this._families=Ai.parseFamilies(e),this._size=t,this._style=i,this._weight=s,this._css=this.toCssString()}static withFamilyList(e,t,i=Ve.Plain,s=He.Regular){const a=new Ri("",t,i,s);return a.families=e,a}toCssString(e=1){if(!(this._css&&Math.abs(e-this._cssScale)<.01)){let t="";this.isBold&&(t+="bold "),this.isItalic&&(t+="italic "),t+=this.size*e,t+="px ",t+=this.families.map((e=>Ai.quoteFont(e))).join(", "),this._css=t,this._cssScale=e}return this._css}static fromJson(e){switch(typeof e){case"undefined":default:return null;case"object":{const t=e;let i=t.get("families"),s=t.get("size"),a=Ii.parseEnum(t.get("style"),Ve),r=Ii.parseEnum(t.get("weight"),He);return Ri.withFamilyList(i,s,a,r)}case"string":{const t=new Ai(e);t.parse();let i=t.families,s=t.size.toLowerCase(),a=0;switch(s){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=s.endsWith("em")?16*parseFloat(s.substr(0,s.length-2)):s.endsWith("pt")?16*parseFloat(s.substr(0,s.length-2))/12:s.endsWith("px")?parseFloat(s.substr(0,s.length-2)):12}catch(e){a=12}}let r=Ve.Plain;"italic"===t.style&&(r=Ve.Italic);let n=He.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=He.Bold}return Ri.withFamilyList(i,a,r,n)}}}static toJson(e){const t=new Map;return t.set("families",e.families),t.set("size",e.size),t.set("style",e.style),t.set("weight",e.weight),t}}class Oi{constructor(){this.copyrightFont=new Ri(Oi.sansFont,12,Ve.Plain,He.Bold),this.titleFont=new Ri(Oi.serifFont,32,Ve.Plain),this.subTitleFont=new Ri(Oi.serifFont,20,Ve.Plain),this.wordsFont=new Ri(Oi.serifFont,15,Ve.Plain),this.effectFont=new Ri(Oi.serifFont,12,Ve.Italic),this.fretboardNumberFont=new Ri(Oi.sansFont,11,Ve.Plain),this.tablatureFont=new Ri(Oi.sansFont,13,Ve.Plain),this.graceFont=new Ri(Oi.sansFont,11,Ve.Plain),this.staffLineColor=new me(165,165,165,255),this.barSeparatorColor=new me(34,34,17,255),this.barNumberFont=new Ri(Oi.sansFont,11,Ve.Plain),this.barNumberColor=new me(200,0,0,255),this.fingeringFont=new Ri(Oi.serifFont,14,Ve.Plain),this.markerFont=new Ri(Oi.serifFont,14,Ve.Plain,He.Bold),this.mainGlyphColor=new me(0,0,0,255),this.secondaryGlyphColor=new me(0,0,0,100),this.scoreInfoColor=new me(0,0,0,255)}}Oi.sansFont="Arial, sans-serif",Oi.serifFont="Georgia, serif",e.SystemsLayoutMode=void 0,(We=e.SystemsLayoutMode||(e.SystemsLayoutMode={}))[We.Automatic=0]="Automatic",We[We.UseModelLayout=1]="UseModelLayout";class Gi{constructor(){this.scale=1,this.stretchForce=1,this.layoutMode=e.LayoutMode.Page,this.staveProfile=e.StaveProfile.Default,this.barsPerRow=-1,this.startBar=1,this.barCount=-1,this.barCountPerPartial=10,this.justifyLastSystem=!1,this.resources=new Oi,this.padding=null,this.systemsLayoutMode=e.SystemsLayoutMode.Automatic}}class Vi{constructor(){this.encoding="utf-8",this.mergePartGroupsInMusicXml=!1,this.beatTextAsLyrics=!1}}e.ScrollMode=void 0,(ze=e.ScrollMode||(e.ScrollMode={}))[ze.Off=0]="Off",ze[ze.Continuous=1]="Continuous",ze[ze.OffScreen=2]="OffScreen";class Hi{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 Wi{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}e.PlayerOutputMode=void 0,(Ue=e.PlayerOutputMode||(e.PlayerOutputMode={}))[Ue.WebAudioAudioWorklets=0]="WebAudioAudioWorklets",Ue[Ue.WebAudioScriptProcessor=1]="WebAudioScriptProcessor";class zi{constructor(){this.soundFont=null,this.scrollElement="html,body",this.outputMode=e.PlayerOutputMode.WebAudioAudioWorklets,this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=e.ScrollMode.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new Hi,this.slide=new Wi,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}class Ui{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scriptfile",e.scriptFile),t.set("fontdirectory",e.fontDirectory),t.set("file",e.file),t.set("tex",e.tex),t.set("tracks",e.tracks),t.set("enablelazyloading",e.enableLazyLoading),t.set("engine",e.engine),t.set("loglevel",e.logLevel),t.set("useworkers",e.useWorkers),t.set("includenotebounds",e.includeNoteBounds),t}static setProperty(t,i,s){switch(i){case"scriptfile":return t.scriptFile=s,!0;case"fontdirectory":return t.fontDirectory=s,!0;case"file":return t.file=s,!0;case"tex":return t.tex=s,!0;case"tracks":return t.tracks=s,!0;case"enablelazyloading":return t.enableLazyLoading=s,!0;case"engine":return t.engine=s,!0;case"loglevel":return t.logLevel=Ii.parseEnum(s,e.LogLevel),!0;case"useworkers":return t.useWorkers=s,!0;case"includenotebounds":return t.includeNoteBounds=s,!0}return!1}}class Xi{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("copyrightfont",Ri.toJson(e.copyrightFont)),t.set("titlefont",Ri.toJson(e.titleFont)),t.set("subtitlefont",Ri.toJson(e.subTitleFont)),t.set("wordsfont",Ri.toJson(e.wordsFont)),t.set("effectfont",Ri.toJson(e.effectFont)),t.set("fretboardnumberfont",Ri.toJson(e.fretboardNumberFont)),t.set("tablaturefont",Ri.toJson(e.tablatureFont)),t.set("gracefont",Ri.toJson(e.graceFont)),t.set("stafflinecolor",me.toJson(e.staffLineColor)),t.set("barseparatorcolor",me.toJson(e.barSeparatorColor)),t.set("barnumberfont",Ri.toJson(e.barNumberFont)),t.set("barnumbercolor",me.toJson(e.barNumberColor)),t.set("fingeringfont",Ri.toJson(e.fingeringFont)),t.set("markerfont",Ri.toJson(e.markerFont)),t.set("mainglyphcolor",me.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",me.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",me.toJson(e.scoreInfoColor)),t}static setProperty(e,t,i){switch(t){case"copyrightfont":return e.copyrightFont=Ri.fromJson(i),!0;case"titlefont":return e.titleFont=Ri.fromJson(i),!0;case"subtitlefont":return e.subTitleFont=Ri.fromJson(i),!0;case"wordsfont":return e.wordsFont=Ri.fromJson(i),!0;case"effectfont":return e.effectFont=Ri.fromJson(i),!0;case"fretboardnumberfont":return e.fretboardNumberFont=Ri.fromJson(i),!0;case"tablaturefont":return e.tablatureFont=Ri.fromJson(i),!0;case"gracefont":return e.graceFont=Ri.fromJson(i),!0;case"stafflinecolor":return e.staffLineColor=me.fromJson(i),!0;case"barseparatorcolor":return e.barSeparatorColor=me.fromJson(i),!0;case"barnumberfont":return e.barNumberFont=Ri.fromJson(i),!0;case"barnumbercolor":return e.barNumberColor=me.fromJson(i),!0;case"fingeringfont":return e.fingeringFont=Ri.fromJson(i),!0;case"markerfont":return e.markerFont=Ri.fromJson(i),!0;case"mainglyphcolor":return e.mainGlyphColor=me.fromJson(i),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=me.fromJson(i),!0;case"scoreinfocolor":return e.scoreInfoColor=me.fromJson(i),!0}return!1}}class Yi{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scale",e.scale),t.set("stretchforce",e.stretchForce),t.set("layoutmode",e.layoutMode),t.set("staveprofile",e.staveProfile),t.set("barsperrow",e.barsPerRow),t.set("startbar",e.startBar),t.set("barcount",e.barCount),t.set("barcountperpartial",e.barCountPerPartial),t.set("justifylastsystem",e.justifyLastSystem),t.set("resources",Xi.toJson(e.resources)),t.set("padding",e.padding),t.set("systemslayoutmode",e.systemsLayoutMode),t}static setProperty(t,i,s){switch(i){case"scale":return t.scale=s,!0;case"stretchforce":return t.stretchForce=s,!0;case"layoutmode":return t.layoutMode=Ii.parseEnum(s,e.LayoutMode),!0;case"staveprofile":return t.staveProfile=Ii.parseEnum(s,e.StaveProfile),!0;case"barsperrow":return t.barsPerRow=s,!0;case"startbar":return t.startBar=s,!0;case"barcount":return t.barCount=s,!0;case"barcountperpartial":return t.barCountPerPartial=s,!0;case"justifylastsystem":return t.justifyLastSystem=s,!0;case"padding":return t.padding=s,!0;case"systemslayoutmode":return t.systemsLayoutMode=Ii.parseEnum(s,e.SystemsLayoutMode),!0}if(["resources"].indexOf(i)>=0)return Xi.fromJson(t.resources,s),!0;for(const e of["resources"])if(0===i.indexOf(e)&&Xi.setProperty(t.resources,i.substring(e.length),s))return!0;return!1}}class qi{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("notationmode",e.notationMode),t.set("fingeringmode",e.fingeringMode);{const i=new Map;t.set("elements",i);for(const[t,s]of e.elements)i.set(t.toString(),s)}return t.set("rhythmmode",e.rhythmMode),t.set("rhythmheight",e.rhythmHeight),t.set("transpositionpitches",e.transpositionPitches),t.set("displaytranspositionpitches",e.displayTranspositionPitches),t.set("smallgracetabnotes",e.smallGraceTabNotes),t.set("extendbendarrowsontiednotes",e.extendBendArrowsOnTiedNotes),t.set("extendlineeffectstobeatend",e.extendLineEffectsToBeatEnd),t.set("slurheight",e.slurHeight),t}static setProperty(t,i,s){switch(i){case"notationmode":return t.notationMode=Ii.parseEnum(s,e.NotationMode),!0;case"fingeringmode":return t.fingeringMode=Ii.parseEnum(s,e.FingeringMode),!0;case"elements":return t.elements=new Map,Ii.forEach(s,((e,i)=>{t.elements.set(Ii.parseEnum(i,v),e)})),!0;case"rhythmmode":return t.rhythmMode=Ii.parseEnum(s,e.TabRhythmMode),!0;case"rhythmheight":return t.rhythmHeight=s,!0;case"transpositionpitches":return t.transpositionPitches=s,!0;case"displaytranspositionpitches":return t.displayTranspositionPitches=s,!0;case"smallgracetabnotes":return t.smallGraceTabNotes=s,!0;case"extendbendarrowsontiednotes":return t.extendBendArrowsOnTiedNotes=s,!0;case"extendlineeffectstobeatend":return t.extendLineEffectsToBeatEnd=s,!0;case"slurheight":return t.slurHeight=s,!0}return!1}}class Ji{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.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,i){switch(t){case"encoding":return e.encoding=i,!0;case"mergepartgroupsinmusicxml":return e.mergePartGroupsInMusicXml=i,!0;case"beattextaslyrics":return e.beatTextAsLyrics=i,!0}return!1}}class ji{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.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,i){switch(t){case"notewidelength":return e.noteWideLength=i,!0;case"notewideamplitude":return e.noteWideAmplitude=i,!0;case"noteslightlength":return e.noteSlightLength=i,!0;case"noteslightamplitude":return e.noteSlightAmplitude=i,!0;case"beatwidelength":return e.beatWideLength=i,!0;case"beatwideamplitude":return e.beatWideAmplitude=i,!0;case"beatslightlength":return e.beatSlightLength=i,!0;case"beatslightamplitude":return e.beatSlightAmplitude=i,!0}return!1}}class Qi{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.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,i){switch(t){case"simpleslidepitchoffset":return e.simpleSlidePitchOffset=i,!0;case"simpleslidedurationratio":return e.simpleSlideDurationRatio=i,!0;case"shiftslidedurationratio":return e.shiftSlideDurationRatio=i,!0}return!1}}class $i{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("soundfont",e.soundFont),t.set("outputmode",e.outputMode),t.set("enableplayer",e.enablePlayer),t.set("enablecursor",e.enableCursor),t.set("enableanimatedbeatcursor",e.enableAnimatedBeatCursor),t.set("enableelementhighlighting",e.enableElementHighlighting),t.set("enableuserinteraction",e.enableUserInteraction),t.set("scrolloffsetx",e.scrollOffsetX),t.set("scrolloffsety",e.scrollOffsetY),t.set("scrollmode",e.scrollMode),t.set("scrollspeed",e.scrollSpeed),t.set("nativebrowsersmoothscroll",e.nativeBrowserSmoothScroll),t.set("songbookbendduration",e.songBookBendDuration),t.set("songbookdipduration",e.songBookDipDuration),t.set("vibrato",ji.toJson(e.vibrato)),t.set("slide",Qi.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t.set("buffertimeinmilliseconds",e.bufferTimeInMilliseconds),t}static setProperty(t,i,s){switch(i){case"soundfont":return t.soundFont=s,!0;case"scrollelement":return t.scrollElement=s,!0;case"outputmode":return t.outputMode=Ii.parseEnum(s,e.PlayerOutputMode),!0;case"enableplayer":return t.enablePlayer=s,!0;case"enablecursor":return t.enableCursor=s,!0;case"enableanimatedbeatcursor":return t.enableAnimatedBeatCursor=s,!0;case"enableelementhighlighting":return t.enableElementHighlighting=s,!0;case"enableuserinteraction":return t.enableUserInteraction=s,!0;case"scrolloffsetx":return t.scrollOffsetX=s,!0;case"scrolloffsety":return t.scrollOffsetY=s,!0;case"scrollmode":return t.scrollMode=Ii.parseEnum(s,e.ScrollMode),!0;case"scrollspeed":return t.scrollSpeed=s,!0;case"nativebrowsersmoothscroll":return t.nativeBrowserSmoothScroll=s,!0;case"songbookbendduration":return t.songBookBendDuration=s,!0;case"songbookdipduration":return t.songBookDipDuration=s,!0;case"playtripletfeel":return t.playTripletFeel=s,!0;case"buffertimeinmilliseconds":return t.bufferTimeInMilliseconds=s,!0}if(["vibrato"].indexOf(i)>=0)return ji.fromJson(t.vibrato,s),!0;for(const e of["vibrato"])if(0===i.indexOf(e)&&ji.setProperty(t.vibrato,i.substring(e.length),s))return!0;if(["slide"].indexOf(i)>=0)return Qi.fromJson(t.slide,s),!0;for(const e of["slide"])if(0===i.indexOf(e)&&Qi.setProperty(t.slide,i.substring(e.length),s))return!0;return!1}}class Ki{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("core",Ui.toJson(e.core)),t.set("display",Yi.toJson(e.display)),t.set("notation",qi.toJson(e.notation)),t.set("importer",Ji.toJson(e.importer)),t.set("player",$i.toJson(e.player)),t}static setProperty(e,t,i){if(["core",""].indexOf(t)>=0)return Ui.fromJson(e.core,i),!0;for(const s of["core",""])if(0===t.indexOf(s)&&Ui.setProperty(e.core,t.substring(s.length),i))return!0;if(["display",""].indexOf(t)>=0)return Yi.fromJson(e.display,i),!0;for(const s of["display",""])if(0===t.indexOf(s)&&Yi.setProperty(e.display,t.substring(s.length),i))return!0;if(["notation"].indexOf(t)>=0)return qi.fromJson(e.notation,i),!0;for(const s of["notation"])if(0===t.indexOf(s)&&qi.setProperty(e.notation,t.substring(s.length),i))return!0;if(["importer"].indexOf(t)>=0)return Ji.fromJson(e.importer,i),!0;for(const s of["importer"])if(0===t.indexOf(s)&&Ji.setProperty(e.importer,t.substring(s.length),i))return!0;if(["player"].indexOf(t)>=0)return $i.fromJson(e.player,i),!0;for(const s of["player"])if(0===t.indexOf(s)&&$i.setProperty(e.player,t.substring(s.length),i))return!0;return!1}}class Zi{constructor(){this.core=new Co,this.display=new Gi,this.notation=new X,this.importer=new Vi,this.player=new zi}setSongBookModeSettings(){this.notation.notationMode=e.NotationMode.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=e.FingeringMode.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(v.ParenthesisOnTiedBends,!1),this.notation.elements.set(v.TabNotesOnTiedBends,!1),this.notation.elements.set(v.ZerosOnDiveWhammys,!0)}static get songBook(){let e=new Zi;return e.setSongBookModeSettings(),e}fillFromJson(e){Ki.fromJson(this,e)}}class es{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"marker":return e.marker=i,!0;case"text":return e.text=i,!0}return!1}}class ts{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"islinear":return e.isLinear=i,!0;case"type":return e.type=Ii.parseEnum(i,r),!0;case"value":return e.value=i,!0;case"ratioposition":return e.ratioPosition=i,!0;case"text":return e.text=i,!0}return!1}}class is{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"type":return e.type=Ii.parseEnum(i,Ne),!0;case"length":return e.length=i,!0}return!1}}class ss{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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",es.toJson(e.section)),t.set("tempoautomation",ts.toJson(e.tempoAutomation)),null!==e.fermata){const i=new Map;t.set("fermata",i);for(const[t,s]of e.fermata)i.set(t.toString(),is.toJson(s))}return t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t}static setProperty(e,t,i){switch(t){case"alternateendings":return e.alternateEndings=i,!0;case"keysignature":return e.keySignature=Ii.parseEnum(i,M),!0;case"keysignaturetype":return e.keySignatureType=Ii.parseEnum(i,D),!0;case"isdoublebar":return e.isDoubleBar=i,!0;case"isrepeatstart":return e.isRepeatStart=i,!0;case"repeatcount":return e.repeatCount=i,!0;case"timesignaturenumerator":return e.timeSignatureNumerator=i,!0;case"timesignaturedenominator":return e.timeSignatureDenominator=i,!0;case"timesignaturecommon":return e.timeSignatureCommon=i,!0;case"tripletfeel":return e.tripletFeel=Ii.parseEnum(i,A),!0;case"fermata":return e.fermata=new Map,Ii.forEach(i,((t,i)=>{const s=new ht;is.fromJson(s,t),e.addFermata(parseInt(i),s)})),!0;case"start":return e.start=i,!0;case"isanacrusis":return e.isAnacrusis=i,!0;case"displayscale":return e.displayScale=i,!0;case"displaywidth":return e.displayWidth=i,!0}return["section"].indexOf(t)>=0?(i?(e.section=new ge,es.fromJson(e.section,i)):e.section=null,!0):["tempoautomation"].indexOf(t)>=0&&(i?(e.tempoAutomation=new H,ts.fromJson(e.tempoAutomation,i)):e.tempoAutomation=null,!0)}}class as{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"offset":return e.offset=i,!0;case"value":return e.value=i,!0}return!1}}class rs{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("accentuated",e.accentuated),t.set("bendtype",e.bendType),t.set("bendstyle",e.bendStyle),t.set("iscontinuedbend",e.isContinuedBend),null!==e.bendPoints&&t.set("bendpoints",e.bendPoints?.map((e=>as.toJson(e)))),t.set("fret",e.fret),t.set("string",e.string),t.set("octave",e.octave),t.set("tone",e.tone),t.set("percussionarticulation",e.percussionArticulation),t.set("isvisible",e.isVisible),t.set("islefthandtapped",e.isLeftHandTapped),t.set("ishammerpullorigin",e.isHammerPullOrigin),t.set("isslurdestination",e.isSlurDestination),t.set("harmonictype",e.harmonicType),t.set("harmonicvalue",e.harmonicValue),t.set("isghost",e.isGhost),t.set("isletring",e.isLetRing),t.set("ispalmmute",e.isPalmMute),t.set("isdead",e.isDead),t.set("isstaccato",e.isStaccato),t.set("slideintype",e.slideInType),t.set("slideouttype",e.slideOutType),t.set("vibrato",e.vibrato),t.set("istiedestination",e.isTieDestination),t.set("lefthandfinger",e.leftHandFinger),t.set("righthandfinger",e.rightHandFinger),t.set("isfingering",e.isFingering),t.set("trillvalue",e.trillValue),t.set("trillspeed",e.trillSpeed),t.set("durationpercent",e.durationPercent),t.set("accidentalmode",e.accidentalMode),t.set("dynamics",e.dynamics),e.toJson(t),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"accentuated":return e.accentuated=Ii.parseEnum(i,a),!0;case"bendtype":return e.bendType=Ii.parseEnum(i,c),!0;case"bendstyle":return e.bendStyle=Ii.parseEnum(i,l),!0;case"iscontinuedbend":return e.isContinuedBend=i,!0;case"bendpoints":if(i){e.bendPoints=[];for(const t of i){const i=new U;as.fromJson(i,t),e.addBendPoint(i)}}return!0;case"fret":return e.fret=i,!0;case"string":return e.string=i,!0;case"octave":return e.octave=i,!0;case"tone":return e.tone=i,!0;case"percussionarticulation":return e.percussionArticulation=i,!0;case"isvisible":return e.isVisible=i,!0;case"islefthandtapped":return e.isLeftHandTapped=i,!0;case"ishammerpullorigin":return e.isHammerPullOrigin=i,!0;case"isslurdestination":return e.isSlurDestination=i,!0;case"harmonictype":return e.harmonicType=Ii.parseEnum(i,y),!0;case"harmonicvalue":return e.harmonicValue=i,!0;case"isghost":return e.isGhost=i,!0;case"isletring":return e.isLetRing=i,!0;case"ispalmmute":return e.isPalmMute=i,!0;case"isdead":return e.isDead=i,!0;case"isstaccato":return e.isStaccato=i,!0;case"slideintype":return e.slideInType=Ii.parseEnum(i,S),!0;case"slideouttype":return e.slideOutType=Ii.parseEnum(i,w),!0;case"vibrato":return e.vibrato=Ii.parseEnum(i,_),!0;case"istiedestination":return e.isTieDestination=i,!0;case"lefthandfinger":return e.leftHandFinger=Ii.parseEnum(i,m),!0;case"righthandfinger":return e.rightHandFinger=Ii.parseEnum(i,m),!0;case"isfingering":return e.isFingering=i,!0;case"trillvalue":return e.trillValue=i,!0;case"trillspeed":return e.trillSpeed=Ii.parseEnum(i,p),!0;case"durationpercent":return e.durationPercent=i,!0;case"accidentalmode":return e.accidentalMode=Ii.parseEnum(i,b),!0;case"dynamics":return e.dynamics=Ii.parseEnum(i,g),!0}return e.setProperty(t,i)}}class ns{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("notes",e.notes.map((e=>rs.toJson(e)))),t.set("isempty",e.isEmpty),t.set("whammystyle",e.whammyStyle),t.set("ottava",e.ottava),t.set("islegatoorigin",e.isLegatoOrigin),t.set("duration",e.duration),t.set("automations",e.automations.map((e=>ts.toJson(e)))),t.set("dots",e.dots),t.set("fadein",e.fadeIn),t.set("lyrics",e.lyrics),t.set("hasrasgueado",e.hasRasgueado),t.set("pop",e.pop),t.set("slap",e.slap),t.set("tap",e.tap),t.set("text",e.text),t.set("brushtype",e.brushType),t.set("brushduration",e.brushDuration),t.set("tupletdenominator",e.tupletDenominator),t.set("tupletnumerator",e.tupletNumerator),t.set("iscontinuedwhammy",e.isContinuedWhammy),t.set("whammybartype",e.whammyBarType),null!==e.whammyBarPoints&&t.set("whammybarpoints",e.whammyBarPoints?.map((e=>as.toJson(e)))),t.set("vibrato",e.vibrato),t.set("chordid",e.chordId),t.set("gracetype",e.graceType),t.set("pickstroke",e.pickStroke),t.set("tremolospeed",e.tremoloSpeed),t.set("crescendo",e.crescendo),t.set("displaystart",e.displayStart),t.set("playbackstart",e.playbackStart),t.set("displayduration",e.displayDuration),t.set("playbackduration",e.playbackDuration),t.set("dynamics",e.dynamics),t.set("invertbeamdirection",e.invertBeamDirection),t.set("preferredbeamdirection",e.preferredBeamDirection),t.set("beamingmode",e.beamingMode),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"notes":e.notes=[];for(const t of i){const i=new ee;rs.fromJson(i,t),e.addNote(i)}return!0;case"isempty":return e.isEmpty=i,!0;case"whammystyle":return e.whammyStyle=Ii.parseEnum(i,l),!0;case"ottava":return e.ottava=Ii.parseEnum(i,o),!0;case"islegatoorigin":return e.isLegatoOrigin=i,!0;case"duration":return e.duration=Ii.parseEnum(i,p),!0;case"automations":e.automations=[];for(const t of i){const i=new H;ts.fromJson(i,t),e.automations.push(i)}return!0;case"dots":return e.dots=i,!0;case"fadein":return e.fadeIn=i,!0;case"lyrics":return e.lyrics=i,!0;case"hasrasgueado":return e.hasRasgueado=i,!0;case"pop":return e.pop=i,!0;case"slap":return e.slap=i,!0;case"tap":return e.tap=i,!0;case"text":return e.text=i,!0;case"brushtype":return e.brushType=Ii.parseEnum(i,d),!0;case"brushduration":return e.brushDuration=i,!0;case"tupletdenominator":return e.tupletDenominator=i,!0;case"tupletnumerator":return e.tupletNumerator=i,!0;case"iscontinuedwhammy":return e.isContinuedWhammy=i,!0;case"whammybartype":return e.whammyBarType=Ii.parseEnum(i,F),!0;case"whammybarpoints":if(i){e.whammyBarPoints=[];for(const t of i){const i=new U;as.fromJson(i,t),e.addWhammyBarPoint(i)}}return!0;case"vibrato":return e.vibrato=Ii.parseEnum(i,_),!0;case"chordid":return e.chordId=i,!0;case"gracetype":return e.graceType=Ii.parseEnum(i,f),!0;case"pickstroke":return e.pickStroke=Ii.parseEnum(i,N),!0;case"tremolospeed":return e.tremoloSpeed=Ii.parseEnum(i,p),!0;case"crescendo":return e.crescendo=Ii.parseEnum(i,u),!0;case"displaystart":return e.displayStart=i,!0;case"playbackstart":return e.playbackStart=i,!0;case"displayduration":return e.displayDuration=i,!0;case"playbackduration":return e.playbackDuration=i,!0;case"dynamics":return e.dynamics=Ii.parseEnum(i,g),!0;case"invertbeamdirection":return e.invertBeamDirection=i,!0;case"preferredbeamdirection":return e.preferredBeamDirection=Ii.parseEnum(i,Ce),!0;case"beamingmode":return e.beamingMode=Ii.parseEnum(i,L),!0}return!1}}class os{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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=>ns.toJson(e)))),t.set("isempty",e.isEmpty),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"beats":e.beats=[];for(const t of i){const i=new oe;ns.fromJson(i,t),e.addBeat(i)}return!0;case"isempty":return e.isEmpty=i,!0}return!1}}class hs{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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=>os.toJson(e)))),t.set("similemark",e.simileMark),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"clef":return e.clef=Ii.parseEnum(i,n),!0;case"clefottava":return e.clefOttava=Ii.parseEnum(i,o),!0;case"voices":e.voices=[];for(const t of i){const i=new _e;os.fromJson(i,t),e.addVoice(i)}return!0;case"similemark":return e.simileMark=Ii.parseEnum(i,h),!0;case"displayscale":return e.displayScale=i,!0;case"displaywidth":return e.displayWidth=i,!0}return!1}}class ls{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"name":return e.name=i,!0;case"firstfret":return e.firstFret=i,!0;case"strings":return e.strings=i,!0;case"barrefrets":return e.barreFrets=i,!0;case"showname":return e.showName=i,!0;case"showdiagram":return e.showDiagram=i,!0;case"showfingering":return e.showFingering=i,!0}return!1}}class cs{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"isstandard":return e.isStandard=i,!0;case"name":return e.name=i,!0;case"tunings":return e.tunings=i,!0}return!1}}class ds{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("bars",e.bars.map((e=>hs.toJson(e)))),null!==e.chords){const i=new Map;t.set("chords",i);for(const[t,s]of e.chords)i.set(t.toString(),ls.toJson(s))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",cs.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,i){switch(t){case"bars":e.bars=[];for(const t of i){const i=new W;hs.fromJson(i,t),e.addBar(i)}return!0;case"chords":return e.chords=new Map,Ii.forEach(i,((t,i)=>{const s=new he;ls.fromJson(s,t),e.addChord(i,s)})),!0;case"capo":return e.capo=i,!0;case"transpositionpitch":return e.transpositionPitch=i,!0;case"displaytranspositionpitch":return e.displayTranspositionPitch=i,!0;case"showtablature":return e.showTablature=i,!0;case"showstandardnotation":return e.showStandardNotation=i,!0;case"ispercussion":return e.isPercussion=i,!0;case"standardnotationlinecount":return e.standardNotationLineCount=i,!0}return["stringtuning"].indexOf(t)>=0&&(cs.fromJson(e.stringTuning,i),!0)}}class us{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"volume":return e.volume=i,!0;case"balance":return e.balance=i,!0;case"port":return e.port=i,!0;case"program":return e.program=i,!0;case"primarychannel":return e.primaryChannel=i,!0;case"secondarychannel":return e.secondaryChannel=i,!0;case"ismute":return e.isMute=i,!0;case"issolo":return e.isSolo=i,!0}return!1}}class ps{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"elementtype":return e.elementType=i,!0;case"staffline":return e.staffLine=i,!0;case"noteheaddefault":return e.noteHeadDefault=Ii.parseEnum(i,P),!0;case"noteheadhalf":return e.noteHeadHalf=Ii.parseEnum(i,P),!0;case"noteheadwhole":return e.noteHeadWhole=Ii.parseEnum(i,P),!0;case"techniquesymbol":return e.techniqueSymbol=Ii.parseEnum(i,P),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=Ii.parseEnum(i,C),!0;case"outputmidinumber":return e.outputMidiNumber=i,!0}return!1}}class gs{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("staves",e.staves.map((e=>ds.toJson(e)))),t.set("playbackinfo",us.toJson(e.playbackInfo)),t.set("color",me.toJson(e.color)),t.set("name",e.name),t.set("shortname",e.shortName),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("percussionarticulations",e.percussionArticulations.map((e=>ps.toJson(e)))),t}static setProperty(e,t,i){switch(t){case"staves":e.staves=[];for(const t of i){const i=new Se;ds.fromJson(i,t),e.addStaff(i)}return!0;case"color":return e.color=me.fromJson(i),!0;case"name":return e.name=i,!0;case"shortname":return e.shortName=i,!0;case"defaultsystemslayout":return e.defaultSystemsLayout=i,!0;case"systemslayout":return e.systemsLayout=i,!0;case"percussionarticulations":e.percussionArticulations=[];for(const t of i){const i=new $;ps.fromJson(i,t),e.percussionArticulations.push(i)}return!0}return["playbackinfo"].indexOf(t)>=0&&(us.fromJson(e.playbackInfo,i),!0)}}class fs{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("hidedynamics",e.hideDynamics),t}static setProperty(e,t,i){return"hidedynamics"===t&&(e.hideDynamics=i,!0)}}class ms{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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=>ss.toJson(e)))),t.set("tracks",e.tracks.map((e=>gs.toJson(e)))),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("stylesheet",fs.toJson(e.stylesheet)),t}static setProperty(e,t,i){switch(t){case"album":return e.album=i,!0;case"artist":return e.artist=i,!0;case"copyright":return e.copyright=i,!0;case"instructions":return e.instructions=i,!0;case"music":return e.music=i,!0;case"notices":return e.notices=i,!0;case"subtitle":return e.subTitle=i,!0;case"title":return e.title=i,!0;case"words":return e.words=i,!0;case"tab":return e.tab=i,!0;case"tempo":return e.tempo=i,!0;case"tempolabel":return e.tempoLabel=i,!0;case"masterbars":e.masterBars=[];for(const t of i){const i=new ce;ss.fromJson(i,t),e.addMasterBar(i)}return!0;case"tracks":e.tracks=[];for(const t of i){const i=new we;gs.fromJson(i,t),e.addTrack(i)}return!0;case"defaultsystemslayout":return e.defaultSystemsLayout=i,!0;case"systemslayout":return e.systemsLayout=i,!0}return["stylesheet"].indexOf(t)>=0&&(fs.fromJson(e.stylesheet,i),!0)}}class ys{static jsonReplacer(e,t){if(t instanceof Map){if("fromEntries"in Object)return Object.fromEntries(t);{const e={};for(const[i,s]of t)e[i]=s;return e}}return ArrayBuffer.isView(t)?Array.apply([],[t]):t}static scoreToJson(e){let t=ys.scoreToJsObject(e);return JSON.stringify(t,ys.jsonReplacer)}static jsonToScore(e,t){return ys.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return ms.toJson(e)}static jsObjectToScore(e,t){let i=new pe;return ms.fromJson(i,e),i.finish(t??new Zi),i}static settingsToJson(e){let t=ys.settingsToJsObject(e);return JSON.stringify(t,ys.jsonReplacer)}static jsonToSettings(e){return ys.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return Ki.toJson(e)}static jsObjectToSettings(e){let t=new Zi;return Ki.fromJson(t,e),t}static jsObjectToMidiFile(e){let t=new Rt;return Ii.forEach(e,((e,i)=>{switch(i){case"division":t.division=e;break;case"tracks":for(let i of e){let e=ys.jsObjectToMidiTrack(i);t.tracks.push(e)}}})),t}static jsObjectToMidiTrack(e){let t=new At;return Ii.forEach(e,((e,i)=>{if("events"===i)for(let i of e){let e=ys.jsObjectToMidiEvent(i);t.events.push(e)}})),t}static jsObjectToMidiEvent(t){let i=Ii.getValue(t,"track"),s=Ii.getValue(t,"tick"),a=Ii.getValue(t,"type");switch(a){case Me.TimeSignature:return new Gt(i,s,Ii.getValue(t,"numerator"),Ii.getValue(t,"denominatorIndex"),Ii.getValue(t,"midiClocksPerMetronomeClick"),Ii.getValue(t,"thirdySecondNodesInQuarter"));case Me.AlphaTabRest:return new Wt(i,s,Ii.getValue(t,"channel"));case Me.AlphaTabMetronome:return new Ht(i,s,Ii.getValue(t,"metronomeNumerator"),Ii.getValue(t,"metronomeDurationInTicks"),Ii.getValue(t,"metronomeDurationInMilliseconds"));case Me.NoteOn:return new Ut(i,s,Ii.getValue(t,"channel"),Ii.getValue(t,"noteKey"),Ii.getValue(t,"noteVelocity"));case Me.NoteOff:return new Xt(i,s,Ii.getValue(t,"channel"),Ii.getValue(t,"noteKey"),Ii.getValue(t,"noteVelocity"));case Me.ControlChange:return new Yt(i,s,Ii.getValue(t,"channel"),Ii.getValue(t,"controller"),Ii.getValue(t,"value"));case Me.ProgramChange:return new qt(i,s,Ii.getValue(t,"channel"),Ii.getValue(t,"program"));case Me.TempoChange:return new Jt(s,Ii.getValue(t,"microSecondsPerQuarterNote"));case Me.PitchBend:return new jt(i,s,Ii.getValue(t,"channel"),Ii.getValue(t,"value"));case Me.PerNotePitchBend:return new Qt(i,s,Ii.getValue(t,"channel"),Ii.getValue(t,"noteKey"),Ii.getValue(t,"value"));case Me.EndOfTrack:return new $t(i,s)}throw new G(e.AlphaTabErrorType.Format,"Unknown Midi Event type: "+a)}static midiFileToJsObject(e){const t=new Map;t.set("division",e.division);const i=[];for(let t of e.tracks)i.push(ys.midiTrackToJsObject(t));return t.set("tracks",i),t}static midiTrackToJsObject(e){const t=new Map,i=[];for(let t of e.events)i.push(ys.midiEventToJsObject(t));return t.set("events",i),t}static midiEventToJsObject(e){const t=new Map;switch(t.set("track",e.track),t.set("tick",e.tick),t.set("type",e.type),e.type){case Me.TimeSignature:t.set("numerator",e.numerator),t.set("denominatorIndex",e.denominatorIndex),t.set("midiClocksPerMetronomeClick",e.midiClocksPerMetronomeClick),t.set("thirdySecondNodesInQuarter",e.thirtySecondNodesInQuarter);break;case Me.AlphaTabRest:t.set("channel",e.channel);break;case Me.AlphaTabMetronome:t.set("metronomeNumerator",e.metronomeNumerator),t.set("metronomeDurationInMilliseconds",e.metronomeDurationInMilliseconds),t.set("metronomeDurationInTicks",e.metronomeDurationInTicks);break;case Me.NoteOn:case Me.NoteOff:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("noteVelocity",e.noteVelocity);break;case Me.ControlChange:t.set("channel",e.channel),t.set("controller",e.controller),t.set("value",e.value);break;case Me.ProgramChange:t.set("channel",e.channel),t.set("program",e.program);break;case Me.TempoChange:t.set("microSecondsPerQuarterNote",e.microSecondsPerQuarterNote);break;case Me.PitchBend:t.set("channel",e.channel),t.set("value",e.value);break;case Me.PerNotePitchBend:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("value",e.value);case Me.EndOfTrack:}return t}}class bs{constructor(){this.ready=new Ei,this.samplesPlayed=new Ci,this.sampleRequest=new Ei}get sampleRate(){return bs.preferredSampleRate}open(){J.debug("AlphaSynth","Initializing synth worker"),this._worker=Eo.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 bs.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case bs.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(){}}bs.CmdOutputPrefix="alphaSynth.output.",bs.CmdOutputAddSamples=bs.CmdOutputPrefix+"addSamples",bs.CmdOutputPlay=bs.CmdOutputPrefix+"play",bs.CmdOutputPause=bs.CmdOutputPrefix+"pause",bs.CmdOutputResetSamples=bs.CmdOutputPrefix+"resetSamples",bs.CmdOutputSampleRequest=bs.CmdOutputPrefix+"sampleRequest",bs.CmdOutputSamplesPlayed=bs.CmdOutputPrefix+"samplesPlayed",bs.preferredSampleRate=0;class Ss{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new Mi(new bs,t),this._player.positionChanged.on(this.onPositionChanged.bind(this)),this._player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this._player.finished.on(this.onFinished.bind(this)),this._player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this._player.soundFontLoadFailed.on(this.onSoundFontLoadFailed.bind(this)),this._player.soundFontLoadFailed.on(this.onSoundFontLoadFailed.bind(this)),this._player.midiLoaded.on(this.onMidiLoaded.bind(this)),this._player.midiLoadFailed.on(this.onMidiLoadFailed.bind(this)),this._player.readyForPlayback.on(this.onReadyForPlayback.bind(this)),this._player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this._player.playbackRangeChanged.on(this.onPlaybackRangeChanged.bind(this)),this._main.postMessage({cmd:"alphaSynth.ready"})}static init(){let e=Eo.globalThis;e.addEventListener("message",(t=>{let i=t.data;if("alphaSynth.initialize"===i.cmd)bs.preferredSampleRate=i.sampleRate,J.logLevel=i.logLevel,Eo.globalThis.alphaSynthWebWorker=new Ss(e,i.bufferTimeInMilliseconds)}))}handleMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":J.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(ys.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(ys.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);break;case"alphaSynth.setChannelSolo":this._player.setChannelSolo(t.channel,t.solo);break;case"alphaSynth.setChannelVolume":this._player.setChannelVolume(t.channel,t.volume);break;case"alphaSynth.resetChannelStates":this._player.resetChannelStates();break;case"alphaSynth.destroy":this._player.destroy(),this._main.postMessage({cmd:"alphaSynth.destroyed"});break;case"alphaSynth.applyTranspositionPitches":this._player.applyTranspositionPitches(new Map(JSON.parse(t.transpositionPitches)))}}onPositionChanged(e){this._main.postMessage({cmd:"alphaSynth.positionChanged",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onPlayerStateChanged(e){this._main.postMessage({cmd:"alphaSynth.playerStateChanged",state:e.state,stopped:e.stopped})}onFinished(){this._main.postMessage({cmd:"alphaSynth.finished"})}onSoundFontLoaded(){this._main.postMessage({cmd:"alphaSynth.soundFontLoaded"})}onSoundFontLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.soundFontLoadFailed",error:this.serializeException(e)})}serializeException(e){let t=JSON.parse(JSON.stringify(e));return e.message&&(t.message=e.message),e.stack&&(t.stack=e.stack),e.constructor&&e.constructor.name&&(t.type=e.constructor.name),t}onMidiLoaded(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onMidiLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",error:this.serializeException(e)})}onReadyForPlayback(){this._main.postMessage({cmd:"alphaSynth.readyForPlayback"})}onMidiEventsPlayed(e){this._main.postMessage({cmd:"alphaSynth.midiEventsPlayed",events:e.events.map(ys.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}class ws{static generateFontLookup(e){if(!ws.FontSizeLookupTables.has(e))if(Eo.isRunningInWorker)ws.FontSizeLookupTables.set(e,new Uint8Array([8]));else{let t=document.createElement("canvas").getContext("2d");t.font=`11px ${e}`;let i=[];for(let e=32;e<255;e++){let s=String.fromCharCode(e);i.push(t.measureText(s).width)}let s=new Uint8Array(i);ws.FontSizeLookupTables.set(e,s)}}static measureString(e,t,i,s,a){let r,n=t[0];for(let e=0;e<t.length;e++)if(ws.FontSizeLookupTables.has(t[e])){n=t[e];break}ws.FontSizeLookupTables.has(n)||ws.generateFontLookup(n),r=ws.FontSizeLookupTables.get(n);let o=1;s===Ve.Italic&&(o*=1.2),a===He.Bold&&(o*=1.2);let h=0;for(let t=0;t<e.length;t++){let s=Math.min(r.length-1,e.charCodeAt(t)-32);s>=0&&(h+=r[s]*i/11)}return h*o}}ws.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]),ws.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]),ws.FontSizeLookupTables=new Map([["Arial",ws.Arial],["'Arial'",ws.Arial],['"Arial"',ws.Arial],["Georgia",ws.Georgia],["'Georgia'",ws.Georgia],['"Georgia"',ws.Georgia]]),ws.ControlChars=32;class _s{constructor(){this.id=Q.newGuid(),this.x=0,this.y=0,this.width=0,this.height=0,this.totalWidth=0,this.totalHeight=0,this.firstMasterBarIndex=-1,this.lastMasterBarIndex=-1,this.renderResult=null}}class Bs{constructor(){this.beats=[]}addBeat(e){e.barBounds=this,this.beats.push(e),this.masterBarBounds.addBeat(e)}findBeatAtPos(e){let t=null;for(let i of this.beats)if(!t||i.realBounds.x<e)t=i;else if(i.realBounds.x>e)break;return t}finish(){this.beats.sort(((e,t)=>e.realBounds.x-t.realBounds.x))}}class Ts{constructor(){this.notes=null}addNote(e){this.notes||(this.notes=[]),e.beatBounds=this,this.notes.push(e)}findNoteAtPos(e,t){const i=this.notes;if(!i)return null;for(let s of i){let i=s.noteHeadBounds.y+s.noteHeadBounds.h,a=s.noteHeadBounds.x+s.noteHeadBounds.w;if(s.noteHeadBounds.x<=e&&s.noteHeadBounds.y<=t&&e<=a&&t<=i)return s.note}return null}}class ks{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 i=null;for(let t of this.bars){let s=t.findBeatAtPos(e);if(s&&(!i||i.realBounds.x<s.realBounds.x)){const t=Math.abs(s.realBounds.x-e);(!i||t<1e7)&&(i=s)}}return i?i.beat:null}finish(){this.bars.sort(((e,t)=>e.realBounds.y<t.realBounds.y?-1:e.realBounds.y>t.realBounds.y?1:e.realBounds.x<t.realBounds.x?-1:e.realBounds.x>t.realBounds.x?1:0));for(const e of this.bars)e.finish()}addBeat(e){this.staveGroupBounds.boundsLookup.addBeat(e)}}class vs{}class xs{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 i of this.bars)if(!t||i.realBounds.x<e)t=i;else if(e>i.realBounds.x+i.realBounds.w)break;return t}}class Ns{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 i={};i.visualBounds=this.boundsToJson(e.visualBounds),i.realBounds=this.boundsToJson(e.realBounds),i.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 i of t.bars){let t={};t.visualBounds=this.boundsToJson(i.visualBounds),t.realBounds=this.boundsToJson(i.realBounds),t.beats=[];for(let e of i.beats){let i={};i.visualBounds=this.boundsToJson(e.visualBounds),i.realBounds=this.boundsToJson(e.realBounds);let s=i;if(s.beatIndex=e.beat.index,s.voiceIndex=e.beat.voice.index,s.barIndex=e.beat.voice.bar.index,s.staffIndex=e.beat.voice.bar.staff.index,s.trackIndex=e.beat.voice.bar.staff.track.index,e.notes){let t=i.notes=[];for(let i of e.notes){let e={};e.index=i.note.index,e.noteHeadBounds=this.boundsToJson(i.noteHeadBounds),t.push(e)}}t.beats.push(i)}e.bars.push(t)}i.bars.push(e)}t.push(i)}return e}static fromJson(e,t){let i=new Ns,s=e.staveGroups;for(let e of s){let s=new xs;s.visualBounds=e.visualBounds,s.realBounds=e.realBounds,i.addStaveGroup(s);for(let i of e.bars){let e=new ks;e.index=i.index,e.isFirstOfLine=i.isFirstOfLine,e.lineAlignedBounds=i.lineAlignedBounds,e.visualBounds=i.visualBounds,e.realBounds=i.realBounds,s.addBar(e);for(let s of i.bars){let i=new Bs;i.visualBounds=s.visualBounds,i.realBounds=s.realBounds,e.addBar(i);for(let e of s.beats){let s=new Ts;s.visualBounds=e.visualBounds,s.realBounds=e.realBounds;let a=e;if(s.beat=t.tracks[a.trackIndex].staves[a.staffIndex].bars[a.barIndex].voices[a.voiceIndex].beats[a.beatIndex],e.notes){s.notes=[];for(let t of e.notes){let e=new vs,i=t;e.note=s.beat.notes[i.index],e.noteHeadBounds=t.noteHeadBounds,s.addNote(e)}}i.addBeat(s)}}}}return i}boundsToJson(e){let t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(){for(let e of this.staveGroups)e.finish();this.isFinished=!0}addStaveGroup(e){e.index=this.staveGroups.length,e.boundsLookup=this,this.staveGroups.push(e),this._currentStaveGroup=e}addMasterBar(e){e.staveGroupBounds?this._masterBarLookup.set(e.index,e):(e.staveGroupBounds=this._currentStaveGroup,this._masterBarLookup.set(e.index,e),this._currentStaveGroup.addBar(e))}addBeat(e){this._beatLookup.has(e.beat.id)||this._beatLookup.set(e.beat.id,[]),this._beatLookup.get(e.beat.id)?.push(e)}findMasterBarByIndex(e){return this._masterBarLookup.has(e)?this._masterBarLookup.get(e):null}findMasterBar(e){let t=e.index;return this._masterBarLookup.has(t)?this._masterBarLookup.get(t):null}findBeat(e){const t=this.findBeats(e);return t?t[0]:null}findBeats(e){let t=e.id;return this._beatLookup.has(t)?this._beatLookup.get(t):null}getBeatAtPos(e,t){let i=0,s=this.staveGroups.length-1,a=-1;for(;i<=s;){let e=(s+i)/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?s=e-1:i=e+1}if(-1===a)return null;let r=this.staveGroups[a].findBarAtPos(e);return r?r.findBeatAtPos(e,t):null}getNoteAtPos(e,t,i){const s=this.findBeats(e);if(s)for(const e of s){const s=e.findNoteAtPos(t,i);if(s)return s}return null}}class Ps{constructor(t){this._currentLayoutMode=e.LayoutMode.Page,this._currentRenderEngine=null,this._renderedTracks=null,this.canvas=null,this.score=null,this.tracks=null,this.layout=null,this.boundsLookup=null,this.width=0,this.preRender=new Ci,this.renderFinished=new Ci,this.partialRenderFinished=new Ci,this.partialLayoutFinished=new Ci,this.postRenderFinished=new Ei,this.error=new Ci,this.settings=t,this.recreateCanvas(),this.recreateLayout()}destroy(){this.score=null,this.canvas?.destroy(),this.canvas=null,this.layout=null,this.boundsLookup=null,this.tracks=null}recreateCanvas(){return this._currentRenderEngine!==this.settings.core.engine&&(this.canvas?.destroy(),this.canvas=Eo.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=Eo.getLayoutEngineFactory(this.settings.display.layoutMode).createLayout(this),this._currentLayoutMode=this.settings.display.layoutMode,!0)}renderScore(e,t){try{this.score=e;let i=null;if(null!=e&&null!=t){if(t){i=[];for(let s of t)s>=0&&s<e.tracks.length&&i.push(e.tracks[s])}else i=e.tracks.slice(0);0===i.length&&e.tracks.length>0&&i.push(e.tracks[0])}this.tracks=i,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?(J.debug("Rendering","Request render of lazy partial "+e),t.renderLazyPartial(e)):J.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 Ns,this.recreateCanvas(),this.canvas.lineWidth=this.settings.display.scale,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){J.debug("Rendering","Rendering "+this.tracks.length+" tracks");for(let e=0;e<this.tracks.length;e++){let t=this.tracks[e];J.debug("Rendering","Track "+e+": "+t.name)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),J.debug("Rendering","Rendering finished")}else J.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),J.debug("Rendering","Clearing finished");else J.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(J.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(J.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new Ns,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):J.debug("Rendering","Current layout does not support dynamic resizing, nothing was done",null),J.debug("Rendering","Resize finished")}layoutAndRender(){J.debug("Rendering","Rendering at scale "+this.settings.display.scale+" with layout "+this.layout.name,null),this.layout.layoutAndRender(),this._renderedTracks=this.tracks,this.onRenderFinished(),this.postRenderFinished.trigger()}onRenderFinished(){this.boundsLookup?.finish();const e=new _s;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}class Es{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){Eo.globalThis.alphaTabWebWorker=new Es(Eo.globalThis)}handleMessage(e){let t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":let e=ys.jsObjectToSettings(t.settings);J.logLevel=e.core.logLevel,this._renderer=new Ps(e),this._renderer.partialRenderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialRenderFinished",result:e})})),this._renderer.partialLayoutFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialLayoutFinished",result:e})})),this._renderer.renderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.renderFinished",result:e})})),this._renderer.postRenderFinished.on((()=>{this._main.postMessage({cmd:"alphaTab.postRenderFinished",boundsLookup:this._renderer.boundsLookup?.toJson()??null})})),this._renderer.preRender.on((e=>{this._main.postMessage({cmd:"alphaTab.preRender",resize:e})})),this._renderer.error.on(this.error.bind(this));break;case"alphaTab.invalidate":this._renderer.render();break;case"alphaTab.resizeRender":this._renderer.resizeRender();break;case"alphaTab.renderResult":this._renderer.renderResult(t.resultId);break;case"alphaTab.setWidth":this._renderer.width=t.width;break;case"alphaTab.renderScore":this.updateFontSizes(t.fontSizes);let i=null==t.score?null:ys.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(i,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(e){ws.FontSizeLookupTables||(ws.FontSizeLookupTables=new Map);for(let t in e)ws.FontSizeLookupTables.set(t,e[t])}}updateSettings(e){Ki.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){J.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class Cs{constructor(){this._canvas=null,this._color=new me(0,0,0,255),this._font=new Ri("Arial",10,Ve.Plain),this._lineWidth=0;let e=document.createElement("span");e.classList.add("at"),document.body.appendChild(e);let t=window.getComputedStyle(e),i=t.fontFamily;(i.startsWith('"')||i.startsWith("'"))&&(i=i.substr(1,i.length-2)),this._musicFont=new Ri(i,parseFloat(t.fontSize),Ve.Plain),this._measureCanvas=document.createElement("canvas"),this._measureCanvas.width=10,this._measureCanvas.height=10,this._measureCanvas.style.width="10px",this._measureCanvas.style.height="10px",this._measureContext=this._measureCanvas.getContext("2d"),this._measureContext.textBaseline="hanging"}destroy(){}onRenderFinished(){return null}beginRender(e,t){this._canvas=document.createElement("canvas"),this._canvas.width=e*Eo.HighDpiFactor|0,this._canvas.height=t*Eo.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(Eo.HighDpiFactor,Eo.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,i,s){i>0&&this._context.fillRect(0|e,0|t,i,s)}strokeRect(e,t,i,s){this._context.strokeRect(0|e,0|t,i,s)}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,i,s){this._context.quadraticCurveTo(e,t,i,s)}bezierCurveTo(e,t,i,s,a,r){this._context.bezierCurveTo(e,t,i,s,a,r)}fillCircle(e,t,i){this._context.beginPath(),this._context.arc(e,t,i,0,2*Math.PI,!0),this.fill()}strokeCircle(e,t,i){this._context.beginPath(),this._context.arc(e,t,i,0,2*Math.PI,!0),this.stroke()}fill(){this._context.fill(),this._context.beginPath()}stroke(){this._context.stroke(),this._context.beginPath()}get font(){return this._font}set font(e){this._font=e,this._context&&(this._context.font=e.toCssString(this.settings.display.scale)),this._measureContext.font=e.toCssString(this.settings.display.scale)}get textAlign(){switch(this._context.textAlign){case"left":default:return E.Left;case"center":return E.Center;case"right":return E.Right}}set textAlign(e){switch(e){case E.Left:this._context.textAlign="left";break;case E.Center:this._context.textAlign="center";break;case E.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return C.Top;case"middle":return C.Middle;case"bottom":return C.Bottom}}set textBaseline(e){switch(e){case C.Top:this._context.textBaseline="hanging";break;case C.Middle:this._context.textBaseline="middle";break;case C.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,i){this._context.fillText(e,t,i)}measureText(e){return this._measureContext.measureText(e).width}fillMusicFontSymbol(e,t,i,s,a=!1){s!==P.None&&this.fillMusicFontSymbolText(e,t,i,String.fromCharCode(s),a)}fillMusicFontSymbols(e,t,i,s,a=!1){let r="";for(let e of s)e!==P.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,i,r,a)}fillMusicFontSymbolText(e,t,i,s,a=!1){let r=this._context.textAlign,n=this._context.textBaseline,o=this._context.font;this._context.font=this._musicFont.toCssString(i),this._context.textBaseline="middle",this._context.textAlign=a?"center":"left",this._context.fillText(s,e,t),this._context.textBaseline=n,this._context.font=o,this._context.textAlign=r}beginRotate(e,t,i){this._context.save(),this._context.translate(e,t),this._context.rotate(i*Math.PI/180)}endRotate(){this._context.restore()}}class Fs{constructor(e,t=!1){this._midiFile=e,this._smf1Mode=t}addTimeSignature(e,t,i){let s=0,a=i;for(;a>>=1,a>0;)s++;this._midiFile.addEvent(new Gt(0,e,t,s,48,8))}addRest(e,t,i){this._smf1Mode||this._midiFile.addEvent(new Wt(e,t,i))}addNote(e,t,i,s,a,r){this._midiFile.addEvent(new Ut(e,t,r,Fs.fixValue(s),Fs.fixValue(a))),this._midiFile.addEvent(new Xt(e,t+i,r,Fs.fixValue(s),Fs.fixValue(a)))}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,i,s,a){this._midiFile.addEvent(new Yt(e,t,i,s,Fs.fixValue(a)))}addProgramChange(e,t,i,s){this._midiFile.addEvent(new qt(e,t,i,s))}addTempo(e,t){const i=6e7/t|0;this._midiFile.addEvent(new Jt(e,i))}addBend(e,t,i,s){s=s>=Zt.MaxPitchWheel?Zt.MaxPitchWheel:Math.floor(s),this._midiFile.addEvent(new jt(e,t,i,s))}addNoteBend(e,t,i,s,a){this._smf1Mode?this.addBend(e,t,i,a):(a=a*Zt.MaxPitchWheel20/Zt.MaxPitchWheel,this._midiFile.addEvent(new Qt(e,t,i,s,a)))}finishTrack(e,t){this._midiFile.format!=Le.MultiTrack&&0!=e||this._midiFile.addEvent(new $t(e,t))}}class Ls{constructor(e,t){this.closingIndex=0,this.group=e,this.opening=t,e.closings=e.closings.sort(((e,t)=>e.index-t.index)),this.iterations=e.closings.map((e=>0))}}class Ms{get finished(){return this.index>=this._score.masterBars.length}constructor(e){this._repeatStack=[],this._groupsOnStack=new Set,this._previousAlternateEndings=0,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}processCurrent(){const e=this._score.masterBars[this.index];let t=e.alternateEndings;if(0===t&&(t=this._previousAlternateEndings),e===e.repeatGroup.opening&&e.repeatGroup.isClosed&&!this._groupsOnStack.has(e.repeatGroup)){const i=new Ls(e.repeatGroup,e);this._repeatStack.push(i),this._groupsOnStack.add(e.repeatGroup),this._previousAlternateEndings=0,t=e.alternateEndings}if(0===this._repeatStack.length||0===t)this.shouldPlay=!0;else{const e=this._repeatStack[this._repeatStack.length-1],i=e.iterations[e.closingIndex];this._previousAlternateEndings=t,this.shouldPlay=!!(t&1<<i)}this.shouldPlay&&(this.currentTick+=e.calculateDuration())}moveNext(){const e=this._score.masterBars[this.index].repeatCount-1;if(this._repeatStack.length>0&&e>0){const t=this._repeatStack[this._repeatStack.length-1];if(t.iterations[t.closingIndex]<e){this.index=t.opening.index,t.iterations[t.closingIndex]++;for(let e=0;e<t.closingIndex;e++)t.iterations[e]=0;t.closingIndex=0,this._previousAlternateEndings=0}else t.closingIndex<t.group.closings.length-1?(t.closingIndex++,this.index++):(this._repeatStack.pop(),this._groupsOnStack.delete(t.group),this.index++)}else this.index++}}class Is{constructor(e,t){this.beat=e,this.playbackStart=t}}class Ds{get duration(){return this.end-this.start}constructor(e,t){this._highlightedBeats=new Map,this.highlightedBeats=[],this.nextBeat=null,this.previousBeat=null,this.start=e,this.end=t}highlightBeat(e,t){e.isEmpty&&!e.voice.isEmpty||this._highlightedBeats.has(e.id)||(this._highlightedBeats.set(e.id,!0),this.highlightedBeats.push(new Is(e,t)))}getVisibleBeatAtStart(e){for(const t of this.highlightedBeats)if(t.playbackStart==this.start&&e.has(t.beat.voice.bar.staff.track.index))return t.beat;return null}}class As{constructor(){this.start=0,this.end=0,this.tempo=0,this.firstBeat=null,this.lastBeat=null,this.nextMasterBar=null,this.previousMasterBar=null}insertAfter(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.nextBeat=e.nextBeat,t.previousBeat=e,e.nextBeat&&(e.nextBeat.previousBeat=t),e.nextBeat=t,e==this.lastBeat&&(this.lastBeat=t))}insertBefore(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.previousBeat=e.previousBeat,t.nextBeat=e,e.previousBeat&&(e.previousBeat.nextBeat=t),e.previousBeat=t,e==this.firstBeat&&(this.firstBeat=t))}addBeat(t,i,s,a){const r=s+a;if(null==this.firstBeat){const e=new Ds(s,r);e.highlightBeat(t,i),this.insertAfter(this.firstBeat,e)}else if(s>=this.lastBeat.end){const e=new Ds(this.lastBeat.end,r);e.highlightBeat(t,i),this.insertAfter(this.lastBeat,e)}else{let a=null;if(s<this.firstBeat.start)a=this.firstBeat;else{let t=this.firstBeat;for(;null!=t;){if(s>=t.start&&s<t.end){a=t;break}t=t.nextBeat}if(null===a)throw new G(e.AlphaTabErrorType.General,"Error on building lookup, unknown variant")}if(s<a.start)if(r==a.start){const e=new Ds(s,a.start);e.highlightBeat(t,i),this.insertBefore(this.firstBeat,e)}else if(r<a.end){const e=new Ds(s,a.start);e.highlightBeat(t,i),this.insertBefore(a,e);const n=new Ds(a.start,r);for(const e of a.highlightedBeats)n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(t,i),this.insertBefore(a,n),a.start=r}else if(r==a.end){const e=new Ds(s,a.start);e.highlightBeat(t,i),a.highlightBeat(t,i),this.insertBefore(a,e)}else{const e=new Ds(s,a.start);e.highlightBeat(t,i),a.highlightBeat(t,i),this.insertBefore(a,e),this.addBeat(t,i,a.end,r-a.end)}else if(s>a.start)if(r==a.end){const e=new Ds(a.start,s);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart);a.start=s,a.highlightBeat(t,i),this.insertBefore(a,e)}else if(r<a.end){const e=new Ds(a.start,s);this.insertBefore(a,e);const n=new Ds(s,r);this.insertBefore(a,n);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart),n.highlightBeat(t.beat,t.playbackStart);n.highlightBeat(t,i),a.start=r}else{const e=new Ds(a.start,s);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart);a.start=s,a.highlightBeat(t,i),this.insertBefore(a,e),this.addBeat(t,i,a.end,r-a.end)}else if(r===a.end)a.highlightBeat(t,i);else if(r<a.end){const e=new Ds(a.start,r);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart);e.highlightBeat(t,i),a.start=r,this.insertBefore(a,e)}else a.highlightBeat(t,i),this.addBeat(t,i,a.end,r-a.end)}}}class Rs{get start(){return this.masterBar.start+this.beatLookup.start}get end(){return this.start+this.tickDuration}constructor(e){this.nextBeat=null,this.tickDuration=0,this.duration=0,this.masterBar=e}}class Os{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[]}findBeat(e,t,i=null){let s=null;return i&&(s=this.findBeatFast(e,i,t)),s||(s=this.findBeatSlow(e,i,t,!1)),s}findBeatFast(e,t,i){if(i>=t.start&&i<t.end)return t;if(t.nextBeat&&i>=t.nextBeat.start&&i<t.nextBeat.end){const i=t.nextBeat;return this.fillNextBeat(i,e),i}return null}fillNextBeat(e,t){e.nextBeat=this.findBeatInMasterBar(e.masterBar,e.beatLookup.nextBeat,e.end,t,!1,!0),null==e.nextBeat&&(e.nextBeat=this.findBeatSlow(t,e,e.end,!0)),e.nextBeat&&(e.tickDuration=e.nextBeat.start-e.start,e.duration=z.ticksToMillis(e.tickDuration,e.masterBar.tempo)),e.nextBeat||(e.tickDuration=e.masterBar.end-e.start,e.duration=z.ticksToMillis(e.tickDuration,e.masterBar.tempo))}findBeatSlow(e,t,i,s){let a=null;if(null!=t&&(t.masterBar.start<=i&&t.masterBar.end>i?a=t.masterBar:t.masterBar.nextMasterBar&&t.masterBar.nextMasterBar.start<=i&&t.masterBar.nextMasterBar.end>i&&(a=t.masterBar.nextMasterBar)),a||(a=this.findMasterBar(i)),!a)return null;for(;a;){if(a.firstBeat){let t=this.findBeatInMasterBar(a,a.firstBeat,i,e,!0,s);if(t)return t}a=a.nextMasterBar}return null}findBeatInMasterBar(e,t,i,s,a,r){if(!t)return null;let n=null,o=null;const h=i-e.start;for(;null!=t&&null==o;){if(t.start<=h&&h<t.end){if(n=t,o=t.getVisibleBeatAtStart(s),!o)if(r){let i=e;for(;null!=i&&null==o;){for(;null!=t;){if(o=t.getVisibleBeatAtStart(s),o){n=t,e=i;break}t=t.nextBeat}o&&n||(i=i.nextMasterBar,t=i?.firstBeat??null)}}else{let i=e;for(;null!=i&&null==o;){for(;null!=t;){if(o=t.getVisibleBeatAtStart(s),o){n=t,e=i;break}t=t.previousBeat}o&&n||(i=i.previousMasterBar,t=i?.firstBeat??null)}}}else if(t.end>h)break;t=t?.nextBeat??null}if(null==o)return null;return this.createResult(e,n,o,a,s)}createResult(e,t,i,s,a){const r=new Rs(e);return r.beat=i,r.beatLookup=t,r.tickDuration=t.end-t.start,s&&this.fillNextBeat(r,a),r.duration=z.ticksToMillis(r.tickDuration,e.tempo),r}findMasterBar(e){const t=this.masterBars;let i=0,s=t.length-1;for(;i<=s;){const a=(s+i)/2|0,r=t[a];if(e>=r.start&&e<r.end)return r;e<r.start?s=a-1:i=a+1}return null}getMasterBar(e){if(!this.masterBarLookup.has(e.index)){const t=new As;return t.masterBar=e,t}return this.masterBarLookup.get(e.index)}getMasterBarStart(e){return this.masterBarLookup.has(e.index)?this.masterBarLookup.get(e.index).start:0}getBeatStart(e){return this.masterBarLookup.has(e.voice.bar.index)?this.masterBarLookup.get(e.voice.bar.index).start+e.playbackStart:0}addMasterBar(e){this.masterBars.push(e),this._currentMasterBar&&(e.previousMasterBar=this._currentMasterBar,this._currentMasterBar.nextMasterBar=e),this._currentMasterBar=e,this.masterBarLookup.has(e.masterBar.index)||this.masterBarLookup.set(e.masterBar.index,e)}addBeat(e,t,i){const s=this._currentMasterBar;if(s)if(t<0&&s.previousMasterBar){const a=s.previousMasterBar.end-s.previousMasterBar.start,r=a+t,n=r+i;if(s.previousMasterBar.addBeat(e,r,r,i),n>a){const a=i+t;s.addBeat(e,t,0,a)}}else s.addBeat(e,t,t,i)}}class Gs{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Vs{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class Hs{constructor(e,t,i){this._currentTempo=0,this._programsPerChannel=new Map,this.tickLookup=new Os,this.applyTranspositionPitches=!0,this.transpositionPitches=new Map,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new Zi,this._currentTempo=this._score.tempo,this._handler=i}generate(){this.transpositionPitches.clear();for(const e of this._score.tracks)this.generateTrack(e);J.debug("Midi","Begin midi generation");const e=new Ms(this._score);let t=null;for(;!e.finished;){const i=e.index,s=this._score.masterBars[i],a=e.currentTick;if(e.processCurrent(),e.shouldPlay){this.generateMasterBar(s,t,a);for(const e of this._score.tracks)for(const t of e.staves)i<t.bars.length&&this.generateBar(t.bars[i],a)}e.moveNext(),t=s}for(const t of this._score.tracks)this._handler.finishTrack(t.index,e.currentTick);J.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,i,s){this._programsPerChannel.has(i)&&this._programsPerChannel.get(i)===s||(this._handler.addProgramChange(e.index,t,i,s),this._programsPerChannel.set(i,s))}static buildTranspositionPitches(e,t){const i=new Map;for(const s of e.tracks){const e=s.index<t.notation.transpositionPitches.length?t.notation.transpositionPitches[s.index]:0;i.set(s.playbackInfo.primaryChannel,e),i.set(s.playbackInfo.secondaryChannel,e)}return i}generateChannel(e,t,i){const s=e.index<this._settings.notation.transpositionPitches.length?this._settings.notation.transpositionPitches[e.index]:0;this.transpositionPitches.set(t,s);let a=Hs.toChannelShort(i.volume),r=Hs.toChannelShort(i.balance);this._handler.addControlChange(e.index,0,t,Ge.VolumeCoarse,a),this._handler.addControlChange(e.index,0,t,Ge.PanCoarse,r),this._handler.addControlChange(e.index,0,t,Ge.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,Ge.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,Ge.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,Ge.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,Ge.DataEntryCoarse,Hs.PitchBendRangeInSemitones),this.addProgramChange(e,0,t,i.program)}static toChannelShort(e){const t=Math.max(-32768,Math.min(32767,8*e-1));return Math.max(t,-1)+1}generateMasterBar(e,t,i){t&&t.timeSignatureDenominator===e.timeSignatureDenominator&&t.timeSignatureNumerator===e.timeSignatureNumerator||this._handler.addTimeSignature(i,e.timeSignatureNumerator,e.timeSignatureDenominator),e.tempoAutomation?(this._handler.addTempo(i,e.tempoAutomation.value),this._currentTempo=e.tempoAutomation.value):t||(this._handler.addTempo(i,e.score.tempo),this._currentTempo=e.score.tempo);const s=new As;s.masterBar=e,s.start=i,s.tempo=this._currentTempo,s.end=s.start+e.calculateDuration(),this.tickLookup.addMasterBar(s)}generateBar(e,t){let i=this.getPlaybackBar(e);for(const s of i.voices)this.generateVoice(s,t,e)}getPlaybackBar(e){switch(e.simileMark){case h.Simple:e.previousBar&&(e=this.getPlaybackBar(e.previousBar));break;case h.FirstOfDouble:case h.SecondOfDouble:e.previousBar&&e.previousBar.previousBar&&(e=this.getPlaybackBar(e.previousBar.previousBar))}return e}generateVoice(e,t,i){if(!e.isEmpty||e.bar.isEmpty&&0===e.index)for(const s of e.beats)this.generateBeat(s,t,i)}generateBeat(e,t,i){let s=e.playbackStart,a=e.playbackDuration;e.voice.bar.isEmpty?a=e.voice.bar.masterBar.calculateDuration():e.voice.bar.masterBar.tripletFeel!==A.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(s-=this._currentTripletFeel.secondBeatStartOffset,a=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=Hs.calculateTripletFeelInfo(s,a,e),this._currentTripletFeel&&(a=this._currentTripletFeel.firstBeatDuration))),i===e.voice.bar?this.tickLookup.addBeat(e,s,a):this.tickLookup.addBeat(e,0,a);const r=e.voice.bar.staff.track;for(const i of e.automations)this.generateAutomation(e,i,t);if(e.isRest)this._handler.addRest(r.index,t+s,r.playbackInfo.primaryChannel);else{let i=this.getBrushInfo(e);for(const r of e.notes)this.generateNote(r,t+s,a,i)}if(e.vibrato!==_.None){let i=240,a=3;switch(e.vibrato){case _.Slight:i=this._settings.player.vibrato.beatSlightLength,a=this._settings.player.vibrato.beatSlightAmplitude;break;case _.Wide:i=this._settings.player.vibrato.beatWideLength,a=this._settings.player.vibrato.beatWideAmplitude}this.generateVibratorWithParams(t+s,e.playbackDuration,i,a,((t,i)=>{this._handler.addBend(e.voice.bar.staff.track.index,t,r.playbackInfo.secondaryChannel,i)}))}}static calculateTripletFeelInfo(e,t,i){let s;switch(i.voice.bar.masterBar.tripletFeel){case A.Triplet8th:case A.Dotted8th:case A.Scottish8th:s=p.Eighth;break;case A.Triplet16th:case A.Dotted16th:case A.Scottish16th:s=p.Sixteenth;break;default:return null}const a=z.toTicks(s);if(t!==a)return null;if(e%a!=0)return null;if(!i.nextBeat||i.nextBeat.voice!==i.voice||i.playbackDuration!==a)return null;const r=new Vs;switch(i.voice.bar.masterBar.tripletFeel){case A.Triplet8th:r.firstBeatDuration=z.applyTuplet(z.toTicks(p.Quarter),3,2),r.secondBeatDuration=z.applyTuplet(z.toTicks(p.Eighth),3,2);break;case A.Dotted8th:r.firstBeatDuration=z.applyDot(z.toTicks(p.Eighth),!1),r.secondBeatDuration=z.toTicks(p.Sixteenth);break;case A.Scottish8th:r.firstBeatDuration=z.toTicks(p.Sixteenth),r.secondBeatDuration=z.applyDot(z.toTicks(p.Eighth),!1);break;case A.Triplet16th:r.firstBeatDuration=z.applyTuplet(z.toTicks(p.Eighth),3,2),r.secondBeatDuration=z.applyTuplet(z.toTicks(p.Sixteenth),3,2);break;case A.Dotted16th:r.firstBeatDuration=z.applyDot(z.toTicks(p.Sixteenth),!1),r.secondBeatDuration=z.toTicks(p.ThirtySecond);break;case A.Scottish16th:r.firstBeatDuration=z.toTicks(p.ThirtySecond),r.secondBeatDuration=z.applyDot(z.toTicks(p.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateNote(e,t,i,s){const a=e.beat.voice.bar.staff.track,r=e.beat.voice.bar.staff;let n=e.calculateRealValue(this.applyTranspositionPitches,!0);if(e.isPercussion){const t=K.getArticulation(e);t&&(n=t.outputMidiNumber)}const o=e.isStringed&&e.string<=s.length?s[e.string-1]:0,h=t+o,l=this.getNoteDuration(e,i);l.untilTieOrSlideEnd-=o,l.noteOnly-=o,l.letRingEnd-=o;const c=Hs.getNoteVelocity(e),d=e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==_.None?a.playbackInfo.secondaryChannel:a.playbackInfo.primaryChannel;let u=0;if(u=e.hasBend?Hs.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?Hs.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===w.Legato?-1:Hs.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!==S.None||e.slideOutType!==w.None?this.generateSlide(e,h,l,n,d):(e.vibrato!==_.None||e.isTieDestination&&e.tieOrigin.vibrato!==_.None)&&this.generateVibrato(e,h,l,n,d),!(e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===w.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(t,i){const s=new Gs;if(s.noteOnly=i,s.untilTieOrSlideEnd=i,s.letRingEnd=i,t.isDead)return s.noteOnly=this.applyStaticDuration(Hs.DefaultDurationDead,i),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(t.isPalmMute)return s.noteOnly=this.applyStaticDuration(Hs.DefaultDurationPalmMute,i),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(t.isStaccato)return s.noteOnly=i/2|0,s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(t.isTieOrigin){const e=t.tieDestination;if(e)if(t.isTieDestination){const t=this.getNoteDuration(e,e.beat.playbackDuration);s.untilTieOrSlideEnd=i+t.untilTieOrSlideEnd}else{const i=t.beat.absolutePlaybackStart,a=this.getNoteDuration(e,e.beat.playbackDuration),r=e.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-i}}else if(t.slideOutType===w.Legato){const e=t.slideTarget;if(e){const i=t.beat.absolutePlaybackStart,a=this.getNoteDuration(e,e.beat.playbackDuration),r=e.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-i}}if(t.isLetRing&&this._settings.notation.notationMode===e.NotationMode.GuitarPro){let e=t.beat,a=0;const r=t.beat.voice.bar.masterBar.calculateDuration();for(;e.nextBeat;){let i=e.nextBeat;if(i.isRest)break;if(t.isStringed&&i.hasNoteOnString(t.string))break;if(e=e.nextBeat,a=e.absolutePlaybackStart-t.beat.absolutePlaybackStart+e.playbackDuration,a>r){a=r;break}}e===t.beat?s.letRingEnd=i:s.letRingEnd=a}else s.letRingEnd=s.untilTieOrSlideEnd;return s}applyStaticDuration(e,t){const i=this._currentTempo*e/U.MaxPosition|0;return Math.min(i,t)}static getNoteVelocity(e){let t=e.dynamics;switch(!e.beat.voice.bar.staff.isPercussion&&e.hammerPullOrigin&&t--,e.isGhost&&t--,e.accentuated){case a.Normal:t++;break;case a.Heavy:t+=2}return z.dynamicToVelocity(t)}generateFadeIn(e,t,i){const s=e.beat.voice.bar.staff.track,a=Hs.toChannelShort(s.playbackInfo.volume)/i.noteOnly,r=i.noteOnly/120|0,n=t+i.noteOnly;for(let e=r-1;e>=0;e--){const i=n-120*e,o=(i-t)*a;e===r-1&&(this._handler.addControlChange(s.index,t,s.playbackInfo.primaryChannel,Ge.VolumeCoarse,o),this._handler.addControlChange(s.index,t,s.playbackInfo.secondaryChannel,Ge.VolumeCoarse,o)),this._handler.addControlChange(s.index,i,s.playbackInfo.primaryChannel,Ge.VolumeCoarse,o),this._handler.addControlChange(s.index,i,s.playbackInfo.secondaryChannel,Ge.VolumeCoarse,o)}}generateVibrato(e,t,i,s,a){let r=0,n=0;switch(e.vibrato!==_.None?e.vibrato:e.isTieDestination?e.tieOrigin.vibrato:_.Slight){case _.Slight:r=this._settings.player.vibrato.noteSlightLength,n=this._settings.player.vibrato.noteSlightAmplitude;break;case _.Wide:r=this._settings.player.vibrato.noteWideLength,n=this._settings.player.vibrato.noteWideAmplitude;break;default:return}const o=e.beat.voice.bar.staff.track;this.generateVibratorWithParams(t,i.noteOnly,r,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,s,t)}))}generateVibratorWithParams(e,t,i,s,a){const r=this.vibratoResolution,n=i/2|0,o=(e+=i)+t;for(;e<o;){let t=0;const h=e+i<o?i:o-e;for(;t<h;){let i=s*Math.sin(t*Math.PI/n);a(e+t|0,Hs.getPitchWheel(i)),t+=r}e+=i}}static getPitchWheel(e){return Zt.DefaultPitchWheel+e/2*Hs.PitchValuePerSemitone}generateSlide(e,t,i,s,a){let r=e.slideOutType===w.Legato?i.noteOnly:i.untilTieOrSlideEnd,n=[],o=e.beat.voice.bar.staff.track;const h=this._settings.player.slide.simpleSlidePitchOffset,l=Math.floor(U.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),c=Math.floor(U.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case S.IntoFromAbove:n.push(new U(0,h)),n.push(new U(l,0));break;case S.IntoFromBelow:n.push(new U(0,-h)),n.push(new U(l,0))}switch(e.slideOutType){case w.Legato:case w.Shift:n.push(new U(c,0));const t=2*(e.slideTarget.calculateRealValue(this.applyTranspositionPitches,!0)-e.calculateRealValue(this.applyTranspositionPitches,!0));n.push(new U(U.MaxPosition,t));break;case w.OutDown:n.push(new U(U.MaxPosition-l,0)),n.push(new U(U.MaxPosition,-h));break;case w.OutUp:n.push(new U(U.MaxPosition-l,0)),n.push(new U(U.MaxPosition,h))}this.generateWhammyOrBend(t,r,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,s,t)}))}generateBend(e,t,i,s,a){let r=e.bendPoints,n=e.beat.voice.bar.staff.track;const o=(e,t)=>{this._handler.addNoteBend(n.index,e,a,s,t)};let h,d=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend;)t=t.tieDestination;h=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==f.None){switch(e.tieDestination.bendType){case c.Bend:case c.BendRelease:case c.PrebendBend:d=e.tieDestination.bendPoints[1].value;break;case c.Prebend:case c.PrebendRelease:d=e.tieDestination.bendPoints[0].value}h=Math.max(i.noteOnly,z.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo))}else h=i.noteOnly;r[0].value>0&&!e.isContinuedBend&&t>0&&t--;const u=Math.min(h,z.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));let p=[];switch(e.bendType){case c.Custom:p=r;break;case c.Bend:case c.Release:switch(e.bendStyle){case l.Default:p=r;break;case l.Gradual:p.push(new U(0,e.bendPoints[0].value)),(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),p.push(new U(U.MaxPosition,d));break;case l.Fast:return(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),void(e.beat.graceType===f.BendGrace?this.generateSongBookWhammyOrBend(t,h,!0,[e.bendPoints[0].value,d],u,o):this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,d],u,o))}break;case c.BendRelease:switch(e.bendStyle){case l.Default:p=r;break;case l.Gradual:p.push(new U(0,e.bendPoints[0].value)),p.push(new U(U.MaxPosition/2|0,e.bendPoints[1].value)),p.push(new U(U.MaxPosition,e.bendPoints[2].value));break;case l.Fast:return void this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],u,o)}break;case c.Hold:case c.Prebend:p=r;break;case c.PrebendBend:switch(e.bendStyle){case l.Default:p=r;break;case l.Gradual:p.push(new U(0,e.bendPoints[0].value)),p.push(new U(U.MaxPosition,e.bendPoints[1].value));break;case l.Fast:return o(t,0|Hs.getPitchWheel(e.bendPoints[0].value)),(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,d],u,o)}break;case c.PrebendRelease:switch(e.bendStyle){case l.Default:p=r;break;case l.Gradual:p.push(new U(0,e.bendPoints[0].value)),p.push(new U(U.MaxPosition,e.bendPoints[1].value));break;case l.Fast:return o(t,0|Hs.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,e.bendPoints[1].value],u,o)}}this.generateWhammyOrBend(t,h,p,o)}generateSongBookWhammyOrBend(e,t,i,s,a,r){const n=i?e:e+t-a,o=a/(s.length-1);for(let e=0;e<s.length-1;e++){const t=Hs.getPitchWheel(s[e]),i=Hs.getPitchWheel(s[e+1]),a=n+o*e;this.generateBendValues(a,o,t,i,r)}}generateWhammy(e,t,i,s){const a=e.whammyBarPoints,r=e.voice.bar.staff.track,n=i.noteOnly;a[0].value>0&&!e.isContinuedWhammy&&t--;const o=(e,t)=>{this._handler.addBend(r.index,e,s,t)};let h=[];switch(e.whammyBarType){case F.Custom:h=a;break;case F.Dive:switch(e.whammyStyle){case l.Default:h=a;break;case l.Gradual:h.push(new U(0,a[0].value)),h.push(new U(U.MaxPosition,a[1].value));break;case l.Fast:const e=Math.min(n,z.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],e,o)}break;case F.Dip:switch(e.whammyStyle){case l.Default:h=a;break;case l.Gradual:h.push(new U(0,a[0].value)),h.push(new U(U.MaxPosition/2|0,a[1].value)),h.push(new U(U.MaxPosition,a[2].value));break;case l.Fast:const e=Math.min(n,z.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 F.Hold:case F.Predive:h=a;break;case F.PrediveDive:switch(e.whammyStyle){case l.Default:h=a;break;case l.Gradual:h.push(new U(0,a[0].value)),h.push(new U(U.MaxPosition/2|0,a[0].value)),h.push(new U(U.MaxPosition,a[1].value));break;case l.Fast:const e=Hs.getPitchWheel(a[0].value);this._handler.addBend(r.index,t,s,0|e);const i=Math.min(n,z.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],i,o)}}this.generateWhammyOrBend(t,n,h,o)}generateWhammyOrBend(e,t,i,s){const a=t/U.MaxPosition;for(let t=0;t<i.length-1;t++){const r=i[t],n=i[t+1],o=Hs.getPitchWheel(r.value),h=Hs.getPitchWheel(n.value),l=a*(n.offset-r.offset),c=e+a*r.offset;this.generateBendValues(c,l,o,h,s)}}generateBendValues(e,t,i,s,a){const r=z.ticksToMillis(t,this._currentTempo),n=Math.abs(s-i)/Hs.PitchValuePerSemitone,o=Math.max(Hs.MinBreakpointsPerSemitone*n,r/Hs.MillisecondsPerBreakpoint),h=t/o,l=(s-i)/o;for(let t=0;t<o;t++)a(0|e,Math.round(i)),i+=l,e+=h;i<s&&a(0|e,s)}generateTrill(e,t,i,s,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=z.toTicks(e.trillSpeed),l=!0,c=t,d=t+i.untilTieOrSlideEnd;for(;c+10<d;)c+h>=d&&(h=d-c),this._handler.addNote(n.index,c,h,l?o:s,a,r),l=!l,c+=h}generateTremoloPicking(e,t,i,s,a,r){const n=e.beat.voice.bar.staff.track;let o=z.toTicks(e.beat.tremoloSpeed),h=t;const l=t+i.untilTieOrSlideEnd;for(;h+10<l;)h+o>=l&&(o=l-h),this._handler.addNote(n.index,h,o,s,a,r),h+=o}getBrushInfo(e){const t=new Int32Array(e.voice.bar.staff.tuning.length);if(e.brushType!==d.None){let i=0,s=0;for(const t of e.notes)t.isTieDestination||(i|=1<<t.string-1,s++);if(e.notes.length>0){let a=0;const r=e.brushDuration/(s-1)|0;for(let s=0;s<e.voice.bar.staff.tuning.length;s++){let n=e.brushType===d.ArpeggioDown||e.brushType===d.BrushDown?s:t.length-1-s;i&1<<n&&(t[n]=a,a+=r)}}}return t}generateAutomation(e,t,i){switch(t.type){case r.Instrument:this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,255&t.value),this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,255&t.value);break;case r.Balance:let s=Hs.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,Ge.PanCoarse,s),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Ge.PanCoarse,s);break;case r.Volume:let a=Hs.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,Ge.VolumeCoarse,a),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Ge.VolumeCoarse,a)}}prepareSingleBeat(e){let t=-1,i=-1,s=e;for(;s&&(-1===t||-1===i);){for(const s of e.automations)switch(s.type){case r.Instrument:i=s.value;break;case r.Tempo:t=s.value}s=s.previousBeat}const a=e.voice.bar.staff.track,n=e.voice.bar.masterBar;-1===t&&(t=n.score.tempo),-1===i&&(i=a.playbackInfo.program);const o=a.playbackInfo.volume;this.generateTrack(a),this._handler.addTimeSignature(0,n.timeSignatureNumerator,n.timeSignatureDenominator),this._handler.addTempo(0,t);let h=Hs.toChannelShort(o);this._handler.addControlChange(0,0,a.playbackInfo.primaryChannel,Ge.VolumeCoarse,h),this._handler.addControlChange(0,0,a.playbackInfo.secondaryChannel,Ge.VolumeCoarse,h)}generateSingleBeat(e){this.prepareSingleBeat(e),this.generateBeat(e,-e.playbackStart,e.voice.bar)}generateSingleNote(e){this.prepareSingleBeat(e.beat),this.generateNote(e,0,e.beat.playbackDuration,new Int32Array(e.beat.voice.bar.staff.tuning.length))}}Hs.DefaultDurationDead=30,Hs.DefaultDurationPalmMute=80,Hs.PitchBendRangeInSemitones=16,Hs.PitchValuePerSemitone=Zt.DefaultPitchWheel/Hs.PitchBendRangeInSemitones,Hs.MinBreakpointsPerSemitone=6,Hs.MillisecondsPerBreakpoint=150;class Ws{constructor(){this.startTick=0,this.endTick=0}}class zs{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,i){}}class Us extends zs{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Xs extends Us{constructor(e,t,i,s){super(e,t),this.glyphScale=0,this.glyphScale=i,this.symbol=s}paint(e,t,i){i.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale*this.scale,this.symbol,!1)}}class Ys extends Xs{constructor(e,t,i,s){super(e,t,s?Ys.GraceScale:1,Ys.getSymbol(i)),this._isGrace=s,this._duration=i}paint(e,t,i){let s=this._isGrace?this.scale:0;i.fillMusicFontSymbol(e+this.x,t+this.y+s,this.glyphScale*this.scale,this.symbol,!1)}doLayout(){let e=(this._isGrace?Ys.GraceScale:1)*this.scale;switch(this._duration){case p.QuadrupleWhole:this.width=14*e;break;case p.DoubleWhole:case p.Whole:this.width=14*(this._isGrace?Ys.GraceScale:1)*this.scale;break;default:this.width=Ys.QuarterNoteHeadWidth*(this._isGrace?Ys.GraceScale:1)*this.scale}this.height=Ys.NoteHeadHeight*e}static getSymbol(e){switch(e){case p.QuadrupleWhole:return P.NoteheadDoubleWholeSquare;case p.DoubleWhole:return P.NoteheadDoubleWhole;case p.Whole:return P.NoteheadWhole;case p.Half:return P.NoteheadHalf;default:return P.NoteheadBlack}}}Ys.GraceScale=.75,Ys.NoteHeadHeight=8,Ys.QuarterNoteHeadWidth=9;class qs extends Xs{constructor(e,t,i,s,a){super(e,t,a?Ys.GraceScale:1,qs.getSymbol(i,s,a))}doLayout(){this.width=0}static getSymbol(e,t,i){if(i&&(e=p.Eighth),t===Ce.Up)switch(e){case p.Eighth:return P.FlagEighthUp;case p.Sixteenth:return P.FlagSixteenthUp;case p.ThirtySecond:return P.FlagThirtySecondUp;case p.SixtyFourth:return P.FlagSixtyFourthUp;case p.OneHundredTwentyEighth:return P.FlagOneHundredTwentyEighthUp;case p.TwoHundredFiftySixth:return P.FlagTwoHundredFiftySixthUp;default:return P.FlagEighthUp}switch(e){case p.Eighth:return P.FlagEighthDown;case p.Sixteenth:return P.FlagSixteenthDown;case p.ThirtySecond:return P.FlagThirtySecondDown;case p.SixtyFourth:return P.FlagSixtyFourthDown;case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:return P.FlagOneHundredTwentyEighthDown;default:return P.FlagEighthDown}}}qs.FlagWidth=11;class Js extends zs{get onTimeX(){return this.onNotes.x+this.onNotes.centerX}constructor(e,t){super(0,0),this.ties=[],this.minWidth=0,this.beat=e,this.ties=[],this.voiceContainer=t}addTie(e){e.renderer=this.renderer,this.ties.push(e)}registerLayoutingInfo(e){let t=this.preNotes.computedWidth+this.onNotes.centerX;this.beat.graceGroup&&!this.beat.graceGroup.isComplete&&(t+=Js.GraceBeatPadding*this.renderer.scale);let i=this.onNotes.computedWidth-this.onNotes.centerX;const s=this.renderer.helpers.getBeamingHelperForBeat(this.beat);(s&&s.hasFlag||this.beat.graceType!==f.None)&&(i+=qs.FlagWidth*this.scale*(this.beat.graceType!==f.None?Ys.GraceScale:1));for(const e of this.ties)i+=e.width;this.beat.graceType!==f.None&&(i+=Js.GraceBeatPadding*this.renderer.scale),e.addBeatSpring(this.beat,t,i),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+=Js.GraceBeatPadding*this.renderer.scale),this.preNotes.x=t,this.preNotes.width=e.getPreBeatSize(this.beat),this.onNotes.width=e.getOnBeatSize(this.beat),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.updateBeamingHelper(),this.updateWidth()}doLayout(){this.preNotes.x=0,this.preNotes.renderer=this.renderer,this.preNotes.container=this,this.preNotes.doLayout(),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.renderer=this.renderer,this.onNotes.container=this,this.onNotes.doLayout();let e=this.beat.notes.length-1;for(;e>=0;)this.createTies(this.beat.notes[e--]);this.renderer.registerTies(this.ties),this.updateWidth()}updateWidth(){if(this.minWidth=this.preNotes.width+this.onNotes.width,!this.beat.isRest)if(1===this.onNotes.beamingHelper.beats.length)this.beat.duration>=p.Eighth&&(this.minWidth+=20*this.scale);else switch(this.beat.duration){case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:this.minWidth+=10*this.scale}let e=0;for(let t of this.ties)t.width>e&&(e=t.width);this.minWidth+=e,this.width=this.minWidth}scaleToWidth(e){this.onNotes.updateBeamingHelper(),this.width=e}createTies(e){}static getGroupId(e){return"b"+e.id}paint(e,t,i){if(this.beat.voice.isEmpty)return;if(this.preNotes.isEmpty&&this.onNotes.isEmpty&&0===this.ties.length)return;i.beginGroup(Js.getGroupId(this.beat)),this.preNotes.paint(e+this.x,t+this.y,i),this.onNotes.paint(e+this.x,t+this.y,i);let s=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(s,a,i)}i.endGroup()}buildBoundingsLookup(e,t,i,s){let a=new Ts;a.beat=this.beat,a.visualBounds=new nt,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 nt,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,s&&(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,i+this.y)}}Js.GraceBeatPadding=3;class js{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new Co}causeIssue(){return this.settings=null,!0}}class Qs{constructor(e){this.activeBeats=e}}class $s{constructor(e){this.bounds=null,this.beat=e}}class Ks{constructor(e,t){this._startTime=0,this._trackIndexes=null,this._trackIndexLookup=null,this._isDestroyed=!1,this.score=null,this.tracks=[],this._tickCache=null,this.player=null,this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null,this._previousTick=0,this._playerState=Ie.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=Ie.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new Ci,this.activeBeatsChanged=new Ci,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new Ci,this.beatMouseMove=new Ci,this.beatMouseUp=new Ci,this.noteMouseDown=new Ci,this.noteMouseMove=new Ci,this.noteMouseUp=new Ci,this.scoreLoaded=new Ci,this.resize=new Ci,this.renderStarted=new Ci,this.renderFinished=new Ci,this.postRenderFinished=new Ei,this.error=new Ci,this.playerReady=new Ei,this.playerFinished=new Ei,this.soundFontLoaded=new Ei,this.midiLoad=new Ci,this.midiLoaded=new Ci,this.playerStateChanged=new Ci,this.playerPositionChanged=new Ci,this.midiEventsPlayed=new Ci,this.playbackRangeChanged=new Ci,this.settingsUpdated=new Ei,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),J.logLevel=this.settings.core.logLevel,this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&Eo.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new Ps(this.settings),this.container.resize.on(Eo.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));let i=new js;i.oldWidth=this.renderer.width,i.newWidth=0|this.container.width,i.settings=this.settings,this.onResize(i),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;J.debug("rendering","Rendering completed in "+e+"ms"),this.onPostRenderFinished()})),this.renderer.preRender.on((e=>{this._startTime=Date.now()})),this.renderer.partialLayoutFinished.on(this.appendRenderResult.bind(this)),this.renderer.partialRenderFinished.on(this.updateRenderResult.bind(this)),this.renderer.renderFinished.on((e=>{this.appendRenderResult(e),this.appendRenderResult(null)})),this.renderer.error.on(this.onError.bind(this)),this.settings.player.enablePlayer&&this.setupPlayer(),this.setupClickHandling(),this.uiFacade.beginInvoke((()=>{this.uiFacade.initialRender()}))}destroy(){this._isDestroyed=!0,this.player&&this.player.destroy(),this.uiFacade.destroy(),this.renderer.destroy()}updateSettings(){const e=this.score;e&&Q.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?(this.setupPlayer(),e&&this.player?.applyTranspositionPitches(Hs.buildTranspositionPitches(e,this.settings))):this.destroyPlayer(),this.onSettingsUpdated()}load(e,t){try{return this.uiFacade.load(e,(e=>{this.renderScore(e,t)}),(e=>{this.onError(e)}))}catch(e){return this.onError(e),!1}}renderScore(e,t){let i=[];if(t)if(0===t.length)e.tracks.length>0&&i.push(e.tracks[0]);else if(1===t.length&&-1===t[0])for(let t of e.tracks)i.push(t);else for(let s of t)s>=0&&s<=e.tracks.length&&i.push(e.tracks[s]);else e.tracks.length>0&&i.push(e.tracks[0]);this.internalRenderTracks(e,i)}renderTracks(t){if(t.length>0){let i=t[0].score;for(let s of t)if(s.score!==i)return void this.onError(new G(e.AlphaTabErrorType.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(i,t)}}internalRenderTracks(e,t){if(Q.applyPitchOffsets(this.settings,e),e!==this.score){this.score=e,this.tracks=t,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this._trackIndexLookup=new Set(this._trackIndexes),this.onScoreLoaded(e),this.loadMidiForScore(),this.render()}else{this.tracks=t,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this._trackIndexLookup=new Set(this._trackIndexes),this.render()}}triggerResize(){if(this.container.isVisible){let e=new js;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 J.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{J.debug("Rendering","AlphaTab container became visible, doing autosizing",null),this.triggerResize()}))}appendRenderResult(e){e?(this.canvasElement.width=e.totalWidth,this.canvasElement.height=e.totalHeight,this._cursorWrapper&&(this._cursorWrapper.width=e.totalWidth,this._cursorWrapper.height=e.totalHeight),(e.width>0||e.height>0)&&this.uiFacade.beginAppendRenderResults(e)):this.uiFacade.beginAppendRenderResults(e)}updateRenderResult(e){e&&e.renderResult&&this.uiFacade.beginUpdateRenderResults(e)}tex(e,t){try{let i=new it;i.logErrors=!0,i.initFromString(e,this.settings);let s=i.readScore();this.renderScore(s,t)}catch(e){this.onError(e)}}loadSoundFont(e,t=!1){return!!this.player&&this.uiFacade.loadSoundFont(e,t)}resetSoundFonts(){this.player&&this.player.resetSoundFonts()}render(){this.renderer&&(this.uiFacade.canRender?(this.renderer.width=this.container.width,this.renderer.renderScore(this.score,this._trackIndexes)):this.uiFacade.canRenderChanged.on((()=>this.render())))}get tickCache(){return this._tickCache}get isReadyForPlayback(){return!!this.player&&this.player.isReadyForPlayback}get playerState(){return this.player?this.player.state:Ie.Paused}get masterVolume(){return this.player?this.player.masterVolume:0}set masterVolume(e){this.player&&(this.player.masterVolume=e)}get metronomeVolume(){return this.player?this.player.metronomeVolume:0}set metronomeVolume(e){this.player&&(this.player.metronomeVolume=e)}get countInVolume(){return this.player?this.player.countInVolume:0}set countInVolume(e){this.player&&(this.player.countInVolume=e)}get midiEventsPlayedFilter(){return this.player?this.player.midiEventsPlayedFilter:[]}set midiEventsPlayedFilter(e){this.player&&(this.player.midiEventsPlayedFilter=e)}get tickPosition(){return this.player?this.player.tickPosition:0}set tickPosition(e){this.player&&(this.player.tickPosition=e)}get timePosition(){return this.player?this.player.timePosition:0}set timePosition(e){this.player&&(this.player.timePosition=e)}get playbackRange(){return this.player?this.player.playbackRange:null}set playbackRange(e){this.player&&(this.player.playbackRange=e,this.settings.player.enableCursor&&this.updateSelectionCursor(e))}get playbackSpeed(){return this.player?this.player.playbackSpeed:0}set playbackSpeed(e){this.player&&(this.player.playbackSpeed=e)}get isLooping(){return!!this.player&&this.player.isLooping}set isLooping(e){this.player&&(this.player.isLooping=e)}destroyPlayer(){this.player&&(this.player.destroy(),this.player=null,this._previousTick=0,this._playerState=Ie.Paused,this.destroyCursors())}setupPlayer(){this.updateCursors(),this.player||(this.player=this.uiFacade.createWorkerPlayer(),this.player&&(this.player.ready.on((()=>{this.loadMidiForScore()})),this.player.readyForPlayback.on((()=>{if(this.onPlayerReady(),this.tracks)for(let e of this.tracks){let t=e.playbackInfo.volume/16;this.player.setChannelVolume(e.playbackInfo.primaryChannel,t),this.player.setChannelVolume(e.playbackInfo.secondaryChannel,t)}})),this.player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this.player.soundFontLoadFailed.on((e=>{this.onError(e)})),this.player.midiLoaded.on(this.onMidiLoaded.bind(this)),this.player.midiLoadFailed.on((e=>{this.onError(e)})),this.player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this.player.positionChanged.on(this.onPlayerPositionChanged.bind(this)),this.player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this.player.playbackRangeChanged.on(this.onPlaybackRangeChanged.bind(this)),this.player.finished.on(this.onPlayerFinished.bind(this)),this.setupPlayerEvents()))}loadMidiForScore(){if(!this.player||!this.score||!this.player.isReady)return;J.debug("AlphaTab","Generating Midi");let e=new Rt,t=new Fs(e),i=new Hs(this.score,this.settings,t);i.applyTranspositionPitches=!1,i.generate(),this._tickCache=i.tickLookup,this.onMidiLoad(e),this.player.loadMidiFile(e),this.player.applyTranspositionPitches(i.transpositionPitches)}changeTrackVolume(e,t){if(this.player)for(let i of e)this.player.setChannelVolume(i.playbackInfo.primaryChannel,t),this.player.setChannelVolume(i.playbackInfo.secondaryChannel,t)}changeTrackSolo(e,t){if(this.player)for(let i of e)this.player.setChannelSolo(i.playbackInfo.primaryChannel,t),this.player.setChannelSolo(i.playbackInfo.secondaryChannel,t)}changeTrackMute(e,t){if(this.player)for(let i of e)this.player.setChannelMute(i.playbackInfo.primaryChannel,t),this.player.setChannelMute(i.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 Rt,i=new Fs(t);new Hs(e.voice.bar.staff.track.score,this.settings,i).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;let t=new Rt,i=new Fs(t);new Hs(e.beat.voice.bar.staff.track.score,this.settings,i).generateSingleNote(e),this.player.playOneTimeMidiFile(t)}destroyCursors(){this._cursorWrapper&&(this.uiFacade.destroyCursors(),this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null)}updateCursors(){if(this.settings.player.enableCursor&&!this._cursorWrapper){let e=this.uiFacade.createCursors();e&&(this._cursorWrapper=e.cursorWrapper,this._barCursor=e.barCursor,this._beatCursor=e.beatCursor,this._selectionWrapper=e.selectionWrapper),null!==this._currentBeat&&this.cursorUpdateBeat(this._currentBeat,!1,this._previousTick>10,!0)}else!this.settings.player.enableCursor&&this._cursorWrapper&&this.destroyCursors()}setupPlayerEvents(){this._previousTick=0,this._playerState=Ie.Paused,this.renderer.postRenderFinished.on((()=>{this._currentBeat=null,this.cursorUpdateTick(this._previousTick,!1,this._previousTick>10)})),this.player&&(this.player.positionChanged.on((e=>{this._previousTick=e.currentTick,this.uiFacade.beginInvoke((()=>{this.cursorUpdateTick(e.currentTick,!1)}))})),this.player.stateChanged.on((e=>{if(this._playerState=e.state,!e.stopped&&e.state===Ie.Paused){let e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getBeatStart(e.beat))}})))}cursorUpdateTick(e,t,i=!1){let s=this._tickCache;if(s){let a=this._trackIndexLookup;if(null!=a&&a.size>0){let r=s.findBeat(a,e,this._currentBeat);r&&this.cursorUpdateBeat(r,t,i)}}}cursorUpdateBeat(e,t,i,s=!1){const a=e.beat,r=e.nextBeat?.beat??null,n=e.duration,o=e.beatLookup.highlightedBeats;if(!a)return;let h=this.renderer.boundsLookup;if(!h)return;let l=this._currentBeat,c=this._previousCursorCache,d=this._previousStateForCursor;if(!s&&a===l?.beat&&h===c&&d===this._playerState)return;let u=h.findBeat(a);u&&(this._currentBeat=e,this._previousCursorCache=h,this._previousStateForCursor=this._playerState,this.uiFacade.beginInvoke((()=>{this.internalCursorUpdateBeat(a,r,n,t,o,h,u,i)})))}scrollToCursor(){const e=this._currentBarBounds;e&&this.internalScrollToCursor(e)}internalScrollToCursor(t){let i=this.uiFacade.getScrollContainer(),s=Eo.getLayoutEngineFactory(this.settings.display.layoutMode).vertical,a=this.settings.player.scrollMode;if(s){let s=t.realBounds.y+this.settings.player.scrollOffsetY;if(s!==this._lastScroll)switch(this._lastScroll=s,a){case e.ScrollMode.Continuous:let a=this.uiFacade.getOffset(i,this.container);this.uiFacade.scrollToY(i,a.y+s,this.settings.player.scrollSpeed);break;case e.ScrollMode.OffScreen:let r=i.scrollTop+this.uiFacade.getOffset(null,i).h;if(t.visualBounds.y+t.visualBounds.h>=r||t.visualBounds.y<i.scrollTop){let e=t.realBounds.y+this.settings.player.scrollOffsetY;this.uiFacade.scrollToY(i,e,this.settings.player.scrollSpeed)}}}else{let s=t.visualBounds.x;if(s!==this._lastScroll)switch(this._lastScroll=s,a){case e.ScrollMode.Continuous:let s=t.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=t.visualBounds.x,this.uiFacade.scrollToX(i,s,this.settings.player.scrollSpeed);break;case e.ScrollMode.OffScreen:let a=i.scrollLeft+this.uiFacade.getOffset(null,i).w;if(t.visualBounds.x+t.visualBounds.w>=a||t.visualBounds.x<i.scrollLeft){let e=t.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=t.visualBounds.x,this.uiFacade.scrollToX(i,e,this.settings.player.scrollSpeed)}}}}internalCursorUpdateBeat(t,i,s,a,r,n,o,h){const l=this._barCursor,c=this._beatCursor;let d=o.barBounds.masterBarBounds,u=d.visualBounds;this._currentBarBounds=d,l&&l.setBounds(u.x,u.y,u.w,u.h),c&&(this.settings.player.enableAnimatedBeatCursor&&c.stopAnimation(),c.setBounds(o.visualBounds.x,u.y,1,u.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let p=!1;if(this._playerState===Ie.Playing&&!a){if(this.settings.player.enableElementHighlighting)for(let e of r){let i=Js.getGroupId(e.beat);this.uiFacade.highlightElements(i,t.voice.bar.index)}if(this.settings.player.enableAnimatedBeatCursor){let e=d.visualBounds.x+d.visualBounds.w;if(i){let t=n.findBeat(i);t&&t.barBounds.masterBarBounds.staveGroupBounds===d.staveGroupBounds&&(e=t.visualBounds.x)}this.uiFacade.beginInvoke((()=>{c&&c.transitionToX(s/this.playbackSpeed,e)}))}h=!a,p=!0}h&&!this._beatMouseDown&&this.settings.player.scrollMode!==e.ScrollMode.Off&&this.internalScrollToCursor(d),p&&(this.onPlayedBeatChanged(t),this.onActiveBeatsChanged(new Qs(r.map((e=>e.beat)))))}onPlayedBeatChanged(e){this._isDestroyed||(this.playedBeatChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playedBeatChanged",e))}onActiveBeatsChanged(e){this._isDestroyed||(this.activeBeatsChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"activeBeatsChanged",e))}onBeatMouseDown(e,t){this._isDestroyed||(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&(this._selectionStart=new $s(t),this._selectionEnd=null),this._beatMouseDown=!0,this.beatMouseDown.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseDown",t,e))}onNoteMouseDown(e,t){this._isDestroyed||(this._noteMouseDown=!0,this.noteMouseDown.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseDown",t,e))}onBeatMouseMove(e,t){this._isDestroyed||(this.settings.player.enableUserInteraction&&(this._selectionEnd&&this._selectionEnd.beat===t||(this._selectionEnd=new $s(t),this.cursorSelectRange(this._selectionStart,this._selectionEnd))),this.beatMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseMove",t,e))}onNoteMouseMove(e,t){this._isDestroyed||(this.noteMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseMove",t,e))}onBeatMouseUp(e,t){if(!this._isDestroyed){if(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction){if(this._selectionEnd){let e=this._tickCache?.getBeatStart(this._selectionStart.beat)??this._selectionStart.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(this._selectionEnd.beat)??this._selectionEnd.beat.absolutePlaybackStart)<e){let e=this._selectionStart;this._selectionStart=this._selectionEnd,this._selectionEnd=e}}if(this._selectionStart&&this._tickCache){let e=this._tickCache,t=e.getMasterBarStart(this._selectionStart.beat.voice.bar.masterBar);if(this._currentBeat=null,this._playerState===Ie.Paused&&this.cursorUpdateTick(this._tickCache.getBeatStart(this._selectionStart.beat),!1),this.tickPosition=t+this._selectionStart.beat.playbackStart,this._selectionEnd&&this._selectionStart.beat!==this._selectionEnd.beat){let i=e.getMasterBarStart(this._selectionEnd.beat.voice.bar.masterBar),s=new Ws;s.startTick=t+this._selectionStart.beat.playbackStart,s.endTick=i+this._selectionEnd.beat.playbackStart+this._selectionEnd.beat.playbackDuration-50,this.playbackRange=s}else this._selectionStart=null,this.playbackRange=null,this.cursorSelectRange(this._selectionStart,this._selectionEnd)}}this.beatMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseUp",t,e),this._beatMouseDown=!1}}onNoteMouseUp(e,t){this._isDestroyed||(this.noteMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseUp",t,e),this._noteMouseDown=!1)}updateSelectionCursor(e){if(this._tickCache)if(e){const t=this._tickCache.findBeat(this._trackIndexLookup,e.startTick),i=this._tickCache.findBeat(this._trackIndexLookup,e.endTick);if(t&&i){const e=new $s(t.beat),s=new $s(i.beat);this.cursorSelectRange(e,s)}}else this.cursorSelectRange(null,null)}setupClickHandling(){this.canvasElement.mouseDown.on((e=>{if(!e.isLeftMouseButton)return;this.settings.player.enableUserInteraction&&e.preventDefault();let t=e.getX(this.canvasElement),i=e.getY(this.canvasElement),s=this.renderer.boundsLookup?.getBeatAtPos(t,i)??null;if(s&&(this.onBeatMouseDown(e,s),this.settings.core.includeNoteBounds)){const a=this.renderer.boundsLookup?.getNoteAtPos(s,t,i);a&&this.onNoteMouseDown(e,a)}})),this.canvasElement.mouseMove.on((e=>{if(!this._beatMouseDown)return;let t=e.getX(this.canvasElement),i=e.getY(this.canvasElement),s=this.renderer.boundsLookup?.getBeatAtPos(t,i)??null;if(s&&(this.onBeatMouseMove(e,s),this._noteMouseDown)){const a=this.renderer.boundsLookup?.getNoteAtPos(s,t,i);a&&this.onNoteMouseMove(e,a)}})),this.canvasElement.mouseUp.on((e=>{if(!this._beatMouseDown)return;this.settings.player.enableUserInteraction&&e.preventDefault();let t=e.getX(this.canvasElement),i=e.getY(this.canvasElement),s=this.renderer.boundsLookup?.getBeatAtPos(t,i)??null;if(this.onBeatMouseUp(e,s),this._noteMouseDown)if(s){const a=this.renderer.boundsLookup?.getNoteAtPos(s,t,i)??null;this.onNoteMouseUp(e,a)}else this.onNoteMouseUp(e,null)})),this.renderer.postRenderFinished.on((()=>{this._selectionStart&&this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&this.cursorSelectRange(this._selectionStart,this._selectionEnd)}))}cursorSelectRange(e,t){let i=this.renderer.boundsLookup;if(!i)return;let s=this._selectionWrapper;if(!s)return;if(s.clear(),!e||!t||e.beat===t.beat)return;e.bounds||(e.bounds=i.findBeat(e.beat)),t.bounds||(t.bounds=i.findBeat(t.beat));let a=this._tickCache?.getBeatStart(e.beat)??e.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(t.beat)??t.beat.absolutePlaybackStart)<a){let i=e;e=t,t=i}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),s.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=i.staveGroups[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),s.appendChild(r)}let d=this.uiFacade.createSelectionElement();d.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),s.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),s.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||(J.error("API","An unexpected error occurred",e),this.error.trigger(e),this.uiFacade.triggerEvent(this.container,"error",e))}onPlayerReady(){this._isDestroyed||(this.playerReady.trigger(),this.uiFacade.triggerEvent(this.container,"playerReady",null))}onPlayerFinished(){this._isDestroyed||(this.playerFinished.trigger(),this.uiFacade.triggerEvent(this.container,"playerFinished",null))}onSoundFontLoaded(){this._isDestroyed||(this.soundFontLoaded.trigger(),this.uiFacade.triggerEvent(this.container,"soundFontLoaded",null))}onMidiLoad(e){this._isDestroyed||(this.midiLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"midiLoad",e))}onMidiLoaded(e){this._isDestroyed||(this.midiLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"midiFileLoaded",e))}onPlayerStateChanged(e){this._isDestroyed||(this.playerStateChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerStateChanged",e))}onPlayerPositionChanged(e){this._isDestroyed||null!==this.score&&this.tracks.length>0&&(this.playerPositionChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerPositionChanged",e))}onMidiEventsPlayed(e){this._isDestroyed||(this.midiEventsPlayed.trigger(e),this.uiFacade.triggerEvent(this.container,"midiEventsPlayed",e))}onPlaybackRangeChanged(e){this._isDestroyed||(this.playbackRangeChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playbackRangeChanged",e))}onSettingsUpdated(){this._isDestroyed||(this.settingsUpdated.trigger(),this.uiFacade.triggerEvent(this.container,"settingsUpdated",null))}}class Zs extends G{constructor(t,i){super(e.AlphaTabErrorType.General,t),this.xhr=i,Object.setPrototypeOf(this,Zs.prototype)}}class ea{static loadScoreAsync(e,t,i,s){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,i=new Uint8Array(e),r=ea.loadScoreFromBytes(i,s);t(r)}catch(e){i(e)}else 0===a.status?i(new Zs("You are offline!!\n Please Check Your Network.",a)):404===a.status?i(new Zs("Requested URL not found.",a)):500===a.status?i(new Zs("Internel Server Error.",a)):"parsererror"===a.statusText?i(new Zs("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?i(new Zs("Request Time out.",a)):i(new Zs("Unknow Error: "+a.responseText,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Zi);let i=Eo.buildImporters();J.debug("ScoreLoader",`Loading score from ${e.length} bytes using ${i.length} importers`);let s=null,a=ke.fromBuffer(e);for(let e of i){a.reset();try{J.debug("ScoreLoader","Importing using importer "+e.name),e.init(a,t),s=e.readScore(),J.debug("ScoreLoader","Score imported using "+e.name);break}catch(t){if(!(t instanceof V))throw J.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;J.debug("ScoreLoader",e.name+" does not support the file")}}if(s)return s;throw new V("No compatible importer found for file")}}class ta{get isLeftMouseButton(){return 0===this.mouseEvent.button}getX(e){let t=e.element,i=t.getBoundingClientRect().left+t.ownerDocument.defaultView.pageXOffset;return this.mouseEvent.pageX-i}getY(e){let t=e.element,i=t.getBoundingClientRect().top+t.ownerDocument.defaultView.pageYOffset;return this.mouseEvent.pageY-i}preventDefault(){this.mouseEvent.preventDefault()}constructor(e){this.mouseEvent=e}}class ia{get width(){return this.element.offsetWidth}set width(e){this.element.style.width=e+"px"}get scrollLeft(){return this.element.scrollLeft}set scrollLeft(e){this.element.scrollTop=e}get scrollTop(){return this.element.scrollLeft}set scrollTop(e){this.element.scrollTop=e}get height(){return this.element.offsetHeight}set height(e){this.element.style.height=e>=0?e+"px":"100%"}get isVisible(){return!!this.element.offsetWidth||!!this.element.offsetHeight||!!this.element.getClientRects().length}constructor(e){this._resizeListeners=0,this.lastBounds=new nt,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new ta(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new ta(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new ta(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&ia.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,ia.resizeObserver.value.unobserve(this.element))}}}stopAnimation(){this.element.style.transition="none"}transitionToX(e,t){this.element.style.transition=`transform ${e}ms linear`,this.setBounds(t,NaN,NaN,NaN)}setBounds(e,t,i,s){isNaN(e)&&(e=this.lastBounds.x),isNaN(t)&&(t=this.lastBounds.y),isNaN(i)&&(i=this.lastBounds.w),isNaN(s)&&(s=this.lastBounds.h),this.element.style.transform=`translate(${e}px, ${t}px) scale(${i}, ${s})`,this.element.style.transformOrigin="top left",this.lastBounds.x=e,this.lastBounds.y=t,this.lastBounds.w=i,this.lastBounds.h=s}appendChild(e){this.element.appendChild(e.element)}clear(){this.element.innerHTML=""}}ia.resizeObserver=new Y((()=>new ResizeObserver((e=>{for(const t of e){let e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class sa{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new Ci,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(Eo.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0,t=window.setInterval((()=>{J.warning("Rendering",`Could not load font '${this._families[0]}' within ${5*(e+1)} seconds`,null),this._families.length>1?(this._families.shift(),e=0):e++}),5e3);J.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);let i=e=>{this._families.length>1?(J.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(J.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},s=e=>{J.debug("Font",`[${e}] Font API signaled available`),this.isFontLoaded=!0,window.clearInterval(t),this.fontLoaded.trigger(this._families[0])},a=async()=>{for(const e of this._families)if(await this.isFontAvailable(e,!1))return void s(e);try{await document.fonts.load(`1em ${this._families[0]}`)}catch(e){i(e)}return J.debug("Font",`[${this._families[0]}] Font API signaled loaded`),await this.isFontAvailable(this._families[0],!0)?s(this._families[0]):i("Font not available"),!0};document.fonts.ready.then((()=>{a()}))}isFontAvailable(e,t){return new Promise((i=>{const s="1em "+e;if(document.fonts.check(s))i(!0);else if(t){J.debug("Font",`Font ${e} not available, creating test element to trigger load`);const t=document.createElement("div");t.style.font=s,t.style.opacity="0",t.style.position="absolute",t.style.top="0",t.style.left="0",t.innerText=`Trigger ${e} load`,document.body.appendChild(t),setTimeout((()=>{document.body.removeChild(t),document.fonts.check(s)?i(!0):i(!1)}),200)}else i(!1)}))}}class aa{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,i){let s=0;i>this._buffer.length-this.count&&(i=this._buffer.length-this.count);const a=Math.min(this._buffer.length-this._writePosition,i);return this._buffer.set(e.subarray(t,t+a),this._writePosition),this._writePosition+=a,this._writePosition%=this._buffer.length,s+=a,s<i&&(this._buffer.set(e.subarray(t+s,t+s+i-s),this._writePosition),this._writePosition+=i-s,s=i),this.count+=s,s}read(e,t,i){i>this.count&&(i=this.count);let s=0;const a=Math.min(this._buffer.length-this._readPosition,i);return e.set(this._buffer.subarray(this._readPosition,this._readPosition+a),t),s+=a,this._readPosition+=a,this._readPosition%=this._buffer.length,s<i&&(e.set(this._buffer.subarray(this._readPosition,this._readPosition+i-s),t+s),this._readPosition+=i-s,s=i),this.count-=s,s}}class ra{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new Ei,this.samplesPlayed=new Ci,this.sampleRequest=new Ei}get sampleRate(){return this._context?this._context.sampleRate:ra.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(J.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{J.debug("WebAudio",`Audio Context resume success: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}`),e&&e()}),(e=>{J.warning("WebAudio",`Audio Context resume failed: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}, reason=${e}`)})))}patchIosSampleRate(){let e=navigator.userAgent;if(-1!==e.indexOf("iPhone")||-1!==e.indexOf("iPad")){let e=this.createAudioContext(),t=e.createBuffer(1,1,ra.PreferredSampleRate),i=e.createBufferSource();i.buffer=t,i.connect(e.destination),i.start(0),i.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in Eo.globalThis)return new AudioContext;if("webkitAudioContext"in Eo.globalThis)return new webkitAudioContext;throw new G(e.AlphaTabErrorType.General,"AudioContext not found")}open(e){this.patchIosSampleRate(),this._context=this.createAudioContext(),"suspended"===this._context.state&&this.registerResumeHandler()}registerResumeHandler(){this._resumeHandler=(()=>{this.activate((()=>{this.unregisterResumeHandler()}))}).bind(this),document.body.addEventListener("touchend",this._resumeHandler,!1),document.body.addEventListener("click",this._resumeHandler,!1)}unregisterResumeHandler(){const e=this._resumeHandler;e&&(document.body.removeEventListener("touchend",e,!1),document.body.removeEventListener("click",e,!1))}play(){let e=this._context;this.activate(),this._buffer=e.createBuffer(2,ra.BufferSize,e.sampleRate),this._source=e.createBufferSource(),this._source.buffer=this._buffer,this._source.loop=!0}pause(){this._source&&(this._source.stop(0),this._source.disconnect()),this._source=null}destroy(){this.pause(),this._context?.close(),this._context=null,this.unregisterResumeHandler()}onSamplesPlayed(e){this.samplesPlayed.trigger(e)}onSampleRequest(){this.sampleRequest.trigger()}onReady(){this.ready.trigger()}}ra.BufferSize=4096,ra.PreferredSampleRate=44100;class na extends ra{constructor(){super(...arguments),this._audioNode=null,this._bufferCount=0,this._requestedBufferCount=0,this._outputBuffer=new Float32Array(0)}open(e){super.open(e),this._bufferCount=Math.floor(e*this.sampleRate/1e3/ra.BufferSize),this._circularBuffer=new aa(ra.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*ra.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*ra.BufferSize<t){for(let t=0;t<e;t++)this.onSampleRequest();this._requestedBufferCount+=e}}generateSound(e){let t=e.outputBuffer.getChannelData(0),i=e.outputBuffer.getChannelData(1),s=t.length+i.length,a=this._outputBuffer;a.length!==s&&(a=new Float32Array(s),this._outputBuffer=a);const r=this._circularBuffer.read(a,0,Math.min(a.length,this._circularBuffer.count));let n=0;for(let e=0;e<t.length;e++)t[e]=a[n++],i[e]=a[n++];this.onSamplesPlayed(r/Zt.AudioChannels),this.requestBuffers()}}class oa{constructor(e,t){this.loaded=e,this.total=t}}class ha{get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return J.logLevel}set logLevel(e){J.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Zt.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Zt.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Zt.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=wi.clamp(e,Zt.MinPlaybackSpeed,Zt.MaxPlaybackSpeed),this._playbackSpeed=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackSpeed",value:e})}get tickPosition(){return this._tickPosition}set tickPosition(e){e<0&&(e=0),this._tickPosition=e,this._synth.postMessage({cmd:"alphaSynth.setTickPosition",value:e})}get timePosition(){return this._timePosition}set timePosition(e){e<0&&(e=0),this._timePosition=e,this._synth.postMessage({cmd:"alphaSynth.setTimePosition",value:e})}get isLooping(){return this._isLooping}set isLooping(e){this._isLooping=e,this._synth.postMessage({cmd:"alphaSynth.setIsLooping",value:e})}get playbackRange(){return this._playbackRange}set playbackRange(e){e&&(e.startTick<0&&(e.startTick=0),e.endTick<0&&(e.endTick=0)),this._playbackRange=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackRange",value:e})}constructor(e,t){this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Ie.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 Ei,this.readyForPlayback=new Ei,this.finished=new Ei,this.soundFontLoaded=new Ei,this.soundFontLoadFailed=new Ci,this.midiLoaded=new Ci,this.midiLoadFailed=new Ci,this.stateChanged=new Ci,this.positionChanged=new Ci,this.midiEventsPlayed=new Ci,this.playbackRangeChanged=new Ci,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Ie.Paused,this._masterVolume=0,this._metronomeVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._output=e,this._output.ready.on(this.onOutputReady.bind(this)),this._output.samplesPlayed.on(this.onOutputSamplesPlayed.bind(this)),this._output.sampleRequest.on(this.onOutputSampleRequest.bind(this)),this._output.open(t.player.bufferTimeInMilliseconds);try{this._synth=Eo.createWebWorker(t)}catch(e){J.error("AlphaSynth","Failed to create WebWorker: "+e)}this._synth.addEventListener("message",this.handleWorkerMessage.bind(this),!1),this._synth.postMessage({cmd:"alphaSynth.initialize",sampleRate:this._output.sampleRate,logLevel:t.core.logLevel,bufferTimeInMilliseconds:t.player.bufferTimeInMilliseconds}),this.masterVolume=1,this.playbackSpeed=1,this.metronomeVolume=0}destroy(){this._synth.postMessage({cmd:"alphaSynth.destroy"})}play(){return this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.play"}),!0}pause(){this._synth.postMessage({cmd:"alphaSynth.pause"})}playPause(){this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.playPause"})}stop(){this._synth.postMessage({cmd:"alphaSynth.stop"})}playOneTimeMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.playOneTimeMidiFile",midi:ys.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,i){J.debug("AlphaSynth",`Start loading Soundfont from url ${e}`);let s=new XMLHttpRequest;s.open("GET",e,!0,null,null),s.responseType="arraybuffer",s.onload=e=>{let i=new Uint8Array(s.response);this.loadSoundFont(i,t)},s.onerror=e=>{J.error("AlphaSynth","Loading failed: "+e.message),this.soundFontLoadFailed.trigger(new Zs(e.message,s))},s.onprogress=e=>{J.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),i(new oa(e.loaded,e.total))},s.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:ys.midiFileToJsObject(e)})}applyTranspositionPitches(e){this._synth.postMessage({cmd:"alphaSynth.applyTranspositionPitches",transpositionPitches:JSON.stringify(Array.from(e.entries()))})}setChannelMute(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelMute",channel:e,mute:t})}resetChannelStates(){this._synth.postMessage({cmd:"alphaSynth.resetChannelStates"})}setChannelSolo(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelSolo",channel:e,solo:t})}setChannelVolume(e,t){t=Math.max(t,Zt.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 ai(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new Fi(t.events.map(ys.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new si(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new Li(this._playbackRange));break;case"alphaSynth.finished":this.finished.trigger();break;case"alphaSynth.soundFontLoaded":this.soundFontLoaded.trigger();break;case"alphaSynth.soundFontLoadFailed":this.soundFontLoadFailed.trigger(t.error);break;case"alphaSynth.midiLoaded":this.checkReadyForPlayback(),this.midiLoaded.trigger(new ai(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 la{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new Ci,this.partialRenderFinished=new Ci,this.partialLayoutFinished=new Ci,this.renderFinished=new Ci,this.postRenderFinished=new Ei,this.error=new Ci,this._api=e;try{this._worker=Eo.createWebWorker(t)}catch(e){return void J.error("Rendering",`Failed to create WebWorker: ${e}`)}this._worker.postMessage({cmd:"alphaTab.initialize",settings:this.serializeSettingsForWorker(t)}),this._worker.addEventListener("message",this.handleWorkerMessage.bind(this))}destroy(){this._worker.terminate()}updateSettings(e){this._worker.postMessage({cmd:"alphaTab.updateSettings",settings:this.serializeSettingsForWorker(e)})}serializeSettingsForWorker(e){const t=ys.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=Ns.fromJson(t.boundsLookup,this._api.score),this.boundsLookup.finish(),this.postRenderFinished.trigger();break;case"alphaTab.error":this.error.trigger(t.error)}}renderScore(e,t){let i=null==e?null:ys.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:i,trackIndexes:t,fontSizes:ws.FontSizeLookupTables})}}class ca{constructor(e,t,i,s){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=i,this.selectionWrapper=s}}e.WebPlatform=void 0,(Xe=e.WebPlatform||(e.WebPlatform={}))[Xe.Browser=0]="Browser",Xe[Xe.NodeJs=1]="NodeJs",Xe[Xe.BrowserModule=2]="BrowserModule";class da{static init(){var e;da._isRegistered||(da._isRegistered=!0,registerProcessor("alphatab",((e=class extends AudioWorkletProcessor{constructor(t){super(t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,J.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new aa(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){let t=e.data;switch(t.cmd){case bs.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case bs.CmdOutputResetSamples:this._circularBuffer.clear()}}process(e,t,i){if(1!==t.length&&2!==t[0].length)return!1;let s=t[0][0],a=t[0][1];if(!s||!a)return!0;let r=s.length+a.length,n=this._outputBuffer;n.length!==r&&(n=new Float32Array(r),this._outputBuffer=n);const o=this._circularBuffer.read(n,0,Math.min(n.length,this._circularBuffer.count));let h=0;for(let e=0;e<s.length;e++)s[e]=n[h++],a[e]=n[h++];return this.port.postMessage({cmd:bs.CmdOutputSamplesPlayed,samples:o/Zt.AudioChannels}),this.requestBuffers(),!0}requestBuffers(){const t=this._bufferCount/2|0;let i=t*e.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*e.BufferSize<i){for(let e=0;e<t;e++)this.port.postMessage({cmd:bs.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}da._isRegistered=!1;class ua extends ra{constructor(e){super(),this._worklet=null,this._bufferTimeInMilliseconds=0,this._settings=e}open(e){super.open(e),this._bufferTimeInMilliseconds=e,this.onReady()}play(){super.play();let e=this._context;Eo.createAudioWorklet(e,this._settings).then((()=>{this._worklet=new AudioWorkletNode(e,"alphatab",{numberOfOutputs:1,outputChannelCount:[2],processorOptions:{bufferTimeInMilliseconds:this._bufferTimeInMilliseconds}}),this._worklet.port.onmessage=this.handleMessage.bind(this),this._source.connect(this._worklet),this._source.start(0),this._worklet.connect(e.destination)}),(e=>{J.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){let t=e.data;switch(t.cmd){case bs.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case bs.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){this._worklet?.port.postMessage({cmd:bs.CmdOutputAddSamples,samples:e})}resetSamples(){this._worklet?.port.postMessage({cmd:bs.CmdOutputResetSamples})}}class pa extends ia{constructor(e,t,i){super(e),this._xscale=t,this._yscale=i}get width(){return this.element.offsetWidth/this._xscale}set width(e){this.element.style.width=e*this._xscale+"px"}get height(){return this.element.offsetHeight/this._yscale}set height(e){this.element.style.height=e>=0?e*this._yscale+"px":"100%"}setBounds(e,t,i,s){isNaN(e)&&(e=this.lastBounds.x),isNaN(t)&&(t=this.lastBounds.y),isNaN(i)?i=this.lastBounds.w:i/=this._xscale,isNaN(s)?s=this.lastBounds.h:s/=this._yscale,this.element.style.transform=`translate(${e}px, ${t}px) scale(${i}, ${s})`,this.element.style.transformOrigin="top left",this.lastBounds.x=e,this.lastBounds.y=t,this.lastBounds.w=i,this.lastBounds.h=s}}!function(e){e[e.LayoutDone=0]="LayoutDone",e[e.RenderRequested=1]="RenderRequested",e[e.RenderDone=2]="RenderDone",e[e.Detached=3]="Detached"}(Ye||(Ye={}));class ga{get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(Eo.bravuraFontChecker.checkForFontAvailability(),!Eo.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(J.debug("Font","All fonts loaded: "+this._fontCheckers.size),!0)}onFontLoaded(e){ws.generateFontLookup(e),this.areAllFontsLoaded()&&this.canRenderChanged.trigger()}constructor(t){if(this._fontCheckers=new Map,this._contents=null,this._file=null,this._totalResultCount=0,this._initialTrackIndexes=null,this._barToElementLookup=new Map,this._resultIdToElementLookup=new Map,this.rootContainerBecameVisible=new Ei,this.canRenderChanged=new Ei,this._highlightedElements=[],this._scrollContainer=null,Eo.webPlatform!==e.WebPlatform.Browser&&Eo.webPlatform!==e.WebPlatform.BrowserModule)throw new G(e.AlphaTabErrorType.General,"Usage of AlphaTabApi is only possible in browser environments. For usage in node use the Low Level APIs");t.classList.add("alphaTab"),this.rootContainer=new ia(t),this.areWorkersSupported="Worker"in window,Eo.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(t)}onElementVisibilityChanged(e){for(const t of e){const e=t.target;if(e===this.rootContainer.element)t.isIntersecting&&(this.rootContainerBecameVisible.trigger(),this._intersectionObserver.unobserve(this.rootContainer.element));else if("layoutResultId"in e&&this._api.settings.core.enableLazyLoading){const i=e;t.isIntersecting?i.renderedResultId!==i.layoutResultId?this._resultIdToElementLookup.has(i.layoutResultId)?i.resultState!==Ye.RenderRequested&&(i.resultState=Ye.RenderRequested,this._api.renderer.renderResult(i.layoutResultId)):e.replaceChildren():i.resultState===Ye.Detached&&(e.replaceChildren(...i.renderedResult),i.resultState=Ye.RenderDone):i.resultState===Ye.RenderDone&&(i.resultState=Ye.Detached,i.replaceChildren())}}}createWorkerRenderer(){return new la(this._api,this._api.settings)}initialize(t,i){let s;this._api=t,s=i instanceof Zi?i:ys.jsObjectToSettings(i);let a=this.getDataAttributes();Ki.fromJson(s,a),s.notation.notationMode===e.NotationMode.SongBook&&s.setSongBookModeSettings(),t.settings=s,this.setupFontCheckers(s),this._initialTrackIndexes=this.parseTracks(s.core.tracks),this._contents="";let r=t.container;s.core.tex&&(this._contents=r.element.innerHTML,r.element.innerHTML=""),this.createStyleElement(s),this._file=s.core.file}setupFontCheckers(e){this.registerFontChecker(e.display.resources.copyrightFont),this.registerFontChecker(e.display.resources.effectFont),this.registerFontChecker(e.display.resources.fingeringFont),this.registerFontChecker(e.display.resources.graceFont),this.registerFontChecker(e.display.resources.markerFont),this.registerFontChecker(e.display.resources.tablatureFont),this.registerFontChecker(e.display.resources.titleFont),this.registerFontChecker(e.display.resources.wordsFont),this.registerFontChecker(e.display.resources.barNumberFont),this.registerFontChecker(e.display.resources.fretboardNumberFont),this.registerFontChecker(e.display.resources.subTitleFont)}registerFontChecker(e){if(!this._fontCheckers.has(e.families.join(", "))){let t=new sa(e.families);this._fontCheckers.set(e.families.join(", "),t),t.fontLoaded.on(this.onFontLoaded.bind(this)),t.checkForFontAvailability()}}destroy(){this.rootContainer.element.innerHTML=""}createCanvasElement(){let e=document.createElement("div");return e.className="at-surface",e.style.fontSize="0",e.style.overflow="hidden",e.style.lineHeight="0",e.style.position="relative",new ia(e)}triggerEvent(e,t,i=null,s){let a=e.element;t="alphaTab."+t;let r=document.createEvent("CustomEvent"),n=s?s.mouseEvent:null;if(r.initCustomEvent(t,!1,!1,i),n&&(r.originalEvent=n),a.dispatchEvent(r),window&&"jQuery"in window){let e=window.jQuery,s=[];s.push(i),n&&s.push(n),e(a).trigger(t,s)}}load(e,t,i){if(e instanceof pe)return t(e),!0;if(e instanceof ArrayBuffer){let i=new Uint8Array(e);return t(ea.loadScoreFromBytes(i,this._api.settings)),!0}return e instanceof Uint8Array?(t(ea.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(ea.loadScoreAsync(e,t,i,this._api.settings),!0)}loadSoundFont(e,t){return!!this._api.player&&(e instanceof ArrayBuffer?(this._api.player.loadSoundFont(new Uint8Array(e),t),!0):e instanceof Uint8Array?(this._api.player.loadSoundFont(e,t),!0):"string"==typeof e&&(this._api.loadSoundFontFromUrl(e,t),!0))}initialRender(){this._api.renderer.preRender.on((e=>{this._totalResultCount=0,this._resultIdToElementLookup.clear(),this._barToElementLookup.clear()}));const e=()=>{this._api.renderer.width=0|this.rootContainer.width,this._api.renderer.updateSettings(this._api.settings),this._contents?(this._api.tex(this._contents,this._initialTrackIndexes??void 0),this._initialTrackIndexes=null):this._file&&ea.loadScoreAsync(this._file,(e=>{this._api.renderScore(e,this._initialTrackIndexes??void 0),this._initialTrackIndexes=null}),(e=>{this._api.onError(e)}),this._api.settings)};this.rootContainer.isVisible?e():this.rootContainerBecameVisible.on(e)}createStyleElement(e){let t=this._api.container.element.ownerDocument;Eo.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 i=e.length,s=e;for(let e=0;e<i;e++){let i=s[e],a=0;a="number"==typeof i?i:"index"in i?i.index:parseInt(i.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 i of Object.keys(t.dataset)){let s=t.dataset[i];try{let e=s;s=JSON.parse(e)}catch(e){""===s&&(s=null)}e.set(i,s)}else for(let i=0;i<t.attributes.length;i++){let s=t.attributes.item(i),a=s.nodeName;if(a.startsWith("data-")){let t=a.substr(5).split("-"),i=t[0];for(let e=1;e<t.length;e++)i+=t[e].substr(0,1).toUpperCase()+t[e].substr(1);let r=s.nodeValue;try{r=JSON.parse(r)}catch(e){""===r&&(r=null)}e.set(i,r)}}return e}beginUpdateRenderResults(e){if(!this._resultIdToElementLookup.has(e.id))return;const t=this._resultIdToElementLookup.get(e.id),i=e.renderResult;"string"==typeof i?t.innerHTML=i:"nodeType"in i&&t.replaceChildren(i),t.resultState=Ye.RenderDone,t.renderedResultId=e.id,t.renderedResult=Array.from(t.children)}beginAppendRenderResults(e){const t=this._api.canvasElement.element;if(e){let i;this._totalResultCount<t.childElementCount?i=t.childNodes.item(this._totalResultCount):(i=document.createElement("div"),t.appendChild(i)),i.style.zIndex="1",i.style.position="absolute",i.style.left=e.x+"px",i.style.top=e.y+"px",i.style.width=e.width+"px",i.style.height=e.height+"px",i.style.display="inline-block",i.layoutResultId=e.id,i.resultState=Ye.LayoutDone,delete i.renderedResultId,delete i.renderedResult,this._resultIdToElementLookup.set(e.id,i);for(let t=e.firstMasterBarIndex;t<=e.lastMasterBarIndex;t++)t>=0&&this._barToElementLookup.set(t,i);this._api.settings.core.enableLazyLoading&&(this._intersectionObserver.unobserve(i),this._intersectionObserver.observe(i)),this._totalResultCount++}else for(;t.childElementCount>this._totalResultCount;)this._api.settings.core.enableLazyLoading&&this._intersectionObserver.unobserve(t.lastChild),t.removeChild(t.lastElementChild)}createWorkerPlayer(){let t=null,i="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window&&this._api.settings.player.outputMode===e.PlayerOutputMode.WebAudioAudioWorklets?(J.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),t=new ha(new ua(this._api.settings),this._api.settings)):i&&(J.debug("Player","Will use webworkers for synthesizing and web audio api with ScriptProcessor for playback"),t=new ha(new na,this._api.settings)),t?t.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):J.error("Player","Player requires webworkers and web audio api, browser unsupported",null),t}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const i=this._barToElementLookup.get(t);if(i){let t=i.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 i=document.createElement("div");i.classList.add("at-selection");const s=this.createScalingElement(),a=this.createScalingElement();let r=s.element;r.classList.add("at-cursor-bar");let n=a.element;return n.classList.add("at-cursor-beat"),e.style.position="relative",e.style.textAlign="left",t.style.position="absolute",t.style.zIndex="1000",t.style.display="inline",t.style.pointerEvents="none",i.style.position="absolute",r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.willChange="transform",s.width=1,s.height=1,s.setBounds(0,0,1,1),n.style.position="absolute",n.style.transition="all 0s linear",n.style.left="0",n.style.top="0",n.style.willChange="transform",a.width=3,a.height=1,a.setBounds(0,0,1,1),e.insertBefore(t,e.firstChild),t.appendChild(i),t.appendChild(r),t.appendChild(n),new ca(new ia(t),s,a,new ia(i))}getOffset(e,t){let i=t.element,s=i.getBoundingClientRect(),a=s.top+i.ownerDocument.defaultView.pageYOffset,r=s.left+i.ownerDocument.defaultView.pageXOffset;if(e){let t=e.element,i=t.nodeName.toLowerCase();if("html"!==i&&"body"!==i){let i=this.getOffset(null,e);a=a+t.scrollTop-i.y,r=r+t.scrollLeft-i.x}}let n=new nt;return n.x=r,n.y=a,n.w=s.width,n.h=s.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 ia(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new pa(e,100,100);return t.width=1,t.height=1,t.setBounds(0,0,1,1),t}scrollToY(e,t,i){this.internalScrollToY(e.element,t,i)}scrollToX(e,t,i){this.internalScrollToX(e.element,t,i)}internalScrollToY(e,t,i){if(this._api.settings.player.nativeBrowserSmoothScroll)e.scrollTo({top:t,behavior:"smooth"});else{let s=e.scrollTop,a=t-s,r=0,n=t=>{0===r&&(r=t);let o=t-r,h=Math.min(o/i,1);e.scrollTop=s+a*h|0,o<i&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}internalScrollToX(e,t,i){if(this._api.settings.player.nativeBrowserSmoothScroll)e.scrollTo({left:t,behavior:"smooth"});else{let s=e.scrollLeft,a=t-s,r=0,n=t=>{0===r&&(r=t);let o=t-r,h=Math.min(o/i,1);e.scrollLeft=s+a*h|0,o<i&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}}class fa extends Ks{constructor(e,t){super(new ga(e),t),this.soundFontLoad=new Ci}tex(e,t){let i=this.uiFacade;super.tex(e,i.parseTracks(t))}print(t,i=null){let s=window.open("","","width=0,height=0"),a=s.document.createElement("div");t?a.style.width=t:this.settings.display.layoutMode===e.LayoutMode.Horizontal?a.style.width="297mm":a.style.width="210mm",s.document.write("\n <!DOCTYPE html>\n <html>\n <head>\n <style>\n .at-surface {\n width: auto !important;\n height: auto !important;\n }\n .at-surface > div {\n position: relative!important;\n left: auto !important;\n top: auto !important;\n break-inside: avoid;\n }\n </style>\n </head>\n <body></body>\n </html>\n ");const r=this.score;r&&(r.artist&&r.title?s.document.title=`${r.title} - ${r.artist}`:r.title&&(s.document.title=`${r.title}`)),s.document.body.appendChild(a);let n=void 0!==window.screenLeft?window.screenLeft:window.left,o=void 0!==window.screenTop?window.screenTop:window.top,h="innerWidth"in window?window.innerWidth:"clientWidth"in document.documentElement?document.documentElement.clientWidth:window.screen.width,l="innerHeight"in window?window.innerHeight:"clientHeight"in document.documentElement?document.documentElement.clientHeight:window.screen.height,c=a.offsetWidth+50,d=window.innerHeight,u=(h/2|0)-(c/2|0)+n,p=(l/2|0)-(d/2|0)+o;s.resizeTo(c,d),s.moveTo(u,p),s.focus();let g=ys.jsObjectToSettings(ys.settingsToJsObject(this.settings));g.core.enableLazyLoading=!1,g.core.useWorkers=!0,g.core.file=null,g.core.tracks=null,g.player.enableCursor=!1,g.player.enablePlayer=!1,g.player.enableElementHighlighting=!1,g.player.enableUserInteraction=!1,g.player.soundFont=null,g.display.scale=.8,g.display.stretchForce=.8,Ki.fromJson(g,i);let f=new fa(a,g);s.onunload=()=>{f.destroy()},f.renderer.postRenderFinished.on((()=>{s.print()})),f.renderTracks(this.tracks)}downloadMidi(e=Le.SingleTrackMultiChannel){if(!this.score)return;let t=new Rt;t.format=e;let i=new Fs(t,!0);new Hs(this.score,this.settings,i).generate();let s=t.toBinary(),a=this.score.title?`${this.score.title}.mid`:"File.mid",r=document.createElement("a");r.download=a;let n=new Blob([s],{type:"audio/midi"}),o=URL.createObjectURL(n);r.href=o,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}changeTrackMute(e,t){let i=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackMute(i,t)}changeTrackSolo(e,t){let i=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackSolo(i,t)}changeTrackVolume(e,t){let i=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackVolume(i,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 i of e)i>=0&&i<this.score.tracks.length&&t.push(this.score.tracks[i]);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 ma{constructor(){this._initListeners=[]}exec(e,t,i){if("string"!=typeof t&&(i=[t],t="init"),95===t.charCodeAt(0)||"exec"===t)return null;let s=new jQuery(e),a=s.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=[s,a].concat(i);return r.apply(this,e)}return J.error("Api","Method '"+t+"' does not exist on jQuery.alphaTab"),null}init(e,t,i){if(!t){t=new fa(e[0],i),e.data("alphaTab",t);for(let s of this._initListeners)s(e,t,i)}}destroy(e,t){e.removeData("alphaTab"),t.destroy()}print(e,t,i,s){t.print(i,s)}load(e,t,i,s){return t.load(i,s)}render(e,t){t.render()}renderScore(e,t,i,s){t.renderScore(i,s)}renderTracks(e,t,i){t.renderTracks(i)}invalidate(e,t){t.render()}tex(e,t,i,s){t.tex(i,s)}muteTrack(e,t,i,s){t.changeTrackMute(i,s)}soloTrack(e,t,i,s){t.changeTrackSolo(i,s)}trackVolume(e,t,i,s){t.changeTrackVolume(i,s)}loadSoundFont(e,t,i,s){t.loadSoundFont(i,s)}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,i){return"number"==typeof i&&(t.masterVolume=i),t.masterVolume}metronomeVolume(e,t,i){return"number"==typeof i&&(t.metronomeVolume=i),t.metronomeVolume}countInVolume(e,t,i){return"number"==typeof i&&(t.countInVolume=i),t.countInVolume}midiEventsPlayedFilter(e,t,i){return Array.isArray(i)&&(t.midiEventsPlayedFilter=i),t.midiEventsPlayedFilter}playbackSpeed(e,t,i){return"number"==typeof i&&(t.playbackSpeed=i),t.playbackSpeed}tickPosition(e,t,i){return"number"==typeof i&&(t.tickPosition=i),t.tickPosition}timePosition(e,t,i){return"number"==typeof i&&(t.timePosition=i),t.timePosition}loop(e,t,i){return"boolean"==typeof i&&(t.isLooping=i),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 ya{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.color=new me(255,255,255,255),this.lineWidth=1,this.font=new Ri("Arial",10,Ve.Plain),this.textAlign=E.Left,this.textBaseline=C.Top}destroy(){}beginRender(e,t){this.buffer=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${0|e}px" height="${0|t}px" class="at-surface-svg">\n`,this._currentPath="",this._currentPathIsEmpty=!0,this.textBaseline=C.Top}beginGroup(e){this.buffer+=`<g class="${e}">`}endGroup(){this.buffer+="</g>"}endRender(){return this.buffer+="</svg>",this.buffer}fillRect(e,t,i,s){i>0&&(this.buffer+=`<rect x="${0|e}" y="${0|t}" width="${i}" height="${s}" fill="${this.color.rgba}" />\n`)}strokeRect(e,t,i,s){this.buffer+=`<rect x="${0|e}" y="${0|t}" width="${i}" height="${s}" 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,i,s){this._currentPathIsEmpty=!1,this._currentPath+=` Q${e},${t},${i},${s}`}bezierCurveTo(e,t,i,s,a,r){this._currentPathIsEmpty=!1,this._currentPath+=` C${e},${t},${i},${s},${a},${r}`}fillCircle(e,t,i){this._currentPathIsEmpty=!1,this._currentPath+=` M${e-i},${t} A1,1 0 0,0 ${e+i},${t} A1,1 0 0,0 ${e-i},${t} z`,this.fill()}strokeCircle(e,t,i){this._currentPathIsEmpty=!1,this._currentPath+=` M${e-i},${t} A1,1 0 0,0 ${e+i},${t} A1,1 0 0,0 ${e-i},${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,i){if(""===e)return;let s=`<text x="${0|t}" y="${0|i}" style="stroke: none; font:${this.font.toCssString(this.settings.display.scale)}" ${this.getSvgBaseLine()}`;"#000000"!==this.color.rgba&&(s+=` fill="${this.color.rgba}"`),this.textAlign!==E.Left&&(s+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),s+=`>${ya.escapeText(e)}</text>`,this.buffer+=s}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 E.Left:return"start";case E.Center:return"middle";case E.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case C.Top:return'dominant-baseline="hanging"';case C.Bottom:return'dominant-baseline="bottom"';default:return""}}measureText(e){return e?ws.measureString(e,this.font.families,this.font.size,this.font.style,this.font.weight):0}onRenderFinished(){return null}beginRotate(e,t,i){this.buffer+='<g transform="translate('+e+" ,"+t+") rotate( "+i+')">'}endRotate(){this.buffer+="</g>"}}class ba extends ya{constructor(){super()}fillMusicFontSymbol(e,t,i,s,a){s!==P.None&&this.fillMusicFontSymbolText(e,t,i,`&#${s};`,a)}fillMusicFontSymbols(e,t,i,s,a){let r="";for(let e of s)e!==P.None&&(r+=`&#${e};`);this.fillMusicFontSymbolText(e,t,i,r,a)}fillMusicFontSymbolText(e,t,i,s,a){this.buffer+=`<g transform="translate(${e} ${t})" class="at" ><text`,this.buffer+=1!==i?` style="font-size: ${100*i}%; stroke:none"`:' style="stroke:none"',"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),a&&(this.buffer+=' text-anchor="'+this.getSvgTextAlignment(E.Center)+'"'),this.buffer+=`>${s}</text></g>`}}class Sa{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"}(qe||(qe={}));class wa extends zs{get isEmpty(){return!this.glyphs||0===this.glyphs.length}constructor(e,t){super(e,t),this.glyphs=null}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);let e=0;for(let t=0,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];i.renderer=this.renderer,i.doLayout(),e=Math.max(e,i.width)}this.width=e}addGlyph(e){this.glyphs||(this.glyphs=[]),this.renderer&&(e.renderer=this.renderer),this.glyphs.push(e)}paint(e,t,i){let s=this.glyphs;if(s&&0!==s.length)for(let a of s)a.paint(e+this.x,t+this.y,i)}}class _a extends wa{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 Ba extends wa{constructor(e,t,i){super(e,t),this.voice=i,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){const t=this.renderer.scale;let i=this.renderer.layoutingInfo.spaceToForce(e/t);this.scaleToForce(i)}scaleToForce(e){const t=this.renderer.scale;this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e)*t;let i=this.renderer.layoutingInfo.buildOnTimePositions(e),s=this.beatGlyphs;for(let e=0,a=s.length;e<a;e++){let r=s[e];if(r.beat.graceType===f.None)r.x=i.get(r.beat.absoluteDisplayStart)*t-r.onTimeX;else{const a=r.beat.graceGroup.beats[0].absoluteDisplayStart,n=r.beat.graceGroup.id;if(r.beat.graceGroup.isComplete&&i.has(a)){r.x=i.get(a)*t-r.onTimeX;let e=this.renderer.layoutingInfo.allGraceRods.get(n);const s=r.beat.graceGroup.beats[r.beat.graceGroup.beats.length-1].nextBeat,o=s?this.renderer.layoutingInfo.getPreBeatSize(s)+Js.GraceBeatPadding*this.renderer.scale:0;r.x-=o,r.x-=e[r.beat.graceIndex].postSpringWidth,r.x+=e[r.beat.graceIndex].graceBeatWidth;const h=e[r.beat.graceGroup.beats.length-1];r.x-=h.graceBeatWidth}else{let t=this.renderer.layoutingInfo.incompleteGraceRods.get(n);const i=t[r.beat.graceIndex].postSpringWidth-t[r.beat.graceIndex].preSpringWidth;e>0?0===r.beat.graceIndex?r.x=s[e-1].x+s[e-1].width:r.x=s[e-1].x+t[r.beat.graceIndex-1].postSpringWidth-t[r.beat.graceIndex-1].preSpringWidth-i:r.x=-i}}if(e>0){let t=r.x-s[e-1].x;s[e-1].scaleToWidth(t)}if(e===a-1){let e=this.width-s[s.length-1].x;r.scaleToWidth(e)}}}registerLayoutingInfo(e){e.updateVoiceSize(this.width);let t=this.beatGlyphs;for(let i of t)i.registerLayoutingInfo(e)}applyLayoutingInfo(e){let t=this.beatGlyphs;for(let i of t)i.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,i){i.color=0===this.voice.index?this.renderer.resources.mainGlyphColor:this.renderer.resources.secondaryGlyphColor;for(let s=0,a=this.beatGlyphs.length;s<a;s++)this.beatGlyphs[s].paint(e+this.x,t+this.y,i)}}Ba.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"}(Je||(Je={}));class Ta{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class ka{constructor(e){this._registeredAccidentals=new Map,this._appliedScoreLines=new Map,this._appliedScoreLinesByValue=new Map,this._notesByValue=new Map,this._beatLines=new Map,this.maxLineBeat=null,this.minLineBeat=null,this.maxLine=-1e3,this.minLine=-1e3,this._barRenderer=e,this._bar=e.bar}static getPercussionLine(e,t){return t<e.staff.track.percussionArticulations.length?e.staff.track.percussionArticulations[t].staffLine:K.getArticulationByValue(t)?.staffLine??0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case b.ForceDoubleFlat:t+=2;break;case b.ForceDoubleSharp:t-=2;break;case b.ForceFlat:t+=1;break;case b.ForceSharp:t-=1}return t}applyAccidental(e){const t=ka.getNoteValue(e);let i=e.hasQuarterToneOffset;return this.getAccidental(t,i,e.beat,!1,e)}applyAccidentalForValue(e,t,i,s){return this.getAccidental(t,i,e,s,null)}static computeLineWithoutAccidentals(e,t){let i=0;const s=ka.getNoteValue(t);if(e.staff.isPercussion)i=ka.getPercussionLine(e,s);else{const a=t?t.accidentalMode:b.Default;i=ka.calculateNoteLine(e,s,a)}return i}getAccidental(e,t,i,s,a=null){let r=Je.None,n=0;if(this._bar.staff.isPercussion)n=ka.getPercussionLine(this._bar,e);else{const i=a?a.accidentalMode:b.Default;n=ka.calculateNoteLine(this._bar,e,i);let s=this._bar.masterBar.keySignature+7,o=e%12,h=s<7?Je.Flat:Je.Sharp,l=ka.KeySignatureLookup[s][o],c=ka.AccidentalNotes[o];if(t)switch(r=c?h:Je.Natural,r){case Je.Natural:r=Je.NaturalQuarterNoteUp;break;case Je.Sharp:r=Je.SharpQuarterNoteUp;break;case Je.Flat:r=Je.FlatQuarterNoteUp}else{switch(i){case b.ForceSharp:r=Je.Sharp;break;case b.ForceDoubleSharp:r=Je.DoubleSharp;break;case b.ForceFlat:r=Je.Flat;break;case b.ForceDoubleFlat:r=Je.DoubleFlat;break;default:c?r=h:l&&(r=Je.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=Je.None:r!==Je.None?(this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===r&&(r=Je.None):l&&r===h&&(r=Je.None),r!==Je.None&&this._registeredAccidentals.set(n,r)):this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===Je.Natural?r=Je.None:(r=Je.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=i),(-1e3===this.maxLine||this.maxLine>n)&&(this.maxLine=n,this.maxLineBeat=i),s||this.registerLine(i,n),r}registerLine(e,t){let i;this._beatLines.has(e.id)?i=this._beatLines.get(e.id):(i=new Ta,this._beatLines.set(e.id,i)),(-1e3===i.minLine||t<i.minLine)&&(i.minLine=t),(-1e3===i.minLine||t>i.maxLine)&&(i.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,i){let s=t,a=e.masterBar.keySignature,r=e.clef,n=s%12,o=(s/12|0)-1,h=ka.OctaveSteps[r];return h-=o*ka.StepsPerOctave,h-=(Q.keySignatureIsSharp(a)||Q.keySignatureIsNatural(a)?ka.SharpNoteSteps:ka.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}}ka.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]],ka.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],ka.StepsPerOctave=7,ka.OctaveSteps=[38,32,30,26,38],ka.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],ka.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class va{constructor(){this.staffId="",this.up=0,this.down=0}}class xa{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 Na{get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}get hasLine(){return 1===this.beats.length&&this.beats[0].duration>p.Whole}get hasFlag(){return 1===this.beats.length&&!this.beats[0].isRest&&(this.beats[0].duration>p.Quarter||this.beats[0].graceType!==f.None)}constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=p.QuadrupleWhole,this.fingeringCount=0,this.hasTuplet=!1,this._firstBeatLowestNoteCompareValue=-1,this._firstBeatHighestNoteCompareValue=-1,this._lastBeatLowestNoteCompareValue=-1,this._lastBeatHighestNoteCompareValue=-1,this.lowestNoteInHelper=null,this._lowestNoteCompareValueInHelper=-1,this.highestNoteInHelper=null,this._highestNoteCompareValueInHelper=-1,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isGrace=!1,this.minRestLine=null,this.beatOfMinRestLine=null,this.maxRestLine=null,this.beatOfMaxRestLine=null,this.direction=Ce.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}getBeatLineX(e){return this.hasBeatLineX(e)?this.direction===Ce.Up?this._beatLineXPositions.get(e.index).up:this._beatLineXPositions.get(e.index).down:0}hasBeatLineX(e){return this._beatLineXPositions.has(e.index)}registerBeatLineX(e,t,i,s){let a=this.getOrCreateBeatPositions(t);a.staffId=e,a.up=i,a.down=s;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 va),this._beatLineXPositions.get(e.index)}finish(){this.direction=this.calculateDirection()}calculateDirection(){let e=null;if(this.voice?null!==this.preferredBeamDirection?e=this.preferredBeamDirection:this.voice.index>0?e=this.invert(Ce.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==f.None)&&(e=this.invert(Ce.Up)):e=Ce.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){let t=this._renderer.getNoteY(this.highestNoteInHelper,Qe.Center),i=this._renderer.getNoteY(this.lowestNoteInHelper,Qe.Center);if(null===e){const s=(t+i)/2;e=this.invert(this._renderer.middleYPosition<s?Ce.Up:Ce.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(Ce.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:return[2,2];case p.Whole:return[0,1];case p.Half:return[1,0];case p.Quarter:return[3,3];case p.Eighth:return[2,2];case p.Sixteenth:return[2,4];case p.ThirtySecond:return[4,4];case p.SixtyFourth:return[4,6];case p.OneHundredTwentyEighth:return[6,6];case p.TwoHundredFiftySixth:return[6,8]}return[0,0]}applyRest(e,t){if(this._lastNonRestBeat&&e.index>=this._lastNonRestBeat.index||this._firstNonRestBeat&&e.index<=this._firstNonRestBeat.index)return;let i=t,s=t;const a=Na.computeLineHeightsForRest(e.duration);i-=a[0],s+=a[1];const r=this.minRestLine,n=this.maxRestLine;(null===r||r>i)&&(this.minRestLine=i,this.beatOfMinRestLine=e),(null===n||n<s)&&(this.maxRestLine=s,this.beatOfMaxRestLine=e)}invert(e){return this.invertBeamDirection?e===Ce.Down?Ce.Up:Ce.Down:e}checkBeat(e){e.invertBeamDirection&&(this.invertBeamDirection=!0),this.voice||(this.voice=e.voice);let t=!1;if(0===this.beats.length)t=!0;else switch(this.beats[this.beats.length-1].beamingMode){case L.Auto:t=Na.canJoin(this.beats[this.beats.length-1],e);break;case L.ForceSplitToNext:t=!1;break;case L.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!==f.None&&(this.isGrace=!0),e.hasTuplet&&(this.hasTuplet=!0);let t=0;for(let i=0;i<e.notes.length;i++){let s=e.notes[i];s.leftHandFinger===m.Unknown&&s.rightHandFinger===m.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,i;this.voice&&e.isPercussion?(t=-ka.getPercussionLine(this.voice.bar,ka.getNoteValue(e)),i=t):(t=ka.getNoteValue(e),i=t,e.harmonicType!==y.None&&e.harmonicType!==y.Natural&&(i=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||i>this._firstBeatHighestNoteCompareValue)&&(this._firstBeatHighestNoteCompareValue=i)),(-1===this._lastBeatLowestNoteCompareValue||t<this._lastBeatLowestNoteCompareValue)&&(this._lastBeatLowestNoteCompareValue=t),(-1===this._lastBeatHighestNoteCompareValue||i>this._lastBeatHighestNoteCompareValue)&&(this._lastBeatHighestNoteCompareValue=i),(!this.lowestNoteInHelper||t<this._lowestNoteCompareValueInHelper)&&(this.lowestNoteInHelper=e,this._lowestNoteCompareValueInHelper=t),(!this.highestNoteInHelper||i>this._highestNoteCompareValueInHelper)&&(this.highestNoteInHelper=e,this._highestNoteCompareValueInHelper=i)}static canJoin(e,t){if(!e||!t||e.graceType!==t.graceType||e.graceType===f.BendGrace||t.graceType===f.BendGrace)return!1;if(e.graceType!==f.None&&t.graceType!==f.None)return!0;let i=e.voice.bar;if(i!==t.voice.bar)return!1;let s=e.playbackStart,a=t.playbackStart;if(!Na.canJoinDuration(e.duration)||!Na.canJoinDuration(t.duration))return s===a;if(e.tupletGroup!==t.tupletGroup)return!1;if(e.hasTuplet&&t.hasTuplet&&e.tupletGroup===t.tupletGroup&&e.tupletGroup.isFull)return!0;let r=z.QuarterTime;if(8===i.masterBar.timeSignatureDenominator)i.masterBar.timeSignatureNumerator%3==0&&(r+=z.QuarterTime/2|0);return((r+s)/r|0)===((r+a)/r|0)}static canJoinDuration(e){switch(e){case p.Whole:case p.Half:case p.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,i){return Q.getIndex(e.duration)-2-i>0&&Q.getIndex(t.duration)-2-i>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 Pa{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class Ea{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new Pa(e,t)),-1e3===this.topY)this.topY=e,this.bottomY=t;else{const i=Math.min(e,t),s=Math.max(e,t);i<this.topY&&(this.topY=i),s>this.bottomY&&(this.bottomY=s)}}}class Ca{constructor(){this.reservedLayoutAreasByDisplayTime=new Map,this.restDurationsByDisplayTime=new Map}getBeatMinMaxY(){let e=-1e3,t=-1e3;for(const i of this.reservedLayoutAreasByDisplayTime.values())-1e3===e?(e=i.topY,t=i.bottomY):(e>i.topY&&(e=i.topY),t<i.bottomY&&(t=i.bottomY));return-1e3===e?[0,0]:[e,t]}reserveBeatSlot(e,t,i){t!=i&&(this.reservedLayoutAreasByDisplayTime.has(e.displayStart)||this.reservedLayoutAreasByDisplayTime.set(e.displayStart,new Ea(e)),this.reservedLayoutAreasByDisplayTime.get(e.displayStart).addSlot(t,i),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,i){if(e.voice.index>0&&this.reservedLayoutAreasByDisplayTime.has(e.playbackStart)){const s=Na.computeLineHeightsForRest(e.duration).map((e=>e*i));let a=t-s[0],r=t+s[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-s[1]-s[0]:o.bottomY;let t=n+s[0]+s[1];const r=2*i;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 Ca}initialize(){var e=this._renderer,t=this._renderer.bar;let i=null,s=null;for(let a=0,r=t.voices.length;a<r;a++){let r=t.voices[a];this.beamHelpers.push([]),this.beamHelperLookup.push(new Map);for(let a=0,n=r.beats.length;a<n;a++){let n,o=r.beats[a];o.graceType!==f.None?n=s:(n=i,s=null),n&&n.checkBeat(o)||(n&&n.finish(),n=new Na(t.staff,e),n.checkBeat(o),o.graceType!==f.None?s=n:i=n,this.beamHelpers[r.index].push(n)),this.beamHelperLookup[r.index].set(o.index,n)}i&&i.finish(),s&&s.finish(),i=null,s=null}}getBeamingHelperForBeat(e){return this.beamHelperLookup[e.voice.index].get(e.index)}}class La extends Us{constructor(e,t,i){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=i}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=La.FretSpacing*e:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+(La.Frets-1)*La.FretSpacing*e+2*La.Padding*e,this.width=this._firstFretSpacing+(this._chord.staff.tuning.length-1)*La.StringSpacing*e+2*La.Padding*e}paint(e,t,i){e+=this.x+La.Padding*this.scale+this._firstFretSpacing,t+=this.y;let s=this.width-2*La.Padding*this.scale+this.scale-this._firstFretSpacing,a=La.StringSpacing*this.scale,r=La.FretSpacing*this.scale,n=this.renderer.resources,o=La.CircleRadius*this.scale,h=i.textAlign,l=i.textBaseline;i.font=n.effectFont,i.textAlign=E.Center,i.textBaseline=C.Top,this._chord.showName&&i.fillText(this._chord.name,e+this.width/2,t+n.effectFont.size/2),t+=this._textRow,e+=a/2,i.font=n.fretboardNumberFont,i.textBaseline=C.Middle;for(let s=0;s<this._chord.staff.tuning.length;s++){let r=e+s*a,n=t+this._fretRow/2,o=this._chord.strings[this._chord.staff.tuning.length-s-1];o<0?i.fillMusicFontSymbol(r,n,this.scale,P.FretboardX,!0):0===o?i.fillMusicFontSymbol(r,n,this.scale,P.FretboardO,!0):(o-=this._chord.firstFret-1,i.fillText(o.toString(),r,n))}t+=this._fretRow;for(let s=0;s<this._chord.staff.tuning.length;s++){let n=e+s*a;i.fillRect(n,t,1,r*La.Frets+this.scale)}this._chord.firstFret>1&&(i.textAlign=E.Left,i.fillText(this._chord.firstFret.toString(),e-this._firstFretSpacing,t+r/2)),i.fillRect(e,t-this.scale,s,2*this.scale);for(let a=0;a<=La.Frets;a++){let n=t+a*r;i.fillRect(e,n,s,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 s=0;s<this._chord.strings.length;s++){let n=this._chord.strings[s];if(n>0){if(n-=this._chord.firstFret,c.has(n)){let e=c.get(n);(-1===e[0]||s<e[0])&&(e[0]=s),(-1===e[1]||s>e[1])&&(e[1]=s)}let h=t+n*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-s-1)*a;i.fillCircle(l,h,o)}}for(const[s,n]of c){let h=t+s*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;i.fillRect(l,h-o,c-l,2*o)}i.textAlign=h,i.textBaseline=l}}La.Padding=5,La.Frets=5,La.CircleRadius=2.5,La.StringSpacing=10,La.FretSpacing=12;class Ma extends wa{constructor(e,t,i=E.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=i}doLayout(){let e=0;switch(this._align){case E.Left:e=0;break;case E.Center:e=(this.width-this._glyphWidth)/2;break;case E.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 Ia extends wa{constructor(e,t,i=E.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=i}doLayout(){let e=0,t=0,i=2*Ia.Padding*this.scale;this._rows=[];let s=new Ma(e,t,this._align);s.width=this.width;for(let a of this.glyphs)e+a.width<this.width?(s.addGlyphToRow(a),e+=a.width):(s.isEmpty||(s.doLayout(),this._rows.push(s),t+=s.height+i),e=0,s=new Ma(e,t,this._align),s.width=this.width,s.addGlyphToRow(a),e+=a.width);s.isEmpty||(s.doLayout(),this._rows.push(s),t+=s.height+i),this.height=t+i}paint(e,t,i){for(let s of this._rows)s.paint(e+this.x,t+this.y+Ia.Padding*this.scale,i)}}Ia.Padding=3;class Da extends Ia{constructor(e,t){super(e,t)}addChord(e){if(e.strings.length>0){let t=new La(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}}class Aa extends Us{constructor(e,t,i,s,a=E.Left){super(e,t),this._lines=i.split("\n"),this.font=s,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,i){let s=i.color;i.color=s,i.font=this.font;let a=i.textAlign;i.textAlign=this.textAlign;let r=t+this.y;for(let t of this._lines)i.fillText(t,e+this.x,r),r+=this.font.size;i.textAlign=a}}class Ra{get staveId(){return this._factory.staffId}constructor(e,t,i){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=i,this.trackIndex=e,this.modelStaff=t}getSharedLayoutData(e,t){return this._sharedLayoutData.has(e)?this._sharedLayoutData.get(e):t}setSharedLayoutData(e,t){this._sharedLayoutData.set(e,t)}get isInAccolade(){return this._factory.isInAccolade}get isRelevantForBoundsLookup(){return this._factory.isRelevantForBoundsLookup}registerStaffTop(e){this.staveTop=e}registerStaffBottom(e){this.staveBottom=e}addBarRenderer(e){e.staff=this,e.index=this.barRenderers.length,e.reLayout(),this.barRenderers.push(e),this.staveGroup.layout.registerBarRenderer(this.staveId,e)}addBar(e,t){let i;i=e?this._factory.create(this.staveGroup.layout.renderer,e):new qa(this.staveGroup.layout.renderer,e),i.staff=this,i.index=this.barRenderers.length,i.layoutingInfo=t,i.doLayout(),i.registerLayoutingInfo();const s=i.barDisplayWidth;s>0&&this.staveGroup.layout.systemsLayoutMode==je.FromModelWithWidths&&(i.width=s),this.barRenderers.push(i),e&&this.staveGroup.layout.registerBarRenderer(this.staveId,i)}revertLastBar(){let e=this.barRenderers[this.barRenderers.length-1];return this.barRenderers.splice(this.barRenderers.length-1,1),this.staveGroup.layout.unregisterBarRenderer(this.staveId,e),e}scaleToWidth(e){this._sharedLayoutData=new Map;let t=this.topOverflow,i=0;switch(this.staveGroup.layout.systemsLayoutMode){case je.Automatic:let s=(e-this.staveGroup.computedWidth)/this.barRenderers.length;for(const e of this.barRenderers){e.x=i,e.y=this.topSpacing+t;let a=e.computedWidth+s;e.scaleToWidth(a),i+=e.width}break;case je.FromModelWithScale:e-=this.staveGroup.accoladeSpacing;const a=this.staveGroup.totalBarDisplayScale;for(const s of this.barRenderers){s.x=i,s.y=this.topSpacing+t;const r=s.barDisplayScale*e/a;s.scaleToWidth(r),i+=s.width}break;case je.FromModelWithWidths:for(const e of this.barRenderers){e.x=i,e.y=this.topSpacing+t;const s=e.barDisplayWidth;s>0?e.scaleToWidth(s):e.scaleToWidth(e.computedWidth),i+=e.width}}}get topOverflow(){let e=0;for(let t=0,i=this.barRenderers.length;t<i;t++){let i=this.barRenderers[t];i.topOverflow>e&&(e=i.topOverflow)}return e}get bottomOverflow(){let e=0;for(let t=0,i=this.barRenderers.length;t<i;t++){let i=this.barRenderers[t];i.bottomOverflow>e&&(e=i.bottomOverflow)}return e}finalizeStaff(){this.height=0;let e=!1,t=this.topOverflow;for(let i=0;i<this.barRenderers.length;i++)this.barRenderers[i].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[i].height),this.barRenderers[i].finalizeRenderer()&&(e=!0);if(e){t=this.topOverflow;for(let e=0;e<this.barRenderers.length;e++)this.barRenderers[e].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[e].height),this.barRenderers[e].finalizeRenderer()}this.height>0&&(this.height+=this.topSpacing+t+this.bottomOverflow+this.bottomSpacing)}paint(e,t,i,s,a){if(0!==this.height&&0!==a)for(let r=s,n=Math.min(s+a,this.barRenderers.length);r<n;r++)this.barRenderers[r].paint(e+this.x,t+this.y,i)}}class Oa{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 Ga{constructor(){this._timeSortedSprings=[],this._xMin=0,this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,this.version=0,this.preBeatSizes=new Map,this.onBeatSizes=new Map,this.onBeatCenterX=new Map,this.preBeatSize=0,this.postBeatSize=0,this.voiceSize=0,this.minStretchForce=0,this.totalSpringConstant=0,this.incompleteGraceRods=new Map,this.allGraceRods=new Map,this.springs=new Map,this.height=0}updateVoiceSize(e){e>this.voiceSize&&(this.voiceSize=e,this.version++)}setPreBeatSize(e,t){(!this.preBeatSizes.has(e.id)||this.preBeatSizes.get(e.id)<t)&&(this.preBeatSizes.set(e.id,t),this.version++)}getPreBeatSize(e){return this.preBeatSizes.has(e.id)?this.preBeatSizes.get(e.id):0}setOnBeatSize(e,t){(!this.onBeatSizes.has(e.id)||this.onBeatSizes.get(e.id)<t)&&(this.onBeatSizes.set(e.id,t),this.version++)}getOnBeatSize(e){return this.onBeatSizes.has(e.id)?this.onBeatSizes.get(e.id):0}getBeatCenterX(e){return this.onBeatCenterX.has(e.id)?this.onBeatCenterX.get(e.id):0}setBeatCenterX(e,t){(!this.onBeatCenterX.has(e.id)||this.onBeatCenterX.get(e.id)<t)&&(this.onBeatCenterX.set(e.id,t),this.version++)}updateMinStretchForce(e){this.minStretchForce<e&&(this.minStretchForce=e)}addSpring(e,t,i,s,a){let r;if(this.version++,this.springs.has(e))r=this.springs.get(e),r.postSpringWidth<a&&(r.postSpringWidth=a),r.graceBeatWidth<i&&(r.graceBeatWidth=i),r.preBeatWidth<s&&(r.preBeatWidth=s),t<r.smallestDuration&&(r.smallestDuration=t),t>r.longestDuration&&(r.longestDuration=t),r.allDurations.add(t);else{if(r=new Oa,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=i,r.preBeatWidth=s,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,i){let s=e.absoluteDisplayStart;if(e.graceType!==f.None){const a=e.graceGroup.id;this.allGraceRods.has(a)||this.allGraceRods.set(a,new Array(e.graceGroup.beats.length)),e.graceGroup.isComplete||this.incompleteGraceRods.has(a)||this.incompleteGraceRods.set(a,new Array(e.graceGroup.beats.length));let r=this.allGraceRods.get(a)[e.graceIndex];if(r)r.postSpringWidth<i&&(r.postSpringWidth=i),r.preBeatWidth<t&&(r.preBeatWidth=t);else{const r=new Oa;r.timePosition=s,r.postSpringWidth=i,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(s,e.displayDuration,a,t,i)}}finish(){for(const[e,t]of this.allGraceRods){let i=0;if(this.incompleteGraceRods.has(e))for(const e of t)i+=e.preBeatWidth,e.graceBeatWidth=i,i+=e.postSpringWidth;else for(let e=t.length-1;e>=0;e--)t[e].graceBeatWidth=i,i-=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,i=this._timeSortedSprings;if(0===i.length)return this.totalSpringConstant=-1,void(this.minStretchForce=-1);for(let e=0;e<i.length;e++){let s=i[e],a=0;if(e===i.length-1)a=s.longestDuration;else{let t=i[e+1];a=Math.abs(t.timePosition-s.timePosition)}s.springConstant=this.calculateSpringConstant(s,a),t+=1/s.springConstant}this.totalSpringConstant=1/t,this.minStretchForce=0;for(let e=0;e<i.length;e++){let t=i[e],s=0;if(e===i.length-1)s=t.postSpringWidth;else{let a=i[e+1];s=t.postSpringWidth+a.preSpringWidth}0===e&&(s+=t.preSpringWidth);let a=s*t.springConstant;this.updateMinStretchForce(a)}}paint(e,t,i){}calculateSpringConstant(e,t){return t<=0&&(t=z.toTicks(p.SixtyFourth)),0===e.smallestDuration&&(e.smallestDuration=t),e.smallestDuration/t*(1/((1+.85*Math.log2(t/Ga.MinDuration))*Ga.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(Q.isAlmostEqualTo(this._onTimePositionsForce,e)&&this._onTimePositions)return this._onTimePositions;this._onTimePositionsForce=e;let t=new Map;this._onTimePositions=t;let i=this._timeSortedSprings;if(0===i.length)return t;let s=i[0].preSpringWidth;for(let a=0;a<i.length;a++)t.set(i[a].timePosition,s),s+=this.calculateWidth(e,i[a].springConstant);return t}}Ga.MinDuration=30,Ga.MinDurationWidth=7;class Va{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.renderers=[]}}class Ha{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 Wa{constructor(){this._allStaves=[],this._firstStaffInAccolade=null,this._lastStaffInAccolade=null,this._accoladeSpacingCalculated=!1,this.x=0,this.y=0,this.index=0,this.accoladeSpacing=0,this.isFull=!1,this.width=0,this.computedWidth=0,this.totalBarDisplayScale=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[]}get firstBarIndex(){return this.masterBarsRenderers[0].masterBar.index}get lastBarIndex(){return this.masterBarsRenderers[this.masterBarsRenderers.length-1].masterBar.index}addMasterBarRenderers(e,t){if(0===e.length)return null;this.masterBarsRenderers.push(t),this.calculateAccoladeSpacing(e),t.layoutingInfo.preBeatSize=0;let i=0;for(let e=0,s=this.staves.length;e<s;e++){let s=this.staves[e];for(let e=0,a=s.staves.length;e<a;e++){let a=s.staves[e],r=t.renderers[i++];a.addBarRenderer(r)}}return this.updateWidthFromLastBar(),t}addBars(e,t){if(0===e.length)return null;let i=new Va;i.layoutingInfo=new Ga,i.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(i),this.calculateAccoladeSpacing(e);let s=i.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,s);let n=a.barRenderers[a.barRenderers.length-1];i.renderers.push(n),n.isLinkedToPrevious&&(i.isLinkedToPrevious=!0),n.canWrap||(i.canWrap=!1)}return s.finish(),i.width=this.updateWidthFromLastBar(),i}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,i=0;for(let e=0,s=this._allStaves.length;e<s;e++){let s=this._allStaves[e].revertLastBar();const a=s.computedWidth;a>t&&(t=a);const r=s.barDisplayScale;r>i&&(i=r)}return this.width-=t,this.computedWidth-=t,this.totalBarDisplayScale-=i,e}return null}updateWidthFromLastBar(){let e=0,t=0;for(let i=0,s=this._allStaves.length;i<s;i++){let s=this._allStaves[i];const a=s.barRenderers[s.barRenderers.length-1];a.applyLayoutingInfo(),a.computedWidth>e&&(e=a.computedWidth);const r=a.barDisplayScale;r>t&&(t=r)}return this.width+=e,this.computedWidth+=e,this.totalBarDisplayScale+=t,e}calculateAccoladeSpacing(e){if(!this._accoladeSpacingCalculated&&0===this.index)if(this._accoladeSpacingCalculated=!0,this.layout.renderer.settings.notation.isNotationElementVisible(v.TrackNames)){let t=this.layout.renderer.canvas,i=this.layout.renderer.settings.display.resources.effectFont;t.font=i;for(let i of e)this.accoladeSpacing=Math.ceil(Math.max(this.accoladeSpacing,t.measureText(i.shortName)));this.accoladeSpacing*=this.layout.scale,this.accoladeSpacing+=2*Wa.AccoladeLabelSpacing*this.layout.scale,this.width+=this.accoladeSpacing,this.computedWidth+=this.accoladeSpacing}else this.accoladeSpacing=0}getStaveTrackGroup(e){for(let t=0,i=this.staves.length;t<i;t++){let i=this.staves[t];if(i.track===e)return i}return null}addStaff(e,t){let i=this.getStaveTrackGroup(e);i||(i=new Ha(this,e),this.staves.push(i)),t.staveTrackGroup=i,t.staveGroup=this,t.index=this._allStaves.length,this._allStaves.push(t),i.addStaff(t),t.isInAccolade&&(this._firstStaffInAccolade||(this._firstStaffInAccolade=t,t.isFirstInAccolade=!0),i.firstStaffInAccolade||(i.firstStaffInAccolade=t),this._lastStaffInAccolade||(this._lastStaffInAccolade=t,t.isLastInAccolade=!0),this._lastStaffInAccolade&&(this._lastStaffInAccolade.isLastInAccolade=!1),this._lastStaffInAccolade=t,this._lastStaffInAccolade.isLastInAccolade=!0,i.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,i=this._allStaves.length;t<i;t++)this._allStaves[t].scaleToWidth(e);this.width=e}paint(e,t,i){this.paintPartial(e+this.x,t+this.y,i,0,this.masterBarsRenderers.length)}paintPartial(e,t,i,s,a){for(let r=0,n=this._allStaves.length;r<n;r++)this._allStaves[r].paint(e,t,i,s,a);let r=this.layout.renderer.settings.display.resources;if(this.staves.length>0&&0===s){if(i.color=r.barSeparatorColor,this._firstStaffInAccolade&&this._lastStaffInAccolade){let s=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;i.beginPath(),i.moveTo(r,s),i.lineTo(r,a),i.stroke()}i.font=r.effectFont;for(let s=0,a=this.staves.length;s<a;s++){let a=this.staves[s];if(a.firstStaffInAccolade&&a.lastStaffInAccolade){let s=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=s-4*o,c=r+4*o;0===this.index&&this.layout.renderer.settings.notation.isNotationElementVisible(v.TrackNames)&&i.fillText(a.track.shortName,e+Wa.AccoladeLabelSpacing*this.layout.scale,s),i.fillRect(n-h-o,l,o,c-l);let d=n-h-o,u=n+2*o;i.beginPath(),i.moveTo(d,l),i.bezierCurveTo(d,l,d,l,u,l-o),i.bezierCurveTo(n,l+o,d,l+o,d,l+o),i.closePath(),i.fill(),i.beginPath(),i.moveTo(d,c),i.bezierCurveTo(d,c,n,c,u,c+o),i.bezierCurveTo(n,c-o,d,c-o,d,c-o),i.closePath(),i.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 i=this._allStaves[this._allStaves.length-1],s=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+i.y+i.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-s,l=t+this.y+i.y+i.height-i.bottomSpacing-i.bottomOverflow-(i.barRenderers.length>0?i.barRenderers[0].bottomPadding:0)-o,c=n-r,d=this.x+this._firstStaffInAccolade.x,u=new xs;u.visualBounds=new nt,u.visualBounds.x=e,u.visualBounds.y=t+this.y,u.visualBounds.w=this.width,u.visualBounds.h=this.height,u.realBounds=new nt,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 i of this.staves[e].stavesRelevantForBoundsLookup)for(let e of i.barRenderers){let a;p.has(e.bar.masterBar.index)?a=p.get(e.bar.masterBar.index):(a=new ks,a.index=e.bar.masterBar.index,a.isFirstOfLine=e.isFirstOfLine,a.realBounds=new nt,a.realBounds.x=d+e.x,a.realBounds.y=r,a.realBounds.w=e.width,a.realBounds.h=c,a.visualBounds=new nt,a.visualBounds.x=d+e.x,a.visualBounds.y=s,a.visualBounds.w=e.width,a.visualBounds.h=h,a.lineAlignedBounds=new nt,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+i.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}}Wa.AccoladeLabelSpacing=10;class za extends wa{constructor(e,t,i,s){super(e,t),this._tuning=i,this._trackLabel=s,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,i=this.renderer.resources;this.height=0;const s=15*t;this._trackLabel.length>0&&(this.addGlyph(new Aa(0,this.height,this._trackLabel,i.effectFont,E.Left)),this.height+=s),this.addGlyph(new Aa(0,this.height,e.name,i.effectFont,E.Left));const a=64*t;if(this.renderer.scoreRenderer.canvas.font=i.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+=s,!e.isStandard){const r=.7,n=za.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=P.GuitarString0+(c+1);this.addGlyph(new Xs(h,l+n/1.2,r,d));const u="= "+be.getTextForTuning(e.tunings[c],!1);this.addGlyph(new Aa(h+n+1*t,l,u,i.effectFont,E.Left)),l+=s,c===o-1&&(l=this.height,h+=a)}this.height+=o*s}this.width+=15*t}}za.CircleNumberHeight=20;class Ua extends Ia{constructor(e,t){super(e,t,E.Left)}addTuning(e,t){if(e.tunings.length>0){let i=new za(0,0,e,t);i.renderer=this.renderer,i.doLayout(),this.glyphs.push(i)}}}class Xa{constructor(e,t){this.args=e,this.renderCallback=t}}!function(e){e[e.Automatic=0]="Automatic",e[e.FromModelWithScale=1]="FromModelWithScale",e[e.FromModelWithWidths=2]="FromModelWithWidths"}(je||(je={}));class Ya{constructor(e){this._barRendererLookup=new Map,this.width=0,this.height=0,this.scoreInfoGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this.systemsLayoutMode=je.Automatic,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t)),this.firstBarIndex=t;let 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.lastBarIndex=i,this.createScoreInfoGlyphs(),this.doLayoutAndRender()}registerPartial(e,t){this.renderer.settings.core.enableLazyLoading?(this._lazyPartials.set(e.id,new Xa(e,t)),this.renderer.partialLayoutFinished.trigger(e)):(this.renderer.partialLayoutFinished.trigger(e),this.internalRenderLazyPartial(e,t))}internalRenderLazyPartial(e,t){const i=this.renderer.canvas;i.beginRender(e.width,e.height),t(i),e.renderResult=i.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(){J.debug("ScoreLayout","Creating score info glyphs");let e=this.renderer.settings.notation,t=this.renderer.score,i=this.renderer.settings.display.resources;this.scoreInfoGlyphs=new Map,t.title&&e.isNotationElementVisible(v.ScoreTitle)&&this.scoreInfoGlyphs.set(v.ScoreTitle,new Aa(0,0,t.title,i.titleFont,E.Center)),t.subTitle&&e.isNotationElementVisible(v.ScoreSubTitle)&&this.scoreInfoGlyphs.set(v.ScoreSubTitle,new Aa(0,0,t.subTitle,i.subTitleFont,E.Center)),t.artist&&e.isNotationElementVisible(v.ScoreArtist)&&this.scoreInfoGlyphs.set(v.ScoreArtist,new Aa(0,0,t.artist,i.subTitleFont,E.Center)),t.album&&e.isNotationElementVisible(v.ScoreAlbum)&&this.scoreInfoGlyphs.set(v.ScoreAlbum,new Aa(0,0,t.album,i.subTitleFont,E.Center)),t.music&&t.music===t.words&&e.isNotationElementVisible(v.ScoreWordsAndMusic)?this.scoreInfoGlyphs.set(v.ScoreWordsAndMusic,new Aa(0,0,"Music and Words by "+t.words,i.wordsFont,E.Center)):(t.music&&e.isNotationElementVisible(v.ScoreMusic)&&this.scoreInfoGlyphs.set(v.ScoreMusic,new Aa(0,0,"Music by "+t.music,i.wordsFont,E.Right)),t.words&&e.isNotationElementVisible(v.ScoreWords)&&this.scoreInfoGlyphs.set(v.ScoreWords,new Aa(0,0,"Words by "+t.words,i.wordsFont,E.Left)));const s=new qa(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);if(e.isNotationElementVisible(v.GuitarTuning)){let e=[];for(let t of this.renderer.tracks)for(let i of t.staves)if(!i.isPercussion&&i.isStringed&&i.tuning.length>0&&i.showTablature){e.push(i);break}if(e.length>0){this.tuningGlyph=new Ua(0,0),this.tuningGlyph.renderer=s;for(const t of e)this.tuningGlyph.addTuning(t.stringTuning,e.length>1?t.track.name:"")}}if(e.isNotationElementVisible(v.ChordDiagrams)){this.chordDiagrams=new Da(0,0),this.chordDiagrams.renderer=s;let e=new Set;for(let t of this.renderer.tracks)for(let i of t.staves){const t=i.chords;if(t)for(const[,i]of t)e.has(i.uniqueId)||i.showDiagram&&(e.add(i.uniqueId),this.chordDiagrams.addChord(i))}}}get scale(){return this.renderer.settings.display.scale}createEmptyStaveGroup(){let t=new Wa;t.layout=this;for(let i=0;i<this.renderer.tracks.length;i++){let s=this.renderer.tracks[i],a=!1;for(let e of s.staves)if(e.showStandardNotation){a=!0;break}for(let r=0;r<s.staves.length;r++){let n,o=s.staves[r];if(o.isPercussion)n=e.StaveProfile.Score;else if(this.renderer.settings.display.staveProfile!==e.StaveProfile.Default)n=this.renderer.settings.display.staveProfile;else if(o.showTablature&&o.showStandardNotation)n=e.StaveProfile.ScoreTab;else if(o.showTablature)n=a?e.StaveProfile.TabMixed:e.StaveProfile.Tab;else{if(!o.showStandardNotation)continue;n=e.StaveProfile.Score}let h=Eo.staveProfiles.get(n);for(let e of h)e.canCreate(s,o)&&t.addStaff(s,new Ra(i,o,e))}}return t}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 i=t.id;return this._barRendererLookup.has(e)&&this._barRendererLookup.get(e).has(i)?this._barRendererLookup.get(e).get(i):null}layoutAndRenderAnnotation(e){let t="rendered by alphaTab",i=this.renderer.settings.display.resources,s=12*this.renderer.settings.display.scale,a=Math.floor(2*s);const r=new _s,n=Ri.withFamilyList(i.copyrightFont.families,s,Ve.Plain,He.Bold);this.renderer.canvas.font=n;const o=Eo.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=i.mainGlyphColor,e.font=n,e.textAlign=E.Left,e.fillText(t,0,s)})),e+a}}!function(e){e[e.TopWithStem=0]="TopWithStem",e[e.Top=1]="Top",e[e.Center=2]="Center",e[e.Bottom=3]="Bottom",e[e.BottomWithStem=4]="BottomWithStem"}(Qe||(Qe={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}($e||($e={}));class qa{get nextRenderer(){return this.bar&&this.bar.nextBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.nextBar):null}get previousRenderer(){return this.bar&&this.bar.previousBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.previousBar):null}constructor(e,t){this._preBeatGlyphs=new _a,this._voiceContainers=new Map,this._postBeatGlyphs=new _a,this._ties=[],this.x=0,this.y=0,this.width=0,this.computedWidth=0,this.height=0,this.index=0,this.topOverflow=0,this.bottomOverflow=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this._wasFirstOfLine=!1,this._appliedLayoutingInfo=0,this.isFinalized=!1,this.topPadding=0,this.bottomPadding=0,this.scoreRenderer=e,this.bar=t,t&&(this.helpers=new Fa(this))}registerTies(e){this._ties.push(...e)}get middleYPosition(){return 0}registerOverflowTop(e){return e>this.topOverflow&&(this.topOverflow=e,!0)}registerOverflowBottom(e){return e>this.bottomOverflow&&(this.bottomOverflow=e,!0)}scaleToWidth(e){let t=e-this._preBeatGlyphs.width-this._postBeatGlyphs.width;for(const e of this._voiceContainers.values())e.scaleToWidth(t);this._postBeatGlyphs.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width+t,this.width=e}get resources(){return this.settings.display.resources}get settings(){return this.scoreRenderer.settings}get scale(){return this.settings.display.scale}get barDisplayScale(){return this.staff.staveGroup.staves.length>1?this.bar.masterBar.displayScale:this.bar.displayScale}get barDisplayWidth(){return this.staff.staveGroup.staves.length>1?this.bar.masterBar.displayWidth:this.bar.displayWidth}get isFirstOfLine(){return 0===this.index}get isLast(){return!this.bar||this.bar.index===this.scoreRenderer.layout.lastBarIndex}registerLayoutingInfo(){let e=this.layoutingInfo,t=this._preBeatGlyphs.width;e.preBeatSize<t&&(e.preBeatSize=t);for(const t of this._voiceContainers.values())t.registerLayoutingInfo(e),t.x,t.width;let i=this._postBeatGlyphs.width;e.postBeatSize<i&&(e.postBeatSize=i)}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 i=t.x+t.width;e<i&&(e=i)}this._postBeatGlyphs.x=Math.floor(e),this._postBeatGlyphs.width=this.layoutingInfo.postBeatSize,this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.computedWidth=this.width;const t=this.barDisplayWidth;return t>0&&this.scoreRenderer.layout.systemsLayoutMode==je.FromModelWithWidths&&(this.width=t,this.computedWidth=t),!0}finalizeRenderer(){this.isFinalized=!0;let e=!1;const t=this.y-this.staff.topSpacing,i=this.y+this.height+this.staff.bottomSpacing;for(const s of this._ties)if(s.doLayout(),s.height>0){const a=s.y+s.height-i;a>0&&this.registerOverflowBottom(a)&&(e=!0);const r=s.y-t;r<0&&this.registerOverflowTop(-1*r)&&(e=!0)}return e}doLayout(){if(this.bar){this.helpers.initialize(),this._ties=[],this._preBeatGlyphs=new _a,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new _a,this._postBeatGlyphs.renderer=this;for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];if(this.hasVoiceContainer(t)){let i=new Ba(0,0,t);i.renderer=this,this._voiceContainers.set(this.bar.voices[e].index,i)}}this.bar.simileMark===h.SecondOfDouble&&(this.canWrap=!1),this.createPreBeatGlyphs(),this.createBeatGlyphs(),this.createPostBeatGlyphs(),this.updateSizes();for(const e of this.helpers.beamHelpers)for(const t of e)t.finish();this.computedWidth=this.width}}hasVoiceContainer(e){return!e.isEmpty||0===e.index}updateSizes(){this.staff.registerStaffTop(this.topPadding),this.staff.registerStaffBottom(this.height-this.bottomPadding);let e=this._voiceContainers,t=this.beatGlyphsStart,i=t;for(const s of e.values()){s.x=t,s.doLayout();let e=s.x+s.width;i<e&&(i=e)}this._postBeatGlyphs.x=Math.floor(i),this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.height+=this.layoutingInfo.height*this.scale}addPreBeatGlyph(e){e.renderer=this,this._preBeatGlyphs.addGlyph(e)}addBeatGlyph(e){e.renderer=this,e.preNotes.renderer=this,e.onNotes.renderer=this,e.onNotes.beamingHelper=this.helpers.beamHelperLookup[e.beat.voice.index].get(e.beat.index),this.getVoiceContainer(e.beat.voice).addGlyph(e)}getVoiceContainer(e){return this._voiceContainers.has(e.index)?this._voiceContainers.get(e.index):void 0}getBeatContainer(e){return this.getVoiceContainer(e.voice)?.beatGlyphs?.[e.index]}getPreNotesGlyphForBeat(e){return this.getBeatContainer(e)?.preNotes}getOnNotesGlyphForBeat(e){return this.getBeatContainer(e)?.onNotes}paint(e,t,i){this.paintBackground(e,t,i),i.color=this.resources.mainGlyphColor,this._preBeatGlyphs.paint(e+this.x,t+this.y,i);for(const s of this._voiceContainers.values())i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.paint(e+this.x,t+this.y,i);i.color=this.resources.mainGlyphColor,this._postBeatGlyphs.paint(e+this.x,t+this.y,i)}paintBackground(e,t,i){this.layoutingInfo.paint(e+this.x+this._preBeatGlyphs.x+this._preBeatGlyphs.width,t+this.y+this.height,i)}buildBoundingsLookup(e,t,i){let s=new Bs;s.bar=this.bar,s.visualBounds=new nt,s.visualBounds.x=t+this.x,s.visualBounds.y=i+this.y+this.topPadding,s.visualBounds.w=this.width,s.visualBounds.h=this.height-this.topPadding-this.bottomPadding,s.realBounds=new nt,s.realBounds.x=t+this.x,s.realBounds.y=i+this.y,s.realBounds.w=this.width,s.realBounds.h=this.height,e.addBar(s);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(s,t+this.x+a.x,i+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=qe.PreNotes){let i=this.getBeatContainer(e);if(i)switch(t){case qe.PreNotes:return i.voiceContainer.x+i.x;case qe.OnNotes:return i.voiceContainer.x+i.x+i.onNotes.x;case qe.MiddleNotes:return i.voiceContainer.x+i.x+i.onTimeX;case qe.Stem:const t=i.onNotes.beamingHelper?i.onNotes.beamingHelper.getBeatLineX(e):i.onNotes.x+i.onNotes.width/2;return i.voiceContainer.x+t;case qe.PostNotes:return i.voiceContainer.x+i.x+i.onNotes.x+i.onNotes.width;case qe.EndBeat:return i.voiceContainer.x+i.x+i.width}return 0}getNoteX(e,t){let i=this.getBeatContainer(e.beat);return i?i.voiceContainer.x+i.x+i.onNotes.x+i.onNotes.getNoteX(e,t):0}getNoteY(e,t){let i=this.getOnNotesGlyphForBeat(e.beat);return i?i.getNoteY(e,t):NaN}reLayout(){(this._wasFirstOfLine&&!this.isFirstOfLine||!this._wasFirstOfLine&&this.isFirstOfLine)&&(this._preBeatGlyphs=new _a,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()),this.updateSizes(),this.registerLayoutingInfo()}paintSimileMark(e,t,i){switch(this.bar.simileMark){case h.Simple:i.fillMusicFontSymbol(e+this.x+(this.width-20*this.scale)/2,t+this.y+this.height/2,1,P.Repeat1Bar,!1);break;case h.SecondOfDouble:i.fillMusicFontSymbol(e+this.x-28*this.scale/2,t+this.y+this.height/2,1,P.Repeat2Bars,!1)}}completeBeamingHelper(e){}}qa.LineSpacing=8,qa.StemWidth=.12*qa.LineSpacing,qa.StaffLineThickness=.13*qa.LineSpacing,qa.BeamThickness=.5*qa.LineSpacing,qa.BeamSpacing=.25*qa.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"}(Ke||(Ke={}));class Ja extends zs{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 Ke.SingleOnBeatToEnd:case Ke.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 i;switch(e){case Ke.FullBar:case Ke.SinglePreBeat:case Ke.SingleOnBeat:case Ke.SingleOnBeatToEnd:return i=this.info.createNewGlyph(this.renderer,t),i.renderer=this.renderer,i.beat=t,i.doLayout(),this._effectGlyphs[t.voice.index].set(t.index,i),this._uniqueEffectGlyphs[t.voice.index].push(i),i;case Ke.GroupedOnBeat:case Ke.GroupedOnBeatToEnd:let s=e===Ke.GroupedOnBeat?Ke.SingleOnBeat:Ke.SingleOnBeatToEnd;if(t.index>0||this.renderer.index>0){let e=t.previousBeat;if(this.info.shouldCreateGlyph(this.renderer.settings,e)){let i=null;if(t.index>0&&this._effectGlyphs[t.voice.index].has(e.index))i=this._effectGlyphs[t.voice.index].get(e.index);else if(this.renderer.index>0){let t=this.renderer.previousRenderer.getBand(e.voice,this.info.effectId);if(t){let s=t._effectGlyphs[e.voice.index];s.has(e.index)&&(i=s.get(e.index))}}let a=this.createOrResizeGlyph(s,t);return i&&this.info.canExpand(e,t)&&(i.nextGlyph=a,a.previousGlyph=i,this.isLinkedToPrevious=!0),a}return this.createOrResizeGlyph(s,t)}return this.createOrResizeGlyph(s,t);default:return this.createOrResizeGlyph(Ke.SingleOnBeat,t)}}paint(e,t,i){super.paint(e,t,i);for(let s=0,a=this._uniqueEffectGlyphs.length;s<a;s++){let a=this._uniqueEffectGlyphs[s];for(let s=0,r=a.length;s<r;s++){a[s].paint(e+this.x,t+this.y,i)}}}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 i,s=this._effectGlyphs[t.voice.index].get(t.index),a=this.renderer.getBeatContainer(t);switch(e){case Ke.SinglePreBeat:i=a.preNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,s.width=i.width;break;case Ke.SingleOnBeat:case Ke.GroupedOnBeat:i=a.onNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,s.width=i.width;break;case Ke.SingleOnBeatToEnd:case Ke.GroupedOnBeatToEnd:i=a.onNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,a.beat.isLastOfVoice?s.width=this.renderer.width-s.x:s.width=a.width-a.preNotes.width-a.preNotes.x;break;case Ke.FullBar:s.width=this.renderer.width}}}class ja{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class Qa{constructor(){this.bands=[],this.shared=new ja}update(e){e.info.canShareBand||(this.shared.uniqueEffectId=e.info.effectId),e.slot=this,this.bands.push(e),e.height>this.shared.height&&(this.shared.height=e.height),this.shared.firstBeat&&!e.firstBeat.isBefore(this.shared.firstBeat)||(this.shared.firstBeat=e.firstBeat),this.shared.lastBeat&&!e.lastBeat.isAfter(this.shared.lastBeat)||(this.shared.lastBeat=e.lastBeat)}canBeUsed(e){return(!this.shared.uniqueEffectId&&e.info.canShareBand||e.info.effectId===this.shared.uniqueEffectId)&&(!this.shared.firstBeat||this.shared.lastBeat.isBefore(e.firstBeat)||this.shared.lastBeat.isBefore(this.shared.firstBeat))}}class $a{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 Qa;return this.slots.push(t),t}register(e){let t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class Ka extends wa{constructor(){super(0,0),this.computedWidth=0}doLayout(){let e=0;if(this.glyphs)for(let t=0,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];i.x=e,i.renderer=this.renderer,i.doLayout(),e+=i.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 Za extends Ka{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,i){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class er extends qa{constructor(e,t,i){super(e,t),this._bands=[],this._bandLookup=new Map,this.sizingInfo=null,this._infos=i}updateSizes(){this.topOverflow=0,this.bottomOverflow=0,this.topPadding=0,this.bottomPadding=0,this.updateHeight(),super.updateSizes()}finalizeRenderer(){let e=super.finalizeRenderer();return this.updateHeight()&&(e=!0),e}updateHeight(){if(!this.sizingInfo)return!1;let e=0;for(let t of this.sizingInfo.slots){t.shared.y=e;for(let i of t.bands)i.y=e,i.height=t.shared.height;e+=t.shared.height}return e!==this.height&&(this.height=e,!0)}applyLayoutingInfo(){if(!super.applyLayoutingInfo())return!1;if(this.index>0){let e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new $a;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 i=new Ja(e,t);i.renderer=this,i.doLayout(),this._bands.push(i),this._bandLookup.set(e.index+"."+t.effectId,i)}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 i=new Js(t,this.getVoiceContainer(e));i.preNotes=new Ka,i.onNotes=new Za,this.addBeatGlyph(i);for(let e of this._bands)e.createGlyph(t)}}paint(e,t,i){this.paintBackground(e,t,i);for(let s of this._bands)i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.isEmpty||s.paint(e+this.x,t+this.y,i)}getBand(e,t){let i=e.index+"."+t;return this._bandLookup.has(i)?this._bandLookup.get(i):null}}class tr extends Sa{get staffId(){return this._staffId}constructor(e,t){super(),this._infos=t,this._staffId=e,this.isInAccolade=!1,this.isRelevantForBoundsLookup=!1}create(e,t){return new er(e,t,this._infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class ir extends Us{constructor(e,t,i){super(e,t),this._endingsString="",this._endings=[];for(let e=0;e<ce.MaxAlternateEndings;e++)i&1<<e&&this._endings.push(e)}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(ir.Padding*this.scale+2);let e="";for(let t=0,i=this._endings.length;t<i;t++)e+=this._endings[t]+1,e+=". ";this._endingsString=e}paint(e,t,i){super.paint(e,t,i);let s=i.textBaseline;if(i.textBaseline=C.Top,this._endings.length>0){let s=this.renderer.resources;i.font=s.wordsFont,i.moveTo(e+this.x,t+this.y+this.height),i.lineTo(e+this.x,t+this.y),i.lineTo(e+this.x+this.width,t+this.y),i.stroke(),i.fillText(this._endingsString,e+this.x+ir.Padding*this.scale,t+this.y*this.scale)}i.textBaseline=s}}ir.Padding=3;class sr{get effectId(){return this.notationElement.toString()}}class ar extends sr{get notationElement(){return v.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Ke.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){return new ir(0,0,t.voice.bar.masterBar.alternateEndings)}canExpand(e,t){return!0}}class rr extends sr{get notationElement(){return v.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Aa(0,0,"Capo. fret "+t.voice.bar.staff.capo,e.resources.effectFont,E.Left)}canExpand(e,t){return!1}}class nr extends sr{get notationElement(){return v.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Aa(0,0,t.chord.name,e.resources.effectFont,E.Center)}canExpand(e,t){return!1}}class or extends Us{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,i){if(this.isLinkedWithPrevious)return;if(!this.isLinkedWithNext&&!this.forceGroupedRendering)return void this.paintNonGrouped(e,t,i);let s;if(!this.isLinkedWithNext&&this.forceGroupedRendering)s=this;else for(s=this.nextGlyph;s.isLinkedWithNext;)s=s.nextGlyph;let a=s.renderer,r=s.beat,n=this.endPosition,o=e-this.renderer.x,h=this.calculateEndX(a,r,o,n);this.paintGrouped(e,t,h,i)}calculateEndX(e,t,i,s){return t?i+e.x+e.getBeatX(t,s):i+e.x+this.x+this.width}paintNonGrouped(e,t,i){let s=e-this.renderer.x,a=this.calculateEndX(this.renderer,this.beat,s,this.endPosition);this.paintGrouped(e,t,a,i)}}class hr extends or{constructor(e,t,i){super(qe.EndBeat),this._crescendo=u.None,this._crescendo=i,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17*this.scale}paintGrouped(e,t,i,s){let a=e+this.x,r=this.height*this.scale;s.beginPath(),this._crescendo===u.Crescendo?(i-=hr.Padding*this.scale,s.moveTo(i,t+this.y),s.lineTo(a,t+this.y+r/2),s.lineTo(i,t+this.y+r)):(i-=hr.Padding*this.scale,s.moveTo(a,t+this.y),s.lineTo(i,t+this.y+r/2),s.lineTo(a,t+this.y+r)),s.stroke()}}hr.Padding=Ys.QuarterNoteHeadWidth/2|0;class lr extends sr{get notationElement(){return v.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==u.None}createNewGlyph(e,t){return new hr(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class cr extends Xs{constructor(e,t,i){super(e,t,.6,cr.getSymbol(i))}doLayout(){super.doLayout(),this.height=17*this.scale,this.y+=this.height/2}static getSymbol(e){switch(e){case g.PPP:return P.DynamicPPP;case g.PP:return P.DynamicPP;case g.P:return P.DynamicPiano;case g.MP:return P.DynamicMP;case g.MF:return P.DynamicMF;case g.F:return P.DynamicForte;case g.FF:return P.DynamicFF;case g.FFF:return P.DynamicFFF;default:return P.None}}}class dr extends sr{get notationElement(){return v.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return this.internalShouldCreateGlyph(t)}internalShouldCreateGlyph(e){if(e.voice.bar.staff.track.score.stylesheet.hideDynamics||e.isEmpty||e.voice.isEmpty||e.isRest||e.graceType!==f.None)return!1;let t=this.getPreviousDynamicsBeat(e),i=0===e.voice.index&&!t||e.dynamics!==t?.dynamics;if(i&&e.voice.index>0)for(let t of e.voice.bar.voices)if(t.index<e.voice.index){let s=t.getBeatAtPlaybackStart(e.playbackStart);s&&e.dynamics===s.dynamics&&this.internalShouldCreateGlyph(s)&&(i=!1)}return i}getPreviousDynamicsBeat(e){let t=e.previousBeat;for(;null!=t;){if(!t.isRest&&t.graceType===f.None)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new cr(0,0,t.dynamics)}canExpand(e,t){return!0}}class ur extends Us{doLayout(){super.doLayout(),this.height=17*this.scale}paint(e,t,i){let s=6*this.scale,a=Math.max(this.width,14*this.scale),r=this.height/2;i.beginPath(),i.moveTo(e+this.x,t+this.y+r),i.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r-s),i.moveTo(e+this.x,t+this.y+r),i.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r+s),i.stroke()}}class pr extends sr{get notationElement(){return v.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return t.fadeIn}createNewGlyph(e,t){return new ur}canExpand(e,t){return!0}}class gr extends Xs{constructor(e,t,i){super(e,t,1,gr.getSymbol(i))}static getSymbol(e){switch(e){case Ne.Short:return P.FermataShortAbove;case Ne.Medium:return P.FermataAbove;case Ne.Long:return P.FermataLongAbove;default:return P.None}}doLayout(){this.width=23*this.scale,this.height=12*this.scale}paint(e,t,i){super.paint(e-this.width/2,t+this.height,i)}}class fr extends sr{get notationElement(){return v.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new gr(0,0,t.fermata.type)}canExpand(e,t){return!0}}class mr extends sr{get notationElement(){return v.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(t,i){return!(0!==i.voice.index||i.isRest||t.notation.fingeringMode!==e.FingeringMode.SingleNoteEffectBand&&t.notation.fingeringMode!==e.FingeringMode.SingleNoteEffectBandForcePiano)&&(1===i.notes.length&&i.notes[0].isFingering)}createNewGlyph(e,t){let i=m.Unknown,s=!1,a=t.notes[0];a.leftHandFinger!==m.Unknown?(i=a.leftHandFinger,s=!0):a.rightHandFinger!==m.Unknown&&(i=a.rightHandFinger);let r=Q.fingerToString(e.settings,t,i,s)??"";return new Aa(0,0,r,e.resources.fingeringFont,E.Left)}canExpand(e,t){return!0}}class yr extends sr{constructor(){super(...arguments),this.lastCreateInfo=null}shouldCreateGlyph(e,t){this.lastCreateInfo=[];for(let e=0,i=t.notes.length;e<i;e++){let i=t.notes[e];this.shouldCreateGlyphForNote(i)&&this.lastCreateInfo.push(i)}return this.lastCreateInfo.length>0}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}canExpand(e,t){return!0}}class br extends or{constructor(e){super(qe.OnNotes),this._label=e}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=qe.EndBeat,this.forceGroupedRendering=!0),super.doLayout(),this.height=this.renderer.resources.effectFont.size}paintNonGrouped(e,t,i){let s=this.renderer.resources;i.font=s.effectFont;let a=i.textAlign;i.textAlign=E.Center,i.fillText(this._label,e+this.x,t+this.y),i.textAlign=a}paintGrouped(e,t,i,s){this.paintNonGrouped(e,t,s);let a=3*this.scale,r=s.measureText(this._label),n=e+this.x+r/2+a,o=t+this.y+4*this.scale,h=8*this.scale;if(i>n){let e=n;for(;e<i;)s.beginPath(),s.moveTo(e,0|o),s.lineTo(Math.min(e+h,i),0|o),e+=h+a,s.stroke();s.beginPath(),s.moveTo(i,o-5*this.scale|0),s.lineTo(i,o+5*this.scale|0),s.stroke()}}}br.LineSpacing=3,br.LineTopPadding=4,br.LineTopOffset=5,br.LineSize=8;class Sr extends yr{get effectId(){return this._effectId}get notationElement(){return v.EffectHarmonics}constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case y.None:this._effectId="harmonics-none";break;case y.Natural:this._effectId="harmonics-natural";break;case y.Artificial:this._effectId="harmonics-artificial";break;case y.Pinch:this._effectId="harmonics-pinch";break;case y.Tap:this._effectId="harmonics-tap";break;case y.Semi:this._effectId="harmonics-semi";break;case y.Feedback:this._effectId="harmonics-feedback";break;default:this._effectId=""}}shouldCreateGlyphForNote(e){return!(!e.isHarmonic||e.harmonicType!==this._harmonicType)&&(e.beat!==this._beat&&(this._beat=e.beat),!0)}get sizingMode(){return Ke.GroupedOnBeat}createNewGlyph(e,t){return new br(Sr.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case y.Natural:return"N.H.";case y.Artificial:return"A.H.";case y.Pinch:return"P.H.";case y.Tap:return"T.H.";case y.Semi:return"S.H.";case y.Feedback:return"Fdbk."}return""}}class wr extends sr{get notationElement(){return v.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return Ke.GroupedOnBeat}createNewGlyph(e,t){return new br("LetRing")}canExpand(e,t){return!0}}class _r extends Us{constructor(e,t,i,s,a=E.Center){super(e,t),this._lines=i,this.font=s,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,i){i.font=this.font;let s=i.textAlign;i.textAlign=this.textAlign;for(let s=0;s<this._lines.length;s++)this._lines[s]&&i.fillText(this._lines[s],e+this.x,t+this.y+s*this.font.size);i.textAlign=s}}class Br extends sr{get notationElement(){return v.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new _r(0,0,t.lyrics,e.resources.effectFont,E.Center)}canExpand(e,t){return!0}}class Tr extends sr{get notationElement(){return v.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return Ke.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 Aa(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,E.Left)}canExpand(e,t){return!0}}class kr extends or{constructor(e,t){super(qe.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=13*this.scale}paintNonGrouped(e,t,i){this.paintOttava(e,t,i)}paintOttava(e,t,i){let s=0;switch(this._ottava){case o._15ma:s=37*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,P.QuindicesimaAlta,!1);break;case o._8va:s=26*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,P.OttavaAlta,!1);break;case o._8vb:s=23*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,P.OttavaBassaVb,!1);break;case o._15mb:s=36*this.scale,i.fillMusicFontSymbols(e+this.x-s/2,t+this.y+this.height,.8,[P.Quindicesima,P.OctaveBaselineM,P.OctaveBaselineB],!1)}return s/2}paintGrouped(e,t,i,s){let a=this.paintOttava(e,t,s),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(i>n){let e=n;for(;e<i;)s.beginPath(),s.moveTo(e,0|o),s.lineTo(Math.min(e+h,i),0|o),e+=h+r,s.stroke();s.beginPath(),this._aboveStaff?(s.moveTo(i,o),s.lineTo(i,t+this.y+this.height)):(s.moveTo(i,o),s.lineTo(i,t+this.y)),s.stroke()}}}class vr extends sr{get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return v.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.GroupedOnBeat}constructor(e){super(),this._aboveStaff=e}shouldCreateGlyph(e,t){switch(t.ottava){case o._15ma:case o._8va:return this._aboveStaff;case o._8vb:case o._15mb:return!this._aboveStaff}return!1}createNewGlyph(e,t){return new kr(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class xr extends yr{get notationElement(){return v.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return Ke.GroupedOnBeat}createNewGlyph(e,t){return new br("P.M.")}constructor(){super()}}class Nr extends yr{get notationElement(){return v.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===w.PickSlideDown||e.slideOutType===w.PickSlideUp}get sizingMode(){return Ke.GroupedOnBeat}createNewGlyph(e,t){return new br("P.S.")}constructor(){super()}}class Pr extends Xs{constructor(e,t,i){super(e,t,Ys.GraceScale,Pr.getSymbol(i))}doLayout(){this.width=9*this.scale,this.height=13*this.scale}paint(e,t,i){super.paint(e,t+this.height,i)}static getSymbol(e){switch(e){case N.Up:return P.StringsUpBow;case N.Down:return P.StringsDownBow;default:return P.None}}}class Er extends sr{get notationElement(){return v.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==N.None}createNewGlyph(e,t){return new Pr(0,0,t.pickStroke)}canExpand(e,t){return!0}}class Cr extends or{constructor(e){super(qe.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case _.Slight:this._stepSize=12*this.scale;break;case _.Wide:this._stepSize=23*this.scale}this.height=18*this.scale}paintGrouped(e,t,i,s){let a=e+this.x,r=i-a,n=Math.max(1,r/this._stepSize);s.beginPath(),s.moveTo(a,t+this.y);for(let e=0;e<n;e++)s.lineTo(a+this._stepSize/2,t+this.y+this.height),s.lineTo(a+this._stepSize,t+this.y),a+=this._stepSize;s.stroke()}}class Fr extends sr{get notationElement(){return v.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===_.Slight}createNewGlyph(e,t){return new Cr(_.Slight)}canExpand(e,t){return!0}}class Lr extends or{constructor(e,t,i,s=1.2,a=!1){super(qe.EndBeat),this._scale=0,this._symbol=P.None,this._symbolSize=0,this._type=i,this._scale=s,this.x=e,this.y=t,this._partialWaves=a}doLayout(){super.doLayout();let e=0;switch(this._type){case _.Slight:this._symbol=P.WiggleTrill,this._symbolSize=9*this._scale,e=6*this._scale;break;case _.Wide:this._symbol=P.WiggleVibratoMediumFast,this._symbolSize=10*this._scale,e=10*this._scale}this.height=e*this.scale}paintGrouped(e,t,i,s){let a=i-(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 i=0;i<n;i++)s.fillMusicFontSymbol(e+this.x+o,t+this.y+2*this.height,this._scale*this.scale,this._symbol,!1),o+=r}}class Mr extends yr{get notationElement(){return v.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===_.Slight||e.isTieDestination&&e.tieOrigin.vibrato===_.Slight}get sizingMode(){return Ke.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Lr(0,0,_.Slight,1.2)}constructor(){super()}}class Ir extends sr{get notationElement(){return v.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){let i=e.resources;return t.slap?new Aa(0,0,"S",i.effectFont,E.Left):t.pop?new Aa(0,0,"P",i.effectFont,E.Left):new Aa(0,0,"T",i.effectFont,E.Left)}canExpand(e,t){return!0}}class Dr extends Us{constructor(e,t,i){super(e,t),this._tempo=0,this._tempo=i}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,i){let s=this.renderer.resources;i.font=s.markerFont,i.fillMusicFontSymbol(e+this.x,t+this.y+.8*this.height,this.scale*Ys.GraceScale,P.NoteQuarterUp,!1),i.fillText("= "+this._tempo.toString(),e+this.x+this.height/2,t+this.y+i.font.size/2)}}class Ar extends sr{get notationElement(){return v.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Ke.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 i=0;return i=t.voice.bar.masterBar.tempoAutomation?t.voice.bar.masterBar.tempoAutomation.value:t.voice.bar.staff.track.score.tempo,new Dr(0,0,i)}canExpand(e,t){return!0}}class Rr extends sr{get notationElement(){return v.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Aa(0,0,t.text,e.resources.effectFont,E.Left)}canExpand(e,t){return!0}}class Or extends Us{constructor(e,t){super(e,t)}doLayout(){super.doLayout(),this.height=this.renderer.resources.markerFont.size*this.scale}paint(e,t,i){let s=this.renderer.resources;i.font=s.markerFont;let a=i.measureText("tr");i.fillText("tr",e+this.x,t+this.y);let r=a+3*this.scale,n=this.width-r,o=11*this.scale*1.2,h=Math.max(1,(n-r)/o),l=r,c=t+this.y+1.2*this.height;for(let t=0;t<h;t++)i.fillMusicFontSymbol(e+this.x+l,c,1.2,P.WiggleTrill,!1),l+=o}}class Gr extends yr{get notationElement(){return v.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return Ke.SingleOnBeat}createNewGlyph(e,t){return new Or(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(Ze||(Ze={}));class Vr extends Us{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,i){e+=this.x;let s=(t+=this.y)+this.height*Ys.GraceScale;i.font=this.renderer.resources.effectFont,i.fillText("(",e,t+.3*this.height);let a=e+10*this.scale,r=e+40*this.scale;switch(this._tripletFeel){case A.NoTripletFeel:this.renderBarNote(a,s,Vr.NoteScale,i,[Ze.Full]),this.renderBarNote(r,s,Vr.NoteScale,i,[Ze.Full]);break;case A.Triplet8th:this.renderBarNote(a,s,Vr.NoteScale,i,[Ze.Full]),i.fillMusicFontSymbol(r,s,Vr.NoteScale,P.NoteQuarterUp,!1),i.fillMusicFontSymbol(r+Vr.NoteSeparation*this.scale,s,Vr.NoteScale,P.NoteEighthUp,!1),this.renderTriplet(r,t,i);break;case A.Triplet16th:this.renderBarNote(a,s,Vr.NoteScale,i,[Ze.Full,Ze.Full]),this.renderBarNote(r,s,Vr.NoteScale,i,[Ze.Full,Ze.PartialRight]),this.renderTriplet(r,t,i);break;case A.Dotted8th:this.renderBarNote(a,s,Vr.NoteScale,i,[Ze.Full]),this.renderBarNote(r,s,Vr.NoteScale,i,[Ze.Full,Ze.PartialRight]),i.fillCircle(r+9*this.scale,s,this.scale);break;case A.Dotted16th:this.renderBarNote(a,s,Vr.NoteScale,i,[Ze.Full,Ze.Full]),this.renderBarNote(r,s,Vr.NoteScale,i,[Ze.Full,Ze.Full,Ze.PartialRight]),i.fillCircle(r+9*this.scale,s,this.scale);break;case A.Scottish8th:this.renderBarNote(a,s,Vr.NoteScale,i,[Ze.Full]),this.renderBarNote(r,s,Vr.NoteScale,i,[Ze.Full,Ze.PartialLeft]),i.fillCircle(r+Vr.NoteSeparation*this.scale+8*this.scale,s,this.scale);break;case A.Scottish16th:this.renderBarNote(a,s,Vr.NoteScale,i,[Ze.Full,Ze.Full]),this.renderBarNote(r,s,Vr.NoteScale,i,[Ze.Full,Ze.Full,Ze.PartialLeft]),i.fillCircle(r+Vr.NoteSeparation*this.scale+8*this.scale,s,this.scale)}i.fillText("=",e+30*this.scale,t+5*this.scale),i.fillText(")",e+65*this.scale,t+.3*this.height)}renderBarNote(e,t,i,s,a){s.fillMusicFontSymbol(e,t,i,P.NoteQuarterUp,!1);let r=Vr.NoteSeparation/2*this.scale;for(let i=0;i<a.length;i++)switch(a[i]){case Ze.Full:s.fillRect(e+4*this.scale,t-Vr.NoteHeight*this.scale+Vr.BarSeparation*this.scale*i,Vr.NoteSeparation*this.scale,Vr.BarHeight*this.scale);break;case Ze.PartialLeft:s.fillRect(e+4*this.scale,t-Vr.NoteHeight*this.scale+Vr.BarSeparation*this.scale*i,r,Vr.BarHeight*this.scale);break;case Ze.PartialRight:s.fillRect(e+4*this.scale+r,t-Vr.NoteHeight*this.scale+Vr.BarSeparation*this.scale*i,r,Vr.BarHeight*this.scale)}s.fillMusicFontSymbol(e+Vr.NoteSeparation*this.scale,t,i,P.NoteQuarterUp,!1)}renderTriplet(e,t,i){t+=2*this.scale;let s=this.renderer.resources.effectFont;i.font=Ri.withFamilyList(s.families,.8*s.size,s.style);let a=e+Vr.NoteSeparation*this.scale+3*this.scale;i.beginPath(),i.moveTo(e,t+3*this.scale),i.lineTo(e,t),i.lineTo(e+5*this.scale,t),i.moveTo(a+5*this.scale,t+3*this.scale),i.lineTo(a+5*this.scale,t),i.lineTo(a,t),i.stroke(),i.fillText("3",e+7*this.scale,t-10*this.scale),i.font=s}}Vr.NoteScale=.4,Vr.NoteHeight=12,Vr.NoteSeparation=12,Vr.BarHeight=2,Vr.BarSeparation=3;class Hr extends sr{get notationElement(){return v.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Ke.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==A.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new Vr(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class Wr extends sr{get notationElement(){return v.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ke.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new br("w/bar")}canExpand(e,t){return!0}}class zr extends sr{get notationElement(){return v.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===_.Wide}createNewGlyph(e,t){return new Cr(_.Wide)}canExpand(e,t){return!0}}class Ur extends yr{get notationElement(){return v.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===_.Wide||e.isTieDestination&&e.tieOrigin.vibrato===_.Wide}get sizingMode(){return Ke.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Lr(0,0,_.Wide,1.2)}}class Xr{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class Yr extends Ya{get name(){return"HorizontalScreen"}constructor(e){super(e),this._group=null,this._pagePadding=null}get supportsResize(){return!1}get firstBarX(){let e=this._pagePadding[0];return this._group&&(e+=this._group.accoladeSpacing),e}doResize(){}doLayoutAndRender(){switch(this._pagePadding=this.renderer.settings.display.padding,this.renderer.settings.display.systemsLayoutMode){case e.SystemsLayoutMode.Automatic:this.systemsLayoutMode=je.Automatic;break;case e.SystemsLayoutMode.UseModelLayout:this.systemsLayoutMode=je.FromModelWithWidths}this._pagePadding||(this._pagePadding=Yr.PagePadding),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let t=this.renderer.score,i=this.renderer.settings.display.startBar;i--,i=Math.min(t.masterBars.length-1,Math.max(0,i));let s=i,a=this.renderer.settings.display.barCount;a<=0&&(a=t.masterBars.length),a=i+a-1,a=Math.min(t.masterBars.length-1,Math.max(0,a)),this._group=this.createEmptyStaveGroup(),this._group.isLast=!0,this._group.x=this._pagePadding[0],this._group.y=this._pagePadding[1];let r=this.renderer.settings.display.barCountPerPartial,n=[],o=new Xr,h=0;for(;s<=a;){let e=this._group.addBars(this.renderer.tracks,s);if(e)if(0===o.masterBars.length&&e.isLinkedToPrevious&&n.length>0){let i=n[n.length-1];i.masterBars.push(t.masterBars[s]),i.width+=e.width,h+=e.width,o.x+=h}else o.masterBars.push(t.masterBars[s]),o.width+=e.width,o.masterBars.length>=r&&(0===n.length&&(o.width+=this._group.accoladeSpacing+this._pagePadding[0]),h+=o.width,n.push(o),J.debug(this.name,"Finished partial from bar "+o.masterBars[0].index+" to "+o.masterBars[o.masterBars.length-1].index,null),o=new Xr,o.x=h);s++}o.masterBars.length>0&&(0===n.length&&(o.width+=this._group.accoladeSpacing+this._pagePadding[0]),n.push(o),J.debug(this.name,"Finished partial from bar "+o.masterBars[0].index+" to "+o.masterBars[o.masterBars.length-1].index,null)),this.finalizeGroup(),this.height=Math.floor(this._group.y+this._group.height),this.width=this._group.x+this._group.width+this._pagePadding[2],s=0;let l=0;for(let e=0;e<n.length;e++){const t=n[e],i=new _s;i.x=l,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,l+=t.width;const a=s,r=e;this._group.buildBoundingsLookup(this._group.x,this._group.y),this.registerPartial(i,(e=>{let i=this._group.getBarX(t.masterBars[0].index)+this._group.accoladeSpacing;0===r&&(i-=this._group.x+this._group.accoladeSpacing),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=E.Left,J.debug(this.name,"Rendering partial from bar "+t.masterBars[0].index+" to "+t.masterBars[t.masterBars.length-1].index,null),this._group.paintPartial(-i,this._group.y,e,a,t.masterBars.length)})),s+=t.masterBars.length}this.height=this.layoutAndRenderAnnotation(this.height)+this._pagePadding[3]}finalizeGroup(){this._group.scaleToWidth(this._group.width),this._group.finalizeGroup()}}Yr.PagePadding=[20,20,20,20],Yr.GroupSpacing=20;class qr extends Ya{get name(){return"PageView"}constructor(e){super(e),this._groups=[],this._allMasterBarRenderers=[],this._barsFromPreviousGroup=[],this._pagePadding=null}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case e.SystemsLayoutMode.Automatic:this.systemsLayoutMode=je.Automatic;break;case e.SystemsLayoutMode.UseModelLayout:this.systemsLayoutMode=je.FromModelWithScale}this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=qr.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 t=0;this.width=this.renderer.width,this._allMasterBarRenderers=[],t=this.layoutAndRenderScoreInfo(t,-1),t=this.layoutAndRenderTunings(t,-1),t=this.layoutAndRenderChordDiagrams(t,-1),t=this.layoutAndRenderScore(t),t=this.layoutAndRenderAnnotation(t),this.height=t+this._pagePadding[3]}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 i=this.renderer.settings.display.resources;this.tuningGlyph.x=this._pagePadding[0],this.tuningGlyph.width=this.width,this.tuningGlyph.doLayout();let s=this.tuningGlyph.height+11*this.scale;const a=new _s;return a.x=0,a.y=e,a.width=this.width,a.height=s,a.totalWidth=this.width,a.totalHeight=t<0?e+a.height:t,this.registerPartial(a,(e=>{e.color=i.scoreInfoColor,e.textAlign=E.Center,this.tuningGlyph.paint(0,0,e)})),e+s}layoutAndRenderChordDiagrams(e,t=-1){if(!this.chordDiagrams)return e;const i=this.renderer.settings.display.resources;this.chordDiagrams.width=this.width,this.chordDiagrams.doLayout();const s=Math.floor(this.chordDiagrams.height),a=new _s;return a.x=0,a.y=e,a.width=this.width,a.height=s,a.totalWidth=this.width,a.totalHeight=t<0?e+s:t,this.registerPartial(a,(e=>{e.color=i.scoreInfoColor,e.textAlign=E.Center,this.chordDiagrams.paint(0,0,e)})),e+s}layoutAndRenderScoreInfo(e,t=-1){J.debug(this.name,"Layouting score info");const i=new _s;i.x=0,i.y=e;let s=this._pagePadding[1],a=this.scale,r=this.renderer.settings.display.resources,n=[v.ScoreTitle,v.ScoreSubTitle,v.ScoreArtist,v.ScoreAlbum,v.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=s,t.textAlign=E.Center,s+=t.font.size*a}let o=!1,h=0;if(this.scoreInfoGlyphs.has(v.ScoreMusic)){let e=this.scoreInfoGlyphs.get(v.ScoreMusic);e.x=this.width-this._pagePadding[2],e.y=s,e.textAlign=E.Right,o=!0,h=e.font.size*a}if(this.scoreInfoGlyphs.has(v.ScoreWords)){let e=this.scoreInfoGlyphs.get(v.ScoreWords);e.x=this._pagePadding[0],e.y=s,e.textAlign=E.Left,o=!0,h=e.font.size*a}return o&&(s+=h),s=Math.floor(s+17*this.scale),i.width=this.width,i.height=s,i.totalWidth=this.width,i.totalHeight=t<0?e+i.height:t,this.registerPartial(i,(e=>{e.color=r.scoreInfoColor,e.textAlign=E.Center;for(const t of this.scoreInfoGlyphs.values())t.paint(0,0,e)})),e+s}resizeAndRenderScore(e,t){if(this.renderer.settings.display.barsPerRow>0||this.systemsLayoutMode==je.FromModelWithScale)for(let i=0;i<this._groups.length;i++){let s=this._groups[i];this.fitGroup(s),e+=this.paintGroup(s,t)}else{this._groups=[];let i=0,s=this.maxWidth,a=this.createEmptyStaveGroup();for(a.index=this._groups.length,a.x=this._pagePadding[0],a.y=e;i<this._allMasterBarRenderers.length;){let r=this._allMasterBarRenderers[i];if(a.width+r.width<=s||0===a.masterBarsRenderers.length)a.addMasterBarRenderers(this.renderer.tracks,r),i++;else{for(;r&&!r.canWrap&&a.masterBarsRenderers.length>1;)r=a.revertLastBar(),i--;a.isFull=!0,a.isLast=this.lastBarIndex===a.lastBarIndex,this._groups.push(a),this.fitGroup(a),e+=this.paintGroup(a,t),a=this.createEmptyStaveGroup(),a.index=this._groups.length,a.x=this._pagePadding[0],a.y=e}}a.isLast=this.lastBarIndex===a.lastBarIndex,this.fitGroup(a),e+=this.paintGroup(a,t)}return e}layoutAndRenderScore(e){let t=this.firstBarIndex,i=this.lastBarIndex;for(this._groups=[];t<=i;){let s=this.createStaveGroup(t,i);this._groups.push(s),s.x=this._pagePadding[0],s.y=e,t=s.lastBarIndex+1,this.fitGroup(s),J.debug(this.name,"Rendering partial from bar "+s.firstBarIndex+" to "+s.lastBarIndex,null),e+=this.paintGroup(s,e)}return e}paintGroup(e,t){let i=Math.floor(e.height+20*this.scale);const s=new _s;return s.x=0,s.y=e.y,s.totalWidth=this.width,s.totalHeight=t,s.width=this.width,s.height=i,s.firstMasterBarIndex=e.firstBarIndex,s.lastMasterBarIndex=e.lastBarIndex,e.buildBoundingsLookup(0,0),this.registerPartial(s,(t=>{this.renderer.canvas.color=this.renderer.settings.display.resources.mainGlyphColor,this.renderer.canvas.textAlign=E.Left,e.paint(0,-s.y,t)})),t+=i,i}fitGroup(e){e.isFull||e.width>this.maxWidth||this.renderer.settings.display.justifyLastSystem?e.scaleToWidth(this.maxWidth):e.scaleToWidth(e.width),e.finalizeGroup()}getBarsPerRow(e){let t=this.renderer.settings.display.barsPerRow;if(this.systemsLayoutMode==je.FromModelWithScale){let i,s;this.renderer.tracks.length>1?(i=this.renderer.score.defaultSystemsLayout,s=this.renderer.score.systemsLayout):(i=this.renderer.tracks[0].defaultSystemsLayout,s=this.renderer.tracks[0].systemsLayout),t=e<s.length?s[e]:i}return t}createStaveGroup(e,t){let i=this.createEmptyStaveGroup();i.index=this._groups.length;let s=this.getBarsPerRow(i.index),a=this.maxWidth,r=t+1,n=e;for(;n<r;){if(this._barsFromPreviousGroup.length>0)for(let e of this._barsFromPreviousGroup)i.addMasterBarRenderers(this.renderer.tracks,e),n=e.masterBar.index;else{let e=i.addBars(this.renderer.tracks,n);e&&this._allMasterBarRenderers.push(e)}this._barsFromPreviousGroup=[];let e=!1;if((-1===s&&i.width>=a&&0!==i.masterBarsRenderers.length||i.masterBarsRenderers.length===s+1)&&(e=!0),e){let e=i.revertLastBar();if(e)for(this._barsFromPreviousGroup.push(e);e&&!e.canWrap&&i.masterBarsRenderers.length>1;)e=i.revertLastBar(),e&&this._barsFromPreviousGroup.push(e);return i.isFull=!0,i.isLast=!1,this._barsFromPreviousGroup.reverse(),i}i.x=0,n++}return i.isLast=t===i.lastBarIndex,i}get maxWidth(){return this.renderer.width-this._pagePadding[0]-this._pagePadding[2]}}qr.PagePadding=[40,40,40,40],qr.GroupSpacing=20;class Jr extends Xs{constructor(e,t,i,s=!1){super(e,t,s?Ys.GraceScale:1,Jr.getMusicSymbol(i)),this._isGrace=s,this._accidentalType=i}static getMusicSymbol(e){switch(e){case Je.Natural:return P.AccidentalNatural;case Je.Sharp:return P.AccidentalSharp;case Je.Flat:return P.AccidentalFlat;case Je.NaturalQuarterNoteUp:return P.AccidentalQuarterToneNaturalArrowUp;case Je.SharpQuarterNoteUp:return P.AccidentalQuarterToneSharpArrowUp;case Je.FlatQuarterNoteUp:return P.AccidentalQuarterToneFlatArrowUp;case Je.DoubleSharp:return P.AccidentalDoubleSharp;case Je.DoubleFlat:return P.AccidentalDoubleFlat}return P.None}doLayout(){if(this._accidentalType===Je.DoubleFlat)this.width=18;else this.width=8;this.width=this.width*(this._isGrace?Ys.GraceScale:1)*this.scale}}class jr extends zs{constructor(e,t,i){super(e,t),this._number=0,this._number=i}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,i){if(!this.renderer.staff.isFirstInAccolade)return;let s=this.renderer.resources,a=i.color;i.color=s.barNumberColor,i.font=s.barNumberFont,i.fillText(this._number.toString(),e+this.x,t+this.y),i.color=a}}class Qr extends zs{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,i){let s=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?(i.fillRect(n+this.width-s-s,a,this.scale,o),i.fillRect(n+this.width-s,a,s,o)):this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart||(i.fillRect(n+this.width-this.scale,a,this.scale,o),this.renderer.bar.masterBar.isDoubleBar&&i.fillRect(n+this.width-5*this.scale,a,this.scale,o))}}class $r extends Xs{constructor(e,t,i,s){super(e,t,1,$r.getSymbol(i)),this._clef=i,this._clefOttava=s}doLayout(){switch(this._clef){case n.Neutral:this.width=15*this.scale;break;case n.C3:case n.C4:case n.F4:case n.G2:this.width=28*this.scale}}static getSymbol(e){switch(e){case n.Neutral:return P.UnpitchedPercussionClef1;case n.C3:case n.C4:return P.CClef;case n.F4:return P.FClef;case n.G2:return P.GClef;default:return P.None}}paint(e,t,i){let s;super.paint(e,t,i);let a=!1;switch(this._clefOttava){case o._15ma:s=new Xs(-4*this.scale,0,.5,P.Quindicesima),a=!0;break;case o._8va:s=new Xs(-2*this.scale,0,.5,P.Ottava),a=!0;break;case o._8vb:s=new Xs(-6*this.scale,0,.5,P.Ottava);break;case o._15mb:s=new Xs(-8*this.scale,0,.5,P.Quindicesima);break;default:return}let r=0,h=0;switch(this._clef){case n.Neutral:r=a?-12:15,h=0;break;case n.C3:case n.C4:r=a?-19:27,h=0;break;case n.F4:r=a?-9:27,h=-4;break;case n.G2:r=a?-37:30,h=0;break;default:return}s.renderer=this.renderer,s.doLayout();let l=this.width/2;s.paint(e+this.x+l+h*this.scale,t+this.y+r*this.scale,i)}}class Kr extends zs{constructor(e,t){super(e,t)}doLayout(){this.width=11*this.scale}paint(e,t,i){let s=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;i.fillCircle(n,l-3*h,h),i.fillCircle(n,l+3*h,h),n+=4*this.scale,i.beginPath(),i.moveTo(n,a),i.lineTo(n,r),i.stroke(),n+=3*this.scale+.5,i.fillRect(n,a,s,o)}}class Zr extends zs{constructor(e,t,i){super(e,t),this._count=0,this._count=0,this._count=i}doLayout(){this.width=0}paint(e,t,i){let s=this.renderer.resources,a=i.textAlign;i.font=s.barNumberFont,i.textAlign=E.Right;let r="x"+this._count,n=i.measureText(r)/1.5;i.fillText(r,e+this.x-n,t+this.y),i.textAlign=a}}class en extends zs{constructor(e,t,i,s){super(e,t),this._dotOffset=0,this._circleSize=0,this._dotOffset=0,this._circleSize=0,this._dotOffset=s,this._circleSize=i}doLayout(){this.width=13*this.scale}paint(e,t,i){let s=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;i.fillRect(n,a,s,o),n+=2*s-.5,i.beginPath(),i.moveTo(n,a),i.lineTo(n,r),i.stroke(),n+=3*this.scale;let h=this._circleSize*this.scale,l=(a+r)/2;i.fillCircle(n,l-h*this._dotOffset,h),i.fillCircle(n,l+h*this._dotOffset,h)}}class tn extends Xs{constructor(e,t,i){super(e,t,1,tn.getSymbol(i))}static getSymbol(e){switch(e){case a.None:return P.None;case a.Normal:return P.ArticAccentAbove;case a.Heavy:return P.ArticMarcatoAbove;default:return P.None}}doLayout(){this.width=9*this.scale,this.height=9*this.scale}paint(e,t,i){super.paint(e-2*this.scale,t+this.height,i)}}class sn extends zs{constructor(e,t,i){super(e,t),this._size=0,this._size=i}doLayout(){this.width=this._size+3*this.scale}paint(e,t,i){i.fillCircle(e+this.x,t+this.y,this._size)}}class an extends Xs{constructor(e,t,i){super(e,t,i?Ys.GraceScale:1,P.NoteheadXOrnate),this._isGrace=i}doLayout(){this.width=9*(this._isGrace?Ys.GraceScale:1)*this.scale,this.height=Ys.NoteHeadHeight*this.scale}}class rn extends Xs{constructor(e,t,i,s){super(e,t,s?Ys.GraceScale:1,rn.getSymbol(i)),this._isGrace=s}static getSymbol(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:case p.Half:return P.NoteheadDiamondWhiteWide;default:return P.NoteheadDiamondBlackWide}}doLayout(){this.width=9*(this._isGrace?Ys.GraceScale:1)*this.scale,this.height=Ys.NoteHeadHeight*this.scale}}class nn extends zs{constructor(e,t,i){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=Ce.Up,this._startX=0,this._startY=0,this._endX=0,this._endY=0,this._tieHeight=0,this._shouldDraw=!1,this.startBeat=e,this.endBeat=t,this.forEnd=i}doLayout(){if(this.width=0,!this.endBeat)return void(this._shouldDraw=!1);let e=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar);this.startNoteRenderer=e;let t=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.endBeat.voice.bar);this.endNoteRenderer=t,this._startX=0,this._endX=0,this._startY=0,this._endY=0,this.height=0,this._shouldDraw=!1,this.tieDirection=e?this.getBeamDirection(this.startBeat,e):this.getBeamDirection(this.endBeat,t),!this.forEnd&&e?(e!==t?(this._startX=e.x+this.getStartX(),this._startY=e.y+this.getStartY()+this.yOffset,t&&e.staff===t.staff?(this._endX=t.x+this.getEndX(),this._endY=t.y+this.getEndY()+this.yOffset):(this._endX=e.x+e.width,this._endY=this._startY)):(this._startX=e.x+this.getStartX(),this._endX=t.x+this.getEndX(),this._startY=e.y+this.getStartY()+this.yOffset,this._endY=t.y+this.getEndY()+this.yOffset),this._shouldDraw=!0):e&&e.staff===t.staff||(this._startX=t.x,this._endX=t.x+this.getEndX(),this._startY=t.y+this.getEndY()+this.yOffset,this._endY=this._startY,this._shouldDraw=!0),this._shouldDraw&&(this.y=Math.min(this._startY,this._endY),this.shouldDrawBendSlur()?this._tieHeight=0:(this._tieHeight=this.getTieHeight(this._startX,this._startY,this._endX,this._endY),this.height=nn.calculateActualTieHeight(this.renderer.scale,this._startX,this._startY,this._endX,this._endY,this.tieDirection===Ce.Down,this._tieHeight,4).h),this.tieDirection===Ce.Up&&(this.y-=this.height))}paint(e,t,i){this._shouldDraw&&(this.shouldDrawBendSlur()?nn.drawBendSlur(i,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Ce.Down,this.scale):nn.paintTie(i,this.scale,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Ce.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,i,s){return 22}getBeamDirection(e,t){return Ce.Down}getStartY(){return 0}getEndY(){return 0}getStartX(){return 0}getEndX(){return 0}static calculateActualTieHeight(e,t,i,s,a,r,n,o){const h=nn.computeBezierControlPoints(e,t,i,s,a,r,n,o);t=h[0],i=h[1];const l=h[2],c=h[3];s=h[6],a=h[7];const d=(t-l)/(t-2*l+s),u=nn.calculateExtrema(t,i,l,c,s,a,d),p=u.length>0?Math.min(t,s,u[0]):Math.min(t,s),g=u.length>0?Math.max(t,s,u[0]):Math.max(t,s),f=(i-c)/(i-2*c+a),m=nn.calculateExtrema(t,i,l,c,s,a,f),y=m.length>0?Math.min(i,a,m[1]):Math.min(i,a),b=m.length>0?Math.max(i,a,m[1]):Math.max(i,a),S=new nt;return S.x=p,S.y=y,S.w=g-p,S.h=b-y,S}static calculateExtrema(e,t,i,s,a,r,n){if(n<=0||1<=n)return[];const o=e+(i-e)*n,h=t+(s-t)*n;return[o+(i+(a-i)*n-o)*n,h+(s+(r-s)*n-h)*n]}static computeBezierControlPoints(e,t,i,s,a,r,n,o){if(t===s&&i===a)return[];if(s<t){let e=t;t=s,s=e,e=i,i=a,a=e}n*=e,o*=e;let h=a-i,l=s-t,c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;let d=(s+t)/2,u=(a+i)/2;return[t,i,d+n*h,u+n*l,d+(n-o)*h,u+(n-o)*l,s,a]}static paintTie(e,t,i,s,a,r,n=!1,o=22,h=4){const l=nn.computeBezierControlPoints(t,i,s,a,r,n,o,h);e.beginPath(),e.moveTo(l[0],l[1]),e.quadraticCurveTo(l[2],l[3],l[6],l[7]),e.quadraticCurveTo(l[4],l[5],l[0],l[1]),e.closePath(),e.fill()}static drawBendSlur(e,t,i,s,a,r,n,o){let h=a-i,l=s-t,c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;let d=(s+t)/2,u=(a+i)/2,p=nn.BendSlurHeight*n;s-t<20&&(p/=2);let g=d+p*h,f=u+p*l;if(e.beginPath(),e.moveTo(t,i),e.lineTo(g,f),e.lineTo(s,a),e.stroke(),o){let t=e.measureText(o),i=r?0:-e.font.size;e.fillText(o,g-t/2,f+i)}}}nn.BendSlurHeight=11;class on extends zs{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=on.Size*this.scale}paint(e,t,i){this._isOpen?nn.paintTie(i,this.scale,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):nn.paintTie(i,this.scale,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3)}}on.Size=6;class hn{constructor(e,t){this.line=0,this.line=e,this.isGhost=t}}class ln extends zs{constructor(e){super(0,0),this._infos=[],this._glyphs=[],this.isEmpty=!0,this._isOpen=e}addParenthesis(e){let t=this.renderer,i=t.getNoteLine(e),s=e.isGhost||this.isTiedBend(e)&&t.settings.notation.isNotationElementVisible(v.ParenthesisOnTiedBends);this.addParenthesisOnLine(i,s)}addParenthesisOnLine(e,t){let i=new hn(e,t);this._infos.push(i),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,i=e.getScoreHeight(1);for(let s=0,a=this._infos.length;s<a;s++){let a;if(this._infos[s].isGhost)if(t){let a=e.getScoreY(this._infos[s].line)+i;t.height=a-t.y}else a=new on(this._isOpen),a.renderer=this.renderer,a.y=e.getScoreY(this._infos[s].line)-i,a.height=2*i,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,i){super.paint(e,t,i);for(let s of this._glyphs)s.paint(e+this.x,t+this.y,i)}}class cn{constructor(e,t){this.line=0,this.glyph=e,this.line=t}}class dn extends zs{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new Ei,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){let i=new cn(e,t);this._infos.push(i),(!this.minNote||this.minNote.line>i.line)&&(this.minNote=i),(!this.maxNote||this.maxNote.line<i.line)&&(this.maxNote=i)}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,i=0,s=!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(i-this._infos[n].line)<=1?t?t=!1:(h=!0,o.x=e,s=!0,t=!0):t=!1,a===Ce.Down?o.x=h?0:e:o.x=h?e:0,o.x+=this.noteStartX,i=this._infos[n].line,r=Math.max(r,o.x+o.width)}s?(this._noteHeadPadding=0,this.upLineX=e,this.downLineX=e):(this._noteHeadPadding=a===Ce.Down?-e:0,r+=this._noteHeadPadding,this.upLineX=r,this.downLineX=0),this.displacedX=e,this.width=r}paint(e,t,i){e+=this.x,t+=this.y;let s=this.renderer,a=3*this.scale,r=this.width-this.noteStartX+2*a;if(this.hasTopOverflow){let n=i.color;i.color=s.resources.staffLineColor;let o=-2;for(;o>=this.minNote.line;){let n=t+s.getScoreY(o);i.fillRect(e-a+this.noteStartX,n,r,this.scale),o-=2}i.color=n}if(this.hasBottomOverflow){let n=i.color;i.color=s.resources.staffLineColor;let o=10;for(;o<=this.maxNote.line;){let n=t+s.getScoreY(o);i.fillRect(e-a+this.noteStartX,n,r,this.scale),o+=2}i.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,i)}}class un extends Xs{constructor(e,t,i){super(e,t,1,un.getSymbol(i))}doLayout(){this.width=12*this.scale}static getSymbol(e){switch(e){case p.ThirtySecond:return P.Tremolo3;case p.Sixteenth:return P.Tremolo2;case p.Eighth:return P.Tremolo1;default:return P.None}}}class pn extends dn{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 i=this._noteGlyphLookup.get(e.id),s=this.x+i.x+this._noteHeadPadding;switch(t){case $e.Left:break;case $e.Center:s+=i.width/2;break;case $e.Right:s+=i.width}return s}return 0}getNoteY(e,t){if(this._noteGlyphLookup.has(e.id)){const i=this._noteGlyphLookup.get(e.id);let s=this.y+i.y;switch(t){case Qe.TopWithStem:s-=this.renderer.getStemSize(this.beamingHelper);break;case Qe.Top:s-=i.height/2;break;case Qe.Center:break;case Qe.Bottom:s+=i.height/2;break;case Qe.BottomWithStem:s+=this.renderer.getStemSize(this.beamingHelper)}return s}return 0}addNoteGlyph(e,t,i){super.add(e,i),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,i=e===Ce.Up?this.minNote:this.maxNote,s=e===Ce.Up?this.displacedX:0,a=this.beat.tremoloSpeed;switch(a){case p.ThirtySecond:t=e===Ce.Up?-15:15;break;case p.Sixteenth:t=e===Ce.Up?-12:15;break;case p.Eighth:t=e===Ce.Up?-10:10;break;default:t=e===Ce.Up?-10:15}this._tremoloPicking=new un(s,i.glyph.y+t*this.scale,a),this._tremoloPicking.renderer=this.renderer,this._tremoloPicking.doLayout()}}buildBoundingsLookup(e,t,i){for(let s of this._notes)if(this._noteGlyphLookup.has(s.id)){let a=this._noteGlyphLookup.get(s.id),r=new vs;r.note=s,r.noteHeadBounds=new nt,r.noteHeadBounds.x=t+this.x+this._noteHeadPadding+a.x,r.noteHeadBounds.y=i+this.y+a.y-a.height/2,r.noteHeadBounds.w=a.width,r.noteHeadBounds.h=a.height,e.addNote(r)}}paint(e,t,i){let s=this.renderer,a=0,r=0,n=1,o=-n;this.beamingHelper.direction===Ce.Up?(r=s.getScoreY(this.minNote.line),a=s.getScoreY(this.maxNote.line-2)):(r=s.getScoreY(this.maxNote.line-1),a=s.getScoreY(this.minNote.line+1),o*=-1,n*=-1);for(const s of this.aboveBeatEffects.values())a+=o*s.height,s.paint(e+this.x+2*this.scale,t+this.y+a,i);for(const s of this.belowBeatEffects.values())r+=n*s.height,s.paint(e+this.x+2*this.scale,t+this.y+r,i);super.paint(e,t,i),this._tremoloPicking&&this._tremoloPicking.paint(e,t,i)}}class gn extends Xs{constructor(e,t,i){super(e,t,1,gn.getSymbol(i)),this._duration=i}static getSymbol(e){switch(e){case p.QuadrupleWhole:return P.RestLonga;case p.DoubleWhole:return P.RestDoubleWhole;case p.Whole:return P.RestWhole;case p.Half:return P.RestHalf;case p.Quarter:return P.RestQuarter;case p.Eighth:return P.RestEighth;case p.Sixteenth:return P.RestSixteenth;case p.ThirtySecond:return P.RestThirtySecond;case p.SixtyFourth:return P.RestSixtyFourth;case p.OneHundredTwentyEighth:return P.RestOneHundredTwentyEighth;case p.TwoHundredFiftySixth:return P.RestTwoHundredFiftySixth;default:return P.None}}static getSize(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:return 9;case p.ThirtySecond:return 12;case p.SixtyFourth:return 14;case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:return 20}return 10}doLayout(){this.width=gn.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 fn{constructor(){this.x=0,this.y=-3e3,this.width=0}}class mn extends wa{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 fn);let t=21*this.scale;for(let i=0,s=this.glyphs.length;i<s;i++){let s=this.glyphs[i];s.renderer=this.renderer,s.doLayout();let a=0;for(;e[a].y>s.y;)a++,a===e.length&&e.push(new fn);s.x=a,e[a].y=s.y+t,e[a].width<s.width&&(e[a].width=s.width)}this.width=0;for(const t of e)this.width+=t.width,t.x=this.width;for(let t=0,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];const s=e[i.x];i.x=this.width-s.x}}}class yn extends dn{get direction(){return Ce.Up}constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new mn,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new ln(!0),this._postNoteParenthesis=new ln(!1))}containsNoteValue(e){return this._noteValueLookup.has(e)}getNoteValueY(e){return this._noteValueLookup.has(e)?this.y+this._noteValueLookup.get(e).y:0}addGlyph(e,t=!1){let i=this.renderer,s=new Ys(0,0,p.Quarter,!0),a=i.accidentalHelper.applyAccidentalForValue(this._beat,e,t,!0),r=i.accidentalHelper.getNoteLineForValue(e,!1);if(s.y=i.getScoreY(r),this._showParenthesis&&(this._preNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.addParenthesisOnLine(r,!0),this._postNoteParenthesis.addParenthesisOnLine(r,!0)),a!==Je.None){let e=new Jr(0,s.y,a,!0);e.renderer=this.renderer,this._accidentals.renderer=this.renderer,this._accidentals.addGlyph(e)}this._noteValueLookup.set(e,s),this.add(s,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+yn.ElementPadding*this.scale),this._accidentals.isEmpty||(e+=this._accidentals.width+yn.ElementPadding*this.scale,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+yn.ElementPadding*this.scale),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+yn.ElementPadding*this.scale,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+yn.ElementPadding*this.scale)}paint(e,t,i){this._accidentals.isEmpty||this._accidentals.paint(e+this.x,t+this.y,i),this._showParenthesis&&(this._preNoteParenthesis.paint(e+this.x,t+this.y,i),this._postNoteParenthesis.paint(e+this.x,t+this.y,i)),super.paint(e,t,i)}}yn.ElementPadding=2;class bn extends zs{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,i,s,a,r,n,o){nn.drawBendSlur(e,t,i,s,a,r,n,o)}doLayout(){super.doLayout(),this.width=0;for(let e of this.BendNoteHeads)e.doLayout(),this.width+=e.width+10*this.scale}getTieDirection(e,t){return t.getBeatDirection(e)===Ce.Up?Ce.Down:Ce.Up}}bn.EndPadding=8;class Sn extends U{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class wn extends zs{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 i=0;switch(e.bendType){case c.Bend:i=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||i<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=i):(-1===this._bendEndMinValue||i<this._bendEndMinValue)&&(this._bendEndMinValue=i);break;case c.Release:i=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||i<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=i):i>0&&(-1===this._releaseMinValue||i<this._releaseMinValue)&&(this._releaseMinValue=i);break;case c.BendRelease:i=t[1].value,(-1===this._bendMiddleMinValue||i<this._bendMiddleMinValue)&&(this._bendMiddleMinValue=i),i=t[2].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||i<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=i):i>0&&(-1===this._releaseMinValue||i<this._releaseMinValue)&&(this._releaseMinValue=i);break;case c.Prebend:i=t[0].value,(-1===this._preBendMinValue||i<this._preBendMinValue)&&(this._preBendMinValue=i);break;case c.PrebendBend:i=t[0].value,(-1===this._preBendMinValue||i<this._preBendMinValue)&&(this._preBendMinValue=i),i=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||i<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=i):(-1===this._bendEndMinValue||i<this._bendEndMinValue)&&(this._bendEndMinValue=i);break;case c.PrebendRelease:i=t[0].value,(-1===this._preBendMinValue||i<this._preBendMinValue)&&(this._preBendMinValue=i),i=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||i<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=i):i>0&&(-1===this._releaseMinValue||i<this._releaseMinValue)&&(this._releaseMinValue=i)}}doLayout(){super.doLayout();let e=this._maxBendValue*wn.BendValueHeight*this.scale;this.renderer.registerOverflowTop(e);let t=0;for(let e of this._notes){let i=this._renderPoints.get(e.id);switch(e.bendType){case c.Bend:i[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case c.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[1].lineValue=t);break;case c.BendRelease:i[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[2].lineValue=t);break;case c.Prebend:i[0].lineValue=this._preBendMinValue;break;case c.PrebendBend:i[0].lineValue=this._preBendMinValue,i[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case c.PrebendRelease:i[0].lineValue=this._preBendMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[1].lineValue=t)}}this.width=0,this._notes.sort(((e,t)=>e.isStringed?e.string-t.string:e.realValue-t.realValue))}createRenderingPoints(e){let t=[];switch(e.bendType){case c.Custom:for(let i of e.bendPoints)t.push(new Sn(i.offset,i.value));break;case c.BendRelease:t.push(new Sn(0,e.bendPoints[0].value)),t.push(new Sn(U.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new Sn(U.MaxPosition,e.bendPoints[3].value));break;case c.Bend:case c.Hold:case c.Prebend:case c.PrebendBend:case c.PrebendRelease:case c.Release:t.push(new Sn(0,e.bendPoints[0].value)),t.push(new Sn(U.MaxPosition,e.bendPoints[1].value))}return t}paint(e,t,i){let s=i.color;this._notes.length>1&&(i.color=this.renderer.resources.secondaryGlyphColor);for(let a of this._notes){let r=this._renderPoints.get(a.id),n=this.renderer,o=a,h=!1,d=null,u=!1,p=a.bendStyle===l.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,h=!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,qe.MiddleNotes):f+=n.getNoteX(a,$e.Right),m=!g||g.isLastOfVoice&&!u?e+d.x+d.postBeatGlyphsStart:u||!g.nextBeat?e+d.x+d.getBeatX(g,qe.MiddleNotes):a.bendType===c.Hold?e+d.x+d.getBeatX(g.nextBeat,qe.OnNotes):e+d.x+d.getBeatX(g.nextBeat,qe.PreNotes),h||(m-=wn.ArrowSize*this.scale);let b=(m-f)/U.MaxPosition;i.beginPath();for(let e=0,t=r.length-1;e<t;e++){let t=r[e],s=r[e+1];0!==e||0===t.value||a.isTieDestination||this.paintBend(a,new Sn(0,0),t,f,y,b,p,i),a.bendType!==c.Prebend?(0===e&&(f+=2*this.scale),this.paintBend(a,t,s,f,y,b,p,i)):a.isTieOrigin&&a.tieDestination.hasBend&&(s=new Sn(U.MaxPosition,t.value),s.lineValue=t.lineValue,this.paintBend(a,t,s,f,y,b,p,i))}i.color=s}}paintBend(e,t,i,s,a,r,n,o){let h=this.renderer,l=this.renderer.resources,c=h.lineOffset/2,d=s+r*t.offset,u=wn.BendValueHeight*this.scale,p=a-u*t.lineValue;0===t.value?i.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,Qe.Top):p+=h.getNoteY(e,Qe.Center):p+=c;let g=s+r*i.offset,f=a-u*i.lineValue;0===i.lineValue?f+=h.getNoteY(e,Qe.Center):f+=c;let m=0,y=wn.ArrowSize*this.scale;if(i.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):i.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===i.value){if(t.lineValue>0){let e=g,t=wn.DashSize*this.scale,i=d+t;if((e-d)/(2*t)<1)o.moveTo(e,p),o.lineTo(d,p);else for(;e>i;)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<i.offset){o.font=l.graceFont;let e=o.measureText(n),t=0,i=0;if(p>f){let s=Math.abs(p-f);t=s>1.3*o.font.size?p-s/2:p,i=(d+g-e)/2}else t=p,i=g-e;o.fillText(n,i,t)}if(0!==i.value&&t.value!==i.value){let e=i.value,s=i.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+=wn.getFractionSign(e)),""!==r){f=a-u*i.value;let e=f;s||(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"}}}wn.ArrowSize=6,wn.DashSize=3,wn.BendValueHeight=6;class _n extends zs{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===F.Custom)return e.whammyBarPoints;let t=[];switch(e.whammyBarType){case F.Dive:case F.Hold:case F.PrediveDive:case F.Predive:t.push(new U(0,e.whammyBarPoints[0].value)),t.push(new U(U.MaxPosition,e.whammyBarPoints[1].value));break;case F.Dip:t.push(new U(0,e.whammyBarPoints[0].value)),t.push(new U(U.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new U(U.MaxPosition,e.whammyBarPoints[e.whammyBarPoints.length-1].value))}return t}doLayout(){super.doLayout(),this._isSimpleDip=this.renderer.settings.notation.notationMode===e.NotationMode.SongBook&&this._beat.whammyBarType===F.Dip;let t=null,i=null,s=this._beat;for(;s&&s.hasWhammyBar;)(!t||t.value>s.minWhammyPoint.value)&&(t=s.minWhammyPoint),(!i||i.value<s.maxWhammyPoint.value)&&(i=s.maxWhammyPoint),s=s.nextBeat;let a=i.value>0?Math.abs(this.getOffset(i.value)):0;(a>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(v.ZerosOnDiveWhammys))&&(a+=2*this.renderer.resources.tablatureFont.size);let r=t.value<0?Math.abs(this.getOffset(t.value)):0;this.renderer.registerOverflowTop(a+r),a>this.renderer.staff.getSharedLayoutData(_n.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(_n.TopOffsetSharedDataKey,a)}getOffset(e){if(0===e)return 0;let t=_n.PerHalfSize*this.scale+Math.log2(Math.abs(e)/2)*_n.PerHalfSize*this.scale;return e<0&&(t=-t),t}paint(t,i,s){let a=this.renderer,r=this._beat.nextBeat,n=null,o=qe.PreNotes;r&&(n=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.voice.bar),n&&n.staff===a.staff&&(n===a||r.hasWhammyBar)?o=!r.hasWhammyBar||a.settings.notation.notationMode===e.NotationMode.SongBook&&r.whammyBarType===F.Dip?qe.PreNotes:qe.MiddleNotes:(r=null,n=null));let h=0,c=0;this._isSimpleDip?(h=t+a.x+a.getBeatX(this._beat,qe.OnNotes)-2*this.scale,c=t+a.x+a.getBeatX(this._beat,qe.PostNotes)+2*this.scale):(h=t+a.x+a.getBeatX(this._beat,qe.MiddleNotes),c=n?t+n.x+n.getBeatX(r,o):t+a.x+a.width-2*this.scale);let d=s.textAlign;if(s.textAlign=E.Center,this._renderPoints.length>=2){let e=(c-h)/U.MaxPosition;s.beginPath();let t=i+this.renderer.staff.getSharedLayoutData(_n.TopOffsetSharedDataKey,0),a=this._beat.whammyStyle===l.Gradual?"grad.":"";for(let i=0,r=this._renderPoints.length-1;i<r;i++){let n=this._renderPoints[i],o=this._renderPoints[i+1],l=i<r-2?this._renderPoints[i+2]:null,c=0===i;0!==i||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new U(0,0),n,o,h,t,e,s),c=!1),this.paintWhammy(c,n,o,l,h,t,e,s,a),a=""}s.stroke()}s.textAlign=d}paintWhammy(e,t,i,s,a,r,n,o,h){let l=a+n*t.offset,c=a+n*i.offset,d=r-this.getOffset(t.value),u=r-this.getOffset(i.value);if(t.offset===i.offset){let e=_n.DashSize*this.scale;if(Math.abs(u-d)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(d,u),i=Math.min(d,u);for(;t>i;)o.moveTo(l,i),o.lineTo(l,i+e),i+=2*e}o.stroke()}else if(t.value===i.value){let e=_n.DashSize*this.scale;if(Math.abs(c-l)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(l,c),i=Math.min(l,c);for(;t>i;)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(v.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2*this.scale,o.fillText(h,l,e))}let g=Math.abs(i.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(v.ZerosOnDiveWhammys)&&!this._isSimpleDip)&&t.value!==i.value){let e="";if(i.value<0&&(e+="-"),g>=4){let t=g/4|0;e+=t,g-=4*t}else 0===g&&(e+="0");g>0&&(e+=wn.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(d,u)-p.tablatureFont.size-2*this.scale:(a=t.offset===i.offset?Math.min(d,u):u,a-=p.tablatureFont.size+2*this.scale,s&&s.value>i.value&&(a-=2*this.scale));let r=c;o.fillText(e,r,a)}}}_n.TopOffsetSharedDataKey="tab.whammy.topoffset",_n.PerHalfSize=6,_n.DashSize=3;class Bn extends bn{constructor(e){super(0,0),this._beat=e}doLayout(){let t=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case F.None:case F.Custom:case F.Hold:return;case F.Dive:case F.PrediveDive:{let e=new yn(this._beat,!1);e.renderer=this.renderer;let t=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let i of this._beat.notes)i.isTieOrigin||e.addGlyph(this.getBendNoteValue(i,t),t.value%2!=0);e.doLayout(),this.BendNoteHeads.push(e)}break;case F.Dip:if(t===e.NotationMode.SongBook){let e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+Bn.SimpleDipHeight*this.scale+Bn.SimpleDipPadding*this.scale}else{let t=new yn(this._beat,!1);if(t.renderer=this.renderer,this.renderer.settings.notation.notationMode===e.NotationMode.GuitarPro){let e=this._beat.whammyBarPoints[1];for(let i of this._beat.notes)t.addGlyph(this.getBendNoteValue(i,this._beat.whammyBarPoints[1]),e.value%2!=0)}t.doLayout(),this.BendNoteHeads.push(t);let i=new yn(this._beat,!1);if(i.renderer=this.renderer,this.renderer.settings.notation.notationMode===e.NotationMode.GuitarPro){let e=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let t of this._beat.notes)i.addGlyph(this.getBendNoteValue(t,e),e.value%2!=0)}i.doLayout(),this.BendNoteHeads.push(i)}case F.Predive:}super.doLayout()}paint(t,i,s){let a=this._beat;switch(a.whammyBarType){case F.None:case F.Custom:return}let r=this.renderer.settings.notation.notationMode,n=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,a.voice.bar),o=t+n.x+n.getBeatX(a,qe.MiddleNotes),h=this.getTieDirection(a,n),c=1===this._beat.notes.length?h:Ce.Up,d=s.textAlign;for(let d=0;d<a.notes.length;d++){let u=a.notes[d],p=i+n.y;d>0&&d>=(this._beat.notes.length/2|0)&&(c=Ce.Down),c===Ce.Down?p+=n.getNoteY(u,Qe.Bottom):p+=n.getNoteY(u,Qe.Top);let g=t+n.x;a.isLastOfVoice?g+=n.width:g+=n.getBeatX(a,qe.EndBeat),g-=8*this.scale;let f=a.whammyStyle===l.Gradual&&0===d?"grad.":"",m=null;u.isTieOrigin&&(m=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,u.tieDestination.beat.voice.bar),m&&m.staff===n.staff?g=t+m.x+m.getBeatX(u.tieDestination.beat,qe.MiddleNotes):m=null);let y=Ys.NoteHeadHeight*this.scale*Ys.GraceScale*.5;c===Ce.Up&&(y=-y);let b=a.whammyBarPoints.length>0?this.getBendNoteValue(u,a.whammyBarPoints[a.whammyBarPoints.length-1]):0,S=0,w=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(b)?(S=this.BendNoteHeads[0].getNoteValueY(b)+y,w=!0):m&&(u.isTieOrigin&&u.tieDestination.beat.hasWhammyBar||u.beat.isContinuedWhammy)?(S=i+m.y+m.getNoteY(u.tieDestination,Qe.Top),w=!0,c===Ce.Down&&(S+=Ys.NoteHeadHeight*this.scale)):u.isTieOrigin&&(S=m?i+m.y+m.getNoteY(u.tieDestination,Qe.Top):p,c===Ce.Down&&(S+=Ys.NoteHeadHeight*this.scale)),a.whammyBarType){case F.Hold:u.isTieOrigin&&nn.paintTie(s,this.scale,o,p,g,S,h===Ce.Down,22,4);break;case F.Dive:0===d&&(this.BendNoteHeads[0].x=g-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=i+n.y,this.BendNoteHeads[0].paint(0,0,s),this.BendNoteHeads[0].containsNoteValue(b)&&(S+=this.BendNoteHeads[0].y)),w?this.drawBendSlur(s,o,p,g,S,c===Ce.Down,this.scale,f):u.isTieOrigin&&nn.paintTie(s,this.scale,o,p,g,S,h===Ce.Down,22,4);break;case F.Dip:if(r===e.NotationMode.SongBook){if(0===d){let e=t+n.x+n.getBeatX(this._beat,qe.OnNotes)-2*this.scale,a=t+n.x+n.getBeatX(this._beat,qe.PostNotes)+2*this.scale,r=(e+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,r,i+this.y);let h=i+this.y+s.font.size+2*this.scale,l=h+Bn.SimpleDipHeight*this.scale;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(s.moveTo(e,l),s.lineTo(r,h),s.lineTo(a,l)):(s.moveTo(e,h),s.lineTo(r,l),s.lineTo(a,h)),s.stroke()}u.isTieOrigin&&nn.paintTie(s,this.scale,o,p,g,S,h===Ce.Down,22,4)}else{let e=(o+g)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=i+n.y,this.BendNoteHeads[0].paint(0,0,s);let t=this.getBendNoteValue(u,a.whammyBarPoints[1]),r=this.BendNoteHeads[0].getNoteValueY(t)+y;this.drawBendSlur(s,o,p,e,r,c===Ce.Down,this.scale,f),this.BendNoteHeads[1].x=g-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=i+n.y,this.BendNoteHeads[1].paint(0,0,s),S=this.BendNoteHeads[1].getNoteValueY(b)+y,this.drawBendSlur(s,e,r,g,S,c===Ce.Down,this.scale,f)}break;case F.PrediveDive:case F.Predive:let l=t+n.x+n.getBeatX(u.beat,qe.PreNotes);l+=n.getPreNotesGlyphForBeat(u.beat).prebendNoteHeadOffset;let m=i+n.y+n.getScoreY(n.accidentalHelper.getNoteLineForValue(u.displayValue-(u.beat.whammyBarPoints[0].value/2|0),!1))+y;this.drawBendSlur(s,l,m,o,p,c===Ce.Down,this.scale,f),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=g-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=i+n.y,this.BendNoteHeads[0].paint(0,0,s),this.drawBendSlur(s,o,p,g,S,c===Ce.Down,this.scale,f))}}s.textAlign=d}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}Bn.SimpleDipHeight=2*_n.PerHalfSize,Bn.SimpleDipPadding=2;class Tn extends zs{constructor(e,t,i){super(e,t),this.width=i}}class kn extends Xs{constructor(e,t,i,s,a){super(e,t,a?Ys.GraceScale:1,i.getSymbol(s)),this._isGrace=a,this._articulation=i}paint(e,t,i){let s=this._isGrace?this.scale:0;i.fillMusicFontSymbol(e+this.x,t+this.y+s,this.glyphScale*this.scale,this.symbol,!1),this._articulation.techniqueSymbol!==P.None&&this._articulation.techniqueSymbolPlacement===C.Middle&&i.fillMusicFontSymbol(e+this.x,t+this.y+s,this.glyphScale*this.scale,this._articulation.techniqueSymbol,!1)}doLayout(){let e=(this._isGrace?Ys.GraceScale:1)*this.scale;switch(this.symbol){case P.NoteheadWhole:this.width=14;break;case P.NoteheadCircleX:case P.NoteheadDiamondWhite:this.width=9;break;case P.NoteheadHeavyXHat:case P.NoteheadHeavyX:this.width=13;break;default:this.width=10}this.width=this.width*(this._isGrace?Ys.GraceScale:1)*this.scale,this.height=Ys.NoteHeadHeight*e}}class vn extends Xs{constructor(e,t){super(e,t,Ys.GraceScale,P.ArticStaccatoAbove)}doLayout(){this.width=Ys.QuarterNoteHeadWidth*this.scale,this.height=7*this.scale}paint(e,t,i){super.paint(e+3*this.scale,t+5*this.scale,i)}}class xn extends Xs{constructor(e,t){super(e,t,.5,P.PictEdgeOfCymbal)}doLayout(){this.width=22*this.scale,this.height=15*this.scale}paint(e,t,i){super.paint(e-3*this.scale,t+this.height,i)}}class Nn extends Xs{constructor(e,t){super(e,t,Ys.GraceScale,P.GuitarGolpe)}doLayout(){this.width=9*this.scale,this.height=10*this.scale}paint(e,t,i){super.paint(e,t+this.height,i)}}class Pn extends Za{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,i){this.noteHeads&&this.noteHeads.buildBoundingsLookup(e,t+this.x,i+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,i){this._skipPaint||super.paint(e,t,i)}doLayout(){let e=this.renderer;if(!this.container.beat.isEmpty)if(this.container.beat.isRest){let t=2*Math.ceil((this.renderer.bar.staff.standardNotationLineCount-1)/2);this.container.beat.duration===p.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const i=new gn(0,e.getScoreY(t),this.container.beat.duration);if(this.restGlyph=i,i.beat=this.container.beat,i.beamingHelper=this.beamingHelper,this.addGlyph(i),this.renderer.bar.isMultiVoice)if(0===this.container.beat.voice.index){const t=Na.computeLineHeightsForRest(this.container.beat.duration);let s=i.y-e.getScoreHeight(t[0]),a=i.y+e.getScoreHeight(t[1]);this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,s,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 Tn(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++){let e=new wa(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addGlyph(e)}}}else{const t=new pn;this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper;let i=new ln(!1);i.renderer=this.renderer;for(let e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),i.addParenthesis(e));if(this.addGlyph(t),i.isEmpty||(this.addGlyph(new Tn(0,0,4*(this.container.beat.graceType!==f.None?Ys.GraceScale:1)*this.scale)),this.addGlyph(i)),this.container.beat.hasWhammyBar){let e=new Bn(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addGlyph(new Tn(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++){let t=new wa(0,0);t.renderer=this.renderer;for(let i of this.container.beat.notes)this.createBeatDot(e.getNoteLine(i),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 i=this.renderer;t.addGlyph(new sn(0,i.getScoreY(e),1.5*this.scale))}createNoteHeadGlyph(e){let t=this.container.beat.graceType!==f.None;if(e.beat.voice.bar.staff.isPercussion){const i=K.getArticulation(e);if(i)return new kn(0,0,i,e.beat.duration,t);J.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new an(0,0,t):e.beat.graceType===f.BendGrace?new Ys(0,0,p.Quarter,!0):e.harmonicType===y.Natural?new rn(0,0,e.beat.duration,t):new Ys(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===f.BendGrace&&!e.hasBend)return;let t=this.renderer,i=this.createNoteHeadGlyph(e),s=t.getNoteLine(e);if(i.y=t.getScoreY(s),this.noteHeads.addNoteGlyph(i,e,s),e.harmonicType!==y.None&&e.harmonicType!==y.Natural){let a=e.displayValue+e.harmonicPitch;i=new rn(0,0,e.beat.duration,this.container.beat.graceType!==f.None),s=t.accidentalHelper.getNoteLineForValue(a,!1),i.y=t.getScoreY(s),this.noteHeads.addNoteGlyph(i,e,s)}if(e.isStaccato&&!this.noteHeads.aboveBeatEffects.has("Staccato")&&this.noteHeads.belowBeatEffects.set("Staccato",new vn(0,0)),e.accentuated!==a.Normal||this.noteHeads.aboveBeatEffects.has("Accent")||this.noteHeads.belowBeatEffects.set("Accent",new tn(0,0,a.Normal)),e.accentuated!==a.Heavy||this.noteHeads.aboveBeatEffects.has("HAccent")||this.noteHeads.belowBeatEffects.set("HAccent",new tn(0,0,a.Heavy)),e.isPercussion){const t=K.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==C.Middle){const e=t.techniqueSymbolPlacement===C.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case P.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new xn(0,0));break;case P.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new vn(0,0));break;case P.StringsUpBow:e.set("StringsUpBow",new Pr(0,0,N.Up));break;case P.StringsDownBow:e.set("StringsDownBow",new Pr(0,0,N.Down));break;case P.GuitarGolpe:e.set("GuitarGolpe",new Nn(0,0))}}}}}class En extends zs{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=this._beat.brushType===d.ArpeggioUp||this._beat.brushType===d.ArpeggioDown?10*this.scale:0}paint(e,t,i){if(this._beat.brushType===d.ArpeggioUp||this._beat.brushType===d.ArpeggioDown){let s=this.renderer,a=s.lineOffset,r=t+this.y+(s.getNoteY(this._beat.maxNote,Qe.Bottom)-a),n=t+this.y+s.getNoteY(this._beat.minNote,Qe.Top)+a,o=e+this.x+this.width/2,h=8*this.scale,l=new Lr(0,0,_.Slight,1.2,!0);l.renderer=this.renderer,l.doLayout();let c=-l.height/2;if(this._beat.brushType===d.ArpeggioUp){let t=r+h,s=n-h;l.width=Math.abs(s-t),i.beginRotate(e+this.x+5*this.scale,s,-90),l.paint(0,c,i),i.endRotate(),i.beginPath(),i.moveTo(o,n),i.lineTo(o+h/2,n-h),i.lineTo(o-h/2,n-h),i.closePath(),i.fill()}else if(this._beat.brushType===d.ArpeggioDown){let t=r+h,s=n;l.width=Math.abs(s-t),i.beginRotate(e+this.x+5*this.scale,t,90),l.paint(0,c,i),i.endRotate(),i.beginPath(),i.moveTo(o,r),i.lineTo(o+h/2,r+h),i.lineTo(o-h/2,r+h),i.closePath(),i.fill()}}}}class Cn extends Ka{get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}doLayout(){if(!this.container.beat.isRest){let e=new mn;e.renderer=this.renderer;let t=new ln(!0);t.renderer=this.renderer;const i=new yn(this.container.beat,!0);this._prebends=i,i.renderer=this.renderer;for(let s of this.container.beat.notes)if(s.isVisible){if(s.hasBend)switch(s.bendType){case c.PrebendBend:case c.Prebend:case c.PrebendRelease:i.addGlyph(s.displayValue-(s.bendPoints[0].value/2|0),!1)}else if(s.beat.hasWhammyBar)switch(s.beat.whammyBarType){case F.PrediveDive:case F.Predive:this._prebends.addGlyph(s.displayValue-(s.beat.whammyBarPoints[0].value/2|0),!1)}this.createAccidentalGlyph(s,e),t.addParenthesis(s)}i.isEmpty||(this.addGlyph(i),this.addGlyph(new Tn(0,0,4*(this.container.beat.graceType!==f.None?Ys.GraceScale:1)*this.scale))),this.container.beat.brushType!==d.None&&(this.addGlyph(new En(this.container.beat)),this.addGlyph(new Tn(0,0,4*this.scale))),t.isEmpty||(this.addGlyph(t),this.addGlyph(new Tn(0,0,4*(this.container.beat.graceType!==f.None?Ys.GraceScale:1)*this.scale))),e.isEmpty||(this.accidentals=e,this.addGlyph(new Tn(0,0,2*(this.container.beat.graceType!==f.None?Ys.GraceScale:1)*this.scale)),this.addGlyph(e),this.addGlyph(new Tn(0,0,2*(this.container.beat.graceType!==f.None?Ys.GraceScale:1)*this.scale)))}super.doLayout()}createAccidentalGlyph(e,t){let i=this.renderer,s=i.accidentalHelper.applyAccidental(e),a=i.getNoteLine(e),r=this.container.beat.graceType!==f.None;if(s!==Je.None){let e=new Jr(0,i.getScoreY(a),s,r);e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==y.None&&e.harmonicType!==y.Natural){let n=e.displayValue+e.harmonicPitch;s=i.accidentalHelper.applyAccidentalForValue(e.beat,n,r,!1),a=i.accidentalHelper.getNoteLineForValue(n,!1);let o=new Jr(0,i.getScoreY(a),s,r);o.renderer=this.renderer,t.addGlyph(o)}}constructor(){super(),this._prebends=null,this.accidentals=null}}class Fn extends Xs{constructor(e,t,i,s){super(e,t,s,Fn.getSymbol(i)),this._digit=0,this._scale=0,this._digit=i,this._scale=s}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 P.TimeSig0;case 1:return P.TimeSig1;case 2:return P.TimeSig2;case 3:return P.TimeSig3;case 4:return P.TimeSig4;case 5:return P.TimeSig5;case 6:return P.TimeSig6;case 7:return P.TimeSig7;case 8:return P.TimeSig8;case 9:return P.TimeSig9;default:return P.None}}}class Ln extends wa{constructor(e,t,i,s=1){super(e,t),this._number=0,this._scale=0,this._number=i,this._scale=s}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,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];i.x=e,i.y=0,i.renderer=this.renderer,i.doLayout(),e+=i.width}this.width=e}}}Ln.numberHeight=18;class Mn extends wa{constructor(e,t,i,s,a){super(e,t),this._numerator=0,this._denominator=0,this._numerator=i,this._denominator=s,this._isCommon=a}doLayout(){if(this._isCommon&&2===this._numerator&&2===this._denominator){let e=new Xs(0,0,this.commonScale,P.TimeSigCutCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){let e=new Xs(0,0,this.commonScale,P.TimeSigCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else{const e=Ln.numberHeight*this.scale;let t=new Ln(0,-e/2,this._numerator,this.numberScale),i=new Ln(0,e/2,this._denominator,this.numberScale);this.addGlyph(t),this.addGlyph(i),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 In extends Mn{get commonScale(){return 1}get numberScale(){return 1}}class Dn extends bn{constructor(e){super(0,0),this._notes=[],this._endNoteGlyph=null,this._middleNoteGlyph=null,this._beat=e}addBends(e){if(this._notes.push(e),!e.isTieOrigin)switch(e.bendType){case c.Bend:case c.PrebendRelease:case c.PrebendBend:{let t=this._endNoteGlyph;t||(t=new yn(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let i=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0)}break;case c.Release:if(!e.isTieOrigin){let t=this._endNoteGlyph;t||(t=new yn(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let i=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0)}break;case c.BendRelease:{let t=this._middleNoteGlyph;t||(t=new yn(e.beat,!1),this._middleNoteGlyph=t,t.renderer=this.renderer,this.BendNoteHeads.push(t));let i=e.bendPoints[1];t.addGlyph(this.getBendNoteValue(e,e.bendPoints[1]),i.value%2!=0);let s=this._endNoteGlyph;s||(s=new yn(e.beat,!1),s.renderer=this.renderer,this._endNoteGlyph=s,this.BendNoteHeads.push(s));let a=e.bendPoints[e.bendPoints.length-1];s.addGlyph(this.getBendNoteValue(e,a),a.value%2!=0)}}}paint(e,t,i){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._beat.voice.bar),a=e+s.x+s.getBeatX(this._beat,qe.MiddleNotes),r=e+s.x;this._beat.isLastOfVoice?r+=s.postBeatGlyphsStart:r+=s.getBeatX(this._beat.nextBeat,qe.PreNotes),r-=8*this.scale;let n=(a+r)/2;this._middleNoteGlyph&&(this._middleNoteGlyph.x=n-this._middleNoteGlyph.noteHeadOffset,this._middleNoteGlyph.y=t+s.y,this._middleNoteGlyph.paint(0,0,i)),this._endNoteGlyph&&(this._endNoteGlyph.x=r-this._endNoteGlyph.noteHeadOffset,this._endNoteGlyph.y=t+s.y,this._endNoteGlyph.paint(0,0,i)),this._notes.sort(((e,t)=>t.displayValue-e.displayValue));let o=this._beat.graceType===f.BendGrace?this._beat.nextBeat:this._beat,h=1===this._notes.length?this.getTieDirection(o,s):Ce.Up;for(let o=0;o<this._notes.length;o++){let d=this._notes[o];o>0&&o>=(this._notes.length/2|0)&&(h=Ce.Down);let u=t+s.y+s.getNoteY(d,Qe.Top),p=Ys.NoteHeadHeight*this.scale*Ys.GraceScale*.5;h===Ce.Down&&(u+=Ys.NoteHeadHeight*this.scale);let g=d.bendStyle===l.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===s.staff){let s=e+n.x+n.getBeatX(r.beat,qe.MiddleNotes),o=t+n.y+n.getNoteY(r,Qe.Top);h===Ce.Down&&(o+=Ys.NoteHeadHeight*this.scale),d.bendType===c.Hold||d.bendType===c.Prebend?nn.paintTie(i,this.scale,a,u,s,o,h===Ce.Down,22,4):this.drawBendSlur(i,a,u,s,o,h===Ce.Down,this.scale,g)}else{let r=e+s.x+s.width,n=d.tieDestination.realValue;s.accidentalHelper.applyAccidentalForValue(d.beat,n,!1,!0);let o=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(n,!1));d.bendType===c.Hold||d.bendType===c.Prebend?nn.paintTie(i,this.scale,a,u,r,o,h===Ce.Down,22,4):this.drawBendSlur(i,a,u,r,o,h===Ce.Down,this.scale,g)}switch(d.bendType){case c.Prebend:case c.PrebendBend:case c.PrebendRelease:let r=e+s.x+s.getBeatX(d.beat,qe.PreNotes);r+=s.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let n=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(d.displayValue-(d.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(i,r,n,a,u,h===Ce.Down,this.scale)}}else{h===Ce.Up&&(p=-p);let o=0,l=0;switch(d.bendType){case c.Bend:o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,l,h===Ce.Down,this.scale,g);break;case c.BendRelease:let f=this.getBendNoteValue(d,d.bendPoints[1]),m=this._middleNoteGlyph.getNoteValueY(f)+p;this.drawBendSlur(i,a,u,n,m,h===Ce.Down,this.scale,g),o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(i,n,m,r,l,h===Ce.Down,this.scale,g);break;case c.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,l,h===Ce.Down,this.scale,g));break;case c.Prebend:case c.PrebendBend:case c.PrebendRelease:let y=e+s.x+s.getBeatX(d.beat,qe.PreNotes);y+=s.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let b=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(d.displayValue-(d.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(i,y,b,a,u,h===Ce.Down,this.scale),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,l,h===Ce.Down,this.scale,g))}}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class An extends nn{constructor(e,t,i=!1){super(e,t,i)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?Ce.Up:t.getBeatDirection(e)===Ce.Up?Ce.Down:Ce.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Ce.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,Qe.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,Qe.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===Ce.Up?e.getScoreY(9):e.getScoreY(0);const t=this.startNoteRenderer.getBeatDirection(this.startBeat),i=e.getBeatDirection(this.endBeat);return t!==i&&this.startBeat.graceType===f.None?i===this.tieDirection?this.tieDirection===Ce.Up?e.getNoteY(this.endBeat.maxNote,Qe.TopWithStem):e.getNoteY(this.endBeat.minNote,Qe.BottomWithStem):this.tieDirection===Ce.Up?e.getNoteY(this.endBeat.maxNote,Qe.BottomWithStem):e.getNoteY(this.endBeat.minNote,Qe.TopWithStem):this.tieDirection===Ce.Up?e.getNoteY(this.endBeat.maxNote,Qe.Top):e.getNoteY(this.endBeat.minNote,Qe.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,qe.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>p.Whole&&e===this.tieDirection?qe.Stem:qe.MiddleNotes)}}class Rn extends zs{constructor(e,t,i,s){super(0,0),this._outType=t,this._inType=e,this._startNote=i,this._parent=s}doLayout(){this.width=0}paint(e,t,i){this.paintSlideIn(e,t,i),this.drawSlideOut(e,t,i)}paintSlideIn(e,t,i){let s=this.renderer,a=12*this.scale,r=e+s.x+s.getNoteX(this._startNote,$e.Left)-2*this.scale,n=t+s.y+s.getNoteY(this._startNote,Qe.Center),o=r-a,h=t+s.y;switch(this._inType){case S.IntoFromBelow:h+=s.getNoteY(this._startNote,Qe.Bottom);break;case S.IntoFromAbove:h+=s.getNoteY(this._startNote,Qe.Top);break;default:return}let l=this.getAccidentalsWidth(s,this._startNote.beat);o-=l,r-=l,this.paintSlideLine(i,!1,o,r,h,n)}getAccidentalsWidth(e,t){let i=e.getPreNotesGlyphForBeat(t);return i&&i.accidentals?i.accidentals.width:0}drawSlideOut(e,t,i){let s=this.renderer,a=12*this.scale,r=1*this.scale,n=2*this.scale,o=0,h=0,l=0,c=0,d=!1;switch(this._outType){case w.Shift:case w.Legato:if(o=e+s.x+s.getBeatX(this._startNote.beat,qe.PostNotes),h=t+s.y+s.getNoteY(this._startNote,Qe.Center),this._startNote.slideTarget){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);i&&i.staff===s.staff?(l=e+i.x+i.getBeatX(this._startNote.slideTarget.beat,qe.PreNotes)-r,c=t+i.y+i.getNoteY(this._startNote.slideTarget,Qe.Center)):(l=e+s.x+s.width,c=h),this._startNote.slideTarget.realValue>this._startNote.realValue?(h+=n,c-=n):(h-=n,c+=n)}else l=e+s.x+this._parent.x,c=h;break;case w.OutUp:o=e+s.x+s.getNoteX(this._startNote,$e.Right),h=t+s.y+s.getNoteY(this._startNote,Qe.Center),l=o+a,c=t+s.y+s.getNoteY(this._startNote,Qe.Top);break;case w.OutDown:o=e+s.x+s.getNoteX(this._startNote,$e.Right),h=t+s.y+s.getNoteY(this._startNote,Qe.Center),l=o+a,c=t+s.y+s.getNoteY(this._startNote,Qe.Bottom);break;case w.PickSlideUp:o=e+s.x+s.getNoteX(this._startNote,$e.Right),h=t+s.y+s.getNoteY(this._startNote,Qe.Center),c=t+s.y+s.getNoteY(this._startNote,Qe.Top),l=e+s.x+s.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(l=e+s.x+s.getBeatX(this._startNote.beat.nextBeat,qe.PreNotes)),d=!0;break;case w.PickSlideDown:o=e+s.x+s.getNoteX(this._startNote,$e.Right),h=t+s.y+s.getNoteY(this._startNote,Qe.Center),c=t+s.y+s.getNoteY(this._startNote,Qe.Bottom),l=e+s.x+s.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(l=e+s.x+s.getBeatX(this._startNote.beat.nextBeat,qe.PreNotes)),d=!0;break;default:return}this.paintSlideLine(i,d,o,l,h,c)}paintSlideLine(e,t,i,s,a,r){if(t){let t=new Lr(0,0,_.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;let n=s-i,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(i,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(i,a),e.lineTo(s,r),e.stroke()}}class On extends An{constructor(e,t,i=!1){super(e.beat,t.beat,i),this._startNote=e,this._endNote=t}getTieHeight(e,t,i,s){return Math.log2(i-e+1)*this.renderer.settings.notation.slurHeight}getStartY(){return this.isStartCentered()?this.tieDirection===Ce.Up?this.startNoteRenderer.getNoteY(this._startNote,Qe.Top):this.startNoteRenderer.getNoteY(this._startNote,Qe.Bottom):this.startNoteRenderer.getNoteY(this._startNote,Qe.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===Ce.Up?this.endNoteRenderer.getNoteY(this._endNote,Qe.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,Qe.BottomWithStem):this.tieDirection===Ce.Up?this.endNoteRenderer.getNoteY(this._endNote,Qe.Top):this.endNoteRenderer.getNoteY(this._endNote,Qe.Bottom):this.endNoteRenderer.getNoteY(this._endNote,Qe.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===Ce.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===Ce.Down}isEndCentered(){return this._startNote.beat.graceType===f.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===Ce.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===Ce.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===f.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,qe.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,$e.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,qe.Stem):this.endNoteRenderer.getNoteX(this._endNote,$e.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,qe.PreNotes)}}class Gn extends nn{constructor(e,t,i=!1){super(e?e.beat:null,t?t.beat:null,i),this.startNote=e,this.endNote=t}shouldDrawBendSlur(){return this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&!!this.startNote.bendOrigin&&this.startNote.isTieOrigin}doLayout(){super.doLayout()}getBeamDirection(e,t){return t.getBeatDirection(e)===Ce.Up?Ce.Down:Ce.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Ce.Up?this.startNoteRenderer.getNoteY(this.startNote,Qe.Top):this.startNoteRenderer.getNoteY(this.startNote,Qe.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===Ce.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===Ce.Up?e.getNoteY(this.endNote,Qe.Top):e.getNoteY(this.endNote,Qe.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,qe.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,qe.PreNotes)}}class Vn extends Js{constructor(e,t){super(e,t),this._bend=null,this._effectSlur=null,this._effectEndSlur=null}doLayout(){if(this._effectSlur=null,this._effectEndSlur=null,super.doLayout(),this.beat.isLegatoOrigin){if(!this.beat.previousBeat||!this.beat.previousBeat.isLegatoOrigin){let e=this.beat.nextBeat;for(;e.nextBeat&&e.nextBeat.isLegatoDestination;)e=e.nextBeat;this.addTie(new An(this.beat,e,!1))}}else if(this.beat.isLegatoDestination&&!this.beat.isLegatoOrigin){let e=this.beat.previousBeat;for(;e.previousBeat&&e.previousBeat.isLegatoOrigin;)e=e.previousBeat;this.addTie(new An(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!==f.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){let t=new Gn(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){let t=new Gn(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==S.None||e.slideOutType!==w.None){let t=new Rn(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){let t=new On(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){let t=new On(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new On(e,e.effectSlurDestination,!1);this._effectSlur=t,this.addTie(t)}if(!this._effectEndSlur&&e.beat.isEffectSlurDestination&&e.beat.effectSlurOrigin){let t=this.onNotes.beamingHelper.direction,i=t===Ce.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,s=t===Ce.Up?e.beat.minNote:e.beat.maxNote;const a=new On(i,s,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new Dn(e.beat);this._bend=t,t.renderer=this.renderer,this.addTie(t)}this._bend.addBends(e)}}}}class Hn extends qa{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._firstLineY=0,this._startSpacing=!1,this.accidentalHelper=new ka(this)}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}get lineOffset(){return(qa.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),i=this.simpleWhammyOverflow;this.registerOverflowTop(i);let s=this.getScoreY(this.accidentalHelper.maxLine),a=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);a.direction===Ce.Up&&(s-=this.getStemSize(a),s-=a.fingeringCount*this.resources.graceFont.size,a.hasTuplet&&(s-=2*this.resources.effectFont.size)),a.hasTuplet&&(s-=1.5*this.resources.effectFont.size),s<e&&this.registerOverflowTop(Math.abs(s)+i);let r=this.getScoreY(this.accidentalHelper.minLine),n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);n.direction===Ce.Down&&(r+=this.getStemSize(n),r+=n.fingeringCount*this.resources.graceFont.size),r>t&&this.registerOverflowBottom(Math.abs(r)-t)}}paint(e,t,i){super.paint(e,t,i),this.paintBeams(e,t,i),this.paintTuplets(e,t,i)}paintTuplets(e,t,i){for(let s of this.bar.voices)if(this.hasVoiceContainer(s)){let a=this.getVoiceContainer(s);for(let s of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,i,s)}}paintBeams(e,t,i){for(let s=0,a=this.helpers.beamHelpers.length;s<a;s++){let a=this.helpers.beamHelpers[s];for(let s=0,r=a.length;s<r;s++){let r=a[s];this.paintBeamHelper(e+this.beatGlyphsStart,t,i,r)}}}paintBeamHelper(e,t,i,s){i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.isRestBeamHelper||(1===s.beats.length?this.paintFlag(e,t,i,s):this.paintBar(e,t,i,s))}paintTupletHelper(e,t,i,s){let a,r=this.resources,n=i.textAlign,o=i.textBaseline;i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.textAlign=E.Center,i.textBaseline=C.Middle;let h=s.beats[0].tupletNumerator,l=s.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!==s.beats.length&&s.isFull){let n=s.beats[0],o=s.beats[s.beats.length-1],h=null,l=null;for(let e=0;e<s.beats.length;e++)if(!s.beats[e].isRest){h=s.beats[e];break}for(let e=s.beats.length-1;e>=0;e--)if(!s.beats[e].isRest){l=s.beats[e];break}let u=!1;h||(h=n,u=!0),l||(l=o);let p=this.helpers.beamHelperLookup[s.voice.index].get(n.index),g=this.helpers.beamHelperLookup[s.voice.index].get(o.index),f=p.getBeatLineX(n),m=g.getBeatLineX(o),y=this.helpers.beamHelperLookup[s.voice.index].get(h.index),b=this.helpers.beamHelperLookup[s.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),i.font=r.effectFont;let B=i.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===Ce.Down&&(c*=-1,d*=-1),i.beginPath(),i.moveTo(e+this.x+f,t+this.y+w-c|0),i.lineTo(e+this.x+f,t+this.y+w-c-d|0),i.lineTo(e+this.x+v,t+this.y+E-c-d|0),i.stroke(),i.beginPath(),i.moveTo(e+this.x+x,t+this.y+F-c-d|0),i.lineTo(e+this.x+m,t+this.y+_-c-d|0),i.lineTo(e+this.x+m,t+this.y+_-c|0),i.stroke(),i.fillText(a,e+this.x+k,t+this.y+C-c-d)}else for(let n=0,o=s.beats.length;n<o;n++){let o=s.beats[n],h=this.helpers.beamHelperLookup[s.voice.index].get(o.index);if(!h)continue;let l=h.direction,u=h.getBeatLineX(o),p=this.calculateBeamYWithDirection(h,u,l);l===Ce.Down&&(c*=-1,d*=-1),i.font=r.effectFont,i.fillText(a,e+this.x+u,t+this.y+p-c-d)}i.textAlign=n,i.textBaseline=o}getStemSize(e){let t=1===e.beats.length?this.getFlagStemSize(e.shortestDuration):this.getBarStemSize(e.shortestDuration);return e.isGrace&&(t*=Ys.GraceScale),t}getBarStemSize(e){let t=0;switch(e){case p.QuadrupleWhole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:t=6;break;case p.ThirtySecond:t=8;break;case p.SixtyFourth:case p.OneHundredTwentyEighth:t=9;break;case p.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}getFlagStemSize(e){let t=0;switch(e){case p.QuadrupleWhole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:case p.ThirtySecond:case p.SixtyFourth:case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:t=6;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){let i=super.getNoteY(e,t);if(isNaN(i)){const t=ka.computeLineWithoutAccidentals(this.bar,e);i=this.getScoreY(t)}return i}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),i=this.helpers.collisionHelper.getBeatMinMaxY();i[0]<e&&this.registerOverflowTop(Math.abs(i[0])),i[1]>t&&this.registerOverflowBottom(Math.abs(i[1])-t)}return e}calculateBeamYWithDirection(e,t,i){let s=this.getStemSize(e);if(!e.drawingInfos.has(i)){let t=new xa;e.drawingInfos.set(i,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?i===Ce.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):i===Ce.Up?this.getScoreY(this.accidentalHelper.getMinLine(a))-s:this.getScoreY(this.accidentalHelper.getMaxLine(a))+s,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?i===Ce.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):i===Ce.Up?this.getScoreY(this.accidentalHelper.getMinLine(r))-s:this.getScoreY(this.accidentalHelper.getMaxLine(r))+s;let o=10*this.scale;if(i===Ce.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),i===Ce.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),i===Ce.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),i===Ce.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(i===Ce.Up){let i=this.getScoreY(this.accidentalHelper.getMinLine(e.beatOfHighestNote))-s;const a=t.calcY(e.getBeatLineX(e.beatOfHighestNote))-i;a>0&&(t.startY-=a,t.endY-=a)}else{const i=this.getScoreY(this.accidentalHelper.getMaxLine(e.beatOfLowestNote))+s-t.calcY(e.getBeatLineX(e.beatOfLowestNote));i>0&&(t.startY+=i,t.endY+=i)}if(null!==e.minRestLine||null!==e.maxRestLine){const s=Q.getIndex(e.shortestDuration)-2;let a=e.isGrace?Ys.GraceScale:1,r=s*(qa.BeamSpacing+qa.BeamThickness)*this.scale*a;if(r+=qa.BeamSpacing,i===Ce.Up&&null!==e.minRestLine){let i=this.getScoreY(e.minRestLine)-r;const s=t.calcY(e.getBeatLineX(e.beatOfMinRestLine))-i;s>0&&(t.startY-=s,t.endY-=s)}else if(i===Ce.Down&&null!==e.maxRestLine){const i=this.getScoreY(e.maxRestLine)+r-t.calcY(e.getBeatLineX(e.beatOfMaxRestLine));i>0&&(t.startY+=i,t.endY+=i)}}}}return e.drawingInfos.get(i).calcY(t)}paintBar(e,t,i,s){for(let a=0,r=s.beats.length;a<r;a++){let r=s.beats[a],n=r.graceType!==f.None?Ys.GraceScale:1,o=s.getBeatLineX(r),h=s.direction,l=t+this.y;l+=h===Ce.Up?this.getScoreY(this.accidentalHelper.getMaxLine(r)):this.getScoreY(this.accidentalHelper.getMinLine(r));let c=t+this.y;c+=this.calculateBeamY(s,o),i.lineWidth=qa.StemWidth*this.scale,i.beginPath(),i.moveTo(e+this.x+o,l),i.lineTo(e+this.x+o,c),i.stroke(),i.lineWidth=this.scale;let d=c;h===Ce.Down?d+=2*i.font.size:0!==a&&(d-=1.5*i.font.size),this.paintFingering(i,r,e+this.x+o,h,d);let u=6*this.scale*n,p=(qa.BeamSpacing+qa.BeamThickness)*this.scale*n,g=qa.BeamThickness*this.scale*n,m=Q.getIndex(r.duration)-2,y=t+this.y;h===Ce.Down&&(p=-p,g=-g);for(let t=0;t<m;t++){let n=0,h=0,l=0,c=0,d=y+t*p;if(a<s.beats.length-1){if(Na.isFullBarJoin(r,s.beats[a+1],t))n=o,h=s.getBeatLineX(s.beats[a+1]);else{if(0!==a&&Na.isFullBarJoin(s.beats[a-1],r,t))continue;n=o,h=n+u}l=d+this.calculateBeamY(s,n),c=d+this.calculateBeamY(s,h),Hn.paintSingleBar(i,e+this.x+n,l,e+this.x+h,c,g)}else a>0&&!Na.isFullBarJoin(r,s.beats[a-1],t)&&(n=o-u,h=o,l=d+this.calculateBeamY(s,n),c=d+this.calculateBeamY(s,h),Hn.paintSingleBar(i,e+this.x+n,l,e+this.x+h,c,g))}}}static paintSingleBar(e,t,i,s,a,r){e.beginPath(),e.moveTo(t,i),e.lineTo(s,a),e.lineTo(s,a+r),e.lineTo(t,i+r),e.closePath(),e.fill()}paintFlag(t,i,s,a){let r=a.beats[0];if(r.graceType===f.BendGrace||r.graceType!==f.None&&this.settings.notation.notationMode===e.NotationMode.SongBook)return;let n=r.graceType!==f.None,o=n?Ys.GraceScale:1,h=this.getFlagStemSize(a.shortestDuration),l=a.getBeatLineX(r),c=a.direction,d=this.getScoreY(this.accidentalHelper.getMinLine(r)),u=this.getScoreY(this.accidentalHelper.getMaxLine(r)),p=0,g=0;if(c===Ce.Down?(u+=h*o,p=u,g=i+this.y+u):(d-=h*o,p=d,g=i+this.y+d),this.paintFingering(s,r,t+this.x+l,c,g),a.hasLine){if(s.lineWidth=qa.StemWidth*this.scale,s.beginPath(),s.moveTo(t+this.x+l,i+this.y+d),s.lineTo(t+this.x+l,i+this.y+u),s.stroke(),s.lineWidth=this.scale,r.graceType===f.BeforeBeat){let e=15*this.scale,a=12*this.scale;s.beginPath(),c===Ce.Down?(s.moveTo(t+this.x+l-a/2,i+this.y+u-e),s.lineTo(t+this.x+l+a/2,i+this.y+u)):(s.moveTo(t+this.x+l-a/2,i+this.y+d+e),s.lineTo(t+this.x+l+a/2,i+this.y+d)),s.stroke()}if(a.hasFlag){let e=new qs(l-this.scale/2,p,r.duration,c,n);e.renderer=this,e.doLayout(),e.paint(t+this.x,i+this.y,s)}}}paintFingering(t,i,s,a,r){let n=this.settings;if(n.notation.fingeringMode!==e.FingeringMode.ScoreDefault&&n.notation.fingeringMode!==e.FingeringMode.ScoreForcePiano)return;a===Ce.Up?s-=10*this.scale:s+=3*this.scale;let o=i.notes.slice(0);o.sort(((e,t)=>e.realValue-t.realValue));for(let e=0;e<o.length;e++){let a=o[e],h=null;a.leftHandFinger!==m.Unknown?h=Q.fingerToString(n,i,a.leftHandFinger,!0):a.rightHandFinger!==m.Unknown&&(h=Q.fingerToString(n,i,a.rightHandFinger,!1)),h&&(t.fillText(h,s,r),r-=0|t.font.size)}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new en(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 n.Neutral:e=this.bar.staff.standardNotationLineCount-1;break;case n.F4:e=2;break;case n.C3:e=4;break;case n.C4:e=2;break;case n.G2:e=6}this.createStartSpacing(),this.addPreBeatGlyph(new $r(0,this.getScoreY(e)+.5*qa.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 jr(0,this.getScoreHeight(-.5),this.bar.index+1))}createBeatGlyphs(){for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];this.hasVoiceContainer(t)&&this.createVoiceGlyphs(t)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new Kr(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Zr(0,this.getScoreHeight(-.5),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new Qr(0,0))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new Tn(0,0,2*this.scale)),this._startSpacing=!0)}createKeySignatureGlyphs(){let e=0,t=this.bar.masterBar.keySignature,i=this.bar.previousBar?this.bar.previousBar.masterBar.keySignature:0;switch(this.bar.clef){case n.Neutral:e=0;break;case n.G2:e=1;break;case n.F4:e=3;break;case n.C3:e=2;break;case n.C4:e=0}let s=new Map,a=[];if(Q.keySignatureIsSharp(t))for(let i=0;i<Math.abs(t);i++){let t=Hn.SharpKsSteps[i]+e;a.push(new Jr(0,this.getScoreY(t),Je.Sharp,!1)),s.set(t,!0)}else for(let i=0;i<Math.abs(t);i++){let t=Hn.FlatKsSteps[i]+e;a.push(new Jr(0,this.getScoreY(t),Je.Flat,!1)),s.set(t,!0)}let r=Math.abs(i),o=Q.keySignatureIsSharp(i)?Hn.SharpKsSteps:Hn.FlatKsSteps;for(let t=0;t<r;t++){let i=o[t]+e;s.has(i)||this.addPreBeatGlyph(new Jr(0,this.getScoreY(o[t]+e),Je.Natural,!1))}for(let e of a)this.addPreBeatGlyph(e)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Tn(0,0,5*this.scale));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new In(0,this.getScoreY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,i=e.beats.length;t<i;t++){let i=e.beats[t],s=new Vn(i,this.getVoiceContainer(e));s.preNotes=new Cn,s.onNotes=new Pn,this.addBeatGlyph(s)}}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,i){super.paintBackground(e,t,i);let s=this.resources;i.color=s.staffLineColor;for(let s=0;s<this.bar.staff.standardNotationLineCount;s++){const a=t+this.y+this.getScoreY(2*s);i.fillRect(e+this.x,0|a,this.width,this.scale*qa.StaffLineThickness)}i.color=s.mainGlyphColor,this.paintSimileMark(e,t,i)}completeBeamingHelper(e){if(this.bar.isMultiVoice&&e.highestNoteInHelper&&e.lowestNoteInHelper){let t=this.getNoteY(e.highestNoteInHelper,Qe.Center),i=this.getNoteY(e.lowestNoteInHelper,Qe.Center),s=this.getStemSize(e);e.hasTuplet&&(s+=2*this.resources.effectFont.size),e.direction==Ce.Up?t-=s:i+=s;for(const s of e.beats)this.helpers.collisionHelper.reserveBeatSlot(s,t,i)}}}Hn.StaffId="score",Hn.SharpKsSteps=[-1,2,-2,1,4,0,3],Hn.FlatKsSteps=[3,0,4,1,5,2,6];class Wn extends Sa{get staffId(){return Hn.StaffId}create(e,t){return new Hn(e,t)}constructor(){super()}}class zn extends zs{constructor(e,t,i,s){super(0,0),this._inType=e,this._outType=t,this._startNote=i,this._parent=s}doLayout(){this.width=0}paint(e,t,i){this.paintSlideIn(e,t,i),this.paintSlideOut(e,t,i)}paintSlideIn(e,t,i){let s=this.renderer,a=12*this.scale,r=3*this.scale,n=0,o=0,h=0,l=0;switch(this._inType){case S.IntoFromBelow:h=e+s.x+s.getNoteX(this._startNote,$e.Left),l=t+s.y+s.getNoteY(this._startNote,Qe.Center),n=h-a,o=t+s.y+s.getNoteY(this._startNote,Qe.Center)+r;break;case S.IntoFromAbove:h=e+s.x+s.getNoteX(this._startNote,$e.Left),l=t+s.y+s.getNoteY(this._startNote,Qe.Center),n=h-a,o=t+s.y+s.getNoteY(this._startNote,Qe.Center)-r;break;default:return}this.paintSlideLine(i,!1,n,h,o,l)}paintSlideOut(e,t,i){let s=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 w.Shift:case w.Legato:if(n=e+s.x+s.getBeatX(this._startNote.beat,qe.PostNotes),o=t+s.y+s.getNoteY(this._startNote,Qe.Center),this._startNote.slideTarget){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);i&&i.staff===s.staff?(h=e+i.x+i.getBeatX(this._startNote.slideTarget.beat,qe.OnNotes)-d,l=t+i.y+i.getNoteY(this._startNote.slideTarget,Qe.Center)):(h=e+s.x+s.width,l=o),this._startNote.slideTarget.fret>this._startNote.fret?(o+=r,l-=r):(o-=r,l+=r)}else h=e+s.x+this._parent.x,l=o;break;case w.OutUp:n=e+s.x+s.getNoteX(this._startNote,$e.Right),o=t+s.y+s.getNoteY(this._startNote,Qe.Center),h=n+a-d,l=t+s.y+s.getNoteY(this._startNote,Qe.Center)-r;break;case w.OutDown:n=e+s.x+s.getNoteX(this._startNote,$e.Right),o=t+s.y+s.getNoteY(this._startNote,Qe.Center),h=n+a-d,l=t+s.y+s.getNoteY(this._startNote,Qe.Center)+r;break;case w.PickSlideDown:n=e+s.x+s.getNoteX(this._startNote,$e.Right),o=t+s.y+s.getNoteY(this._startNote,Qe.Center),h=e+s.x+s.getBeatX(this._startNote.beat,qe.EndBeat),l=o+3*r,c=!0;break;case w.PickSlideUp:n=e+s.x+s.getNoteX(this._startNote,$e.Right),o=t+s.y+s.getNoteY(this._startNote,Qe.Center),h=e+s.x+s.getBeatX(this._startNote.beat,qe.EndBeat),l=o-3*r,c=!0;break;default:return}this.paintSlideLine(i,c,n,h,o,l)}paintSlideLine(e,t,i,s,a,r){if(t){let t=new Lr(0,0,_.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;let n=s-i,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(i,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(i,a),e.lineTo(s,r),e.stroke()}}class Un extends nn{constructor(e,t,i=!1){super(e.beat,t.beat,i),this.startNote=e,this.endNote=t}getTieHeight(e,t,i,s){return this.startNote===this.endNote?15:super.getTieHeight(e,t,i,s)}getBeamDirection(e,t){return this.startNote===this.endNote?Ce.Up:Un.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?Ce.Up:Ce.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,Qe.Center):this.tieDirection===Ce.Up?this.startNoteRenderer.getNoteY(this.startNote,Qe.Top):this.startNoteRenderer.getNoteY(this.startNote,Qe.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20*this.scale:this.startNoteRenderer.getNoteX(this.startNote,$e.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,$e.Left):this.endNoteRenderer.getNoteX(this.endNote,$e.Center)}}class Xn extends Un{constructor(e,t,i,s=!1){super(e,t,s),this._direction=Un.getBeamDirectionForNote(e),this._forSlide=i}getTieHeight(e,t,i,s){return Math.log(i-e+1)*this.renderer.settings.notation.slurHeight}tryExpand(e,t,i,s){if(this._forSlide!==i)return!1;if(this.forEnd!==s)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!==Un.getBeamDirectionForNote(e))return!1;switch(this._direction){case Ce.Up:e.realValue>this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue>this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat);break;case Ce.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,i){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar),a=this.getBeamDirection(this.startBeat,s),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,i))}}class Yn extends Js{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 Un(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){let t=new Un(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new Un(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(let i of this._effectSlurs)if(i.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){let t=new Xn(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(let i of this._effectSlurs)if(i.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){let t=new Xn(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==S.None||e.slideOutType!==w.None){let t=new zn(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new wn;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class qn extends zs{constructor(e,t,i){super(e,t),this._noteString=null,this._trillNoteString=null,this._trillNoteStringWidth=0,this.isEmpty=!1,this.noteStringWidth=0,this._note=i}doLayout(){let t=this._note,i=t.fret-t.beat.voice.bar.staff.transpositionPitch;if(t.harmonicType===y.Natural&&0!==t.harmonicValue&&(i=t.harmonicValue-t.beat.voice.bar.staff.transpositionPitch),t.isTieDestination)0===t.beat.index&&this.renderer.settings.notation.notationMode==e.NotationMode.GuitarPro||(t.bendType===c.Bend||t.bendType===c.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(v.TabNotesOnTiedBends)?this._noteString="("+(t.tieOrigin.fret-t.beat.voice.bar.staff.transpositionPitch).toString()+")":this._noteString="";else if(this._noteString=t.isDead?"x":i.toString(),t.isGhost)this._noteString="("+this._noteString+")";else if(t.harmonicType===y.Natural){let e=this._noteString.indexOf(String.fromCharCode(46));e>=0&&(this._noteString=this._noteString.substr(0,e+2)),this._noteString="<"+this._noteString+">"}if(t.isTrill)this._trillNoteString="("+(t.trillFret-t.beat.voice.bar.staff.transpositionPitch).toString()+")";else if(Q.isAlmostEqualTo(t.harmonicValue,0))this._trillNoteString="";else switch(t.harmonicType){case y.Artificial:case y.Pinch:case y.Tap:case y.Semi:case y.Feedback:let e=(i+t.harmonicValue).toString(),s=e.indexOf(String.fromCharCode(46));s>=0&&(e=e.substr(0,s+2)),this._trillNoteString="<"+e+">";break;default:this._trillNoteString=""}if(this.isEmpty=!this._noteString,!this.isEmpty){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.tablatureFont,this.noteStringWidth=this.renderer.scoreRenderer.canvas.measureText(this._noteString)*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,i){if(this.isEmpty)return;let s=this.noteStringWidth+this._trillNoteStringWidth,a=e+this.x+(this.width-s)/2,r=this.renderer.scoreRenderer.canvas.font;this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,i.fillText(this._trillNoteString,a+this.noteStringWidth+3*this.scale,t+this.y),this.renderer.scoreRenderer.canvas.font=r,i.fillText(this._noteString,a,t+this.y)}buildBoundingsLookup(e,t,i){let s=new vs;s.note=this._note,s.noteHeadBounds=new nt,s.noteHeadBounds.x=t+this.x,s.noteHeadBounds.y=i+this.y-this.height/2,s.noteHeadBounds.w=this.width,s.noteHeadBounds.h=this.height,e.addNote(s)}}class Jn extends zs{constructor(e,t,i){super(e,t),this._notes=[],this.minStringNote=null,this.beatEffects=new Map,this.notesPerString=new Map,this.noteStringWidth=0,this._isGrace=i}buildBoundingsLookup(e,t,i){for(const s of this._notes)s.buildBoundingsLookup(e,t+this.x,i+this.y)}getNoteX(e,t){if(this.notesPerString.has(e.string)){let i=this.notesPerString.get(e.string),s=this.x+i.x;switch(t){case $e.Left:break;case $e.Center:s+=i.noteStringWidth/2;break;case $e.Right:s+=i.width}return s}return 0}getNoteY(e,t){if(this.notesPerString.has(e.string)){const i=this.notesPerString.get(e.string);let s=this.y+i.y;switch(t){case Qe.Top:case Qe.TopWithStem:s-=i.height/2+2*this.scale;break;case Qe.Center:break;case Qe.Bottom:case Qe.BottomWithStem:s+=i.height/2}return s}return 0}doLayout(){let e=0,t=0;for(let i=0,s=this._notes.length;i<s;i++){let s=this._notes[i];s.renderer=this.renderer,s.doLayout(),s.width>e&&(e=s.width),s.noteStringWidth>t&&(t=s.noteStringWidth)}this.noteStringWidth=t;let i=this.renderer.resources.tablatureFont.size,s=this.getNoteY(this.minStringNote,Qe.Center)+i/2,a=7*this.scale;for(const e of this.beatEffects.values())e.y+=s,e.x+=this.width/2,e.renderer=this.renderer,s+=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,i){e+=this.x,t+=this.y;let s=this.renderer.resources,a=i.textBaseline;i.textBaseline=C.Middle,i.font=this._isGrace?s.graceFont:s.tablatureFont;let r=this._notes,n=this.width;for(let s of r)s.renderer=this.renderer,s.width=n,s.paint(e,t,i);i.textBaseline=a;for(const s of this.beatEffects.values())s.paint(e,t,i)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class jn extends Xs{constructor(e,t,i,s){super(e,t,1,gn.getSymbol(s)),this._isVisibleRest=i,this._duration=s}doLayout(){this._isVisibleRest?this.width=gn.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,i){this._isVisibleRest&&super.paint(e,t,i)}}class Qn extends Za{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,i){this.noteNumbers&&this.noteNumbers.buildBoundingsLookup(e,t+this.x,i+this.y)}doLayout(){let t=this.renderer;if(this.container.beat.isRest){let e=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),i=t.getTabY(e);const s=new jn(0,i,t.showRests,this.container.beat.duration);if(this.restGlyph=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper,this.addGlyph(s),this.container.beat.dots>0&&t.showRests){this.addGlyph(new Tn(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new sn(0,i,1.5*this.scale))}}else{let i=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==f.None;const s=new Jn(0,0,i);this.noteNumbers=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper;for(let e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);if(this.addGlyph(s),this.container.beat.hasWhammyBar){let e=new _n(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!this.noteNumbers.beatEffects.has("tremolo")){let e=0,t=this.container.beat.tremoloSpeed;switch(t){case p.ThirtySecond:e=10;break;case p.Sixteenth:e=5;break;case p.Eighth:e=0}this.noteNumbers.beatEffects.set("tremolo",new un(5*this.scale,e*this.scale,t))}if(this.container.beat.dots>0&&t.settings.notation.rhythmMode!==e.TabRhythmMode.Hidden){this.addGlyph(new Tn(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new sn(0,t.lineOffset*t.bar.staff.tuning.length+t.settings.notation.rhythmHeight*t.scale,1.5*this.scale))}}if(!this.glyphs)return;let i=0;for(let e=0,t=this.glyphs.length;e<t;e++){let t=this.glyphs[e];t.x=i,t.renderer=this.renderer,t.doLayout(),i+=t.width}this.width=i,this.computedWidth=i,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,i=new qn(0,0,e),s=e.beat.voice.bar.staff.tuning.length-e.string;i.y=t.getTabY(s),i.renderer=this.renderer,i.doLayout(),this.noteNumbers.addNoteGlyph(i,e);let a=i.y-i.height/2,r=a+i.height;this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,a,r)}}class $n extends zs{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10*this.scale}paint(e,t,i){let s=this.renderer,a=t+this.x+s.getNoteY(this._beat.maxStringNote,Qe.Top),r=t+this.y+s.getNoteY(this._beat.minStringNote,Qe.Bottom),n=e+this.x+this.width/2|0,o=8*this.scale;if(this._beat.brushType!==d.None){if(this._beat.brushType===d.BrushUp||this._beat.brushType===d.BrushDown)i.beginPath(),i.moveTo(n,a),i.lineTo(n,r),i.stroke();else if(this._beat.brushType===d.ArpeggioUp){let t=new Lr(0,0,_.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let s=a,n=r-o;t.width=Math.abs(n-s),i.beginRotate(e+this.x+4*this.scale,n,-90),t.paint(0,-t.height/2,i),i.endRotate()}else if(this._beat.brushType===d.ArpeggioDown){let t=new Lr(0,0,_.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let s=a+o,n=r;t.width=Math.abs(n-s),i.beginRotate(e+this.x+4*this.scale,s,90),t.paint(0,-t.height/2,i),i.endRotate()}this._beat.brushType===d.BrushUp||this._beat.brushType===d.ArpeggioUp?(i.beginPath(),i.moveTo(n,r),i.lineTo(n+o/2,r-o),i.lineTo(n-o/2,r-o),i.closePath(),i.fill()):(i.beginPath(),i.moveTo(n,a),i.lineTo(n+o/2,a+o),i.lineTo(n-o/2,a+o),i.closePath(),i.fill())}}}class Kn extends Ka{doLayout(){this.container.beat.brushType===d.None||this.container.beat.isRest||(this.addGlyph(new $n(this.container.beat)),this.addGlyph(new Tn(0,0,4*this.scale))),super.doLayout()}constructor(){super()}}class Zn extends zs{constructor(e,t){super(e,t)}doLayout(){this.width=28*this.scale}paint(e,t,i){let s=this.renderer.bar.staff.tuning.length,a=s<=4?P.FourStringTabClef:P.SixStringTabClef,r=s<=4?s/4.5:s/6.5;i.fillMusicFontSymbol(e+this.x+5*this.scale,t+this.y,r*this.scale,a,!1)}}class eo extends Mn{get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?Ys.GraceScale:1}}class to extends qa{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(to.TabLineSpacing+1)*this.scale}updateSizes(){let t=this.resources,i=(t.tablatureFont.size/2+.2*t.tablatureFont.size)*this.scale;this.topPadding=i,this.bottomPadding=i,this.height=this.lineOffset*(this.bar.staff.tuning.length-1)+2*i,this.settings.notation.rhythmMode!==e.TabRhythmMode.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!==e.TabRhythmMode.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 en(0,0,1.5,3)),this.isFirstOfLine){let e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new Zn(5*this.scale,this.getTabY(e)))}this.showTimeSignature&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new jr(0,this.getTabHeight(-.5),this.bar.index+1))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new Tn(0,0,2*this.scale)),this._startSpacing=!0)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Tn(0,0,5*this.scale));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new eo(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,i=e.beats.length;t<i;t++){let i=e.beats[t],s=new Yn(i,this.getVoiceContainer(e));s.preNotes=new Kn,s.onNotes=new Qn,this.addBeatGlyph(s)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new Kr(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Zr(0,this.getTabY(-1),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new Qr(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,i){super.paintBackground(e,t,i);let s=this.resources;i.color=s.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 i=e.onNotes,s=i.noteNumbers;if(s)for(const[n,o]of s.notesPerString)o.isEmpty||r[this.bar.staff.tuning.length-n].push(new Float32Array([t.x+e.x+i.x+s.x,s.width+a]))}}for(let e of r)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));for(let s=0,a=this.bar.staff.tuning.length;s<a;s++){const a=this.getTabY(s);let n=0;for(let o of r[s])i.fillRect(e+this.x+n,t+this.y+a|0,o[0]-n,this.scale*qa.StaffLineThickness),n=o[0]+o[1];i.fillRect(e+this.x+n,t+this.y+a|0,this.width-n,this.scale*qa.StaffLineThickness)}i.color=s.mainGlyphColor,this.paintSimileMark(e,t,i)}paint(t,i,s){super.paint(t,i,s),this.settings.notation.rhythmMode!==e.TabRhythmMode.Hidden&&(this.paintBeams(t,i,s),this.paintTuplets(t,i,s))}paintBeams(e,t,i){for(let s=0,a=this.helpers.beamHelpers.length;s<a;s++){let a=this.helpers.beamHelpers[s];for(let s=0,r=a.length;s<r;s++){let r=a[s];this.paintBeamHelper(e+this.beatGlyphsStart,t,i,r)}}}paintTuplets(e,t,i){for(let s of this.bar.voices)if(this.hasVoiceContainer(s)){let a=this.getVoiceContainer(s);for(let s of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,i,s)}}paintBeamHelper(t,i,s,a){s.color=0===a.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,a.isRestBeamHelper||(1===a.beats.length||this.settings.notation.rhythmMode===e.TabRhythmMode.ShowWithBeams?this.paintFooter(t,i,s,a):this.paintBar(t,i,s,a))}paintBar(e,t,i,s){for(let a=0,r=s.beats.length;a<r;a++){let r=s.beats[a];if(s.hasBeatLineX(r)){let n=s.getBeatLineX(r),o=t+this.y,h=t+this.y+this.height-this._tupletSize,l=this.getOnNotesGlyphForBeat(r);l.noteNumbers&&r.duration!==p.Half?o+=l.noteNumbers.getNoteY(l.noteNumbers.minStringNote,Qe.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,i);let c=6*this.scale,d=-6*this.scale,u=3*this.scale,g=Q.getIndex(r.duration)-2,f=h;for(let t=0;t<g;t++){let o=0,h=0,l=0,p=0,g=f+t*d;if(1===s.beats.length)o=n,h=n+c,l=g,p=g,to.paintSingleBar(i,e+this.x+o,l,e+this.x+h,p,u);else if(a<s.beats.length-1){if(Na.isFullBarJoin(r,s.beats[a+1],t))o=n,h=s.getBeatLineX(s.beats[a+1]);else{if(0!==a&&Na.isFullBarJoin(s.beats[a-1],r,t))continue;o=n,h=o+c}l=g,p=g,to.paintSingleBar(i,e+this.x+o,l,e+this.x+h,p,u)}else a>0&&!Na.isFullBarJoin(r,s.beats[a-1],t)&&(o=n-c,h=n,l=g,p=g,to.paintSingleBar(i,e+this.x+o,l,e+this.x+h,p,u))}}}}paintTupletHelper(e,t,i,s){let a,r=this.resources,n=i.textAlign,o=i.textBaseline;i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.textAlign=E.Center,i.textBaseline=C.Middle;let h=s.beats[0].tupletNumerator,l=s.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!==s.beats.length&&s.isFull){let n=s.beats[0],o=s.beats[s.beats.length-1],h=this.helpers.beamHelperLookup[s.voice.index].get(n.index),l=this.helpers.beamHelperLookup[s.voice.index].get(o.index);if(h&&l){let s=h.getBeatLineX(n),c=l.getBeatLineX(o);i.font=r.effectFont;let d=i.measureText(a),u=3*this.scale,p=(s+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;i.beginPath(),i.moveTo(e+this.x+s,m-y|0),i.lineTo(e+this.x+s,m-y-b|0),i.lineTo(e+this.x+g,m-y-b|0),i.stroke(),i.beginPath(),i.moveTo(e+this.x+f,m-y-b|0),i.lineTo(e+this.x+c,m-y-b|0),i.lineTo(e+this.x+c,m-y|0),i.stroke(),i.fillText(a,e+this.x+p,m-y-b)}}else for(let n=0,o=s.beats.length;n<o;n++){let o=s.beats[n],h=this.helpers.beamHelperLookup[s.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;i.font=r.effectFont,i.fillText(a,e+this.x+l,c)}i.textAlign=n,i.textBaseline=o}static paintSingleBar(e,t,i,s,a,r){e.beginPath(),e.moveTo(t,i),e.lineTo(s,a),e.lineTo(s,a-r),e.lineTo(t,i-r),e.closePath(),e.fill()}paintBeamingStem(e,t,i,s,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>s;){r.moveTo(i,o);let e=s;if(!(n.length>0&&n[n.length-1].bottomY>e)){r.lineTo(i,e);break}{const s=n.pop();e=t+s.bottomY,r.lineTo(i,e),o=t+s.topY}}r.stroke()}paintFooter(e,t,i,s){for(let a of s.beats){if(a.graceType!==f.None||a.duration===p.Whole||a.duration===p.DoubleWhole||a.duration===p.QuadrupleWhole)return;let r=s.getBeatLineX(a),n=t+this.y,o=t+this.y+this.height-this._tupletSize,h=this.getOnNotesGlyphForBeat(a);if(h.noteNumbers&&a.duration!==p.Half?n+=h.noteNumbers.getNoteY(h.noteNumbers.minStringNote,Qe.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,i),a.duration>p.Quarter){let t=new qs(0,0,a.duration,Ce.Down,!1);t.renderer=this,t.doLayout(),t.paint(e+this.x+r,o,i)}}}}to.StaffId="tab",to.TabLineSpacing=10;class io extends Sa{get staffId(){return to.StaffId}constructor(e,t,i){super(),this._showTimeSignature=e,this._showRests=t,this._showTiedNotes=i,this.hideOnPercussionTrack=!0}canCreate(e,t){return t.tuning.length>0&&super.canCreate(e,t)}create(e,t){let i=new to(e,t);return i.showRests=this._showRests,i.showTimeSignature=this._showTimeSignature,i.showTiedNotes=this._showTiedNotes,i}}class so extends Us{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+so.Padding*this.scale}paint(e,t,i){let s=this.renderer.resources;i.font=s.effectFont;let a=i.textAlign;i.textAlign=E.Center,i.fillText("T",e+this.x,t+this.y+i.font.size/2),i.textAlign=a,i.strokeCircle(e+this.x,t+this.y+i.font.size/2+(so.Padding-1)*this.scale,i.font.size/1.6)}}so.Padding=4;class ao extends yr{get notationElement(){return v.EffectTap}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new so}}class ro{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"}(et||(et={}));class no extends ro{constructor(){super(...arguments),this.align=E.Left,this.frame=et.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class oo extends ro{constructor(){super(...arguments),this.chord=new he}}class ho extends ro{}class lo extends ro{}class co extends ro{constructor(){super(...arguments),this.number=0}}class uo extends ro{constructor(){super(...arguments),this.decrescendo=!1}}class po extends ro{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class go extends ro{constructor(){super(...arguments),this.octave=1}}class fo extends ro{}class mo{constructor(){this.defaultClef=n.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class yo{constructor(){this.from=0,this.to=0,this.curly=!1}}class bo{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=L.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new ce,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 i=new pt;try{i.parse(e)}catch(e){throw new V("Could not parse XML",e)}this.parseDom(i),this.consolidate(),this.score.finish(t)}consolidate(){let e=this.score.tempo;for(const t of this.score.tracks){const i=this._voiceCounts.get(t.index);for(const s of t.staves){for(;s.bars.length<this.score.masterBars.length;)this.addNewBar(s);for(const t of s.bars){for(;t.voices.length<i;)t.addVoice(new _e);for(const e of t.voices)if(0===e.beats.length){const t=new oe;t.isEmpty=!0,e.addBeat(t)}const s=t.masterBar;s.tempoAutomation&&(s.tempoAutomation.value!==e?e=s.tempoAutomation.value:s.tempoAutomation=null)}}}So.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),So.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?u.Decrescendo:u.Crescendo}))}static applyEffectRange(e,t){for(const[i,s]of e){const e=s.noteRange;let a=i;for(let i=0;i<e;i++)if(t(s,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 V("No valid XML");if("score"!==t.localName)throw new V('Root node of XML was not "score"');this.score=new pe,this.score.tempo=120;for(let e of t.childNodes)if(e.nodeType===Pe.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===Pe.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 i=0,s=null;for(let e=0;e<this._staffLayouts.length;e++){const a=this._staffLayouts[e];for(;i<t.length&&e>t[i].to;)i++;s&&i<t.length&&e>t[i].from&&e<=t[i].to?s.ensureStaveCount(s.staves.length+1):(s=new we,s.ensureStaveCount(1),s.name=a.description,s.playbackInfo.volume=Math.floor(a.volume/128*16),s.playbackInfo.program=a.instrument,a.percussion?(s.playbackInfo.primaryChannel=9,s.playbackInfo.secondaryChannel=9):(s.playbackInfo.primaryChannel=this._trackChannel++,s.playbackInfo.secondaryChannel=this._trackChannel++),this.score.addTrack(s));const r=s.staves[s.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===Pe.Element&&"bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new yo;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===Pe.Element&&"staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new mo;t.description=e.getAttribute("description");for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"notation":i.attributes.has("defaultClef")&&(t.defaultClef=this.parseClef(i.attributes.get("defaultClef")));break;case"sound":i.attributes.has("percussion")&&(t.percussion="true"===i.attributes.get("percussion")),i.attributes.has("instr")&&(t.instrument=parseInt(i.attributes.get("instr"))),i.attributes.has("volume")&&(t.volume=parseInt(i.attributes.get("volume"))),i.attributes.has("transpose")&&(t.transpose=parseInt(i.attributes.get("transpose")))}this._staffLayoutLookup.set(t.description,t),t.index=this._staffLayouts.length,this._staffLayouts.push(t)}parseClef(e){switch(e){case"treble":return n.G2;case"bass":return n.F4;case"alto":case"tenor":return n.C4}return n.G2}parseClefOttava(e){return e.endsWith("-")?o._8vb:e.endsWith("+")?o._8va:o.Regular}parseSystems(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"system"===t.localName)this.parseSystem(t)}parseSystem(e){e.attributes.has("tempo")&&0===this.score.masterBars.length&&(this.score.tempo=parseInt(e.attributes.get("tempo"))),"0"===e.getAttribute("beamGrouping")&&(this._beamingMode=L.ForceSplitToNext);for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"staves"===t.localName)this.parseStaves(e,t);this._isFirstSystem=!1}parseStaves(e,t){let i=this.score.masterBars.length;for(let s of t.childNodes)if(s.nodeType===Pe.Element&&"staff"===s.localName)this.parseStaff(e,i,s)}parseStaff(e,t,i){const s=i.getAttribute("layout");this._currentStaffLayout=this._staffLayoutLookup.get(s),this._timeSignature.timeSignatureNumerator=4,this._timeSignature.timeSignatureDenominator=4,this._timeSignature.timeSignatureCommon=!1,this.parseTime(i.getAttribute("defaultTime"));const a=this._staffLookup.get(this._currentStaffLayout.index);for(;a.bars.length<t;)this.addNewBar(a);for(let r of i.childNodes)if(r.nodeType===Pe.Element&&"voices"===r.localName)this.parseVoices(s,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,i,s,a){let r=0;for(let n of a.childNodes)if(n.nodeType===Pe.Element&&"voice"===n.localName)this.parseVoice(e,t,i,r,s,n),r++}getOrCreateBar(e,t){return t<e.bars.length?e.bars[t]:this.addNewBar(e)}addNewBar(e){let t=new W;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 ce;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,i,s,a,n){const o=e+"_"+s;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,s)):(this._currentVoiceState=new bo,this._currentVoiceState.currentBarIndex=a-1,this._voiceStates.set(o,this._currentVoiceState),this.newBar(t,s)),n.attributes.has("stemDir"))switch(n.attributes.get("stemDir")){case"up":this._currentVoiceState.voiceStemDir=Ce.Up;break;case"down":this._currentVoiceState.voiceStemDir=Ce.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const h=n.findChildElement("noteObjects");if(i.attributes.has("tempo")&&(this._currentBar.masterBar.tempoAutomation=new H,this._currentBar.masterBar.tempoAutomation.isLinear=!0,this._currentBar.masterBar.tempoAutomation.type=r.Tempo,this._currentBar.masterBar.tempoAutomation.value=parseInt(i.attributes.get("tempo"))),h)for(let e of h.childNodes)if(e.nodeType===Pe.Element)switch(this._currentVoiceState.currentBarComplete&&"barline"!==e.localName&&this.newBar(t,s),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,s),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,s),this._currentBar.masterBar.isRepeatStart=!0;break;default:this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0}break;case"chord":let i=new oe;this.initFromPreviousBeat(i,this._currentVoice),i.beamingMode=this._beamingMode,this._currentVoiceState.voiceStemDir&&(i.preferredBeamDirection=this._currentVoiceState.voiceStemDir),this.parseDuration(this._currentBar,i,e.findChildElement("duration")),i.updateDurations(),this._currentVoiceState.currentPosition+=i.playbackDuration,this._currentVoice.addBeat(i),this.parseChord(i,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 i=this.getLastBeat(t);i&&(e.dynamics=i.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 i=t.voices[e.index];return this.getLastBeat(i)}}return null}ensureVoice(e,t){for(;this._currentBar.voices.length<t+1;)this._currentBar.addVoice(new _e);(!this._voiceCounts.has(e.track.index)||this._voiceCounts.get(e.track.index)<this._currentBar.voices.length)&&this._voiceCounts.set(e.track.index,this._currentBar.voices.length),this._currentVoice=this._currentBar.voices[t]}parseChord(e,t){const i=new ee;for(let s of t.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"stem":switch(s.getAttribute("dir")){case"up":e.preferredBeamDirection=Ce.Up;break;case"down":e.preferredBeamDirection=Ce.Down}break;case"articulation":switch(s.getAttribute("type")){case"staccato":i.isStaccato=!0;break;case"normalAccent":i.accentuated=a.Normal;break;case"strongAccent":i.accentuated=a.Heavy}break;case"lyric":this.parseLyric(e,s);break;case"drawObjects":this.parseBeatDrawObject(e,s);break;case"heads":this.parseHeads(e,i,s);break;case"beam":switch(s.getAttribute("group")){case"force":e.beamingMode=L.ForceMergeWithNext;break;case"divide":e.beamingMode=L.ForceSplitToNext}}}parseHeads(e,t,i){for(let s of i.childNodes)if(s.nodeType===Pe.Element&&"head"===s.localName)this.parseHead(e,t,s)}parseHead(e,t,i){const s=new ee,a=Q.parseTuning(i.getAttribute("pitch"));s.octave=a.octave-1,s.tone=a.noteValue,s.isStaccato=t.isStaccato,s.accentuated=t.accentuated,e.addNote(s);for(let e of i.childNodes)if(e.nodeType===Pe.Element)switch(e.localName){case"alter":e.attributes.has("step")&&(s.tone+=parseInt(e.attributes.get("step")));break;case"tie":e.attributes.has("begin")?this._tieStartIds.has(s.id)||(this._tieStartIds.set(s.id,!0),this._tieStarts.push(s)):e.attributes.has("end")&&this._tieStarts.length>0&&!s.isTieDestination&&(s.isTieDestination=!0,s.tieOrigin=this._tieStarts[0],this._tieStarts.splice(0,1),this._tieStartIds.delete(s.id))}}parseBeatDrawObject(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"drawObj"===i.localName){const t=this.parseDrawObj(i);if(t)if(t instanceof no)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new ht,e.fermata.type=Ne.Medium):"f"===t.text?e.dynamics=g.F:"j"===t.text&&(e.dynamics=g.MF):this._isFirstSystem&&""===this.score.title&&t.align===E.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===E.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===E.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof oo);else if(t instanceof lo)e.vibrato=_.Slight;else if(t instanceof uo)e.crescendo=t.decrescendo?u.Decrescendo:u.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof ho){const i=t;this._slurs.set(e,i)}else t instanceof po&&this.applyVolta(t)}}parseBarDrawObject(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof po&&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 i=e.firstNumber;i<=e.lastNumber;i++)t|=1<<i-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 i of t.childNodes)if(i.nodeType===Pe.Element&&"verse"===i.localName){e.lyrics||(e.lyrics=[]);let t=i.innerText;"true"===i.getAttribute("hyphen")&&(t+="-"),e.lyrics.push(t)}}parseRestDurations(e,t){const i=t.getAttribute("base");if(-1!==i.indexOf("/")){let i=new oe;return i.beamingMode=this._beamingMode,this.parseDuration(e,i,t),i}if(1===parseInt(i)){let e=new oe;return e.beamingMode=this._beamingMode,e.duration=p.Whole,e}return J.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return p.DoubleWhole;case"1/1":return p.Whole;case"1/2":return p.Half;case"1/4":return p.Quarter;case"1/8":return p.Eighth;case"1/16":return p.Sixteenth;case"1/32":return p.ThirtySecond;case"1/64":return p.SixtyFourth;case"1/128":return p.OneHundredTwentyEighth;default:return J.warning("Importer","Unsupported duration"),p.Quarter}}parseDuration(e,t,i){const s=i.getAttribute("base");t.duration=this.parseDurationValue(s),i.attributes.has("dots")&&(t.dots=parseInt(i.attributes.get("dots")));const a=i.findChildElement("tuplet");if(a){t.tupletNumerator=parseInt(a.getAttribute("count"));const e="true"===a.getAttribute("tripartite")?3:1,i="true"===a.getAttribute("prolong")?0:1;let s=0;for(;e*Math.pow(2,s+i)<t.tupletNumerator;)s++;t.tupletDenominator=e*Math.pow(2,s)}}parsePageObjects(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof no)switch(e.align){case E.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case E.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&this._galleryObjects.set(t.getAttribute("name"),e)}}parseDrawObj(e){let t=null,i=1;for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"text":t=this.parseText(s);break;case"guitar":t=this.parseGuitar(s);break;case"slur":t=this.parseSlur(s);break;case"wavyLine":t=this.parseWavyLine(s);break;case"bracket":t=this.parseTupletBracket(s);break;case"wedge":t=this.parseWedge(s);break;case"volta":t=this.parseVolta(s);break;case"octaveClef":t=this.parseOctaveClef(s);break;case"trill":t=this.parseTrill(s);break;case"basic":s.attributes.has("noteRange")&&(i=parseInt(s.attributes.get("noteRange")))}return t&&(t.noteRange=i),t}parseTrill(e){return new fo}parseOctaveClef(e){const t=new go;return e.attributes.has("octave")&&(t.octave=parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new po;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 uo;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new co;return e.attributes.has("number")&&(t.number=parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new lo}parseSlur(e){return new ho}parseGuitar(e){const t=new oo,i=e.innerText.trim();for(let e=0;e<i.length;e++)"/"===i.charAt(e)?t.chord.strings.push(0):t.chord.strings.push(parseInt(i.charAt(e)));return t}parseText(e){const t=new no;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=E.Left;break;case"center":t.align=E.Center;break;case"right":t.align=E.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=et.Rectangle;break;case"ellipse":t.frame=et.Ellipse;break;case"circle":t.frame=et.Circle;break;case"none":t.frame=et.None}if(e.firstElement){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"font":t.fontFace=i.getAttribute("face"),i.attributes.has("weight")&&(t.weight=parseInt(i.attributes.get("weight"))),i.attributes.has("height")&&(t.height=parseInt(i.attributes.get("height")));break;case"content":t.text=i.innerText}}else t.text=e.innerText;return t}parseInfo(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class wo extends O{get name(){return"Capella"}constructor(){super()}readScore(){J.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new Pt(this.data).read(),J.debug(this.name,"Zip entries loaded"),e.length>0){for(let i of e)if("score.xml"===i.fileName)t=Te.toString(i.data,this.settings.importer.encoding)}else this.data.reset(),t=Te.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new V("No valid capella file");J.debug(this.name,"Start Parsing score.xml");try{let e=new So;return e.parseXml(t,this.settings),J.debug(this.name,"score.xml parsed"),e.score}catch(e){throw new V("Failed to parse CapXML",e)}}}class _o{constructor(e){this._targets=new Set,this._callback=e,window.addEventListener("resize",this.onWindowResize.bind(this),!1)}observe(e){this._targets.add(e)}unobserve(e){this._targets.delete(e)}disconnect(){this._targets.clear()}onWindowResize(){const e=[];for(const t of this._targets)e.push({target:t,contentRect:void 0,borderBoxSize:void 0,contentBoxSize:[],devicePixelContentBoxSize:[]});this._callback(e,this)}}class Bo{constructor(e){this._elements=[];let t=null;const i=this._check.bind(this);this._check=()=>{t||(t=setTimeout((()=>{i(),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 i=t.getBoundingClientRect();i.top+i.height>=0&&i.top<=window.innerHeight&&i.left+i.width>=0&&i.left<=window.innerWidth&&e.push({target:t,isIntersecting:!0})})),e.length&&this._callback(e,this)}}function To(e,t,i){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var s;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");s=t[Symbol.asyncDispose]}if(void 0===s){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");s=t[Symbol.dispose]}if("function"!=typeof s)throw new TypeError("Object not disposable.");e.stack.push({value:t,dispose:s,async:i})}else i&&e.stack.push({async:!0});return t}var ko="function"==typeof SuppressedError?SuppressedError:function(e,t,i){var s=new Error(i);return s.name="SuppressedError",s.error=e,s.suppressed=t,s};function vo(e){function t(t){e.error=e.hasError?new ko(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}return function i(){for(;e.stack.length;){var s=e.stack.pop();try{var a=s.dispose&&s.dispose.call(s.value);if(s.async)return Promise.resolve(a).then(i,(function(e){return t(e),i()}))}catch(e){t(e)}}if(e.hasError)throw e.error}()}class xo{static enable(e,t){xo.alphaSkia=t,xo.initializeMusicFont(xo.alphaSkia.AlphaSkiaTypeface.register(e))}static initializeMusicFont(e){xo.musicFont=e}static registerFont(e,t){const i=xo.alphaSkia.AlphaSkiaTypeface.register(e.buffer);t||(t=Ri.withFamilyList([i.familyName],12,i.isItalic?Ve.Italic:Ve.Plain,i.isBold?He.Bold:He.Regular));for(const e of t.families)this.customTypeFaces.set(xo.customTypefaceKey(e,t.isBold,t.isItalic),i);return t}static customTypefaceKey(e,t,i){return e.toLowerCase()+"_"+t+"_"+i}getTypeFace(){if(this._typeFaceCache!=this.font.toCssString(this.settings.display.scale)){if(this._typeFaceIsSystem){const e={stack:[],error:void 0,hasError:!1};try{To(e,this._typeFace,!1)}catch(t){e.error=t,e.hasError=!0}finally{vo(e)}}for(const t of this.font.families){var e=xo.customTypefaceKey(t,this.font.isBold,this.font.isItalic);xo.customTypeFaces.has(e)?(this._typeFaceIsSystem=!1,this._typeFace=xo.customTypeFaces.get(e)):(this._typeFaceIsSystem=!0,this._typeFace=xo.alphaSkia.AlphaSkiaTypeface.create(t,this.font.isBold,this.font.isItalic))}this._typeFaceCache=this.font.toCssString(this.settings.display.scale)}return this._typeFace}constructor(){this._color=new me(0,0,0,0),this._lineWidth=0,this._typeFaceCache="",this._typeFaceIsSystem=!1,this._typeFace=null,this.font=new Ri("Arial",10,Ve.Plain),this.textAlign=E.Left,this.textBaseline=C.Top,this._canvas=new xo.alphaSkia.AlphaSkiaCanvas,this.color=new me(0,0,0,255)}destroy(){const e={stack:[],error:void 0,hasError:!1};try{To(e,this._canvas,!1)}catch(t){e.error=t,e.hasError=!0}finally{vo(e)}}onRenderFinished(){return null}beginRender(e,t){this._canvas.beginRender(e,t,Eo.HighDpiFactor)}endRender(){return this._canvas.endRender()}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._canvas.color=xo.alphaSkia.AlphaSkiaCanvas.rgbaToColor(e.r,e.g,e.b,e.a))}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._canvas.lineWidth=e}fillRect(e,t,i,s){i>0&&this._canvas.fillRect(0|e,0|t,i,s)}strokeRect(e,t,i,s){this._canvas.strokeRect(0|e,0|t,i,s)}beginPath(){this._canvas.beginPath()}closePath(){this._canvas.closePath()}moveTo(e,t){this._canvas.moveTo(e,t)}lineTo(e,t){this._canvas.lineTo(e,t)}quadraticCurveTo(e,t,i,s){this._canvas.quadraticCurveTo(e,t,i,s)}bezierCurveTo(e,t,i,s,a,r){this._canvas.bezierCurveTo(e,t,i,s,a,r)}fillCircle(e,t,i){this._canvas.fillCircle(e,t,i)}strokeCircle(e,t,i){this._canvas.strokeCircle(e,t,i)}fill(){this._canvas.fill()}stroke(){this._canvas.stroke()}beginGroup(e){}endGroup(){}fillText(e,t,i){if(0==e.length)return;let s=xo.alphaSkia.AlphaSkiaTextAlign.Left;switch(this.textAlign){case E.Left:s=xo.alphaSkia.AlphaSkiaTextAlign.Left;break;case E.Center:s=xo.alphaSkia.AlphaSkiaTextAlign.Center;break;case E.Right:s=xo.alphaSkia.AlphaSkiaTextAlign.Right}let a=xo.alphaSkia.AlphaSkiaTextBaseline.Top;switch(this.textBaseline){case C.Top:a=xo.alphaSkia.AlphaSkiaTextBaseline.Top;break;case C.Middle:a=xo.alphaSkia.AlphaSkiaTextBaseline.Middle;break;case C.Bottom:a=xo.alphaSkia.AlphaSkiaTextBaseline.Bottom}this._canvas.fillText(e,this.getTypeFace(),this.font.size*this.settings.display.scale,t,i,s,a)}measureText(e){return this._canvas.measureText(e,this.getTypeFace(),this.font.size*this.settings.display.scale)}fillMusicFontSymbol(e,t,i,s,a){s!==P.None&&this.fillMusicFontSymbolText(e,t,i,String.fromCharCode(s),a)}fillMusicFontSymbols(e,t,i,s,a){let r="";for(let e of s)e!==P.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,i,r,a)}fillMusicFontSymbolText(e,t,i,s,a){this._canvas.fillText(s,xo.musicFont,Eo.MusicFontSize*this.settings.display.scale*i,e,t,a?xo.alphaSkia.AlphaSkiaTextAlign.Center:xo.alphaSkia.AlphaSkiaTextAlign.Left,xo.alphaSkia.AlphaSkiaTextBaseline.Alphabetic)}beginRotate(e,t,i){this._canvas.beginRotate(e,t,i)}endRotate(){this._canvas.endRotate()}}xo.musicFont=null,xo.customTypeFaces=new Map;class No{constructor(e,t){this.vertical=e,this.createLayout=t}}class Po{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class Eo{static createStyleElement(e,t){let i=e.getElementById("alphaTabStyle");if(!i){if(!t)return void J.error("AlphaTab","Font directory could not be detected, cannot create style element");i=e.createElement("style"),i.id="alphaTabStyle";let s=`\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: ${Eo.MusicFontSize}px;\n overflow: visible !important;\n }`;i.innerHTML=s,e.getElementsByTagName("head").item(0).appendChild(i),Eo.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===Eo._globalThis){try{Eo._globalThis=globalThis}catch(e){}void 0===Eo._globalThis&&(Eo._globalThis=self),void 0===Eo._globalThis&&(Eo._globalThis=global),void 0===Eo._globalThis&&(Eo._globalThis=window),void 0===Eo._globalThis&&(Eo._globalThis=Function("return this")())}return this._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in Eo.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in Eo.globalThis}static throttle(e,t){let i=0;return()=>{Eo.globalThis.clearTimeout(i),i=Eo.globalThis.setTimeout(e,t)}}static detectScriptFile(){if(!Eo.isRunningInWorker&&Eo.globalThis.ALPHATAB_ROOT){let e=Eo.globalThis.ALPHATAB_ROOT;return e=Eo.ensureFullUrl(e),e=Eo.appendScriptName(e),e}try{const e={};if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in Eo.globalThis&&document.currentScript?document.currentScript.src:null}static ensureFullUrl(e){if(!e)return"";if(!e.startsWith("http")&&!e.startsWith("https")&&!e.startsWith("file")){let t="",i=Eo.globalThis.location;if(t+=i.protocol?.toString(),t+="//"?.toString(),i.hostname&&(t+=i.hostname?.toString()),i.port&&(t+=":"?.toString(),t+=i.port?.toString()),!e.startsWith("/")){let e=i.pathname.split("/").slice(0,-1).join("/");e.length>0&&(e.startsWith("/")||(t+="/"?.toString()),t+=e?.toString())}return e.startsWith("/")||(t+="/"?.toString()),t+=e?.toString(),t}return e}static appendScriptName(e){return e&&!e.endsWith(".js")&&(e.endsWith("/")||(e+="/"),e+="alphaTab.js"),e}static detectFontDirectory(){if(!Eo.isRunningInWorker&&Eo.globalThis.ALPHATAB_FONT)return Eo.ensureFullUrl(Eo.globalThis.ALPHATAB_FONT);const e=Eo.scriptFile;if(e){let t=e.lastIndexOf(String.fromCharCode(47));if(t>=0)return e.substr(0,t)+"/font/"}return null}static registerJQueryPlugin(){if(!Eo.isRunningInWorker&&Eo.globalThis&&"jQuery"in Eo.globalThis){let e=Eo.globalThis.jQuery,t=new ma;e.fn.alphaTab=function(e){const i=Array.prototype.slice.call(arguments,1);return 1===this.length?t.exec(this[0],e,i):this.each(((s,a)=>{t.exec(a,e,i)}))},e.alphaTab={restore:ma.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&Eo.renderEngines.has(e)?Eo.renderEngines.get(e):Eo.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&Eo.layoutEngines.has(t)?Eo.layoutEngines.get(t):Eo.layoutEngines.get(e.LayoutMode.Page)}static buildImporters(){return[new st,new It,new Et,new Dt,new wo,new it]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new Po(!0,(()=>new ba))),e.set("default",e.get("svg")),e.set("skia",new Po(!1,(()=>new xo))),Eo.createPlatformSpecificRenderEngines(e),e}static enableAlphaSkia(e,t){xo.enable(e,t)}static registerAlphaSkiaCustomFont(e,t){return xo.registerFont(e,t)}static createPlatformSpecificRenderEngines(e){e.set("html5",new Po(!1,(()=>new Cs)))}static createDefaultStaveProfiles(){const t=new Map;t.set(e.StaveProfile.ScoreTab,[new tr("score-effects",[new Ar,new Hr,new Tr,new Rr,new nr,new fr,new Wr,new Gr,new vr(!0),new zr,new Fr,new Ur,new Mr,new ao,new ar]),new Wn,new tr("tab-effects",[new lr,new vr(!1),new dr,new Br,new Gr,new zr,new Fr,new Ur,new Mr,new Ir,new pr,new Sr(y.Natural),new Sr(y.Artificial),new Sr(y.Pinch),new Sr(y.Tap),new Sr(y.Semi),new Sr(y.Feedback),new wr,new rr,new mr,new xr,new Er,new Nr,new ao]),new io(!1,!1,!1)]),t.set(e.StaveProfile.Score,[new tr("score-effects",[new Ar,new Hr,new Tr,new Rr,new nr,new fr,new Wr,new Gr,new vr(!0),new zr,new Fr,new Ur,new Mr,new pr,new wr,new xr,new Er,new Nr,new ao,new ar]),new Wn,new tr("score-bottom-effects",[new lr,new vr(!1),new dr,new Br])]);let i=[new Ar,new Hr,new Tr,new Rr,new nr,new fr,new Gr,new zr,new Fr,new Ur,new Mr,new Ir,new pr,new Sr(y.Artificial),new Sr(y.Pinch),new Sr(y.Tap),new Sr(y.Semi),new Sr(y.Feedback),new wr,new rr,new mr,new xr,new Er,new Nr,new ao,new ar];return t.set(e.StaveProfile.Tab,[new tr("tab-effects",i),new io(!0,!0,!0),new tr("tab-bottom-effects",[new Br])]),t.set(e.StaveProfile.TabMixed,[new tr("tab-effects",i),new io(!1,!1,!1),new tr("tab-bottom-effects",[new Br])]),t}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.LayoutMode.Page,new No(!0,(e=>new qr(e)))),t.set(e.LayoutMode.Horizontal,new No(!1,(e=>new Yr(e)))),t}static initializeMain(t,i){Eo.isRunningInWorker||Eo.isRunningInAudioWorklet||(Eo.webPlatform!==e.WebPlatform.Browser&&Eo.webPlatform!==e.WebPlatform.BrowserModule||(Eo.registerJQueryPlugin(),Eo.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in Eo.globalThis||(Eo.globalThis.ResizeObserver=_o),"IntersectionObserver"in Eo.globalThis||(Eo.globalThis.IntersectionObserver=Bo),"replaceChildren"in Element.prototype||(Element.prototype.replaceChildren=function(...e){this.innerHTML="",this.append(...e)},Document.prototype.replaceChildren=Element.prototype.replaceChildren,DocumentFragment.prototype.replaceChildren=Element.prototype.replaceChildren),"replaceAll"in String.prototype||(String.prototype.replaceAll=function(e,t){return this.replace(new RegExp(e,"g"),t)})),Eo.createWebWorker=t,Eo.createAudioWorklet=i)}static get alphaTabWorker(){return this.globalThis.Worker}static initializeWorker(){if(!Eo.isRunningInWorker)throw new G(e.AlphaTabErrorType.General,"Not running in worker, cannot run worker initialization");Es.init(),Ss.init(),Eo.createWebWorker=t=>{throw new G(e.AlphaTabErrorType.General,"Nested workers are not supported")}}static initializeAudioWorklet(){if(!Eo.isRunningInAudioWorklet)throw new G(e.AlphaTabErrorType.General,"Not running in audio worklet, cannot run worklet initialization");da.init()}static detectWebPack(){try{if("function"==typeof __webpack_require__)return!0}catch(e){}return!1}static detectVite(){try{if("string"==typeof __BASE__)return!0}catch(e){}return!1}static detectWebPlatform(){try{if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return e.WebPlatform.NodeJs}catch(e){}try{const t={};if(t&&"string"==typeof t&&!t.startsWith("file://"))return e.WebPlatform.BrowserModule}catch(e){}return e.WebPlatform.Browser}}Eo.MusicFontSize=34,Eo.HighDpiFactor=1,Eo._globalThis=void 0,Eo.webPlatform=Eo.detectWebPlatform(),Eo.isWebPackBundled=Eo.detectWebPack(),Eo.isViteBundled=Eo.detectVite(),Eo.scriptFile=Eo.detectScriptFile(),Eo.fontDirectory=Eo.detectFontDirectory(),Eo.bravuraFontChecker=new sa(["alphaTab"]),Eo.renderEngines=Eo.createDefaultRenderEngines(),Eo.layoutEngines=Eo.createDefaultLayoutEngines(),Eo.staveProfiles=Eo.createDefaultStaveProfiles();class Co{constructor(){this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=e.LogLevel.Info,this.useWorkers=!0,this.includeNoteBounds=!1,this.scriptFile=Eo.scriptFile,this.fontDirectory=Eo.fontDirectory}}class Fo{}Fo.version="1.3.0",Fo.date="2024-05-15T11:07:17.263Z";var Lo,Mo=Object.freeze({__proto__:null,ScoreImporter:O,ScoreLoader:ea,UnsupportedFormatError:V});class Io{init(e,t){this.data=e,this.settings=t}export(e,t=null){const i=ke.withCapacity(1024);return this.init(i,t??new Zi),this.writeScore(e),i.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"}(Lo||(Lo={}));class Do{constructor(e,t,i=null){if(this.icon=Lo.Piano,this.icon=e,this.instrumentSetName=t,i)this.instrumentSetType=i;else{const e=t.split(" ");e[0]=e[0].substr(0,1).toLowerCase()+e[0].substr(1),this.instrumentSetType=e.join("")}}}class Ao{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new pt;return this._rhythmIdLookup=new Map,this.writeDom(t,e),t.toFormattedString("",!0)}writeDom(e,t){const i=e.addElement("GPIF");i.addElement("GPVersion").innerText="7";const s=i.addElement("GPRevision");s.innerText="7",s.attributes.set("required","12021"),s.attributes.set("recommended","12023"),s.innerText="12025",i.addElement("Encoding").addElement("EncodingDescription").innerText="GP7",this.writeScoreNode(i,t),this.writeMasterTrackNode(i,t),this.writeAudioTracksNode(i,t),this.writeTracksNode(i,t),this.writeMasterBarsNode(i,t);const a=i.addElement("Bars"),r=i.addElement("Voices"),n=i.addElement("Beats"),o=i.addElement("Notes"),h=i.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 i=e.addElement("Note");i.attributes.set("id",t.id.toString()),this.writeNoteProperties(i,t),t.isGhost&&(i.addElement("AntiAccent").innerText="normal"),t.isLetRing&&i.addElement("LetRing"),t.isTrill&&(i.addElement("Trill").innerText=t.trillValue.toString());let s=0;switch(t.isStaccato&&(s|=1),t.accentuated){case a.Normal:s|=8;break;case a.Heavy:s|=4}if(s>0&&(i.addElement("Accent").innerText=s.toString()),t.isTieOrigin||t.isTieDestination){const e=i.addElement("Tie");e.attributes.set("origin",t.isTieOrigin?"true":"false"),e.attributes.set("destination",t.isTieDestination?"true":"false")}switch(t.vibrato){case _.Slight:i.addElement("Vibrato").innerText="Slight";break;case _.Wide:i.addElement("Vibrato").innerText="Wide"}if(t.isFingering){switch(t.leftHandFinger){case m.Thumb:i.addElement("LeftFingering").innerText="P";break;case m.IndexFinger:i.addElement("LeftFingering").innerText="I";break;case m.MiddleFinger:i.addElement("LeftFingering").innerText="M";break;case m.AnnularFinger:i.addElement("LeftFingering").innerText="A";break;case m.LittleFinger:i.addElement("LeftFingering").innerText="C"}switch(t.rightHandFinger){case m.Thumb:i.addElement("RightFingering").innerText="P";break;case m.IndexFinger:i.addElement("RightFingering").innerText="I";break;case m.MiddleFinger:i.addElement("RightFingering").innerText="M";break;case m.AnnularFinger:i.addElement("RightFingering").innerText="A";break;case m.LittleFinger:i.addElement("RightFingering").innerText="C"}}t.percussionArticulation>=0?i.addElement("InstrumentArticulation").innerText=t.percussionArticulation.toString():i.addElement("InstrumentArticulation").innerText="0"}writeNoteProperties(e,t){const i=e.addElement("Properties");if(this.writeConcertPitch(i,t),this.writeTransposedPitch(i,t),t.isStringed&&(this.writeSimplePropertyNode(i,"String","String",(t.string-1).toString()),this.writeSimplePropertyNode(i,"Fret","Fret",t.fret.toString()),this.writeSimplePropertyNode(i,"Midi","Number",t.realValue.toString())),t.isPiano&&(this.writeSimplePropertyNode(i,"Octave","Number",t.octave.toString()),this.writeSimplePropertyNode(i,"Tone","Step",t.tone.toString()),this.writeSimplePropertyNode(i,"Midi","Number",t.realValue.toString())),t.beat.tap&&this.writeSimplePropertyNode(i,"Tapped","Enable",null),t.harmonicType!==y.None){switch(t.harmonicType){case y.Natural:this.writeSimplePropertyNode(i,"HarmonicType","HType","Natural");break;case y.Artificial:this.writeSimplePropertyNode(i,"HarmonicType","HType","Artificial");break;case y.Pinch:this.writeSimplePropertyNode(i,"HarmonicType","HType","Pinch");break;case y.Tap:this.writeSimplePropertyNode(i,"HarmonicType","HType","Tap");break;case y.Semi:this.writeSimplePropertyNode(i,"HarmonicType","HType","Semi");break;case y.Feedback:this.writeSimplePropertyNode(i,"HarmonicType","HType","Feedback")}0!==t.harmonicValue&&this.writeSimplePropertyNode(i,"HarmonicFret","HFret",t.harmonicValue.toString())}t.isDead&&this.writeSimplePropertyNode(i,"Muted","Enable",null),t.isPalmMute&&this.writeSimplePropertyNode(i,"PalmMuted","Enable",null),t.hasBend&&this.writeBend(i,t),t.isHammerPullOrigin&&this.writeSimplePropertyNode(i,"HopoOrigin","Enable",null),t.isHammerPullDestination&&this.writeSimplePropertyNode(i,"HopoDestination","Enable",null),t.isLeftHandTapped&&this.writeSimplePropertyNode(i,"LeftHandTapped","Enable",null);let s=0;switch(t.slideInType){case S.IntoFromAbove:s|=32;break;case S.IntoFromBelow:s|=16}switch(t.slideOutType){case w.Shift:s|=1;break;case w.Legato:s|=2;break;case w.OutDown:s|=4;break;case w.OutUp:s|=8;break;case w.PickSlideDown:s|=64;break;case w.PickSlideUp:s|=128}s>0&&this.writeSimplePropertyNode(i,"Slide","Flags",s.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,i,s){let a=0,r=0,n="",o="";const h=()=>{a=i%12,r=i/12|0,n=be.defaultSteps[a],o=be.defaultAccidentals[a]};switch(h(),s){case b.Default:break;case b.ForceNone:case b.ForceNatural:o="";break;case b.ForceSharp:o="#";break;case b.ForceDoubleSharp:"#"===o&&(i-=2,h()),o="x";break;case b.ForceFlat:"#"===o&&(i+=1,h()),o="b";break;case b.ForceDoubleFlat:"#"===o&&(i+=2,h()),o="bb"}this.writePitch(e,t,n,r.toString(),o)}writePitch(e,t,i,s,a){const r=e.addElement("Property");r.attributes.set("name",t);const n=r.addElement("Pitch");n.addElement("Step").innerText=i,n.addElement("Accidental").innerText=a,n.addElement("Octave").innerText=s}writeBend(e,t){t.hasBend&&t.bendPoints.length<=4&&this.writeStandardBend(e,t.bendPoints)}writeStandardBend(e,t){this.writeSimplePropertyNode(e,"Bended","Enable",null);var i,s,a=t[0],r=t[t.length-1];switch(t.length){case 4:i=t[1],s=t[2];break;case 3:i=t[1],s=t[1];break;default:s=i=new U((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(i.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset2","Float",this.toBendOffset(s.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleValue","Float",this.toBendValue(i.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/U.MaxPosition*100}writeBeatNode(e,t,i){const s=e.addElement("Beat");if(s.attributes.set("id",t.id.toString()),s.addElement("Dynamic").innerText=g[t.dynamics],t.fadeIn&&(s.addElement("Fadding").innerText="FadeIn"),t.isTremolo)switch(t.tremoloSpeed){case p.Eighth:s.addElement("Tremolo").innerText="1/2";break;case p.Sixteenth:s.addElement("Tremolo").innerText="1/4";break;case p.ThirtySecond:s.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&s.addElement("Chord").setCData(t.chordId),t.crescendo!==u.None&&(s.addElement("Hairpin").innerText=u[t.crescendo]),t.brushType){case d.ArpeggioUp:s.addElement("Arpeggio").innerText="Up";break;case d.ArpeggioDown:s.addElement("Arpeggio").innerText="Down"}switch(t.text&&s.addElement("FreeText").setCData(t.text),t.graceType){case f.OnBeat:case f.BeforeBeat:s.addElement("GraceNotes").innerText=f[t.graceType]}if(t.ottava!==o.Regular&&(s.addElement("Ottavia").innerText=o[t.ottava].substr(1)),t.hasWhammyBar&&this.writeWhammyNode(s,t),t.isLegatoOrigin||t.isLegatoDestination){const e=s.addElement("Legato");e.attributes.set("origin",t.isLegatoOrigin?"true":"false"),e.attributes.set("destination",t.isLegatoDestination?"true":"false")}if(this.writeRhythm(s,t,i),null!==t.preferredBeamDirection)switch(t.preferredBeamDirection){case Ce.Up:s.addElement("TransposedPitchStemOrientation").innerText="Upward";break;case Ce.Down:s.addElement("TransposedPitchStemOrientation").innerText="Downward"}s.addElement("ConcertPitchStemOrientation").innerText="Undefined",t.isRest||(s.addElement("Notes").innerText=t.notes.map((e=>e.id)).join(" ")),this.writeBeatProperties(s,t),this.writeBeatXProperties(s,t),t.lyrics&&t.lyrics.length>0&&this.writeBeatLyrics(s,t.lyrics)}writeBeatLyrics(e,t){const i=e.addElement("Lyrics");for(const e of t){i.addElement("Line").setCData(e)}}writeBeatXProperties(e,t){const i=e.addElement("XProperties");t.brushDuration>0&&this.writeSimpleXPropertyNode(i,"687935489","Int",t.brushDuration.toString())}writeBeatProperties(e,t){const i=e.addElement("Properties");switch(t.brushType){case d.BrushUp:this.writeSimplePropertyNode(i,"Brush","Direction","Up");break;case d.BrushDown:this.writeSimplePropertyNode(i,"Brush","Direction","Down")}switch(t.pickStroke){case N.Up:this.writeSimplePropertyNode(i,"PickStroke","Direction","Up");break;case N.Down:this.writeSimplePropertyNode(i,"PickStroke","Direction","Down")}switch(t.slap&&this.writeSimplePropertyNode(i,"Slapped","Enable",null),t.pop&&this.writeSimplePropertyNode(i,"Popped","Enable",null),t.vibrato){case _.Wide:this.writeSimplePropertyNode(i,"VibratoWTremBar","Strength","Wide");break;case _.Slight:this.writeSimplePropertyNode(i,"VibratoWTremBar","Strength","Slight")}}writeRhythm(e,t,i){const s=`${t.duration}_${t.dots}_${t.tupletNumerator}_${t.tupletDenominator}';`;let a;if(this._rhythmIdLookup.has(s))a=this._rhythmIdLookup.get(s);else{a=this._rhythmIdLookup.size.toString(),this._rhythmIdLookup.set(s,a);const e=i.addElement("Rhythm");if(e.attributes.set("id",a),t.hasTuplet){const i=e.addElement("PrimaryTuplet");i.attributes.set("num",t.tupletNumerator.toString()),i.attributes.set("den",t.tupletDenominator.toString())}t.dots>0&&e.addElement("AugmentationDot").attributes.set("count",t.dots.toString());let r="Quarter";switch(t.duration){case p.QuadrupleWhole:r="Long";break;case p.DoubleWhole:r="DoubleWhole";break;case p.Whole:r="Whole";break;case p.Half:r="Half";break;case p.Quarter:r="Quarter";break;case p.Eighth:r="Eighth";break;case p.Sixteenth:r="16th";break;case p.ThirtySecond:r="32nd";break;case p.SixtyFourth:r="64th";break;case p.OneHundredTwentyEighth:r="128th";break;case p.TwoHundredFiftySixth:r="256th"}e.addElement("NoteValue").innerText=r}e.addElement("Rhythm").attributes.set("ref",a)}writeWhammyNode(e,t){t.hasWhammyBar&&t.whammyBarPoints.length<=4&&this.writeStandardWhammy(e,t.whammyBarPoints)}writeStandardWhammy(e,t){const i=e.addElement("Whammy");var s,a,r=t[0],n=t[t.length-1];switch(t.length){case 4:s=t[1],a=t[2];break;case 3:s=t[1],a=t[1];break;default:a=s=new U((r.offset+n.offset)/2,(r.value+n.value)/2)}i.attributes.set("destinationOffset",this.toBendOffset(n.offset).toString()),i.attributes.set("destinationValue",this.toBendValue(n.value).toString()),i.attributes.set("middleOffset1",this.toBendOffset(s.offset).toString()),i.attributes.set("middleOffset2",this.toBendOffset(a.offset).toString()),i.attributes.set("middleValue",this.toBendValue(s.value).toString()),i.attributes.set("originOffset",this.toBendOffset(r.offset).toString()),i.attributes.set("originValue",this.toBendValue(r.value).toString())}writeScoreNode(e,t){const i=e.addElement("Score");i.addElement("Title").setCData(t.title),i.addElement("SubTitle").setCData(t.subTitle),i.addElement("Artist").setCData(t.artist),i.addElement("Album").setCData(t.album),i.addElement("Words").setCData(t.words),i.addElement("Music").setCData(t.music),i.addElement("WordsAndMusic").setCData(t.words===t.music?t.words:""),i.addElement("Copyright").setCData(t.copyright),i.addElement("Tabber").setCData(t.tab),i.addElement("Instructions").setCData(t.instructions),i.addElement("Notices").setCData(t.notices),i.addElement("FirstPageHeader").setCData(""),i.addElement("FirstPageFooter").setCData(""),i.addElement("PageHeader").setCData(""),i.addElement("PageFooter").setCData(""),i.addElement("ScoreSystemsDefaultLayout").setCData(t.defaultSystemsLayout.toString()),i.addElement("ScoreSystemsLayout").setCData(t.systemsLayout.join(" ")),i.addElement("ScoreZoomPolicy").innerText="Value",i.addElement("ScoreZoom").innerText="1",i.addElement("MultiVoice").innerText="1>"}writeMasterTrackNode(e,t){const i=e.addElement("MasterTrack");i.addElement("Tracks").innerText=t.tracks.map((e=>e.index)).join(" ");const s=i.addElement("Automations");t.masterBars.length>0&&t.masterBars[0].isAnacrusis&&i.addElement("Anacrusis");const a=s.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=s.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 i=e.addElement("Tracks");for(const e of t.tracks)this.writeTrackNode(i,e)}writeTrackNode(e,t){const i=e.addElement("Track");i.attributes.set("id",t.index.toString()),i.addElement("Name").setCData(t.name),i.addElement("ShortName").setCData(t.shortName),i.addElement("Color").innerText=`${t.color.r} ${t.color.g} ${t.color.b}`,i.addElement("SystemsDefautLayout").innerText=t.defaultSystemsLayout.toString(),i.addElement("SystemsLayout").innerText=t.systemsLayout.join(" "),i.addElement("AutoBrush"),i.addElement("PalmMute").innerText="0",i.addElement("PlayingStyle").innerText=R.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",i.addElement("UseOneChannelPerString"),i.addElement("IconId").innerText=Ao.getIconId(t.playbackInfo).toString(),this.writeInstrumentSetNode(i,t),this.writeTransposeNode(i,t),this.writeRseNode(i,t),i.addElement("ForcedSound").innerText="-1",this.writeMidiConnectionNode(i,t),t.playbackInfo.isSolo?i.addElement("PlaybackState").innerText="Solo":t.playbackInfo.isMute?i.addElement("PlaybackState").innerText="Mute":i.addElement("PlaybackState").innerText="Default",i.addElement("AudioEngineState").innerText="MIDI",this.writeLyricsNode(i,t),this.writeStavesNode(i,t),this.writeSoundsAndAutomations(i,t)}static getIconId(e){return 9===e.primaryChannel?Ao.DrumKitProgramInfo.icon:Ao.MidiProgramInfoLookup.has(e.program)?Ao.MidiProgramInfoLookup.get(e.program).icon:Lo.SteelGuitar}writeSoundAndAutomation(e,t,i,s,a,r,n,o=0){const h=e.addElement("Sound");h.addElement("Name").setCData(i),h.addElement("Label").setCData(i),h.addElement("Path").setCData(s),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(`${s};${i};${a}`)}writeSoundsAndAutomations(e,t){const i=e.addElement("Sounds"),s=e.addElement("Automations");if(t.staves.length>0&&t.staves[0].bars.length>0){const e=`Track_${t.index}_Initial`,a=`Midi/${t.playbackInfo.program}`,n="Factory";let o=!1;for(const h of t.staves)for(const l of h.bars)for(const h of l.voices)for(const c of h.beats){const h=c.getAutomation(r.Instrument),d=0===l.index&&0===c.index;if(h){const r=d?e:`ProgramChange_${c.id}`,u=d?a:`Midi/${h.value}`,p=d?n:"User";d||o||(this.writeSoundAndAutomation(i,s,e,a,n,t.staves[0].bars[0].index,t.playbackInfo.program),o=!0),this.writeSoundAndAutomation(i,s,r,u,p,l.index,h.value,h.ratioPosition),d&&(o=!0)}}}}writeMidiConnectionNode(e,t){const i=e.addElement("MidiConnection");i.addElement("Port").innerText=t.playbackInfo.port.toString(),i.addElement("PrimaryChannel").innerText=t.playbackInfo.primaryChannel.toString(),i.addElement("SecondaryChannel").innerText=t.playbackInfo.secondaryChannel.toString(),i.addElement("ForeOneChannelPerString").innerText="false"}writeRseNode(e,t){const i=e.addElement("RSE").addElement("ChannelStrip");i.attributes.set("version","E56");i.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 i=e.addElement("Staves");for(const e of t.staves)this.writeStaffNode(i,e)}writeStaffNode(e,t){const i=e.addElement("Staff").addElement("Properties");if(this.writeSimplePropertyNode(i,"CapoFret","Fret",t.capo.toString()),this.writeSimplePropertyNode(i,"FretCount","Fret","24"),t.tuning.length>0){const e=i.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(i,"PartialCapoFret","Fret","0"),this.writeSimplePropertyNode(i,"PartialCapoStringFlags","Bitset",t.tuning.map((e=>"0")).join("")),this.writeSimplePropertyNode(i,"TuningFlat","Enable",null),this.writeDiagramCollection(i,t,"DiagramCollection"),this.writeDiagramCollection(i,t,"DiagramWorkingSet")}writeDiagramCollection(e,t,i){const s=e.addElement("Property");s.attributes.set("name",i);const a=s.addElement("Items"),r=t.chords;if(r)for(const[e,t]of r){const i=a.addElement("Item");i.attributes.set("id",e),i.attributes.set("name",t.name);const s=i.addElement("Diagram");s.attributes.set("stringCount",t.strings.length.toString()),s.attributes.set("fretCount","5"),s.attributes.set("baseFret",(t.firstFret-1).toString()),s.attributes.set("barStates",t.strings.map((e=>"1")).join(" "));const r=[],n=new Map;for(let e=0;e<t.strings.length;e++){let i=t.strings[e];if(-1!==i){const a=s.addElement("Fret"),o=t.strings.length-1-e;a.attributes.set("string",o.toString()),a.attributes.set("fret",(i-t.firstFret+1).toString()),n.has(i)||(n.set(i,[]),r.push(i)),n.get(i).push(o)}}r.sort();const o=s.addElement("Fingering");if(t.barreFrets.length>0){const e=[m.LittleFinger,m.AnnularFinger,m.MiddleFinger,m.IndexFinger];for(const i of r){const s=n.get(i);if(s.length>1&&t.barreFrets.indexOf(i)>=0){const a=e.length>0?e.pop():m.IndexFinger;for(const e of s){const s=o.addElement("Position");switch(a){case m.LittleFinger:s.attributes.set("finger","Pinky");break;case m.AnnularFinger:s.attributes.set("finger","Ring");break;case m.MiddleFinger:s.attributes.set("finger","Middle");break;case m.IndexFinger:s.attributes.set("finger","Index")}s.attributes.set("fret",(i-t.firstFret+1).toString()),s.attributes.set("string",e.toString())}}}}const h=s.addElement("Property");h.attributes.set("name","ShowName"),h.attributes.set("type","bool"),h.attributes.set("value",t.showName?"true":"false");const l=s.addElement("Property");l.attributes.set("name","ShowDiagram"),l.attributes.set("type","bool"),l.attributes.set("value",t.showDiagram?"true":"false");const c=s.addElement("Property");c.attributes.set("name","ShowFingering"),c.attributes.set("type","bool"),c.attributes.set("value",t.showFingering?"true":"false");const d=s.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 f=d.addElement("Degree");f.attributes.set("interval","Fifth"),f.attributes.set("alteration","Perfect"),f.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,i,s){const a=e.addElement("Property");a.attributes.set("name",t);const r=a.addElement(i);return null!==s&&(r.innerText=s),a}writeSimpleXPropertyNode(e,t,i,s){const a=e.addElement("XProperty");a.attributes.set("id",t);const r=a.addElement(i);return null!==s&&(r.innerText=s),a}writeLyricsNode(e,t){const i=e.addElement("Lyrics");i.attributes.set("dispatched","true");let s=[];for(const e of t.staves[0].bars)for(const t of e.voices)if(!t.isEmpty)for(const i of t.beats)if(i.lyrics)for(let t=0;t<i.lyrics.length;t++){for(;t>=s.length;){const t=new le;t.startBar=e.index,t.text="[Empty]",s.push(t)}const a=s[t];a.text="[Empty]"==a.text?i.lyrics[t]:a.text+" "+i.lyrics[t].split(" ").join("+")}for(let e=0;e<s.length;e++){const t=i.addElement("Line");t.addElement("Text").setCData(s[e].text),t.addElement("Offset").innerText=s[e].startBar.toString()}}writeTransposeNode(e,t){const i=e.addElement("Transpose"),s=Math.floor(t.staves[0].displayTranspositionPitch/12),a=t.staves[0].displayTranspositionPitch-12*s;i.addElement("Chromatic").innerText=a.toString(),i.addElement("Octave").innerText=s.toString()}writeInstrumentSetNode(e,t){const i=e.addElement("InstrumentSet"),s=t.staves[0];if(i.addElement("LineCount").innerText=s.standardNotationLineCount.toString(),t.percussionArticulations.length>0||s.isPercussion){const e=t.percussionArticulations.length>0?t.percussionArticulations:Array.from(K.instrumentArticulations.values());i.addElement("Name").innerText=Ao.DrumKitProgramInfo.instrumentSetName,i.addElement("Type").innerText=Ao.DrumKitProgramInfo.instrumentSetType;let s="",r=new lt,n=new Map;const o=i.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);s=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=s+" "+r.childNodes.length,e.addElement("StaffLine").innerText=t.staffLine.toString(),e.addElement("Noteheads").innerText=[this.mapMusicSymbol(t.noteHeadDefault),this.mapMusicSymbol(t.noteHeadHalf),this.mapMusicSymbol(t.noteHeadWhole)].join(" "),t.techniqueSymbolPlacement){case C.Top:e.addElement("TechniquePlacement").innerText="below";break;case C.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case C.Bottom:e.addElement("TechniquePlacement").innerText="above"}e.addElement("TechniqueSymbol").innerText=this.mapMusicSymbol(t.techniqueSymbol),e.addElement("InputMidiNumbers").innerText="",e.addElement("OutputMidiNumber").innerText=t.outputMidiNumber.toString()}}else{const e=Ao.MidiProgramInfoLookup.has(t.playbackInfo.program)?Ao.MidiProgramInfoLookup.get(t.playbackInfo.program):Ao.MidiProgramInfoLookup.get(0);i.addElement("Name").innerText=e.instrumentSetName,i.addElement("Type").innerText=e.instrumentSetType;const s=i.addElement("Elements").addElement("Element");s.addElement("Pitched").innerText="Pitched",s.addElement("Type").innerText="pitched",s.addElement("SoundbankName").innerText="";const a=s.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===P.None)return"";let t=P[e];return t.substring(0,1).toLowerCase()+t.substring(1)}writeMasterBarsNode(e,t){const i=e.addElement("MasterBars");for(const e of t.masterBars)this.writeMasterBarNode(i,e)}writeMasterBarNode(e,t){const i=e.addElement("MasterBar"),s=i.addElement("Key");s.addElement("AccidentalCount").innerText=t.keySignature.toString(),s.addElement("Mode").innerText=D[t.keySignatureType],s.addElement("Sharps").innerText="Sharps",i.addElement("Time").innerText=`${t.timeSignatureNumerator}/${t.timeSignatureDenominator}`;let a=[];for(const e of t.score.tracks)for(const i of e.staves)a.push(i.bars[t.index].id.toString());if(i.addElement("Bars").innerText=a.join(" "),t.isDoubleBar&&i.addElement("DoubleBar"),t.isSectionStart){const e=i.addElement("Section");e.addElement("Letter").setCData(t.section.marker),e.addElement("Text").setCData(t.section.text)}if(t.isRepeatStart||t.isRepeatEnd){const e=i.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 s=[];let a=0;for(;e>0;)1==(e>>a&1)&&(s.push(a+1),e&=~(1<<a)),a++;i.addElement("AlternateEndings").innerText=s.join(" ")}t.tripletFeel!==A.NoTripletFeel&&(i.addElement("TripletFeel").innerText=A[t.tripletFeel]),this.writeFermatas(i,t)}writeFermatas(e,t){const i=t.fermata?.size??0;if(0!==i&&i>0){const i=e.addElement("Fermatas");for(const[e,s]of t.fermata)this.writeFermata(i,e,s)}}writeFermata(e,t,i){let s=-1,a=1;if(t>0)for(;a<10&&(s=t/z.QuarterTime*a,s!==Math.floor(s));)s=-1,a++;else s=0,a=1;if(-1===s)return;const r=e.addElement("Fermata");r.addElement("Type").innerText=Ne[i.type],r.addElement("Length").innerText=i.length.toString(),r.addElement("Offset").innerText=`${s}/${a}`}writeBarNode(e,t){const i=e.addElement("Bar");i.attributes.set("id",t.id.toString()),i.addElement("Voices").innerText=t.voices.map((e=>e.isEmpty?"-1":e.id.toString())).join(" "),i.addElement("Clef").innerText=n[t.clef],t.clefOttava!==o.Regular&&(i.addElement("Ottavia").innerText=o[t.clefOttava].substr(1)),t.simileMark!==h.None&&(i.addElement("SimileMark").innerText=h[t.simileMark])}writeVoiceNode(e,t){if(t.isEmpty)return;const i=e.addElement("Voice");i.attributes.set("id",t.id.toString()),i.addElement("Beats").innerText=t.beats.map((e=>e.id)).join(" ")}}Ao.MidiProgramInfoLookup=new Map([[0,new Do(Lo.Piano,"Acoustic Piano")],[1,new Do(Lo.Piano,"Acoustic Piano")],[2,new Do(Lo.Piano,"Electric Piano")],[3,new Do(Lo.Piano,"Acoustic Piano")],[4,new Do(Lo.Piano,"Electric Piano")],[5,new Do(Lo.Piano,"Electric Piano")],[6,new Do(Lo.Piano,"Harpsichord")],[7,new Do(Lo.Piano,"Harpsichord")],[8,new Do(Lo.PitchedIdiophone,"Celesta")],[9,new Do(Lo.PitchedIdiophone,"Vibraphone")],[10,new Do(Lo.PitchedIdiophone,"Vibraphone")],[11,new Do(Lo.PitchedIdiophone,"Vibraphone")],[12,new Do(Lo.PitchedIdiophone,"Xylophone")],[13,new Do(Lo.PitchedIdiophone,"Xylophone")],[14,new Do(Lo.PitchedIdiophone,"Vibraphone")],[15,new Do(Lo.Banjo,"Banjo")],[16,new Do(Lo.Piano,"Electric Organ")],[17,new Do(Lo.Piano,"Electric Organ")],[18,new Do(Lo.Piano,"Electric Organ")],[19,new Do(Lo.Piano,"Electric Organ")],[20,new Do(Lo.Piano,"Electric Organ")],[21,new Do(Lo.Piano,"Electric Organ")],[22,new Do(Lo.Woodwind,"Recorder")],[23,new Do(Lo.Piano,"Electric Organ")],[24,new Do(Lo.ClassicalGuitar,"Nylon Guitar")],[25,new Do(Lo.SteelGuitar,"Steel Guitar")],[26,new Do(Lo.SteelGuitar,"Electric Guitar")],[27,new Do(Lo.ElectricGuitar,"Electric Guitar")],[28,new Do(Lo.ElectricGuitar,"Electric Guitar")],[29,new Do(Lo.ElectricGuitar,"Electric Guitar")],[30,new Do(Lo.SteelGuitar,"Electric Guitar")],[31,new Do(Lo.SteelGuitar,"Electric Guitar")],[32,new Do(Lo.Bass,"Acoustic Bass")],[33,new Do(Lo.Bass,"Electric Bass")],[34,new Do(Lo.Bass,"Electric Bass")],[35,new Do(Lo.Bass,"Acoustic Bass")],[36,new Do(Lo.Bass,"Electric Bass")],[37,new Do(Lo.Bass,"Electric Bass")],[38,new Do(Lo.Synth,"Synth Bass")],[39,new Do(Lo.Synth,"Synth Bass")],[40,new Do(Lo.Strings,"Violin")],[41,new Do(Lo.Strings,"Viola")],[42,new Do(Lo.Strings,"Cello")],[43,new Do(Lo.Strings,"Contrabass")],[44,new Do(Lo.Strings,"Violin")],[45,new Do(Lo.Strings,"Violin")],[46,new Do(Lo.Piano,"Harp")],[47,new Do(Lo.Membraphone,"Timpani")],[48,new Do(Lo.Strings,"Violin")],[49,new Do(Lo.Strings,"Violin")],[50,new Do(Lo.Strings,"Violin")],[51,new Do(Lo.Strings,"Violin")],[52,new Do(Lo.Vocal,"Voice")],[53,new Do(Lo.Vocal,"Voice")],[54,new Do(Lo.Vocal,"Voice")],[55,new Do(Lo.Synth,"Pad Synthesizer")],[56,new Do(Lo.Brass,"Trumpet")],[57,new Do(Lo.Brass,"Trombone")],[58,new Do(Lo.Brass,"Tuba")],[59,new Do(Lo.Brass,"Trumpet")],[60,new Do(Lo.Brass,"French Horn")],[61,new Do(Lo.Brass,"Trumpet")],[62,new Do(Lo.Brass,"Trumpet")],[63,new Do(Lo.Brass,"Trumpet")],[64,new Do(Lo.Reed,"Saxophone")],[65,new Do(Lo.Reed,"Saxophone")],[66,new Do(Lo.Reed,"Saxophone")],[67,new Do(Lo.Reed,"Saxophone")],[68,new Do(Lo.Reed,"Oboe")],[69,new Do(Lo.Reed,"English Horn")],[70,new Do(Lo.Reed,"Bassoon")],[71,new Do(Lo.Reed,"Clarinet")],[72,new Do(Lo.Reed,"Piccolo")],[73,new Do(Lo.Woodwind,"Flute")],[74,new Do(Lo.Woodwind,"Recorder")],[75,new Do(Lo.Woodwind,"Flute")],[76,new Do(Lo.Woodwind,"Recorder")],[77,new Do(Lo.Woodwind,"Flute")],[78,new Do(Lo.Woodwind,"Recorder")],[79,new Do(Lo.Woodwind,"Flute")],[80,new Do(Lo.Synth,"Lead Synthesizer")],[81,new Do(Lo.Synth,"Lead Synthesizer")],[82,new Do(Lo.Synth,"Lead Synthesizer")],[83,new Do(Lo.Synth,"Lead Synthesizer")],[84,new Do(Lo.Synth,"Lead Synthesizer")],[85,new Do(Lo.Synth,"Lead Synthesizer")],[86,new Do(Lo.Synth,"Lead Synthesizer")],[87,new Do(Lo.Synth,"Lead Synthesizer")],[88,new Do(Lo.Synth,"Pad Synthesizer")],[89,new Do(Lo.Synth,"Pad Synthesizer")],[90,new Do(Lo.Synth,"Pad Synthesizer")],[91,new Do(Lo.Synth,"Pad Synthesizer")],[92,new Do(Lo.Synth,"Pad Synthesizer")],[93,new Do(Lo.Synth,"Pad Synthesizer")],[94,new Do(Lo.Synth,"Pad Synthesizer")],[95,new Do(Lo.Synth,"Pad Synthesizer")],[96,new Do(Lo.Fx,"Pad Synthesizer")],[97,new Do(Lo.Fx,"Pad Synthesizer")],[98,new Do(Lo.Fx,"Pad Synthesizer")],[99,new Do(Lo.Fx,"Pad Synthesizer")],[100,new Do(Lo.Fx,"Lead Synthesizer")],[101,new Do(Lo.Fx,"Lead Synthesizer")],[102,new Do(Lo.Fx,"Lead Synthesizer")],[103,new Do(Lo.Fx,"Trumpet")],[104,new Do(Lo.ElectricGuitar,"Banjo")],[105,new Do(Lo.Banjo,"Banjo")],[106,new Do(Lo.Ukulele,"Ukulele")],[107,new Do(Lo.Banjo,"Banjo")],[108,new Do(Lo.PitchedIdiophone,"Xylophone")],[109,new Do(Lo.Reed,"Bassoon")],[110,new Do(Lo.Strings,"Violin")],[111,new Do(Lo.Woodwind,"Flute")],[112,new Do(Lo.PitchedIdiophone,"Xylophone")],[113,new Do(Lo.Idiophone,"Celesta")],[114,new Do(Lo.PitchedIdiophone,"Vibraphone")],[115,new Do(Lo.Idiophone,"Xylophone")],[116,new Do(Lo.Membraphone,"Xylophone")],[117,new Do(Lo.Membraphone,"Xylophone")],[118,new Do(Lo.Membraphone,"Xylophone")],[119,new Do(Lo.Idiophone,"Celesta")],[120,new Do(Lo.Fx,"Steel Guitar")],[121,new Do(Lo.Fx,"Recorder")],[122,new Do(Lo.Fx,"Recorder")],[123,new Do(Lo.Fx,"Recorder")],[124,new Do(Lo.Fx,"Recorder")],[125,new Do(Lo.Fx,"Recorder")],[126,new Do(Lo.Fx,"Recorder")],[127,new Do(Lo.Fx,"Timpani")]]),Ao.DrumKitProgramInfo=new Do(Lo.PercussionKit,"Drums","drumKit");class Ro{static buildCrc32Lookup(){const e=new Uint32Array(256);for(let t=0;t<e.length;t++){let i=t;for(let e=0;e<8;e++)i=1&~i?i>>>1:i>>>1^3988292384;e[t]=i}return e}get value(){return~this._checkValue}constructor(){this._checkValue=Ro.CrcInit,this.reset()}update(e,t,i){for(let s=0;s<i;s++)this._checkValue=Ro.Crc32Lookup[255&(this._checkValue^e[t+s])]^this._checkValue>>>8}reset(){this._checkValue=Ro.CrcInit}}Ro.Crc32Lookup=Ro.buildCrc32Lookup(),Ro.CrcInit=4294967295;class Oo{}Oo.MAX_WBITS=15,Oo.WSIZE=1<<Oo.MAX_WBITS,Oo.WMASK=Oo.WSIZE-1,Oo.MIN_MATCH=3,Oo.MAX_MATCH=258,Oo.DEFAULT_MEM_LEVEL=8,Oo.PENDING_BUF_SIZE=1<<Oo.DEFAULT_MEM_LEVEL+8,Oo.HASH_BITS=Oo.DEFAULT_MEM_LEVEL+7,Oo.HASH_SIZE=1<<Oo.HASH_BITS,Oo.HASH_SHIFT=(Oo.HASH_BITS+Oo.MIN_MATCH-1)/Oo.MIN_MATCH,Oo.HASH_MASK=Oo.HASH_SIZE-1,Oo.MIN_LOOKAHEAD=Oo.MAX_MATCH+Oo.MIN_MATCH+1,Oo.MAX_DIST=Oo.WSIZE-Oo.MIN_LOOKAHEAD;class Go{constructor(e,t,i,s){this.length=null,this.numCodes=0,this.codes=null,this.huffman=e,this.minNumCodes=i,this.maxLength=s,this.freqs=new Int16Array(t),this.bitLengthCounts=new Int32Array(s)}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),i=0,s=0;for(let a=0;a<e;a++){let e=this.freqs[a];if(0!==e){let r=i++;for(;r>0;){let i=Math.floor((r-1)/2);if(!(this.freqs[t[i]]>e))break;t[r]=t[i],r=i}t[r]=a,s=a}}for(;i<2;){let e=s<2?++s:0;t[i++]=e}this.numCodes=Math.max(s+1,this.minNumCodes);let a=i,r=new Int32Array(4*i-2),n=new Int32Array(2*i-1),o=a;for(let e=0;e<i;e++){let i=t[e];r[2*e]=i,r[2*e+1]=-1,n[e]=this.freqs[i]<<8,t[e]=e}do{let e=t[0],s=t[--i],a=0,h=1;for(;h<i;)h+1<i&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*h+1;let l=n[s];for(;h=a,a>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=s;let c=t[0];s=o++,r[2*s]=e,r[2*s+1]=c;let d=Math.min(255&n[e],255&n[c]);for(l=n[e]+n[c]-d+1,n[s]=l,a=0,h=1;h<i;)h+1<i&&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]=s}while(i>1);this.buildLength(r)}buildLength(e){this.length=new Uint8Array(this.freqs.length);let t=Math.floor(e.length/2),i=Math.floor((t+1)/2),s=0;for(let e=0;e<this.maxLength;e++)this.bitLengthCounts[e]=0;let a=new Int32Array(t);a[t-1]=0;for(let i=t-1;i>=0;i--)if(-1!=e[2*i+1]){let t=a[i]+1;t>this.maxLength&&(t=this.maxLength,s++),a[e[2*i]]=t,a[e[2*i+1]]=t}else{let t=a[i];this.bitLengthCounts[t-1]++,this.length[e[2*i]]=a[i]}if(0==s)return;let r=this.maxLength-1;do{for(;0==this.bitLengthCounts[--r];);do{this.bitLengthCounts[r]--,this.bitLengthCounts[++r]++,s-=1<<this.maxLength-1-r}while(s>0&&r<this.maxLength-1)}while(s>0);this.bitLengthCounts[this.maxLength-1]+=s,this.bitLengthCounts[this.maxLength-2]-=s;let n=2*i;for(let t=this.maxLength;0!=t;t--){let i=this.bitLengthCounts[t-1];for(;i>0;){let s=2*e[n++];-1==e[s+1]&&(this.length[e[s]]=t,i--)}}}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,i,s,a=-1,r=0;for(;r<this.numCodes;){s=1;let n=this.length[r];for(0==n?(t=138,i=3):(t=6,i=3,a!=n&&(e.freqs[n]++,s=0)),a=n,r++;r<this.numCodes&&a==this.length[r]&&(r++,!(++s>=t)););s<i?e.freqs[a]+=s:0!=a?e.freqs[Go.Repeat3To6]++:s<=10?e.freqs[Go.Repeat3To10]++:e.freqs[Go.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 i=0;i<this.maxLength;i++)e[i]=t,t+=this.bitLengthCounts[i]<<15-i;for(let t=0;t<this.numCodes;t++){let i=this.length[t];i>0&&(this.codes[t]=Vo.bitReverse(e[i-1]),e[i-1]+=1<<16-i)}}writeTree(e){let t,i,s,a=-1,r=0;for(;r<this.numCodes;){s=1;let n=this.length[r];for(0==n?(t=138,i=3):(t=6,i=3,a!=n&&(e.writeSymbol(n),s=0)),a=n,r++;r<this.numCodes&&a==this.length[r]&&(r++,!(++s>=t)););if(s<i)for(;s-- >0;)e.writeSymbol(a);else 0!=a?(e.writeSymbol(Go.Repeat3To6),this.huffman.pending.writeBits(s-3,2)):s<=10?(e.writeSymbol(Go.Repeat3To10),this.huffman.pending.writeBits(s-3,3)):(e.writeSymbol(Go.Repeat11To138),this.huffman.pending.writeBits(s-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}Go.Repeat3To6=16,Go.Repeat3To10=17,Go.Repeat11To138=18;class Vo{static staticInit(){let e=0;for(;e<144;)Vo.staticLCodes[e]=Vo.bitReverse(48+e<<8),Vo.staticLLength[e++]=8;for(;e<256;)Vo.staticLCodes[e]=Vo.bitReverse(256+e<<7),Vo.staticLLength[e++]=9;for(;e<280;)Vo.staticLCodes[e]=Vo.bitReverse(-256+e<<9),Vo.staticLLength[e++]=7;for(;e<Vo.LITERAL_NUM;)Vo.staticLCodes[e]=Vo.bitReverse(-88+e<<8),Vo.staticLLength[e++]=8;for(e=0;e<Vo.DIST_NUM;e++)Vo.staticDCodes[e]=Vo.bitReverse(e<<11),Vo.staticDLength[e]=5}static bitReverse(e){return Vo.bit4Reverse[15&e]<<12|Vo.bit4Reverse[e>>4&15]<<8|Vo.bit4Reverse[e>>8&15]<<4|Vo.bit4Reverse[e>>12]}constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new Go(this,Vo.LITERAL_NUM,257,15),this.distTree=new Go(this,Vo.DIST_NUM,1,15),this.blTree=new Go(this,Vo.BITLEN_NUM,4,7),this.d_buf=new Int16Array(Vo.BUFSIZE),this.l_buf=new Uint8Array(Vo.BUFSIZE)}isFull(){return this.last_lit>=Vo.BUFSIZE}reset(){this.last_lit=0,this.extra_bits=0,this.literalTree.reset(),this.distTree.reset(),this.blTree.reset()}flushStoredBlock(e,t,i,s){this.pending.writeBits((Vo.STORED_BLOCK<<1)+(s?1:0),3),this.pending.alignToByte(),this.pending.writeShort(i),this.pending.writeShort(~i),this.pending.writeBlock(e,t,i),this.reset()}flushBlock(e,t,i,s){this.literalTree.freqs[Vo.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[Vo.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<Vo.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*Vo.staticLLength[e];for(let e=0;e<Vo.DIST_NUM;e++)n+=this.distTree.freqs[e]*Vo.staticDLength[e];r>=n&&(r=n),t>=0&&i+4<r>>3?this.flushStoredBlock(e,t,i,s):r==n?(this.pending.writeBits((Vo.STATIC_TREES<<1)+(s?1:0),3),this.literalTree.setStaticCodes(Vo.staticLCodes,Vo.staticLLength),this.distTree.setStaticCodes(Vo.staticDCodes,Vo.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((Vo.DYN_TREES<<1)+(s?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[Vo.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],i=this.d_buf[e];if(0!=i--){let e=Vo.Lcode(t);this.literalTree.writeSymbol(e);let s=Math.floor((e-261)/4);s>0&&s<=5&&this.pending.writeBits(t&(1<<s)-1,s);let a=Vo.Dcode(i);this.distTree.writeSymbol(a),s=Math.floor(a/2)-1,s>0&&this.pending.writeBits(i&(1<<s)-1,s)}else this.literalTree.writeSymbol(t)}this.literalTree.writeSymbol(Vo.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;let i=Vo.Lcode(t-3);this.literalTree.freqs[i]++,i>=265&&i<285&&(this.extra_bits+=Math.floor((i-261)/4));let s=Vo.Dcode(e-1);return this.distTree.freqs[s]++,s>=4&&(this.extra_bits+=Math.floor(s/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}}Vo.BUFSIZE=1<<Oo.DEFAULT_MEM_LEVEL+6,Vo.LITERAL_NUM=286,Vo.STORED_BLOCK=0,Vo.STATIC_TREES=1,Vo.DYN_TREES=2,Vo.DIST_NUM=30,Vo.staticLCodes=new Int16Array(Vo.LITERAL_NUM),Vo.staticLLength=new Uint8Array(Vo.LITERAL_NUM),Vo.staticDCodes=new Int16Array(Vo.DIST_NUM),Vo.staticDLength=new Uint8Array(Vo.DIST_NUM),Vo.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Vo.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),Vo.BITLEN_NUM=19,Vo.EOF_SYMBOL=256,Vo.staticInit();class Ho{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 Vo(e),this.inputCrc=new Ro,this.window=new Uint8Array(2*Oo.WSIZE),this.head=new Int16Array(Oo.HASH_SIZE),this.prev=new Int16Array(Oo.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=Oo.MIN_MATCH-1;for(let e=0;e<Oo.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<Oo.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<Oo.HASH_SHIFT^this.window[this.strstart+1]}needsInput(){return this.inputEnd==this.inputOff}setInput(e,t,i){let s=t+i;this.inputBuf=e,this.inputOff=t,this.inputEnd=s}deflate(e,t){let i;do{this.fillWindow();let s=e&&this.inputOff==this.inputEnd;i=this.deflateSlow(s,t)}while(this.pending.isFlushed&&i);return i}deflateSlow(e,t){if(this.lookahead<Oo.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=Oo.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*Oo.WSIZE-Oo.MIN_LOOKAHEAD&&this.slideWindow();let e=this.matchStart,i=this.matchLen;if(this.lookahead>=Oo.MIN_MATCH){let e=this.insertString();0!=e&&this.strstart-e<=Oo.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen==Oo.MIN_MATCH&&this.strstart-this.matchStart>Ho.TooFar&&(this.matchLen=Oo.MIN_MATCH-1)}if(i>=Oo.MIN_MATCH&&this.matchLen<=i){this.huffman.tallyDist(this.strstart-1-e,i),i-=2;do{this.strstart++,this.lookahead--,this.lookahead>=Oo.MIN_MATCH&&this.insertString()}while(--i>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=Oo.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 i=t&&0==this.lookahead&&!this.prevAvailable;return this.huffman.flushBlock(this.window,this.blockStart,e,i),this.blockStart+=e,!i}}return!0}findLongestMatch(e){let t,i=this.strstart,s=i+Math.min(Oo.MAX_MATCH,this.lookahead)-1,a=Math.max(i-Oo.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,Oo.MIN_MATCH-1),i+this.matchLen>s)return!1;let l=r[i+this.matchLen-1],c=r[i+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,i=this.strstart,r[t+this.matchLen]==c&&r[t+this.matchLen-1]==l&&r[t]==r[i]&&r[++t]==r[++i]){switch((s-i)%8){case 1:if(r[++i]==r[++t])break;break;case 2:if(r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 3:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 4:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 5:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 6:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 7:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break}if(r[i]==r[t])do{if(i==s){++i,++t;break}}while(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]);if(i-this.strstart>this.matchLen){if(this.matchStart=e,this.matchLen=i-this.strstart,this.matchLen>=h)break;l=r[i-1],c=r[i]}e=65535&n[e&Oo.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=Oo.MIN_MATCH}insertString(){let e,t=(this.insertHashIndex<<Oo.HASH_SHIFT^this.window[this.strstart+(Oo.MIN_MATCH-1)])&Oo.HASH_MASK;return e=this.head[t],this.prev[this.strstart&Oo.WMASK]=e,this.head[t]=this.strstart,this.insertHashIndex=t,65535&e}fillWindow(){if(this.strstart>=Oo.WSIZE+Oo.MAX_DIST&&this.slideWindow(),this.lookahead<Oo.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*Oo.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>=Oo.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(Oo.WSIZE,Oo.WSIZE+Oo.WSIZE),0),this.matchStart-=Oo.WSIZE,this.strstart-=Oo.WSIZE,this.blockStart-=Oo.WSIZE;for(let e=0;e<Oo.HASH_SIZE;++e){let t=65535&this.head[e];this.head[e]=t>=Oo.WSIZE?t-Oo.WSIZE:0}for(let e=0;e<Oo.WSIZE;e++){let t=65535&this.prev[e];this.prev[e]=t>=Oo.WSIZE?t-Oo.WSIZE:0}}}Ho.TooFar=4096;class Wo{get isFlushed(){return 0===this._end}constructor(e){this._start=0,this._end=0,this._bits=0,this.bitCount=0,this._buffer=new Uint8Array(e)}reset(){this._start=0,this._end=0,this.bitCount=0}writeShortMSB(e){this._buffer[this._end++]=e>>8&255,this._buffer[this._end++]=255&e}writeShort(e){this._buffer[this._end++]=e,this._buffer[this._end++]=e>>8}writeBlock(e,t,i){this._buffer.set(e.subarray(t,t+i),this._end),this._end+=i}flush(e,t,i){return this.bitCount>=8&&(this._buffer[this._end++]=255&this._bits,this._bits>>=8,this.bitCount-=8),i>this._end-this._start?(i=this._end-this._start,e.set(this._buffer.subarray(this._start,this._start+i),t),this._start=0,this._end=0):(e.set(this._buffer.subarray(this._start,this._start+i),t),this._start+=i),i}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 zo{get inputCrc(){return this._engine.inputCrc.value}constructor(){this._state=0,this._pending=new Wo(Oo.PENDING_BUF_SIZE),this._engine=new Ho(this._pending),this.reset()}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state==zo.FinishedState&&this._pending.isFlushed}reset(){this._state=zo.BusyState,this._pending.reset(),this._engine.reset()}setInput(e,t,i){this._engine.setInput(e,t,i)}deflate(e,t,i){let s=i;for(;;){let a=this._pending.flush(e,t,i);if(t+=a,0==(i-=a)||this._state==zo.FinishedState)break;if(!this._engine.deflate(!!(this._state&zo.IsFlushing),!!(this._state&zo.IsFinishing)))switch(this._state){case zo.BusyState:return s-i;case zo.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=zo.BusyState;break;case zo.FinishingState:this._pending.alignToByte(),this._state=zo.FinishedState}}return s-i}finish(){this._state|=zo.IsFlushing|zo.IsFinishing}}zo.IsFlushing=4,zo.IsFinishing=8,zo.BusyState=16,zo.FlushingState=20,zo.FinishingState=28,zo.FinishedState=30;class Uo{constructor(e,t,i,s,a){this.entry=e,this.crc32=t,this.localHeaderOffset=i,this.compressionMode=s,this.compressedSize=a}}class Xo{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new zo,this._data=e}writeEntry(e){const t=Nt.CompressionMethodDeflate,i=ke.empty(),s=this.compress(i,e.data,t),a=i.toArray(),r=new Uo(e,s,this._data.bytesWritten,t,i.length);this._centralDirectoryHeaders.push(r),Te.writeInt32LE(this._data,Nt.LocalFileHeaderSignature),Te.writeUInt16LE(this._data,10),Te.writeUInt16LE(this._data,2048),Te.writeUInt16LE(this._data,t),Te.writeInt16LE(this._data,0),Te.writeInt16LE(this._data,0),Te.writeInt32LE(this._data,s),Te.writeInt32LE(this._data,a.length),Te.writeInt32LE(this._data,e.data.length),Te.writeInt16LE(this._data,e.fullName.length),Te.writeInt16LE(this._data,0);const n=Te.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,i){if(i!=Nt.CompressionMethodDeflate){const i=new Ro;return i.update(t,0,t.length),e.write(t,0,t.length),i.value}{let i=new Uint8Array(512);for(this._deflater.reset(),this._deflater.setInput(t,0,t.length);!this._deflater.isNeedingInput;){const t=this._deflater.deflate(i,0,i.length);if(t<=0)break;e.write(i,0,t)}for(this._deflater.finish();!this._deflater.isFinished;){const t=this._deflater.deflate(i,0,i.length);if(t<=0)break;e.write(i,0,t)}return this._deflater.inputCrc}}end(){const e=this._data.bytesWritten;for(const e of this._centralDirectoryHeaders)this.writeCentralDirectoryHeader(e);const t=this._data.bytesWritten;this.writeEndOfCentralDirectoryRecord(e,t)}writeEndOfCentralDirectoryRecord(e,t){Te.writeInt32LE(this._data,Nt.EndOfCentralDirSignature),Te.writeInt16LE(this._data,0),Te.writeInt16LE(this._data,0),Te.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Te.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Te.writeInt32LE(this._data,t-e),Te.writeInt32LE(this._data,e),Te.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){Te.writeInt32LE(this._data,Nt.CentralFileHeaderSignature),Te.writeUInt16LE(this._data,10),Te.writeUInt16LE(this._data,10),Te.writeUInt16LE(this._data,2048),Te.writeUInt16LE(this._data,e.compressionMode),Te.writeInt16LE(this._data,0),Te.writeInt16LE(this._data,0),Te.writeInt32LE(this._data,e.crc32),Te.writeInt32LE(this._data,e.compressedSize),Te.writeInt32LE(this._data,e.entry.data.length),Te.writeInt16LE(this._data,e.entry.fullName.length),Te.writeInt16LE(this._data,0),Te.writeInt16LE(this._data,0),Te.writeInt16LE(this._data,0),Te.writeInt16LE(this._data,0),Te.writeInt32LE(this._data,0),Te.writeInt32LE(this._data,e.localHeaderOffset);const t=Te.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}var Yo=Object.freeze({__proto__:null,Gp7Exporter:class extends Io{get name(){return"Guitar Pro 7"}constructor(){super()}writeScore(e){J.debug(this.name,"Writing data entries");const t=(new Ao).writeXml(e),i=ot.writeForScore(e),s=St.writeForScore(e);J.debug(this.name,"Writing ZIP entries");let a=new Xo(this.data);a.writeEntry(new Nt("VERSION",Te.stringToBytes("7.0"))),a.writeEntry(new Nt("Content/",new Uint8Array(0))),a.writeEntry(new Nt("Content/BinaryStylesheet",i)),a.writeEntry(new Nt("Content/PartConfiguration",s)),a.writeEntry(new Nt("Content/score.gpif",Te.stringToBytes(t))),a.end()}},ScoreExporter:Io}),qo=Object.freeze({__proto__:null,AlphaSynthMidiFileHandler:Fs,AlphaTabMetronomeEvent:Ht,AlphaTabRestEvent:Wt,BeatTickLookup:Ds,ControlChangeEvent:Yt,get ControllerType(){return Ge},EndOfTrackEvent:$t,MasterBarTickLookup:As,MidiEvent:Ot,get MidiEventType(){return Me},MidiFile:Rt,get MidiFileFormat(){return Le},MidiFileGenerator:Hs,MidiTickLookup:Os,MidiTickLookupFindBeatResult:Rs,NoteBendEvent:Qt,NoteEvent:zt,NoteOffEvent:Xt,NoteOnEvent:Ut,PitchBendEvent:jt,ProgramChangeEvent:qt,TempoChangeEvent:Jt,TimeSignatureEvent:Gt}),Jo=Object.freeze({__proto__:null,get AccentuationType(){return a},get AccidentalType(){return Je},Automation:H,get AutomationType(){return r},Bar:W,Beat:oe,BendPoint:U,get BendStyle(){return l},get BendType(){return c},get BrushType(){return d},Chord:he,get Clef(){return n},Color:me,get CrescendoType(){return u},get Duration(){return p},get DynamicValue(){return g},Fermata:ht,get FermataType(){return Ne},get Fingers(){return m},Font:Ri,get FontStyle(){return Ve},get GraceType(){return f},get HarmonicType(){return y},InstrumentArticulation:$,JsonConverter:ys,get KeySignature(){return M},get KeySignatureType(){return D},Lyrics:le,MasterBar:ce,get MusicFontSymbol(){return P},Note:ee,get NoteAccidentalMode(){return b},get Ottavia(){return o},get PickStroke(){return N},PlaybackInformation:ye,RenderStylesheet:de,RepeatGroup:ue,Score:pe,Section:ge,get SimileMark(){return h},get SlideInType(){return S},get SlideOutType(){return w},Staff:Se,Track:we,get TripletFeel(){return A},Tuning:be,TupletGroup:te,get VibratoType(){return _},Voice:_e,get WhammyType(){return F}}),jo=Object.freeze({__proto__:null,BarBounds:Bs,BeatBounds:Ts,Bounds:nt,BoundsLookup:Ns,MasterBarBounds:ks,NoteBounds:vs,RenderFinishedEventArgs:_s,ScoreRenderer:Ps,StaveGroupBounds:xs}),Qo=Object.freeze({__proto__:null,CssFontSvgCanvas:ba,Cursors:ca,FontSizes:ws,SvgCanvas:ya,get TextAlign(){return E},get TextBaseline(){return C}}),$o=Object.freeze({__proto__:null,ActiveBeatsChangedEventArgs:Qs,AlphaSynth:Mi,AlphaSynthAudioWorkletOutput:ua,AlphaSynthScriptProcessorOutput:na,AlphaSynthWebAudioOutputBase:ra,AlphaSynthWebWorkerApi:ha,CircularSampleBuffer:aa,MidiEventsPlayedEventArgs:Fi,PlaybackRange:Ws,PlaybackRangeChangedEventArgs:Li,get PlayerState(){return Ie},PlayerStateChangedEventArgs:si,PositionChangedEventArgs:ai});Eo.isRunningInWorker?Eo.initializeWorker():Eo.isRunningInAudioWorklet?Eo.initializeAudioWorklet():Eo.initializeMain((t=>{if(Eo.webPlatform==e.WebPlatform.NodeJs)throw new G(e.AlphaTabErrorType.General,"Workers not yet supported in Node.js");if(Eo.webPlatform==e.WebPlatform.BrowserModule||Eo.isWebPackBundled||Eo.isViteBundled)return J.debug("AlphaTab","Creating webworker"),new Eo.alphaTabWorker(new URL("./alphaTab.worker",{}),{type:"module"});if(!t.core.scriptFile)throw new G(e.AlphaTabErrorType.General,"Could not detect alphaTab script file, cannot initialize renderer");try{J.debug("AlphaTab","Creating Blob worker");const e=`importScripts('${t.core.scriptFile}')`,i=new Blob([e]);return new Worker(URL.createObjectURL(i))}catch(e){return J.warning("Rendering","Could not create inline worker, fallback to normal worker"),new Worker(t.core.scriptFile)}}),((t,i)=>{if(Eo.webPlatform==e.WebPlatform.NodeJs)throw new G(e.AlphaTabErrorType.General,"Audio Worklets not yet supported in Node.js");if(Eo.webPlatform==e.WebPlatform.BrowserModule||Eo.isWebPackBundled||Eo.isViteBundled){J.debug("AlphaTab","Creating Module worklet");return t.audioWorklet.addModule(new URL("./alphaTab.worklet",{}))}return J.debug("AlphaTab","Creating Script worklet"),t.audioWorklet.addModule(i.core.scriptFile)})),e.AlphaTabApi=fa,e.AlphaTabError=G,e.CoreSettings=Co,e.DisplaySettings=Gi,e.Environment=Eo,e.FileLoadError=Zs,e.FormatError=fe,e.ImporterSettings=Vi,e.Logger=J,e.NotationSettings=X,e.PlayerSettings=zi,e.ProgressEventArgs=oa,e.RenderingResources=Oi,e.ResizeEventArgs=js,e.Settings=Zi,e.VibratoPlaybackSettings=Hi,e.exporter=Yo,e.importer=Mo,e.meta=Fo,e.midi=qo,e.model=Jo,e.platform=Qo,e.rendering=jo,e.synth=$o}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).alphaTab={})}(this,(function(e){"use strict";var t,i,s,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,A;e.LayoutMode=void 0,(t=e.LayoutMode||(e.LayoutMode={}))[t.Page=0]="Page",t[t.Horizontal=1]="Horizontal",e.StaveProfile=void 0,(i=e.StaveProfile||(e.StaveProfile={}))[i.Default=0]="Default",i[i.ScoreTab=1]="ScoreTab",i[i.Score=2]="Score",i[i.Tab=3]="Tab",i[i.TabMixed=4]="TabMixed";class R{static getValue(e){return R._values||(R._values=new Map),e=e.toLowerCase().replaceAll(" ",""),R._values.has(e)?R._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}}R._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 O{init(e,t){this.data=e,this.settings=t}}e.AlphaTabErrorType=void 0,(s=e.AlphaTabErrorType||(e.AlphaTabErrorType={}))[s.General=0]="General",s[s.Format=1]="Format",s[s.AlphaTex=2]="AlphaTex";class G extends Error{constructor(e,t="",i){super(t??"",{cause:i}),this.type=e,this.inner=i??null,Object.setPrototypeOf(this,G.prototype)}}class V extends G{constructor(t=null,i=null){super(e.AlphaTabErrorType.Format,t??"Unsupported format"),this.inner=i,Object.setPrototypeOf(this,V.prototype)}}!function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy"}(a||(a={})),function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(r||(r={}));class H{constructor(){this.isLinear=!1,this.type=r.Tempo,this.value=0,this.ratioPosition=0,this.text=""}static buildTempoAutomation(e,t,i,s){(s<1||s>5)&&(s=2);let a=new Float32Array([1,.5,1,1.5,2,3]),n=new H;return n.type=r.Tempo,n.isLinear=e,n.ratioPosition=t,n.value=i*a[s],n}static buildInstrumentAutomation(e,t,i){let s=new H;return s.type=r.Instrument,s.isLinear=e,s.ratioPosition=t,s.value=i,s}}!function(e){e[e.Neutral=0]="Neutral",e[e.C3=1]="C3",e[e.C4=2]="C4",e[e.F4=3]="F4",e[e.G2=4]="G2"}(n||(n={})),function(e){e[e._15ma=0]="_15ma",e[e._8va=1]="_8va",e[e.Regular=2]="Regular",e[e._8vb=3]="_8vb",e[e._15mb=4]="_15mb"}(o||(o={})),function(e){e[e.None=0]="None",e[e.Simple=1]="Simple",e[e.FirstOfDouble=2]="FirstOfDouble",e[e.SecondOfDouble=3]="SecondOfDouble"}(h||(h={}));class W{constructor(){this.id=W._globalBarId++,this.index=0,this.nextBar=null,this.previousBar=null,this.clef=n.G2,this.clefOttava=o.Regular,this.voices=[],this.simileMark=h.None,this.isMultiVoice=!1,this.displayScale=1,this.displayWidth=-1}get masterBar(){return this.staff.track.score.masterBars[this.index]}get isEmpty(){for(let e=0,t=this.voices.length;e<t;e++)if(!this.voices[e].isEmpty)return!1;return!0}addVoice(e){e.bar=this,e.index=this.voices.length,this.voices.push(e)}finish(e,t=null){this.isMultiVoice=!1;for(let i=0,s=this.voices.length;i<s;i++){let s=this.voices[i];s.finish(e,t),i>0&&!s.isEmpty&&(this.isMultiVoice=!0)}}calculateDuration(){let e=0;for(let t of this.voices){let i=t.calculateDuration();i>e&&(e=i)}return e}}W._globalBarId=0;class z{static ticksToMillis(e,t){return e*(6e4/(t*z.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*z.QuarterTime))|0}static toTicks(e){return z.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),z.QuarterTime*(4/t)|0}static applyDot(e,t){return t?e+3*(e/4|0):e+(e/2|0)}static applyTuplet(e,t,i){return e*i/t|0}static removeTuplet(e,t,i){return e*t/i|0}static dynamicToVelocity(e){return z.MinVelocity+e*z.VelocityIncrement}}z.QuarterTime=960,z.MinVelocity=15,z.VelocityIncrement=16;class U{constructor(e=0,t=0){this.offset=e,this.value=t}}U.MaxPosition=60,U.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(l||(l={})),function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Bend=2]="Bend",e[e.Release=3]="Release",e[e.BendRelease=4]="BendRelease",e[e.Hold=5]="Hold",e[e.Prebend=6]="Prebend",e[e.PrebendBend=7]="PrebendBend",e[e.PrebendRelease=8]="PrebendRelease"}(c||(c={})),function(e){e[e.None=0]="None",e[e.BrushUp=1]="BrushUp",e[e.BrushDown=2]="BrushDown",e[e.ArpeggioUp=3]="ArpeggioUp",e[e.ArpeggioDown=4]="ArpeggioDown"}(d||(d={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(u||(u={})),function(e){e[e.QuadrupleWhole=-4]="QuadrupleWhole",e[e.DoubleWhole=-2]="DoubleWhole",e[e.Whole=1]="Whole",e[e.Half=2]="Half",e[e.Quarter=4]="Quarter",e[e.Eighth=8]="Eighth",e[e.Sixteenth=16]="Sixteenth",e[e.ThirtySecond=32]="ThirtySecond",e[e.SixtyFourth=64]="SixtyFourth",e[e.OneHundredTwentyEighth=128]="OneHundredTwentyEighth",e[e.TwoHundredFiftySixth=256]="TwoHundredFiftySixth"}(p||(p={})),function(e){e[e.PPP=0]="PPP",e[e.PP=1]="PP",e[e.P=2]="P",e[e.MP=3]="MP",e[e.MF=4]="MF",e[e.F=5]="F",e[e.FF=6]="FF",e[e.FFF=7]="FFF"}(g||(g={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(f||(f={})),function(e){e[e.Unknown=-2]="Unknown",e[e.NoOrDead=-1]="NoOrDead",e[e.Thumb=0]="Thumb",e[e.IndexFinger=1]="IndexFinger",e[e.MiddleFinger=2]="MiddleFinger",e[e.AnnularFinger=3]="AnnularFinger",e[e.LittleFinger=4]="LittleFinger"}(m||(m={})),function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Artificial=2]="Artificial",e[e.Pinch=3]="Pinch",e[e.Tap=4]="Tap",e[e.Semi=5]="Semi",e[e.Feedback=6]="Feedback"}(y||(y={})),function(e){e[e.Default=0]="Default",e[e.ForceNone=1]="ForceNone",e[e.ForceNatural=2]="ForceNatural",e[e.ForceSharp=3]="ForceSharp",e[e.ForceDoubleSharp=4]="ForceDoubleSharp",e[e.ForceFlat=5]="ForceFlat",e[e.ForceDoubleFlat=6]="ForceDoubleFlat"}(b||(b={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(S||(S={})),function(e){e[e.None=0]="None",e[e.Shift=1]="Shift",e[e.Legato=2]="Legato",e[e.OutUp=3]="OutUp",e[e.OutDown=4]="OutDown",e[e.PickSlideDown=5]="PickSlideDown",e[e.PickSlideUp=6]="PickSlideUp"}(w||(w={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(_||(_={})),e.TabRhythmMode=void 0,(B=e.TabRhythmMode||(e.TabRhythmMode={}))[B.Hidden=0]="Hidden",B[B.ShowWithBeams=1]="ShowWithBeams",B[B.ShowWithBars=2]="ShowWithBars",e.FingeringMode=void 0,(T=e.FingeringMode||(e.FingeringMode={}))[T.ScoreDefault=0]="ScoreDefault",T[T.ScoreForcePiano=1]="ScoreForcePiano",T[T.SingleNoteEffectBand=2]="SingleNoteEffectBand",T[T.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano",e.NotationMode=void 0,(k=e.NotationMode||(e.NotationMode={}))[k.GuitarPro=0]="GuitarPro",k[k.SongBook=1]="SongBook",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"}(v||(v={}));class X{constructor(){this.notationMode=e.NotationMode.GuitarPro,this.fingeringMode=e.FingeringMode.ScoreDefault,this.elements=new Map,this.rhythmMode=e.TabRhythmMode.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):!X.defaultElements.has(e)||X.defaultElements.get(e)}}X.defaultElements=new Map([[v.ZerosOnDiveWhammys,!1]]);class Y{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}e.LogLevel=void 0,(x=e.LogLevel||(e.LogLevel={}))[x.None=0]="None",x[x.Debug=1]="Debug",x[x.Info=2]="Info",x[x.Warning=3]="Warning",x[x.Error=4]="Error";class q{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...i){console.debug(q.format(e,t),...i)}warning(e,t,...i){console.warn(q.format(e,t),...i)}info(e,t,...i){console.info(q.format(e,t),...i)}error(e,t,...i){console.error(q.format(e,t),...i)}}q.logLevel=e.LogLevel.Info;class J{static shouldLog(t){return J.logLevel!==e.LogLevel.None&&t>=J.logLevel}static debug(t,i,...s){J.shouldLog(e.LogLevel.Debug)&&J.log.debug(t,i,...s)}static warning(t,i,...s){J.shouldLog(e.LogLevel.Warning)&&J.log.warning(t,i,...s)}static info(t,i,...s){J.shouldLog(e.LogLevel.Info)&&J.log.info(t,i,...s)}static error(t,i,...s){J.shouldLog(e.LogLevel.Error)&&J.log.error(t,i,...s)}}J.logLevel=e.LogLevel.Info,J.log=new q;class j{constructor(){this.note=null,this.noteValue=0,this.octave=0}get realValue(){return 12*this.octave+this.noteValue}}class Q{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 i=0;i<t.tracks.length;i++){if(i<e.notation.displayTranspositionPitches.length)for(let s of t.tracks[i].staves)s.displayTranspositionPitch=-e.notation.displayTranspositionPitches[i];if(i<e.notation.transpositionPitches.length)for(let s of t.tracks[i].staves)s.transpositionPitch=-e.notation.transpositionPitches[i]}}static fingerToString(t,i,s,a){if(t.notation.fingeringMode===e.FingeringMode.ScoreForcePiano||t.notation.fingeringMode===e.FingeringMode.SingleNoteEffectBandForcePiano||R.isPiano(i.voice.bar.staff.track.playbackInfo.program))switch(s){case m.Unknown:case m.NoOrDead:return null;case m.Thumb:return"1";case m.IndexFinger:return"2";case m.MiddleFinger:return"3";case m.AnnularFinger:return"4";case m.LittleFinger:return"5";default:return null}if(a)switch(s){case m.Unknown:case m.NoOrDead:return"0";case m.Thumb:return"T";case m.IndexFinger:return"1";case m.MiddleFinger:return"2";case m.AnnularFinger:return"3";case m.LittleFinger:return"4";default:return null}switch(s){case m.Unknown:case m.NoOrDead:return null;case m.Thumb:return"p";case m.IndexFinger:return"i";case m.MiddleFinger:return"m";case m.AnnularFinger:return"a";case m.LittleFinger:return"c";default:return null}}static isTuning(e){return!!Q.parseTuning(e)}static parseTuning(e){let t="",i="";for(let s=0;s<e.length;s++){let a=e.charCodeAt(s);if(a>=48&&a<=57){if(!t)return null;i+=String.fromCharCode(a)}else{if(!(a>=65&&a<=90||a>=97&&a<=122||35===a))return null;t+=String.fromCharCode(a)}}if(!i||!t)return null;let s=new j;return s.octave=parseInt(i)+1,s.note=t.toLowerCase(),s.noteValue=Q.getToneForText(s.note),s}static getTuningForText(e){let t=Q.parseTuning(e);return t?t.realValue:-1}static getToneForText(e){switch(e.toLowerCase()){case"c":default:return 0;case"c#":case"db":return 1;case"d":return 2;case"d#":case"eb":return 3;case"e":return 4;case"f":return 5;case"f#":case"gb":return 6;case"g":return 7;case"g#":case"ab":return 8;case"a":return 9;case"a#":case"bb":return 10;case"b":return 11}}static newGuid(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+"-"+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)}static isAlmostEqualTo(e,t){return Math.abs(e-t)<1e-5}static toHexString(e,t=0){let i="";do{i=String.fromCharCode("0123456789ABCDEF".charCodeAt(15&e))+i,e>>=4}while(e>0);for(;i.length<t;)i="0"+i;return i}}!function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(N||(N={})),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"}(P||(P={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(E||(E={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(C||(C={}));class ${constructor(e="",t=0,i=0,s=P.None,a=P.None,r=P.None,n=P.None,o=C.Middle){this.elementType=e,this.outputMidiNumber=i,this.staffLine=t,this.noteHeadDefault=s,this.noteHeadHalf=a!==P.None?a:s,this.noteHeadWhole=r!==P.None?r:s,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case p.Whole:return this.noteHeadWhole;case p.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class K{static articulationFromElementVariation(e,t){return e<K.gp6ElementAndVariationToArticulation.length?(t>=K.gp6ElementAndVariationToArticulation.length&&(t=0),K.gp6ElementAndVariationToArticulation[e][t]):38}static getArticulation(e){const t=e.percussionArticulation,i=e.beat.voice.bar.staff.track.percussionArticulations;return t<i.length?i[t]:K.getArticulationByValue(t)}static getElementAndVariation(e){const t=K.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<K.gp6ElementAndVariationToArticulation.length;e++){const i=K.gp6ElementAndVariationToArticulation[e];for(let s=0;s<i.length;s++){const a=K.getArticulationByValue(i[s]);if(a?.outputMidiNumber===t.outputMidiNumber)return[e,s]}}return[-1,-1]}static getArticulationByValue(e){return K.instrumentArticulations.has(e)?K.instrumentArticulations.get(e):null}}K.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]],K.instrumentArticulations=new Map([[38,new $("snare",3,38,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[37,new $("snare",3,37,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[91,new $("snare",3,38,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite)],[42,new $("hiHat",-1,42,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[92,new $("hiHat",-1,46,P.NoteheadCircleSlash,P.NoteheadCircleSlash,P.NoteheadCircleSlash)],[46,new $("hiHat",-1,46,P.NoteheadCircleX,P.NoteheadCircleX,P.NoteheadCircleX)],[44,new $("hiHat",9,44,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[35,new $("kickDrum",8,35,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[36,new $("kickDrum",7,36,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[50,new $("tom",1,50,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[48,new $("tom",2,48,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[47,new $("tom",4,47,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[45,new $("tom",5,45,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[43,new $("tom",6,43,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[93,new $("ride",0,51,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.PictEdgeOfCymbal,C.Bottom)],[51,new $("ride",0,51,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[53,new $("ride",0,53,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite)],[94,new $("ride",0,51,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.ArticStaccatoAbove,C.Top)],[55,new $("splash",-2,55,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[95,new $("splash",-2,55,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.ArticStaccatoAbove,C.Bottom)],[52,new $("china",-3,52,P.NoteheadHeavyXHat,P.NoteheadHeavyXHat,P.NoteheadHeavyXHat)],[96,new $("china",-3,52,P.NoteheadHeavyXHat,P.NoteheadHeavyXHat,P.NoteheadHeavyXHat)],[49,new $("crash",-2,49,P.NoteheadHeavyX,P.NoteheadHeavyX,P.NoteheadHeavyX)],[97,new $("crash",-2,49,P.NoteheadHeavyX,P.NoteheadHeavyX,P.NoteheadHeavyX,P.ArticStaccatoAbove,C.Bottom)],[57,new $("crash",-1,57,P.NoteheadHeavyX,P.NoteheadHeavyX,P.NoteheadHeavyX)],[98,new $("crash",-1,57,P.NoteheadHeavyX,P.NoteheadHeavyX,P.NoteheadHeavyX,P.ArticStaccatoAbove,C.Bottom)],[99,new $("cowbell",1,56,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpHalf,P.NoteheadTriangleUpWhole)],[100,new $("cowbell",1,56,P.NoteheadXBlack,P.NoteheadXHalf,P.NoteheadXWhole)],[56,new $("cowbell",0,56,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpHalf,P.NoteheadTriangleUpWhole)],[101,new $("cowbell",0,56,P.NoteheadXBlack,P.NoteheadXHalf,P.NoteheadXWhole)],[102,new $("cowbell",-1,56,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpHalf,P.NoteheadTriangleUpWhole)],[103,new $("cowbell",-1,56,P.NoteheadXBlack,P.NoteheadXHalf,P.NoteheadXWhole)],[77,new $("woodblock",-9,77,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack)],[76,new $("woodblock",-10,76,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack)],[60,new $("bongo",-4,60,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[104,new $("bongo",-5,60,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.NoteheadParenthesis,C.Middle)],[105,new $("bongo",-6,60,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[61,new $("bongo",-7,61,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[106,new $("bongo",-8,61,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.NoteheadParenthesis,C.Middle)],[107,new $("bongo",-16,61,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[66,new $("timbale",10,66,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[65,new $("timbale",9,65,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[68,new $("agogo",12,68,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[67,new $("agogo",11,67,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[64,new $("conga",17,64,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[108,new $("conga",16,64,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[109,new $("conga",15,64,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.NoteheadParenthesis,C.Middle)],[63,new $("conga",14,63,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[110,new $("conga",13,63,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[62,new $("conga",19,62,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.NoteheadParenthesis,C.Middle)],[72,new $("whistle",-11,72,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[71,new $("whistle",-17,71,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[73,new $("guiro",38,73,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[74,new $("guiro",37,74,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[86,new $("surdo",36,86,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[87,new $("surdo",35,87,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadParenthesis,C.Middle)],[54,new $("tambourine",3,54,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack)],[111,new $("tambourine",2,54,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.StringsUpBow,C.Bottom)],[112,new $("tambourine",1,54,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.NoteheadTriangleUpBlack,P.StringsDownBow,C.Bottom)],[113,new $("tambourine",-7,54,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[79,new $("cuica",30,79,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[78,new $("cuica",29,78,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[58,new $("vibraslap",28,58,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[81,new $("triangle",27,81,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[80,new $("triangle",26,80,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadParenthesis,C.Middle)],[114,new $("grancassa",25,43,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[115,new $("piatti",18,49,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[116,new $("piatti",24,49,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[69,new $("cabasa",23,69,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[117,new $("cabasa",22,69,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[85,new $("castanets",21,85,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[75,new $("claves",20,75,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[70,new $("maraca",-12,70,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[118,new $("maraca",-13,70,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[119,new $("maraca",-14,70,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[120,new $("maraca",-15,70,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[82,new $("shaker",-23,54,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[122,new $("shaker",-24,54,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[84,new $("bellTree",-18,53,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[123,new $("bellTree",-19,53,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole,P.StringsUpBow,C.Bottom)],[83,new $("jingleBell",-20,53,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[124,new $("unpitched",-21,62,P.NoteheadNull,P.NoteheadNull,P.NoteheadNull,P.GuitarGolpe,C.Top)],[125,new $("unpitched",-22,62,P.NoteheadNull,P.NoteheadNull,P.NoteheadNull,P.GuitarGolpe,C.Bottom)],[39,new $("handClap",3,39,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[40,new $("snare",3,40,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[31,new $("snare",3,40,P.NoteheadSlashedBlack2,P.NoteheadSlashedBlack2,P.NoteheadSlashedBlack2)],[41,new $("tom",5,41,P.NoteheadBlack,P.NoteheadHalf,P.NoteheadWhole)],[59,new $("ride",2,59,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.PictEdgeOfCymbal,C.Bottom)],[126,new $("ride",2,59,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[127,new $("ride",2,59,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite,P.NoteheadDiamondWhite)],[29,new $("ride",2,59,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack,P.ArticStaccatoAbove,C.Top)],[30,new $("crash",-3,49,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[33,new $("snare",3,37,P.NoteheadXBlack,P.NoteheadXBlack,P.NoteheadXBlack)],[34,new $("snare",3,38,P.NoteheadBlack,P.NoteheadBlack,P.NoteheadBlack)]]);class Z{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1}}class ee{constructor(){this.id=ee.GlobalNoteId++,this.index=0,this.accentuated=a.None,this.bendType=c.None,this.bendStyle=l.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=y.None,this.harmonicValue=0,this.isGhost=!1,this.isLetRing=!1,this.letRingDestination=null,this.isPalmMute=!1,this.palmMuteDestination=null,this.isDead=!1,this.isStaccato=!1,this.slideInType=S.None,this.slideOutType=w.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=_.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=m.Unknown,this.rightHandFinger=m.Unknown,this.isFingering=!1,this.trillValue=-1,this.trillSpeed=p.ThirtySecond,this.durationPercent=1,this.accidentalMode=b.Default,this.dynamics=g.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this._noteIdBag=null}get hasBend(){return null!==this.bendPoints&&this.bendType!==c.None}get isStringed(){return this.string>=0}get isPiano(){return!this.isStringed&&this.octave>=0&&this.tone>=0}get isPercussion(){return!this.isStringed&&this.percussionArticulation>=0}get element(){return this.isPercussion?K.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?K.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==y.None}get isTieOrigin(){return null!==this.tieDestination}get 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+ee.getStringTuning(this.beat.voice.bar.staff,this.string)}static getStringTuning(e,t){return e.tuning.length>0?e.tuning[e.tuning.length-(t-1)-1]:0}get realValue(){return this.calculateRealValue(!0,!0)}get realValueWithoutHarmonic(){return this.calculateRealValue(!0,!1)}calculateRealValue(e,t){const i=e?this.beat.voice.bar.staff.transpositionPitch:0;if(t){let t=this.calculateRealValue(e,!1);return this.isStringed&&(this.harmonicType===y.Natural?t=this.harmonicPitch+this.stringTuning-i:t+=this.harmonicPitch),t}return this.isPercussion?this.percussionArticulation:this.isStringed?this.fret+this.stringTuning-i:this.isPiano?12*this.octave+this.tone-i:0}get harmonicPitch(){if(this.harmonicType===y.None||!this.isStringed)return 0;let e=this.harmonicValue;return Q.isAlmostEqualTo(e,2.4)?36:Q.isAlmostEqualTo(e,2.7)?34:e<3?0:e<=3.5?31:e<=4?28:e<=5?24:e<=6?34:e<=7?19:e<=8.5?36:e<=9?28:e<=10?34:e<=11?0:e<=12?12:e<14?0:e<=15?34:e<=16?28:e<=17?36:e<=18?0:e<=19?19:e<=21?0:e<=22?36:e<=24?24:0}get initialBendValue(){return this.hasBend?Math.floor(this.bendPoints[0].value/2):this.bendOrigin?Math.floor(this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value/2):this.isTieDestination&&this.tieOrigin.bendOrigin?Math.floor(this.tieOrigin.bendOrigin.bendPoints[this.tieOrigin.bendOrigin.bendPoints.length-1].value/2):this.beat.hasWhammyBar?Math.floor(this.beat.whammyBarPoints[0].value/2):this.beat.isContinuedWhammy?Math.floor(this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value/2):0}get displayValue(){return this.displayValueWithoutBend+this.initialBendValue}get displayValueWithoutBend(){let e=this.realValue;switch(this.harmonicType!==y.Natural&&this.harmonicType!==y.None&&(e-=this.harmonicPitch),this.beat.ottava){case o._15ma:e-=24;break;case o._8va:e-=12;break;case o.Regular:break;case o._8vb:e+=12;break;case o._15mb:e+=24}switch(this.beat.voice.bar.clefOttava){case o._15ma:e-=24;break;case o._8va:e-=12;break;case o.Regular:break;case o._8vb:e+=12;break;case o._15mb:e+=24}return e-this.beat.voice.bar.staff.displayTranspositionPitch}get hasQuarterToneOffset(){return this.hasBend?this.bendPoints[0].value%2!=0:this.bendOrigin?this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value%2!=0:this.beat.hasWhammyBar?this.beat.whammyBarPoints[0].value%2!=0:!!this.beat.isContinuedWhammy&&this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value%2!=0}addBendPoint(e){let t=this.bendPoints;null===t&&(t=[],this.bendPoints=t),t.push(e),(!this.maxBendPoint||e.value>this.maxBendPoint.value)&&(this.maxBendPoint=e),this.bendType===c.None&&(this.bendType=c.Custom)}finish(t,i=null){let s=new Y((()=>ee.nextNoteOnSameLine(this))),a=t&&t.notation.notationMode===e.NotationMode.SongBook;if(this.isTieDestination&&(this.chain(i),a&&this.tieOrigin&&this.tieOrigin.isLetRing&&(this.isLetRing=!0)),this.isLetRing&&(s.value&&s.value.isLetRing?this.letRingDestination=s.value:this.letRingDestination=this,a&&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=ee.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case w.Shift:case w.Legato:this.slideTarget=s.value,this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=w.None}let r=null;this.isHammerPullOrigin&&this.hammerPullDestination?r=this.hammerPullDestination:this.slideOutType===w.Legato&&this.slideTarget&&(r=this.slideTarget),r&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===N.None?(this.effectSlurOrigin.effectSlurDestination=r,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=r,this.effectSlurDestination.effectSlurOrigin=this));const n=this.bendPoints;if(null!=n&&n.length>0&&this.bendType===c.Custom){let e=this.isTieDestination&&this.tieOrigin.hasBend;if(this.isContinuedBend=e,4===n.length){let t=n[0],i=n[1],s=n[2],a=n[3];i.value===s.value?a.value>t.value?i.value>a.value?this.bendType=c.BendRelease:!e&&t.value>0?(this.bendType=c.PrebendBend,n.splice(2,1),n.splice(1,1)):(this.bendType=c.Bend,n.splice(2,1),n.splice(1,1)):a.value<t.value?e?(this.bendType=c.Release,n.splice(2,1),n.splice(1,1)):(this.bendType=c.PrebendRelease,n.splice(2,1),n.splice(1,1)):i.value>t.value?this.bendType=c.BendRelease:t.value>0&&!e?(this.bendType=c.Prebend,n.splice(2,1),n.splice(1,1)):(this.bendType=c.Hold,n.splice(2,1),n.splice(1,1)):J.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===n.length){let t=n[0],i=n[1];i.value>t.value?!e&&t.value>0?this.bendType=c.PrebendBend:this.bendType=c.Bend:i.value<t.value?this.bendType=e?c.Release:c.PrebendRelease:this.bendType=c.Hold}}else null!==n&&0!==n.length||(this.bendType=c.None);this.initialBendValue>0&&(this.accidentalMode=b.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+ee.MaxOffsetForSameLineSearch;){let i=t.getNoteOnString(e.string);if(i)return i;t=t.nextBeat}return null}static findHammerPullDestination(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+ee.MaxOffsetForSameLineSearch;){let i=t.getNoteOnString(e.string);if(i)return i;for(let s=e.string;s>0;s--)if(i=t.getNoteOnString(s),i){if(i.isLeftHandTapped)return i;break}for(let s=e.string;s<=e.beat.voice.bar.staff.tuning.length;s++)if(i=t.getNoteOnString(s),i){if(i.isLeftHandTapped)return i;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-ee.MaxOffsetForSameLineSearch;){if(e.isStringed){let i=t.getNoteOnString(e.string);if(i)return i}else if(-1===e.octave&&-1===e.tone){if(e.index<t.notes.length)return t.notes[e.index]}else{let i=t.getNoteWithRealValue(e.realValue);if(i)return i}t=t.previousBeat}return null}chain(e=null){if(null!==e)if(null!==this._noteIdBag){let t;e.has(ee.NoteIdLookupKey)?t=e.get(ee.NoteIdLookupKey):(t=new Map,e.set(ee.NoteIdLookupKey,t)),-1===this._noteIdBag.hammerPullDestinationNoteId&&-1===this._noteIdBag.tieDestinationNoteId&&-1===this._noteIdBag.slurDestinationNoteId||t.set(this.id,this),-1!==this._noteIdBag.hammerPullOriginNoteId&&(this.hammerPullOrigin=t.get(this._noteIdBag.hammerPullOriginNoteId),this.hammerPullOrigin.hammerPullDestination=this),-1!==this._noteIdBag.tieOriginNoteId&&(this.tieOrigin=t.get(this._noteIdBag.tieOriginNoteId),this.tieOrigin.tieDestination=this),-1!==this._noteIdBag.slurOriginNoteId&&(this.slurOrigin=t.get(this._noteIdBag.slurOriginNoteId),this.slurOrigin.slurDestination=this),this._noteIdBag=null}else{if(!this.isTieDestination&&null===this.tieOrigin)return;let e=this.tieOrigin??ee.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 Z),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Z),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Z),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Z),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Z),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new Z),this._noteIdBag.hammerPullDestinationNoteId=t,!0}return!1}}ee.GlobalNoteId=0,ee.MaxOffsetForSameLineSearch=3,ee.NoteIdLookupKey="NoteIdLookup";class te{constructor(e){this._isEqualLengthTuplet=!0,this.totalDuration=0,this.beats=[],this.isFull=!1,this.voice=e}check(e){if(0===this.beats.length)return this.beats.push(e),this.totalDuration+=e.playbackDuration,!0;if(e.graceType!==f.None)return!0;if(e.voice!==this.voice||this.isFull||e.tupletNumerator!==this.beats[0].tupletNumerator||e.tupletDenominator!==this.beats[0].tupletDenominator)return!1;if(e.playbackDuration!==this.beats[0].playbackDuration&&(this._isEqualLengthTuplet=!1),this.beats.push(e),this.totalDuration+=e.playbackDuration,this._isEqualLengthTuplet)this.beats.length===this.beats[0].tupletNumerator&&(this.isFull=!0);else{let e=this.beats[0].tupletNumerator/this.beats[0].tupletDenominator|0;for(let t of te.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}te.HalfTicks=1920,te.QuarterTicks=960,te.EighthTicks=480,te.SixteenthTicks=240,te.ThirtySecondTicks=120,te.SixtyFourthTicks=60,te.OneHundredTwentyEighthTicks=30,te.TwoHundredFiftySixthTicks=15,te.AllTicks=[te.HalfTicks,te.QuarterTicks,te.EighthTicks,te.SixteenthTicks,te.ThirtySecondTicks,te.SixtyFourthTicks,te.OneHundredTwentyEighthTicks,te.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"}(F||(F={}));class ie{static clone(e){const t=new U;return t.offset=e.offset,t.value=e.value,t}}class se{static clone(e){const t=new ee;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 i of e.bendPoints)t.addBendPoint(ie.clone(i))}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 ae{static clone(e){const t=new H;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class re{static clone(e){const t=new oe;t.index=e.index,t.notes=[];for(const i of e.notes)t.addNote(se.clone(i));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 i of e.automations)t.automations.push(ae.clone(i));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 i of e.whammyBarPoints)t.addWhammyBarPoint(ie.clone(i))}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 ne{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"}(L||(L={}));class oe{constructor(){this.id=oe._globalBeatId++,this.index=0,this.previousBeat=null,this.nextBeat=null,this.notes=[],this.noteStringLookup=new Map,this.noteValueLookup=new Map,this.isEmpty=!1,this.whammyStyle=l.Default,this.ottava=o.Regular,this.fermata=null,this.isLegatoOrigin=!1,this.minNote=null,this.maxNote=null,this.maxStringNote=null,this.minStringNote=null,this.duration=p.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fadeIn=!1,this.lyrics=null,this.hasRasgueado=!1,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.brushType=d.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=F.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=_.None,this.chordId=null,this.graceType=f.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=N.None,this.tremoloSpeed=null,this.crescendo=u.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.dynamics=g.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=L.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===p.Whole}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==F.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===F.None&&(this.whammyBarType=F.Custom)}removeWhammyBarPoint(e){const t=this.whammyBarPoints;if(null===t||e<0||e>=t.length)return;t.splice(e,1);let i=t[e];if(i===this.maxWhammyPoint){this.maxWhammyPoint=null;for(let e of t)(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e)}if(i===this.minWhammyPoint){this.minWhammyPoint=null;for(let e of t)(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e)}}addNote(e){e.beat=this,e.index=this.notes.length,this.notes.push(e),e.isStringed&&this.noteStringLookup.set(e.string,e)}removeNote(e){let t=this.notes.indexOf(e);t>=0&&(this.notes.splice(t,1),e.isStringed&&this.noteStringLookup.delete(e.string))}getAutomation(e){for(let t=0,i=this.automations.length;t<i;t++){let i=this.automations[t];if(i.type===e)return i}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=z.toTicks(this.duration);return 2===this.dots?e=z.applyDot(e,!0):1===this.dots&&(e=z.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=z.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){let e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case f.BeforeBeat:case f.OnBeat:switch(this.duration){case p.Sixteenth:this.playbackDuration=z.toTicks(p.SixtyFourth);break;case p.ThirtySecond:this.playbackDuration=z.toTicks(p.OneHundredTwentyEighth);break;default:this.playbackDuration=z.toTicks(p.ThirtySecond)}this.displayDuration=0;break;case f.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;let t=this.previousBeat;t&&t.graceType===f.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){let e=this.previousBeat,t=e?e.tupletGroup:null;(this.hasTuplet||this.graceType!==f.None&&t)&&(e&&t&&t.check(this)||(t=new te(this.voice),t.check(this)),this.tupletGroup=t)}finish(t,i=null){switch(null===this.getAutomation(r.Instrument)&&0===this.index&&0===this.voice.index&&0===this.voice.bar.index&&0===this.voice.bar.staff.index&&this.automations.push(H.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case f.OnBeat:case f.BeforeBeat:let e=this.graceGroup.beats.length;this.duration=1===e?p.Eighth:2===e?p.Sixteenth:p.ThirtySecond}let s=t?t.notation.notationMode:e.NotationMode.GuitarPro,a="grad"===this.text||"grad."===this.text;a&&s===e.NotationMode.SongBook&&(this.text="");let n=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let o=0,h=!1;for(let r=0,d=this.notes.length;r<d;r++){let d=this.notes[r];if(d.dynamics=this.dynamics,d.finish(t,i),d.isLetRing&&(this.isLetRing=!0),d.isPalmMute&&(this.isPalmMute=!0),s===e.NotationMode.SongBook&&d.hasBend&&this.graceType!==f.BendGrace){if(!d.isTieOrigin)switch(d.bendType){case c.Bend:case c.PrebendRelease:case c.PrebendBend:n=!0}a||d.bendStyle===l.Gradual?(a=!0,d.bendStyle=l.Gradual,n=!1):d.bendStyle=l.Fast}d.isVisible&&(o++,(!this.minNote||d.realValue<this.minNote.realValue)&&(this.minNote=d),(!this.maxNote||d.realValue>this.maxNote.realValue)&&(this.maxNote=d),(!this.minStringNote||d.string<this.minStringNote.string)&&(this.minStringNote=d),(!this.maxStringNote||d.string>this.maxStringNote.string)&&(this.maxStringNote=d),d.hasEffectSlur&&(h=!0))}if(h&&(this.effectSlurOrigin?(this.effectSlurOrigin.effectSlurDestination=this.nextBeat,this.effectSlurOrigin.effectSlurDestination&&(this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin),this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=this.nextBeat,this.effectSlurDestination&&(this.effectSlurDestination.effectSlurOrigin=this))),this.notes.length>0&&0===o&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&t&&t.notation.notationMode===e.NotationMode.GuitarPro&&(this.previousBeat.isLetRing&&(this.isLetRing=!0),this.previousBeat.isPalmMute&&(this.isPalmMute=!0));else{let e=this.previousBeat;for(;e&&e.isRest;)this.isLetRing||(e.isLetRing=!1),this.isPalmMute||(e.isPalmMute=!1),e=e.previousBeat}const d=this.whammyBarPoints;if(null!==d&&d.length>0&&this.whammyBarType===F.Custom){s===e.NotationMode.SongBook&&(this.whammyStyle=a?l.Gradual:l.Fast);let t=!!this.previousBeat&&this.previousBeat.hasWhammyBar;if(this.isContinuedWhammy=t,4===d.length){let i=d[0],a=d[1],r=d[2],n=d[3];a.value===r.value&&(i.value<a.value&&a.value<n.value||i.value>a.value&&a.value>n.value?(0===i.value||t?this.whammyBarType=F.Dive:this.whammyBarType=F.PrediveDive,d.splice(2,1),d.splice(1,1)):i.value>a.value&&a.value<n.value||i.value<a.value&&a.value>n.value?(this.whammyBarType=F.Dip,a.offset!==r.offset&&s!==e.NotationMode.SongBook||d.splice(2,1)):i.value===a.value&&a.value===n.value&&(0===i.value||t?this.whammyBarType=F.Hold:this.whammyBarType=F.Predive,d.splice(2,1),d.splice(1,1)))}}if(this.updateDurations(),n){let e=re.clone(this);e.id=oe._globalBeatId++,e.pickStroke=N.None;for(let t=0,i=e.notes.length;t<i;t++){let i=e.notes[t],s=this.notes[t];if(i.bendType=c.None,i.maxBendPoint=null,i.bendPoints=null,i.bendStyle=l.Default,i.id=ee.GlobalNoteId++,s.isTieOrigin&&(i.tieDestination=s.tieDestination,s.tieDestination.tieOrigin=i),s.isTieDestination&&(i.tieOrigin=s.tieOrigin?s.tieOrigin:null,s.tieOrigin.tieDestination=i),s.hasBend&&s.isTieOrigin){let e=ee.findTieOrigin(s);if(e&&e.hasBend){i.bendType=c.Hold;let e=s.bendPoints[s.bendPoints.length-1];i.addBendPoint(new U(0,e.value)),i.addBendPoint(new U(U.MaxPosition,e.value))}}i.isTieDestination=!0}this.graceType=f.BendGrace,this.graceGroup=new ne,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new ne,e.graceGroup.addBeat(this),e.graceGroup.isComplete=!0,e.graceGroup.finish()}}isBefore(e){return this.voice.bar.index<e.voice.bar.index||e.voice.bar.index===this.voice.bar.index&&this.index<e.index}isAfter(e){return this.voice.bar.index>e.voice.bar.index||e.voice.bar.index===this.voice.bar.index&&this.index>e.index}hasNoteOnString(e){return this.noteStringLookup.has(e)}getNoteWithRealValue(e){return this.noteValueLookup.has(e)?this.noteValueLookup.get(e):null}chain(e=null){for(const t of this.notes)this.noteValueLookup.set(t.realValue,t),t.chain(e)}}oe._globalBeatId=0;class he{constructor(){this.name="",this.firstFret=1,this.strings=[],this.barreFrets=[],this.showName=!0,this.showDiagram=!0,this.showFingering=!0}get uniqueId(){return[this.name,this.firstFret.toString(),this.strings.join(","),this.barreFrets.join(","),this.showDiagram.toString(),this.showFingering.toString(),this.showName.toString()].join("|")}}!function(e){e[e.Cb=-7]="Cb",e[e.Gb=-6]="Gb",e[e.Db=-5]="Db",e[e.Ab=-4]="Ab",e[e.Eb=-3]="Eb",e[e.Bb=-2]="Bb",e[e.F=-1]="F",e[e.C=0]="C",e[e.G=1]="G",e[e.D=2]="D",e[e.A=3]="A",e[e.E=4]="E",e[e.B=5]="B",e[e.FSharp=6]="FSharp",e[e.CSharp=7]="CSharp"}(M||(M={})),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"}(I||(I={}));class le{constructor(){this.startBar=0,this.text=""}finish(e=!1){this.chunks=[],this.parse(this.text,0,this.chunks,e)}parse(e,t,i,s){if(!e)return;let a=I.Begin,r=I.Begin,n=!1,o=0;for(;t<e.length;){let i=e.charCodeAt(t);switch(a){case I.IgnoreSpaces:switch(i){case le.CharCodeLF:case le.CharCodeCR:case le.CharCodeTab:break;case le.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case I.Begin:if(i!==le.CharCodeBrackedOpen){o=t,a=I.Text;continue}a=I.Comment;break;case I.Comment:if(i===le.CharCodeBrackedClose)a=I.Begin;break;case I.Text:switch(i){case le.CharCodeDash:a=I.Dash;break;case le.CharCodeCR:case le.CharCodeLF:case le.CharCodeSpace:let i=e.substr(o,t-o);this.addChunk(i,s),a=I.IgnoreSpaces,r=I.Begin}break;case I.Dash:if(i!==le.CharCodeDash){let i=e.substr(o,t-o);this.addChunk(i,s),n=!0,a=I.IgnoreSpaces,r=I.Begin;continue}}t+=1}a===I.Text&&t!==o&&this.addChunk(e.substr(o,t-o),s)}addChunk(e,t){e=this.prepareChunk(e),(!t||e.length>0&&"-"!==e)&&this.chunks.push(e)}prepareChunk(e){let t=e.split("+").join(" "),i=t.length;for(;i>0&&"_"===t.charAt(i-1);)i--;return i!==t.length?t.substr(0,i):t}}le.CharCodeLF=10,le.CharCodeTab=9,le.CharCodeCR=13,le.CharCodeSpace=32,le.CharCodeBrackedClose=93,le.CharCodeBrackedOpen=91,le.CharCodeDash=45,function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(D||(D={})),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"}(A||(A={}));class ce{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=M.C,this.keySignatureType=D.Major,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.tripletFeel=A.NoTripletFeel,this.section=null,this.tempoAutomation=null,this.fermata=null,this.start=0,this.isAnacrusis=!1,this.displayScale=1,this.displayWidth=-1}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}calculateDuration(e=!0){if(this.isAnacrusis&&e){let e=0;for(let t of this.score.tracks)for(let i of t.staves){let t=this.index<i.bars.length?i.bars[this.index].calculateDuration():0;t>e&&(e=t)}return e}return this.timeSignatureNumerator*z.valueToTicks(this.timeSignatureDenominator)}addFermata(e,t){let i=this.fermata;null===i&&(i=new Map,this.fermata=i),i.set(e,t)}getFermata(e){const t=this.fermata;return null===t?null:t.has(e.playbackStart)?t.get(e.playbackStart):null}}ce.MaxAlternateEndings=8;class de{constructor(){this.hideDynamics=!1}}class ue{constructor(){this.masterBars=[],this.opening=null,this.closings=[],this.isClosed=!1}get openings(){const e=this.opening;return e?[e]:[]}get isOpened(){return!0===this.opening?.isRepeatStart}addMasterBar(e){null===this.opening&&(this.opening=e),this.masterBars.push(e),e.repeatGroup=this,e.isRepeatEnd&&(this.closings.push(e),this.isClosed=!0)}}class pe{constructor(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0,this.album="",this.artist="",this.copyright="",this.instructions="",this.music="",this.notices="",this.subTitle="",this.title="",this.words="",this.tab="",this.tempo=120,this.tempoLabel="",this.masterBars=[],this.tracks=[],this.defaultSystemsLayout=3,this.systemsLayout=[],this.stylesheet=new de}rebuildRepeatGroups(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0;for(const e of this.masterBars)this.addMasterBarToRepeatGroups(e)}addMasterBar(e){e.score=this,e.index=this.masterBars.length,0!==this.masterBars.length&&(e.previousMasterBar=this.masterBars[this.masterBars.length-1],e.previousMasterBar.nextMasterBar=e,e.start=e.previousMasterBar.start+(e.previousMasterBar.isAnacrusis?0:e.previousMasterBar.calculateDuration())),this.addMasterBarToRepeatGroups(e),this.masterBars.push(e)}addMasterBarToRepeatGroups(e){e.isRepeatStart?(this._currentRepeatGroup?.isClosed&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--),this._currentRepeatGroup=new ue,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new ue,this._openedRepeatGroups.push(this._currentRepeatGroup)),this._currentRepeatGroup.addMasterBar(e),e.isRepeatEnd&&this._properlyOpenedRepeatGroups>1&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--,this._currentRepeatGroup=this._openedRepeatGroups.length>0?this._openedRepeatGroups[this._openedRepeatGroups.length-1]:null)}addTrack(e){e.score=this,e.index=this.tracks.length,this.tracks.push(e)}finish(e){const t=new Map;for(let i=0,s=this.tracks.length;i<s;i++)this.tracks[i].finish(e,t)}}class ge{constructor(){this.marker="",this.text=""}}class fe extends G{constructor(t){super(e.AlphaTabErrorType.Format,t),Object.setPrototypeOf(this,fe.prototype)}}class me{constructor(e,t,i,s=255){this.raw=0,this.raw=(255&s)<<24|(255&e)<<16|(255&t)<<8|255&i,this.updateRgba()}updateRgba(){255===this.a?this.rgba="#"+Q.toHexString(this.r,2)+Q.toHexString(this.g,2)+Q.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 me(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){switch(typeof e){case"number":{const t=new me(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 me(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16));if(5===t.length)return new me(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16),17*parseInt(t[4],16));if(7===t.length)return new me(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16));if(9===t.length)return new me(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16),parseInt(t.substring(7,9),16))}else if(t.startsWith("rgba")||t.startsWith("rgb")){const e=t.indexOf("("),i=t.lastIndexOf(")");if(-1===e||-1===i)throw new fe("No values specified for rgb/rgba function");const s=t.substring(e+1,i).split(",");if(3===s.length)return new me(parseInt(s[0]),parseInt(s[1]),parseInt(s[2]));if(4===s.length)return new me(parseInt(s[0]),parseInt(s[1]),parseInt(s[2]),255*parseFloat(s[3]))}return null}}throw new fe("Unsupported format for color")}static toJson(e){return e.raw}}me.BlackRgb="#000000";class ye{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 be{static getTextForTuning(e,t){let i=be.getTextPartsForTuning(e);return t?i.join(""):i[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 be._defaultTunings.has(e)?be._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return be._sevenStrings;case 6:return be._sixStrings;case 5:return be._fiveStrings;case 4:return be._fourStrings}return[]}static initialize(){be._defaultTunings.set(7,new be("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),be._sevenStrings.push(be._defaultTunings.get(7)),be._defaultTunings.set(6,new be("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),be._sixStrings.push(be._defaultTunings.get(6)),be._sixStrings.push(new be("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),be._sixStrings.push(new be("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),be._sixStrings.push(new be("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),be._sixStrings.push(new be("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),be._sixStrings.push(new be("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),be._sixStrings.push(new be("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),be._sixStrings.push(new be("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),be._sixStrings.push(new be("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),be._sixStrings.push(new be("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),be._sixStrings.push(new be("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),be._sixStrings.push(new be("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),be._sixStrings.push(new be("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),be._sixStrings.push(new be("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),be._sixStrings.push(new be("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),be._sixStrings.push(new be("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),be._sixStrings.push(new be("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),be._sixStrings.push(new be("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),be._sixStrings.push(new be("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),be._sixStrings.push(new be("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),be._sixStrings.push(new be("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),be._sixStrings.push(new be("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),be._sixStrings.push(new be("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),be._sixStrings.push(new be("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),be._sixStrings.push(new be("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),be._sixStrings.push(new be("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),be._sixStrings.push(new be("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),be._sixStrings.push(new be("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),be._sixStrings.push(new be("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),be._sixStrings.push(new be("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),be._sixStrings.push(new be("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),be._defaultTunings.set(5,new be("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),be._fiveStrings.push(be._defaultTunings.get(5)),be._fiveStrings.push(new be("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),be._fiveStrings.push(new be("Banjo Open D Tuning",[62,57,54,50,69],!1)),be._fiveStrings.push(new be("Banjo Open G Tuning",[62,59,55,50,67],!1)),be._fiveStrings.push(new be("Banjo G Minor Tuning",[62,58,55,50,67],!1)),be._fiveStrings.push(new be("Banjo G Modal Tuning",[62,57,55,50,67],!1)),be._defaultTunings.set(4,new be("Bass Standard Tuning",[43,38,33,28],!0)),be._fourStrings.push(be._defaultTunings.get(4)),be._fourStrings.push(new be("Bass Tune down ½ step",[42,37,32,27],!1)),be._fourStrings.push(new be("Bass Tune down 1 step",[41,36,31,26],!1)),be._fourStrings.push(new be("Bass Tune down 2 step",[39,34,29,24],!1)),be._fourStrings.push(new be("Bass Dropped D Tuning",[43,38,33,26],!1)),be._fourStrings.push(new be("Ukulele C Tuning",[45,40,36,43],!1)),be._fourStrings.push(new be("Ukulele G Tuning",[52,47,43,38],!1)),be._fourStrings.push(new be("Mandolin Standard Tuning",[64,57,50,43],!1)),be._fourStrings.push(new be("Mandolin or Violin Tuning",[76,69,62,55],!1)),be._fourStrings.push(new be("Viola Tuning",[69,62,55,48],!1)),be._fourStrings.push(new be("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){let t=be.getPresetsFor(e.length);for(let i=0,s=t.length;i<s;i++){let s=t[i],a=!0;for(let t=0,i=e.length;t<i;t++)if(e[t]!==s.tunings[t]){a=!1;break}if(a)return s}return null}constructor(e="",t=null,i=!1){this.isStandard=i,this.name=e,this.tunings=t??[]}finish(){const e=be.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}be._sevenStrings=[],be._sixStrings=[],be._fiveStrings=[],be._fourStrings=[],be._defaultTunings=new Map,be.defaultAccidentals=["","#","","#","","","#","","#","","#",""],be.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],be.initialize();class Se{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new be("",[],!1),this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=5}get tuning(){return this.stringTuning.tunings}get tuningName(){return this.stringTuning.name}get isStringed(){return this.stringTuning.tunings.length>0}finish(e,t=null){this.stringTuning.finish();for(let i=0,s=this.bars.length;i<s;i++)this.bars[i].finish(e,t)}addChord(e,t){t.staff=this;let i=this.chords;null===i&&(i=new Map,this.chords=i),i.set(e,t)}hasChord(e){return this.chords?.has(e)??!1}getChord(e){return this.chords?.get(e)??null}addBar(e){let t=this.bars;e.staff=this,e.index=t.length,t.length>0&&(e.previousBar=t[t.length-1],e.previousBar.nextBar=e),t.push(e)}}class we{constructor(){this.index=0,this.staves=[],this.playbackInfo=new ye,this.color=new me(200,0,0,255),this.name="",this.shortName="",this.defaultSystemsLayout=3,this.systemsLayout=[],this.percussionArticulations=[]}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new Se)}addStaff(e){e.index=this.staves.length,e.track=this,this.staves.push(e)}finish(e,t=null){this.shortName||(this.shortName=this.name,this.shortName.length>we.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,we.ShortNameMaxLength)));for(let i=0,s=this.staves.length;i<s;i++)this.staves[i].finish(e,t)}applyLyrics(e){for(let t of e)t.finish();let t=this.staves[0];for(let i=0;i<e.length;i++){let s=e[i];if(s.startBar>=0&&s.startBar<t.bars.length){let a=t.bars[s.startBar].voices[0].beats[0];for(let t=0;t<s.chunks.length&&a;t++){for(;a&&(a.isEmpty||a.isRest);)a=a.nextBeat;a&&(a.lyrics||(a.lyrics=new Array(e.length),a.lyrics.fill("")),a.lyrics[i]=s.chunks[t],a=a.nextBeat)}}}}}we.ShortNameMaxLength=10;let _e=class e{constructor(){this.id=e._globalBarId++,this.index=0,this.beats=[],this.isEmpty=!0}insertBeat(e,t){t.nextBeat=e.nextBeat,t.nextBeat&&(t.nextBeat.previousBeat=t),t.previousBeat=e,t.voice=this,e.nextBeat=t,this.beats.splice(e.index+1,0,t)}addBeat(e){e.voice=this,e.index=this.beats.length,this.beats.push(e),e.isEmpty||(this.isEmpty=!1)}chain(e,t=null){if(this.bar){if(e.index<this.beats.length-1)e.nextBeat=this.beats[e.index+1],e.nextBeat.previousBeat=e;else if(e.isLastOfVoice&&e.voice.bar.nextBar){let t=this.bar.nextBar.voices[this.index];t.beats.length>0?(e.nextBeat=t.beats[0],e.nextBeat.previousBeat=e):e.nextBeat.previousBeat=e}e.chain(t)}}addGraceBeat(e){if(0===this.beats.length)return void this.addBeat(e);let t=this.beats[this.beats.length-1];this.beats.splice(this.beats.length-1,1),this.addBeat(e),this.addBeat(t),this.isEmpty=!1}getBeatAtPlaybackStart(e){return this._beatLookup.has(e)?this._beatLookup.get(e):null}finish(e,t=null){this._beatLookup=new Map;let i=null;for(let e=0;e<this.beats.length;e++){let s=this.beats[e];s.index=e,this.chain(s,t),s.graceType===f.None?(s.graceGroup=i,i&&(i.isComplete=!0),i=null):(i||(i=new ne),i.addBeat(s))}let s=0,a=0;for(let i=0;i<this.beats.length;i++){let r=this.beats[i];if(r.index=i,r.finish(e,t),r.graceType===f.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==f.BendGrace){let i=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case f.BeforeBeat:e.previousBeat?(e.previousBeat.playbackDuration-=i,a=e.previousBeat.voice==this?e.previousBeat.playbackStart+e.previousBeat.playbackDuration:-i):a=-i;for(const e of r.graceGroup.beats)this._beatLookup.delete(e.playbackStart),e.playbackStart=a,this._beatLookup.set(e.playbackStart,r),a+=e.playbackDuration;break;case f.OnBeat:r.playbackDuration-=i,a=t.voice===this?t.playbackStart+t.playbackDuration:-i}}}r.displayStart=s,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=s,r.playbackStart=a;r.finishTuplet(),r.graceGroup&&r.graceGroup.finish(),s+=r.displayDuration,a+=r.playbackDuration}}calculateDuration(){if(this.isEmpty||0===this.beats.length)return 0;let e=this.beats[this.beats.length-1],t=this.beats[0];return e.playbackStart+e.playbackDuration-t.playbackStart}};_e._globalBarId=0;class Be{static float64ToBytes(e){return Be._dataView.setFloat64(0,e,!0),this._conversionByteArray}static bytesToFloat64(e){throw Be._conversionByteArray.set(e,0),Be._dataView.getFloat64(0,!0)}static uint16ToInt16(e){return Be._dataView.setUint16(0,e,!0),Be._dataView.getInt16(0,!0)}static int16ToUint32(e){return Be._dataView.setInt16(0,e,!0),Be._dataView.getUint32(0,!0)}static int32ToUint16(e){return Be._dataView.setInt32(0,e,!0),Be._dataView.getUint16(0,!0)}static int32ToInt16(e){return Be._dataView.setInt32(0,e,!0),Be._dataView.getInt16(0,!0)}static int32ToUint32(e){return Be._dataView.setInt32(0,e,!0),Be._dataView.getUint32(0,!0)}static uint8ToInt8(e){return Be._dataView.setUint8(0,e),Be._dataView.getInt8(0)}}Be._conversionBuffer=new ArrayBuffer(8),Be._conversionByteArray=new Uint8Array(Be._conversionBuffer),Be._dataView=new DataView(Be._conversionBuffer);class Te{static readInt32BE(e){return e.readByte()<<24|e.readByte()<<16|e.readByte()<<8|e.readByte()}static readInt32LE(e){let t=e.readByte(),i=e.readByte(),s=e.readByte();return e.readByte()<<24|s<<16|i<<8|t}static readUInt32LE(e){let t=e.readByte(),i=e.readByte(),s=e.readByte();return e.readByte()<<24|s<<16|i<<8|t}static decodeUInt32LE(e,t){let i=e[t],s=e[t+1],a=e[t+2];return e[t+3]<<24|a<<16|s<<8|i}static readUInt16LE(e){let t=e.readByte(),i=e.readByte();return Be.int32ToUint16(i<<8|t)}static readInt16LE(e){let t=e.readByte(),i=e.readByte();return Be.int32ToInt16(i<<8|t)}static readUInt32BE(e){let t=e.readByte(),i=e.readByte(),s=e.readByte(),a=e.readByte();return Be.int32ToUint32(t<<24|i<<16|s<<8|a)}static readUInt16BE(e){let t=e.readByte(),i=e.readByte();return Be.int32ToInt16(t<<8|i)}static readInt16BE(e){let t=e.readByte(),i=e.readByte();return Be.int32ToInt16(t<<8|i)}static readByteArray(e,t){let i=new Uint8Array(t);return e.read(i,0,t),i}static read8BitChars(e,t){let i=new Uint8Array(t);return e.read(i,0,i.length),Te.toString(i,"utf-8")}static read8BitString(e){let t="",i=e.readByte();for(;0!==i;)t+=String.fromCharCode(i),i=e.readByte();return t}static read8BitStringLength(e,t){let i="",s=-1;for(let a=0;a<t;a++){let t=e.readByte();0===t&&-1===s&&(s=a),i+=String.fromCharCode(t)}let a=i;return s>=0?a.substr(0,s):a}static readSInt8(e){let t=e.readByte();return-256*((255&t)>>7)+(255&t)}static readInt24(e,t){let i=e[t]|e[t+1]<<8|e[t+2]<<16;return 8388608&~i||(i|=255<<24),i}static readInt16(e,t){return Be.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){let i=Te.detectEncoding(e);return i&&(t=i),t||(t="utf-8"),new TextDecoder(t).decode(e.buffer)}static detectEncoding(e){return e.length>2&&254===e[0]&&255===e[1]?"utf-16be":e.length>2&&255===e[0]&&254===e[1]?"utf-16le":e.length>4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3]?"utf-32be":e.length>4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3]?"utf-32le":null}static stringToBytes(e){return(new TextEncoder).encode(e)}static writeInt32BE(e,t){e.writeByte(t>>24&255),e.writeByte(t>>16&255),e.writeByte(t>>8&255),e.writeByte(255&t)}static writeInt32LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255),e.writeByte(t>>16&255),e.writeByte(t>>24&255)}static writeUInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16BE(e,t){e.writeByte(t>>8&255),e.writeByte(255&t)}}class ke{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return ke.withCapacity(0)}static withCapacity(e){let t=new ke;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){let t=new ke;return t._buffer=e,t.length=e.length,t}static fromString(e){let t=Te.stringToBytes(e);return ke.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,i){let s=this.length-this.position;return s>i&&(s=i),s<=0?0:(e.set(this._buffer.subarray(this.position,this.position+s),t),this.position+=s,s)}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,i){let s=this.position+i;this.ensureCapacity(s);let a=Math.min(i,e.length-t);this._buffer.set(e.subarray(t,t+a),this.position),s>this.length&&(this.length=s),this.position=s}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 i=new Uint8Array(t);this.length>0&&i.set(this._buffer.subarray(0,0+this.length),0),this._buffer=i}}readAll(){return this.toArray()}toArray(){let e=new Uint8Array(this.length);return e.set(this._buffer.subarray(0,0+this.length),0),e}copyTo(e){e.write(this._buffer,0,this.length)}}var ve,xe,Ne,Pe,Ee,Ce,Fe,Le,Me,Ie,De,Ae,Re,Oe,Ge,Ve,He,We,ze,Ue,Xe,Ye,qe,Je,je,Qe,$e,Ke,Ze,et;!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"}(ve||(ve={}));class tt extends G{constructor(t,i,s,a,r,n,o,h=null){super(e.AlphaTabErrorType.AlphaTex,t),this.position=i,this.line=s,this.col=a,this.nonTerm=r??"",this.expected=n??ve.No,this.symbol=o??ve.No,this.symbolData=h,Object.setPrototypeOf(this,tt.prototype)}static symbolError(e,t,i,s,a,r,n=null){let o=`MalFormed AlphaTex: @${e} (line ${t}, col ${i}): Error on block ${s}`;return a!==r?(o+=`, expected a ${ve[a]} found a ${ve[r]}`,null!==n&&(o+=`: '${n}'`)):o+=`, invalid value: '${n}'`,new tt(o,e,t,i,s,a,r,n)}static errorMessage(e,t,i,s){return new tt(e=`MalFormed AlphaTex: @${t} (line ${i}, col ${s}): ${e}`,t,i,s,null,null,null,null)}}class it extends O{constructor(){super(),this._trackChannel=0,this._input="",this._ch=it.Eof,this._curChPos=0,this._line=1,this._col=0,this._lastValidSpot=[0,1,0],this._sy=ve.No,this._syData="",this._allowNegatives=!1,this._allowFloat=!1,this._allowTuning=!1,this._currentDuration=p.QuadrupleWhole,this._currentDynamics=g.PPP,this._currentTuplet=0,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=ke.empty(),this._input=e,this.settings=t}readScore(){try{if(this.data.length>0&&(this._input=Te.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this.createDefaultScore(),this._curChPos=0,this._line=1,this._col=0,this.saveValidSpot(),this._currentDuration=p.Quarter,this._currentDynamics=g.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===ve.LowerThan)throw new V("Unknown start sign '<' (meant to import as XML?)");if(this._sy===ve.Eof)throw new V("Unexpected end of file");const e=this.metaData(),t=this.bars();if(!e&&!t)throw new V("No alphaTex data found");this.consolidate(),this._score.finish(this.settings),this._score.rebuildRepeatGroups();for(const[e,t]of this._lyrics)this._score.tracks[e].applyLyrics(t);return this._score}catch(e){throw e instanceof tt?new V(e.message,e):e}}consolidate(){for(let e of this._score.tracks)for(let t of e.staves)for(;t.bars.length<this._score.masterBars.length;){let e=this.newBar(t),i=new oe;i.isEmpty=!0,e.voices[0].addBeat(i)}}error(e,t,i=!0){let s,a=!1;i?(s=this._sy,s!==ve.String&&s!==ve.Number&&s!==ve.MetaCommand||(a=!0)):s=t;let r=tt.symbolError(this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2],e,t,s,a?this._syData:null);throw this.logErrors&&J.error(this.name,r.message),r}errorMessage(e){let t=tt.errorMessage(e,this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2]);throw this.logErrors&&J.error(this.name,t.message),t}createDefaultScore(){this._score=new pe,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new we,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=be.getDefaultTuningFor(6).tunings,this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=g.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":default:return n.G2;case"f4":case"bass":return n.F4;case"c3":case"tenor":return n.C3;case"c4":case"alto":return n.C4;case"n":case"neutral":return n.Neutral}}parseClefFromInt(e){switch(e){case 43:default:return n.G2;case 65:return n.F4;case 48:return n.C3;case 60:return n.C4}}parseTripletFeelFromString(e){switch(e.toLowerCase()){case"no":case"none":default:return A.NoTripletFeel;case"t16":case"triplet-16th":return A.Triplet16th;case"t8":case"triplet-8th":return A.Triplet8th;case"d16":case"dotted-16th":return A.Dotted16th;case"d8":case"dotted-8th":return A.Dotted8th;case"s16":case"scottish-16th":return A.Scottish16th;case"s8":case"scottish-8th":return A.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return A.NoTripletFeel;case 1:return A.Triplet16th;case 2:return A.Triplet8th;case 3:return A.Dotted16th;case 4:return A.Dotted8th;case 5:return A.Scottish16th;case 6:return A.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":return M.Cb;case"gb":case"gbmajor":case"d#minor":return M.Gb;case"db":case"dbmajor":case"bbminor":return M.Db;case"ab":case"abmajor":case"fminor":return M.Ab;case"eb":case"ebmajor":case"cminor":return M.Eb;case"bb":case"bbmajor":case"gminor":return M.Bb;case"f":case"fmajor":case"dminor":return M.F;case"c":case"cmajor":case"aminor":default:return M.C;case"g":case"gmajor":case"eminor":return M.G;case"d":case"dmajor":case"bminor":return M.D;case"a":case"amajor":case"f#minor":return M.A;case"e":case"emajor":case"c#minor":return M.E;case"b":case"bmajor":case"g#minor":return M.B;case"f#":case"f#major":case"ebminor":return M.FSharp;case"c#":case"c#major":return M.CSharp}}nextChar(){return this._curChPos<this._input.length?(this._ch=this._input.charCodeAt(this._curChPos++),10===this._ch?(this._line++,this._col=0):this._col++):this._ch=it.Eof,this._ch}saveValidSpot(){this._lastValidSpot=[this._curChPos,this._line,this._col]}newSy(){for(this.saveValidSpot(),this._sy=ve.No;this._sy===ve.No;)if(this._ch===it.Eof)this._sy=ve.Eof;else if(it.isWhiteSpace(this._ch))this._ch=this.nextChar(),this.saveValidSpot();else if(47===this._ch){if(this._ch=this.nextChar(),47===this._ch)for(;13!==this._ch&&10!==this._ch&&this._ch!==it.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;this._ch!==it.Eof;)if(42===this._ch){if(this._ch=this.nextChar(),47===this._ch){this._ch=this.nextChar();break}}else this._ch=this.nextChar();else this.error("comment",ve.String,!1);this.saveValidSpot()}else if(34===this._ch||39===this._ch){let e=this._ch;this._ch=this.nextChar();let t="";for(this._sy=ve.String;this._ch!==e&&this._ch!==it.Eof;)t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._ch===it.Eof&&this.errorMessage("String opened but never closed"),this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)this._allowNegatives?(this._sy=ve.Number,this._syData=this.readNumber()):(this._sy=ve.String,this._syData=this.readName());else if(46===this._ch)this._sy=ve.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=ve.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=ve.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=ve.MetaCommand,this._syData=this.readName();else if(41===this._ch)this._sy=ve.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=ve.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=ve.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=ve.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=ve.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=ve.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this._sy=ve.Number,this._syData=this.readNumber();else if(it.isNameLetter(this._ch)){let e=this.readName(),t=this._allowTuning?Q.parseTuning(e):null;t?(this._sy=ve.Tuning,this._syData=t):(this._sy=ve.String,this._syData=e)}else this.error("symbol",ve.String,!1);return this._sy}static isNameLetter(e){return!it.isTerminal(e)&&(33<=e&&e<=47||58<=e&&e<=126||128<=e)}static isTerminal(e){return 46===e||123===e||125===e||91===e||93===e||40===e||41===e||124===e||39===e||34===e||92===e}static isWhiteSpace(e){return 9===e||10===e||11===e||13===e||32===e}isDigit(e){return e>=48&&e<=57||this._allowNegatives&&45===e||this._allowFloat&&46===e}readName(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(it.isNameLetter(this._ch)||this.isDigit(this._ch));return e}readNumber(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(this.isDigit(this._ch));return this._allowFloat?parseFloat(e):parseInt(e)}metaData(){let e=!1,t=!0;for(;this._sy===ve.MetaCommand&&t;){let i=this._syData.toLowerCase();switch(i){case"title":case"subtitle":case"artist":case"album":case"words":case"music":case"copyright":this._sy=this.newSy(),this._sy!==ve.String&&this.error(i,ve.String,!0);let s=this._syData;switch(i){case"title":this._score.title=s;break;case"subtitle":this._score.subTitle=s;break;case"artist":this._score.artist=s;break;case"album":this._score.album=s;break;case"words":this._score.words=s;break;case"music":this._score.music=s;break;case"copyright":this._score.copyright=s}this._sy=this.newSy(),e=!0;break;case"tempo":this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy===ve.Number?this._score.tempo=this._syData:this.error("tempo",ve.Number,!0),this._sy=this.newSy(),e=!0;break;default:this.handleStaffMeta()?e=!0:e?this.error("metaDataTags",ve.String,!1):t=!1}}return e?(this._sy!==ve.Dot&&this.error("song",ve.Dot,!0),this._sy=this.newSy()):this._sy===ve.Dot&&(this._sy=this.newSy()),e}handleStaffMeta(){switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===ve.Number?this._currentStaff.capo=this._syData:this.error("capo",ve.Number,!0),this._sy=this.newSy(),!0;case"tuning":this._sy=this.newSy();let e=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case ve.String:let e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?(this._currentStaff.stringTuning.tunings=[],this._currentStaff.displayTranspositionPitch=0):this.error("tuning",ve.Tuning,!0),this._sy=this.newSy();break;case ve.Tuning:let t=[];do{let e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===ve.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",ve.Tuning,!0)}return e!==this._currentStaff.tuning.length&&(this._currentStaff.chords?.size??0)>0&&this.errorMessage("Tuning must be defined before any chord"),!0;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===ve.Number){let e=this._syData;e>=0&&e<=127?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",ve.Number,!1)}else if(this._sy===ve.String){let e=this._syData.toLowerCase();this._currentTrack.playbackInfo.program=R.getValue(e)}else this.error("instrument",ve.Number,!0);return this._sy=this.newSy(),!0;case"lyrics":this._sy=this.newSy();let t=new le;return t.startBar=0,t.text="",this._sy===ve.Number&&(t.startBar=this._syData,this._sy=this.newSy()),this._sy===ve.String?(t.text=this._syData,this._sy=this.newSy()):this.error("lyrics",ve.String,!0),this._lyrics.get(this._currentTrack.index).push(t),!0;case"chord":this._sy=this.newSy();let i=new he;this.chordProperties(i),this._sy===ve.String?(i.name=this._syData,this._sy=this.newSy()):this.error("chord-name",ve.Number,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===ve.Number?i.strings.push(this._syData):this._sy===ve.String&&"x"===this._syData.toLowerCase()&&i.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,i.name),i),!0;default:return!1}}chordProperties(e){if(this._sy===ve.LBrace){for(this._sy=this.newSy();this._sy===ve.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===ve.Number)e.firstFret=this._syData;else this.error("chord-firstfret",ve.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case ve.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case ve.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",ve.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case ve.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case ve.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",ve.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case ve.String:e.showName="false"!==this._syData.toLowerCase();break;case ve.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",ve.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===ve.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",ve.String,!1)}this._sy!==ve.RBrace&&this.error("chord-properties",ve.RBrace,!0),this._sy=this.newSy()}}bars(){let e=this.bar();for(;this._sy!==ve.Eof;)if(this._sy===ve.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==ve.MetaCommand)break;this.bar()}return e}trackStaffMeta(){return this._sy===ve.MetaCommand&&("track"===this._syData.toLowerCase()&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===ve.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===ve.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy())),this._sy===ve.MetaCommand&&"staff"===this._syData.toLowerCase()&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0&&(this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this._currentStaff=this._currentTrack.staves[this._currentTrack.staves.length-1],this._currentDynamics=g.F),this.staffProperties()),!0)}staffProperties(){if(this._sy!==ve.LBrace)return;this._sy=this.newSy();let e=!1,t=!1;for(;this._sy===ve.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",ve.String,!1)}(e||t)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t),this._sy!==ve.RBrace&&this.error("staff-properties",ve.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 ce;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 i=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=be.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 s=!1,a=t.voices[0];for(;this._sy!==ve.Pipe&&this._sy!==ve.Eof&&this.beat(a);)s=!0;if(0===a.beats.length){let e=new oe;e.isEmpty=!0,a.addBeat(e)}return e||i||s}newBar(e){let t=new W;e.addBar(t),t.index>0&&(t.clef=t.previousBar.clef);let i=new _e;return t.addVoice(i),t}beat(e){this.beatDuration();let t=new oe;if(e.addBeat(t),this._sy===ve.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==ve.RParensis&&this._sy!==ve.Eof&&this.note(t););this._sy!==ve.RParensis&&this.error("note-list",ve.RParensis,!0),this._sy=this.newSy()}else if(this._sy===ve.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===ve.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==ve.Number&&this.error("duration",ve.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||it.applyTuplet(t,this._currentTuplet);let i=1;this._sy===ve.Multiply&&(this._sy=this.newSy(),this._sy!==ve.Number?this.error("multiplier",ve.Number,!0):i=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let s=0;s<i-1;s++)e.addBeat(re.clone(t));return!0}beatDuration(){if(this._sy===ve.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==ve.Number&&this.error("duration",ve.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===ve.LBrace)){for(this._sy=this.newSy();this._sy===ve.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==ve.Number&&this.error("duration-tuplet",ve.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",ve.String,!1)}this._sy!==ve.RBrace&&this.error("beat-duration",ve.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===ve.LBrace){for(this._sy=this.newSy();this._sy===ve.String;)this.applyBeatEffect(e)||this.error("beat-effects",ve.String,!1);this._sy!==ve.RBrace&&this.error("beat-effects",ve.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){let t=this._syData.toLowerCase();if("f"===t)e.fadeIn=!0;else if("v"===t)e.vibrato=_.Slight;else if("s"===t)e.slap=!0;else if("p"===t)e.pop=!0;else if("tt"===t)e.tap=!0;else if("dd"===t)e.dots=2;else if("d"===t)e.dots=1;else if("su"===t)e.pickStroke=N.Up;else if("sd"===t)e.pickStroke=N.Down;else if("tu"===t){if(this._sy=this.newSy(),this._sy!==ve.Number)return this.error("tuplet",ve.Number,!0),!1;it.applyTuplet(e,this._syData)}else if("tb"===t||"tbe"===t){let i="tbe"===t;for(this._sy=this.newSy(),this._sy!==ve.LParensis&&this.error("tremolobar-effect",ve.LParensis,!0),this._allowNegatives=!0,this._sy=this.newSy();this._sy!==ve.RParensis&&this._sy!==ve.Eof;){let t=0,s=0;i?(this._sy!==ve.Number&&this.error("tremolobar-effect",ve.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==ve.Number&&this.error("tremolobar-effect",ve.Number,!0),s=this._syData):(this._sy!==ve.Number&&this.error("tremolobar-effect",ve.Number,!0),t=0,s=this._syData),e.addWhammyBarPoint(new U(t,s)),this._sy=this.newSy()}if(null!=e.whammyBarPoints){for(;e.whammyBarPoints.length>60;)e.removeWhammyBarPoint(e.whammyBarPoints.length-1);if(i)e.whammyBarPoints.sort(((e,t)=>e.offset-t.offset));else{let t=e.whammyBarPoints.length,i=60/t|0,s=0;for(;s<t;)e.whammyBarPoints[s].offset=Math.min(60,s*i),s++}}this._allowNegatives=!1,this._sy!==ve.RParensis&&this.error("tremolobar-effect",ve.RParensis,!0)}else{if("bu"===t||"bd"===t||"au"===t||"ad"===t){switch(t){case"bu":e.brushType=d.BrushUp;break;case"bd":e.brushType=d.BrushDown;break;case"au":e.brushType=d.ArpeggioUp;break;case"ad":e.brushType=d.ArpeggioDown}return this._sy=this.newSy(),this._sy===ve.Number?(e.brushDuration=this._syData,this._sy=this.newSy(),!0):(e.updateDurations(),"bu"===t||"bd"===t?e.brushDuration=e.playbackDuration/4/e.notes.length:"au"!==t&&"ad"!==t||(e.brushDuration=e.playbackDuration/e.notes.length),!0)}if("ch"===t){this._sy=this.newSy();let t=this._syData,i=this.getChordId(this._currentStaff,t);if(!this._currentStaff.hasChord(i)){let e=new he;e.showDiagram=!1,e.name=t,this._currentStaff.addChord(i,e)}e.chordId=i}else{if("gr"===t)return this._sy=this.newSy(),"ob"===this._syData.toLowerCase()?(e.graceType=f.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=f.BendGrace,this._sy=this.newSy()):e.graceType=f.BeforeBeat,!0;if("dy"===t){switch(this._sy=this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=g.PPP;break;case"pp":e.dynamics=g.PP;break;case"p":e.dynamics=g.P;break;case"mp":e.dynamics=g.MP;break;case"mf":e.dynamics=g.MF;break;case"f":e.dynamics=g.F;break;case"ff":e.dynamics=g.FF;break;case"fff":e.dynamics=g.FFF}this._currentDynamics=e.dynamics}else if("cre"===t)e.crescendo=u.Crescendo;else{if("dec"!==t){if("tp"===t){if(this._sy=this.newSy(),e.tremoloSpeed=p.Eighth,this._sy===ve.Number){switch(this._syData){case 8:default:e.tremoloSpeed=p.Eighth;break;case 16:e.tremoloSpeed=p.Sixteenth;break;case 32:e.tremoloSpeed=p.ThirtySecond}this._sy=this.newSy()}return!0}return!1}e.crescendo=u.Decrescendo}}}return this._sy=this.newSy(),!0}getChordId(e,t){return t.toLowerCase()+e.index+e.track.index}static applyTuplet(e,t){switch(t){case 3:e.tupletNumerator=3,e.tupletDenominator=2;break;case 5:e.tupletNumerator=5,e.tupletDenominator=4;break;case 6:e.tupletNumerator=6,e.tupletDenominator=4;break;case 7:e.tupletNumerator=7,e.tupletDenominator=4;break;case 9:e.tupletNumerator=9,e.tupletDenominator=8;break;case 10:e.tupletNumerator=10,e.tupletDenominator=8;break;case 11:e.tupletNumerator=11,e.tupletDenominator=8;break;case 12:e.tupletNumerator=12,e.tupletDenominator=8;break;default:e.tupletNumerator=1,e.tupletDenominator=1}}isNoteText(e){return"x"===e||"-"===e||"r"===e}note(e){let t=!1,i=!1,s=-1,a=-1,r=-1;switch(this._sy){case ve.Number:s=this._syData;break;case ve.String:t="x"===this._syData,i="-"===this._syData,i||t?s=0:this.error("note-fret",ve.Number,!0);break;case ve.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!==ve.Dot&&this.error("note",ve.Dot,!0),this._sy=this.newSy(),this._sy!==ve.Number&&this.error("note-string",ve.Number,!0),o=this._syData,(o<1||o>this._currentStaff.tuning.length)&&this.error("note-string",ve.Number,!1),this._sy=this.newSy());let h=new ee;return n?(h.string=this._currentStaff.tuning.length-(o-1),h.isDead=t,h.isTieDestination=i,i||(h.fret=s)):(h.octave=a,h.tone=r,h.isTieDestination=i),e.addNote(h),this.noteEffects(h),!0}noteEffects(e){if(this._sy===ve.LBrace){for(this._sy=this.newSy();this._sy===ve.String;){let t=this._syData.toLowerCase();if("b"===t||"be"===t){let i="be"===t;for(this._sy=this.newSy(),this._sy!==ve.LParensis&&this.error("bend-effect",ve.LParensis,!0),this._sy=this.newSy();this._sy!==ve.RParensis&&this._sy!==ve.Eof;){let t=0,s=0;i?(this._sy!==ve.Number&&this.error("bend-effect-value",ve.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==ve.Number&&this.error("bend-effect-value",ve.Number,!0),s=this._syData):(this._sy!==ve.Number&&this.error("bend-effect-value",ve.Number,!0),s=this._syData),e.addBendPoint(new U(t,s)),this._sy=this.newSy()}const s=e.bendPoints;if(null!=s){for(;s.length>60;)s.splice(s.length-1,1);if(i)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!==ve.RParensis&&this.error("bend-effect",ve.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=y.Natural,this._sy=this.newSy();else if("ah"===t)e.harmonicType=y.Artificial,this._sy=this.newSy();else if("th"===t)e.harmonicType=y.Tap,this._sy=this.newSy();else if("ph"===t)e.harmonicType=y.Pinch,this._sy=this.newSy();else if("sh"===t)e.harmonicType=y.Semi,this._sy=this.newSy();else if("tr"===t){this._sy=this.newSy(),this._sy!==ve.Number&&this.error("trill-effect",ve.Number,!0);let t=this._syData;this._sy=this.newSy();let i=p.Sixteenth;if(this._sy===ve.Number){switch(this._syData){case 16:default:i=p.Sixteenth;break;case 32:i=p.ThirtySecond;break;case 64:i=p.SixtyFourth}this._sy=this.newSy()}e.trillValue=t+e.stringTuning,e.trillSpeed=i}else if("v"===t)this._sy=this.newSy(),e.vibrato=_.Slight;else if("sl"===t)this._sy=this.newSy(),e.slideOutType=w.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=w.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=S.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=S.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=w.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=w.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=w.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=w.PickSlideUp;else if("h"===t)this._sy=this.newSy(),e.isHammerPullOrigin=!0;else if("lht"===t)this._sy=this.newSy(),e.isLeftHandTapped=!0;else if("g"===t)this._sy=this.newSy(),e.isGhost=!0;else if("ac"===t)this._sy=this.newSy(),e.accentuated=a.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=a.Heavy;else if("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=m.Thumb;this._sy===ve.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.leftHandFinger=t}else if("rf"===t){this._sy=this.newSy();let t=m.Thumb;this._sy===ve.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else this.applyBeatEffect(e.beat)||this.error(t,ve.String,!1)}this._sy!==ve.RBrace&&this.error("note-effect",ve.RBrace,!1),this._sy=this.newSy()}}toFinger(e){switch(e){case 1:return m.Thumb;case 2:return m.IndexFinger;case 3:return m.MiddleFinger;case 4:return m.AnnularFinger;case 5:return m.LittleFinger}return m.Thumb}parseDuration(e){switch(e){case-4:return p.QuadrupleWhole;case-2:return p.DoubleWhole;case 1:return p.Whole;case 2:return p.Half;case 4:return p.Quarter;case 8:return p.Eighth;case 16:return p.Sixteenth;case 32:return p.ThirtySecond;case 64:return p.SixtyFourth;case 128:return p.OneHundredTwentyEighth;case 256:return p.TwoHundredFiftySixth;default:return p.Quarter}}barMeta(e){let t=!1,i=e.masterBar;for(;this._sy===ve.MetaCommand;){t=!0;let s=this._syData.toLowerCase();if("ts"===s)this._sy=this.newSy(),this._sy!==ve.Number&&this.error("timesignature-numerator",ve.Number,!0),i.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==ve.Number&&this.error("timesignature-denominator",ve.Number,!0),i.timeSignatureDenominator=this._syData,this._sy=this.newSy();else if("ro"===s)i.isRepeatStart=!0,this._sy=this.newSy();else if("rc"===s)this._sy=this.newSy(),this._sy!==ve.Number&&this.error("repeatclose",ve.Number,!0),this._syData>2048&&this.error("repeatclose",ve.Number,!1),i.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===s)if(this._sy=this.newSy(),this._sy===ve.LParensis){for(this._sy=this.newSy(),this._sy!==ve.Number&&this.error("alternateending",ve.Number,!0),this.applyAlternateEnding(i);this._sy===ve.Number;)this.applyAlternateEnding(i);this._sy!==ve.RParensis&&this.error("alternateending-list",ve.RParensis,!0),this._sy=this.newSy()}else this._sy!==ve.Number&&this.error("alternateending",ve.Number,!0),this.applyAlternateEnding(i);else if("ks"===s)this._sy=this.newSy(),this._sy!==ve.String&&this.error("keysignature",ve.String,!0),i.keySignature=this.parseKeySignature(this._syData),this._sy=this.newSy();else if("clef"===s){switch(this._sy=this.newSy(),this._sy){case ve.String:e.clef=this.parseClefFromString(this._syData);break;case ve.Number:e.clef=this.parseClefFromInt(this._syData);break;case ve.Tuning:let t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",ve.String,!0)}this._sy=this.newSy()}else if("tempo"===s){this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==ve.Number&&this.error("tempo",ve.Number,!0);let e=new H;e.isLinear=!1,e.type=r.Tempo,e.value=this._syData,i.tempoAutomation=e,this._sy=this.newSy()}else if("section"===s){this._sy=this.newSy(),this._sy!==ve.String&&this.error("section",ve.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==ve.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());let s=new ge;s.marker=t,s.text=e,i.section=s}else if("tf"===s){switch(this._allowTuning=!1,this._sy=this.newSy(),this._allowTuning=!0,this._sy){case ve.String:i.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case ve.Number:i.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",ve.String,!0)}this._sy=this.newSy()}else"ac"===s?(i.isAnacrusis=!0,this._sy=this.newSy()):0===e.index&&this.handleStaffMeta()||this.error("measure-effects",ve.String,!1)}if(0===i.index&&!i.tempoAutomation){let e=new H;e.isLinear=!1,e.type=r.Tempo,e.value=this._score.tempo,i.tempoAutomation=e}return t}applyAlternateEnding(e){let t=this._syData;t<1&&this.error("alternateending",ve.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}}it.Eof=0;class st extends O{get name(){return"Guitar Pro 3-5"}constructor(){super(),this._versionNumber=0,this._globalTripletFeel=A.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._beatTextChunksByTrack=new Map}readScore(){return this.readVersion(),this._score=new pe,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=at.gpReadBool(this.data)?A.Triplet8th:A.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=at.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=Te.readInt32LE(this.data),this._versionNumber>=510&&at.gpReadBool(this.data),Te.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.data.skip(38),this.data.skip(4)),this._barCount=Te.readInt32LE(this.data),this._trackCount=Te.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0&&(this._score.masterBars[0].tempoAutomation=H.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=at.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(st.VersionString))throw new V("Unsupported format");e=e.substr(st.VersionString.length+1);let t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*parseInt(e.substr(0,t))+parseInt(e.substr(t+1)),J.debug(this.name,"Guitar Pro version "+e+" detected")}readScoreInformation(){this._score.title=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?at.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding);let e=Te.readInt32LE(this.data),t="";for(let i=0;i<e;i++)i>0&&(t+="\r\n"),t+=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding)?.toString();this._score.notices=t}readLyrics(){this._lyrics=[],this._lyricsTrack=Te.readInt32LE(this.data)-1;for(let e=0;e<5;e++){let e=new le;e.startBar=Te.readInt32LE(this.data)-1,e.text=at.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(30);for(let e=0;e<10;e++)at.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){let t=new ye;t.primaryChannel=e,t.secondaryChannel=e,t.program=Te.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 ce,i=this.data.readByte();if(1&i?t.timeSignatureNumerator=this.data.readByte():e&&(t.timeSignatureNumerator=e.timeSignatureNumerator),2&i?t.timeSignatureDenominator=this.data.readByte():e&&(t.timeSignatureDenominator=e.timeSignatureDenominator),t.isRepeatStart=!!(4&i),8&i&&(t.repeatCount=this.data.readByte()+(this._versionNumber>=500?0:1)),16&i&&this._versionNumber<500){let i=e,s=0;for(;i&&(!i.isRepeatEnd||i===e)&&!i.isRepeatStart;)s|=i.alternateEndings,i=i.previousMasterBar;let a=0,r=this.data.readByte();for(let e=0;e<8;e++){let t=1<<e;r>e&&!(s&t)&&(a|=t)}t.alternateEndings=a}if(32&i){let e=new ge;e.text=at.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",at.gpReadColor(this.data,!1),t.section=e}if(64&i?(t.keySignature=Te.readSInt8(this.data),t.keySignatureType=this.data.readByte()):e&&(t.keySignature=e.keySignature,t.keySignatureType=e.keySignatureType),this._versionNumber>=500&&3&i&&this.data.skip(4),this._versionNumber>=500&&(t.alternateEndings=this.data.readByte()),this._versionNumber>=500){switch(this.data.readByte()){case 1:t.tripletFeel=A.Triplet8th;break;case 2:t.tripletFeel=A.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=!!(128&i),this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){let e=new we;e.ensureStaveCount(1),this._score.addTrack(e);let t=e.staves[0],i=this.data.readByte();e.name=at.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),1&i&&(t.isPercussion=!0);let s=Te.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){let t=Te.readInt32LE(this.data);s>e&&a.push(t)}t.stringTuning.tunings=a;let r=Te.readInt32LE(this.data),n=Te.readInt32LE(this.data)-1,o=Te.readInt32LE(this.data)-1;if(this.data.skip(4),n>=0&&n<this._playbackInfos.length){let s=this._playbackInfos[n];s.port=r,s.isSolo=!!(16&i),s.isMute=!!(32&i),s.secondaryChannel=o,R.isGuitar(s.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=s}t.capo=Te.readInt32LE(this.data),e.color=at.gpReadColor(this.data,!1),this._versionNumber>=500&&(this.data.readByte(),this.data.readByte(),this.data.skip(43)),this._versionNumber>=510&&(this.data.skip(4),at.gpReadStringIntByte(this.data,this.settings.importer.encoding),at.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 W,i=e.staves[0];i.isPercussion&&(t.clef=n.Neutral),i.addBar(t);let s=1;this._versionNumber>=500&&(this.data.readByte(),s=2);for(let i=0;i<s;i++)this.readVoice(e,t)}readVoice(e,t){let i=Te.readInt32LE(this.data);if(0===i)return;let s=new _e;t.addVoice(s);for(let a=0;a<i;a++)this.readBeat(e,t,s)}readBeat(e,t,i){let s=new oe,a=this.data.readByte();if(1&a&&(s.dots=1),64&a){let e=this.data.readByte();s.isEmpty=!(2&e)}switch(i.addBeat(s),Te.readSInt8(this.data)){case-2:s.duration=p.Whole;break;case-1:s.duration=p.Half;break;case 0:s.duration=p.Quarter;break;case 1:s.duration=p.Eighth;break;case 2:s.duration=p.Sixteenth;break;case 3:s.duration=p.ThirtySecond;break;case 4:s.duration=p.SixtyFourth;break;default:s.duration=p.Quarter}if(32&a)switch(s.tupletNumerator=Te.readInt32LE(this.data),s.tupletNumerator){case 1:s.tupletDenominator=1;break;case 3:s.tupletDenominator=2;break;case 5:case 6:case 7:s.tupletDenominator=4;break;case 9:case 10:case 11:case 12:case 13:s.tupletDenominator=8;break;case 2:case 4:case 8:break;default:s.tupletNumerator=1,s.tupletDenominator=1}2&a&&this.readChord(s);let r=this.settings.importer.beatTextAsLyrics&&e.index!==this._lyricsTrack;if(4&a){const t=at.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const i=new le;i.text=t.trim(),i.finish(!0);const s=[];for(let e=i.chunks.length-1;e>=0;e--)s.push(i.chunks[e]);this._beatTextChunksByTrack.set(e.index,s)}else s.text=t}let n=y.None;8&a&&(n=this.readBeatEffects(s)),16&a&&this.readMixTableChange(s);let o=this.data.readByte();for(let a=6;a>=0;a--)if(o&1<<a&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,i,s,6-a);n!==y.None&&(r.harmonicType=n,r.harmonicType===y.Natural&&(r.harmonicValue=this.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){this.data.readByte(),8&this.data.readByte()&&this.data.readByte()}r&&!s.isRest&&this._beatTextChunksByTrack.has(e.index)&&this._beatTextChunksByTrack.get(e.index).length>0&&(s.lyrics=[this._beatTextChunksByTrack.get(e.index).pop()])}readChord(e){let t=new he,i=Q.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=at.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Te.readInt32LE(this.data);for(let i=0;i<7;i++){let s=Te.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}let i=this.data.readByte(),s=new Uint8Array(5);this.data.read(s,0,s.length);for(let e=0;e<i;e++)t.barreFrets.push(s[e]);this.data.skip(26)}else if(0!==this.data.readByte())if(this._versionNumber>=400){this.data.skip(16),t.name=at.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Te.readInt32LE(this.data);for(let i=0;i<7;i++){let s=Te.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}let i=this.data.readByte(),s=new Uint8Array(5);this.data.read(s,0,s.length);for(let e=0;e<i;e++)t.barreFrets.push(s[e]);this.data.skip(26)}else{this.data.skip(25),t.name=at.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=Te.readInt32LE(this.data);for(let i=0;i<6;i++){let s=Te.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}this.data.skip(36)}else{let i=this._versionNumber>=406?7:6;if(t.name=at.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=Te.readInt32LE(this.data),t.firstFret>0)for(let s=0;s<i;s++){let i=Te.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}}t.name&&(e.chordId=i,e.voice.bar.staff.addChord(e.chordId,t))}readBeatEffects(e){let t=this.data.readByte(),i=0;if(this._versionNumber>=400&&(i=this.data.readByte()),e.fadeIn=!!(16&t),(this._versionNumber<400&&1&t||2&t)&&(e.vibrato=_.Slight),e.hasRasgueado=!!(1&i),32&t&&this._versionNumber>=400){switch(Te.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}}else if(32&t){switch(Te.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}this.data.skip(4)}if(4&i&&this.readTremoloBarEffect(e),64&t){let t=0,i=0;this._versionNumber<500?(i=this.data.readByte(),t=this.data.readByte()):(t=this.data.readByte(),i=this.data.readByte()),t>0?(e.brushType=d.BrushUp,e.brushDuration=st.toStrokeValue(t)):i>0&&(e.brushType=d.BrushDown,e.brushDuration=st.toStrokeValue(i))}if(2&i)switch(Te.readSInt8(this.data)){case 0:e.pickStroke=N.None;break;case 1:e.pickStroke=N.Up;break;case 2:e.pickStroke=N.Down}if(this._versionNumber<400){if(4&t)return y.Natural;if(8&t)return y.Artificial}return y.None}readTremoloBarEffect(e){this.data.readByte(),Te.readInt32LE(this.data);let t=Te.readInt32LE(this.data);if(t>0)for(let i=0;i<t;i++){let t=new U(0,0);t.offset=Te.readInt32LE(this.data),t.value=Te.readInt32LE(this.data)/st.BendStep|0,at.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 rt;t.instrument=Te.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=Te.readSInt8(this.data),t.balance=Te.readSInt8(this.data);let i=Te.readSInt8(this.data),s=Te.readSInt8(this.data),a=Te.readSInt8(this.data),n=Te.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=at.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=Te.readInt32LE(this.data),t.volume>=0&&this.data.readByte(),t.balance>=0&&this.data.readByte(),i>=0&&this.data.readByte(),s>=0&&this.data.readByte(),a>=0&&this.data.readByte(),n>=0&&this.data.readByte(),t.tempo>=0&&(t.duration=Te.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500&&this.data.readByte(),this._versionNumber>=510&&(at.gpReadStringIntByte(this.data,this.settings.importer.encoding),at.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){let i=new H;i.isLinear=!0,i.type=r.Volume,i.value=t.volume,e.automations.push(i)}if(t.balance>=0){let i=new H;i.isLinear=!0,i.type=r.Balance,i.value=t.balance,e.automations.push(i)}if(t.instrument>=0){let i=new H;i.isLinear=!0,i.type=r.Instrument,i.value=t.instrument,e.automations.push(i)}if(t.tempo>=0){let i=new H;i.isLinear=!0,i.type=r.Tempo,i.value=t.tempo,e.automations.push(i),e.voice.bar.masterBar.tempoAutomation=i}}readNote(e,t,i,s,r){let n=new ee;n.string=t.staff.tuning.length-r;let o=this.data.readByte();if(2&o?n.accentuated=a.Heavy:64&o&&(n.accentuated=a.Normal),n.isGhost=!!(4&o),32&o){let e=this.data.readByte();3===e?n.isDead=!0:2===e&&(n.isTieDestination=!0)}if(1&o&&this._versionNumber<500&&(this.data.readByte(),this.data.readByte()),16&o){let e=Te.readSInt8(this.data);n.dynamics=this.toDynamicValue(e),s.dynamics=n.dynamics}32&o&&(n.fret=Te.readSInt8(this.data)),128&o&&(n.leftHandFinger=Te.readSInt8(this.data),n.rightHandFinger=Te.readSInt8(this.data),n.isFingering=!0);let h=!1;if(this._versionNumber>=500){1&o&&(n.durationPercent=at.gpReadDouble(this.data)),h=!!(2&this.data.readByte())}if(s.addNote(n),8&o&&this.readNoteEffects(e,i,s,n),t.staff.isPercussion&&(n.percussionArticulation=n.fret,n.string=-1,n.fret=-1),h){const e=be.defaultAccidentals[n.realValueWithoutHarmonic%12];"#"===e?n.accidentalMode=b.ForceFlat:"b"===e&&(n.accidentalMode=b.ForceSharp)}return n}toDynamicValue(e){switch(e){case 1:return g.PPP;case 2:return g.PP;case 3:return g.P;case 4:return g.MP;case 5:return g.MF;case 6:default:return g.F;case 7:return g.FF;case 8:return g.FFF}}readNoteEffects(e,t,i,s){let a=this.data.readByte(),r=0;this._versionNumber>=400&&(r=this.data.readByte()),1&a&&this.readBend(s),16&a&&this.readGrace(t,s),4&r&&this.readTremoloPicking(i),8&r?this.readSlide(s):this._versionNumber<400&&4&a&&(s.slideOutType=w.Shift),16&r&&this.readArtificialHarmonic(s),32&r&&this.readTrill(s),s.isLetRing=!!(8&a),s.isHammerPullOrigin=!!(2&a),64&r&&(s.vibrato=_.Slight),s.isPalmMute=!!(2&r),s.isStaccato=!!(1&r)}readBend(e){this.data.readByte(),Te.readInt32LE(this.data);let t=Te.readInt32LE(this.data);if(t>0)for(let i=0;i<t;i++){let t=new U(0,0);t.offset=Te.readInt32LE(this.data),t.value=Te.readInt32LE(this.data)/st.BendStep|0,at.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){let i=new oe,s=new ee;switch(s.string=t.string,s.fret=Te.readSInt8(this.data),i.duration=p.ThirtySecond,i.dynamics=this.toDynamicValue(Te.readSInt8(this.data)),Te.readSInt8(this.data)){case 0:case 2:break;case 1:s.slideOutType=w.Legato,s.slideTarget=t;break;case 3:s.isHammerPullOrigin=!0}if(s.dynamics=i.dynamics,this.data.skip(1),this._versionNumber<500)i.graceType=f.BeforeBeat;else{let e=this.data.readByte();s.isDead=!!(1&e),i.graceType=2&e?f.OnBeat:f.BeforeBeat}e.addGraceBeat(i),i.addNote(s)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=p.Eighth;break;case 2:e.tremoloSpeed=p.Sixteenth;break;case 3:e.tremoloSpeed=p.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){let t=Te.readSInt8(this.data);1&t?e.slideOutType=w.Shift:2&t?e.slideOutType=w.Legato:4&t?e.slideOutType=w.OutDown:8&t&&(e.slideOutType=w.OutUp),16&t?e.slideInType=S.IntoFromBelow:32&t&&(e.slideInType=S.IntoFromAbove)}else{switch(Te.readSInt8(this.data)){case 1:e.slideOutType=w.Shift;break;case 2:e.slideOutType=w.Legato;break;case 3:e.slideOutType=w.OutDown;break;case 4:e.slideOutType=w.OutUp;break;case-1:e.slideInType=S.IntoFromBelow;break;case-2:e.slideInType=S.IntoFromAbove}}}readArtificialHarmonic(e){let t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=y.Natural,e.harmonicValue=this.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=y.Artificial;break;case 3:e.harmonicType=y.Tap,e.harmonicValue=this.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=y.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=y.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=y.Natural;break;case 3:e.harmonicType=y.Tap;break;case 4:e.harmonicType=y.Pinch;break;case 5:e.harmonicType=y.Semi;break;case 15:case 17:case 22:e.harmonicType=y.Artificial}}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=p.Sixteenth;break;case 2:e.trillSpeed=p.ThirtySecond;break;case 3:e.trillSpeed=p.SixtyFourth}}}st.VersionString="FICHIER GUITAR PRO ",st.BendStep=25;class at{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 i=e.readByte(),s=e.readByte(),a=e.readByte(),r=255;return t?r=e.readByte():e.skip(1),new me(i,s,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),at.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return at.gpReadString(e,Te.readInt32LE(e),t)}static gpReadStringIntByte(e,t){let i=Te.readInt32LE(e)-1;return e.readByte(),at.gpReadString(e,i,t)}static gpReadString(e,t,i){let s=new Uint8Array(t);return e.read(s,0,s.length),Te.toString(s,i)}static gpWriteString(e,t){const i=Te.stringToBytes(t);e.writeByte(t.length),e.write(i,0,i.length)}static gpReadStringByteLength(e,t,i){let s=e.readByte(),a=at.gpReadString(e,s,i);return s<t&&e.skip(t-s),a}}class rt{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class nt{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"}(xe||(xe={}));class ot{constructor(e){this.raw=new Map;let t=ke.fromBuffer(e),i=Te.readInt32BE(t);for(let e=0;e<i;e++){let e=at.gpReadString(t,t.readByte(),"utf-8");switch(t.readByte()){case xe.Boolean:let i=1===t.readByte();this.addValue(e,i);break;case xe.Integer:let s=Te.readInt32BE(t);this.addValue(e,s);break;case xe.Float:let a=at.gpReadFloat(t);this.addValue(e,a);break;case xe.String:let r=at.gpReadString(t,Te.readInt16BE(t),"utf-8");this.addValue(e,r);break;case xe.Point:let n=Te.readInt32BE(t),o=Te.readInt32BE(t);this.addValue(e,new U(n,o));break;case xe.Size:let h=Te.readInt32BE(t),l=Te.readInt32BE(t);this.addValue(e,new U(h,l));break;case xe.Rectangle:let c=new nt;c.x=Te.readInt32BE(t),c.y=Te.readInt32BE(t),c.w=Te.readInt32BE(t),c.h=Te.readInt32BE(t),this.addValue(e,c);break;case xe.Color:let d=at.gpReadColor(t,!0);this.addValue(e,d)}}}apply(e){for(const[t,i]of this.raw)if("StandardNotation/hideDynamics"===t)e.stylesheet.hideDynamics=i}addValue(e,t){this.raw.set(e,t)}static writeForScore(e){const t=ke.withCapacity(128);return Te.writeInt32BE(t,1),ot.writeBooleanEntry(t,"StandardNotation/hideDynamics",e.stylesheet.hideDynamics),t.toArray()}static writeBooleanEntry(e,t,i){at.gpWriteString(e,t),e.writeByte(xe.Boolean),e.writeByte(i?1:0)}}!function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(Ne||(Ne={}));class ht{constructor(){this.type=Ne.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"}(Pe||(Pe={}));class lt{constructor(){this.nodeType=Pe.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!==Pe.Element&&e.nodeType!==Pe.CDATA||(this.firstElement=e)}getAttribute(e){return this.attributes.has(e)?this.attributes.get(e):""}getElementsByTagName(e,t=!1){let i=[];return this.searchElementsByTagName(this.childNodes,i,e,t),i}searchElementsByTagName(e,t,i,s=!1){for(let a of e)a&&a.nodeType===Pe.Element&&a.localName===i&&t.push(a),s&&this.searchElementsByTagName(a.childNodes,t,i,!0)}findChildElement(e){for(let t of this.childNodes)if(t&&t.nodeType===Pe.Element&&t.localName===e)return t;return null}addElement(e){const t=new lt;return t.nodeType=Pe.Element,t.localName=e,this.addChild(t),t}get innerText(){if(this.nodeType===Pe.Element||this.nodeType===Pe.Document){if(this.firstElement&&this.firstElement.nodeType===Pe.CDATA)return this.firstElement.innerText;let e="";for(let t of this.childNodes)e+=t.innerText?.toString();return e.trim()}return this.value??""}set innerText(e){const t=new lt;t.nodeType=Pe.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new lt;t.nodeType=Pe.CDATA,t.value=e,this.childNodes=[t]}}class ct extends G{constructor(t,i,s){super(e.AlphaTabErrorType.Format,t),this.pos=0,this.xml=i,this.pos=s,Object.setPrototypeOf(this,ct.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"}(Ee||(Ee={}));class dt{static parse(e,t,i){let s=e.charCodeAt(t),a=Ee.Begin,r=Ee.Begin,n=0,o="",h=Ee.Begin,l=null,c=null,d=0,u=0;for(;t<e.length;){switch(s=e.charCodeAt(t),a){case Ee.IgnoreSpaces:switch(s){case dt.CharCodeLF:case dt.CharCodeCR:case dt.CharCodeTab:case dt.CharCodeSpace:break;default:a=r;continue}break;case Ee.Begin:if(s!==dt.CharCodeLowerThan){n=t,a=Ee.Pcdata;continue}a=Ee.IgnoreSpaces,r=Ee.BeginNode;break;case Ee.Pcdata:if(s===dt.CharCodeLowerThan){o+=e.substr(n,t-n);let s=new lt;s.nodeType=Pe.Text,s.value=o,o="",i.addChild(s),a=Ee.IgnoreSpaces,r=Ee.BeginNode}else s===dt.CharCodeAmp&&(o+=e.substr(n,t-n),a=Ee.Escape,h=Ee.Pcdata,n=t+1);break;case Ee.Cdata:if(s===dt.CharCodeBrackedClose&&e.charCodeAt(t+1)===dt.CharCodeBrackedClose&&e.charCodeAt(t+2)===dt.CharCodeGreaterThan){let s=new lt;s.nodeType=Pe.CDATA,s.value=e.substr(n,t-n),i.addChild(s),t+=2,a=Ee.Begin}break;case Ee.BeginNode:switch(s){case dt.CharCodeExclamation:if(e.charCodeAt(t+1)===dt.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new ct("Expected <![CDATA[",e,t);t+=5,a=Ee.Cdata,n=t+1}else if(e.charCodeAt(t+1)===dt.CharCodeUpperD||e.charCodeAt(t+1)===dt.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new ct("Expected <!DOCTYPE",e,t);t+=8,a=Ee.Doctype,n=t+1}else{if(e.charCodeAt(t+1)!==dt.CharCodeMinus||e.charCodeAt(t+2)!==dt.CharCodeMinus)throw new ct("Expected \x3c!--",e,t);t+=2,a=Ee.Comment,n=t+1}break;case dt.CharCodeQuestion:a=Ee.Header,n=t;break;case dt.CharCodeSlash:if(!i)throw new ct("Expected node name",e,t);n=t+1,a=Ee.IgnoreSpaces,r=Ee.Close;break;default:a=Ee.TagName,n=t;continue}break;case Ee.TagName:if(!dt.isValidChar(s)){if(t===n)throw new ct("Expected node name",e,t);l=new lt,l.nodeType=Pe.Element,l.localName=e.substr(n,t-n),i.addChild(l),a=Ee.IgnoreSpaces,r=Ee.Body;continue}break;case Ee.Body:switch(s){case dt.CharCodeSlash:a=Ee.WaitEnd;break;case dt.CharCodeGreaterThan:a=Ee.Childs;break;default:a=Ee.AttribName,n=t;continue}break;case Ee.AttribName:if(!dt.isValidChar(s)){if(n===t)throw new ct("Expected attribute name",e,t);if(c=e.substr(n,t-n),l.attributes.has(c))throw new ct(`Duplicate attribute [${c}]`,e,t);a=Ee.IgnoreSpaces,r=Ee.Equals;continue}break;case Ee.Equals:if(s!==dt.CharCodeEquals)throw new ct("Expected =",e,t);a=Ee.IgnoreSpaces,r=Ee.AttvalBegin;break;case Ee.AttvalBegin:switch(s){case dt.CharCodeDoubleQuote:case dt.CharCodeSingleQuote:o="",a=Ee.AttribVal,n=t+1,u=s}break;case Ee.AttribVal:if(s===dt.CharCodeAmp)o+=e.substr(n,t-n),a=Ee.Escape,h=Ee.AttribVal,n=t+1;else if(s===u){o+=e.substr(n,t-n);let i=o;o="",l.attributes.set(c,i),a=Ee.IgnoreSpaces,r=Ee.Body}break;case Ee.Childs:n=t=dt.parse(e,t,l),a=Ee.Begin;break;case Ee.WaitEnd:if(s!==dt.CharCodeGreaterThan)throw new ct("Expected >",e,t);a=Ee.Begin;break;case Ee.WaitEndRet:if(s===dt.CharCodeGreaterThan)return t;throw new ct("Expected >",e,t);case Ee.Close:if(!dt.isValidChar(s)){if(n===t)throw new ct("Expected node name",e,t);if(e.substr(n,t-n)!==i.localName)throw new ct("Expected </"+i.localName+">",e,t);a=Ee.IgnoreSpaces,r=Ee.WaitEndRet;continue}break;case Ee.Comment:s===dt.CharCodeMinus&&e.charCodeAt(t+1)===dt.CharCodeMinus&&e.charCodeAt(t+2)===dt.CharCodeGreaterThan&&(t+=2,a=Ee.Begin);break;case Ee.Doctype:if(s===dt.CharCodeBrackedOpen)d++;else if(s===dt.CharCodeBrackedClose)d--;else if(s===dt.CharCodeGreaterThan&&0===d){let s=new lt;s.nodeType=Pe.DocumentType,s.value=e.substr(n,t-n),i.addChild(s),a=Ee.Begin}break;case Ee.Header:s===dt.CharCodeQuestion&&e.charCodeAt(t+1)===dt.CharCodeGreaterThan&&(t++,a=Ee.Begin);break;case Ee.Escape:if(s===dt.CharCodeSemi){let i=e.substr(n,t-n);if(i.charCodeAt(0)===dt.CharCodeSharp){let e=i.charCodeAt(1)===dt.CharCodeLowerX?parseInt("0"+i.substr(1,i.length-1)):parseInt(i.substr(1,i.length-1));o+=String.fromCharCode(e)}else dt.Escapes.has(i)?o+=dt.Escapes.get(i):o+=("&"+i+";")?.toString();n=t+1,a=h}else dt.isValidChar(s)||s===dt.CharCodeSharp||(o+="&",o+=e.substr(n,t-n),n=--t+1,a=h)}t++}if(a===Ee.Begin&&(n=t,a=Ee.Pcdata),a===Ee.Pcdata){if(t!==n){o+=e.substr(n,t-n);let s=new lt;s.nodeType=Pe.Text,s.value=o,i.addChild(s)}return t}if(a===Ee.Escape&&h===Ee.Pcdata){o+="&",o+=e.substr(n,t-n);let s=new lt;return s.nodeType=Pe.Text,s.value=o,i.addChild(s),t}throw new ct("Unexpected end",e,t)}static isValidChar(e){return e>=dt.CharCodeLowerA&&e<=dt.CharCodeLowerZ||e>=dt.CharCodeUpperA&&e<=dt.CharCodeUpperZ||e>=dt.CharCode0&&e<=dt.CharCode9||e===dt.CharCodeColon||e===dt.CharCodeDot||e===dt.CharCodeUnderscore||e===dt.CharCodeMinus}}dt.CharCodeLF=10,dt.CharCodeTab=9,dt.CharCodeCR=13,dt.CharCodeSpace=32,dt.CharCodeLowerThan=60,dt.CharCodeAmp=38,dt.CharCodeBrackedClose=93,dt.CharCodeBrackedOpen=91,dt.CharCodeGreaterThan=62,dt.CharCodeExclamation=33,dt.CharCodeUpperD=68,dt.CharCodeLowerD=100,dt.CharCodeMinus=45,dt.CharCodeQuestion=63,dt.CharCodeSlash=47,dt.CharCodeEquals=61,dt.CharCodeDoubleQuote=34,dt.CharCodeSingleQuote=39,dt.CharCodeSharp=35,dt.CharCodeLowerX=120,dt.CharCodeLowerA=97,dt.CharCodeLowerZ=122,dt.CharCodeUpperA=65,dt.CharCodeUpperZ=90,dt.CharCode0=48,dt.CharCode9=57,dt.CharCodeColon=58,dt.CharCodeDot=46,dt.CharCodeUnderscore=95,dt.CharCodeSemi=59,dt.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class ut{static write(e,t,i){const s=new ut(t,i);return s.writeNode(e),s.toString()}constructor(e,t){this._result=[],this._indention=e,this._xmlHeader=t,this._currentIndention="",this._isStartOfLine=!0}writeNode(e){switch(e.nodeType){case Pe.None:break;case Pe.Element:this._result.length>0&&this.writeLine(),this.write(`<${e.localName}`);for(const[t,i]of e.attributes)this.write(` ${t}="`),this.writeAttributeValue(i),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===Pe.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case Pe.Text:e.value&&this.write(e.value);break;case Pe.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case Pe.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case Pe.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 i=e.charAt(t);switch(i){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(i)}}}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 pt extends lt{constructor(){super(),this.nodeType=Pe.Document}parse(e){dt.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return ut.write(this,e,t)}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(Ce||(Ce={}));class gt{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=p.Quarter}}class ft{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return this.path+";"+this.name+";"+this.role}}class mt{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 i=new pt;try{i.parse(e)}catch(e){throw new V("Could not parse XML",e)}if(this.parseDom(i),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 V("Root node of XML was not GPIF");this.score=new pe;for(let e of t.childNodes)if(e.nodeType===Pe.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===Pe.Element)switch(t.localName){case"Title":this.score.title=t.firstChild.innerText;break;case"SubTitle":this.score.subTitle=t.firstChild.innerText;break;case"Artist":this.score.artist=t.firstChild.innerText;break;case"Album":this.score.album=t.firstChild.innerText;break;case"Words":this.score.words=t.firstChild.innerText;break;case"Music":this.score.music=t.firstChild.innerText;break;case"WordsAndMusic":if(t.firstChild&&""!==t.firstChild.innerText){let e=t.firstChild.innerText;e&&!this.score.words&&(this.score.words=e),e&&!this.score.music&&(this.score.music=e)}break;case"Copyright":this.score.copyright=t.firstChild.innerText;break;case"Tabber":this.score.tab=t.firstChild.innerText;break;case"Instructions":this.score.instructions=t.firstChild.innerText;break;case"Notices":this.score.notices=t.firstChild.innerText;break;case"ScoreSystemsDefaultLayout":this.score.defaultSystemsLayout=parseInt(t.innerText);break;case"ScoreSystemsLayout":this.score.systemsLayout=t.innerText.split(" ").map((e=>parseInt(e)))}}parseMasterTrackNode(e){for(let t of e.childNodes)if(t.nodeType===Pe.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,i){for(let s of e.childNodes)if(s.nodeType===Pe.Element&&"Automation"===s.localName)this.parseAutomation(s,t,i)}parseAutomation(e,t,i){let s=null,a=!1,r=-1,n=0,o=0,h=null,l=0,c=null;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"Type":s=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===Pe.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(!s)return;let d=null;switch(s){case"Tempo":d=H.buildTempoAutomation(a,n,o,l);break;case"Sound":h&&i&&i.has(h)&&(d=H.buildInstrumentAutomation(a,n,i.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===Pe.Element&&"Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;let t=new we;t.ensureStaveCount(1),t.staves[0].showStandardNotation=!0;let i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"Name":t.name=s.innerText;break;case"Color":let e=s.innerText.split(" ");if(e.length>=3){let i=parseInt(e[0]),s=parseInt(e[1]),a=parseInt(e[2]);t.color=new me(i,s,a,255)}break;case"Instrument":let a=s.getAttribute("ref");(a.endsWith("-gs")||a.endsWith("GrandStaff"))&&(t.ensureStaveCount(2),t.staves[1].showStandardNotation=!0);break;case"InstrumentSet":this.parseInstrumentSet(t,s);break;case"NotationPatch":this.parseNotationPatch(t,s);break;case"ShortName":t.shortName=s.innerText;break;case"SystemsDefautLayout":t.defaultSystemsLayout=parseInt(s.innerText);break;case"SystemsLayout":t.systemsLayout=s.innerText.split(" ").map((e=>parseInt(e)));break;case"Lyrics":this.parseLyrics(i,s);break;case"Properties":this.parseTrackProperties(t,s);break;case"GeneralMidi":case"MidiConnection":case"MIDISettings":this.parseGeneralMidi(t,s);break;case"Sounds":this.parseSounds(i,t,s);break;case"PlaybackState":let r=s.innerText;t.playbackInfo.isSolo="Solo"===r,t.playbackInfo.isMute="Mute"===r;break;case"PartSounding":this.parsePartSounding(t,s);break;case"Staves":this.parseStaves(t,s);break;case"Transpose":this.parseTranspose(t,s);break;case"RSE":this.parseRSE(t,s);break;case"Automations":this.parseTrackAutomations(i,s)}this._tracksById.set(i,t)}parseTrackAutomations(e,t){const i=new Map;this._automationsPerTrackIdAndBarIndex.set(e,i),this.parseAutomations(t,i,this._soundsByTrack.get(e))}parseNotationPatch(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"LineCount":const t=parseInt(i.innerText);for(let i of e.staves)i.standardNotationLineCount=t;break;case"Elements":this.parseElements(e,i)}}parseInstrumentSet(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"Type":if("drumKit"===i.innerText)for(let t of e.staves)t.isPercussion=!0;if("drumKit"===i.innerText)for(let t of e.staves)t.isPercussion=!0;break;case"Elements":this.parseElements(e,i);break;case"LineCount":const t=parseInt(i.innerText);for(let i of e.staves)i.standardNotationLineCount=t}}parseElements(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"Element"===i.localName)this.parseElement(e,i)}parseElement(e,t){const i=t.findChildElement("Type"),s=i?i.innerText:"";for(let i of t.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"Name":case"Articulations":this.parseArticulations(e,i,s)}}parseArticulations(e,t,i){for(let s of t.childNodes)if(s.nodeType===Pe.Element&&"Articulation"===s.localName)this.parseArticulation(e,s,i)}parseArticulation(e,t,i){const s=new $;s.outputMidiNumber=-1,s.elementType=i;let a="";for(let e of t.childNodes)if(e.nodeType===Pe.Element){const t=e.innerText;switch(e.localName){case"Name":a=e.innerText;break;case"OutputMidiNumber":t.length>0&&(s.outputMidiNumber=parseInt(t));break;case"TechniqueSymbol":s.techniqueSymbol=this.parseTechniqueSymbol(t);break;case"TechniquePlacement":switch(t){case"outside":case"above":s.techniqueSymbolPlacement=C.Bottom;break;case"inside":s.techniqueSymbolPlacement=C.Middle;break;case"below":s.techniqueSymbolPlacement=C.Top}break;case"Noteheads":const i=t.split(" ");i.length>=1&&(s.noteHeadDefault=this.parseNoteHead(i[0])),i.length>=2&&(s.noteHeadHalf=this.parseNoteHead(i[1])),i.length>=3&&(s.noteHeadWhole=this.parseNoteHead(i[2])),s.noteHeadHalf==P.None&&(s.noteHeadHalf=s.noteHeadDefault),s.noteHeadWhole==P.None&&(s.noteHeadWhole=s.noteHeadDefault);break;case"StaffLine":t.length>0&&(s.staffLine=parseInt(t))}}-1!==s.outputMidiNumber?(e.percussionArticulations.push(s),a.length>0&&this._articulationByName.set(a,s)):a.length>0&&this._articulationByName.has(a)&&(this._articulationByName.get(a).staffLine=s.staffLine)}parseTechniqueSymbol(e){switch(e){case"pictEdgeOfCymbal":return P.PictEdgeOfCymbal;case"articStaccatoAbove":return P.ArticStaccatoAbove;case"noteheadParenthesis":return P.NoteheadParenthesis;case"stringsUpBow":return P.StringsUpBow;case"stringsDownBow":return P.StringsDownBow;case"guitarGolpe":return P.GuitarGolpe;default:return P.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return P.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return P.NoteheadDoubleWhole;case"noteheadWhole":return P.NoteheadWhole;case"noteheadHalf":return P.NoteheadHalf;case"noteheadBlack":return P.NoteheadBlack;case"noteheadNull":return P.NoteheadNull;case"noteheadXOrnate":return P.NoteheadXOrnate;case"noteheadTriangleUpWhole":return P.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return P.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return P.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return P.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return P.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return P.NoteheadDiamondWhiteWide;case"noteheadCircleX":return P.NoteheadCircleX;case"noteheadXWhole":return P.NoteheadXWhole;case"noteheadXHalf":return P.NoteheadXHalf;case"noteheadXBlack":return P.NoteheadXBlack;case"noteheadParenthesis":return P.NoteheadParenthesis;case"noteheadSlashedBlack2":return P.NoteheadSlashedBlack2;case"noteheadCircleSlash":return P.NoteheadCircleSlash;case"noteheadHeavyX":return P.NoteheadHeavyX;case"noteheadHeavyXHat":return P.NoteheadHeavyXHat;default:return J.warning("GPIF","Unknown notehead symbol",e),P.None}}parseStaves(e,t){let i=0;for(let s of t.childNodes)if(s.nodeType===Pe.Element&&"Staff"===s.localName){e.ensureStaveCount(i+1);let t=e.staves[i];this.parseStaff(t,s),i++}}parseStaff(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"Properties"===i.localName)this.parseStaffProperties(e,i)}parseStaffProperties(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"Property"===i.localName)this.parseStaffProperty(e,i)}parseStaffProperty(e,t){switch(t.getAttribute("name")){case"Tuning":for(let i of t.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"Pitches":let s=t.findChildElement("Pitches").innerText.split(" "),a=new Array(s.length);for(let e=0;e<a.length;e++)a[a.length-1-e]=parseInt(s[e]);e.stringTuning.tunings=a;break;case"Label":e.stringTuning.name=i.innerText}e.isPercussion||(e.showTablature=!0);break;case"DiagramCollection":case"ChordCollection":this.parseDiagramCollectionForStaff(e,t);break;case"CapoFret":let i=parseInt(t.findChildElement("Fret").innerText);e.capo=i}}parseLyrics(e,t){let i=[];for(let e of t.childNodes)if(e.nodeType===Pe.Element&&"Line"===e.localName)i.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,i)}parseLyricsLine(e){let t=new le;for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"Offset":t.startBar=parseInt(i.innerText);break;case"Text":t.text=i.innerText}return t}parseDiagramCollectionForTrack(e,t){let i=t.findChildElement("Items");for(let t of i.childNodes)if(t.nodeType===Pe.Element&&"Item"===t.localName)this.parseDiagramItemForTrack(e,t)}parseDiagramCollectionForStaff(e,t){let i=t.findChildElement("Items");for(let t of i.childNodes)if(t.nodeType===Pe.Element&&"Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){let i=new he,s=t.getAttribute("id");for(let t of e.staves)t.addChord(s,i);this.parseDiagramItemForChord(i,t)}parseDiagramItemForStaff(e,t){let i=new he,s=t.getAttribute("id");e.addChord(s,i),this.parseDiagramItemForChord(i,t)}parseDiagramItemForChord(e,t){e.name=t.getAttribute("name");let i=t.findChildElement("Diagram");if(!i)return e.showDiagram=!1,void(e.showFingering=!1);let s=parseInt(i.getAttribute("stringCount")),a=parseInt(i.getAttribute("baseFret"));e.firstFret=a+1;for(let t=0;t<s;t++)e.strings.push(-1);for(let t of i.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"Fret":let i=parseInt(t.getAttribute("string"));e.strings[s-i-1]=a+parseInt(t.getAttribute("fret"));break;case"Fingering":let r=new Map;for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"Position"===i.localName){let t=m.Unknown,s=a+parseInt(i.getAttribute("fret"));switch(i.getAttribute("finger")){case"Index":t=m.IndexFinger;break;case"Middle":t=m.MiddleFinger;break;case"Rank":t=m.AnnularFinger;break;case"Pinky":t=m.LittleFinger;break;case"Thumb":t=m.Thumb}t!==m.Unknown&&(r.has(t)?e.barreFrets.push(s):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 i of t.childNodes)if(i.nodeType===Pe.Element&&"Property"===i.localName)this.parseTrackProperty(e,i)}parseTrackProperty(e,t){switch(t.getAttribute("name")){case"Tuning":let i=t.findChildElement("Pitches").innerText.split(" "),s=new Array(i.length);for(let e=0;e<s.length;e++)s[s.length-1-e]=parseInt(i[e]);for(let t of e.staves)t.stringTuning.tunings=s,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 i of t.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"Program":e.playbackInfo.program=parseInt(i.innerText);break;case"Port":e.playbackInfo.port=parseInt(i.innerText);break;case"PrimaryChannel":e.playbackInfo.primaryChannel=parseInt(i.innerText);break;case"SecondaryChannel":e.playbackInfo.secondaryChannel=parseInt(i.innerText)}if("Percussion"===t.getAttribute("table"))for(let t of e.staves)t.isPercussion=!0}parseSounds(e,t,i){for(let s of i.childNodes)if(s.nodeType===Pe.Element&&"Sound"===s.localName)this.parseSound(e,t,s)}parseSound(e,t,i){const s=new ft;for(let e of i.childNodes)if(e.nodeType===Pe.Element)switch(e.localName){case"Name":s.name=e.innerText;break;case"Path":s.path=e.innerText;break;case"Role":s.role=e.innerText;break;case"MIDI":this.parseSoundMidi(s,e)}"Factory"!==s.role&&0!==t.playbackInfo.program||(t.playbackInfo.program=s.program),this._soundsByTrack.has(e)||this._soundsByTrack.set(e,new Map),this._soundsByTrack.get(e).set(s.uniqueId,s)}parseSoundMidi(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"Program"===i.localName)e.program=parseInt(i.innerText)}parsePartSounding(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"TranspositionPitch"===i.localName)for(let t of e.staves)t.displayTranspositionPitch=parseInt(i.innerText)}parseTranspose(e,t){let i=0,s=0;for(let e of t.childNodes)if(e.nodeType===Pe.Element)switch(e.localName){case"Chromatic":s=parseInt(e.innerText);break;case"Octave":i=parseInt(e.innerText)}for(let t of e.staves)t.displayTranspositionPitch=12*i+s}parseRSE(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"ChannelStrip"===i.localName)this.parseChannelStrip(e,i)}parseChannelStrip(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"Parameters"===i.localName)this.parseChannelStripParameters(e,i)}parseChannelStripParameters(e,t){if(t.firstChild&&t.firstChild.value){let i=t.firstChild.value.split(" ");i.length>=12&&(e.playbackInfo.balance=Math.floor(16*parseFloat(i[11])),e.playbackInfo.volume=Math.floor(16*parseFloat(i[12])))}}parseMasterBarsNode(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){let t=new ce;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"Time":let e=i.innerText.split("/");t.timeSignatureNumerator=parseInt(e[0]),t.timeSignatureDenominator=parseInt(e[1]);break;case"DoubleBar":t.isDoubleBar=!0;break;case"Section":t.section=new ge,t.section.marker=i.findChildElement("Letter").innerText,t.section.text=i.findChildElement("Text").innerText;break;case"Repeat":"true"===i.getAttribute("start").toLowerCase()&&(t.isRepeatStart=!0),"true"===i.getAttribute("end").toLowerCase()&&i.getAttribute("count")&&(t.repeatCount=parseInt(i.getAttribute("count")));break;case"AlternateEndings":let s=i.innerText.split(" "),a=0;for(let e=0;e<s.length;e++)a|=1<<-1+parseInt(s[e]);t.alternateEndings=a;break;case"Bars":this._barsOfMasterBar.push(i.innerText.split(" "));break;case"TripletFeel":switch(i.innerText){case"NoTripletFeel":t.tripletFeel=A.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=A.Triplet8th;break;case"Triplet16th":t.tripletFeel=A.Triplet16th;break;case"Dotted8th":t.tripletFeel=A.Dotted8th;break;case"Dotted16th":t.tripletFeel=A.Dotted16th;break;case"Scottish8th":t.tripletFeel=A.Scottish8th;break;case"Scottish16th":t.tripletFeel=A.Scottish16th}break;case"Key":t.keySignature=parseInt(i.findChildElement("AccidentalCount").innerText);let r=i.findChildElement("Mode");if(r)switch(r.innerText.toLowerCase()){case"major":t.keySignatureType=D.Major;break;case"minor":t.keySignatureType=D.Minor}break;case"Fermatas":this.parseFermatas(t,i);break;case"XProperties":this.parseMasterBarXProperties(i,t)}this._masterBars.push(t)}parseFermatas(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"Fermata"===i.localName)this.parseFermata(e,i)}parseFermata(e,t){let i=0,s=new ht;for(let e of t.childNodes)if(e.nodeType===Pe.Element)switch(e.localName){case"Type":switch(e.innerText){case"Short":s.type=Ne.Short;break;case"Medium":s.type=Ne.Medium;break;case"Long":s.type=Ne.Long}break;case"Length":s.length=parseFloat(e.innerText);break;case"Offset":let t=e.innerText.split("/");if(2===t.length){i=parseInt(t[0])/parseInt(t[1])*z.QuarterTime|0}}e.addFermata(i,s)}parseBars(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"Bar"===t.localName)this.parseBar(t)}parseBar(e){let t=new W,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"Voices":this._voicesOfBar.set(i,s.innerText.split(" "));break;case"Clef":switch(s.innerText){case"Neutral":t.clef=n.Neutral;break;case"G2":t.clef=n.G2;break;case"F4":t.clef=n.F4;break;case"C4":t.clef=n.C4;break;case"C3":t.clef=n.C3}break;case"Ottavia":switch(s.innerText){case"8va":t.clefOttava=o._8va;break;case"15ma":t.clefOttava=o._15ma;break;case"8vb":t.clefOttava=o._8vb;break;case"15mb":t.clefOttava=o._15mb}break;case"SimileMark":switch(s.innerText){case"Simple":t.simileMark=h.Simple;break;case"FirstOfDouble":t.simileMark=h.FirstOfDouble;break;case"SecondOfDouble":t.simileMark=h.SecondOfDouble}break;case"XProperties":this.parseBarXProperties(s,t)}this._barsById.set(i,t)}parseVoices(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"Voice"===t.localName)this.parseVoice(t)}parseVoice(e){let t=new _e,i=e.getAttribute("id");for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"Beats"===t.localName)this._beatsOfVoice.set(i,t.innerText.split(" "));this._voiceById.set(i,t)}parseBeats(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"Beat"===t.localName)this.parseBeat(t)}parseBeat(e){let t=new oe,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"Notes":this._notesOfBeat.set(i,s.innerText.split(" "));break;case"Rhythm":this._rhythmOfBeat.set(i,s.getAttribute("ref"));break;case"Fadding":"FadeIn"===s.innerText&&(t.fadeIn=!0);break;case"Tremolo":switch(s.innerText){case"1/2":t.tremoloSpeed=p.Eighth;break;case"1/4":t.tremoloSpeed=p.Sixteenth;break;case"1/8":t.tremoloSpeed=p.ThirtySecond}break;case"Chord":t.chordId=s.innerText;break;case"Hairpin":switch(s.innerText){case"Crescendo":t.crescendo=u.Crescendo;break;case"Decrescendo":t.crescendo=u.Decrescendo}break;case"Arpeggio":"Up"===s.innerText?t.brushType=d.ArpeggioUp:t.brushType=d.ArpeggioDown;break;case"Properties":this.parseBeatProperties(s,t);break;case"XProperties":this.parseBeatXProperties(s,t);break;case"FreeText":t.text=s.innerText;break;case"TransposedPitchStemOrientation":switch(s.innerText){case"Upward":t.preferredBeamDirection=Ce.Up;break;case"Downward":t.preferredBeamDirection=Ce.Down}break;case"Dynamic":switch(s.innerText){case"PPP":t.dynamics=g.PPP;break;case"PP":t.dynamics=g.PP;break;case"P":t.dynamics=g.P;break;case"MP":t.dynamics=g.MP;break;case"MF":t.dynamics=g.MF;break;case"F":t.dynamics=g.F;break;case"FF":t.dynamics=g.FF;break;case"FFF":t.dynamics=g.FFF}break;case"GraceNotes":switch(s.innerText){case"OnBeat":t.graceType=f.OnBeat;break;case"BeforeBeat":t.graceType=f.BeforeBeat}break;case"Legato":"true"===s.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":let e=new U(0,0);e.value=this.toBendValue(parseFloat(s.getAttribute("originValue"))),e.offset=this.toBendOffset(parseFloat(s.getAttribute("originOffset"))),t.addWhammyBarPoint(e);let a=new U(0,0);a.value=this.toBendValue(parseFloat(s.getAttribute("middleValue"))),a.offset=this.toBendOffset(parseFloat(s.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);let r=new U(0,0);r.value=this.toBendValue(parseFloat(s.getAttribute("middleValue"))),r.offset=this.toBendOffset(parseFloat(s.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);let n=new U(0,0);n.value=this.toBendValue(parseFloat(s.getAttribute("destinationValue"))),n.offset=this.toBendOffset(parseFloat(s.getAttribute("destinationOffset"))),t.addWhammyBarPoint(n);break;case"Ottavia":switch(s.innerText){case"8va":t.ottava=o._8va;break;case"8vb":t.ottava=o._8vb;break;case"15ma":t.ottava=o._15ma;break;case"15mb":t.ottava=o._15mb}break;case"Lyrics":t.lyrics=this.parseBeatLyrics(s),this._skipApplyLyrics=!0}this._beatById.set(i,t)}parseBeatLyrics(e){const t=[];for(let i of e.childNodes)if(i.nodeType===Pe.Element&&"Line"===i.localName)t.push(i.innerText);return t}parseBeatXProperties(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element&&"XProperty"===i.localName){let e=0;switch(i.getAttribute("id")){case"1124204545":e=parseInt(i.findChildElement("Int").innerText),t.invertBeamDirection=1===e;break;case"687935489":e=parseInt(i.findChildElement("Int").innerText),t.brushDuration=e}}}parseBarXProperties(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element&&"XProperty"===i.localName){if("1124139520"===i.getAttribute("id")){const e=i.findChildElement("Double")??i.findChildElement("Float");t.displayScale=parseFloat(e.innerText)}}}parseMasterBarXProperties(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element&&"XProperty"===i.localName){if("1124073984"===i.getAttribute("id"))t.displayScale=parseFloat(i.findChildElement("Double").innerText)}}parseBeatProperties(e,t){let i=!1,s=null,a=null,r=null,n=null,o=null;for(let h of e.childNodes)if(h.nodeType===Pe.Element&&"Property"===h.localName){switch(h.getAttribute("name")){case"Brush":"Up"===h.findChildElement("Direction").innerText?t.brushType=d.BrushUp:t.brushType=d.BrushDown;break;case"PickStroke":"Up"===h.findChildElement("Direction").innerText?t.pickStroke=N.Up:t.pickStroke=N.Down;break;case"Slapped":h.findChildElement("Enable")&&(t.slap=!0);break;case"Popped":h.findChildElement("Enable")&&(t.pop=!0);break;case"VibratoWTremBar":switch(h.findChildElement("Strength").innerText){case"Wide":t.vibrato=_.Wide;break;case"Slight":t.vibrato=_.Slight}break;case"WhammyBar":i=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":s||(s=new U(0,0)),s.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":s||(s=new U(0,0)),s.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 U(U.MaxPosition,0)),o.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new U(0,0)),o.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText))}}i&&(s||(s=new U(0,0)),o||(o=new U(U.MaxPosition,0)),t.addWhammyBarPoint(s),r&&a&&t.addWhammyBarPoint(new U(r,a)),n&&a&&t.addWhammyBarPoint(new U(n,a)),r||n||!a||t.addWhammyBarPoint(new U(U.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"Note"===t.localName)this.parseNote(t)}parseNote(e){let t=new ee,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"Properties":this.parseNoteProperties(s,t,i);break;case"AntiAccent":"normal"===s.innerText.toLowerCase()&&(t.isGhost=!0);break;case"LetRing":t.isLetRing=!0;break;case"Trill":t.trillValue=parseInt(s.innerText),t.trillSpeed=p.Sixteenth;break;case"Accent":let e=parseInt(s.innerText);1&e&&(t.isStaccato=!0),4&e&&(t.accentuated=a.Heavy),8&e&&(t.accentuated=a.Normal);break;case"Tie":"true"===s.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(s.innerText){case"Slight":t.vibrato=_.Slight;break;case"Wide":t.vibrato=_.Wide}break;case"LeftFingering":switch(t.isFingering=!0,s.innerText){case"P":t.leftHandFinger=m.Thumb;break;case"I":t.leftHandFinger=m.IndexFinger;break;case"M":t.leftHandFinger=m.MiddleFinger;break;case"A":t.leftHandFinger=m.AnnularFinger;break;case"C":t.leftHandFinger=m.LittleFinger}break;case"RightFingering":switch(t.isFingering=!0,s.innerText){case"P":t.rightHandFinger=m.Thumb;break;case"I":t.rightHandFinger=m.IndexFinger;break;case"M":t.rightHandFinger=m.MiddleFinger;break;case"A":t.rightHandFinger=m.AnnularFinger;break;case"C":t.rightHandFinger=m.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=parseInt(s.innerText)}this._noteById.set(i,t)}parseNoteProperties(e,t,i){let s=!1,a=null,r=null,n=null,o=null,h=null,l=-1,c=-1;for(let d of e.childNodes)if(d.nodeType===Pe.Element&&"Property"===d.localName){switch(d.getAttribute("name")){case"String":t.string=parseInt(d.findChildElement("String").innerText)+1;break;case"Fret":t.fret=parseInt(d.findChildElement("Fret").innerText);break;case"Element":l=parseInt(d.findChildElement("Element").innerText);break;case"Variation":c=parseInt(d.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(i,!0);break;case"HarmonicType":let e=d.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=y.None;break;case"Natural":t.harmonicType=y.Natural;break;case"Artificial":t.harmonicType=y.Artificial;break;case"Pinch":t.harmonicType=y.Pinch;break;case"Tap":t.harmonicType=y.Tap;break;case"Semi":t.harmonicType=y.Semi;break;case"Feedback":t.harmonicType=y.Feedback}break;case"HarmonicFret":let u=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":s=!0;break;case"BendOriginValue":a||(a=new U(0,0)),a.value=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new U(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 U(U.MaxPosition,0)),h.value=this.toBendValue(parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new U(0,0)),h.offset=this.toBendOffset(parseFloat(d.findChildElement("Float").innerText));break;case"HopoOrigin":d.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":let p=parseInt(d.findChildElement("Flags").innerText);1&p?t.slideOutType=w.Shift:2&p?t.slideOutType=w.Legato:4&p?t.slideOutType=w.OutDown:8&p&&(t.slideOutType=w.OutUp),16&p?t.slideInType=S.IntoFromBelow:32&p&&(t.slideInType=S.IntoFromAbove),64&p?t.slideOutType=w.PickSlideDown:128&p&&(t.slideOutType=w.PickSlideUp)}}s&&(a||(a=new U(0,0)),h||(h=new U(U.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new U(n,r)),o&&r&&t.addBendPoint(new U(o,r)),n||o||!r||t.addBendPoint(new U(U.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==c&&(t.percussionArticulation=K.articulationFromElementVariation(l,c))}parseConcertPitch(e,t){const i=e.findChildElement("Pitch");if(i)for(let e of i.childNodes)if(e.nodeType===Pe.Element&&"Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=b.ForceDoubleSharp;break;case"#":t.accidentalMode=b.ForceSharp;break;case"b":t.accidentalMode=b.ForceFlat;break;case"bb":t.accidentalMode=b.ForceDoubleFlat}}toBendValue(e){return e*mt.BendPointValueFactor|0}toBendOffset(e){return e*mt.BendPointPositionFactor}parseRhythms(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){let t=new gt,i=e.getAttribute("id");t.id=i;for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"NoteValue":switch(i.innerText){case"Long":t.value=p.QuadrupleWhole;break;case"DoubleWhole":t.value=p.DoubleWhole;break;case"Whole":t.value=p.Whole;break;case"Half":t.value=p.Half;break;case"Quarter":t.value=p.Quarter;break;case"Eighth":t.value=p.Eighth;break;case"16th":t.value=p.Sixteenth;break;case"32nd":t.value=p.ThirtySecond;break;case"64th":t.value=p.SixtyFourth;break;case"128th":t.value=p.OneHundredTwentyEighth;break;case"256th":t.value=p.TwoHundredFiftySixth}break;case"PrimaryTuplet":t.tupletNumerator=parseInt(i.getAttribute("num")),t.tupletDenominator=parseInt(i.getAttribute("den"));break;case"AugmentationDot":t.dots=parseInt(i.getAttribute("count"))}this._rhythmById.set(i,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 i=0,s=0;i<e.length&&s<this.score.tracks.length;i++){let a=e[i];if(a!==mt.InvalidId){let e=this._barsById.get(a),i=this.score.tracks[s],r=i.staves[t];if(r.addBar(e),this._voicesOfBar.has(a))for(let t of this._voicesOfBar.get(a))if(t!==mt.InvalidId){let i=this._voiceById.get(t);if(e.addVoice(i),this._beatsOfVoice.has(t))for(let e of this._beatsOfVoice.get(t))if(e!==mt.InvalidId){let t=re.clone(this._beatById.get(e));i.addBeat(t);let s=this._rhythmOfBeat.get(e),a=this._rhythmById.get(s);if(t.duration=a.value,t.dots=a.dots,t.tupletNumerator=a.tupletNumerator,t.tupletDenominator=a.tupletDenominator,this._notesOfBeat.has(e))for(let i of this._notesOfBeat.get(e))if(i!==mt.InvalidId){const e=se.clone(this._noteById.get(i));r.isPercussion?(e.fret=-1,e.string=-1):e.percussionArticulation=-1,t.addNote(e),this._tappedNotes.has(i)&&(t.tap=!0)}}}else{let t=new _e;e.addVoice(t);let i=new oe;i.isEmpty=!0,i.duration=p.Quarter,t.addBeat(i)}t===i.staves.length-1?(s++,t=0):t++}else s++}}for(let e of this._tracksMapping){if(!e)continue;let t=this._tracksById.get(e),i=!1;for(const e of t.staves)if(e.isPercussion){i=!0;break}if(i||(t.percussionArticulations=[]),this._automationsPerTrackIdAndBarIndex.has(e)){const i=this._automationsPerTrackIdAndBarIndex.get(e);for(const[e,s]of i)if(t.staves.length>0&&e<t.staves[0].bars.length){const i=t.staves[0].bars[e];if(i.voices.length>0&&i.voices[0].beats.length>0){const e=i.voices[0].beats[0];for(const t of s)e.automations.push(t)}}}}for(const[e,t]of this._masterTrackAutomations){let i=this.score.masterBars[e];for(let s=0,a=t.length;s<a;s++){let a=t[s];a.type===r.Tempo&&(0===e&&(this.score.tempo=0|a.value,a.text&&(this.score.tempoLabel=a.text)),i.tempoAutomation=a)}}}}mt.InvalidId="-1",mt.BendPointPositionFactor=U.MaxPosition/100,mt.BendPointValueFactor=.04;class yt{constructor(){this.isMultiRest=!1,this.trackViewGroups=[]}}class bt{constructor(){this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class St{apply(e){if(this.scoreViews.length>0){let t=0;for(let i of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){const s=e.tracks[t];for(const e of s.staves)e.showTablature=i.showTablature,e.showStandardNotation=i.showStandardNotation}t++}}}constructor(e){this.scoreViews=[];let t=ke.fromBuffer(e);const i=Te.readInt32BE(t);for(let e=0;e<i;e++){const e=new yt;this.scoreViews.push(e),e.isMultiRest=at.gpReadBool(t);const i=Te.readInt32BE(t);for(let s=0;s<i;s++){let i=t.readByte();0===i&&(i=1);let s=new bt;s.showStandardNotation=!!(1&i),s.showTablature=!!(2&i),s.showSlash=!!(4&i),e.trackViewGroups.push(s)}}}static writeForScore(e){const t=ke.withCapacity(128),i=[new yt];for(const t of e.tracks){const e=new bt;e.showStandardNotation=t.staves[0].showStandardNotation,e.showTablature=t.staves[0].showTablature,i[0].trackViewGroups.push(e);const s=new yt;s.trackViewGroups.push(e),i.push(s)}Te.writeInt32BE(t,i.length);for(const e of i){t.writeByte(e.isMultiRest?1:0),Te.writeInt32BE(t,e.trackViewGroups.length);for(const i of e.trackViewGroups){let e=0;i.showStandardNotation&&(e|=1),i.showTablature&&(e|=2),i.showSlash&&(e|=4),t.writeByte(e)}}return Te.writeInt32BE(t,1),t.toArray()}}class wt{}class _t extends wt{constructor(e){super(),this.n=e}}class Bt extends wt{constructor(e,t){super(),this.left=e,this.right=t}}class Tt extends wt{constructor(e,t){super(),this.n=e,this.table=t}}class kt{static make(e,t,i,s){let a=[],r=[];if(s>32)throw new fe("Invalid huffman");for(let e=0;e<s;e++)a.push(0),r.push(0);for(let r=0;r<i;r++){let i=e[r+t];if(i>=s)throw new fe("Invalid huffman");a[i]++}let n=0;for(let e=1;e<s-1;e++)n=n+a[e]<<1,r[e]=n;let o=new Map;for(let s=0;s<i;s++){let i=e[s+t];if(0!==i){let e=r[i-1];r[i-1]=e+1,o.set(e<<5|i,s)}}return kt.treeCompress(new Bt(kt.treeMake(o,s,0,1),kt.treeMake(o,s,1,1)))}static treeMake(e,t,i,s){if(s>t)throw new fe("Invalid huffman");let a=i<<5|s;return e.has(a)?new _t(e.get(a)):(i<<=1,s+=1,new Bt(kt.treeMake(e,t,i,s),kt.treeMake(e,t,1|i,s)))}static treeCompress(e){let t=kt.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof Bt)return new Bt(kt.treeCompress(e.left),kt.treeCompress(e.right));throw new fe("assert")}let i=1<<t,s=[];for(let e=0;e<i;e++)s.push(new _t(-1));return kt.treeWalk(s,0,0,t,e),new Tt(t,s)}static treeWalk(e,t,i,s,a){a instanceof Bt&&s>0?(kt.treeWalk(e,t,i+1,s-1,a.left),kt.treeWalk(e,t|1<<i,i+1,s-1,a.right)):e[t]=kt.treeCompress(a)}static treeDepth(e){if(e instanceof _t)return 0;if(e instanceof Tt)throw new fe("assert");if(e instanceof Bt){let t=kt.treeDepth(e.left),i=kt.treeDepth(e.right);return 1+(t<i?t:i)}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"}(Fe||(Fe={}));class vt{constructor(){this.buffer=new Uint8Array(vt.BufferSize),this.pos=0}slide(){let e=new Uint8Array(vt.BufferSize);this.pos-=vt.Size,e.set(this.buffer.subarray(vt.Size,vt.Size+this.pos),0),this.buffer=e}addBytes(e,t,i){this.pos+i>vt.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+i),this.pos),this.pos+=i}addByte(e){this.pos===vt.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}vt.Size=32768,vt.BufferSize=65536;class xt{static buildFixedHuffman(){let e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return kt.make(e,0,288,10)}constructor(e){this._nbits=0,this._bits=0,this._state=Fe.Block,this._isFinal=!1,this._huffman=xt._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new vt,this._input=e;for(let e=0;e<19;e++)this._lengths.push(-1)}readBytes(e,t,i){if(this._needed=i,this._outpos=t,this._output=e,i>0)for(;this.inflateLoop(););return i-this._needed}inflateLoop(){switch(this._state){case Fe.Head:let e=this._input.readByte();if(8!==(15&e))throw new fe("Invalid data");let t=this._input.readByte(),i=!!(32&t);if(((e<<8)+t)%31!=0)throw new fe("Invalid data");if(i)throw new fe("Unsupported dictionary");return this._state=Fe.Block,!0;case Fe.Crc:return this._state=Fe.Done,!0;case Fe.Done:return!1;case Fe.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:if(this._len=Te.readUInt16LE(this._input),Te.readUInt16LE(this._input)!==65535-this._len)throw new fe("Invalid data");this._state=Fe.Flat;let e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=xt._fixedHuffman,this._huffdist=null,this._state=Fe.CData,!0;case 2:let t=this.getBits(5)+257,i=this.getBits(5)+1,s=this.getBits(4)+4;for(let e=0;e<s;e++)this._lengths[xt.CodeLengthsPos[e]]=this.getBits(3);for(let e=s;e<19;e++)this._lengths[xt.CodeLengthsPos[e]]=0;this._huffman=kt.make(this._lengths,0,19,8);let a=[];for(let e=0;e<t+i;e++)a.push(0);return this.inflateLengths(a,t+i),this._huffdist=kt.make(a,t,i,16),this._huffman=kt.make(a,0,t,16),this._state=Fe.CData,!0;default:throw new fe("Invalid data")}case Fe.Flat:{let e=this._len<this._needed?this._len:this._needed,t=Te.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?Fe.Crc:Fe.Block),this._needed>0}case Fe.DistOne:{let e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=Fe.CData),this._needed>0}case Fe.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=Fe.CData),this._needed>0;case Fe.CData:let s=this.applyHuffman(this._huffman);if(s<256)return this.addByte(s),this._needed>0;if(256===s)return this._state=this._isFinal?Fe.Crc:Fe.Block,!0;{s=s-257&255;let e=xt.LenExtraBitsTbl[s];if(-1===e)throw new fe("Invalid data");this._len=xt.LenBaseValTbl[s]+this.getBits(e);let t=this._huffdist,i=t?this.applyHuffman(t):this.getRevBits(5);if(e=xt.DistExtraBitsTbl[i],-1===e)throw new fe("Invalid data");if(this._dist=xt.DistBaseValTbl[i]+this.getBits(e),this._dist>this._window.available())throw new fe("Invalid data");return this._state=1===this._dist?Fe.DistOne:Fe.Dist,!0}}return!1}addDistOne(e){let t=this._window.getLastChar();for(let i=0;i<e;i++)this.addByte(t)}addByte(e){this._window.addByte(e),this._output[this._outpos]=e,this._needed--,this._outpos++}addDist(e,t){this.addBytes(this._window.buffer,this._window.pos-e,t)}getBit(){0===this._nbits&&(this._nbits=8,this._bits=this._input.readByte());let e=!(1&~this._bits);return this._nbits--,this._bits=this._bits>>1,e}getBits(e){for(;this._nbits<e;)this._bits=this._bits|this._input.readByte()<<this._nbits,this._nbits+=8;let t=this._bits&(1<<e)-1;return this._nbits-=e,this._bits=this._bits>>e,t}getRevBits(e){return 0===e?0:this.getBit()?1<<e-1|this.getRevBits(e-1):this.getRevBits(e-1)}resetBits(){this._bits=0,this._nbits=0}addBytes(e,t,i){this._window.addBytes(e,t,i),this._output.set(e.subarray(t,t+i),this._outpos),this._needed-=i,this._outpos+=i}inflateLengths(e,t){let i=0,s=0;for(;i<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:s=a,e[i]=a,i++;break;case 16:let r=i+3+this.getBits(2);if(r>t)throw new fe("Invalid data");for(;i<r;)e[i]=s,i++;break;case 17:if(i+=3+this.getBits(3),i>t)throw new fe("Invalid data");break;case 18:if(i+=11+this.getBits(7),i>t)throw new fe("Invalid data");break;default:throw new fe("Invalid data")}}}applyHuffman(e){if(e instanceof _t)return e.n;if(e instanceof Bt)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof Tt)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new fe("Invalid data")}}xt.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],xt.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],xt.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],xt.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],xt.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],xt._fixedHuffman=xt.buildFixedHuffman();class Nt{constructor(e,t){this.fullName=e;let i=e.lastIndexOf("/");this.fileName=-1===i||i===e.length-1?this.fullName:e.substr(i+1),this.data=t}}Nt.OptionalDataDescriptorSignature=134695760,Nt.CompressionMethodDeflate=8,Nt.LocalFileHeaderSignature=67324752,Nt.CentralFileHeaderSignature=33639248,Nt.EndOfCentralDirSignature=101010256;class Pt{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(Te.readInt32LE(e)!==Nt.LocalFileHeaderSignature)return null;Te.readUInt16LE(e);let t=Te.readUInt16LE(e),i=Te.readUInt16LE(e),s=0!==i;if(s&&i!==Nt.CompressionMethodDeflate)return null;Te.readInt16LE(this._readable),Te.readInt16LE(this._readable),Te.readInt32LE(e),Te.readInt32LE(e);let a,r=Te.readInt32LE(e),n=Te.readInt16LE(e),o=Te.readInt16LE(e),h=Te.toString(Te.readByteArray(e,n),"utf-8");if(e.skip(o),s){let e=ke.empty(),t=new xt(this._readable),i=new Uint8Array(65536);for(;;){let s=t.readBytes(i,0,i.length);if(e.write(i,0,s),s<i.length)break}a=e.toArray()}else a=Te.readByteArray(this._readable,r);if(8&t){Te.readInt32LE(this._readable)===Nt.OptionalDataDescriptorSignature&&Te.readInt32LE(this._readable),Te.readInt32LE(this._readable),Te.readInt32LE(this._readable)}return new Nt(h,a)}}class Et extends O{get name(){return"Guitar Pro 7"}constructor(){super()}readScore(){J.debug(this.name,"Loading ZIP entries");let e,t=new Pt(this.data);try{e=t.read()}catch(e){throw new V("No Zip archive",e)}J.debug(this.name,"Zip entries loaded");let i=null,s=null,a=null;for(let t of e)switch(t.fileName){case"score.gpif":i=Te.toString(t.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=t.data;break;case"PartConfiguration":a=t.data}if(!i)throw new V("No score.gpif found in zip archive");J.debug(this.name,"Start Parsing score.gpif");let r=new mt;r.parseXml(i,this.settings),J.debug(this.name,"score.gpif parsed");let n=r.score;if(s){J.debug(this.name,"Start Parsing BinaryStylesheet"),new ot(s).apply(n),J.debug(this.name,"BinaryStylesheet parsed")}if(a){J.debug(this.name,"Start Parsing Part Configuration"),new St(a).apply(n),J.debug(this.name,"Part Configuration parsed")}return n}}class Ct extends G{constructor(){super(e.AlphaTabErrorType.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,Ct.prototype)}}class Ft{constructor(e){this._currentByte=0,this._position=Ft.ByteSize,this._source=e}readByte(){return this.readBits(8)}readBytes(e){const t=new Uint8Array(e);for(let i=0;i<e;i++)t[i]=255&this.readByte();return t}readBits(e){let t=0,i=e-1;for(;i>=0;)t|=this.readBit()<<i,i--;return t}readBitsReversed(e){let t=0;for(let i=0;i<e;i++)t|=this.readBit()<<i;return t}readBit(){if(this._position>=8){if(this._currentByte=this._source.readByte(),-1===this._currentByte)throw new Ct;this._position=0}const e=this._currentByte>>Ft.ByteSize-this._position-1&1;return this._position++,e}readAll(){let e=ke.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof Ct))throw e}return e.toArray()}}Ft.ByteSize=8;class Lt{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class Mt{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){let t=new Ft(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){let i,s=ke.empty(),a=this.getInteger(e.readBytes(4),0);try{for(;s.length<a;){if(1===e.readBits(1)){let t=e.readBits(4),a=e.readBitsReversed(t),r=e.readBitsReversed(t),n=s.length-a,o=Math.min(a,r);i=s.getBuffer(),s.write(i,n,o)}else{let t=e.readBitsReversed(2);for(let i=0;i<t;i++)s.writeByte(e.readByte())}}}catch(e){if(!(e instanceof Ct))throw e}i=s.getBuffer();let r=t?4:0,n=s.length-r,o=new Uint8Array(n),h=n;return o.set(i.subarray(r,r+h),0),o}readBlock(e){let t=this.readHeader(e);if("BCFZ"===t)this.readUncompressedBlock(this.decompress(e,!0));else{if("BCFS"!==t)throw new V("Unsupported format");this.readUncompressedBlock(e.readAll())}}readUncompressedBlock(e){let t=4096,i=t;for(;i+3<e.length;){if(2===this.getInteger(e,i)){let s=new Lt;s.fileName=this.getString(e,i+4,127),s.fileSize=this.getInteger(e,i+140);let a=!this.fileFilter||this.fileFilter(s.fileName);a&&this.files.push(s);let r=i+148,n=0,o=0,h=a?ke.withCapacity(s.fileSize):null;for(;n=this.getInteger(e,r+4*o++),0!==n;)i=n*t,a&&h.write(e,i,t);if(a){s.data=new Uint8Array(Math.min(s.fileSize,h.length));let e=h.toArray();s.data.set(e.subarray(0,0+s.data.length),0)}}i+=t}}getString(e,t,i){let s="";for(let a=0;a<i;a++){let i=255&e[t+a];if(0===i)break;s+=String.fromCharCode(i)}return s}getInteger(e,t){return e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}}Mt.HeaderBcFs="BCFS",Mt.HeaderBcFz="BCFZ",Mt.ScoreGpif="score.gpif",Mt.BinaryStylesheet="BinaryStylesheet",Mt.PartConfiguration="PartConfiguration";class It extends O{get name(){return"Guitar Pro 6"}constructor(){super()}readScore(){J.debug(this.name,"Loading GPX filesystem");let e=new Mt;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration"),e.load(this.data),J.debug(this.name,"GPX filesystem loaded");let t=null,i=null,s=null;for(let a of e.files)switch(a.fileName){case"score.gpif":t=Te.toString(a.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=a.data;break;case"PartConfiguration":s=a.data}if(!t)throw new V("No score.gpif found in GPX");J.debug(this.name,"Start Parsing score.gpif");let a=new mt;a.parseXml(t,this.settings),J.debug(this.name,"score.gpif parsed");let r=a.score;if(i){J.debug(this.name,"Start Parsing BinaryStylesheet"),new ot(i).apply(r),J.debug(this.name,"BinaryStylesheet parsed")}if(s){J.debug(this.name,"Start Parsing Part Configuration"),new St(s).apply(r),J.debug(this.name,"Part Configuration parsed")}return r}}class Dt extends O{get name(){return"MusicXML"}constructor(){super(),this._currentPartGroup=null,this._trackFirstMeasureNumber=0,this._maxVoices=0,this._currentDirection=null,this._currentChord=null,this._divisionsPerQuarterNote=0,this._voiceOfStaff=new Map,this._isBeamContinue=!1,this._previousBeatWasPulled=!1,this._previousBeat=null}readScore(){this._trackById=new Map,this._partGroups=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._slurStarts=new Map;let e=Te.toString(this.data.readAll(),this.settings.importer.encoding),t=new pt;try{t.parse(e)}catch(e){throw new V("Unsupported format")}return this._score=new pe,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 i=1;i<e.length;i++){let s=e[i];for(let e of s.staves)t.addStaff(e);let a=this._score.tracks.indexOf(s);this._score.tracks.splice(a,1)}}parseDom(e){let t=e.firstElement;if(!t)throw new V("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":break;default:throw new V("Unsupported format")}}parsePartwise(e){for(let t of e.childNodes)if(t.nodeType===Pe.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===Pe.Element&&"work-title"===t.localName)this._score.title=t.innerText}parsePart(e){let t=e.getAttribute("id");if(!this._trackById.has(t)){if(1!==this._trackById.size)return;for(const[e,i]of this._trackById)0!==i.staves.length&&0!==i.staves[0].bars.length||(t=e);if(!this._trackById.has(t))return}let i=this._trackById.get(t),s=!0;this._maxVoices=0;for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"measure"===t.localName)this.parseMeasure(t,i,s)&&(s=!1);for(let e of i.staves)for(let t of e.bars)this.ensureVoices(t)}parseMeasure(e,t,i){if("yes"===e.getAttribute("implicit")&&0===e.getElementsByTagName("note",!1).length)return!1;let s=0;if(i)this._divisionsPerQuarterNote=0,this._trackFirstMeasureNumber=parseInt(e.getAttribute("number")),this._trackFirstMeasureNumber||(this._trackFirstMeasureNumber=0),s=0;else{if(s=parseInt(e.getAttribute("number")),!s)return!1;s-=this._trackFirstMeasureNumber}if(i){let i=e.getElementsByTagName("attributes",!1);if(i.length>0){let e=i[0].getElementsByTagName("staves",!1);if(e.length>0){let i=parseInt(e[0].innerText);t.ensureStaveCount(i)}}}let a=new Array(t.staves.length),r=null;for(let e=t.staves[0].bars.length;e<=s;e++)for(let e=0;e<t.staves.length;e++){let i=new W;if(a[e]=i,t.staves[e].bars.length>0){let s=t.staves[e].bars[t.staves[e].bars.length-1];i.clef=s.clef}r=this.getOrCreateMasterBar(s),t.staves[e].addBar(i),this.ensureVoices(i)}let n=new Map;if(r){let i=!1;for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"note":this.parseNoteBeat(s,a);break;case"forward":this.parseForward(s,a);break;case"direction":this.parseDirection(s,r);break;case"attributes":i||(this.parseAttributes(s,a,r,t),i=!0);break;case"harmony":this.parseHarmony(s,t,n);break;case"sound":break;case"barline":this.parseBarline(s,r)}}return!0}ensureVoices(e){for(;e.voices.length<this._maxVoices;){let t=new _e;e.addVoice(t);let i=new oe;i.isEmpty=!0,i.chordId=this._currentChord,t.addBeat(i)}}getOrCreateBeat(e,t,i){let s=0,a=e.getElementsByTagName("voice",!1);a.length>0&&(s=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,s)}l--,n=l<0?t[0]:l>=t.length?t[t.length-1]:t[l];let c=this.getOrCreateVoice(n,s);return i&&c.beats.length>0||1===c.beats.length&&c.isEmpty?o=c.beats[c.beats.length-1]:(o=new oe,o.isEmpty=!1,c.addBeat(o)),this._isBeamContinue=!1,this._previousBeat=o,o}parseForward(e,t){let i=this.getOrCreateBeat(e,t,!1),s=parseInt(e.findChildElement("duration").innerText)*p.Quarter/this._divisionsPerQuarterNote,a=[p.SixtyFourth,p.ThirtySecond,p.Sixteenth,p.Eighth,p.Quarter,p.Half,p.Whole];for(let e of a)if(s>=e){i.duration=e,s-=e;break}i.isEmpty=!1}parseStaffDetails(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"staff-lines":for(let e of t.staves)e.stringTuning.tunings=new Array(parseInt(i.innerText)).fill(0);break;case"staff-tuning":this.parseStaffTuning(i,t)}for(let e of t.staves)this.isEmptyTuning(e.tuning)&&(e.stringTuning.tunings=[])}parseStaffTuning(e,t){let i=parseInt(e.getAttribute("line")),s="C",a="",r=0;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"tuning-step":s=t.innerText;break;case"tuning-alter":r=parseInt(t.innerText);break;case"tuning-octave":a=t.innerText}let n=Q.getTuningForText(s+a)+r;for(let e of t.staves)e.tuning[e.tuning.length-i]=n}parseHarmony(e,t,i){let s=new he;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"root":s.name=this.parseHarmonyRoot(t);break;case"kind":s.name=s.name+this.parseHarmonyKind(t);break;case"frame":this.parseHarmonyFrame(t,s)}this._currentChord=Q.newGuid();const a=s.uniqueId;i.has(a)&&(s.showDiagram=!1);for(let e of t.staves)e.addChord(this._currentChord,s);i.set(a,s)}parseHarmonyRoot(e){let t="",i="";for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"root-step":t=s.innerText;break;case"root-alter":switch(parseInt(e.innerText)){case-2:i="bb";break;case-1:i="b";break;case 0:i="";break;case 1:i="#";break;case 2:i="##"}}return t+i}parseHarmonyKind(e){const t=e.getAttribute("text");let i="";if(t)i=t;else{switch(e.innerText){case"major":i="";break;case"minor":i="m";break;case"augmented":i="+";break;case"diminished":i="○";break;case"dominant":i="7";break;case"major-seventh":i="7M";break;case"minor-seventh":i="m7";break;case"diminished-seventh":i="○7";break;case"augmented-seventh":i="+7";break;case"half-diminished":i="⍉";break;case"major-minor":i="mMaj";break;case"major-sixth":i="maj6";break;case"minor-sixth":i="m6";break;case"dominant-ninth":i="9";break;case"major-ninth":i="maj9";break;case"minor-ninth":i="m9";break;case"dominant-11th":i="11";break;case"major-11th":i="maj11";break;case"minor-11th":i="m11";break;case"dominant-13th":i="13";break;case"major-13th":i="maj13";break;case"minor-13th":i="m13";break;case"suspended-second":i="sus2";break;case"suspended-fourth":i="sus4"}}return i}parseHarmonyFrame(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"frame-strings":const e=parseInt(i.innerText);t.strings=new Array(e);for(let i=0;i<e;i++)t.strings[i]=-1;break;case"first-fret":t.firstFret=parseInt(i.innerText);break;case"frame-note":let s=null,a=null;for(let e of i.childNodes)switch(e.localName){case"string":s=parseInt(e.innerText);break;case"fret":a=parseInt(e.innerText),s&&a>=0&&(t.strings[s-1]=a);break;case"barre":s&&a&&"start"===e.getAttribute("type")&&t.barreFrets.push(a)}}}parseBarline(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"repeat":this.parseRepeat(i,t);break;case"ending":this.parseEnding(i,t)}}parseEnding(e,t){let i=parseInt(e.getAttribute("number"));i>0&&(--i,t.alternateEndings=t.alternateEndings|1<<i&255)}parseRepeat(e,t){let i=e.getAttribute("direction"),s=parseInt(e.getAttribute("times"));(s<0||isNaN(s))&&(s=2),"backward"===i?t.repeatCount=s:"forward"===i&&(t.isRepeatStart=!0)}parseNoteBeat(e,t){let i=e.getElementsByTagName("chord",!1).length>0,s=this.getOrCreateBeat(e,t,i);!s.chordId&&this._currentChord&&(s.chordId=this._currentChord,this._currentChord=null),this._currentDirection&&(s.text=this._currentDirection,this._currentDirection=null);let a=new ee;s.voice.isEmpty=!1,s.isEmpty=!1,s.addNote(a),s.dots=0;let r=!1;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"grace":s.graceType=f.BeforeBeat,s.duration=p.ThirtySecond;break;case"duration":if(s.isRest&&!r){switch(parseInt(t.innerText)){case 1:s.duration=p.Whole;break;case 2:s.duration=p.Half;break;case 4:default:s.duration=p.Quarter;break;case 8:s.duration=p.Eighth;break;case 16:s.duration=p.Sixteenth;break;case 32:s.duration=p.ThirtySecond;break;case 64:s.duration=p.SixtyFourth}}break;case"tie":this.parseTied(t,a);break;case"cue":case"instrument":case"stem":break;case"type":s.duration=this.getDuration(t.innerText),s.graceType!==f.None&&s.duration<p.Sixteenth&&(s.duration=p.Eighth);break;case"dot":s.dots++;break;case"accidental":this.parseAccidental(t,a);break;case"time-modification":this.parseTimeModification(t,s);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,s,a);break;case"lyric":this.parseLyric(t,s);break;case"pitch":this.parsePitch(t,a);break;case"unpitched":this.parseUnpitched(t,a);break;case"rest":r="yes"===t.getAttribute("measure"),s.isEmpty=!1,s.notes=[],s.duration=p.Whole}if(a.isStringed)for(let e=0;e<s.notes.length;e++)if(s.notes[e].string===a.string&&s.notes[e]!==a){s.removeNote(a);break}}getDuration(e){switch(e){case"256th":case"128th":case"64th":return p.SixtyFourth;case"32nd":return p.ThirtySecond;case"16th":return p.Sixteenth;case"eighth":return p.Eighth;case"quarter":return p.Quarter;case"half":return p.Half;case"long":case"breve":case"whole":return p.Whole}return p.Quarter}parseLyric(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element&&"text"===i.localName)t.text?t.text+=" "+i.innerText:t.text=i.innerText}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=b.ForceSharp;break;case"natural":t.accidentalMode=b.ForceNatural;break;case"flat":t.accidentalMode=b.ForceFlat}}parseTied(e,t){if("start"===e.getAttribute("type"))this._tieStartIds.has(t.id)||(this._tieStartIds.set(t.id,!0),this._tieStarts.push(t));else if("stop"===e.getAttribute("type")&&this._tieStarts.length>0&&!t.isTieDestination){const e=this._tieStarts[0];e.beat.voice.index===t.beat.voice.index&&e.beat.voice.bar.staff.index===t.beat.voice.bar.staff.index&&e.beat.voice.bar.staff.track.index===t.beat.voice.bar.staff.track.index&&(t.isTieDestination=!0,t.tieOrigin=this._tieStarts[0]),this._tieStarts.splice(0,1),this._tieStartIds.delete(t.id)}}parseNotations(e,t,i){for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"articulations":this.parseArticulations(s,i);break;case"tied":this.parseTied(s,i);break;case"slide":case"glissando":"start"===s.getAttribute("type")&&(i.slideOutType=w.Shift);break;case"dynamics":this.parseDynamics(s,t);break;case"technical":this.parseTechnical(s,i);break;case"ornaments":this.parseOrnaments(s,i);break;case"slur":let e=s.getAttribute("number");switch(e||(e="1"),e=t.voice.bar.staff.index+"_"+e,s.getAttribute("type")){case"start":this._slurStarts.set(e,i);break;case"stop":if(this._slurStarts.has(e)){i.isSlurDestination=!0;let t=this._slurStarts.get(e);t.slurDestination=i,i.slurOrigin=t}}}}parseOrnaments(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element&&"tremolo"===i.localName){switch(parseInt(i.innerText)){case 1:t.beat.tremoloSpeed=p.Eighth;break;case 2:t.beat.tremoloSpeed=p.Sixteenth;break;case 3:t.beat.tremoloSpeed=p.ThirtySecond}}}parseTechnical(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"string":t.string=parseInt(i.innerText),-2147483648!==t.string&&(t.string=t.beat.voice.bar.staff.tuning.length-t.string+1);break;case"fret":t.fret=parseInt(i.innerText);break;case"down-bow":t.beat.pickStroke=N.Down;break;case"up-bow":t.beat.pickStroke=N.Up}-2147483648!==t.string&&-2147483648!==t.fret||(t.string=-1,t.fret=-1)}parseArticulations(e,t){for(let i of e.childNodes)switch(i.localName){case"accent":t.accentuated=a.Normal;break;case"strong-accent":t.accentuated=a.Heavy;break;case"staccato":case"detached-legato":t.isStaccato=!0}}parseDynamics(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"p":t.dynamics=g.P;break;case"pp":t.dynamics=g.PP;break;case"ppp":t.dynamics=g.PPP;break;case"f":t.dynamics=g.F;break;case"ff":t.dynamics=g.FF;break;case"fff":t.dynamics=g.FFF;break;case"mp":t.dynamics=g.MP;break;case"mf":t.dynamics=g.MF}}parseTimeModification(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"actual-notes":t.tupletNumerator=parseInt(i.innerText);break;case"normal-notes":t.tupletDenominator=parseInt(i.innerText)}}parseUnpitched(e,t){let i="",s=0,a=0;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"display-step":i=t.innerText;break;case"display-alter":s=parseInt(t.innerText);break;case"display-octave":a=parseInt(t.innerText)}let r=12*a+Q.getToneForText(i)+s;t.octave=r/12|0,t.tone=r-12*t.octave}parsePitch(e,t){let i="",s=0,a=0;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"step":i=t.innerText;break;case"alter":s=parseFloat(t.innerText),isNaN(s)&&(s=0);break;case"octave":a=parseInt(t.innerText)+1}let r=12*a+Q.getToneForText(i)+(0|s);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 i=e.voices.length;i<=t;i++)e.addVoice(new _e);return this._maxVoices=Math.max(this._maxVoices,e.voices.length),e.voices[t]}parseDirection(e,t){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"sound":let e=i.getAttribute("tempo");if(e){let i=new H;i.isLinear=!0,i.type=r.Tempo,i.value=parseInt(e),t.tempoAutomation=i,0===t.index&&(t.score.tempo=i.value)}break;case"direction-type":let s=i.firstElement;switch(s.localName){case"words":this._currentDirection=s.innerText;break;case"metronome":this.parseMetronome(s,t)}}}parseMetronome(e,t){let i=p.Quarter,s=120;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"beat-unit":i=this.getDuration(t.innerText);break;case"per-minute":s=parseInt(t.innerText)}let a=new H;a.type=r.Tempo,a.value=s*(i/4|0),t.tempoAutomation=a,0===t.index&&(t.score.tempo=a.value)}parseAttributes(e,t,i,s){let a=0,r=!1;for(let n of e.childNodes)if(n.nodeType===Pe.Element)switch(n.localName){case"divisions":this._divisionsPerQuarterNote=parseInt(n.innerText);break;case"key":this.parseKey(n,i);break;case"time":this.parseTime(n,i),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,s);break;case"transpose":this.parseTranspose(n,s)}r||(i.timeSignatureCommon=!0)}parseTranspose(e,t){let i=0;for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"chromatic":i+=parseInt(t.innerText);break;case"octave-change":i+=12*parseInt(t.innerText)}for(let e of t.staves)e.transpositionPitch=i}parseClef(e,t){let i="s",s=0;for(let a of e.childNodes)if(a.nodeType===Pe.Element)switch(a.localName){case"sign":i=a.innerText.toLowerCase();break;case"line":s=parseInt(a.innerText);break;case"clef-octave-change":switch(parseInt(a.innerText)){case-2:t.clefOttava=o._15mb;break;case-1:t.clefOttava=o._8vb;break;case 1:t.clefOttava=o._8va;break;case 2:t.clefOttava=o._15mb}}switch(i){case"g":default:t.clef=n.G2;break;case"f":t.clef=n.F4;break;case"c":t.clef=3===s?n.C3:n.C4;break;case"percussion":t.clef=n.Neutral,t.staff.isPercussion=!0;break;case"tab":t.clef=n.G2,t.staff.showTablature=!0}}parseTime(e,t){"common"===e.getAttribute("symbol")&&(t.timeSignatureCommon=!0);let i=!1,s=!1;for(let a of e.childNodes)if(a.nodeType===Pe.Element){let e=a.innerText;switch(a.localName){case"beats":i||(-1===e.indexOf("+")?t.timeSignatureNumerator=parseInt(e):t.timeSignatureNumerator=4,i=!0);break;case"beat-type":s||(-1===e.indexOf("+")?t.timeSignatureDenominator=parseInt(e):t.timeSignatureDenominator=4,s=!0)}}}parseKey(e,t){let i=-2147483648,s="";for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"fifths":i=parseInt(t.innerText);break;case"key-step":case"key-alter":break;case"mode":s=t.innerText}t.keySignature=-7<=i&&i<=7?i:M.C,t.keySignatureType="minor"===s?D.Minor:D.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 ce;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===Pe.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===Pe.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"),i=new we;i.ensureStaveCount(1),i.staves[0].showStandardNotation=!0,this._trackById.set(t,i),this._score.addTrack(i),this._currentPartGroup&&this._partGroups.get(this._currentPartGroup).push(i);for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"part-name":i.name=t.innerText;break;case"part-abbreviation":i.shortName=t.innerText;break;case"midi-instrument":this.parseMidiInstrument(t,i)}this.isEmptyTuning(i.staves[0].tuning)&&(i.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 i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"midi-channel":t.playbackInfo.primaryChannel=parseInt(i.innerText);break;case"midi-program":t.playbackInfo.program=parseInt(i.innerText);break;case"volume":t.playbackInfo.volume=Math.floor(parseInt(i.innerText)/100*16);break;case"pan":t.playbackInfo.balance=Math.max(0,Math.min(16,Math.floor((parseInt(i.innerText)+90)/180*16)))}}}!function(e){e[e.SingleTrackMultiChannel=0]="SingleTrackMultiChannel",e[e.MultiTrack=1]="MultiTrack"}(Le||(Le={}));class At{constructor(){this.events=[]}addEvent(e){if(0===this.events.length||e.tick>=this.events[this.events.length-1].tick)this.events.push(e);else{let t=this.events.length;for(;t>0;){if(!(this.events[t-1].tick>e.tick))break;t--}this.events.splice(t,0,e)}}writeTo(e){let t=ke.empty(),i=0;for(let e of this.events){let s=e.tick-i;Rt.writeVariableInt(t,s),e.writeTo(t),i=e.tick}const s=new Uint8Array([77,84,114,107]);e.write(s,0,s.length);let a=t.toArray();Te.writeInt32BE(e,a.length),e.write(a,0,a.length)}}class Rt{constructor(){this.format=Le.SingleTrackMultiChannel,this.division=z.QuarterTime,this.tracks=[]}get events(){if(1==this.tracks.length)return this.tracks[0].events;{const e=[];for(const e of this.tracks)this.events.push(...e.events);return e.sort(((e,t)=>e.tick-t.tick)),e}}ensureTracks(e){for(;this.tracks.length<e;)this.tracks.push(new At)}addEvent(e){this.format==Le.SingleTrackMultiChannel?(this.ensureTracks(1),this.tracks[0].addEvent(e)):(this.ensureTracks(e.track+1),this.tracks[e.track].addEvent(e))}toBinary(){let e=ke.empty();return this.writeTo(e),e.toArray()}writeTo(e){let t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),Te.writeInt32BE(e,6),Te.writeInt16BE(e,this.format),Te.writeInt16BE(e,this.tracks.length),Te.writeInt16BE(e,this.division);for(const t of this.tracks)t.writeTo(e)}static writeVariableInt(e,t){let i=new Uint8Array(4),s=0;do{i[s++]=127&t,t>>=7}while(t>0);for(;s>0;)s--,s>0?e.writeByte(128|i[s]):e.writeByte(i[s])}}!function(e){e[e.TimeSignature=88]="TimeSignature",e[e.NoteOn=128]="NoteOn",e[e.NoteOff=144]="NoteOff",e[e.ControlChange=176]="ControlChange",e[e.ProgramChange=192]="ProgramChange",e[e.TempoChange=81]="TempoChange",e[e.PitchBend=224]="PitchBend",e[e.PerNotePitchBend=96]="PerNotePitchBend",e[e.EndOfTrack=47]="EndOfTrack",e[e.AlphaTabRest=241]="AlphaTabRest",e[e.AlphaTabMetronome=242]="AlphaTabMetronome",e[e.SystemExclusive=240]="SystemExclusive",e[e.SystemExclusive2=247]="SystemExclusive2",e[e.Meta=255]="Meta"}(Me||(Me={}));class Ot{constructor(e,t,i){this.track=e,this.tick=t,this.type=i}get command(){return this.type}get message(){return 0}get data1(){return 0}get data2(){return 0}}class Gt extends Ot{constructor(e,t,i,s,a,r){super(e,t,Me.TimeSignature),this.track=e,this.tick=t,this.numerator=i,this.denominatorIndex=s,this.midiClocksPerMetronomeClick=a,this.thirtySecondNodesInQuarter=r}writeTo(e){e.writeByte(255),e.writeByte(88),Rt.writeVariableInt(e,4),e.writeByte(255&this.numerator),e.writeByte(255&this.denominatorIndex),e.writeByte(255&this.midiClocksPerMetronomeClick),e.writeByte(255&this.thirtySecondNodesInQuarter)}}class Vt extends Ot{constructor(e,t,i){super(e,t,i)}writeTo(e){e.writeByte(240);const t=ke.withCapacity(16);t.writeByte(Vt.AlphaTabManufacturerId),this.writeEventData(t),t.writeByte(247),Rt.writeVariableInt(e,t.length),t.copyTo(e)}}Vt.AlphaTabManufacturerId=125,Vt.MetronomeEventId=0,Vt.RestEventId=1;class Ht extends Vt{constructor(e,t,i,s,a){super(e,t,Me.AlphaTabMetronome),this.isMetronome=!0,this.metronomeNumerator=i,this.metronomeDurationInMilliseconds=a,this.metronomeDurationInTicks=s}writeEventData(e){e.writeByte(Vt.MetronomeEventId),e.writeByte(this.metronomeNumerator),Te.writeInt32LE(e,this.metronomeDurationInTicks),Te.writeInt32LE(e,this.metronomeDurationInMilliseconds)}}class Wt extends Vt{constructor(e,t,i){super(e,t,Me.AlphaTabRest),this.channel=i}writeEventData(e){e.writeByte(Vt.RestEventId),e.writeByte(this.channel)}}class zt extends Ot{constructor(e,t,i,s,a,r){super(e,t,i),this.channel=s,this.noteKey=a,this.noteVelocity=r}get data1(){return this.noteKey}get data2(){return this.noteVelocity}}class Ut extends zt{constructor(e,t,i,s,a){super(e,t,Me.NoteOn,i,s,a)}writeTo(e){e.writeByte(15&this.channel|144),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class Xt extends zt{constructor(e,t,i,s,a){super(e,t,Me.NoteOff,i,s,a)}writeTo(e){e.writeByte(15&this.channel|128),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class Yt extends Ot{constructor(e,t,i,s,a){super(e,t,Me.ControlChange),this.channel=i,this.controller=s,this.value=a}writeTo(e){e.writeByte(15&this.channel|176),e.writeByte(255&this.controller),e.writeByte(255&this.value)}get data1(){return this.controller}get data2(){return this.value}}class qt extends Ot{constructor(e,t,i,s){super(e,t,Me.ProgramChange),this.channel=i,this.program=s}writeTo(e){e.writeByte(15&this.channel|192),e.writeByte(255&this.program)}get data1(){return this.program}}class Jt extends Ot{constructor(e,t){super(0,e,Me.TempoChange),this.microSecondsPerQuarterNote=t}writeTo(e){e.writeByte(255),e.writeByte(81),e.writeByte(3),e.writeByte(this.microSecondsPerQuarterNote>>16&255),e.writeByte(this.microSecondsPerQuarterNote>>8&255),e.writeByte(255&this.microSecondsPerQuarterNote)}}class jt extends Ot{constructor(e,t,i,s){super(e,t,Me.PitchBend),this.channel=i,this.value=s}writeTo(e){e.writeByte(15&this.channel|224),e.writeByte(127&this.value),e.writeByte(this.value>>7&127)}get data1(){return 127&this.value}get data2(){return this.value>>7&127}}class Qt extends Ot{constructor(e,t,i,s,a){super(e,t,Me.PerNotePitchBend),this.channel=i,this.noteKey=s,this.value=a}writeTo(t){throw new G(e.AlphaTabErrorType.General,"Note Bend (Midi2.0) events cannot be exported to SMF1.0")}}class $t extends Ot{constructor(e,t){super(e,t,Me.EndOfTrack)}writeTo(e){e.writeByte(255),e.writeByte(47),e.writeByte(0)}}class Kt{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event.type==Me.AlphaTabMetronome}static newMetronomeEvent(e,t,i,s,a){const r=new Ht(0,t,i,s,a);return new Kt(e,r)}}class Zt{}Zt.DefaultChannelCount=17,Zt.MetronomeChannel=Zt.DefaultChannelCount-1,Zt.AudioChannels=2,Zt.MinVolume=0,Zt.MinProgram=0,Zt.MaxProgram=127,Zt.MinPlaybackSpeed=.125,Zt.MaxPlaybackSpeed=8,Zt.MaxPitchWheel=16384,Zt.MaxPitchWheel20=4294967296,Zt.DefaultPitchWheel=Zt.MaxPitchWheel/2,Zt.MicroBufferCount=32,Zt.MicroBufferSize=64;class ei{constructor(e,t,i){this.bpm=e,this.ticks=t,this.time=i}}class ti{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=z.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class ii{get isPlayingMain(){return this._currentState==this._mainState}get isPlayingOneTimeMidi(){return this._currentState==this._oneTimeState}get isPlayingCountIn(){return this._currentState==this._countInState}constructor(e){this._oneTimeState=null,this._countInState=null,this.isLooping=!1,this.playbackSpeed=1,this._synthesizer=e,this._mainState=new ti,this._currentState=this._mainState}get mainPlaybackRange(){return this._mainState.playbackRange}set mainPlaybackRange(e){this._mainState.playbackRange=e,e&&(this._mainState.playbackRangeStartTime=this.tickPositionToTimePositionWithSpeed(this._mainState,e.startTick,1),this._mainState.playbackRangeEndTime=this.tickPositionToTimePositionWithSpeed(this._mainState,e.endTick,1))}get currentTime(){return this._currentState.currentTime/this.playbackSpeed}get currentEndTick(){return this._currentState.endTick}get currentEndTime(){return this._currentState.endTime/this.playbackSpeed}mainSeek(e){if(e*=this.playbackSpeed,this.mainPlaybackRange&&(e<this._mainState.playbackRangeStartTime?e=this._mainState.playbackRangeStartTime:e>this._mainState.playbackRangeEndTime&&(e=this._mainState.playbackRangeEndTime)),e>this._mainState.currentTime)this.mainSilentProcess(e-this._mainState.currentTime);else if(e<this._mainState.currentTime){if(this._mainState.currentTime=0,this._mainState.eventIndex=0,this.isPlayingMain){let e=this._synthesizer.metronomeVolume;this._synthesizer.noteOffAll(!0),this._synthesizer.resetSoft(),this._synthesizer.setupMetronomeChannel(e)}this.mainSilentProcess(e)}}mainSilentProcess(e){if(e<=0)return;let t=Date.now(),i=this._mainState.currentTime+e;if(this.isPlayingMain)for(;this._mainState.currentTime<i;)this.fillMidiEventQueueLimited(i-this._mainState.currentTime)&&this._synthesizer.synthesizeSilent(Zt.MicroBufferSize);this._mainState.currentTime=i;let s=Date.now()-t;J.debug("Sequencer","Silent seek finished in "+s+"ms (main)")}loadOneTimeMidi(e){this._oneTimeState=this.createStateFromFile(e),this._currentState=this._oneTimeState}loadMidi(e){this._mainState=this.createStateFromFile(e),this._currentState=this._mainState}createStateFromFile(e){const t=new ti;t.tempoChanges=[],t.division=e.division,t.eventIndex=0,t.currentTime=0,t.synthData=[];let i=120,s=0,a=0,r=0,n=0,o=0,h=0,l=0,c=0;for(let d of e.events){let u=new Kt(t.synthData.length,d);t.synthData.push(u);let p=d.tick-c;if(s+=p,a+=p*(6e4/(i*e.division)),u.time=a,c=d.tick,n>0)for(;h<s;){let e=Kt.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(d.type===Me.TempoChange){i=6e7/d.microSecondsPerQuarterNote,t.tempoChanges.push(new ei(i,s,a)),o=n*(6e4/(i*e.division))}else if(d.type===Me.TimeSignature){let s=d,a=Math.pow(2,s.denominatorIndex);r=s.numerator,n=t.division*(4/a)|0,o=n*(6e4/(i*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=s.numerator,t.firstTimeSignatureDenominator=a)}else if(d.type===Me.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=s,t}fillMidiEventQueue(){return this.fillMidiEventQueueLimited(-1)}fillMidiEventQueueLimited(e){let t=Zt.MicroBufferSize/this._synthesizer.outSampleRate*1e3*this.playbackSpeed,i=this.internalEndTime;e>0&&(e<t&&(t=e),i=Math.min(this.internalEndTime,this._currentState.currentTime+e));let s=!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<i;)this._synthesizer.dispatchEvent(this._currentState.synthData[this._currentState.eventIndex]),this._currentState.eventIndex++,s=!0;return s}mainTickPositionToTimePosition(e){return this.tickPositionToTimePositionWithSpeed(this._mainState,e,this.playbackSpeed)}mainTimePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(this._mainState,e,this.playbackSpeed)}currentTimePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(this._currentState,e,this.playbackSpeed)}tickPositionToTimePositionWithSpeed(e,t,i){let s=0,a=120,r=0;for(const i of e.tempoChanges){if(t<i.ticks)break;s=i.time,a=i.bpm,r=i.ticks}return s+=(t-=r)*(6e4/(a*e.division)),s/i}timePositionToTickPositionWithSpeed(e,t,i){t*=i;let s=0,a=120,r=0;for(const i of e.tempoChanges){if(t<i.time)break;s=i.ticks,a=i.bpm,r=i.time}return s+=(t-=r)/(6e4/(a*e.division))|0,s+1}get internalEndTime(){return this.isPlayingMain&&this.mainPlaybackRange?this._currentState.playbackRangeEndTime:this._currentState.endTime}get isFinished(){return this._currentState.currentTime>=this.internalEndTime}stop(){this.isPlayingMain&&this.mainPlaybackRange?this._currentState.currentTime=this.mainPlaybackRange.startTick:this._currentState.currentTime=0,this._currentState.eventIndex=0}resetOneTimeMidi(){this._oneTimeState=null,this._currentState=this._mainState}resetCountIn(){this._countInState=null,this._currentState=this._mainState}startCountIn(){this.generateCountInMidi(),this._currentState=this._countInState,this.stop(),this._synthesizer.noteOffAll(!0)}generateCountInMidi(){const e=new ti;e.division=this._mainState.division;let t=120,i=4,s=4;0===this._mainState.eventIndex?(t=this._mainState.tempoChanges[0].bpm,i=this._mainState.firstTimeSignatureNumerator,s=this._mainState.firstTimeSignatureDenominator):(t=this._synthesizer.currentTempo,i=this._synthesizer.timeSignatureNumerator,s=this._synthesizer.timeSignatureDenominator),e.tempoChanges.push(new ei(t,0,0));let a=e.division*(4/s)|0,r=a*(6e4/(t*this._mainState.division)),n=0,o=0;for(let t=0;t<i;t++){let i=Kt.newMetronomeEvent(e.synthData.length,n,t,a,r);e.synthData.push(i),i.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"}(Ie||(Ie={}));class si{constructor(e,t){this.state=e,this.stopped=t}}class ai{constructor(e,t,i,s,a){this.currentTime=e,this.endTime=t,this.currentTick=i,this.endTick=s,this.isSeek=a}}class ri{constructor(){this.id="",this.size=0}static load(e,t,i){if(e&&ri.HeaderSize>e.size)return!1;if(i.position+ri.HeaderSize>=i.length)return!1;if(t.id=Te.read8BitStringLength(i,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=Te.readUInt32LE(i),e&&ri.HeaderSize+t.size>e.size)return!1;e&&(e.size-=ri.HeaderSize+t.size);let s="RIFF"===t.id,a="LIST"===t.id;return(!s||!e)&&(!s&&!a||(t.id=Te.read8BitStringLength(i,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}ri.HeaderSize=8;class ni{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 ri,i=new ri;if(!ri.load(null,t,e)||"sfbk"!==t.id)throw new fe("Soundfont is not a valid Soundfont2 file");for(;ri.load(t,i,e);){let t=new ri;if("pdta"===i.id)for(;ri.load(i,t,e);)switch(t.id){case"phdr":for(let i=0,s=t.size/pi.SizeInFile|0;i<s;i++)this.phdrs.push(new pi(e));break;case"pbag":for(let i=0,s=t.size/di.SizeInFile|0;i<s;i++)this.pbags.push(new di(e));break;case"pmod":for(let i=0,s=t.size/gi.SizeInFile|0;i<s;i++)this.pmods.push(new gi(e));break;case"pgen":for(let i=0,s=t.size/ui.SizeInFile|0;i<s;i++)this.pgens.push(new ui(e));break;case"inst":for(let i=0,s=t.size/ci.SizeInFile|0;i<s;i++)this.insts.push(new ci(e));break;case"ibag":for(let i=0,s=t.size/oi.SizeInFile|0;i<s;i++)this.ibags.push(new oi(e));break;case"imod":for(let i=0,s=t.size/hi.SizeInFile|0;i<s;i++)this.imods.push(new hi(e));break;case"igen":for(let i=0,s=t.size/li.SizeInFile|0;i<s;i++)this.igens.push(new li(e));break;case"shdr":for(let i=0,s=t.size/fi.SizeInFile|0;i<s;i++)this.sHdrs.push(new fi(e));break;default:e.position+=t.size}else if("sdta"===i.id)for(;ri.load(i,t,e);)if("smpl"===t.id)this.fontSamples=ni.loadSamples(t,e);else e.position+=t.size;else e.position+=i.size}}static loadSamples(e,t){let i=e.size/2|0;const s=new Float32Array(i);let a=0;const r=new Uint8Array(16384);for(;i>0;){let e=Math.min(i,r.length/2|0);t.read(r,0,2*e);for(let t=0;t<e;t++){const e=Be.int32ToInt16(r[2*t+1]<<8|r[2*t]);s[a+t]=e/32767}i-=e,a+=e}return s}}class oi{constructor(e){this.instGenNdx=Te.readUInt16LE(e),this.instModNdx=Te.readUInt16LE(e)}}oi.SizeInFile=4;class hi{constructor(e){this.modSrcOper=Te.readUInt16LE(e),this.modDestOper=Te.readUInt16LE(e),this.modAmount=Te.readInt16LE(e),this.modAmtSrcOper=Te.readUInt16LE(e),this.modTransOper=Te.readUInt16LE(e)}}hi.SizeInFile=10;class li{constructor(e){this.genOper=Te.readUInt16LE(e),this.genAmount=new mi(e)}}li.SizeInFile=4;class ci{constructor(e){this.instName=Te.read8BitStringLength(e,20),this.instBagNdx=Te.readUInt16LE(e)}}ci.SizeInFile=22;class di{constructor(e){this.genNdx=Te.readUInt16LE(e),this.modNdx=Te.readUInt16LE(e)}}di.SizeInFile=4;class ui{constructor(e){this.genOper=Te.readUInt16LE(e),this.genAmount=new mi(e)}}ui.SizeInFile=4,ui.GenInstrument=41,ui.GenKeyRange=43,ui.GenVelRange=44,ui.GenSampleId=53;class pi{constructor(e){this.presetName=Te.read8BitStringLength(e,20),this.preset=Te.readUInt16LE(e),this.bank=Te.readUInt16LE(e),this.presetBagNdx=Te.readUInt16LE(e),this.library=Te.readUInt32LE(e),this.genre=Te.readUInt32LE(e),this.morphology=Te.readUInt32LE(e)}}pi.SizeInFile=38;class gi{constructor(e){this.modSrcOper=Te.readUInt16LE(e),this.modDestOper=Te.readUInt16LE(e),this.modAmount=Te.readUInt16LE(e),this.modAmtSrcOper=Te.readUInt16LE(e),this.modTransOper=Te.readUInt16LE(e)}}gi.SizeInFile=10;class fi{constructor(e){this.sampleName=Te.read8BitStringLength(e,20),this.start=Te.readUInt32LE(e),this.end=Te.readUInt32LE(e),this.startLoop=Te.readUInt32LE(e),this.endLoop=Te.readUInt32LE(e),this.sampleRate=Te.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=Te.readSInt8(e),this.sampleLink=Te.readUInt16LE(e),this.sampleType=Te.readUInt16LE(e)}}fi.SizeInFile=46;class mi{get shortAmount(){return Be.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}constructor(e){this.wordAmount=Te.readUInt16LE(e)}}class yi{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 bi{constructor(){this.activeChannel=0,this.channelList=[]}setupVoice(e,t){const i=this.channelList[this.activeChannel],s=t.region.pan+i.panOffset;t.playingChannel=this.activeChannel,t.mixVolume=i.mixVolume,t.noteGainDb+=i.gainDb,t.updatePitchRatio(i,e.outSampleRate),s<=-.5?(t.panFactorLeft=1,t.panFactorRight=0):s>=.5?(t.panFactorLeft=0,t.panFactorRight=1):(t.panFactorLeft=Math.sqrt(.5-s),t.panFactorRight=Math.sqrt(.5+s))}}!function(e){e[e.None=0]="None",e[e.Continuous=1]="Continuous",e[e.Sustain=2]="Sustain"}(De||(De={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(Ae||(Ae={}));class Si{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null,this.fontSamples=null}}class wi{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,i){return e<=t?t:e>=i?i:e}}class _i{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:wi.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:wi.timecents2Secs(this.attack),this.release=this.release<-11950?0:wi.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:wi.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:wi.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?wi.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"}(Re||(Re={}));class Bi{constructor(e){this.loopMode=De.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 _i,this.modEnv=new _i,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 _i(e.ampEnv),this.modEnv=new _i(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=De.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 Re.StartAddrsOffset:this.offset+=Be.int16ToUint32(t.shortAmount);break;case Re.EndAddrsOffset:this.end+=Be.int16ToUint32(t.shortAmount);break;case Re.StartloopAddrsOffset:this.loopStart+=Be.int16ToUint32(t.shortAmount);break;case Re.EndloopAddrsOffset:this.loopEnd+=Be.int16ToUint32(t.shortAmount);break;case Re.StartAddrsCoarseOffset:this.offset+=32768*Be.int16ToUint32(t.shortAmount);break;case Re.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case Re.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case Re.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case Re.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case Re.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case Re.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case Re.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case Re.EndAddrsCoarseOffset:this.end+=32768*Be.int16ToUint32(t.shortAmount);break;case Re.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case Re.Pan:this.pan=t.shortAmount/1e3;break;case Re.DelayModLFO:this.delayModLFO=t.shortAmount;break;case Re.FreqModLFO:this.freqModLFO=t.shortAmount;break;case Re.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case Re.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case Re.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case Re.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case Re.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case Re.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case Re.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case Re.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case Re.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case Re.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case Re.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case Re.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case Re.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case Re.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case Re.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case Re.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case Re.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case Re.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case Re.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case Re.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case Re.StartloopAddrsCoarseOffset:this.loopStart+=32768*Be.int16ToUint32(t.shortAmount);break;case Re.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case Re.EndloopAddrsCoarseOffset:this.loopEnd+=32768*Be.int16ToUint32(t.shortAmount);break;case Re.CoarseTune:this.transpose+=t.shortAmount;break;case Re.FineTune:this.tune+=t.shortAmount;break;case Re.SampleModes:this.loopMode=3&~t.wordAmount?1==(3&t.wordAmount)?De.Continuous:De.None:De.Sustain;break;case Re.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case Re.ExclusiveClass:this.group=t.wordAmount;break;case Re.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"}(Oe||(Oe={}));class Ti{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=Oe.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case Oe.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=Oe.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=Oe.Delay;break;case Oe.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=Oe.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=Oe.Attack;break;case Oe.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=Oe.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=Oe.Hold;break;case Oe.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=Oe.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=Oe.Decay;break;case Oe.Decay:return this.segment=Oe.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case Oe.Sustain:if(this.segment=Oe.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?Ti.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=Oe.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,i,s,a){this.parameters=new _i(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:wi.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:wi.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|i,this.isAmpEnv=s,this.nextSegment(Oe.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)}}Ti.FastReleaseTime=.01;class ki{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,i){this.samplesUntil=e*i|0,this.delta=4*wi.cents2Hertz(t)/i,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 vi{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),i=t*t,s=1/(1+t*this.qInv+i);this.a0=i*s,this.a1=2*this.a0,this.b1=2*(i-1)*s,this.b2=(1-t*this.qInv+i)*s}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 xi{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 Ti,this.modEnv=new Ti,this.lowPass=new vi,this.modLfo=new ki,this.vibLfo=new ki,this.mixVolume=0,this.mute=!1}updatePitchRatio(e,t){let i=e.pitchWheel;e.perNotePitchWheel.has(this.playingKey)&&(i+=e.perNotePitchWheel.get(this.playingKey)-8192);const s=8192===i?e.tuning:i/16383*e.pitchRange*2-e.pitchRange+e.tuning;this.calcPitchRatio(s,t)}calcPitchRatio(e,t){if(!this.region)return;const i=this.playingKey+this.region.transpose+this.region.tune/100;let s=this.region.pitchKeyCenter+(i-this.region.pitchKeyCenter)*(this.region.pitchKeyTrack/100);0!==e&&(s+=e),this.pitchInputTimecents=100*s,this.pitchOutputFactor=this.region.sampleRate/(wi.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(Oe.Sustain,e),this.modEnv.nextSegment(Oe.Sustain,e),this.region.loopMode===De.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(Oe.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(Oe.Sustain,e)}render(e,t,i,s,a){if(!this.region)return;let r=this.region;let n=e.presets[this.playingPreset].fontSamples,o=0,h=e.outputMode===Ae.StereoUnweaved?s:-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 vi(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=wi.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,x=0,N=0,P=0),E?F=.1*r.modLfoToVolume:(C=wi.decibelsToGain(this.noteGainDb),F=0);s>0;){let r,L,M=0,I=s>xi.RenderEffectSampleBlock?xi.RenderEffectSampleBlock:s;if(s-=I,S){let e=_+this.modLfo.level*B+this.modEnv.level*T;b.active=e<=13500,b.active&&b.setup(wi.cents2Hertz(e)/w)}switch(k&&(v=wi.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*x+this.vibLfo.level*N+this.modEnv.level*P))*this.pitchOutputFactor),E&&(C=wi.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 Ae.StereoInterleaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;I-- >0&&y<f;){let e=0|y,s=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[s]*a;b.active&&(r=b.process(r)),t[i+o]+=r*L,o++,t[i+o]+=r*M,o++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case Ae.StereoUnweaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;I-- >0&&y<f;){let e=0|y,s=e>=g&&u?p:e+1,a=y-e,r=n[e]*(1-a)+n[s]*a;b.active&&(r=b.process(r)),t[i+o]+=r*L,o++,t[i+h]+=r*M,h++,y+=v,y>=m&&u&&(y-=g-p+1)}break;case Ae.Mono:for(;I-- >0&&y<f;){let e=0|y,s=e>=g&&u?p:e+1,a=y-e,h=n[e]*(1-a)+n[s]*a;b.active&&(h=b.process(h)),t[i+o]=h*r,o++,y+=v,y>=m&&u&&(y-=g-p+1)}}if(y>=f||this.ampEnv.segment===Oe.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}xi.RenderEffectSampleBlock=Zt.MicroBufferSize;class Ni{constructor(){this._items=[],this._position=0,this.isEmpty=!0}clear(){this._items=[],this._position=0,this.isEmpty=!0}enqueue(e){this.isEmpty=!1,this._items.push(e)}peek(){return this._items[this._position]}dequeue(){const e=this._items[this._position];return this._position++,this._position>=this._items.length/2&&(this._items=this._items.slice(this._position),this._position=0),this.isEmpty=0==this._items.length,e}toArray(){const e=this._items.slice(this._position);return e.reverse(),e}}!function(e){e[e.BankSelectCoarse=0]="BankSelectCoarse",e[e.ModulationCoarse=1]="ModulationCoarse",e[e.DataEntryCoarse=6]="DataEntryCoarse",e[e.VolumeCoarse=7]="VolumeCoarse",e[e.PanCoarse=10]="PanCoarse",e[e.ExpressionControllerCoarse=11]="ExpressionControllerCoarse",e[e.BankSelectFine=32]="BankSelectFine",e[e.ModulationFine=33]="ModulationFine",e[e.DataEntryFine=38]="DataEntryFine",e[e.VolumeFine=39]="VolumeFine",e[e.PanFine=42]="PanFine",e[e.ExpressionControllerFine=43]="ExpressionControllerFine",e[e.HoldPedal=64]="HoldPedal",e[e.LegatoPedal=68]="LegatoPedal",e[e.NonRegisteredParameterFine=98]="NonRegisteredParameterFine",e[e.NonRegisteredParameterCourse=99]="NonRegisteredParameterCourse",e[e.RegisteredParameterFine=100]="RegisteredParameterFine",e[e.RegisteredParameterCourse=101]="RegisteredParameterCourse",e[e.AllSoundOff=120]="AllSoundOff",e[e.ResetControllers=121]="ResetControllers",e[e.AllNotesOff=123]="AllNotesOff"}(Ge||(Ge={}));class Pi{constructor(e){this._midiEventQueue=new Ni,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this._transpositionPitches=new Map,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=Ae.StereoInterleaved,this.outSampleRate=0,this.globalGainDb=0,this.outSampleRate=e}synthesize(e,t,i){return this.fillWorkingBuffer(e,t,i)}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 i=this.channelInit(e);for(let i of this._voices)i.playingChannel===e&&-1!==i.playingPreset&&(i.mixVolume=t);i.mixVolume=t}channelSetMute(e,t){t?this._mutedChannels.set(e,!0):this._mutedChannels.delete(e)}channelSetSolo(e,t){t?this._soloChannels.set(e,!0):this._soloChannels.delete(e),this._isAnySolo=this._soloChannels.size>0}resetChannelStates(){this._mutedChannels=new Map,this._soloChannels=new Map,this.applyTranspositionPitches(new Map),this._isAnySolo=!1}applyTranspositionPitches(e){const t=this._transpositionPitches;for(const i of this._voices)if(i.playingChannel>=0&&9!==i.playingChannel){let s=0;t.has(i.playingChannel)&&(s-=t.get(i.playingChannel)),e.has(i.playingChannel)&&(s+=e.get(i.playingChannel)),i.playingKey+=s,this._channels&&i.updatePitchRatio(this._channels.channelList[i.playingChannel],this.outSampleRate)}this._transpositionPitches=e}dispatchEvent(e){this._midiEventQueue.enqueue(e)}fillWorkingBuffer(e,t,i){const s=this._isAnySolo,a=[];for(;!this._midiEventQueue.isEmpty;){let e=this._midiEventQueue.dequeue();e.isMetronome&&this.metronomeVolume>0?(this.channelNoteOff(Zt.MetronomeChannel,33),this.channelNoteOn(Zt.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)||s&&r!=Zt.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,i,n):a.kill()}return a}processMidiMessage(e){J.debug("MIdi","Processing Midi message "+Me[e.type]+"/"+e.tick);switch(e.type){case Me.TimeSignature:const t=e;this.timeSignatureNumerator=t.numerator,this.timeSignatureDenominator=Math.pow(2,t.denominatorIndex);break;case Me.NoteOn:const i=e;this.channelNoteOn(i.channel,i.noteKey,i.noteVelocity/127);break;case Me.NoteOff:const s=e;this.channelNoteOff(s.channel,s.noteKey);break;case Me.ControlChange:const a=e;this.channelMidiControl(a.channel,a.controller,a.value);break;case Me.ProgramChange:const r=e;this.channelSetPresetNumber(r.channel,r.program,9===r.channel);break;case Me.TempoChange:const n=e;this.currentTempo=6e7/n.microSecondsPerQuarterNote;break;case Me.PitchBend:const o=e;this.channelSetPitchWheel(o.channel,o.value);break;case Me.PerNotePitchBend:const h=e;let l=h.value;l=l*Zt.MaxPitchWheel/Zt.MaxPitchWheel20,this.channelSetPerNotePitchWheel(h.channel,h.noteKey,l)}}get metronomeVolume(){return this.channelGetMixVolume(Zt.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Zt.MetronomeChannel,e),e>0&&(this.channelSetVolume(Zt.MetronomeChannel,1),this.channelSetPresetNumber(Zt.MetronomeChannel,0,!0))}get masterVolume(){return wi.decibelsToGain(this.globalGainDb)}set masterVolume(e){var t=wi.gainToDecibels(e);const i=t-this.globalGainDb;if(0!==i){for(const e of this._voices)-1!==e.playingPreset&&(e.noteGainDb+=i);this.globalGainDb=t}}resetSoft(){for(const e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<Oe.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);if(this._channels)for(const e of this._channels.channelList)e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.perNotePitchWheel.clear(),e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0}get presetCount(){return this.presets?.length??0}reset(){for(let e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<Oe.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);this._channels=null}setOutput(e,t,i){this.outputMode=e,this.outSampleRate=t>=1?t:44100,this.globalGainDb=i}noteOn(e,t,i){if(!this.presets)return;const s=127*i|0;if(e<0||e>=this.presets.length)return;if(i<=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||s<r.loVel||s>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 xi;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-wi.gainToDecibels(1/i),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!==De.None&&r.loopStart<r.loopEnd;n.loopStart=o?r.loopStart:0,n.loopEnd=o?r.loopEnd:0,n.ampEnv.setup(r.ampEnv,t,s,!0,this.outSampleRate),n.modEnv.setup(r.modEnv,t,s,!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(wi.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,i,s){let a=this.getPresetIndex(e,t);return-1!==a&&(this.noteOn(a,i,s),!0)}noteOff(e,t){let i=null,s=null,a=[];for(let r of this._voices)r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=Oe.Release||(!i||r.playIndex<i.playIndex?(i=r,s=r,a.push(r)):r.playIndex===i.playIndex&&(s=r,a.push(r)));if(i)for(const r of a)r!==i&&r!==s&&(r.playIndex!==i.playIndex||r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=Oe.Release)||r.end(this.outSampleRate)}bankNoteOff(e,t,i){const s=this.getPresetIndex(e,t);return-1!==s&&(this.noteOff(s,i),!0)}noteOffAll(e){for(const t of this._voices)-1!==t.playingPreset&&t.ampEnv.segment<Oe.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 bi);for(let t=this._channels.channelList.length;t<=e;t++){let e=new yi;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 i=this.presets.length-1;i>=0;i--){let s=this.presets[i];if(s.presetNumber===t&&s.bank===e)return i}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,i){!this._channels||e>this._channels.channelList.length||(this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,i))}channelNoteOff(e,t){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e));const i=[];let s=null,a=null;for(const r of this._voices)-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=Oe.Release||(!s||r.playIndex<s.playIndex?(s=r,a=r,i.push(r)):r.playIndex===s.playIndex&&(a=r,i.push(r)));if(this.channelInit(e).perNotePitchWheel.delete(t),s)for(const r of i)r!==s&&r!==a&&(r.playIndex!==s.playIndex||-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=Oe.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<Oe.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<Oe.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=Be.int32ToUint16(t)}channelSetPresetNumber(e,t,i=!1){const s=this.channelInit(e);let a=0;return i?(a=this.getPresetIndex(128|32767&s.bank,t),-1===a&&(a=this.getPresetIndex(128,t)),-1===a&&(a=this.getPresetIndex(128,0)),-1===a&&(a=this.getPresetIndex(2047&s.bank,t))):a=this.getPresetIndex(2047&s.bank,t),s.presetIndex=a,-1!==a}channelSetBank(e,t){this.channelInit(e).bank=Be.int32ToUint16(t)}channelSetBankPreset(e,t,i){const s=this.channelInit(e),a=this.getPresetIndex(t,i);return-1!==a&&(s.presetIndex=Be.int32ToUint16(a),s.bank=Be.int32ToUint16(t),!0)}channelSetPan(e,t){for(const i of this._voices)if(i.playingChannel===e&&-1!==i.playingPreset){let e=i.region.pan+t-.5;e<=-.5?(i.panFactorLeft=1,i.panFactorRight=0):e>=.5?(i.panFactorLeft=0,i.panFactorRight=1):(i.panFactorLeft=Math.sqrt(.5-e),i.panFactorRight=Math.sqrt(.5+e))}this.channelInit(e).panOffset=t-.5}channelSetVolume(e,t){const i=this.channelInit(e),s=wi.gainToDecibels(t),a=s-i.gainDb;if(0!==a){for(const t of this._voices)t.playingChannel===e&&-1!==t.playingPreset&&(t.noteGainDb+=a);i.gainDb=s}}channelSetPitchWheel(e,t){const i=this.channelInit(e);i.pitchWheel!==t&&(i.pitchWheel=Be.int32ToUint16(t),this.channelApplyPitch(e,i))}channelSetPerNotePitchWheel(e,t,i){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e));const s=this.channelInit(e);s.perNotePitchWheel.has(t)&&s.perNotePitchWheel.get(t)===i||(s.perNotePitchWheel.set(t,i),this.channelApplyPitch(e,s,t))}channelApplyPitch(e,t,i=-1){for(const s of this._voices)s.playingChannel!==e||-1===s.playingPreset||-1!=i&&s.playingKey!==i||s.updatePitchRatio(t,this.outSampleRate)}channelSetPitchRange(e,t){const i=this.channelInit(e);i.pitchRange!==t&&(i.pitchRange=t,8192!==i.pitchWheel&&this.channelApplyPitch(e,i))}channelSetTuning(e,t){const i=this.channelInit(e);i.tuning!==t&&(i.tuning=t,this.channelApplyPitch(e,i))}channelMidiControl(e,t,i){let s=this.channelInit(e);switch(t){case Ge.DataEntryFine:return s.midiData=Be.int32ToUint16(16256&s.midiData|i),void(0===s.midiRpn?this.channelSetPitchRange(e,(s.midiData>>7)+.01*(127&s.midiData)):1===s.midiRpn?this.channelSetTuning(e,(0|s.tuning)+(s.midiData-8192)/8192):2===s.midiRpn&&this.channelSetTuning(e,i-64+(s.tuning-(0|s.tuning))));case Ge.VolumeCoarse:return s.midiVolume=Be.int32ToUint16(127&s.midiVolume|i<<7),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case Ge.VolumeFine:return s.midiVolume=Be.int32ToUint16(16256&s.midiVolume|i),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case Ge.ExpressionControllerCoarse:return s.midiExpression=Be.int32ToUint16(127&s.midiExpression|i<<7),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case Ge.ExpressionControllerFine:return s.midiExpression=Be.int32ToUint16(16256&s.midiExpression|i),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case Ge.PanCoarse:return s.midiPan=Be.int32ToUint16(127&s.midiPan|i<<7),void this.channelSetPan(e,s.midiPan/16383);case Ge.PanFine:return s.midiPan=Be.int32ToUint16(16256&s.midiPan|i),void this.channelSetPan(e,s.midiPan/16383);case Ge.DataEntryCoarse:return s.midiData=Be.int32ToUint16(127&s.midiData|i<<7),void(0===s.midiRpn?this.channelSetPitchRange(e,(s.midiData>>7)+.01*(127&s.midiData)):1===s.midiRpn?this.channelSetTuning(e,(0|s.tuning)+(s.midiData-8192)/8192):2===s.midiRpn&&t===Ge.DataEntryCoarse&&this.channelSetTuning(e,i-64+(s.tuning-(0|s.tuning))));case Ge.BankSelectCoarse:return void(s.bank=Be.int32ToUint16(32768|i));case Ge.BankSelectFine:return void(s.bank=Be.int32ToUint16((32768&s.bank?(127&s.bank)<<7:0)|i));case Ge.RegisteredParameterCourse:return void(s.midiRpn=Be.int32ToUint16(127&(65535===s.midiRpn?0:s.midiRpn)|i<<7));case Ge.RegisteredParameterFine:return void(s.midiRpn=Be.int32ToUint16(16256&(65535===s.midiRpn?0:s.midiRpn)|i));case Ge.NonRegisteredParameterFine:case Ge.NonRegisteredParameterCourse:return void(s.midiRpn=65535);case Ge.AllSoundOff:return void this.channelSoundsOffAll(e);case Ge.AllNotesOff:return void this.channelNoteOffAll(e);case Ge.ResetControllers:return s.midiVolume=16383,s.midiExpression=16383,s.midiPan=8192,s.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?wi.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 i=[];for(let t=0;t<e.phdrs.length-1;t++){const s=e.phdrs[t];let a=0;const r=new Si;i.push(r),r.name=s.presetName,r.bank=s.bank,r.presetNumber=s.preset,r.fontSamples=e.fontSamples;let n=0;for(let i=s.presetBagNdx;i<e.phdrs[t+1].presetBagNdx;i++){let t=0,s=127,a=0,r=127;for(let o=e.pbags[i].genNdx;o<e.pbags[i+1].genNdx;o++){let i=e.pgens[o];if(i.genOper!==ui.GenKeyRange)if(i.genOper!==ui.GenVelRange){if(i.genOper===ui.GenInstrument&&!(i.genAmount.wordAmount>=e.insts.length))for(let o=e.insts[i.genAmount.wordAmount].instBagNdx;o<e.insts[i.genAmount.wordAmount+1].instBagNdx;o++){let i=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!==ui.GenKeyRange?o.genOper!==ui.GenVelRange?53===o.genOper&&h>=t&&i<=s&&c>=a&&l<=r&&n++:(l=o.genAmount.lowByteAmount,c=o.genAmount.highByteAmount):(i=o.genAmount.lowByteAmount,h=o.genAmount.highByteAmount)}}}else a=i.genAmount.lowByteAmount,r=i.genAmount.highByteAmount;else t=i.genAmount.lowByteAmount,s=i.genAmount.highByteAmount}}r.regions=new Array(n);let o=new Bi;o.clear(!0);for(let i=s.presetBagNdx;i<e.phdrs[t+1].presetBagNdx;i++){const t=e.pbags[i],n=new Bi(o);let h=!1;for(let s=t.genNdx;s<e.pbags[i+1].genNdx;s++){const t=e.pgens[s];if(t.genOper===ui.GenInstrument){let i=t.genAmount.wordAmount;if(i>=e.insts.length)continue;let s=new Bi;s.clear(!1);let o=e.insts[i];for(let t=o.instBagNdx;t<e.insts[i+1].instBagNdx;t++){let i=e.ibags[t],h=new Bi(s),l=!1;for(let s=i.instGenNdx;s<e.ibags[t+1].instGenNdx;s++){let t=e.igens[s];if(t.genOper===ui.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:wi.timecents2Secs(h.delayModLFO),h.delayVibLFO=h.delayVibLFO<-11950?0:wi.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 i=e.sHdrs[t.genAmount.wordAmount];h.offset+=i.start,h.end+=i.end,h.loopStart+=i.startLoop,h.loopEnd+=i.endLoop,i.endLoop>0&&(h.loopEnd-=1),-1===h.pitchKeyCenter&&(h.pitchKeyCenter=i.originalPitch),h.tune+=i.pitchCorrection,h.sampleRate=i.sampleRate,0!==h.end&&h.end<r.fontSamples.length?h.end++:h.end=r.fontSamples.length,r.regions[a]=new Bi(h),a++,l=!0}else h.operator(t.genOper,t.genAmount)}i!==e.ibags[o.instBagNdx]||l||(s=new Bi(h))}h=!0}else n.operator(t.genOper,t.genAmount)}t!==e.pbags[s.presetBagNdx]||h||(o=n)}}if(t&&this.presets)for(const e of i)this.presets.push(e);else this.presets=i}}class Ei{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 Ci{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 Fi{constructor(e){this.events=e}}class Li{constructor(e){this.playbackRange=e}}class Mi{get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return J.logLevel}set logLevel(e){J.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Zt.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Zt.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Zt.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=wi.clamp(e,Zt.MinPlaybackSpeed,Zt.MaxPlaybackSpeed);let t=this._sequencer.playbackSpeed;this._sequencer.playbackSpeed=e,this.timePosition=this.timePosition*(t/e)}get tickPosition(){return this._tickPosition}set tickPosition(e){this.timePosition=this._sequencer.mainTickPositionToTimePosition(e)}get timePosition(){return this._timePosition}set timePosition(e){J.debug("AlphaSynth",`Seeking to position ${e}ms (main)`),this._sequencer.mainSeek(e),this.updateTimePosition(e,!0),this._sequencer.isPlayingMain&&(this._notPlayedSamples=0,this.output.resetSamples())}get playbackRange(){return this._sequencer.mainPlaybackRange}set playbackRange(e){this._sequencer.mainPlaybackRange=e,e&&(this.tickPosition=e.startTick),this.playbackRangeChanged.trigger(new Li(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){J.debug("AlphaSynth","Destroying player"),this.stop(),this.output.destroy()}constructor(e,t){this._isSoundFontLoaded=!1,this._isMidiLoaded=!1,this._tickPosition=0,this._timePosition=0,this._metronomeVolume=0,this._countInVolume=0,this._playedEventsQueue=new Ni,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this.isReady=!1,this.state=Ie.Paused,this.ready=new Ei,this.readyForPlayback=new Ei,this.finished=new Ei,this.soundFontLoaded=new Ei,this.soundFontLoadFailed=new Ci,this.midiLoaded=new Ci,this.midiLoadFailed=new Ci,this.stateChanged=new Ci,this.positionChanged=new Ci,this.midiEventsPlayed=new Ci,this.playbackRangeChanged=new Ci,J.debug("AlphaSynth","Initializing player"),this.state=Ie.Paused,J.debug("AlphaSynth","Creating output"),this.output=e,J.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new Pi(this.output.sampleRate),this._sequencer=new ii(this._synthesizer),J.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this.state!=Ie.Playing||this._sequencer.isFinished){let e=new Float32Array(0);this.output.addSamples(e)}else{let e=new Float32Array(Zt.MicroBufferSize*Zt.MicroBufferCount*Zt.AudioChannels),t=0;for(let i=0;i<Zt.MicroBufferCount;i++){this._sequencer.fillMidiEventQueue();const i=this._synthesizer.synthesize(e,t,Zt.MicroBufferSize);t+=Zt.MicroBufferSize*Zt.AudioChannels;for(const e of i)this._midiEventsPlayedFilter.has(e.event.type)&&this._playedEventsQueue.enqueue(e);if(this._sequencer.isFinished)break}t<e.length&&(e=e.subarray(0,t)),this._notPlayedSamples+=e.length,this.output.addSamples(e)}})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open(t)}play(){return!(this.state!==Ie.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(J.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(J.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),J.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.state=Ie.Playing,this.stateChanged.trigger(new si(this.state,!1))}pause(){this.state!==Ie.Paused&&this._isMidiLoaded&&(J.debug("AlphaSynth","Pausing playback"),this.state=Ie.Paused,this.stateChanged.trigger(new si(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===Ie.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(J.debug("AlphaSynth","Stopping playback"),this.state=Ie.Paused,this.output.pause(),this._notPlayedSamples=0,this._sequencer.stop(),this._synthesizer.noteOffAll(!0),this.tickPosition=this._sequencer.mainPlaybackRange?this._sequencer.mainPlaybackRange.startTick:0,this.stateChanged.trigger(new si(this.state,!0)))}playOneTimeMidiFile(e){this._sequencer.isPlayingOneTimeMidi?this.stopOneTimeMidi():this.pause(),this._sequencer.loadOneTimeMidi(e),this._synthesizer.noteOffAll(!0),this.updateTimePosition(0,!0),this._notPlayedSamples=0,this.output.resetSamples(),this.output.play()}resetSoundFonts(){this.stop(),this._synthesizer.resetPresets(),this._isSoundFontLoaded=!1,this.soundFontLoaded.trigger()}loadSoundFont(e,t){this.pause();let i=ke.fromBuffer(e);try{J.debug("AlphaSynth","Loading soundfont from bytes");let e=new ni;e.load(i),this._synthesizer.loadPresets(e,t),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),J.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){J.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{J.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new ai(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),J.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){J.error("AlphaSynth","Could not load midi from model "+e),this.midiLoadFailed.trigger(e)}}applyTranspositionPitches(e){this._synthesizer.applyTranspositionPitches(e)}setChannelMute(e,t){this._synthesizer.channelSetMute(e,t)}resetChannelStates(){this._synthesizer.resetChannelStates()}setChannelSolo(e,t){this._synthesizer.channelSetSolo(e,t)}setChannelVolume(e,t){t=Math.max(t,Zt.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;let t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*Zt.AudioChannels,this.updateTimePosition(this._timePosition+t,!1),this.checkForFinish()}checkForFinish(){let e=0,t=0;this.playbackRange&&this._sequencer.isPlayingMain?(e=this.playbackRange.startTick,t=this.playbackRange.endTick):t=this._sequencer.currentEndTick,this._tickPosition>=t&&this._notPlayedSamples<=0&&(this._notPlayedSamples=0,this._sequencer.isPlayingCountIn?(J.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(J.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=Ie.Paused,this.stopOneTimeMidi()):(J.debug("AlphaSynth","Finished playback (main)"),this.finished.trigger(),this.isLooping?this.tickPosition=e:this.stop()))}stopOneTimeMidi(){this.output.pause(),this._synthesizer.noteOffAll(!0),this._sequencer.resetOneTimeMidi(),this.timePosition=this._sequencer.currentTime}updateTimePosition(e,t){const i=e;this._timePosition=i;const s=this._sequencer.currentTimePositionToTickPosition(i);this._tickPosition=s;const a=this._sequencer.currentEndTime,r=this._sequencer.currentEndTick,n=this._sequencer.isPlayingMain?"main":this._sequencer.isPlayingCountIn?"count-in":"one-time";if(J.debug("AlphaSynth",`Position changed: (time: ${i}/${a}, tick: ${s}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new ai(i,a,s,r,t)),t)this._playedEventsQueue.clear();else{const e=new Ni;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<i;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new Fi(e.toArray()))}}}class Ii{static parseEnum(t,i){switch(typeof t){case"string":const e=parseInt(t);return isNaN(e)?i[Object.keys(i).find((e=>e.toLowerCase()===t.toLowerCase()))]:e;case"number":return t;case"undefined":case"object":return null}throw new G(e.AlphaTabErrorType.Format,`Could not parse enum value '${t}'`)}static forEach(e,t){if(e instanceof Map)e.forEach(t);else if("object"==typeof e)for(const i in e)t(e[i],i)}static getValue(e,t){return e instanceof Map?e.get(t):"object"==typeof e?e[t]:null}}class Di{constructor(e,t,i){this.text=e,this.startPos=t,this.endPos=i}}class Ai{constructor(e){this.style="normal",this.variant="normal",this.weight="normal",this.stretch="normal",this.lineHeight="normal",this.size="1rem",this.families=[],this.parseOnlyFamilies=!1,this._currentTokenIndex=-1,this._input="",this._currentToken=null,this._input=e,this._tokens=this.splitToTokens(e)}splitToTokens(e){const t=[];let i=0;for(;i<e.length;){let s=i;for(;s<e.length&&" "!==e.charAt(s);)s++;s>i&&t.push(new Di(e.substring(i,s),i,s)),i=s+1}return t}parse(){if(this.reset(),1===this._tokens.length)switch(this._currentToken?.text){case"caption":case"icon":case"menu":case"message-box":case"small-caption":case"status-bar":case"inherit":return}this.parseOnlyFamilies||(this.fontStyleVariantWeight(),this.fontSizeLineHeight()),this.fontFamily()}static parseFamilies(e){const t=new Ai(e);return t.parseOnlyFamilies=!0,t.parse(),t.families}fontFamily(){if(!this._currentToken){if(this.parseOnlyFamilies)return;throw new Error("Missing font list")}const e=this._input.substr(this._currentToken.startPos).trim();let t=0;for(;t<e.length;){let i=e.charAt(t);if(" "===i||","==i)t++;else if('"'===i||"'"===i){const s=this.findEndOfQuote(e,t+1,i);this.families.push(e.substring(t+1,s).split("\\"+i).join(i)),t=s+1}else{const i=this.findEndOfQuote(e,t+1,",");this.families.push(e.substring(t,i).trim()),t=i+1}}}findEndOfQuote(e,t,i){let s=!1;for(;t<e.length;){const a=e.charAt(t);if(!s&&a===i)return t;s=!s&&"\\"===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,i=!1,s=3,a=[];for(;;){if(!this._currentToken)return;let r=this._currentToken.text;switch(r){case"normal":case"inherit":a.push(r),s--,this.nextToken();break;case"italic":case"oblique":this.style=r,e=!0,s--,this.nextToken();break;case"small-caps":this.variant=r,t=!0,s--,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,i=!0,s--,this.nextToken();break;default:return}if(0===s)break}for(;a.length>0;){const s=a.pop();i?t?e||(this.style=s):this.variant=s:this.weight=s}}reset(){this._currentTokenIndex=-1,this.nextToken()}static quoteFont(e){if(-1===e.indexOf(" "))return e;return`"${e.replaceAll('"','\\"')}"`}}!function(e){e[e.Plain=0]="Plain",e[e.Italic=1]="Italic"}(Ve||(Ve={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(He||(He={}));class Ri{reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=Ai.parseFamilies(e)}get families(){return this._families}set families(e){this._families=e,this.reset()}get size(){return this._size}set size(e){this._size=e,this.reset()}get style(){return this._style}set style(e){this._style=e,this.reset()}get weight(){return this._weight}set weight(e){this._weight=e,this.reset()}get isBold(){return this.weight===He.Bold}get isItalic(){return this.style===Ve.Italic}constructor(e,t,i=Ve.Plain,s=He.Regular){this._cssScale=0,this._families=Ai.parseFamilies(e),this._size=t,this._style=i,this._weight=s,this._css=this.toCssString()}static withFamilyList(e,t,i=Ve.Plain,s=He.Regular){const a=new Ri("",t,i,s);return a.families=e,a}toCssString(e=1){if(!(this._css&&Math.abs(e-this._cssScale)<.01)){let t="";this.isBold&&(t+="bold "),this.isItalic&&(t+="italic "),t+=this.size*e,t+="px ",t+=this.families.map((e=>Ai.quoteFont(e))).join(", "),this._css=t,this._cssScale=e}return this._css}static fromJson(e){switch(typeof e){case"undefined":default:return null;case"object":{const t=e;let i=t.get("families"),s=t.get("size"),a=Ii.parseEnum(t.get("style"),Ve),r=Ii.parseEnum(t.get("weight"),He);return Ri.withFamilyList(i,s,a,r)}case"string":{const t=new Ai(e);t.parse();let i=t.families,s=t.size.toLowerCase(),a=0;switch(s){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=s.endsWith("em")?16*parseFloat(s.substr(0,s.length-2)):s.endsWith("pt")?16*parseFloat(s.substr(0,s.length-2))/12:s.endsWith("px")?parseFloat(s.substr(0,s.length-2)):12}catch(e){a=12}}let r=Ve.Plain;"italic"===t.style&&(r=Ve.Italic);let n=He.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=He.Bold}return Ri.withFamilyList(i,a,r,n)}}}static toJson(e){const t=new Map;return t.set("families",e.families),t.set("size",e.size),t.set("style",e.style),t.set("weight",e.weight),t}}class Oi{constructor(){this.copyrightFont=new Ri(Oi.sansFont,12,Ve.Plain,He.Bold),this.titleFont=new Ri(Oi.serifFont,32,Ve.Plain),this.subTitleFont=new Ri(Oi.serifFont,20,Ve.Plain),this.wordsFont=new Ri(Oi.serifFont,15,Ve.Plain),this.effectFont=new Ri(Oi.serifFont,12,Ve.Italic),this.fretboardNumberFont=new Ri(Oi.sansFont,11,Ve.Plain),this.tablatureFont=new Ri(Oi.sansFont,13,Ve.Plain),this.graceFont=new Ri(Oi.sansFont,11,Ve.Plain),this.staffLineColor=new me(165,165,165,255),this.barSeparatorColor=new me(34,34,17,255),this.barNumberFont=new Ri(Oi.sansFont,11,Ve.Plain),this.barNumberColor=new me(200,0,0,255),this.fingeringFont=new Ri(Oi.serifFont,14,Ve.Plain),this.markerFont=new Ri(Oi.serifFont,14,Ve.Plain,He.Bold),this.mainGlyphColor=new me(0,0,0,255),this.secondaryGlyphColor=new me(0,0,0,100),this.scoreInfoColor=new me(0,0,0,255)}}Oi.sansFont="Arial, sans-serif",Oi.serifFont="Georgia, serif",e.SystemsLayoutMode=void 0,(We=e.SystemsLayoutMode||(e.SystemsLayoutMode={}))[We.Automatic=0]="Automatic",We[We.UseModelLayout=1]="UseModelLayout";class Gi{constructor(){this.scale=1,this.stretchForce=1,this.layoutMode=e.LayoutMode.Page,this.staveProfile=e.StaveProfile.Default,this.barsPerRow=-1,this.startBar=1,this.barCount=-1,this.barCountPerPartial=10,this.justifyLastSystem=!1,this.resources=new Oi,this.padding=null,this.systemsLayoutMode=e.SystemsLayoutMode.Automatic}}class Vi{constructor(){this.encoding="utf-8",this.mergePartGroupsInMusicXml=!1,this.beatTextAsLyrics=!1}}e.ScrollMode=void 0,(ze=e.ScrollMode||(e.ScrollMode={}))[ze.Off=0]="Off",ze[ze.Continuous=1]="Continuous",ze[ze.OffScreen=2]="OffScreen";class Hi{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 Wi{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}e.PlayerOutputMode=void 0,(Ue=e.PlayerOutputMode||(e.PlayerOutputMode={}))[Ue.WebAudioAudioWorklets=0]="WebAudioAudioWorklets",Ue[Ue.WebAudioScriptProcessor=1]="WebAudioScriptProcessor";class zi{constructor(){this.soundFont=null,this.scrollElement="html,body",this.outputMode=e.PlayerOutputMode.WebAudioAudioWorklets,this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=e.ScrollMode.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new Hi,this.slide=new Wi,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}class Ui{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scriptfile",e.scriptFile),t.set("fontdirectory",e.fontDirectory),t.set("file",e.file),t.set("tex",e.tex),t.set("tracks",e.tracks),t.set("enablelazyloading",e.enableLazyLoading),t.set("engine",e.engine),t.set("loglevel",e.logLevel),t.set("useworkers",e.useWorkers),t.set("includenotebounds",e.includeNoteBounds),t}static setProperty(t,i,s){switch(i){case"scriptfile":return t.scriptFile=s,!0;case"fontdirectory":return t.fontDirectory=s,!0;case"file":return t.file=s,!0;case"tex":return t.tex=s,!0;case"tracks":return t.tracks=s,!0;case"enablelazyloading":return t.enableLazyLoading=s,!0;case"engine":return t.engine=s,!0;case"loglevel":return t.logLevel=Ii.parseEnum(s,e.LogLevel),!0;case"useworkers":return t.useWorkers=s,!0;case"includenotebounds":return t.includeNoteBounds=s,!0}return!1}}class Xi{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("copyrightfont",Ri.toJson(e.copyrightFont)),t.set("titlefont",Ri.toJson(e.titleFont)),t.set("subtitlefont",Ri.toJson(e.subTitleFont)),t.set("wordsfont",Ri.toJson(e.wordsFont)),t.set("effectfont",Ri.toJson(e.effectFont)),t.set("fretboardnumberfont",Ri.toJson(e.fretboardNumberFont)),t.set("tablaturefont",Ri.toJson(e.tablatureFont)),t.set("gracefont",Ri.toJson(e.graceFont)),t.set("stafflinecolor",me.toJson(e.staffLineColor)),t.set("barseparatorcolor",me.toJson(e.barSeparatorColor)),t.set("barnumberfont",Ri.toJson(e.barNumberFont)),t.set("barnumbercolor",me.toJson(e.barNumberColor)),t.set("fingeringfont",Ri.toJson(e.fingeringFont)),t.set("markerfont",Ri.toJson(e.markerFont)),t.set("mainglyphcolor",me.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",me.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",me.toJson(e.scoreInfoColor)),t}static setProperty(e,t,i){switch(t){case"copyrightfont":return e.copyrightFont=Ri.fromJson(i),!0;case"titlefont":return e.titleFont=Ri.fromJson(i),!0;case"subtitlefont":return e.subTitleFont=Ri.fromJson(i),!0;case"wordsfont":return e.wordsFont=Ri.fromJson(i),!0;case"effectfont":return e.effectFont=Ri.fromJson(i),!0;case"fretboardnumberfont":return e.fretboardNumberFont=Ri.fromJson(i),!0;case"tablaturefont":return e.tablatureFont=Ri.fromJson(i),!0;case"gracefont":return e.graceFont=Ri.fromJson(i),!0;case"stafflinecolor":return e.staffLineColor=me.fromJson(i),!0;case"barseparatorcolor":return e.barSeparatorColor=me.fromJson(i),!0;case"barnumberfont":return e.barNumberFont=Ri.fromJson(i),!0;case"barnumbercolor":return e.barNumberColor=me.fromJson(i),!0;case"fingeringfont":return e.fingeringFont=Ri.fromJson(i),!0;case"markerfont":return e.markerFont=Ri.fromJson(i),!0;case"mainglyphcolor":return e.mainGlyphColor=me.fromJson(i),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=me.fromJson(i),!0;case"scoreinfocolor":return e.scoreInfoColor=me.fromJson(i),!0}return!1}}class Yi{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scale",e.scale),t.set("stretchforce",e.stretchForce),t.set("layoutmode",e.layoutMode),t.set("staveprofile",e.staveProfile),t.set("barsperrow",e.barsPerRow),t.set("startbar",e.startBar),t.set("barcount",e.barCount),t.set("barcountperpartial",e.barCountPerPartial),t.set("justifylastsystem",e.justifyLastSystem),t.set("resources",Xi.toJson(e.resources)),t.set("padding",e.padding),t.set("systemslayoutmode",e.systemsLayoutMode),t}static setProperty(t,i,s){switch(i){case"scale":return t.scale=s,!0;case"stretchforce":return t.stretchForce=s,!0;case"layoutmode":return t.layoutMode=Ii.parseEnum(s,e.LayoutMode),!0;case"staveprofile":return t.staveProfile=Ii.parseEnum(s,e.StaveProfile),!0;case"barsperrow":return t.barsPerRow=s,!0;case"startbar":return t.startBar=s,!0;case"barcount":return t.barCount=s,!0;case"barcountperpartial":return t.barCountPerPartial=s,!0;case"justifylastsystem":return t.justifyLastSystem=s,!0;case"padding":return t.padding=s,!0;case"systemslayoutmode":return t.systemsLayoutMode=Ii.parseEnum(s,e.SystemsLayoutMode),!0}if(["resources"].indexOf(i)>=0)return Xi.fromJson(t.resources,s),!0;for(const e of["resources"])if(0===i.indexOf(e)&&Xi.setProperty(t.resources,i.substring(e.length),s))return!0;return!1}}class qi{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("notationmode",e.notationMode),t.set("fingeringmode",e.fingeringMode);{const i=new Map;t.set("elements",i);for(const[t,s]of e.elements)i.set(t.toString(),s)}return t.set("rhythmmode",e.rhythmMode),t.set("rhythmheight",e.rhythmHeight),t.set("transpositionpitches",e.transpositionPitches),t.set("displaytranspositionpitches",e.displayTranspositionPitches),t.set("smallgracetabnotes",e.smallGraceTabNotes),t.set("extendbendarrowsontiednotes",e.extendBendArrowsOnTiedNotes),t.set("extendlineeffectstobeatend",e.extendLineEffectsToBeatEnd),t.set("slurheight",e.slurHeight),t}static setProperty(t,i,s){switch(i){case"notationmode":return t.notationMode=Ii.parseEnum(s,e.NotationMode),!0;case"fingeringmode":return t.fingeringMode=Ii.parseEnum(s,e.FingeringMode),!0;case"elements":return t.elements=new Map,Ii.forEach(s,((e,i)=>{t.elements.set(Ii.parseEnum(i,v),e)})),!0;case"rhythmmode":return t.rhythmMode=Ii.parseEnum(s,e.TabRhythmMode),!0;case"rhythmheight":return t.rhythmHeight=s,!0;case"transpositionpitches":return t.transpositionPitches=s,!0;case"displaytranspositionpitches":return t.displayTranspositionPitches=s,!0;case"smallgracetabnotes":return t.smallGraceTabNotes=s,!0;case"extendbendarrowsontiednotes":return t.extendBendArrowsOnTiedNotes=s,!0;case"extendlineeffectstobeatend":return t.extendLineEffectsToBeatEnd=s,!0;case"slurheight":return t.slurHeight=s,!0}return!1}}class Ji{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.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,i){switch(t){case"encoding":return e.encoding=i,!0;case"mergepartgroupsinmusicxml":return e.mergePartGroupsInMusicXml=i,!0;case"beattextaslyrics":return e.beatTextAsLyrics=i,!0}return!1}}class ji{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.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,i){switch(t){case"notewidelength":return e.noteWideLength=i,!0;case"notewideamplitude":return e.noteWideAmplitude=i,!0;case"noteslightlength":return e.noteSlightLength=i,!0;case"noteslightamplitude":return e.noteSlightAmplitude=i,!0;case"beatwidelength":return e.beatWideLength=i,!0;case"beatwideamplitude":return e.beatWideAmplitude=i,!0;case"beatslightlength":return e.beatSlightLength=i,!0;case"beatslightamplitude":return e.beatSlightAmplitude=i,!0}return!1}}class Qi{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.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,i){switch(t){case"simpleslidepitchoffset":return e.simpleSlidePitchOffset=i,!0;case"simpleslidedurationratio":return e.simpleSlideDurationRatio=i,!0;case"shiftslidedurationratio":return e.shiftSlideDurationRatio=i,!0}return!1}}class $i{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("soundfont",e.soundFont),t.set("outputmode",e.outputMode),t.set("enableplayer",e.enablePlayer),t.set("enablecursor",e.enableCursor),t.set("enableanimatedbeatcursor",e.enableAnimatedBeatCursor),t.set("enableelementhighlighting",e.enableElementHighlighting),t.set("enableuserinteraction",e.enableUserInteraction),t.set("scrolloffsetx",e.scrollOffsetX),t.set("scrolloffsety",e.scrollOffsetY),t.set("scrollmode",e.scrollMode),t.set("scrollspeed",e.scrollSpeed),t.set("nativebrowsersmoothscroll",e.nativeBrowserSmoothScroll),t.set("songbookbendduration",e.songBookBendDuration),t.set("songbookdipduration",e.songBookDipDuration),t.set("vibrato",ji.toJson(e.vibrato)),t.set("slide",Qi.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t.set("buffertimeinmilliseconds",e.bufferTimeInMilliseconds),t}static setProperty(t,i,s){switch(i){case"soundfont":return t.soundFont=s,!0;case"scrollelement":return t.scrollElement=s,!0;case"outputmode":return t.outputMode=Ii.parseEnum(s,e.PlayerOutputMode),!0;case"enableplayer":return t.enablePlayer=s,!0;case"enablecursor":return t.enableCursor=s,!0;case"enableanimatedbeatcursor":return t.enableAnimatedBeatCursor=s,!0;case"enableelementhighlighting":return t.enableElementHighlighting=s,!0;case"enableuserinteraction":return t.enableUserInteraction=s,!0;case"scrolloffsetx":return t.scrollOffsetX=s,!0;case"scrolloffsety":return t.scrollOffsetY=s,!0;case"scrollmode":return t.scrollMode=Ii.parseEnum(s,e.ScrollMode),!0;case"scrollspeed":return t.scrollSpeed=s,!0;case"nativebrowsersmoothscroll":return t.nativeBrowserSmoothScroll=s,!0;case"songbookbendduration":return t.songBookBendDuration=s,!0;case"songbookdipduration":return t.songBookDipDuration=s,!0;case"playtripletfeel":return t.playTripletFeel=s,!0;case"buffertimeinmilliseconds":return t.bufferTimeInMilliseconds=s,!0}if(["vibrato"].indexOf(i)>=0)return ji.fromJson(t.vibrato,s),!0;for(const e of["vibrato"])if(0===i.indexOf(e)&&ji.setProperty(t.vibrato,i.substring(e.length),s))return!0;if(["slide"].indexOf(i)>=0)return Qi.fromJson(t.slide,s),!0;for(const e of["slide"])if(0===i.indexOf(e)&&Qi.setProperty(t.slide,i.substring(e.length),s))return!0;return!1}}class Ki{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("core",Ui.toJson(e.core)),t.set("display",Yi.toJson(e.display)),t.set("notation",qi.toJson(e.notation)),t.set("importer",Ji.toJson(e.importer)),t.set("player",$i.toJson(e.player)),t}static setProperty(e,t,i){if(["core",""].indexOf(t)>=0)return Ui.fromJson(e.core,i),!0;for(const s of["core",""])if(0===t.indexOf(s)&&Ui.setProperty(e.core,t.substring(s.length),i))return!0;if(["display",""].indexOf(t)>=0)return Yi.fromJson(e.display,i),!0;for(const s of["display",""])if(0===t.indexOf(s)&&Yi.setProperty(e.display,t.substring(s.length),i))return!0;if(["notation"].indexOf(t)>=0)return qi.fromJson(e.notation,i),!0;for(const s of["notation"])if(0===t.indexOf(s)&&qi.setProperty(e.notation,t.substring(s.length),i))return!0;if(["importer"].indexOf(t)>=0)return Ji.fromJson(e.importer,i),!0;for(const s of["importer"])if(0===t.indexOf(s)&&Ji.setProperty(e.importer,t.substring(s.length),i))return!0;if(["player"].indexOf(t)>=0)return $i.fromJson(e.player,i),!0;for(const s of["player"])if(0===t.indexOf(s)&&$i.setProperty(e.player,t.substring(s.length),i))return!0;return!1}}class Zi{constructor(){this.core=new Co,this.display=new Gi,this.notation=new X,this.importer=new Vi,this.player=new zi}setSongBookModeSettings(){this.notation.notationMode=e.NotationMode.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=e.FingeringMode.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(v.ParenthesisOnTiedBends,!1),this.notation.elements.set(v.TabNotesOnTiedBends,!1),this.notation.elements.set(v.ZerosOnDiveWhammys,!0)}static get songBook(){let e=new Zi;return e.setSongBookModeSettings(),e}fillFromJson(e){Ki.fromJson(this,e)}}class es{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"marker":return e.marker=i,!0;case"text":return e.text=i,!0}return!1}}class ts{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"islinear":return e.isLinear=i,!0;case"type":return e.type=Ii.parseEnum(i,r),!0;case"value":return e.value=i,!0;case"ratioposition":return e.ratioPosition=i,!0;case"text":return e.text=i,!0}return!1}}class is{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"type":return e.type=Ii.parseEnum(i,Ne),!0;case"length":return e.length=i,!0}return!1}}class ss{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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",es.toJson(e.section)),t.set("tempoautomation",ts.toJson(e.tempoAutomation)),null!==e.fermata){const i=new Map;t.set("fermata",i);for(const[t,s]of e.fermata)i.set(t.toString(),is.toJson(s))}return t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t}static setProperty(e,t,i){switch(t){case"alternateendings":return e.alternateEndings=i,!0;case"keysignature":return e.keySignature=Ii.parseEnum(i,M),!0;case"keysignaturetype":return e.keySignatureType=Ii.parseEnum(i,D),!0;case"isdoublebar":return e.isDoubleBar=i,!0;case"isrepeatstart":return e.isRepeatStart=i,!0;case"repeatcount":return e.repeatCount=i,!0;case"timesignaturenumerator":return e.timeSignatureNumerator=i,!0;case"timesignaturedenominator":return e.timeSignatureDenominator=i,!0;case"timesignaturecommon":return e.timeSignatureCommon=i,!0;case"tripletfeel":return e.tripletFeel=Ii.parseEnum(i,A),!0;case"fermata":return e.fermata=new Map,Ii.forEach(i,((t,i)=>{const s=new ht;is.fromJson(s,t),e.addFermata(parseInt(i),s)})),!0;case"start":return e.start=i,!0;case"isanacrusis":return e.isAnacrusis=i,!0;case"displayscale":return e.displayScale=i,!0;case"displaywidth":return e.displayWidth=i,!0}return["section"].indexOf(t)>=0?(i?(e.section=new ge,es.fromJson(e.section,i)):e.section=null,!0):["tempoautomation"].indexOf(t)>=0&&(i?(e.tempoAutomation=new H,ts.fromJson(e.tempoAutomation,i)):e.tempoAutomation=null,!0)}}class as{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"offset":return e.offset=i,!0;case"value":return e.value=i,!0}return!1}}class rs{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("accentuated",e.accentuated),t.set("bendtype",e.bendType),t.set("bendstyle",e.bendStyle),t.set("iscontinuedbend",e.isContinuedBend),null!==e.bendPoints&&t.set("bendpoints",e.bendPoints?.map((e=>as.toJson(e)))),t.set("fret",e.fret),t.set("string",e.string),t.set("octave",e.octave),t.set("tone",e.tone),t.set("percussionarticulation",e.percussionArticulation),t.set("isvisible",e.isVisible),t.set("islefthandtapped",e.isLeftHandTapped),t.set("ishammerpullorigin",e.isHammerPullOrigin),t.set("isslurdestination",e.isSlurDestination),t.set("harmonictype",e.harmonicType),t.set("harmonicvalue",e.harmonicValue),t.set("isghost",e.isGhost),t.set("isletring",e.isLetRing),t.set("ispalmmute",e.isPalmMute),t.set("isdead",e.isDead),t.set("isstaccato",e.isStaccato),t.set("slideintype",e.slideInType),t.set("slideouttype",e.slideOutType),t.set("vibrato",e.vibrato),t.set("istiedestination",e.isTieDestination),t.set("lefthandfinger",e.leftHandFinger),t.set("righthandfinger",e.rightHandFinger),t.set("isfingering",e.isFingering),t.set("trillvalue",e.trillValue),t.set("trillspeed",e.trillSpeed),t.set("durationpercent",e.durationPercent),t.set("accidentalmode",e.accidentalMode),t.set("dynamics",e.dynamics),e.toJson(t),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"accentuated":return e.accentuated=Ii.parseEnum(i,a),!0;case"bendtype":return e.bendType=Ii.parseEnum(i,c),!0;case"bendstyle":return e.bendStyle=Ii.parseEnum(i,l),!0;case"iscontinuedbend":return e.isContinuedBend=i,!0;case"bendpoints":if(i){e.bendPoints=[];for(const t of i){const i=new U;as.fromJson(i,t),e.addBendPoint(i)}}return!0;case"fret":return e.fret=i,!0;case"string":return e.string=i,!0;case"octave":return e.octave=i,!0;case"tone":return e.tone=i,!0;case"percussionarticulation":return e.percussionArticulation=i,!0;case"isvisible":return e.isVisible=i,!0;case"islefthandtapped":return e.isLeftHandTapped=i,!0;case"ishammerpullorigin":return e.isHammerPullOrigin=i,!0;case"isslurdestination":return e.isSlurDestination=i,!0;case"harmonictype":return e.harmonicType=Ii.parseEnum(i,y),!0;case"harmonicvalue":return e.harmonicValue=i,!0;case"isghost":return e.isGhost=i,!0;case"isletring":return e.isLetRing=i,!0;case"ispalmmute":return e.isPalmMute=i,!0;case"isdead":return e.isDead=i,!0;case"isstaccato":return e.isStaccato=i,!0;case"slideintype":return e.slideInType=Ii.parseEnum(i,S),!0;case"slideouttype":return e.slideOutType=Ii.parseEnum(i,w),!0;case"vibrato":return e.vibrato=Ii.parseEnum(i,_),!0;case"istiedestination":return e.isTieDestination=i,!0;case"lefthandfinger":return e.leftHandFinger=Ii.parseEnum(i,m),!0;case"righthandfinger":return e.rightHandFinger=Ii.parseEnum(i,m),!0;case"isfingering":return e.isFingering=i,!0;case"trillvalue":return e.trillValue=i,!0;case"trillspeed":return e.trillSpeed=Ii.parseEnum(i,p),!0;case"durationpercent":return e.durationPercent=i,!0;case"accidentalmode":return e.accidentalMode=Ii.parseEnum(i,b),!0;case"dynamics":return e.dynamics=Ii.parseEnum(i,g),!0}return e.setProperty(t,i)}}class ns{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("notes",e.notes.map((e=>rs.toJson(e)))),t.set("isempty",e.isEmpty),t.set("whammystyle",e.whammyStyle),t.set("ottava",e.ottava),t.set("islegatoorigin",e.isLegatoOrigin),t.set("duration",e.duration),t.set("automations",e.automations.map((e=>ts.toJson(e)))),t.set("dots",e.dots),t.set("fadein",e.fadeIn),t.set("lyrics",e.lyrics),t.set("hasrasgueado",e.hasRasgueado),t.set("pop",e.pop),t.set("slap",e.slap),t.set("tap",e.tap),t.set("text",e.text),t.set("brushtype",e.brushType),t.set("brushduration",e.brushDuration),t.set("tupletdenominator",e.tupletDenominator),t.set("tupletnumerator",e.tupletNumerator),t.set("iscontinuedwhammy",e.isContinuedWhammy),t.set("whammybartype",e.whammyBarType),null!==e.whammyBarPoints&&t.set("whammybarpoints",e.whammyBarPoints?.map((e=>as.toJson(e)))),t.set("vibrato",e.vibrato),t.set("chordid",e.chordId),t.set("gracetype",e.graceType),t.set("pickstroke",e.pickStroke),t.set("tremolospeed",e.tremoloSpeed),t.set("crescendo",e.crescendo),t.set("displaystart",e.displayStart),t.set("playbackstart",e.playbackStart),t.set("displayduration",e.displayDuration),t.set("playbackduration",e.playbackDuration),t.set("dynamics",e.dynamics),t.set("invertbeamdirection",e.invertBeamDirection),t.set("preferredbeamdirection",e.preferredBeamDirection),t.set("beamingmode",e.beamingMode),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"notes":e.notes=[];for(const t of i){const i=new ee;rs.fromJson(i,t),e.addNote(i)}return!0;case"isempty":return e.isEmpty=i,!0;case"whammystyle":return e.whammyStyle=Ii.parseEnum(i,l),!0;case"ottava":return e.ottava=Ii.parseEnum(i,o),!0;case"islegatoorigin":return e.isLegatoOrigin=i,!0;case"duration":return e.duration=Ii.parseEnum(i,p),!0;case"automations":e.automations=[];for(const t of i){const i=new H;ts.fromJson(i,t),e.automations.push(i)}return!0;case"dots":return e.dots=i,!0;case"fadein":return e.fadeIn=i,!0;case"lyrics":return e.lyrics=i,!0;case"hasrasgueado":return e.hasRasgueado=i,!0;case"pop":return e.pop=i,!0;case"slap":return e.slap=i,!0;case"tap":return e.tap=i,!0;case"text":return e.text=i,!0;case"brushtype":return e.brushType=Ii.parseEnum(i,d),!0;case"brushduration":return e.brushDuration=i,!0;case"tupletdenominator":return e.tupletDenominator=i,!0;case"tupletnumerator":return e.tupletNumerator=i,!0;case"iscontinuedwhammy":return e.isContinuedWhammy=i,!0;case"whammybartype":return e.whammyBarType=Ii.parseEnum(i,F),!0;case"whammybarpoints":if(i){e.whammyBarPoints=[];for(const t of i){const i=new U;as.fromJson(i,t),e.addWhammyBarPoint(i)}}return!0;case"vibrato":return e.vibrato=Ii.parseEnum(i,_),!0;case"chordid":return e.chordId=i,!0;case"gracetype":return e.graceType=Ii.parseEnum(i,f),!0;case"pickstroke":return e.pickStroke=Ii.parseEnum(i,N),!0;case"tremolospeed":return e.tremoloSpeed=Ii.parseEnum(i,p),!0;case"crescendo":return e.crescendo=Ii.parseEnum(i,u),!0;case"displaystart":return e.displayStart=i,!0;case"playbackstart":return e.playbackStart=i,!0;case"displayduration":return e.displayDuration=i,!0;case"playbackduration":return e.playbackDuration=i,!0;case"dynamics":return e.dynamics=Ii.parseEnum(i,g),!0;case"invertbeamdirection":return e.invertBeamDirection=i,!0;case"preferredbeamdirection":return e.preferredBeamDirection=Ii.parseEnum(i,Ce),!0;case"beamingmode":return e.beamingMode=Ii.parseEnum(i,L),!0}return!1}}class os{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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=>ns.toJson(e)))),t.set("isempty",e.isEmpty),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"beats":e.beats=[];for(const t of i){const i=new oe;ns.fromJson(i,t),e.addBeat(i)}return!0;case"isempty":return e.isEmpty=i,!0}return!1}}class hs{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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=>os.toJson(e)))),t.set("similemark",e.simileMark),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"clef":return e.clef=Ii.parseEnum(i,n),!0;case"clefottava":return e.clefOttava=Ii.parseEnum(i,o),!0;case"voices":e.voices=[];for(const t of i){const i=new _e;os.fromJson(i,t),e.addVoice(i)}return!0;case"similemark":return e.simileMark=Ii.parseEnum(i,h),!0;case"displayscale":return e.displayScale=i,!0;case"displaywidth":return e.displayWidth=i,!0}return!1}}class ls{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"name":return e.name=i,!0;case"firstfret":return e.firstFret=i,!0;case"strings":return e.strings=i,!0;case"barrefrets":return e.barreFrets=i,!0;case"showname":return e.showName=i,!0;case"showdiagram":return e.showDiagram=i,!0;case"showfingering":return e.showFingering=i,!0}return!1}}class cs{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"isstandard":return e.isStandard=i,!0;case"name":return e.name=i,!0;case"tunings":return e.tunings=i,!0}return!1}}class ds{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("bars",e.bars.map((e=>hs.toJson(e)))),null!==e.chords){const i=new Map;t.set("chords",i);for(const[t,s]of e.chords)i.set(t.toString(),ls.toJson(s))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",cs.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,i){switch(t){case"bars":e.bars=[];for(const t of i){const i=new W;hs.fromJson(i,t),e.addBar(i)}return!0;case"chords":return e.chords=new Map,Ii.forEach(i,((t,i)=>{const s=new he;ls.fromJson(s,t),e.addChord(i,s)})),!0;case"capo":return e.capo=i,!0;case"transpositionpitch":return e.transpositionPitch=i,!0;case"displaytranspositionpitch":return e.displayTranspositionPitch=i,!0;case"showtablature":return e.showTablature=i,!0;case"showstandardnotation":return e.showStandardNotation=i,!0;case"ispercussion":return e.isPercussion=i,!0;case"standardnotationlinecount":return e.standardNotationLineCount=i,!0}return["stringtuning"].indexOf(t)>=0&&(cs.fromJson(e.stringTuning,i),!0)}}class us{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"volume":return e.volume=i,!0;case"balance":return e.balance=i,!0;case"port":return e.port=i,!0;case"program":return e.program=i,!0;case"primarychannel":return e.primaryChannel=i,!0;case"secondarychannel":return e.secondaryChannel=i,!0;case"ismute":return e.isMute=i,!0;case"issolo":return e.isSolo=i,!0}return!1}}class ps{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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,i){switch(t){case"elementtype":return e.elementType=i,!0;case"staffline":return e.staffLine=i,!0;case"noteheaddefault":return e.noteHeadDefault=Ii.parseEnum(i,P),!0;case"noteheadhalf":return e.noteHeadHalf=Ii.parseEnum(i,P),!0;case"noteheadwhole":return e.noteHeadWhole=Ii.parseEnum(i,P),!0;case"techniquesymbol":return e.techniqueSymbol=Ii.parseEnum(i,P),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=Ii.parseEnum(i,C),!0;case"outputmidinumber":return e.outputMidiNumber=i,!0}return!1}}class gs{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("staves",e.staves.map((e=>ds.toJson(e)))),t.set("playbackinfo",us.toJson(e.playbackInfo)),t.set("color",me.toJson(e.color)),t.set("name",e.name),t.set("shortname",e.shortName),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("percussionarticulations",e.percussionArticulations.map((e=>ps.toJson(e)))),t}static setProperty(e,t,i){switch(t){case"staves":e.staves=[];for(const t of i){const i=new Se;ds.fromJson(i,t),e.addStaff(i)}return!0;case"color":return e.color=me.fromJson(i),!0;case"name":return e.name=i,!0;case"shortname":return e.shortName=i,!0;case"defaultsystemslayout":return e.defaultSystemsLayout=i,!0;case"systemslayout":return e.systemsLayout=i,!0;case"percussionarticulations":e.percussionArticulations=[];for(const t of i){const i=new $;ps.fromJson(i,t),e.percussionArticulations.push(i)}return!0}return["playbackinfo"].indexOf(t)>=0&&(us.fromJson(e.playbackInfo,i),!0)}}class fs{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("hidedynamics",e.hideDynamics),t}static setProperty(e,t,i){return"hidedynamics"===t&&(e.hideDynamics=i,!0)}}class ms{static fromJson(e,t){t&&Ii.forEach(t,((t,i)=>this.setProperty(e,i,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=>ss.toJson(e)))),t.set("tracks",e.tracks.map((e=>gs.toJson(e)))),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("stylesheet",fs.toJson(e.stylesheet)),t}static setProperty(e,t,i){switch(t){case"album":return e.album=i,!0;case"artist":return e.artist=i,!0;case"copyright":return e.copyright=i,!0;case"instructions":return e.instructions=i,!0;case"music":return e.music=i,!0;case"notices":return e.notices=i,!0;case"subtitle":return e.subTitle=i,!0;case"title":return e.title=i,!0;case"words":return e.words=i,!0;case"tab":return e.tab=i,!0;case"tempo":return e.tempo=i,!0;case"tempolabel":return e.tempoLabel=i,!0;case"masterbars":e.masterBars=[];for(const t of i){const i=new ce;ss.fromJson(i,t),e.addMasterBar(i)}return!0;case"tracks":e.tracks=[];for(const t of i){const i=new we;gs.fromJson(i,t),e.addTrack(i)}return!0;case"defaultsystemslayout":return e.defaultSystemsLayout=i,!0;case"systemslayout":return e.systemsLayout=i,!0}return["stylesheet"].indexOf(t)>=0&&(fs.fromJson(e.stylesheet,i),!0)}}class ys{static jsonReplacer(e,t){if(t instanceof Map){if("fromEntries"in Object)return Object.fromEntries(t);{const e={};for(const[i,s]of t)e[i]=s;return e}}return ArrayBuffer.isView(t)?Array.apply([],[t]):t}static scoreToJson(e){let t=ys.scoreToJsObject(e);return JSON.stringify(t,ys.jsonReplacer)}static jsonToScore(e,t){return ys.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return ms.toJson(e)}static jsObjectToScore(e,t){let i=new pe;return ms.fromJson(i,e),i.finish(t??new Zi),i}static settingsToJson(e){let t=ys.settingsToJsObject(e);return JSON.stringify(t,ys.jsonReplacer)}static jsonToSettings(e){return ys.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return Ki.toJson(e)}static jsObjectToSettings(e){let t=new Zi;return Ki.fromJson(t,e),t}static jsObjectToMidiFile(e){let t=new Rt;return Ii.forEach(e,((e,i)=>{switch(i){case"division":t.division=e;break;case"tracks":for(let i of e){let e=ys.jsObjectToMidiTrack(i);t.tracks.push(e)}}})),t}static jsObjectToMidiTrack(e){let t=new At;return Ii.forEach(e,((e,i)=>{if("events"===i)for(let i of e){let e=ys.jsObjectToMidiEvent(i);t.events.push(e)}})),t}static jsObjectToMidiEvent(t){let i=Ii.getValue(t,"track"),s=Ii.getValue(t,"tick"),a=Ii.getValue(t,"type");switch(a){case Me.TimeSignature:return new Gt(i,s,Ii.getValue(t,"numerator"),Ii.getValue(t,"denominatorIndex"),Ii.getValue(t,"midiClocksPerMetronomeClick"),Ii.getValue(t,"thirdySecondNodesInQuarter"));case Me.AlphaTabRest:return new Wt(i,s,Ii.getValue(t,"channel"));case Me.AlphaTabMetronome:return new Ht(i,s,Ii.getValue(t,"metronomeNumerator"),Ii.getValue(t,"metronomeDurationInTicks"),Ii.getValue(t,"metronomeDurationInMilliseconds"));case Me.NoteOn:return new Ut(i,s,Ii.getValue(t,"channel"),Ii.getValue(t,"noteKey"),Ii.getValue(t,"noteVelocity"));case Me.NoteOff:return new Xt(i,s,Ii.getValue(t,"channel"),Ii.getValue(t,"noteKey"),Ii.getValue(t,"noteVelocity"));case Me.ControlChange:return new Yt(i,s,Ii.getValue(t,"channel"),Ii.getValue(t,"controller"),Ii.getValue(t,"value"));case Me.ProgramChange:return new qt(i,s,Ii.getValue(t,"channel"),Ii.getValue(t,"program"));case Me.TempoChange:return new Jt(s,Ii.getValue(t,"microSecondsPerQuarterNote"));case Me.PitchBend:return new jt(i,s,Ii.getValue(t,"channel"),Ii.getValue(t,"value"));case Me.PerNotePitchBend:return new Qt(i,s,Ii.getValue(t,"channel"),Ii.getValue(t,"noteKey"),Ii.getValue(t,"value"));case Me.EndOfTrack:return new $t(i,s)}throw new G(e.AlphaTabErrorType.Format,"Unknown Midi Event type: "+a)}static midiFileToJsObject(e){const t=new Map;t.set("division",e.division);const i=[];for(let t of e.tracks)i.push(ys.midiTrackToJsObject(t));return t.set("tracks",i),t}static midiTrackToJsObject(e){const t=new Map,i=[];for(let t of e.events)i.push(ys.midiEventToJsObject(t));return t.set("events",i),t}static midiEventToJsObject(e){const t=new Map;switch(t.set("track",e.track),t.set("tick",e.tick),t.set("type",e.type),e.type){case Me.TimeSignature:t.set("numerator",e.numerator),t.set("denominatorIndex",e.denominatorIndex),t.set("midiClocksPerMetronomeClick",e.midiClocksPerMetronomeClick),t.set("thirdySecondNodesInQuarter",e.thirtySecondNodesInQuarter);break;case Me.AlphaTabRest:t.set("channel",e.channel);break;case Me.AlphaTabMetronome:t.set("metronomeNumerator",e.metronomeNumerator),t.set("metronomeDurationInMilliseconds",e.metronomeDurationInMilliseconds),t.set("metronomeDurationInTicks",e.metronomeDurationInTicks);break;case Me.NoteOn:case Me.NoteOff:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("noteVelocity",e.noteVelocity);break;case Me.ControlChange:t.set("channel",e.channel),t.set("controller",e.controller),t.set("value",e.value);break;case Me.ProgramChange:t.set("channel",e.channel),t.set("program",e.program);break;case Me.TempoChange:t.set("microSecondsPerQuarterNote",e.microSecondsPerQuarterNote);break;case Me.PitchBend:t.set("channel",e.channel),t.set("value",e.value);break;case Me.PerNotePitchBend:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("value",e.value);case Me.EndOfTrack:}return t}}class bs{constructor(){this.ready=new Ei,this.samplesPlayed=new Ci,this.sampleRequest=new Ei}get sampleRate(){return bs.preferredSampleRate}open(){J.debug("AlphaSynth","Initializing synth worker"),this._worker=Eo.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 bs.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case bs.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(){}}bs.CmdOutputPrefix="alphaSynth.output.",bs.CmdOutputAddSamples=bs.CmdOutputPrefix+"addSamples",bs.CmdOutputPlay=bs.CmdOutputPrefix+"play",bs.CmdOutputPause=bs.CmdOutputPrefix+"pause",bs.CmdOutputResetSamples=bs.CmdOutputPrefix+"resetSamples",bs.CmdOutputSampleRequest=bs.CmdOutputPrefix+"sampleRequest",bs.CmdOutputSamplesPlayed=bs.CmdOutputPrefix+"samplesPlayed",bs.preferredSampleRate=0;class Ss{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new Mi(new bs,t),this._player.positionChanged.on(this.onPositionChanged.bind(this)),this._player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this._player.finished.on(this.onFinished.bind(this)),this._player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this._player.soundFontLoadFailed.on(this.onSoundFontLoadFailed.bind(this)),this._player.soundFontLoadFailed.on(this.onSoundFontLoadFailed.bind(this)),this._player.midiLoaded.on(this.onMidiLoaded.bind(this)),this._player.midiLoadFailed.on(this.onMidiLoadFailed.bind(this)),this._player.readyForPlayback.on(this.onReadyForPlayback.bind(this)),this._player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this._player.playbackRangeChanged.on(this.onPlaybackRangeChanged.bind(this)),this._main.postMessage({cmd:"alphaSynth.ready"})}static init(){let e=Eo.globalThis;e.addEventListener("message",(t=>{let i=t.data;if("alphaSynth.initialize"===i.cmd)bs.preferredSampleRate=i.sampleRate,J.logLevel=i.logLevel,Eo.globalThis.alphaSynthWebWorker=new Ss(e,i.bufferTimeInMilliseconds)}))}handleMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":J.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(ys.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(ys.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);break;case"alphaSynth.setChannelSolo":this._player.setChannelSolo(t.channel,t.solo);break;case"alphaSynth.setChannelVolume":this._player.setChannelVolume(t.channel,t.volume);break;case"alphaSynth.resetChannelStates":this._player.resetChannelStates();break;case"alphaSynth.destroy":this._player.destroy(),this._main.postMessage({cmd:"alphaSynth.destroyed"});break;case"alphaSynth.applyTranspositionPitches":this._player.applyTranspositionPitches(new Map(JSON.parse(t.transpositionPitches)))}}onPositionChanged(e){this._main.postMessage({cmd:"alphaSynth.positionChanged",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onPlayerStateChanged(e){this._main.postMessage({cmd:"alphaSynth.playerStateChanged",state:e.state,stopped:e.stopped})}onFinished(){this._main.postMessage({cmd:"alphaSynth.finished"})}onSoundFontLoaded(){this._main.postMessage({cmd:"alphaSynth.soundFontLoaded"})}onSoundFontLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.soundFontLoadFailed",error:this.serializeException(e)})}serializeException(e){let t=JSON.parse(JSON.stringify(e));return e.message&&(t.message=e.message),e.stack&&(t.stack=e.stack),e.constructor&&e.constructor.name&&(t.type=e.constructor.name),t}onMidiLoaded(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onMidiLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",error:this.serializeException(e)})}onReadyForPlayback(){this._main.postMessage({cmd:"alphaSynth.readyForPlayback"})}onMidiEventsPlayed(e){this._main.postMessage({cmd:"alphaSynth.midiEventsPlayed",events:e.events.map(ys.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}class ws{static generateFontLookup(e){if(!ws.FontSizeLookupTables.has(e))if(Eo.isRunningInWorker)ws.FontSizeLookupTables.set(e,new Uint8Array([8]));else{let t=document.createElement("canvas").getContext("2d");t.font=`11px ${e}`;let i=[];for(let e=32;e<255;e++){let s=String.fromCharCode(e);i.push(t.measureText(s).width)}let s=new Uint8Array(i);ws.FontSizeLookupTables.set(e,s)}}static measureString(e,t,i,s,a){let r,n=t[0];for(let e=0;e<t.length;e++)if(ws.FontSizeLookupTables.has(t[e])){n=t[e];break}ws.FontSizeLookupTables.has(n)||ws.generateFontLookup(n),r=ws.FontSizeLookupTables.get(n);let o=1;s===Ve.Italic&&(o*=1.2),a===He.Bold&&(o*=1.2);let h=0;for(let t=0;t<e.length;t++){let s=Math.min(r.length-1,e.charCodeAt(t)-32);s>=0&&(h+=r[s]*i/11)}return h*o}}ws.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]),ws.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]),ws.FontSizeLookupTables=new Map([["Arial",ws.Arial],["'Arial'",ws.Arial],['"Arial"',ws.Arial],["Georgia",ws.Georgia],["'Georgia'",ws.Georgia],['"Georgia"',ws.Georgia]]),ws.ControlChars=32;class _s{constructor(){this.id=Q.newGuid(),this.x=0,this.y=0,this.width=0,this.height=0,this.totalWidth=0,this.totalHeight=0,this.firstMasterBarIndex=-1,this.lastMasterBarIndex=-1,this.renderResult=null}}class Bs{constructor(){this.beats=[]}addBeat(e){e.barBounds=this,this.beats.push(e),this.masterBarBounds.addBeat(e)}findBeatAtPos(e){let t=null;for(let i of this.beats)if(!t||i.realBounds.x<e)t=i;else if(i.realBounds.x>e)break;return t}finish(){this.beats.sort(((e,t)=>e.realBounds.x-t.realBounds.x))}}class Ts{constructor(){this.notes=null}addNote(e){this.notes||(this.notes=[]),e.beatBounds=this,this.notes.push(e)}findNoteAtPos(e,t){const i=this.notes;if(!i)return null;for(let s of i){let i=s.noteHeadBounds.y+s.noteHeadBounds.h,a=s.noteHeadBounds.x+s.noteHeadBounds.w;if(s.noteHeadBounds.x<=e&&s.noteHeadBounds.y<=t&&e<=a&&t<=i)return s.note}return null}}class ks{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 i=null;for(let t of this.bars){let s=t.findBeatAtPos(e);if(s&&(!i||i.realBounds.x<s.realBounds.x)){const t=Math.abs(s.realBounds.x-e);(!i||t<1e7)&&(i=s)}}return i?i.beat:null}finish(){this.bars.sort(((e,t)=>e.realBounds.y<t.realBounds.y?-1:e.realBounds.y>t.realBounds.y?1:e.realBounds.x<t.realBounds.x?-1:e.realBounds.x>t.realBounds.x?1:0));for(const e of this.bars)e.finish()}addBeat(e){this.staveGroupBounds.boundsLookup.addBeat(e)}}class vs{}class xs{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 i of this.bars)if(!t||i.realBounds.x<e)t=i;else if(e>i.realBounds.x+i.realBounds.w)break;return t}}class Ns{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 i={};i.visualBounds=this.boundsToJson(e.visualBounds),i.realBounds=this.boundsToJson(e.realBounds),i.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 i of t.bars){let t={};t.visualBounds=this.boundsToJson(i.visualBounds),t.realBounds=this.boundsToJson(i.realBounds),t.beats=[];for(let e of i.beats){let i={};i.visualBounds=this.boundsToJson(e.visualBounds),i.realBounds=this.boundsToJson(e.realBounds);let s=i;if(s.beatIndex=e.beat.index,s.voiceIndex=e.beat.voice.index,s.barIndex=e.beat.voice.bar.index,s.staffIndex=e.beat.voice.bar.staff.index,s.trackIndex=e.beat.voice.bar.staff.track.index,e.notes){let t=i.notes=[];for(let i of e.notes){let e={};e.index=i.note.index,e.noteHeadBounds=this.boundsToJson(i.noteHeadBounds),t.push(e)}}t.beats.push(i)}e.bars.push(t)}i.bars.push(e)}t.push(i)}return e}static fromJson(e,t){let i=new Ns,s=e.staveGroups;for(let e of s){let s=new xs;s.visualBounds=e.visualBounds,s.realBounds=e.realBounds,i.addStaveGroup(s);for(let i of e.bars){let e=new ks;e.index=i.index,e.isFirstOfLine=i.isFirstOfLine,e.lineAlignedBounds=i.lineAlignedBounds,e.visualBounds=i.visualBounds,e.realBounds=i.realBounds,s.addBar(e);for(let s of i.bars){let i=new Bs;i.visualBounds=s.visualBounds,i.realBounds=s.realBounds,e.addBar(i);for(let e of s.beats){let s=new Ts;s.visualBounds=e.visualBounds,s.realBounds=e.realBounds;let a=e;if(s.beat=t.tracks[a.trackIndex].staves[a.staffIndex].bars[a.barIndex].voices[a.voiceIndex].beats[a.beatIndex],e.notes){s.notes=[];for(let t of e.notes){let e=new vs,i=t;e.note=s.beat.notes[i.index],e.noteHeadBounds=t.noteHeadBounds,s.addNote(e)}}i.addBeat(s)}}}}return i}boundsToJson(e){let t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(){for(let e of this.staveGroups)e.finish();this.isFinished=!0}addStaveGroup(e){e.index=this.staveGroups.length,e.boundsLookup=this,this.staveGroups.push(e),this._currentStaveGroup=e}addMasterBar(e){e.staveGroupBounds?this._masterBarLookup.set(e.index,e):(e.staveGroupBounds=this._currentStaveGroup,this._masterBarLookup.set(e.index,e),this._currentStaveGroup.addBar(e))}addBeat(e){this._beatLookup.has(e.beat.id)||this._beatLookup.set(e.beat.id,[]),this._beatLookup.get(e.beat.id)?.push(e)}findMasterBarByIndex(e){return this._masterBarLookup.has(e)?this._masterBarLookup.get(e):null}findMasterBar(e){let t=e.index;return this._masterBarLookup.has(t)?this._masterBarLookup.get(t):null}findBeat(e){const t=this.findBeats(e);return t?t[0]:null}findBeats(e){let t=e.id;return this._beatLookup.has(t)?this._beatLookup.get(t):null}getBeatAtPos(e,t){let i=0,s=this.staveGroups.length-1,a=-1;for(;i<=s;){let e=(s+i)/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?s=e-1:i=e+1}if(-1===a)return null;let r=this.staveGroups[a].findBarAtPos(e);return r?r.findBeatAtPos(e,t):null}getNoteAtPos(e,t,i){const s=this.findBeats(e);if(s)for(const e of s){const s=e.findNoteAtPos(t,i);if(s)return s}return null}}class Ps{constructor(t){this._currentLayoutMode=e.LayoutMode.Page,this._currentRenderEngine=null,this._renderedTracks=null,this.canvas=null,this.score=null,this.tracks=null,this.layout=null,this.boundsLookup=null,this.width=0,this.preRender=new Ci,this.renderFinished=new Ci,this.partialRenderFinished=new Ci,this.partialLayoutFinished=new Ci,this.postRenderFinished=new Ei,this.error=new Ci,this.settings=t,this.recreateCanvas(),this.recreateLayout()}destroy(){this.score=null,this.canvas?.destroy(),this.canvas=null,this.layout=null,this.boundsLookup=null,this.tracks=null}recreateCanvas(){return this._currentRenderEngine!==this.settings.core.engine&&(this.canvas?.destroy(),this.canvas=Eo.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=Eo.getLayoutEngineFactory(this.settings.display.layoutMode).createLayout(this),this._currentLayoutMode=this.settings.display.layoutMode,!0)}renderScore(e,t){try{this.score=e;let i=null;if(null!=e&&null!=t){if(t){i=[];for(let s of t)s>=0&&s<e.tracks.length&&i.push(e.tracks[s])}else i=e.tracks.slice(0);0===i.length&&e.tracks.length>0&&i.push(e.tracks[0])}this.tracks=i,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?(J.debug("Rendering","Request render of lazy partial "+e),t.renderLazyPartial(e)):J.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 Ns,this.recreateCanvas(),this.canvas.lineWidth=this.settings.display.scale,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){J.debug("Rendering","Rendering "+this.tracks.length+" tracks");for(let e=0;e<this.tracks.length;e++){let t=this.tracks[e];J.debug("Rendering","Track "+e+": "+t.name)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),J.debug("Rendering","Rendering finished")}else J.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),J.debug("Rendering","Clearing finished");else J.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(J.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(J.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new Ns,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):J.debug("Rendering","Current layout does not support dynamic resizing, nothing was done",null),J.debug("Rendering","Resize finished")}layoutAndRender(){J.debug("Rendering","Rendering at scale "+this.settings.display.scale+" with layout "+this.layout.name,null),this.layout.layoutAndRender(),this._renderedTracks=this.tracks,this.onRenderFinished(),this.postRenderFinished.trigger()}onRenderFinished(){this.boundsLookup?.finish();const e=new _s;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}class Es{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){Eo.globalThis.alphaTabWebWorker=new Es(Eo.globalThis)}handleMessage(e){let t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":let e=ys.jsObjectToSettings(t.settings);J.logLevel=e.core.logLevel,this._renderer=new Ps(e),this._renderer.partialRenderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialRenderFinished",result:e})})),this._renderer.partialLayoutFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialLayoutFinished",result:e})})),this._renderer.renderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.renderFinished",result:e})})),this._renderer.postRenderFinished.on((()=>{this._main.postMessage({cmd:"alphaTab.postRenderFinished",boundsLookup:this._renderer.boundsLookup?.toJson()??null})})),this._renderer.preRender.on((e=>{this._main.postMessage({cmd:"alphaTab.preRender",resize:e})})),this._renderer.error.on(this.error.bind(this));break;case"alphaTab.invalidate":this._renderer.render();break;case"alphaTab.resizeRender":this._renderer.resizeRender();break;case"alphaTab.renderResult":this._renderer.renderResult(t.resultId);break;case"alphaTab.setWidth":this._renderer.width=t.width;break;case"alphaTab.renderScore":this.updateFontSizes(t.fontSizes);let i=null==t.score?null:ys.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(i,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(e){ws.FontSizeLookupTables||(ws.FontSizeLookupTables=new Map);for(let t in e)ws.FontSizeLookupTables.set(t,e[t])}}updateSettings(e){Ki.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){J.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class Cs{constructor(){this._canvas=null,this._color=new me(0,0,0,255),this._font=new Ri("Arial",10,Ve.Plain),this._lineWidth=0;let e=document.createElement("span");e.classList.add("at"),document.body.appendChild(e);let t=window.getComputedStyle(e),i=t.fontFamily;(i.startsWith('"')||i.startsWith("'"))&&(i=i.substr(1,i.length-2)),this._musicFont=new Ri(i,parseFloat(t.fontSize),Ve.Plain),this._measureCanvas=document.createElement("canvas"),this._measureCanvas.width=10,this._measureCanvas.height=10,this._measureCanvas.style.width="10px",this._measureCanvas.style.height="10px",this._measureContext=this._measureCanvas.getContext("2d"),this._measureContext.textBaseline="hanging"}destroy(){}onRenderFinished(){return null}beginRender(e,t){this._canvas=document.createElement("canvas"),this._canvas.width=e*Eo.HighDpiFactor|0,this._canvas.height=t*Eo.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(Eo.HighDpiFactor,Eo.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,i,s){i>0&&this._context.fillRect(0|e,0|t,i,s)}strokeRect(e,t,i,s){this._context.strokeRect(0|e,0|t,i,s)}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,i,s){this._context.quadraticCurveTo(e,t,i,s)}bezierCurveTo(e,t,i,s,a,r){this._context.bezierCurveTo(e,t,i,s,a,r)}fillCircle(e,t,i){this._context.beginPath(),this._context.arc(e,t,i,0,2*Math.PI,!0),this.fill()}strokeCircle(e,t,i){this._context.beginPath(),this._context.arc(e,t,i,0,2*Math.PI,!0),this.stroke()}fill(){this._context.fill(),this._context.beginPath()}stroke(){this._context.stroke(),this._context.beginPath()}get font(){return this._font}set font(e){this._font=e,this._context&&(this._context.font=e.toCssString(this.settings.display.scale)),this._measureContext.font=e.toCssString(this.settings.display.scale)}get textAlign(){switch(this._context.textAlign){case"left":default:return E.Left;case"center":return E.Center;case"right":return E.Right}}set textAlign(e){switch(e){case E.Left:this._context.textAlign="left";break;case E.Center:this._context.textAlign="center";break;case E.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return C.Top;case"middle":return C.Middle;case"bottom":return C.Bottom}}set textBaseline(e){switch(e){case C.Top:this._context.textBaseline="hanging";break;case C.Middle:this._context.textBaseline="middle";break;case C.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,i){this._context.fillText(e,t,i)}measureText(e){return this._measureContext.measureText(e).width}fillMusicFontSymbol(e,t,i,s,a=!1){s!==P.None&&this.fillMusicFontSymbolText(e,t,i,String.fromCharCode(s),a)}fillMusicFontSymbols(e,t,i,s,a=!1){let r="";for(let e of s)e!==P.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,i,r,a)}fillMusicFontSymbolText(e,t,i,s,a=!1){let r=this._context.textAlign,n=this._context.textBaseline,o=this._context.font;this._context.font=this._musicFont.toCssString(i),this._context.textBaseline="middle",this._context.textAlign=a?"center":"left",this._context.fillText(s,e,t),this._context.textBaseline=n,this._context.font=o,this._context.textAlign=r}beginRotate(e,t,i){this._context.save(),this._context.translate(e,t),this._context.rotate(i*Math.PI/180)}endRotate(){this._context.restore()}}class Fs{constructor(e,t=!1){this._midiFile=e,this._smf1Mode=t}addTimeSignature(e,t,i){let s=0,a=i;for(;a>>=1,a>0;)s++;this._midiFile.addEvent(new Gt(0,e,t,s,48,8))}addRest(e,t,i){this._smf1Mode||this._midiFile.addEvent(new Wt(e,t,i))}addNote(e,t,i,s,a,r){this._midiFile.addEvent(new Ut(e,t,r,Fs.fixValue(s),Fs.fixValue(a))),this._midiFile.addEvent(new Xt(e,t+i,r,Fs.fixValue(s),Fs.fixValue(a)))}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,i,s,a){this._midiFile.addEvent(new Yt(e,t,i,s,Fs.fixValue(a)))}addProgramChange(e,t,i,s){this._midiFile.addEvent(new qt(e,t,i,s))}addTempo(e,t){const i=6e7/t|0;this._midiFile.addEvent(new Jt(e,i))}addBend(e,t,i,s){s=s>=Zt.MaxPitchWheel?Zt.MaxPitchWheel:Math.floor(s),this._midiFile.addEvent(new jt(e,t,i,s))}addNoteBend(e,t,i,s,a){this._smf1Mode?this.addBend(e,t,i,a):(a=a*Zt.MaxPitchWheel20/Zt.MaxPitchWheel,this._midiFile.addEvent(new Qt(e,t,i,s,a)))}finishTrack(e,t){this._midiFile.format!=Le.MultiTrack&&0!=e||this._midiFile.addEvent(new $t(e,t))}}class Ls{constructor(e,t){this.closingIndex=0,this.group=e,this.opening=t,e.closings=e.closings.sort(((e,t)=>e.index-t.index)),this.iterations=e.closings.map((e=>0))}}class Ms{get finished(){return this.index>=this._score.masterBars.length}constructor(e){this._repeatStack=[],this._groupsOnStack=new Set,this._previousAlternateEndings=0,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}processCurrent(){const e=this._score.masterBars[this.index];let t=e.alternateEndings;if(0===t&&(t=this._previousAlternateEndings),e===e.repeatGroup.opening&&e.repeatGroup.isClosed&&!this._groupsOnStack.has(e.repeatGroup)){const i=new Ls(e.repeatGroup,e);this._repeatStack.push(i),this._groupsOnStack.add(e.repeatGroup),this._previousAlternateEndings=0,t=e.alternateEndings}if(0===this._repeatStack.length||0===t)this.shouldPlay=!0;else{const e=this._repeatStack[this._repeatStack.length-1],i=e.iterations[e.closingIndex];this._previousAlternateEndings=t,this.shouldPlay=!!(t&1<<i)}this.shouldPlay&&(this.currentTick+=e.calculateDuration())}moveNext(){const e=this._score.masterBars[this.index].repeatCount-1;if(this._repeatStack.length>0&&e>0){const t=this._repeatStack[this._repeatStack.length-1];if(t.iterations[t.closingIndex]<e){this.index=t.opening.index,t.iterations[t.closingIndex]++;for(let e=0;e<t.closingIndex;e++)t.iterations[e]=0;t.closingIndex=0,this._previousAlternateEndings=0}else t.closingIndex<t.group.closings.length-1?(t.closingIndex++,this.index++):(this._repeatStack.pop(),this._groupsOnStack.delete(t.group),this.index++)}else this.index++}}class Is{constructor(e,t){this.beat=e,this.playbackStart=t}}class Ds{get duration(){return this.end-this.start}constructor(e,t){this._highlightedBeats=new Map,this.highlightedBeats=[],this.nextBeat=null,this.previousBeat=null,this.start=e,this.end=t}highlightBeat(e,t){e.isEmpty&&!e.voice.isEmpty||this._highlightedBeats.has(e.id)||(this._highlightedBeats.set(e.id,!0),this.highlightedBeats.push(new Is(e,t)))}getVisibleBeatAtStart(e){for(const t of this.highlightedBeats)if(t.playbackStart==this.start&&e.has(t.beat.voice.bar.staff.track.index))return t.beat;return null}}class As{constructor(){this.start=0,this.end=0,this.tempo=0,this.firstBeat=null,this.lastBeat=null,this.nextMasterBar=null,this.previousMasterBar=null}insertAfter(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.nextBeat=e.nextBeat,t.previousBeat=e,e.nextBeat&&(e.nextBeat.previousBeat=t),e.nextBeat=t,e==this.lastBeat&&(this.lastBeat=t))}insertBefore(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.previousBeat=e.previousBeat,t.nextBeat=e,e.previousBeat&&(e.previousBeat.nextBeat=t),e.previousBeat=t,e==this.firstBeat&&(this.firstBeat=t))}addBeat(t,i,s,a){const r=s+a;if(null==this.firstBeat){const e=new Ds(s,r);e.highlightBeat(t,i),this.insertAfter(this.firstBeat,e)}else if(s>=this.lastBeat.end){const e=new Ds(this.lastBeat.end,r);e.highlightBeat(t,i),this.insertAfter(this.lastBeat,e)}else{let a=null;if(s<this.firstBeat.start)a=this.firstBeat;else{let t=this.firstBeat;for(;null!=t;){if(s>=t.start&&s<t.end){a=t;break}t=t.nextBeat}if(null===a)throw new G(e.AlphaTabErrorType.General,"Error on building lookup, unknown variant")}if(s<a.start)if(r==a.start){const e=new Ds(s,a.start);e.highlightBeat(t,i),this.insertBefore(this.firstBeat,e)}else if(r<a.end){const e=new Ds(s,a.start);e.highlightBeat(t,i),this.insertBefore(a,e);const n=new Ds(a.start,r);for(const e of a.highlightedBeats)n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(t,i),this.insertBefore(a,n),a.start=r}else if(r==a.end){const e=new Ds(s,a.start);e.highlightBeat(t,i),a.highlightBeat(t,i),this.insertBefore(a,e)}else{const e=new Ds(s,a.start);e.highlightBeat(t,i),a.highlightBeat(t,i),this.insertBefore(a,e),this.addBeat(t,i,a.end,r-a.end)}else if(s>a.start)if(r==a.end){const e=new Ds(a.start,s);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart);a.start=s,a.highlightBeat(t,i),this.insertBefore(a,e)}else if(r<a.end){const e=new Ds(a.start,s);this.insertBefore(a,e);const n=new Ds(s,r);this.insertBefore(a,n);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart),n.highlightBeat(t.beat,t.playbackStart);n.highlightBeat(t,i),a.start=r}else{const e=new Ds(a.start,s);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart);a.start=s,a.highlightBeat(t,i),this.insertBefore(a,e),this.addBeat(t,i,a.end,r-a.end)}else if(r===a.end)a.highlightBeat(t,i);else if(r<a.end){const e=new Ds(a.start,r);for(const t of a.highlightedBeats)e.highlightBeat(t.beat,t.playbackStart);e.highlightBeat(t,i),a.start=r,this.insertBefore(a,e)}else a.highlightBeat(t,i),this.addBeat(t,i,a.end,r-a.end)}}}class Rs{get start(){return this.masterBar.start+this.beatLookup.start}get end(){return this.start+this.tickDuration}constructor(e){this.nextBeat=null,this.tickDuration=0,this.duration=0,this.masterBar=e}}class Os{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[]}findBeat(e,t,i=null){let s=null;return i&&(s=this.findBeatFast(e,i,t)),s||(s=this.findBeatSlow(e,i,t,!1)),s}findBeatFast(e,t,i){if(i>=t.start&&i<t.end)return t;if(t.nextBeat&&i>=t.nextBeat.start&&i<t.nextBeat.end){const i=t.nextBeat;return this.fillNextBeat(i,e),i}return null}fillNextBeat(e,t){e.nextBeat=this.findBeatInMasterBar(e.masterBar,e.beatLookup.nextBeat,e.end,t,!1,!0),null==e.nextBeat&&(e.nextBeat=this.findBeatSlow(t,e,e.end,!0)),e.nextBeat&&(e.tickDuration=e.nextBeat.start-e.start,e.duration=z.ticksToMillis(e.tickDuration,e.masterBar.tempo)),e.nextBeat||(e.tickDuration=e.masterBar.end-e.start,e.duration=z.ticksToMillis(e.tickDuration,e.masterBar.tempo))}findBeatSlow(e,t,i,s){let a=null;if(null!=t&&(t.masterBar.start<=i&&t.masterBar.end>i?a=t.masterBar:t.masterBar.nextMasterBar&&t.masterBar.nextMasterBar.start<=i&&t.masterBar.nextMasterBar.end>i&&(a=t.masterBar.nextMasterBar)),a||(a=this.findMasterBar(i)),!a)return null;for(;a;){if(a.firstBeat){let t=this.findBeatInMasterBar(a,a.firstBeat,i,e,!0,s);if(t)return t}a=a.nextMasterBar}return null}findBeatInMasterBar(e,t,i,s,a,r){if(!t)return null;let n=null,o=null;const h=i-e.start;for(;null!=t&&null==o;){if(t.start<=h&&h<t.end){if(n=t,o=t.getVisibleBeatAtStart(s),!o)if(r){let i=e;for(;null!=i&&null==o;){for(;null!=t;){if(o=t.getVisibleBeatAtStart(s),o){n=t,e=i;break}t=t.nextBeat}o&&n||(i=i.nextMasterBar,t=i?.firstBeat??null)}}else{let i=e;for(;null!=i&&null==o;){for(;null!=t;){if(o=t.getVisibleBeatAtStart(s),o){n=t,e=i;break}t=t.previousBeat}o&&n||(i=i.previousMasterBar,t=i?.firstBeat??null)}}}else if(t.end>h)break;t=t?.nextBeat??null}if(null==o)return null;return this.createResult(e,n,o,a,s)}createResult(e,t,i,s,a){const r=new Rs(e);return r.beat=i,r.beatLookup=t,r.tickDuration=t.end-t.start,s&&this.fillNextBeat(r,a),r.duration=z.ticksToMillis(r.tickDuration,e.tempo),r}findMasterBar(e){const t=this.masterBars;let i=0,s=t.length-1;for(;i<=s;){const a=(s+i)/2|0,r=t[a];if(e>=r.start&&e<r.end)return r;e<r.start?s=a-1:i=a+1}return null}getMasterBar(e){if(!this.masterBarLookup.has(e.index)){const t=new As;return t.masterBar=e,t}return this.masterBarLookup.get(e.index)}getMasterBarStart(e){return this.masterBarLookup.has(e.index)?this.masterBarLookup.get(e.index).start:0}getBeatStart(e){return this.masterBarLookup.has(e.voice.bar.index)?this.masterBarLookup.get(e.voice.bar.index).start+e.playbackStart:0}addMasterBar(e){this.masterBars.push(e),this._currentMasterBar&&(e.previousMasterBar=this._currentMasterBar,this._currentMasterBar.nextMasterBar=e),this._currentMasterBar=e,this.masterBarLookup.has(e.masterBar.index)||this.masterBarLookup.set(e.masterBar.index,e)}addBeat(e,t,i){const s=this._currentMasterBar;if(s)if(t<0&&s.previousMasterBar){const a=s.previousMasterBar.end-s.previousMasterBar.start,r=a+t,n=r+i;if(s.previousMasterBar.addBeat(e,r,r,i),n>a){const a=i+t;s.addBeat(e,t,0,a)}}else s.addBeat(e,t,t,i)}}class Gs{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Vs{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class Hs{constructor(e,t,i){this._currentTempo=0,this._programsPerChannel=new Map,this.tickLookup=new Os,this.applyTranspositionPitches=!0,this.transpositionPitches=new Map,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new Zi,this._currentTempo=this._score.tempo,this._handler=i}generate(){this.transpositionPitches.clear();for(const e of this._score.tracks)this.generateTrack(e);J.debug("Midi","Begin midi generation");const e=new Ms(this._score);let t=null;for(;!e.finished;){const i=e.index,s=this._score.masterBars[i],a=e.currentTick;if(e.processCurrent(),e.shouldPlay){this.generateMasterBar(s,t,a);for(const e of this._score.tracks)for(const t of e.staves)i<t.bars.length&&this.generateBar(t.bars[i],a)}e.moveNext(),t=s}for(const t of this._score.tracks)this._handler.finishTrack(t.index,e.currentTick);J.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,i,s){this._programsPerChannel.has(i)&&this._programsPerChannel.get(i)===s||(this._handler.addProgramChange(e.index,t,i,s),this._programsPerChannel.set(i,s))}static buildTranspositionPitches(e,t){const i=new Map;for(const s of e.tracks){const e=s.index<t.notation.transpositionPitches.length?t.notation.transpositionPitches[s.index]:0;i.set(s.playbackInfo.primaryChannel,e),i.set(s.playbackInfo.secondaryChannel,e)}return i}generateChannel(e,t,i){const s=e.index<this._settings.notation.transpositionPitches.length?this._settings.notation.transpositionPitches[e.index]:0;this.transpositionPitches.set(t,s);let a=Hs.toChannelShort(i.volume),r=Hs.toChannelShort(i.balance);this._handler.addControlChange(e.index,0,t,Ge.VolumeCoarse,a),this._handler.addControlChange(e.index,0,t,Ge.PanCoarse,r),this._handler.addControlChange(e.index,0,t,Ge.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,Ge.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,Ge.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,Ge.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,Ge.DataEntryCoarse,Hs.PitchBendRangeInSemitones),this.addProgramChange(e,0,t,i.program)}static toChannelShort(e){const t=Math.max(-32768,Math.min(32767,8*e-1));return Math.max(t,-1)+1}generateMasterBar(e,t,i){t&&t.timeSignatureDenominator===e.timeSignatureDenominator&&t.timeSignatureNumerator===e.timeSignatureNumerator||this._handler.addTimeSignature(i,e.timeSignatureNumerator,e.timeSignatureDenominator),e.tempoAutomation?(this._handler.addTempo(i,e.tempoAutomation.value),this._currentTempo=e.tempoAutomation.value):t||(this._handler.addTempo(i,e.score.tempo),this._currentTempo=e.score.tempo);const s=new As;s.masterBar=e,s.start=i,s.tempo=this._currentTempo,s.end=s.start+e.calculateDuration(),this.tickLookup.addMasterBar(s)}generateBar(e,t){let i=this.getPlaybackBar(e);for(const s of i.voices)this.generateVoice(s,t,e)}getPlaybackBar(e){switch(e.simileMark){case h.Simple:e.previousBar&&(e=this.getPlaybackBar(e.previousBar));break;case h.FirstOfDouble:case h.SecondOfDouble:e.previousBar&&e.previousBar.previousBar&&(e=this.getPlaybackBar(e.previousBar.previousBar))}return e}generateVoice(e,t,i){if(!e.isEmpty||e.bar.isEmpty&&0===e.index)for(const s of e.beats)this.generateBeat(s,t,i)}generateBeat(e,t,i){let s=e.playbackStart,a=e.playbackDuration;e.voice.bar.isEmpty?a=e.voice.bar.masterBar.calculateDuration():e.voice.bar.masterBar.tripletFeel!==A.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(s-=this._currentTripletFeel.secondBeatStartOffset,a=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=Hs.calculateTripletFeelInfo(s,a,e),this._currentTripletFeel&&(a=this._currentTripletFeel.firstBeatDuration))),i===e.voice.bar?this.tickLookup.addBeat(e,s,a):this.tickLookup.addBeat(e,0,a);const r=e.voice.bar.staff.track;for(const i of e.automations)this.generateAutomation(e,i,t);if(e.isRest)this._handler.addRest(r.index,t+s,r.playbackInfo.primaryChannel);else{let i=this.getBrushInfo(e);for(const r of e.notes)this.generateNote(r,t+s,a,i)}if(e.vibrato!==_.None){let i=240,a=3;switch(e.vibrato){case _.Slight:i=this._settings.player.vibrato.beatSlightLength,a=this._settings.player.vibrato.beatSlightAmplitude;break;case _.Wide:i=this._settings.player.vibrato.beatWideLength,a=this._settings.player.vibrato.beatWideAmplitude}this.generateVibratorWithParams(t+s,e.playbackDuration,i,a,((t,i)=>{this._handler.addBend(e.voice.bar.staff.track.index,t,r.playbackInfo.secondaryChannel,i)}))}}static calculateTripletFeelInfo(e,t,i){let s;switch(i.voice.bar.masterBar.tripletFeel){case A.Triplet8th:case A.Dotted8th:case A.Scottish8th:s=p.Eighth;break;case A.Triplet16th:case A.Dotted16th:case A.Scottish16th:s=p.Sixteenth;break;default:return null}const a=z.toTicks(s);if(t!==a)return null;if(e%a!=0)return null;if(!i.nextBeat||i.nextBeat.voice!==i.voice||i.playbackDuration!==a)return null;const r=new Vs;switch(i.voice.bar.masterBar.tripletFeel){case A.Triplet8th:r.firstBeatDuration=z.applyTuplet(z.toTicks(p.Quarter),3,2),r.secondBeatDuration=z.applyTuplet(z.toTicks(p.Eighth),3,2);break;case A.Dotted8th:r.firstBeatDuration=z.applyDot(z.toTicks(p.Eighth),!1),r.secondBeatDuration=z.toTicks(p.Sixteenth);break;case A.Scottish8th:r.firstBeatDuration=z.toTicks(p.Sixteenth),r.secondBeatDuration=z.applyDot(z.toTicks(p.Eighth),!1);break;case A.Triplet16th:r.firstBeatDuration=z.applyTuplet(z.toTicks(p.Eighth),3,2),r.secondBeatDuration=z.applyTuplet(z.toTicks(p.Sixteenth),3,2);break;case A.Dotted16th:r.firstBeatDuration=z.applyDot(z.toTicks(p.Sixteenth),!1),r.secondBeatDuration=z.toTicks(p.ThirtySecond);break;case A.Scottish16th:r.firstBeatDuration=z.toTicks(p.ThirtySecond),r.secondBeatDuration=z.applyDot(z.toTicks(p.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateNote(e,t,i,s){const a=e.beat.voice.bar.staff.track,r=e.beat.voice.bar.staff;let n=e.calculateRealValue(this.applyTranspositionPitches,!0);if(e.isPercussion){const t=K.getArticulation(e);t&&(n=t.outputMidiNumber)}const o=e.isStringed&&e.string<=s.length?s[e.string-1]:0,h=t+o,l=this.getNoteDuration(e,i);l.untilTieOrSlideEnd-=o,l.noteOnly-=o,l.letRingEnd-=o;const c=Hs.getNoteVelocity(e),d=e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==_.None?a.playbackInfo.secondaryChannel:a.playbackInfo.primaryChannel;let u=0;if(u=e.hasBend?Hs.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?Hs.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===w.Legato?-1:Hs.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!==S.None||e.slideOutType!==w.None?this.generateSlide(e,h,l,n,d):(e.vibrato!==_.None||e.isTieDestination&&e.tieOrigin.vibrato!==_.None)&&this.generateVibrato(e,h,l,n,d),!(e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===w.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(t,i){const s=new Gs;if(s.noteOnly=i,s.untilTieOrSlideEnd=i,s.letRingEnd=i,t.isDead)return s.noteOnly=this.applyStaticDuration(Hs.DefaultDurationDead,i),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(t.isPalmMute)return s.noteOnly=this.applyStaticDuration(Hs.DefaultDurationPalmMute,i),s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(t.isStaccato)return s.noteOnly=i/2|0,s.untilTieOrSlideEnd=s.noteOnly,s.letRingEnd=s.noteOnly,s;if(t.isTieOrigin){const e=t.tieDestination;if(e)if(t.isTieDestination){const t=this.getNoteDuration(e,e.beat.playbackDuration);s.untilTieOrSlideEnd=i+t.untilTieOrSlideEnd}else{const i=t.beat.absolutePlaybackStart,a=this.getNoteDuration(e,e.beat.playbackDuration),r=e.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-i}}else if(t.slideOutType===w.Legato){const e=t.slideTarget;if(e){const i=t.beat.absolutePlaybackStart,a=this.getNoteDuration(e,e.beat.playbackDuration),r=e.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;s.untilTieOrSlideEnd=r-i}}if(t.isLetRing&&this._settings.notation.notationMode===e.NotationMode.GuitarPro){let e=t.beat,a=0;const r=t.beat.voice.bar.masterBar.calculateDuration();for(;e.nextBeat;){let i=e.nextBeat;if(i.isRest)break;if(t.isStringed&&i.hasNoteOnString(t.string))break;if(e=e.nextBeat,a=e.absolutePlaybackStart-t.beat.absolutePlaybackStart+e.playbackDuration,a>r){a=r;break}}e===t.beat?s.letRingEnd=i:s.letRingEnd=a}else s.letRingEnd=s.untilTieOrSlideEnd;return s}applyStaticDuration(e,t){const i=this._currentTempo*e/U.MaxPosition|0;return Math.min(i,t)}static getNoteVelocity(e){let t=e.dynamics;switch(!e.beat.voice.bar.staff.isPercussion&&e.hammerPullOrigin&&t--,e.isGhost&&t--,e.accentuated){case a.Normal:t++;break;case a.Heavy:t+=2}return z.dynamicToVelocity(t)}generateFadeIn(e,t,i){const s=e.beat.voice.bar.staff.track,a=Hs.toChannelShort(s.playbackInfo.volume)/i.noteOnly,r=i.noteOnly/120|0,n=t+i.noteOnly;for(let e=r-1;e>=0;e--){const i=n-120*e,o=(i-t)*a;e===r-1&&(this._handler.addControlChange(s.index,t,s.playbackInfo.primaryChannel,Ge.VolumeCoarse,o),this._handler.addControlChange(s.index,t,s.playbackInfo.secondaryChannel,Ge.VolumeCoarse,o)),this._handler.addControlChange(s.index,i,s.playbackInfo.primaryChannel,Ge.VolumeCoarse,o),this._handler.addControlChange(s.index,i,s.playbackInfo.secondaryChannel,Ge.VolumeCoarse,o)}}generateVibrato(e,t,i,s,a){let r=0,n=0;switch(e.vibrato!==_.None?e.vibrato:e.isTieDestination?e.tieOrigin.vibrato:_.Slight){case _.Slight:r=this._settings.player.vibrato.noteSlightLength,n=this._settings.player.vibrato.noteSlightAmplitude;break;case _.Wide:r=this._settings.player.vibrato.noteWideLength,n=this._settings.player.vibrato.noteWideAmplitude;break;default:return}const o=e.beat.voice.bar.staff.track;this.generateVibratorWithParams(t,i.noteOnly,r,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,s,t)}))}generateVibratorWithParams(e,t,i,s,a){const r=this.vibratoResolution,n=i/2|0,o=(e+=i)+t;for(;e<o;){let t=0;const h=e+i<o?i:o-e;for(;t<h;){let i=s*Math.sin(t*Math.PI/n);a(e+t|0,Hs.getPitchWheel(i)),t+=r}e+=i}}static getPitchWheel(e){return Zt.DefaultPitchWheel+e/2*Hs.PitchValuePerSemitone}generateSlide(e,t,i,s,a){let r=e.slideOutType===w.Legato?i.noteOnly:i.untilTieOrSlideEnd,n=[],o=e.beat.voice.bar.staff.track;const h=this._settings.player.slide.simpleSlidePitchOffset,l=Math.floor(U.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),c=Math.floor(U.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case S.IntoFromAbove:n.push(new U(0,h)),n.push(new U(l,0));break;case S.IntoFromBelow:n.push(new U(0,-h)),n.push(new U(l,0))}switch(e.slideOutType){case w.Legato:case w.Shift:n.push(new U(c,0));const t=2*(e.slideTarget.calculateRealValue(this.applyTranspositionPitches,!0)-e.calculateRealValue(this.applyTranspositionPitches,!0));n.push(new U(U.MaxPosition,t));break;case w.OutDown:n.push(new U(U.MaxPosition-l,0)),n.push(new U(U.MaxPosition,-h));break;case w.OutUp:n.push(new U(U.MaxPosition-l,0)),n.push(new U(U.MaxPosition,h))}this.generateWhammyOrBend(t,r,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,s,t)}))}generateBend(e,t,i,s,a){let r=e.bendPoints,n=e.beat.voice.bar.staff.track;const o=(e,t)=>{this._handler.addNoteBend(n.index,e,a,s,t)};let h,d=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend;)t=t.tieDestination;h=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==f.None){switch(e.tieDestination.bendType){case c.Bend:case c.BendRelease:case c.PrebendBend:d=e.tieDestination.bendPoints[1].value;break;case c.Prebend:case c.PrebendRelease:d=e.tieDestination.bendPoints[0].value}h=Math.max(i.noteOnly,z.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo))}else h=i.noteOnly;r[0].value>0&&!e.isContinuedBend&&t>0&&t--;const u=Math.min(h,z.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));let p=[];switch(e.bendType){case c.Custom:p=r;break;case c.Bend:case c.Release:switch(e.bendStyle){case l.Default:p=r;break;case l.Gradual:p.push(new U(0,e.bendPoints[0].value)),(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),p.push(new U(U.MaxPosition,d));break;case l.Fast:return(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),void(e.beat.graceType===f.BendGrace?this.generateSongBookWhammyOrBend(t,h,!0,[e.bendPoints[0].value,d],u,o):this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,d],u,o))}break;case c.BendRelease:switch(e.bendStyle){case l.Default:p=r;break;case l.Gradual:p.push(new U(0,e.bendPoints[0].value)),p.push(new U(U.MaxPosition/2|0,e.bendPoints[1].value)),p.push(new U(U.MaxPosition,e.bendPoints[2].value));break;case l.Fast:return void this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],u,o)}break;case c.Hold:case c.Prebend:p=r;break;case c.PrebendBend:switch(e.bendStyle){case l.Default:p=r;break;case l.Gradual:p.push(new U(0,e.bendPoints[0].value)),p.push(new U(U.MaxPosition,e.bendPoints[1].value));break;case l.Fast:return o(t,0|Hs.getPitchWheel(e.bendPoints[0].value)),(!d||d<e.bendPoints[1].value)&&(d=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,d],u,o)}break;case c.PrebendRelease:switch(e.bendStyle){case l.Default:p=r;break;case l.Gradual:p.push(new U(0,e.bendPoints[0].value)),p.push(new U(U.MaxPosition,e.bendPoints[1].value));break;case l.Fast:return o(t,0|Hs.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,h,!1,[e.bendPoints[0].value,e.bendPoints[1].value],u,o)}}this.generateWhammyOrBend(t,h,p,o)}generateSongBookWhammyOrBend(e,t,i,s,a,r){const n=i?e:e+t-a,o=a/(s.length-1);for(let e=0;e<s.length-1;e++){const t=Hs.getPitchWheel(s[e]),i=Hs.getPitchWheel(s[e+1]),a=n+o*e;this.generateBendValues(a,o,t,i,r)}}generateWhammy(e,t,i,s){const a=e.whammyBarPoints,r=e.voice.bar.staff.track,n=i.noteOnly;a[0].value>0&&!e.isContinuedWhammy&&t--;const o=(e,t)=>{this._handler.addBend(r.index,e,s,t)};let h=[];switch(e.whammyBarType){case F.Custom:h=a;break;case F.Dive:switch(e.whammyStyle){case l.Default:h=a;break;case l.Gradual:h.push(new U(0,a[0].value)),h.push(new U(U.MaxPosition,a[1].value));break;case l.Fast:const e=Math.min(n,z.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],e,o)}break;case F.Dip:switch(e.whammyStyle){case l.Default:h=a;break;case l.Gradual:h.push(new U(0,a[0].value)),h.push(new U(U.MaxPosition/2|0,a[1].value)),h.push(new U(U.MaxPosition,a[2].value));break;case l.Fast:const e=Math.min(n,z.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 F.Hold:case F.Predive:h=a;break;case F.PrediveDive:switch(e.whammyStyle){case l.Default:h=a;break;case l.Gradual:h.push(new U(0,a[0].value)),h.push(new U(U.MaxPosition/2|0,a[0].value)),h.push(new U(U.MaxPosition,a[1].value));break;case l.Fast:const e=Hs.getPitchWheel(a[0].value);this._handler.addBend(r.index,t,s,0|e);const i=Math.min(n,z.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],i,o)}}this.generateWhammyOrBend(t,n,h,o)}generateWhammyOrBend(e,t,i,s){const a=t/U.MaxPosition;for(let t=0;t<i.length-1;t++){const r=i[t],n=i[t+1],o=Hs.getPitchWheel(r.value),h=Hs.getPitchWheel(n.value),l=a*(n.offset-r.offset),c=e+a*r.offset;this.generateBendValues(c,l,o,h,s)}}generateBendValues(e,t,i,s,a){const r=z.ticksToMillis(t,this._currentTempo),n=Math.abs(s-i)/Hs.PitchValuePerSemitone,o=Math.max(Hs.MinBreakpointsPerSemitone*n,r/Hs.MillisecondsPerBreakpoint),h=t/o,l=(s-i)/o;for(let t=0;t<o;t++)a(0|e,Math.round(i)),i+=l,e+=h;i<s&&a(0|e,s)}generateTrill(e,t,i,s,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=z.toTicks(e.trillSpeed),l=!0,c=t,d=t+i.untilTieOrSlideEnd;for(;c+10<d;)c+h>=d&&(h=d-c),this._handler.addNote(n.index,c,h,l?o:s,a,r),l=!l,c+=h}generateTremoloPicking(e,t,i,s,a,r){const n=e.beat.voice.bar.staff.track;let o=z.toTicks(e.beat.tremoloSpeed),h=t;const l=t+i.untilTieOrSlideEnd;for(;h+10<l;)h+o>=l&&(o=l-h),this._handler.addNote(n.index,h,o,s,a,r),h+=o}getBrushInfo(e){const t=new Int32Array(e.voice.bar.staff.tuning.length);if(e.brushType!==d.None){let i=0,s=0;for(const t of e.notes)t.isTieDestination||(i|=1<<t.string-1,s++);if(e.notes.length>0){let a=0;const r=e.brushDuration/(s-1)|0;for(let s=0;s<e.voice.bar.staff.tuning.length;s++){let n=e.brushType===d.ArpeggioDown||e.brushType===d.BrushDown?s:t.length-1-s;i&1<<n&&(t[n]=a,a+=r)}}}return t}generateAutomation(e,t,i){switch(t.type){case r.Instrument:this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,255&t.value),this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,255&t.value);break;case r.Balance:let s=Hs.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,Ge.PanCoarse,s),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Ge.PanCoarse,s);break;case r.Volume:let a=Hs.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,Ge.VolumeCoarse,a),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Ge.VolumeCoarse,a)}}prepareSingleBeat(e){let t=-1,i=-1,s=e;for(;s&&(-1===t||-1===i);){for(const s of e.automations)switch(s.type){case r.Instrument:i=s.value;break;case r.Tempo:t=s.value}s=s.previousBeat}const a=e.voice.bar.staff.track,n=e.voice.bar.masterBar;-1===t&&(t=n.score.tempo),-1===i&&(i=a.playbackInfo.program);const o=a.playbackInfo.volume;this.generateTrack(a),this._handler.addTimeSignature(0,n.timeSignatureNumerator,n.timeSignatureDenominator),this._handler.addTempo(0,t);let h=Hs.toChannelShort(o);this._handler.addControlChange(0,0,a.playbackInfo.primaryChannel,Ge.VolumeCoarse,h),this._handler.addControlChange(0,0,a.playbackInfo.secondaryChannel,Ge.VolumeCoarse,h)}generateSingleBeat(e){this.prepareSingleBeat(e),this.generateBeat(e,-e.playbackStart,e.voice.bar)}generateSingleNote(e){this.prepareSingleBeat(e.beat),this.generateNote(e,0,e.beat.playbackDuration,new Int32Array(e.beat.voice.bar.staff.tuning.length))}}Hs.DefaultDurationDead=30,Hs.DefaultDurationPalmMute=80,Hs.PitchBendRangeInSemitones=16,Hs.PitchValuePerSemitone=Zt.DefaultPitchWheel/Hs.PitchBendRangeInSemitones,Hs.MinBreakpointsPerSemitone=6,Hs.MillisecondsPerBreakpoint=150;class Ws{constructor(){this.startTick=0,this.endTick=0}}class zs{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,i){}}class Us extends zs{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Xs extends Us{constructor(e,t,i,s){super(e,t),this.glyphScale=0,this.glyphScale=i,this.symbol=s}paint(e,t,i){i.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale*this.scale,this.symbol,!1)}}class Ys extends Xs{constructor(e,t,i,s){super(e,t,s?Ys.GraceScale:1,Ys.getSymbol(i)),this._isGrace=s,this._duration=i}paint(e,t,i){let s=this._isGrace?this.scale:0;i.fillMusicFontSymbol(e+this.x,t+this.y+s,this.glyphScale*this.scale,this.symbol,!1)}doLayout(){let e=(this._isGrace?Ys.GraceScale:1)*this.scale;switch(this._duration){case p.QuadrupleWhole:this.width=14*e;break;case p.DoubleWhole:case p.Whole:this.width=14*(this._isGrace?Ys.GraceScale:1)*this.scale;break;default:this.width=Ys.QuarterNoteHeadWidth*(this._isGrace?Ys.GraceScale:1)*this.scale}this.height=Ys.NoteHeadHeight*e}static getSymbol(e){switch(e){case p.QuadrupleWhole:return P.NoteheadDoubleWholeSquare;case p.DoubleWhole:return P.NoteheadDoubleWhole;case p.Whole:return P.NoteheadWhole;case p.Half:return P.NoteheadHalf;default:return P.NoteheadBlack}}}Ys.GraceScale=.75,Ys.NoteHeadHeight=8,Ys.QuarterNoteHeadWidth=9;class qs extends Xs{constructor(e,t,i,s,a){super(e,t,a?Ys.GraceScale:1,qs.getSymbol(i,s,a))}doLayout(){this.width=0}static getSymbol(e,t,i){if(i&&(e=p.Eighth),t===Ce.Up)switch(e){case p.Eighth:return P.FlagEighthUp;case p.Sixteenth:return P.FlagSixteenthUp;case p.ThirtySecond:return P.FlagThirtySecondUp;case p.SixtyFourth:return P.FlagSixtyFourthUp;case p.OneHundredTwentyEighth:return P.FlagOneHundredTwentyEighthUp;case p.TwoHundredFiftySixth:return P.FlagTwoHundredFiftySixthUp;default:return P.FlagEighthUp}switch(e){case p.Eighth:return P.FlagEighthDown;case p.Sixteenth:return P.FlagSixteenthDown;case p.ThirtySecond:return P.FlagThirtySecondDown;case p.SixtyFourth:return P.FlagSixtyFourthDown;case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:return P.FlagOneHundredTwentyEighthDown;default:return P.FlagEighthDown}}}qs.FlagWidth=11;class Js extends zs{get onTimeX(){return this.onNotes.x+this.onNotes.centerX}constructor(e,t){super(0,0),this.ties=[],this.minWidth=0,this.beat=e,this.ties=[],this.voiceContainer=t}addTie(e){e.renderer=this.renderer,this.ties.push(e)}registerLayoutingInfo(e){let t=this.preNotes.computedWidth+this.onNotes.centerX;this.beat.graceGroup&&!this.beat.graceGroup.isComplete&&(t+=Js.GraceBeatPadding*this.renderer.scale);let i=this.onNotes.computedWidth-this.onNotes.centerX;const s=this.renderer.helpers.getBeamingHelperForBeat(this.beat);(s&&s.hasFlag||this.beat.graceType!==f.None)&&(i+=qs.FlagWidth*this.scale*(this.beat.graceType!==f.None?Ys.GraceScale:1));for(const e of this.ties)i+=e.width;this.beat.graceType!==f.None&&(i+=Js.GraceBeatPadding*this.renderer.scale),e.addBeatSpring(this.beat,t,i),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+=Js.GraceBeatPadding*this.renderer.scale),this.preNotes.x=t,this.preNotes.width=e.getPreBeatSize(this.beat),this.onNotes.width=e.getOnBeatSize(this.beat),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.updateBeamingHelper(),this.updateWidth()}doLayout(){this.preNotes.x=0,this.preNotes.renderer=this.renderer,this.preNotes.container=this,this.preNotes.doLayout(),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.renderer=this.renderer,this.onNotes.container=this,this.onNotes.doLayout();let e=this.beat.notes.length-1;for(;e>=0;)this.createTies(this.beat.notes[e--]);this.renderer.registerTies(this.ties),this.updateWidth()}updateWidth(){if(this.minWidth=this.preNotes.width+this.onNotes.width,!this.beat.isRest)if(1===this.onNotes.beamingHelper.beats.length)this.beat.duration>=p.Eighth&&(this.minWidth+=20*this.scale);else switch(this.beat.duration){case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:this.minWidth+=10*this.scale}let e=0;for(let t of this.ties)t.width>e&&(e=t.width);this.minWidth+=e,this.width=this.minWidth}scaleToWidth(e){this.onNotes.updateBeamingHelper(),this.width=e}createTies(e){}static getGroupId(e){return"b"+e.id}paint(e,t,i){if(this.beat.voice.isEmpty)return;if(this.preNotes.isEmpty&&this.onNotes.isEmpty&&0===this.ties.length)return;i.beginGroup(Js.getGroupId(this.beat)),this.preNotes.paint(e+this.x,t+this.y,i),this.onNotes.paint(e+this.x,t+this.y,i);let s=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(s,a,i)}i.endGroup()}buildBoundingsLookup(e,t,i,s){let a=new Ts;a.beat=this.beat,a.visualBounds=new nt,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 nt,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,s&&(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,i+this.y)}}Js.GraceBeatPadding=3;class js{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new Co}causeIssue(){return this.settings=null,!0}}class Qs{constructor(e){this.activeBeats=e}}class $s{constructor(e){this.bounds=null,this.beat=e}}class Ks{constructor(e,t){this._startTime=0,this._trackIndexes=null,this._trackIndexLookup=null,this._isDestroyed=!1,this.score=null,this.tracks=[],this._tickCache=null,this.player=null,this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null,this._previousTick=0,this._playerState=Ie.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=Ie.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new Ci,this.activeBeatsChanged=new Ci,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new Ci,this.beatMouseMove=new Ci,this.beatMouseUp=new Ci,this.noteMouseDown=new Ci,this.noteMouseMove=new Ci,this.noteMouseUp=new Ci,this.scoreLoaded=new Ci,this.resize=new Ci,this.renderStarted=new Ci,this.renderFinished=new Ci,this.postRenderFinished=new Ei,this.error=new Ci,this.playerReady=new Ei,this.playerFinished=new Ei,this.soundFontLoaded=new Ei,this.midiLoad=new Ci,this.midiLoaded=new Ci,this.playerStateChanged=new Ci,this.playerPositionChanged=new Ci,this.midiEventsPlayed=new Ci,this.playbackRangeChanged=new Ci,this.settingsUpdated=new Ei,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),J.logLevel=this.settings.core.logLevel,this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&Eo.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new Ps(this.settings),this.container.resize.on(Eo.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));let i=new js;i.oldWidth=this.renderer.width,i.newWidth=0|this.container.width,i.settings=this.settings,this.onResize(i),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;J.debug("rendering","Rendering completed in "+e+"ms"),this.onPostRenderFinished()})),this.renderer.preRender.on((e=>{this._startTime=Date.now()})),this.renderer.partialLayoutFinished.on(this.appendRenderResult.bind(this)),this.renderer.partialRenderFinished.on(this.updateRenderResult.bind(this)),this.renderer.renderFinished.on((e=>{this.appendRenderResult(e),this.appendRenderResult(null)})),this.renderer.error.on(this.onError.bind(this)),this.settings.player.enablePlayer&&this.setupPlayer(),this.setupClickHandling(),this.uiFacade.beginInvoke((()=>{this.uiFacade.initialRender()}))}destroy(){this._isDestroyed=!0,this.player&&this.player.destroy(),this.uiFacade.destroy(),this.renderer.destroy()}updateSettings(){const e=this.score;e&&Q.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?(this.setupPlayer(),e&&this.player?.applyTranspositionPitches(Hs.buildTranspositionPitches(e,this.settings))):this.destroyPlayer(),this.onSettingsUpdated()}load(e,t){try{return this.uiFacade.load(e,(e=>{this.renderScore(e,t)}),(e=>{this.onError(e)}))}catch(e){return this.onError(e),!1}}renderScore(e,t){let i=[];if(t)if(0===t.length)e.tracks.length>0&&i.push(e.tracks[0]);else if(1===t.length&&-1===t[0])for(let t of e.tracks)i.push(t);else for(let s of t)s>=0&&s<=e.tracks.length&&i.push(e.tracks[s]);else e.tracks.length>0&&i.push(e.tracks[0]);this.internalRenderTracks(e,i)}renderTracks(t){if(t.length>0){let i=t[0].score;for(let s of t)if(s.score!==i)return void this.onError(new G(e.AlphaTabErrorType.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(i,t)}}internalRenderTracks(e,t){if(Q.applyPitchOffsets(this.settings,e),e!==this.score){this.score=e,this.tracks=t,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this._trackIndexLookup=new Set(this._trackIndexes),this.onScoreLoaded(e),this.loadMidiForScore(),this.render()}else{this.tracks=t,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this._trackIndexLookup=new Set(this._trackIndexes),this.render()}}triggerResize(){if(this.container.isVisible){let e=new js;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 J.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{J.debug("Rendering","AlphaTab container became visible, doing autosizing",null),this.triggerResize()}))}appendRenderResult(e){e?(this.canvasElement.width=e.totalWidth,this.canvasElement.height=e.totalHeight,this._cursorWrapper&&(this._cursorWrapper.width=e.totalWidth,this._cursorWrapper.height=e.totalHeight),(e.width>0||e.height>0)&&this.uiFacade.beginAppendRenderResults(e)):this.uiFacade.beginAppendRenderResults(e)}updateRenderResult(e){e&&e.renderResult&&this.uiFacade.beginUpdateRenderResults(e)}tex(e,t){try{let i=new it;i.logErrors=!0,i.initFromString(e,this.settings);let s=i.readScore();this.renderScore(s,t)}catch(e){this.onError(e)}}loadSoundFont(e,t=!1){return!!this.player&&this.uiFacade.loadSoundFont(e,t)}resetSoundFonts(){this.player&&this.player.resetSoundFonts()}render(){this.renderer&&(this.uiFacade.canRender?(this.renderer.width=this.container.width,this.renderer.renderScore(this.score,this._trackIndexes)):this.uiFacade.canRenderChanged.on((()=>this.render())))}get tickCache(){return this._tickCache}get isReadyForPlayback(){return!!this.player&&this.player.isReadyForPlayback}get playerState(){return this.player?this.player.state:Ie.Paused}get masterVolume(){return this.player?this.player.masterVolume:0}set masterVolume(e){this.player&&(this.player.masterVolume=e)}get metronomeVolume(){return this.player?this.player.metronomeVolume:0}set metronomeVolume(e){this.player&&(this.player.metronomeVolume=e)}get countInVolume(){return this.player?this.player.countInVolume:0}set countInVolume(e){this.player&&(this.player.countInVolume=e)}get midiEventsPlayedFilter(){return this.player?this.player.midiEventsPlayedFilter:[]}set midiEventsPlayedFilter(e){this.player&&(this.player.midiEventsPlayedFilter=e)}get tickPosition(){return this.player?this.player.tickPosition:0}set tickPosition(e){this.player&&(this.player.tickPosition=e)}get timePosition(){return this.player?this.player.timePosition:0}set timePosition(e){this.player&&(this.player.timePosition=e)}get playbackRange(){return this.player?this.player.playbackRange:null}set playbackRange(e){this.player&&(this.player.playbackRange=e,this.settings.player.enableCursor&&this.updateSelectionCursor(e))}get playbackSpeed(){return this.player?this.player.playbackSpeed:0}set playbackSpeed(e){this.player&&(this.player.playbackSpeed=e)}get isLooping(){return!!this.player&&this.player.isLooping}set isLooping(e){this.player&&(this.player.isLooping=e)}destroyPlayer(){this.player&&(this.player.destroy(),this.player=null,this._previousTick=0,this._playerState=Ie.Paused,this.destroyCursors())}setupPlayer(){this.updateCursors(),this.player||(this.player=this.uiFacade.createWorkerPlayer(),this.player&&(this.player.ready.on((()=>{this.loadMidiForScore()})),this.player.readyForPlayback.on((()=>{if(this.onPlayerReady(),this.tracks)for(let e of this.tracks){let t=e.playbackInfo.volume/16;this.player.setChannelVolume(e.playbackInfo.primaryChannel,t),this.player.setChannelVolume(e.playbackInfo.secondaryChannel,t)}})),this.player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this.player.soundFontLoadFailed.on((e=>{this.onError(e)})),this.player.midiLoaded.on(this.onMidiLoaded.bind(this)),this.player.midiLoadFailed.on((e=>{this.onError(e)})),this.player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this.player.positionChanged.on(this.onPlayerPositionChanged.bind(this)),this.player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this.player.playbackRangeChanged.on(this.onPlaybackRangeChanged.bind(this)),this.player.finished.on(this.onPlayerFinished.bind(this)),this.setupPlayerEvents()))}loadMidiForScore(){if(!this.player||!this.score||!this.player.isReady)return;J.debug("AlphaTab","Generating Midi");let e=new Rt,t=new Fs(e),i=new Hs(this.score,this.settings,t);i.applyTranspositionPitches=!1,i.generate(),this._tickCache=i.tickLookup,this.onMidiLoad(e),this.player.loadMidiFile(e),this.player.applyTranspositionPitches(i.transpositionPitches)}changeTrackVolume(e,t){if(this.player)for(let i of e)this.player.setChannelVolume(i.playbackInfo.primaryChannel,t),this.player.setChannelVolume(i.playbackInfo.secondaryChannel,t)}changeTrackSolo(e,t){if(this.player)for(let i of e)this.player.setChannelSolo(i.playbackInfo.primaryChannel,t),this.player.setChannelSolo(i.playbackInfo.secondaryChannel,t)}changeTrackMute(e,t){if(this.player)for(let i of e)this.player.setChannelMute(i.playbackInfo.primaryChannel,t),this.player.setChannelMute(i.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 Rt,i=new Fs(t);new Hs(e.voice.bar.staff.track.score,this.settings,i).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;let t=new Rt,i=new Fs(t);new Hs(e.beat.voice.bar.staff.track.score,this.settings,i).generateSingleNote(e),this.player.playOneTimeMidiFile(t)}destroyCursors(){this._cursorWrapper&&(this.uiFacade.destroyCursors(),this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null)}updateCursors(){if(this.settings.player.enableCursor&&!this._cursorWrapper){let e=this.uiFacade.createCursors();e&&(this._cursorWrapper=e.cursorWrapper,this._barCursor=e.barCursor,this._beatCursor=e.beatCursor,this._selectionWrapper=e.selectionWrapper),null!==this._currentBeat&&this.cursorUpdateBeat(this._currentBeat,!1,this._previousTick>10,!0)}else!this.settings.player.enableCursor&&this._cursorWrapper&&this.destroyCursors()}setupPlayerEvents(){this._previousTick=0,this._playerState=Ie.Paused,this.renderer.postRenderFinished.on((()=>{this._currentBeat=null,this.cursorUpdateTick(this._previousTick,!1,this._previousTick>10)})),this.player&&(this.player.positionChanged.on((e=>{this._previousTick=e.currentTick,this.uiFacade.beginInvoke((()=>{this.cursorUpdateTick(e.currentTick,!1)}))})),this.player.stateChanged.on((e=>{if(this._playerState=e.state,!e.stopped&&e.state===Ie.Paused){let e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getBeatStart(e.beat))}})))}cursorUpdateTick(e,t,i=!1){let s=this._tickCache;if(s){let a=this._trackIndexLookup;if(null!=a&&a.size>0){let r=s.findBeat(a,e,this._currentBeat);r&&this.cursorUpdateBeat(r,t,i)}}}cursorUpdateBeat(e,t,i,s=!1){const a=e.beat,r=e.nextBeat?.beat??null,n=e.duration,o=e.beatLookup.highlightedBeats;if(!a)return;let h=this.renderer.boundsLookup;if(!h)return;let l=this._currentBeat,c=this._previousCursorCache,d=this._previousStateForCursor;if(!s&&a===l?.beat&&h===c&&d===this._playerState)return;let u=h.findBeat(a);u&&(this._currentBeat=e,this._previousCursorCache=h,this._previousStateForCursor=this._playerState,this.uiFacade.beginInvoke((()=>{this.internalCursorUpdateBeat(a,r,n,t,o,h,u,i)})))}scrollToCursor(){const e=this._currentBarBounds;e&&this.internalScrollToCursor(e)}internalScrollToCursor(t){let i=this.uiFacade.getScrollContainer(),s=Eo.getLayoutEngineFactory(this.settings.display.layoutMode).vertical,a=this.settings.player.scrollMode;if(s){let s=t.realBounds.y+this.settings.player.scrollOffsetY;if(s!==this._lastScroll)switch(this._lastScroll=s,a){case e.ScrollMode.Continuous:let a=this.uiFacade.getOffset(i,this.container);this.uiFacade.scrollToY(i,a.y+s,this.settings.player.scrollSpeed);break;case e.ScrollMode.OffScreen:let r=i.scrollTop+this.uiFacade.getOffset(null,i).h;if(t.visualBounds.y+t.visualBounds.h>=r||t.visualBounds.y<i.scrollTop){let e=t.realBounds.y+this.settings.player.scrollOffsetY;this.uiFacade.scrollToY(i,e,this.settings.player.scrollSpeed)}}}else{let s=t.visualBounds.x;if(s!==this._lastScroll)switch(this._lastScroll=s,a){case e.ScrollMode.Continuous:let s=t.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=t.visualBounds.x,this.uiFacade.scrollToX(i,s,this.settings.player.scrollSpeed);break;case e.ScrollMode.OffScreen:let a=i.scrollLeft+this.uiFacade.getOffset(null,i).w;if(t.visualBounds.x+t.visualBounds.w>=a||t.visualBounds.x<i.scrollLeft){let e=t.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=t.visualBounds.x,this.uiFacade.scrollToX(i,e,this.settings.player.scrollSpeed)}}}}internalCursorUpdateBeat(t,i,s,a,r,n,o,h){const l=this._barCursor,c=this._beatCursor;let d=o.barBounds.masterBarBounds,u=d.visualBounds;this._currentBarBounds=d,l&&l.setBounds(u.x,u.y,u.w,u.h),c&&(this.settings.player.enableAnimatedBeatCursor&&c.stopAnimation(),c.setBounds(o.visualBounds.x,u.y,1,u.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let p=!1;if(this._playerState===Ie.Playing&&!a){if(this.settings.player.enableElementHighlighting)for(let e of r){let i=Js.getGroupId(e.beat);this.uiFacade.highlightElements(i,t.voice.bar.index)}if(this.settings.player.enableAnimatedBeatCursor){let e=d.visualBounds.x+d.visualBounds.w;if(i){let t=n.findBeat(i);t&&t.barBounds.masterBarBounds.staveGroupBounds===d.staveGroupBounds&&(e=t.visualBounds.x)}this.uiFacade.beginInvoke((()=>{c&&c.transitionToX(s/this.playbackSpeed,e)}))}h=!a,p=!0}h&&!this._beatMouseDown&&this.settings.player.scrollMode!==e.ScrollMode.Off&&this.internalScrollToCursor(d),p&&(this.onPlayedBeatChanged(t),this.onActiveBeatsChanged(new Qs(r.map((e=>e.beat)))))}onPlayedBeatChanged(e){this._isDestroyed||(this.playedBeatChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playedBeatChanged",e))}onActiveBeatsChanged(e){this._isDestroyed||(this.activeBeatsChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"activeBeatsChanged",e))}onBeatMouseDown(e,t){this._isDestroyed||(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&(this._selectionStart=new $s(t),this._selectionEnd=null),this._beatMouseDown=!0,this.beatMouseDown.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseDown",t,e))}onNoteMouseDown(e,t){this._isDestroyed||(this._noteMouseDown=!0,this.noteMouseDown.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseDown",t,e))}onBeatMouseMove(e,t){this._isDestroyed||(this.settings.player.enableUserInteraction&&(this._selectionEnd&&this._selectionEnd.beat===t||(this._selectionEnd=new $s(t),this.cursorSelectRange(this._selectionStart,this._selectionEnd))),this.beatMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseMove",t,e))}onNoteMouseMove(e,t){this._isDestroyed||(this.noteMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseMove",t,e))}onBeatMouseUp(e,t){if(!this._isDestroyed){if(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction){if(this._selectionEnd){let e=this._tickCache?.getBeatStart(this._selectionStart.beat)??this._selectionStart.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(this._selectionEnd.beat)??this._selectionEnd.beat.absolutePlaybackStart)<e){let e=this._selectionStart;this._selectionStart=this._selectionEnd,this._selectionEnd=e}}if(this._selectionStart&&this._tickCache){let e=this._tickCache,t=e.getMasterBarStart(this._selectionStart.beat.voice.bar.masterBar);if(this._currentBeat=null,this._playerState===Ie.Paused&&this.cursorUpdateTick(this._tickCache.getBeatStart(this._selectionStart.beat),!1),this.tickPosition=t+this._selectionStart.beat.playbackStart,this._selectionEnd&&this._selectionStart.beat!==this._selectionEnd.beat){let i=e.getMasterBarStart(this._selectionEnd.beat.voice.bar.masterBar),s=new Ws;s.startTick=t+this._selectionStart.beat.playbackStart,s.endTick=i+this._selectionEnd.beat.playbackStart+this._selectionEnd.beat.playbackDuration-50,this.playbackRange=s}else this._selectionStart=null,this.playbackRange=null,this.cursorSelectRange(this._selectionStart,this._selectionEnd)}}this.beatMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseUp",t,e),this._beatMouseDown=!1}}onNoteMouseUp(e,t){this._isDestroyed||(this.noteMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseUp",t,e),this._noteMouseDown=!1)}updateSelectionCursor(e){if(this._tickCache)if(e){const t=this._tickCache.findBeat(this._trackIndexLookup,e.startTick),i=this._tickCache.findBeat(this._trackIndexLookup,e.endTick);if(t&&i){const e=new $s(t.beat),s=new $s(i.beat);this.cursorSelectRange(e,s)}}else this.cursorSelectRange(null,null)}setupClickHandling(){this.canvasElement.mouseDown.on((e=>{if(!e.isLeftMouseButton)return;this.settings.player.enableUserInteraction&&e.preventDefault();let t=e.getX(this.canvasElement),i=e.getY(this.canvasElement),s=this.renderer.boundsLookup?.getBeatAtPos(t,i)??null;if(s&&(this.onBeatMouseDown(e,s),this.settings.core.includeNoteBounds)){const a=this.renderer.boundsLookup?.getNoteAtPos(s,t,i);a&&this.onNoteMouseDown(e,a)}})),this.canvasElement.mouseMove.on((e=>{if(!this._beatMouseDown)return;let t=e.getX(this.canvasElement),i=e.getY(this.canvasElement),s=this.renderer.boundsLookup?.getBeatAtPos(t,i)??null;if(s&&(this.onBeatMouseMove(e,s),this._noteMouseDown)){const a=this.renderer.boundsLookup?.getNoteAtPos(s,t,i);a&&this.onNoteMouseMove(e,a)}})),this.canvasElement.mouseUp.on((e=>{if(!this._beatMouseDown)return;this.settings.player.enableUserInteraction&&e.preventDefault();let t=e.getX(this.canvasElement),i=e.getY(this.canvasElement),s=this.renderer.boundsLookup?.getBeatAtPos(t,i)??null;if(this.onBeatMouseUp(e,s),this._noteMouseDown)if(s){const a=this.renderer.boundsLookup?.getNoteAtPos(s,t,i)??null;this.onNoteMouseUp(e,a)}else this.onNoteMouseUp(e,null)})),this.renderer.postRenderFinished.on((()=>{this._selectionStart&&this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&this.cursorSelectRange(this._selectionStart,this._selectionEnd)}))}cursorSelectRange(e,t){let i=this.renderer.boundsLookup;if(!i)return;let s=this._selectionWrapper;if(!s)return;if(s.clear(),!e||!t||e.beat===t.beat)return;e.bounds||(e.bounds=i.findBeat(e.beat)),t.bounds||(t.bounds=i.findBeat(t.beat));let a=this._tickCache?.getBeatStart(e.beat)??e.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(t.beat)??t.beat.absolutePlaybackStart)<a){let i=e;e=t,t=i}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),s.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=i.staveGroups[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),s.appendChild(r)}let d=this.uiFacade.createSelectionElement();d.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),s.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),s.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||(J.error("API","An unexpected error occurred",e),this.error.trigger(e),this.uiFacade.triggerEvent(this.container,"error",e))}onPlayerReady(){this._isDestroyed||(this.playerReady.trigger(),this.uiFacade.triggerEvent(this.container,"playerReady",null))}onPlayerFinished(){this._isDestroyed||(this.playerFinished.trigger(),this.uiFacade.triggerEvent(this.container,"playerFinished",null))}onSoundFontLoaded(){this._isDestroyed||(this.soundFontLoaded.trigger(),this.uiFacade.triggerEvent(this.container,"soundFontLoaded",null))}onMidiLoad(e){this._isDestroyed||(this.midiLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"midiLoad",e))}onMidiLoaded(e){this._isDestroyed||(this.midiLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"midiFileLoaded",e))}onPlayerStateChanged(e){this._isDestroyed||(this.playerStateChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerStateChanged",e))}onPlayerPositionChanged(e){this._isDestroyed||null!==this.score&&this.tracks.length>0&&(this.playerPositionChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerPositionChanged",e))}onMidiEventsPlayed(e){this._isDestroyed||(this.midiEventsPlayed.trigger(e),this.uiFacade.triggerEvent(this.container,"midiEventsPlayed",e))}onPlaybackRangeChanged(e){this._isDestroyed||(this.playbackRangeChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playbackRangeChanged",e))}onSettingsUpdated(){this._isDestroyed||(this.settingsUpdated.trigger(),this.uiFacade.triggerEvent(this.container,"settingsUpdated",null))}}class Zs extends G{constructor(t,i){super(e.AlphaTabErrorType.General,t),this.xhr=i,Object.setPrototypeOf(this,Zs.prototype)}}class ea{static loadScoreAsync(e,t,i,s){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,i=new Uint8Array(e),r=ea.loadScoreFromBytes(i,s);t(r)}catch(e){i(e)}else 0===a.status?i(new Zs("You are offline!!\n Please Check Your Network.",a)):404===a.status?i(new Zs("Requested URL not found.",a)):500===a.status?i(new Zs("Internel Server Error.",a)):"parsererror"===a.statusText?i(new Zs("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?i(new Zs("Request Time out.",a)):i(new Zs("Unknow Error: "+a.responseText,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Zi);let i=Eo.buildImporters();J.debug("ScoreLoader",`Loading score from ${e.length} bytes using ${i.length} importers`);let s=null,a=ke.fromBuffer(e);for(let e of i){a.reset();try{J.debug("ScoreLoader","Importing using importer "+e.name),e.init(a,t),s=e.readScore(),J.debug("ScoreLoader","Score imported using "+e.name);break}catch(t){if(!(t instanceof V))throw J.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;J.debug("ScoreLoader",e.name+" does not support the file")}}if(s)return s;throw new V("No compatible importer found for file")}}class ta{get isLeftMouseButton(){return 0===this.mouseEvent.button}getX(e){let t=e.element,i=t.getBoundingClientRect().left+t.ownerDocument.defaultView.pageXOffset;return this.mouseEvent.pageX-i}getY(e){let t=e.element,i=t.getBoundingClientRect().top+t.ownerDocument.defaultView.pageYOffset;return this.mouseEvent.pageY-i}preventDefault(){this.mouseEvent.preventDefault()}constructor(e){this.mouseEvent=e}}class ia{get width(){return this.element.offsetWidth}set width(e){this.element.style.width=e+"px"}get scrollLeft(){return this.element.scrollLeft}set scrollLeft(e){this.element.scrollTop=e}get scrollTop(){return this.element.scrollLeft}set scrollTop(e){this.element.scrollTop=e}get height(){return this.element.offsetHeight}set height(e){this.element.style.height=e>=0?e+"px":"100%"}get isVisible(){return!!this.element.offsetWidth||!!this.element.offsetHeight||!!this.element.getClientRects().length}constructor(e){this._resizeListeners=0,this.lastBounds=new nt,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new ta(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new ta(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new ta(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&ia.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,ia.resizeObserver.value.unobserve(this.element))}}}stopAnimation(){this.element.style.transition="none"}transitionToX(e,t){this.element.style.transition=`transform ${e}ms linear`,this.setBounds(t,NaN,NaN,NaN)}setBounds(e,t,i,s){isNaN(e)&&(e=this.lastBounds.x),isNaN(t)&&(t=this.lastBounds.y),isNaN(i)&&(i=this.lastBounds.w),isNaN(s)&&(s=this.lastBounds.h),this.element.style.transform=`translate(${e}px, ${t}px) scale(${i}, ${s})`,this.element.style.transformOrigin="top left",this.lastBounds.x=e,this.lastBounds.y=t,this.lastBounds.w=i,this.lastBounds.h=s}appendChild(e){this.element.appendChild(e.element)}clear(){this.element.innerHTML=""}}ia.resizeObserver=new Y((()=>new ResizeObserver((e=>{for(const t of e){let e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class sa{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new Ci,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(Eo.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0,t=window.setInterval((()=>{J.warning("Rendering",`Could not load font '${this._families[0]}' within ${5*(e+1)} seconds`,null),this._families.length>1?(this._families.shift(),e=0):e++}),5e3);J.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);let i=e=>{this._families.length>1?(J.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(J.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},s=e=>{J.debug("Font",`[${e}] Font API signaled available`),this.isFontLoaded=!0,window.clearInterval(t),this.fontLoaded.trigger(this._families[0])},a=async()=>{for(const e of this._families)if(await this.isFontAvailable(e,!1))return void s(e);try{await document.fonts.load(`1em ${this._families[0]}`)}catch(e){i(e)}return J.debug("Font",`[${this._families[0]}] Font API signaled loaded`),await this.isFontAvailable(this._families[0],!0)?s(this._families[0]):i("Font not available"),!0};document.fonts.ready.then((()=>{a()}))}isFontAvailable(e,t){return new Promise((i=>{const s="1em "+e;if(document.fonts.check(s))i(!0);else if(t){J.debug("Font",`Font ${e} not available, creating test element to trigger load`);const t=document.createElement("div");t.style.font=s,t.style.opacity="0",t.style.position="absolute",t.style.top="0",t.style.left="0",t.innerText=`Trigger ${e} load`,document.body.appendChild(t),setTimeout((()=>{document.body.removeChild(t),document.fonts.check(s)?i(!0):i(!1)}),200)}else i(!1)}))}}class aa{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,i){let s=0;i>this._buffer.length-this.count&&(i=this._buffer.length-this.count);const a=Math.min(this._buffer.length-this._writePosition,i);return this._buffer.set(e.subarray(t,t+a),this._writePosition),this._writePosition+=a,this._writePosition%=this._buffer.length,s+=a,s<i&&(this._buffer.set(e.subarray(t+s,t+s+i-s),this._writePosition),this._writePosition+=i-s,s=i),this.count+=s,s}read(e,t,i){i>this.count&&(i=this.count);let s=0;const a=Math.min(this._buffer.length-this._readPosition,i);return e.set(this._buffer.subarray(this._readPosition,this._readPosition+a),t),s+=a,this._readPosition+=a,this._readPosition%=this._buffer.length,s<i&&(e.set(this._buffer.subarray(this._readPosition,this._readPosition+i-s),t+s),this._readPosition+=i-s,s=i),this.count-=s,s}}class ra{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new Ei,this.samplesPlayed=new Ci,this.sampleRequest=new Ei}get sampleRate(){return this._context?this._context.sampleRate:ra.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(J.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{J.debug("WebAudio",`Audio Context resume success: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}`),e&&e()}),(e=>{J.warning("WebAudio",`Audio Context resume failed: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}, reason=${e}`)})))}patchIosSampleRate(){let e=navigator.userAgent;if(-1!==e.indexOf("iPhone")||-1!==e.indexOf("iPad")){let e=this.createAudioContext(),t=e.createBuffer(1,1,ra.PreferredSampleRate),i=e.createBufferSource();i.buffer=t,i.connect(e.destination),i.start(0),i.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in Eo.globalThis)return new AudioContext;if("webkitAudioContext"in Eo.globalThis)return new webkitAudioContext;throw new G(e.AlphaTabErrorType.General,"AudioContext not found")}open(e){this.patchIosSampleRate(),this._context=this.createAudioContext(),"suspended"===this._context.state&&this.registerResumeHandler()}registerResumeHandler(){this._resumeHandler=(()=>{this.activate((()=>{this.unregisterResumeHandler()}))}).bind(this),document.body.addEventListener("touchend",this._resumeHandler,!1),document.body.addEventListener("click",this._resumeHandler,!1)}unregisterResumeHandler(){const e=this._resumeHandler;e&&(document.body.removeEventListener("touchend",e,!1),document.body.removeEventListener("click",e,!1))}play(){let e=this._context;this.activate(),this._buffer=e.createBuffer(2,ra.BufferSize,e.sampleRate),this._source=e.createBufferSource(),this._source.buffer=this._buffer,this._source.loop=!0}pause(){this._source&&(this._source.stop(0),this._source.disconnect()),this._source=null}destroy(){this.pause(),this._context?.close(),this._context=null,this.unregisterResumeHandler()}onSamplesPlayed(e){this.samplesPlayed.trigger(e)}onSampleRequest(){this.sampleRequest.trigger()}onReady(){this.ready.trigger()}}ra.BufferSize=4096,ra.PreferredSampleRate=44100;class na extends ra{constructor(){super(...arguments),this._audioNode=null,this._bufferCount=0,this._requestedBufferCount=0,this._outputBuffer=new Float32Array(0)}open(e){super.open(e),this._bufferCount=Math.floor(e*this.sampleRate/1e3/ra.BufferSize),this._circularBuffer=new aa(ra.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*ra.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*ra.BufferSize<t){for(let t=0;t<e;t++)this.onSampleRequest();this._requestedBufferCount+=e}}generateSound(e){let t=e.outputBuffer.getChannelData(0),i=e.outputBuffer.getChannelData(1),s=t.length+i.length,a=this._outputBuffer;a.length!==s&&(a=new Float32Array(s),this._outputBuffer=a);const r=this._circularBuffer.read(a,0,Math.min(a.length,this._circularBuffer.count));let n=0;for(let e=0;e<t.length;e++)t[e]=a[n++],i[e]=a[n++];this.onSamplesPlayed(r/Zt.AudioChannels),this.requestBuffers()}}class oa{constructor(e,t){this.loaded=e,this.total=t}}class ha{get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return J.logLevel}set logLevel(e){J.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Zt.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Zt.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Zt.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=wi.clamp(e,Zt.MinPlaybackSpeed,Zt.MaxPlaybackSpeed),this._playbackSpeed=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackSpeed",value:e})}get tickPosition(){return this._tickPosition}set tickPosition(e){e<0&&(e=0),this._tickPosition=e,this._synth.postMessage({cmd:"alphaSynth.setTickPosition",value:e})}get timePosition(){return this._timePosition}set timePosition(e){e<0&&(e=0),this._timePosition=e,this._synth.postMessage({cmd:"alphaSynth.setTimePosition",value:e})}get isLooping(){return this._isLooping}set isLooping(e){this._isLooping=e,this._synth.postMessage({cmd:"alphaSynth.setIsLooping",value:e})}get playbackRange(){return this._playbackRange}set playbackRange(e){e&&(e.startTick<0&&(e.startTick=0),e.endTick<0&&(e.endTick=0)),this._playbackRange=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackRange",value:e})}constructor(e,t){this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Ie.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 Ei,this.readyForPlayback=new Ei,this.finished=new Ei,this.soundFontLoaded=new Ei,this.soundFontLoadFailed=new Ci,this.midiLoaded=new Ci,this.midiLoadFailed=new Ci,this.stateChanged=new Ci,this.positionChanged=new Ci,this.midiEventsPlayed=new Ci,this.playbackRangeChanged=new Ci,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Ie.Paused,this._masterVolume=0,this._metronomeVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._output=e,this._output.ready.on(this.onOutputReady.bind(this)),this._output.samplesPlayed.on(this.onOutputSamplesPlayed.bind(this)),this._output.sampleRequest.on(this.onOutputSampleRequest.bind(this)),this._output.open(t.player.bufferTimeInMilliseconds);try{this._synth=Eo.createWebWorker(t)}catch(e){J.error("AlphaSynth","Failed to create WebWorker: "+e)}this._synth.addEventListener("message",this.handleWorkerMessage.bind(this),!1),this._synth.postMessage({cmd:"alphaSynth.initialize",sampleRate:this._output.sampleRate,logLevel:t.core.logLevel,bufferTimeInMilliseconds:t.player.bufferTimeInMilliseconds}),this.masterVolume=1,this.playbackSpeed=1,this.metronomeVolume=0}destroy(){this._synth.postMessage({cmd:"alphaSynth.destroy"})}play(){return this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.play"}),!0}pause(){this._synth.postMessage({cmd:"alphaSynth.pause"})}playPause(){this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.playPause"})}stop(){this._synth.postMessage({cmd:"alphaSynth.stop"})}playOneTimeMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.playOneTimeMidiFile",midi:ys.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,i){J.debug("AlphaSynth",`Start loading Soundfont from url ${e}`);let s=new XMLHttpRequest;s.open("GET",e,!0,null,null),s.responseType="arraybuffer",s.onload=e=>{let i=new Uint8Array(s.response);this.loadSoundFont(i,t)},s.onerror=e=>{J.error("AlphaSynth","Loading failed: "+e.message),this.soundFontLoadFailed.trigger(new Zs(e.message,s))},s.onprogress=e=>{J.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),i(new oa(e.loaded,e.total))},s.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:ys.midiFileToJsObject(e)})}applyTranspositionPitches(e){this._synth.postMessage({cmd:"alphaSynth.applyTranspositionPitches",transpositionPitches:JSON.stringify(Array.from(e.entries()))})}setChannelMute(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelMute",channel:e,mute:t})}resetChannelStates(){this._synth.postMessage({cmd:"alphaSynth.resetChannelStates"})}setChannelSolo(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelSolo",channel:e,solo:t})}setChannelVolume(e,t){t=Math.max(t,Zt.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 ai(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new Fi(t.events.map(ys.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new si(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new Li(this._playbackRange));break;case"alphaSynth.finished":this.finished.trigger();break;case"alphaSynth.soundFontLoaded":this.soundFontLoaded.trigger();break;case"alphaSynth.soundFontLoadFailed":this.soundFontLoadFailed.trigger(t.error);break;case"alphaSynth.midiLoaded":this.checkReadyForPlayback(),this.midiLoaded.trigger(new ai(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 la{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new Ci,this.partialRenderFinished=new Ci,this.partialLayoutFinished=new Ci,this.renderFinished=new Ci,this.postRenderFinished=new Ei,this.error=new Ci,this._api=e;try{this._worker=Eo.createWebWorker(t)}catch(e){return void J.error("Rendering",`Failed to create WebWorker: ${e}`)}this._worker.postMessage({cmd:"alphaTab.initialize",settings:this.serializeSettingsForWorker(t)}),this._worker.addEventListener("message",this.handleWorkerMessage.bind(this))}destroy(){this._worker.terminate()}updateSettings(e){this._worker.postMessage({cmd:"alphaTab.updateSettings",settings:this.serializeSettingsForWorker(e)})}serializeSettingsForWorker(e){const t=ys.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=Ns.fromJson(t.boundsLookup,this._api.score),this.boundsLookup.finish(),this.postRenderFinished.trigger();break;case"alphaTab.error":this.error.trigger(t.error)}}renderScore(e,t){let i=null==e?null:ys.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:i,trackIndexes:t,fontSizes:ws.FontSizeLookupTables})}}class ca{constructor(e,t,i,s){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=i,this.selectionWrapper=s}}e.WebPlatform=void 0,(Xe=e.WebPlatform||(e.WebPlatform={}))[Xe.Browser=0]="Browser",Xe[Xe.NodeJs=1]="NodeJs",Xe[Xe.BrowserModule=2]="BrowserModule";class da{static init(){var e;da._isRegistered||(da._isRegistered=!0,registerProcessor("alphatab",((e=class extends AudioWorkletProcessor{constructor(t){super(t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,J.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new aa(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){let t=e.data;switch(t.cmd){case bs.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case bs.CmdOutputResetSamples:this._circularBuffer.clear()}}process(e,t,i){if(1!==t.length&&2!==t[0].length)return!1;let s=t[0][0],a=t[0][1];if(!s||!a)return!0;let r=s.length+a.length,n=this._outputBuffer;n.length!==r&&(n=new Float32Array(r),this._outputBuffer=n);const o=this._circularBuffer.read(n,0,Math.min(n.length,this._circularBuffer.count));let h=0;for(let e=0;e<s.length;e++)s[e]=n[h++],a[e]=n[h++];return this.port.postMessage({cmd:bs.CmdOutputSamplesPlayed,samples:o/Zt.AudioChannels}),this.requestBuffers(),!0}requestBuffers(){const t=this._bufferCount/2|0;let i=t*e.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*e.BufferSize<i){for(let e=0;e<t;e++)this.port.postMessage({cmd:bs.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}da._isRegistered=!1;class ua extends ra{constructor(e){super(),this._worklet=null,this._bufferTimeInMilliseconds=0,this._settings=e}open(e){super.open(e),this._bufferTimeInMilliseconds=e,this.onReady()}play(){super.play();let e=this._context;Eo.createAudioWorklet(e,this._settings).then((()=>{this._worklet=new AudioWorkletNode(e,"alphatab",{numberOfOutputs:1,outputChannelCount:[2],processorOptions:{bufferTimeInMilliseconds:this._bufferTimeInMilliseconds}}),this._worklet.port.onmessage=this.handleMessage.bind(this),this._source.connect(this._worklet),this._source.start(0),this._worklet.connect(e.destination)}),(e=>{J.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){let t=e.data;switch(t.cmd){case bs.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case bs.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){this._worklet?.port.postMessage({cmd:bs.CmdOutputAddSamples,samples:e})}resetSamples(){this._worklet?.port.postMessage({cmd:bs.CmdOutputResetSamples})}}class pa extends ia{constructor(e,t,i){super(e),this._xscale=t,this._yscale=i}get width(){return this.element.offsetWidth/this._xscale}set width(e){this.element.style.width=e*this._xscale+"px"}get height(){return this.element.offsetHeight/this._yscale}set height(e){this.element.style.height=e>=0?e*this._yscale+"px":"100%"}setBounds(e,t,i,s){isNaN(e)&&(e=this.lastBounds.x),isNaN(t)&&(t=this.lastBounds.y),isNaN(i)?i=this.lastBounds.w:i/=this._xscale,isNaN(s)?s=this.lastBounds.h:s/=this._yscale,this.element.style.transform=`translate(${e}px, ${t}px) scale(${i}, ${s})`,this.element.style.transformOrigin="top left",this.lastBounds.x=e,this.lastBounds.y=t,this.lastBounds.w=i,this.lastBounds.h=s}}!function(e){e[e.LayoutDone=0]="LayoutDone",e[e.RenderRequested=1]="RenderRequested",e[e.RenderDone=2]="RenderDone",e[e.Detached=3]="Detached"}(Ye||(Ye={}));class ga{get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(Eo.bravuraFontChecker.checkForFontAvailability(),!Eo.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(J.debug("Font","All fonts loaded: "+this._fontCheckers.size),!0)}onFontLoaded(e){ws.generateFontLookup(e),this.areAllFontsLoaded()&&this.canRenderChanged.trigger()}constructor(t){if(this._fontCheckers=new Map,this._contents=null,this._file=null,this._totalResultCount=0,this._initialTrackIndexes=null,this._barToElementLookup=new Map,this._resultIdToElementLookup=new Map,this.rootContainerBecameVisible=new Ei,this.canRenderChanged=new Ei,this._highlightedElements=[],this._scrollContainer=null,Eo.webPlatform!==e.WebPlatform.Browser&&Eo.webPlatform!==e.WebPlatform.BrowserModule)throw new G(e.AlphaTabErrorType.General,"Usage of AlphaTabApi is only possible in browser environments. For usage in node use the Low Level APIs");t.classList.add("alphaTab"),this.rootContainer=new ia(t),this.areWorkersSupported="Worker"in window,Eo.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(t)}onElementVisibilityChanged(e){for(const t of e){const e=t.target;if(e===this.rootContainer.element)t.isIntersecting&&(this.rootContainerBecameVisible.trigger(),this._intersectionObserver.unobserve(this.rootContainer.element));else if("layoutResultId"in e&&this._api.settings.core.enableLazyLoading){const i=e;t.isIntersecting?i.renderedResultId!==i.layoutResultId?this._resultIdToElementLookup.has(i.layoutResultId)?i.resultState!==Ye.RenderRequested&&(i.resultState=Ye.RenderRequested,this._api.renderer.renderResult(i.layoutResultId)):e.replaceChildren():i.resultState===Ye.Detached&&(e.replaceChildren(...i.renderedResult),i.resultState=Ye.RenderDone):i.resultState===Ye.RenderDone&&(i.resultState=Ye.Detached,i.replaceChildren())}}}createWorkerRenderer(){return new la(this._api,this._api.settings)}initialize(t,i){let s;this._api=t,s=i instanceof Zi?i:ys.jsObjectToSettings(i);let a=this.getDataAttributes();Ki.fromJson(s,a),s.notation.notationMode===e.NotationMode.SongBook&&s.setSongBookModeSettings(),t.settings=s,this.setupFontCheckers(s),this._initialTrackIndexes=this.parseTracks(s.core.tracks),this._contents="";let r=t.container;s.core.tex&&(this._contents=r.element.innerHTML,r.element.innerHTML=""),this.createStyleElement(s),this._file=s.core.file}setupFontCheckers(e){this.registerFontChecker(e.display.resources.copyrightFont),this.registerFontChecker(e.display.resources.effectFont),this.registerFontChecker(e.display.resources.fingeringFont),this.registerFontChecker(e.display.resources.graceFont),this.registerFontChecker(e.display.resources.markerFont),this.registerFontChecker(e.display.resources.tablatureFont),this.registerFontChecker(e.display.resources.titleFont),this.registerFontChecker(e.display.resources.wordsFont),this.registerFontChecker(e.display.resources.barNumberFont),this.registerFontChecker(e.display.resources.fretboardNumberFont),this.registerFontChecker(e.display.resources.subTitleFont)}registerFontChecker(e){if(!this._fontCheckers.has(e.families.join(", "))){let t=new sa(e.families);this._fontCheckers.set(e.families.join(", "),t),t.fontLoaded.on(this.onFontLoaded.bind(this)),t.checkForFontAvailability()}}destroy(){this.rootContainer.element.innerHTML=""}createCanvasElement(){let e=document.createElement("div");return e.className="at-surface",e.style.fontSize="0",e.style.overflow="hidden",e.style.lineHeight="0",e.style.position="relative",new ia(e)}triggerEvent(e,t,i=null,s){let a=e.element;t="alphaTab."+t;let r=document.createEvent("CustomEvent"),n=s?s.mouseEvent:null;if(r.initCustomEvent(t,!1,!1,i),n&&(r.originalEvent=n),a.dispatchEvent(r),window&&"jQuery"in window){let e=window.jQuery,s=[];s.push(i),n&&s.push(n),e(a).trigger(t,s)}}load(e,t,i){if(e instanceof pe)return t(e),!0;if(e instanceof ArrayBuffer){let i=new Uint8Array(e);return t(ea.loadScoreFromBytes(i,this._api.settings)),!0}return e instanceof Uint8Array?(t(ea.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(ea.loadScoreAsync(e,t,i,this._api.settings),!0)}loadSoundFont(e,t){return!!this._api.player&&(e instanceof ArrayBuffer?(this._api.player.loadSoundFont(new Uint8Array(e),t),!0):e instanceof Uint8Array?(this._api.player.loadSoundFont(e,t),!0):"string"==typeof e&&(this._api.loadSoundFontFromUrl(e,t),!0))}initialRender(){this._api.renderer.preRender.on((e=>{this._totalResultCount=0,this._resultIdToElementLookup.clear(),this._barToElementLookup.clear()}));const e=()=>{this._api.renderer.width=0|this.rootContainer.width,this._api.renderer.updateSettings(this._api.settings),this._contents?(this._api.tex(this._contents,this._initialTrackIndexes??void 0),this._initialTrackIndexes=null):this._file&&ea.loadScoreAsync(this._file,(e=>{this._api.renderScore(e,this._initialTrackIndexes??void 0),this._initialTrackIndexes=null}),(e=>{this._api.onError(e)}),this._api.settings)};this.rootContainer.isVisible?e():this.rootContainerBecameVisible.on(e)}createStyleElement(e){let t=this._api.container.element.ownerDocument;Eo.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 i=e.length,s=e;for(let e=0;e<i;e++){let i=s[e],a=0;a="number"==typeof i?i:"index"in i?i.index:parseInt(i.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 i of Object.keys(t.dataset)){let s=t.dataset[i];try{let e=s;s=JSON.parse(e)}catch(e){""===s&&(s=null)}e.set(i,s)}else for(let i=0;i<t.attributes.length;i++){let s=t.attributes.item(i),a=s.nodeName;if(a.startsWith("data-")){let t=a.substr(5).split("-"),i=t[0];for(let e=1;e<t.length;e++)i+=t[e].substr(0,1).toUpperCase()+t[e].substr(1);let r=s.nodeValue;try{r=JSON.parse(r)}catch(e){""===r&&(r=null)}e.set(i,r)}}return e}beginUpdateRenderResults(e){if(!this._resultIdToElementLookup.has(e.id))return;const t=this._resultIdToElementLookup.get(e.id),i=e.renderResult;"string"==typeof i?t.innerHTML=i:"nodeType"in i&&t.replaceChildren(i),t.resultState=Ye.RenderDone,t.renderedResultId=e.id,t.renderedResult=Array.from(t.children)}beginAppendRenderResults(e){const t=this._api.canvasElement.element;if(e){let i;this._totalResultCount<t.childElementCount?i=t.childNodes.item(this._totalResultCount):(i=document.createElement("div"),t.appendChild(i)),i.style.zIndex="1",i.style.position="absolute",i.style.left=e.x+"px",i.style.top=e.y+"px",i.style.width=e.width+"px",i.style.height=e.height+"px",i.style.display="inline-block",i.layoutResultId=e.id,i.resultState=Ye.LayoutDone,delete i.renderedResultId,delete i.renderedResult,this._resultIdToElementLookup.set(e.id,i);for(let t=e.firstMasterBarIndex;t<=e.lastMasterBarIndex;t++)t>=0&&this._barToElementLookup.set(t,i);this._api.settings.core.enableLazyLoading&&(this._intersectionObserver.unobserve(i),this._intersectionObserver.observe(i)),this._totalResultCount++}else for(;t.childElementCount>this._totalResultCount;)this._api.settings.core.enableLazyLoading&&this._intersectionObserver.unobserve(t.lastChild),t.removeChild(t.lastElementChild)}createWorkerPlayer(){let t=null,i="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window&&this._api.settings.player.outputMode===e.PlayerOutputMode.WebAudioAudioWorklets?(J.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),t=new ha(new ua(this._api.settings),this._api.settings)):i&&(J.debug("Player","Will use webworkers for synthesizing and web audio api with ScriptProcessor for playback"),t=new ha(new na,this._api.settings)),t?t.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):J.error("Player","Player requires webworkers and web audio api, browser unsupported",null),t}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const i=this._barToElementLookup.get(t);if(i){let t=i.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 i=document.createElement("div");i.classList.add("at-selection");const s=this.createScalingElement(),a=this.createScalingElement();let r=s.element;r.classList.add("at-cursor-bar");let n=a.element;return n.classList.add("at-cursor-beat"),e.style.position="relative",e.style.textAlign="left",t.style.position="absolute",t.style.zIndex="1000",t.style.display="inline",t.style.pointerEvents="none",i.style.position="absolute",r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.willChange="transform",s.width=1,s.height=1,s.setBounds(0,0,1,1),n.style.position="absolute",n.style.transition="all 0s linear",n.style.left="0",n.style.top="0",n.style.willChange="transform",a.width=3,a.height=1,a.setBounds(0,0,1,1),e.insertBefore(t,e.firstChild),t.appendChild(i),t.appendChild(r),t.appendChild(n),new ca(new ia(t),s,a,new ia(i))}getOffset(e,t){let i=t.element,s=i.getBoundingClientRect(),a=s.top+i.ownerDocument.defaultView.pageYOffset,r=s.left+i.ownerDocument.defaultView.pageXOffset;if(e){let t=e.element,i=t.nodeName.toLowerCase();if("html"!==i&&"body"!==i){let i=this.getOffset(null,e);a=a+t.scrollTop-i.y,r=r+t.scrollLeft-i.x}}let n=new nt;return n.x=r,n.y=a,n.w=s.width,n.h=s.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 ia(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new pa(e,100,100);return t.width=1,t.height=1,t.setBounds(0,0,1,1),t}scrollToY(e,t,i){this.internalScrollToY(e.element,t,i)}scrollToX(e,t,i){this.internalScrollToX(e.element,t,i)}internalScrollToY(e,t,i){if(this._api.settings.player.nativeBrowserSmoothScroll)e.scrollTo({top:t,behavior:"smooth"});else{let s=e.scrollTop,a=t-s,r=0,n=t=>{0===r&&(r=t);let o=t-r,h=Math.min(o/i,1);e.scrollTop=s+a*h|0,o<i&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}internalScrollToX(e,t,i){if(this._api.settings.player.nativeBrowserSmoothScroll)e.scrollTo({left:t,behavior:"smooth"});else{let s=e.scrollLeft,a=t-s,r=0,n=t=>{0===r&&(r=t);let o=t-r,h=Math.min(o/i,1);e.scrollLeft=s+a*h|0,o<i&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}}class fa extends Ks{constructor(e,t){super(new ga(e),t),this.soundFontLoad=new Ci}tex(e,t){let i=this.uiFacade;super.tex(e,i.parseTracks(t))}print(t,i=null){let s=window.open("","","width=0,height=0"),a=s.document.createElement("div");t?a.style.width=t:this.settings.display.layoutMode===e.LayoutMode.Horizontal?a.style.width="297mm":a.style.width="210mm",s.document.write("\n <!DOCTYPE html>\n <html>\n <head>\n <style>\n .at-surface {\n width: auto !important;\n height: auto !important;\n }\n .at-surface > div {\n position: relative!important;\n left: auto !important;\n top: auto !important;\n break-inside: avoid;\n }\n </style>\n </head>\n <body></body>\n </html>\n ");const r=this.score;r&&(r.artist&&r.title?s.document.title=`${r.title} - ${r.artist}`:r.title&&(s.document.title=`${r.title}`)),s.document.body.appendChild(a);let n=void 0!==window.screenLeft?window.screenLeft:window.left,o=void 0!==window.screenTop?window.screenTop:window.top,h="innerWidth"in window?window.innerWidth:"clientWidth"in document.documentElement?document.documentElement.clientWidth:window.screen.width,l="innerHeight"in window?window.innerHeight:"clientHeight"in document.documentElement?document.documentElement.clientHeight:window.screen.height,c=a.offsetWidth+50,d=window.innerHeight,u=(h/2|0)-(c/2|0)+n,p=(l/2|0)-(d/2|0)+o;s.resizeTo(c,d),s.moveTo(u,p),s.focus();let g=ys.jsObjectToSettings(ys.settingsToJsObject(this.settings));g.core.enableLazyLoading=!1,g.core.useWorkers=!0,g.core.file=null,g.core.tracks=null,g.player.enableCursor=!1,g.player.enablePlayer=!1,g.player.enableElementHighlighting=!1,g.player.enableUserInteraction=!1,g.player.soundFont=null,g.display.scale=.8,g.display.stretchForce=.8,Ki.fromJson(g,i);let f=new fa(a,g);s.onunload=()=>{f.destroy()},f.renderer.postRenderFinished.on((()=>{s.print()})),f.renderTracks(this.tracks)}downloadMidi(e=Le.SingleTrackMultiChannel){if(!this.score)return;let t=new Rt;t.format=e;let i=new Fs(t,!0);new Hs(this.score,this.settings,i).generate();let s=t.toBinary(),a=this.score.title?`${this.score.title}.mid`:"File.mid",r=document.createElement("a");r.download=a;let n=new Blob([s],{type:"audio/midi"}),o=URL.createObjectURL(n);r.href=o,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}changeTrackMute(e,t){let i=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackMute(i,t)}changeTrackSolo(e,t){let i=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackSolo(i,t)}changeTrackVolume(e,t){let i=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackVolume(i,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 i of e)i>=0&&i<this.score.tracks.length&&t.push(this.score.tracks[i]);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 ma{constructor(){this._initListeners=[]}exec(e,t,i){if("string"!=typeof t&&(i=[t],t="init"),95===t.charCodeAt(0)||"exec"===t)return null;let s=new jQuery(e),a=s.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=[s,a].concat(i);return r.apply(this,e)}return J.error("Api","Method '"+t+"' does not exist on jQuery.alphaTab"),null}init(e,t,i){if(!t){t=new fa(e[0],i),e.data("alphaTab",t);for(let s of this._initListeners)s(e,t,i)}}destroy(e,t){e.removeData("alphaTab"),t.destroy()}print(e,t,i,s){t.print(i,s)}load(e,t,i,s){return t.load(i,s)}render(e,t){t.render()}renderScore(e,t,i,s){t.renderScore(i,s)}renderTracks(e,t,i){t.renderTracks(i)}invalidate(e,t){t.render()}tex(e,t,i,s){t.tex(i,s)}muteTrack(e,t,i,s){t.changeTrackMute(i,s)}soloTrack(e,t,i,s){t.changeTrackSolo(i,s)}trackVolume(e,t,i,s){t.changeTrackVolume(i,s)}loadSoundFont(e,t,i,s){t.loadSoundFont(i,s)}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,i){return"number"==typeof i&&(t.masterVolume=i),t.masterVolume}metronomeVolume(e,t,i){return"number"==typeof i&&(t.metronomeVolume=i),t.metronomeVolume}countInVolume(e,t,i){return"number"==typeof i&&(t.countInVolume=i),t.countInVolume}midiEventsPlayedFilter(e,t,i){return Array.isArray(i)&&(t.midiEventsPlayedFilter=i),t.midiEventsPlayedFilter}playbackSpeed(e,t,i){return"number"==typeof i&&(t.playbackSpeed=i),t.playbackSpeed}tickPosition(e,t,i){return"number"==typeof i&&(t.tickPosition=i),t.tickPosition}timePosition(e,t,i){return"number"==typeof i&&(t.timePosition=i),t.timePosition}loop(e,t,i){return"boolean"==typeof i&&(t.isLooping=i),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 ya{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.color=new me(255,255,255,255),this.lineWidth=1,this.font=new Ri("Arial",10,Ve.Plain),this.textAlign=E.Left,this.textBaseline=C.Top}destroy(){}beginRender(e,t){this.buffer=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${0|e}px" height="${0|t}px" class="at-surface-svg">\n`,this._currentPath="",this._currentPathIsEmpty=!0,this.textBaseline=C.Top}beginGroup(e){this.buffer+=`<g class="${e}">`}endGroup(){this.buffer+="</g>"}endRender(){return this.buffer+="</svg>",this.buffer}fillRect(e,t,i,s){i>0&&(this.buffer+=`<rect x="${0|e}" y="${0|t}" width="${i}" height="${s}" fill="${this.color.rgba}" />\n`)}strokeRect(e,t,i,s){this.buffer+=`<rect x="${0|e}" y="${0|t}" width="${i}" height="${s}" 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,i,s){this._currentPathIsEmpty=!1,this._currentPath+=` Q${e},${t},${i},${s}`}bezierCurveTo(e,t,i,s,a,r){this._currentPathIsEmpty=!1,this._currentPath+=` C${e},${t},${i},${s},${a},${r}`}fillCircle(e,t,i){this._currentPathIsEmpty=!1,this._currentPath+=` M${e-i},${t} A1,1 0 0,0 ${e+i},${t} A1,1 0 0,0 ${e-i},${t} z`,this.fill()}strokeCircle(e,t,i){this._currentPathIsEmpty=!1,this._currentPath+=` M${e-i},${t} A1,1 0 0,0 ${e+i},${t} A1,1 0 0,0 ${e-i},${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,i){if(""===e)return;let s=`<text x="${0|t}" y="${0|i}" style="stroke: none; font:${this.font.toCssString(this.settings.display.scale)}" ${this.getSvgBaseLine()}`;"#000000"!==this.color.rgba&&(s+=` fill="${this.color.rgba}"`),this.textAlign!==E.Left&&(s+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),s+=`>${ya.escapeText(e)}</text>`,this.buffer+=s}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 E.Left:return"start";case E.Center:return"middle";case E.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case C.Top:return'dominant-baseline="hanging"';case C.Bottom:return'dominant-baseline="bottom"';default:return""}}measureText(e){return e?ws.measureString(e,this.font.families,this.font.size,this.font.style,this.font.weight):0}onRenderFinished(){return null}beginRotate(e,t,i){this.buffer+='<g transform="translate('+e+" ,"+t+") rotate( "+i+')">'}endRotate(){this.buffer+="</g>"}}class ba extends ya{constructor(){super()}fillMusicFontSymbol(e,t,i,s,a){s!==P.None&&this.fillMusicFontSymbolText(e,t,i,`&#${s};`,a)}fillMusicFontSymbols(e,t,i,s,a){let r="";for(let e of s)e!==P.None&&(r+=`&#${e};`);this.fillMusicFontSymbolText(e,t,i,r,a)}fillMusicFontSymbolText(e,t,i,s,a){this.buffer+=`<g transform="translate(${e} ${t})" class="at" ><text`,this.buffer+=1!==i?` style="font-size: ${100*i}%; stroke:none"`:' style="stroke:none"',"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),a&&(this.buffer+=' text-anchor="'+this.getSvgTextAlignment(E.Center)+'"'),this.buffer+=`>${s}</text></g>`}}class Sa{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"}(qe||(qe={}));class wa extends zs{get isEmpty(){return!this.glyphs||0===this.glyphs.length}constructor(e,t){super(e,t),this.glyphs=null}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);let e=0;for(let t=0,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];i.renderer=this.renderer,i.doLayout(),e=Math.max(e,i.width)}this.width=e}addGlyph(e){this.glyphs||(this.glyphs=[]),this.renderer&&(e.renderer=this.renderer),this.glyphs.push(e)}paint(e,t,i){let s=this.glyphs;if(s&&0!==s.length)for(let a of s)a.paint(e+this.x,t+this.y,i)}}class _a extends wa{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 Ba extends wa{constructor(e,t,i){super(e,t),this.voice=i,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){const t=this.renderer.scale;let i=this.renderer.layoutingInfo.spaceToForce(e/t);this.scaleToForce(i)}scaleToForce(e){const t=this.renderer.scale;this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e)*t;let i=this.renderer.layoutingInfo.buildOnTimePositions(e),s=this.beatGlyphs;for(let e=0,a=s.length;e<a;e++){let r=s[e];if(r.beat.graceType===f.None)r.x=i.get(r.beat.absoluteDisplayStart)*t-r.onTimeX;else{const a=r.beat.graceGroup.beats[0].absoluteDisplayStart,n=r.beat.graceGroup.id;if(r.beat.graceGroup.isComplete&&i.has(a)){r.x=i.get(a)*t-r.onTimeX;let e=this.renderer.layoutingInfo.allGraceRods.get(n);const s=r.beat.graceGroup.beats[r.beat.graceGroup.beats.length-1].nextBeat,o=s?this.renderer.layoutingInfo.getPreBeatSize(s)+Js.GraceBeatPadding*this.renderer.scale:0;r.x-=o,r.x-=e[r.beat.graceIndex].postSpringWidth,r.x+=e[r.beat.graceIndex].graceBeatWidth;const h=e[r.beat.graceGroup.beats.length-1];r.x-=h.graceBeatWidth}else{let t=this.renderer.layoutingInfo.incompleteGraceRods.get(n);const i=t[r.beat.graceIndex].postSpringWidth-t[r.beat.graceIndex].preSpringWidth;e>0?0===r.beat.graceIndex?r.x=s[e-1].x+s[e-1].width:r.x=s[e-1].x+t[r.beat.graceIndex-1].postSpringWidth-t[r.beat.graceIndex-1].preSpringWidth-i:r.x=-i}}if(e>0){let t=r.x-s[e-1].x;s[e-1].scaleToWidth(t)}if(e===a-1){let e=this.width-s[s.length-1].x;r.scaleToWidth(e)}}}registerLayoutingInfo(e){e.updateVoiceSize(this.width);let t=this.beatGlyphs;for(let i of t)i.registerLayoutingInfo(e)}applyLayoutingInfo(e){let t=this.beatGlyphs;for(let i of t)i.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,i){i.color=0===this.voice.index?this.renderer.resources.mainGlyphColor:this.renderer.resources.secondaryGlyphColor;for(let s=0,a=this.beatGlyphs.length;s<a;s++)this.beatGlyphs[s].paint(e+this.x,t+this.y,i)}}Ba.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"}(Je||(Je={}));class Ta{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class ka{constructor(e){this._registeredAccidentals=new Map,this._appliedScoreLines=new Map,this._appliedScoreLinesByValue=new Map,this._notesByValue=new Map,this._beatLines=new Map,this.maxLineBeat=null,this.minLineBeat=null,this.maxLine=-1e3,this.minLine=-1e3,this._barRenderer=e,this._bar=e.bar}static getPercussionLine(e,t){return t<e.staff.track.percussionArticulations.length?e.staff.track.percussionArticulations[t].staffLine:K.getArticulationByValue(t)?.staffLine??0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case b.ForceDoubleFlat:t+=2;break;case b.ForceDoubleSharp:t-=2;break;case b.ForceFlat:t+=1;break;case b.ForceSharp:t-=1}return t}applyAccidental(e){const t=ka.getNoteValue(e);let i=e.hasQuarterToneOffset;return this.getAccidental(t,i,e.beat,!1,e)}applyAccidentalForValue(e,t,i,s){return this.getAccidental(t,i,e,s,null)}static computeLineWithoutAccidentals(e,t){let i=0;const s=ka.getNoteValue(t);if(e.staff.isPercussion)i=ka.getPercussionLine(e,s);else{const a=t?t.accidentalMode:b.Default;i=ka.calculateNoteLine(e,s,a)}return i}getAccidental(e,t,i,s,a=null){let r=Je.None,n=0;if(this._bar.staff.isPercussion)n=ka.getPercussionLine(this._bar,e);else{const i=a?a.accidentalMode:b.Default;n=ka.calculateNoteLine(this._bar,e,i);let s=this._bar.masterBar.keySignature+7,o=e%12,h=s<7?Je.Flat:Je.Sharp,l=ka.KeySignatureLookup[s][o],c=ka.AccidentalNotes[o];if(t)switch(r=c?h:Je.Natural,r){case Je.Natural:r=Je.NaturalQuarterNoteUp;break;case Je.Sharp:r=Je.SharpQuarterNoteUp;break;case Je.Flat:r=Je.FlatQuarterNoteUp}else{switch(i){case b.ForceSharp:r=Je.Sharp;break;case b.ForceDoubleSharp:r=Je.DoubleSharp;break;case b.ForceFlat:r=Je.Flat;break;case b.ForceDoubleFlat:r=Je.DoubleFlat;break;default:c?r=h:l&&(r=Je.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=Je.None:r!==Je.None?(this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===r&&(r=Je.None):l&&r===h&&(r=Je.None),r!==Je.None&&this._registeredAccidentals.set(n,r)):this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===Je.Natural?r=Je.None:(r=Je.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=i),(-1e3===this.maxLine||this.maxLine>n)&&(this.maxLine=n,this.maxLineBeat=i),s||this.registerLine(i,n),r}registerLine(e,t){let i;this._beatLines.has(e.id)?i=this._beatLines.get(e.id):(i=new Ta,this._beatLines.set(e.id,i)),(-1e3===i.minLine||t<i.minLine)&&(i.minLine=t),(-1e3===i.minLine||t>i.maxLine)&&(i.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,i){let s=t,a=e.masterBar.keySignature,r=e.clef,n=s%12,o=(s/12|0)-1,h=ka.OctaveSteps[r];return h-=o*ka.StepsPerOctave,h-=(Q.keySignatureIsSharp(a)||Q.keySignatureIsNatural(a)?ka.SharpNoteSteps:ka.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}}ka.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]],ka.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],ka.StepsPerOctave=7,ka.OctaveSteps=[38,32,30,26,38],ka.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],ka.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class va{constructor(){this.staffId="",this.up=0,this.down=0}}class xa{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 Na{get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}get hasLine(){return 1===this.beats.length&&this.beats[0].duration>p.Whole}get hasFlag(){return 1===this.beats.length&&!this.beats[0].isRest&&(this.beats[0].duration>p.Quarter||this.beats[0].graceType!==f.None)}constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=p.QuadrupleWhole,this.fingeringCount=0,this.hasTuplet=!1,this._firstBeatLowestNoteCompareValue=-1,this._firstBeatHighestNoteCompareValue=-1,this._lastBeatLowestNoteCompareValue=-1,this._lastBeatHighestNoteCompareValue=-1,this.lowestNoteInHelper=null,this._lowestNoteCompareValueInHelper=-1,this.highestNoteInHelper=null,this._highestNoteCompareValueInHelper=-1,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isGrace=!1,this.minRestLine=null,this.beatOfMinRestLine=null,this.maxRestLine=null,this.beatOfMaxRestLine=null,this.direction=Ce.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}getBeatLineX(e){return this.hasBeatLineX(e)?this.direction===Ce.Up?this._beatLineXPositions.get(e.index).up:this._beatLineXPositions.get(e.index).down:0}hasBeatLineX(e){return this._beatLineXPositions.has(e.index)}registerBeatLineX(e,t,i,s){let a=this.getOrCreateBeatPositions(t);a.staffId=e,a.up=i,a.down=s;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 va),this._beatLineXPositions.get(e.index)}finish(){this.direction=this.calculateDirection()}calculateDirection(){let e=null;if(this.voice?null!==this.preferredBeamDirection?e=this.preferredBeamDirection:this.voice.index>0?e=this.invert(Ce.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==f.None)&&(e=this.invert(Ce.Up)):e=Ce.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){let t=this._renderer.getNoteY(this.highestNoteInHelper,Qe.Center),i=this._renderer.getNoteY(this.lowestNoteInHelper,Qe.Center);if(null===e){const s=(t+i)/2;e=this.invert(this._renderer.middleYPosition<s?Ce.Up:Ce.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(Ce.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:return[2,2];case p.Whole:return[0,1];case p.Half:return[1,0];case p.Quarter:return[3,3];case p.Eighth:return[2,2];case p.Sixteenth:return[2,4];case p.ThirtySecond:return[4,4];case p.SixtyFourth:return[4,6];case p.OneHundredTwentyEighth:return[6,6];case p.TwoHundredFiftySixth:return[6,8]}return[0,0]}applyRest(e,t){if(this._lastNonRestBeat&&e.index>=this._lastNonRestBeat.index||this._firstNonRestBeat&&e.index<=this._firstNonRestBeat.index)return;let i=t,s=t;const a=Na.computeLineHeightsForRest(e.duration);i-=a[0],s+=a[1];const r=this.minRestLine,n=this.maxRestLine;(null===r||r>i)&&(this.minRestLine=i,this.beatOfMinRestLine=e),(null===n||n<s)&&(this.maxRestLine=s,this.beatOfMaxRestLine=e)}invert(e){return this.invertBeamDirection?e===Ce.Down?Ce.Up:Ce.Down:e}checkBeat(e){e.invertBeamDirection&&(this.invertBeamDirection=!0),this.voice||(this.voice=e.voice);let t=!1;if(0===this.beats.length)t=!0;else switch(this.beats[this.beats.length-1].beamingMode){case L.Auto:t=Na.canJoin(this.beats[this.beats.length-1],e);break;case L.ForceSplitToNext:t=!1;break;case L.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!==f.None&&(this.isGrace=!0),e.hasTuplet&&(this.hasTuplet=!0);let t=0;for(let i=0;i<e.notes.length;i++){let s=e.notes[i];s.leftHandFinger===m.Unknown&&s.rightHandFinger===m.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,i;this.voice&&e.isPercussion?(t=-ka.getPercussionLine(this.voice.bar,ka.getNoteValue(e)),i=t):(t=ka.getNoteValue(e),i=t,e.harmonicType!==y.None&&e.harmonicType!==y.Natural&&(i=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||i>this._firstBeatHighestNoteCompareValue)&&(this._firstBeatHighestNoteCompareValue=i)),(-1===this._lastBeatLowestNoteCompareValue||t<this._lastBeatLowestNoteCompareValue)&&(this._lastBeatLowestNoteCompareValue=t),(-1===this._lastBeatHighestNoteCompareValue||i>this._lastBeatHighestNoteCompareValue)&&(this._lastBeatHighestNoteCompareValue=i),(!this.lowestNoteInHelper||t<this._lowestNoteCompareValueInHelper)&&(this.lowestNoteInHelper=e,this._lowestNoteCompareValueInHelper=t),(!this.highestNoteInHelper||i>this._highestNoteCompareValueInHelper)&&(this.highestNoteInHelper=e,this._highestNoteCompareValueInHelper=i)}static canJoin(e,t){if(!e||!t||e.graceType!==t.graceType||e.graceType===f.BendGrace||t.graceType===f.BendGrace)return!1;if(e.graceType!==f.None&&t.graceType!==f.None)return!0;let i=e.voice.bar;if(i!==t.voice.bar)return!1;let s=e.playbackStart,a=t.playbackStart;if(!Na.canJoinDuration(e.duration)||!Na.canJoinDuration(t.duration))return s===a;if(e.tupletGroup!==t.tupletGroup)return!1;if(e.hasTuplet&&t.hasTuplet&&e.tupletGroup===t.tupletGroup&&e.tupletGroup.isFull)return!0;let r=z.QuarterTime;if(8===i.masterBar.timeSignatureDenominator)i.masterBar.timeSignatureNumerator%3==0&&(r+=z.QuarterTime/2|0);return((r+s)/r|0)===((r+a)/r|0)}static canJoinDuration(e){switch(e){case p.Whole:case p.Half:case p.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,i){return Q.getIndex(e.duration)-2-i>0&&Q.getIndex(t.duration)-2-i>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 Pa{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class Ea{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new Pa(e,t)),-1e3===this.topY)this.topY=e,this.bottomY=t;else{const i=Math.min(e,t),s=Math.max(e,t);i<this.topY&&(this.topY=i),s>this.bottomY&&(this.bottomY=s)}}}class Ca{constructor(){this.reservedLayoutAreasByDisplayTime=new Map,this.restDurationsByDisplayTime=new Map}getBeatMinMaxY(){let e=-1e3,t=-1e3;for(const i of this.reservedLayoutAreasByDisplayTime.values())-1e3===e?(e=i.topY,t=i.bottomY):(e>i.topY&&(e=i.topY),t<i.bottomY&&(t=i.bottomY));return-1e3===e?[0,0]:[e,t]}reserveBeatSlot(e,t,i){t!=i&&(this.reservedLayoutAreasByDisplayTime.has(e.displayStart)||this.reservedLayoutAreasByDisplayTime.set(e.displayStart,new Ea(e)),this.reservedLayoutAreasByDisplayTime.get(e.displayStart).addSlot(t,i),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,i){if(e.voice.index>0&&this.reservedLayoutAreasByDisplayTime.has(e.playbackStart)){const s=Na.computeLineHeightsForRest(e.duration).map((e=>e*i));let a=t-s[0],r=t+s[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-s[1]-s[0]:o.bottomY;let t=n+s[0]+s[1];const r=2*i;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 Ca}initialize(){var e=this._renderer,t=this._renderer.bar;let i=null,s=null;for(let a=0,r=t.voices.length;a<r;a++){let r=t.voices[a];this.beamHelpers.push([]),this.beamHelperLookup.push(new Map);for(let a=0,n=r.beats.length;a<n;a++){let n,o=r.beats[a];o.graceType!==f.None?n=s:(n=i,s=null),n&&n.checkBeat(o)||(n&&n.finish(),n=new Na(t.staff,e),n.checkBeat(o),o.graceType!==f.None?s=n:i=n,this.beamHelpers[r.index].push(n)),this.beamHelperLookup[r.index].set(o.index,n)}i&&i.finish(),s&&s.finish(),i=null,s=null}}getBeamingHelperForBeat(e){return this.beamHelperLookup[e.voice.index].get(e.index)}}class La extends Us{constructor(e,t,i){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=i}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=La.FretSpacing*e:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+(La.Frets-1)*La.FretSpacing*e+2*La.Padding*e,this.width=this._firstFretSpacing+(this._chord.staff.tuning.length-1)*La.StringSpacing*e+2*La.Padding*e}paint(e,t,i){e+=this.x+La.Padding*this.scale+this._firstFretSpacing,t+=this.y;let s=this.width-2*La.Padding*this.scale+this.scale-this._firstFretSpacing,a=La.StringSpacing*this.scale,r=La.FretSpacing*this.scale,n=this.renderer.resources,o=La.CircleRadius*this.scale,h=i.textAlign,l=i.textBaseline;i.font=n.effectFont,i.textAlign=E.Center,i.textBaseline=C.Top,this._chord.showName&&i.fillText(this._chord.name,e+this.width/2,t+n.effectFont.size/2),t+=this._textRow,e+=a/2,i.font=n.fretboardNumberFont,i.textBaseline=C.Middle;for(let s=0;s<this._chord.staff.tuning.length;s++){let r=e+s*a,n=t+this._fretRow/2,o=this._chord.strings[this._chord.staff.tuning.length-s-1];o<0?i.fillMusicFontSymbol(r,n,this.scale,P.FretboardX,!0):0===o?i.fillMusicFontSymbol(r,n,this.scale,P.FretboardO,!0):(o-=this._chord.firstFret-1,i.fillText(o.toString(),r,n))}t+=this._fretRow;for(let s=0;s<this._chord.staff.tuning.length;s++){let n=e+s*a;i.fillRect(n,t,1,r*La.Frets+this.scale)}this._chord.firstFret>1&&(i.textAlign=E.Left,i.fillText(this._chord.firstFret.toString(),e-this._firstFretSpacing,t+r/2)),i.fillRect(e,t-this.scale,s,2*this.scale);for(let a=0;a<=La.Frets;a++){let n=t+a*r;i.fillRect(e,n,s,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 s=0;s<this._chord.strings.length;s++){let n=this._chord.strings[s];if(n>0){if(n-=this._chord.firstFret,c.has(n)){let e=c.get(n);(-1===e[0]||s<e[0])&&(e[0]=s),(-1===e[1]||s>e[1])&&(e[1]=s)}let h=t+n*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-s-1)*a;i.fillCircle(l,h,o)}}for(const[s,n]of c){let h=t+s*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;i.fillRect(l,h-o,c-l,2*o)}i.textAlign=h,i.textBaseline=l}}La.Padding=5,La.Frets=5,La.CircleRadius=2.5,La.StringSpacing=10,La.FretSpacing=12;class Ma extends wa{constructor(e,t,i=E.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=i}doLayout(){let e=0;switch(this._align){case E.Left:e=0;break;case E.Center:e=(this.width-this._glyphWidth)/2;break;case E.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 Ia extends wa{constructor(e,t,i=E.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=i}doLayout(){let e=0,t=0,i=2*Ia.Padding*this.scale;this._rows=[];let s=new Ma(e,t,this._align);s.width=this.width;for(let a of this.glyphs)e+a.width<this.width?(s.addGlyphToRow(a),e+=a.width):(s.isEmpty||(s.doLayout(),this._rows.push(s),t+=s.height+i),e=0,s=new Ma(e,t,this._align),s.width=this.width,s.addGlyphToRow(a),e+=a.width);s.isEmpty||(s.doLayout(),this._rows.push(s),t+=s.height+i),this.height=t+i}paint(e,t,i){for(let s of this._rows)s.paint(e+this.x,t+this.y+Ia.Padding*this.scale,i)}}Ia.Padding=3;class Da extends Ia{constructor(e,t){super(e,t)}addChord(e){if(e.strings.length>0){let t=new La(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}}class Aa extends Us{constructor(e,t,i,s,a=E.Left){super(e,t),this._lines=i.split("\n"),this.font=s,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,i){let s=i.color;i.color=s,i.font=this.font;let a=i.textAlign;i.textAlign=this.textAlign;let r=t+this.y;for(let t of this._lines)i.fillText(t,e+this.x,r),r+=this.font.size;i.textAlign=a}}class Ra{get staveId(){return this._factory.staffId}constructor(e,t,i){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=i,this.trackIndex=e,this.modelStaff=t}getSharedLayoutData(e,t){return this._sharedLayoutData.has(e)?this._sharedLayoutData.get(e):t}setSharedLayoutData(e,t){this._sharedLayoutData.set(e,t)}get isInAccolade(){return this._factory.isInAccolade}get isRelevantForBoundsLookup(){return this._factory.isRelevantForBoundsLookup}registerStaffTop(e){this.staveTop=e}registerStaffBottom(e){this.staveBottom=e}addBarRenderer(e){e.staff=this,e.index=this.barRenderers.length,e.reLayout(),this.barRenderers.push(e),this.staveGroup.layout.registerBarRenderer(this.staveId,e)}addBar(e,t){let i;i=e?this._factory.create(this.staveGroup.layout.renderer,e):new qa(this.staveGroup.layout.renderer,e),i.staff=this,i.index=this.barRenderers.length,i.layoutingInfo=t,i.doLayout(),i.registerLayoutingInfo();const s=i.barDisplayWidth;s>0&&this.staveGroup.layout.systemsLayoutMode==je.FromModelWithWidths&&(i.width=s),this.barRenderers.push(i),e&&this.staveGroup.layout.registerBarRenderer(this.staveId,i)}revertLastBar(){let e=this.barRenderers[this.barRenderers.length-1];return this.barRenderers.splice(this.barRenderers.length-1,1),this.staveGroup.layout.unregisterBarRenderer(this.staveId,e),e}scaleToWidth(e){this._sharedLayoutData=new Map;let t=this.topOverflow,i=0;switch(this.staveGroup.layout.systemsLayoutMode){case je.Automatic:let s=(e-this.staveGroup.computedWidth)/this.barRenderers.length;for(const e of this.barRenderers){e.x=i,e.y=this.topSpacing+t;let a=e.computedWidth+s;e.scaleToWidth(a),i+=e.width}break;case je.FromModelWithScale:e-=this.staveGroup.accoladeSpacing;const a=this.staveGroup.totalBarDisplayScale;for(const s of this.barRenderers){s.x=i,s.y=this.topSpacing+t;const r=s.barDisplayScale*e/a;s.scaleToWidth(r),i+=s.width}break;case je.FromModelWithWidths:for(const e of this.barRenderers){e.x=i,e.y=this.topSpacing+t;const s=e.barDisplayWidth;s>0?e.scaleToWidth(s):e.scaleToWidth(e.computedWidth),i+=e.width}}}get topOverflow(){let e=0;for(let t=0,i=this.barRenderers.length;t<i;t++){let i=this.barRenderers[t];i.topOverflow>e&&(e=i.topOverflow)}return e}get bottomOverflow(){let e=0;for(let t=0,i=this.barRenderers.length;t<i;t++){let i=this.barRenderers[t];i.bottomOverflow>e&&(e=i.bottomOverflow)}return e}finalizeStaff(){this.height=0;let e=!1,t=this.topOverflow;for(let i=0;i<this.barRenderers.length;i++)this.barRenderers[i].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[i].height),this.barRenderers[i].finalizeRenderer()&&(e=!0);if(e){t=this.topOverflow;for(let e=0;e<this.barRenderers.length;e++)this.barRenderers[e].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[e].height),this.barRenderers[e].finalizeRenderer()}this.height>0&&(this.height+=this.topSpacing+t+this.bottomOverflow+this.bottomSpacing)}paint(e,t,i,s,a){if(0!==this.height&&0!==a)for(let r=s,n=Math.min(s+a,this.barRenderers.length);r<n;r++)this.barRenderers[r].paint(e+this.x,t+this.y,i)}}class Oa{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 Ga{constructor(){this._timeSortedSprings=[],this._xMin=0,this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,this.version=0,this.preBeatSizes=new Map,this.onBeatSizes=new Map,this.onBeatCenterX=new Map,this.preBeatSize=0,this.postBeatSize=0,this.voiceSize=0,this.minStretchForce=0,this.totalSpringConstant=0,this.incompleteGraceRods=new Map,this.allGraceRods=new Map,this.springs=new Map,this.height=0}updateVoiceSize(e){e>this.voiceSize&&(this.voiceSize=e,this.version++)}setPreBeatSize(e,t){(!this.preBeatSizes.has(e.id)||this.preBeatSizes.get(e.id)<t)&&(this.preBeatSizes.set(e.id,t),this.version++)}getPreBeatSize(e){return this.preBeatSizes.has(e.id)?this.preBeatSizes.get(e.id):0}setOnBeatSize(e,t){(!this.onBeatSizes.has(e.id)||this.onBeatSizes.get(e.id)<t)&&(this.onBeatSizes.set(e.id,t),this.version++)}getOnBeatSize(e){return this.onBeatSizes.has(e.id)?this.onBeatSizes.get(e.id):0}getBeatCenterX(e){return this.onBeatCenterX.has(e.id)?this.onBeatCenterX.get(e.id):0}setBeatCenterX(e,t){(!this.onBeatCenterX.has(e.id)||this.onBeatCenterX.get(e.id)<t)&&(this.onBeatCenterX.set(e.id,t),this.version++)}updateMinStretchForce(e){this.minStretchForce<e&&(this.minStretchForce=e)}addSpring(e,t,i,s,a){let r;if(this.version++,this.springs.has(e))r=this.springs.get(e),r.postSpringWidth<a&&(r.postSpringWidth=a),r.graceBeatWidth<i&&(r.graceBeatWidth=i),r.preBeatWidth<s&&(r.preBeatWidth=s),t<r.smallestDuration&&(r.smallestDuration=t),t>r.longestDuration&&(r.longestDuration=t),r.allDurations.add(t);else{if(r=new Oa,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=i,r.preBeatWidth=s,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,i){let s=e.absoluteDisplayStart;if(e.graceType!==f.None){const a=e.graceGroup.id;this.allGraceRods.has(a)||this.allGraceRods.set(a,new Array(e.graceGroup.beats.length)),e.graceGroup.isComplete||this.incompleteGraceRods.has(a)||this.incompleteGraceRods.set(a,new Array(e.graceGroup.beats.length));let r=this.allGraceRods.get(a)[e.graceIndex];if(r)r.postSpringWidth<i&&(r.postSpringWidth=i),r.preBeatWidth<t&&(r.preBeatWidth=t);else{const r=new Oa;r.timePosition=s,r.postSpringWidth=i,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(s,e.displayDuration,a,t,i)}}finish(){for(const[e,t]of this.allGraceRods){let i=0;if(this.incompleteGraceRods.has(e))for(const e of t)i+=e.preBeatWidth,e.graceBeatWidth=i,i+=e.postSpringWidth;else for(let e=t.length-1;e>=0;e--)t[e].graceBeatWidth=i,i-=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,i=this._timeSortedSprings;if(0===i.length)return this.totalSpringConstant=-1,void(this.minStretchForce=-1);for(let e=0;e<i.length;e++){let s=i[e],a=0;if(e===i.length-1)a=s.longestDuration;else{let t=i[e+1];a=Math.abs(t.timePosition-s.timePosition)}s.springConstant=this.calculateSpringConstant(s,a),t+=1/s.springConstant}this.totalSpringConstant=1/t,this.minStretchForce=0;for(let e=0;e<i.length;e++){let t=i[e],s=0;if(e===i.length-1)s=t.postSpringWidth;else{let a=i[e+1];s=t.postSpringWidth+a.preSpringWidth}0===e&&(s+=t.preSpringWidth);let a=s*t.springConstant;this.updateMinStretchForce(a)}}paint(e,t,i){}calculateSpringConstant(e,t){return t<=0&&(t=z.toTicks(p.SixtyFourth)),0===e.smallestDuration&&(e.smallestDuration=t),e.smallestDuration/t*(1/((1+.85*Math.log2(t/Ga.MinDuration))*Ga.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(Q.isAlmostEqualTo(this._onTimePositionsForce,e)&&this._onTimePositions)return this._onTimePositions;this._onTimePositionsForce=e;let t=new Map;this._onTimePositions=t;let i=this._timeSortedSprings;if(0===i.length)return t;let s=i[0].preSpringWidth;for(let a=0;a<i.length;a++)t.set(i[a].timePosition,s),s+=this.calculateWidth(e,i[a].springConstant);return t}}Ga.MinDuration=30,Ga.MinDurationWidth=7;class Va{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.renderers=[]}}class Ha{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 Wa{constructor(){this._allStaves=[],this._firstStaffInAccolade=null,this._lastStaffInAccolade=null,this._accoladeSpacingCalculated=!1,this.x=0,this.y=0,this.index=0,this.accoladeSpacing=0,this.isFull=!1,this.width=0,this.computedWidth=0,this.totalBarDisplayScale=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[]}get firstBarIndex(){return this.masterBarsRenderers[0].masterBar.index}get lastBarIndex(){return this.masterBarsRenderers[this.masterBarsRenderers.length-1].masterBar.index}addMasterBarRenderers(e,t){if(0===e.length)return null;this.masterBarsRenderers.push(t),this.calculateAccoladeSpacing(e),t.layoutingInfo.preBeatSize=0;let i=0;for(let e=0,s=this.staves.length;e<s;e++){let s=this.staves[e];for(let e=0,a=s.staves.length;e<a;e++){let a=s.staves[e],r=t.renderers[i++];a.addBarRenderer(r)}}return this.updateWidthFromLastBar(),t}addBars(e,t){if(0===e.length)return null;let i=new Va;i.layoutingInfo=new Ga,i.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(i),this.calculateAccoladeSpacing(e);let s=i.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,s);let n=a.barRenderers[a.barRenderers.length-1];i.renderers.push(n),n.isLinkedToPrevious&&(i.isLinkedToPrevious=!0),n.canWrap||(i.canWrap=!1)}return s.finish(),i.width=this.updateWidthFromLastBar(),i}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,i=0;for(let e=0,s=this._allStaves.length;e<s;e++){let s=this._allStaves[e].revertLastBar();const a=s.computedWidth;a>t&&(t=a);const r=s.barDisplayScale;r>i&&(i=r)}return this.width-=t,this.computedWidth-=t,this.totalBarDisplayScale-=i,e}return null}updateWidthFromLastBar(){let e=0,t=0;for(let i=0,s=this._allStaves.length;i<s;i++){let s=this._allStaves[i];const a=s.barRenderers[s.barRenderers.length-1];a.applyLayoutingInfo(),a.computedWidth>e&&(e=a.computedWidth);const r=a.barDisplayScale;r>t&&(t=r)}return this.width+=e,this.computedWidth+=e,this.totalBarDisplayScale+=t,e}calculateAccoladeSpacing(e){if(!this._accoladeSpacingCalculated&&0===this.index)if(this._accoladeSpacingCalculated=!0,this.layout.renderer.settings.notation.isNotationElementVisible(v.TrackNames)){let t=this.layout.renderer.canvas,i=this.layout.renderer.settings.display.resources.effectFont;t.font=i;for(let i of e)this.accoladeSpacing=Math.ceil(Math.max(this.accoladeSpacing,t.measureText(i.shortName)));this.accoladeSpacing*=this.layout.scale,this.accoladeSpacing+=2*Wa.AccoladeLabelSpacing*this.layout.scale,this.width+=this.accoladeSpacing,this.computedWidth+=this.accoladeSpacing}else this.accoladeSpacing=0}getStaveTrackGroup(e){for(let t=0,i=this.staves.length;t<i;t++){let i=this.staves[t];if(i.track===e)return i}return null}addStaff(e,t){let i=this.getStaveTrackGroup(e);i||(i=new Ha(this,e),this.staves.push(i)),t.staveTrackGroup=i,t.staveGroup=this,t.index=this._allStaves.length,this._allStaves.push(t),i.addStaff(t),t.isInAccolade&&(this._firstStaffInAccolade||(this._firstStaffInAccolade=t,t.isFirstInAccolade=!0),i.firstStaffInAccolade||(i.firstStaffInAccolade=t),this._lastStaffInAccolade||(this._lastStaffInAccolade=t,t.isLastInAccolade=!0),this._lastStaffInAccolade&&(this._lastStaffInAccolade.isLastInAccolade=!1),this._lastStaffInAccolade=t,this._lastStaffInAccolade.isLastInAccolade=!0,i.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,i=this._allStaves.length;t<i;t++)this._allStaves[t].scaleToWidth(e);this.width=e}paint(e,t,i){this.paintPartial(e+this.x,t+this.y,i,0,this.masterBarsRenderers.length)}paintPartial(e,t,i,s,a){for(let r=0,n=this._allStaves.length;r<n;r++)this._allStaves[r].paint(e,t,i,s,a);let r=this.layout.renderer.settings.display.resources;if(this.staves.length>0&&0===s){if(i.color=r.barSeparatorColor,this._firstStaffInAccolade&&this._lastStaffInAccolade){let s=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;i.beginPath(),i.moveTo(r,s),i.lineTo(r,a),i.stroke()}i.font=r.effectFont;for(let s=0,a=this.staves.length;s<a;s++){let a=this.staves[s];if(a.firstStaffInAccolade&&a.lastStaffInAccolade){let s=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=s-4*o,c=r+4*o;0===this.index&&this.layout.renderer.settings.notation.isNotationElementVisible(v.TrackNames)&&i.fillText(a.track.shortName,e+Wa.AccoladeLabelSpacing*this.layout.scale,s),i.fillRect(n-h-o,l,o,c-l);let d=n-h-o,u=n+2*o;i.beginPath(),i.moveTo(d,l),i.bezierCurveTo(d,l,d,l,u,l-o),i.bezierCurveTo(n,l+o,d,l+o,d,l+o),i.closePath(),i.fill(),i.beginPath(),i.moveTo(d,c),i.bezierCurveTo(d,c,n,c,u,c+o),i.bezierCurveTo(n,c-o,d,c-o,d,c-o),i.closePath(),i.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 i=this._allStaves[this._allStaves.length-1],s=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+i.y+i.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-s,l=t+this.y+i.y+i.height-i.bottomSpacing-i.bottomOverflow-(i.barRenderers.length>0?i.barRenderers[0].bottomPadding:0)-o,c=n-r,d=this.x+this._firstStaffInAccolade.x,u=new xs;u.visualBounds=new nt,u.visualBounds.x=e,u.visualBounds.y=t+this.y,u.visualBounds.w=this.width,u.visualBounds.h=this.height,u.realBounds=new nt,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 i of this.staves[e].stavesRelevantForBoundsLookup)for(let e of i.barRenderers){let a;p.has(e.bar.masterBar.index)?a=p.get(e.bar.masterBar.index):(a=new ks,a.index=e.bar.masterBar.index,a.isFirstOfLine=e.isFirstOfLine,a.realBounds=new nt,a.realBounds.x=d+e.x,a.realBounds.y=r,a.realBounds.w=e.width,a.realBounds.h=c,a.visualBounds=new nt,a.visualBounds.x=d+e.x,a.visualBounds.y=s,a.visualBounds.w=e.width,a.visualBounds.h=h,a.lineAlignedBounds=new nt,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+i.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}}Wa.AccoladeLabelSpacing=10;class za extends wa{constructor(e,t,i,s){super(e,t),this._tuning=i,this._trackLabel=s,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,i=this.renderer.resources;this.height=0;const s=15*t;this._trackLabel.length>0&&(this.addGlyph(new Aa(0,this.height,this._trackLabel,i.effectFont,E.Left)),this.height+=s),this.addGlyph(new Aa(0,this.height,e.name,i.effectFont,E.Left));const a=64*t;if(this.renderer.scoreRenderer.canvas.font=i.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+=s,!e.isStandard){const r=.7,n=za.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=P.GuitarString0+(c+1);this.addGlyph(new Xs(h,l+n/1.2,r,d));const u="= "+be.getTextForTuning(e.tunings[c],!1);this.addGlyph(new Aa(h+n+1*t,l,u,i.effectFont,E.Left)),l+=s,c===o-1&&(l=this.height,h+=a)}this.height+=o*s}this.width+=15*t}}za.CircleNumberHeight=20;class Ua extends Ia{constructor(e,t){super(e,t,E.Left)}addTuning(e,t){if(e.tunings.length>0){let i=new za(0,0,e,t);i.renderer=this.renderer,i.doLayout(),this.glyphs.push(i)}}}class Xa{constructor(e,t){this.args=e,this.renderCallback=t}}!function(e){e[e.Automatic=0]="Automatic",e[e.FromModelWithScale=1]="FromModelWithScale",e[e.FromModelWithWidths=2]="FromModelWithWidths"}(je||(je={}));class Ya{constructor(e){this._barRendererLookup=new Map,this.width=0,this.height=0,this.scoreInfoGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this.systemsLayoutMode=je.Automatic,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t)),this.firstBarIndex=t;let 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.lastBarIndex=i,this.createScoreInfoGlyphs(),this.doLayoutAndRender()}registerPartial(e,t){this.renderer.settings.core.enableLazyLoading?(this._lazyPartials.set(e.id,new Xa(e,t)),this.renderer.partialLayoutFinished.trigger(e)):(this.renderer.partialLayoutFinished.trigger(e),this.internalRenderLazyPartial(e,t))}internalRenderLazyPartial(e,t){const i=this.renderer.canvas;i.beginRender(e.width,e.height),t(i),e.renderResult=i.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(){J.debug("ScoreLayout","Creating score info glyphs");let e=this.renderer.settings.notation,t=this.renderer.score,i=this.renderer.settings.display.resources;this.scoreInfoGlyphs=new Map,t.title&&e.isNotationElementVisible(v.ScoreTitle)&&this.scoreInfoGlyphs.set(v.ScoreTitle,new Aa(0,0,t.title,i.titleFont,E.Center)),t.subTitle&&e.isNotationElementVisible(v.ScoreSubTitle)&&this.scoreInfoGlyphs.set(v.ScoreSubTitle,new Aa(0,0,t.subTitle,i.subTitleFont,E.Center)),t.artist&&e.isNotationElementVisible(v.ScoreArtist)&&this.scoreInfoGlyphs.set(v.ScoreArtist,new Aa(0,0,t.artist,i.subTitleFont,E.Center)),t.album&&e.isNotationElementVisible(v.ScoreAlbum)&&this.scoreInfoGlyphs.set(v.ScoreAlbum,new Aa(0,0,t.album,i.subTitleFont,E.Center)),t.music&&t.music===t.words&&e.isNotationElementVisible(v.ScoreWordsAndMusic)?this.scoreInfoGlyphs.set(v.ScoreWordsAndMusic,new Aa(0,0,"Music and Words by "+t.words,i.wordsFont,E.Center)):(t.music&&e.isNotationElementVisible(v.ScoreMusic)&&this.scoreInfoGlyphs.set(v.ScoreMusic,new Aa(0,0,"Music by "+t.music,i.wordsFont,E.Right)),t.words&&e.isNotationElementVisible(v.ScoreWords)&&this.scoreInfoGlyphs.set(v.ScoreWords,new Aa(0,0,"Words by "+t.words,i.wordsFont,E.Left)));const s=new qa(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);if(e.isNotationElementVisible(v.GuitarTuning)){let e=[];for(let t of this.renderer.tracks)for(let i of t.staves)if(!i.isPercussion&&i.isStringed&&i.tuning.length>0&&i.showTablature){e.push(i);break}if(e.length>0){this.tuningGlyph=new Ua(0,0),this.tuningGlyph.renderer=s;for(const t of e)this.tuningGlyph.addTuning(t.stringTuning,e.length>1?t.track.name:"")}}if(e.isNotationElementVisible(v.ChordDiagrams)){this.chordDiagrams=new Da(0,0),this.chordDiagrams.renderer=s;let e=new Set;for(let t of this.renderer.tracks)for(let i of t.staves){const t=i.chords;if(t)for(const[,i]of t)e.has(i.uniqueId)||i.showDiagram&&(e.add(i.uniqueId),this.chordDiagrams.addChord(i))}}}get scale(){return this.renderer.settings.display.scale}createEmptyStaveGroup(){let t=new Wa;t.layout=this;for(let i=0;i<this.renderer.tracks.length;i++){let s=this.renderer.tracks[i],a=!1;for(let e of s.staves)if(e.showStandardNotation){a=!0;break}for(let r=0;r<s.staves.length;r++){let n,o=s.staves[r];if(o.isPercussion)n=e.StaveProfile.Score;else if(this.renderer.settings.display.staveProfile!==e.StaveProfile.Default)n=this.renderer.settings.display.staveProfile;else if(o.showTablature&&o.showStandardNotation)n=e.StaveProfile.ScoreTab;else if(o.showTablature)n=a?e.StaveProfile.TabMixed:e.StaveProfile.Tab;else{if(!o.showStandardNotation)continue;n=e.StaveProfile.Score}let h=Eo.staveProfiles.get(n);for(let e of h)e.canCreate(s,o)&&t.addStaff(s,new Ra(i,o,e))}}return t}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 i=t.id;return this._barRendererLookup.has(e)&&this._barRendererLookup.get(e).has(i)?this._barRendererLookup.get(e).get(i):null}layoutAndRenderAnnotation(e){let t="rendered by alphaTab",i=this.renderer.settings.display.resources,s=12*this.renderer.settings.display.scale,a=Math.floor(2*s);const r=new _s,n=Ri.withFamilyList(i.copyrightFont.families,s,Ve.Plain,He.Bold);this.renderer.canvas.font=n;const o=Eo.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=i.mainGlyphColor,e.font=n,e.textAlign=E.Left,e.fillText(t,0,s)})),e+a}}!function(e){e[e.TopWithStem=0]="TopWithStem",e[e.Top=1]="Top",e[e.Center=2]="Center",e[e.Bottom=3]="Bottom",e[e.BottomWithStem=4]="BottomWithStem"}(Qe||(Qe={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}($e||($e={}));class qa{get nextRenderer(){return this.bar&&this.bar.nextBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.nextBar):null}get previousRenderer(){return this.bar&&this.bar.previousBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.previousBar):null}constructor(e,t){this._preBeatGlyphs=new _a,this._voiceContainers=new Map,this._postBeatGlyphs=new _a,this._ties=[],this.x=0,this.y=0,this.width=0,this.computedWidth=0,this.height=0,this.index=0,this.topOverflow=0,this.bottomOverflow=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this._wasFirstOfLine=!1,this._appliedLayoutingInfo=0,this.isFinalized=!1,this.topPadding=0,this.bottomPadding=0,this.scoreRenderer=e,this.bar=t,t&&(this.helpers=new Fa(this))}registerTies(e){this._ties.push(...e)}get middleYPosition(){return 0}registerOverflowTop(e){return e>this.topOverflow&&(this.topOverflow=e,!0)}registerOverflowBottom(e){return e>this.bottomOverflow&&(this.bottomOverflow=e,!0)}scaleToWidth(e){let t=e-this._preBeatGlyphs.width-this._postBeatGlyphs.width;for(const e of this._voiceContainers.values())e.scaleToWidth(t);this._postBeatGlyphs.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width+t,this.width=e}get resources(){return this.settings.display.resources}get settings(){return this.scoreRenderer.settings}get scale(){return this.settings.display.scale}get barDisplayScale(){return this.staff.staveGroup.staves.length>1?this.bar.masterBar.displayScale:this.bar.displayScale}get barDisplayWidth(){return this.staff.staveGroup.staves.length>1?this.bar.masterBar.displayWidth:this.bar.displayWidth}get isFirstOfLine(){return 0===this.index}get isLast(){return!this.bar||this.bar.index===this.scoreRenderer.layout.lastBarIndex}registerLayoutingInfo(){let e=this.layoutingInfo,t=this._preBeatGlyphs.width;e.preBeatSize<t&&(e.preBeatSize=t);for(const t of this._voiceContainers.values())t.registerLayoutingInfo(e),t.x,t.width;let i=this._postBeatGlyphs.width;e.postBeatSize<i&&(e.postBeatSize=i)}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 i=t.x+t.width;e<i&&(e=i)}this._postBeatGlyphs.x=Math.floor(e),this._postBeatGlyphs.width=this.layoutingInfo.postBeatSize,this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.computedWidth=this.width;const t=this.barDisplayWidth;return t>0&&this.scoreRenderer.layout.systemsLayoutMode==je.FromModelWithWidths&&(this.width=t,this.computedWidth=t),!0}finalizeRenderer(){this.isFinalized=!0;let e=!1;const t=this.y-this.staff.topSpacing,i=this.y+this.height+this.staff.bottomSpacing;for(const s of this._ties)if(s.doLayout(),s.height>0){const a=s.y+s.height-i;a>0&&this.registerOverflowBottom(a)&&(e=!0);const r=s.y-t;r<0&&this.registerOverflowTop(-1*r)&&(e=!0)}return e}doLayout(){if(this.bar){this.helpers.initialize(),this._ties=[],this._preBeatGlyphs=new _a,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new _a,this._postBeatGlyphs.renderer=this;for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];if(this.hasVoiceContainer(t)){let i=new Ba(0,0,t);i.renderer=this,this._voiceContainers.set(this.bar.voices[e].index,i)}}this.bar.simileMark===h.SecondOfDouble&&(this.canWrap=!1),this.createPreBeatGlyphs(),this.createBeatGlyphs(),this.createPostBeatGlyphs(),this.updateSizes();for(const e of this.helpers.beamHelpers)for(const t of e)t.finish();this.computedWidth=this.width}}hasVoiceContainer(e){return!e.isEmpty||0===e.index}updateSizes(){this.staff.registerStaffTop(this.topPadding),this.staff.registerStaffBottom(this.height-this.bottomPadding);let e=this._voiceContainers,t=this.beatGlyphsStart,i=t;for(const s of e.values()){s.x=t,s.doLayout();let e=s.x+s.width;i<e&&(i=e)}this._postBeatGlyphs.x=Math.floor(i),this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.height+=this.layoutingInfo.height*this.scale}addPreBeatGlyph(e){e.renderer=this,this._preBeatGlyphs.addGlyph(e)}addBeatGlyph(e){e.renderer=this,e.preNotes.renderer=this,e.onNotes.renderer=this,e.onNotes.beamingHelper=this.helpers.beamHelperLookup[e.beat.voice.index].get(e.beat.index),this.getVoiceContainer(e.beat.voice).addGlyph(e)}getVoiceContainer(e){return this._voiceContainers.has(e.index)?this._voiceContainers.get(e.index):void 0}getBeatContainer(e){return this.getVoiceContainer(e.voice)?.beatGlyphs?.[e.index]}getPreNotesGlyphForBeat(e){return this.getBeatContainer(e)?.preNotes}getOnNotesGlyphForBeat(e){return this.getBeatContainer(e)?.onNotes}paint(e,t,i){this.paintBackground(e,t,i),i.color=this.resources.mainGlyphColor,this._preBeatGlyphs.paint(e+this.x,t+this.y,i);for(const s of this._voiceContainers.values())i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.paint(e+this.x,t+this.y,i);i.color=this.resources.mainGlyphColor,this._postBeatGlyphs.paint(e+this.x,t+this.y,i)}paintBackground(e,t,i){this.layoutingInfo.paint(e+this.x+this._preBeatGlyphs.x+this._preBeatGlyphs.width,t+this.y+this.height,i)}buildBoundingsLookup(e,t,i){let s=new Bs;s.bar=this.bar,s.visualBounds=new nt,s.visualBounds.x=t+this.x,s.visualBounds.y=i+this.y+this.topPadding,s.visualBounds.w=this.width,s.visualBounds.h=this.height-this.topPadding-this.bottomPadding,s.realBounds=new nt,s.realBounds.x=t+this.x,s.realBounds.y=i+this.y,s.realBounds.w=this.width,s.realBounds.h=this.height,e.addBar(s);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(s,t+this.x+a.x,i+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=qe.PreNotes){let i=this.getBeatContainer(e);if(i)switch(t){case qe.PreNotes:return i.voiceContainer.x+i.x;case qe.OnNotes:return i.voiceContainer.x+i.x+i.onNotes.x;case qe.MiddleNotes:return i.voiceContainer.x+i.x+i.onTimeX;case qe.Stem:const t=i.onNotes.beamingHelper?i.onNotes.beamingHelper.getBeatLineX(e):i.onNotes.x+i.onNotes.width/2;return i.voiceContainer.x+t;case qe.PostNotes:return i.voiceContainer.x+i.x+i.onNotes.x+i.onNotes.width;case qe.EndBeat:return i.voiceContainer.x+i.x+i.width}return 0}getNoteX(e,t){let i=this.getBeatContainer(e.beat);return i?i.voiceContainer.x+i.x+i.onNotes.x+i.onNotes.getNoteX(e,t):0}getNoteY(e,t){let i=this.getOnNotesGlyphForBeat(e.beat);return i?i.getNoteY(e,t):NaN}reLayout(){(this._wasFirstOfLine&&!this.isFirstOfLine||!this._wasFirstOfLine&&this.isFirstOfLine)&&(this._preBeatGlyphs=new _a,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()),this.updateSizes(),this.registerLayoutingInfo()}paintSimileMark(e,t,i){switch(this.bar.simileMark){case h.Simple:i.fillMusicFontSymbol(e+this.x+(this.width-20*this.scale)/2,t+this.y+this.height/2,1,P.Repeat1Bar,!1);break;case h.SecondOfDouble:i.fillMusicFontSymbol(e+this.x-28*this.scale/2,t+this.y+this.height/2,1,P.Repeat2Bars,!1)}}completeBeamingHelper(e){}}qa.LineSpacing=8,qa.StemWidth=.12*qa.LineSpacing,qa.StaffLineThickness=.13*qa.LineSpacing,qa.BeamThickness=.5*qa.LineSpacing,qa.BeamSpacing=.25*qa.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"}(Ke||(Ke={}));class Ja extends zs{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 Ke.SingleOnBeatToEnd:case Ke.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 i;switch(e){case Ke.FullBar:case Ke.SinglePreBeat:case Ke.SingleOnBeat:case Ke.SingleOnBeatToEnd:return i=this.info.createNewGlyph(this.renderer,t),i.renderer=this.renderer,i.beat=t,i.doLayout(),this._effectGlyphs[t.voice.index].set(t.index,i),this._uniqueEffectGlyphs[t.voice.index].push(i),i;case Ke.GroupedOnBeat:case Ke.GroupedOnBeatToEnd:let s=e===Ke.GroupedOnBeat?Ke.SingleOnBeat:Ke.SingleOnBeatToEnd;if(t.index>0||this.renderer.index>0){let e=t.previousBeat;if(this.info.shouldCreateGlyph(this.renderer.settings,e)){let i=null;if(t.index>0&&this._effectGlyphs[t.voice.index].has(e.index))i=this._effectGlyphs[t.voice.index].get(e.index);else if(this.renderer.index>0){let t=this.renderer.previousRenderer.getBand(e.voice,this.info.effectId);if(t){let s=t._effectGlyphs[e.voice.index];s.has(e.index)&&(i=s.get(e.index))}}let a=this.createOrResizeGlyph(s,t);return i&&this.info.canExpand(e,t)&&(i.nextGlyph=a,a.previousGlyph=i,this.isLinkedToPrevious=!0),a}return this.createOrResizeGlyph(s,t)}return this.createOrResizeGlyph(s,t);default:return this.createOrResizeGlyph(Ke.SingleOnBeat,t)}}paint(e,t,i){super.paint(e,t,i);for(let s=0,a=this._uniqueEffectGlyphs.length;s<a;s++){let a=this._uniqueEffectGlyphs[s];for(let s=0,r=a.length;s<r;s++){a[s].paint(e+this.x,t+this.y,i)}}}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 i,s=this._effectGlyphs[t.voice.index].get(t.index),a=this.renderer.getBeatContainer(t);switch(e){case Ke.SinglePreBeat:i=a.preNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,s.width=i.width;break;case Ke.SingleOnBeat:case Ke.GroupedOnBeat:i=a.onNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,s.width=i.width;break;case Ke.SingleOnBeatToEnd:case Ke.GroupedOnBeatToEnd:i=a.onNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,a.beat.isLastOfVoice?s.width=this.renderer.width-s.x:s.width=a.width-a.preNotes.width-a.preNotes.x;break;case Ke.FullBar:s.width=this.renderer.width}}}class ja{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class Qa{constructor(){this.bands=[],this.shared=new ja}update(e){e.info.canShareBand||(this.shared.uniqueEffectId=e.info.effectId),e.slot=this,this.bands.push(e),e.height>this.shared.height&&(this.shared.height=e.height),this.shared.firstBeat&&!e.firstBeat.isBefore(this.shared.firstBeat)||(this.shared.firstBeat=e.firstBeat),this.shared.lastBeat&&!e.lastBeat.isAfter(this.shared.lastBeat)||(this.shared.lastBeat=e.lastBeat)}canBeUsed(e){return(!this.shared.uniqueEffectId&&e.info.canShareBand||e.info.effectId===this.shared.uniqueEffectId)&&(!this.shared.firstBeat||this.shared.lastBeat.isBefore(e.firstBeat)||this.shared.lastBeat.isBefore(this.shared.firstBeat))}}class $a{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 Qa;return this.slots.push(t),t}register(e){let t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class Ka extends wa{constructor(){super(0,0),this.computedWidth=0}doLayout(){let e=0;if(this.glyphs)for(let t=0,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];i.x=e,i.renderer=this.renderer,i.doLayout(),e+=i.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 Za extends Ka{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,i){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class er extends qa{constructor(e,t,i){super(e,t),this._bands=[],this._bandLookup=new Map,this.sizingInfo=null,this._infos=i}updateSizes(){this.topOverflow=0,this.bottomOverflow=0,this.topPadding=0,this.bottomPadding=0,this.updateHeight(),super.updateSizes()}finalizeRenderer(){let e=super.finalizeRenderer();return this.updateHeight()&&(e=!0),e}updateHeight(){if(!this.sizingInfo)return!1;let e=0;for(let t of this.sizingInfo.slots){t.shared.y=e;for(let i of t.bands)i.y=e,i.height=t.shared.height;e+=t.shared.height}return e!==this.height&&(this.height=e,!0)}applyLayoutingInfo(){if(!super.applyLayoutingInfo())return!1;if(this.index>0){let e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new $a;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 i=new Ja(e,t);i.renderer=this,i.doLayout(),this._bands.push(i),this._bandLookup.set(e.index+"."+t.effectId,i)}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 i=new Js(t,this.getVoiceContainer(e));i.preNotes=new Ka,i.onNotes=new Za,this.addBeatGlyph(i);for(let e of this._bands)e.createGlyph(t)}}paint(e,t,i){this.paintBackground(e,t,i);for(let s of this._bands)i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.isEmpty||s.paint(e+this.x,t+this.y,i)}getBand(e,t){let i=e.index+"."+t;return this._bandLookup.has(i)?this._bandLookup.get(i):null}}class tr extends Sa{get staffId(){return this._staffId}constructor(e,t){super(),this._infos=t,this._staffId=e,this.isInAccolade=!1,this.isRelevantForBoundsLookup=!1}create(e,t){return new er(e,t,this._infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class ir extends Us{constructor(e,t,i){super(e,t),this._endingsString="",this._endings=[];for(let e=0;e<ce.MaxAlternateEndings;e++)i&1<<e&&this._endings.push(e)}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(ir.Padding*this.scale+2);let e="";for(let t=0,i=this._endings.length;t<i;t++)e+=this._endings[t]+1,e+=". ";this._endingsString=e}paint(e,t,i){super.paint(e,t,i);let s=i.textBaseline;if(i.textBaseline=C.Top,this._endings.length>0){let s=this.renderer.resources;i.font=s.wordsFont,i.moveTo(e+this.x,t+this.y+this.height),i.lineTo(e+this.x,t+this.y),i.lineTo(e+this.x+this.width,t+this.y),i.stroke(),i.fillText(this._endingsString,e+this.x+ir.Padding*this.scale,t+this.y*this.scale)}i.textBaseline=s}}ir.Padding=3;class sr{get effectId(){return this.notationElement.toString()}}class ar extends sr{get notationElement(){return v.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Ke.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){return new ir(0,0,t.voice.bar.masterBar.alternateEndings)}canExpand(e,t){return!0}}class rr extends sr{get notationElement(){return v.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Aa(0,0,"Capo. fret "+t.voice.bar.staff.capo,e.resources.effectFont,E.Left)}canExpand(e,t){return!1}}class nr extends sr{get notationElement(){return v.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Aa(0,0,t.chord.name,e.resources.effectFont,E.Center)}canExpand(e,t){return!1}}class or extends Us{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,i){if(this.isLinkedWithPrevious)return;if(!this.isLinkedWithNext&&!this.forceGroupedRendering)return void this.paintNonGrouped(e,t,i);let s;if(!this.isLinkedWithNext&&this.forceGroupedRendering)s=this;else for(s=this.nextGlyph;s.isLinkedWithNext;)s=s.nextGlyph;let a=s.renderer,r=s.beat,n=this.endPosition,o=e-this.renderer.x,h=this.calculateEndX(a,r,o,n);this.paintGrouped(e,t,h,i)}calculateEndX(e,t,i,s){return t?i+e.x+e.getBeatX(t,s):i+e.x+this.x+this.width}paintNonGrouped(e,t,i){let s=e-this.renderer.x,a=this.calculateEndX(this.renderer,this.beat,s,this.endPosition);this.paintGrouped(e,t,a,i)}}class hr extends or{constructor(e,t,i){super(qe.EndBeat),this._crescendo=u.None,this._crescendo=i,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17*this.scale}paintGrouped(e,t,i,s){let a=e+this.x,r=this.height*this.scale;s.beginPath(),this._crescendo===u.Crescendo?(i-=hr.Padding*this.scale,s.moveTo(i,t+this.y),s.lineTo(a,t+this.y+r/2),s.lineTo(i,t+this.y+r)):(i-=hr.Padding*this.scale,s.moveTo(a,t+this.y),s.lineTo(i,t+this.y+r/2),s.lineTo(a,t+this.y+r)),s.stroke()}}hr.Padding=Ys.QuarterNoteHeadWidth/2|0;class lr extends sr{get notationElement(){return v.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==u.None}createNewGlyph(e,t){return new hr(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class cr extends Xs{constructor(e,t,i){super(e,t,.6,cr.getSymbol(i))}doLayout(){super.doLayout(),this.height=17*this.scale,this.y+=this.height/2}static getSymbol(e){switch(e){case g.PPP:return P.DynamicPPP;case g.PP:return P.DynamicPP;case g.P:return P.DynamicPiano;case g.MP:return P.DynamicMP;case g.MF:return P.DynamicMF;case g.F:return P.DynamicForte;case g.FF:return P.DynamicFF;case g.FFF:return P.DynamicFFF;default:return P.None}}}class dr extends sr{get notationElement(){return v.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return this.internalShouldCreateGlyph(t)}internalShouldCreateGlyph(e){if(e.voice.bar.staff.track.score.stylesheet.hideDynamics||e.isEmpty||e.voice.isEmpty||e.isRest||e.graceType!==f.None)return!1;let t=this.getPreviousDynamicsBeat(e),i=0===e.voice.index&&!t||e.dynamics!==t?.dynamics;if(i&&e.voice.index>0)for(let t of e.voice.bar.voices)if(t.index<e.voice.index){let s=t.getBeatAtPlaybackStart(e.playbackStart);s&&e.dynamics===s.dynamics&&this.internalShouldCreateGlyph(s)&&(i=!1)}return i}getPreviousDynamicsBeat(e){let t=e.previousBeat;for(;null!=t;){if(!t.isRest&&t.graceType===f.None)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new cr(0,0,t.dynamics)}canExpand(e,t){return!0}}class ur extends Us{doLayout(){super.doLayout(),this.height=17*this.scale}paint(e,t,i){let s=6*this.scale,a=Math.max(this.width,14*this.scale),r=this.height/2;i.beginPath(),i.moveTo(e+this.x,t+this.y+r),i.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r-s),i.moveTo(e+this.x,t+this.y+r),i.quadraticCurveTo(e+this.x+a/2,t+this.y+r,e+this.x+a,t+this.y+r+s),i.stroke()}}class pr extends sr{get notationElement(){return v.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return t.fadeIn}createNewGlyph(e,t){return new ur}canExpand(e,t){return!0}}class gr extends Xs{constructor(e,t,i){super(e,t,1,gr.getSymbol(i))}static getSymbol(e){switch(e){case Ne.Short:return P.FermataShortAbove;case Ne.Medium:return P.FermataAbove;case Ne.Long:return P.FermataLongAbove;default:return P.None}}doLayout(){this.width=23*this.scale,this.height=12*this.scale}paint(e,t,i){super.paint(e-this.width/2,t+this.height,i)}}class fr extends sr{get notationElement(){return v.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new gr(0,0,t.fermata.type)}canExpand(e,t){return!0}}class mr extends sr{get notationElement(){return v.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(t,i){return!(0!==i.voice.index||i.isRest||t.notation.fingeringMode!==e.FingeringMode.SingleNoteEffectBand&&t.notation.fingeringMode!==e.FingeringMode.SingleNoteEffectBandForcePiano)&&(1===i.notes.length&&i.notes[0].isFingering)}createNewGlyph(e,t){let i=m.Unknown,s=!1,a=t.notes[0];a.leftHandFinger!==m.Unknown?(i=a.leftHandFinger,s=!0):a.rightHandFinger!==m.Unknown&&(i=a.rightHandFinger);let r=Q.fingerToString(e.settings,t,i,s)??"";return new Aa(0,0,r,e.resources.fingeringFont,E.Left)}canExpand(e,t){return!0}}class yr extends sr{constructor(){super(...arguments),this.lastCreateInfo=null}shouldCreateGlyph(e,t){this.lastCreateInfo=[];for(let e=0,i=t.notes.length;e<i;e++){let i=t.notes[e];this.shouldCreateGlyphForNote(i)&&this.lastCreateInfo.push(i)}return this.lastCreateInfo.length>0}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}canExpand(e,t){return!0}}class br extends or{constructor(e){super(qe.OnNotes),this._label=e}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=qe.EndBeat,this.forceGroupedRendering=!0),super.doLayout(),this.height=this.renderer.resources.effectFont.size}paintNonGrouped(e,t,i){let s=this.renderer.resources;i.font=s.effectFont;let a=i.textAlign;i.textAlign=E.Center,i.fillText(this._label,e+this.x,t+this.y),i.textAlign=a}paintGrouped(e,t,i,s){this.paintNonGrouped(e,t,s);let a=3*this.scale,r=s.measureText(this._label),n=e+this.x+r/2+a,o=t+this.y+4*this.scale,h=8*this.scale;if(i>n){let e=n;for(;e<i;)s.beginPath(),s.moveTo(e,0|o),s.lineTo(Math.min(e+h,i),0|o),e+=h+a,s.stroke();s.beginPath(),s.moveTo(i,o-5*this.scale|0),s.lineTo(i,o+5*this.scale|0),s.stroke()}}}br.LineSpacing=3,br.LineTopPadding=4,br.LineTopOffset=5,br.LineSize=8;class Sr extends yr{get effectId(){return this._effectId}get notationElement(){return v.EffectHarmonics}constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case y.None:this._effectId="harmonics-none";break;case y.Natural:this._effectId="harmonics-natural";break;case y.Artificial:this._effectId="harmonics-artificial";break;case y.Pinch:this._effectId="harmonics-pinch";break;case y.Tap:this._effectId="harmonics-tap";break;case y.Semi:this._effectId="harmonics-semi";break;case y.Feedback:this._effectId="harmonics-feedback";break;default:this._effectId=""}}shouldCreateGlyphForNote(e){return!(!e.isHarmonic||e.harmonicType!==this._harmonicType)&&(e.beat!==this._beat&&(this._beat=e.beat),!0)}get sizingMode(){return Ke.GroupedOnBeat}createNewGlyph(e,t){return new br(Sr.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case y.Natural:return"N.H.";case y.Artificial:return"A.H.";case y.Pinch:return"P.H.";case y.Tap:return"T.H.";case y.Semi:return"S.H.";case y.Feedback:return"Fdbk."}return""}}class wr extends sr{get notationElement(){return v.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return Ke.GroupedOnBeat}createNewGlyph(e,t){return new br("LetRing")}canExpand(e,t){return!0}}class _r extends Us{constructor(e,t,i,s,a=E.Center){super(e,t),this._lines=i,this.font=s,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,i){i.font=this.font;let s=i.textAlign;i.textAlign=this.textAlign;for(let s=0;s<this._lines.length;s++)this._lines[s]&&i.fillText(this._lines[s],e+this.x,t+this.y+s*this.font.size);i.textAlign=s}}class Br extends sr{get notationElement(){return v.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new _r(0,0,t.lyrics,e.resources.effectFont,E.Center)}canExpand(e,t){return!0}}class Tr extends sr{get notationElement(){return v.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return Ke.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 Aa(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,E.Left)}canExpand(e,t){return!0}}class kr extends or{constructor(e,t){super(qe.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=13*this.scale}paintNonGrouped(e,t,i){this.paintOttava(e,t,i)}paintOttava(e,t,i){let s=0;switch(this._ottava){case o._15ma:s=37*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,P.QuindicesimaAlta,!1);break;case o._8va:s=26*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,P.OttavaAlta,!1);break;case o._8vb:s=23*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,P.OttavaBassaVb,!1);break;case o._15mb:s=36*this.scale,i.fillMusicFontSymbols(e+this.x-s/2,t+this.y+this.height,.8,[P.Quindicesima,P.OctaveBaselineM,P.OctaveBaselineB],!1)}return s/2}paintGrouped(e,t,i,s){let a=this.paintOttava(e,t,s),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(i>n){let e=n;for(;e<i;)s.beginPath(),s.moveTo(e,0|o),s.lineTo(Math.min(e+h,i),0|o),e+=h+r,s.stroke();s.beginPath(),this._aboveStaff?(s.moveTo(i,o),s.lineTo(i,t+this.y+this.height)):(s.moveTo(i,o),s.lineTo(i,t+this.y)),s.stroke()}}}class vr extends sr{get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return v.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.GroupedOnBeat}constructor(e){super(),this._aboveStaff=e}shouldCreateGlyph(e,t){switch(t.ottava){case o._15ma:case o._8va:return this._aboveStaff;case o._8vb:case o._15mb:return!this._aboveStaff}return!1}createNewGlyph(e,t){return new kr(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class xr extends yr{get notationElement(){return v.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return Ke.GroupedOnBeat}createNewGlyph(e,t){return new br("P.M.")}constructor(){super()}}class Nr extends yr{get notationElement(){return v.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===w.PickSlideDown||e.slideOutType===w.PickSlideUp}get sizingMode(){return Ke.GroupedOnBeat}createNewGlyph(e,t){return new br("P.S.")}constructor(){super()}}class Pr extends Xs{constructor(e,t,i){super(e,t,Ys.GraceScale,Pr.getSymbol(i))}doLayout(){this.width=9*this.scale,this.height=13*this.scale}paint(e,t,i){super.paint(e,t+this.height,i)}static getSymbol(e){switch(e){case N.Up:return P.StringsUpBow;case N.Down:return P.StringsDownBow;default:return P.None}}}class Er extends sr{get notationElement(){return v.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==N.None}createNewGlyph(e,t){return new Pr(0,0,t.pickStroke)}canExpand(e,t){return!0}}class Cr extends or{constructor(e){super(qe.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case _.Slight:this._stepSize=12*this.scale;break;case _.Wide:this._stepSize=23*this.scale}this.height=18*this.scale}paintGrouped(e,t,i,s){let a=e+this.x,r=i-a,n=Math.max(1,r/this._stepSize);s.beginPath(),s.moveTo(a,t+this.y);for(let e=0;e<n;e++)s.lineTo(a+this._stepSize/2,t+this.y+this.height),s.lineTo(a+this._stepSize,t+this.y),a+=this._stepSize;s.stroke()}}class Fr extends sr{get notationElement(){return v.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===_.Slight}createNewGlyph(e,t){return new Cr(_.Slight)}canExpand(e,t){return!0}}class Lr extends or{constructor(e,t,i,s=1.2,a=!1){super(qe.EndBeat),this._scale=0,this._symbol=P.None,this._symbolSize=0,this._type=i,this._scale=s,this.x=e,this.y=t,this._partialWaves=a}doLayout(){super.doLayout();let e=0;switch(this._type){case _.Slight:this._symbol=P.WiggleTrill,this._symbolSize=9*this._scale,e=6*this._scale;break;case _.Wide:this._symbol=P.WiggleVibratoMediumFast,this._symbolSize=10*this._scale,e=10*this._scale}this.height=e*this.scale}paintGrouped(e,t,i,s){let a=i-(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 i=0;i<n;i++)s.fillMusicFontSymbol(e+this.x+o,t+this.y+2*this.height,this._scale*this.scale,this._symbol,!1),o+=r}}class Mr extends yr{get notationElement(){return v.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===_.Slight||e.isTieDestination&&e.tieOrigin.vibrato===_.Slight}get sizingMode(){return Ke.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Lr(0,0,_.Slight,1.2)}constructor(){super()}}class Ir extends sr{get notationElement(){return v.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){let i=e.resources;return t.slap?new Aa(0,0,"S",i.effectFont,E.Left):t.pop?new Aa(0,0,"P",i.effectFont,E.Left):new Aa(0,0,"T",i.effectFont,E.Left)}canExpand(e,t){return!0}}class Dr extends Us{constructor(e,t,i){super(e,t),this._tempo=0,this._tempo=i}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,i){let s=this.renderer.resources;i.font=s.markerFont,i.fillMusicFontSymbol(e+this.x,t+this.y+.8*this.height,this.scale*Ys.GraceScale,P.NoteQuarterUp,!1),i.fillText("= "+this._tempo.toString(),e+this.x+this.height/2,t+this.y+i.font.size/2)}}class Ar extends sr{get notationElement(){return v.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Ke.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 i=0;return i=t.voice.bar.masterBar.tempoAutomation?t.voice.bar.masterBar.tempoAutomation.value:t.voice.bar.staff.track.score.tempo,new Dr(0,0,i)}canExpand(e,t){return!0}}class Rr extends sr{get notationElement(){return v.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Aa(0,0,t.text,e.resources.effectFont,E.Left)}canExpand(e,t){return!0}}class Or extends Us{constructor(e,t){super(e,t)}doLayout(){super.doLayout(),this.height=this.renderer.resources.markerFont.size*this.scale}paint(e,t,i){let s=this.renderer.resources;i.font=s.markerFont;let a=i.measureText("tr");i.fillText("tr",e+this.x,t+this.y);let r=a+3*this.scale,n=this.width-r,o=11*this.scale*1.2,h=Math.max(1,(n-r)/o),l=r,c=t+this.y+1.2*this.height;for(let t=0;t<h;t++)i.fillMusicFontSymbol(e+this.x+l,c,1.2,P.WiggleTrill,!1),l+=o}}class Gr extends yr{get notationElement(){return v.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return Ke.SingleOnBeat}createNewGlyph(e,t){return new Or(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(Ze||(Ze={}));class Vr extends Us{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25*this.scale}paint(e,t,i){e+=this.x;let s=(t+=this.y)+this.height*Ys.GraceScale;i.font=this.renderer.resources.effectFont,i.fillText("(",e,t+.3*this.height);let a=e+10*this.scale,r=e+40*this.scale;switch(this._tripletFeel){case A.NoTripletFeel:this.renderBarNote(a,s,Vr.NoteScale,i,[Ze.Full]),this.renderBarNote(r,s,Vr.NoteScale,i,[Ze.Full]);break;case A.Triplet8th:this.renderBarNote(a,s,Vr.NoteScale,i,[Ze.Full]),i.fillMusicFontSymbol(r,s,Vr.NoteScale,P.NoteQuarterUp,!1),i.fillMusicFontSymbol(r+Vr.NoteSeparation*this.scale,s,Vr.NoteScale,P.NoteEighthUp,!1),this.renderTriplet(r,t,i);break;case A.Triplet16th:this.renderBarNote(a,s,Vr.NoteScale,i,[Ze.Full,Ze.Full]),this.renderBarNote(r,s,Vr.NoteScale,i,[Ze.Full,Ze.PartialRight]),this.renderTriplet(r,t,i);break;case A.Dotted8th:this.renderBarNote(a,s,Vr.NoteScale,i,[Ze.Full]),this.renderBarNote(r,s,Vr.NoteScale,i,[Ze.Full,Ze.PartialRight]),i.fillCircle(r+9*this.scale,s,this.scale);break;case A.Dotted16th:this.renderBarNote(a,s,Vr.NoteScale,i,[Ze.Full,Ze.Full]),this.renderBarNote(r,s,Vr.NoteScale,i,[Ze.Full,Ze.Full,Ze.PartialRight]),i.fillCircle(r+9*this.scale,s,this.scale);break;case A.Scottish8th:this.renderBarNote(a,s,Vr.NoteScale,i,[Ze.Full]),this.renderBarNote(r,s,Vr.NoteScale,i,[Ze.Full,Ze.PartialLeft]),i.fillCircle(r+Vr.NoteSeparation*this.scale+8*this.scale,s,this.scale);break;case A.Scottish16th:this.renderBarNote(a,s,Vr.NoteScale,i,[Ze.Full,Ze.Full]),this.renderBarNote(r,s,Vr.NoteScale,i,[Ze.Full,Ze.Full,Ze.PartialLeft]),i.fillCircle(r+Vr.NoteSeparation*this.scale+8*this.scale,s,this.scale)}i.fillText("=",e+30*this.scale,t+5*this.scale),i.fillText(")",e+65*this.scale,t+.3*this.height)}renderBarNote(e,t,i,s,a){s.fillMusicFontSymbol(e,t,i,P.NoteQuarterUp,!1);let r=Vr.NoteSeparation/2*this.scale;for(let i=0;i<a.length;i++)switch(a[i]){case Ze.Full:s.fillRect(e+4*this.scale,t-Vr.NoteHeight*this.scale+Vr.BarSeparation*this.scale*i,Vr.NoteSeparation*this.scale,Vr.BarHeight*this.scale);break;case Ze.PartialLeft:s.fillRect(e+4*this.scale,t-Vr.NoteHeight*this.scale+Vr.BarSeparation*this.scale*i,r,Vr.BarHeight*this.scale);break;case Ze.PartialRight:s.fillRect(e+4*this.scale+r,t-Vr.NoteHeight*this.scale+Vr.BarSeparation*this.scale*i,r,Vr.BarHeight*this.scale)}s.fillMusicFontSymbol(e+Vr.NoteSeparation*this.scale,t,i,P.NoteQuarterUp,!1)}renderTriplet(e,t,i){t+=2*this.scale;let s=this.renderer.resources.effectFont;i.font=Ri.withFamilyList(s.families,.8*s.size,s.style);let a=e+Vr.NoteSeparation*this.scale+3*this.scale;i.beginPath(),i.moveTo(e,t+3*this.scale),i.lineTo(e,t),i.lineTo(e+5*this.scale,t),i.moveTo(a+5*this.scale,t+3*this.scale),i.lineTo(a+5*this.scale,t),i.lineTo(a,t),i.stroke(),i.fillText("3",e+7*this.scale,t-10*this.scale),i.font=s}}Vr.NoteScale=.4,Vr.NoteHeight=12,Vr.NoteSeparation=12,Vr.BarHeight=2,Vr.BarSeparation=3;class Hr extends sr{get notationElement(){return v.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return Ke.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==A.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new Vr(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class Wr extends sr{get notationElement(){return v.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return Ke.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new br("w/bar")}canExpand(e,t){return!0}}class zr extends sr{get notationElement(){return v.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return Ke.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===_.Wide}createNewGlyph(e,t){return new Cr(_.Wide)}canExpand(e,t){return!0}}class Ur extends yr{get notationElement(){return v.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===_.Wide||e.isTieDestination&&e.tieOrigin.vibrato===_.Wide}get sizingMode(){return Ke.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Lr(0,0,_.Wide,1.2)}}class Xr{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class Yr extends Ya{get name(){return"HorizontalScreen"}constructor(e){super(e),this._group=null,this._pagePadding=null}get supportsResize(){return!1}get firstBarX(){let e=this._pagePadding[0];return this._group&&(e+=this._group.accoladeSpacing),e}doResize(){}doLayoutAndRender(){switch(this._pagePadding=this.renderer.settings.display.padding,this.renderer.settings.display.systemsLayoutMode){case e.SystemsLayoutMode.Automatic:this.systemsLayoutMode=je.Automatic;break;case e.SystemsLayoutMode.UseModelLayout:this.systemsLayoutMode=je.FromModelWithWidths}this._pagePadding||(this._pagePadding=Yr.PagePadding),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let t=this.renderer.score,i=this.renderer.settings.display.startBar;i--,i=Math.min(t.masterBars.length-1,Math.max(0,i));let s=i,a=this.renderer.settings.display.barCount;a<=0&&(a=t.masterBars.length),a=i+a-1,a=Math.min(t.masterBars.length-1,Math.max(0,a)),this._group=this.createEmptyStaveGroup(),this._group.isLast=!0,this._group.x=this._pagePadding[0],this._group.y=this._pagePadding[1];let r=this.renderer.settings.display.barCountPerPartial,n=[],o=new Xr,h=0;for(;s<=a;){let e=this._group.addBars(this.renderer.tracks,s);if(e)if(0===o.masterBars.length&&e.isLinkedToPrevious&&n.length>0){let i=n[n.length-1];i.masterBars.push(t.masterBars[s]),i.width+=e.width,h+=e.width,o.x+=h}else o.masterBars.push(t.masterBars[s]),o.width+=e.width,o.masterBars.length>=r&&(0===n.length&&(o.width+=this._group.accoladeSpacing+this._pagePadding[0]),h+=o.width,n.push(o),J.debug(this.name,"Finished partial from bar "+o.masterBars[0].index+" to "+o.masterBars[o.masterBars.length-1].index,null),o=new Xr,o.x=h);s++}o.masterBars.length>0&&(0===n.length&&(o.width+=this._group.accoladeSpacing+this._pagePadding[0]),n.push(o),J.debug(this.name,"Finished partial from bar "+o.masterBars[0].index+" to "+o.masterBars[o.masterBars.length-1].index,null)),this.finalizeGroup(),this.height=Math.floor(this._group.y+this._group.height),this.width=this._group.x+this._group.width+this._pagePadding[2],s=0;let l=0;for(let e=0;e<n.length;e++){const t=n[e],i=new _s;i.x=l,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,l+=t.width;const a=s,r=e;this._group.buildBoundingsLookup(this._group.x,this._group.y),this.registerPartial(i,(e=>{let i=this._group.getBarX(t.masterBars[0].index)+this._group.accoladeSpacing;0===r&&(i-=this._group.x+this._group.accoladeSpacing),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=E.Left,J.debug(this.name,"Rendering partial from bar "+t.masterBars[0].index+" to "+t.masterBars[t.masterBars.length-1].index,null),this._group.paintPartial(-i,this._group.y,e,a,t.masterBars.length)})),s+=t.masterBars.length}this.height=this.layoutAndRenderAnnotation(this.height)+this._pagePadding[3]}finalizeGroup(){this._group.scaleToWidth(this._group.width),this._group.finalizeGroup()}}Yr.PagePadding=[20,20,20,20],Yr.GroupSpacing=20;class qr extends Ya{get name(){return"PageView"}constructor(e){super(e),this._groups=[],this._allMasterBarRenderers=[],this._barsFromPreviousGroup=[],this._pagePadding=null}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case e.SystemsLayoutMode.Automatic:this.systemsLayoutMode=je.Automatic;break;case e.SystemsLayoutMode.UseModelLayout:this.systemsLayoutMode=je.FromModelWithScale}this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=qr.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 t=0;this.width=this.renderer.width,this._allMasterBarRenderers=[],t=this.layoutAndRenderScoreInfo(t,-1),t=this.layoutAndRenderTunings(t,-1),t=this.layoutAndRenderChordDiagrams(t,-1),t=this.layoutAndRenderScore(t),t=this.layoutAndRenderAnnotation(t),this.height=t+this._pagePadding[3]}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 i=this.renderer.settings.display.resources;this.tuningGlyph.x=this._pagePadding[0],this.tuningGlyph.width=this.width,this.tuningGlyph.doLayout();let s=this.tuningGlyph.height+11*this.scale;const a=new _s;return a.x=0,a.y=e,a.width=this.width,a.height=s,a.totalWidth=this.width,a.totalHeight=t<0?e+a.height:t,this.registerPartial(a,(e=>{e.color=i.scoreInfoColor,e.textAlign=E.Center,this.tuningGlyph.paint(0,0,e)})),e+s}layoutAndRenderChordDiagrams(e,t=-1){if(!this.chordDiagrams)return e;const i=this.renderer.settings.display.resources;this.chordDiagrams.width=this.width,this.chordDiagrams.doLayout();const s=Math.floor(this.chordDiagrams.height),a=new _s;return a.x=0,a.y=e,a.width=this.width,a.height=s,a.totalWidth=this.width,a.totalHeight=t<0?e+s:t,this.registerPartial(a,(e=>{e.color=i.scoreInfoColor,e.textAlign=E.Center,this.chordDiagrams.paint(0,0,e)})),e+s}layoutAndRenderScoreInfo(e,t=-1){J.debug(this.name,"Layouting score info");const i=new _s;i.x=0,i.y=e;let s=this._pagePadding[1],a=this.scale,r=this.renderer.settings.display.resources,n=[v.ScoreTitle,v.ScoreSubTitle,v.ScoreArtist,v.ScoreAlbum,v.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=s,t.textAlign=E.Center,s+=t.font.size*a}let o=!1,h=0;if(this.scoreInfoGlyphs.has(v.ScoreMusic)){let e=this.scoreInfoGlyphs.get(v.ScoreMusic);e.x=this.width-this._pagePadding[2],e.y=s,e.textAlign=E.Right,o=!0,h=e.font.size*a}if(this.scoreInfoGlyphs.has(v.ScoreWords)){let e=this.scoreInfoGlyphs.get(v.ScoreWords);e.x=this._pagePadding[0],e.y=s,e.textAlign=E.Left,o=!0,h=e.font.size*a}return o&&(s+=h),s=Math.floor(s+17*this.scale),i.width=this.width,i.height=s,i.totalWidth=this.width,i.totalHeight=t<0?e+i.height:t,this.registerPartial(i,(e=>{e.color=r.scoreInfoColor,e.textAlign=E.Center;for(const t of this.scoreInfoGlyphs.values())t.paint(0,0,e)})),e+s}resizeAndRenderScore(e,t){if(this.renderer.settings.display.barsPerRow>0||this.systemsLayoutMode==je.FromModelWithScale)for(let i=0;i<this._groups.length;i++){let s=this._groups[i];this.fitGroup(s),e+=this.paintGroup(s,t)}else{this._groups=[];let i=0,s=this.maxWidth,a=this.createEmptyStaveGroup();for(a.index=this._groups.length,a.x=this._pagePadding[0],a.y=e;i<this._allMasterBarRenderers.length;){let r=this._allMasterBarRenderers[i];if(a.width+r.width<=s||0===a.masterBarsRenderers.length)a.addMasterBarRenderers(this.renderer.tracks,r),i++;else{for(;r&&!r.canWrap&&a.masterBarsRenderers.length>1;)r=a.revertLastBar(),i--;a.isFull=!0,a.isLast=this.lastBarIndex===a.lastBarIndex,this._groups.push(a),this.fitGroup(a),e+=this.paintGroup(a,t),a=this.createEmptyStaveGroup(),a.index=this._groups.length,a.x=this._pagePadding[0],a.y=e}}a.isLast=this.lastBarIndex===a.lastBarIndex,this.fitGroup(a),e+=this.paintGroup(a,t)}return e}layoutAndRenderScore(e){let t=this.firstBarIndex,i=this.lastBarIndex;for(this._groups=[];t<=i;){let s=this.createStaveGroup(t,i);this._groups.push(s),s.x=this._pagePadding[0],s.y=e,t=s.lastBarIndex+1,this.fitGroup(s),J.debug(this.name,"Rendering partial from bar "+s.firstBarIndex+" to "+s.lastBarIndex,null),e+=this.paintGroup(s,e)}return e}paintGroup(e,t){let i=Math.floor(e.height+20*this.scale);const s=new _s;return s.x=0,s.y=e.y,s.totalWidth=this.width,s.totalHeight=t,s.width=this.width,s.height=i,s.firstMasterBarIndex=e.firstBarIndex,s.lastMasterBarIndex=e.lastBarIndex,e.buildBoundingsLookup(0,0),this.registerPartial(s,(t=>{this.renderer.canvas.color=this.renderer.settings.display.resources.mainGlyphColor,this.renderer.canvas.textAlign=E.Left,e.paint(0,-s.y,t)})),t+=i,i}fitGroup(e){e.isFull||e.width>this.maxWidth||this.renderer.settings.display.justifyLastSystem?e.scaleToWidth(this.maxWidth):e.scaleToWidth(e.width),e.finalizeGroup()}getBarsPerRow(e){let t=this.renderer.settings.display.barsPerRow;if(this.systemsLayoutMode==je.FromModelWithScale){let i,s;this.renderer.tracks.length>1?(i=this.renderer.score.defaultSystemsLayout,s=this.renderer.score.systemsLayout):(i=this.renderer.tracks[0].defaultSystemsLayout,s=this.renderer.tracks[0].systemsLayout),t=e<s.length?s[e]:i}return t}createStaveGroup(e,t){let i=this.createEmptyStaveGroup();i.index=this._groups.length;let s=this.getBarsPerRow(i.index),a=this.maxWidth,r=t+1,n=e;for(;n<r;){if(this._barsFromPreviousGroup.length>0)for(let e of this._barsFromPreviousGroup)i.addMasterBarRenderers(this.renderer.tracks,e),n=e.masterBar.index;else{let e=i.addBars(this.renderer.tracks,n);e&&this._allMasterBarRenderers.push(e)}this._barsFromPreviousGroup=[];let e=!1;if((-1===s&&i.width>=a&&0!==i.masterBarsRenderers.length||i.masterBarsRenderers.length===s+1)&&(e=!0),e){let e=i.revertLastBar();if(e)for(this._barsFromPreviousGroup.push(e);e&&!e.canWrap&&i.masterBarsRenderers.length>1;)e=i.revertLastBar(),e&&this._barsFromPreviousGroup.push(e);return i.isFull=!0,i.isLast=!1,this._barsFromPreviousGroup.reverse(),i}i.x=0,n++}return i.isLast=t===i.lastBarIndex,i}get maxWidth(){return this.renderer.width-this._pagePadding[0]-this._pagePadding[2]}}qr.PagePadding=[40,40,40,40],qr.GroupSpacing=20;class Jr extends Xs{constructor(e,t,i,s=!1){super(e,t,s?Ys.GraceScale:1,Jr.getMusicSymbol(i)),this._isGrace=s,this._accidentalType=i}static getMusicSymbol(e){switch(e){case Je.Natural:return P.AccidentalNatural;case Je.Sharp:return P.AccidentalSharp;case Je.Flat:return P.AccidentalFlat;case Je.NaturalQuarterNoteUp:return P.AccidentalQuarterToneNaturalArrowUp;case Je.SharpQuarterNoteUp:return P.AccidentalQuarterToneSharpArrowUp;case Je.FlatQuarterNoteUp:return P.AccidentalQuarterToneFlatArrowUp;case Je.DoubleSharp:return P.AccidentalDoubleSharp;case Je.DoubleFlat:return P.AccidentalDoubleFlat}return P.None}doLayout(){if(this._accidentalType===Je.DoubleFlat)this.width=18;else this.width=8;this.width=this.width*(this._isGrace?Ys.GraceScale:1)*this.scale}}class jr extends zs{constructor(e,t,i){super(e,t),this._number=0,this._number=i}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,i){if(!this.renderer.staff.isFirstInAccolade)return;let s=this.renderer.resources,a=i.color;i.color=s.barNumberColor,i.font=s.barNumberFont,i.fillText(this._number.toString(),e+this.x,t+this.y),i.color=a}}class Qr extends zs{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,i){let s=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?(i.fillRect(n+this.width-s-s,a,this.scale,o),i.fillRect(n+this.width-s,a,s,o)):this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart||(i.fillRect(n+this.width-this.scale,a,this.scale,o),this.renderer.bar.masterBar.isDoubleBar&&i.fillRect(n+this.width-5*this.scale,a,this.scale,o))}}class $r extends Xs{constructor(e,t,i,s){super(e,t,1,$r.getSymbol(i)),this._clef=i,this._clefOttava=s}doLayout(){switch(this._clef){case n.Neutral:this.width=15*this.scale;break;case n.C3:case n.C4:case n.F4:case n.G2:this.width=28*this.scale}}static getSymbol(e){switch(e){case n.Neutral:return P.UnpitchedPercussionClef1;case n.C3:case n.C4:return P.CClef;case n.F4:return P.FClef;case n.G2:return P.GClef;default:return P.None}}paint(e,t,i){let s;super.paint(e,t,i);let a=!1;switch(this._clefOttava){case o._15ma:s=new Xs(-4*this.scale,0,.5,P.Quindicesima),a=!0;break;case o._8va:s=new Xs(-2*this.scale,0,.5,P.Ottava),a=!0;break;case o._8vb:s=new Xs(-6*this.scale,0,.5,P.Ottava);break;case o._15mb:s=new Xs(-8*this.scale,0,.5,P.Quindicesima);break;default:return}let r=0,h=0;switch(this._clef){case n.Neutral:r=a?-12:15,h=0;break;case n.C3:case n.C4:r=a?-19:27,h=0;break;case n.F4:r=a?-9:27,h=-4;break;case n.G2:r=a?-37:30,h=0;break;default:return}s.renderer=this.renderer,s.doLayout();let l=this.width/2;s.paint(e+this.x+l+h*this.scale,t+this.y+r*this.scale,i)}}class Kr extends zs{constructor(e,t){super(e,t)}doLayout(){this.width=11*this.scale}paint(e,t,i){let s=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;i.fillCircle(n,l-3*h,h),i.fillCircle(n,l+3*h,h),n+=4*this.scale,i.beginPath(),i.moveTo(n,a),i.lineTo(n,r),i.stroke(),n+=3*this.scale+.5,i.fillRect(n,a,s,o)}}class Zr extends zs{constructor(e,t,i){super(e,t),this._count=0,this._count=0,this._count=i}doLayout(){this.width=0}paint(e,t,i){let s=this.renderer.resources,a=i.textAlign;i.font=s.barNumberFont,i.textAlign=E.Right;let r="x"+this._count,n=i.measureText(r)/1.5;i.fillText(r,e+this.x-n,t+this.y),i.textAlign=a}}class en extends zs{constructor(e,t,i,s){super(e,t),this._dotOffset=0,this._circleSize=0,this._dotOffset=0,this._circleSize=0,this._dotOffset=s,this._circleSize=i}doLayout(){this.width=13*this.scale}paint(e,t,i){let s=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;i.fillRect(n,a,s,o),n+=2*s-.5,i.beginPath(),i.moveTo(n,a),i.lineTo(n,r),i.stroke(),n+=3*this.scale;let h=this._circleSize*this.scale,l=(a+r)/2;i.fillCircle(n,l-h*this._dotOffset,h),i.fillCircle(n,l+h*this._dotOffset,h)}}class tn extends Xs{constructor(e,t,i){super(e,t,1,tn.getSymbol(i))}static getSymbol(e){switch(e){case a.None:return P.None;case a.Normal:return P.ArticAccentAbove;case a.Heavy:return P.ArticMarcatoAbove;default:return P.None}}doLayout(){this.width=9*this.scale,this.height=9*this.scale}paint(e,t,i){super.paint(e-2*this.scale,t+this.height,i)}}class sn extends zs{constructor(e,t,i){super(e,t),this._size=0,this._size=i}doLayout(){this.width=this._size+3*this.scale}paint(e,t,i){i.fillCircle(e+this.x,t+this.y,this._size)}}class an extends Xs{constructor(e,t,i){super(e,t,i?Ys.GraceScale:1,P.NoteheadXOrnate),this._isGrace=i}doLayout(){this.width=9*(this._isGrace?Ys.GraceScale:1)*this.scale,this.height=Ys.NoteHeadHeight*this.scale}}class rn extends Xs{constructor(e,t,i,s){super(e,t,s?Ys.GraceScale:1,rn.getSymbol(i)),this._isGrace=s}static getSymbol(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:case p.Half:return P.NoteheadDiamondWhiteWide;default:return P.NoteheadDiamondBlackWide}}doLayout(){this.width=9*(this._isGrace?Ys.GraceScale:1)*this.scale,this.height=Ys.NoteHeadHeight*this.scale}}class nn extends zs{constructor(e,t,i){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=Ce.Up,this._startX=0,this._startY=0,this._endX=0,this._endY=0,this._tieHeight=0,this._shouldDraw=!1,this.startBeat=e,this.endBeat=t,this.forEnd=i}doLayout(){if(this.width=0,!this.endBeat)return void(this._shouldDraw=!1);let e=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar);this.startNoteRenderer=e;let t=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.endBeat.voice.bar);this.endNoteRenderer=t,this._startX=0,this._endX=0,this._startY=0,this._endY=0,this.height=0,this._shouldDraw=!1,this.tieDirection=e?this.getBeamDirection(this.startBeat,e):this.getBeamDirection(this.endBeat,t),!this.forEnd&&e?(e!==t?(this._startX=e.x+this.getStartX(),this._startY=e.y+this.getStartY()+this.yOffset,t&&e.staff===t.staff?(this._endX=t.x+this.getEndX(),this._endY=t.y+this.getEndY()+this.yOffset):(this._endX=e.x+e.width,this._endY=this._startY)):(this._startX=e.x+this.getStartX(),this._endX=t.x+this.getEndX(),this._startY=e.y+this.getStartY()+this.yOffset,this._endY=t.y+this.getEndY()+this.yOffset),this._shouldDraw=!0):e&&e.staff===t.staff||(this._startX=t.x,this._endX=t.x+this.getEndX(),this._startY=t.y+this.getEndY()+this.yOffset,this._endY=this._startY,this._shouldDraw=!0),this._shouldDraw&&(this.y=Math.min(this._startY,this._endY),this.shouldDrawBendSlur()?this._tieHeight=0:(this._tieHeight=this.getTieHeight(this._startX,this._startY,this._endX,this._endY),this.height=nn.calculateActualTieHeight(this.renderer.scale,this._startX,this._startY,this._endX,this._endY,this.tieDirection===Ce.Down,this._tieHeight,4).h),this.tieDirection===Ce.Up&&(this.y-=this.height))}paint(e,t,i){this._shouldDraw&&(this.shouldDrawBendSlur()?nn.drawBendSlur(i,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Ce.Down,this.scale):nn.paintTie(i,this.scale,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===Ce.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,i,s){return 22}getBeamDirection(e,t){return Ce.Down}getStartY(){return 0}getEndY(){return 0}getStartX(){return 0}getEndX(){return 0}static calculateActualTieHeight(e,t,i,s,a,r,n,o){const h=nn.computeBezierControlPoints(e,t,i,s,a,r,n,o);t=h[0],i=h[1];const l=h[2],c=h[3];s=h[6],a=h[7];const d=(t-l)/(t-2*l+s),u=nn.calculateExtrema(t,i,l,c,s,a,d),p=u.length>0?Math.min(t,s,u[0]):Math.min(t,s),g=u.length>0?Math.max(t,s,u[0]):Math.max(t,s),f=(i-c)/(i-2*c+a),m=nn.calculateExtrema(t,i,l,c,s,a,f),y=m.length>0?Math.min(i,a,m[1]):Math.min(i,a),b=m.length>0?Math.max(i,a,m[1]):Math.max(i,a),S=new nt;return S.x=p,S.y=y,S.w=g-p,S.h=b-y,S}static calculateExtrema(e,t,i,s,a,r,n){if(n<=0||1<=n)return[];const o=e+(i-e)*n,h=t+(s-t)*n;return[o+(i+(a-i)*n-o)*n,h+(s+(r-s)*n-h)*n]}static computeBezierControlPoints(e,t,i,s,a,r,n,o){if(t===s&&i===a)return[];if(s<t){let e=t;t=s,s=e,e=i,i=a,a=e}n*=e,o*=e;let h=a-i,l=s-t,c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;let d=(s+t)/2,u=(a+i)/2;return[t,i,d+n*h,u+n*l,d+(n-o)*h,u+(n-o)*l,s,a]}static paintTie(e,t,i,s,a,r,n=!1,o=22,h=4){const l=nn.computeBezierControlPoints(t,i,s,a,r,n,o,h);e.beginPath(),e.moveTo(l[0],l[1]),e.quadraticCurveTo(l[2],l[3],l[6],l[7]),e.quadraticCurveTo(l[4],l[5],l[0],l[1]),e.closePath(),e.fill()}static drawBendSlur(e,t,i,s,a,r,n,o){let h=a-i,l=s-t,c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;let d=(s+t)/2,u=(a+i)/2,p=nn.BendSlurHeight*n;s-t<20&&(p/=2);let g=d+p*h,f=u+p*l;if(e.beginPath(),e.moveTo(t,i),e.lineTo(g,f),e.lineTo(s,a),e.stroke(),o){let t=e.measureText(o),i=r?0:-e.font.size;e.fillText(o,g-t/2,f+i)}}}nn.BendSlurHeight=11;class on extends zs{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=on.Size*this.scale}paint(e,t,i){this._isOpen?nn.paintTie(i,this.scale,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):nn.paintTie(i,this.scale,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3)}}on.Size=6;class hn{constructor(e,t){this.line=0,this.line=e,this.isGhost=t}}class ln extends zs{constructor(e){super(0,0),this._infos=[],this._glyphs=[],this.isEmpty=!0,this._isOpen=e}addParenthesis(e){let t=this.renderer,i=t.getNoteLine(e),s=e.isGhost||this.isTiedBend(e)&&t.settings.notation.isNotationElementVisible(v.ParenthesisOnTiedBends);this.addParenthesisOnLine(i,s)}addParenthesisOnLine(e,t){let i=new hn(e,t);this._infos.push(i),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,i=e.getScoreHeight(1);for(let s=0,a=this._infos.length;s<a;s++){let a;if(this._infos[s].isGhost)if(t){let a=e.getScoreY(this._infos[s].line)+i;t.height=a-t.y}else a=new on(this._isOpen),a.renderer=this.renderer,a.y=e.getScoreY(this._infos[s].line)-i,a.height=2*i,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,i){super.paint(e,t,i);for(let s of this._glyphs)s.paint(e+this.x,t+this.y,i)}}class cn{constructor(e,t){this.line=0,this.glyph=e,this.line=t}}class dn extends zs{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new Ei,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){let i=new cn(e,t);this._infos.push(i),(!this.minNote||this.minNote.line>i.line)&&(this.minNote=i),(!this.maxNote||this.maxNote.line<i.line)&&(this.maxNote=i)}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,i=0,s=!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(i-this._infos[n].line)<=1?t?t=!1:(h=!0,o.x=e,s=!0,t=!0):t=!1,a===Ce.Down?o.x=h?0:e:o.x=h?e:0,o.x+=this.noteStartX,i=this._infos[n].line,r=Math.max(r,o.x+o.width)}s?(this._noteHeadPadding=0,this.upLineX=e,this.downLineX=e):(this._noteHeadPadding=a===Ce.Down?-e:0,r+=this._noteHeadPadding,this.upLineX=r,this.downLineX=0),this.displacedX=e,this.width=r}paint(e,t,i){e+=this.x,t+=this.y;let s=this.renderer,a=3*this.scale,r=this.width-this.noteStartX+2*a;if(this.hasTopOverflow){let n=i.color;i.color=s.resources.staffLineColor;let o=-2;for(;o>=this.minNote.line;){let n=t+s.getScoreY(o);i.fillRect(e-a+this.noteStartX,n,r,this.scale),o-=2}i.color=n}if(this.hasBottomOverflow){let n=i.color;i.color=s.resources.staffLineColor;let o=10;for(;o<=this.maxNote.line;){let n=t+s.getScoreY(o);i.fillRect(e-a+this.noteStartX,n,r,this.scale),o+=2}i.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,i)}}class un extends Xs{constructor(e,t,i){super(e,t,1,un.getSymbol(i))}doLayout(){this.width=12*this.scale}static getSymbol(e){switch(e){case p.ThirtySecond:return P.Tremolo3;case p.Sixteenth:return P.Tremolo2;case p.Eighth:return P.Tremolo1;default:return P.None}}}class pn extends dn{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 i=this._noteGlyphLookup.get(e.id),s=this.x+i.x+this._noteHeadPadding;switch(t){case $e.Left:break;case $e.Center:s+=i.width/2;break;case $e.Right:s+=i.width}return s}return 0}getNoteY(e,t){if(this._noteGlyphLookup.has(e.id)){const i=this._noteGlyphLookup.get(e.id);let s=this.y+i.y;switch(t){case Qe.TopWithStem:s-=this.renderer.getStemSize(this.beamingHelper);break;case Qe.Top:s-=i.height/2;break;case Qe.Center:break;case Qe.Bottom:s+=i.height/2;break;case Qe.BottomWithStem:s+=this.renderer.getStemSize(this.beamingHelper)}return s}return 0}addNoteGlyph(e,t,i){super.add(e,i),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,i=e===Ce.Up?this.minNote:this.maxNote,s=e===Ce.Up?this.displacedX:0,a=this.beat.tremoloSpeed;switch(a){case p.ThirtySecond:t=e===Ce.Up?-15:15;break;case p.Sixteenth:t=e===Ce.Up?-12:15;break;case p.Eighth:t=e===Ce.Up?-10:10;break;default:t=e===Ce.Up?-10:15}this._tremoloPicking=new un(s,i.glyph.y+t*this.scale,a),this._tremoloPicking.renderer=this.renderer,this._tremoloPicking.doLayout()}}buildBoundingsLookup(e,t,i){for(let s of this._notes)if(this._noteGlyphLookup.has(s.id)){let a=this._noteGlyphLookup.get(s.id),r=new vs;r.note=s,r.noteHeadBounds=new nt,r.noteHeadBounds.x=t+this.x+this._noteHeadPadding+a.x,r.noteHeadBounds.y=i+this.y+a.y-a.height/2,r.noteHeadBounds.w=a.width,r.noteHeadBounds.h=a.height,e.addNote(r)}}paint(e,t,i){let s=this.renderer,a=0,r=0,n=1,o=-n;this.beamingHelper.direction===Ce.Up?(r=s.getScoreY(this.minNote.line),a=s.getScoreY(this.maxNote.line-2)):(r=s.getScoreY(this.maxNote.line-1),a=s.getScoreY(this.minNote.line+1),o*=-1,n*=-1);for(const s of this.aboveBeatEffects.values())a+=o*s.height,s.paint(e+this.x+2*this.scale,t+this.y+a,i);for(const s of this.belowBeatEffects.values())r+=n*s.height,s.paint(e+this.x+2*this.scale,t+this.y+r,i);super.paint(e,t,i),this._tremoloPicking&&this._tremoloPicking.paint(e,t,i)}}class gn extends Xs{constructor(e,t,i){super(e,t,1,gn.getSymbol(i)),this._duration=i}static getSymbol(e){switch(e){case p.QuadrupleWhole:return P.RestLonga;case p.DoubleWhole:return P.RestDoubleWhole;case p.Whole:return P.RestWhole;case p.Half:return P.RestHalf;case p.Quarter:return P.RestQuarter;case p.Eighth:return P.RestEighth;case p.Sixteenth:return P.RestSixteenth;case p.ThirtySecond:return P.RestThirtySecond;case p.SixtyFourth:return P.RestSixtyFourth;case p.OneHundredTwentyEighth:return P.RestOneHundredTwentyEighth;case p.TwoHundredFiftySixth:return P.RestTwoHundredFiftySixth;default:return P.None}}static getSize(e){switch(e){case p.QuadrupleWhole:case p.DoubleWhole:case p.Whole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:return 9;case p.ThirtySecond:return 12;case p.SixtyFourth:return 14;case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:return 20}return 10}doLayout(){this.width=gn.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 fn{constructor(){this.x=0,this.y=-3e3,this.width=0}}class mn extends wa{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 fn);let t=21*this.scale;for(let i=0,s=this.glyphs.length;i<s;i++){let s=this.glyphs[i];s.renderer=this.renderer,s.doLayout();let a=0;for(;e[a].y>s.y;)a++,a===e.length&&e.push(new fn);s.x=a,e[a].y=s.y+t,e[a].width<s.width&&(e[a].width=s.width)}this.width=0;for(const t of e)this.width+=t.width,t.x=this.width;for(let t=0,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];const s=e[i.x];i.x=this.width-s.x}}}class yn extends dn{get direction(){return Ce.Up}constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new mn,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new ln(!0),this._postNoteParenthesis=new ln(!1))}containsNoteValue(e){return this._noteValueLookup.has(e)}getNoteValueY(e){return this._noteValueLookup.has(e)?this.y+this._noteValueLookup.get(e).y:0}addGlyph(e,t=!1){let i=this.renderer,s=new Ys(0,0,p.Quarter,!0),a=i.accidentalHelper.applyAccidentalForValue(this._beat,e,t,!0),r=i.accidentalHelper.getNoteLineForValue(e,!1);if(s.y=i.getScoreY(r),this._showParenthesis&&(this._preNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.addParenthesisOnLine(r,!0),this._postNoteParenthesis.addParenthesisOnLine(r,!0)),a!==Je.None){let e=new Jr(0,s.y,a,!0);e.renderer=this.renderer,this._accidentals.renderer=this.renderer,this._accidentals.addGlyph(e)}this._noteValueLookup.set(e,s),this.add(s,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+yn.ElementPadding*this.scale),this._accidentals.isEmpty||(e+=this._accidentals.width+yn.ElementPadding*this.scale,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+yn.ElementPadding*this.scale),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+yn.ElementPadding*this.scale,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+yn.ElementPadding*this.scale)}paint(e,t,i){this._accidentals.isEmpty||this._accidentals.paint(e+this.x,t+this.y,i),this._showParenthesis&&(this._preNoteParenthesis.paint(e+this.x,t+this.y,i),this._postNoteParenthesis.paint(e+this.x,t+this.y,i)),super.paint(e,t,i)}}yn.ElementPadding=2;class bn extends zs{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,i,s,a,r,n,o){nn.drawBendSlur(e,t,i,s,a,r,n,o)}doLayout(){super.doLayout(),this.width=0;for(let e of this.BendNoteHeads)e.doLayout(),this.width+=e.width+10*this.scale}getTieDirection(e,t){return t.getBeatDirection(e)===Ce.Up?Ce.Down:Ce.Up}}bn.EndPadding=8;class Sn extends U{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class wn extends zs{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 i=0;switch(e.bendType){case c.Bend:i=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||i<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=i):(-1===this._bendEndMinValue||i<this._bendEndMinValue)&&(this._bendEndMinValue=i);break;case c.Release:i=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||i<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=i):i>0&&(-1===this._releaseMinValue||i<this._releaseMinValue)&&(this._releaseMinValue=i);break;case c.BendRelease:i=t[1].value,(-1===this._bendMiddleMinValue||i<this._bendMiddleMinValue)&&(this._bendMiddleMinValue=i),i=t[2].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||i<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=i):i>0&&(-1===this._releaseMinValue||i<this._releaseMinValue)&&(this._releaseMinValue=i);break;case c.Prebend:i=t[0].value,(-1===this._preBendMinValue||i<this._preBendMinValue)&&(this._preBendMinValue=i);break;case c.PrebendBend:i=t[0].value,(-1===this._preBendMinValue||i<this._preBendMinValue)&&(this._preBendMinValue=i),i=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||i<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=i):(-1===this._bendEndMinValue||i<this._bendEndMinValue)&&(this._bendEndMinValue=i);break;case c.PrebendRelease:i=t[0].value,(-1===this._preBendMinValue||i<this._preBendMinValue)&&(this._preBendMinValue=i),i=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||i<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=i):i>0&&(-1===this._releaseMinValue||i<this._releaseMinValue)&&(this._releaseMinValue=i)}}doLayout(){super.doLayout();let e=this._maxBendValue*wn.BendValueHeight*this.scale;this.renderer.registerOverflowTop(e);let t=0;for(let e of this._notes){let i=this._renderPoints.get(e.id);switch(e.bendType){case c.Bend:i[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case c.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[1].lineValue=t);break;case c.BendRelease:i[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[2].lineValue=t);break;case c.Prebend:i[0].lineValue=this._preBendMinValue;break;case c.PrebendBend:i[0].lineValue=this._preBendMinValue,i[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case c.PrebendRelease:i[0].lineValue=this._preBendMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[1].lineValue=t)}}this.width=0,this._notes.sort(((e,t)=>e.isStringed?e.string-t.string:e.realValue-t.realValue))}createRenderingPoints(e){let t=[];switch(e.bendType){case c.Custom:for(let i of e.bendPoints)t.push(new Sn(i.offset,i.value));break;case c.BendRelease:t.push(new Sn(0,e.bendPoints[0].value)),t.push(new Sn(U.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new Sn(U.MaxPosition,e.bendPoints[3].value));break;case c.Bend:case c.Hold:case c.Prebend:case c.PrebendBend:case c.PrebendRelease:case c.Release:t.push(new Sn(0,e.bendPoints[0].value)),t.push(new Sn(U.MaxPosition,e.bendPoints[1].value))}return t}paint(e,t,i){let s=i.color;this._notes.length>1&&(i.color=this.renderer.resources.secondaryGlyphColor);for(let a of this._notes){let r=this._renderPoints.get(a.id),n=this.renderer,o=a,h=!1,d=null,u=!1,p=a.bendStyle===l.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,h=!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,qe.MiddleNotes):f+=n.getNoteX(a,$e.Right),m=!g||g.isLastOfVoice&&!u?e+d.x+d.postBeatGlyphsStart:u||!g.nextBeat?e+d.x+d.getBeatX(g,qe.MiddleNotes):a.bendType===c.Hold?e+d.x+d.getBeatX(g.nextBeat,qe.OnNotes):e+d.x+d.getBeatX(g.nextBeat,qe.PreNotes),h||(m-=wn.ArrowSize*this.scale);let b=(m-f)/U.MaxPosition;i.beginPath();for(let e=0,t=r.length-1;e<t;e++){let t=r[e],s=r[e+1];0!==e||0===t.value||a.isTieDestination||this.paintBend(a,new Sn(0,0),t,f,y,b,p,i),a.bendType!==c.Prebend?(0===e&&(f+=2*this.scale),this.paintBend(a,t,s,f,y,b,p,i)):a.isTieOrigin&&a.tieDestination.hasBend&&(s=new Sn(U.MaxPosition,t.value),s.lineValue=t.lineValue,this.paintBend(a,t,s,f,y,b,p,i))}i.color=s}}paintBend(e,t,i,s,a,r,n,o){let h=this.renderer,l=this.renderer.resources,c=h.lineOffset/2,d=s+r*t.offset,u=wn.BendValueHeight*this.scale,p=a-u*t.lineValue;0===t.value?i.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,Qe.Top):p+=h.getNoteY(e,Qe.Center):p+=c;let g=s+r*i.offset,f=a-u*i.lineValue;0===i.lineValue?f+=h.getNoteY(e,Qe.Center):f+=c;let m=0,y=wn.ArrowSize*this.scale;if(i.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):i.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===i.value){if(t.lineValue>0){let e=g,t=wn.DashSize*this.scale,i=d+t;if((e-d)/(2*t)<1)o.moveTo(e,p),o.lineTo(d,p);else for(;e>i;)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<i.offset){o.font=l.graceFont;let e=o.measureText(n),t=0,i=0;if(p>f){let s=Math.abs(p-f);t=s>1.3*o.font.size?p-s/2:p,i=(d+g-e)/2}else t=p,i=g-e;o.fillText(n,i,t)}if(0!==i.value&&t.value!==i.value){let e=i.value,s=i.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+=wn.getFractionSign(e)),""!==r){f=a-u*i.value;let e=f;s||(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"}}}wn.ArrowSize=6,wn.DashSize=3,wn.BendValueHeight=6;class _n extends zs{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===F.Custom)return e.whammyBarPoints;let t=[];switch(e.whammyBarType){case F.Dive:case F.Hold:case F.PrediveDive:case F.Predive:t.push(new U(0,e.whammyBarPoints[0].value)),t.push(new U(U.MaxPosition,e.whammyBarPoints[1].value));break;case F.Dip:t.push(new U(0,e.whammyBarPoints[0].value)),t.push(new U(U.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new U(U.MaxPosition,e.whammyBarPoints[e.whammyBarPoints.length-1].value))}return t}doLayout(){super.doLayout(),this._isSimpleDip=this.renderer.settings.notation.notationMode===e.NotationMode.SongBook&&this._beat.whammyBarType===F.Dip;let t=null,i=null,s=this._beat;for(;s&&s.hasWhammyBar;)(!t||t.value>s.minWhammyPoint.value)&&(t=s.minWhammyPoint),(!i||i.value<s.maxWhammyPoint.value)&&(i=s.maxWhammyPoint),s=s.nextBeat;let a=i.value>0?Math.abs(this.getOffset(i.value)):0;(a>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(v.ZerosOnDiveWhammys))&&(a+=2*this.renderer.resources.tablatureFont.size);let r=t.value<0?Math.abs(this.getOffset(t.value)):0;this.renderer.registerOverflowTop(a+r),a>this.renderer.staff.getSharedLayoutData(_n.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(_n.TopOffsetSharedDataKey,a)}getOffset(e){if(0===e)return 0;let t=_n.PerHalfSize*this.scale+Math.log2(Math.abs(e)/2)*_n.PerHalfSize*this.scale;return e<0&&(t=-t),t}paint(t,i,s){let a=this.renderer,r=this._beat.nextBeat,n=null,o=qe.PreNotes;r&&(n=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.voice.bar),n&&n.staff===a.staff&&(n===a||r.hasWhammyBar)?o=!r.hasWhammyBar||a.settings.notation.notationMode===e.NotationMode.SongBook&&r.whammyBarType===F.Dip?qe.PreNotes:qe.MiddleNotes:(r=null,n=null));let h=0,c=0;this._isSimpleDip?(h=t+a.x+a.getBeatX(this._beat,qe.OnNotes)-2*this.scale,c=t+a.x+a.getBeatX(this._beat,qe.PostNotes)+2*this.scale):(h=t+a.x+a.getBeatX(this._beat,qe.MiddleNotes),c=n?t+n.x+n.getBeatX(r,o):t+a.x+a.width-2*this.scale);let d=s.textAlign;if(s.textAlign=E.Center,this._renderPoints.length>=2){let e=(c-h)/U.MaxPosition;s.beginPath();let t=i+this.renderer.staff.getSharedLayoutData(_n.TopOffsetSharedDataKey,0),a=this._beat.whammyStyle===l.Gradual?"grad.":"";for(let i=0,r=this._renderPoints.length-1;i<r;i++){let n=this._renderPoints[i],o=this._renderPoints[i+1],l=i<r-2?this._renderPoints[i+2]:null,c=0===i;0!==i||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new U(0,0),n,o,h,t,e,s),c=!1),this.paintWhammy(c,n,o,l,h,t,e,s,a),a=""}s.stroke()}s.textAlign=d}paintWhammy(e,t,i,s,a,r,n,o,h){let l=a+n*t.offset,c=a+n*i.offset,d=r-this.getOffset(t.value),u=r-this.getOffset(i.value);if(t.offset===i.offset){let e=_n.DashSize*this.scale;if(Math.abs(u-d)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(d,u),i=Math.min(d,u);for(;t>i;)o.moveTo(l,i),o.lineTo(l,i+e),i+=2*e}o.stroke()}else if(t.value===i.value){let e=_n.DashSize*this.scale;if(Math.abs(c-l)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(l,c),i=Math.min(l,c);for(;t>i;)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(v.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2*this.scale,o.fillText(h,l,e))}let g=Math.abs(i.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(v.ZerosOnDiveWhammys)&&!this._isSimpleDip)&&t.value!==i.value){let e="";if(i.value<0&&(e+="-"),g>=4){let t=g/4|0;e+=t,g-=4*t}else 0===g&&(e+="0");g>0&&(e+=wn.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(d,u)-p.tablatureFont.size-2*this.scale:(a=t.offset===i.offset?Math.min(d,u):u,a-=p.tablatureFont.size+2*this.scale,s&&s.value>i.value&&(a-=2*this.scale));let r=c;o.fillText(e,r,a)}}}_n.TopOffsetSharedDataKey="tab.whammy.topoffset",_n.PerHalfSize=6,_n.DashSize=3;class Bn extends bn{constructor(e){super(0,0),this._beat=e}doLayout(){let t=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case F.None:case F.Custom:case F.Hold:return;case F.Dive:case F.PrediveDive:{let e=new yn(this._beat,!1);e.renderer=this.renderer;let t=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let i of this._beat.notes)i.isTieOrigin||e.addGlyph(this.getBendNoteValue(i,t),t.value%2!=0);e.doLayout(),this.BendNoteHeads.push(e)}break;case F.Dip:if(t===e.NotationMode.SongBook){let e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+Bn.SimpleDipHeight*this.scale+Bn.SimpleDipPadding*this.scale}else{let t=new yn(this._beat,!1);if(t.renderer=this.renderer,this.renderer.settings.notation.notationMode===e.NotationMode.GuitarPro){let e=this._beat.whammyBarPoints[1];for(let i of this._beat.notes)t.addGlyph(this.getBendNoteValue(i,this._beat.whammyBarPoints[1]),e.value%2!=0)}t.doLayout(),this.BendNoteHeads.push(t);let i=new yn(this._beat,!1);if(i.renderer=this.renderer,this.renderer.settings.notation.notationMode===e.NotationMode.GuitarPro){let e=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let t of this._beat.notes)i.addGlyph(this.getBendNoteValue(t,e),e.value%2!=0)}i.doLayout(),this.BendNoteHeads.push(i)}case F.Predive:}super.doLayout()}paint(t,i,s){let a=this._beat;switch(a.whammyBarType){case F.None:case F.Custom:return}let r=this.renderer.settings.notation.notationMode,n=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,a.voice.bar),o=t+n.x+n.getBeatX(a,qe.MiddleNotes),h=this.getTieDirection(a,n),c=1===this._beat.notes.length?h:Ce.Up,d=s.textAlign;for(let d=0;d<a.notes.length;d++){let u=a.notes[d],p=i+n.y;d>0&&d>=(this._beat.notes.length/2|0)&&(c=Ce.Down),c===Ce.Down?p+=n.getNoteY(u,Qe.Bottom):p+=n.getNoteY(u,Qe.Top);let g=t+n.x;a.isLastOfVoice?g+=n.width:g+=n.getBeatX(a,qe.EndBeat),g-=8*this.scale;let f=a.whammyStyle===l.Gradual&&0===d?"grad.":"",m=null;u.isTieOrigin&&(m=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,u.tieDestination.beat.voice.bar),m&&m.staff===n.staff?g=t+m.x+m.getBeatX(u.tieDestination.beat,qe.MiddleNotes):m=null);let y=Ys.NoteHeadHeight*this.scale*Ys.GraceScale*.5;c===Ce.Up&&(y=-y);let b=a.whammyBarPoints.length>0?this.getBendNoteValue(u,a.whammyBarPoints[a.whammyBarPoints.length-1]):0,S=0,w=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(b)?(S=this.BendNoteHeads[0].getNoteValueY(b)+y,w=!0):m&&(u.isTieOrigin&&u.tieDestination.beat.hasWhammyBar||u.beat.isContinuedWhammy)?(S=i+m.y+m.getNoteY(u.tieDestination,Qe.Top),w=!0,c===Ce.Down&&(S+=Ys.NoteHeadHeight*this.scale)):u.isTieOrigin&&(S=m?i+m.y+m.getNoteY(u.tieDestination,Qe.Top):p,c===Ce.Down&&(S+=Ys.NoteHeadHeight*this.scale)),a.whammyBarType){case F.Hold:u.isTieOrigin&&nn.paintTie(s,this.scale,o,p,g,S,h===Ce.Down,22,4);break;case F.Dive:0===d&&(this.BendNoteHeads[0].x=g-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=i+n.y,this.BendNoteHeads[0].paint(0,0,s),this.BendNoteHeads[0].containsNoteValue(b)&&(S+=this.BendNoteHeads[0].y)),w?this.drawBendSlur(s,o,p,g,S,c===Ce.Down,this.scale,f):u.isTieOrigin&&nn.paintTie(s,this.scale,o,p,g,S,h===Ce.Down,22,4);break;case F.Dip:if(r===e.NotationMode.SongBook){if(0===d){let e=t+n.x+n.getBeatX(this._beat,qe.OnNotes)-2*this.scale,a=t+n.x+n.getBeatX(this._beat,qe.PostNotes)+2*this.scale,r=(e+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,r,i+this.y);let h=i+this.y+s.font.size+2*this.scale,l=h+Bn.SimpleDipHeight*this.scale;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(s.moveTo(e,l),s.lineTo(r,h),s.lineTo(a,l)):(s.moveTo(e,h),s.lineTo(r,l),s.lineTo(a,h)),s.stroke()}u.isTieOrigin&&nn.paintTie(s,this.scale,o,p,g,S,h===Ce.Down,22,4)}else{let e=(o+g)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=i+n.y,this.BendNoteHeads[0].paint(0,0,s);let t=this.getBendNoteValue(u,a.whammyBarPoints[1]),r=this.BendNoteHeads[0].getNoteValueY(t)+y;this.drawBendSlur(s,o,p,e,r,c===Ce.Down,this.scale,f),this.BendNoteHeads[1].x=g-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=i+n.y,this.BendNoteHeads[1].paint(0,0,s),S=this.BendNoteHeads[1].getNoteValueY(b)+y,this.drawBendSlur(s,e,r,g,S,c===Ce.Down,this.scale,f)}break;case F.PrediveDive:case F.Predive:let l=t+n.x+n.getBeatX(u.beat,qe.PreNotes);l+=n.getPreNotesGlyphForBeat(u.beat).prebendNoteHeadOffset;let m=i+n.y+n.getScoreY(n.accidentalHelper.getNoteLineForValue(u.displayValue-(u.beat.whammyBarPoints[0].value/2|0),!1))+y;this.drawBendSlur(s,l,m,o,p,c===Ce.Down,this.scale,f),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=g-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=i+n.y,this.BendNoteHeads[0].paint(0,0,s),this.drawBendSlur(s,o,p,g,S,c===Ce.Down,this.scale,f))}}s.textAlign=d}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}Bn.SimpleDipHeight=2*_n.PerHalfSize,Bn.SimpleDipPadding=2;class Tn extends zs{constructor(e,t,i){super(e,t),this.width=i}}class kn extends Xs{constructor(e,t,i,s,a){super(e,t,a?Ys.GraceScale:1,i.getSymbol(s)),this._isGrace=a,this._articulation=i}paint(e,t,i){let s=this._isGrace?this.scale:0;i.fillMusicFontSymbol(e+this.x,t+this.y+s,this.glyphScale*this.scale,this.symbol,!1),this._articulation.techniqueSymbol!==P.None&&this._articulation.techniqueSymbolPlacement===C.Middle&&i.fillMusicFontSymbol(e+this.x,t+this.y+s,this.glyphScale*this.scale,this._articulation.techniqueSymbol,!1)}doLayout(){let e=(this._isGrace?Ys.GraceScale:1)*this.scale;switch(this.symbol){case P.NoteheadWhole:this.width=14;break;case P.NoteheadCircleX:case P.NoteheadDiamondWhite:this.width=9;break;case P.NoteheadHeavyXHat:case P.NoteheadHeavyX:this.width=13;break;default:this.width=10}this.width=this.width*(this._isGrace?Ys.GraceScale:1)*this.scale,this.height=Ys.NoteHeadHeight*e}}class vn extends Xs{constructor(e,t){super(e,t,Ys.GraceScale,P.ArticStaccatoAbove)}doLayout(){this.width=Ys.QuarterNoteHeadWidth*this.scale,this.height=7*this.scale}paint(e,t,i){super.paint(e+3*this.scale,t+5*this.scale,i)}}class xn extends Xs{constructor(e,t){super(e,t,.5,P.PictEdgeOfCymbal)}doLayout(){this.width=22*this.scale,this.height=15*this.scale}paint(e,t,i){super.paint(e-3*this.scale,t+this.height,i)}}class Nn extends Xs{constructor(e,t){super(e,t,Ys.GraceScale,P.GuitarGolpe)}doLayout(){this.width=9*this.scale,this.height=10*this.scale}paint(e,t,i){super.paint(e,t+this.height,i)}}class Pn extends Za{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,i){this.noteHeads&&this.noteHeads.buildBoundingsLookup(e,t+this.x,i+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,i){this._skipPaint||super.paint(e,t,i)}doLayout(){let e=this.renderer;if(!this.container.beat.isEmpty)if(this.container.beat.isRest){let t=2*Math.ceil((this.renderer.bar.staff.standardNotationLineCount-1)/2);this.container.beat.duration===p.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const i=new gn(0,e.getScoreY(t),this.container.beat.duration);if(this.restGlyph=i,i.beat=this.container.beat,i.beamingHelper=this.beamingHelper,this.addGlyph(i),this.renderer.bar.isMultiVoice)if(0===this.container.beat.voice.index){const t=Na.computeLineHeightsForRest(this.container.beat.duration);let s=i.y-e.getScoreHeight(t[0]),a=i.y+e.getScoreHeight(t[1]);this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,s,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 Tn(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++){let e=new wa(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addGlyph(e)}}}else{const t=new pn;this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper;let i=new ln(!1);i.renderer=this.renderer;for(let e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),i.addParenthesis(e));if(this.addGlyph(t),i.isEmpty||(this.addGlyph(new Tn(0,0,4*(this.container.beat.graceType!==f.None?Ys.GraceScale:1)*this.scale)),this.addGlyph(i)),this.container.beat.hasWhammyBar){let e=new Bn(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addGlyph(new Tn(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++){let t=new wa(0,0);t.renderer=this.renderer;for(let i of this.container.beat.notes)this.createBeatDot(e.getNoteLine(i),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 i=this.renderer;t.addGlyph(new sn(0,i.getScoreY(e),1.5*this.scale))}createNoteHeadGlyph(e){let t=this.container.beat.graceType!==f.None;if(e.beat.voice.bar.staff.isPercussion){const i=K.getArticulation(e);if(i)return new kn(0,0,i,e.beat.duration,t);J.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new an(0,0,t):e.beat.graceType===f.BendGrace?new Ys(0,0,p.Quarter,!0):e.harmonicType===y.Natural?new rn(0,0,e.beat.duration,t):new Ys(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===f.BendGrace&&!e.hasBend)return;let t=this.renderer,i=this.createNoteHeadGlyph(e),s=t.getNoteLine(e);if(i.y=t.getScoreY(s),this.noteHeads.addNoteGlyph(i,e,s),e.harmonicType!==y.None&&e.harmonicType!==y.Natural){let a=e.displayValue+e.harmonicPitch;i=new rn(0,0,e.beat.duration,this.container.beat.graceType!==f.None),s=t.accidentalHelper.getNoteLineForValue(a,!1),i.y=t.getScoreY(s),this.noteHeads.addNoteGlyph(i,e,s)}if(e.isStaccato&&!this.noteHeads.aboveBeatEffects.has("Staccato")&&this.noteHeads.belowBeatEffects.set("Staccato",new vn(0,0)),e.accentuated!==a.Normal||this.noteHeads.aboveBeatEffects.has("Accent")||this.noteHeads.belowBeatEffects.set("Accent",new tn(0,0,a.Normal)),e.accentuated!==a.Heavy||this.noteHeads.aboveBeatEffects.has("HAccent")||this.noteHeads.belowBeatEffects.set("HAccent",new tn(0,0,a.Heavy)),e.isPercussion){const t=K.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==C.Middle){const e=t.techniqueSymbolPlacement===C.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case P.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new xn(0,0));break;case P.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new vn(0,0));break;case P.StringsUpBow:e.set("StringsUpBow",new Pr(0,0,N.Up));break;case P.StringsDownBow:e.set("StringsDownBow",new Pr(0,0,N.Down));break;case P.GuitarGolpe:e.set("GuitarGolpe",new Nn(0,0))}}}}}class En extends zs{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=this._beat.brushType===d.ArpeggioUp||this._beat.brushType===d.ArpeggioDown?10*this.scale:0}paint(e,t,i){if(this._beat.brushType===d.ArpeggioUp||this._beat.brushType===d.ArpeggioDown){let s=this.renderer,a=s.lineOffset,r=t+this.y+(s.getNoteY(this._beat.maxNote,Qe.Bottom)-a),n=t+this.y+s.getNoteY(this._beat.minNote,Qe.Top)+a,o=e+this.x+this.width/2,h=8*this.scale,l=new Lr(0,0,_.Slight,1.2,!0);l.renderer=this.renderer,l.doLayout();let c=-l.height/2;if(this._beat.brushType===d.ArpeggioUp){let t=r+h,s=n-h;l.width=Math.abs(s-t),i.beginRotate(e+this.x+5*this.scale,s,-90),l.paint(0,c,i),i.endRotate(),i.beginPath(),i.moveTo(o,n),i.lineTo(o+h/2,n-h),i.lineTo(o-h/2,n-h),i.closePath(),i.fill()}else if(this._beat.brushType===d.ArpeggioDown){let t=r+h,s=n;l.width=Math.abs(s-t),i.beginRotate(e+this.x+5*this.scale,t,90),l.paint(0,c,i),i.endRotate(),i.beginPath(),i.moveTo(o,r),i.lineTo(o+h/2,r+h),i.lineTo(o-h/2,r+h),i.closePath(),i.fill()}}}}class Cn extends Ka{get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}doLayout(){if(!this.container.beat.isRest){let e=new mn;e.renderer=this.renderer;let t=new ln(!0);t.renderer=this.renderer;const i=new yn(this.container.beat,!0);this._prebends=i,i.renderer=this.renderer;for(let s of this.container.beat.notes)if(s.isVisible){if(s.hasBend)switch(s.bendType){case c.PrebendBend:case c.Prebend:case c.PrebendRelease:i.addGlyph(s.displayValue-(s.bendPoints[0].value/2|0),!1)}else if(s.beat.hasWhammyBar)switch(s.beat.whammyBarType){case F.PrediveDive:case F.Predive:this._prebends.addGlyph(s.displayValue-(s.beat.whammyBarPoints[0].value/2|0),!1)}this.createAccidentalGlyph(s,e),t.addParenthesis(s)}i.isEmpty||(this.addGlyph(i),this.addGlyph(new Tn(0,0,4*(this.container.beat.graceType!==f.None?Ys.GraceScale:1)*this.scale))),this.container.beat.brushType!==d.None&&(this.addGlyph(new En(this.container.beat)),this.addGlyph(new Tn(0,0,4*this.scale))),t.isEmpty||(this.addGlyph(t),this.addGlyph(new Tn(0,0,4*(this.container.beat.graceType!==f.None?Ys.GraceScale:1)*this.scale))),e.isEmpty||(this.accidentals=e,this.addGlyph(new Tn(0,0,2*(this.container.beat.graceType!==f.None?Ys.GraceScale:1)*this.scale)),this.addGlyph(e),this.addGlyph(new Tn(0,0,2*(this.container.beat.graceType!==f.None?Ys.GraceScale:1)*this.scale)))}super.doLayout()}createAccidentalGlyph(e,t){let i=this.renderer,s=i.accidentalHelper.applyAccidental(e),a=i.getNoteLine(e),r=this.container.beat.graceType!==f.None;if(s!==Je.None){let e=new Jr(0,i.getScoreY(a),s,r);e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==y.None&&e.harmonicType!==y.Natural){let n=e.displayValue+e.harmonicPitch;s=i.accidentalHelper.applyAccidentalForValue(e.beat,n,r,!1),a=i.accidentalHelper.getNoteLineForValue(n,!1);let o=new Jr(0,i.getScoreY(a),s,r);o.renderer=this.renderer,t.addGlyph(o)}}constructor(){super(),this._prebends=null,this.accidentals=null}}class Fn extends Xs{constructor(e,t,i,s){super(e,t,s,Fn.getSymbol(i)),this._digit=0,this._scale=0,this._digit=i,this._scale=s}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 P.TimeSig0;case 1:return P.TimeSig1;case 2:return P.TimeSig2;case 3:return P.TimeSig3;case 4:return P.TimeSig4;case 5:return P.TimeSig5;case 6:return P.TimeSig6;case 7:return P.TimeSig7;case 8:return P.TimeSig8;case 9:return P.TimeSig9;default:return P.None}}}class Ln extends wa{constructor(e,t,i,s=1){super(e,t),this._number=0,this._scale=0,this._number=i,this._scale=s}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,i=this.glyphs.length;t<i;t++){let i=this.glyphs[t];i.x=e,i.y=0,i.renderer=this.renderer,i.doLayout(),e+=i.width}this.width=e}}}Ln.numberHeight=18;class Mn extends wa{constructor(e,t,i,s,a){super(e,t),this._numerator=0,this._denominator=0,this._numerator=i,this._denominator=s,this._isCommon=a}doLayout(){if(this._isCommon&&2===this._numerator&&2===this._denominator){let e=new Xs(0,0,this.commonScale,P.TimeSigCutCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){let e=new Xs(0,0,this.commonScale,P.TimeSigCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else{const e=Ln.numberHeight*this.scale;let t=new Ln(0,-e/2,this._numerator,this.numberScale),i=new Ln(0,e/2,this._denominator,this.numberScale);this.addGlyph(t),this.addGlyph(i),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 In extends Mn{get commonScale(){return 1}get numberScale(){return 1}}class Dn extends bn{constructor(e){super(0,0),this._notes=[],this._endNoteGlyph=null,this._middleNoteGlyph=null,this._beat=e}addBends(e){if(this._notes.push(e),!e.isTieOrigin)switch(e.bendType){case c.Bend:case c.PrebendRelease:case c.PrebendBend:{let t=this._endNoteGlyph;t||(t=new yn(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let i=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0)}break;case c.Release:if(!e.isTieOrigin){let t=this._endNoteGlyph;t||(t=new yn(e.beat,!1),t.renderer=this.renderer,this._endNoteGlyph=t,this.BendNoteHeads.push(t));let i=e.bendPoints[e.bendPoints.length-1];t.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0)}break;case c.BendRelease:{let t=this._middleNoteGlyph;t||(t=new yn(e.beat,!1),this._middleNoteGlyph=t,t.renderer=this.renderer,this.BendNoteHeads.push(t));let i=e.bendPoints[1];t.addGlyph(this.getBendNoteValue(e,e.bendPoints[1]),i.value%2!=0);let s=this._endNoteGlyph;s||(s=new yn(e.beat,!1),s.renderer=this.renderer,this._endNoteGlyph=s,this.BendNoteHeads.push(s));let a=e.bendPoints[e.bendPoints.length-1];s.addGlyph(this.getBendNoteValue(e,a),a.value%2!=0)}}}paint(e,t,i){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._beat.voice.bar),a=e+s.x+s.getBeatX(this._beat,qe.MiddleNotes),r=e+s.x;this._beat.isLastOfVoice?r+=s.postBeatGlyphsStart:r+=s.getBeatX(this._beat.nextBeat,qe.PreNotes),r-=8*this.scale;let n=(a+r)/2;this._middleNoteGlyph&&(this._middleNoteGlyph.x=n-this._middleNoteGlyph.noteHeadOffset,this._middleNoteGlyph.y=t+s.y,this._middleNoteGlyph.paint(0,0,i)),this._endNoteGlyph&&(this._endNoteGlyph.x=r-this._endNoteGlyph.noteHeadOffset,this._endNoteGlyph.y=t+s.y,this._endNoteGlyph.paint(0,0,i)),this._notes.sort(((e,t)=>t.displayValue-e.displayValue));let o=this._beat.graceType===f.BendGrace?this._beat.nextBeat:this._beat,h=1===this._notes.length?this.getTieDirection(o,s):Ce.Up;for(let o=0;o<this._notes.length;o++){let d=this._notes[o];o>0&&o>=(this._notes.length/2|0)&&(h=Ce.Down);let u=t+s.y+s.getNoteY(d,Qe.Top),p=Ys.NoteHeadHeight*this.scale*Ys.GraceScale*.5;h===Ce.Down&&(u+=Ys.NoteHeadHeight*this.scale);let g=d.bendStyle===l.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===s.staff){let s=e+n.x+n.getBeatX(r.beat,qe.MiddleNotes),o=t+n.y+n.getNoteY(r,Qe.Top);h===Ce.Down&&(o+=Ys.NoteHeadHeight*this.scale),d.bendType===c.Hold||d.bendType===c.Prebend?nn.paintTie(i,this.scale,a,u,s,o,h===Ce.Down,22,4):this.drawBendSlur(i,a,u,s,o,h===Ce.Down,this.scale,g)}else{let r=e+s.x+s.width,n=d.tieDestination.realValue;s.accidentalHelper.applyAccidentalForValue(d.beat,n,!1,!0);let o=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(n,!1));d.bendType===c.Hold||d.bendType===c.Prebend?nn.paintTie(i,this.scale,a,u,r,o,h===Ce.Down,22,4):this.drawBendSlur(i,a,u,r,o,h===Ce.Down,this.scale,g)}switch(d.bendType){case c.Prebend:case c.PrebendBend:case c.PrebendRelease:let r=e+s.x+s.getBeatX(d.beat,qe.PreNotes);r+=s.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let n=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(d.displayValue-(d.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(i,r,n,a,u,h===Ce.Down,this.scale)}}else{h===Ce.Up&&(p=-p);let o=0,l=0;switch(d.bendType){case c.Bend:o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,l,h===Ce.Down,this.scale,g);break;case c.BendRelease:let f=this.getBendNoteValue(d,d.bendPoints[1]),m=this._middleNoteGlyph.getNoteValueY(f)+p;this.drawBendSlur(i,a,u,n,m,h===Ce.Down,this.scale,g),o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(i,n,m,r,l,h===Ce.Down,this.scale,g);break;case c.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,l,h===Ce.Down,this.scale,g));break;case c.Prebend:case c.PrebendBend:case c.PrebendRelease:let y=e+s.x+s.getBeatX(d.beat,qe.PreNotes);y+=s.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;let b=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(d.displayValue-(d.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(i,y,b,a,u,h===Ce.Down,this.scale),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,l,h===Ce.Down,this.scale,g))}}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class An extends nn{constructor(e,t,i=!1){super(e,t,i)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?Ce.Up:t.getBeatDirection(e)===Ce.Up?Ce.Down:Ce.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Ce.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,Qe.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,Qe.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===Ce.Up?e.getScoreY(9):e.getScoreY(0);const t=this.startNoteRenderer.getBeatDirection(this.startBeat),i=e.getBeatDirection(this.endBeat);return t!==i&&this.startBeat.graceType===f.None?i===this.tieDirection?this.tieDirection===Ce.Up?e.getNoteY(this.endBeat.maxNote,Qe.TopWithStem):e.getNoteY(this.endBeat.minNote,Qe.BottomWithStem):this.tieDirection===Ce.Up?e.getNoteY(this.endBeat.maxNote,Qe.BottomWithStem):e.getNoteY(this.endBeat.minNote,Qe.TopWithStem):this.tieDirection===Ce.Up?e.getNoteY(this.endBeat.maxNote,Qe.Top):e.getNoteY(this.endBeat.minNote,Qe.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,qe.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>p.Whole&&e===this.tieDirection?qe.Stem:qe.MiddleNotes)}}class Rn extends zs{constructor(e,t,i,s){super(0,0),this._outType=t,this._inType=e,this._startNote=i,this._parent=s}doLayout(){this.width=0}paint(e,t,i){this.paintSlideIn(e,t,i),this.drawSlideOut(e,t,i)}paintSlideIn(e,t,i){let s=this.renderer,a=12*this.scale,r=e+s.x+s.getNoteX(this._startNote,$e.Left)-2*this.scale,n=t+s.y+s.getNoteY(this._startNote,Qe.Center),o=r-a,h=t+s.y;switch(this._inType){case S.IntoFromBelow:h+=s.getNoteY(this._startNote,Qe.Bottom);break;case S.IntoFromAbove:h+=s.getNoteY(this._startNote,Qe.Top);break;default:return}let l=this.getAccidentalsWidth(s,this._startNote.beat);o-=l,r-=l,this.paintSlideLine(i,!1,o,r,h,n)}getAccidentalsWidth(e,t){let i=e.getPreNotesGlyphForBeat(t);return i&&i.accidentals?i.accidentals.width:0}drawSlideOut(e,t,i){let s=this.renderer,a=12*this.scale,r=1*this.scale,n=2*this.scale,o=0,h=0,l=0,c=0,d=!1;switch(this._outType){case w.Shift:case w.Legato:if(o=e+s.x+s.getBeatX(this._startNote.beat,qe.PostNotes),h=t+s.y+s.getNoteY(this._startNote,Qe.Center),this._startNote.slideTarget){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);i&&i.staff===s.staff?(l=e+i.x+i.getBeatX(this._startNote.slideTarget.beat,qe.PreNotes)-r,c=t+i.y+i.getNoteY(this._startNote.slideTarget,Qe.Center)):(l=e+s.x+s.width,c=h),this._startNote.slideTarget.realValue>this._startNote.realValue?(h+=n,c-=n):(h-=n,c+=n)}else l=e+s.x+this._parent.x,c=h;break;case w.OutUp:o=e+s.x+s.getNoteX(this._startNote,$e.Right),h=t+s.y+s.getNoteY(this._startNote,Qe.Center),l=o+a,c=t+s.y+s.getNoteY(this._startNote,Qe.Top);break;case w.OutDown:o=e+s.x+s.getNoteX(this._startNote,$e.Right),h=t+s.y+s.getNoteY(this._startNote,Qe.Center),l=o+a,c=t+s.y+s.getNoteY(this._startNote,Qe.Bottom);break;case w.PickSlideUp:o=e+s.x+s.getNoteX(this._startNote,$e.Right),h=t+s.y+s.getNoteY(this._startNote,Qe.Center),c=t+s.y+s.getNoteY(this._startNote,Qe.Top),l=e+s.x+s.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(l=e+s.x+s.getBeatX(this._startNote.beat.nextBeat,qe.PreNotes)),d=!0;break;case w.PickSlideDown:o=e+s.x+s.getNoteX(this._startNote,$e.Right),h=t+s.y+s.getNoteY(this._startNote,Qe.Center),c=t+s.y+s.getNoteY(this._startNote,Qe.Bottom),l=e+s.x+s.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(l=e+s.x+s.getBeatX(this._startNote.beat.nextBeat,qe.PreNotes)),d=!0;break;default:return}this.paintSlideLine(i,d,o,l,h,c)}paintSlideLine(e,t,i,s,a,r){if(t){let t=new Lr(0,0,_.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;let n=s-i,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(i,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(i,a),e.lineTo(s,r),e.stroke()}}class On extends An{constructor(e,t,i=!1){super(e.beat,t.beat,i),this._startNote=e,this._endNote=t}getTieHeight(e,t,i,s){return Math.log2(i-e+1)*this.renderer.settings.notation.slurHeight}getStartY(){return this.isStartCentered()?this.tieDirection===Ce.Up?this.startNoteRenderer.getNoteY(this._startNote,Qe.Top):this.startNoteRenderer.getNoteY(this._startNote,Qe.Bottom):this.startNoteRenderer.getNoteY(this._startNote,Qe.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===Ce.Up?this.endNoteRenderer.getNoteY(this._endNote,Qe.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,Qe.BottomWithStem):this.tieDirection===Ce.Up?this.endNoteRenderer.getNoteY(this._endNote,Qe.Top):this.endNoteRenderer.getNoteY(this._endNote,Qe.Bottom):this.endNoteRenderer.getNoteY(this._endNote,Qe.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===Ce.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===Ce.Down}isEndCentered(){return this._startNote.beat.graceType===f.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===Ce.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===Ce.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===f.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,qe.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,$e.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,qe.Stem):this.endNoteRenderer.getNoteX(this._endNote,$e.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,qe.PreNotes)}}class Gn extends nn{constructor(e,t,i=!1){super(e?e.beat:null,t?t.beat:null,i),this.startNote=e,this.endNote=t}shouldDrawBendSlur(){return this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&!!this.startNote.bendOrigin&&this.startNote.isTieOrigin}doLayout(){super.doLayout()}getBeamDirection(e,t){return t.getBeatDirection(e)===Ce.Up?Ce.Down:Ce.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===Ce.Up?this.startNoteRenderer.getNoteY(this.startNote,Qe.Top):this.startNoteRenderer.getNoteY(this.startNote,Qe.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===Ce.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===Ce.Up?e.getNoteY(this.endNote,Qe.Top):e.getNoteY(this.endNote,Qe.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,qe.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,qe.PreNotes)}}class Vn extends Js{constructor(e,t){super(e,t),this._bend=null,this._effectSlur=null,this._effectEndSlur=null}doLayout(){if(this._effectSlur=null,this._effectEndSlur=null,super.doLayout(),this.beat.isLegatoOrigin){if(!this.beat.previousBeat||!this.beat.previousBeat.isLegatoOrigin){let e=this.beat.nextBeat;for(;e.nextBeat&&e.nextBeat.isLegatoDestination;)e=e.nextBeat;this.addTie(new An(this.beat,e,!1))}}else if(this.beat.isLegatoDestination&&!this.beat.isLegatoOrigin){let e=this.beat.previousBeat;for(;e.previousBeat&&e.previousBeat.isLegatoOrigin;)e=e.previousBeat;this.addTie(new An(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!==f.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){let t=new Gn(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){let t=new Gn(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==S.None||e.slideOutType!==w.None){let t=new Rn(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){let t=new On(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){let t=new On(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new On(e,e.effectSlurDestination,!1);this._effectSlur=t,this.addTie(t)}if(!this._effectEndSlur&&e.beat.isEffectSlurDestination&&e.beat.effectSlurOrigin){let t=this.onNotes.beamingHelper.direction,i=t===Ce.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,s=t===Ce.Up?e.beat.minNote:e.beat.maxNote;const a=new On(i,s,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new Dn(e.beat);this._bend=t,t.renderer=this.renderer,this.addTie(t)}this._bend.addBends(e)}}}}class Hn extends qa{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._firstLineY=0,this._startSpacing=!1,this.accidentalHelper=new ka(this)}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}get lineOffset(){return(qa.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),i=this.simpleWhammyOverflow;this.registerOverflowTop(i);let s=this.getScoreY(this.accidentalHelper.maxLine),a=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);a.direction===Ce.Up&&(s-=this.getStemSize(a),s-=a.fingeringCount*this.resources.graceFont.size,a.hasTuplet&&(s-=2*this.resources.effectFont.size)),a.hasTuplet&&(s-=1.5*this.resources.effectFont.size),s<e&&this.registerOverflowTop(Math.abs(s)+i);let r=this.getScoreY(this.accidentalHelper.minLine),n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);n.direction===Ce.Down&&(r+=this.getStemSize(n),r+=n.fingeringCount*this.resources.graceFont.size),r>t&&this.registerOverflowBottom(Math.abs(r)-t)}}paint(e,t,i){super.paint(e,t,i),this.paintBeams(e,t,i),this.paintTuplets(e,t,i)}paintTuplets(e,t,i){for(let s of this.bar.voices)if(this.hasVoiceContainer(s)){let a=this.getVoiceContainer(s);for(let s of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,i,s)}}paintBeams(e,t,i){for(let s=0,a=this.helpers.beamHelpers.length;s<a;s++){let a=this.helpers.beamHelpers[s];for(let s=0,r=a.length;s<r;s++){let r=a[s];this.paintBeamHelper(e+this.beatGlyphsStart,t,i,r)}}}paintBeamHelper(e,t,i,s){i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.isRestBeamHelper||(1===s.beats.length?this.paintFlag(e,t,i,s):this.paintBar(e,t,i,s))}paintTupletHelper(e,t,i,s){let a,r=this.resources,n=i.textAlign,o=i.textBaseline;i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.textAlign=E.Center,i.textBaseline=C.Middle;let h=s.beats[0].tupletNumerator,l=s.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!==s.beats.length&&s.isFull){let n=s.beats[0],o=s.beats[s.beats.length-1],h=null,l=null;for(let e=0;e<s.beats.length;e++)if(!s.beats[e].isRest){h=s.beats[e];break}for(let e=s.beats.length-1;e>=0;e--)if(!s.beats[e].isRest){l=s.beats[e];break}let u=!1;h||(h=n,u=!0),l||(l=o);let p=this.helpers.beamHelperLookup[s.voice.index].get(n.index),g=this.helpers.beamHelperLookup[s.voice.index].get(o.index),f=p.getBeatLineX(n),m=g.getBeatLineX(o),y=this.helpers.beamHelperLookup[s.voice.index].get(h.index),b=this.helpers.beamHelperLookup[s.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),i.font=r.effectFont;let B=i.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===Ce.Down&&(c*=-1,d*=-1),i.beginPath(),i.moveTo(e+this.x+f,t+this.y+w-c|0),i.lineTo(e+this.x+f,t+this.y+w-c-d|0),i.lineTo(e+this.x+v,t+this.y+E-c-d|0),i.stroke(),i.beginPath(),i.moveTo(e+this.x+x,t+this.y+F-c-d|0),i.lineTo(e+this.x+m,t+this.y+_-c-d|0),i.lineTo(e+this.x+m,t+this.y+_-c|0),i.stroke(),i.fillText(a,e+this.x+k,t+this.y+C-c-d)}else for(let n=0,o=s.beats.length;n<o;n++){let o=s.beats[n],h=this.helpers.beamHelperLookup[s.voice.index].get(o.index);if(!h)continue;let l=h.direction,u=h.getBeatLineX(o),p=this.calculateBeamYWithDirection(h,u,l);l===Ce.Down&&(c*=-1,d*=-1),i.font=r.effectFont,i.fillText(a,e+this.x+u,t+this.y+p-c-d)}i.textAlign=n,i.textBaseline=o}getStemSize(e){let t=1===e.beats.length?this.getFlagStemSize(e.shortestDuration):this.getBarStemSize(e.shortestDuration);return e.isGrace&&(t*=Ys.GraceScale),t}getBarStemSize(e){let t=0;switch(e){case p.QuadrupleWhole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:t=6;break;case p.ThirtySecond:t=8;break;case p.SixtyFourth:case p.OneHundredTwentyEighth:t=9;break;case p.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}getFlagStemSize(e){let t=0;switch(e){case p.QuadrupleWhole:case p.Half:case p.Quarter:case p.Eighth:case p.Sixteenth:case p.ThirtySecond:case p.SixtyFourth:case p.OneHundredTwentyEighth:case p.TwoHundredFiftySixth:t=6;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){let i=super.getNoteY(e,t);if(isNaN(i)){const t=ka.computeLineWithoutAccidentals(this.bar,e);i=this.getScoreY(t)}return i}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),i=this.helpers.collisionHelper.getBeatMinMaxY();i[0]<e&&this.registerOverflowTop(Math.abs(i[0])),i[1]>t&&this.registerOverflowBottom(Math.abs(i[1])-t)}return e}calculateBeamYWithDirection(e,t,i){let s=this.getStemSize(e);if(!e.drawingInfos.has(i)){let t=new xa;e.drawingInfos.set(i,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?i===Ce.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):i===Ce.Up?this.getScoreY(this.accidentalHelper.getMinLine(a))-s:this.getScoreY(this.accidentalHelper.getMaxLine(a))+s,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?i===Ce.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):i===Ce.Up?this.getScoreY(this.accidentalHelper.getMinLine(r))-s:this.getScoreY(this.accidentalHelper.getMaxLine(r))+s;let o=10*this.scale;if(i===Ce.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),i===Ce.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),i===Ce.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),i===Ce.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(i===Ce.Up){let i=this.getScoreY(this.accidentalHelper.getMinLine(e.beatOfHighestNote))-s;const a=t.calcY(e.getBeatLineX(e.beatOfHighestNote))-i;a>0&&(t.startY-=a,t.endY-=a)}else{const i=this.getScoreY(this.accidentalHelper.getMaxLine(e.beatOfLowestNote))+s-t.calcY(e.getBeatLineX(e.beatOfLowestNote));i>0&&(t.startY+=i,t.endY+=i)}if(null!==e.minRestLine||null!==e.maxRestLine){const s=Q.getIndex(e.shortestDuration)-2;let a=e.isGrace?Ys.GraceScale:1,r=s*(qa.BeamSpacing+qa.BeamThickness)*this.scale*a;if(r+=qa.BeamSpacing,i===Ce.Up&&null!==e.minRestLine){let i=this.getScoreY(e.minRestLine)-r;const s=t.calcY(e.getBeatLineX(e.beatOfMinRestLine))-i;s>0&&(t.startY-=s,t.endY-=s)}else if(i===Ce.Down&&null!==e.maxRestLine){const i=this.getScoreY(e.maxRestLine)+r-t.calcY(e.getBeatLineX(e.beatOfMaxRestLine));i>0&&(t.startY+=i,t.endY+=i)}}}}return e.drawingInfos.get(i).calcY(t)}paintBar(e,t,i,s){for(let a=0,r=s.beats.length;a<r;a++){let r=s.beats[a],n=r.graceType!==f.None?Ys.GraceScale:1,o=s.getBeatLineX(r),h=s.direction,l=t+this.y;l+=h===Ce.Up?this.getScoreY(this.accidentalHelper.getMaxLine(r)):this.getScoreY(this.accidentalHelper.getMinLine(r));let c=t+this.y;c+=this.calculateBeamY(s,o),i.lineWidth=qa.StemWidth*this.scale,i.beginPath(),i.moveTo(e+this.x+o,l),i.lineTo(e+this.x+o,c),i.stroke(),i.lineWidth=this.scale;let d=c;h===Ce.Down?d+=2*i.font.size:0!==a&&(d-=1.5*i.font.size),this.paintFingering(i,r,e+this.x+o,h,d);let u=6*this.scale*n,p=(qa.BeamSpacing+qa.BeamThickness)*this.scale*n,g=qa.BeamThickness*this.scale*n,m=Q.getIndex(r.duration)-2,y=t+this.y;h===Ce.Down&&(p=-p,g=-g);for(let t=0;t<m;t++){let n=0,h=0,l=0,c=0,d=y+t*p;if(a<s.beats.length-1){if(Na.isFullBarJoin(r,s.beats[a+1],t))n=o,h=s.getBeatLineX(s.beats[a+1]);else{if(0!==a&&Na.isFullBarJoin(s.beats[a-1],r,t))continue;n=o,h=n+u}l=d+this.calculateBeamY(s,n),c=d+this.calculateBeamY(s,h),Hn.paintSingleBar(i,e+this.x+n,l,e+this.x+h,c,g)}else a>0&&!Na.isFullBarJoin(r,s.beats[a-1],t)&&(n=o-u,h=o,l=d+this.calculateBeamY(s,n),c=d+this.calculateBeamY(s,h),Hn.paintSingleBar(i,e+this.x+n,l,e+this.x+h,c,g))}}}static paintSingleBar(e,t,i,s,a,r){e.beginPath(),e.moveTo(t,i),e.lineTo(s,a),e.lineTo(s,a+r),e.lineTo(t,i+r),e.closePath(),e.fill()}paintFlag(t,i,s,a){let r=a.beats[0];if(r.graceType===f.BendGrace||r.graceType!==f.None&&this.settings.notation.notationMode===e.NotationMode.SongBook)return;let n=r.graceType!==f.None,o=n?Ys.GraceScale:1,h=this.getFlagStemSize(a.shortestDuration),l=a.getBeatLineX(r),c=a.direction,d=this.getScoreY(this.accidentalHelper.getMinLine(r)),u=this.getScoreY(this.accidentalHelper.getMaxLine(r)),p=0,g=0;if(c===Ce.Down?(u+=h*o,p=u,g=i+this.y+u):(d-=h*o,p=d,g=i+this.y+d),this.paintFingering(s,r,t+this.x+l,c,g),a.hasLine){if(s.lineWidth=qa.StemWidth*this.scale,s.beginPath(),s.moveTo(t+this.x+l,i+this.y+d),s.lineTo(t+this.x+l,i+this.y+u),s.stroke(),s.lineWidth=this.scale,r.graceType===f.BeforeBeat){let e=15*this.scale,a=12*this.scale;s.beginPath(),c===Ce.Down?(s.moveTo(t+this.x+l-a/2,i+this.y+u-e),s.lineTo(t+this.x+l+a/2,i+this.y+u)):(s.moveTo(t+this.x+l-a/2,i+this.y+d+e),s.lineTo(t+this.x+l+a/2,i+this.y+d)),s.stroke()}if(a.hasFlag){let e=new qs(l-this.scale/2,p,r.duration,c,n);e.renderer=this,e.doLayout(),e.paint(t+this.x,i+this.y,s)}}}paintFingering(t,i,s,a,r){let n=this.settings;if(n.notation.fingeringMode!==e.FingeringMode.ScoreDefault&&n.notation.fingeringMode!==e.FingeringMode.ScoreForcePiano)return;a===Ce.Up?s-=10*this.scale:s+=3*this.scale;let o=i.notes.slice(0);o.sort(((e,t)=>e.realValue-t.realValue));for(let e=0;e<o.length;e++){let a=o[e],h=null;a.leftHandFinger!==m.Unknown?h=Q.fingerToString(n,i,a.leftHandFinger,!0):a.rightHandFinger!==m.Unknown&&(h=Q.fingerToString(n,i,a.rightHandFinger,!1)),h&&(t.fillText(h,s,r),r-=0|t.font.size)}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new en(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 n.Neutral:e=this.bar.staff.standardNotationLineCount-1;break;case n.F4:e=2;break;case n.C3:e=4;break;case n.C4:e=2;break;case n.G2:e=6}this.createStartSpacing(),this.addPreBeatGlyph(new $r(0,this.getScoreY(e)+.5*qa.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 jr(0,this.getScoreHeight(-.5),this.bar.index+1))}createBeatGlyphs(){for(let e=0;e<this.bar.voices.length;e++){let t=this.bar.voices[e];this.hasVoiceContainer(t)&&this.createVoiceGlyphs(t)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new Kr(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Zr(0,this.getScoreHeight(-.5),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new Qr(0,0))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new Tn(0,0,2*this.scale)),this._startSpacing=!0)}createKeySignatureGlyphs(){let e=0,t=this.bar.masterBar.keySignature,i=this.bar.previousBar?this.bar.previousBar.masterBar.keySignature:0;switch(this.bar.clef){case n.Neutral:e=0;break;case n.G2:e=1;break;case n.F4:e=3;break;case n.C3:e=2;break;case n.C4:e=0}let s=new Map,a=[];if(Q.keySignatureIsSharp(t))for(let i=0;i<Math.abs(t);i++){let t=Hn.SharpKsSteps[i]+e;a.push(new Jr(0,this.getScoreY(t),Je.Sharp,!1)),s.set(t,!0)}else for(let i=0;i<Math.abs(t);i++){let t=Hn.FlatKsSteps[i]+e;a.push(new Jr(0,this.getScoreY(t),Je.Flat,!1)),s.set(t,!0)}let r=Math.abs(i),o=Q.keySignatureIsSharp(i)?Hn.SharpKsSteps:Hn.FlatKsSteps;for(let t=0;t<r;t++){let i=o[t]+e;s.has(i)||this.addPreBeatGlyph(new Jr(0,this.getScoreY(o[t]+e),Je.Natural,!1))}for(let e of a)this.addPreBeatGlyph(e)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Tn(0,0,5*this.scale));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new In(0,this.getScoreY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,i=e.beats.length;t<i;t++){let i=e.beats[t],s=new Vn(i,this.getVoiceContainer(e));s.preNotes=new Cn,s.onNotes=new Pn,this.addBeatGlyph(s)}}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,i){super.paintBackground(e,t,i);let s=this.resources;i.color=s.staffLineColor;for(let s=0;s<this.bar.staff.standardNotationLineCount;s++){const a=t+this.y+this.getScoreY(2*s);i.fillRect(e+this.x,0|a,this.width,this.scale*qa.StaffLineThickness)}i.color=s.mainGlyphColor,this.paintSimileMark(e,t,i)}completeBeamingHelper(e){if(this.bar.isMultiVoice&&e.highestNoteInHelper&&e.lowestNoteInHelper){let t=this.getNoteY(e.highestNoteInHelper,Qe.Center),i=this.getNoteY(e.lowestNoteInHelper,Qe.Center),s=this.getStemSize(e);e.hasTuplet&&(s+=2*this.resources.effectFont.size),e.direction==Ce.Up?t-=s:i+=s;for(const s of e.beats)this.helpers.collisionHelper.reserveBeatSlot(s,t,i)}}}Hn.StaffId="score",Hn.SharpKsSteps=[-1,2,-2,1,4,0,3],Hn.FlatKsSteps=[3,0,4,1,5,2,6];class Wn extends Sa{get staffId(){return Hn.StaffId}create(e,t){return new Hn(e,t)}constructor(){super()}}class zn extends zs{constructor(e,t,i,s){super(0,0),this._inType=e,this._outType=t,this._startNote=i,this._parent=s}doLayout(){this.width=0}paint(e,t,i){this.paintSlideIn(e,t,i),this.paintSlideOut(e,t,i)}paintSlideIn(e,t,i){let s=this.renderer,a=12*this.scale,r=3*this.scale,n=0,o=0,h=0,l=0;switch(this._inType){case S.IntoFromBelow:h=e+s.x+s.getNoteX(this._startNote,$e.Left),l=t+s.y+s.getNoteY(this._startNote,Qe.Center),n=h-a,o=t+s.y+s.getNoteY(this._startNote,Qe.Center)+r;break;case S.IntoFromAbove:h=e+s.x+s.getNoteX(this._startNote,$e.Left),l=t+s.y+s.getNoteY(this._startNote,Qe.Center),n=h-a,o=t+s.y+s.getNoteY(this._startNote,Qe.Center)-r;break;default:return}this.paintSlideLine(i,!1,n,h,o,l)}paintSlideOut(e,t,i){let s=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 w.Shift:case w.Legato:if(n=e+s.x+s.getBeatX(this._startNote.beat,qe.PostNotes),o=t+s.y+s.getNoteY(this._startNote,Qe.Center),this._startNote.slideTarget){let i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);i&&i.staff===s.staff?(h=e+i.x+i.getBeatX(this._startNote.slideTarget.beat,qe.OnNotes)-d,l=t+i.y+i.getNoteY(this._startNote.slideTarget,Qe.Center)):(h=e+s.x+s.width,l=o),this._startNote.slideTarget.fret>this._startNote.fret?(o+=r,l-=r):(o-=r,l+=r)}else h=e+s.x+this._parent.x,l=o;break;case w.OutUp:n=e+s.x+s.getNoteX(this._startNote,$e.Right),o=t+s.y+s.getNoteY(this._startNote,Qe.Center),h=n+a-d,l=t+s.y+s.getNoteY(this._startNote,Qe.Center)-r;break;case w.OutDown:n=e+s.x+s.getNoteX(this._startNote,$e.Right),o=t+s.y+s.getNoteY(this._startNote,Qe.Center),h=n+a-d,l=t+s.y+s.getNoteY(this._startNote,Qe.Center)+r;break;case w.PickSlideDown:n=e+s.x+s.getNoteX(this._startNote,$e.Right),o=t+s.y+s.getNoteY(this._startNote,Qe.Center),h=e+s.x+s.getBeatX(this._startNote.beat,qe.EndBeat),l=o+3*r,c=!0;break;case w.PickSlideUp:n=e+s.x+s.getNoteX(this._startNote,$e.Right),o=t+s.y+s.getNoteY(this._startNote,Qe.Center),h=e+s.x+s.getBeatX(this._startNote.beat,qe.EndBeat),l=o-3*r,c=!0;break;default:return}this.paintSlideLine(i,c,n,h,o,l)}paintSlideLine(e,t,i,s,a,r){if(t){let t=new Lr(0,0,_.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;let n=s-i,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(i,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(i,a),e.lineTo(s,r),e.stroke()}}class Un extends nn{constructor(e,t,i=!1){super(e.beat,t.beat,i),this.startNote=e,this.endNote=t}getTieHeight(e,t,i,s){return this.startNote===this.endNote?15:super.getTieHeight(e,t,i,s)}getBeamDirection(e,t){return this.startNote===this.endNote?Ce.Up:Un.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?Ce.Up:Ce.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,Qe.Center):this.tieDirection===Ce.Up?this.startNoteRenderer.getNoteY(this.startNote,Qe.Top):this.startNoteRenderer.getNoteY(this.startNote,Qe.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20*this.scale:this.startNoteRenderer.getNoteX(this.startNote,$e.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,$e.Left):this.endNoteRenderer.getNoteX(this.endNote,$e.Center)}}class Xn extends Un{constructor(e,t,i,s=!1){super(e,t,s),this._direction=Un.getBeamDirectionForNote(e),this._forSlide=i}getTieHeight(e,t,i,s){return Math.log(i-e+1)*this.renderer.settings.notation.slurHeight}tryExpand(e,t,i,s){if(this._forSlide!==i)return!1;if(this.forEnd!==s)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!==Un.getBeamDirectionForNote(e))return!1;switch(this._direction){case Ce.Up:e.realValue>this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue>this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat);break;case Ce.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,i){let s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar),a=this.getBeamDirection(this.startBeat,s),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,i))}}class Yn extends Js{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 Un(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){let t=new Un(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new Un(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(let i of this._effectSlurs)if(i.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){let t=new Xn(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(let i of this._effectSlurs)if(i.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){let t=new Xn(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==S.None||e.slideOutType!==w.None){let t=new zn(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new wn;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class qn extends zs{constructor(e,t,i){super(e,t),this._noteString=null,this._trillNoteString=null,this._trillNoteStringWidth=0,this.isEmpty=!1,this.noteStringWidth=0,this._note=i}doLayout(){let t=this._note,i=t.fret-t.beat.voice.bar.staff.transpositionPitch;if(t.harmonicType===y.Natural&&0!==t.harmonicValue&&(i=t.harmonicValue-t.beat.voice.bar.staff.transpositionPitch),t.isTieDestination)0===t.beat.index&&this.renderer.settings.notation.notationMode==e.NotationMode.GuitarPro||(t.bendType===c.Bend||t.bendType===c.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(v.TabNotesOnTiedBends)?this._noteString="("+(t.tieOrigin.fret-t.beat.voice.bar.staff.transpositionPitch).toString()+")":this._noteString="";else if(this._noteString=t.isDead?"x":i.toString(),t.isGhost)this._noteString="("+this._noteString+")";else if(t.harmonicType===y.Natural){let e=this._noteString.indexOf(String.fromCharCode(46));e>=0&&(this._noteString=this._noteString.substr(0,e+2)),this._noteString="<"+this._noteString+">"}if(t.isTrill)this._trillNoteString="("+(t.trillFret-t.beat.voice.bar.staff.transpositionPitch).toString()+")";else if(Q.isAlmostEqualTo(t.harmonicValue,0))this._trillNoteString="";else switch(t.harmonicType){case y.Artificial:case y.Pinch:case y.Tap:case y.Semi:case y.Feedback:let e=(i+t.harmonicValue).toString(),s=e.indexOf(String.fromCharCode(46));s>=0&&(e=e.substr(0,s+2)),this._trillNoteString="<"+e+">";break;default:this._trillNoteString=""}if(this.isEmpty=!this._noteString,!this.isEmpty){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.tablatureFont,this.noteStringWidth=this.renderer.scoreRenderer.canvas.measureText(this._noteString)*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,i){if(this.isEmpty)return;let s=this.noteStringWidth+this._trillNoteStringWidth,a=e+this.x+(this.width-s)/2,r=this.renderer.scoreRenderer.canvas.font;this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,i.fillText(this._trillNoteString,a+this.noteStringWidth+3*this.scale,t+this.y),this.renderer.scoreRenderer.canvas.font=r,i.fillText(this._noteString,a,t+this.y)}buildBoundingsLookup(e,t,i){let s=new vs;s.note=this._note,s.noteHeadBounds=new nt,s.noteHeadBounds.x=t+this.x,s.noteHeadBounds.y=i+this.y-this.height/2,s.noteHeadBounds.w=this.width,s.noteHeadBounds.h=this.height,e.addNote(s)}}class Jn extends zs{constructor(e,t,i){super(e,t),this._notes=[],this.minStringNote=null,this.beatEffects=new Map,this.notesPerString=new Map,this.noteStringWidth=0,this._isGrace=i}buildBoundingsLookup(e,t,i){for(const s of this._notes)s.buildBoundingsLookup(e,t+this.x,i+this.y)}getNoteX(e,t){if(this.notesPerString.has(e.string)){let i=this.notesPerString.get(e.string),s=this.x+i.x;switch(t){case $e.Left:break;case $e.Center:s+=i.noteStringWidth/2;break;case $e.Right:s+=i.width}return s}return 0}getNoteY(e,t){if(this.notesPerString.has(e.string)){const i=this.notesPerString.get(e.string);let s=this.y+i.y;switch(t){case Qe.Top:case Qe.TopWithStem:s-=i.height/2+2*this.scale;break;case Qe.Center:break;case Qe.Bottom:case Qe.BottomWithStem:s+=i.height/2}return s}return 0}doLayout(){let e=0,t=0;for(let i=0,s=this._notes.length;i<s;i++){let s=this._notes[i];s.renderer=this.renderer,s.doLayout(),s.width>e&&(e=s.width),s.noteStringWidth>t&&(t=s.noteStringWidth)}this.noteStringWidth=t;let i=this.renderer.resources.tablatureFont.size,s=this.getNoteY(this.minStringNote,Qe.Center)+i/2,a=7*this.scale;for(const e of this.beatEffects.values())e.y+=s,e.x+=this.width/2,e.renderer=this.renderer,s+=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,i){e+=this.x,t+=this.y;let s=this.renderer.resources,a=i.textBaseline;i.textBaseline=C.Middle,i.font=this._isGrace?s.graceFont:s.tablatureFont;let r=this._notes,n=this.width;for(let s of r)s.renderer=this.renderer,s.width=n,s.paint(e,t,i);i.textBaseline=a;for(const s of this.beatEffects.values())s.paint(e,t,i)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}}class jn extends Xs{constructor(e,t,i,s){super(e,t,1,gn.getSymbol(s)),this._isVisibleRest=i,this._duration=s}doLayout(){this._isVisibleRest?this.width=gn.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,i){this._isVisibleRest&&super.paint(e,t,i)}}class Qn extends Za{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,i){this.noteNumbers&&this.noteNumbers.buildBoundingsLookup(e,t+this.x,i+this.y)}doLayout(){let t=this.renderer;if(this.container.beat.isRest){let e=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),i=t.getTabY(e);const s=new jn(0,i,t.showRests,this.container.beat.duration);if(this.restGlyph=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper,this.addGlyph(s),this.container.beat.dots>0&&t.showRests){this.addGlyph(new Tn(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new sn(0,i,1.5*this.scale))}}else{let i=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==f.None;const s=new Jn(0,0,i);this.noteNumbers=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper;for(let e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);if(this.addGlyph(s),this.container.beat.hasWhammyBar){let e=new _n(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!this.noteNumbers.beatEffects.has("tremolo")){let e=0,t=this.container.beat.tremoloSpeed;switch(t){case p.ThirtySecond:e=10;break;case p.Sixteenth:e=5;break;case p.Eighth:e=0}this.noteNumbers.beatEffects.set("tremolo",new un(5*this.scale,e*this.scale,t))}if(this.container.beat.dots>0&&t.settings.notation.rhythmMode!==e.TabRhythmMode.Hidden){this.addGlyph(new Tn(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new sn(0,t.lineOffset*t.bar.staff.tuning.length+t.settings.notation.rhythmHeight*t.scale,1.5*this.scale))}}if(!this.glyphs)return;let i=0;for(let e=0,t=this.glyphs.length;e<t;e++){let t=this.glyphs[e];t.x=i,t.renderer=this.renderer,t.doLayout(),i+=t.width}this.width=i,this.computedWidth=i,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,i=new qn(0,0,e),s=e.beat.voice.bar.staff.tuning.length-e.string;i.y=t.getTabY(s),i.renderer=this.renderer,i.doLayout(),this.noteNumbers.addNoteGlyph(i,e);let a=i.y-i.height/2,r=a+i.height;this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,a,r)}}class $n extends zs{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10*this.scale}paint(e,t,i){let s=this.renderer,a=t+this.x+s.getNoteY(this._beat.maxStringNote,Qe.Top),r=t+this.y+s.getNoteY(this._beat.minStringNote,Qe.Bottom),n=e+this.x+this.width/2|0,o=8*this.scale;if(this._beat.brushType!==d.None){if(this._beat.brushType===d.BrushUp||this._beat.brushType===d.BrushDown)i.beginPath(),i.moveTo(n,a),i.lineTo(n,r),i.stroke();else if(this._beat.brushType===d.ArpeggioUp){let t=new Lr(0,0,_.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let s=a,n=r-o;t.width=Math.abs(n-s),i.beginRotate(e+this.x+4*this.scale,n,-90),t.paint(0,-t.height/2,i),i.endRotate()}else if(this._beat.brushType===d.ArpeggioDown){let t=new Lr(0,0,_.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();let s=a+o,n=r;t.width=Math.abs(n-s),i.beginRotate(e+this.x+4*this.scale,s,90),t.paint(0,-t.height/2,i),i.endRotate()}this._beat.brushType===d.BrushUp||this._beat.brushType===d.ArpeggioUp?(i.beginPath(),i.moveTo(n,r),i.lineTo(n+o/2,r-o),i.lineTo(n-o/2,r-o),i.closePath(),i.fill()):(i.beginPath(),i.moveTo(n,a),i.lineTo(n+o/2,a+o),i.lineTo(n-o/2,a+o),i.closePath(),i.fill())}}}class Kn extends Ka{doLayout(){this.container.beat.brushType===d.None||this.container.beat.isRest||(this.addGlyph(new $n(this.container.beat)),this.addGlyph(new Tn(0,0,4*this.scale))),super.doLayout()}constructor(){super()}}class Zn extends zs{constructor(e,t){super(e,t)}doLayout(){this.width=28*this.scale}paint(e,t,i){let s=this.renderer.bar.staff.tuning.length,a=s<=4?P.FourStringTabClef:P.SixStringTabClef,r=s<=4?s/4.5:s/6.5;i.fillMusicFontSymbol(e+this.x+5*this.scale,t+this.y,r*this.scale,a,!1)}}class eo extends Mn{get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?Ys.GraceScale:1}}class to extends qa{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(to.TabLineSpacing+1)*this.scale}updateSizes(){let t=this.resources,i=(t.tablatureFont.size/2+.2*t.tablatureFont.size)*this.scale;this.topPadding=i,this.bottomPadding=i,this.height=this.lineOffset*(this.bar.staff.tuning.length-1)+2*i,this.settings.notation.rhythmMode!==e.TabRhythmMode.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!==e.TabRhythmMode.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 en(0,0,1.5,3)),this.isFirstOfLine){let e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new Zn(5*this.scale,this.getTabY(e)))}this.showTimeSignature&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new jr(0,this.getTabHeight(-.5),this.bar.index+1))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new Tn(0,0,2*this.scale)),this._startSpacing=!0)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new Tn(0,0,5*this.scale));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new eo(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,i=e.beats.length;t<i;t++){let i=e.beats[t],s=new Yn(i,this.getVoiceContainer(e));s.preNotes=new Kn,s.onNotes=new Qn,this.addBeatGlyph(s)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new Kr(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Zr(0,this.getTabY(-1),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new Qr(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,i){super.paintBackground(e,t,i);let s=this.resources;i.color=s.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 i=e.onNotes,s=i.noteNumbers;if(s)for(const[n,o]of s.notesPerString)o.isEmpty||r[this.bar.staff.tuning.length-n].push(new Float32Array([t.x+e.x+i.x+s.x,s.width+a]))}}for(let e of r)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));for(let s=0,a=this.bar.staff.tuning.length;s<a;s++){const a=this.getTabY(s);let n=0;for(let o of r[s])i.fillRect(e+this.x+n,t+this.y+a|0,o[0]-n,this.scale*qa.StaffLineThickness),n=o[0]+o[1];i.fillRect(e+this.x+n,t+this.y+a|0,this.width-n,this.scale*qa.StaffLineThickness)}i.color=s.mainGlyphColor,this.paintSimileMark(e,t,i)}paint(t,i,s){super.paint(t,i,s),this.settings.notation.rhythmMode!==e.TabRhythmMode.Hidden&&(this.paintBeams(t,i,s),this.paintTuplets(t,i,s))}paintBeams(e,t,i){for(let s=0,a=this.helpers.beamHelpers.length;s<a;s++){let a=this.helpers.beamHelpers[s];for(let s=0,r=a.length;s<r;s++){let r=a[s];this.paintBeamHelper(e+this.beatGlyphsStart,t,i,r)}}}paintTuplets(e,t,i){for(let s of this.bar.voices)if(this.hasVoiceContainer(s)){let a=this.getVoiceContainer(s);for(let s of a.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,i,s)}}paintBeamHelper(t,i,s,a){s.color=0===a.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,a.isRestBeamHelper||(1===a.beats.length||this.settings.notation.rhythmMode===e.TabRhythmMode.ShowWithBeams?this.paintFooter(t,i,s,a):this.paintBar(t,i,s,a))}paintBar(e,t,i,s){for(let a=0,r=s.beats.length;a<r;a++){let r=s.beats[a];if(s.hasBeatLineX(r)){let n=s.getBeatLineX(r),o=t+this.y,h=t+this.y+this.height-this._tupletSize,l=this.getOnNotesGlyphForBeat(r);l.noteNumbers&&r.duration!==p.Half?o+=l.noteNumbers.getNoteY(l.noteNumbers.minStringNote,Qe.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,i);let c=6*this.scale,d=-6*this.scale,u=3*this.scale,g=Q.getIndex(r.duration)-2,f=h;for(let t=0;t<g;t++){let o=0,h=0,l=0,p=0,g=f+t*d;if(1===s.beats.length)o=n,h=n+c,l=g,p=g,to.paintSingleBar(i,e+this.x+o,l,e+this.x+h,p,u);else if(a<s.beats.length-1){if(Na.isFullBarJoin(r,s.beats[a+1],t))o=n,h=s.getBeatLineX(s.beats[a+1]);else{if(0!==a&&Na.isFullBarJoin(s.beats[a-1],r,t))continue;o=n,h=o+c}l=g,p=g,to.paintSingleBar(i,e+this.x+o,l,e+this.x+h,p,u)}else a>0&&!Na.isFullBarJoin(r,s.beats[a-1],t)&&(o=n-c,h=n,l=g,p=g,to.paintSingleBar(i,e+this.x+o,l,e+this.x+h,p,u))}}}}paintTupletHelper(e,t,i,s){let a,r=this.resources,n=i.textAlign,o=i.textBaseline;i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.textAlign=E.Center,i.textBaseline=C.Middle;let h=s.beats[0].tupletNumerator,l=s.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!==s.beats.length&&s.isFull){let n=s.beats[0],o=s.beats[s.beats.length-1],h=this.helpers.beamHelperLookup[s.voice.index].get(n.index),l=this.helpers.beamHelperLookup[s.voice.index].get(o.index);if(h&&l){let s=h.getBeatLineX(n),c=l.getBeatLineX(o);i.font=r.effectFont;let d=i.measureText(a),u=3*this.scale,p=(s+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;i.beginPath(),i.moveTo(e+this.x+s,m-y|0),i.lineTo(e+this.x+s,m-y-b|0),i.lineTo(e+this.x+g,m-y-b|0),i.stroke(),i.beginPath(),i.moveTo(e+this.x+f,m-y-b|0),i.lineTo(e+this.x+c,m-y-b|0),i.lineTo(e+this.x+c,m-y|0),i.stroke(),i.fillText(a,e+this.x+p,m-y-b)}}else for(let n=0,o=s.beats.length;n<o;n++){let o=s.beats[n],h=this.helpers.beamHelperLookup[s.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;i.font=r.effectFont,i.fillText(a,e+this.x+l,c)}i.textAlign=n,i.textBaseline=o}static paintSingleBar(e,t,i,s,a,r){e.beginPath(),e.moveTo(t,i),e.lineTo(s,a),e.lineTo(s,a-r),e.lineTo(t,i-r),e.closePath(),e.fill()}paintBeamingStem(e,t,i,s,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>s;){r.moveTo(i,o);let e=s;if(!(n.length>0&&n[n.length-1].bottomY>e)){r.lineTo(i,e);break}{const s=n.pop();e=t+s.bottomY,r.lineTo(i,e),o=t+s.topY}}r.stroke()}paintFooter(e,t,i,s){for(let a of s.beats){if(a.graceType!==f.None||a.duration===p.Whole||a.duration===p.DoubleWhole||a.duration===p.QuadrupleWhole)return;let r=s.getBeatLineX(a),n=t+this.y,o=t+this.y+this.height-this._tupletSize,h=this.getOnNotesGlyphForBeat(a);if(h.noteNumbers&&a.duration!==p.Half?n+=h.noteNumbers.getNoteY(h.noteNumbers.minStringNote,Qe.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,i),a.duration>p.Quarter){let t=new qs(0,0,a.duration,Ce.Down,!1);t.renderer=this,t.doLayout(),t.paint(e+this.x+r,o,i)}}}}to.StaffId="tab",to.TabLineSpacing=10;class io extends Sa{get staffId(){return to.StaffId}constructor(e,t,i){super(),this._showTimeSignature=e,this._showRests=t,this._showTiedNotes=i,this.hideOnPercussionTrack=!0}canCreate(e,t){return t.tuning.length>0&&super.canCreate(e,t)}create(e,t){let i=new to(e,t);return i.showRests=this._showRests,i.showTimeSignature=this._showTimeSignature,i.showTiedNotes=this._showTiedNotes,i}}class so extends Us{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+so.Padding*this.scale}paint(e,t,i){let s=this.renderer.resources;i.font=s.effectFont;let a=i.textAlign;i.textAlign=E.Center,i.fillText("T",e+this.x,t+this.y+i.font.size/2),i.textAlign=a,i.strokeCircle(e+this.x,t+this.y+i.font.size/2+(so.Padding-1)*this.scale,i.font.size/1.6)}}so.Padding=4;class ao extends yr{get notationElement(){return v.EffectTap}get sizingMode(){return Ke.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new so}}class ro{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"}(et||(et={}));class no extends ro{constructor(){super(...arguments),this.align=E.Left,this.frame=et.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class oo extends ro{constructor(){super(...arguments),this.chord=new he}}class ho extends ro{}class lo extends ro{}class co extends ro{constructor(){super(...arguments),this.number=0}}class uo extends ro{constructor(){super(...arguments),this.decrescendo=!1}}class po extends ro{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class go extends ro{constructor(){super(...arguments),this.octave=1}}class fo extends ro{}class mo{constructor(){this.defaultClef=n.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class yo{constructor(){this.from=0,this.to=0,this.curly=!1}}class bo{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=L.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new ce,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 i=new pt;try{i.parse(e)}catch(e){throw new V("Could not parse XML",e)}this.parseDom(i),this.consolidate(),this.score.finish(t)}consolidate(){let e=this.score.tempo;for(const t of this.score.tracks){const i=this._voiceCounts.get(t.index);for(const s of t.staves){for(;s.bars.length<this.score.masterBars.length;)this.addNewBar(s);for(const t of s.bars){for(;t.voices.length<i;)t.addVoice(new _e);for(const e of t.voices)if(0===e.beats.length){const t=new oe;t.isEmpty=!0,e.addBeat(t)}const s=t.masterBar;s.tempoAutomation&&(s.tempoAutomation.value!==e?e=s.tempoAutomation.value:s.tempoAutomation=null)}}}So.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),So.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?u.Decrescendo:u.Crescendo}))}static applyEffectRange(e,t){for(const[i,s]of e){const e=s.noteRange;let a=i;for(let i=0;i<e;i++)if(t(s,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 V("No valid XML");if("score"!==t.localName)throw new V('Root node of XML was not "score"');this.score=new pe,this.score.tempo=120;for(let e of t.childNodes)if(e.nodeType===Pe.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===Pe.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 i=0,s=null;for(let e=0;e<this._staffLayouts.length;e++){const a=this._staffLayouts[e];for(;i<t.length&&e>t[i].to;)i++;s&&i<t.length&&e>t[i].from&&e<=t[i].to?s.ensureStaveCount(s.staves.length+1):(s=new we,s.ensureStaveCount(1),s.name=a.description,s.playbackInfo.volume=Math.floor(a.volume/128*16),s.playbackInfo.program=a.instrument,a.percussion?(s.playbackInfo.primaryChannel=9,s.playbackInfo.secondaryChannel=9):(s.playbackInfo.primaryChannel=this._trackChannel++,s.playbackInfo.secondaryChannel=this._trackChannel++),this.score.addTrack(s));const r=s.staves[s.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===Pe.Element&&"bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new yo;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===Pe.Element&&"staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new mo;t.description=e.getAttribute("description");for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"notation":i.attributes.has("defaultClef")&&(t.defaultClef=this.parseClef(i.attributes.get("defaultClef")));break;case"sound":i.attributes.has("percussion")&&(t.percussion="true"===i.attributes.get("percussion")),i.attributes.has("instr")&&(t.instrument=parseInt(i.attributes.get("instr"))),i.attributes.has("volume")&&(t.volume=parseInt(i.attributes.get("volume"))),i.attributes.has("transpose")&&(t.transpose=parseInt(i.attributes.get("transpose")))}this._staffLayoutLookup.set(t.description,t),t.index=this._staffLayouts.length,this._staffLayouts.push(t)}parseClef(e){switch(e){case"treble":return n.G2;case"bass":return n.F4;case"alto":case"tenor":return n.C4}return n.G2}parseClefOttava(e){return e.endsWith("-")?o._8vb:e.endsWith("+")?o._8va:o.Regular}parseSystems(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"system"===t.localName)this.parseSystem(t)}parseSystem(e){e.attributes.has("tempo")&&0===this.score.masterBars.length&&(this.score.tempo=parseInt(e.attributes.get("tempo"))),"0"===e.getAttribute("beamGrouping")&&(this._beamingMode=L.ForceSplitToNext);for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"staves"===t.localName)this.parseStaves(e,t);this._isFirstSystem=!1}parseStaves(e,t){let i=this.score.masterBars.length;for(let s of t.childNodes)if(s.nodeType===Pe.Element&&"staff"===s.localName)this.parseStaff(e,i,s)}parseStaff(e,t,i){const s=i.getAttribute("layout");this._currentStaffLayout=this._staffLayoutLookup.get(s),this._timeSignature.timeSignatureNumerator=4,this._timeSignature.timeSignatureDenominator=4,this._timeSignature.timeSignatureCommon=!1,this.parseTime(i.getAttribute("defaultTime"));const a=this._staffLookup.get(this._currentStaffLayout.index);for(;a.bars.length<t;)this.addNewBar(a);for(let r of i.childNodes)if(r.nodeType===Pe.Element&&"voices"===r.localName)this.parseVoices(s,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,i,s,a){let r=0;for(let n of a.childNodes)if(n.nodeType===Pe.Element&&"voice"===n.localName)this.parseVoice(e,t,i,r,s,n),r++}getOrCreateBar(e,t){return t<e.bars.length?e.bars[t]:this.addNewBar(e)}addNewBar(e){let t=new W;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 ce;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,i,s,a,n){const o=e+"_"+s;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,s)):(this._currentVoiceState=new bo,this._currentVoiceState.currentBarIndex=a-1,this._voiceStates.set(o,this._currentVoiceState),this.newBar(t,s)),n.attributes.has("stemDir"))switch(n.attributes.get("stemDir")){case"up":this._currentVoiceState.voiceStemDir=Ce.Up;break;case"down":this._currentVoiceState.voiceStemDir=Ce.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const h=n.findChildElement("noteObjects");if(i.attributes.has("tempo")&&(this._currentBar.masterBar.tempoAutomation=new H,this._currentBar.masterBar.tempoAutomation.isLinear=!0,this._currentBar.masterBar.tempoAutomation.type=r.Tempo,this._currentBar.masterBar.tempoAutomation.value=parseInt(i.attributes.get("tempo"))),h)for(let e of h.childNodes)if(e.nodeType===Pe.Element)switch(this._currentVoiceState.currentBarComplete&&"barline"!==e.localName&&this.newBar(t,s),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,s),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,s),this._currentBar.masterBar.isRepeatStart=!0;break;default:this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0}break;case"chord":let i=new oe;this.initFromPreviousBeat(i,this._currentVoice),i.beamingMode=this._beamingMode,this._currentVoiceState.voiceStemDir&&(i.preferredBeamDirection=this._currentVoiceState.voiceStemDir),this.parseDuration(this._currentBar,i,e.findChildElement("duration")),i.updateDurations(),this._currentVoiceState.currentPosition+=i.playbackDuration,this._currentVoice.addBeat(i),this.parseChord(i,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 i=this.getLastBeat(t);i&&(e.dynamics=i.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 i=t.voices[e.index];return this.getLastBeat(i)}}return null}ensureVoice(e,t){for(;this._currentBar.voices.length<t+1;)this._currentBar.addVoice(new _e);(!this._voiceCounts.has(e.track.index)||this._voiceCounts.get(e.track.index)<this._currentBar.voices.length)&&this._voiceCounts.set(e.track.index,this._currentBar.voices.length),this._currentVoice=this._currentBar.voices[t]}parseChord(e,t){const i=new ee;for(let s of t.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"stem":switch(s.getAttribute("dir")){case"up":e.preferredBeamDirection=Ce.Up;break;case"down":e.preferredBeamDirection=Ce.Down}break;case"articulation":switch(s.getAttribute("type")){case"staccato":i.isStaccato=!0;break;case"normalAccent":i.accentuated=a.Normal;break;case"strongAccent":i.accentuated=a.Heavy}break;case"lyric":this.parseLyric(e,s);break;case"drawObjects":this.parseBeatDrawObject(e,s);break;case"heads":this.parseHeads(e,i,s);break;case"beam":switch(s.getAttribute("group")){case"force":e.beamingMode=L.ForceMergeWithNext;break;case"divide":e.beamingMode=L.ForceSplitToNext}}}parseHeads(e,t,i){for(let s of i.childNodes)if(s.nodeType===Pe.Element&&"head"===s.localName)this.parseHead(e,t,s)}parseHead(e,t,i){const s=new ee,a=Q.parseTuning(i.getAttribute("pitch"));s.octave=a.octave-1,s.tone=a.noteValue,s.isStaccato=t.isStaccato,s.accentuated=t.accentuated,e.addNote(s);for(let e of i.childNodes)if(e.nodeType===Pe.Element)switch(e.localName){case"alter":e.attributes.has("step")&&(s.tone+=parseInt(e.attributes.get("step")));break;case"tie":e.attributes.has("begin")?this._tieStartIds.has(s.id)||(this._tieStartIds.set(s.id,!0),this._tieStarts.push(s)):e.attributes.has("end")&&this._tieStarts.length>0&&!s.isTieDestination&&(s.isTieDestination=!0,s.tieOrigin=this._tieStarts[0],this._tieStarts.splice(0,1),this._tieStartIds.delete(s.id))}}parseBeatDrawObject(e,t){for(let i of t.childNodes)if(i.nodeType===Pe.Element&&"drawObj"===i.localName){const t=this.parseDrawObj(i);if(t)if(t instanceof no)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new ht,e.fermata.type=Ne.Medium):"f"===t.text?e.dynamics=g.F:"j"===t.text&&(e.dynamics=g.MF):this._isFirstSystem&&""===this.score.title&&t.align===E.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===E.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===E.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof oo);else if(t instanceof lo)e.vibrato=_.Slight;else if(t instanceof uo)e.crescendo=t.decrescendo?u.Decrescendo:u.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof ho){const i=t;this._slurs.set(e,i)}else t instanceof po&&this.applyVolta(t)}}parseBarDrawObject(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof po&&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 i=e.firstNumber;i<=e.lastNumber;i++)t|=1<<i-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 i of t.childNodes)if(i.nodeType===Pe.Element&&"verse"===i.localName){e.lyrics||(e.lyrics=[]);let t=i.innerText;"true"===i.getAttribute("hyphen")&&(t+="-"),e.lyrics.push(t)}}parseRestDurations(e,t){const i=t.getAttribute("base");if(-1!==i.indexOf("/")){let i=new oe;return i.beamingMode=this._beamingMode,this.parseDuration(e,i,t),i}if(1===parseInt(i)){let e=new oe;return e.beamingMode=this._beamingMode,e.duration=p.Whole,e}return J.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return p.DoubleWhole;case"1/1":return p.Whole;case"1/2":return p.Half;case"1/4":return p.Quarter;case"1/8":return p.Eighth;case"1/16":return p.Sixteenth;case"1/32":return p.ThirtySecond;case"1/64":return p.SixtyFourth;case"1/128":return p.OneHundredTwentyEighth;default:return J.warning("Importer","Unsupported duration"),p.Quarter}}parseDuration(e,t,i){const s=i.getAttribute("base");t.duration=this.parseDurationValue(s),i.attributes.has("dots")&&(t.dots=parseInt(i.attributes.get("dots")));const a=i.findChildElement("tuplet");if(a){t.tupletNumerator=parseInt(a.getAttribute("count"));const e="true"===a.getAttribute("tripartite")?3:1,i="true"===a.getAttribute("prolong")?0:1;let s=0;for(;e*Math.pow(2,s+i)<t.tupletNumerator;)s++;t.tupletDenominator=e*Math.pow(2,s)}}parsePageObjects(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof no)switch(e.align){case E.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case E.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&this._galleryObjects.set(t.getAttribute("name"),e)}}parseDrawObj(e){let t=null,i=1;for(let s of e.childNodes)if(s.nodeType===Pe.Element)switch(s.localName){case"text":t=this.parseText(s);break;case"guitar":t=this.parseGuitar(s);break;case"slur":t=this.parseSlur(s);break;case"wavyLine":t=this.parseWavyLine(s);break;case"bracket":t=this.parseTupletBracket(s);break;case"wedge":t=this.parseWedge(s);break;case"volta":t=this.parseVolta(s);break;case"octaveClef":t=this.parseOctaveClef(s);break;case"trill":t=this.parseTrill(s);break;case"basic":s.attributes.has("noteRange")&&(i=parseInt(s.attributes.get("noteRange")))}return t&&(t.noteRange=i),t}parseTrill(e){return new fo}parseOctaveClef(e){const t=new go;return e.attributes.has("octave")&&(t.octave=parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new po;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 uo;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new co;return e.attributes.has("number")&&(t.number=parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new lo}parseSlur(e){return new ho}parseGuitar(e){const t=new oo,i=e.innerText.trim();for(let e=0;e<i.length;e++)"/"===i.charAt(e)?t.chord.strings.push(0):t.chord.strings.push(parseInt(i.charAt(e)));return t}parseText(e){const t=new no;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=E.Left;break;case"center":t.align=E.Center;break;case"right":t.align=E.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=et.Rectangle;break;case"ellipse":t.frame=et.Ellipse;break;case"circle":t.frame=et.Circle;break;case"none":t.frame=et.None}if(e.firstElement){for(let i of e.childNodes)if(i.nodeType===Pe.Element)switch(i.localName){case"font":t.fontFace=i.getAttribute("face"),i.attributes.has("weight")&&(t.weight=parseInt(i.attributes.get("weight"))),i.attributes.has("height")&&(t.height=parseInt(i.attributes.get("height")));break;case"content":t.text=i.innerText}}else t.text=e.innerText;return t}parseInfo(e){for(let t of e.childNodes)if(t.nodeType===Pe.Element)switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class wo extends O{get name(){return"Capella"}constructor(){super()}readScore(){J.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new Pt(this.data).read(),J.debug(this.name,"Zip entries loaded"),e.length>0){for(let i of e)if("score.xml"===i.fileName)t=Te.toString(i.data,this.settings.importer.encoding)}else this.data.reset(),t=Te.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new V("No valid capella file");J.debug(this.name,"Start Parsing score.xml");try{let e=new So;return e.parseXml(t,this.settings),J.debug(this.name,"score.xml parsed"),e.score}catch(e){throw new V("Failed to parse CapXML",e)}}}class _o{constructor(e){this._targets=new Set,this._callback=e,window.addEventListener("resize",this.onWindowResize.bind(this),!1)}observe(e){this._targets.add(e)}unobserve(e){this._targets.delete(e)}disconnect(){this._targets.clear()}onWindowResize(){const e=[];for(const t of this._targets)e.push({target:t,contentRect:void 0,borderBoxSize:void 0,contentBoxSize:[],devicePixelContentBoxSize:[]});this._callback(e,this)}}class Bo{constructor(e){this._elements=[];let t=null;const i=this._check.bind(this);this._check=()=>{t||(t=setTimeout((()=>{i(),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 i=t.getBoundingClientRect();i.top+i.height>=0&&i.top<=window.innerHeight&&i.left+i.width>=0&&i.left<=window.innerWidth&&e.push({target:t,isIntersecting:!0})})),e.length&&this._callback(e,this)}}function To(e,t,i){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var s;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");s=t[Symbol.asyncDispose]}if(void 0===s){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");s=t[Symbol.dispose]}if("function"!=typeof s)throw new TypeError("Object not disposable.");e.stack.push({value:t,dispose:s,async:i})}else i&&e.stack.push({async:!0});return t}var ko="function"==typeof SuppressedError?SuppressedError:function(e,t,i){var s=new Error(i);return s.name="SuppressedError",s.error=e,s.suppressed=t,s};function vo(e){function t(t){e.error=e.hasError?new ko(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}return function i(){for(;e.stack.length;){var s=e.stack.pop();try{var a=s.dispose&&s.dispose.call(s.value);if(s.async)return Promise.resolve(a).then(i,(function(e){return t(e),i()}))}catch(e){t(e)}}if(e.hasError)throw e.error}()}class xo{static enable(e,t){xo.alphaSkia=t,xo.initializeMusicFont(xo.alphaSkia.AlphaSkiaTypeface.register(e))}static initializeMusicFont(e){xo.musicFont=e}static registerFont(e,t){const i=xo.alphaSkia.AlphaSkiaTypeface.register(e.buffer);t||(t=Ri.withFamilyList([i.familyName],12,i.isItalic?Ve.Italic:Ve.Plain,i.isBold?He.Bold:He.Regular));for(const e of t.families)this.customTypeFaces.set(xo.customTypefaceKey(e,t.isBold,t.isItalic),i);return t}static customTypefaceKey(e,t,i){return e.toLowerCase()+"_"+t+"_"+i}getTypeFace(){if(this._typeFaceCache!=this.font.toCssString(this.settings.display.scale)){if(this._typeFaceIsSystem){const e={stack:[],error:void 0,hasError:!1};try{To(e,this._typeFace,!1)}catch(t){e.error=t,e.hasError=!0}finally{vo(e)}}for(const t of this.font.families){var e=xo.customTypefaceKey(t,this.font.isBold,this.font.isItalic);xo.customTypeFaces.has(e)?(this._typeFaceIsSystem=!1,this._typeFace=xo.customTypeFaces.get(e)):(this._typeFaceIsSystem=!0,this._typeFace=xo.alphaSkia.AlphaSkiaTypeface.create(t,this.font.isBold,this.font.isItalic))}this._typeFaceCache=this.font.toCssString(this.settings.display.scale)}return this._typeFace}constructor(){this._color=new me(0,0,0,0),this._lineWidth=0,this._typeFaceCache="",this._typeFaceIsSystem=!1,this._typeFace=null,this.font=new Ri("Arial",10,Ve.Plain),this.textAlign=E.Left,this.textBaseline=C.Top,this._canvas=new xo.alphaSkia.AlphaSkiaCanvas,this.color=new me(0,0,0,255)}destroy(){const e={stack:[],error:void 0,hasError:!1};try{To(e,this._canvas,!1)}catch(t){e.error=t,e.hasError=!0}finally{vo(e)}}onRenderFinished(){return null}beginRender(e,t){this._canvas.beginRender(e,t,Eo.HighDpiFactor)}endRender(){return this._canvas.endRender()}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._canvas.color=xo.alphaSkia.AlphaSkiaCanvas.rgbaToColor(e.r,e.g,e.b,e.a))}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._canvas.lineWidth=e}fillRect(e,t,i,s){i>0&&this._canvas.fillRect(0|e,0|t,i,s)}strokeRect(e,t,i,s){this._canvas.strokeRect(0|e,0|t,i,s)}beginPath(){this._canvas.beginPath()}closePath(){this._canvas.closePath()}moveTo(e,t){this._canvas.moveTo(e,t)}lineTo(e,t){this._canvas.lineTo(e,t)}quadraticCurveTo(e,t,i,s){this._canvas.quadraticCurveTo(e,t,i,s)}bezierCurveTo(e,t,i,s,a,r){this._canvas.bezierCurveTo(e,t,i,s,a,r)}fillCircle(e,t,i){this._canvas.fillCircle(e,t,i)}strokeCircle(e,t,i){this._canvas.strokeCircle(e,t,i)}fill(){this._canvas.fill()}stroke(){this._canvas.stroke()}beginGroup(e){}endGroup(){}fillText(e,t,i){if(0==e.length)return;let s=xo.alphaSkia.AlphaSkiaTextAlign.Left;switch(this.textAlign){case E.Left:s=xo.alphaSkia.AlphaSkiaTextAlign.Left;break;case E.Center:s=xo.alphaSkia.AlphaSkiaTextAlign.Center;break;case E.Right:s=xo.alphaSkia.AlphaSkiaTextAlign.Right}let a=xo.alphaSkia.AlphaSkiaTextBaseline.Top;switch(this.textBaseline){case C.Top:a=xo.alphaSkia.AlphaSkiaTextBaseline.Top;break;case C.Middle:a=xo.alphaSkia.AlphaSkiaTextBaseline.Middle;break;case C.Bottom:a=xo.alphaSkia.AlphaSkiaTextBaseline.Bottom}this._canvas.fillText(e,this.getTypeFace(),this.font.size*this.settings.display.scale,t,i,s,a)}measureText(e){return this._canvas.measureText(e,this.getTypeFace(),this.font.size*this.settings.display.scale)}fillMusicFontSymbol(e,t,i,s,a){s!==P.None&&this.fillMusicFontSymbolText(e,t,i,String.fromCharCode(s),a)}fillMusicFontSymbols(e,t,i,s,a){let r="";for(let e of s)e!==P.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,i,r,a)}fillMusicFontSymbolText(e,t,i,s,a){this._canvas.fillText(s,xo.musicFont,Eo.MusicFontSize*this.settings.display.scale*i,e,t,a?xo.alphaSkia.AlphaSkiaTextAlign.Center:xo.alphaSkia.AlphaSkiaTextAlign.Left,xo.alphaSkia.AlphaSkiaTextBaseline.Alphabetic)}beginRotate(e,t,i){this._canvas.beginRotate(e,t,i)}endRotate(){this._canvas.endRotate()}}xo.musicFont=null,xo.customTypeFaces=new Map;class No{constructor(e,t){this.vertical=e,this.createLayout=t}}class Po{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class Eo{static createStyleElement(e,t){let i=e.getElementById("alphaTabStyle");if(!i){if(!t)return void J.error("AlphaTab","Font directory could not be detected, cannot create style element");i=e.createElement("style"),i.id="alphaTabStyle";let s=`\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: ${Eo.MusicFontSize}px;\n overflow: visible !important;\n }`;i.innerHTML=s,e.getElementsByTagName("head").item(0).appendChild(i),Eo.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===Eo._globalThis){try{Eo._globalThis=globalThis}catch(e){}void 0===Eo._globalThis&&(Eo._globalThis=self),void 0===Eo._globalThis&&(Eo._globalThis=global),void 0===Eo._globalThis&&(Eo._globalThis=window),void 0===Eo._globalThis&&(Eo._globalThis=Function("return this")())}return this._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in Eo.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in Eo.globalThis}static throttle(e,t){let i=0;return()=>{Eo.globalThis.clearTimeout(i),i=Eo.globalThis.setTimeout(e,t)}}static detectScriptFile(){if(!Eo.isRunningInWorker&&Eo.globalThis.ALPHATAB_ROOT){let e=Eo.globalThis.ALPHATAB_ROOT;return e=Eo.ensureFullUrl(e),e=Eo.appendScriptName(e),e}try{const e={};if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in Eo.globalThis&&document.currentScript?document.currentScript.src:null}static ensureFullUrl(e){if(!e)return"";if(!e.startsWith("http")&&!e.startsWith("https")&&!e.startsWith("file")){let t="",i=Eo.globalThis.location;if(t+=i.protocol?.toString(),t+="//"?.toString(),i.hostname&&(t+=i.hostname?.toString()),i.port&&(t+=":"?.toString(),t+=i.port?.toString()),!e.startsWith("/")){let e=i.pathname.split("/").slice(0,-1).join("/");e.length>0&&(e.startsWith("/")||(t+="/"?.toString()),t+=e?.toString())}return e.startsWith("/")||(t+="/"?.toString()),t+=e?.toString(),t}return e}static appendScriptName(e){return e&&!e.endsWith(".js")&&(e.endsWith("/")||(e+="/"),e+="alphaTab.js"),e}static detectFontDirectory(){if(!Eo.isRunningInWorker&&Eo.globalThis.ALPHATAB_FONT)return Eo.ensureFullUrl(Eo.globalThis.ALPHATAB_FONT);const e=Eo.scriptFile;if(e){let t=e.lastIndexOf(String.fromCharCode(47));if(t>=0)return e.substr(0,t)+"/font/"}return null}static registerJQueryPlugin(){if(!Eo.isRunningInWorker&&Eo.globalThis&&"jQuery"in Eo.globalThis){let e=Eo.globalThis.jQuery,t=new ma;e.fn.alphaTab=function(e){const i=Array.prototype.slice.call(arguments,1);return 1===this.length?t.exec(this[0],e,i):this.each(((s,a)=>{t.exec(a,e,i)}))},e.alphaTab={restore:ma.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&Eo.renderEngines.has(e)?Eo.renderEngines.get(e):Eo.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&Eo.layoutEngines.has(t)?Eo.layoutEngines.get(t):Eo.layoutEngines.get(e.LayoutMode.Page)}static buildImporters(){return[new st,new It,new Et,new Dt,new wo,new it]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new Po(!0,(()=>new ba))),e.set("default",e.get("svg")),e.set("skia",new Po(!1,(()=>new xo))),Eo.createPlatformSpecificRenderEngines(e),e}static enableAlphaSkia(e,t){xo.enable(e,t)}static registerAlphaSkiaCustomFont(e,t){return xo.registerFont(e,t)}static createPlatformSpecificRenderEngines(e){e.set("html5",new Po(!1,(()=>new Cs)))}static createDefaultStaveProfiles(){const t=new Map;t.set(e.StaveProfile.ScoreTab,[new tr("score-effects",[new Ar,new Hr,new Tr,new Rr,new nr,new fr,new Wr,new Gr,new vr(!0),new zr,new Fr,new Ur,new Mr,new ao,new ar]),new Wn,new tr("tab-effects",[new lr,new vr(!1),new dr,new Br,new Gr,new zr,new Fr,new Ur,new Mr,new Ir,new pr,new Sr(y.Natural),new Sr(y.Artificial),new Sr(y.Pinch),new Sr(y.Tap),new Sr(y.Semi),new Sr(y.Feedback),new wr,new rr,new mr,new xr,new Er,new Nr,new ao]),new io(!1,!1,!1)]),t.set(e.StaveProfile.Score,[new tr("score-effects",[new Ar,new Hr,new Tr,new Rr,new nr,new fr,new Wr,new Gr,new vr(!0),new zr,new Fr,new Ur,new Mr,new pr,new wr,new xr,new Er,new Nr,new ao,new ar]),new Wn,new tr("score-bottom-effects",[new lr,new vr(!1),new dr,new Br])]);let i=[new Ar,new Hr,new Tr,new Rr,new nr,new fr,new Gr,new zr,new Fr,new Ur,new Mr,new Ir,new pr,new Sr(y.Artificial),new Sr(y.Pinch),new Sr(y.Tap),new Sr(y.Semi),new Sr(y.Feedback),new wr,new rr,new mr,new xr,new Er,new Nr,new ao,new ar];return t.set(e.StaveProfile.Tab,[new tr("tab-effects",i),new io(!0,!0,!0),new tr("tab-bottom-effects",[new Br])]),t.set(e.StaveProfile.TabMixed,[new tr("tab-effects",i),new io(!1,!1,!1),new tr("tab-bottom-effects",[new Br])]),t}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.LayoutMode.Page,new No(!0,(e=>new qr(e)))),t.set(e.LayoutMode.Horizontal,new No(!1,(e=>new Yr(e)))),t}static initializeMain(t,i){Eo.isRunningInWorker||Eo.isRunningInAudioWorklet||(Eo.webPlatform!==e.WebPlatform.Browser&&Eo.webPlatform!==e.WebPlatform.BrowserModule||(Eo.registerJQueryPlugin(),Eo.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in Eo.globalThis||(Eo.globalThis.ResizeObserver=_o),"IntersectionObserver"in Eo.globalThis||(Eo.globalThis.IntersectionObserver=Bo),"replaceChildren"in Element.prototype||(Element.prototype.replaceChildren=function(...e){this.innerHTML="",this.append(...e)},Document.prototype.replaceChildren=Element.prototype.replaceChildren,DocumentFragment.prototype.replaceChildren=Element.prototype.replaceChildren),"replaceAll"in String.prototype||(String.prototype.replaceAll=function(e,t){return this.replace(new RegExp(e,"g"),t)})),Eo.createWebWorker=t,Eo.createAudioWorklet=i)}static get alphaTabWorker(){return this.globalThis.Worker}static initializeWorker(){if(!Eo.isRunningInWorker)throw new G(e.AlphaTabErrorType.General,"Not running in worker, cannot run worker initialization");Es.init(),Ss.init(),Eo.createWebWorker=t=>{throw new G(e.AlphaTabErrorType.General,"Nested workers are not supported")}}static initializeAudioWorklet(){if(!Eo.isRunningInAudioWorklet)throw new G(e.AlphaTabErrorType.General,"Not running in audio worklet, cannot run worklet initialization");da.init()}static detectWebPack(){try{if("function"==typeof __webpack_require__)return!0}catch(e){}return!1}static detectVite(){try{if("string"==typeof __BASE__)return!0}catch(e){}return!1}static detectWebPlatform(){try{if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return e.WebPlatform.NodeJs}catch(e){}try{const t={};if(t&&"string"==typeof t&&!t.startsWith("file://"))return e.WebPlatform.BrowserModule}catch(e){}return e.WebPlatform.Browser}}Eo.MusicFontSize=34,Eo.HighDpiFactor=1,Eo._globalThis=void 0,Eo.webPlatform=Eo.detectWebPlatform(),Eo.isWebPackBundled=Eo.detectWebPack(),Eo.isViteBundled=Eo.detectVite(),Eo.scriptFile=Eo.detectScriptFile(),Eo.fontDirectory=Eo.detectFontDirectory(),Eo.bravuraFontChecker=new sa(["alphaTab"]),Eo.renderEngines=Eo.createDefaultRenderEngines(),Eo.layoutEngines=Eo.createDefaultLayoutEngines(),Eo.staveProfiles=Eo.createDefaultStaveProfiles();class Co{constructor(){this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=e.LogLevel.Info,this.useWorkers=!0,this.includeNoteBounds=!1,this.scriptFile=Eo.scriptFile,this.fontDirectory=Eo.fontDirectory}}class Fo{}Fo.version="1.3.1",Fo.date="2024-06-15T16:02:03.898Z";var Lo,Mo=Object.freeze({__proto__:null,ScoreImporter:O,ScoreLoader:ea,UnsupportedFormatError:V});class Io{init(e,t){this.data=e,this.settings=t}export(e,t=null){const i=ke.withCapacity(1024);return this.init(i,t??new Zi),this.writeScore(e),i.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"}(Lo||(Lo={}));class Do{constructor(e,t,i=null){if(this.icon=Lo.Piano,this.icon=e,this.instrumentSetName=t,i)this.instrumentSetType=i;else{const e=t.split(" ");e[0]=e[0].substr(0,1).toLowerCase()+e[0].substr(1),this.instrumentSetType=e.join("")}}}class Ao{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new pt;return this._rhythmIdLookup=new Map,this.writeDom(t,e),t.toFormattedString("",!0)}writeDom(e,t){const i=e.addElement("GPIF");i.addElement("GPVersion").innerText="7";const s=i.addElement("GPRevision");s.innerText="7",s.attributes.set("required","12021"),s.attributes.set("recommended","12023"),s.innerText="12025",i.addElement("Encoding").addElement("EncodingDescription").innerText="GP7",this.writeScoreNode(i,t),this.writeMasterTrackNode(i,t),this.writeAudioTracksNode(i,t),this.writeTracksNode(i,t),this.writeMasterBarsNode(i,t);const a=i.addElement("Bars"),r=i.addElement("Voices"),n=i.addElement("Beats"),o=i.addElement("Notes"),h=i.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 i=e.addElement("Note");i.attributes.set("id",t.id.toString()),this.writeNoteProperties(i,t),t.isGhost&&(i.addElement("AntiAccent").innerText="normal"),t.isLetRing&&i.addElement("LetRing"),t.isTrill&&(i.addElement("Trill").innerText=t.trillValue.toString());let s=0;switch(t.isStaccato&&(s|=1),t.accentuated){case a.Normal:s|=8;break;case a.Heavy:s|=4}if(s>0&&(i.addElement("Accent").innerText=s.toString()),t.isTieOrigin||t.isTieDestination){const e=i.addElement("Tie");e.attributes.set("origin",t.isTieOrigin?"true":"false"),e.attributes.set("destination",t.isTieDestination?"true":"false")}switch(t.vibrato){case _.Slight:i.addElement("Vibrato").innerText="Slight";break;case _.Wide:i.addElement("Vibrato").innerText="Wide"}if(t.isFingering){switch(t.leftHandFinger){case m.Thumb:i.addElement("LeftFingering").innerText="P";break;case m.IndexFinger:i.addElement("LeftFingering").innerText="I";break;case m.MiddleFinger:i.addElement("LeftFingering").innerText="M";break;case m.AnnularFinger:i.addElement("LeftFingering").innerText="A";break;case m.LittleFinger:i.addElement("LeftFingering").innerText="C"}switch(t.rightHandFinger){case m.Thumb:i.addElement("RightFingering").innerText="P";break;case m.IndexFinger:i.addElement("RightFingering").innerText="I";break;case m.MiddleFinger:i.addElement("RightFingering").innerText="M";break;case m.AnnularFinger:i.addElement("RightFingering").innerText="A";break;case m.LittleFinger:i.addElement("RightFingering").innerText="C"}}t.percussionArticulation>=0?i.addElement("InstrumentArticulation").innerText=t.percussionArticulation.toString():i.addElement("InstrumentArticulation").innerText="0"}writeNoteProperties(e,t){const i=e.addElement("Properties");if(this.writeConcertPitch(i,t),this.writeTransposedPitch(i,t),t.isStringed&&(this.writeSimplePropertyNode(i,"String","String",(t.string-1).toString()),this.writeSimplePropertyNode(i,"Fret","Fret",t.fret.toString()),this.writeSimplePropertyNode(i,"Midi","Number",t.realValue.toString())),t.isPiano&&(this.writeSimplePropertyNode(i,"Octave","Number",t.octave.toString()),this.writeSimplePropertyNode(i,"Tone","Step",t.tone.toString()),this.writeSimplePropertyNode(i,"Midi","Number",t.realValue.toString())),t.beat.tap&&this.writeSimplePropertyNode(i,"Tapped","Enable",null),t.harmonicType!==y.None){switch(t.harmonicType){case y.Natural:this.writeSimplePropertyNode(i,"HarmonicType","HType","Natural");break;case y.Artificial:this.writeSimplePropertyNode(i,"HarmonicType","HType","Artificial");break;case y.Pinch:this.writeSimplePropertyNode(i,"HarmonicType","HType","Pinch");break;case y.Tap:this.writeSimplePropertyNode(i,"HarmonicType","HType","Tap");break;case y.Semi:this.writeSimplePropertyNode(i,"HarmonicType","HType","Semi");break;case y.Feedback:this.writeSimplePropertyNode(i,"HarmonicType","HType","Feedback")}0!==t.harmonicValue&&this.writeSimplePropertyNode(i,"HarmonicFret","HFret",t.harmonicValue.toString())}t.isDead&&this.writeSimplePropertyNode(i,"Muted","Enable",null),t.isPalmMute&&this.writeSimplePropertyNode(i,"PalmMuted","Enable",null),t.hasBend&&this.writeBend(i,t),t.isHammerPullOrigin&&this.writeSimplePropertyNode(i,"HopoOrigin","Enable",null),t.isHammerPullDestination&&this.writeSimplePropertyNode(i,"HopoDestination","Enable",null),t.isLeftHandTapped&&this.writeSimplePropertyNode(i,"LeftHandTapped","Enable",null);let s=0;switch(t.slideInType){case S.IntoFromAbove:s|=32;break;case S.IntoFromBelow:s|=16}switch(t.slideOutType){case w.Shift:s|=1;break;case w.Legato:s|=2;break;case w.OutDown:s|=4;break;case w.OutUp:s|=8;break;case w.PickSlideDown:s|=64;break;case w.PickSlideUp:s|=128}s>0&&this.writeSimplePropertyNode(i,"Slide","Flags",s.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,i,s){let a=0,r=0,n="",o="";const h=()=>{a=i%12,r=i/12|0,n=be.defaultSteps[a],o=be.defaultAccidentals[a]};switch(h(),s){case b.Default:break;case b.ForceNone:case b.ForceNatural:o="";break;case b.ForceSharp:o="#";break;case b.ForceDoubleSharp:"#"===o&&(i-=2,h()),o="x";break;case b.ForceFlat:"#"===o&&(i+=1,h()),o="b";break;case b.ForceDoubleFlat:"#"===o&&(i+=2,h()),o="bb"}this.writePitch(e,t,n,r.toString(),o)}writePitch(e,t,i,s,a){const r=e.addElement("Property");r.attributes.set("name",t);const n=r.addElement("Pitch");n.addElement("Step").innerText=i,n.addElement("Accidental").innerText=a,n.addElement("Octave").innerText=s}writeBend(e,t){t.hasBend&&t.bendPoints.length<=4&&this.writeStandardBend(e,t.bendPoints)}writeStandardBend(e,t){this.writeSimplePropertyNode(e,"Bended","Enable",null);var i,s,a=t[0],r=t[t.length-1];switch(t.length){case 4:i=t[1],s=t[2];break;case 3:i=t[1],s=t[1];break;default:s=i=new U((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(i.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset2","Float",this.toBendOffset(s.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleValue","Float",this.toBendValue(i.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/U.MaxPosition*100}writeBeatNode(e,t,i){const s=e.addElement("Beat");if(s.attributes.set("id",t.id.toString()),s.addElement("Dynamic").innerText=g[t.dynamics],t.fadeIn&&(s.addElement("Fadding").innerText="FadeIn"),t.isTremolo)switch(t.tremoloSpeed){case p.Eighth:s.addElement("Tremolo").innerText="1/2";break;case p.Sixteenth:s.addElement("Tremolo").innerText="1/4";break;case p.ThirtySecond:s.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&s.addElement("Chord").setCData(t.chordId),t.crescendo!==u.None&&(s.addElement("Hairpin").innerText=u[t.crescendo]),t.brushType){case d.ArpeggioUp:s.addElement("Arpeggio").innerText="Up";break;case d.ArpeggioDown:s.addElement("Arpeggio").innerText="Down"}switch(t.text&&s.addElement("FreeText").setCData(t.text),t.graceType){case f.OnBeat:case f.BeforeBeat:s.addElement("GraceNotes").innerText=f[t.graceType]}if(t.ottava!==o.Regular&&(s.addElement("Ottavia").innerText=o[t.ottava].substr(1)),t.hasWhammyBar&&this.writeWhammyNode(s,t),t.isLegatoOrigin||t.isLegatoDestination){const e=s.addElement("Legato");e.attributes.set("origin",t.isLegatoOrigin?"true":"false"),e.attributes.set("destination",t.isLegatoDestination?"true":"false")}if(this.writeRhythm(s,t,i),null!==t.preferredBeamDirection)switch(t.preferredBeamDirection){case Ce.Up:s.addElement("TransposedPitchStemOrientation").innerText="Upward";break;case Ce.Down:s.addElement("TransposedPitchStemOrientation").innerText="Downward"}s.addElement("ConcertPitchStemOrientation").innerText="Undefined",t.isRest||(s.addElement("Notes").innerText=t.notes.map((e=>e.id)).join(" ")),this.writeBeatProperties(s,t),this.writeBeatXProperties(s,t),t.lyrics&&t.lyrics.length>0&&this.writeBeatLyrics(s,t.lyrics)}writeBeatLyrics(e,t){const i=e.addElement("Lyrics");for(const e of t){i.addElement("Line").setCData(e)}}writeBeatXProperties(e,t){const i=e.addElement("XProperties");t.brushDuration>0&&this.writeSimpleXPropertyNode(i,"687935489","Int",t.brushDuration.toString())}writeBeatProperties(e,t){const i=e.addElement("Properties");switch(t.brushType){case d.BrushUp:this.writeSimplePropertyNode(i,"Brush","Direction","Up");break;case d.BrushDown:this.writeSimplePropertyNode(i,"Brush","Direction","Down")}switch(t.pickStroke){case N.Up:this.writeSimplePropertyNode(i,"PickStroke","Direction","Up");break;case N.Down:this.writeSimplePropertyNode(i,"PickStroke","Direction","Down")}switch(t.slap&&this.writeSimplePropertyNode(i,"Slapped","Enable",null),t.pop&&this.writeSimplePropertyNode(i,"Popped","Enable",null),t.vibrato){case _.Wide:this.writeSimplePropertyNode(i,"VibratoWTremBar","Strength","Wide");break;case _.Slight:this.writeSimplePropertyNode(i,"VibratoWTremBar","Strength","Slight")}}writeRhythm(e,t,i){const s=`${t.duration}_${t.dots}_${t.tupletNumerator}_${t.tupletDenominator}';`;let a;if(this._rhythmIdLookup.has(s))a=this._rhythmIdLookup.get(s);else{a=this._rhythmIdLookup.size.toString(),this._rhythmIdLookup.set(s,a);const e=i.addElement("Rhythm");if(e.attributes.set("id",a),t.hasTuplet){const i=e.addElement("PrimaryTuplet");i.attributes.set("num",t.tupletNumerator.toString()),i.attributes.set("den",t.tupletDenominator.toString())}t.dots>0&&e.addElement("AugmentationDot").attributes.set("count",t.dots.toString());let r="Quarter";switch(t.duration){case p.QuadrupleWhole:r="Long";break;case p.DoubleWhole:r="DoubleWhole";break;case p.Whole:r="Whole";break;case p.Half:r="Half";break;case p.Quarter:r="Quarter";break;case p.Eighth:r="Eighth";break;case p.Sixteenth:r="16th";break;case p.ThirtySecond:r="32nd";break;case p.SixtyFourth:r="64th";break;case p.OneHundredTwentyEighth:r="128th";break;case p.TwoHundredFiftySixth:r="256th"}e.addElement("NoteValue").innerText=r}e.addElement("Rhythm").attributes.set("ref",a)}writeWhammyNode(e,t){t.hasWhammyBar&&t.whammyBarPoints.length<=4&&this.writeStandardWhammy(e,t.whammyBarPoints)}writeStandardWhammy(e,t){const i=e.addElement("Whammy");var s,a,r=t[0],n=t[t.length-1];switch(t.length){case 4:s=t[1],a=t[2];break;case 3:s=t[1],a=t[1];break;default:a=s=new U((r.offset+n.offset)/2,(r.value+n.value)/2)}i.attributes.set("destinationOffset",this.toBendOffset(n.offset).toString()),i.attributes.set("destinationValue",this.toBendValue(n.value).toString()),i.attributes.set("middleOffset1",this.toBendOffset(s.offset).toString()),i.attributes.set("middleOffset2",this.toBendOffset(a.offset).toString()),i.attributes.set("middleValue",this.toBendValue(s.value).toString()),i.attributes.set("originOffset",this.toBendOffset(r.offset).toString()),i.attributes.set("originValue",this.toBendValue(r.value).toString())}writeScoreNode(e,t){const i=e.addElement("Score");i.addElement("Title").setCData(t.title),i.addElement("SubTitle").setCData(t.subTitle),i.addElement("Artist").setCData(t.artist),i.addElement("Album").setCData(t.album),i.addElement("Words").setCData(t.words),i.addElement("Music").setCData(t.music),i.addElement("WordsAndMusic").setCData(t.words===t.music?t.words:""),i.addElement("Copyright").setCData(t.copyright),i.addElement("Tabber").setCData(t.tab),i.addElement("Instructions").setCData(t.instructions),i.addElement("Notices").setCData(t.notices),i.addElement("FirstPageHeader").setCData(""),i.addElement("FirstPageFooter").setCData(""),i.addElement("PageHeader").setCData(""),i.addElement("PageFooter").setCData(""),i.addElement("ScoreSystemsDefaultLayout").setCData(t.defaultSystemsLayout.toString()),i.addElement("ScoreSystemsLayout").setCData(t.systemsLayout.join(" ")),i.addElement("ScoreZoomPolicy").innerText="Value",i.addElement("ScoreZoom").innerText="1",i.addElement("MultiVoice").innerText="1>"}writeMasterTrackNode(e,t){const i=e.addElement("MasterTrack");i.addElement("Tracks").innerText=t.tracks.map((e=>e.index)).join(" ");const s=i.addElement("Automations");t.masterBars.length>0&&t.masterBars[0].isAnacrusis&&i.addElement("Anacrusis");const a=s.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=s.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 i=e.addElement("Tracks");for(const e of t.tracks)this.writeTrackNode(i,e)}writeTrackNode(e,t){const i=e.addElement("Track");i.attributes.set("id",t.index.toString()),i.addElement("Name").setCData(t.name),i.addElement("ShortName").setCData(t.shortName),i.addElement("Color").innerText=`${t.color.r} ${t.color.g} ${t.color.b}`,i.addElement("SystemsDefautLayout").innerText=t.defaultSystemsLayout.toString(),i.addElement("SystemsLayout").innerText=t.systemsLayout.join(" "),i.addElement("AutoBrush"),i.addElement("PalmMute").innerText="0",i.addElement("PlayingStyle").innerText=R.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",i.addElement("UseOneChannelPerString"),i.addElement("IconId").innerText=Ao.getIconId(t.playbackInfo).toString(),this.writeInstrumentSetNode(i,t),this.writeTransposeNode(i,t),this.writeRseNode(i,t),i.addElement("ForcedSound").innerText="-1",this.writeMidiConnectionNode(i,t),t.playbackInfo.isSolo?i.addElement("PlaybackState").innerText="Solo":t.playbackInfo.isMute?i.addElement("PlaybackState").innerText="Mute":i.addElement("PlaybackState").innerText="Default",i.addElement("AudioEngineState").innerText="MIDI",this.writeLyricsNode(i,t),this.writeStavesNode(i,t),this.writeSoundsAndAutomations(i,t)}static getIconId(e){return 9===e.primaryChannel?Ao.DrumKitProgramInfo.icon:Ao.MidiProgramInfoLookup.has(e.program)?Ao.MidiProgramInfoLookup.get(e.program).icon:Lo.SteelGuitar}writeSoundAndAutomation(e,t,i,s,a,r,n,o=0){const h=e.addElement("Sound");h.addElement("Name").setCData(i),h.addElement("Label").setCData(i),h.addElement("Path").setCData(s),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(`${s};${i};${a}`)}writeSoundsAndAutomations(e,t){const i=e.addElement("Sounds"),s=e.addElement("Automations");if(t.staves.length>0&&t.staves[0].bars.length>0){const e=`Track_${t.index}_Initial`,a=`Midi/${t.playbackInfo.program}`,n="Factory";let o=!1;for(const h of t.staves)for(const l of h.bars)for(const h of l.voices)for(const c of h.beats){const h=c.getAutomation(r.Instrument),d=0===l.index&&0===c.index;if(h){const r=d?e:`ProgramChange_${c.id}`,u=d?a:`Midi/${h.value}`,p=d?n:"User";d||o||(this.writeSoundAndAutomation(i,s,e,a,n,t.staves[0].bars[0].index,t.playbackInfo.program),o=!0),this.writeSoundAndAutomation(i,s,r,u,p,l.index,h.value,h.ratioPosition),d&&(o=!0)}}}}writeMidiConnectionNode(e,t){const i=e.addElement("MidiConnection");i.addElement("Port").innerText=t.playbackInfo.port.toString(),i.addElement("PrimaryChannel").innerText=t.playbackInfo.primaryChannel.toString(),i.addElement("SecondaryChannel").innerText=t.playbackInfo.secondaryChannel.toString(),i.addElement("ForeOneChannelPerString").innerText="false"}writeRseNode(e,t){const i=e.addElement("RSE").addElement("ChannelStrip");i.attributes.set("version","E56");i.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 i=e.addElement("Staves");for(const e of t.staves)this.writeStaffNode(i,e)}writeStaffNode(e,t){const i=e.addElement("Staff").addElement("Properties");if(this.writeSimplePropertyNode(i,"CapoFret","Fret",t.capo.toString()),this.writeSimplePropertyNode(i,"FretCount","Fret","24"),t.tuning.length>0){const e=i.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(i,"PartialCapoFret","Fret","0"),this.writeSimplePropertyNode(i,"PartialCapoStringFlags","Bitset",t.tuning.map((e=>"0")).join("")),this.writeSimplePropertyNode(i,"TuningFlat","Enable",null),this.writeDiagramCollection(i,t,"DiagramCollection"),this.writeDiagramCollection(i,t,"DiagramWorkingSet")}writeDiagramCollection(e,t,i){const s=e.addElement("Property");s.attributes.set("name",i);const a=s.addElement("Items"),r=t.chords;if(r)for(const[e,t]of r){const i=a.addElement("Item");i.attributes.set("id",e),i.attributes.set("name",t.name);const s=i.addElement("Diagram");s.attributes.set("stringCount",t.strings.length.toString()),s.attributes.set("fretCount","5"),s.attributes.set("baseFret",(t.firstFret-1).toString()),s.attributes.set("barStates",t.strings.map((e=>"1")).join(" "));const r=[],n=new Map;for(let e=0;e<t.strings.length;e++){let i=t.strings[e];if(-1!==i){const a=s.addElement("Fret"),o=t.strings.length-1-e;a.attributes.set("string",o.toString()),a.attributes.set("fret",(i-t.firstFret+1).toString()),n.has(i)||(n.set(i,[]),r.push(i)),n.get(i).push(o)}}r.sort();const o=s.addElement("Fingering");if(t.barreFrets.length>0){const e=[m.LittleFinger,m.AnnularFinger,m.MiddleFinger,m.IndexFinger];for(const i of r){const s=n.get(i);if(s.length>1&&t.barreFrets.indexOf(i)>=0){const a=e.length>0?e.pop():m.IndexFinger;for(const e of s){const s=o.addElement("Position");switch(a){case m.LittleFinger:s.attributes.set("finger","Pinky");break;case m.AnnularFinger:s.attributes.set("finger","Ring");break;case m.MiddleFinger:s.attributes.set("finger","Middle");break;case m.IndexFinger:s.attributes.set("finger","Index")}s.attributes.set("fret",(i-t.firstFret+1).toString()),s.attributes.set("string",e.toString())}}}}const h=s.addElement("Property");h.attributes.set("name","ShowName"),h.attributes.set("type","bool"),h.attributes.set("value",t.showName?"true":"false");const l=s.addElement("Property");l.attributes.set("name","ShowDiagram"),l.attributes.set("type","bool"),l.attributes.set("value",t.showDiagram?"true":"false");const c=s.addElement("Property");c.attributes.set("name","ShowFingering"),c.attributes.set("type","bool"),c.attributes.set("value",t.showFingering?"true":"false");const d=s.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 f=d.addElement("Degree");f.attributes.set("interval","Fifth"),f.attributes.set("alteration","Perfect"),f.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,i,s){const a=e.addElement("Property");a.attributes.set("name",t);const r=a.addElement(i);return null!==s&&(r.innerText=s),a}writeSimpleXPropertyNode(e,t,i,s){const a=e.addElement("XProperty");a.attributes.set("id",t);const r=a.addElement(i);return null!==s&&(r.innerText=s),a}writeLyricsNode(e,t){const i=e.addElement("Lyrics");i.attributes.set("dispatched","true");let s=[];for(const e of t.staves[0].bars)for(const t of e.voices)if(!t.isEmpty)for(const i of t.beats)if(i.lyrics)for(let t=0;t<i.lyrics.length;t++){for(;t>=s.length;){const t=new le;t.startBar=e.index,t.text="[Empty]",s.push(t)}const a=s[t];a.text="[Empty]"==a.text?i.lyrics[t]:a.text+" "+i.lyrics[t].split(" ").join("+")}for(let e=0;e<s.length;e++){const t=i.addElement("Line");t.addElement("Text").setCData(s[e].text),t.addElement("Offset").innerText=s[e].startBar.toString()}}writeTransposeNode(e,t){const i=e.addElement("Transpose"),s=Math.floor(t.staves[0].displayTranspositionPitch/12),a=t.staves[0].displayTranspositionPitch-12*s;i.addElement("Chromatic").innerText=a.toString(),i.addElement("Octave").innerText=s.toString()}writeInstrumentSetNode(e,t){const i=e.addElement("InstrumentSet"),s=t.staves[0];if(i.addElement("LineCount").innerText=s.standardNotationLineCount.toString(),t.percussionArticulations.length>0||s.isPercussion){const e=t.percussionArticulations.length>0?t.percussionArticulations:Array.from(K.instrumentArticulations.values());i.addElement("Name").innerText=Ao.DrumKitProgramInfo.instrumentSetName,i.addElement("Type").innerText=Ao.DrumKitProgramInfo.instrumentSetType;let s="",r=new lt,n=new Map;const o=i.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);s=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=s+" "+r.childNodes.length,e.addElement("StaffLine").innerText=t.staffLine.toString(),e.addElement("Noteheads").innerText=[this.mapMusicSymbol(t.noteHeadDefault),this.mapMusicSymbol(t.noteHeadHalf),this.mapMusicSymbol(t.noteHeadWhole)].join(" "),t.techniqueSymbolPlacement){case C.Top:e.addElement("TechniquePlacement").innerText="below";break;case C.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case C.Bottom:e.addElement("TechniquePlacement").innerText="above"}e.addElement("TechniqueSymbol").innerText=this.mapMusicSymbol(t.techniqueSymbol),e.addElement("InputMidiNumbers").innerText="",e.addElement("OutputMidiNumber").innerText=t.outputMidiNumber.toString()}}else{const e=Ao.MidiProgramInfoLookup.has(t.playbackInfo.program)?Ao.MidiProgramInfoLookup.get(t.playbackInfo.program):Ao.MidiProgramInfoLookup.get(0);i.addElement("Name").innerText=e.instrumentSetName,i.addElement("Type").innerText=e.instrumentSetType;const s=i.addElement("Elements").addElement("Element");s.addElement("Pitched").innerText="Pitched",s.addElement("Type").innerText="pitched",s.addElement("SoundbankName").innerText="";const a=s.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===P.None)return"";let t=P[e];return t.substring(0,1).toLowerCase()+t.substring(1)}writeMasterBarsNode(e,t){const i=e.addElement("MasterBars");for(const e of t.masterBars)this.writeMasterBarNode(i,e)}writeMasterBarNode(e,t){const i=e.addElement("MasterBar"),s=i.addElement("Key");s.addElement("AccidentalCount").innerText=t.keySignature.toString(),s.addElement("Mode").innerText=D[t.keySignatureType],s.addElement("Sharps").innerText="Sharps",i.addElement("Time").innerText=`${t.timeSignatureNumerator}/${t.timeSignatureDenominator}`;let a=[];for(const e of t.score.tracks)for(const i of e.staves)a.push(i.bars[t.index].id.toString());if(i.addElement("Bars").innerText=a.join(" "),t.isDoubleBar&&i.addElement("DoubleBar"),t.isSectionStart){const e=i.addElement("Section");e.addElement("Letter").setCData(t.section.marker),e.addElement("Text").setCData(t.section.text)}if(t.isRepeatStart||t.isRepeatEnd){const e=i.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 s=[];let a=0;for(;e>0;)1==(e>>a&1)&&(s.push(a+1),e&=~(1<<a)),a++;i.addElement("AlternateEndings").innerText=s.join(" ")}t.tripletFeel!==A.NoTripletFeel&&(i.addElement("TripletFeel").innerText=A[t.tripletFeel]),this.writeFermatas(i,t)}writeFermatas(e,t){const i=t.fermata?.size??0;if(0!==i&&i>0){const i=e.addElement("Fermatas");for(const[e,s]of t.fermata)this.writeFermata(i,e,s)}}writeFermata(e,t,i){let s=-1,a=1;if(t>0)for(;a<10&&(s=t/z.QuarterTime*a,s!==Math.floor(s));)s=-1,a++;else s=0,a=1;if(-1===s)return;const r=e.addElement("Fermata");r.addElement("Type").innerText=Ne[i.type],r.addElement("Length").innerText=i.length.toString(),r.addElement("Offset").innerText=`${s}/${a}`}writeBarNode(e,t){const i=e.addElement("Bar");i.attributes.set("id",t.id.toString()),i.addElement("Voices").innerText=t.voices.map((e=>e.isEmpty?"-1":e.id.toString())).join(" "),i.addElement("Clef").innerText=n[t.clef],t.clefOttava!==o.Regular&&(i.addElement("Ottavia").innerText=o[t.clefOttava].substr(1)),t.simileMark!==h.None&&(i.addElement("SimileMark").innerText=h[t.simileMark])}writeVoiceNode(e,t){if(t.isEmpty)return;const i=e.addElement("Voice");i.attributes.set("id",t.id.toString()),i.addElement("Beats").innerText=t.beats.map((e=>e.id)).join(" ")}}Ao.MidiProgramInfoLookup=new Map([[0,new Do(Lo.Piano,"Acoustic Piano")],[1,new Do(Lo.Piano,"Acoustic Piano")],[2,new Do(Lo.Piano,"Electric Piano")],[3,new Do(Lo.Piano,"Acoustic Piano")],[4,new Do(Lo.Piano,"Electric Piano")],[5,new Do(Lo.Piano,"Electric Piano")],[6,new Do(Lo.Piano,"Harpsichord")],[7,new Do(Lo.Piano,"Harpsichord")],[8,new Do(Lo.PitchedIdiophone,"Celesta")],[9,new Do(Lo.PitchedIdiophone,"Vibraphone")],[10,new Do(Lo.PitchedIdiophone,"Vibraphone")],[11,new Do(Lo.PitchedIdiophone,"Vibraphone")],[12,new Do(Lo.PitchedIdiophone,"Xylophone")],[13,new Do(Lo.PitchedIdiophone,"Xylophone")],[14,new Do(Lo.PitchedIdiophone,"Vibraphone")],[15,new Do(Lo.Banjo,"Banjo")],[16,new Do(Lo.Piano,"Electric Organ")],[17,new Do(Lo.Piano,"Electric Organ")],[18,new Do(Lo.Piano,"Electric Organ")],[19,new Do(Lo.Piano,"Electric Organ")],[20,new Do(Lo.Piano,"Electric Organ")],[21,new Do(Lo.Piano,"Electric Organ")],[22,new Do(Lo.Woodwind,"Recorder")],[23,new Do(Lo.Piano,"Electric Organ")],[24,new Do(Lo.ClassicalGuitar,"Nylon Guitar")],[25,new Do(Lo.SteelGuitar,"Steel Guitar")],[26,new Do(Lo.SteelGuitar,"Electric Guitar")],[27,new Do(Lo.ElectricGuitar,"Electric Guitar")],[28,new Do(Lo.ElectricGuitar,"Electric Guitar")],[29,new Do(Lo.ElectricGuitar,"Electric Guitar")],[30,new Do(Lo.SteelGuitar,"Electric Guitar")],[31,new Do(Lo.SteelGuitar,"Electric Guitar")],[32,new Do(Lo.Bass,"Acoustic Bass")],[33,new Do(Lo.Bass,"Electric Bass")],[34,new Do(Lo.Bass,"Electric Bass")],[35,new Do(Lo.Bass,"Acoustic Bass")],[36,new Do(Lo.Bass,"Electric Bass")],[37,new Do(Lo.Bass,"Electric Bass")],[38,new Do(Lo.Synth,"Synth Bass")],[39,new Do(Lo.Synth,"Synth Bass")],[40,new Do(Lo.Strings,"Violin")],[41,new Do(Lo.Strings,"Viola")],[42,new Do(Lo.Strings,"Cello")],[43,new Do(Lo.Strings,"Contrabass")],[44,new Do(Lo.Strings,"Violin")],[45,new Do(Lo.Strings,"Violin")],[46,new Do(Lo.Piano,"Harp")],[47,new Do(Lo.Membraphone,"Timpani")],[48,new Do(Lo.Strings,"Violin")],[49,new Do(Lo.Strings,"Violin")],[50,new Do(Lo.Strings,"Violin")],[51,new Do(Lo.Strings,"Violin")],[52,new Do(Lo.Vocal,"Voice")],[53,new Do(Lo.Vocal,"Voice")],[54,new Do(Lo.Vocal,"Voice")],[55,new Do(Lo.Synth,"Pad Synthesizer")],[56,new Do(Lo.Brass,"Trumpet")],[57,new Do(Lo.Brass,"Trombone")],[58,new Do(Lo.Brass,"Tuba")],[59,new Do(Lo.Brass,"Trumpet")],[60,new Do(Lo.Brass,"French Horn")],[61,new Do(Lo.Brass,"Trumpet")],[62,new Do(Lo.Brass,"Trumpet")],[63,new Do(Lo.Brass,"Trumpet")],[64,new Do(Lo.Reed,"Saxophone")],[65,new Do(Lo.Reed,"Saxophone")],[66,new Do(Lo.Reed,"Saxophone")],[67,new Do(Lo.Reed,"Saxophone")],[68,new Do(Lo.Reed,"Oboe")],[69,new Do(Lo.Reed,"English Horn")],[70,new Do(Lo.Reed,"Bassoon")],[71,new Do(Lo.Reed,"Clarinet")],[72,new Do(Lo.Reed,"Piccolo")],[73,new Do(Lo.Woodwind,"Flute")],[74,new Do(Lo.Woodwind,"Recorder")],[75,new Do(Lo.Woodwind,"Flute")],[76,new Do(Lo.Woodwind,"Recorder")],[77,new Do(Lo.Woodwind,"Flute")],[78,new Do(Lo.Woodwind,"Recorder")],[79,new Do(Lo.Woodwind,"Flute")],[80,new Do(Lo.Synth,"Lead Synthesizer")],[81,new Do(Lo.Synth,"Lead Synthesizer")],[82,new Do(Lo.Synth,"Lead Synthesizer")],[83,new Do(Lo.Synth,"Lead Synthesizer")],[84,new Do(Lo.Synth,"Lead Synthesizer")],[85,new Do(Lo.Synth,"Lead Synthesizer")],[86,new Do(Lo.Synth,"Lead Synthesizer")],[87,new Do(Lo.Synth,"Lead Synthesizer")],[88,new Do(Lo.Synth,"Pad Synthesizer")],[89,new Do(Lo.Synth,"Pad Synthesizer")],[90,new Do(Lo.Synth,"Pad Synthesizer")],[91,new Do(Lo.Synth,"Pad Synthesizer")],[92,new Do(Lo.Synth,"Pad Synthesizer")],[93,new Do(Lo.Synth,"Pad Synthesizer")],[94,new Do(Lo.Synth,"Pad Synthesizer")],[95,new Do(Lo.Synth,"Pad Synthesizer")],[96,new Do(Lo.Fx,"Pad Synthesizer")],[97,new Do(Lo.Fx,"Pad Synthesizer")],[98,new Do(Lo.Fx,"Pad Synthesizer")],[99,new Do(Lo.Fx,"Pad Synthesizer")],[100,new Do(Lo.Fx,"Lead Synthesizer")],[101,new Do(Lo.Fx,"Lead Synthesizer")],[102,new Do(Lo.Fx,"Lead Synthesizer")],[103,new Do(Lo.Fx,"Trumpet")],[104,new Do(Lo.ElectricGuitar,"Banjo")],[105,new Do(Lo.Banjo,"Banjo")],[106,new Do(Lo.Ukulele,"Ukulele")],[107,new Do(Lo.Banjo,"Banjo")],[108,new Do(Lo.PitchedIdiophone,"Xylophone")],[109,new Do(Lo.Reed,"Bassoon")],[110,new Do(Lo.Strings,"Violin")],[111,new Do(Lo.Woodwind,"Flute")],[112,new Do(Lo.PitchedIdiophone,"Xylophone")],[113,new Do(Lo.Idiophone,"Celesta")],[114,new Do(Lo.PitchedIdiophone,"Vibraphone")],[115,new Do(Lo.Idiophone,"Xylophone")],[116,new Do(Lo.Membraphone,"Xylophone")],[117,new Do(Lo.Membraphone,"Xylophone")],[118,new Do(Lo.Membraphone,"Xylophone")],[119,new Do(Lo.Idiophone,"Celesta")],[120,new Do(Lo.Fx,"Steel Guitar")],[121,new Do(Lo.Fx,"Recorder")],[122,new Do(Lo.Fx,"Recorder")],[123,new Do(Lo.Fx,"Recorder")],[124,new Do(Lo.Fx,"Recorder")],[125,new Do(Lo.Fx,"Recorder")],[126,new Do(Lo.Fx,"Recorder")],[127,new Do(Lo.Fx,"Timpani")]]),Ao.DrumKitProgramInfo=new Do(Lo.PercussionKit,"Drums","drumKit");class Ro{static buildCrc32Lookup(){const e=new Uint32Array(256);for(let t=0;t<e.length;t++){let i=t;for(let e=0;e<8;e++)i=1&~i?i>>>1:i>>>1^3988292384;e[t]=i}return e}get value(){return~this._checkValue}constructor(){this._checkValue=Ro.CrcInit,this.reset()}update(e,t,i){for(let s=0;s<i;s++)this._checkValue=Ro.Crc32Lookup[255&(this._checkValue^e[t+s])]^this._checkValue>>>8}reset(){this._checkValue=Ro.CrcInit}}Ro.Crc32Lookup=Ro.buildCrc32Lookup(),Ro.CrcInit=4294967295;class Oo{}Oo.MAX_WBITS=15,Oo.WSIZE=1<<Oo.MAX_WBITS,Oo.WMASK=Oo.WSIZE-1,Oo.MIN_MATCH=3,Oo.MAX_MATCH=258,Oo.DEFAULT_MEM_LEVEL=8,Oo.PENDING_BUF_SIZE=1<<Oo.DEFAULT_MEM_LEVEL+8,Oo.HASH_BITS=Oo.DEFAULT_MEM_LEVEL+7,Oo.HASH_SIZE=1<<Oo.HASH_BITS,Oo.HASH_SHIFT=(Oo.HASH_BITS+Oo.MIN_MATCH-1)/Oo.MIN_MATCH,Oo.HASH_MASK=Oo.HASH_SIZE-1,Oo.MIN_LOOKAHEAD=Oo.MAX_MATCH+Oo.MIN_MATCH+1,Oo.MAX_DIST=Oo.WSIZE-Oo.MIN_LOOKAHEAD;class Go{constructor(e,t,i,s){this.length=null,this.numCodes=0,this.codes=null,this.huffman=e,this.minNumCodes=i,this.maxLength=s,this.freqs=new Int16Array(t),this.bitLengthCounts=new Int32Array(s)}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),i=0,s=0;for(let a=0;a<e;a++){let e=this.freqs[a];if(0!==e){let r=i++;for(;r>0;){let i=Math.floor((r-1)/2);if(!(this.freqs[t[i]]>e))break;t[r]=t[i],r=i}t[r]=a,s=a}}for(;i<2;){let e=s<2?++s:0;t[i++]=e}this.numCodes=Math.max(s+1,this.minNumCodes);let a=i,r=new Int32Array(4*i-2),n=new Int32Array(2*i-1),o=a;for(let e=0;e<i;e++){let i=t[e];r[2*e]=i,r[2*e+1]=-1,n[e]=this.freqs[i]<<8,t[e]=e}do{let e=t[0],s=t[--i],a=0,h=1;for(;h<i;)h+1<i&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*h+1;let l=n[s];for(;h=a,a>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=s;let c=t[0];s=o++,r[2*s]=e,r[2*s+1]=c;let d=Math.min(255&n[e],255&n[c]);for(l=n[e]+n[c]-d+1,n[s]=l,a=0,h=1;h<i;)h+1<i&&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]=s}while(i>1);this.buildLength(r)}buildLength(e){this.length=new Uint8Array(this.freqs.length);let t=Math.floor(e.length/2),i=Math.floor((t+1)/2),s=0;for(let e=0;e<this.maxLength;e++)this.bitLengthCounts[e]=0;let a=new Int32Array(t);a[t-1]=0;for(let i=t-1;i>=0;i--)if(-1!=e[2*i+1]){let t=a[i]+1;t>this.maxLength&&(t=this.maxLength,s++),a[e[2*i]]=t,a[e[2*i+1]]=t}else{let t=a[i];this.bitLengthCounts[t-1]++,this.length[e[2*i]]=a[i]}if(0==s)return;let r=this.maxLength-1;do{for(;0==this.bitLengthCounts[--r];);do{this.bitLengthCounts[r]--,this.bitLengthCounts[++r]++,s-=1<<this.maxLength-1-r}while(s>0&&r<this.maxLength-1)}while(s>0);this.bitLengthCounts[this.maxLength-1]+=s,this.bitLengthCounts[this.maxLength-2]-=s;let n=2*i;for(let t=this.maxLength;0!=t;t--){let i=this.bitLengthCounts[t-1];for(;i>0;){let s=2*e[n++];-1==e[s+1]&&(this.length[e[s]]=t,i--)}}}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,i,s,a=-1,r=0;for(;r<this.numCodes;){s=1;let n=this.length[r];for(0==n?(t=138,i=3):(t=6,i=3,a!=n&&(e.freqs[n]++,s=0)),a=n,r++;r<this.numCodes&&a==this.length[r]&&(r++,!(++s>=t)););s<i?e.freqs[a]+=s:0!=a?e.freqs[Go.Repeat3To6]++:s<=10?e.freqs[Go.Repeat3To10]++:e.freqs[Go.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 i=0;i<this.maxLength;i++)e[i]=t,t+=this.bitLengthCounts[i]<<15-i;for(let t=0;t<this.numCodes;t++){let i=this.length[t];i>0&&(this.codes[t]=Vo.bitReverse(e[i-1]),e[i-1]+=1<<16-i)}}writeTree(e){let t,i,s,a=-1,r=0;for(;r<this.numCodes;){s=1;let n=this.length[r];for(0==n?(t=138,i=3):(t=6,i=3,a!=n&&(e.writeSymbol(n),s=0)),a=n,r++;r<this.numCodes&&a==this.length[r]&&(r++,!(++s>=t)););if(s<i)for(;s-- >0;)e.writeSymbol(a);else 0!=a?(e.writeSymbol(Go.Repeat3To6),this.huffman.pending.writeBits(s-3,2)):s<=10?(e.writeSymbol(Go.Repeat3To10),this.huffman.pending.writeBits(s-3,3)):(e.writeSymbol(Go.Repeat11To138),this.huffman.pending.writeBits(s-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}Go.Repeat3To6=16,Go.Repeat3To10=17,Go.Repeat11To138=18;class Vo{static staticInit(){let e=0;for(;e<144;)Vo.staticLCodes[e]=Vo.bitReverse(48+e<<8),Vo.staticLLength[e++]=8;for(;e<256;)Vo.staticLCodes[e]=Vo.bitReverse(256+e<<7),Vo.staticLLength[e++]=9;for(;e<280;)Vo.staticLCodes[e]=Vo.bitReverse(-256+e<<9),Vo.staticLLength[e++]=7;for(;e<Vo.LITERAL_NUM;)Vo.staticLCodes[e]=Vo.bitReverse(-88+e<<8),Vo.staticLLength[e++]=8;for(e=0;e<Vo.DIST_NUM;e++)Vo.staticDCodes[e]=Vo.bitReverse(e<<11),Vo.staticDLength[e]=5}static bitReverse(e){return Vo.bit4Reverse[15&e]<<12|Vo.bit4Reverse[e>>4&15]<<8|Vo.bit4Reverse[e>>8&15]<<4|Vo.bit4Reverse[e>>12]}constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new Go(this,Vo.LITERAL_NUM,257,15),this.distTree=new Go(this,Vo.DIST_NUM,1,15),this.blTree=new Go(this,Vo.BITLEN_NUM,4,7),this.d_buf=new Int16Array(Vo.BUFSIZE),this.l_buf=new Uint8Array(Vo.BUFSIZE)}isFull(){return this.last_lit>=Vo.BUFSIZE}reset(){this.last_lit=0,this.extra_bits=0,this.literalTree.reset(),this.distTree.reset(),this.blTree.reset()}flushStoredBlock(e,t,i,s){this.pending.writeBits((Vo.STORED_BLOCK<<1)+(s?1:0),3),this.pending.alignToByte(),this.pending.writeShort(i),this.pending.writeShort(~i),this.pending.writeBlock(e,t,i),this.reset()}flushBlock(e,t,i,s){this.literalTree.freqs[Vo.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[Vo.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<Vo.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*Vo.staticLLength[e];for(let e=0;e<Vo.DIST_NUM;e++)n+=this.distTree.freqs[e]*Vo.staticDLength[e];r>=n&&(r=n),t>=0&&i+4<r>>3?this.flushStoredBlock(e,t,i,s):r==n?(this.pending.writeBits((Vo.STATIC_TREES<<1)+(s?1:0),3),this.literalTree.setStaticCodes(Vo.staticLCodes,Vo.staticLLength),this.distTree.setStaticCodes(Vo.staticDCodes,Vo.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((Vo.DYN_TREES<<1)+(s?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[Vo.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],i=this.d_buf[e];if(0!=i--){let e=Vo.Lcode(t);this.literalTree.writeSymbol(e);let s=Math.floor((e-261)/4);s>0&&s<=5&&this.pending.writeBits(t&(1<<s)-1,s);let a=Vo.Dcode(i);this.distTree.writeSymbol(a),s=Math.floor(a/2)-1,s>0&&this.pending.writeBits(i&(1<<s)-1,s)}else this.literalTree.writeSymbol(t)}this.literalTree.writeSymbol(Vo.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;let i=Vo.Lcode(t-3);this.literalTree.freqs[i]++,i>=265&&i<285&&(this.extra_bits+=Math.floor((i-261)/4));let s=Vo.Dcode(e-1);return this.distTree.freqs[s]++,s>=4&&(this.extra_bits+=Math.floor(s/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}}Vo.BUFSIZE=1<<Oo.DEFAULT_MEM_LEVEL+6,Vo.LITERAL_NUM=286,Vo.STORED_BLOCK=0,Vo.STATIC_TREES=1,Vo.DYN_TREES=2,Vo.DIST_NUM=30,Vo.staticLCodes=new Int16Array(Vo.LITERAL_NUM),Vo.staticLLength=new Uint8Array(Vo.LITERAL_NUM),Vo.staticDCodes=new Int16Array(Vo.DIST_NUM),Vo.staticDLength=new Uint8Array(Vo.DIST_NUM),Vo.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Vo.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),Vo.BITLEN_NUM=19,Vo.EOF_SYMBOL=256,Vo.staticInit();class Ho{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 Vo(e),this.inputCrc=new Ro,this.window=new Uint8Array(2*Oo.WSIZE),this.head=new Int16Array(Oo.HASH_SIZE),this.prev=new Int16Array(Oo.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=Oo.MIN_MATCH-1;for(let e=0;e<Oo.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<Oo.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<Oo.HASH_SHIFT^this.window[this.strstart+1]}needsInput(){return this.inputEnd==this.inputOff}setInput(e,t,i){let s=t+i;this.inputBuf=e,this.inputOff=t,this.inputEnd=s}deflate(e,t){let i;do{this.fillWindow();let s=e&&this.inputOff==this.inputEnd;i=this.deflateSlow(s,t)}while(this.pending.isFlushed&&i);return i}deflateSlow(e,t){if(this.lookahead<Oo.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=Oo.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*Oo.WSIZE-Oo.MIN_LOOKAHEAD&&this.slideWindow();let e=this.matchStart,i=this.matchLen;if(this.lookahead>=Oo.MIN_MATCH){let e=this.insertString();0!=e&&this.strstart-e<=Oo.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen==Oo.MIN_MATCH&&this.strstart-this.matchStart>Ho.TooFar&&(this.matchLen=Oo.MIN_MATCH-1)}if(i>=Oo.MIN_MATCH&&this.matchLen<=i){this.huffman.tallyDist(this.strstart-1-e,i),i-=2;do{this.strstart++,this.lookahead--,this.lookahead>=Oo.MIN_MATCH&&this.insertString()}while(--i>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=Oo.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 i=t&&0==this.lookahead&&!this.prevAvailable;return this.huffman.flushBlock(this.window,this.blockStart,e,i),this.blockStart+=e,!i}}return!0}findLongestMatch(e){let t,i=this.strstart,s=i+Math.min(Oo.MAX_MATCH,this.lookahead)-1,a=Math.max(i-Oo.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,Oo.MIN_MATCH-1),i+this.matchLen>s)return!1;let l=r[i+this.matchLen-1],c=r[i+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,i=this.strstart,r[t+this.matchLen]==c&&r[t+this.matchLen-1]==l&&r[t]==r[i]&&r[++t]==r[++i]){switch((s-i)%8){case 1:if(r[++i]==r[++t])break;break;case 2:if(r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 3:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 4:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 5:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 6:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break;break;case 7:if(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t])break}if(r[i]==r[t])do{if(i==s){++i,++t;break}}while(r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]&&r[++i]==r[++t]);if(i-this.strstart>this.matchLen){if(this.matchStart=e,this.matchLen=i-this.strstart,this.matchLen>=h)break;l=r[i-1],c=r[i]}e=65535&n[e&Oo.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=Oo.MIN_MATCH}insertString(){let e,t=(this.insertHashIndex<<Oo.HASH_SHIFT^this.window[this.strstart+(Oo.MIN_MATCH-1)])&Oo.HASH_MASK;return e=this.head[t],this.prev[this.strstart&Oo.WMASK]=e,this.head[t]=this.strstart,this.insertHashIndex=t,65535&e}fillWindow(){if(this.strstart>=Oo.WSIZE+Oo.MAX_DIST&&this.slideWindow(),this.lookahead<Oo.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*Oo.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>=Oo.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(Oo.WSIZE,Oo.WSIZE+Oo.WSIZE),0),this.matchStart-=Oo.WSIZE,this.strstart-=Oo.WSIZE,this.blockStart-=Oo.WSIZE;for(let e=0;e<Oo.HASH_SIZE;++e){let t=65535&this.head[e];this.head[e]=t>=Oo.WSIZE?t-Oo.WSIZE:0}for(let e=0;e<Oo.WSIZE;e++){let t=65535&this.prev[e];this.prev[e]=t>=Oo.WSIZE?t-Oo.WSIZE:0}}}Ho.TooFar=4096;class Wo{get isFlushed(){return 0===this._end}constructor(e){this._start=0,this._end=0,this._bits=0,this.bitCount=0,this._buffer=new Uint8Array(e)}reset(){this._start=0,this._end=0,this.bitCount=0}writeShortMSB(e){this._buffer[this._end++]=e>>8&255,this._buffer[this._end++]=255&e}writeShort(e){this._buffer[this._end++]=e,this._buffer[this._end++]=e>>8}writeBlock(e,t,i){this._buffer.set(e.subarray(t,t+i),this._end),this._end+=i}flush(e,t,i){return this.bitCount>=8&&(this._buffer[this._end++]=255&this._bits,this._bits>>=8,this.bitCount-=8),i>this._end-this._start?(i=this._end-this._start,e.set(this._buffer.subarray(this._start,this._start+i),t),this._start=0,this._end=0):(e.set(this._buffer.subarray(this._start,this._start+i),t),this._start+=i),i}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 zo{get inputCrc(){return this._engine.inputCrc.value}constructor(){this._state=0,this._pending=new Wo(Oo.PENDING_BUF_SIZE),this._engine=new Ho(this._pending),this.reset()}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state==zo.FinishedState&&this._pending.isFlushed}reset(){this._state=zo.BusyState,this._pending.reset(),this._engine.reset()}setInput(e,t,i){this._engine.setInput(e,t,i)}deflate(e,t,i){let s=i;for(;;){let a=this._pending.flush(e,t,i);if(t+=a,0==(i-=a)||this._state==zo.FinishedState)break;if(!this._engine.deflate(!!(this._state&zo.IsFlushing),!!(this._state&zo.IsFinishing)))switch(this._state){case zo.BusyState:return s-i;case zo.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=zo.BusyState;break;case zo.FinishingState:this._pending.alignToByte(),this._state=zo.FinishedState}}return s-i}finish(){this._state|=zo.IsFlushing|zo.IsFinishing}}zo.IsFlushing=4,zo.IsFinishing=8,zo.BusyState=16,zo.FlushingState=20,zo.FinishingState=28,zo.FinishedState=30;class Uo{constructor(e,t,i,s,a){this.entry=e,this.crc32=t,this.localHeaderOffset=i,this.compressionMode=s,this.compressedSize=a}}class Xo{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new zo,this._data=e}writeEntry(e){const t=Nt.CompressionMethodDeflate,i=ke.empty(),s=this.compress(i,e.data,t),a=i.toArray(),r=new Uo(e,s,this._data.bytesWritten,t,i.length);this._centralDirectoryHeaders.push(r),Te.writeInt32LE(this._data,Nt.LocalFileHeaderSignature),Te.writeUInt16LE(this._data,10),Te.writeUInt16LE(this._data,2048),Te.writeUInt16LE(this._data,t),Te.writeInt16LE(this._data,0),Te.writeInt16LE(this._data,0),Te.writeInt32LE(this._data,s),Te.writeInt32LE(this._data,a.length),Te.writeInt32LE(this._data,e.data.length),Te.writeInt16LE(this._data,e.fullName.length),Te.writeInt16LE(this._data,0);const n=Te.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,i){if(i!=Nt.CompressionMethodDeflate){const i=new Ro;return i.update(t,0,t.length),e.write(t,0,t.length),i.value}{let i=new Uint8Array(512);for(this._deflater.reset(),this._deflater.setInput(t,0,t.length);!this._deflater.isNeedingInput;){const t=this._deflater.deflate(i,0,i.length);if(t<=0)break;e.write(i,0,t)}for(this._deflater.finish();!this._deflater.isFinished;){const t=this._deflater.deflate(i,0,i.length);if(t<=0)break;e.write(i,0,t)}return this._deflater.inputCrc}}end(){const e=this._data.bytesWritten;for(const e of this._centralDirectoryHeaders)this.writeCentralDirectoryHeader(e);const t=this._data.bytesWritten;this.writeEndOfCentralDirectoryRecord(e,t)}writeEndOfCentralDirectoryRecord(e,t){Te.writeInt32LE(this._data,Nt.EndOfCentralDirSignature),Te.writeInt16LE(this._data,0),Te.writeInt16LE(this._data,0),Te.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Te.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Te.writeInt32LE(this._data,t-e),Te.writeInt32LE(this._data,e),Te.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){Te.writeInt32LE(this._data,Nt.CentralFileHeaderSignature),Te.writeUInt16LE(this._data,10),Te.writeUInt16LE(this._data,10),Te.writeUInt16LE(this._data,2048),Te.writeUInt16LE(this._data,e.compressionMode),Te.writeInt16LE(this._data,0),Te.writeInt16LE(this._data,0),Te.writeInt32LE(this._data,e.crc32),Te.writeInt32LE(this._data,e.compressedSize),Te.writeInt32LE(this._data,e.entry.data.length),Te.writeInt16LE(this._data,e.entry.fullName.length),Te.writeInt16LE(this._data,0),Te.writeInt16LE(this._data,0),Te.writeInt16LE(this._data,0),Te.writeInt16LE(this._data,0),Te.writeInt32LE(this._data,0),Te.writeInt32LE(this._data,e.localHeaderOffset);const t=Te.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}var Yo=Object.freeze({__proto__:null,Gp7Exporter:class extends Io{get name(){return"Guitar Pro 7"}constructor(){super()}writeScore(e){J.debug(this.name,"Writing data entries");const t=(new Ao).writeXml(e),i=ot.writeForScore(e),s=St.writeForScore(e);J.debug(this.name,"Writing ZIP entries");let a=new Xo(this.data);a.writeEntry(new Nt("VERSION",Te.stringToBytes("7.0"))),a.writeEntry(new Nt("Content/",new Uint8Array(0))),a.writeEntry(new Nt("Content/BinaryStylesheet",i)),a.writeEntry(new Nt("Content/PartConfiguration",s)),a.writeEntry(new Nt("Content/score.gpif",Te.stringToBytes(t))),a.end()}},ScoreExporter:Io}),qo=Object.freeze({__proto__:null,AlphaSynthMidiFileHandler:Fs,AlphaTabMetronomeEvent:Ht,AlphaTabRestEvent:Wt,BeatTickLookup:Ds,ControlChangeEvent:Yt,get ControllerType(){return Ge},EndOfTrackEvent:$t,MasterBarTickLookup:As,MidiEvent:Ot,get MidiEventType(){return Me},MidiFile:Rt,get MidiFileFormat(){return Le},MidiFileGenerator:Hs,MidiTickLookup:Os,MidiTickLookupFindBeatResult:Rs,NoteBendEvent:Qt,NoteEvent:zt,NoteOffEvent:Xt,NoteOnEvent:Ut,PitchBendEvent:jt,ProgramChangeEvent:qt,TempoChangeEvent:Jt,TimeSignatureEvent:Gt}),Jo=Object.freeze({__proto__:null,get AccentuationType(){return a},get AccidentalType(){return Je},Automation:H,get AutomationType(){return r},Bar:W,Beat:oe,BendPoint:U,get BendStyle(){return l},get BendType(){return c},get BrushType(){return d},Chord:he,get Clef(){return n},Color:me,get CrescendoType(){return u},get Duration(){return p},get DynamicValue(){return g},Fermata:ht,get FermataType(){return Ne},get Fingers(){return m},Font:Ri,get FontStyle(){return Ve},get GraceType(){return f},get HarmonicType(){return y},InstrumentArticulation:$,JsonConverter:ys,get KeySignature(){return M},get KeySignatureType(){return D},Lyrics:le,MasterBar:ce,get MusicFontSymbol(){return P},Note:ee,get NoteAccidentalMode(){return b},get Ottavia(){return o},get PickStroke(){return N},PlaybackInformation:ye,RenderStylesheet:de,RepeatGroup:ue,Score:pe,Section:ge,get SimileMark(){return h},get SlideInType(){return S},get SlideOutType(){return w},Staff:Se,Track:we,get TripletFeel(){return A},Tuning:be,TupletGroup:te,get VibratoType(){return _},Voice:_e,get WhammyType(){return F}}),jo=Object.freeze({__proto__:null,BarBounds:Bs,BeatBounds:Ts,Bounds:nt,BoundsLookup:Ns,MasterBarBounds:ks,NoteBounds:vs,RenderFinishedEventArgs:_s,ScoreRenderer:Ps,StaveGroupBounds:xs}),Qo=Object.freeze({__proto__:null,CssFontSvgCanvas:ba,Cursors:ca,FontSizes:ws,SvgCanvas:ya,get TextAlign(){return E},get TextBaseline(){return C}}),$o=Object.freeze({__proto__:null,ActiveBeatsChangedEventArgs:Qs,AlphaSynth:Mi,AlphaSynthAudioWorkletOutput:ua,AlphaSynthScriptProcessorOutput:na,AlphaSynthWebAudioOutputBase:ra,AlphaSynthWebWorkerApi:ha,CircularSampleBuffer:aa,MidiEventsPlayedEventArgs:Fi,PlaybackRange:Ws,PlaybackRangeChangedEventArgs:Li,get PlayerState(){return Ie},PlayerStateChangedEventArgs:si,PositionChangedEventArgs:ai});Eo.isRunningInWorker?Eo.initializeWorker():Eo.isRunningInAudioWorklet?Eo.initializeAudioWorklet():Eo.initializeMain((t=>{if(Eo.webPlatform==e.WebPlatform.NodeJs)throw new G(e.AlphaTabErrorType.General,"Workers not yet supported in Node.js");if(Eo.webPlatform==e.WebPlatform.BrowserModule||Eo.isWebPackBundled||Eo.isViteBundled)return J.debug("AlphaTab","Creating webworker"),new Eo.alphaTabWorker(new URL("./alphaTab.worker",{}),{type:"module"});if(!t.core.scriptFile)throw new G(e.AlphaTabErrorType.General,"Could not detect alphaTab script file, cannot initialize renderer");try{J.debug("AlphaTab","Creating Blob worker");const e=`importScripts('${t.core.scriptFile}')`,i=new Blob([e]);return new Worker(URL.createObjectURL(i))}catch(e){return J.warning("Rendering","Could not create inline worker, fallback to normal worker"),new Worker(t.core.scriptFile)}}),((t,i)=>{if(Eo.webPlatform==e.WebPlatform.NodeJs)throw new G(e.AlphaTabErrorType.General,"Audio Worklets not yet supported in Node.js");if(Eo.webPlatform==e.WebPlatform.BrowserModule||Eo.isWebPackBundled||Eo.isViteBundled){J.debug("AlphaTab","Creating Module worklet");return t.audioWorklet.addModule(new URL("./alphaTab.worklet",{}))}return J.debug("AlphaTab","Creating Script worklet"),t.audioWorklet.addModule(i.core.scriptFile)})),e.AlphaTabApi=fa,e.AlphaTabError=G,e.CoreSettings=Co,e.DisplaySettings=Gi,e.Environment=Eo,e.FileLoadError=Zs,e.FormatError=fe,e.ImporterSettings=Vi,e.Logger=J,e.NotationSettings=X,e.PlayerSettings=zi,e.ProgressEventArgs=oa,e.RenderingResources=Oi,e.ResizeEventArgs=js,e.Settings=Zi,e.VibratoPlaybackSettings=Hi,e.exporter=Yo,e.importer=Mo,e.meta=Fo,e.midi=qo,e.model=Jo,e.platform=Qo,e.rendering=jo,e.synth=$o}));
2
2
  //# sourceMappingURL=alphaTab.min.js.map