@coderline/alphatab 1.3.0-alpha.605 → 1.3.0-alpha.607
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/alphaTab.d.ts +4 -4
- package/dist/alphaTab.js +20 -20
- package/dist/alphaTab.min.js +2 -2
- package/dist/alphaTab.min.mjs +2 -2
- package/dist/alphaTab.mjs +20 -20
- package/package.json +1 -1
package/dist/alphaTab.min.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* alphaTab v1.3.0-alpha.
|
|
2
|
+
* alphaTab v1.3.0-alpha.607 (develop, build 607)
|
|
3
3
|
*
|
|
4
4
|
* Copyright © 2023, Daniel Kuschny and Contributors, All rights reserved.
|
|
5
5
|
*
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
* Copyright (C) 2012 Steve Folta (https://github.com/stevefolta/SFZero)
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
var e,t,i,s,a,r,n,o,h,l,d,c,u,p,g,f,m,y,b,S,_,w,B,T,k,v,N,x,P,E,C,F,L,M,D,I,R,A,O,G,V,H,W,z,U,X,Y,q,J,j,Q,$,K,Z,ee,te,ie,se,ae,re,ne,oe,he,le,de;!function(e){e[e.Page=0]="Page",e[e.Horizontal=1]="Horizontal"}(e||(e={})),function(e){e[e.Default=0]="Default",e[e.ScoreTab=1]="ScoreTab",e[e.Score=2]="Score",e[e.Tab=3]="Tab",e[e.TabMixed=4]="TabMixed"}(t||(t={}));class ce{static getValue(e){return ce._values||(ce._values=new Map),e=e.toLowerCase().replaceAll(" ",""),ce._values.has(e)?ce._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}}ce._values=new Map([["acousticgrandpiano",0],["brightacousticpiano",1],["electricgrandpiano",2],["honkytonkpiano",3],["electricpiano1",4],["electricpiano2",5],["harpsichord",6],["clavinet",7],["celesta",8],["glockenspiel",9],["musicbox",10],["vibraphone",11],["marimba",12],["xylophone",13],["tubularbells",14],["dulcimer",15],["drawbarorgan",16],["percussiveorgan",17],["rockorgan",18],["churchorgan",19],["reedorgan",20],["accordion",21],["harmonica",22],["tangoaccordion",23],["acousticguitarnylon",24],["acousticguitarsteel",25],["electricguitarjazz",26],["electricguitarclean",27],["electricguitarmuted",28],["overdrivenguitar",29],["distortionguitar",30],["guitarharmonics",31],["acousticbass",32],["electricbassfinger",33],["electricbasspick",34],["fretlessbass",35],["slapbass1",36],["slapbass2",37],["synthbass1",38],["synthbass2",39],["violin",40],["viola",41],["cello",42],["contrabass",43],["tremolostrings",44],["pizzicatostrings",45],["orchestralharp",46],["timpani",47],["stringensemble1",48],["stringensemble2",49],["synthstrings1",50],["synthstrings2",51],["choiraahs",52],["voiceoohs",53],["synthvoice",54],["orchestrahit",55],["trumpet",56],["trombone",57],["tuba",58],["mutedtrumpet",59],["frenchhorn",60],["brasssection",61],["synthbrass1",62],["synthbrass2",63],["sopranosax",64],["altosax",65],["tenorsax",66],["baritonesax",67],["oboe",68],["englishhorn",69],["bassoon",70],["clarinet",71],["piccolo",72],["flute",73],["recorder",74],["panflute",75],["blownbottle",76],["shakuhachi",77],["whistle",78],["ocarina",79],["lead1square",80],["lead2sawtooth",81],["lead3calliope",82],["lead4chiff",83],["lead5charang",84],["lead6voice",85],["lead7fifths",86],["lead8bassandlead",87],["pad1newage",88],["pad2warm",89],["pad3polysynth",90],["pad4choir",91],["pad5bowed",92],["pad6metallic",93],["pad7halo",94],["pad8sweep",95],["fx1rain",96],["fx2soundtrack",97],["fx3crystal",98],["fx4atmosphere",99],["fx5brightness",100],["fx6goblins",101],["fx7echoes",102],["fx8scifi",103],["sitar",104],["banjo",105],["shamisen",106],["koto",107],["kalimba",108],["bagpipe",109],["fiddle",110],["shanai",111],["tinklebell",112],["agogo",113],["steeldrums",114],["woodblock",115],["taikodrum",116],["melodictom",117],["synthdrum",118],["reversecymbal",119],["guitarfretnoise",120],["breathnoise",121],["seashore",122],["birdtweet",123],["telephonering",124],["helicopter",125],["applause",126],["gunshot",127]]);class ue{init(e,t){this.data=e,this.settings=t}}!function(e){e[e.General=0]="General",e[e.Format=1]="Format",e[e.AlphaTex=2]="AlphaTex"}(i||(i={}));class pe extends Error{constructor(e,t="",i){super(null!=t?t:""),this.type=e,this.inner=null!=i?i:null,Object.setPrototypeOf(this,pe.prototype)}}class ge extends pe{constructor(e=null,t=null){super(i.Format,null!=e?e:"Unsupported format"),this.inner=t,Object.setPrototypeOf(this,ge.prototype)}}!function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy"}(s||(s={})),function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(a||(a={}));class fe{constructor(){this.isLinear=!1,this.type=a.Tempo,this.value=0,this.ratioPosition=0,this.text=""}static buildTempoAutomation(e,t,i,s){(s<1||s>5)&&(s=2);let r=new Float32Array([1,.5,1,1.5,2,3]),n=new fe;return n.type=a.Tempo,n.isLinear=e,n.ratioPosition=t,n.value=i*r[s],n}static buildInstrumentAutomation(e,t,i){let s=new fe;return s.type=a.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"}(r||(r={})),function(e){e[e._15ma=0]="_15ma",e[e._8va=1]="_8va",e[e.Regular=2]="Regular",e[e._8vb=3]="_8vb",e[e._15mb=4]="_15mb"}(n||(n={})),function(e){e[e.None=0]="None",e[e.Simple=1]="Simple",e[e.FirstOfDouble=2]="FirstOfDouble",e[e.SecondOfDouble=3]="SecondOfDouble"}(o||(o={}));class me{constructor(){this.id=me._globalBarId++,this.index=0,this.nextBar=null,this.previousBar=null,this.clef=r.G2,this.clefOttava=n.Regular,this.voices=[],this.simileMark=o.None,this.isMultiVoice=!1}get masterBar(){return this.staff.track.score.masterBars[this.index]}get isEmpty(){for(let e=0,t=this.voices.length;e<t;e++)if(!this.voices[e].isEmpty)return!1;return!0}addVoice(e){e.bar=this,e.index=this.voices.length,this.voices.push(e)}finish(e,t=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}}me._globalBarId=0;class ye{static ticksToMillis(e,t){return e*(6e4/(t*ye.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*ye.QuarterTime))|0}static toTicks(e){return ye.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),ye.QuarterTime*(4/t)|0}static applyDot(e,t){return t?e+3*(e/4|0):e+(e/2|0)}static applyTuplet(e,t,i){return e*i/t|0}static removeTuplet(e,t,i){return e*t/i|0}static dynamicToVelocity(e){return ye.MinVelocity+e*ye.VelocityIncrement}}ye.QuarterTime=960,ye.MinVelocity=15,ye.VelocityIncrement=16;class be{constructor(e=0,t=0){this.offset=e,this.value=t}}be.MaxPosition=60,be.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(h||(h={})),function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Bend=2]="Bend",e[e.Release=3]="Release",e[e.BendRelease=4]="BendRelease",e[e.Hold=5]="Hold",e[e.Prebend=6]="Prebend",e[e.PrebendBend=7]="PrebendBend",e[e.PrebendRelease=8]="PrebendRelease"}(l||(l={})),function(e){e[e.None=0]="None",e[e.BrushUp=1]="BrushUp",e[e.BrushDown=2]="BrushDown",e[e.ArpeggioUp=3]="ArpeggioUp",e[e.ArpeggioDown=4]="ArpeggioDown"}(d||(d={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(c||(c={})),function(e){e[e.QuadrupleWhole=-4]="QuadrupleWhole",e[e.DoubleWhole=-2]="DoubleWhole",e[e.Whole=1]="Whole",e[e.Half=2]="Half",e[e.Quarter=4]="Quarter",e[e.Eighth=8]="Eighth",e[e.Sixteenth=16]="Sixteenth",e[e.ThirtySecond=32]="ThirtySecond",e[e.SixtyFourth=64]="SixtyFourth",e[e.OneHundredTwentyEighth=128]="OneHundredTwentyEighth",e[e.TwoHundredFiftySixth=256]="TwoHundredFiftySixth"}(u||(u={})),function(e){e[e.PPP=0]="PPP",e[e.PP=1]="PP",e[e.P=2]="P",e[e.MP=3]="MP",e[e.MF=4]="MF",e[e.F=5]="F",e[e.FF=6]="FF",e[e.FFF=7]="FFF"}(p||(p={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(g||(g={})),function(e){e[e.Unknown=-2]="Unknown",e[e.NoOrDead=-1]="NoOrDead",e[e.Thumb=0]="Thumb",e[e.IndexFinger=1]="IndexFinger",e[e.MiddleFinger=2]="MiddleFinger",e[e.AnnularFinger=3]="AnnularFinger",e[e.LittleFinger=4]="LittleFinger"}(f||(f={})),function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Artificial=2]="Artificial",e[e.Pinch=3]="Pinch",e[e.Tap=4]="Tap",e[e.Semi=5]="Semi",e[e.Feedback=6]="Feedback"}(m||(m={})),function(e){e[e.Default=0]="Default",e[e.ForceNone=1]="ForceNone",e[e.ForceNatural=2]="ForceNatural",e[e.ForceSharp=3]="ForceSharp",e[e.ForceDoubleSharp=4]="ForceDoubleSharp",e[e.ForceFlat=5]="ForceFlat",e[e.ForceDoubleFlat=6]="ForceDoubleFlat"}(y||(y={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(b||(b={})),function(e){e[e.None=0]="None",e[e.Shift=1]="Shift",e[e.Legato=2]="Legato",e[e.OutUp=3]="OutUp",e[e.OutDown=4]="OutDown",e[e.PickSlideDown=5]="PickSlideDown",e[e.PickSlideUp=6]="PickSlideUp"}(S||(S={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(_||(_={})),function(e){e[e.Hidden=0]="Hidden",e[e.ShowWithBeams=1]="ShowWithBeams",e[e.ShowWithBars=2]="ShowWithBars"}(w||(w={})),function(e){e[e.ScoreDefault=0]="ScoreDefault",e[e.ScoreForcePiano=1]="ScoreForcePiano",e[e.SingleNoteEffectBand=2]="SingleNoteEffectBand",e[e.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano"}(B||(B={})),function(e){e[e.GuitarPro=0]="GuitarPro",e[e.SongBook=1]="SongBook"}(T||(T={})),function(e){e[e.ScoreTitle=0]="ScoreTitle",e[e.ScoreSubTitle=1]="ScoreSubTitle",e[e.ScoreArtist=2]="ScoreArtist",e[e.ScoreAlbum=3]="ScoreAlbum",e[e.ScoreWords=4]="ScoreWords",e[e.ScoreMusic=5]="ScoreMusic",e[e.ScoreWordsAndMusic=6]="ScoreWordsAndMusic",e[e.ScoreCopyright=7]="ScoreCopyright",e[e.GuitarTuning=8]="GuitarTuning",e[e.TrackNames=9]="TrackNames",e[e.ChordDiagrams=10]="ChordDiagrams",e[e.ParenthesisOnTiedBends=11]="ParenthesisOnTiedBends",e[e.TabNotesOnTiedBends=12]="TabNotesOnTiedBends",e[e.ZerosOnDiveWhammys=13]="ZerosOnDiveWhammys",e[e.EffectAlternateEndings=14]="EffectAlternateEndings",e[e.EffectCapo=15]="EffectCapo",e[e.EffectChordNames=16]="EffectChordNames",e[e.EffectCrescendo=17]="EffectCrescendo",e[e.EffectDynamics=18]="EffectDynamics",e[e.EffectFadeIn=19]="EffectFadeIn",e[e.EffectFermata=20]="EffectFermata",e[e.EffectFingering=21]="EffectFingering",e[e.EffectHarmonics=22]="EffectHarmonics",e[e.EffectLetRing=23]="EffectLetRing",e[e.EffectLyrics=24]="EffectLyrics",e[e.EffectMarker=25]="EffectMarker",e[e.EffectOttavia=26]="EffectOttavia",e[e.EffectPalmMute=27]="EffectPalmMute",e[e.EffectPickSlide=28]="EffectPickSlide",e[e.EffectPickStroke=29]="EffectPickStroke",e[e.EffectSlightBeatVibrato=30]="EffectSlightBeatVibrato",e[e.EffectSlightNoteVibrato=31]="EffectSlightNoteVibrato",e[e.EffectTap=32]="EffectTap",e[e.EffectTempo=33]="EffectTempo",e[e.EffectText=34]="EffectText",e[e.EffectTrill=35]="EffectTrill",e[e.EffectTripletFeel=36]="EffectTripletFeel",e[e.EffectWhammyBar=37]="EffectWhammyBar",e[e.EffectWideBeatVibrato=38]="EffectWideBeatVibrato",e[e.EffectWideNoteVibrato=39]="EffectWideNoteVibrato",e[e.EffectLeftHandTap=40]="EffectLeftHandTap"}(k||(k={}));class Se{constructor(){this.notationMode=T.GuitarPro,this.fingeringMode=B.ScoreDefault,this.elements=new Map,this.rhythmMode=w.Hidden,this.rhythmHeight=15,this.transpositionPitches=[],this.displayTranspositionPitches=[],this.smallGraceTabNotes=!0,this.extendBendArrowsOnTiedNotes=!0,this.extendLineEffectsToBeatEnd=!1,this.slurHeight=5}isNotationElementVisible(e){return this.elements.has(e)?this.elements.get(e):!Se.defaultElements.has(e)||Se.defaultElements.get(e)}}Se.defaultElements=new Map([[k.ZerosOnDiveWhammys,!1]]);class _e{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}!function(e){e[e.None=0]="None",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warning=3]="Warning",e[e.Error=4]="Error"}(v||(v={}));class we{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...i){console.debug(we.format(e,t),...i)}warning(e,t,...i){console.warn(we.format(e,t),...i)}info(e,t,...i){console.info(we.format(e,t),...i)}error(e,t,...i){console.error(we.format(e,t),...i)}}we.logLevel=v.Info;class Be{static shouldLog(e){return Be.logLevel!==v.None&&e>=Be.logLevel}static debug(e,t,...i){Be.shouldLog(v.Debug)&&Be.log.debug(e,t,...i)}static warning(e,t,...i){Be.shouldLog(v.Warning)&&Be.log.warning(e,t,...i)}static info(e,t,...i){Be.shouldLog(v.Info)&&Be.log.info(e,t,...i)}static error(e,t,...i){Be.shouldLog(v.Error)&&Be.log.error(e,t,...i)}}Be.logLevel=v.Info,Be.log=new we;class Te{constructor(){this.note=null,this.noteValue=0,this.octave=0}get realValue(){return 12*this.octave+this.noteValue}}class ke{static getIndex(e){return e<0?0:0|Math.log2(e)}static keySignatureIsFlat(e){return e<0}static keySignatureIsNatural(e){return 0===e}static keySignatureIsSharp(e){return e>0}static applyPitchOffsets(e,t){for(let 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(e,t,i,s){if(e.notation.fingeringMode===B.ScoreForcePiano||e.notation.fingeringMode===B.SingleNoteEffectBandForcePiano||ce.isPiano(t.voice.bar.staff.track.playbackInfo.program))switch(i){case f.Unknown:case f.NoOrDead:return null;case f.Thumb:return"1";case f.IndexFinger:return"2";case f.MiddleFinger:return"3";case f.AnnularFinger:return"4";case f.LittleFinger:return"5";default:return null}if(s)switch(i){case f.Unknown:case f.NoOrDead:return"0";case f.Thumb:return"T";case f.IndexFinger:return"1";case f.MiddleFinger:return"2";case f.AnnularFinger:return"3";case f.LittleFinger:return"4";default:return null}switch(i){case f.Unknown:case f.NoOrDead:return null;case f.Thumb:return"p";case f.IndexFinger:return"i";case f.MiddleFinger:return"m";case f.AnnularFinger:return"a";case f.LittleFinger:return"c";default:return null}}static isTuning(e){return!!ke.parseTuning(e)}static parseTuning(e){let t="",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 Te;return s.octave=parseInt(i)+1,s.note=t.toLowerCase(),s.noteValue=ke.getToneForText(s.note),s}static getTuningForText(e){let t=ke.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"}(x||(x={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(P||(P={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(E||(E={}));class ve{constructor(e="",t=0,i=0,s=x.None,a=x.None,r=x.None,n=x.None,o=E.Middle){this.elementType=e,this.outputMidiNumber=i,this.staffLine=t,this.noteHeadDefault=s,this.noteHeadHalf=a!==x.None?a:s,this.noteHeadWhole=r!==x.None?r:s,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case u.Whole:return this.noteHeadWhole;case u.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class Ne{static articulationFromElementVariation(e,t){return e<Ne.gp6ElementAndVariationToArticulation.length?(t>=Ne.gp6ElementAndVariationToArticulation.length&&(t=0),Ne.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]:Ne.getArticulationByValue(t)}static getElementAndVariation(e){const t=Ne.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<Ne.gp6ElementAndVariationToArticulation.length;e++){const i=Ne.gp6ElementAndVariationToArticulation[e];for(let s=0;s<i.length;s++){const a=Ne.getArticulationByValue(i[s]);if((null==a?void 0:a.outputMidiNumber)===t.outputMidiNumber)return[e,s]}}return[-1,-1]}static getArticulationByValue(e){return Ne.instrumentArticulations.has(e)?Ne.instrumentArticulations.get(e):null}}Ne.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]],Ne.instrumentArticulations=new Map([[38,new ve("snare",3,38,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[37,new ve("snare",3,37,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[91,new ve("snare",3,38,x.NoteheadDiamondWhite,x.NoteheadDiamondWhite,x.NoteheadDiamondWhite)],[42,new ve("hiHat",-1,42,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[92,new ve("hiHat",-1,46,x.NoteheadCircleSlash,x.NoteheadCircleSlash,x.NoteheadCircleSlash)],[46,new ve("hiHat",-1,46,x.NoteheadCircleX,x.NoteheadCircleX,x.NoteheadCircleX)],[44,new ve("hiHat",9,44,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[35,new ve("kickDrum",8,35,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[36,new ve("kickDrum",7,36,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[50,new ve("tom",1,50,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[48,new ve("tom",2,48,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[47,new ve("tom",4,47,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[45,new ve("tom",5,45,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[43,new ve("tom",6,43,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[93,new ve("ride",0,51,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack,x.PictEdgeOfCymbal,E.Bottom)],[51,new ve("ride",0,51,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[53,new ve("ride",0,53,x.NoteheadDiamondWhite,x.NoteheadDiamondWhite,x.NoteheadDiamondWhite)],[94,new ve("ride",0,51,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack,x.ArticStaccatoAbove,E.Top)],[55,new ve("splash",-2,55,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[95,new ve("splash",-2,55,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack,x.ArticStaccatoAbove,E.Bottom)],[52,new ve("china",-3,52,x.NoteheadHeavyXHat,x.NoteheadHeavyXHat,x.NoteheadHeavyXHat)],[96,new ve("china",-3,52,x.NoteheadHeavyXHat,x.NoteheadHeavyXHat,x.NoteheadHeavyXHat)],[49,new ve("crash",-2,49,x.NoteheadHeavyX,x.NoteheadHeavyX,x.NoteheadHeavyX)],[97,new ve("crash",-2,49,x.NoteheadHeavyX,x.NoteheadHeavyX,x.NoteheadHeavyX,x.ArticStaccatoAbove,E.Bottom)],[57,new ve("crash",-1,57,x.NoteheadHeavyX,x.NoteheadHeavyX,x.NoteheadHeavyX)],[98,new ve("crash",-1,57,x.NoteheadHeavyX,x.NoteheadHeavyX,x.NoteheadHeavyX,x.ArticStaccatoAbove,E.Bottom)],[99,new ve("cowbell",1,56,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpHalf,x.NoteheadTriangleUpWhole)],[100,new ve("cowbell",1,56,x.NoteheadXBlack,x.NoteheadXHalf,x.NoteheadXWhole)],[56,new ve("cowbell",0,56,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpHalf,x.NoteheadTriangleUpWhole)],[101,new ve("cowbell",0,56,x.NoteheadXBlack,x.NoteheadXHalf,x.NoteheadXWhole)],[102,new ve("cowbell",-1,56,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpHalf,x.NoteheadTriangleUpWhole)],[103,new ve("cowbell",-1,56,x.NoteheadXBlack,x.NoteheadXHalf,x.NoteheadXWhole)],[77,new ve("woodblock",-9,77,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack)],[76,new ve("woodblock",-10,76,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack)],[60,new ve("bongo",-4,60,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[104,new ve("bongo",-5,60,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.NoteheadParenthesis,E.Middle)],[105,new ve("bongo",-6,60,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[61,new ve("bongo",-7,61,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[106,new ve("bongo",-8,61,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.NoteheadParenthesis,E.Middle)],[107,new ve("bongo",-16,61,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[66,new ve("timbale",10,66,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[65,new ve("timbale",9,65,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[68,new ve("agogo",12,68,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[67,new ve("agogo",11,67,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[64,new ve("conga",17,64,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[108,new ve("conga",16,64,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[109,new ve("conga",15,64,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.NoteheadParenthesis,E.Middle)],[63,new ve("conga",14,63,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[110,new ve("conga",13,63,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[62,new ve("conga",19,62,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.NoteheadParenthesis,E.Middle)],[72,new ve("whistle",-11,72,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[71,new ve("whistle",-17,71,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[73,new ve("guiro",38,73,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[74,new ve("guiro",37,74,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[86,new ve("surdo",36,86,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[87,new ve("surdo",35,87,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadParenthesis,E.Middle)],[54,new ve("tambourine",3,54,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack)],[111,new ve("tambourine",2,54,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack,x.StringsUpBow,E.Bottom)],[112,new ve("tambourine",1,54,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack,x.StringsDownBow,E.Bottom)],[113,new ve("tambourine",-7,54,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[79,new ve("cuica",30,79,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[78,new ve("cuica",29,78,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[58,new ve("vibraslap",28,58,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[81,new ve("triangle",27,81,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[80,new ve("triangle",26,80,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadParenthesis,E.Middle)],[114,new ve("grancassa",25,43,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[115,new ve("piatti",18,49,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[116,new ve("piatti",24,49,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[69,new ve("cabasa",23,69,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[117,new ve("cabasa",22,69,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.StringsUpBow,E.Bottom)],[85,new ve("castanets",21,85,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[75,new ve("claves",20,75,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[70,new ve("maraca",-12,70,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[118,new ve("maraca",-13,70,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.StringsUpBow,E.Bottom)],[119,new ve("maraca",-14,70,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[120,new ve("maraca",-15,70,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.StringsUpBow,E.Bottom)],[82,new ve("shaker",-23,54,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[122,new ve("shaker",-24,54,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.StringsUpBow,E.Bottom)],[84,new ve("bellTree",-18,53,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[123,new ve("bellTree",-19,53,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.StringsUpBow,E.Bottom)],[83,new ve("jingleBell",-20,53,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[124,new ve("unpitched",-21,62,x.NoteheadNull,x.NoteheadNull,x.NoteheadNull,x.GuitarGolpe,E.Top)],[125,new ve("unpitched",-22,62,x.NoteheadNull,x.NoteheadNull,x.NoteheadNull,x.GuitarGolpe,E.Bottom)],[39,new ve("handClap",3,39,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[40,new ve("snare",3,40,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[31,new ve("snare",3,40,x.NoteheadSlashedBlack2,x.NoteheadSlashedBlack2,x.NoteheadSlashedBlack2)],[41,new ve("tom",5,41,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[59,new ve("ride",2,59,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack,x.PictEdgeOfCymbal,E.Bottom)],[126,new ve("ride",2,59,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[127,new ve("ride",2,59,x.NoteheadDiamondWhite,x.NoteheadDiamondWhite,x.NoteheadDiamondWhite)],[29,new ve("ride",2,59,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack,x.ArticStaccatoAbove,E.Top)],[30,new ve("crash",-3,49,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[33,new ve("snare",3,37,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[34,new ve("snare",3,38,x.NoteheadBlack,x.NoteheadBlack,x.NoteheadBlack)]]);class xe{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1}}class Pe{constructor(){this.id=Pe.GlobalNoteId++,this.index=0,this.accentuated=s.None,this.bendType=l.None,this.bendStyle=h.Default,this.bendOrigin=null,this.isContinuedBend=!1,this.bendPoints=null,this.maxBendPoint=null,this.fret=-1,this.string=-1,this.octave=-1,this.tone=-1,this.percussionArticulation=-1,this.isVisible=!0,this.isLeftHandTapped=!1,this.isHammerPullOrigin=!1,this.hammerPullOrigin=null,this.hammerPullDestination=null,this.isSlurDestination=!1,this.slurOrigin=null,this.slurDestination=null,this.harmonicType=m.None,this.harmonicValue=0,this.isGhost=!1,this.isLetRing=!1,this.letRingDestination=null,this.isPalmMute=!1,this.palmMuteDestination=null,this.isDead=!1,this.isStaccato=!1,this.slideInType=b.None,this.slideOutType=S.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=_.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=f.Unknown,this.rightHandFinger=f.Unknown,this.isFingering=!1,this.trillValue=-1,this.trillSpeed=u.ThirtySecond,this.durationPercent=1,this.accidentalMode=y.Default,this.dynamics=p.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this._noteIdBag=null}get hasBend(){return null!==this.bendPoints&&this.bendType!==l.None}get isStringed(){return this.string>=0}get isPiano(){return!this.isStringed&&this.octave>=0&&this.tone>=0}get isPercussion(){return!this.isStringed&&this.percussionArticulation>=0}get element(){return this.isPercussion?Ne.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?Ne.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==m.None}get isTieOrigin(){return null!==this.tieDestination}get trillFret(){return this.trillValue-this.stringTuning}get isTrill(){return this.trillValue>=0}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get stringTuning(){return this.beat.voice.bar.staff.capo+Pe.getStringTuning(this.beat.voice.bar.staff,this.string)}static getStringTuning(e,t){return e.tuning.length>0?e.tuning[e.tuning.length-(t-1)-1]:0}get realValue(){let e=this.realValueWithoutHarmonic;return this.isStringed&&(this.harmonicType===m.Natural?e=this.harmonicPitch+this.stringTuning-this.beat.voice.bar.staff.transpositionPitch:e+=this.harmonicPitch),e}get realValueWithoutHarmonic(){return this.isPercussion?this.percussionArticulation:this.isStringed?this.fret+this.stringTuning-this.beat.voice.bar.staff.transpositionPitch:this.isPiano?12*this.octave+this.tone-this.beat.voice.bar.staff.transpositionPitch:0}get harmonicPitch(){if(this.harmonicType===m.None||!this.isStringed)return 0;let e=this.harmonicValue;return ke.isAlmostEqualTo(e,2.4)?36:ke.isAlmostEqualTo(e,2.7)?34:e<3?0:e<=3.5?31:e<=4?28:e<=5?24:e<=6?34:e<=7?19:e<=8.5?36:e<=9?28:e<=10?34:e<=11?0:e<=12?12:e<14?0:e<=15?34:e<=16?28:e<=17?36:e<=18?0:e<=19?19:e<=21?0:e<=22?36:e<=24?24:0}get initialBendValue(){return this.hasBend?Math.floor(this.bendPoints[0].value/2):this.bendOrigin?Math.floor(this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value/2):this.isTieDestination&&this.tieOrigin.bendOrigin?Math.floor(this.tieOrigin.bendOrigin.bendPoints[this.tieOrigin.bendOrigin.bendPoints.length-1].value/2):this.beat.hasWhammyBar?Math.floor(this.beat.whammyBarPoints[0].value/2):this.beat.isContinuedWhammy?Math.floor(this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value/2):0}get displayValue(){return this.displayValueWithoutBend+this.initialBendValue}get displayValueWithoutBend(){let e=this.realValue;switch(this.harmonicType!==m.Natural&&this.harmonicType!==m.None&&(e-=this.harmonicPitch),this.beat.ottava){case n._15ma:e-=24;break;case n._8va:e-=12;break;case n.Regular:break;case n._8vb:e+=12;break;case n._15mb:e+=24}switch(this.beat.voice.bar.clefOttava){case n._15ma:e-=24;break;case n._8va:e-=12;break;case n.Regular:break;case n._8vb:e+=12;break;case n._15mb:e+=24}return e-this.beat.voice.bar.staff.displayTranspositionPitch}get hasQuarterToneOffset(){return this.hasBend?this.bendPoints[0].value%2!=0:this.bendOrigin?this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value%2!=0:this.beat.hasWhammyBar?this.beat.whammyBarPoints[0].value%2!=0:!!this.beat.isContinuedWhammy&&this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value%2!=0}addBendPoint(e){let t=this.bendPoints;null===t&&(t=[],this.bendPoints=t),t.push(e),(!this.maxBendPoint||e.value>this.maxBendPoint.value)&&(this.maxBendPoint=e),this.bendType===l.None&&(this.bendType=l.Custom)}finish(e,t=null){let i=new _e((()=>Pe.nextNoteOnSameLine(this))),s=e&&e.notation.notationMode===T.SongBook;if(this.isTieDestination&&(this.chain(t),s&&this.tieOrigin&&this.tieOrigin.isLetRing&&(this.isLetRing=!0)),this.isLetRing&&(i.value&&i.value.isLetRing?this.letRingDestination=i.value:this.letRingDestination=this,s&&this.isTieDestination&&!this.tieOrigin.hasBend&&(this.isVisible=!1)),this.isPalmMute&&(i.value&&i.value.isPalmMute?this.palmMuteDestination=i.value:this.palmMuteDestination=this),this.isHammerPullOrigin){let e=Pe.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case S.Shift:case S.Legato:this.slideTarget=i.value,this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=S.None}let a=null;this.isHammerPullOrigin&&this.hammerPullDestination?a=this.hammerPullDestination:this.slideOutType===S.Legato&&this.slideTarget&&(a=this.slideTarget),a&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===N.None?(this.effectSlurOrigin.effectSlurDestination=a,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=a,this.effectSlurDestination.effectSlurOrigin=this));const r=this.bendPoints;if(null!=r&&r.length>0&&this.bendType===l.Custom){let e=this.isTieDestination&&this.tieOrigin.hasBend;if(this.isContinuedBend=e,4===r.length){let t=r[0],i=r[1],s=r[2],a=r[3];i.value===s.value?a.value>t.value?i.value>a.value?this.bendType=l.BendRelease:!e&&t.value>0?(this.bendType=l.PrebendBend,r.splice(2,1),r.splice(1,1)):(this.bendType=l.Bend,r.splice(2,1),r.splice(1,1)):a.value<t.value?e?(this.bendType=l.Release,r.splice(2,1),r.splice(1,1)):(this.bendType=l.PrebendRelease,r.splice(2,1),r.splice(1,1)):i.value>t.value?this.bendType=l.BendRelease:t.value>0&&!e?(this.bendType=l.Prebend,r.splice(2,1),r.splice(1,1)):(this.bendType=l.Hold,r.splice(2,1),r.splice(1,1)):Be.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===r.length){let t=r[0],i=r[1];i.value>t.value?!e&&t.value>0?this.bendType=l.PrebendBend:this.bendType=l.Bend:i.value<t.value?this.bendType=e?l.Release:l.PrebendRelease:this.bendType=l.Hold}}else null!==r&&0!==r.length||(this.bendType=l.None);this.initialBendValue>0&&(this.accidentalMode=y.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+Pe.MaxOffsetForSameLineSearch;){let 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+Pe.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-Pe.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(Pe.NoteIdLookupKey)?t=e.get(Pe.NoteIdLookupKey):(t=new Map,e.set(Pe.NoteIdLookupKey,t)),-1===this._noteIdBag.hammerPullDestinationNoteId&&-1===this._noteIdBag.tieDestinationNoteId&&-1===this._noteIdBag.slurDestinationNoteId||t.set(this.id,this),-1!==this._noteIdBag.hammerPullOriginNoteId&&(this.hammerPullOrigin=t.get(this._noteIdBag.hammerPullOriginNoteId),this.hammerPullOrigin.hammerPullDestination=this),-1!==this._noteIdBag.tieOriginNoteId&&(this.tieOrigin=t.get(this._noteIdBag.tieOriginNoteId),this.tieOrigin.tieDestination=this),-1!==this._noteIdBag.slurOriginNoteId&&(this.slurOrigin=t.get(this._noteIdBag.slurOriginNoteId),this.slurOrigin.slurDestination=this),this._noteIdBag=null}else{if(!this.isTieDestination&&null==this.tieOrigin)return;let e=Pe.findTieOrigin(this);e?(e.tieDestination=this,this.tieOrigin=e,this.fret=e.fret,this.octave=e.octave,this.tone=e.tone,e.hasBend&&(this.bendOrigin=this.tieOrigin)):this.isTieDestination=!1}}toJson(e){null!==this.tieDestination&&e.set("tiedestinationnoteid",this.tieDestination.id),null!==this.tieOrigin&&e.set("tieoriginnoteid",this.tieOrigin.id),null!==this.slurDestination&&e.set("slurdestinationnoteid",this.slurDestination.id),null!==this.slurOrigin&&e.set("sluroriginnoteid",this.slurOrigin.id),null!==this.hammerPullOrigin&&e.set("hammerpulloriginnoteid",this.hammerPullOrigin.id),null!==this.hammerPullDestination&&e.set("hammerpulldestinationnoteid",this.hammerPullDestination.id)}setProperty(e,t){switch(e){case"tiedestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new xe),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new xe),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new xe),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new xe),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new xe),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new xe),this._noteIdBag.hammerPullDestinationNoteId=t,!0}return!1}}Pe.GlobalNoteId=0,Pe.MaxOffsetForSameLineSearch=3,Pe.NoteIdLookupKey="NoteIdLookup";class Ee{constructor(e){this._isEqualLengthTuplet=!0,this.totalDuration=0,this.beats=[],this.isFull=!1,this.voice=e}check(e){if(0===this.beats.length)return this.beats.push(e),this.totalDuration+=e.playbackDuration,!0;if(e.graceType!==g.None)return!0;if(e.voice!==this.voice||this.isFull||e.tupletNumerator!==this.beats[0].tupletNumerator||e.tupletDenominator!==this.beats[0].tupletDenominator)return!1;if(e.playbackDuration!==this.beats[0].playbackDuration&&(this._isEqualLengthTuplet=!1),this.beats.push(e),this.totalDuration+=e.playbackDuration,this._isEqualLengthTuplet)this.beats.length===this.beats[0].tupletNumerator&&(this.isFull=!0);else{let e=this.beats[0].tupletNumerator/this.beats[0].tupletDenominator|0;for(let t of Ee.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}Ee.HalfTicks=1920,Ee.QuarterTicks=960,Ee.EighthTicks=480,Ee.SixteenthTicks=240,Ee.ThirtySecondTicks=120,Ee.SixtyFourthTicks=60,Ee.OneHundredTwentyEighthTicks=30,Ee.TwoHundredFiftySixthTicks=15,Ee.AllTicks=[Ee.HalfTicks,Ee.QuarterTicks,Ee.EighthTicks,Ee.SixteenthTicks,Ee.ThirtySecondTicks,Ee.SixtyFourthTicks,Ee.OneHundredTwentyEighthTicks,Ee.TwoHundredFiftySixthTicks],function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Dive=2]="Dive",e[e.Dip=3]="Dip",e[e.Hold=4]="Hold",e[e.Predive=5]="Predive",e[e.PrediveDive=6]="PrediveDive"}(C||(C={}));class Ce{static clone(e){const t=new be;return t.offset=e.offset,t.value=e.value,t}}class Fe{static clone(e){const t=new Pe;if(t.index=e.index,t.accentuated=e.accentuated,t.bendType=e.bendType,t.bendStyle=e.bendStyle,t.isContinuedBend=e.isContinuedBend,e.bendPoints){t.bendPoints=[];for(const i of e.bendPoints)t.addBendPoint(Ce.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 Le{static clone(e){const t=new fe;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class Me{static clone(e){const t=new Ie;t.index=e.index,t.notes=[];for(const i of e.notes)t.addNote(Fe.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(Le.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(Ce.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 De{constructor(){this.beats=[],this.id="empty",this.isComplete=!1}addBeat(e){e.graceIndex=this.beats.length,e.graceGroup=this,this.beats.push(e)}finish(){this.beats.length>0&&(this.id=this.beats[0].absoluteDisplayStart+"_"+this.beats[0].voice.index)}}!function(e){e[e.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext"}(F||(F={}));class Ie{constructor(){this.id=Ie._globalBeatId++,this.index=0,this.previousBeat=null,this.nextBeat=null,this.notes=[],this.noteStringLookup=new Map,this.noteValueLookup=new Map,this.isEmpty=!1,this.whammyStyle=h.Default,this.ottava=n.Regular,this.fermata=null,this.isLegatoOrigin=!1,this.minNote=null,this.maxNote=null,this.maxStringNote=null,this.minStringNote=null,this.duration=u.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fadeIn=!1,this.lyrics=null,this.hasRasgueado=!1,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.brushType=d.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=C.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=_.None,this.chordId=null,this.graceType=g.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=N.None,this.tremoloSpeed=null,this.crescendo=c.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.dynamics=p.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=F.Auto}get isLastOfVoice(){return this.index===this.voice.beats.length-1}get isLegatoDestination(){return!!this.previousBeat&&this.previousBeat.isLegatoOrigin}get isRest(){return this.isEmpty||0===this.notes.length}get isFullBarRest(){return this.isRest&&1===this.voice.beats.length&&this.duration===u.Whole}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==C.None}get hasChord(){return!!this.chordId}get chord(){return this.chordId?this.voice.bar.staff.getChord(this.chordId):null}get isTremolo(){return!!this.tremoloSpeed}get absoluteDisplayStart(){return this.voice.bar.masterBar.start+this.displayStart}get absolutePlaybackStart(){return this.voice.bar.masterBar.start+this.playbackStart}get isEffectSlurDestination(){return!!this.effectSlurOrigin}addWhammyBarPoint(e){let t=this.whammyBarPoints;null===t&&(t=[],this.whammyBarPoints=t),t.push(e),(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e),(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e),this.whammyBarType===C.None&&(this.whammyBarType=C.Custom)}removeWhammyBarPoint(e){const t=this.whammyBarPoints;if(null===t||e<0||e>=t.length)return;t.splice(e,1);let 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=ye.toTicks(this.duration);return 2===this.dots?e=ye.applyDot(e,!0):1===this.dots&&(e=ye.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=ye.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){let e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case g.BeforeBeat:case g.OnBeat:switch(this.duration){case u.Sixteenth:this.playbackDuration=ye.toTicks(u.SixtyFourth);break;case u.ThirtySecond:this.playbackDuration=ye.toTicks(u.OneHundredTwentyEighth);break;default:this.playbackDuration=ye.toTicks(u.ThirtySecond)}this.displayDuration=0;break;case g.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;let t=this.previousBeat;t&&t.graceType===g.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){let e=this.previousBeat,t=e?e.tupletGroup:null;(this.hasTuplet||this.graceType!==g.None&&t)&&(e&&t&&t.check(this)||(t=new Ee(this.voice),t.check(this)),this.tupletGroup=t)}finish(e,t=null){switch(null===this.getAutomation(a.Instrument)&&0===this.index&&0===this.voice.index&&0===this.voice.bar.index&&0===this.voice.bar.staff.index&&this.automations.push(fe.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case g.OnBeat:case g.BeforeBeat:let e=this.graceGroup.beats.length;this.duration=1===e?u.Eighth:2===e?u.Sixteenth:u.ThirtySecond}let i=e?e.notation.notationMode:T.GuitarPro,s="grad"===this.text||"grad."===this.text;s&&i===T.SongBook&&(this.text="");let r=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let n=0,o=!1;for(let a=0,d=this.notes.length;a<d;a++){let d=this.notes[a];if(d.dynamics=this.dynamics,d.finish(e,t),d.isLetRing&&(this.isLetRing=!0),d.isPalmMute&&(this.isPalmMute=!0),i===T.SongBook&&d.hasBend&&this.graceType!==g.BendGrace){if(!d.isTieOrigin)switch(d.bendType){case l.Bend:case l.PrebendRelease:case l.PrebendBend:r=!0}s||d.bendStyle===h.Gradual?(s=!0,d.bendStyle=h.Gradual,r=!1):d.bendStyle=h.Fast}d.isVisible&&(n++,(!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&&(o=!0))}if(o&&(this.effectSlurOrigin?(this.effectSlurOrigin.effectSlurDestination=this.nextBeat,this.effectSlurOrigin.effectSlurDestination&&(this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin),this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=this.nextBeat,this.effectSlurDestination&&(this.effectSlurDestination.effectSlurOrigin=this))),this.notes.length>0&&0===n&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&e&&e.notation.notationMode===T.GuitarPro&&(this.previousBeat.isLetRing&&(this.isLetRing=!0),this.previousBeat.isPalmMute&&(this.isPalmMute=!0));else{let e=this.previousBeat;for(;e&&e.isRest;)this.isLetRing||(e.isLetRing=!1),this.isPalmMute||(e.isPalmMute=!1),e=e.previousBeat}const d=this.whammyBarPoints;if(null!==d&&d.length>0&&this.whammyBarType===C.Custom){i===T.SongBook&&(this.whammyStyle=s?h.Gradual:h.Fast);let e=!!this.previousBeat&&this.previousBeat.hasWhammyBar;if(this.isContinuedWhammy=e,4===d.length){let t=d[0],s=d[1],a=d[2],r=d[3];s.value===a.value?t.value<s.value&&s.value<r.value||t.value>s.value&&s.value>r.value?(0===t.value||e?this.whammyBarType=C.Dive:this.whammyBarType=C.PrediveDive,d.splice(2,1),d.splice(1,1)):t.value>s.value&&s.value<r.value||t.value<s.value&&s.value>r.value?(this.whammyBarType=C.Dip,s.offset!==a.offset&&i!==T.SongBook||d.splice(2,1)):t.value===s.value&&s.value===r.value?(0===t.value||e?this.whammyBarType=C.Hold:this.whammyBarType=C.Predive,d.splice(2,1),d.splice(1,1)):Be.warning("Model","Unsupported whammy type detected, fallback to custom"):Be.warning("Model","Unsupported whammy type detected, fallback to custom")}}if(this.updateDurations(),r){let e=Me.clone(this);e.id=Ie._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=l.None,i.maxBendPoint=null,i.bendPoints=null,i.bendStyle=h.Default,i.id=Pe.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=Pe.findTieOrigin(s);if(e&&e.hasBend){i.bendType=l.Hold;let e=s.bendPoints[s.bendPoints.length-1];i.addBendPoint(new be(0,e.value)),i.addBendPoint(new be(be.MaxPosition,e.value))}}i.isTieDestination=!0}this.graceType=g.BendGrace,this.graceGroup=new De,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new De,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)}}Ie._globalBeatId=0;class Re{constructor(){this.name="",this.firstFret=1,this.strings=[],this.barreFrets=[],this.showName=!0,this.showDiagram=!0,this.showFingering=!0}}!function(e){e[e.Cb=-7]="Cb",e[e.Gb=-6]="Gb",e[e.Db=-5]="Db",e[e.Ab=-4]="Ab",e[e.Eb=-3]="Eb",e[e.Bb=-2]="Bb",e[e.F=-1]="F",e[e.C=0]="C",e[e.G=1]="G",e[e.D=2]="D",e[e.A=3]="A",e[e.E=4]="E",e[e.B=5]="B",e[e.FSharp=6]="FSharp",e[e.CSharp=7]="CSharp"}(L||(L={})),function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.Text=2]="Text",e[e.Comment=3]="Comment",e[e.Dash=4]="Dash"}(M||(M={}));class Ae{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=M.Begin,r=M.Begin,n=!1,o=0;for(;t<e.length;){let i=e.charCodeAt(t);switch(a){case M.IgnoreSpaces:switch(i){case Ae.CharCodeLF:case Ae.CharCodeCR:case Ae.CharCodeTab:break;case Ae.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case M.Begin:if(i!==Ae.CharCodeBrackedOpen){o=t,a=M.Text;continue}a=M.Comment;break;case M.Comment:if(i===Ae.CharCodeBrackedClose)a=M.Begin;break;case M.Text:switch(i){case Ae.CharCodeDash:a=M.Dash;break;case Ae.CharCodeCR:case Ae.CharCodeLF:case Ae.CharCodeSpace:let i=e.substr(o,t-o);this.addChunk(i,s),a=M.IgnoreSpaces,r=M.Begin}break;case M.Dash:if(i!==Ae.CharCodeDash){let i=e.substr(o,t-o);this.addChunk(i,s),n=!0,a=M.IgnoreSpaces,r=M.Begin;continue}}t+=1}a===M.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}}Ae.CharCodeLF=10,Ae.CharCodeTab=9,Ae.CharCodeCR=13,Ae.CharCodeSpace=32,Ae.CharCodeBrackedClose=93,Ae.CharCodeBrackedOpen=91,Ae.CharCodeDash=45,function(e){e[e.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"}(I||(I={}));class Oe{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=L.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=I.NoTripletFeel,this.section=null,this.tempoAutomation=null,this.fermata=null,this.start=0,this.isAnacrusis=!1}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}calculateDuration(e=!0){if(this.isAnacrusis&&e){let e=0;for(let t of this.score.tracks)for(let 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*ye.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}}Oe.MaxAlternateEndings=8;class Ge{constructor(){this.hideDynamics=!1}}class Ve{constructor(){this.masterBars=[],this.opening=null,this.closings=[],this.isClosed=!1}get openings(){const e=this.opening;return e?[e]:[]}get isOpened(){var e;return!0===(null===(e=this.opening)||void 0===e?void 0:e.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 He{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.stylesheet=new Ge}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){var t;e.isRepeatStart?((null===(t=this._currentRepeatGroup)||void 0===t?void 0:t.isClosed)&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--),this._currentRepeatGroup=new Ve,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new Ve,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 We{constructor(){this.marker="",this.text=""}}class ze extends pe{constructor(e){super(i.Format,e),Object.setPrototypeOf(this,ze.prototype)}}class Ue{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="#"+ke.toHexString(this.r,2)+ke.toHexString(this.g,2)+ke.toHexString(this.b,2):this.rgba=`rgba(${this.r},${this.g},${this.b},${this.a/255})`}get a(){return this.raw>>24&255}get r(){return this.raw>>16&255}get g(){return this.raw>>8&255}get b(){return 255&this.raw}static random(e=100){return new Ue(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){switch(typeof e){case"number":{const t=new Ue(0,0,0,0);return t.raw=e,t.updateRgba(),t}case"string":{const t=e;if(t.startsWith("#")){if(4===t.length)return new Ue(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16));if(5===t.length)return new Ue(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 Ue(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16));if(9===t.length)return new Ue(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 ze("No values specified for rgb/rgba function");const s=t.substring(e+1,i).split(",");if(3===s.length)return new Ue(parseInt(s[0]),parseInt(s[1]),parseInt(s[2]));if(4===s.length)return new Ue(parseInt(s[0]),parseInt(s[1]),parseInt(s[2]),255*parseFloat(s[3]))}return null}}throw new ze("Unsupported format for color")}static toJson(e){return e.raw}}Ue.BlackRgb="#000000";class Xe{constructor(){this.volume=15,this.balance=8,this.port=1,this.program=0,this.primaryChannel=0,this.secondaryChannel=0,this.isMute=!1,this.isSolo=!1}}class Ye{static getTextForTuning(e,t){let i=Ye.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 Ye._defaultTunings.has(e)?Ye._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return Ye._sevenStrings;case 6:return Ye._sixStrings;case 5:return Ye._fiveStrings;case 4:return Ye._fourStrings}return[]}static initialize(){Ye._defaultTunings.set(7,new Ye("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),Ye._sevenStrings.push(Ye._defaultTunings.get(7)),Ye._defaultTunings.set(6,new Ye("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),Ye._sixStrings.push(Ye._defaultTunings.get(6)),Ye._sixStrings.push(new Ye("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),Ye._sixStrings.push(new Ye("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),Ye._sixStrings.push(new Ye("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),Ye._sixStrings.push(new Ye("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),Ye._sixStrings.push(new Ye("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),Ye._sixStrings.push(new Ye("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),Ye._defaultTunings.set(5,new Ye("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),Ye._fiveStrings.push(Ye._defaultTunings.get(5)),Ye._fiveStrings.push(new Ye("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),Ye._fiveStrings.push(new Ye("Banjo Open D Tuning",[62,57,54,50,69],!1)),Ye._fiveStrings.push(new Ye("Banjo Open G Tuning",[62,59,55,50,67],!1)),Ye._fiveStrings.push(new Ye("Banjo G Minor Tuning",[62,58,55,50,67],!1)),Ye._fiveStrings.push(new Ye("Banjo G Modal Tuning",[62,57,55,50,67],!1)),Ye._defaultTunings.set(4,new Ye("Bass Standard Tuning",[43,38,33,28],!0)),Ye._fourStrings.push(Ye._defaultTunings.get(4)),Ye._fourStrings.push(new Ye("Bass Tune down ½ step",[42,37,32,27],!1)),Ye._fourStrings.push(new Ye("Bass Tune down 1 step",[41,36,31,26],!1)),Ye._fourStrings.push(new Ye("Bass Tune down 2 step",[39,34,29,24],!1)),Ye._fourStrings.push(new Ye("Bass Dropped D Tuning",[43,38,33,26],!1)),Ye._fourStrings.push(new Ye("Ukulele C Tuning",[45,40,36,43],!1)),Ye._fourStrings.push(new Ye("Ukulele G Tuning",[52,47,43,38],!1)),Ye._fourStrings.push(new Ye("Mandolin Standard Tuning",[64,57,50,43],!1)),Ye._fourStrings.push(new Ye("Mandolin or Violin Tuning",[76,69,62,55],!1)),Ye._fourStrings.push(new Ye("Viola Tuning",[69,62,55,48],!1)),Ye._fourStrings.push(new Ye("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){let t=Ye.getPresetsFor(e.length);for(let 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=null!=t?t:[]}finish(){const e=Ye.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}Ye._sevenStrings=[],Ye._sixStrings=[],Ye._fiveStrings=[],Ye._fourStrings=[],Ye._defaultTunings=new Map,Ye.defaultAccidentals=["","#","","#","","","#","","#","","#",""],Ye.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],Ye.initialize();class qe{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new Ye("",[],!1),this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=5}get tuning(){return this.stringTuning.tunings}get tuningName(){return this.stringTuning.name}get isStringed(){return this.stringTuning.tunings.length>0}finish(e,t=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){var t,i;return null!==(i=null===(t=this.chords)||void 0===t?void 0:t.has(e))&&void 0!==i&&i}getChord(e){var t,i;return null!==(i=null===(t=this.chords)||void 0===t?void 0:t.get(e))&&void 0!==i?i:null}addBar(e){let t=this.bars;e.staff=this,e.index=t.length,t.length>0&&(e.previousBar=t[t.length-1],e.previousBar.nextBar=e),t.push(e)}}class Je{constructor(){this.index=0,this.staves=[],this.playbackInfo=new Xe,this.color=new Ue(200,0,0,255),this.name="",this.shortName="",this.percussionArticulations=[]}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new qe)}addStaff(e){e.index=this.staves.length,e.track=this,this.staves.push(e)}finish(e,t=null){this.shortName||(this.shortName=this.name,this.shortName.length>Je.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,Je.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)}}}}}Je.ShortNameMaxLength=10;class je{constructor(){this.id=je._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===g.None?(s.graceGroup=i,i&&(i.isComplete=!0),i=null):(i||(i=new De),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===g.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==g.BendGrace){let i=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case g.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 g.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}}je._globalBarId=0;class Qe{static float64ToBytes(e){return Qe._dataView.setFloat64(0,e,!0),this._conversionByteArray}static bytesToFloat64(e){throw Qe._conversionByteArray.set(e,0),Qe._dataView.getFloat64(0,!0)}static uint16ToInt16(e){return Qe._dataView.setUint16(0,e,!0),Qe._dataView.getInt16(0,!0)}static int16ToUint32(e){return Qe._dataView.setInt16(0,e,!0),Qe._dataView.getUint32(0,!0)}static int32ToUint16(e){return Qe._dataView.setInt32(0,e,!0),Qe._dataView.getUint16(0,!0)}static int32ToInt16(e){return Qe._dataView.setInt32(0,e,!0),Qe._dataView.getInt16(0,!0)}static int32ToUint32(e){return Qe._dataView.setInt32(0,e,!0),Qe._dataView.getUint32(0,!0)}static uint8ToInt8(e){return Qe._dataView.setUint8(0,e),Qe._dataView.getInt8(0)}}Qe._conversionBuffer=new ArrayBuffer(8),Qe._conversionByteArray=new Uint8Array(Qe._conversionBuffer),Qe._dataView=new DataView(Qe._conversionBuffer);class $e{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 Qe.int32ToUint16(i<<8|t)}static readInt16LE(e){let t=e.readByte(),i=e.readByte();return Qe.int32ToInt16(i<<8|t)}static readUInt32BE(e){let t=e.readByte(),i=e.readByte(),s=e.readByte(),a=e.readByte();return Qe.int32ToUint32(t<<24|i<<16|s<<8|a)}static readUInt16BE(e){let t=e.readByte(),i=e.readByte();return Qe.int32ToInt16(t<<8|i)}static readInt16BE(e){let t=e.readByte(),i=e.readByte();return Qe.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),$e.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==(8388608&i)&&(i|=255<<24),i}static readInt16(e,t){return Qe.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){let i=$e.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(t>>0&255)}static writeInt32LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255),e.writeByte(t>>16&255),e.writeByte(t>>24&255)}static writeUInt16LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255)}static writeInt16LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255)}}class 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=$e.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}}!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"}(R||(R={}));class Ze extends pe{constructor(e,t,s,a,r,n,o,h=null){super(i.AlphaTex,e),this.position=t,this.line=s,this.col=a,this.nonTerm=null!=r?r:"",this.expected=null!=n?n:R.No,this.symbol=null!=o?o:R.No,this.symbolData=h,Object.setPrototypeOf(this,Ze.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 ${R[a]} found a ${R[r]}`,null!==n&&(o+=`: '${n}'`)):o+=`, invalid value: '${n}'`,new Ze(o,e,t,i,s,a,r,n)}static errorMessage(e,t,i,s){return new Ze(e=`MalFormed AlphaTex: @${t} (line ${i}, col ${s}): ${e}`,t,i,s,null,null,null,null)}}class et extends ue{constructor(){super(),this._trackChannel=0,this._input="",this._ch=et.Eof,this._curChPos=0,this._line=1,this._col=0,this._lastValidSpot=[0,1,0],this._sy=R.No,this._syData="",this._allowNegatives=!1,this._allowTuning=!1,this._currentDuration=u.QuadrupleWhole,this._currentDynamics=p.PPP,this._currentTuplet=0,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=Ke.empty(),this._input=e,this.settings=t}readScore(){try{if(this.data.length>0&&(this._input=$e.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this.createDefaultScore(),this._curChPos=0,this._line=1,this._col=0,this.saveValidSpot(),this._currentDuration=u.Quarter,this._currentDynamics=p.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===R.LowerThan)throw new ge("Unknown start sign '<' (meant to import as XML?)");if(this._sy===R.Eof)throw new ge("Unexpected end of file");const e=this.metaData(),t=this.bars();if(!e&&!t)throw new ge("No alphaTex data found");this.consolidate(),this._score.finish(this.settings),this._score.rebuildRepeatGroups();for(const[e,t]of this._lyrics)this._score.tracks[e].applyLyrics(t);return this._score}catch(e){throw e instanceof Ze?new ge(e.message,e):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 Ie;i.isEmpty=!0,e.voices[0].addBeat(i)}}error(e,t,i=!0){let s,a=!1;i?(s=this._sy,s!==R.String&&s!==R.Number&&s!==R.MetaCommand||(a=!0)):s=t;let r=Ze.symbolError(this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2],e,t,s,a?this._syData:null);throw this.logErrors&&Be.error(this.name,r.message),r}errorMessage(e){let t=Ze.errorMessage(e,this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2]);throw this.logErrors&&Be.error(this.name,t.message),t}createDefaultScore(){this._score=new He,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new Je,this._currentTrack.ensureStaveCount(1),this._currentTrack.playbackInfo.program=25,this._currentTrack.playbackInfo.primaryChannel=this._trackChannel++,this._currentTrack.playbackInfo.secondaryChannel=this._trackChannel++,this._currentStaff=this._currentTrack.staves[0],this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=Ye.getDefaultTuningFor(6).tunings,this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=p.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":default:return r.G2;case"f4":case"bass":return r.F4;case"c3":case"tenor":return r.C3;case"c4":case"alto":return r.C4;case"n":case"neutral":return r.Neutral}}parseClefFromInt(e){switch(e){case 43:default:return r.G2;case 65:return r.F4;case 48:return r.C3;case 60:return r.C4}}parseTripletFeelFromString(e){switch(e.toLowerCase()){case"no":case"none":default:return I.NoTripletFeel;case"t16":case"triplet-16th":return I.Triplet16th;case"t8":case"triplet-8th":return I.Triplet8th;case"d16":case"dotted-16th":return I.Dotted16th;case"d8":case"dotted-8th":return I.Dotted8th;case"s16":case"scottish-16th":return I.Scottish16th;case"s8":case"scottish-8th":return I.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return I.NoTripletFeel;case 1:return I.Triplet16th;case 2:return I.Triplet8th;case 3:return I.Dotted16th;case 4:return I.Dotted8th;case 5:return I.Scottish16th;case 6:return I.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":return L.Cb;case"gb":case"gbmajor":case"d#minor":return L.Gb;case"db":case"dbmajor":case"bbminor":return L.Db;case"ab":case"abmajor":case"fminor":return L.Ab;case"eb":case"ebmajor":case"cminor":return L.Eb;case"bb":case"bbmajor":case"gminor":return L.Bb;case"f":case"fmajor":case"dminor":return L.F;case"c":case"cmajor":case"aminor":default:return L.C;case"g":case"gmajor":case"eminor":return L.G;case"d":case"dmajor":case"bminor":return L.D;case"a":case"amajor":case"f#minor":return L.A;case"e":case"emajor":case"c#minor":return L.E;case"b":case"bmajor":case"g#minor":return L.B;case"f#":case"f#major":case"ebminor":return L.FSharp;case"c#":case"c#major":return L.CSharp}}nextChar(){return this._curChPos<this._input.length?(this._ch=this._input.charCodeAt(this._curChPos++),10===this._ch?(this._line++,this._col=0):this._col++):this._ch=et.Eof,this._ch}saveValidSpot(){this._lastValidSpot=[this._curChPos,this._line,this._col]}newSy(){for(this.saveValidSpot(),this._sy=R.No;this._sy===R.No;)if(this._ch===et.Eof)this._sy=R.Eof;else if(et.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!==et.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;this._ch!==et.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",R.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=R.String;this._ch!==e&&this._ch!==et.Eof;)t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._ch===et.Eof&&this.errorMessage("String opened but never closed"),this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)this._allowNegatives&&this.isDigit(this._ch)?(this._sy=R.Number,this._syData=this.readNumber()):(this._sy=R.String,this._syData=this.readName());else if(46===this._ch)this._sy=R.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=R.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=R.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=R.MetaCommand,this._syData=this.readName();else if(41===this._ch)this._sy=R.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=R.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=R.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=R.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=R.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=R.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this._sy=R.Number,this._syData=this.readNumber();else if(et.isNameLetter(this._ch)){let e=this.readName(),t=this._allowTuning?ke.parseTuning(e):null;t?(this._sy=R.Tuning,this._syData=t):(this._sy=R.String,this._syData=e)}else this.error("symbol",R.String,!1);return this._sy}static isNameLetter(e){return!et.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}readName(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(et.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 parseInt(e)}metaData(){let e=!1,t=!0;for(;this._sy===R.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!==R.String&&this.error(i,R.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._sy=this.newSy(),this._sy===R.Number?this._score.tempo=this._syData:this.error("tempo",R.Number,!0),this._sy=this.newSy(),e=!0;break;default:this.handleStaffMeta()?e=!0:e?this.error("metaDataTags",R.String,!1):t=!1}}return e?(this._sy!==R.Dot&&this.error("song",R.Dot,!0),this._sy=this.newSy()):this._sy===R.Dot&&(this._sy=this.newSy()),e}handleStaffMeta(){var e,t;switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===R.Number?this._currentStaff.capo=this._syData:this.error("capo",R.Number,!0),this._sy=this.newSy(),!0;case"tuning":this._sy=this.newSy();let i=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case R.String:let e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?(this._currentStaff.stringTuning.tunings=[],this._currentStaff.displayTranspositionPitch=0):this.error("tuning",R.Tuning,!0),this._sy=this.newSy();break;case R.Tuning:let t=[];do{let e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===R.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",R.Tuning,!0)}return i!==this._currentStaff.tuning.length&&(null!==(t=null===(e=this._currentStaff.chords)||void 0===e?void 0:e.size)&&void 0!==t?t:0)>0&&this.errorMessage("Tuning must be defined before any chord"),!0;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===R.Number){let e=this._syData;e>=0&&e<=127?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",R.Number,!1)}else if(this._sy===R.String){let e=this._syData.toLowerCase();this._currentTrack.playbackInfo.program=ce.getValue(e)}else this.error("instrument",R.Number,!0);return this._sy=this.newSy(),!0;case"lyrics":this._sy=this.newSy();let s=new Ae;return s.startBar=0,s.text="",this._sy===R.Number&&(s.startBar=this._syData,this._sy=this.newSy()),this._sy===R.String?(s.text=this._syData,this._sy=this.newSy()):this.error("lyrics",R.String,!0),this._lyrics.get(this._currentTrack.index).push(s),!0;case"chord":this._sy=this.newSy();let a=new Re;this.chordProperties(a),this._sy===R.String?(a.name=this._syData,this._sy=this.newSy()):this.error("chord-name",R.Number,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===R.Number?a.strings.push(this._syData):this._sy===R.String&&"x"===this._syData.toLowerCase()&&a.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,a.name),a),!0;default:return!1}}chordProperties(e){if(this._sy===R.LBrace){for(this._sy=this.newSy();this._sy===R.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===R.Number)e.firstFret=this._syData;else this.error("chord-firstfret",R.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case R.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case R.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",R.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case R.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case R.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",R.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case R.String:e.showName="false"!==this._syData.toLowerCase();break;case R.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",R.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===R.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",R.String,!1)}this._sy!==R.RBrace&&this.error("chord-properties",R.RBrace,!0),this._sy=this.newSy()}}bars(){let e=this.bar();for(;this._sy!==R.Eof;)if(this._sy===R.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==R.MetaCommand)break;this.bar()}return e}trackStaffMeta(){return this._sy===R.MetaCommand&&("track"===this._syData.toLowerCase()&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===R.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===R.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy())),this._sy===R.MetaCommand&&"staff"===this._syData.toLowerCase()&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0&&(this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this._currentStaff=this._currentTrack.staves[this._currentTrack.staves.length-1],this._currentDynamics=p.F),this.staffProperties()),!0)}staffProperties(){if(this._sy!==R.LBrace)return;this._sy=this.newSy();let e=!1,t=!1;for(;this._sy===R.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy();break;case"tabs":t=!0,this._sy=this.newSy();break;default:this.error("staff-properties",R.String,!1)}(e||t)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t),this._sy!==R.RBrace&&this.error("staff-properties",R.RBrace,!0),this._sy=this.newSy()}bar(){const e=this.trackStaffMeta();let t=this.newBar(this._currentStaff);if(this._currentStaff.bars.length>this._score.masterBars.length){let e=new Oe;this._score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.timeSignatureDenominator=e.previousMasterBar.timeSignatureDenominator,e.timeSignatureNumerator=e.previousMasterBar.timeSignatureNumerator,e.tripletFeel=e.previousMasterBar.tripletFeel)}const 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=Ye.getDefaultTuningFor(6).tunings):e>=32&&e<=39?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):40==e||44==e||45==e||48==e||49==e||50==e||51==e?this._currentStaff.stringTuning.tunings=[52,57,50,43]:41==e?this._currentStaff.stringTuning.tunings=[57,50,43,36]:42==e?this._currentStaff.stringTuning.tunings=[45,38,31,24]:43==e?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):105==e?this._currentStaff.stringTuning.tunings=[50,47,43,38,55]:106==e?this._currentStaff.stringTuning.tunings=[57,52,45]:107==e?this._currentStaff.stringTuning.tunings=[52,45,38,31]:110==e&&(this._currentStaff.stringTuning.tunings=[64,57,50,43]),this._staffTuningApplied=!0}let s=!1,a=t.voices[0];for(;this._sy!==R.Pipe&&this._sy!==R.Eof&&this.beat(a);)s=!0;if(0===a.beats.length){let e=new Ie;e.isEmpty=!0,a.addBeat(e)}return e||i||s}newBar(e){let t=new me;e.addBar(t),t.index>0&&(t.clef=t.previousBar.clef);let i=new je;return t.addVoice(i),t}beat(e){this.beatDuration();let t=new Ie;if(e.addBeat(t),this._sy===R.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==R.RParensis&&this._sy!==R.Eof&&this.note(t););this._sy!==R.RParensis&&this.error("note-list",R.RParensis,!0),this._sy=this.newSy()}else if(this._sy===R.String&&"r"===this._syData.toLowerCase())this._sy=this.newSy();else if(!this.note(t))return e.beats.splice(e.beats.length-1,1),!1;this._sy===R.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==R.Number&&this.error("duration",R.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._sy=this.newSy()),t.duration=this._currentDuration,t.dynamics=this._currentDynamics,1===this._currentTuplet||t.hasTuplet||et.applyTuplet(t,this._currentTuplet);let i=1;this._sy===R.Multiply&&(this._sy=this.newSy(),this._sy!==R.Number?this.error("multiplier",R.Number,!0):i=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let s=0;s<i-1;s++)e.addBeat(Me.clone(t));return!0}beatDuration(){if(this._sy===R.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==R.Number&&this.error("duration",R.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===R.LBrace)){for(this._sy=this.newSy();this._sy===R.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==R.Number&&this.error("duration-tuplet",R.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",R.String,!1)}this._sy!==R.RBrace&&this.error("beat-duration",R.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===R.LBrace){for(this._sy=this.newSy();this._sy===R.String;)this.applyBeatEffect(e)||this.error("beat-effects",R.String,!1);this._sy!==R.RBrace&&this.error("beat-effects",R.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){let t=this._syData.toLowerCase();if("f"===t)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!==R.Number)return this.error("tuplet",R.Number,!0),!1;et.applyTuplet(e,this._syData)}else if("tb"===t||"tbe"===t){let i="tbe"===t;for(this._sy=this.newSy(),this._sy!==R.LParensis&&this.error("tremolobar-effect",R.LParensis,!0),this._allowNegatives=!0,this._sy=this.newSy();this._sy!==R.RParensis&&this._sy!==R.Eof;){let t=0,s=0;i?(this._sy!==R.Number&&this.error("tremolobar-effect",R.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==R.Number&&this.error("tremolobar-effect",R.Number,!0),s=this._syData):(this._sy!==R.Number&&this.error("tremolobar-effect",R.Number,!0),t=0,s=this._syData),e.addWhammyBarPoint(new be(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!==R.RParensis&&this.error("tremolobar-effect",R.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===R.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 Re;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=g.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=g.BendGrace,this._sy=this.newSy()):e.graceType=g.BeforeBeat,!0;if("dy"===t){switch(this._sy=this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=p.PPP;break;case"pp":e.dynamics=p.PP;break;case"p":e.dynamics=p.P;break;case"mp":e.dynamics=p.MP;break;case"mf":e.dynamics=p.MF;break;case"f":e.dynamics=p.F;break;case"ff":e.dynamics=p.FF;break;case"fff":e.dynamics=p.FFF}this._currentDynamics=e.dynamics}else if("cre"===t)e.crescendo=c.Crescendo;else{if("dec"!==t){if("tp"===t){if(this._sy=this.newSy(),e.tremoloSpeed=u.Eighth,this._sy===R.Number){switch(this._syData){case 8:default:e.tremoloSpeed=u.Eighth;break;case 16:e.tremoloSpeed=u.Sixteenth;break;case 32:e.tremoloSpeed=u.ThirtySecond}this._sy=this.newSy()}return!0}return!1}e.crescendo=c.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 R.Number:s=this._syData;break;case R.String:t="x"===this._syData,i="-"===this._syData,i||t?s=0:this.error("note-fret",R.Number,!0);break;case R.Tuning:let e=this._syData;a=e.octave,r=e.noteValue;break;default:return!1}this._sy=this.newSy();let n=-1===a&&this._currentStaff.tuning.length>0,o=-1;n&&(this._sy!==R.Dot&&this.error("note",R.Dot,!0),this._sy=this.newSy(),this._sy!==R.Number&&this.error("note-string",R.Number,!0),o=this._syData,(o<1||o>this._currentStaff.tuning.length)&&this.error("note-string",R.Number,!1),this._sy=this.newSy());let h=new Pe;return n?(h.string=this._currentStaff.tuning.length-(o-1),h.isDead=t,h.isTieDestination=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===R.LBrace){for(this._sy=this.newSy();this._sy===R.String;){let t=this._syData.toLowerCase();if("b"===t||"be"===t){let i="be"===t;for(this._sy=this.newSy(),this._sy!==R.LParensis&&this.error("bend-effect",R.LParensis,!0),this._sy=this.newSy();this._sy!==R.RParensis&&this._sy!==R.Eof;){let t=0,s=0;i?(this._sy!==R.Number&&this.error("bend-effect-value",R.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==R.Number&&this.error("bend-effect-value",R.Number,!0),s=this._syData):(this._sy!==R.Number&&this.error("bend-effect-value",R.Number,!0),s=this._syData),e.addBendPoint(new be(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!==R.RParensis&&this.error("bend-effect",R.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=m.Natural,this._sy=this.newSy();else if("ah"===t)e.harmonicType=m.Artificial,this._sy=this.newSy();else if("th"===t)e.harmonicType=m.Tap,this._sy=this.newSy();else if("ph"===t)e.harmonicType=m.Pinch,this._sy=this.newSy();else if("sh"===t)e.harmonicType=m.Semi,this._sy=this.newSy();else if("tr"===t){this._sy=this.newSy(),this._sy!==R.Number&&this.error("trill-effect",R.Number,!0);let t=this._syData;this._sy=this.newSy();let i=u.Sixteenth;if(this._sy===R.Number){switch(this._syData){case 16:default:i=u.Sixteenth;break;case 32:i=u.ThirtySecond;break;case 64:i=u.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=S.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=S.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=b.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=b.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=S.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=S.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=S.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=S.PickSlideUp;else if("h"===t)this._sy=this.newSy(),e.isHammerPullOrigin=!0;else if("lht"===t)this._sy=this.newSy(),e.isLeftHandTapped=!0;else if("g"===t)this._sy=this.newSy(),e.isGhost=!0;else if("ac"===t)this._sy=this.newSy(),e.accentuated=s.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=s.Heavy;else if("pm"===t)this._sy=this.newSy(),e.isPalmMute=!0;else if("st"===t)this._sy=this.newSy(),e.isStaccato=!0;else if("lr"===t)this._sy=this.newSy(),e.isLetRing=!0;else if("x"===t)this._sy=this.newSy(),e.fret=0,e.isDead=!0;else if("-"===t||"t"===t)this._sy=this.newSy(),e.isTieDestination=!0;else if("lf"===t){this._sy=this.newSy();let t=f.Thumb;this._sy===R.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.leftHandFinger=t}else if("rf"===t){this._sy=this.newSy();let t=f.Thumb;this._sy===R.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else this.applyBeatEffect(e.beat)||this.error(t,R.String,!1)}this._sy!==R.RBrace&&this.error("note-effect",R.RBrace,!1),this._sy=this.newSy()}}toFinger(e){switch(e){case 1:return f.Thumb;case 2:return f.IndexFinger;case 3:return f.MiddleFinger;case 4:return f.AnnularFinger;case 5:return f.LittleFinger}return f.Thumb}parseDuration(e){switch(e){case-4:return u.QuadrupleWhole;case-2:return u.DoubleWhole;case 1:return u.Whole;case 2:return u.Half;case 4:return u.Quarter;case 8:return u.Eighth;case 16:return u.Sixteenth;case 32:return u.ThirtySecond;case 64:return u.SixtyFourth;case 128:return u.OneHundredTwentyEighth;case 256:return u.TwoHundredFiftySixth;default:return u.Quarter}}barMeta(e){let t=!1,i=e.masterBar;for(;this._sy===R.MetaCommand;){t=!0;let s=this._syData.toLowerCase();if("ts"===s)this._sy=this.newSy(),this._sy!==R.Number&&this.error("timesignature-numerator",R.Number,!0),i.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==R.Number&&this.error("timesignature-denominator",R.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!==R.Number&&this.error("repeatclose",R.Number,!0),this._syData>2048&&this.error("repeatclose",R.Number,!1),i.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===s)if(this._sy=this.newSy(),this._sy===R.LParensis){for(this._sy=this.newSy(),this._sy!==R.Number&&this.error("alternateending",R.Number,!0),this.applyAlternateEnding(i);this._sy===R.Number;)this.applyAlternateEnding(i);this._sy!==R.RParensis&&this.error("alternateending-list",R.RParensis,!0),this._sy=this.newSy()}else this._sy!==R.Number&&this.error("alternateending",R.Number,!0),this.applyAlternateEnding(i);else if("ks"===s)this._sy=this.newSy(),this._sy!==R.String&&this.error("keysignature",R.String,!0),i.keySignature=this.parseKeySignature(this._syData),this._sy=this.newSy();else if("clef"===s){switch(this._sy=this.newSy(),this._sy){case R.String:e.clef=this.parseClefFromString(this._syData);break;case R.Number:e.clef=this.parseClefFromInt(this._syData);break;case R.Tuning:let t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",R.String,!0)}this._sy=this.newSy()}else if("tempo"===s){this._sy=this.newSy(),this._sy!==R.Number&&this.error("tempo",R.Number,!0);let e=new fe;e.isLinear=!1,e.type=a.Tempo,e.value=this._syData,i.tempoAutomation=e,this._sy=this.newSy()}else if("section"===s){this._sy=this.newSy(),this._sy!==R.String&&this.error("section",R.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==R.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());let s=new We;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 R.String:i.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case R.Number:i.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",R.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",R.String,!1)}if(0===i.index&&!i.tempoAutomation){let e=new fe;e.isLinear=!1,e.type=a.Tempo,e.value=this._score.tempo,i.tempoAutomation=e}return t}applyAlternateEnding(e){let t=this._syData;t<1&&this.error("alternateending",R.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}}et.Eof=0;class tt extends ue{get name(){return"Guitar Pro 3-5"}constructor(){super(),this._versionNumber=0,this._globalTripletFeel=I.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 He,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=it.gpReadBool(this.data)?I.Triplet8th:I.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=it.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=$e.readInt32LE(this.data),this._versionNumber>=510&&it.gpReadBool(this.data),$e.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.data.skip(38),this.data.skip(4)),this._barCount=$e.readInt32LE(this.data),this._trackCount=$e.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0&&(this._score.masterBars[0].tempoAutomation=fe.buildTempoAutomation(!1,0,this._score.tempo,2),this._score.masterBars[0].tempoAutomation.text=this._score.tempoLabel),this._score.finish(this.settings),this._lyrics&&this._lyricsTrack>=0&&this._score.tracks[this._lyricsTrack].applyLyrics(this._lyrics),this._score}readVersion(){let e=it.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(tt.VersionString))throw new ge("Unsupported format");e=e.substr(tt.VersionString.length+1);let t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*parseInt(e.substr(0,t))+parseInt(e.substr(t+1)),Be.debug(this.name,"Guitar Pro version "+e+" detected")}readScoreInformation(){var e;this._score.title=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?it.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding);let t=$e.readInt32LE(this.data),i="";for(let s=0;s<t;s++)s>0&&(i+="\r\n"),i+=null===(e=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding))||void 0===e?void 0:e.toString();this._score.notices=i}readLyrics(){this._lyrics=[],this._lyricsTrack=$e.readInt32LE(this.data)-1;for(let e=0;e<5;e++){let e=new Ae;e.startBar=$e.readInt32LE(this.data)-1,e.text=it.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(30);for(let e=0;e<10;e++)it.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){let t=new Xe;t.primaryChannel=e,t.secondaryChannel=e,t.program=$e.readInt32LE(this.data),t.volume=this.data.readByte(),t.balance=this.data.readByte(),this.data.skip(6),this._playbackInfos.push(t)}}readMasterBars(){for(let e=0;e<this._barCount;e++)this.readMasterBar()}readMasterBar(){let e=null;this._score.masterBars.length>0&&(e=this._score.masterBars[this._score.masterBars.length-1]);let t=new Oe,i=this.data.readByte();if(0!=(1&i)?t.timeSignatureNumerator=this.data.readByte():e&&(t.timeSignatureNumerator=e.timeSignatureNumerator),0!=(2&i)?t.timeSignatureDenominator=this.data.readByte():e&&(t.timeSignatureDenominator=e.timeSignatureDenominator),t.isRepeatStart=0!=(4&i),0!=(8&i)&&(t.repeatCount=this.data.readByte()+(this._versionNumber>=500?0:1)),0!=(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&&0==(s&t)&&(a|=t)}t.alternateEndings=a}if(0!=(32&i)){let e=new We;e.text=it.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",it.gpReadColor(this.data,!1),t.section=e}if(0!=(64&i)?(t.keySignature=$e.readSInt8(this.data),t.keySignatureType=this.data.readByte()):e&&(t.keySignature=e.keySignature,t.keySignatureType=e.keySignatureType),this._versionNumber>=500&&0!=(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=I.Triplet8th;break;case 2:t.tripletFeel=I.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=0!=(128&i),this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){let e=new Je;e.ensureStaveCount(1),this._score.addTrack(e);let t=e.staves[0],i=this.data.readByte();e.name=it.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),0!=(1&i)&&(t.isPercussion=!0);let s=$e.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){let t=$e.readInt32LE(this.data);s>e&&a.push(t)}t.stringTuning.tunings=a;let r=$e.readInt32LE(this.data),n=$e.readInt32LE(this.data)-1,o=$e.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=0!=(16&i),s.isMute=0!=(32&i),s.secondaryChannel=o,ce.isGuitar(s.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=s}t.capo=$e.readInt32LE(this.data),e.color=it.gpReadColor(this.data,!1),this._versionNumber>=500&&(this.data.readByte(),this.data.readByte(),this.data.skip(43)),this._versionNumber>=510&&(this.data.skip(4),it.gpReadStringIntByte(this.data,this.settings.importer.encoding),it.gpReadStringIntByte(this.data,this.settings.importer.encoding))}readBars(){for(let e=0;e<this._barCount;e++)for(let e=0;e<this._trackCount;e++)this.readBar(this._score.tracks[e])}readBar(e){let t=new me,i=e.staves[0];i.isPercussion&&(t.clef=r.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=$e.readInt32LE(this.data);if(0===i)return;let s=new je;t.addVoice(s);for(let a=0;a<i;a++)this.readBeat(e,t,s)}readBeat(e,t,i){let s=new Ie,a=this.data.readByte();if(0!=(1&a)&&(s.dots=1),0!=(64&a)){let e=this.data.readByte();s.isEmpty=0==(2&e)}switch(i.addBeat(s),$e.readSInt8(this.data)){case-2:s.duration=u.Whole;break;case-1:s.duration=u.Half;break;case 0:s.duration=u.Quarter;break;case 1:s.duration=u.Eighth;break;case 2:s.duration=u.Sixteenth;break;case 3:s.duration=u.ThirtySecond;break;case 4:s.duration=u.SixtyFourth;break;default:s.duration=u.Quarter}if(0!=(32&a))switch(s.tupletNumerator=$e.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}0!=(2&a)&&this.readChord(s);let r=this.settings.importer.beatTextAsLyrics&&e.index!==this._lyricsTrack;if(0!=(4&a)){const t=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const i=new Ae;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=m.None;0!=(8&a)&&(n=this.readBeatEffects(s)),0!=(16&a)&&this.readMixTableChange(s);let o=this.data.readByte();for(let a=6;a>=0;a--)if(0!=(o&1<<a)&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,i,s,6-a);n!==m.None&&(r.harmonicType=n,r.harmonicType===m.Natural&&(r.harmonicValue=this.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){this.data.readByte(),0!=(8&this.data.readByte())&&this.data.readByte()}r&&!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 Re,i=ke.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=it.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=$e.readInt32LE(this.data);for(let i=0;i<7;i++){let s=$e.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=it.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=$e.readInt32LE(this.data);for(let i=0;i<7;i++){let s=$e.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=it.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=$e.readInt32LE(this.data);for(let i=0;i<6;i++){let s=$e.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=it.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=$e.readInt32LE(this.data),t.firstFret>0)for(let s=0;s<i;s++){let i=$e.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=0!=(16&t),(this._versionNumber<400&&0!=(1&t)||0!=(2&t))&&(e.vibrato=_.Slight),e.hasRasgueado=0!=(1&i),0!=(32&t)&&this._versionNumber>=400){switch($e.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}}else if(0!=(32&t)){switch($e.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}this.data.skip(4)}if(0!=(4&i)&&this.readTremoloBarEffect(e),0!=(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=tt.toStrokeValue(t)):i>0&&(e.brushType=d.BrushDown,e.brushDuration=tt.toStrokeValue(i))}if(0!=(2&i))switch($e.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(0!=(4&t))return m.Natural;if(0!=(8&t))return m.Artificial}return m.None}readTremoloBarEffect(e){this.data.readByte(),$e.readInt32LE(this.data);let t=$e.readInt32LE(this.data);if(t>0)for(let i=0;i<t;i++){let t=new be(0,0);t.offset=$e.readInt32LE(this.data),t.value=$e.readInt32LE(this.data)/tt.BendStep|0,it.gpReadBool(this.data),e.addWhammyBarPoint(t)}}static toStrokeValue(e){switch(e){case 1:case 2:return 30;case 3:return 60;case 4:return 120;case 5:return 240;case 6:return 480;default:return 0}}readMixTableChange(e){let t=new st;t.instrument=$e.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=$e.readSInt8(this.data),t.balance=$e.readSInt8(this.data);let i=$e.readSInt8(this.data),s=$e.readSInt8(this.data),r=$e.readSInt8(this.data),n=$e.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=it.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=$e.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(),r>=0&&this.data.readByte(),n>=0&&this.data.readByte(),t.tempo>=0&&(t.duration=$e.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500&&this.data.readByte(),this._versionNumber>=510&&(it.gpReadStringIntByte(this.data,this.settings.importer.encoding),it.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){let i=new fe;i.isLinear=!0,i.type=a.Volume,i.value=t.volume,e.automations.push(i)}if(t.balance>=0){let i=new fe;i.isLinear=!0,i.type=a.Balance,i.value=t.balance,e.automations.push(i)}if(t.instrument>=0){let i=new fe;i.isLinear=!0,i.type=a.Instrument,i.value=t.instrument,e.automations.push(i)}if(t.tempo>=0){let i=new fe;i.isLinear=!0,i.type=a.Tempo,i.value=t.tempo,e.automations.push(i),e.voice.bar.masterBar.tempoAutomation=i}}readNote(e,t,i,a,r){let n=new Pe;n.string=t.staff.tuning.length-r;let o=this.data.readByte();if(0!=(2&o)?n.accentuated=s.Heavy:0!=(64&o)&&(n.accentuated=s.Normal),n.isGhost=0!=(4&o),0!=(32&o)){let e=this.data.readByte();3===e?n.isDead=!0:2===e&&(n.isTieDestination=!0)}if(0!=(1&o)&&this._versionNumber<500&&(this.data.readByte(),this.data.readByte()),0!=(16&o)){let e=$e.readSInt8(this.data);n.dynamics=this.toDynamicValue(e),a.dynamics=n.dynamics}0!=(32&o)&&(n.fret=$e.readSInt8(this.data)),0!=(128&o)&&(n.leftHandFinger=$e.readSInt8(this.data),n.rightHandFinger=$e.readSInt8(this.data),n.isFingering=!0);let h=!1;if(this._versionNumber>=500){0!=(1&o)&&(n.durationPercent=it.gpReadDouble(this.data)),h=0!=(2&this.data.readByte())}if(a.addNote(n),0!=(8&o)&&this.readNoteEffects(e,i,a,n),t.staff.isPercussion&&(n.percussionArticulation=n.fret,n.string=-1,n.fret=-1),h){const e=Ye.defaultAccidentals[n.realValueWithoutHarmonic%12];"#"===e?n.accidentalMode=y.ForceFlat:"b"===e&&(n.accidentalMode=y.ForceSharp)}return n}toDynamicValue(e){switch(e){case 1:return p.PPP;case 2:return p.PP;case 3:return p.P;case 4:return p.MP;case 5:return p.MF;case 6:default:return p.F;case 7:return p.FF;case 8:return p.FFF}}readNoteEffects(e,t,i,s){let a=this.data.readByte(),r=0;this._versionNumber>=400&&(r=this.data.readByte()),0!=(1&a)&&this.readBend(s),0!=(16&a)&&this.readGrace(t,s),0!=(4&r)&&this.readTremoloPicking(i),0!=(8&r)?this.readSlide(s):this._versionNumber<400&&0!=(4&a)&&(s.slideOutType=S.Shift),0!=(16&r)&&this.readArtificialHarmonic(s),0!=(32&r)&&this.readTrill(s),s.isLetRing=0!=(8&a),s.isHammerPullOrigin=0!=(2&a),0!=(64&r)&&(s.vibrato=_.Slight),s.isPalmMute=0!=(2&r),s.isStaccato=0!=(1&r)}readBend(e){this.data.readByte(),$e.readInt32LE(this.data);let t=$e.readInt32LE(this.data);if(t>0)for(let i=0;i<t;i++){let t=new be(0,0);t.offset=$e.readInt32LE(this.data),t.value=$e.readInt32LE(this.data)/tt.BendStep|0,it.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){let i=new Ie,s=new Pe;switch(s.string=t.string,s.fret=$e.readSInt8(this.data),i.duration=u.ThirtySecond,i.dynamics=this.toDynamicValue($e.readSInt8(this.data)),$e.readSInt8(this.data)){case 0:case 2:break;case 1:s.slideOutType=S.Legato,s.slideTarget=t;break;case 3:s.isHammerPullOrigin=!0}if(s.dynamics=i.dynamics,this.data.skip(1),this._versionNumber<500)i.graceType=g.BeforeBeat;else{let e=this.data.readByte();s.isDead=0!=(1&e),i.graceType=0!=(2&e)?g.OnBeat:g.BeforeBeat}e.addGraceBeat(i),i.addNote(s)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=u.Eighth;break;case 2:e.tremoloSpeed=u.Sixteenth;break;case 3:e.tremoloSpeed=u.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){let t=$e.readSInt8(this.data);0!=(1&t)?e.slideOutType=S.Shift:0!=(2&t)?e.slideOutType=S.Legato:0!=(4&t)?e.slideOutType=S.OutDown:0!=(8&t)&&(e.slideOutType=S.OutUp),0!=(16&t)?e.slideInType=b.IntoFromBelow:0!=(32&t)&&(e.slideInType=b.IntoFromAbove)}else{switch($e.readSInt8(this.data)){case 1:e.slideOutType=S.Shift;break;case 2:e.slideOutType=S.Legato;break;case 3:e.slideOutType=S.OutDown;break;case 4:e.slideOutType=S.OutUp;break;case-1:e.slideInType=b.IntoFromBelow;break;case-2:e.slideInType=b.IntoFromAbove}}}readArtificialHarmonic(e){let t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=m.Natural,e.harmonicValue=this.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=m.Artificial;break;case 3:e.harmonicType=m.Tap,e.harmonicValue=this.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=m.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=m.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=m.Natural;break;case 3:e.harmonicType=m.Tap;break;case 4:e.harmonicType=m.Pinch;break;case 5:e.harmonicType=m.Semi;break;case 15:case 17:case 22:e.harmonicType=m.Artificial}}deltaFretToHarmonicValue(e){switch(e){case 2:return 2.4;case 3:return 3.2;case 4:case 5:case 7:case 9:case 12:case 16:case 17:case 19:case 24:return e;case 8:return 8.2;case 10:return 9.6;case 14:case 15:return 14.7;case 21:case 22:return 21.7;default:return 12}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=u.Sixteenth;break;case 2:e.trillSpeed=u.ThirtySecond;break;case 3:e.trillSpeed=u.SixtyFourth}}}tt.VersionString="FICHIER GUITAR PRO ",tt.BendStep=25;class it{static gpReadDouble(e){let t=new Uint8Array(8);return e.read(t,0,t.length),new Float64Array(t.buffer)[0]}static gpReadFloat(e){let t=new Uint8Array(4);return t[3]=e.readByte(),t[2]=e.readByte(),t[2]=e.readByte(),t[1]=e.readByte(),new Float32Array(t.buffer)[0]}static gpReadColor(e,t=!1){let i=e.readByte(),s=e.readByte(),a=e.readByte(),r=255;return t?r=e.readByte():e.skip(1),new Ue(i,s,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),it.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return it.gpReadString(e,$e.readInt32LE(e),t)}static gpReadStringIntByte(e,t){let i=$e.readInt32LE(e)-1;return e.readByte(),it.gpReadString(e,i,t)}static gpReadString(e,t,i){let s=new Uint8Array(t);return e.read(s,0,s.length),$e.toString(s,i)}static gpWriteString(e,t){const i=$e.stringToBytes(t);e.writeByte(t.length),e.write(i,0,i.length)}static gpReadStringByteLength(e,t,i){let s=e.readByte(),a=it.gpReadString(e,s,i);return s<t&&e.skip(t-s),a}}class st{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class at{constructor(){this.x=0,this.y=0,this.w=0,this.h=0}}!function(e){e[e.Boolean=0]="Boolean",e[e.Integer=1]="Integer",e[e.Float=2]="Float",e[e.String=3]="String",e[e.Point=4]="Point",e[e.Size=5]="Size",e[e.Rectangle=6]="Rectangle",e[e.Color=7]="Color"}(A||(A={}));class rt{constructor(e){this.raw=new Map;let t=Ke.fromBuffer(e),i=$e.readInt32BE(t);for(let e=0;e<i;e++){let e=it.gpReadString(t,t.readByte(),"utf-8");switch(t.readByte()){case A.Boolean:let i=1===t.readByte();this.addValue(e,i);break;case A.Integer:let s=$e.readInt32BE(t);this.addValue(e,s);break;case A.Float:let a=it.gpReadFloat(t);this.addValue(e,a);break;case A.String:let r=it.gpReadString(t,$e.readInt16BE(t),"utf-8");this.addValue(e,r);break;case A.Point:let n=$e.readInt32BE(t),o=$e.readInt32BE(t);this.addValue(e,new be(n,o));break;case A.Size:let h=$e.readInt32BE(t),l=$e.readInt32BE(t);this.addValue(e,new be(h,l));break;case A.Rectangle:let d=new at;d.x=$e.readInt32BE(t),d.y=$e.readInt32BE(t),d.w=$e.readInt32BE(t),d.h=$e.readInt32BE(t),this.addValue(e,d);break;case A.Color:let c=it.gpReadColor(t,!0);this.addValue(e,c)}}}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 $e.writeInt32BE(t,1),rt.writeBooleanEntry(t,"StandardNotation/hideDynamics",e.stylesheet.hideDynamics),t.toArray()}static writeBooleanEntry(e,t,i){it.gpWriteString(e,t),e.writeByte(A.Boolean),e.writeByte(i?1:0)}}!function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(O||(O={}));class nt{constructor(){this.type=O.Short,this.length=0}}!function(e){e[e.None=0]="None",e[e.Element=1]="Element",e[e.Text=2]="Text",e[e.CDATA=3]="CDATA",e[e.Document=4]="Document",e[e.DocumentType=5]="DocumentType"}(G||(G={}));class ot{constructor(){this.nodeType=G.None,this.localName=null,this.value=null,this.childNodes=[],this.attributes=new Map,this.firstChild=null,this.firstElement=null}addChild(e){this.childNodes.push(e),this.firstChild=e,e.nodeType!==G.Element&&e.nodeType!==G.CDATA||(this.firstElement=e)}getAttribute(e){return this.attributes.has(e)?this.attributes.get(e):""}getElementsByTagName(e,t=!1){let i=[];return this.searchElementsByTagName(this.childNodes,i,e,t),i}searchElementsByTagName(e,t,i,s=!1){for(let a of e)a&&a.nodeType===G.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===G.Element&&t.localName===e)return t;return null}addElement(e){const t=new ot;return t.nodeType=G.Element,t.localName=e,this.addChild(t),t}get innerText(){var e,t;if(this.nodeType===G.Element||this.nodeType===G.Document){if(this.firstElement&&this.firstElement.nodeType===G.CDATA)return this.firstElement.innerText;let t="";for(let i of this.childNodes)t+=null===(e=i.innerText)||void 0===e?void 0:e.toString();return t.trim()}return null!==(t=this.value)&&void 0!==t?t:""}set innerText(e){const t=new ot;t.nodeType=G.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new ot;t.nodeType=G.CDATA,t.value=e,this.childNodes=[t]}}class ht extends pe{constructor(e,t,s){super(i.Format,e),this.pos=0,this.xml=t,this.pos=s,Object.setPrototypeOf(this,ht.prototype)}}!function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.BeginNode=2]="BeginNode",e[e.TagName=3]="TagName",e[e.Body=4]="Body",e[e.AttribName=5]="AttribName",e[e.Equals=6]="Equals",e[e.AttvalBegin=7]="AttvalBegin",e[e.AttribVal=8]="AttribVal",e[e.Childs=9]="Childs",e[e.Close=10]="Close",e[e.WaitEnd=11]="WaitEnd",e[e.WaitEndRet=12]="WaitEndRet",e[e.Pcdata=13]="Pcdata",e[e.Header=14]="Header",e[e.Comment=15]="Comment",e[e.Doctype=16]="Doctype",e[e.Cdata=17]="Cdata",e[e.Escape=18]="Escape"}(V||(V={}));class lt{static parse(e,t,i){var s;let a=e.charCodeAt(t),r=V.Begin,n=V.Begin,o=0,h="",l=V.Begin,d=null,c=null,u=0,p=0;for(;t<e.length;){switch(a=e.charCodeAt(t),r){case V.IgnoreSpaces:switch(a){case lt.CharCodeLF:case lt.CharCodeCR:case lt.CharCodeTab:case lt.CharCodeSpace:break;default:r=n;continue}break;case V.Begin:if(a!==lt.CharCodeLowerThan){o=t,r=V.Pcdata;continue}r=V.IgnoreSpaces,n=V.BeginNode;break;case V.Pcdata:if(a===lt.CharCodeLowerThan){h+=e.substr(o,t-o);let s=new ot;s.nodeType=G.Text,s.value=h,h="",i.addChild(s),r=V.IgnoreSpaces,n=V.BeginNode}else a===lt.CharCodeAmp&&(h+=e.substr(o,t-o),r=V.Escape,l=V.Pcdata,o=t+1);break;case V.Cdata:if(a===lt.CharCodeBrackedClose&&e.charCodeAt(t+1)===lt.CharCodeBrackedClose&&e.charCodeAt(t+2)===lt.CharCodeGreaterThan){let s=new ot;s.nodeType=G.CDATA,s.value=e.substr(o,t-o),i.addChild(s),t+=2,r=V.Begin}break;case V.BeginNode:switch(a){case lt.CharCodeExclamation:if(e.charCodeAt(t+1)===lt.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new ht("Expected <![CDATA[",e,t);t+=5,r=V.Cdata,o=t+1}else if(e.charCodeAt(t+1)===lt.CharCodeUpperD||e.charCodeAt(t+1)===lt.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new ht("Expected <!DOCTYPE",e,t);t+=8,r=V.Doctype,o=t+1}else{if(e.charCodeAt(t+1)!==lt.CharCodeMinus||e.charCodeAt(t+2)!==lt.CharCodeMinus)throw new ht("Expected \x3c!--",e,t);t+=2,r=V.Comment,o=t+1}break;case lt.CharCodeQuestion:r=V.Header,o=t;break;case lt.CharCodeSlash:if(!i)throw new ht("Expected node name",e,t);o=t+1,r=V.IgnoreSpaces,n=V.Close;break;default:r=V.TagName,o=t;continue}break;case V.TagName:if(!lt.isValidChar(a)){if(t===o)throw new ht("Expected node name",e,t);d=new ot,d.nodeType=G.Element,d.localName=e.substr(o,t-o),i.addChild(d),r=V.IgnoreSpaces,n=V.Body;continue}break;case V.Body:switch(a){case lt.CharCodeSlash:r=V.WaitEnd;break;case lt.CharCodeGreaterThan:r=V.Childs;break;default:r=V.AttribName,o=t;continue}break;case V.AttribName:if(!lt.isValidChar(a)){if(o===t)throw new ht("Expected attribute name",e,t);if(c=e.substr(o,t-o),d.attributes.has(c))throw new ht(`Duplicate attribute [${c}]`,e,t);r=V.IgnoreSpaces,n=V.Equals;continue}break;case V.Equals:if(a!==lt.CharCodeEquals)throw new ht("Expected =",e,t);r=V.IgnoreSpaces,n=V.AttvalBegin;break;case V.AttvalBegin:switch(a){case lt.CharCodeDoubleQuote:case lt.CharCodeSingleQuote:h="",r=V.AttribVal,o=t+1,p=a}break;case V.AttribVal:if(a===lt.CharCodeAmp)h+=e.substr(o,t-o),r=V.Escape,l=V.AttribVal,o=t+1;else if(a===p){h+=e.substr(o,t-o);let i=h;h="",d.attributes.set(c,i),r=V.IgnoreSpaces,n=V.Body}break;case V.Childs:o=t=lt.parse(e,t,d),r=V.Begin;break;case V.WaitEnd:if(a!==lt.CharCodeGreaterThan)throw new ht("Expected >",e,t);r=V.Begin;break;case V.WaitEndRet:if(a===lt.CharCodeGreaterThan)return t;throw new ht("Expected >",e,t);case V.Close:if(!lt.isValidChar(a)){if(o===t)throw new ht("Expected node name",e,t);if(e.substr(o,t-o)!==i.localName)throw new ht("Expected </"+i.localName+">",e,t);r=V.IgnoreSpaces,n=V.WaitEndRet;continue}break;case V.Comment:a===lt.CharCodeMinus&&e.charCodeAt(t+1)===lt.CharCodeMinus&&e.charCodeAt(t+2)===lt.CharCodeGreaterThan&&(t+=2,r=V.Begin);break;case V.Doctype:if(a===lt.CharCodeBrackedOpen)u++;else if(a===lt.CharCodeBrackedClose)u--;else if(a===lt.CharCodeGreaterThan&&0===u){let s=new ot;s.nodeType=G.DocumentType,s.value=e.substr(o,t-o),i.addChild(s),r=V.Begin}break;case V.Header:a===lt.CharCodeQuestion&&e.charCodeAt(t+1)===lt.CharCodeGreaterThan&&(t++,r=V.Begin);break;case V.Escape:if(a===lt.CharCodeSemi){let i=e.substr(o,t-o);if(i.charCodeAt(0)===lt.CharCodeSharp){let e=i.charCodeAt(1)===lt.CharCodeLowerX?parseInt("0"+i.substr(1,i.length-1)):parseInt(i.substr(1,i.length-1));h+=String.fromCharCode(e)}else lt.Escapes.has(i)?h+=lt.Escapes.get(i):h+=null===(s="&"+i+";")||void 0===s?void 0:s.toString();o=t+1,r=l}else lt.isValidChar(a)||a===lt.CharCodeSharp||(h+="&",h+=e.substr(o,t-o),o=--t+1,r=l)}t++}if(r===V.Begin&&(o=t,r=V.Pcdata),r===V.Pcdata){if(t!==o){h+=e.substr(o,t-o);let s=new ot;s.nodeType=G.Text,s.value=h,i.addChild(s)}return t}if(r===V.Escape&&l===V.Pcdata){h+="&",h+=e.substr(o,t-o);let s=new ot;return s.nodeType=G.Text,s.value=h,i.addChild(s),t}throw new ht("Unexpected end",e,t)}static isValidChar(e){return e>=lt.CharCodeLowerA&&e<=lt.CharCodeLowerZ||e>=lt.CharCodeUpperA&&e<=lt.CharCodeUpperZ||e>=lt.CharCode0&&e<=lt.CharCode9||e===lt.CharCodeColon||e===lt.CharCodeDot||e===lt.CharCodeUnderscore||e===lt.CharCodeMinus}}lt.CharCodeLF=10,lt.CharCodeTab=9,lt.CharCodeCR=13,lt.CharCodeSpace=32,lt.CharCodeLowerThan=60,lt.CharCodeAmp=38,lt.CharCodeBrackedClose=93,lt.CharCodeBrackedOpen=91,lt.CharCodeGreaterThan=62,lt.CharCodeExclamation=33,lt.CharCodeUpperD=68,lt.CharCodeLowerD=100,lt.CharCodeMinus=45,lt.CharCodeQuestion=63,lt.CharCodeSlash=47,lt.CharCodeEquals=61,lt.CharCodeDoubleQuote=34,lt.CharCodeSingleQuote=39,lt.CharCodeSharp=35,lt.CharCodeLowerX=120,lt.CharCodeLowerA=97,lt.CharCodeLowerZ=122,lt.CharCodeUpperA=65,lt.CharCodeUpperZ=90,lt.CharCode0=48,lt.CharCode9=57,lt.CharCodeColon=58,lt.CharCodeDot=46,lt.CharCodeUnderscore=95,lt.CharCodeSemi=59,lt.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class dt{static write(e,t,i){const s=new dt(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 G.None:break;case G.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===G.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case G.Text:e.value&&this.write(e.value);break;case G.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case G.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case G.DocumentType:this.write(`<!DOCTYPE ${e.value}>`)}}unindend(){this._currentIndention=this._currentIndention.substr(0,this._currentIndention.length-this._indention.length)}indent(){this._currentIndention+=this._indention}writeAttributeValue(e){for(let t=0;t<e.length;t++){const i=e.charAt(t);switch(i){case"<":this._result.push("<");break;case">":this._result.push(">");break;case"&":this._result.push("&");break;case"'":this._result.push("'");break;case'"':this._result.push(""");break;default:this._result.push(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 ct extends ot{constructor(){super(),this.nodeType=G.Document}parse(e){lt.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return dt.write(this,e,t)}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(H||(H={}));class ut{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=u.Quarter}}class pt{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return this.path+";"+this.name+";"+this.role}}class gt{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1}parseXml(e,t){this._masterTrackAutomations=new Map,this._automationsPerTrackIdAndBarIndex=new Map,this._tracksMapping=[],this._tracksById=new Map,this._masterBars=[],this._barsOfMasterBar=[],this._voicesOfBar=new Map,this._barsById=new Map,this._voiceById=new Map,this._beatsOfVoice=new Map,this._beatById=new Map,this._rhythmOfBeat=new Map,this._rhythmById=new Map,this._notesOfBeat=new Map,this._noteById=new Map,this._tappedNotes=new Map,this._lyricsByTrack=new Map,this._soundsByTrack=new Map,this._skipApplyLyrics=!1;let i=new ct;try{i.parse(e)}catch(e){throw new ge("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 ge("Root node of XML was not GPIF");this.score=new He;for(let e of t.childNodes)if(e.nodeType===G.Element)switch(e.localName){case"Score":this.parseScoreNode(e);break;case"MasterTrack":this.parseMasterTrackNode(e);break;case"Tracks":this.parseTracksNode(e);break;case"MasterBars":this.parseMasterBarsNode(e);break;case"Bars":this.parseBars(e);break;case"Voices":this.parseVoices(e);break;case"Beats":this.parseBeats(e);break;case"Notes":this.parseNotes(e);break;case"Rhythms":this.parseRhythms(e)}}}parseScoreNode(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Title":this.score.title=t.firstChild.innerText;break;case"SubTitle":this.score.subTitle=t.firstChild.innerText;break;case"Artist":this.score.artist=t.firstChild.innerText;break;case"Album":this.score.album=t.firstChild.innerText;break;case"Words":this.score.words=t.firstChild.innerText;break;case"Music":this.score.music=t.firstChild.innerText;break;case"WordsAndMusic":if(t.firstChild&&""!==t.firstChild.innerText){let e=t.firstChild.innerText;e&&!this.score.words&&(this.score.words=e),e&&!this.score.music&&(this.score.music=e)}break;case"Copyright":this.score.copyright=t.firstChild.innerText;break;case"Tabber":this.score.tab=t.firstChild.innerText;break;case"Instructions":this.score.instructions=t.firstChild.innerText;break;case"Notices":this.score.notices=t.firstChild.innerText}}parseMasterTrackNode(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null);break;case"Tracks":this._tracksMapping=t.innerText.split(" ");break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,i){for(let s of e.childNodes)if(s.nodeType===G.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,d=null;for(let t of e.childNodes)if(t.nodeType===G.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===G.CDATA)h=t.innerText;else{let e=t.innerText.split(" ");1===e.length?(o=parseFloat(e[0]),l=1):(o=parseFloat(e[0]),l=parseInt(e[1]))}break;case"Text":d=t.innerText}if(!s)return;let c=null;switch(s){case"Tempo":c=fe.buildTempoAutomation(a,n,o,l);break;case"Sound":h&&i&&i.has(h)&&(c=fe.buildInstrumentAutomation(a,n,i.get(h).program))}c&&(d&&(c.text=d),r>=0&&(t.has(r)||t.set(r,[]),t.get(r).push(c)))}parseTracksNode(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;let t=new Je;t.ensureStaveCount(1),t.staves[0].showStandardNotation=!0;let i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===G.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 Ue(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"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===G.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===G.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===G.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===G.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===G.Element&&"Articulation"===s.localName)this.parseArticulation(e,s,i)}parseArticulation(e,t,i){const s=new ve;s.outputMidiNumber=-1,s.elementType=i;let a="";for(let e of t.childNodes)if(e.nodeType===G.Element){const t=e.innerText;switch(e.localName){case"Name":a=e.innerText;break;case"OutputMidiNumber":t.length>0&&(s.outputMidiNumber=parseInt(t));break;case"TechniqueSymbol":s.techniqueSymbol=this.parseTechniqueSymbol(t);break;case"TechniquePlacement":switch(t){case"outside":case"above":s.techniqueSymbolPlacement=E.Bottom;break;case"inside":s.techniqueSymbolPlacement=E.Middle;break;case"below":s.techniqueSymbolPlacement=E.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==x.None&&(s.noteHeadHalf=s.noteHeadDefault),s.noteHeadWhole==x.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 x.PictEdgeOfCymbal;case"articStaccatoAbove":return x.ArticStaccatoAbove;case"noteheadParenthesis":return x.NoteheadParenthesis;case"stringsUpBow":return x.StringsUpBow;case"stringsDownBow":return x.StringsDownBow;case"guitarGolpe":return x.GuitarGolpe;default:return x.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return x.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return x.NoteheadDoubleWhole;case"noteheadWhole":return x.NoteheadWhole;case"noteheadHalf":return x.NoteheadHalf;case"noteheadBlack":return x.NoteheadBlack;case"noteheadNull":return x.NoteheadNull;case"noteheadXOrnate":return x.NoteheadXOrnate;case"noteheadTriangleUpWhole":return x.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return x.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return x.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return x.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return x.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return x.NoteheadDiamondWhiteWide;case"noteheadCircleX":return x.NoteheadCircleX;case"noteheadXWhole":return x.NoteheadXWhole;case"noteheadXHalf":return x.NoteheadXHalf;case"noteheadXBlack":return x.NoteheadXBlack;case"noteheadParenthesis":return x.NoteheadParenthesis;case"noteheadSlashedBlack2":return x.NoteheadSlashedBlack2;case"noteheadCircleSlash":return x.NoteheadCircleSlash;case"noteheadHeavyX":return x.NoteheadHeavyX;case"noteheadHeavyXHat":return x.NoteheadHeavyXHat;default:return Be.warning("GPIF","Unknown notehead symbol",e),x.None}}parseStaves(e,t){let i=0;for(let s of t.childNodes)if(s.nodeType===G.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===G.Element&&"Properties"===i.localName)this.parseStaffProperties(e,i)}parseStaffProperties(e,t){for(let i of t.childNodes)if(i.nodeType===G.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===G.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===G.Element&&"Line"===e.localName)i.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,i)}parseLyricsLine(e){let t=new Ae;for(let i of e.childNodes)if(i.nodeType===G.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===G.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===G.Element&&"Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){let i=new Re,s=t.getAttribute("id");for(let t of e.staves)t.addChord(s,i);this.parseDiagramItemForChord(i,t)}parseDiagramItemForStaff(e,t){let i=new Re,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"),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===G.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===G.Element&&"Position"===i.localName){let t=f.Unknown,s=a+parseInt(i.getAttribute("fret"));switch(i.getAttribute("finger")){case"Index":t=f.IndexFinger;break;case"Middle":t=f.MiddleFinger;break;case"Rank":t=f.AnnularFinger;break;case"Pinky":t=f.LittleFinger;break;case"Thumb":t=f.Thumb}t!==f.Unknown&&(r.has(t)?e.barreFrets.push(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===G.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===G.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===G.Element&&"Sound"===s.localName)this.parseSound(e,t,s)}parseSound(e,t,i){const s=new pt;for(let e of i.childNodes)if(e.nodeType===G.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===G.Element&&"Program"===i.localName)e.program=parseInt(i.innerText)}parsePartSounding(e,t){for(let i of t.childNodes)if(i.nodeType===G.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===G.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===G.Element&&"ChannelStrip"===i.localName)this.parseChannelStrip(e,i)}parseChannelStrip(e,t){for(let i of t.childNodes)if(i.nodeType===G.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===G.Element&&"MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){let t=new Oe;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(let i of e.childNodes)if(i.nodeType===G.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 We,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=I.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=I.Triplet8th;break;case"Triplet16th":t.tripletFeel=I.Triplet16th;break;case"Dotted8th":t.tripletFeel=I.Dotted8th;break;case"Dotted16th":t.tripletFeel=I.Dotted16th;break;case"Scottish8th":t.tripletFeel=I.Scottish8th;break;case"Scottish16th":t.tripletFeel=I.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)}this._masterBars.push(t)}parseFermatas(e,t){for(let i of t.childNodes)if(i.nodeType===G.Element&&"Fermata"===i.localName)this.parseFermata(e,i)}parseFermata(e,t){let i=0,s=new nt;for(let e of t.childNodes)if(e.nodeType===G.Element)switch(e.localName){case"Type":switch(e.innerText){case"Short":s.type=O.Short;break;case"Medium":s.type=O.Medium;break;case"Long":s.type=O.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])*ye.QuarterTime|0}}e.addFermata(i,s)}parseBars(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"Bar"===t.localName)this.parseBar(t)}parseBar(e){let t=new me,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"Voices":this._voicesOfBar.set(i,s.innerText.split(" "));break;case"Clef":switch(s.innerText){case"Neutral":t.clef=r.Neutral;break;case"G2":t.clef=r.G2;break;case"F4":t.clef=r.F4;break;case"C4":t.clef=r.C4;break;case"C3":t.clef=r.C3}break;case"Ottavia":switch(s.innerText){case"8va":t.clefOttava=n._8va;break;case"15ma":t.clefOttava=n._15ma;break;case"8vb":t.clefOttava=n._8vb;break;case"15mb":t.clefOttava=n._15mb}break;case"SimileMark":switch(s.innerText){case"Simple":t.simileMark=o.Simple;break;case"FirstOfDouble":t.simileMark=o.FirstOfDouble;break;case"SecondOfDouble":t.simileMark=o.SecondOfDouble}}this._barsById.set(i,t)}parseVoices(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"Voice"===t.localName)this.parseVoice(t)}parseVoice(e){let t=new je,i=e.getAttribute("id");for(let t of e.childNodes)if(t.nodeType===G.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===G.Element&&"Beat"===t.localName)this.parseBeat(t)}parseBeat(e){let t=new Ie,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===G.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=u.Eighth;break;case"1/4":t.tremoloSpeed=u.Sixteenth;break;case"1/8":t.tremoloSpeed=u.ThirtySecond}break;case"Chord":t.chordId=s.innerText;break;case"Hairpin":switch(s.innerText){case"Crescendo":t.crescendo=c.Crescendo;break;case"Decrescendo":t.crescendo=c.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=H.Up;break;case"Downward":t.preferredBeamDirection=H.Down}break;case"Dynamic":switch(s.innerText){case"PPP":t.dynamics=p.PPP;break;case"PP":t.dynamics=p.PP;break;case"P":t.dynamics=p.P;break;case"MP":t.dynamics=p.MP;break;case"MF":t.dynamics=p.MF;break;case"F":t.dynamics=p.F;break;case"FF":t.dynamics=p.FF;break;case"FFF":t.dynamics=p.FFF}break;case"GraceNotes":switch(s.innerText){case"OnBeat":t.graceType=g.OnBeat;break;case"BeforeBeat":t.graceType=g.BeforeBeat}break;case"Legato":"true"===s.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":let e=new be(0,0);e.value=this.toBendValue(parseFloat(s.getAttribute("originValue"))),e.offset=this.toBendOffset(parseFloat(s.getAttribute("originOffset"))),t.addWhammyBarPoint(e);let a=new be(0,0);a.value=this.toBendValue(parseFloat(s.getAttribute("middleValue"))),a.offset=this.toBendOffset(parseFloat(s.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);let r=new be(0,0);r.value=this.toBendValue(parseFloat(s.getAttribute("middleValue"))),r.offset=this.toBendOffset(parseFloat(s.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);let o=new be(0,0);o.value=this.toBendValue(parseFloat(s.getAttribute("destinationValue"))),o.offset=this.toBendOffset(parseFloat(s.getAttribute("destinationOffset"))),t.addWhammyBarPoint(o);break;case"Ottavia":switch(s.innerText){case"8va":t.ottava=n._8va;break;case"8vb":t.ottava=n._8vb;break;case"15ma":t.ottava=n._15ma;break;case"15mb":t.ottava=n._15mb}break;case"Lyrics":t.lyrics=this.parseBeatLyrics(s),this._skipApplyLyrics=!0}this._beatById.set(i,t)}parseBeatLyrics(e){const t=[];for(let i of e.childNodes)if(i.nodeType===G.Element&&"Line"===i.localName)t.push(i.innerText);return t}parseBeatXProperties(e,t){for(let i of e.childNodes)if(i.nodeType===G.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}}}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===G.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 be(0,0)),s.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":s||(s=new be(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 be(be.MaxPosition,0)),o.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new be(0,0)),o.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText))}}i&&(s||(s=new be(0,0)),o||(o=new be(be.MaxPosition,0)),t.addWhammyBarPoint(s),r&&a&&t.addWhammyBarPoint(new be(r,a)),n&&a&&t.addWhammyBarPoint(new be(n,a)),r||n||!a||t.addWhammyBarPoint(new be(be.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"Note"===t.localName)this.parseNote(t)}parseNote(e){let t=new Pe,i=e.getAttribute("id");for(let a of e.childNodes)if(a.nodeType===G.Element)switch(a.localName){case"Properties":this.parseNoteProperties(a,t,i);break;case"AntiAccent":"normal"===a.innerText.toLowerCase()&&(t.isGhost=!0);break;case"LetRing":t.isLetRing=!0;break;case"Trill":t.trillValue=parseInt(a.innerText),t.trillSpeed=u.Sixteenth;break;case"Accent":let e=parseInt(a.innerText);0!=(1&e)&&(t.isStaccato=!0),0!=(4&e)&&(t.accentuated=s.Heavy),0!=(8&e)&&(t.accentuated=s.Normal);break;case"Tie":"true"===a.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(a.innerText){case"Slight":t.vibrato=_.Slight;break;case"Wide":t.vibrato=_.Wide}break;case"LeftFingering":switch(t.isFingering=!0,a.innerText){case"P":t.leftHandFinger=f.Thumb;break;case"I":t.leftHandFinger=f.IndexFinger;break;case"M":t.leftHandFinger=f.MiddleFinger;break;case"A":t.leftHandFinger=f.AnnularFinger;break;case"C":t.leftHandFinger=f.LittleFinger}break;case"RightFingering":switch(t.isFingering=!0,a.innerText){case"P":t.rightHandFinger=f.Thumb;break;case"I":t.rightHandFinger=f.IndexFinger;break;case"M":t.rightHandFinger=f.MiddleFinger;break;case"A":t.rightHandFinger=f.AnnularFinger;break;case"C":t.rightHandFinger=f.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=parseInt(a.innerText)}this._noteById.set(i,t)}parseNoteProperties(e,t,i){let s=!1,a=null,r=null,n=null,o=null,h=null,l=-1,d=-1;for(let c of e.childNodes)if(c.nodeType===G.Element&&"Property"===c.localName){switch(c.getAttribute("name")){case"String":t.string=parseInt(c.findChildElement("String").innerText)+1;break;case"Fret":t.fret=parseInt(c.findChildElement("Fret").innerText);break;case"Element":l=parseInt(c.findChildElement("Element").innerText);break;case"Variation":d=parseInt(c.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(i,!0);break;case"HarmonicType":let e=c.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=m.None;break;case"Natural":t.harmonicType=m.Natural;break;case"Artificial":t.harmonicType=m.Artificial;break;case"Pinch":t.harmonicType=m.Pinch;break;case"Tap":t.harmonicType=m.Tap;break;case"Semi":t.harmonicType=m.Semi;break;case"Feedback":t.harmonicType=m.Feedback}break;case"HarmonicFret":let u=c.findChildElement("HFret");u&&(t.harmonicValue=parseFloat(u.innerText));break;case"Muted":c.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":c.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=parseInt(c.findChildElement("Number").innerText),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=parseInt(c.findChildElement("Step").innerText);break;case"ConcertPitch":this.parseConcertPitch(c,t);break;case"Bended":s=!0;break;case"BendOriginValue":a||(a=new be(0,0)),a.value=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new be(0,0)),a.offset=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleValue":r=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleOffset1":n=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleOffset2":o=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendDestinationValue":h||(h=new be(be.MaxPosition,0)),h.value=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new be(0,0)),h.offset=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"HopoOrigin":c.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":let p=parseInt(c.findChildElement("Flags").innerText);0!=(1&p)?t.slideOutType=S.Shift:0!=(2&p)?t.slideOutType=S.Legato:0!=(4&p)?t.slideOutType=S.OutDown:0!=(8&p)&&(t.slideOutType=S.OutUp),0!=(16&p)?t.slideInType=b.IntoFromBelow:0!=(32&p)&&(t.slideInType=b.IntoFromAbove),0!=(64&p)?t.slideOutType=S.PickSlideDown:0!=(128&p)&&(t.slideOutType=S.PickSlideUp)}}s&&(a||(a=new be(0,0)),h||(h=new be(be.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new be(n,r)),o&&r&&t.addBendPoint(new be(o,r)),n||o||!r||t.addBendPoint(new be(be.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==d&&(t.percussionArticulation=Ne.articulationFromElementVariation(l,d))}parseConcertPitch(e,t){const i=e.findChildElement("Pitch");if(i)for(let e of i.childNodes)if(e.nodeType===G.Element&&"Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=y.ForceDoubleSharp;break;case"#":t.accidentalMode=y.ForceSharp;break;case"b":t.accidentalMode=y.ForceFlat;break;case"bb":t.accidentalMode=y.ForceDoubleFlat}}toBendValue(e){return e*gt.BendPointValueFactor|0}toBendOffset(e){return e*gt.BendPointPositionFactor}parseRhythms(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){let t=new ut,i=e.getAttribute("id");t.id=i;for(let i of e.childNodes)if(i.nodeType===G.Element)switch(i.localName){case"NoteValue":switch(i.innerText){case"Long":t.value=u.QuadrupleWhole;break;case"DoubleWhole":t.value=u.DoubleWhole;break;case"Whole":t.value=u.Whole;break;case"Half":t.value=u.Half;break;case"Quarter":t.value=u.Quarter;break;case"Eighth":t.value=u.Eighth;break;case"16th":t.value=u.Sixteenth;break;case"32nd":t.value=u.ThirtySecond;break;case"64th":t.value=u.SixtyFourth;break;case"128th":t.value=u.OneHundredTwentyEighth;break;case"256th":t.value=u.TwoHundredFiftySixth}break;case"PrimaryTuplet":t.tupletNumerator=parseInt(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!==gt.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!==gt.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!==gt.InvalidId){let t=Me.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!==gt.InvalidId){const e=Fe.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 je;e.addVoice(t);let i=new Ie;i.isEmpty=!0,i.duration=u.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,r=t.length;s<r;s++){let r=t[s];r.type===a.Tempo&&(0===e&&(this.score.tempo=0|r.value,r.text&&(this.score.tempoLabel=r.text)),i.tempoAutomation=r)}}}}gt.InvalidId="-1",gt.BendPointPositionFactor=be.MaxPosition/100,gt.BendPointValueFactor=.04;class ft{constructor(){this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class mt{constructor(){this.isMultiRest=!1,this.tracks=[]}}class yt{apply(e){let t=0,i=0;for(let s of this.parts)for(let a of s.tracks){if(i<e.tracks.length){let s=e.tracks[i];if(t<s.staves.length){let e=s.staves[t];e.showTablature=a.showTablature,e.showStandardNotation=a.showStandardNotation}}i++,i>=e.tracks.length&&(t++,i=0)}}constructor(e){this.parts=[],this.zoomLevel=0,this.layout=0;let t=Ke.fromBuffer(e),i=$e.readInt32BE(t);for(let e=0;e<i;e++){let e=new mt;this.parts.push(e),e.isMultiRest=it.gpReadBool(t);let i=$e.readInt32BE(t);for(let s=0;s<i;s++){let i=t.readByte();0===i&&(i=1);let s=new ft;s.showStandardNotation=0!=(1&i),s.showTablature=0!=(2&i),s.showSlash=0!=(4&i),e.tracks.push(s)}}}static writeForScore(e){const t=Ke.withCapacity(128),i=[new mt];for(const t of e.tracks)for(const e of t.staves){const t=new ft;if(t.showStandardNotation=e.showStandardNotation,t.showTablature=e.showTablature,0===e.index)i[0].tracks.push(t);else{let e=new mt;e.tracks.push(t),i.push(e)}}$e.writeInt32BE(t,i.length);for(const e of i){t.writeByte(e.isMultiRest?1:0),$e.writeInt32BE(t,e.tracks.length);for(const i of e.tracks){let e=0;i.showStandardNotation&&(e|=1),i.showTablature&&(e|=2),i.showSlash&&(e|=4),t.writeByte(e)}}return t.toArray()}}class bt{}class St extends bt{constructor(e){super(),this.n=e}}class _t extends bt{constructor(e,t){super(),this.left=e,this.right=t}}class wt extends bt{constructor(e,t){super(),this.n=e,this.table=t}}class Bt{static make(e,t,i,s){let a=[],r=[];if(s>32)throw new ze("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 ze("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 Bt.treeCompress(new _t(Bt.treeMake(o,s,0,1),Bt.treeMake(o,s,1,1)))}static treeMake(e,t,i,s){if(s>t)throw new ze("Invalid huffman");let a=i<<5|s;return e.has(a)?new St(e.get(a)):(i<<=1,s+=1,new _t(Bt.treeMake(e,t,i,s),Bt.treeMake(e,t,1|i,s)))}static treeCompress(e){let t=Bt.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof _t)return new _t(Bt.treeCompress(e.left),Bt.treeCompress(e.right));throw new ze("assert")}let i=1<<t,s=[];for(let e=0;e<i;e++)s.push(new St(-1));return Bt.treeWalk(s,0,0,t,e),new wt(t,s)}static treeWalk(e,t,i,s,a){a instanceof _t&&s>0?(Bt.treeWalk(e,t,i+1,s-1,a.left),Bt.treeWalk(e,t|1<<i,i+1,s-1,a.right)):e[t]=Bt.treeCompress(a)}static treeDepth(e){if(e instanceof St)return 0;if(e instanceof wt)throw new ze("assert");if(e instanceof _t){let t=Bt.treeDepth(e.left),i=Bt.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"}(W||(W={}));class Tt{constructor(){this.buffer=new Uint8Array(Tt.BufferSize),this.pos=0}slide(){let e=new Uint8Array(Tt.BufferSize);this.pos-=Tt.Size,e.set(this.buffer.subarray(Tt.Size,Tt.Size+this.pos),0),this.buffer=e}addBytes(e,t,i){this.pos+i>Tt.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+i),this.pos),this.pos+=i}addByte(e){this.pos===Tt.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}Tt.Size=32768,Tt.BufferSize=65536;class kt{static buildFixedHuffman(){let e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return Bt.make(e,0,288,10)}constructor(e){this._nbits=0,this._bits=0,this._state=W.Block,this._isFinal=!1,this._huffman=kt._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new Tt,this._input=e;for(let e=0;e<19;e++)this._lengths.push(-1)}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 W.Head:let e=this._input.readByte();if(8!==(15&e))throw new ze("Invalid data");let t=this._input.readByte(),i=0!=(32&t);if(((e<<8)+t)%31!=0)throw new ze("Invalid data");if(i)throw new ze("Unsupported dictionary");return this._state=W.Block,!0;case W.Crc:return this._state=W.Done,!0;case W.Done:return!1;case W.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:if(this._len=$e.readUInt16LE(this._input),$e.readUInt16LE(this._input)!==65535-this._len)throw new ze("Invalid data");this._state=W.Flat;let e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=kt._fixedHuffman,this._huffdist=null,this._state=W.CData,!0;case 2:let t=this.getBits(5)+257,i=this.getBits(5)+1,s=this.getBits(4)+4;for(let e=0;e<s;e++)this._lengths[kt.CodeLengthsPos[e]]=this.getBits(3);for(let e=s;e<19;e++)this._lengths[kt.CodeLengthsPos[e]]=0;this._huffman=Bt.make(this._lengths,0,19,8);let a=[];for(let e=0;e<t+i;e++)a.push(0);return this.inflateLengths(a,t+i),this._huffdist=Bt.make(a,t,i,16),this._huffman=Bt.make(a,0,t,16),this._state=W.CData,!0;default:throw new ze("Invalid data")}case W.Flat:{let e=this._len<this._needed?this._len:this._needed,t=$e.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?W.Crc:W.Block),this._needed>0}case W.DistOne:{let e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=W.CData),this._needed>0}case W.Dist:for(;this._len>0&&this._needed>0;){let e=this._len<this._dist?this._len:this._dist,t=this._needed<e?this._needed:e;this.addDist(this._dist,t),this._len-=t}return 0===this._len&&(this._state=W.CData),this._needed>0;case W.CData:let s=this.applyHuffman(this._huffman);if(s<256)return this.addByte(s),this._needed>0;if(256===s)return this._state=this._isFinal?W.Crc:W.Block,!0;{s=s-257&255;let e=kt.LenExtraBitsTbl[s];if(-1===e)throw new ze("Invalid data");this._len=kt.LenBaseValTbl[s]+this.getBits(e);let t=this._huffdist,i=t?this.applyHuffman(t):this.getRevBits(5);if(e=kt.DistExtraBitsTbl[i],-1===e)throw new ze("Invalid data");if(this._dist=kt.DistBaseValTbl[i]+this.getBits(e),this._dist>this._window.available())throw new ze("Invalid data");return this._state=1===this._dist?W.DistOne:W.Dist,!0}}return!1}addDistOne(e){let t=this._window.getLastChar();for(let 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==(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 ze("Invalid data");for(;i<r;)e[i]=s,i++;break;case 17:if(i+=3+this.getBits(3),i>t)throw new ze("Invalid data");break;case 18:if(i+=11+this.getBits(7),i>t)throw new ze("Invalid data");break;default:throw new ze("Invalid data")}}}applyHuffman(e){if(e instanceof St)return e.n;if(e instanceof _t)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof wt)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new ze("Invalid data")}}kt.LenExtraBitsTbl=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,-1,-1],kt.LenBaseValTbl=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],kt.DistExtraBitsTbl=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,-1,-1],kt.DistBaseValTbl=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],kt.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],kt._fixedHuffman=kt.buildFixedHuffman();class vt{constructor(e,t){this.fullName=e;let i=e.lastIndexOf("/");this.fileName=-1===i||i===e.length-1?this.fullName:e.substr(i+1),this.data=t}}vt.OptionalDataDescriptorSignature=134695760,vt.CompressionMethodDeflate=8,vt.LocalFileHeaderSignature=67324752,vt.CentralFileHeaderSignature=33639248,vt.EndOfCentralDirSignature=101010256;class Nt{constructor(e){this._readable=e}read(){let e=[];for(;;){let t=this.readEntry();if(!t)break;e.push(t)}return e}readEntry(){let e=this._readable;if($e.readInt32LE(e)!==vt.LocalFileHeaderSignature)return null;$e.readUInt16LE(e);let t=$e.readUInt16LE(e),i=$e.readUInt16LE(e),s=0!==i;if(s&&i!==vt.CompressionMethodDeflate)return null;$e.readInt16LE(this._readable),$e.readInt16LE(this._readable),$e.readInt32LE(e),$e.readInt32LE(e);let a,r=$e.readInt32LE(e),n=$e.readInt16LE(e),o=$e.readInt16LE(e),h=$e.toString($e.readByteArray(e,n),"utf-8");if(e.skip(o),s){let e=Ke.empty(),t=new kt(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=$e.readByteArray(this._readable,r);if(0!=(8&t)){$e.readInt32LE(this._readable)===vt.OptionalDataDescriptorSignature&&$e.readInt32LE(this._readable),$e.readInt32LE(this._readable),$e.readInt32LE(this._readable)}return new vt(h,a)}}class xt extends ue{get name(){return"Guitar Pro 7"}constructor(){super()}readScore(){Be.debug(this.name,"Loading ZIP entries");let e,t=new Nt(this.data);try{e=t.read()}catch(e){throw new ge("No Zip archive",e)}Be.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=$e.toString(t.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=t.data;break;case"PartConfiguration":a=t.data}if(!i)throw new ge("No score.gpif found in zip archive");Be.debug(this.name,"Start Parsing score.gpif");let r=new gt;r.parseXml(i,this.settings),Be.debug(this.name,"score.gpif parsed");let n=r.score;if(s){Be.debug(this.name,"Start Parsing BinaryStylesheet"),new rt(s).apply(n),Be.debug(this.name,"BinaryStylesheet parsed")}if(a){Be.debug(this.name,"Start Parsing Part Configuration"),new yt(a).apply(n),Be.debug(this.name,"Part Configuration parsed")}return n}}class Pt extends pe{constructor(){super(i.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,Pt.prototype)}}class Et{constructor(e){this._currentByte=0,this._position=Et.ByteSize,this._source=e}readByte(){return this.readBits(8)}readBytes(e){const t=new Uint8Array(e);for(let 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 Pt;this._position=0}const e=this._currentByte>>Et.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 Pt))throw e}return e.toArray()}}Et.ByteSize=8;class Ct{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class Ft{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){let t=new Et(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){let 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 Pt))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 ge("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 Ct;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]}}Ft.HeaderBcFs="BCFS",Ft.HeaderBcFz="BCFZ",Ft.ScoreGpif="score.gpif",Ft.BinaryStylesheet="BinaryStylesheet",Ft.PartConfiguration="PartConfiguration";class Lt extends ue{get name(){return"Guitar Pro 6"}constructor(){super()}readScore(){Be.debug(this.name,"Loading GPX filesystem");let e=new Ft;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration"),e.load(this.data),Be.debug(this.name,"GPX filesystem loaded");let t=null,i=null,s=null;for(let a of e.files)switch(a.fileName){case"score.gpif":t=$e.toString(a.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=a.data;break;case"PartConfiguration":s=a.data}if(!t)throw new ge("No score.gpif found in GPX");Be.debug(this.name,"Start Parsing score.gpif");let a=new gt;a.parseXml(t,this.settings),Be.debug(this.name,"score.gpif parsed");let r=a.score;if(i){Be.debug(this.name,"Start Parsing BinaryStylesheet"),new rt(i).apply(r),Be.debug(this.name,"BinaryStylesheet parsed")}if(s){Be.debug(this.name,"Start Parsing Part Configuration"),new yt(s).apply(r),Be.debug(this.name,"Part Configuration parsed")}return r}}class Mt extends ue{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=$e.toString(this.data.readAll(),this.settings.importer.encoding),t=new ct;try{t.parse(e)}catch(e){throw new ge("Unsupported format")}return this._score=new He,this._score.tempo=120,this.parseDom(t),this.settings.importer.mergePartGroupsInMusicXml&&this.mergePartGroups(),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}mergePartGroups(){let e=!1;for(const t of this._partGroups.values())t.length>1&&(this.mergeGroup(t),e=!0);if(e)for(let e=0;e<this._score.tracks.length;e++)this._score.tracks[e].index=e}mergeGroup(e){let t=e[0];for(let 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 ge("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":break;default:throw new ge("Unsupported format")}}parsePartwise(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"work":this.parseWork(t);break;case"movement-title":this._score.title=t.innerText;break;case"identification":this.parseIdentification(t);break;case"part-list":this.parsePartList(t);break;case"part":this.parsePart(t)}}parseWork(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"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===G.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 me;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)}if(r){let i=!1;for(let s of e.childNodes)if(s.nodeType===G.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);break;case"sound":break;case"barline":this.parseBarline(s,r)}}return!0}ensureVoices(e){for(;e.voices.length<this._maxVoices;){let t=new je;e.addVoice(t);let i=new Ie;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 d=this.getOrCreateVoice(n,s);return i&&d.beats.length>0||1===d.beats.length&&d.isEmpty?o=d.beats[d.beats.length-1]:(o=new Ie,o.isEmpty=!1,d.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)*u.Quarter/this._divisionsPerQuarterNote,a=[u.SixtyFourth,u.ThirtySecond,u.Sixteenth,u.Eighth,u.Quarter,u.Half,u.Whole];for(let e of a)if(s>=e){i.duration=e,s-=e;break}i.isEmpty=!1}parseStaffDetails(e,t){for(let i of e.childNodes)if(i.nodeType===G.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===G.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=ke.getTuningForText(s+a)+r;for(let e of t.staves)e.tuning[e.tuning.length-i]=n}parseHarmony(e,t){let i=null,s="";for(let t of e.childNodes)if(t.nodeType===G.Element&&"root"===t.localName)for(let e of t.childNodes)if(e.nodeType===G.Element)switch(e.localName){case"root-step":i=e.innerText;break;case"root-alter":switch(parseInt(t.innerText)){case-2:s=" bb";break;case-1:s=" b";break;case 0:s="";break;case 1:s=" #";break;case 2:s=" ##"}}let a=new Re;a.name=i+s,this._currentChord=ke.newGuid();for(let e of t.staves)e.addChord(this._currentChord,a)}parseBarline(e,t){for(let i of e.childNodes)if(i.nodeType===G.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 Pe;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===G.Element)switch(t.localName){case"grace":s.graceType=g.BeforeBeat,s.duration=u.ThirtySecond;break;case"duration":if(s.isRest&&!r){switch(parseInt(t.innerText)){case 1:s.duration=u.Whole;break;case 2:s.duration=u.Half;break;case 4:default:s.duration=u.Quarter;break;case 8:s.duration=u.Eighth;break;case 16:s.duration=u.Sixteenth;break;case 32:s.duration=u.ThirtySecond;break;case 64:s.duration=u.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!==g.None&&s.duration<u.Sixteenth&&(s.duration=u.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=u.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 u.SixtyFourth;case"32nd":return u.ThirtySecond;case"16th":return u.Sixteenth;case"eighth":return u.Eighth;case"quarter":return u.Quarter;case"half":return u.Half;case"long":case"breve":case"whole":return u.Whole}return u.Quarter}parseLyric(e,t){for(let i of e.childNodes)if(i.nodeType===G.Element&&"text"===i.localName)t.text?t.text+=" "+i.innerText:t.text=i.innerText}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=y.ForceSharp;break;case"natural":t.accidentalMode=y.ForceNatural;break;case"flat":t.accidentalMode=y.ForceFlat}}parseTied(e,t){"start"===e.getAttribute("type")?this._tieStartIds.has(t.id)||(this._tieStartIds.set(t.id,!0),this._tieStarts.push(t)):"stop"===e.getAttribute("type")&&this._tieStarts.length>0&&!t.isTieDestination&&(t.isTieDestination=!0,t.tieOrigin=this._tieStarts[0],this._tieStarts.splice(0,1),this._tieStartIds.delete(t.id))}parseNotations(e,t,i){for(let s of e.childNodes)if(s.nodeType===G.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=S.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===G.Element&&"tremolo"===i.localName){switch(parseInt(i.innerText)){case 1:t.beat.tremoloSpeed=u.Eighth;break;case 2:t.beat.tremoloSpeed=u.Sixteenth;break;case 3:t.beat.tremoloSpeed=u.ThirtySecond}}}parseTechnical(e,t){for(let i of e.childNodes)if(i.nodeType===G.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=s.Normal;break;case"strong-accent":t.accentuated=s.Heavy;break;case"staccato":case"detached-legato":t.isStaccato=!0}}parseDynamics(e,t){for(let i of e.childNodes)if(i.nodeType===G.Element)switch(i.localName){case"p":t.dynamics=p.P;break;case"pp":t.dynamics=p.PP;break;case"ppp":t.dynamics=p.PPP;break;case"f":t.dynamics=p.F;break;case"ff":t.dynamics=p.FF;break;case"fff":t.dynamics=p.FFF;break;case"mp":t.dynamics=p.MP;break;case"mf":t.dynamics=p.MF}}parseTimeModification(e,t){for(let i of e.childNodes)if(i.nodeType===G.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===G.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+ke.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===G.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+ke.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 je);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===G.Element)switch(i.localName){case"sound":let e=i.getAttribute("tempo");if(e){let i=new fe;i.isLinear=!0,i.type=a.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=u.Quarter,s=120;for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"beat-unit":i=this.getDuration(t.innerText);break;case"per-minute":s=parseInt(t.innerText)}let r=new fe;r.type=a.Tempo,r.value=s*(i/4|0),t.tempoAutomation=r,0===t.index&&(t.score.tempo=r.value)}parseAttributes(e,t,i,s){let a=0,r=!1;for(let n of e.childNodes)if(n.nodeType===G.Element)switch(n.localName){case"divisions":this._divisionsPerQuarterNote=parseInt(n.innerText);break;case"key":this.parseKey(n,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===G.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===G.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=n._15mb;break;case-1:t.clefOttava=n._8vb;break;case 1:t.clefOttava=n._8va;break;case 2:t.clefOttava=n._15mb}}switch(i){case"g":default:t.clef=r.G2;break;case"f":t.clef=r.F4;break;case"c":t.clef=3===s?r.C3:r.C4;break;case"percussion":t.clef=r.Neutral,t.staff.isPercussion=!0;break;case"tab":t.clef=r.G2,t.staff.showTablature=!0}}parseTime(e,t){"common"===e.getAttribute("symbol")&&(t.timeSignatureCommon=!0);let i=!1,s=!1;for(let a of e.childNodes)if(a.nodeType===G.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===G.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:L.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 Oe;if(this._score.masterBars.length>0){let t=this._score.masterBars[this._score.masterBars.length-1];e.timeSignatureDenominator=t.timeSignatureDenominator,e.timeSignatureNumerator=t.timeSignatureNumerator,e.keySignature=t.keySignature,e.keySignatureType=t.keySignatureType}this._score.addMasterBar(e)}return this._score.masterBars[e]}parseIdentification(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"creator":"composer"===t.getAttribute("type")&&(this._score.music=t.innerText);break;case"rights":this._score.copyright&&(this._score.copyright+="\n"),this._score.copyright+=t.innerText}}parsePartList(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"part-group":this.parsePartGroup(t);break;case"score-part":this.parseScorePart(t)}}parsePartGroup(e){switch(e.getAttribute("type")){case"start":this._currentPartGroup=e.getAttribute("number"),this._partGroups.set(this._currentPartGroup,[]);break;case"stop":this._currentPartGroup=null}}parseScorePart(e){let t=e.getAttribute("id"),i=new Je;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===G.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===G.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.PerNotePitchBend=96]="PerNotePitchBend",e[e.NoteOff=128]="NoteOff",e[e.NoteOn=144]="NoteOn",e[e.NoteAftertouch=160]="NoteAftertouch",e[e.Controller=176]="Controller",e[e.ProgramChange=192]="ProgramChange",e[e.ChannelAftertouch=208]="ChannelAftertouch",e[e.PitchBend=224]="PitchBend",e[e.SystemExclusive=240]="SystemExclusive",e[e.SystemExclusive2=247]="SystemExclusive2",e[e.Meta=255]="Meta"}(z||(z={}));class Dt{get channel(){return 15&this.message}get command(){return 240&this.message}get data1(){return(65280&this.message)>>8}set data1(e){this.message&=-65281,this.message|=e<<8}get data2(){return(16711680&this.message)>>16}set data2(e){this.message&=-16711681,this.message|=e<<16}constructor(e,t,i,s,a){this.track=e,this.tick=t,this.message=i|s<<8|a<<16}writeTo(e){let t=new Uint8Array([this.message>>24&255,this.message>>16&255,this.message>>8&255,255&this.message]);e.write(t,0,t.length)}}!function(e){e[e.SequenceNumber=0]="SequenceNumber",e[e.TextEvent=1]="TextEvent",e[e.CopyrightNotice=2]="CopyrightNotice",e[e.SequenceOrTrackName=3]="SequenceOrTrackName",e[e.InstrumentName=4]="InstrumentName",e[e.LyricText=5]="LyricText",e[e.MarkerText=6]="MarkerText",e[e.CuePoint=7]="CuePoint",e[e.PatchName=8]="PatchName",e[e.PortName=9]="PortName",e[e.MidiChannel=32]="MidiChannel",e[e.MidiPort=33]="MidiPort",e[e.EndOfTrack=47]="EndOfTrack",e[e.Tempo=81]="Tempo",e[e.SmpteOffset=84]="SmpteOffset",e[e.TimeSignature=88]="TimeSignature",e[e.KeySignature=89]="KeySignature",e[e.SequencerSpecific=127]="SequencerSpecific"}(U||(U={}));class It extends Dt{get channel(){return-1}get command(){return 255&this.message}get metaStatus(){return this.data1}constructor(e,t,i,s,a){super(e,t,i,s,a)}}!function(e){e[e.SystemExclusive=240]="SystemExclusive",e[e.MtcQuarterFrame=241]="MtcQuarterFrame",e[e.SongPosition=242]="SongPosition",e[e.SongSelect=243]="SongSelect",e[e.TuneRequest=246]="TuneRequest",e[e.SystemExclusive2=247]="SystemExclusive2"}(X||(X={}));class Rt extends Dt{get channel(){return-1}get command(){return 255&this.message}constructor(e,t,i,s,a){super(e,t,i,s,a)}}!function(e){e[e.MetronomeTick=0]="MetronomeTick",e[e.Rest=1]="Rest"}(Y||(Y={}));class At extends Rt{get isMetronome(){return this.manufacturerId==At.AlphaTabManufacturerId&&this.data[0]==Y.MetronomeTick}get metronomeNumerator(){return this.isMetronome?this.data[1]:-1}get metronomeDurationInTicks(){return this.isMetronome?$e.decodeUInt32LE(this.data,2):-1}get metronomeDurationInMilliseconds(){return this.isMetronome?$e.decodeUInt32LE(this.data,6):-1}get isRest(){return this.manufacturerId==At.AlphaTabManufacturerId&&this.data[0]==Y.Rest}get manufacturerId(){return this.message>>8}constructor(e,t,i,s,a){super(e,t,i,255&s,s>>8&255),this.data=a}writeTo(e){e.writeByte(240);let t=this.data.length+2;e.writeByte(this.manufacturerId);let i=new Uint8Array([t>>24&255,t>>16&255,t>>8&255,255&t]);e.write(i,0,i.length),e.writeByte(247)}static encodeMetronome(e,t,i){const s=Ke.withCapacity(10);return s.writeByte(Y.MetronomeTick),s.writeByte(e),$e.writeInt32LE(s,t),$e.writeInt32LE(s,i),s.toArray()}}At.AlphaTabManufacturerId=125;class Ot{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event instanceof At&&this.event.isMetronome}static newMetronomeEvent(e,t,i,s,a){const r=new At(0,t,z.SystemExclusive2,At.AlphaTabManufacturerId,At.encodeMetronome(i,s,a));return new Ot(e,r)}}class Gt{}Gt.DefaultChannelCount=17,Gt.MetronomeChannel=Gt.DefaultChannelCount-1,Gt.AudioChannels=2,Gt.MinVolume=0,Gt.MinProgram=0,Gt.MaxProgram=127,Gt.MinPlaybackSpeed=.125,Gt.MaxPlaybackSpeed=8,Gt.MaxPitchWheel=16384,Gt.MaxPitchWheel20=4294967296,Gt.DefaultPitchWheel=Gt.MaxPitchWheel/2,Gt.MicroBufferCount=32,Gt.MicroBufferSize=64;class Vt{constructor(e,t,i){this.bpm=e,this.ticks=t,this.time=i}}class Ht{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=ye.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class Wt{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 Ht,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(Gt.MicroBufferSize);this._mainState.currentTime=i;let s=Date.now()-t;Be.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 Ht;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,d=0;for(let c of e.events){let u=new Ot(t.synthData.length,c);t.synthData.push(u);let p=c.tick-d;if(s+=p,a+=p*(6e4/(i*e.division)),u.time=a,d=c.tick,n>0)for(;h<s;){let e=Ot.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(c.command===z.Meta&&c.data1===U.Tempo){i=6e7/c.value,t.tempoChanges.push(new Vt(i,s,a)),o=n*(6e4/(i*e.division))}else if(c.command===z.Meta&&c.data1===U.TimeSignature){let s=c,a=Math.pow(2,s.data[1]);r=s.data[0],n=t.division*(4/a)|0,o=n*(6e4/(i*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=s.data[0],t.firstTimeSignatureDenominator=a)}else if(c.command===z.ProgramChange){let e=c.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=Gt.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 Ht;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 Vt(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=Ot.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"}(q||(q={}));class zt{constructor(e,t){this.state=e,this.stopped=t}}class Ut{constructor(e,t,i,s,a){this.currentTime=e,this.endTime=t,this.currentTick=i,this.endTick=s,this.isSeek=a}}class Xt{constructor(){this.id="",this.size=0}static load(e,t,i){if(e&&Xt.HeaderSize>e.size)return!1;if(i.position+Xt.HeaderSize>=i.length)return!1;if(t.id=$e.read8BitStringLength(i,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=$e.readUInt32LE(i),e&&Xt.HeaderSize+t.size>e.size)return!1;e&&(e.size-=Xt.HeaderSize+t.size);let s="RIFF"===t.id,a="LIST"===t.id;return(!s||!e)&&(!s&&!a||(t.id=$e.read8BitStringLength(i,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}Xt.HeaderSize=8;class Yt{constructor(){this.phdrs=[],this.pbags=[],this.pmods=[],this.pgens=[],this.insts=[],this.ibags=[],this.imods=[],this.igens=[],this.sHdrs=[],this.fontSamples=new Float32Array(0)}load(e){const t=new Xt,i=new Xt;if(!Xt.load(null,t,e)||"sfbk"!==t.id)throw new ze("Soundfont is not a valid Soundfont2 file");for(;Xt.load(t,i,e);){let t=new Xt;if("pdta"===i.id)for(;Xt.load(i,t,e);)switch(t.id){case"phdr":for(let i=0,s=t.size/Zt.SizeInFile|0;i<s;i++)this.phdrs.push(new Zt(e));break;case"pbag":for(let i=0,s=t.size/$t.SizeInFile|0;i<s;i++)this.pbags.push(new $t(e));break;case"pmod":for(let i=0,s=t.size/ei.SizeInFile|0;i<s;i++)this.pmods.push(new ei(e));break;case"pgen":for(let i=0,s=t.size/Kt.SizeInFile|0;i<s;i++)this.pgens.push(new Kt(e));break;case"inst":for(let i=0,s=t.size/Qt.SizeInFile|0;i<s;i++)this.insts.push(new Qt(e));break;case"ibag":for(let i=0,s=t.size/qt.SizeInFile|0;i<s;i++)this.ibags.push(new qt(e));break;case"imod":for(let i=0,s=t.size/Jt.SizeInFile|0;i<s;i++)this.imods.push(new Jt(e));break;case"igen":for(let i=0,s=t.size/jt.SizeInFile|0;i<s;i++)this.igens.push(new jt(e));break;case"shdr":for(let i=0,s=t.size/ti.SizeInFile|0;i<s;i++)this.sHdrs.push(new ti(e));break;default:e.position+=t.size}else if("sdta"===i.id)for(;Xt.load(i,t,e);)if("smpl"===t.id)this.fontSamples=Yt.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=Qe.int32ToInt16(r[2*t+1]<<8|r[2*t]);s[a+t]=e/32767}i-=e,a+=e}return s}}class qt{constructor(e){this.instGenNdx=$e.readUInt16LE(e),this.instModNdx=$e.readUInt16LE(e)}}qt.SizeInFile=4;class Jt{constructor(e){this.modSrcOper=$e.readUInt16LE(e),this.modDestOper=$e.readUInt16LE(e),this.modAmount=$e.readInt16LE(e),this.modAmtSrcOper=$e.readUInt16LE(e),this.modTransOper=$e.readUInt16LE(e)}}Jt.SizeInFile=10;class jt{constructor(e){this.genOper=$e.readUInt16LE(e),this.genAmount=new ii(e)}}jt.SizeInFile=4;class Qt{constructor(e){this.instName=$e.read8BitStringLength(e,20),this.instBagNdx=$e.readUInt16LE(e)}}Qt.SizeInFile=22;class $t{constructor(e){this.genNdx=$e.readUInt16LE(e),this.modNdx=$e.readUInt16LE(e)}}$t.SizeInFile=4;class Kt{constructor(e){this.genOper=$e.readUInt16LE(e),this.genAmount=new ii(e)}}Kt.SizeInFile=4,Kt.GenInstrument=41,Kt.GenKeyRange=43,Kt.GenVelRange=44,Kt.GenSampleId=53;class Zt{constructor(e){this.presetName=$e.read8BitStringLength(e,20),this.preset=$e.readUInt16LE(e),this.bank=$e.readUInt16LE(e),this.presetBagNdx=$e.readUInt16LE(e),this.library=$e.readUInt32LE(e),this.genre=$e.readUInt32LE(e),this.morphology=$e.readUInt32LE(e)}}Zt.SizeInFile=38;class ei{constructor(e){this.modSrcOper=$e.readUInt16LE(e),this.modDestOper=$e.readUInt16LE(e),this.modAmount=$e.readUInt16LE(e),this.modAmtSrcOper=$e.readUInt16LE(e),this.modTransOper=$e.readUInt16LE(e)}}ei.SizeInFile=10;class ti{constructor(e){this.sampleName=$e.read8BitStringLength(e,20),this.start=$e.readUInt32LE(e),this.end=$e.readUInt32LE(e),this.startLoop=$e.readUInt32LE(e),this.endLoop=$e.readUInt32LE(e),this.sampleRate=$e.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=$e.readSInt8(e),this.sampleLink=$e.readUInt16LE(e),this.sampleType=$e.readUInt16LE(e)}}ti.SizeInFile=46;class ii{get shortAmount(){return Qe.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}constructor(e){this.wordAmount=$e.readUInt16LE(e)}}class si{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 ai{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"}(J||(J={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(j||(j={}));class ri{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null,this.fontSamples=null}}class ni{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 oi{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:ni.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:ni.timecents2Secs(this.attack),this.release=this.release<-11950?0:ni.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:ni.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:ni.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?ni.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"}(Q||(Q={}));class hi{constructor(e){this.loopMode=J.None,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv=new oi,this.modEnv=new oi,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 oi(e.ampEnv),this.modEnv=new oi(e.modEnv),this.initialFilterQ=e.initialFilterQ,this.initialFilterFc=e.initialFilterFc,this.modEnvToPitch=e.modEnvToPitch,this.modEnvToFilterFc=e.modEnvToFilterFc,this.modLfoToFilterFc=e.modLfoToFilterFc,this.modLfoToVolume=e.modLfoToVolume,this.delayModLFO=e.delayModLFO,this.freqModLFO=e.freqModLFO,this.modLfoToPitch=e.modLfoToPitch,this.delayVibLFO=e.delayVibLFO,this.freqVibLFO=e.freqVibLFO,this.vibLfoToPitch=e.vibLfoToPitch)}clear(e){this.loopMode=J.None,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv.clear(),this.modEnv.clear(),this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,this.hiKey=127,this.hiVel=127,this.pitchKeyCenter=60,e||(this.pitchKeyTrack=100,this.pitchKeyCenter=-1,this.ampEnv.delay=-12e3,this.ampEnv.attack=-12e3,this.ampEnv.hold=-12e3,this.ampEnv.decay=-12e3,this.ampEnv.release=-12e3,this.modEnv.delay=-12e3,this.modEnv.attack=-12e3,this.modEnv.hold=-12e3,this.modEnv.decay=-12e3,this.modEnv.release=-12e3,this.initialFilterFc=13500,this.delayModLFO=-12e3,this.delayVibLFO=-12e3)}operator(e,t){switch(e){case Q.StartAddrsOffset:this.offset+=Qe.int16ToUint32(t.shortAmount);break;case Q.EndAddrsOffset:this.end+=Qe.int16ToUint32(t.shortAmount);break;case Q.StartloopAddrsOffset:this.loopStart+=Qe.int16ToUint32(t.shortAmount);break;case Q.EndloopAddrsOffset:this.loopEnd+=Qe.int16ToUint32(t.shortAmount);break;case Q.StartAddrsCoarseOffset:this.offset+=32768*Qe.int16ToUint32(t.shortAmount);break;case Q.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case Q.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case Q.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case Q.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case Q.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case Q.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case Q.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case Q.EndAddrsCoarseOffset:this.end+=32768*Qe.int16ToUint32(t.shortAmount);break;case Q.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case Q.Pan:this.pan=t.shortAmount/1e3;break;case Q.DelayModLFO:this.delayModLFO=t.shortAmount;break;case Q.FreqModLFO:this.freqModLFO=t.shortAmount;break;case Q.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case Q.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case Q.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case Q.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case Q.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case Q.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case Q.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case Q.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case Q.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case Q.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case Q.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case Q.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case Q.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case Q.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case Q.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case Q.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case Q.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case Q.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case Q.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case Q.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case Q.StartloopAddrsCoarseOffset:this.loopStart+=32768*Qe.int16ToUint32(t.shortAmount);break;case Q.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case Q.EndloopAddrsCoarseOffset:this.loopEnd+=32768*Qe.int16ToUint32(t.shortAmount);break;case Q.CoarseTune:this.transpose+=t.shortAmount;break;case Q.FineTune:this.tune+=t.shortAmount;break;case Q.SampleModes:this.loopMode=3==(3&t.wordAmount)?J.Sustain:1==(3&t.wordAmount)?J.Continuous:J.None;break;case Q.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case Q.ExclusiveClass:this.group=t.wordAmount;break;case Q.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"}($||($={}));class li{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=$.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case $.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=$.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=$.Delay;break;case $.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=$.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=$.Attack;break;case $.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=$.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=$.Hold;break;case $.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=$.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=$.Decay;break;case $.Decay:return this.segment=$.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case $.Sustain:if(this.segment=$.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?li.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=$.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,i,s,a){this.parameters=new oi(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:ni.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:ni.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|i,this.isAmpEnv=s,this.nextSegment($.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)}}li.FastReleaseTime=.01;class di{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,i){this.samplesUntil=e*i|0,this.delta=4*ni.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 ci{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 ui{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 li,this.modEnv=new li,this.lowPass=new ci,this.modLfo=new di,this.vibLfo=new di,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/(ni.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment($.Sustain,e),this.modEnv.nextSegment($.Sustain,e),this.region.loopMode===J.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment($.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment($.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===j.StereoUnweaved?s:-1,l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,d=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),c=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,f=r.end,m=g+1,y=this.sourceSamplePosition,b=new ci(this.lowPass),S=0!==r.modLfoToFilterFc||0!==r.modEnvToFilterFc,_=0,w=0,B=0,T=0,k=0!==r.modLfoToPitch||0!==r.modEnvToPitch||0!==r.vibLfoToPitch,v=0,N=0,x=0,P=0,E=0!==r.modLfoToVolume,C=0,F=0;for(S?(_=e.outSampleRate,w=r.initialFilterFc,B=r.modLfoToFilterFc,T=r.modEnvToFilterFc):(_=0,w=0,B=0,T=0),k?(v=0,N=r.modLfoToPitch,x=r.vibLfoToPitch,P=r.modEnvToPitch):(v=ni.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,N=0,x=0,P=0),E?F=.1*r.modLfoToVolume:(C=ni.decibelsToGain(this.noteGainDb),F=0);s>0;){let r,L,M=0,D=s>ui.RenderEffectSampleBlock?ui.RenderEffectSampleBlock:s;if(s-=D,S){let e=w+this.modLfo.level*B+this.modEnv.level*T;b.active=e<=13500,b.active&&b.setup(ni.cents2Hertz(e)/_)}switch(k&&(v=ni.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*N+this.vibLfo.level*x+this.modEnv.level*P))*this.pitchOutputFactor),E&&(C=ni.decibelsToGain(this.noteGainDb+this.modLfo.level*F)),r=C*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(D,e.outSampleRate),l&&this.modEnv.process(D,e.outSampleRate),d&&this.modLfo.process(D),c&&this.vibLfo.process(D),e.outputMode){case j.StereoInterleaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;D-- >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 j.StereoUnweaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;D-- >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 j.Mono:for(;D-- >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===$.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}ui.RenderEffectSampleBlock=Gt.MicroBufferSize;class pi{constructor(){this._items=[],this._position=0,this.isEmpty=!0}clear(){this._items=[],this._position=0,this.isEmpty=!0}enqueue(e){this.isEmpty=!1,this._items.push(e)}peek(){return this._items[this._position]}dequeue(){const e=this._items[this._position];return this._position++,this._position>=this._items.length/2&&(this._items=this._items.slice(this._position),this._position=0),this.isEmpty=0==this._items.length,e}toArray(){const e=this._items.slice(this._position);return e.reverse(),e}}class gi{constructor(e){this._midiEventQueue=new pi,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=j.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._isAnySolo=!1}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(Gt.MetronomeChannel,33),this.channelNoteOn(Gt.MetronomeChannel,33,95/127)):e.event&&this.processMidiMessage(e.event),a.push(e)}for(const a of this._voices)if(-1!==a.playingPreset){const r=a.playingChannel,n=this._mutedChannels.has(r)||s&&r!=Gt.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,i,n):a.kill()}return a}processMidiMessage(e){const t=e.command,i=e.channel,s=e.data1,a=e.data2;switch(t){case z.NoteOff:this.channelNoteOff(i,s);break;case z.NoteOn:this.channelNoteOn(i,s,a/127);break;case z.NoteAftertouch:break;case z.Controller:this.channelMidiControl(i,s,a);break;case z.ProgramChange:this.channelSetPresetNumber(i,s,9===i);break;case z.ChannelAftertouch:break;case z.PitchBend:this.channelSetPitchWheel(i,s|a<<7);break;case z.PerNotePitchBend:const t=e;let r=t.pitch;r=r*Gt.MaxPitchWheel/Gt.MaxPitchWheel20,this.channelSetPerNotePitchWheel(i,t.noteKey,r);break;case z.Meta:switch(e.data1){case U.Tempo:this.currentTempo=6e7/e.value;break;case U.TimeSignature:this.timeSignatureNumerator=e.data[0],this.timeSignatureDenominator=Math.pow(2,e.data[1])}}}get metronomeVolume(){return this.channelGetMixVolume(Gt.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Gt.MetronomeChannel,e),e>0&&(this.channelSetVolume(Gt.MetronomeChannel,1),this.channelSetPresetNumber(Gt.MetronomeChannel,0,!0))}get masterVolume(){return ni.decibelsToGain(this.globalGainDb)}set masterVolume(e){var t=ni.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<$.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);if(this._channels)for(const e of this._channels.channelList)e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.perNotePitchWheel.clear(),e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0}get presetCount(){var e,t;return null!==(t=null===(e=this.presets)||void 0===e?void 0:e.length)&&void 0!==t?t:0}reset(){for(let e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<$.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 ui;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-ni.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!==J.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(ni.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>=$.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>=$.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<$.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 ai);for(let t=this._channels.channelList.length;t<=e;t++){let e=new si;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._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,i))}channelNoteOff(e,t){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>=$.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>=$.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<$.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<$.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=Qe.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=Qe.int32ToUint16(t)}channelSetBankPreset(e,t,i){const s=this.channelInit(e),a=this.getPresetIndex(t,i);return-1!==a&&(s.presetIndex=Qe.int32ToUint16(a),s.bank=Qe.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=ni.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=Qe.int32ToUint16(t),this.channelApplyPitch(e,i))}channelSetPerNotePitchWheel(e,t,i){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 5:case 96:case 97:case 64:case 65:case 66:case 122:case 124:case 125:case 126:case 127:return;case 38:return s.midiData=Qe.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 7:return s.midiVolume=Qe.int32ToUint16(127&s.midiVolume|i<<7),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 39:return s.midiVolume=Qe.int32ToUint16(16256&s.midiVolume|i),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 11:return s.midiExpression=Qe.int32ToUint16(127&s.midiExpression|i<<7),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 43:return s.midiExpression=Qe.int32ToUint16(16256&s.midiExpression|i),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 10:return s.midiPan=Qe.int32ToUint16(127&s.midiPan|i<<7),void this.channelSetPan(e,s.midiPan/16383);case 42:return s.midiPan=Qe.int32ToUint16(16256&s.midiPan|i),void this.channelSetPan(e,s.midiPan/16383);case 6:return s.midiData=Qe.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&&6===t&&this.channelSetTuning(e,i-64+(s.tuning-(0|s.tuning))));case 0:return void(s.bank=Qe.int32ToUint16(32768|i));case 32:return void(s.bank=Qe.int32ToUint16((0!=(32768&s.bank)?(127&s.bank)<<7:0)|i));case 101:return void(s.midiRpn=Qe.int32ToUint16(127&(65535===s.midiRpn?0:s.midiRpn)|i<<7));case 100:return void(s.midiRpn=Qe.int32ToUint16(16256&(65535===s.midiRpn?0:s.midiRpn)|i));case 98:case 99:return void(s.midiRpn=65535);case 120:return void this.channelSoundsOffAll(e);case 123:return void this.channelNoteOffAll(e);case 121: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?ni.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 ri;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!==Kt.GenKeyRange)if(i.genOper!==Kt.GenVelRange){if(i.genOper===Kt.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,d=127;for(let c=e.ibags[o].instGenNdx;c<e.ibags[o+1].instGenNdx;c++){let o=e.igens[c];o.genOper!==Kt.GenKeyRange?o.genOper!==Kt.GenVelRange?53===o.genOper&&h>=t&&i<=s&&d>=a&&l<=r&&n++:(l=o.genAmount.lowByteAmount,d=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 hi;o.clear(!0);for(let i=s.presetBagNdx;i<e.phdrs[t+1].presetBagNdx;i++){const t=e.pbags[i],n=new hi(o);let h=!1;for(let s=t.genNdx;s<e.pbags[i+1].genNdx;s++){const t=e.pgens[s];if(t.genOper===Kt.GenInstrument){let i=t.genAmount.wordAmount;if(i>=e.insts.length)continue;let s=new hi;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 hi(s),l=!1;for(let s=i.instGenNdx;s<e.ibags[t+1].instGenNdx;s++){let t=e.igens[s];if(t.genOper===Kt.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:ni.timecents2Secs(h.delayModLFO),h.delayVibLFO=h.delayVibLFO<-11950?0:ni.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 hi(h),a++,l=!0}else h.operator(t.genOper,t.genAmount)}i!==e.ibags[o.instBagNdx]||l||(s=new hi(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 fi{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 mi{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 yi{constructor(e){this.events=e}}class bi{constructor(e){this.playbackRange=e}}class Si{get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return Be.logLevel}set logLevel(e){Be.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Gt.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Gt.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Gt.MinVolume),this._countInVolume=e}get midiEventsPlayedFilter(){return Array.from(this._midiEventsPlayedFilter)}set midiEventsPlayedFilter(e){this._midiEventsPlayedFilter=new Set(e)}get playbackSpeed(){return this._sequencer.playbackSpeed}set playbackSpeed(e){e=ni.clamp(e,Gt.MinPlaybackSpeed,Gt.MaxPlaybackSpeed);let t=this._sequencer.playbackSpeed;this._sequencer.playbackSpeed=e,this.timePosition=this.timePosition*(t/e)}get tickPosition(){return this._tickPosition}set tickPosition(e){this.timePosition=this._sequencer.mainTickPositionToTimePosition(e)}get timePosition(){return this._timePosition}set timePosition(e){Be.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 bi(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){Be.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 pi,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this.isReady=!1,this.state=q.Paused,this.ready=new fi,this.readyForPlayback=new fi,this.finished=new fi,this.soundFontLoaded=new fi,this.soundFontLoadFailed=new mi,this.midiLoaded=new mi,this.midiLoadFailed=new mi,this.stateChanged=new mi,this.positionChanged=new mi,this.midiEventsPlayed=new mi,this.playbackRangeChanged=new mi,Be.debug("AlphaSynth","Initializing player"),this.state=q.Paused,Be.debug("AlphaSynth","Creating output"),this.output=e,Be.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new gi(this.output.sampleRate),this._sequencer=new Wt(this._synthesizer),Be.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this._sequencer.isFinished){let e=new Float32Array(0);this.output.addSamples(e)}else{let e=new Float32Array(Gt.MicroBufferSize*Gt.MicroBufferCount*Gt.AudioChannels),t=0;for(let i=0;i<Gt.MicroBufferCount;i++){this._sequencer.fillMidiEventQueue();const i=this._synthesizer.synthesize(e,t,Gt.MicroBufferSize);t+=Gt.MicroBufferSize*Gt.AudioChannels;for(const e of i)this._midiEventsPlayedFilter.has(e.event.command)&&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!==q.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(Be.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(Be.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),Be.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.state=q.Playing,this.stateChanged.trigger(new zt(this.state,!1))}pause(){this.state!==q.Paused&&this._isMidiLoaded&&(Be.debug("AlphaSynth","Pausing playback"),this.state=q.Paused,this.stateChanged.trigger(new zt(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===q.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(Be.debug("AlphaSynth","Stopping playback"),this.state=q.Paused,this.output.pause(),this._notPlayedSamples=0,this._sequencer.stop(),this._synthesizer.noteOffAll(!0),this.tickPosition=this._sequencer.mainPlaybackRange?this._sequencer.mainPlaybackRange.startTick:0,this.stateChanged.trigger(new zt(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{Be.debug("AlphaSynth","Loading soundfont from bytes");let e=new Yt;e.load(i),this._synthesizer.loadPresets(e,t),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),Be.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){Be.error("AlphaSynth","Could not load soundfont from bytes "+e),this.soundFontLoadFailed.trigger(e)}}checkReadyForPlayback(){this.isReadyForPlayback&&(this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.readyForPlayback.trigger())}loadMidiFile(e){this.stop();try{Be.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new Ut(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),Be.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){Be.error("AlphaSynth","Could not load midi from model "+e),this.midiLoadFailed.trigger(e)}}setChannelMute(e,t){this._synthesizer.channelSetMute(e,t)}resetChannelStates(){this._synthesizer.resetChannelStates()}setChannelSolo(e,t){this._synthesizer.channelSetSolo(e,t)}setChannelVolume(e,t){t=Math.max(t,Gt.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;let t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*Gt.AudioChannels,this.updateTimePosition(this._timePosition+t,!1),this.checkForFinish()}checkForFinish(){let e=0,t=0;this.playbackRange?(e=this.playbackRange.startTick,t=this.playbackRange.endTick):t=this._sequencer.currentEndTick,this._tickPosition>=t&&this._notPlayedSamples<=0&&(this._notPlayedSamples=0,this._sequencer.isPlayingCountIn?(Be.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(Be.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=q.Paused,this.stopOneTimeMidi()):(Be.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(Be.debug("AlphaSynth",`Position changed: (time: ${i}/${a}, tick: ${s}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new Ut(i,a,s,r,t)),t)this._playedEventsQueue.clear();else{const e=new pi;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<i;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new yi(e.toArray()))}}}class _i{constructor(){this.division=ye.QuarterTime,this.events=[]}addEvent(e){if(0===this.events.length)this.events.push(e);else{let t=this.events.length;for(;t>0;){if(!(this.events[t-1].tick>e.tick))break;t--}this.events.splice(t,0,e)}}toBinary(){let e=Ke.empty();return this.writeTo(e),e.toArray()}writeTo(e){let t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),t=new Uint8Array([0,0,0,6]),e.write(t,0,t.length),t=new Uint8Array([0,0]),e.write(t,0,t.length);let i=1;t=new Uint8Array([i>>8&255,255&i]),e.write(t,0,t.length),i=this.division,t=new Uint8Array([i>>8&255,255&i]),e.write(t,0,t.length);let s=Ke.empty(),a=0;for(let e of this.events){let t=e.tick-a;_i.writeVariableInt(s,t),e.writeTo(s),a=e.tick}t=new Uint8Array([77,84,114,107]),e.write(t,0,t.length);let r=s.toArray(),n=r.length;t=new Uint8Array([n>>24&255,n>>16&255,n>>8&255,255&n]),e.write(t,0,t.length),e.write(r,0,r.length)}static writeVariableInt(e,t){let 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])}}class wi extends It{constructor(e,t,i,s,a){super(e,t,i,s,0),this.data=a}writeTo(e){e.writeByte(255),e.writeByte(this.metaStatus);let t=this.data.length;_i.writeVariableInt(e,t),e.write(this.data,0,this.data.length)}}class Bi extends It{constructor(e,t,i,s,a){super(e,t,i,s,0),this.value=a}writeTo(e){e.writeByte(255),e.writeByte(this.metaStatus),_i.writeVariableInt(e,3);let t=new Uint8Array([this.value>>16&255,this.value>>8&255,255&this.value]);e.write(t,0,t.length)}}class Ti{static parseEnum(e,t){switch(typeof e){case"string":const i=parseInt(e);return isNaN(i)?t[Object.keys(t).find((t=>t.toLowerCase()===e.toLowerCase()))]:i;case"number":return e;case"undefined":case"object":return null}throw new pe(i.Format,`Could not parse enum value '${e}'`)}static forEach(e,t){if(e instanceof Map)e.forEach(t);else if("object"==typeof e)for(const i in e)t(e[i],i)}}class ki{constructor(e,t,i){this.text=e,this.startPos=t,this.endPos=i}}class vi{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 ki(e.substring(i,s),i,s)),i=s+1}return t}parse(){var e;if(this.reset(),1===this._tokens.length)switch(null===(e=this._currentToken)||void 0===e?void 0:e.text){case"caption":case"icon":case"menu":case"message-box":case"small-caption":case"status-bar":case"inherit":return}this.parseOnlyFamilies||(this.fontStyleVariantWeight(),this.fontSizeLineHeight()),this.fontFamily()}static parseFamilies(e){const t=new vi(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"}(K||(K={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(Z||(Z={}));class Ni{reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=vi.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===Z.Bold}get isItalic(){return this.style===K.Italic}constructor(e,t,i=K.Plain,s=Z.Regular){this._cssScale=0,this._families=vi.parseFamilies(e),this._size=t,this._style=i,this._weight=s,this._css=this.toCssString()}static withFamilyList(e,t,i=K.Plain,s=Z.Regular){const a=new Ni("",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=>vi.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=Ti.parseEnum(t.get("style"),K),r=Ti.parseEnum(t.get("weight"),Z);return Ni.withFamilyList(i,s,a,r)}case"string":{const t=new vi(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=K.Plain;"italic"===t.style&&(r=K.Italic);let n=Z.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=Z.Bold}return Ni.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 xi{constructor(){this.copyrightFont=new Ni(xi.sansFont,12,K.Plain,Z.Bold),this.titleFont=new Ni(xi.serifFont,32,K.Plain),this.subTitleFont=new Ni(xi.serifFont,20,K.Plain),this.wordsFont=new Ni(xi.serifFont,15,K.Plain),this.effectFont=new Ni(xi.serifFont,12,K.Italic),this.fretboardNumberFont=new Ni(xi.sansFont,11,K.Plain),this.tablatureFont=new Ni(xi.sansFont,13,K.Plain),this.graceFont=new Ni(xi.sansFont,11,K.Plain),this.staffLineColor=new Ue(165,165,165,255),this.barSeparatorColor=new Ue(34,34,17,255),this.barNumberFont=new Ni(xi.sansFont,11,K.Plain),this.barNumberColor=new Ue(200,0,0,255),this.fingeringFont=new Ni(xi.serifFont,14,K.Plain),this.markerFont=new Ni(xi.serifFont,14,K.Plain,Z.Bold),this.mainGlyphColor=new Ue(0,0,0,255),this.secondaryGlyphColor=new Ue(0,0,0,100),this.scoreInfoColor=new Ue(0,0,0,255)}}xi.sansFont="Arial, sans-serif",xi.serifFont="Georgia, serif";class Pi{constructor(){this.scale=1,this.stretchForce=1,this.layoutMode=e.Page,this.staveProfile=t.Default,this.barsPerRow=-1,this.startBar=1,this.barCount=-1,this.barCountPerPartial=10,this.resources=new xi,this.padding=null}}class Ei{constructor(){this.encoding="utf-8",this.mergePartGroupsInMusicXml=!1,this.beatTextAsLyrics=!1}}!function(e){e[e.Off=0]="Off",e[e.Continuous=1]="Continuous",e[e.OffScreen=2]="OffScreen"}(ee||(ee={}));class Ci{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 Fi{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}class Li{constructor(){this.soundFont=null,this.scrollElement="html,body",this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=ee.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new Ci,this.slide=new Fi,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}class Mi{static fromJson(e,t){t&&Ti.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(e,t,i){switch(t){case"scriptfile":return e.scriptFile=i,!0;case"fontdirectory":return e.fontDirectory=i,!0;case"file":return e.file=i,!0;case"tex":return e.tex=i,!0;case"tracks":return e.tracks=i,!0;case"enablelazyloading":return e.enableLazyLoading=i,!0;case"engine":return e.engine=i,!0;case"loglevel":return e.logLevel=Ti.parseEnum(i,v),!0;case"useworkers":return e.useWorkers=i,!0;case"includenotebounds":return e.includeNoteBounds=i,!0}return!1}}class Di{static fromJson(e,t){t&&Ti.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",Ni.toJson(e.copyrightFont)),t.set("titlefont",Ni.toJson(e.titleFont)),t.set("subtitlefont",Ni.toJson(e.subTitleFont)),t.set("wordsfont",Ni.toJson(e.wordsFont)),t.set("effectfont",Ni.toJson(e.effectFont)),t.set("fretboardnumberfont",Ni.toJson(e.fretboardNumberFont)),t.set("tablaturefont",Ni.toJson(e.tablatureFont)),t.set("gracefont",Ni.toJson(e.graceFont)),t.set("stafflinecolor",Ue.toJson(e.staffLineColor)),t.set("barseparatorcolor",Ue.toJson(e.barSeparatorColor)),t.set("barnumberfont",Ni.toJson(e.barNumberFont)),t.set("barnumbercolor",Ue.toJson(e.barNumberColor)),t.set("fingeringfont",Ni.toJson(e.fingeringFont)),t.set("markerfont",Ni.toJson(e.markerFont)),t.set("mainglyphcolor",Ue.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",Ue.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",Ue.toJson(e.scoreInfoColor)),t}static setProperty(e,t,i){switch(t){case"copyrightfont":return e.copyrightFont=Ni.fromJson(i),!0;case"titlefont":return e.titleFont=Ni.fromJson(i),!0;case"subtitlefont":return e.subTitleFont=Ni.fromJson(i),!0;case"wordsfont":return e.wordsFont=Ni.fromJson(i),!0;case"effectfont":return e.effectFont=Ni.fromJson(i),!0;case"fretboardnumberfont":return e.fretboardNumberFont=Ni.fromJson(i),!0;case"tablaturefont":return e.tablatureFont=Ni.fromJson(i),!0;case"gracefont":return e.graceFont=Ni.fromJson(i),!0;case"stafflinecolor":return e.staffLineColor=Ue.fromJson(i),!0;case"barseparatorcolor":return e.barSeparatorColor=Ue.fromJson(i),!0;case"barnumberfont":return e.barNumberFont=Ni.fromJson(i),!0;case"barnumbercolor":return e.barNumberColor=Ue.fromJson(i),!0;case"fingeringfont":return e.fingeringFont=Ni.fromJson(i),!0;case"markerfont":return e.markerFont=Ni.fromJson(i),!0;case"mainglyphcolor":return e.mainGlyphColor=Ue.fromJson(i),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=Ue.fromJson(i),!0;case"scoreinfocolor":return e.scoreInfoColor=Ue.fromJson(i),!0}return!1}}class Ii{static fromJson(e,t){t&&Ti.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("resources",Di.toJson(e.resources)),t.set("padding",e.padding),t}static setProperty(i,s,a){switch(s){case"scale":return i.scale=a,!0;case"stretchforce":return i.stretchForce=a,!0;case"layoutmode":return i.layoutMode=Ti.parseEnum(a,e),!0;case"staveprofile":return i.staveProfile=Ti.parseEnum(a,t),!0;case"barsperrow":return i.barsPerRow=a,!0;case"startbar":return i.startBar=a,!0;case"barcount":return i.barCount=a,!0;case"barcountperpartial":return i.barCountPerPartial=a,!0;case"padding":return i.padding=a,!0}if(["resources"].indexOf(s)>=0)return Di.fromJson(i.resources,a),!0;for(const e of["resources"])if(0===s.indexOf(e)&&Di.setProperty(i.resources,s.substring(e.length),a))return!0;return!1}}class Ri{static fromJson(e,t){t&&Ti.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(e,t,i){switch(t){case"notationmode":return e.notationMode=Ti.parseEnum(i,T),!0;case"fingeringmode":return e.fingeringMode=Ti.parseEnum(i,B),!0;case"elements":return e.elements=new Map,Ti.forEach(i,((t,i)=>{e.elements.set(Ti.parseEnum(i,k),t)})),!0;case"rhythmmode":return e.rhythmMode=Ti.parseEnum(i,w),!0;case"rhythmheight":return e.rhythmHeight=i,!0;case"transpositionpitches":return e.transpositionPitches=i,!0;case"displaytranspositionpitches":return e.displayTranspositionPitches=i,!0;case"smallgracetabnotes":return e.smallGraceTabNotes=i,!0;case"extendbendarrowsontiednotes":return e.extendBendArrowsOnTiedNotes=i,!0;case"extendlineeffectstobeatend":return e.extendLineEffectsToBeatEnd=i,!0;case"slurheight":return e.slurHeight=i,!0}return!1}}class Ai{static fromJson(e,t){t&&Ti.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 Oi{static fromJson(e,t){t&&Ti.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 Gi{static fromJson(e,t){t&&Ti.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 Vi{static fromJson(e,t){t&&Ti.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("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",Oi.toJson(e.vibrato)),t.set("slide",Gi.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t.set("buffertimeinmilliseconds",e.bufferTimeInMilliseconds),t}static setProperty(e,t,i){switch(t){case"soundfont":return e.soundFont=i,!0;case"scrollelement":return e.scrollElement=i,!0;case"enableplayer":return e.enablePlayer=i,!0;case"enablecursor":return e.enableCursor=i,!0;case"enableanimatedbeatcursor":return e.enableAnimatedBeatCursor=i,!0;case"enableelementhighlighting":return e.enableElementHighlighting=i,!0;case"enableuserinteraction":return e.enableUserInteraction=i,!0;case"scrolloffsetx":return e.scrollOffsetX=i,!0;case"scrolloffsety":return e.scrollOffsetY=i,!0;case"scrollmode":return e.scrollMode=Ti.parseEnum(i,ee),!0;case"scrollspeed":return e.scrollSpeed=i,!0;case"nativebrowsersmoothscroll":return e.nativeBrowserSmoothScroll=i,!0;case"songbookbendduration":return e.songBookBendDuration=i,!0;case"songbookdipduration":return e.songBookDipDuration=i,!0;case"playtripletfeel":return e.playTripletFeel=i,!0;case"buffertimeinmilliseconds":return e.bufferTimeInMilliseconds=i,!0}if(["vibrato"].indexOf(t)>=0)return Oi.fromJson(e.vibrato,i),!0;for(const s of["vibrato"])if(0===t.indexOf(s)&&Oi.setProperty(e.vibrato,t.substring(s.length),i))return!0;if(["slide"].indexOf(t)>=0)return Gi.fromJson(e.slide,i),!0;for(const s of["slide"])if(0===t.indexOf(s)&&Gi.setProperty(e.slide,t.substring(s.length),i))return!0;return!1}}class Hi{static fromJson(e,t){t&&Ti.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",Mi.toJson(e.core)),t.set("display",Ii.toJson(e.display)),t.set("notation",Ri.toJson(e.notation)),t.set("importer",Ai.toJson(e.importer)),t.set("player",Vi.toJson(e.player)),t}static setProperty(e,t,i){if(["core",""].indexOf(t)>=0)return Mi.fromJson(e.core,i),!0;for(const s of["core",""])if(0===t.indexOf(s)&&Mi.setProperty(e.core,t.substring(s.length),i))return!0;if(["display",""].indexOf(t)>=0)return Ii.fromJson(e.display,i),!0;for(const s of["display",""])if(0===t.indexOf(s)&&Ii.setProperty(e.display,t.substring(s.length),i))return!0;if(["notation"].indexOf(t)>=0)return Ri.fromJson(e.notation,i),!0;for(const s of["notation"])if(0===t.indexOf(s)&&Ri.setProperty(e.notation,t.substring(s.length),i))return!0;if(["importer"].indexOf(t)>=0)return Ai.fromJson(e.importer,i),!0;for(const s of["importer"])if(0===t.indexOf(s)&&Ai.setProperty(e.importer,t.substring(s.length),i))return!0;if(["player"].indexOf(t)>=0)return Vi.fromJson(e.player,i),!0;for(const s of["player"])if(0===t.indexOf(s)&&Vi.setProperty(e.player,t.substring(s.length),i))return!0;return!1}}class Wi{constructor(){this.core=new fo,this.display=new Pi,this.notation=new Se,this.importer=new Ei,this.player=new Li}setSongBookModeSettings(){this.notation.notationMode=T.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=B.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(k.ParenthesisOnTiedBends,!1),this.notation.elements.set(k.TabNotesOnTiedBends,!1),this.notation.elements.set(k.ZerosOnDiveWhammys,!0)}static get songBook(){let e=new Wi;return e.setSongBookModeSettings(),e}fillFromJson(e){Hi.fromJson(this,e)}}class zi extends Dt{constructor(e,t,i,s,a){super(e,t,i,0,0),this.noteKey=s,this.pitch=a}writeTo(e){let t=new Uint8Array([64,255&this.message,255&this.noteKey,0,this.pitch>>24&255,this.pitch>>16&255,this.pitch>>8&255,255&this.pitch]);e.write(t,0,t.length)}}class Ui{static fromJson(e,t){t&&Ti.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 Xi{static fromJson(e,t){t&&Ti.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=Ti.parseEnum(i,a),!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 Yi{static fromJson(e,t){t&&Ti.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=Ti.parseEnum(i,O),!0;case"length":return e.length=i,!0}return!1}}class qi{static fromJson(e,t){t&&Ti.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",Ui.toJson(e.section)),t.set("tempoautomation",Xi.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(),Yi.toJson(s))}return t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t}static setProperty(e,t,i){switch(t){case"alternateendings":return e.alternateEndings=i,!0;case"keysignature":return e.keySignature=Ti.parseEnum(i,L),!0;case"keysignaturetype":return e.keySignatureType=Ti.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=Ti.parseEnum(i,I),!0;case"fermata":return e.fermata=new Map,Ti.forEach(i,((t,i)=>{const s=new nt;Yi.fromJson(s,t),e.addFermata(parseInt(i),s)})),!0;case"start":return e.start=i,!0;case"isanacrusis":return e.isAnacrusis=i,!0}return["section"].indexOf(t)>=0?(i?(e.section=new We,Ui.fromJson(e.section,i)):e.section=null,!0):["tempoautomation"].indexOf(t)>=0&&(i?(e.tempoAutomation=new fe,Xi.fromJson(e.tempoAutomation,i)):e.tempoAutomation=null,!0)}}class Ji{static fromJson(e,t){t&&Ti.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 ji{static fromJson(e,t){t&&Ti.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){var t;if(!e)return null;const i=new Map;return i.set("id",e.id),i.set("accentuated",e.accentuated),i.set("bendtype",e.bendType),i.set("bendstyle",e.bendStyle),i.set("iscontinuedbend",e.isContinuedBend),null!==e.bendPoints&&i.set("bendpoints",null===(t=e.bendPoints)||void 0===t?void 0:t.map((e=>Ji.toJson(e)))),i.set("fret",e.fret),i.set("string",e.string),i.set("octave",e.octave),i.set("tone",e.tone),i.set("percussionarticulation",e.percussionArticulation),i.set("isvisible",e.isVisible),i.set("islefthandtapped",e.isLeftHandTapped),i.set("ishammerpullorigin",e.isHammerPullOrigin),i.set("isslurdestination",e.isSlurDestination),i.set("harmonictype",e.harmonicType),i.set("harmonicvalue",e.harmonicValue),i.set("isghost",e.isGhost),i.set("isletring",e.isLetRing),i.set("ispalmmute",e.isPalmMute),i.set("isdead",e.isDead),i.set("isstaccato",e.isStaccato),i.set("slideintype",e.slideInType),i.set("slideouttype",e.slideOutType),i.set("vibrato",e.vibrato),i.set("istiedestination",e.isTieDestination),i.set("lefthandfinger",e.leftHandFinger),i.set("righthandfinger",e.rightHandFinger),i.set("isfingering",e.isFingering),i.set("trillvalue",e.trillValue),i.set("trillspeed",e.trillSpeed),i.set("durationpercent",e.durationPercent),i.set("accidentalmode",e.accidentalMode),i.set("dynamics",e.dynamics),e.toJson(i),i}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"accentuated":return e.accentuated=Ti.parseEnum(i,s),!0;case"bendtype":return e.bendType=Ti.parseEnum(i,l),!0;case"bendstyle":return e.bendStyle=Ti.parseEnum(i,h),!0;case"iscontinuedbend":return e.isContinuedBend=i,!0;case"bendpoints":if(i){e.bendPoints=[];for(const t of i){const i=new be;Ji.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=Ti.parseEnum(i,m),!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=Ti.parseEnum(i,b),!0;case"slideouttype":return e.slideOutType=Ti.parseEnum(i,S),!0;case"vibrato":return e.vibrato=Ti.parseEnum(i,_),!0;case"istiedestination":return e.isTieDestination=i,!0;case"lefthandfinger":return e.leftHandFinger=Ti.parseEnum(i,f),!0;case"righthandfinger":return e.rightHandFinger=Ti.parseEnum(i,f),!0;case"isfingering":return e.isFingering=i,!0;case"trillvalue":return e.trillValue=i,!0;case"trillspeed":return e.trillSpeed=Ti.parseEnum(i,u),!0;case"durationpercent":return e.durationPercent=i,!0;case"accidentalmode":return e.accidentalMode=Ti.parseEnum(i,y),!0;case"dynamics":return e.dynamics=Ti.parseEnum(i,p),!0}return e.setProperty(t,i)}}class Qi{static fromJson(e,t){t&&Ti.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){var t;if(!e)return null;const i=new Map;return i.set("id",e.id),i.set("notes",e.notes.map((e=>ji.toJson(e)))),i.set("isempty",e.isEmpty),i.set("whammystyle",e.whammyStyle),i.set("ottava",e.ottava),i.set("islegatoorigin",e.isLegatoOrigin),i.set("duration",e.duration),i.set("automations",e.automations.map((e=>Xi.toJson(e)))),i.set("dots",e.dots),i.set("fadein",e.fadeIn),i.set("lyrics",e.lyrics),i.set("hasrasgueado",e.hasRasgueado),i.set("pop",e.pop),i.set("slap",e.slap),i.set("tap",e.tap),i.set("text",e.text),i.set("brushtype",e.brushType),i.set("brushduration",e.brushDuration),i.set("tupletdenominator",e.tupletDenominator),i.set("tupletnumerator",e.tupletNumerator),i.set("iscontinuedwhammy",e.isContinuedWhammy),i.set("whammybartype",e.whammyBarType),null!==e.whammyBarPoints&&i.set("whammybarpoints",null===(t=e.whammyBarPoints)||void 0===t?void 0:t.map((e=>Ji.toJson(e)))),i.set("vibrato",e.vibrato),i.set("chordid",e.chordId),i.set("gracetype",e.graceType),i.set("pickstroke",e.pickStroke),i.set("tremolospeed",e.tremoloSpeed),i.set("crescendo",e.crescendo),i.set("displaystart",e.displayStart),i.set("playbackstart",e.playbackStart),i.set("displayduration",e.displayDuration),i.set("playbackduration",e.playbackDuration),i.set("dynamics",e.dynamics),i.set("invertbeamdirection",e.invertBeamDirection),i.set("preferredbeamdirection",e.preferredBeamDirection),i.set("beamingmode",e.beamingMode),i}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 Pe;ji.fromJson(i,t),e.addNote(i)}return!0;case"isempty":return e.isEmpty=i,!0;case"whammystyle":return e.whammyStyle=Ti.parseEnum(i,h),!0;case"ottava":return e.ottava=Ti.parseEnum(i,n),!0;case"islegatoorigin":return e.isLegatoOrigin=i,!0;case"duration":return e.duration=Ti.parseEnum(i,u),!0;case"automations":e.automations=[];for(const t of i){const i=new fe;Xi.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=Ti.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=Ti.parseEnum(i,C),!0;case"whammybarpoints":if(i){e.whammyBarPoints=[];for(const t of i){const i=new be;Ji.fromJson(i,t),e.addWhammyBarPoint(i)}}return!0;case"vibrato":return e.vibrato=Ti.parseEnum(i,_),!0;case"chordid":return e.chordId=i,!0;case"gracetype":return e.graceType=Ti.parseEnum(i,g),!0;case"pickstroke":return e.pickStroke=Ti.parseEnum(i,N),!0;case"tremolospeed":return e.tremoloSpeed=Ti.parseEnum(i,u),!0;case"crescendo":return e.crescendo=Ti.parseEnum(i,c),!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=Ti.parseEnum(i,p),!0;case"invertbeamdirection":return e.invertBeamDirection=i,!0;case"preferredbeamdirection":return e.preferredBeamDirection=Ti.parseEnum(i,H),!0;case"beamingmode":return e.beamingMode=Ti.parseEnum(i,F),!0}return!1}}class $i{static fromJson(e,t){t&&Ti.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=>Qi.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 Ie;Qi.fromJson(i,t),e.addBeat(i)}return!0;case"isempty":return e.isEmpty=i,!0}return!1}}class Ki{static fromJson(e,t){t&&Ti.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=>$i.toJson(e)))),t.set("similemark",e.simileMark),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"clef":return e.clef=Ti.parseEnum(i,r),!0;case"clefottava":return e.clefOttava=Ti.parseEnum(i,n),!0;case"voices":e.voices=[];for(const t of i){const i=new je;$i.fromJson(i,t),e.addVoice(i)}return!0;case"similemark":return e.simileMark=Ti.parseEnum(i,o),!0}return!1}}class Zi{static fromJson(e,t){t&&Ti.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 es{static fromJson(e,t){t&&Ti.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 ts{static fromJson(e,t){t&&Ti.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=>Ki.toJson(e)))),null!==e.chords){const i=new Map;t.set("chords",i);for(const[t,s]of e.chords)i.set(t.toString(),Zi.toJson(s))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",es.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 me;Ki.fromJson(i,t),e.addBar(i)}return!0;case"chords":return e.chords=new Map,Ti.forEach(i,((t,i)=>{const s=new Re;Zi.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&&(es.fromJson(e.stringTuning,i),!0)}}class is{static fromJson(e,t){t&&Ti.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 ss{static fromJson(e,t){t&&Ti.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=Ti.parseEnum(i,x),!0;case"noteheadhalf":return e.noteHeadHalf=Ti.parseEnum(i,x),!0;case"noteheadwhole":return e.noteHeadWhole=Ti.parseEnum(i,x),!0;case"techniquesymbol":return e.techniqueSymbol=Ti.parseEnum(i,x),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=Ti.parseEnum(i,E),!0;case"outputmidinumber":return e.outputMidiNumber=i,!0}return!1}}class as{static fromJson(e,t){t&&Ti.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=>ts.toJson(e)))),t.set("playbackinfo",is.toJson(e.playbackInfo)),t.set("color",Ue.toJson(e.color)),t.set("name",e.name),t.set("shortname",e.shortName),t.set("percussionarticulations",e.percussionArticulations.map((e=>ss.toJson(e)))),t}static setProperty(e,t,i){switch(t){case"staves":e.staves=[];for(const t of i){const i=new qe;ts.fromJson(i,t),e.addStaff(i)}return!0;case"color":return e.color=Ue.fromJson(i),!0;case"name":return e.name=i,!0;case"shortname":return e.shortName=i,!0;case"percussionarticulations":e.percussionArticulations=[];for(const t of i){const i=new ve;ss.fromJson(i,t),e.percussionArticulations.push(i)}return!0}return["playbackinfo"].indexOf(t)>=0&&(is.fromJson(e.playbackInfo,i),!0)}}class rs{static fromJson(e,t){t&&Ti.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 ns{static fromJson(e,t){t&&Ti.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=>qi.toJson(e)))),t.set("tracks",e.tracks.map((e=>as.toJson(e)))),t.set("stylesheet",rs.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 Oe;qi.fromJson(i,t),e.addMasterBar(i)}return!0;case"tracks":e.tracks=[];for(const t of i){const i=new Je;as.fromJson(i,t),e.addTrack(i)}return!0}return["stylesheet"].indexOf(t)>=0&&(rs.fromJson(e.stylesheet,i),!0)}}class os{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=os.scoreToJsObject(e);return JSON.stringify(t,os.jsonReplacer)}static jsonToScore(e,t){return os.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return ns.toJson(e)}static jsObjectToScore(e,t){let i=new He;return ns.fromJson(i,e),i.finish(null!=t?t:new Wi),i}static settingsToJson(e){let t=os.settingsToJsObject(e);return JSON.stringify(t,os.jsonReplacer)}static jsonToSettings(e){return os.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return Hi.toJson(e)}static jsObjectToSettings(e){let t=new Wi;return Hi.fromJson(t,e),t}static jsObjectToMidiFile(e){let t=new _i;t.division=e.division;let i=e.events;for(let e of i){let i=os.jsObjectToMidiEvent(e);t.events.push(i)}return t}static jsObjectToMidiEvent(e){let t,i=e.track,s=e.tick,a=e.message;switch(e.type){case"SystemExclusiveEvent":t=new At(i,s,0,0,e.data),t.message=a;break;case"MetaDataEvent":t=new wi(i,s,0,0,e.data),t.message=a;break;case"MetaNumberEvent":t=new Bi(i,s,0,0,e.value),t.message=a;break;case"Midi20PerNotePitchBendEvent":t=new zi(i,s,0,e.noteKey,e.pitch),t.message=a;break;default:t=new Dt(i,s,0,0,0),t.message=a}return t}static midiFileToJsObject(e){let t={};t.division=e.division;let i=[];t.events=i;for(let t of e.events)i.push(os.midiEventToJsObject(t));return t}static midiEventToJsObject(e){let t={};return t.track=e.track,t.tick=e.tick,t.message=e.message,e instanceof At?(t.type="SystemExclusiveEvent",t.data=e.data):e instanceof wi?(t.type="MetaDataEvent",t.data=e.data):e instanceof Bi?(t.type="MetaNumberEvent",t.value=e.value):e instanceof zi&&(t.type="Midi20PerNotePitchBendEvent",t.noteKey=e.noteKey,t.pitch=e.pitch),t}}class hs{constructor(){this.ready=new fi,this.samplesPlayed=new mi,this.sampleRequest=new fi}get sampleRate(){return hs.preferredSampleRate}open(){Be.debug("AlphaSynth","Initializing webworker worker"),this._worker=go.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 hs.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case hs.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(){}}hs.CmdOutputPrefix="alphaSynth.output.",hs.CmdOutputAddSamples=hs.CmdOutputPrefix+"addSamples",hs.CmdOutputPlay=hs.CmdOutputPrefix+"play",hs.CmdOutputPause=hs.CmdOutputPrefix+"pause",hs.CmdOutputResetSamples=hs.CmdOutputPrefix+"resetSamples",hs.CmdOutputSampleRequest=hs.CmdOutputPrefix+"sampleRequest",hs.CmdOutputSamplesPlayed=hs.CmdOutputPrefix+"samplesPlayed",hs.preferredSampleRate=0;class ls{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new Si(new hs,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=go.globalThis;e.addEventListener("message",(t=>{let i=t.data;if("alphaSynth.initialize"===i.cmd)hs.preferredSampleRate=i.sampleRate,Be.logLevel=i.logLevel,go.globalThis.alphaSynthWebWorker=new ls(e,i.bufferTimeInMilliseconds)}))}handleMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":Be.logLevel=t.value;break;case"alphaSynth.setMasterVolume":this._player.masterVolume=t.value;break;case"alphaSynth.setMetronomeVolume":this._player.metronomeVolume=t.value;break;case"alphaSynth.setPlaybackSpeed":this._player.playbackSpeed=t.value;break;case"alphaSynth.setTickPosition":this._player.tickPosition=t.value;break;case"alphaSynth.setTimePosition":this._player.timePosition=t.value;break;case"alphaSynth.setPlaybackRange":this._player.playbackRange=t.value;break;case"alphaSynth.setIsLooping":this._player.isLooping=t.value;break;case"alphaSynth.setCountInVolume":this._player.countInVolume=t.value;break;case"alphaSynth.setMidiEventsPlayedFilter":this._player.midiEventsPlayedFilter=t.value;break;case"alphaSynth.play":this._player.play();break;case"alphaSynth.pause":this._player.pause();break;case"alphaSynth.playPause":this._player.playPause();break;case"alphaSynth.stop":this._player.stop();break;case"alphaSynth.playOneTimeMidiFile":this._player.playOneTimeMidiFile(os.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(os.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);break;case"alphaSynth.setChannelSolo":this._player.setChannelSolo(t.channel,t.solo);break;case"alphaSynth.setChannelVolume":this._player.setChannelVolume(t.channel,t.volume);break;case"alphaSynth.resetChannelStates":this._player.resetChannelStates();break;case"alphaSynth.destroy":this._player.destroy(),this._main.postMessage({cmd:"alphaSynth.destroyed"})}}onPositionChanged(e){this._main.postMessage({cmd:"alphaSynth.positionChanged",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onPlayerStateChanged(e){this._main.postMessage({cmd:"alphaSynth.playerStateChanged",state:e.state,stopped:e.stopped})}onFinished(){this._main.postMessage({cmd:"alphaSynth.finished"})}onSoundFontLoaded(){this._main.postMessage({cmd:"alphaSynth.soundFontLoaded"})}onSoundFontLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.soundFontLoadFailed",error:this.serializeException(e)})}serializeException(e){let t=JSON.parse(JSON.stringify(e));return e.message&&(t.message=e.message),e.stack&&(t.stack=e.stack),e.constructor&&e.constructor.name&&(t.type=e.constructor.name),t}onMidiLoaded(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onMidiLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",error:this.serializeException(e)})}onReadyForPlayback(){this._main.postMessage({cmd:"alphaSynth.readyForPlayback"})}onMidiEventsPlayed(e){this._main.postMessage({cmd:"alphaSynth.midiEventsPlayed",events:e.events.map(os.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}class ds{static generateFontLookup(e){if(!ds.FontSizeLookupTables.has(e))if(go.isRunningInWorker)ds.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);ds.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(ds.FontSizeLookupTables.has(t[e])){n=t[e];break}ds.FontSizeLookupTables.has(n)||ds.generateFontLookup(n),r=ds.FontSizeLookupTables.get(n);let o=1;s===K.Italic&&(o*=1.2),a===Z.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}}ds.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]),ds.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]),ds.FontSizeLookupTables=new Map([["Arial",ds.Arial],["'Arial'",ds.Arial],['"Arial"',ds.Arial],["Georgia",ds.Georgia],["'Georgia'",ds.Georgia],['"Georgia"',ds.Georgia]]),ds.ControlChars=32;class cs{constructor(){this.id=ke.newGuid(),this.x=0,this.y=0,this.width=0,this.height=0,this.totalWidth=0,this.totalHeight=0,this.firstMasterBarIndex=-1,this.lastMasterBarIndex=-1,this.renderResult=null}}class us{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 ps{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 gs{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 fs{}class ms{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 ys{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 ys,s=e.staveGroups;for(let e of s){let s=new ms;s.visualBounds=e.visualBounds,s.realBounds=e.realBounds,i.addStaveGroup(s);for(let i of e.bars){let e=new gs;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 us;i.visualBounds=s.visualBounds,i.realBounds=s.realBounds,e.addBar(i);for(let e of s.beats){let s=new ps;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 fs,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){var t;this._beatLookup.has(e.beat.id)||this._beatLookup.set(e.beat.id,[]),null===(t=this._beatLookup.get(e.beat.id))||void 0===t||t.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 bs{constructor(t){this._currentLayoutMode=e.Page,this._currentRenderEngine=null,this._renderedTracks=null,this.canvas=null,this.score=null,this.tracks=null,this.layout=null,this.boundsLookup=null,this.width=0,this.preRender=new mi,this.renderFinished=new mi,this.partialRenderFinished=new mi,this.partialLayoutFinished=new mi,this.postRenderFinished=new fi,this.error=new mi,this.settings=t,this.recreateCanvas(),this.recreateLayout()}destroy(){this.score=null,this.canvas=null,this.layout=null,this.boundsLookup=null,this.tracks=null}recreateCanvas(){return this._currentRenderEngine!==this.settings.core.engine&&(this.canvas=go.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=go.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?(Be.debug("Rendering","Request render of lazy partial "+e),t.renderLazyPartial(e)):Be.warning("Rendering","Request render of lazy partial "+e+" ignored, no layout exists")}catch(e){this.error.trigger(e)}}render(){if(0!==this.width)if(this.boundsLookup=new ys,this.recreateCanvas(),this.canvas.lineWidth=this.settings.display.scale,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){Be.debug("Rendering","Rendering "+this.tracks.length+" tracks");for(let e=0;e<this.tracks.length;e++){let t=this.tracks[e];Be.debug("Rendering","Track "+e+": "+t.name)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),Be.debug("Rendering","Rendering finished")}else Be.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),Be.debug("Rendering","Clearing finished");else Be.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(Be.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(Be.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new ys,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):Be.debug("Rendering","Current layout does not support dynamic resizing, nothing was done",null),Be.debug("Rendering","Resize finished")}layoutAndRender(){Be.debug("Rendering","Rendering at scale "+this.settings.display.scale+" with layout "+this.layout.name,null),this.layout.layoutAndRender(),this._renderedTracks=this.tracks,this.onRenderFinished(),this.postRenderFinished.trigger()}onRenderFinished(){var e;null===(e=this.boundsLookup)||void 0===e||e.finish();const t=new cs;t.totalHeight=this.layout.height,t.totalWidth=this.layout.width,t.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(t)}}class Ss{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){go.globalThis.alphaTabWebWorker=new Ss(go.globalThis)}handleMessage(e){let t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":let e=os.jsObjectToSettings(t.settings);Be.logLevel=e.core.logLevel,this._renderer=new bs(e),this._renderer.partialRenderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialRenderFinished",result:e})})),this._renderer.partialLayoutFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialLayoutFinished",result:e})})),this._renderer.renderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.renderFinished",result:e})})),this._renderer.postRenderFinished.on((()=>{var e,t;this._main.postMessage({cmd:"alphaTab.postRenderFinished",boundsLookup:null!==(t=null===(e=this._renderer.boundsLookup)||void 0===e?void 0:e.toJson())&&void 0!==t?t:null})})),this._renderer.preRender.on((e=>{this._main.postMessage({cmd:"alphaTab.preRender",resize:e})})),this._renderer.error.on(this.error.bind(this));break;case"alphaTab.invalidate":this._renderer.render();break;case"alphaTab.resizeRender":this._renderer.resizeRender();break;case"alphaTab.renderResult":this._renderer.renderResult(t.resultId);break;case"alphaTab.setWidth":this._renderer.width=t.width;break;case"alphaTab.renderScore":this.updateFontSizes(t.fontSizes);let i=null==t.score?null:os.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(i,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(e){ds.FontSizeLookupTables||(ds.FontSizeLookupTables=new Map);for(let t in e)ds.FontSizeLookupTables.set(t,e[t])}}updateSettings(e){Hi.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){Be.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class _s{constructor(){this._canvas=null,this._color=new Ue(0,0,0,255),this._font=new Ni("Arial",10,K.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 Ni(i,parseFloat(t.fontSize),K.Plain),this._measureCanvas=document.createElement("canvas"),this._measureCanvas.width=10,this._measureCanvas.height=10,this._measureCanvas.style.width="10px",this._measureCanvas.style.height="10px",this._measureContext=this._measureCanvas.getContext("2d"),this._measureContext.textBaseline="hanging"}onRenderFinished(){return null}beginRender(e,t){this._canvas=document.createElement("canvas"),this._canvas.width=e*go.HighDpiFactor|0,this._canvas.height=t*go.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(go.HighDpiFactor,go.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 P.Left;case"center":return P.Center;case"right":return P.Right}}set textAlign(e){switch(e){case P.Left:this._context.textAlign="left";break;case P.Center:this._context.textAlign="center";break;case P.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return E.Top;case"middle":return E.Middle;case"bottom":return E.Bottom}}set textBaseline(e){switch(e){case E.Top:this._context.textBaseline="hanging";break;case E.Middle:this._context.textBaseline="middle";break;case E.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,i){this._context.fillText(e,t,i)}measureText(e){return this._measureContext.measureText(e).width}fillMusicFontSymbol(e,t,i,s,a=!1){s!==x.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!==x.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 ws{constructor(e){this._midiFile=e}addTimeSignature(e,t,i){let s=0;for(;(i>>=1)>0;)s++;const a=new wi(0,e,255,U.TimeSignature,new Uint8Array([255&t,255&s,48,8]));this._midiFile.addEvent(a)}addRest(e,t,i){const s=new At(e,t,X.SystemExclusive,At.AlphaTabManufacturerId,new Uint8Array([Y.Rest]));this._midiFile.addEvent(s)}addNote(e,t,i,s,a,r){const n=ye.dynamicToVelocity(a),o=new Dt(e,t,this.makeCommand(z.NoteOn,r),ws.fixValue(s),ws.fixValue(n));this._midiFile.addEvent(o);const h=new Dt(e,t+i,this.makeCommand(z.NoteOff,r),ws.fixValue(s),ws.fixValue(n));this._midiFile.addEvent(h)}makeCommand(e,t){return 240&e|15&t}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,i,s,a){const r=new Dt(e,t,this.makeCommand(z.Controller,i),ws.fixValue(s),ws.fixValue(a));this._midiFile.addEvent(r)}addProgramChange(e,t,i,s){const a=new Dt(e,t,this.makeCommand(z.ProgramChange,i),ws.fixValue(s),0);this._midiFile.addEvent(a)}addTempo(e,t){const i=6e7/t|0,s=new Bi(0,e,255,U.Tempo,i);this._midiFile.addEvent(s)}addBend(e,t,i,s){s=s>=Gt.MaxPitchWheel?Gt.MaxPitchWheel:Math.floor(s);const a=new Dt(e,t,this.makeCommand(z.PitchBend,i),127&s,s>>7&127);this._midiFile.addEvent(a)}addNoteBend(e,t,i,s,a){a=(a=a>=Gt.MaxPitchWheel?Gt.MaxPitchWheel:Math.floor(a))*Gt.MaxPitchWheel20/Gt.MaxPitchWheel;const r=new zi(e,t,this.makeCommand(z.PerNotePitchBend,i),s,a);this._midiFile.addEvent(r)}finishTrack(e,t){const i=new wi(e,t,255,U.EndOfTrack,new Uint8Array(0));this._midiFile.addEvent(i)}}class Bs{constructor(){this._highlightedBeats=new Map,this.index=0,this.start=0,this.end=0,this.isEmptyBar=!1,this.beatsToHighlight=[]}highlightBeat(e){this._highlightedBeats.has(e.id)||(this._highlightedBeats.set(e.id,!0),this.beatsToHighlight.push(e))}}!function(e){e[e.BankSelectCoarse=0]="BankSelectCoarse",e[e.ModulationCoarse=1]="ModulationCoarse",e[e.DataEntryCoarse=6]="DataEntryCoarse",e[e.VolumeCoarse=7]="VolumeCoarse",e[e.PanCoarse=10]="PanCoarse",e[e.ExpressionControllerCoarse=11]="ExpressionControllerCoarse",e[e.ModulationFine=33]="ModulationFine",e[e.DataEntryFine=38]="DataEntryFine",e[e.VolumeFine=39]="VolumeFine",e[e.PanFine=42]="PanFine",e[e.ExpressionControllerFine=43]="ExpressionControllerFine",e[e.HoldPedal=64]="HoldPedal",e[e.LegatoPedal=68]="LegatoPedal",e[e.NonRegisteredParameterFine=98]="NonRegisteredParameterFine",e[e.NonRegisteredParameterCourse=99]="NonRegisteredParameterCourse",e[e.RegisteredParameterFine=100]="RegisteredParameterFine",e[e.RegisteredParameterCourse=101]="RegisteredParameterCourse",e[e.ResetControllers=121]="ResetControllers",e[e.AllNotesOff=123]="AllNotesOff"}(te||(te={}));class Ts{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 ks{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 Ts(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=0!=(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 vs{constructor(){this.start=0,this.end=0,this.tempo=0,this.beats=[],this.nextMasterBar=null}finish(){this.beats.sort(((e,t)=>e.start-t.start))}addBeat(e){e.masterBar=this,e.index=this.beats.length,this.beats.push(e)}}class Ns{constructor(){this.duration=0,this.tickDuration=0,this.nextBeatLookup=null}get currentBeat(){return this.currentBeatLookup.beat}get nextBeat(){var e,t;return null!==(t=null===(e=this.nextBeatLookup)||void 0===e?void 0:e.beat)&&void 0!==t?t:null}}class xs{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[]}finish(){let e=null,t=[];for(let i of this.masterBars){i.finish(),e&&(e.nextMasterBar=i);for(const e of i.beats){const i=[];for(let s of t)s.end>e.start&&(i.push(s),e.highlightBeat(s.beat),e.start<=s.start&&s.highlightBeat(e.beat));i.push(e),t=i}e=i}}findBeat(e,t,i=null){const s=new Map;for(const t of e)s.set(t.index,!0);let a=null;return i&&(a=this.findBeatFast(s,i,t)),a||(a=this.findBeatSlow(s,t)),a}findBeatFast(e,t,i){const s=t.currentBeatLookup.start+t.tickDuration;return i>=t.currentBeatLookup.start&&i<s?t:t.nextBeatLookup&&i>=t.nextBeatLookup.start&&i<t.nextBeatLookup.end?this.createResult(t.nextBeatLookup,e):null}findBeatSlow(e,t){const i=this.findMasterBar(t);if(!i)return null;let s=null,a=i.beats;for(let i=0;i<a.length;i++){let r=a[i];if(e.has(r.beat.voice.bar.staff.track.index))if(r.start<=t&&t<r.end)(!s||s.start<r.start)&&(s=a[i]);else if(r.end>t)break}return s?this.createResult(s,e):null}createResult(e,t){const i=this.findNextBeat(e,t),s=new Ns;return s.currentBeatLookup=e,s.nextBeatLookup=i,s.tickDuration=i?i.start-e.start:e.end-e.start,s.duration=ye.ticksToMillis(s.tickDuration,e.masterBar.tempo),s.beatsToHighlight=e.beatsToHighlight,s}findNextBeat(e,t){const i=e.masterBar;let s=i.beats,a=null;for(let i=e.index+1;i<s.length;i++){const r=s[i];if(r.start>e.start&&t.has(r.beat.voice.bar.staff.track.index)){a=r;break}}if(!a&&i.nextMasterBar){s=i.nextMasterBar.beats;for(let e=0;e<s.length;e++){const i=s[e];if(t.has(i.beat.voice.bar.staff.track.index)){a=i;break}}}return a}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 vs;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,this.masterBarLookup.has(e.masterBar.index)||this.masterBarLookup.set(e.masterBar.index,e)}addBeat(e){var t;null===(t=this._currentMasterBar)||void 0===t||t.addBeat(e)}}class Ps{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Es{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class Cs{constructor(e,t,i){this._currentTempo=0,this._currentBarRepeatLookup=null,this._programsPerChannel=new Map,this.tickLookup=new xs,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new Wi,this._currentTempo=this._score.tempo,this._handler=i}generate(){for(const e of this._score.tracks)this.generateTrack(e);Be.debug("Midi","Begin midi generation");const e=new ks(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);this.tickLookup.finish(),Be.debug("Midi","Midi generation done")}generateTrack(e){this.generateChannel(e,e.playbackInfo.primaryChannel,e.playbackInfo),e.playbackInfo.primaryChannel!==e.playbackInfo.secondaryChannel&&this.generateChannel(e,e.playbackInfo.secondaryChannel,e.playbackInfo)}addProgramChange(e,t,i,s){this._programsPerChannel.has(i)&&this._programsPerChannel.get(i)===s||(this._handler.addProgramChange(e.index,t,i,s),this._programsPerChannel.set(i,s))}generateChannel(e,t,i){let s=Cs.toChannelShort(i.volume),a=Cs.toChannelShort(i.balance);this._handler.addControlChange(e.index,0,t,te.VolumeCoarse,s),this._handler.addControlChange(e.index,0,t,te.PanCoarse,a),this._handler.addControlChange(e.index,0,t,te.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,te.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,te.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,te.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,te.DataEntryCoarse,Cs.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 vs;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);this._currentBarRepeatLookup=null;for(const s of i.voices)this.generateVoice(s,t,e)}getPlaybackBar(e){switch(e.simileMark){case o.Simple:e.previousBar&&(e=this.getPlaybackBar(e.previousBar));break;case o.FirstOfDouble:case o.SecondOfDouble:e.previousBar&&e.previousBar.previousBar&&(e=this.getPlaybackBar(e.previousBar.previousBar))}return e}generateVoice(e,t,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!==I.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(s-=this._currentTripletFeel.secondBeatStartOffset,a=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=Cs.calculateTripletFeelInfo(s,a,e),this._currentTripletFeel&&(a=this._currentTripletFeel.firstBeatDuration)));const r=new Bs;r.start=t+s;const n=e.nextBeat?e.nextBeat.absolutePlaybackStart-e.absolutePlaybackStart:a;r.end=t+s,r.highlightBeat(e),r.end+=n>a?n:a,i===e.voice.bar?(r.beat=e,this.tickLookup.addBeat(r)):(r.isEmptyBar=!0,r.beat=i.voices[0].beats[0],this._currentBarRepeatLookup?this._currentBarRepeatLookup.end=r.end:(this._currentBarRepeatLookup=r,this.tickLookup.addBeat(this._currentBarRepeatLookup)));const o=e.voice.bar.staff.track;for(const i of e.automations)this.generateAutomation(e,i,t);if(e.isRest)this._handler.addRest(o.index,t+s,o.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,o.playbackInfo.secondaryChannel,i)}))}}static calculateTripletFeelInfo(e,t,i){let s;switch(i.voice.bar.masterBar.tripletFeel){case I.Triplet8th:case I.Dotted8th:case I.Scottish8th:s=u.Eighth;break;case I.Triplet16th:case I.Dotted16th:case I.Scottish16th:s=u.Sixteenth;break;default:return null}const a=ye.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 Es;switch(i.voice.bar.masterBar.tripletFeel){case I.Triplet8th:r.firstBeatDuration=ye.applyTuplet(ye.toTicks(u.Quarter),3,2),r.secondBeatDuration=ye.applyTuplet(ye.toTicks(u.Eighth),3,2);break;case I.Dotted8th:r.firstBeatDuration=ye.applyDot(ye.toTicks(u.Eighth),!1),r.secondBeatDuration=ye.toTicks(u.Sixteenth);break;case I.Scottish8th:r.firstBeatDuration=ye.toTicks(u.Sixteenth),r.secondBeatDuration=ye.applyDot(ye.toTicks(u.Eighth),!1);break;case I.Triplet16th:r.firstBeatDuration=ye.applyTuplet(ye.toTicks(u.Eighth),3,2),r.secondBeatDuration=ye.applyTuplet(ye.toTicks(u.Sixteenth),3,2);break;case I.Dotted16th:r.firstBeatDuration=ye.applyDot(ye.toTicks(u.Sixteenth),!1),r.secondBeatDuration=ye.toTicks(u.ThirtySecond);break;case I.Scottish16th:r.firstBeatDuration=ye.toTicks(u.ThirtySecond),r.secondBeatDuration=ye.applyDot(ye.toTicks(u.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateNote(e,t,i,s){const a=e.beat.voice.bar.staff.track,r=e.beat.voice.bar.staff;let n=e.realValue;if(e.isPercussion){const t=Ne.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 d=Cs.getDynamicValue(e),c=e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==_.None?a.playbackInfo.secondaryChannel:a.playbackInfo.primaryChannel;let u=0;if(u=e.hasBend?Cs.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?Cs.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===S.Legato?-1:Cs.getPitchWheel(0),u>=0&&this._handler.addNoteBend(a.index,h,c,n,u),e.beat.fadeIn&&this.generateFadeIn(e,h,l),!e.isTrill||r.isPercussion){if(e.beat.isTremolo)this.generateTremoloPicking(e,h,l,n,d,c);else if(e.hasBend?this.generateBend(e,h,l,n,c):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,h,l,c):e.slideInType!==b.None||e.slideOutType!==S.None?this.generateSlide(e,h,l,n,d,c):(e.vibrato!==_.None||e.isTieDestination&&e.tieOrigin.vibrato!==_.None)&&this.generateVibrato(e,h,l,n,c),!(e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===S.Legato)){let e=Math.max(l.untilTieOrSlideEnd,l.letRingEnd);this._handler.addNote(a.index,h,e,n,d,c)}}else this.generateTrill(e,h,l,n,d,c)}getNoteDuration(e,t){const i=new Ps;if(i.noteOnly=t,i.untilTieOrSlideEnd=t,i.letRingEnd=t,e.isDead)return i.noteOnly=this.applyStaticDuration(Cs.DefaultDurationDead,t),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isPalmMute)return i.noteOnly=this.applyStaticDuration(Cs.DefaultDurationPalmMute,t),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isStaccato)return i.noteOnly=t/2|0,i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isTieOrigin){const s=e.tieDestination;if(s)if(e.isTieDestination){const e=this.getNoteDuration(s,s.beat.playbackDuration);i.untilTieOrSlideEnd=t+e.untilTieOrSlideEnd}else{const t=e.beat.absolutePlaybackStart,a=this.getNoteDuration(s,s.beat.playbackDuration),r=s.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;i.untilTieOrSlideEnd=r-t}}else if(e.slideOutType===S.Legato){const t=e.slideTarget;if(t){const s=e.beat.absolutePlaybackStart,a=this.getNoteDuration(t,t.beat.playbackDuration),r=t.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;i.untilTieOrSlideEnd=r-s}}if(e.isLetRing&&this._settings.notation.notationMode===T.GuitarPro){let s=e.beat,a=0;const r=e.beat.voice.bar.masterBar.calculateDuration();for(;s.nextBeat;){let t=s.nextBeat;if(t.isRest)break;if(e.isStringed&&t.hasNoteOnString(e.string))break;if(s=s.nextBeat,a=s.absolutePlaybackStart-e.beat.absolutePlaybackStart+s.playbackDuration,a>r){a=r;break}}s===e.beat?i.letRingEnd=t:i.letRingEnd=a}else i.letRingEnd=i.untilTieOrSlideEnd;return i}applyStaticDuration(e,t){const i=this._currentTempo*e/be.MaxPosition|0;return Math.min(i,t)}static getDynamicValue(e){let t=e.dynamics;switch(!e.beat.voice.bar.staff.isPercussion&&e.hammerPullOrigin&&t--,e.isGhost&&t--,e.accentuated){case s.Normal:t++;break;case s.Heavy:t+=2}return t<0&&(t=0),t}generateFadeIn(e,t,i){const s=e.beat.voice.bar.staff.track,a=Cs.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,te.VolumeCoarse,o),this._handler.addControlChange(s.index,t,s.playbackInfo.secondaryChannel,te.VolumeCoarse,o)),this._handler.addControlChange(s.index,i,s.playbackInfo.primaryChannel,te.VolumeCoarse,o),this._handler.addControlChange(s.index,i,s.playbackInfo.secondaryChannel,te.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,Cs.getPitchWheel(i)),t+=r}e+=i}}static getPitchWheel(e){return Gt.DefaultPitchWheel+e/2*Cs.PitchValuePerSemitone}generateSlide(e,t,i,s,a,r){let n=e.slideOutType===S.Legato?i.noteOnly:i.untilTieOrSlideEnd,o=[],h=e.beat.voice.bar.staff.track;const l=this._settings.player.slide.simpleSlidePitchOffset,d=Math.floor(be.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),c=Math.floor(be.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case b.IntoFromAbove:o.push(new be(0,l)),o.push(new be(d,0));break;case b.IntoFromBelow:o.push(new be(0,-l)),o.push(new be(d,0))}switch(e.slideOutType){case S.Legato:case S.Shift:o.push(new be(c,0));const t=2*(e.slideTarget.realValue-e.realValue);o.push(new be(be.MaxPosition,t));break;case S.OutDown:o.push(new be(be.MaxPosition-d,0)),o.push(new be(be.MaxPosition,-l));break;case S.OutUp:o.push(new be(be.MaxPosition-d,0)),o.push(new be(be.MaxPosition,l))}this.generateWhammyOrBend(t,n,o,((e,t)=>{this._handler.addNoteBend(h.index,e,r,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 d,c=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend;)t=t.tieDestination;d=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==g.None){switch(e.tieDestination.bendType){case l.Bend:case l.BendRelease:case l.PrebendBend:c=e.tieDestination.bendPoints[1].value;break;case l.Prebend:case l.PrebendRelease:c=e.tieDestination.bendPoints[0].value}d=Math.max(i.noteOnly,ye.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo))}else d=i.noteOnly;r[0].value>0&&!e.isContinuedBend&&t>0&&t--;const u=Math.min(d,ye.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));let p=[];switch(e.bendType){case l.Custom:p=r;break;case l.Bend:case l.Release:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),p.push(new be(be.MaxPosition,c));break;case h.Fast:return(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),void(e.beat.graceType===g.BendGrace?this.generateSongBookWhammyOrBend(t,d,!0,[e.bendPoints[0].value,c],u,o):this.generateSongBookWhammyOrBend(t,d,!1,[e.bendPoints[0].value,c],u,o))}break;case l.BendRelease:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),p.push(new be(be.MaxPosition/2|0,e.bendPoints[1].value)),p.push(new be(be.MaxPosition,e.bendPoints[2].value));break;case h.Fast:return void this.generateSongBookWhammyOrBend(t,d,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],u,o)}break;case l.Hold:case l.Prebend:p=r;break;case l.PrebendBend:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),p.push(new be(be.MaxPosition,e.bendPoints[1].value));break;case h.Fast:return o(t,0|Cs.getPitchWheel(e.bendPoints[0].value)),(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,d,!1,[e.bendPoints[0].value,c],u,o)}break;case l.PrebendRelease:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),p.push(new be(be.MaxPosition,e.bendPoints[1].value));break;case h.Fast:return o(t,0|Cs.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,d,!1,[e.bendPoints[0].value,e.bendPoints[1].value],u,o)}}this.generateWhammyOrBend(t,d,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=Cs.getPitchWheel(s[e]),i=Cs.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 l=[];switch(e.whammyBarType){case C.Custom:l=a;break;case C.Dive:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new be(0,a[0].value)),l.push(new be(be.MaxPosition,a[1].value));break;case h.Fast:const e=Math.min(n,ye.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],e,o)}break;case C.Dip:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new be(0,a[0].value)),l.push(new be(be.MaxPosition/2|0,a[1].value)),l.push(new be(be.MaxPosition,a[2].value));break;case h.Fast:const e=Math.min(n,ye.millisToTicks(this._settings.player.songBookDipDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!0,[a[0].value,a[1].value,a[2].value],e,o)}break;case C.Hold:case C.Predive:l=a;break;case C.PrediveDive:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new be(0,a[0].value)),l.push(new be(be.MaxPosition/2|0,a[0].value)),l.push(new be(be.MaxPosition,a[1].value));break;case h.Fast:const e=Cs.getPitchWheel(a[0].value);this._handler.addBend(r.index,t,s,0|e);const i=Math.min(n,ye.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,l,o)}generateWhammyOrBend(e,t,i,s){const a=t/be.MaxPosition;for(let t=0;t<i.length-1;t++){const r=i[t],n=i[t+1],o=Cs.getPitchWheel(r.value),h=Cs.getPitchWheel(n.value),l=a*(n.offset-r.offset),d=e+a*r.offset;this.generateBendValues(d,l,o,h,s)}}generateBendValues(e,t,i,s,a){const r=ye.ticksToMillis(t,this._currentTempo),n=Math.abs(s-i)/Cs.PitchValuePerSemitone,o=Math.max(Cs.MinBreakpointsPerSemitone*n,r/Cs.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=ye.toTicks(e.trillSpeed),l=!0,d=t,c=t+i.untilTieOrSlideEnd;for(;d+10<c;)d+h>=c&&(h=c-d),this._handler.addNote(n.index,d,h,l?o:s,a,r),l=!l,d+=h}generateTremoloPicking(e,t,i,s,a,r){const n=e.beat.voice.bar.staff.track;let o=ye.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;0!=(i&1<<n)&&(t[n]=a,a+=r)}}}return t}generateAutomation(e,t,i){switch(t.type){case a.Instrument:this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,255&(0|t.value)),this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,255&(0|t.value));break;case a.Balance:let s=Cs.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,te.PanCoarse,s),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,te.PanCoarse,s);break;case a.Volume:let r=Cs.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,te.VolumeCoarse,r),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,te.VolumeCoarse,r)}}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 a.Instrument:i=s.value;break;case a.Tempo:t=s.value}s=s.previousBeat}const r=e.voice.bar.staff.track,n=e.voice.bar.masterBar;-1===t&&(t=n.score.tempo),-1===i&&(i=r.playbackInfo.program);const o=r.playbackInfo.volume;this.generateTrack(r),this._handler.addTimeSignature(0,n.timeSignatureNumerator,n.timeSignatureDenominator),this._handler.addTempo(0,t);let h=Cs.toChannelShort(o);this._handler.addControlChange(0,0,r.playbackInfo.primaryChannel,te.VolumeCoarse,h),this._handler.addControlChange(0,0,r.playbackInfo.secondaryChannel,te.VolumeCoarse,h)}generateSingleBeat(e){this.prepareSingleBeat(e),this.generateBeat(e,-e.playbackStart,e.voice.bar)}generateSingleNote(e){this.prepareSingleBeat(e.beat),this.generateNote(e,0,e.beat.playbackDuration,new Int32Array(e.beat.voice.bar.staff.tuning.length))}}Cs.DefaultDurationDead=30,Cs.DefaultDurationPalmMute=80,Cs.PitchBendRangeInSemitones=16,Cs.PitchValuePerSemitone=Gt.DefaultPitchWheel/Cs.PitchBendRangeInSemitones,Cs.MinBreakpointsPerSemitone=6,Cs.MillisecondsPerBreakpoint=150;class Fs{constructor(){this.startTick=0,this.endTick=0}}class Ls{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 Ms extends Ls{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Ds extends Ms{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 Is extends Ds{constructor(e,t,i,s){super(e,t,s?Is.GraceScale:1,Is.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?Is.GraceScale:1)*this.scale;switch(this._duration){case u.QuadrupleWhole:this.width=14*e;break;case u.DoubleWhole:case u.Whole:this.width=14*(this._isGrace?Is.GraceScale:1)*this.scale;break;default:this.width=Is.QuarterNoteHeadWidth*(this._isGrace?Is.GraceScale:1)*this.scale}this.height=Is.NoteHeadHeight*e}static getSymbol(e){switch(e){case u.QuadrupleWhole:return x.NoteheadDoubleWholeSquare;case u.DoubleWhole:return x.NoteheadDoubleWhole;case u.Whole:return x.NoteheadWhole;case u.Half:return x.NoteheadHalf;default:return x.NoteheadBlack}}}Is.GraceScale=.75,Is.NoteHeadHeight=8,Is.QuarterNoteHeadWidth=9;class Rs extends Ds{constructor(e,t,i,s,a){super(e,t,a?Is.GraceScale:1,Rs.getSymbol(i,s,a))}doLayout(){this.width=0}static getSymbol(e,t,i){if(i&&(e=u.Eighth),t===H.Up)switch(e){case u.Eighth:return x.FlagEighthUp;case u.Sixteenth:return x.FlagSixteenthUp;case u.ThirtySecond:return x.FlagThirtySecondUp;case u.SixtyFourth:return x.FlagSixtyFourthUp;case u.OneHundredTwentyEighth:return x.FlagOneHundredTwentyEighthUp;case u.TwoHundredFiftySixth:return x.FlagTwoHundredFiftySixthUp;default:return x.FlagEighthUp}switch(e){case u.Eighth:return x.FlagEighthDown;case u.Sixteenth:return x.FlagSixteenthDown;case u.ThirtySecond:return x.FlagThirtySecondDown;case u.SixtyFourth:return x.FlagSixtyFourthDown;case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:return x.FlagOneHundredTwentyEighthDown;default:return x.FlagEighthDown}}}Rs.FlagWidth=11;class As extends Ls{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+=As.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!==g.None)&&(i+=Rs.FlagWidth*this.scale*(this.beat.graceType!==g.None?Is.GraceScale:1));for(const e of this.ties)i+=e.width;this.beat.graceType!==g.None&&(i+=As.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+=As.GraceBeatPadding*this.renderer.scale),this.preNotes.x=t,this.preNotes.width=e.getPreBeatSize(this.beat),this.onNotes.width=e.getOnBeatSize(this.beat),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.updateBeamingHelper(),this.updateWidth()}doLayout(){this.preNotes.x=0,this.preNotes.renderer=this.renderer,this.preNotes.container=this,this.preNotes.doLayout(),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.renderer=this.renderer,this.onNotes.container=this,this.onNotes.doLayout();let e=this.beat.notes.length-1;for(;e>=0;)this.createTies(this.beat.notes[e--]);this.renderer.registerTies(this.ties),this.updateWidth()}updateWidth(){if(this.minWidth=this.preNotes.width+this.onNotes.width,!this.beat.isRest)if(1===this.onNotes.beamingHelper.beats.length)this.beat.duration>=u.Eighth&&(this.minWidth+=20*this.scale);else switch(this.beat.duration){case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:this.minWidth+=10*this.scale}let e=0;for(let t of this.ties)t.width>e&&(e=t.width);this.minWidth+=e,this.width=this.minWidth}scaleToWidth(e){this.onNotes.updateBeamingHelper(),this.width=e}createTies(e){}static getGroupId(e){return"b"+e.id}paint(e,t,i){if(this.beat.voice.isEmpty)return;if(this.preNotes.isEmpty&&this.onNotes.isEmpty&&0===this.ties.length)return;i.beginGroup(As.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 ps;a.beat=this.beat,a.visualBounds=new at,a.visualBounds.x=t+this.x+this.onNotes.x,a.visualBounds.y=e.visualBounds.y,a.visualBounds.w=this.onNotes.width,a.visualBounds.h=e.visualBounds.h,a.realBounds=new at,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,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)}}As.GraceBeatPadding=3;class Os{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new fo}causeIssue(){return this.settings=null,!0}}class Gs{constructor(e){this.activeBeats=e}}class Vs{constructor(e){this.bounds=null,this.beat=e}}class Hs{constructor(e,t){this._startTime=0,this._trackIndexes=null,this._isDestroyed=!1,this.score=null,this.tracks=[],this._tickCache=null,this.player=null,this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null,this._previousTick=0,this._playerState=q.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=q.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new mi,this.activeBeatsChanged=new mi,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new mi,this.beatMouseMove=new mi,this.beatMouseUp=new mi,this.noteMouseDown=new mi,this.noteMouseMove=new mi,this.noteMouseUp=new mi,this.scoreLoaded=new mi,this.resize=new mi,this.renderStarted=new mi,this.renderFinished=new mi,this.postRenderFinished=new fi,this.error=new mi,this.playerReady=new fi,this.playerFinished=new fi,this.soundFontLoaded=new fi,this.midiLoad=new mi,this.midiLoaded=new mi,this.playerStateChanged=new mi,this.playerPositionChanged=new mi,this.midiEventsPlayed=new mi,this.playbackRangeChanged=new mi,this.settingsUpdated=new fi,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),Be.logLevel=this.settings.core.logLevel,this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&go.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new bs(this.settings),this.container.resize.on(go.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));let i=new Os;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;Be.debug("rendering","Rendering completed in "+e+"ms"),this.onPostRenderFinished()})),this.renderer.preRender.on((e=>{this._startTime=Date.now()})),this.renderer.partialLayoutFinished.on(this.appendRenderResult.bind(this)),this.renderer.partialRenderFinished.on(this.updateRenderResult.bind(this)),this.renderer.renderFinished.on((e=>{this.appendRenderResult(e),this.appendRenderResult(null)})),this.renderer.error.on(this.onError.bind(this)),this.settings.player.enablePlayer&&this.setupPlayer(),this.setupClickHandling(),this.uiFacade.beginInvoke((()=>{this.uiFacade.initialRender()}))}destroy(){this._isDestroyed=!0,this.player&&this.player.destroy(),this.uiFacade.destroy(),this.renderer.destroy()}updateSettings(){const e=this.score;e&&ke.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?this.setupPlayer():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(e){if(e.length>0){let t=e[0].score;for(let s of e)if(s.score!==t)return void this.onError(new pe(i.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(t,e)}}internalRenderTracks(e,t){if(ke.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.onScoreLoaded(e),this.loadMidiForScore(),this.render()}else{this.tracks=t,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this.render()}}triggerResize(){if(this.container.isVisible){let e=new Os;e.oldWidth=this.renderer.width,e.newWidth=this.container.width,e.settings=this.settings,this.onResize(e),this.renderer.updateSettings(this.settings),this.renderer.width=this.container.width,this.renderer.resizeRender()}else Be.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{Be.debug("Rendering","AlphaTab container became visible, doing autosizing",null),this.triggerResize()}))}appendRenderResult(e){e?(this.canvasElement.width=e.totalWidth,this.canvasElement.height=e.totalHeight,this._cursorWrapper&&(this._cursorWrapper.width=e.totalWidth,this._cursorWrapper.height=e.totalHeight),(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 et;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:q.Paused}get masterVolume(){return this.player?this.player.masterVolume:0}set masterVolume(e){this.player&&(this.player.masterVolume=e)}get metronomeVolume(){return this.player?this.player.metronomeVolume:0}set metronomeVolume(e){this.player&&(this.player.metronomeVolume=e)}get countInVolume(){return this.player?this.player.countInVolume:0}set countInVolume(e){this.player&&(this.player.countInVolume=e)}get midiEventsPlayedFilter(){return this.player?this.player.midiEventsPlayedFilter:[]}set midiEventsPlayedFilter(e){this.player&&(this.player.midiEventsPlayedFilter=e)}get tickPosition(){return this.player?this.player.tickPosition:0}set tickPosition(e){this.player&&(this.player.tickPosition=e)}get timePosition(){return this.player?this.player.timePosition:0}set timePosition(e){this.player&&(this.player.timePosition=e)}get playbackRange(){return this.player?this.player.playbackRange:null}set playbackRange(e){this.player&&(this.player.playbackRange=e,this.settings.player.enableCursor&&this.updateSelectionCursor(e))}get playbackSpeed(){return this.player?this.player.playbackSpeed:0}set playbackSpeed(e){this.player&&(this.player.playbackSpeed=e)}get isLooping(){return!!this.player&&this.player.isLooping}set isLooping(e){this.player&&(this.player.isLooping=e)}destroyPlayer(){this.player&&(this.player.destroy(),this.player=null,this._previousTick=0,this._playerState=q.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;Be.debug("AlphaTab","Generating Midi");let e=new _i,t=new ws(e),i=new Cs(this.score,this.settings,t);i.generate(),this._tickCache=i.tickLookup,this.onMidiLoad(e),this.player.loadMidiFile(e)}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 _i,i=new ws(t);new Cs(e.voice.bar.staff.track.score,this.settings,i).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;let t=new _i,i=new ws(t);new Cs(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=q.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===q.Paused){let e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getBeatStart(e.currentBeat))}})))}cursorUpdateTick(e,t,i=!1){let s=this._tickCache;if(s){let a=this.tracks;if(a.length>0){let r=s.findBeat(a,e,this._currentBeat);r&&this.cursorUpdateBeat(r,t,i)}}}cursorUpdateBeat(e,t,i,s=!1){const a=e.currentBeat,r=e.nextBeat,n=e.duration,o=e.beatsToHighlight;if(!a)return;let h=this.renderer.boundsLookup;if(!h)return;let l=this._currentBeat,d=this._previousCursorCache,c=this._previousStateForCursor;if(!s&&a===(null==l?void 0:l.currentBeat)&&h===d&&c===this._playerState)return;let u=h.findBeat(a);u&&(this._currentBeat=e,this._previousCursorCache=h,this._previousStateForCursor=this._playerState,this.uiFacade.beginInvoke((()=>{this.internalCursorUpdateBeat(a,r,n,t,o,h,u,i)})))}scrollToCursor(){const e=this._currentBarBounds;e&&this.internalScrollToCursor(e)}internalScrollToCursor(e){let t=this.uiFacade.getScrollContainer(),i=go.getLayoutEngineFactory(this.settings.display.layoutMode).vertical,s=this.settings.player.scrollMode;if(i){let i=e.realBounds.y+this.settings.player.scrollOffsetY;if(i!==this._lastScroll)switch(this._lastScroll=i,s){case ee.Continuous:let s=this.uiFacade.getOffset(t,this.container);this.uiFacade.scrollToY(t,s.y+i,this.settings.player.scrollSpeed);break;case ee.OffScreen:let a=t.scrollTop+this.uiFacade.getOffset(null,t).h;if(e.visualBounds.y+e.visualBounds.h>=a||e.visualBounds.y<t.scrollTop){let i=e.realBounds.y+this.settings.player.scrollOffsetY;this.uiFacade.scrollToY(t,i,this.settings.player.scrollSpeed)}}}else{let i=e.visualBounds.x;if(i!==this._lastScroll)switch(this._lastScroll=i,s){case ee.Continuous:let i=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,i,this.settings.player.scrollSpeed);break;case ee.OffScreen:let s=t.scrollLeft+this.uiFacade.getOffset(null,t).w;if(e.visualBounds.x+e.visualBounds.w>=s||e.visualBounds.x<t.scrollLeft){let i=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,i,this.settings.player.scrollSpeed)}}}}internalCursorUpdateBeat(e,t,i,s,a,r,n,o){const h=this._barCursor,l=this._beatCursor;let d=n.barBounds.masterBarBounds,c=d.visualBounds;this._currentBarBounds=d,h&&h.setBounds(c.x,c.y,c.w,c.h),l&&(this.settings.player.enableAnimatedBeatCursor&&l.stopAnimation(),l.setBounds(n.visualBounds.x,c.y,1,c.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let u=!1;if(this._playerState===q.Playing&&!s){if(this.settings.player.enableElementHighlighting)for(let t of a){let i=As.getGroupId(t);this.uiFacade.highlightElements(i,e.voice.bar.index)}if(this.settings.player.enableAnimatedBeatCursor){let s=d.visualBounds.x+d.visualBounds.w;if(t&&(t.voice.bar.index===e.voice.bar.index&&t.index>e.index||t.voice.bar.index===e.voice.bar.index+1)){let e=r.findBeat(t);e&&e.barBounds.masterBarBounds.staveGroupBounds===d.staveGroupBounds&&(s=e.visualBounds.x)}this.uiFacade.beginInvoke((()=>{l&&l.transitionToX(i/this.playbackSpeed,s)}))}o=!s,u=!0}o&&!this._beatMouseDown&&this.settings.player.scrollMode!==ee.Off&&this.internalScrollToCursor(d),u&&(this.onPlayedBeatChanged(e),this.onActiveBeatsChanged(new Gs(a)))}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 Vs(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 Vs(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){var i,s,a,r;if(!this._isDestroyed){if(this.settings.player.enableUserInteraction){if(this._selectionEnd){let e=null!==(s=null===(i=this._tickCache)||void 0===i?void 0:i.getBeatStart(this._selectionStart.beat))&&void 0!==s?s:this._selectionStart.beat.absolutePlaybackStart;if((null!==(r=null===(a=this._tickCache)||void 0===a?void 0:a.getBeatStart(this._selectionEnd.beat))&&void 0!==r?r: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===q.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 Fs;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.tracks,e.startTick),i=this._tickCache.findBeat(this.tracks,e.endTick);if(t&&i){const e=new Vs(t.currentBeat),s=new Vs(i.currentBeat);this.cursorSelectRange(e,s)}}else this.cursorSelectRange(null,null)}setupClickHandling(){this.canvasElement.mouseDown.on((e=>{var t,i,s;if(!e.isLeftMouseButton)return;this.settings.player.enableUserInteraction&&e.preventDefault();let a=e.getX(this.canvasElement),r=e.getY(this.canvasElement),n=null!==(i=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(a,r))&&void 0!==i?i:null;if(n&&(this.onBeatMouseDown(e,n),this.settings.core.includeNoteBounds)){const t=null===(s=this.renderer.boundsLookup)||void 0===s?void 0:s.getNoteAtPos(n,a,r);t&&this.onNoteMouseDown(e,t)}})),this.canvasElement.mouseMove.on((e=>{var t,i,s;if(!this._beatMouseDown)return;let a=e.getX(this.canvasElement),r=e.getY(this.canvasElement),n=null!==(i=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(a,r))&&void 0!==i?i:null;if(n&&(this.onBeatMouseMove(e,n),this._noteMouseDown)){const t=null===(s=this.renderer.boundsLookup)||void 0===s?void 0:s.getNoteAtPos(n,a,r);t&&this.onNoteMouseMove(e,t)}})),this.canvasElement.mouseUp.on((e=>{var t,i,s,a;if(!this._beatMouseDown)return;this.settings.player.enableUserInteraction&&e.preventDefault();let r=e.getX(this.canvasElement),n=e.getY(this.canvasElement),o=null!==(i=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(r,n))&&void 0!==i?i:null;if(this.onBeatMouseUp(e,o),this._noteMouseDown)if(o){const t=null!==(a=null===(s=this.renderer.boundsLookup)||void 0===s?void 0:s.getNoteAtPos(o,r,n))&&void 0!==a?a:null;this.onNoteMouseUp(e,t)}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){var i,s,a,r;let n=this.renderer.boundsLookup;if(!n)return;let o=this._selectionWrapper;if(!o)return;if(o.clear(),!e||!t||e.beat===t.beat)return;e.bounds||(e.bounds=n.findBeat(e.beat)),t.bounds||(t.bounds=n.findBeat(t.beat));let h=null!==(s=null===(i=this._tickCache)||void 0===i?void 0:i.getBeatStart(e.beat))&&void 0!==s?s:e.beat.absolutePlaybackStart;if((null!==(r=null===(a=this._tickCache)||void 0===a?void 0:a.getBeatStart(t.beat))&&void 0!==r?r:t.beat.absolutePlaybackStart)<h){let i=e;e=t,t=i}let l=e.bounds.realBounds.x,d=t.bounds.realBounds.x+t.bounds.realBounds.w;if(t.beat.index===t.beat.voice.beats.length-1&&(d=t.bounds.barBounds.masterBarBounds.realBounds.x+t.bounds.barBounds.masterBarBounds.realBounds.w),e.bounds.barBounds.masterBarBounds.staveGroupBounds!==t.bounds.barBounds.masterBarBounds.staveGroupBounds){let i=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x,s=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x+e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.w,a=this.uiFacade.createSelectionElement();a.setBounds(l,e.bounds.barBounds.masterBarBounds.visualBounds.y,s-l,e.bounds.barBounds.masterBarBounds.visualBounds.h),o.appendChild(a);let r=e.bounds.barBounds.masterBarBounds.staveGroupBounds.index+1,h=t.bounds.barBounds.masterBarBounds.staveGroupBounds.index;for(let e=r;e<h;e++){let t=n.staveGroups[e],a=this.uiFacade.createSelectionElement();a.setBounds(i,t.visualBounds.y,s-i,t.visualBounds.h),o.appendChild(a)}let c=this.uiFacade.createSelectionElement();c.setBounds(i,t.bounds.barBounds.masterBarBounds.visualBounds.y,d-i,t.bounds.barBounds.masterBarBounds.visualBounds.h),o.appendChild(c)}else{let t=this.uiFacade.createSelectionElement();t.setBounds(l,e.bounds.barBounds.masterBarBounds.visualBounds.y,d-l,e.bounds.barBounds.masterBarBounds.visualBounds.h),o.appendChild(t)}}onScoreLoaded(e){this._isDestroyed||(this.scoreLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"scoreLoaded",e))}onResize(e){this._isDestroyed||(this.resize.trigger(e),this.uiFacade.triggerEvent(this.container,"resize",e))}onRenderStarted(e){this._isDestroyed||(this.renderStarted.trigger(e),this.uiFacade.triggerEvent(this.container,"renderStarted",e))}onRenderFinished(e){this._isDestroyed||(this.renderFinished.trigger(e),this.uiFacade.triggerEvent(this.container,"renderFinished",e))}onPostRenderFinished(){this._isDestroyed||(this.postRenderFinished.trigger(),this.uiFacade.triggerEvent(this.container,"postRenderFinished",null))}onError(e){this._isDestroyed||(Be.error("API","An unexpected error occurred",e),this.error.trigger(e),this.uiFacade.triggerEvent(this.container,"error",e))}onPlayerReady(){this._isDestroyed||(this.playerReady.trigger(),this.uiFacade.triggerEvent(this.container,"playerReady",null))}onPlayerFinished(){this._isDestroyed||(this.playerFinished.trigger(),this.uiFacade.triggerEvent(this.container,"playerFinished",null))}onSoundFontLoaded(){this._isDestroyed||(this.soundFontLoaded.trigger(),this.uiFacade.triggerEvent(this.container,"soundFontLoaded",null))}onMidiLoad(e){this._isDestroyed||(this.midiLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"midiLoad",e))}onMidiLoaded(e){this._isDestroyed||(this.midiLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"midiFileLoaded",e))}onPlayerStateChanged(e){this._isDestroyed||(this.playerStateChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerStateChanged",e))}onPlayerPositionChanged(e){this._isDestroyed||null!==this.score&&this.tracks.length>0&&(this.playerPositionChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerPositionChanged",e))}onMidiEventsPlayed(e){this._isDestroyed||(this.midiEventsPlayed.trigger(e),this.uiFacade.triggerEvent(this.container,"midiEventsPlayed",e))}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 Ws extends pe{constructor(e,t){super(i.General,e),this.xhr=t,Object.setPrototypeOf(this,Ws.prototype)}}class zs{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=zs.loadScoreFromBytes(i,s);t(r)}catch(e){i(e)}else 0===a.status?i(new Ws("You are offline!!\n Please Check Your Network.",a)):404===a.status?i(new Ws("Requested URL not found.",a)):500===a.status?i(new Ws("Internel Server Error.",a)):"parsererror"===a.statusText?i(new Ws("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?i(new Ws("Request Time out.",a)):i(new Ws("Unknow Error: "+a.responseText,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Wi);let i=go.buildImporters();Be.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{Be.debug("ScoreLoader","Importing using importer "+e.name),e.init(a,t),s=e.readScore(),Be.debug("ScoreLoader","Score imported using "+e.name);break}catch(t){if(!(t instanceof ge))throw Be.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;Be.debug("ScoreLoader",e.name+" does not support the file")}}if(s)return s;throw Be.error("ScoreLoader","No compatible importer found for file"),new ge("No compatible importer found for file")}}class Us{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 Xs{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 at,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new Us(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new Us(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new Us(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&Xs.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,Xs.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=""}}Xs.resizeObserver=new _e((()=>new ResizeObserver((e=>{for(const t of e){let e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class Ys{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new mi,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(go.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0,t=window.setInterval((()=>{Be.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);Be.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);let i=e=>{this._families.length>1?(Be.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(Be.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},s=e=>{Be.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 Be.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){Be.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 qs{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 Js{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new fi,this.samplesPlayed=new mi,this.sampleRequest=new fi}get sampleRate(){return this._context?this._context.sampleRate:Js.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(Be.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{var t,i;Be.debug("WebAudio",`Audio Context resume success: state=${null===(t=this._context)||void 0===t?void 0:t.state}, sampleRate:${null===(i=this._context)||void 0===i?void 0:i.sampleRate}`),e&&e()}),(e=>{var t,i;Be.warning("WebAudio",`Audio Context resume failed: state=${null===(t=this._context)||void 0===t?void 0:t.state}, sampleRate:${null===(i=this._context)||void 0===i?void 0:i.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,Js.PreferredSampleRate),i=e.createBufferSource();i.buffer=t,i.connect(e.destination),i.start(0),i.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in go.globalThis)return new AudioContext;if("webkitAudioContext"in go.globalThis)return new webkitAudioContext;throw new pe(i.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,Js.BufferSize,e.sampleRate),this._source=e.createBufferSource(),this._source.buffer=this._buffer,this._source.loop=!0}pause(){this._source&&(this._source.stop(0),this._source.disconnect()),this._source=null}destroy(){var e;this.pause(),null===(e=this._context)||void 0===e||e.close(),this._context=null,this.unregisterResumeHandler()}onSamplesPlayed(e){this.samplesPlayed.trigger(e)}onSampleRequest(){this.sampleRequest.trigger()}onReady(){this.ready.trigger()}}Js.BufferSize=4096,Js.PreferredSampleRate=44100;class js extends Js{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/Js.BufferSize),this._circularBuffer=new qs(Js.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*Js.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*Js.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/Gt.AudioChannels),this.requestBuffers()}}class Qs{constructor(e,t){this.loaded=e,this.total=t}}class $s{get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return Be.logLevel}set logLevel(e){Be.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Gt.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Gt.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Gt.MinVolume),this._countInVolume=e,this._synth.postMessage({cmd:"alphaSynth.setCountInVolume",value:e})}get midiEventsPlayedFilter(){return this._midiEventsPlayedFilter}set midiEventsPlayedFilter(e){this._midiEventsPlayedFilter=e,this._synth.postMessage({cmd:"alphaSynth.setMidiEventsPlayedFilter",value:e})}get playbackSpeed(){return this._playbackSpeed}set playbackSpeed(e){e=ni.clamp(e,Gt.MinPlaybackSpeed,Gt.MaxPlaybackSpeed),this._playbackSpeed=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackSpeed",value:e})}get tickPosition(){return this._tickPosition}set tickPosition(e){e<0&&(e=0),this._tickPosition=e,this._synth.postMessage({cmd:"alphaSynth.setTickPosition",value:e})}get timePosition(){return this._timePosition}set timePosition(e){e<0&&(e=0),this._timePosition=e,this._synth.postMessage({cmd:"alphaSynth.setTimePosition",value:e})}get isLooping(){return this._isLooping}set isLooping(e){this._isLooping=e,this._synth.postMessage({cmd:"alphaSynth.setIsLooping",value:e})}get playbackRange(){return this._playbackRange}set playbackRange(e){e&&(e.startTick<0&&(e.startTick=0),e.endTick<0&&(e.endTick=0)),this._playbackRange=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackRange",value:e})}constructor(e,t,i,s){this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=q.Paused,this._masterVolume=0,this._metronomeVolume=0,this._countInVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._midiEventsPlayedFilter=[],this.ready=new fi,this.readyForPlayback=new fi,this.finished=new fi,this.soundFontLoaded=new fi,this.soundFontLoadFailed=new mi,this.midiLoaded=new mi,this.midiLoadFailed=new mi,this.stateChanged=new mi,this.positionChanged=new mi,this.midiEventsPlayed=new mi,this.playbackRangeChanged=new mi,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=q.Paused,this._masterVolume=0,this._metronomeVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._output=e,this._output.ready.on(this.onOutputReady.bind(this)),this._output.samplesPlayed.on(this.onOutputSamplesPlayed.bind(this)),this._output.sampleRequest.on(this.onOutputSampleRequest.bind(this)),this._output.open(s);try{this._synth=go.createAlphaTabWorker(t)}catch(e){Be.error("AlphaSynth","Failed to create WebWorker: "+e)}this._synth.addEventListener("message",this.handleWorkerMessage.bind(this),!1),this._synth.postMessage({cmd:"alphaSynth.initialize",sampleRate:this._output.sampleRate,logLevel:i,bufferTimeInMilliseconds:s}),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:os.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,i){Be.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=>{Be.error("AlphaSynth","Loading failed: "+e.message),this.soundFontLoadFailed.trigger(new Ws(e.message,s))},s.onprogress=e=>{Be.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),i(new Qs(e.loaded,e.total))},s.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:os.midiFileToJsObject(e)})}setChannelMute(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelMute",channel:e,mute:t})}resetChannelStates(){this._synth.postMessage({cmd:"alphaSynth.resetChannelStates"})}setChannelSolo(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelSolo",channel:e,solo:t})}setChannelVolume(e,t){t=Math.max(t,Gt.MinVolume),this._synth.postMessage({cmd:"alphaSynth.setChannelVolume",channel:e,volume:t})}handleWorkerMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.ready":this._workerIsReady=!0,this.checkReady();break;case"alphaSynth.destroyed":this._synth.terminate();break;case"alphaSynth.readyForPlayback":this._workerIsReadyForPlayback=!0,this.checkReadyForPlayback();break;case"alphaSynth.positionChanged":this._timePosition=t.currentTime,this._tickPosition=t.currentTick,this.positionChanged.trigger(new Ut(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new yi(t.events.map(os.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new zt(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new bi(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 Ut(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiLoadFailed":this.checkReadyForPlayback(),this.midiLoadFailed.trigger(t.error);break;case"alphaSynth.output.addSamples":this._output.addSamples(t.samples);break;case"alphaSynth.output.play":this._output.play();break;case"alphaSynth.output.pause":this._output.pause();break;case"alphaSynth.output.destroy":this._output.destroy();break;case"alphaSynth.output.resetSamples":this._output.resetSamples()}}checkReady(){this.isReady&&this.ready.trigger()}checkReadyForPlayback(){this.isReadyForPlayback&&this.readyForPlayback.trigger()}onOutputSampleRequest(){this._synth.postMessage({cmd:"alphaSynth.output.sampleRequest"})}onOutputSamplesPlayed(e){this._synth.postMessage({cmd:"alphaSynth.output.samplesPlayed",samples:e})}onOutputReady(){this._outputIsReady=!0,this.checkReady()}}class Ks{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new mi,this.partialRenderFinished=new mi,this.partialLayoutFinished=new mi,this.renderFinished=new mi,this.postRenderFinished=new fi,this.error=new mi,this._api=e;try{this._worker=go.createAlphaTabWorker(t.core.scriptFile)}catch(e){return void Be.error("Rendering",`Failed to create WebWorker: ${e}`)}this._worker.postMessage({cmd:"alphaTab.initialize",settings:this.serializeSettingsForWorker(t)}),this._worker.addEventListener("message",this.handleWorkerMessage.bind(this))}destroy(){this._worker.terminate()}updateSettings(e){this._worker.postMessage({cmd:"alphaTab.updateSettings",settings:this.serializeSettingsForWorker(e)})}serializeSettingsForWorker(e){const t=os.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=ys.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:os.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:i,trackIndexes:t,fontSizes:ds.FontSizeLookupTables})}}class Zs{constructor(e,t,i,s){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=i,this.selectionWrapper=s}}!function(e){e[e.Browser=0]="Browser",e[e.NodeJs=1]="NodeJs",e[e.BrowserModule=2]="BrowserModule"}(ie||(ie={}));class ea{static init(){var e;ea._isRegistered||(ea._isRegistered=!0,registerProcessor("alphatab",((e=class e extends AudioWorkletProcessor{constructor(t){super(t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,Be.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new qs(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){let t=e.data;switch(t.cmd){case hs.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case hs.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:hs.CmdOutputSamplesPlayed,samples:o/Gt.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:hs.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}ea._isRegistered=!1;class ta extends Js{constructor(){super(...arguments),this._worklet=null,this._bufferTimeInMilliseconds=0}open(e){super.open(e),this._bufferTimeInMilliseconds=e,this.onReady()}play(){super.play();let e=this._context;e.audioWorklet.addModule(go.scriptFile).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=>{Be.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){let t=e.data;switch(t.cmd){case hs.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case hs.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){var t;null===(t=this._worklet)||void 0===t||t.port.postMessage({cmd:hs.CmdOutputAddSamples,samples:e})}resetSamples(){var e;null===(e=this._worklet)||void 0===e||e.port.postMessage({cmd:hs.CmdOutputResetSamples})}}class ia extends Xs{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"}(se||(se={}));class sa{get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(go.bravuraFontChecker.checkForFontAvailability(),!go.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(Be.debug("Font","All fonts loaded: "+this._fontCheckers.size),!0)}onFontLoaded(e){ds.generateFontLookup(e),this.areAllFontsLoaded()&&this.canRenderChanged.trigger()}constructor(e){if(this._fontCheckers=new Map,this._contents=null,this._file=null,this._totalResultCount=0,this._initialTrackIndexes=null,this._barToElementLookup=new Map,this._resultIdToElementLookup=new Map,this.rootContainerBecameVisible=new fi,this.canRenderChanged=new fi,this._highlightedElements=[],this._scrollContainer=null,go.webPlatform!==ie.Browser&&go.webPlatform!==ie.BrowserModule)throw new pe(i.General,"Usage of AlphaTabApi is only possible in browser environments. For usage in node use the Low Level APIs");e.classList.add("alphaTab"),this.rootContainer=new Xs(e),this.areWorkersSupported="Worker"in window,go.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(e)}onElementVisibilityChanged(e){for(const t of e){const e=t.target;if(e===this.rootContainer.element)t.isIntersecting&&(this.rootContainerBecameVisible.trigger(),this._intersectionObserver.unobserve(this.rootContainer.element));else if("layoutResultId"in e&&this._api.settings.core.enableLazyLoading){const i=e;t.isIntersecting?i.renderedResultId!==i.layoutResultId?this._resultIdToElementLookup.has(i.layoutResultId)?this._api.renderer.renderResult(i.layoutResultId):e.replaceChildren():i.resultState===se.Detached&&(e.replaceChildren(...i.renderedResult),i.resultState=se.RenderDone):i.resultState===se.RenderDone&&(i.resultState=se.Detached,i.replaceChildren())}}}createWorkerRenderer(){return new Ks(this._api,this._api.settings)}initialize(e,t){let i;this._api=e,i=t instanceof Wi?t:os.jsObjectToSettings(t);let s=this.getDataAttributes();Hi.fromJson(i,s),i.notation.notationMode===T.SongBook&&i.setSongBookModeSettings(),e.settings=i,this.setupFontCheckers(i),this._initialTrackIndexes=this.parseTracks(i.core.tracks),this._contents="";let a=e.container;i.core.tex&&(this._contents=a.element.innerHTML,a.element.innerHTML=""),this.createStyleElement(i),this._file=i.core.file}setupFontCheckers(e){this.registerFontChecker(e.display.resources.copyrightFont),this.registerFontChecker(e.display.resources.effectFont),this.registerFontChecker(e.display.resources.fingeringFont),this.registerFontChecker(e.display.resources.graceFont),this.registerFontChecker(e.display.resources.markerFont),this.registerFontChecker(e.display.resources.tablatureFont),this.registerFontChecker(e.display.resources.titleFont),this.registerFontChecker(e.display.resources.wordsFont),this.registerFontChecker(e.display.resources.barNumberFont),this.registerFontChecker(e.display.resources.fretboardNumberFont),this.registerFontChecker(e.display.resources.subTitleFont)}registerFontChecker(e){if(!this._fontCheckers.has(e.families.join(", "))){let t=new Ys(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 Xs(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 He)return t(e),!0;if(e instanceof ArrayBuffer){let i=new Uint8Array(e);return t(zs.loadScoreFromBytes(i,this._api.settings)),!0}return e instanceof Uint8Array?(t(zs.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(zs.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=()=>{var e;this._api.renderer.width=0|this.rootContainer.width,this._api.renderer.updateSettings(this._api.settings),this._contents?(this._api.tex(this._contents,null!==(e=this._initialTrackIndexes)&&void 0!==e?e:void 0),this._initialTrackIndexes=null):this._file&&zs.loadScoreAsync(this._file,(e=>{var t;this._api.renderScore(e,null!==(t=this._initialTrackIndexes)&&void 0!==t?t:void 0),this._initialTrackIndexes=null}),(e=>{this._api.onError(e)}),this._api.settings)};this.rootContainer.isVisible?e():this.rootContainerBecameVisible.on(e)}createStyleElement(e){let t=this._api.container.element.ownerDocument;go.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=se.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=se.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 e=go.scriptFile;if(!e)return Be.error("Player","alphaTab script file could not be detected, player cannot initialize"),null;let t=null,i="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window&&!go.isWebPackBundled?(Be.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),t=new $s(new ta,e,this._api.settings.core.logLevel,this._api.settings.player.bufferTimeInMilliseconds)):i&&(Be.debug("Player","Will use webworkers for synthesizing and web audio api for playback"),t=new $s(new js,e,this._api.settings.core.logLevel,this._api.settings.player.bufferTimeInMilliseconds)),t?t.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):Be.error("Player","Player requires webworkers and web audio api, browser unsupported",null),t}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const 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 Zs(new Xs(t),s,a,new Xs(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 at;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 Xs(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new ia(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 aa extends Hs{constructor(e,t){super(new sa(e),t),this.soundFontLoad=new mi}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.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,d=a.offsetWidth+50,c=window.innerHeight,u=(h/2|0)-(d/2|0)+n,p=(l/2|0)-(c/2|0)+o;s.resizeTo(d,c),s.moveTo(u,p),s.focus();let g=os.jsObjectToSettings(os.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,Hi.fromJson(g,i);let f=new aa(a,g);s.onunload=()=>{f.destroy()},f.renderer.postRenderFinished.on((()=>{s.print()})),f.renderTracks(this.tracks)}downloadMidi(){if(!this.score)return;let e=new _i,t=new ws(e);new Cs(this.score,this.settings,t).generate();let i=e.toBinary(),s=this.score.title?`${this.score.title}.mid`:"File.mid",a=document.createElement("a");a.download=s;let r=new Blob([i],{type:"audio/midi"}),n=URL.createObjectURL(r);a.href=n,a.style.display="none",document.body.appendChild(a),a.click(),document.body.removeChild(a)}changeTrackMute(e,t){let 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 ra{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 Be.error("Api","Method '"+t+"' does not exist on jQuery.alphaTab"),null}init(e,t,i){if(!t){t=new aa(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 na{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.color=new Ue(255,255,255,255),this.lineWidth=1,this.font=new Ni("Arial",10,K.Plain),this.textAlign=P.Left,this.textBaseline=E.Top}beginRender(e,t){this.buffer=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${0|e}px" height="${0|t}px" class="at-surface-svg">\n`,this._currentPath="",this._currentPathIsEmpty=!0,this.textBaseline=E.Top}beginGroup(e){this.buffer+=`<g class="${e}">`}endGroup(){this.buffer+="</g>"}endRender(){return this.buffer+="</svg>",this.buffer}fillRect(e,t,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!==P.Left&&(s+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),s+=`>${na.escapeText(e)}</text>`,this.buffer+=s}static escapeText(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}getSvgTextAlignment(e){switch(e){case P.Left:return"start";case P.Center:return"middle";case P.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case E.Top:return'dominant-baseline="hanging"';case E.Bottom:return'dominant-baseline="bottom"';default:return""}}measureText(e){return e?ds.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 oa extends na{constructor(){super()}fillMusicFontSymbol(e,t,i,s,a){s!==x.None&&this.fillMusicFontSymbolText(e,t,i,`&#${s};`,a)}fillMusicFontSymbols(e,t,i,s,a){let r="";for(let e of s)e!==x.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(P.Center)+'"'),this.buffer+=`>${s}</text></g>`}}class ha{constructor(){this.isInAccolade=!0,this.isRelevantForBoundsLookup=!0,this.hideOnMultiTrack=!1,this.hideOnPercussionTrack=!1}canCreate(e,t){return!this.hideOnPercussionTrack||!t.isPercussion}}!function(e){e[e.PreNotes=0]="PreNotes",e[e.OnNotes=1]="OnNotes",e[e.MiddleNotes=2]="MiddleNotes",e[e.Stem=3]="Stem",e[e.PostNotes=4]="PostNotes",e[e.EndBeat=5]="EndBeat"}(ae||(ae={}));class la extends Ls{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 da extends la{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 ca extends la{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===g.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)+As.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)}}ca.KeySizeBeat="Beat",function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Sharp=2]="Sharp",e[e.Flat=3]="Flat",e[e.NaturalQuarterNoteUp=4]="NaturalQuarterNoteUp",e[e.SharpQuarterNoteUp=5]="SharpQuarterNoteUp",e[e.FlatQuarterNoteUp=6]="FlatQuarterNoteUp",e[e.DoubleSharp=7]="DoubleSharp",e[e.DoubleFlat=8]="DoubleFlat"}(re||(re={}));class ua{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class pa{constructor(e){this._registeredAccidentals=new Map,this._appliedScoreLines=new Map,this._appliedScoreLinesByValue=new Map,this._notesByValue=new Map,this._beatLines=new Map,this.maxLineBeat=null,this.minLineBeat=null,this.maxLine=-1e3,this.minLine=-1e3,this._barRenderer=e,this._bar=e.bar}static getPercussionLine(e,t){var i,s;return t<e.staff.track.percussionArticulations.length?e.staff.track.percussionArticulations[t].staffLine:null!==(s=null===(i=Ne.getArticulationByValue(t))||void 0===i?void 0:i.staffLine)&&void 0!==s?s:0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case y.ForceDoubleFlat:t+=2;break;case y.ForceDoubleSharp:t-=2;break;case y.ForceFlat:t+=1;break;case y.ForceSharp:t-=1}return t}applyAccidental(e){const t=pa.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=pa.getNoteValue(t);if(e.staff.isPercussion)i=pa.getPercussionLine(e,s);else{const a=t?t.accidentalMode:y.Default;i=pa.calculateNoteLine(e,s,a)}return i}getAccidental(e,t,i,s,a=null){let r=re.None,n=0;if(this._bar.staff.isPercussion)n=pa.getPercussionLine(this._bar,e);else{const i=a?a.accidentalMode:y.Default;n=pa.calculateNoteLine(this._bar,e,i);let s=this._bar.masterBar.keySignature+7,o=e%12,h=s<7?re.Flat:re.Sharp,l=pa.KeySignatureLookup[s][o],d=pa.AccidentalNotes[o];if(t)switch(r=d?h:re.Natural,r){case re.Natural:r=re.NaturalQuarterNoteUp;break;case re.Sharp:r=re.SharpQuarterNoteUp;break;case re.Flat:r=re.FlatQuarterNoteUp}else{switch(i){case y.ForceSharp:r=re.Sharp;break;case y.ForceDoubleSharp:r=re.DoubleSharp;break;case y.ForceFlat:r=re.Flat;break;case y.ForceDoubleFlat:r=re.DoubleFlat;break;default:d?r=h:l&&(r=re.Natural)}let e=!1;if(a&&a.isTieDestination&&0===a.beat.index){const t=this._barRenderer.previousRenderer;if(t){t.accidentalHelper.getNoteLine(a.tieOrigin)===n&&(e=!0)}}e?r=re.None:r!==re.None?(this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===r&&(r=re.None):l&&r===h&&(r=re.None),r!==re.None&&this._registeredAccidentals.set(n,r)):this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===re.Natural?r=re.None:(r=re.Natural,this._registeredAccidentals.set(n,r)):this._registeredAccidentals.delete(n)}}return a?(this._appliedScoreLines.set(a.id,n),this._notesByValue.set(e,a)):this._appliedScoreLinesByValue.set(e,n),(-1e3===this.minLine||this.minLine<n)&&(this.minLine=n,this.minLineBeat=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 ua,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=pa.OctaveSteps[r];return h-=o*pa.StepsPerOctave,h-=(ke.keySignatureIsSharp(a)||ke.keySignatureIsNatural(a)?pa.SharpNoteSteps:pa.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}}pa.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]],pa.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],pa.StepsPerOctave=7,pa.OctaveSteps=[38,32,30,26,38],pa.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],pa.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class ga{constructor(){this.staffId="",this.up=0,this.down=0}}class fa{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 ma{get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}get hasLine(){return 1===this.beats.length&&this.beats[0].duration>u.Whole}get hasFlag(){return 1===this.beats.length&&!this.beats[0].isRest&&(this.beats[0].duration>u.Quarter||this.beats[0].graceType!==g.None)}constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=u.QuadrupleWhole,this.fingeringCount=0,this.hasTuplet=!1,this._firstBeatLowestNoteCompareValue=-1,this._firstBeatHighestNoteCompareValue=-1,this._lastBeatLowestNoteCompareValue=-1,this._lastBeatHighestNoteCompareValue=-1,this.lowestNoteInHelper=null,this._lowestNoteCompareValueInHelper=-1,this.highestNoteInHelper=null,this._highestNoteCompareValueInHelper=-1,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isGrace=!1,this.minRestLine=null,this.beatOfMinRestLine=null,this.maxRestLine=null,this.beatOfMaxRestLine=null,this.direction=H.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}getBeatLineX(e){return this.hasBeatLineX(e)?this.direction===H.Up?this._beatLineXPositions.get(e.index).up:this._beatLineXPositions.get(e.index).down:0}hasBeatLineX(e){return this._beatLineXPositions.has(e.index)}registerBeatLineX(e,t,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 ga),this._beatLineXPositions.get(e.index)}finish(){this.direction=this.calculateDirection()}calculateDirection(){let e=null;if(this.voice?null!==this.preferredBeamDirection?e=this.preferredBeamDirection:this.voice.index>0?e=this.invert(H.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==g.None)&&(e=this.invert(H.Up)):e=H.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){let t=this._renderer.getNoteY(this.highestNoteInHelper,ne.Center),i=this._renderer.getNoteY(this.lowestNoteInHelper,ne.Center);if(null===e){const s=(t+i)/2;e=this.invert(this._renderer.middleYPosition<s?H.Up:H.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(H.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:return[2,2];case u.Whole:return[0,1];case u.Half:return[1,0];case u.Quarter:return[3,3];case u.Eighth:return[2,2];case u.Sixteenth:return[2,4];case u.ThirtySecond:return[4,4];case u.SixtyFourth:return[4,6];case u.OneHundredTwentyEighth:return[6,6];case u.TwoHundredFiftySixth:return[6,8]}return[0,0]}applyRest(e,t){if(this._lastNonRestBeat&&e.index>=this._lastNonRestBeat.index||this._firstNonRestBeat&&e.index<=this._firstNonRestBeat.index)return;let i=t,s=t;const a=ma.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===H.Down?H.Up:H.Down:e}checkBeat(e){e.invertBeamDirection&&(this.invertBeamDirection=!0),this.voice||(this.voice=e.voice);let t=!1;if(0===this.beats.length)t=!0;else switch(this.beats[this.beats.length-1].beamingMode){case F.Auto:t=ma.canJoin(this.beats[this.beats.length-1],e);break;case F.ForceSplitToNext:t=!1;break;case F.ForceMergeWithNext:t=!0}if(t){if(null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.isRest)0===this.beats.length&&this.beats.push(e);else{this.isRestBeamHelper&&(this.beats=[]),this.beats.push(e),e.graceType!==g.None&&(this.isGrace=!0),e.hasTuplet&&(this.hasTuplet=!0);let t=0;for(let i=0;i<e.notes.length;i++){let s=e.notes[i];s.leftHandFinger===f.Unknown&&s.rightHandFinger===f.Unknown||t++}t>this.fingeringCount&&(this.fingeringCount=t),this.checkNote(e.minNote),this.checkNote(e.maxNote),this.shortestDuration<e.duration&&(this.shortestDuration=e.duration),this._firstNonRestBeat||(this._firstNonRestBeat=e),this._lastNonRestBeat=e}e.hasTuplet&&(this.hasTuplet=!0)}return t}checkNote(e){if(!e)return;let t,i;this.voice&&e.isPercussion?(t=-pa.getPercussionLine(this.voice.bar,pa.getNoteValue(e)),i=t):(t=pa.getNoteValue(e),i=t,e.harmonicType!==m.None&&e.harmonicType!==m.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===g.BendGrace||t.graceType===g.BendGrace)return!1;if(e.graceType!==g.None&&t.graceType!==g.None)return!0;let i=e.voice.bar;if(i!==t.voice.bar)return!1;let s=e.playbackStart,a=t.playbackStart;if(!ma.canJoinDuration(e.duration)||!ma.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=ye.QuarterTime;if(8===i.masterBar.timeSignatureDenominator)i.masterBar.timeSignatureNumerator%3==0&&(r+=ye.QuarterTime/2|0);return(0|(r+s)/r)===(0|(r+a)/r)}static canJoinDuration(e){switch(e){case u.Whole:case u.Half:case u.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,i){return ke.getIndex(e.duration)-2-i>0&&ke.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 ya{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class ba{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new ya(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 Sa{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 ba(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=ma.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 _a{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this._renderer=e,this.collisionHelper=new Sa}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!==g.None?n=s:(n=i,s=null),n&&n.checkBeat(o)||(n&&n.finish(),n=new ma(t.staff,e),n.checkBeat(o),o.graceType!==g.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)}}!function(e){e[e.TopWithStem=0]="TopWithStem",e[e.Top=1]="Top",e[e.Center=2]="Center",e[e.Bottom=3]="Bottom",e[e.BottomWithStem=4]="BottomWithStem"}(ne||(ne={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(oe||(oe={}));class wa{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 da,this._voiceContainers=new Map,this._postBeatGlyphs=new da,this._ties=[],this.x=0,this.y=0,this.width=0,this.height=0,this.index=0,this.topOverflow=0,this.bottomOverflow=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this._wasFirstOfLine=!1,this._appliedLayoutingInfo=0,this.isFinalized=!1,this.topPadding=0,this.bottomPadding=0,this.scoreRenderer=e,this.bar=t,t&&(this.helpers=new _a(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 isFirstOfLine(){return 0===this.index}get isLast(){return!this.bar||this.bar.index===this.scoreRenderer.layout.lastBarIndex}registerLayoutingInfo(){let e=this.layoutingInfo,t=this._preBeatGlyphs.width;e.preBeatSize<t&&(e.preBeatSize=t);for(const t of this._voiceContainers.values())t.registerLayoutingInfo(e);let 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)}return this._postBeatGlyphs.x=Math.floor(e),this._postBeatGlyphs.width=this.layoutingInfo.postBeatSize,this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),!0}finalizeRenderer(){this.isFinalized=!0;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 da,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new da,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 ca(0,0,t);i.renderer=this,this._voiceContainers.set(this.bar.voices[e].index,i)}}this.bar.simileMark===o.SecondOfDouble&&(this.canWrap=!1),this.createPreBeatGlyphs(),this.createBeatGlyphs(),this.createPostBeatGlyphs(),this.updateSizes();for(const e of this.helpers.beamHelpers)for(const t of e)t.finish()}}hasVoiceContainer(e){return!e.isEmpty||0===e.index}updateSizes(){this.staff.registerStaffTop(this.topPadding),this.staff.registerStaffBottom(this.height-this.bottomPadding);let e=this._voiceContainers,t=this.beatGlyphsStart,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){var t,i;return null===(i=null===(t=this.getVoiceContainer(e.voice))||void 0===t?void 0:t.beatGlyphs)||void 0===i?void 0:i[e.index]}getPreNotesGlyphForBeat(e){var t;return null===(t=this.getBeatContainer(e))||void 0===t?void 0:t.preNotes}getOnNotesGlyphForBeat(e){var t;return null===(t=this.getBeatContainer(e))||void 0===t?void 0:t.onNotes}paint(e,t,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 us;s.bar=this.bar,s.visualBounds=new at,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 at,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=ae.PreNotes){let i=this.getBeatContainer(e);if(i)switch(t){case ae.PreNotes:return i.voiceContainer.x+i.x;case ae.OnNotes:return i.voiceContainer.x+i.x+i.onNotes.x;case ae.MiddleNotes:return i.voiceContainer.x+i.x+i.onTimeX;case ae.Stem:const t=i.onNotes.beamingHelper?i.onNotes.beamingHelper.getBeatLineX(e):i.onNotes.x+i.onNotes.width/2;return i.voiceContainer.x+t;case ae.PostNotes:return i.voiceContainer.x+i.x+i.onNotes.x+i.onNotes.width;case ae.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 da,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()),this.updateSizes(),this.registerLayoutingInfo()}paintSimileMark(e,t,i){switch(this.bar.simileMark){case o.Simple:i.fillMusicFontSymbol(e+this.x+(this.width-20*this.scale)/2,t+this.y+this.height/2,1,x.Repeat1Bar,!1);break;case o.SecondOfDouble:i.fillMusicFontSymbol(e+this.x-28*this.scale/2,t+this.y+this.height/2,1,x.Repeat2Bars,!1)}}completeBeamingHelper(e){}}wa.LineSpacing=8,wa.StemWidth=.12*wa.LineSpacing,wa.StaffLineThickness=.13*wa.LineSpacing,wa.BeamThickness=.5*wa.LineSpacing,wa.BeamSpacing=.25*wa.LineSpacing,function(e){e[e.SinglePreBeat=0]="SinglePreBeat",e[e.SingleOnBeat=1]="SingleOnBeat",e[e.SingleOnBeatToEnd=2]="SingleOnBeatToEnd",e[e.GroupedOnBeat=3]="GroupedOnBeat",e[e.GroupedOnBeatToEnd=4]="GroupedOnBeatToEnd",e[e.FullBar=5]="FullBar"}(he||(he={}));class Ba extends Ls{constructor(e,t){super(0,0),this._uniqueEffectGlyphs=[],this._effectGlyphs=[],this.isEmpty=!0,this.previousBand=null,this.isLinkedToPrevious=!1,this.firstBeat=null,this.lastBeat=null,this.height=0,this.slot=null,this.voice=e,this.info=t}doLayout(){super.doLayout();for(let e=0;e<this.renderer.bar.voices.length;e++)this._effectGlyphs.push(new Map),this._uniqueEffectGlyphs.push([])}createGlyph(e){if(e.voice===this.voice&&this.info.shouldCreateGlyph(this.renderer.settings,e)&&(!this.info.hideOnMultiTrack||0===this.renderer.staff.trackIndex)){if(this.isEmpty=!1,this.firstBeat&&!e.isBefore(this.firstBeat)||(this.firstBeat=e),!this.lastBeat||e.isAfter(this.lastBeat))switch(this.lastBeat=e,this.info.sizingMode){case he.SingleOnBeatToEnd:case he.GroupedOnBeatToEnd:this.lastBeat.nextBeat&&(this.lastBeat=this.lastBeat.nextBeat)}let t=this.createOrResizeGlyph(this.info.sizingMode,e);t.height>this.height&&(this.height=t.height)}}createOrResizeGlyph(e,t){let i;switch(e){case he.FullBar:case he.SinglePreBeat:case he.SingleOnBeat:case he.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 he.GroupedOnBeat:case he.GroupedOnBeatToEnd:let s=e===he.GroupedOnBeat?he.SingleOnBeat:he.SingleOnBeatToEnd;if(t.index>0||this.renderer.index>0){let e=t.previousBeat;if(this.info.shouldCreateGlyph(this.renderer.settings,e)){let 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 s=this.renderer.previousRenderer.getBand(this.voice,this.info.effectId)._effectGlyphs[t.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(he.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 he.SinglePreBeat:i=a.preNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,s.width=i.width;break;case he.SingleOnBeat:case he.GroupedOnBeat:i=a.onNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,s.width=i.width;break;case he.SingleOnBeatToEnd:case he.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 he.FullBar:s.width=this.renderer.width}}}class Ta{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class ka{constructor(){this.bands=[],this.shared=new Ta}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 va{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 ka;return this.slots.push(t),t}register(e){let t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class Na extends la{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 xa extends Na{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,i){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class Pa extends wa{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 va;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 Ba(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 As(t,this.getVoiceContainer(e));i.preNotes=new Na,i.onNotes=new xa,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 Ea extends ha{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 Pa(e,t,this._infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class Ca extends Ms{constructor(e,t,i){super(e,t),this._endingsString="",this._endings=[];for(let e=0;e<Oe.MaxAlternateEndings;e++)0!=(i&1<<e)&&this._endings.push(e)}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(Ca.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=E.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+Ca.Padding*this.scale,t+this.y*this.scale)}i.textBaseline=s}}Ca.Padding=3;class Fa{get effectId(){return this.notationElement.toString()}}class La extends Fa{get notationElement(){return k.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return he.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){return new Ca(0,0,t.voice.bar.masterBar.alternateEndings)}canExpand(e,t){return!0}}class Ma extends Ms{constructor(e,t,i,s,a=P.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 Da extends Fa{get notationElement(){return k.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Ma(0,0,"Capo. fret "+t.voice.bar.staff.capo,e.resources.effectFont,P.Left)}canExpand(e,t){return!1}}class Ia extends Fa{get notationElement(){return k.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Ma(0,0,t.chord.name,e.resources.effectFont,P.Center)}canExpand(e,t){return!1}}class Ra extends Ms{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 Aa extends Ra{constructor(e,t,i){super(ae.EndBeat),this._crescendo=c.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===c.Crescendo?(i-=Aa.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-=Aa.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()}}Aa.Padding=Is.QuarterNoteHeadWidth/2|0;class Oa extends Fa{get notationElement(){return k.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==c.None}createNewGlyph(e,t){return new Aa(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class Ga extends Ds{constructor(e,t,i){super(e,t,.6,Ga.getSymbol(i))}doLayout(){super.doLayout(),this.height=17*this.scale,this.y+=this.height/2}static getSymbol(e){switch(e){case p.PPP:return x.DynamicPPP;case p.PP:return x.DynamicPP;case p.P:return x.DynamicPiano;case p.MP:return x.DynamicMP;case p.MF:return x.DynamicMF;case p.F:return x.DynamicForte;case p.FF:return x.DynamicFF;case p.FFF:return x.DynamicFFF;default:return x.None}}}class Va extends Fa{get notationElement(){return k.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return this.internalShouldCreateGlyph(t)}internalShouldCreateGlyph(e){if(e.voice.bar.staff.track.score.stylesheet.hideDynamics||e.isEmpty||e.voice.isEmpty||e.isRest||e.graceType!==g.None)return!1;let t=this.getPreviousDynamicsBeat(e),i=0===e.voice.index&&!t||e.dynamics!==(null==t?void 0: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===g.None)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new Ga(0,0,t.dynamics)}canExpand(e,t){return!0}}class Ha extends Ms{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 Wa extends Fa{get notationElement(){return k.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.fadeIn}createNewGlyph(e,t){return new Ha}canExpand(e,t){return!0}}class za extends Ds{constructor(e,t,i){super(e,t,1,za.getSymbol(i))}static getSymbol(e){switch(e){case O.Short:return x.FermataShortAbove;case O.Medium:return x.FermataAbove;case O.Long:return x.FermataLongAbove;default:return x.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 Ua extends Fa{get notationElement(){return k.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new za(0,0,t.fermata.type)}canExpand(e,t){return!0}}class Xa extends Fa{get notationElement(){return k.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return!(0!==t.voice.index||t.isRest||e.notation.fingeringMode!==B.SingleNoteEffectBand&&e.notation.fingeringMode!==B.SingleNoteEffectBandForcePiano)&&(1===t.notes.length&&t.notes[0].isFingering)}createNewGlyph(e,t){var i;let s=f.Unknown,a=!1,r=t.notes[0];r.leftHandFinger!==f.Unknown?(s=r.leftHandFinger,a=!0):r.rightHandFinger!==f.Unknown&&(s=r.rightHandFinger);let n=null!==(i=ke.fingerToString(e.settings,t,s,a))&&void 0!==i?i:"";return new Ma(0,0,n,e.resources.fingeringFont,P.Left)}canExpand(e,t){return!0}}class Ya extends Fa{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 qa extends Ra{constructor(e){super(ae.OnNotes),this._label=e}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=ae.EndBeat,this.forceGroupedRendering=!0),super.doLayout(),this.height=this.renderer.resources.effectFont.size}paintNonGrouped(e,t,i){let s=this.renderer.resources;i.font=s.effectFont;let a=i.textAlign;i.textAlign=P.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()}}}qa.LineSpacing=3,qa.LineTopPadding=4,qa.LineTopOffset=5,qa.LineSize=8;class Ja extends Ya{get effectId(){return this._effectId}get notationElement(){return k.EffectHarmonics}constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case m.None:this._effectId="harmonics-none";break;case m.Natural:this._effectId="harmonics-natural";break;case m.Artificial:this._effectId="harmonics-artificial";break;case m.Pinch:this._effectId="harmonics-pinch";break;case m.Tap:this._effectId="harmonics-tap";break;case m.Semi:this._effectId="harmonics-semi";break;case m.Feedback:this._effectId="harmonics-feedback";break;default:this._effectId=""}}shouldCreateGlyphForNote(e){return!(!e.isHarmonic||e.harmonicType!==this._harmonicType)&&(e.beat!==this._beat&&(this._beat=e.beat),!0)}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new qa(Ja.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case m.Natural:return"N.H.";case m.Artificial:return"A.H.";case m.Pinch:return"P.H.";case m.Tap:return"T.H.";case m.Semi:return"S.H.";case m.Feedback:return"Fdbk."}return""}}class ja extends Fa{get notationElement(){return k.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new qa("LetRing")}canExpand(e,t){return!0}}class Qa extends Ms{constructor(e,t,i,s,a=P.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 $a extends Fa{get notationElement(){return k.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new Qa(0,0,t.lyrics,e.resources.effectFont,P.Center)}canExpand(e,t){return!0}}class Ka extends Fa{get notationElement(){return k.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return he.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&t.voice.bar.masterBar.isSectionStart}createNewGlyph(e,t){return new Ma(0,0,t.voice.bar.masterBar.section.marker?"["+t.voice.bar.masterBar.section.marker+"] "+t.voice.bar.masterBar.section.text:t.voice.bar.masterBar.section.text,e.resources.markerFont,P.Left)}canExpand(e,t){return!0}}class Za extends Ra{constructor(e,t){super(ae.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 n._15ma:s=37*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,x.QuindicesimaAlta,!1);break;case n._8va:s=26*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,x.OttavaAlta,!1);break;case n._8vb:s=23*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,x.OttavaBassaVb,!1);break;case n._15mb:s=36*this.scale,i.fillMusicFontSymbols(e+this.x-s/2,t+this.y+this.height,.8,[x.Quindicesima,x.OctaveBaselineM,x.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 er extends Fa{get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return k.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeat}constructor(e){super(),this._aboveStaff=e}shouldCreateGlyph(e,t){switch(t.ottava){case n._15ma:case n._8va:return this._aboveStaff;case n._8vb:case n._15mb:return!this._aboveStaff}return!1}createNewGlyph(e,t){return new Za(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class tr extends Ya{get notationElement(){return k.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new qa("P.M.")}constructor(){super()}}class ir extends Ya{get notationElement(){return k.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===S.PickSlideDown||e.slideOutType===S.PickSlideUp}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new qa("P.S.")}constructor(){super()}}class sr extends Ds{constructor(e,t,i){super(e,t,Is.GraceScale,sr.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 x.StringsUpBow;case N.Down:return x.StringsDownBow;default:return x.None}}}class ar extends Fa{get notationElement(){return k.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==N.None}createNewGlyph(e,t){return new sr(0,0,t.pickStroke)}canExpand(e,t){return!0}}class rr extends Ra{constructor(e){super(ae.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 nr extends Fa{get notationElement(){return k.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===_.Slight}createNewGlyph(e,t){return new rr(_.Slight)}canExpand(e,t){return!0}}class or extends Ra{constructor(e,t,i,s=1.2,a=!1){super(ae.EndBeat),this._scale=0,this._symbol=x.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=x.WiggleTrill,this._symbolSize=9*this._scale,e=6*this._scale;break;case _.Wide:this._symbol=x.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 hr extends Ya{get notationElement(){return k.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===_.Slight||e.isTieDestination&&e.tieOrigin.vibrato===_.Slight}get sizingMode(){return he.GroupedOnBeatToEnd}createNewGlyph(e,t){return new or(0,0,_.Slight,1.2)}constructor(){super()}}class lr extends Fa{get notationElement(){return k.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){let i=e.resources;return t.slap?new Ma(0,0,"S",i.effectFont,P.Left):t.pop?new Ma(0,0,"P",i.effectFont,P.Left):new Ma(0,0,"T",i.effectFont,P.Left)}canExpand(e,t){return!0}}class dr extends Ms{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*Is.GraceScale,x.NoteQuarterUp,!1),i.fillText("= "+this._tempo.toString(),e+this.x+this.height/2,t+this.y+i.font.size/2)}}class cr extends Fa{get notationElement(){return k.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return he.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&(!!t.voice.bar.masterBar.tempoAutomation||0===t.voice.bar.index)}createNewGlyph(e,t){let 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 ur extends Fa{get notationElement(){return k.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Ma(0,0,t.text,e.resources.effectFont,P.Left)}canExpand(e,t){return!0}}class pr extends Ms{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,d=t+this.y+1.2*this.height;for(let t=0;t<h;t++)i.fillMusicFontSymbol(e+this.x+l,d,1.2,x.WiggleTrill,!1),l+=o}}class gr extends Ya{get notationElement(){return k.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return he.SingleOnBeat}createNewGlyph(e,t){return new pr(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(le||(le={}));class fr extends Ms{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*Is.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 I.NoTripletFeel:this.renderBarNote(a,s,fr.NoteScale,i,[le.Full]),this.renderBarNote(r,s,fr.NoteScale,i,[le.Full]);break;case I.Triplet8th:this.renderBarNote(a,s,fr.NoteScale,i,[le.Full]),i.fillMusicFontSymbol(r,s,fr.NoteScale,x.NoteQuarterUp,!1),i.fillMusicFontSymbol(r+fr.NoteSeparation*this.scale,s,fr.NoteScale,x.NoteEighthUp,!1),this.renderTriplet(r,t,i);break;case I.Triplet16th:this.renderBarNote(a,s,fr.NoteScale,i,[le.Full,le.Full]),this.renderBarNote(r,s,fr.NoteScale,i,[le.Full,le.PartialRight]),this.renderTriplet(r,t,i);break;case I.Dotted8th:this.renderBarNote(a,s,fr.NoteScale,i,[le.Full]),this.renderBarNote(r,s,fr.NoteScale,i,[le.Full,le.PartialRight]),i.fillCircle(r+9*this.scale,s,this.scale);break;case I.Dotted16th:this.renderBarNote(a,s,fr.NoteScale,i,[le.Full,le.Full]),this.renderBarNote(r,s,fr.NoteScale,i,[le.Full,le.Full,le.PartialRight]),i.fillCircle(r+9*this.scale,s,this.scale);break;case I.Scottish8th:this.renderBarNote(a,s,fr.NoteScale,i,[le.Full]),this.renderBarNote(r,s,fr.NoteScale,i,[le.Full,le.PartialLeft]),i.fillCircle(r+fr.NoteSeparation*this.scale+8*this.scale,s,this.scale);break;case I.Scottish16th:this.renderBarNote(a,s,fr.NoteScale,i,[le.Full,le.Full]),this.renderBarNote(r,s,fr.NoteScale,i,[le.Full,le.Full,le.PartialLeft]),i.fillCircle(r+fr.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,x.NoteQuarterUp,!1);let r=fr.NoteSeparation/2*this.scale;for(let i=0;i<a.length;i++)switch(a[i]){case le.Full:s.fillRect(e+4*this.scale,t-fr.NoteHeight*this.scale+fr.BarSeparation*this.scale*i,fr.NoteSeparation*this.scale,fr.BarHeight*this.scale);break;case le.PartialLeft:s.fillRect(e+4*this.scale,t-fr.NoteHeight*this.scale+fr.BarSeparation*this.scale*i,r,fr.BarHeight*this.scale);break;case le.PartialRight:s.fillRect(e+4*this.scale+r,t-fr.NoteHeight*this.scale+fr.BarSeparation*this.scale*i,r,fr.BarHeight*this.scale)}s.fillMusicFontSymbol(e+fr.NoteSeparation*this.scale,t,i,x.NoteQuarterUp,!1)}renderTriplet(e,t,i){t+=2*this.scale;let s=this.renderer.resources.effectFont;i.font=Ni.withFamilyList(s.families,.8*s.size,s.style);let a=e+fr.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}}fr.NoteScale=.4,fr.NoteHeight=12,fr.NoteSeparation=12,fr.BarHeight=2,fr.BarSeparation=3;class mr extends Fa{get notationElement(){return k.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return he.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==I.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new fr(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class yr extends Fa{get notationElement(){return k.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new qa("w/bar")}canExpand(e,t){return!0}}class br extends Fa{get notationElement(){return k.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===_.Wide}createNewGlyph(e,t){return new rr(_.Wide)}canExpand(e,t){return!0}}class Sr extends Ya{get notationElement(){return k.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===_.Wide||e.isTieDestination&&e.tieOrigin.vibrato===_.Wide}get sizingMode(){return he.GroupedOnBeatToEnd}createNewGlyph(e,t){return new or(0,0,_.Wide,1.2)}}class _r extends Ms{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=_r.FretSpacing*e:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+(_r.Frets-1)*_r.FretSpacing*e+2*_r.Padding*e,this.width=this._firstFretSpacing+(this._chord.staff.tuning.length-1)*_r.StringSpacing*e+2*_r.Padding*e}paint(e,t,i){e+=this.x+_r.Padding*this.scale+this._firstFretSpacing,t+=this.y;let s=this.width-2*_r.Padding*this.scale+this.scale-this._firstFretSpacing,a=_r.StringSpacing*this.scale,r=_r.FretSpacing*this.scale,n=this.renderer.resources,o=_r.CircleRadius*this.scale,h=i.textAlign,l=i.textBaseline;i.font=n.effectFont,i.textAlign=P.Center,i.textBaseline=E.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=E.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,x.FretboardX,!0):0===o?i.fillMusicFontSymbol(r,n,this.scale,x.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*_r.Frets+this.scale)}this._chord.firstFret>1&&(i.textAlign=P.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<=_r.Frets;a++){let n=t+a*r;i.fillRect(e,n,s,this.scale)}let d=new Map;for(let e of this._chord.barreFrets){let t=[-1,-1];d.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,d.has(n)){let e=d.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 d){let h=t+s*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-n[1]-1)*a,d=e+(this._chord.strings.length-n[0]-1)*a;i.fillRect(l,h-o,d-l,2*o)}i.textAlign=h,i.textBaseline=l}}_r.Padding=5,_r.Frets=5,_r.CircleRadius=2.5,_r.StringSpacing=10,_r.FretSpacing=12;class wr extends la{constructor(e,t,i=P.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=i}doLayout(){let e=0;switch(this._align){case P.Left:e=0;break;case P.Center:e=(this.width-this._glyphWidth)/2;break;case P.Right:e=this.width-this._glyphWidth}for(let t of this.glyphs)t.x=e,e+=t.width}addGlyphToRow(e){this.glyphs.push(e),this._glyphWidth+=e.width,e.height>this.height&&(this.height=e.height)}}class Br extends la{constructor(e,t,i=P.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=i}doLayout(){let e=0,t=0,i=2*Br.Padding*this.scale;this._rows=[];let s=new wr(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 wr(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+Br.Padding*this.scale,i)}}Br.Padding=3;class Tr extends Br{constructor(e,t){super(e,t)}addChord(e){if(e.strings.length>0){let t=new _r(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}}class kr{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 wa(this.staveGroup.layout.renderer,e),i.staff=this,i.index=this.barRenderers.length,i.layoutingInfo=t,i.doLayout(),i.registerLayoutingInfo(),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=e-this.staveGroup.width,i=t/this.barRenderers.length,s=0,a=this.topOverflow;for(let e=0,r=this.barRenderers.length;e<r;e++)this.barRenderers[e].x=s,this.barRenderers[e].y=this.topSpacing+a,0!==t&&this.barRenderers[e].scaleToWidth(this.barRenderers[e].width+i),s+=this.barRenderers[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 vr{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 Nr{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 vr,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!==g.None){const a=e.graceGroup.id;this.allGraceRods.has(a)||this.allGraceRods.set(a,new Array(e.graceGroup.beats.length)),e.graceGroup.isComplete||this.incompleteGraceRods.has(a)||this.incompleteGraceRods.set(a,new Array(e.graceGroup.beats.length));let r=this.allGraceRods.get(a)[e.graceIndex];if(r)r.postSpringWidth<i&&(r.postSpringWidth=i),r.preBeatWidth<t&&(r.preBeatWidth=t);else{const r=new vr;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=ye.toTicks(u.SixtyFourth)),0===e.smallestDuration&&(e.smallestDuration=t),e.smallestDuration/t*(1/((1+.85*Math.log2(t/Nr.MinDuration))*Nr.MinDurationWidth))}spaceToForce(e){return-1!==this.totalSpringConstant?(this._timeSortedSprings.length>0&&(e-=this._timeSortedSprings[0].preSpringWidth),e-=this._incompleteGraceRodsWidth,Math.max(e,0)*this.totalSpringConstant):-1}calculateVoiceWidth(e){let t=0;return-1!==this.totalSpringConstant&&(t=this.calculateWidth(e,this.totalSpringConstant)),this._timeSortedSprings.length>0&&(t+=this._timeSortedSprings[0].preSpringWidth),t+=this._incompleteGraceRodsWidth,t}calculateWidth(e,t){return e/t}buildOnTimePositions(e){if(-1===this.totalSpringConstant)return new Map;if(ke.isAlmostEqualTo(this._onTimePositionsForce,e)&&this._onTimePositions)return this._onTimePositions;this._onTimePositionsForce=e;let t=new Map;this._onTimePositions=t;let 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}}Nr.MinDuration=30,Nr.MinDurationWidth=7;class xr{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.renderers=[]}}class Pr{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 Er{constructor(){this._allStaves=[],this._firstStaffInAccolade=null,this._lastStaffInAccolade=null,this._accoladeSpacingCalculated=!1,this.x=0,this.y=0,this.index=0,this.accoladeSpacing=0,this.isFull=!1,this.width=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[]}get firstBarIndex(){return this.masterBarsRenderers[0].masterBar.index}get lastBarIndex(){return this.masterBarsRenderers[this.masterBarsRenderers.length-1].masterBar.index}addMasterBarRenderers(e,t){if(0===e.length)return null;this.masterBarsRenderers.push(t),this.calculateAccoladeSpacing(e),t.layoutingInfo.preBeatSize=0;let 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.updateWidth(),t}addBars(e,t){if(0===e.length)return null;let i=new xr;i.layoutingInfo=new Nr,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.updateWidth(),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;for(let e=0,i=this._allStaves.length;e<i;e++){let i=this._allStaves[e].revertLastBar();t=Math.max(t,i.width)}return this.width-=t,e}return null}updateWidth(){let e=0;for(let t=0,i=this._allStaves.length;t<i;t++){let i=this._allStaves[t];i.barRenderers[i.barRenderers.length-1].applyLayoutingInfo(),i.barRenderers[i.barRenderers.length-1].width>e&&(e=i.barRenderers[i.barRenderers.length-1].width)}return this.width+=e,e}calculateAccoladeSpacing(e){if(!this._accoladeSpacingCalculated&&0===this.index)if(this._accoladeSpacingCalculated=!0,this.layout.renderer.settings.notation.isNotationElementVisible(k.TrackNames)){let t=this.layout.renderer.canvas,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*Er.AccoladeLabelSpacing*this.layout.scale,this.width+=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 Pr(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,d=r+4*o;0===this.index&&this.layout.renderer.settings.notation.isNotationElementVisible(k.TrackNames)&&i.fillText(a.track.shortName,e+Er.AccoladeLabelSpacing*this.layout.scale,s),i.fillRect(n-h-o,l,o,d-l);let c=n-h-o,u=n+2*o;i.beginPath(),i.moveTo(c,l),i.bezierCurveTo(c,l,c,l,u,l-o),i.bezierCurveTo(n,l+o,c,l+o,c,l+o),i.closePath(),i.fill(),i.beginPath(),i.moveTo(c,d),i.bezierCurveTo(c,d,n,d,u,d+o),i.bezierCurveTo(n,d-o,c,d-o,c,d-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,d=n-r,c=this.x+this._firstStaffInAccolade.x,u=new ms;u.visualBounds=new at,u.visualBounds.x=e,u.visualBounds.y=t+this.y,u.visualBounds.w=this.width,u.visualBounds.h=this.height,u.realBounds=new at,u.realBounds.x=e,u.realBounds.y=t+this.y,u.realBounds.w=this.width,u.realBounds.h=this.height,this.layout.renderer.boundsLookup.addStaveGroup(u);let p=new Map;for(let e=0;e<this.staves.length;e++)for(let 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 gs,a.index=e.bar.masterBar.index,a.isFirstOfLine=e.isFirstOfLine,a.realBounds=new at,a.realBounds.x=c+e.x,a.realBounds.y=r,a.realBounds.w=e.width,a.realBounds.h=d,a.visualBounds=new at,a.visualBounds.x=c+e.x,a.visualBounds.y=s,a.visualBounds.w=e.width,a.visualBounds.h=h,a.lineAlignedBounds=new at,a.lineAlignedBounds.x=c+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,c,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}}Er.AccoladeLabelSpacing=10;class Cr extends la{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 Ma(0,this.height,this._trackLabel,i.effectFont,P.Left)),this.height+=s),this.addGlyph(new Ma(0,this.height,e.name,i.effectFont,P.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=Cr.CircleNumberHeight*r*t;let o=0|Math.ceil(e.tunings.length/2),h=0,l=this.height;for(let d=0,c=e.tunings.length;d<c;d++){const c=x.GuitarString0+(d+1);this.addGlyph(new Ds(h,l+n/1.2,r,c));const u="= "+Ye.getTextForTuning(e.tunings[d],!1);this.addGlyph(new Ma(h+n+1*t,l,u,i.effectFont,P.Left)),l+=s,d===o-1&&(l=this.height,h+=a)}this.height+=o*s}this.width+=15*t}}Cr.CircleNumberHeight=20;class Fr extends Br{constructor(e,t){super(e,t,P.Left)}addTuning(e,t){if(e.tunings.length>0){let i=new Cr(0,0,e,t);i.renderer=this.renderer,i.doLayout(),this.glyphs.push(i)}}}class Lr{constructor(e,t){this.args=e,this.renderCallback=t}}class Mr{constructor(e){this._barRendererLookup=new Map,this.width=0,this.height=0,this.scoreInfoGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t)),this.firstBarIndex=t;let 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.partialLayoutFinished.trigger(e),this.renderer.settings.core.enableLazyLoading?this._lazyPartials.set(e.id,new Lr(e,t)):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(){Be.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(k.ScoreTitle)&&this.scoreInfoGlyphs.set(k.ScoreTitle,new Ma(0,0,t.title,i.titleFont,P.Center)),t.subTitle&&e.isNotationElementVisible(k.ScoreSubTitle)&&this.scoreInfoGlyphs.set(k.ScoreSubTitle,new Ma(0,0,t.subTitle,i.subTitleFont,P.Center)),t.artist&&e.isNotationElementVisible(k.ScoreArtist)&&this.scoreInfoGlyphs.set(k.ScoreArtist,new Ma(0,0,t.artist,i.subTitleFont,P.Center)),t.album&&e.isNotationElementVisible(k.ScoreAlbum)&&this.scoreInfoGlyphs.set(k.ScoreAlbum,new Ma(0,0,t.album,i.subTitleFont,P.Center)),t.music&&t.music===t.words&&e.isNotationElementVisible(k.ScoreWordsAndMusic)?this.scoreInfoGlyphs.set(k.ScoreWordsAndMusic,new Ma(0,0,"Music and Words by "+t.words,i.wordsFont,P.Center)):(t.music&&e.isNotationElementVisible(k.ScoreMusic)&&this.scoreInfoGlyphs.set(k.ScoreMusic,new Ma(0,0,"Music by "+t.music,i.wordsFont,P.Right)),t.words&&e.isNotationElementVisible(k.ScoreWords)&&this.scoreInfoGlyphs.set(k.ScoreWords,new Ma(0,0,"Words by "+t.words,i.wordsFont,P.Left)));const s=new wa(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);if(e.isNotationElementVisible(k.GuitarTuning)){let e=[];for(let t of this.renderer.tracks)for(let 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 Fr(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(k.ChordDiagrams)){this.chordDiagrams=new Tr(0,0),this.chordDiagrams.renderer=s;let e=new Map;for(let t of this.renderer.tracks)for(let i of t.staves){const t=i.chords;if(t)for(const[i,s]of t)e.has(i)||s.showDiagram&&(e.set(i,s),this.chordDiagrams.addChord(s))}}}get scale(){return this.renderer.settings.display.scale}createEmptyStaveGroup(){let e=new Er;e.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=t.Score;else if(this.renderer.settings.display.staveProfile!==t.Default)n=this.renderer.settings.display.staveProfile;else if(o.showTablature&&o.showStandardNotation)n=t.ScoreTab;else if(o.showTablature)n=a?t.TabMixed:t.Tab;else{if(!o.showStandardNotation)continue;n=t.Score}let h=go.staveProfiles.get(n);for(let t of h)t.canCreate(s,o)&&e.addStaff(s,new kr(i,o,t))}}return e}registerBarRenderer(e,t){this._barRendererLookup.has(e)||this._barRendererLookup.set(e,new Map),this._barRendererLookup.get(e).set(t.bar.id,t)}unregisterBarRenderer(e,t){if(this._barRendererLookup.has(e)){this._barRendererLookup.get(e).delete(t.bar.id)}}getRendererForBar(e,t){let 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 cs,n=Ni.withFamilyList(i.copyrightFont.families,s,K.Plain,Z.Bold);this.renderer.canvas.font=n;const o=go.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=P.Left,e.fillText(t,0,s)})),e+a}}class Dr{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class Ir extends Mr{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(){this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=Ir.PagePadding),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t));let i=t,s=this.renderer.settings.display.barCount;s<=0&&(s=e.masterBars.length),s=t+s-1,s=Math.min(e.masterBars.length-1,Math.max(0,s)),this._group=this.createEmptyStaveGroup(),this._group.isLast=!0,this._group.x=this._pagePadding[0],this._group.y=this._pagePadding[1];let a=this.renderer.settings.display.barCountPerPartial,r=[],n=new Dr,o=0;for(;i<=s;){let t=this._group.addBars(this.renderer.tracks,i);if(t)if(0===n.masterBars.length&&t.isLinkedToPrevious&&r.length>0){let s=r[r.length-1];s.masterBars.push(e.masterBars[i]),s.width+=t.width,o+=t.width,n.x+=o}else n.masterBars.push(e.masterBars[i]),n.width+=t.width,n.masterBars.length>=a&&(0===r.length&&(n.width+=this._group.accoladeSpacing+this._pagePadding[0]),o+=n.width,r.push(n),Be.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null),n=new Dr,n.x=o);i++}n.masterBars.length>0&&(0===r.length&&(n.width+=this._group.accoladeSpacing+this._pagePadding[0]),r.push(n),Be.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null)),this.finalizeGroup(),this.height=Math.floor(this._group.y+this._group.height),this.width=this._group.x+this._group.width+this._pagePadding[2],i=0;let h=0;for(let e=0;e<r.length;e++){const t=r[e],s=new cs;s.x=h,s.y=0,s.totalWidth=this.width,s.totalHeight=this.height,s.width=t.width,s.height=this.height,s.firstMasterBarIndex=t.masterBars[0].index,s.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,h+=t.width;const a=i,n=e;this._group.buildBoundingsLookup(this._group.x,this._group.y),this.registerPartial(s,(e=>{let i=this._group.getBarX(t.masterBars[0].index)+this._group.accoladeSpacing;0===n&&(i-=this._group.x+this._group.accoladeSpacing),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=P.Left,Be.debug(this.name,"Rendering partial from bar "+t.masterBars[0].index+" to "+t.masterBars[t.masterBars.length-1].index,null),this._group.paintPartial(-i,this._group.y,e,a,t.masterBars.length)})),i+=t.masterBars.length}this.height=this.layoutAndRenderAnnotation(this.height)+this._pagePadding[3]}finalizeGroup(){this._group.scaleToWidth(this._group.width),this._group.finalizeGroup()}}Ir.PagePadding=[20,20,20,20],Ir.GroupSpacing=20;class Rr extends Mr{get name(){return"PageView"}constructor(e){super(e),this._groups=[],this._allMasterBarRenderers=[],this._barsFromPreviousGroup=[],this._pagePadding=null}doLayoutAndRender(){this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=Rr.PagePadding),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let e=0;this.width=this.renderer.width,this._allMasterBarRenderers=[],e=this.layoutAndRenderScoreInfo(e,-1),e=this.layoutAndRenderTunings(e,-1),e=this.layoutAndRenderChordDiagrams(e,-1),e=this.layoutAndRenderScore(e),e=this.layoutAndRenderAnnotation(e),this.height=e+this._pagePadding[3]}get supportsResize(){return!0}get firstBarX(){let e=this._pagePadding[0];return this._groups.length>0&&(e+=this._groups[0].accoladeSpacing),e}doResize(){let e=0;this.width=this.renderer.width;let t=this.height;e=this.layoutAndRenderScoreInfo(e,t),e=this.layoutAndRenderTunings(e,t),e=this.layoutAndRenderChordDiagrams(e,t),e=this.resizeAndRenderScore(e,t),e=this.layoutAndRenderAnnotation(e),this.height=e+this._pagePadding[3]}layoutAndRenderTunings(e,t=-1){if(!this.tuningGlyph)return e;let 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 cs;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=P.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 cs;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=P.Center,this.chordDiagrams.paint(0,0,e)})),e+s}layoutAndRenderScoreInfo(e,t=-1){Be.debug(this.name,"Layouting score info");const i=new cs;i.x=0,i.y=e;let s=this._pagePadding[1],a=this.scale,r=this.renderer.settings.display.resources,n=[k.ScoreTitle,k.ScoreSubTitle,k.ScoreArtist,k.ScoreAlbum,k.ScoreWordsAndMusic];for(let e=0;e<n.length;e++)if(this.scoreInfoGlyphs.has(n[e])){let t=this.scoreInfoGlyphs.get(n[e]);t.x=this.width/2,t.y=s,t.textAlign=P.Center,s+=t.font.size*a}let o=!1,h=0;if(this.scoreInfoGlyphs.has(k.ScoreMusic)){let e=this.scoreInfoGlyphs.get(k.ScoreMusic);e.x=this.width-this._pagePadding[2],e.y=s,e.textAlign=P.Right,o=!0,h=e.font.size*a}if(this.scoreInfoGlyphs.has(k.ScoreWords)){let e=this.scoreInfoGlyphs.get(k.ScoreWords);e.x=this._pagePadding[0],e.y=s,e.textAlign=P.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=P.Center;for(const t of this.scoreInfoGlyphs.values())t.paint(0,0,e)})),e+s}resizeAndRenderScore(e,t){if(-1!==this.renderer.settings.display.barsPerRow)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),Be.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 cs;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=P.Left,e.paint(0,-s.y,t)})),t+=i,i}fitGroup(e){e.isFull||e.width>this.maxWidth?e.scaleToWidth(this.maxWidth):e.scaleToWidth(e.width),e.finalizeGroup()}createStaveGroup(e,t){let i=this.createEmptyStaveGroup();i.index=this._groups.length;let s=this.renderer.settings.display.barsPerRow,a=this.maxWidth,r=t+1,n=e;for(;n<r;){if(this._barsFromPreviousGroup.length>0)for(let e of this._barsFromPreviousGroup)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]}}Rr.PagePadding=[40,40,40,40],Rr.GroupSpacing=20;class Ar extends Ds{constructor(e,t,i,s=!1){super(e,t,s?Is.GraceScale:1,Ar.getMusicSymbol(i)),this._isGrace=s,this._accidentalType=i}static getMusicSymbol(e){switch(e){case re.Natural:return x.AccidentalNatural;case re.Sharp:return x.AccidentalSharp;case re.Flat:return x.AccidentalFlat;case re.NaturalQuarterNoteUp:return x.AccidentalQuarterToneNaturalArrowUp;case re.SharpQuarterNoteUp:return x.AccidentalQuarterToneSharpArrowUp;case re.FlatQuarterNoteUp:return x.AccidentalQuarterToneFlatArrowUp;case re.DoubleSharp:return x.AccidentalDoubleSharp;case re.DoubleFlat:return x.AccidentalDoubleFlat}return x.None}doLayout(){if(this._accidentalType===re.DoubleFlat)this.width=18;else this.width=8;this.width=this.width*(this._isGrace?Is.GraceScale:1)*this.scale}}class Or extends Ls{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 Gr extends Ls{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 Vr extends Ds{constructor(e,t,i,s){super(e,t,1,Vr.getSymbol(i)),this._clef=i,this._clefOttava=s}doLayout(){switch(this._clef){case r.Neutral:this.width=15*this.scale;break;case r.C3:case r.C4:case r.F4:case r.G2:this.width=28*this.scale}}static getSymbol(e){switch(e){case r.Neutral:return x.UnpitchedPercussionClef1;case r.C3:case r.C4:return x.CClef;case r.F4:return x.FClef;case r.G2:return x.GClef;default:return x.None}}paint(e,t,i){let s;super.paint(e,t,i);let a=!1;switch(this._clefOttava){case n._15ma:s=new Ds(-4*this.scale,0,.5,x.Quindicesima),a=!0;break;case n._8va:s=new Ds(-2*this.scale,0,.5,x.Ottava),a=!0;break;case n._8vb:s=new Ds(-6*this.scale,0,.5,x.Ottava);break;case n._15mb:s=new Ds(-8*this.scale,0,.5,x.Quindicesima);break;default:return}let o=0,h=0;switch(this._clef){case r.Neutral:o=a?-12:15,h=0;break;case r.C3:case r.C4:o=a?-19:27,h=0;break;case r.F4:o=a?-9:27,h=-4;break;case r.G2:o=a?-37:30,h=0;break;default:return}s.renderer=this.renderer,s.doLayout();let l=this.width/2;s.paint(e+this.x+l+h*this.scale,t+this.y+o*this.scale,i)}}class Hr extends Ls{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 Wr extends Ls{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=P.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 zr extends Ls{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 Ur extends Ds{constructor(e,t,i){super(e,t,1,Ur.getSymbol(i))}static getSymbol(e){switch(e){case s.None:return x.None;case s.Normal:return x.ArticAccentAbove;case s.Heavy:return x.ArticMarcatoAbove;default:return x.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 Xr extends Ls{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 Yr extends Ds{constructor(e,t,i){super(e,t,i?Is.GraceScale:1,x.NoteheadXOrnate),this._isGrace=i}doLayout(){this.width=9*(this._isGrace?Is.GraceScale:1)*this.scale,this.height=Is.NoteHeadHeight*this.scale}}class qr extends Ds{constructor(e,t,i,s){super(e,t,s?Is.GraceScale:1,qr.getSymbol(i)),this._isGrace=s}static getSymbol(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:case u.Whole:case u.Half:return x.NoteheadDiamondWhiteWide;default:return x.NoteheadDiamondBlackWide}}doLayout(){this.width=9*(this._isGrace?Is.GraceScale:1)*this.scale,this.height=Is.NoteHeadHeight*this.scale}}class Jr extends Ls{constructor(e,t,i){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=H.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=Jr.calculateActualTieHeight(this.renderer.scale,this._startX,this._startY,this._endX,this._endY,this.tieDirection===H.Down,this._tieHeight,4).h),this.tieDirection===H.Up&&(this.y-=this.height))}paint(e,t,i){this._shouldDraw&&(this.shouldDrawBendSlur()?Jr.drawBendSlur(i,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===H.Down,this.scale):Jr.paintTie(i,this.scale,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===H.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,i,s){return 22}getBeamDirection(e,t){return H.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=Jr.computeBezierControlPoints(e,t,i,s,a,r,n,o);t=h[0],i=h[1];const l=h[2],d=h[3];s=h[6],a=h[7];const c=(t-l)/(t-2*l+s),u=Jr.calculateExtrema(t,i,l,d,s,a,c),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-d)/(i-2*d+a),m=Jr.calculateExtrema(t,i,l,d,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 at;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,d=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=d,l/=d;let c=(s+t)/2,u=(a+i)/2;return[t,i,c+n*h,u+n*l,c+(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=Jr.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,d=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=d,l/=d;let c=(s+t)/2,u=(a+i)/2,p=Jr.BendSlurHeight*n;s-t<20&&(p/=2);let g=c+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)}}}Jr.BendSlurHeight=11;class jr extends Ls{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=jr.Size*this.scale}paint(e,t,i){this._isOpen?Jr.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):Jr.paintTie(i,this.scale,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3)}}jr.Size=6;class Qr{constructor(e,t){this.line=0,this.line=e,this.isGhost=t}}class $r extends Ls{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(k.ParenthesisOnTiedBends);this.addParenthesisOnLine(i,s)}addParenthesisOnLine(e,t){let i=new Qr(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 jr(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 Kr{constructor(e,t){this.line=0,this.glyph=e,this.line=t}}class Zr extends Ls{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new fi,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){let i=new Kr(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===H.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===H.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 en extends Ds{constructor(e,t,i){super(e,t,1,en.getSymbol(i))}doLayout(){this.width=12*this.scale}static getSymbol(e){switch(e){case u.ThirtySecond:return x.Tremolo3;case u.Sixteenth:return x.Tremolo2;case u.Eighth:return x.Tremolo1;default:return x.None}}}class tn extends Zr{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 oe.Left:break;case oe.Center:s+=i.width/2;break;case oe.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 ne.TopWithStem:s-=this.renderer.getStemSize(this.beamingHelper);break;case ne.Top:s-=i.height/2;break;case ne.Center:break;case ne.Bottom:s+=i.height/2;break;case ne.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===H.Up?this.minNote:this.maxNote,s=e===H.Up?this.displacedX:0,a=this.beat.tremoloSpeed;switch(a){case u.ThirtySecond:t=e===H.Up?-15:15;break;case u.Sixteenth:t=e===H.Up?-12:15;break;case u.Eighth:t=e===H.Up?-10:10;break;default:t=e===H.Up?-10:15}this._tremoloPicking=new en(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 fs;r.note=s,r.noteHeadBounds=new at,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===H.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 sn extends Ds{constructor(e,t,i){super(e,t,1,sn.getSymbol(i)),this._duration=i}static getSymbol(e){switch(e){case u.QuadrupleWhole:return x.RestLonga;case u.DoubleWhole:return x.RestDoubleWhole;case u.Whole:return x.RestWhole;case u.Half:return x.RestHalf;case u.Quarter:return x.RestQuarter;case u.Eighth:return x.RestEighth;case u.Sixteenth:return x.RestSixteenth;case u.ThirtySecond:return x.RestThirtySecond;case u.SixtyFourth:return x.RestSixtyFourth;case u.OneHundredTwentyEighth:return x.RestOneHundredTwentyEighth;case u.TwoHundredFiftySixth:return x.RestTwoHundredFiftySixth;default:return x.None}}static getSize(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:case u.Whole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:return 9;case u.ThirtySecond:return 12;case u.SixtyFourth:return 14;case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:return 20}return 10}doLayout(){this.width=sn.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 an{constructor(){this.x=0,this.y=-3e3,this.width=0}}class rn extends la{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 an);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 an);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 nn extends Zr{get direction(){return H.Up}constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new rn,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new $r(!0),this._postNoteParenthesis=new $r(!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 Is(0,0,u.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!==re.None){let e=new Ar(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+nn.ElementPadding*this.scale),this._accidentals.isEmpty||(e+=this._accidentals.width+nn.ElementPadding*this.scale,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+nn.ElementPadding*this.scale),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+nn.ElementPadding*this.scale,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+nn.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)}}nn.ElementPadding=2;class on extends Ls{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,i,s,a,r,n,o){Jr.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)===H.Up?H.Down:H.Up}}on.EndPadding=8;class hn extends be{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class ln extends Ls{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 l.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 l.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 l.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 l.Prebend:i=t[0].value,(-1===this._preBendMinValue||i<this._preBendMinValue)&&(this._preBendMinValue=i);break;case l.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 l.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*ln.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 l.Bend:i[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case l.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[1].lineValue=t);break;case l.BendRelease:i[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[2].lineValue=t);break;case l.Prebend:i[0].lineValue=this._preBendMinValue;break;case l.PrebendBend:i[0].lineValue=this._preBendMinValue,i[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case l.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 l.Custom:for(let i of e.bendPoints)t.push(new hn(i.offset,i.value));break;case l.BendRelease:t.push(new hn(0,e.bendPoints[0].value)),t.push(new hn(be.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new hn(be.MaxPosition,e.bendPoints[3].value));break;case l.Bend:case l.Hold:case l.Prebend:case l.PrebendBend:case l.PrebendRelease:case l.Release:t.push(new hn(0,e.bendPoints[0].value)),t.push(new hn(be.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,d=!1,c=null,u=!1,p=a.bendStyle===h.Gradual?"grad.":"",g=null;for(;o.isTieOrigin;){let e=o.tieDestination;if(c=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,e.beat.voice.bar),!c||n.staff!==c.staff)break;if(o=e,d=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes){u=!0;break}}g=o.beat,c=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,g.voice.bar),g.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(g=null);let f=0,m=0,y=t+n.y;f=e+n.x,r[0].value>0||a.isContinuedBend?f+=n.getBeatX(a.beat,ae.MiddleNotes):f+=n.getNoteX(a,oe.Right),m=!g||g.isLastOfVoice&&!u?e+c.x+c.postBeatGlyphsStart:u||!g.nextBeat?e+c.x+c.getBeatX(g,ae.MiddleNotes):a.bendType===l.Hold?e+c.x+c.getBeatX(g.nextBeat,ae.OnNotes):e+c.x+c.getBeatX(g.nextBeat,ae.PreNotes),d||(m-=ln.ArrowSize*this.scale);let b=(m-f)/be.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 hn(0,0),t,f,y,b,p,i),a.bendType!==l.Prebend?(0===e&&(f+=2*this.scale),this.paintBend(a,t,s,f,y,b,p,i)):a.isTieOrigin&&a.tieDestination.hasBend&&(s=new hn(be.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,d=h.lineOffset/2,c=s+r*t.offset,u=ln.BendValueHeight*this.scale,p=a-u*t.lineValue;0===t.value?i.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,ne.Top):p+=h.getNoteY(e,ne.Center):p+=d;let g=s+r*i.offset,f=a-u*i.lineValue;0===i.lineValue?f+=h.getNoteY(e,ne.Center):f+=d;let m=0,y=ln.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=ln.DashSize*this.scale,i=c+t;if((e-c)/(2*t)<1)o.moveTo(e,p),o.lineTo(c,p);else for(;e>i;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>c?(o.moveTo(c,p),o.bezierCurveTo((c+g)/2,p,g,p,g,f+m),o.stroke()):(o.moveTo(c,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=(c+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+=ln.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"}}}ln.ArrowSize=6,ln.DashSize=3,ln.BendValueHeight=6;class dn extends Ls{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===C.Custom)return e.whammyBarPoints;let t=[];switch(e.whammyBarType){case C.Dive:case C.Hold:case C.PrediveDive:case C.Predive:t.push(new be(0,e.whammyBarPoints[0].value)),t.push(new be(be.MaxPosition,e.whammyBarPoints[1].value));break;case C.Dip:t.push(new be(0,e.whammyBarPoints[0].value)),t.push(new be(be.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new be(be.MaxPosition,e.whammyBarPoints[e.whammyBarPoints.length-1].value))}return t}doLayout(){super.doLayout(),this._isSimpleDip=this.renderer.settings.notation.notationMode===T.SongBook&&this._beat.whammyBarType===C.Dip;let e=null,t=null,i=this._beat;for(;i&&i.hasWhammyBar;)(!e||e.value>i.minWhammyPoint.value)&&(e=i.minWhammyPoint),(!t||t.value<i.maxWhammyPoint.value)&&(t=i.maxWhammyPoint),i=i.nextBeat;let s=t.value>0?Math.abs(this.getOffset(t.value)):0;(s>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys))&&(s+=2*this.renderer.resources.tablatureFont.size);let a=e.value<0?Math.abs(this.getOffset(e.value)):0;this.renderer.registerOverflowTop(s+a),s>this.renderer.staff.getSharedLayoutData(dn.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(dn.TopOffsetSharedDataKey,s)}getOffset(e){if(0===e)return 0;let t=dn.PerHalfSize*this.scale+Math.log2(Math.abs(e)/2)*dn.PerHalfSize*this.scale;return e<0&&(t=-t),t}paint(e,t,i){let s=this.renderer,a=this._beat.nextBeat,r=null,n=ae.PreNotes;a&&(r=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,a.voice.bar),r&&r.staff===s.staff&&(r===s||a.hasWhammyBar)?n=!a.hasWhammyBar||s.settings.notation.notationMode===T.SongBook&&a.whammyBarType===C.Dip?ae.PreNotes:ae.MiddleNotes:(a=null,r=null));let o=0,l=0;this._isSimpleDip?(o=e+s.x+s.getBeatX(this._beat,ae.OnNotes)-2*this.scale,l=e+s.x+s.getBeatX(this._beat,ae.PostNotes)+2*this.scale):(o=e+s.x+s.getBeatX(this._beat,ae.MiddleNotes),l=r?e+r.x+r.getBeatX(a,n):e+s.x+s.width-2*this.scale);let d=i.textAlign;if(i.textAlign=P.Center,this._renderPoints.length>=2){let e=(l-o)/be.MaxPosition;i.beginPath();let s=t+this.renderer.staff.getSharedLayoutData(dn.TopOffsetSharedDataKey,0),a=this._beat.whammyStyle===h.Gradual?"grad.":"";for(let t=0,r=this._renderPoints.length-1;t<r;t++){let n=this._renderPoints[t],h=this._renderPoints[t+1],l=t<r-2?this._renderPoints[t+2]:null,d=0===t;0!==t||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new be(0,0),n,h,o,s,e,i),d=!1),this.paintWhammy(d,n,h,l,o,s,e,i,a),a=""}i.stroke()}i.textAlign=d}paintWhammy(e,t,i,s,a,r,n,o,h){let l=a+n*t.offset,d=a+n*i.offset,c=r-this.getOffset(t.value),u=r-this.getOffset(i.value);if(t.offset===i.offset){let e=dn.DashSize*this.scale;if(Math.abs(u-c)/(2*e)<1)o.moveTo(l,c),o.lineTo(d,u);else{let t=Math.max(c,u),i=Math.min(c,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=dn.DashSize*this.scale;if(Math.abs(d-l)/(2*e)<1)o.moveTo(l,c),o.lineTo(d,u);else{let t=Math.max(l,d),i=Math.min(l,d);for(;t>i;)o.moveTo(t,c),o.lineTo(t-e,c),t-=2*e}o.stroke()}else o.moveTo(l,c),o.lineTo(d,u);let p=this.renderer.resources;if(e&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let e=c;e-=p.tablatureFont.size+2*this.scale,this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2*this.scale,o.fillText(h,l,e))}let g=Math.abs(i.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(k.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+=ln.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(c,u)-p.tablatureFont.size-2*this.scale:(a=t.offset===i.offset?Math.min(c,u):u,a-=p.tablatureFont.size+2*this.scale,s&&s.value>i.value&&(a-=2*this.scale));let r=d;o.fillText(e,r,a)}}}dn.TopOffsetSharedDataKey="tab.whammy.topoffset",dn.PerHalfSize=6,dn.DashSize=3;class cn extends on{constructor(e){super(0,0),this._beat=e}doLayout(){let e=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case C.None:case C.Custom:case C.Hold:return;case C.Dive:case C.PrediveDive:{let e=new nn(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 C.Dip:if(e===T.SongBook){let e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+cn.SimpleDipHeight*this.scale+cn.SimpleDipPadding*this.scale}else{let e=new nn(this._beat,!1);if(e.renderer=this.renderer,this.renderer.settings.notation.notationMode===T.GuitarPro){let t=this._beat.whammyBarPoints[1];for(let i of this._beat.notes)e.addGlyph(this.getBendNoteValue(i,this._beat.whammyBarPoints[1]),t.value%2!=0)}e.doLayout(),this.BendNoteHeads.push(e);let t=new nn(this._beat,!1);if(t.renderer=this.renderer,this.renderer.settings.notation.notationMode===T.GuitarPro){let e=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let i of this._beat.notes)t.addGlyph(this.getBendNoteValue(i,e),e.value%2!=0)}t.doLayout(),this.BendNoteHeads.push(t)}case C.Predive:}super.doLayout()}paint(e,t,i){let s=this._beat;switch(s.whammyBarType){case C.None:case C.Custom:return}let a=this.renderer.settings.notation.notationMode,r=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,s.voice.bar),n=e+r.x+r.getBeatX(s,ae.MiddleNotes),o=this.getTieDirection(s,r),l=1===this._beat.notes.length?o:H.Up,d=i.textAlign;for(let d=0;d<s.notes.length;d++){let c=s.notes[d],u=t+r.y;d>0&&d>=(this._beat.notes.length/2|0)&&(l=H.Down),l===H.Down?u+=r.getNoteY(c,ne.Bottom):u+=r.getNoteY(c,ne.Top);let p=e+r.x;s.isLastOfVoice?p+=r.width:p+=r.getBeatX(s,ae.EndBeat),p-=8*this.scale;let g=s.whammyStyle===h.Gradual&&0===d?"grad.":"",f=null;c.isTieOrigin&&(f=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,c.tieDestination.beat.voice.bar),f&&f.staff===r.staff?p=e+f.x+f.getBeatX(c.tieDestination.beat,ae.MiddleNotes):f=null);let m=Is.NoteHeadHeight*this.scale*Is.GraceScale*.5;l===H.Up&&(m=-m);let y=s.whammyBarPoints.length>0?this.getBendNoteValue(c,s.whammyBarPoints[s.whammyBarPoints.length-1]):0,b=0,S=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(y)?(b=this.BendNoteHeads[0].getNoteValueY(y)+m,S=!0):f&&(c.isTieOrigin&&c.tieDestination.beat.hasWhammyBar||c.beat.isContinuedWhammy)?(b=t+f.y+f.getNoteY(c.tieDestination,ne.Top),S=!0,l===H.Down&&(b+=Is.NoteHeadHeight*this.scale)):c.isTieOrigin&&(b=f?t+f.y+f.getNoteY(c.tieDestination,ne.Top):u,l===H.Down&&(b+=Is.NoteHeadHeight*this.scale)),s.whammyBarType){case C.Hold:c.isTieOrigin&&Jr.paintTie(i,this.scale,n,u,p,b,o===H.Down,22,4);break;case C.Dive:0===d&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,i),this.BendNoteHeads[0].containsNoteValue(y)&&(b+=this.BendNoteHeads[0].y)),S?this.drawBendSlur(i,n,u,p,b,l===H.Down,this.scale,g):c.isTieOrigin&&Jr.paintTie(i,this.scale,n,u,p,b,o===H.Down,22,4);break;case C.Dip:if(a===T.SongBook){if(0===d){let s=e+r.x+r.getBeatX(this._beat,ae.OnNotes)-2*this.scale,a=e+r.x+r.getBeatX(this._beat,ae.PostNotes)+2*this.scale,n=(s+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();i.font=this.renderer.resources.tablatureFont,i.fillText(o,n,t+this.y);let h=t+this.y+i.font.size+2*this.scale,l=h+cn.SimpleDipHeight*this.scale;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(i.moveTo(s,l),i.lineTo(n,h),i.lineTo(a,l)):(i.moveTo(s,h),i.lineTo(n,l),i.lineTo(a,h)),i.stroke()}c.isTieOrigin&&Jr.paintTie(i,this.scale,n,u,p,b,o===H.Down,22,4)}else{let e=(n+p)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,i);let a=this.getBendNoteValue(c,s.whammyBarPoints[1]),o=this.BendNoteHeads[0].getNoteValueY(a)+m;this.drawBendSlur(i,n,u,e,o,l===H.Down,this.scale,g),this.BendNoteHeads[1].x=p-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=t+r.y,this.BendNoteHeads[1].paint(0,0,i),b=this.BendNoteHeads[1].getNoteValueY(y)+m,this.drawBendSlur(i,e,o,p,b,l===H.Down,this.scale,g)}break;case C.PrediveDive:case C.Predive:let h=e+r.x+r.getBeatX(c.beat,ae.PreNotes);h+=r.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;let f=t+r.y+r.getScoreY(r.accidentalHelper.getNoteLineForValue(c.displayValue-(c.beat.whammyBarPoints[0].value/2|0),!1))+m;this.drawBendSlur(i,h,f,n,u,l===H.Down,this.scale,g),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,i),this.drawBendSlur(i,n,u,p,b,l===H.Down,this.scale,g))}}i.textAlign=d}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}cn.SimpleDipHeight=2*dn.PerHalfSize,cn.SimpleDipPadding=2;class un extends Ls{constructor(e,t,i){super(e,t),this.width=i}}class pn extends Ds{constructor(e,t,i,s,a){super(e,t,a?Is.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!==x.None&&this._articulation.techniqueSymbolPlacement===E.Middle&&i.fillMusicFontSymbol(e+this.x,t+this.y+s,this.glyphScale*this.scale,this._articulation.techniqueSymbol,!1)}doLayout(){let e=(this._isGrace?Is.GraceScale:1)*this.scale;switch(this.symbol){case x.NoteheadWhole:this.width=14;break;case x.NoteheadCircleX:case x.NoteheadDiamondWhite:this.width=9;break;case x.NoteheadHeavyXHat:case x.NoteheadHeavyX:this.width=13;break;default:this.width=10}this.width=this.width*(this._isGrace?Is.GraceScale:1)*this.scale,this.height=Is.NoteHeadHeight*e}}class gn extends Ds{constructor(e,t){super(e,t,Is.GraceScale,x.ArticStaccatoAbove)}doLayout(){this.width=Is.QuarterNoteHeadWidth*this.scale,this.height=7*this.scale}paint(e,t,i){super.paint(e+3*this.scale,t+5*this.scale,i)}}class fn extends Ds{constructor(e,t){super(e,t,.5,x.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 mn extends Ds{constructor(e,t){super(e,t,Is.GraceScale,x.GuitarGolpe)}doLayout(){this.width=9*this.scale,this.height=10*this.scale}paint(e,t,i){super.paint(e,t+this.height,i)}}class yn extends xa{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===u.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const i=new sn(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=ma.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 un(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++){let e=new la(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addGlyph(e)}}}else{const t=new tn;this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper;let i=new $r(!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 un(0,0,4*(this.container.beat.graceType!==g.None?Is.GraceScale:1)*this.scale)),this.addGlyph(i)),this.container.beat.hasWhammyBar){let e=new cn(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addGlyph(new un(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++){let t=new la(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 Xr(0,i.getScoreY(e),1.5*this.scale))}createNoteHeadGlyph(e){let t=this.container.beat.graceType!==g.None;if(e.beat.voice.bar.staff.isPercussion){const i=Ne.getArticulation(e);if(i)return new pn(0,0,i,e.beat.duration,t);Be.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new Yr(0,0,t):e.beat.graceType===g.BendGrace?new Is(0,0,u.Quarter,!0):e.harmonicType===m.Natural?new qr(0,0,e.beat.duration,t):new Is(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===g.BendGrace&&!e.hasBend)return;let t=this.renderer,i=this.createNoteHeadGlyph(e),a=t.getNoteLine(e);if(i.y=t.getScoreY(a),this.noteHeads.addNoteGlyph(i,e,a),e.harmonicType!==m.None&&e.harmonicType!==m.Natural){let s=e.displayValue+e.harmonicPitch;i=new qr(0,0,e.beat.duration,this.container.beat.graceType!==g.None),a=t.accidentalHelper.getNoteLineForValue(s,!1),i.y=t.getScoreY(a),this.noteHeads.addNoteGlyph(i,e,a)}if(e.isStaccato&&!this.noteHeads.aboveBeatEffects.has("Staccato")&&this.noteHeads.belowBeatEffects.set("Staccato",new gn(0,0)),e.accentuated!==s.Normal||this.noteHeads.aboveBeatEffects.has("Accent")||this.noteHeads.belowBeatEffects.set("Accent",new Ur(0,0,s.Normal)),e.accentuated!==s.Heavy||this.noteHeads.aboveBeatEffects.has("HAccent")||this.noteHeads.belowBeatEffects.set("HAccent",new Ur(0,0,s.Heavy)),e.isPercussion){const t=Ne.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==E.Middle){const e=t.techniqueSymbolPlacement===E.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case x.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new fn(0,0));break;case x.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new gn(0,0));break;case x.StringsUpBow:e.set("StringsUpBow",new sr(0,0,N.Up));break;case x.StringsDownBow:e.set("StringsDownBow",new sr(0,0,N.Down));break;case x.GuitarGolpe:e.set("GuitarGolpe",new mn(0,0))}}}}}class bn extends Ls{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,ne.Bottom)-a),n=t+this.y+s.getNoteY(this._beat.minNote,ne.Top)+a,o=e+this.x+this.width/2,h=8*this.scale,l=new or(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 Sn extends Na{get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}doLayout(){if(!this.container.beat.isRest){let e=new rn;e.renderer=this.renderer;let t=new $r(!0);t.renderer=this.renderer;const i=new nn(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 l.PrebendBend:case l.Prebend:case l.PrebendRelease:i.addGlyph(s.displayValue-(s.bendPoints[0].value/2|0),!1)}else if(s.beat.hasWhammyBar)switch(s.beat.whammyBarType){case C.PrediveDive:case C.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 un(0,0,4*(this.container.beat.graceType!==g.None?Is.GraceScale:1)*this.scale))),this.container.beat.brushType!==d.None&&(this.addGlyph(new bn(this.container.beat)),this.addGlyph(new un(0,0,4*this.scale))),t.isEmpty||(this.addGlyph(t),this.addGlyph(new un(0,0,4*(this.container.beat.graceType!==g.None?Is.GraceScale:1)*this.scale))),e.isEmpty||(this.accidentals=e,this.addGlyph(new un(0,0,2*(this.container.beat.graceType!==g.None?Is.GraceScale:1)*this.scale)),this.addGlyph(e),this.addGlyph(new un(0,0,2*(this.container.beat.graceType!==g.None?Is.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!==g.None;if(s!==re.None){let e=new Ar(0,i.getScoreY(a),s,r);e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==m.None&&e.harmonicType!==m.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 Ar(0,i.getScoreY(a),s,r);o.renderer=this.renderer,t.addGlyph(o)}}constructor(){super(),this._prebends=null,this.accidentals=null}}class _n extends Ds{constructor(e,t,i,s){super(e,t,s,_n.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 x.TimeSig0;case 1:return x.TimeSig1;case 2:return x.TimeSig2;case 3:return x.TimeSig3;case 4:return x.TimeSig4;case 5:return x.TimeSig5;case 6:return x.TimeSig6;case 7:return x.TimeSig7;case 8:return x.TimeSig8;case 9:return x.TimeSig9;default:return x.None}}}class wn extends la{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 _n(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}}}wn.numberHeight=18;class Bn extends la{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 Ds(0,0,this.commonScale,x.TimeSigCutCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){let e=new Ds(0,0,this.commonScale,x.TimeSigCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else{const e=wn.numberHeight*this.scale;let t=new wn(0,-e/2,this._numerator,this.numberScale),i=new wn(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 Tn extends Bn{get commonScale(){return 1}get numberScale(){return 1}}class kn extends on{constructor(e){super(0,0),this._notes=[],this._endNoteGlyph=null,this._middleNoteGlyph=null,this._beat=e}addBends(e){if(this._notes.push(e),!e.isTieOrigin)switch(e.bendType){case l.Bend:case l.PrebendRelease:case l.PrebendBend:{let t=this._endNoteGlyph;t||(t=new nn(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 l.Release:if(!e.isTieOrigin){let t=this._endNoteGlyph;t||(t=new nn(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 l.BendRelease:{let t=this._middleNoteGlyph;t||(t=new nn(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 nn(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,ae.MiddleNotes),r=e+s.x;this._beat.isLastOfVoice?r+=s.postBeatGlyphsStart:r+=s.getBeatX(this._beat.nextBeat,ae.PreNotes),r-=8*this.scale;let n=(a+r)/2;this._middleNoteGlyph&&(this._middleNoteGlyph.x=n-this._middleNoteGlyph.noteHeadOffset,this._middleNoteGlyph.y=t+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===g.BendGrace?this._beat.nextBeat:this._beat,d=1===this._notes.length?this.getTieDirection(o,s):H.Up;for(let o=0;o<this._notes.length;o++){let c=this._notes[o];o>0&&o>=(this._notes.length/2|0)&&(d=H.Down);let u=t+s.y+s.getNoteY(c,ne.Top),p=Is.NoteHeadHeight*this.scale*Is.GraceScale*.5;d===H.Down&&(u+=Is.NoteHeadHeight*this.scale);let g=c.bendStyle===h.Gradual?"grad.":"";if(c.isTieOrigin){let r=c.tieDestination,n=r?this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.beat.voice.bar):null;if(n&&n.staff===s.staff){let s=e+n.x+n.getBeatX(r.beat,ae.MiddleNotes),o=t+n.y+n.getNoteY(r,ne.Top);d===H.Down&&(o+=Is.NoteHeadHeight*this.scale),c.bendType===l.Hold||c.bendType===l.Prebend?Jr.paintTie(i,this.scale,a,u,s,o,d===H.Down,22,4):this.drawBendSlur(i,a,u,s,o,d===H.Down,this.scale,g)}else{let r=e+s.x+s.width,n=c.tieDestination.realValue;s.accidentalHelper.applyAccidentalForValue(c.beat,n,!1,!0);let o=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(n,!1));c.bendType===l.Hold||c.bendType===l.Prebend?Jr.paintTie(i,this.scale,a,u,r,o,d===H.Down,22,4):this.drawBendSlur(i,a,u,r,o,d===H.Down,this.scale,g)}switch(c.bendType){case l.Prebend:case l.PrebendBend:case l.PrebendRelease:let r=e+s.x+s.getBeatX(c.beat,ae.PreNotes);r+=s.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;let n=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(i,r,n,a,u,d===H.Down,this.scale)}}else{d===H.Up&&(p=-p);let o=0,h=0;switch(c.bendType){case l.Bend:o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),h=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,h,d===H.Down,this.scale,g);break;case l.BendRelease:let f=this.getBendNoteValue(c,c.bendPoints[1]),m=this._middleNoteGlyph.getNoteValueY(f)+p;this.drawBendSlur(i,a,u,n,m,d===H.Down,this.scale,g),o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),h=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(i,n,m,r,h,d===H.Down,this.scale,g);break;case l.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),h=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,h,d===H.Down,this.scale,g));break;case l.Prebend:case l.PrebendBend:case l.PrebendRelease:let y=e+s.x+s.getBeatX(c.beat,ae.PreNotes);y+=s.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;let b=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(i,y,b,a,u,d===H.Down,this.scale),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),h=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,h,d===H.Down,this.scale,g))}}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class vn extends Jr{constructor(e,t,i=!1){super(e,t,i)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?H.Up:t.getBeatDirection(e)===H.Up?H.Down:H.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===H.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,ne.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,ne.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===H.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===g.None?i===this.tieDirection?this.tieDirection===H.Up?e.getNoteY(this.endBeat.maxNote,ne.TopWithStem):e.getNoteY(this.endBeat.minNote,ne.BottomWithStem):this.tieDirection===H.Up?e.getNoteY(this.endBeat.maxNote,ne.BottomWithStem):e.getNoteY(this.endBeat.minNote,ne.TopWithStem):this.tieDirection===H.Up?e.getNoteY(this.endBeat.maxNote,ne.Top):e.getNoteY(this.endBeat.minNote,ne.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,ae.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>u.Whole&&e===this.tieDirection?ae.Stem:ae.MiddleNotes)}}class Nn extends Ls{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,oe.Left)-2*this.scale,n=t+s.y+s.getNoteY(this._startNote,ne.Center),o=r-a,h=t+s.y;switch(this._inType){case b.IntoFromBelow:h+=s.getNoteY(this._startNote,ne.Bottom);break;case b.IntoFromAbove:h+=s.getNoteY(this._startNote,ne.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,d=0,c=!1;switch(this._outType){case S.Shift:case S.Legato:if(o=e+s.x+s.getBeatX(this._startNote.beat,ae.PostNotes),h=t+s.y+s.getNoteY(this._startNote,ne.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,ae.PreNotes)-r,d=t+i.y+i.getNoteY(this._startNote.slideTarget,ne.Center)):(l=e+s.x+s.width,d=h),this._startNote.slideTarget.realValue>this._startNote.realValue?(h+=n,d-=n):(h-=n,d+=n)}else l=e+s.x+this._parent.x,d=h;break;case S.OutUp:o=e+s.x+s.getNoteX(this._startNote,oe.Right),h=t+s.y+s.getNoteY(this._startNote,ne.Center),l=o+a,d=t+s.y+s.getNoteY(this._startNote,ne.Top);break;case S.OutDown:o=e+s.x+s.getNoteX(this._startNote,oe.Right),h=t+s.y+s.getNoteY(this._startNote,ne.Center),l=o+a,d=t+s.y+s.getNoteY(this._startNote,ne.Bottom);break;case S.PickSlideUp:o=e+s.x+s.getNoteX(this._startNote,oe.Right),h=t+s.y+s.getNoteY(this._startNote,ne.Center),d=t+s.y+s.getNoteY(this._startNote,ne.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,ae.PreNotes)),c=!0;break;case S.PickSlideDown:o=e+s.x+s.getNoteX(this._startNote,oe.Right),h=t+s.y+s.getNoteY(this._startNote,ne.Center),d=t+s.y+s.getNoteY(this._startNote,ne.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,ae.PreNotes)),c=!0;break;default:return}this.paintSlideLine(i,c,o,l,h,d)}paintSlideLine(e,t,i,s,a,r){if(t){let t=new or(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 xn extends vn{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===H.Up?this.startNoteRenderer.getNoteY(this._startNote,ne.Top):this.startNoteRenderer.getNoteY(this._startNote,ne.Bottom):this.startNoteRenderer.getNoteY(this._startNote,ne.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===H.Up?this.endNoteRenderer.getNoteY(this._endNote,ne.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,ne.BottomWithStem):this.tieDirection===H.Up?this.endNoteRenderer.getNoteY(this._endNote,ne.Top):this.endNoteRenderer.getNoteY(this._endNote,ne.Bottom):this.endNoteRenderer.getNoteY(this._endNote,ne.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===H.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===H.Down}isEndCentered(){return this._startNote.beat.graceType===g.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===H.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===H.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===g.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,ae.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,oe.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,ae.Stem):this.endNoteRenderer.getNoteX(this._endNote,oe.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,ae.PreNotes)}}class Pn extends Jr{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)===H.Up?H.Down:H.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===H.Up?this.startNoteRenderer.getNoteY(this.startNote,ne.Top):this.startNoteRenderer.getNoteY(this.startNote,ne.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===H.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===H.Up?e.getNoteY(this.endNote,ne.Top):e.getNoteY(this.endNote,ne.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,ae.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,ae.PreNotes)}}class En extends As{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 vn(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 vn(e,this.beat,!0))}this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(e.isVisible){if(e.isTieOrigin&&!e.hasBend&&!e.beat.hasWhammyBar&&e.beat.graceType!==g.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){let t=new Pn(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){let t=new Pn(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==b.None||e.slideOutType!==S.None){let t=new Nn(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){let t=new xn(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){let t=new xn(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new xn(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===H.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,s=t===H.Up?e.beat.minNote:e.beat.maxNote;const a=new xn(i,s,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new kn(e.beat);this._bend=t,t.renderer=this.renderer,this.addTie(t)}this._bend.addBends(e)}}}}class Cn extends wa{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._firstLineY=0,this._startSpacing=!1,this.accidentalHelper=new pa(this)}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}get lineOffset(){return(wa.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===H.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===H.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=P.Center,i.textBaseline=E.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 d=10*this.scale,c=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,_=this.calculateBeamYWithDirection(y,f,S),w=this.calculateBeamYWithDirection(b,m,S);u&&(_=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,N=k+B/2+T,x=(w-_)/(m-f),P=_-x*f,E=x*v+P,C=x*k+P,F=x*N+P;S===H.Down&&(d*=-1,c*=-1),i.beginPath(),i.moveTo(e+this.x+f,t+this.y+_-d|0),i.lineTo(e+this.x+f,t+this.y+_-d-c|0),i.lineTo(e+this.x+v,t+this.y+E-d-c|0),i.stroke(),i.beginPath(),i.moveTo(e+this.x+N,t+this.y+F-d-c|0),i.lineTo(e+this.x+m,t+this.y+w-d-c|0),i.lineTo(e+this.x+m,t+this.y+w-d|0),i.stroke(),i.fillText(a,e+this.x+k,t+this.y+C-d-c)}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===H.Down&&(d*=-1,c*=-1),i.font=r.effectFont,i.fillText(a,e+this.x+u,t+this.y+p-d-c)}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*=Is.GraceScale),t}getBarStemSize(e){let t=0;switch(e){case u.QuadrupleWhole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:t=6;break;case u.ThirtySecond:t=8;break;case u.SixtyFourth:case u.OneHundredTwentyEighth:t=9;break;case u.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}getFlagStemSize(e){let t=0;switch(e){case u.QuadrupleWhole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:case u.ThirtySecond:case u.SixtyFourth:case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:t=6;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){let i=super.getNoteY(e,t);if(isNaN(i)){const t=pa.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 fa;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===H.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):i===H.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===H.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):i===H.Up?this.getScoreY(this.accidentalHelper.getMinLine(r))-s:this.getScoreY(this.accidentalHelper.getMaxLine(r))+s;let o=10*this.scale;if(i===H.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),i===H.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),i===H.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),i===H.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(i===H.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=ke.getIndex(e.shortestDuration)-2;let a=e.isGrace?Is.GraceScale:1,r=s*(wa.BeamSpacing+wa.BeamThickness)*this.scale*a;if(r+=wa.BeamSpacing,i===H.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===H.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!==g.None?Is.GraceScale:1,o=s.getBeatLineX(r),h=s.direction,l=t+this.y;l+=h===H.Up?this.getScoreY(this.accidentalHelper.getMaxLine(r)):this.getScoreY(this.accidentalHelper.getMinLine(r));let d=t+this.y;d+=this.calculateBeamY(s,o),i.lineWidth=wa.StemWidth*this.scale,i.beginPath(),i.moveTo(e+this.x+o,l),i.lineTo(e+this.x+o,d),i.stroke(),i.lineWidth=this.scale;let c=d;h===H.Down?c+=2*i.font.size:0!==a&&(c-=1.5*i.font.size),this.paintFingering(i,r,e+this.x+o,h,c);let u=6*this.scale*n,p=(wa.BeamSpacing+wa.BeamThickness)*this.scale*n,f=wa.BeamThickness*this.scale*n,m=ke.getIndex(r.duration)-2,y=t+this.y;h===H.Down&&(p=-p,f=-f);for(let t=0;t<m;t++){let n=0,h=0,l=0,d=0,c=y+t*p;if(a<s.beats.length-1){if(ma.isFullBarJoin(r,s.beats[a+1],t))n=o,h=s.getBeatLineX(s.beats[a+1]);else{if(0!==a&&ma.isFullBarJoin(s.beats[a-1],r,t))continue;n=o,h=n+u}l=c+this.calculateBeamY(s,n),d=c+this.calculateBeamY(s,h),Cn.paintSingleBar(i,e+this.x+n,l,e+this.x+h,d,f)}else a>0&&!ma.isFullBarJoin(r,s.beats[a-1],t)&&(n=o-u,h=o,l=c+this.calculateBeamY(s,n),d=c+this.calculateBeamY(s,h),Cn.paintSingleBar(i,e+this.x+n,l,e+this.x+h,d,f))}}}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(e,t,i,s){let a=s.beats[0];if(a.graceType===g.BendGrace||a.graceType!==g.None&&this.settings.notation.notationMode===T.SongBook)return;let r=a.graceType!==g.None,n=r?Is.GraceScale:1,o=this.getFlagStemSize(s.shortestDuration),h=s.getBeatLineX(a),l=s.direction,d=this.getScoreY(this.accidentalHelper.getMinLine(a)),c=this.getScoreY(this.accidentalHelper.getMaxLine(a)),u=0,p=0;if(l===H.Down?(c+=o*n,u=c,p=t+this.y+c):(d-=o*n,u=d,p=t+this.y+d),this.paintFingering(i,a,e+this.x+h,l,p),s.hasLine){if(i.lineWidth=wa.StemWidth*this.scale,i.beginPath(),i.moveTo(e+this.x+h,t+this.y+d),i.lineTo(e+this.x+h,t+this.y+c),i.stroke(),i.lineWidth=this.scale,a.graceType===g.BeforeBeat){let s=15*this.scale,a=12*this.scale;i.beginPath(),l===H.Down?(i.moveTo(e+this.x+h-a/2,t+this.y+c-s),i.lineTo(e+this.x+h+a/2,t+this.y+c)):(i.moveTo(e+this.x+h-a/2,t+this.y+d+s),i.lineTo(e+this.x+h+a/2,t+this.y+d)),i.stroke()}if(s.hasFlag){let s=new Rs(h-this.scale/2,u,a.duration,l,r);s.renderer=this,s.doLayout(),s.paint(e+this.x,t+this.y,i)}}}paintFingering(e,t,i,s,a){let r=this.settings;if(r.notation.fingeringMode!==B.ScoreDefault&&r.notation.fingeringMode!==B.ScoreForcePiano)return;s===H.Up?i-=10*this.scale:i+=3*this.scale;let n=t.notes.slice(0);n.sort(((e,t)=>e.realValue-t.realValue));for(let s=0;s<n.length;s++){let o=n[s],h=null;o.leftHandFinger!==f.Unknown?h=ke.fingerToString(r,t,o.leftHandFinger,!0):o.rightHandFinger!==f.Unknown&&(h=ke.fingerToString(r,t,o.rightHandFinger,!1)),h&&(e.fillText(h,i,a),a-=0|e.font.size)}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new zr(0,0,1.5,3)),this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let e=0;switch(this.bar.clef){case r.Neutral:e=this.bar.staff.standardNotationLineCount-1;break;case r.F4:e=2;break;case r.C3:e=4;break;case r.C4:e=2;break;case r.G2:e=6}this.createStartSpacing(),this.addPreBeatGlyph(new Vr(0,this.getScoreY(e)+.5*wa.StaffLineThickness,this.bar.clef,this.bar.clefOttava))}(0===this.index&&this.bar.masterBar.keySignature!==L.C||this.bar.previousBar&&this.bar.masterBar.keySignature!==this.bar.previousBar.masterBar.keySignature)&&(this.createStartSpacing(),this.createKeySignatureGlyphs()),(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new Or(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 Hr(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Wr(0,this.getScoreHeight(-.5),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new Gr(0,0))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new un(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 r.Neutral:e=0;break;case r.G2:e=1;break;case r.F4:e=3;break;case r.C3:e=2;break;case r.C4:e=0}let s=new Map,a=[];if(ke.keySignatureIsSharp(t))for(let i=0;i<Math.abs(t);i++){let t=Cn.SharpKsSteps[i]+e;a.push(new Ar(0,this.getScoreY(t),re.Sharp,!1)),s.set(t,!0)}else for(let i=0;i<Math.abs(t);i++){let t=Cn.FlatKsSteps[i]+e;a.push(new Ar(0,this.getScoreY(t),re.Flat,!1)),s.set(t,!0)}let n=Math.abs(i),o=ke.keySignatureIsSharp(i)?Cn.SharpKsSteps:Cn.FlatKsSteps;for(let t=0;t<n;t++){let i=o[t]+e;s.has(i)||this.addPreBeatGlyph(new Ar(0,this.getScoreY(o[t]+e),re.Natural,!1))}for(let e of a)this.addPreBeatGlyph(e)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new un(0,0,5*this.scale));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new Tn(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 En(i,this.getVoiceContainer(e));s.preNotes=new Sn,s.onNotes=new yn,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*wa.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,ne.Center),i=this.getNoteY(e.lowestNoteInHelper,ne.Center),s=this.getStemSize(e);e.hasTuplet&&(s+=2*this.resources.effectFont.size),e.direction==H.Up?t-=s:i+=s;for(const s of e.beats)this.helpers.collisionHelper.reserveBeatSlot(s,t,i)}}}Cn.StaffId="score",Cn.SharpKsSteps=[-1,2,-2,1,4,0,3],Cn.FlatKsSteps=[3,0,4,1,5,2,6];class Fn extends ha{get staffId(){return Cn.StaffId}create(e,t){return new Cn(e,t)}constructor(){super()}}class Ln extends Ls{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 b.IntoFromBelow:h=e+s.x+s.getNoteX(this._startNote,oe.Left),l=t+s.y+s.getNoteY(this._startNote,ne.Center),n=h-a,o=t+s.y+s.getNoteY(this._startNote,ne.Center)+r;break;case b.IntoFromAbove:h=e+s.x+s.getNoteX(this._startNote,oe.Left),l=t+s.y+s.getNoteY(this._startNote,ne.Center),n=h-a,o=t+s.y+s.getNoteY(this._startNote,ne.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,d=!1;const c=2*this.scale;switch(this._outType){case S.Shift:case S.Legato:if(n=e+s.x+s.getBeatX(this._startNote.beat,ae.PostNotes),o=t+s.y+s.getNoteY(this._startNote,ne.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,ae.OnNotes)-c,l=t+i.y+i.getNoteY(this._startNote.slideTarget,ne.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 S.OutUp:n=e+s.x+s.getNoteX(this._startNote,oe.Right),o=t+s.y+s.getNoteY(this._startNote,ne.Center),h=n+a-c,l=t+s.y+s.getNoteY(this._startNote,ne.Center)-r;break;case S.OutDown:n=e+s.x+s.getNoteX(this._startNote,oe.Right),o=t+s.y+s.getNoteY(this._startNote,ne.Center),h=n+a-c,l=t+s.y+s.getNoteY(this._startNote,ne.Center)+r;break;case S.PickSlideDown:n=e+s.x+s.getNoteX(this._startNote,oe.Right),o=t+s.y+s.getNoteY(this._startNote,ne.Center),h=e+s.x+s.getBeatX(this._startNote.beat,ae.EndBeat),l=o+3*r,d=!0;break;case S.PickSlideUp:n=e+s.x+s.getNoteX(this._startNote,oe.Right),o=t+s.y+s.getNoteY(this._startNote,ne.Center),h=e+s.x+s.getBeatX(this._startNote.beat,ae.EndBeat),l=o-3*r,d=!0;break;default:return}this.paintSlideLine(i,d,n,h,o,l)}paintSlideLine(e,t,i,s,a,r){if(t){let t=new or(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 Mn extends Jr{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?H.Up:Mn.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?H.Up:H.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,ne.Center):this.tieDirection===H.Up?this.startNoteRenderer.getNoteY(this.startNote,ne.Top):this.startNoteRenderer.getNoteY(this.startNote,ne.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20*this.scale:this.startNoteRenderer.getNoteX(this.startNote,oe.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,oe.Left):this.endNoteRenderer.getNoteX(this.endNote,oe.Center)}}class Dn extends Mn{constructor(e,t,i,s=!1){super(e,t,s),this._direction=Mn.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!==Mn.getBeamDirectionForNote(e))return!1;switch(this._direction){case H.Up:e.realValue>this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue>this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat);break;case H.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,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 In extends As{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 Mn(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){let t=new Mn(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new Mn(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 Dn(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 Dn(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==b.None||e.slideOutType!==S.None){let t=new Ln(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new ln;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class Rn extends Ls{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 e=this._note,t=e.fret-e.beat.voice.bar.staff.transpositionPitch;if(e.harmonicType===m.Natural&&0!==e.harmonicValue&&(t=e.harmonicValue-e.beat.voice.bar.staff.transpositionPitch),e.isTieDestination)0===e.beat.index&&this.renderer.settings.notation.notationMode==T.GuitarPro||(e.bendType===l.Bend||e.bendType===l.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(k.TabNotesOnTiedBends)?this._noteString="("+(e.tieOrigin.fret-e.beat.voice.bar.staff.transpositionPitch).toString()+")":this._noteString="";else if(this._noteString=e.isDead?"x":t.toString(),e.isGhost)this._noteString="("+this._noteString+")";else if(e.harmonicType===m.Natural){let e=this._noteString.indexOf(String.fromCharCode(46));e>=0&&(this._noteString=this._noteString.substr(0,e+2)),this._noteString="<"+this._noteString+">"}if(e.isTrill)this._trillNoteString="("+(e.trillFret-e.beat.voice.bar.staff.transpositionPitch).toString()+")";else if(ke.isAlmostEqualTo(e.harmonicValue,0))this._trillNoteString="";else switch(e.harmonicType){case m.Artificial:case m.Pinch:case m.Tap:case m.Semi:case m.Feedback:let i=(t+e.harmonicValue).toString(),s=i.indexOf(String.fromCharCode(46));s>=0&&(i=i.substr(0,s+2)),this._trillNoteString="<"+i+">";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 fs;s.note=this._note,s.noteHeadBounds=new at,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 An extends Ls{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 oe.Left:break;case oe.Center:s+=i.noteStringWidth/2;break;case oe.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 ne.Top:case ne.TopWithStem:s-=i.height/2+2*this.scale;break;case ne.Center:break;case ne.Bottom:case ne.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,ne.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=E.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 On extends Ds{constructor(e,t,i,s){super(e,t,1,sn.getSymbol(s)),this._isVisibleRest=i,this._duration=s}doLayout(){this._isVisibleRest?this.width=sn.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 Gn extends xa{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 e=this.renderer;if(this.container.beat.isRest){let t=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),i=e.getTabY(t);const s=new On(0,i,e.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&&e.showRests){this.addGlyph(new un(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new Xr(0,i,1.5*this.scale))}}else{let t=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==g.None;const i=new An(0,0,t);this.noteNumbers=i,i.beat=this.container.beat,i.beamingHelper=this.beamingHelper;for(let e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);if(this.addGlyph(i),this.container.beat.hasWhammyBar){let e=new dn(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!this.noteNumbers.beatEffects.has("tremolo")){let e=0,t=this.container.beat.tremoloSpeed;switch(t){case u.ThirtySecond:e=10;break;case u.Sixteenth:e=5;break;case u.Eighth:e=0}this.noteNumbers.beatEffects.set("tremolo",new en(5*this.scale,e*this.scale,t))}if(this.container.beat.dots>0&&e.settings.notation.rhythmMode!==w.Hidden){this.addGlyph(new un(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++)this.addGlyph(new Xr(0,e.lineOffset*e.bar.staff.tuning.length+e.settings.notation.rhythmHeight*e.scale,1.5*this.scale))}}if(!this.glyphs)return;let t=0;for(let e=0,i=this.glyphs.length;e<i;e++){let i=this.glyphs[e];i.x=t,i.renderer=this.renderer,i.doLayout(),t+=i.width}this.width=t,this.computedWidth=t,this.container.beat.isEmpty?this.centerX=this.width/2:this.container.beat.isRest?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.centerX=this.noteNumbers.x+this.noteNumbers.noteStringWidth/2}updateBeamingHelper(){this.container.beat.isRest?this.restGlyph.updateBeamingHelper(this.container.x+this.x):this.noteNumbers.updateBeamingHelper(this.container.x+this.x)}createNoteGlyph(e){let t=this.renderer,i=new Rn(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 Vn extends Ls{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,ne.Top),r=t+this.y+s.getNoteY(this._beat.minStringNote,ne.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 or(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 or(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 Hn extends Na{doLayout(){this.container.beat.brushType===d.None||this.container.beat.isRest||(this.addGlyph(new Vn(this.container.beat)),this.addGlyph(new un(0,0,4*this.scale))),super.doLayout()}constructor(){super()}}class Wn extends Ls{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?x.FourStringTabClef:x.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 zn extends Bn{get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?Is.GraceScale:1}}class Un extends wa{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(Un.TabLineSpacing+1)*this.scale}updateSizes(){let e=this.resources,t=(e.tablatureFont.size/2+.2*e.tablatureFont.size)*this.scale;this.topPadding=t,this.bottomPadding=t,this.height=this.lineOffset*(this.bar.staff.tuning.length-1)+2*t,this.settings.notation.rhythmMode!==w.Hidden&&(this.height+=this.settings.notation.rhythmHeight*this.settings.display.scale,this.bottomPadding+=this.settings.notation.rhythmHeight*this.settings.display.scale),this.updateFirstLineY(),super.updateSizes()}updateFirstLineY(){let e=this.resources;this._firstLineY=(e.tablatureFont.size/2+.2*e.tablatureFont.size)*this.scale}doLayout(){if(this.updateFirstLineY(),super.doLayout(),this.settings.notation.rhythmMode!==w.Hidden){let e=!1;for(let t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}e&&(this._tupletSize=.8*this.resources.effectFont.size,this.registerOverflowBottom(this._tupletSize))}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new zr(0,0,1.5,3)),this.isFirstOfLine){let e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new Wn(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 Or(0,this.getTabHeight(-.5),this.bar.index+1))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new un(0,0,2*this.scale)),this._startSpacing=!0)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new un(0,0,5*this.scale));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new zn(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,i=e.beats.length;t<i;t++){let i=e.beats[t],s=new In(i,this.getVoiceContainer(e));s.preNotes=new Hn,s.onNotes=new Gn,this.addBeatGlyph(s)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new Hr(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Wr(0,this.getTabY(-1),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new Gr(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*wa.StaffLineThickness),n=o[0]+o[1];i.fillRect(e+this.x+n,t+this.y+a|0,this.width-n,this.scale*wa.StaffLineThickness)}i.color=s.mainGlyphColor,this.paintSimileMark(e,t,i)}paint(e,t,i){super.paint(e,t,i),this.settings.notation.rhythmMode!==w.Hidden&&(this.paintBeams(e,t,i),this.paintTuplets(e,t,i))}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(e,t,i,s){i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.isRestBeamHelper||(1===s.beats.length||this.settings.notation.rhythmMode===w.ShowWithBeams?this.paintFooter(e,t,i,s):this.paintBar(e,t,i,s))}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!==u.Half?o+=l.noteNumbers.getNoteY(l.noteNumbers.minStringNote,ne.Bottom)+this.lineOffset/2:o+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(r,t+this.y,e+this.x+n,o,h,i);let d=6*this.scale,c=-6*this.scale,p=3*this.scale,g=ke.getIndex(r.duration)-2,f=h;for(let t=0;t<g;t++){let o=0,h=0,l=0,u=0,g=f+t*c;if(1===s.beats.length)o=n,h=n+d,l=g,u=g,Un.paintSingleBar(i,e+this.x+o,l,e+this.x+h,u,p);else if(a<s.beats.length-1){if(ma.isFullBarJoin(r,s.beats[a+1],t))o=n,h=s.getBeatLineX(s.beats[a+1]);else{if(0!==a&&ma.isFullBarJoin(s.beats[a-1],r,t))continue;o=n,h=o+d}l=g,u=g,Un.paintSingleBar(i,e+this.x+o,l,e+this.x+h,u,p)}else a>0&&!ma.isFullBarJoin(r,s.beats[a-1],t)&&(o=n-d,h=n,l=g,u=g,Un.paintSingleBar(i,e+this.x+o,l,e+this.x+h,u,p))}}}}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=P.Center,i.textBaseline=E.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),d=l.getBeatLineX(o);i.font=r.effectFont;let c=i.measureText(a),u=3*this.scale,p=(s+d)/2,g=p-c/2-u,f=p+c/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+d,m-y-b|0),i.lineTo(e+this.x+d,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),d=t+this.y+this.height-this._tupletSize+.5*r.effectFont.size;i.font=r.effectFont,i.fillText(a,e+this.x+l,d)}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!==g.None||a.duration===u.Whole||a.duration===u.DoubleWhole||a.duration===u.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!==u.Half?n+=h.noteNumbers.getNoteY(h.noteNumbers.minStringNote,ne.Bottom):n+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(a,t+this.y,e+this.x+r,n,o,i),a.duration>u.Quarter){let t=new Rs(0,0,a.duration,H.Down,!1);t.renderer=this,t.doLayout(),t.paint(e+this.x+r,o,i)}}}}Un.StaffId="tab",Un.TabLineSpacing=10;class Xn extends ha{get staffId(){return Un.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 Un(e,t);return i.showRests=this._showRests,i.showTimeSignature=this._showTimeSignature,i.showTiedNotes=this._showTiedNotes,i}}class Yn extends Ms{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+Yn.Padding*this.scale}paint(e,t,i){let s=this.renderer.resources;i.font=s.effectFont;let a=i.textAlign;i.textAlign=P.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+(Yn.Padding-1)*this.scale,i.font.size/1.6)}}Yn.Padding=4;class qn extends Ya{get notationElement(){return k.EffectTap}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new Yn}}class Jn{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"}(de||(de={}));class jn extends Jn{constructor(){super(...arguments),this.align=P.Left,this.frame=de.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class Qn extends Jn{constructor(){super(...arguments),this.chord=new Re}}class $n extends Jn{}class Kn extends Jn{}class Zn extends Jn{constructor(){super(...arguments),this.number=0}}class eo extends Jn{constructor(){super(...arguments),this.decrescendo=!1}}class to extends Jn{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class io extends Jn{constructor(){super(...arguments),this.octave=1}}class so extends Jn{}class ao{constructor(){this.defaultClef=r.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class ro{constructor(){this.from=0,this.to=0,this.curly=!1}}class no{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class oo{constructor(){this._trackChannel=0,this._beamingMode=F.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new Oe,this._voiceStates=new Map}parseXml(e,t){this._galleryObjects=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._voiceCounts=new Map,this._slurs=new Map,this._crescendo=new Map,this._isFirstSystem=!0;let i=new ct;try{i.parse(e)}catch(e){throw new ge("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 je);for(const e of t.voices)if(0===e.beats.length){const t=new Ie;t.isEmpty=!0,e.addBeat(t)}const s=t.masterBar;s.tempoAutomation&&(s.tempoAutomation.value!==e?e=s.tempoAutomation.value:s.tempoAutomation=null)}}}oo.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),oo.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?c.Decrescendo:c.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 ge("No valid XML");if("score"!==t.localName)throw new ge('Root node of XML was not "score"');this.score=new He,this.score.tempo=120;for(let e of t.childNodes)if(e.nodeType===G.Element)switch(e.localName){case"info":this.parseInfo(e);break;case"layout":this.parseLayout(e);break;case"gallery":this.parseGallery(e);break;case"pageObjects":this.parsePageObjects(e);break;case"systems":this.parseSystems(e)}}parseLayout(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"staves":this.parseLayoutStaves(t);break;case"brackets":this.parseBrackets(t)}const t=this._brackets.filter((e=>!!e.curly));t.sort(((e,t)=>e.from-t.from));let 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 Je,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===G.Element&&"bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new ro;t.from=parseInt(e.getAttribute("from")),t.to=parseInt(e.getAttribute("to")),e.attributes.has("curly")&&(t.curly="true"===e.attributes.get("curly")),this._brackets.push(t)}parseLayoutStaves(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new ao;t.description=e.getAttribute("description");for(let i of e.childNodes)if(i.nodeType===G.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 r.G2;case"bass":return r.F4;case"alto":case"tenor":return r.C4}return r.G2}parseClefOttava(e){return e.endsWith("-")?n._8vb:e.endsWith("+")?n._8va:n.Regular}parseSystems(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"system"===t.localName)this.parseSystem(t)}parseSystem(e){e.attributes.has("tempo")&&0===this.score.masterBars.length&&(this.score.tempo=parseInt(e.attributes.get("tempo"))),"0"===e.getAttribute("beamGrouping")&&(this._beamingMode=F.ForceSplitToNext);for(let t of e.childNodes)if(t.nodeType===G.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===G.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===G.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===G.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 me;if(e.bars.length>0?(t.clef=e.bars[e.bars.length-1].clef,t.clefOttava=e.bars[e.bars.length-1].clefOttava):t.clef=this._currentStaffLayout.defaultClef,e.addBar(t),e.bars.length>this.score.masterBars.length){let e=new Oe;this.score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.tripletFeel=e.previousMasterBar.tripletFeel),e.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,e.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,e.timeSignatureCommon=this._timeSignature.timeSignatureCommon}return t}newBar(e,t){this._currentVoiceState.currentBarIndex++,this._currentBar=this.getOrCreateBar(e,this._currentVoiceState.currentBarIndex),this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1),this._currentVoiceState.currentBarComplete=!1,this._currentVoiceState.currentPosition=0,this.ensureVoice(e,t)}parseVoice(e,t,i,s,r,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 no,this._currentVoiceState.currentBarIndex=r-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=H.Up;break;case"down":this._currentVoiceState.voiceStemDir=H.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const h=n.findChildElement("noteObjects");if(i.attributes.has("tempo")&&(this._currentBar.masterBar.tempoAutomation=new fe,this._currentBar.masterBar.tempoAutomation.isLinear=!0,this._currentBar.masterBar.tempoAutomation.type=a.Tempo,this._currentBar.masterBar.tempoAutomation.value=parseInt(i.attributes.get("tempo"))),h)for(let e of h.childNodes)if(e.nodeType===G.Element)switch(this._currentVoiceState.currentBarComplete&&"barline"!==e.localName&&this.newBar(t,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 Ie;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 je);(!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 Pe;for(let a of t.childNodes)if(a.nodeType===G.Element)switch(a.localName){case"stem":switch(a.getAttribute("dir")){case"up":e.preferredBeamDirection=H.Up;break;case"down":e.preferredBeamDirection=H.Down}break;case"articulation":switch(a.getAttribute("type")){case"staccato":i.isStaccato=!0;break;case"normalAccent":i.accentuated=s.Normal;break;case"strongAccent":i.accentuated=s.Heavy}break;case"lyric":this.parseLyric(e,a);break;case"drawObjects":this.parseBeatDrawObject(e,a);break;case"heads":this.parseHeads(e,i,a);break;case"beam":switch(a.getAttribute("group")){case"force":e.beamingMode=F.ForceMergeWithNext;break;case"divide":e.beamingMode=F.ForceSplitToNext}}}parseHeads(e,t,i){for(let s of i.childNodes)if(s.nodeType===G.Element&&"head"===s.localName)this.parseHead(e,t,s)}parseHead(e,t,i){const s=new Pe,a=ke.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===G.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===G.Element&&"drawObj"===i.localName){const t=this.parseDrawObj(i);if(t)if(t instanceof jn)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new nt,e.fermata.type=O.Medium):"f"===t.text?e.dynamics=p.F:"j"===t.text&&(e.dynamics=p.MF):this._isFirstSystem&&""===this.score.title&&t.align===P.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===P.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===P.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof Qn);else if(t instanceof Kn)e.vibrato=_.Slight;else if(t instanceof eo)e.crescendo=t.decrescendo?c.Decrescendo:c.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof $n){const i=t;this._slurs.set(e,i)}else t instanceof to&&this.applyVolta(t)}}parseBarDrawObject(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof to&&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===G.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 Ie;return i.beamingMode=this._beamingMode,this.parseDuration(e,i,t),i}if(1===parseInt(i)){let e=new Ie;return e.beamingMode=this._beamingMode,e.duration=u.Whole,e}return Be.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return u.DoubleWhole;case"1/1":return u.Whole;case"1/2":return u.Half;case"1/4":return u.Quarter;case"1/8":return u.Eighth;case"1/16":return u.Sixteenth;case"1/32":return u.ThirtySecond;case"1/64":return u.SixtyFourth;case"1/128":return u.OneHundredTwentyEighth;default:return Be.warning("Importer","Unsupported duration"),u.Quarter}}parseDuration(e,t,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===G.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof jn)switch(e.align){case P.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case P.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"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===G.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 so}parseOctaveClef(e){const t=new io;return e.attributes.has("octave")&&(t.octave=parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new to;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 eo;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new Zn;return e.attributes.has("number")&&(t.number=parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new Kn}parseSlur(e){return new $n}parseGuitar(e){const t=new Qn,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 jn;switch(e.attributes.has("x")&&(t.x=parseFloat(e.attributes.get("x"))),e.attributes.has("x")&&(t.y=parseFloat(e.attributes.get("y"))),e.getAttribute("align")){case"left":t.align=P.Left;break;case"center":t.align=P.Center;break;case"right":t.align=P.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=de.Rectangle;break;case"ellipse":t.frame=de.Ellipse;break;case"circle":t.frame=de.Circle;break;case"none":t.frame=de.None}if(e.firstElement){for(let i of e.childNodes)if(i.nodeType===G.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===G.Element)switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class ho extends ue{get name(){return"Capella"}constructor(){super()}readScore(){Be.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new Nt(this.data).read(),Be.debug(this.name,"Zip entries loaded"),e.length>0){for(let i of e)if("score.xml"===i.fileName)t=$e.toString(i.data,this.settings.importer.encoding)}else this.data.reset(),t=$e.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new ge("No valid capella file");Be.debug(this.name,"Start Parsing score.xml");try{let e=new oo;return e.parseXml(t,this.settings),Be.debug(this.name,"score.xml parsed"),e.score}catch(e){throw new ge("Failed to parse CapXML",e)}}}class lo{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 co{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)}}class uo{constructor(e,t){this.vertical=e,this.createLayout=t}}class po{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class go{static createStyleElement(e,t){let i=e.getElementById("alphaTabStyle");if(!i){if(!t)return void Be.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: ${go.MusicFontSize}px;\n overflow: visible !important;\n }`;i.innerHTML=s,e.getElementsByTagName("head").item(0).appendChild(i),go.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===go._globalThis){try{go._globalThis=globalThis}catch(e){}void 0===go._globalThis&&(go._globalThis=self),void 0===go._globalThis&&(go._globalThis=global),void 0===go._globalThis&&(go._globalThis=window),void 0===go._globalThis&&(go._globalThis=Function("return this")())}return this._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in go.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in go.globalThis}static createAlphaTabWorker(e){if(go.isWebPackBundled)return new Worker(new URL("@coderline/alphatab",import.meta.url));if(!e)throw new pe(i.General,"Could not detect alphaTab script file, cannot initialize renderer");try{if(go.webPlatform===ie.BrowserModule){const t=`import * as alphaTab from '${e}'`,i=new Blob([t],{type:"text/javascript"});return new Worker(URL.createObjectURL(i),{type:"module"})}{const t=`importScripts('${e}')`,i=new Blob([t]);return new Worker(URL.createObjectURL(i))}}catch(t){return Be.warning("Rendering","Could not create inline worker, fallback to normal worker"),new Worker(e)}}static throttle(e,t){let i=0;return()=>{go.globalThis.clearTimeout(i),i=go.globalThis.setTimeout(e,t)}}static detectScriptFile(){try{const e=import.meta.url;if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in go.globalThis&&document.currentScript?document.currentScript.src:null}static registerJQueryPlugin(){if(!go.isRunningInWorker&&go.globalThis&&"jQuery"in go.globalThis){let e=go.globalThis.jQuery,t=new ra;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:ra.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&go.renderEngines.has(e)?go.renderEngines.get(e):go.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&go.layoutEngines.has(t)?go.layoutEngines.get(t):go.layoutEngines.get(e.Page)}static buildImporters(){return[new tt,new Lt,new xt,new Mt,new ho,new et]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new po(!0,(()=>new oa))),e.set("default",e.get("svg")),go.createPlatformSpecificRenderEngines(e),e}static createPlatformSpecificRenderEngines(e){e.set("html5",new po(!1,(()=>new _s)))}static createDefaultStaveProfiles(){const e=new Map;e.set(t.ScoreTab,[new Ea("score-effects",[new cr,new mr,new Ka,new ur,new Ia,new Ua,new yr,new gr,new er(!0),new br,new nr,new Sr,new hr,new qn,new La]),new Fn,new Ea("tab-effects",[new Oa,new er(!1),new Va,new $a,new gr,new br,new nr,new Sr,new hr,new lr,new Wa,new Ja(m.Natural),new Ja(m.Artificial),new Ja(m.Pinch),new Ja(m.Tap),new Ja(m.Semi),new Ja(m.Feedback),new ja,new Da,new Xa,new tr,new ar,new ir,new qn]),new Xn(!1,!1,!1)]),e.set(t.Score,[new Ea("score-effects",[new cr,new mr,new Ka,new ur,new Ia,new Ua,new yr,new gr,new er(!0),new br,new nr,new Sr,new hr,new Wa,new ja,new tr,new ar,new ir,new qn,new La]),new Fn,new Ea("score-bottom-effects",[new Oa,new er(!1),new Va,new $a])]);let i=[new cr,new mr,new Ka,new ur,new Ia,new Ua,new gr,new br,new nr,new Sr,new hr,new lr,new Wa,new Ja(m.Artificial),new Ja(m.Pinch),new Ja(m.Tap),new Ja(m.Semi),new Ja(m.Feedback),new ja,new Da,new Xa,new tr,new ar,new ir,new qn,new La];return e.set(t.Tab,[new Ea("tab-effects",i),new Xn(!0,!0,!0),new Ea("tab-bottom-effects",[new $a])]),e.set(t.TabMixed,[new Ea("tab-effects",i),new Xn(!1,!1,!1),new Ea("tab-bottom-effects",[new $a])]),e}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.Page,new uo(!0,(e=>new Rr(e)))),t.set(e.Horizontal,new uo(!1,(e=>new Ir(e)))),t}static platformInit(){go.isRunningInAudioWorklet?ea.init():go.isRunningInWorker?(Ss.init(),ls.init()):go.webPlatform!==ie.Browser&&go.webPlatform!==ie.BrowserModule||(go.registerJQueryPlugin(),go.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in go.globalThis||(go.globalThis.ResizeObserver=lo),"IntersectionObserver"in go.globalThis||(go.globalThis.IntersectionObserver=co),"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)}))}static detectWebPack(){try{if("function"==typeof __webpack_require__)return!0}catch(e){}return!1}static detectWebPlatform(){try{if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return ie.NodeJs}catch(e){}try{const e=import.meta.url;if(e&&"string"==typeof e&&!e.startsWith("file://"))return ie.BrowserModule}catch(e){}return ie.Browser}}go.MusicFontSize=34,go.HighDpiFactor=1,go._globalThis=void 0,go.webPlatform=go.detectWebPlatform(),go.isWebPackBundled=go.detectWebPack(),go.scriptFile=go.detectScriptFile(),go.bravuraFontChecker=new Ys(["alphaTab"]),go.renderEngines=go.createDefaultRenderEngines(),go.layoutEngines=go.createDefaultLayoutEngines(),go.staveProfiles=go.createDefaultStaveProfiles(),go.platformInit();class fo{constructor(){if(this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=v.Info,this.useWorkers=!0,this.includeNoteBounds=!1,!go.isRunningInWorker&&go.globalThis.ALPHATAB_ROOT?(this.scriptFile=go.globalThis.ALPHATAB_ROOT,this.scriptFile=fo.ensureFullUrl(this.scriptFile),this.scriptFile=fo.appendScriptName(this.scriptFile)):this.scriptFile=go.scriptFile,!go.isRunningInWorker&&go.globalThis.ALPHATAB_FONT)this.fontDirectory=go.globalThis.ALPHATAB_FONT,this.fontDirectory=fo.ensureFullUrl(this.fontDirectory);else if(this.fontDirectory=this.scriptFile,this.fontDirectory){let e=this.fontDirectory.lastIndexOf(String.fromCharCode(47));e>=0&&(this.fontDirectory=this.fontDirectory.substr(0,e)+"/font/")}}static ensureFullUrl(e){var t,i,s;if(!e)return"";if(!e.startsWith("http")&&!e.startsWith("https")&&!e.startsWith("file")){let a="",r=go.globalThis.location;if(a+=null===(t=r.protocol)||void 0===t?void 0:t.toString(),a+="//".toString(),r.hostname&&(a+=null===(i=r.hostname)||void 0===i?void 0:i.toString()),r.port&&(a+=":".toString(),a+=null===(s=r.port)||void 0===s?void 0:s.toString()),!e.startsWith("/")){let e=r.pathname.split("/").slice(0,-1).join("/");e.length>0&&(e.startsWith("/")||(a+="/".toString()),a+=null==e?void 0:e.toString())}return e.startsWith("/")||(a+="/".toString()),a+=null==e?void 0:e.toString(),a}return e}static appendScriptName(e){return e&&!e.endsWith(".js")&&(e.endsWith("/")||(e+="/"),e+="alphaTab.js"),e}}class mo{}mo.version="1.3.0-alpha.605",mo.date="2023-04-11T01:36:41.857Z";var yo,bo=Object.freeze({__proto__:null,ScoreImporter:ue,ScoreLoader:zs,UnsupportedFormatError:ge});class So{init(e,t){this.data=e,this.settings=t}export(e,t=null){const i=Ke.withCapacity(1024);return this.init(i,null!=t?t:new Wi),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"}(yo||(yo={}));class _o{constructor(e,t,i=null){if(this.icon=yo.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 wo{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new ct;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 a=0;switch(t.isStaccato&&(a|=1),t.accentuated){case s.Normal:a|=8;break;case s.Heavy:a|=4}if(a>0&&(i.addElement("Accent").innerText=a.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 f.Thumb:i.addElement("LeftFingering").innerText="P";break;case f.IndexFinger:i.addElement("LeftFingering").innerText="I";break;case f.MiddleFinger:i.addElement("LeftFingering").innerText="M";break;case f.AnnularFinger:i.addElement("LeftFingering").innerText="A";break;case f.LittleFinger:i.addElement("LeftFingering").innerText="C"}switch(t.rightHandFinger){case f.Thumb:i.addElement("RightFingering").innerText="P";break;case f.IndexFinger:i.addElement("RightFingering").innerText="I";break;case f.MiddleFinger:i.addElement("RightFingering").innerText="M";break;case f.AnnularFinger:i.addElement("RightFingering").innerText="A";break;case f.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!==m.None){switch(t.harmonicType){case m.Natural:this.writeSimplePropertyNode(i,"HarmonicType","HType","Natural");break;case m.Artificial:this.writeSimplePropertyNode(i,"HarmonicType","HType","Artificial");break;case m.Pinch:this.writeSimplePropertyNode(i,"HarmonicType","HType","Pinch");break;case m.Tap:this.writeSimplePropertyNode(i,"HarmonicType","HType","Tap");break;case m.Semi:this.writeSimplePropertyNode(i,"HarmonicType","HType","Semi");break;case m.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 b.IntoFromAbove:s|=32;break;case b.IntoFromBelow:s|=16}switch(t.slideOutType){case S.Shift:s|=1;break;case S.Legato:s|=2;break;case S.OutDown:s|=4;break;case S.OutUp:s|=8;break;case S.PickSlideDown:s|=64;break;case S.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=Ye.defaultSteps[a],o=Ye.defaultAccidentals[a]};switch(h(),s){case y.Default:break;case y.ForceNone:case y.ForceNatural:o="";break;case y.ForceSharp:o="#";break;case y.ForceDoubleSharp:"#"===o&&(i-=2,h()),o="x";break;case y.ForceFlat:"#"===o&&(i+=1,h()),o="b";break;case y.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 be((a.offset+r.offset)/2,(a.value+r.value)/2)}this.writeSimplePropertyNode(e,"BendDestinationOffset","Float",this.toBendOffset(r.offset).toString()),this.writeSimplePropertyNode(e,"BendDestinationValue","Float",this.toBendValue(r.value).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset1","Float",this.toBendOffset(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/be.MaxPosition*100}writeBeatNode(e,t,i){const s=e.addElement("Beat");if(s.attributes.set("id",t.id.toString()),s.addElement("Dynamic").innerText=p[t.dynamics],t.fadeIn&&(s.addElement("Fadding").innerText="FadeIn"),t.isTremolo)switch(t.tremoloSpeed){case u.Eighth:s.addElement("Tremolo").innerText="1/2";break;case u.Sixteenth:s.addElement("Tremolo").innerText="1/4";break;case u.ThirtySecond:s.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&s.addElement("Chord").setCData(t.chordId),t.crescendo!==c.None&&(s.addElement("Hairpin").innerText=c[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 g.OnBeat:case g.BeforeBeat:s.addElement("GraceNotes").innerText=g[t.graceType]}if(t.ottava!==n.Regular&&(s.addElement("Ottavia").innerText=n[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 H.Up:s.addElement("TransposedPitchStemOrientation").innerText="Upward";break;case H.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 u.QuadrupleWhole:r="Long";break;case u.DoubleWhole:r="DoubleWhole";break;case u.Whole:r="Whole";break;case u.Half:r="Half";break;case u.Quarter:r="Quarter";break;case u.Eighth:r="Eighth";break;case u.Sixteenth:r="16th";break;case u.ThirtySecond:r="32nd";break;case u.SixtyFourth:r="64th";break;case u.OneHundredTwentyEighth:r="128th";break;case u.TwoHundredFiftySixth:r="256th"}e.addElement("NoteValue").innerText=r}e.addElement("Rhythm").attributes.set("ref",a)}writeWhammyNode(e,t){t.hasWhammyBar&&t.whammyBarPoints.length<=4&&this.writeStandardWhammy(e,t.whammyBarPoints)}writeStandardWhammy(e,t){const 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 be((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("4"),i.addElement("ScoreSystemsLayout").setCData("4"),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="3",i.addElement("SystemsLayout").innerText="1",i.addElement("AutoBrush"),i.addElement("PalmMute").innerText="0",i.addElement("PlayingStyle").innerText=ce.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",i.addElement("UseOneChannelPerString"),i.addElement("IconId").innerText=wo.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?wo.DrumKitProgramInfo.icon:wo.MidiProgramInfoLookup.has(e.program)?wo.MidiProgramInfoLookup.get(e.program).icon:yo.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 d=t.addElement("Automation");d.addElement("Type").innerText="Sound",d.addElement("Linear").innerText="false",d.addElement("Bar").innerText=r.toString(),d.addElement("Position").innerText=o.toString(),d.addElement("Visible").innerText="true",d.addElement("Value").setCData(`${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`,r=`Midi/${t.playbackInfo.program}`,n="Factory";let o=!1;for(const h of t.staves)for(const l of h.bars)for(const h of l.voices)for(const d of h.beats){const h=d.getAutomation(a.Instrument),c=0===l.index&&0===d.index;if(h){const a=c?e:`ProgramChange_${d.id}`,u=c?r:`Midi/${h.value}`,p=c?n:"User";c||o||(this.writeSoundAndAutomation(i,s,e,r,n,t.staves[0].bars[0].index,t.playbackInfo.program),o=!0),this.writeSoundAndAutomation(i,s,a,u,p,l.index,h.value,h.ratioPosition),c&&(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=[f.LittleFinger,f.AnnularFinger,f.MiddleFinger,f.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():f.IndexFinger;for(const e of s){const s=o.addElement("Position");switch(a){case f.LittleFinger:s.attributes.set("finger","Pinky");break;case f.AnnularFinger:s.attributes.set("finger","Ring");break;case f.MiddleFinger:s.attributes.set("finger","Middle");break;case f.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 d=s.addElement("Property");d.attributes.set("name","ShowFingering"),d.attributes.set("type","bool"),d.attributes.set("value",t.showFingering?"true":"false");const c=s.addElement("Chord"),u=c.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=c.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=c.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const m=c.addElement("Degree");m.attributes.set("interval","Fifth"),m.attributes.set("alteration","Perfect"),m.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,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 Ae;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(Ne.instrumentArticulations.values());i.addElement("Name").innerText=wo.DrumKitProgramInfo.instrumentSetName,i.addElement("Type").innerText=wo.DrumKitProgramInfo.instrumentSetType;let s="",r=new ot,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 E.Top:e.addElement("TechniquePlacement").innerText="below";break;case E.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case E.Bottom:e.addElement("TechniquePlacement").innerText="above"}e.addElement("TechniqueSymbol").innerText=this.mapMusicSymbol(t.techniqueSymbol),e.addElement("InputMidiNumbers").innerText="",e.addElement("OutputMidiNumber").innerText=t.outputMidiNumber.toString()}}else{const e=wo.MidiProgramInfoLookup.has(t.playbackInfo.program)?wo.MidiProgramInfoLookup.get(t.playbackInfo.program):wo.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===x.None)return"";let t=x[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!==I.NoTripletFeel&&(i.addElement("TripletFeel").innerText=I[t.tripletFeel]),this.writeFermatas(i,t)}writeFermatas(e,t){var i,s;const a=null!==(s=null===(i=t.fermata)||void 0===i?void 0:i.size)&&void 0!==s?s:0;if(0!==a&&a>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/ye.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=O[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=r[t.clef],t.clefOttava!==n.Regular&&(i.addElement("Ottavia").innerText=n[t.clefOttava].substr(1)),t.simileMark!==o.None&&(i.addElement("SimileMark").innerText=o[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(" ")}}wo.MidiProgramInfoLookup=new Map([[0,new _o(yo.Piano,"Acoustic Piano")],[1,new _o(yo.Piano,"Acoustic Piano")],[2,new _o(yo.Piano,"Electric Piano")],[3,new _o(yo.Piano,"Acoustic Piano")],[4,new _o(yo.Piano,"Electric Piano")],[5,new _o(yo.Piano,"Electric Piano")],[6,new _o(yo.Piano,"Harpsichord")],[7,new _o(yo.Piano,"Harpsichord")],[8,new _o(yo.PitchedIdiophone,"Celesta")],[9,new _o(yo.PitchedIdiophone,"Vibraphone")],[10,new _o(yo.PitchedIdiophone,"Vibraphone")],[11,new _o(yo.PitchedIdiophone,"Vibraphone")],[12,new _o(yo.PitchedIdiophone,"Xylophone")],[13,new _o(yo.PitchedIdiophone,"Xylophone")],[14,new _o(yo.PitchedIdiophone,"Vibraphone")],[15,new _o(yo.Banjo,"Banjo")],[16,new _o(yo.Piano,"Electric Organ")],[17,new _o(yo.Piano,"Electric Organ")],[18,new _o(yo.Piano,"Electric Organ")],[19,new _o(yo.Piano,"Electric Organ")],[20,new _o(yo.Piano,"Electric Organ")],[21,new _o(yo.Piano,"Electric Organ")],[22,new _o(yo.Woodwind,"Recorder")],[23,new _o(yo.Piano,"Electric Organ")],[24,new _o(yo.ClassicalGuitar,"Nylon Guitar")],[25,new _o(yo.SteelGuitar,"Steel Guitar")],[26,new _o(yo.SteelGuitar,"Electric Guitar")],[27,new _o(yo.ElectricGuitar,"Electric Guitar")],[28,new _o(yo.ElectricGuitar,"Electric Guitar")],[29,new _o(yo.ElectricGuitar,"Electric Guitar")],[30,new _o(yo.SteelGuitar,"Electric Guitar")],[31,new _o(yo.SteelGuitar,"Electric Guitar")],[32,new _o(yo.Bass,"Acoustic Bass")],[33,new _o(yo.Bass,"Electric Bass")],[34,new _o(yo.Bass,"Electric Bass")],[35,new _o(yo.Bass,"Acoustic Bass")],[36,new _o(yo.Bass,"Electric Bass")],[37,new _o(yo.Bass,"Electric Bass")],[38,new _o(yo.Synth,"Synth Bass")],[39,new _o(yo.Synth,"Synth Bass")],[40,new _o(yo.Strings,"Violin")],[41,new _o(yo.Strings,"Viola")],[42,new _o(yo.Strings,"Cello")],[43,new _o(yo.Strings,"Contrabass")],[44,new _o(yo.Strings,"Violin")],[45,new _o(yo.Strings,"Violin")],[46,new _o(yo.Piano,"Harp")],[47,new _o(yo.Membraphone,"Timpani")],[48,new _o(yo.Strings,"Violin")],[49,new _o(yo.Strings,"Violin")],[50,new _o(yo.Strings,"Violin")],[51,new _o(yo.Strings,"Violin")],[52,new _o(yo.Vocal,"Voice")],[53,new _o(yo.Vocal,"Voice")],[54,new _o(yo.Vocal,"Voice")],[55,new _o(yo.Synth,"Pad Synthesizer")],[56,new _o(yo.Brass,"Trumpet")],[57,new _o(yo.Brass,"Trombone")],[58,new _o(yo.Brass,"Tuba")],[59,new _o(yo.Brass,"Trumpet")],[60,new _o(yo.Brass,"French Horn")],[61,new _o(yo.Brass,"Trumpet")],[62,new _o(yo.Brass,"Trumpet")],[63,new _o(yo.Brass,"Trumpet")],[64,new _o(yo.Reed,"Saxophone")],[65,new _o(yo.Reed,"Saxophone")],[66,new _o(yo.Reed,"Saxophone")],[67,new _o(yo.Reed,"Saxophone")],[68,new _o(yo.Reed,"Oboe")],[69,new _o(yo.Reed,"English Horn")],[70,new _o(yo.Reed,"Bassoon")],[71,new _o(yo.Reed,"Clarinet")],[72,new _o(yo.Reed,"Piccolo")],[73,new _o(yo.Woodwind,"Flute")],[74,new _o(yo.Woodwind,"Recorder")],[75,new _o(yo.Woodwind,"Flute")],[76,new _o(yo.Woodwind,"Recorder")],[77,new _o(yo.Woodwind,"Flute")],[78,new _o(yo.Woodwind,"Recorder")],[79,new _o(yo.Woodwind,"Flute")],[80,new _o(yo.Synth,"Lead Synthesizer")],[81,new _o(yo.Synth,"Lead Synthesizer")],[82,new _o(yo.Synth,"Lead Synthesizer")],[83,new _o(yo.Synth,"Lead Synthesizer")],[84,new _o(yo.Synth,"Lead Synthesizer")],[85,new _o(yo.Synth,"Lead Synthesizer")],[86,new _o(yo.Synth,"Lead Synthesizer")],[87,new _o(yo.Synth,"Lead Synthesizer")],[88,new _o(yo.Synth,"Pad Synthesizer")],[89,new _o(yo.Synth,"Pad Synthesizer")],[90,new _o(yo.Synth,"Pad Synthesizer")],[91,new _o(yo.Synth,"Pad Synthesizer")],[92,new _o(yo.Synth,"Pad Synthesizer")],[93,new _o(yo.Synth,"Pad Synthesizer")],[94,new _o(yo.Synth,"Pad Synthesizer")],[95,new _o(yo.Synth,"Pad Synthesizer")],[96,new _o(yo.Fx,"Pad Synthesizer")],[97,new _o(yo.Fx,"Pad Synthesizer")],[98,new _o(yo.Fx,"Pad Synthesizer")],[99,new _o(yo.Fx,"Pad Synthesizer")],[100,new _o(yo.Fx,"Lead Synthesizer")],[101,new _o(yo.Fx,"Lead Synthesizer")],[102,new _o(yo.Fx,"Lead Synthesizer")],[103,new _o(yo.Fx,"Trumpet")],[104,new _o(yo.ElectricGuitar,"Banjo")],[105,new _o(yo.Banjo,"Banjo")],[106,new _o(yo.Ukulele,"Ukulele")],[107,new _o(yo.Banjo,"Banjo")],[108,new _o(yo.PitchedIdiophone,"Xylophone")],[109,new _o(yo.Reed,"Bassoon")],[110,new _o(yo.Strings,"Violin")],[111,new _o(yo.Woodwind,"Flute")],[112,new _o(yo.PitchedIdiophone,"Xylophone")],[113,new _o(yo.Idiophone,"Celesta")],[114,new _o(yo.PitchedIdiophone,"Vibraphone")],[115,new _o(yo.Idiophone,"Xylophone")],[116,new _o(yo.Membraphone,"Xylophone")],[117,new _o(yo.Membraphone,"Xylophone")],[118,new _o(yo.Membraphone,"Xylophone")],[119,new _o(yo.Idiophone,"Celesta")],[120,new _o(yo.Fx,"Steel Guitar")],[121,new _o(yo.Fx,"Recorder")],[122,new _o(yo.Fx,"Recorder")],[123,new _o(yo.Fx,"Recorder")],[124,new _o(yo.Fx,"Recorder")],[125,new _o(yo.Fx,"Recorder")],[126,new _o(yo.Fx,"Recorder")],[127,new _o(yo.Fx,"Timpani")]]),wo.DrumKitProgramInfo=new _o(yo.PercussionKit,"Drums","drumKit");class Bo{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==(1&i)?i>>>1^3988292384:i>>>1;e[t]=i}return e}get value(){return~this._checkValue}constructor(){this._checkValue=Bo.CrcInit,this.reset()}update(e,t,i){for(let s=0;s<i;s++)this._checkValue=Bo.Crc32Lookup[255&(this._checkValue^e[t+s])]^this._checkValue>>>8}reset(){this._checkValue=Bo.CrcInit}}Bo.Crc32Lookup=Bo.buildCrc32Lookup(),Bo.CrcInit=4294967295;class To{}To.MAX_WBITS=15,To.WSIZE=1<<To.MAX_WBITS,To.WMASK=To.WSIZE-1,To.MIN_MATCH=3,To.MAX_MATCH=258,To.DEFAULT_MEM_LEVEL=8,To.PENDING_BUF_SIZE=1<<To.DEFAULT_MEM_LEVEL+8,To.HASH_BITS=To.DEFAULT_MEM_LEVEL+7,To.HASH_SIZE=1<<To.HASH_BITS,To.HASH_SHIFT=(To.HASH_BITS+To.MIN_MATCH-1)/To.MIN_MATCH,To.HASH_MASK=To.HASH_SIZE-1,To.MIN_LOOKAHEAD=To.MAX_MATCH+To.MIN_MATCH+1,To.MAX_DIST=To.WSIZE-To.MIN_LOOKAHEAD;class ko{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 d=t[0];s=o++,r[2*s]=e,r[2*s+1]=d;let c=Math.min(255&n[e],255&n[d]);for(l=n[e]+n[d]-c+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[ko.Repeat3To6]++:s<=10?e.freqs[ko.Repeat3To10]++:e.freqs[ko.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(ko.Repeat3To6),this.huffman.pending.writeBits(s-3,2)):s<=10?(e.writeSymbol(ko.Repeat3To10),this.huffman.pending.writeBits(s-3,3)):(e.writeSymbol(ko.Repeat11To138),this.huffman.pending.writeBits(s-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}ko.Repeat3To6=16,ko.Repeat3To10=17,ko.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 ko(this,vo.LITERAL_NUM,257,15),this.distTree=new ko(this,vo.DIST_NUM,1,15),this.blTree=new ko(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<<To.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 No{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 Bo,this.window=new Uint8Array(2*To.WSIZE),this.head=new Int16Array(To.HASH_SIZE),this.prev=new Int16Array(To.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=To.MIN_MATCH-1;for(let e=0;e<To.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<To.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<To.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<To.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=To.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*To.WSIZE-To.MIN_LOOKAHEAD&&this.slideWindow();let e=this.matchStart,i=this.matchLen;if(this.lookahead>=To.MIN_MATCH){let e=this.insertString();0!=e&&this.strstart-e<=To.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen==To.MIN_MATCH&&this.strstart-this.matchStart>No.TooFar&&(this.matchLen=To.MIN_MATCH-1)}if(i>=To.MIN_MATCH&&this.matchLen<=i){this.huffman.tallyDist(this.strstart-1-e,i),i-=2;do{this.strstart++,this.lookahead--,this.lookahead>=To.MIN_MATCH&&this.insertString()}while(--i>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=To.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(To.MAX_MATCH,this.lookahead)-1,a=Math.max(i-To.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,To.MIN_MATCH-1),i+this.matchLen>s)return!1;let l=r[i+this.matchLen-1],d=r[i+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,i=this.strstart,r[t+this.matchLen]==d&&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],d=r[i]}e=65535&n[e&To.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=To.MIN_MATCH}insertString(){let e,t=(this.insertHashIndex<<To.HASH_SHIFT^this.window[this.strstart+(To.MIN_MATCH-1)])&To.HASH_MASK;return e=this.head[t],this.prev[this.strstart&To.WMASK]=e,this.head[t]=this.strstart,this.insertHashIndex=t,65535&e}fillWindow(){if(this.strstart>=To.WSIZE+To.MAX_DIST&&this.slideWindow(),this.lookahead<To.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*To.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>=To.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(To.WSIZE,To.WSIZE+To.WSIZE),0),this.matchStart-=To.WSIZE,this.strstart-=To.WSIZE,this.blockStart-=To.WSIZE;for(let e=0;e<To.HASH_SIZE;++e){let t=65535&this.head[e];this.head[e]=t>=To.WSIZE?t-To.WSIZE:0}for(let e=0;e<To.WSIZE;e++){let t=65535&this.prev[e];this.prev[e]=t>=To.WSIZE?t-To.WSIZE:0}}}No.TooFar=4096;class xo{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 Po{get inputCrc(){return this._engine.inputCrc.value}constructor(){this._state=0,this._pending=new xo(To.PENDING_BUF_SIZE),this._engine=new No(this._pending),this.reset()}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state==Po.FinishedState&&this._pending.isFlushed}reset(){this._state=Po.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==Po.FinishedState)break;if(!this._engine.deflate(0!=(this._state&Po.IsFlushing),0!=(this._state&Po.IsFinishing)))switch(this._state){case Po.BusyState:return s-i;case Po.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=Po.BusyState;break;case Po.FinishingState:this._pending.alignToByte(),this._state=Po.FinishedState}}return s-i}finish(){this._state|=Po.IsFlushing|Po.IsFinishing}}Po.IsFlushing=4,Po.IsFinishing=8,Po.BusyState=16,Po.FlushingState=20,Po.FinishingState=28,Po.FinishedState=30;class Eo{constructor(e,t,i,s,a){this.entry=e,this.crc32=t,this.localHeaderOffset=i,this.compressionMode=s,this.compressedSize=a}}class Co{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new Po,this._data=e}writeEntry(e){const t=vt.CompressionMethodDeflate,i=Ke.empty(),s=this.compress(i,e.data,t),a=i.toArray(),r=new Eo(e,s,this._data.bytesWritten,t,i.length);this._centralDirectoryHeaders.push(r),$e.writeInt32LE(this._data,vt.LocalFileHeaderSignature),$e.writeUInt16LE(this._data,10),$e.writeUInt16LE(this._data,2048),$e.writeUInt16LE(this._data,t),$e.writeInt16LE(this._data,0),$e.writeInt16LE(this._data,0),$e.writeInt32LE(this._data,s),$e.writeInt32LE(this._data,a.length),$e.writeInt32LE(this._data,e.data.length),$e.writeInt16LE(this._data,e.fullName.length),$e.writeInt16LE(this._data,0);const n=$e.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,i){if(i!=vt.CompressionMethodDeflate){const i=new Bo;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){$e.writeInt32LE(this._data,vt.EndOfCentralDirSignature),$e.writeInt16LE(this._data,0),$e.writeInt16LE(this._data,0),$e.writeInt16LE(this._data,this._centralDirectoryHeaders.length),$e.writeInt16LE(this._data,this._centralDirectoryHeaders.length),$e.writeInt32LE(this._data,t-e),$e.writeInt32LE(this._data,e),$e.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){$e.writeInt32LE(this._data,vt.CentralFileHeaderSignature),$e.writeUInt16LE(this._data,10),$e.writeUInt16LE(this._data,10),$e.writeUInt16LE(this._data,2048),$e.writeUInt16LE(this._data,e.compressionMode),$e.writeInt16LE(this._data,0),$e.writeInt16LE(this._data,0),$e.writeInt32LE(this._data,e.crc32),$e.writeInt32LE(this._data,e.compressedSize),$e.writeInt32LE(this._data,e.entry.data.length),$e.writeInt16LE(this._data,e.entry.fullName.length),$e.writeInt16LE(this._data,0),$e.writeInt16LE(this._data,0),$e.writeInt16LE(this._data,0),$e.writeInt16LE(this._data,0),$e.writeInt32LE(this._data,0),$e.writeInt32LE(this._data,e.localHeaderOffset);const t=$e.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}var Fo=Object.freeze({__proto__:null,ScoreExporter:So,Gp7Exporter:class extends So{get name(){return"Guitar Pro 7"}constructor(){super()}writeScore(e){Be.debug(this.name,"Writing data entries");const t=(new wo).writeXml(e),i=rt.writeForScore(e),s=yt.writeForScore(e);Be.debug(this.name,"Writing ZIP entries");let a=new Co(this.data);a.writeEntry(new vt("VERSION",$e.stringToBytes("7.0"))),a.writeEntry(new vt("Content/",new Uint8Array(0))),a.writeEntry(new vt("Content/BinaryStylesheet",i)),a.writeEntry(new vt("Content/PartConfiguration",s)),a.writeEntry(new vt("Content/score.gpif",$e.stringToBytes(t))),a.end()}}}),Lo=Object.freeze({__proto__:null,BeatTickLookup:Bs,MasterBarTickLookup:vs,MidiTickLookup:xs,MidiTickLookupFindBeatResult:Ns,MidiFile:_i,get ControllerType(){return te},MetaDataEvent:wi,MetaEvent:It,get MetaEventType(){return U},MetaNumberEvent:Bi,MidiEvent:Dt,get MidiEventType(){return z},Midi20PerNotePitchBendEvent:zi,SystemCommonEvent:Rt,get SystemCommonType(){return X},SystemExclusiveEvent:At,MidiFileGenerator:Cs,AlphaSynthMidiFileHandler:ws}),Mo=Object.freeze({__proto__:null,get AccentuationType(){return s},get AccidentalType(){return re},get AutomationType(){return a},Automation:fe,Bar:me,Beat:Ie,BendPoint:be,get BendStyle(){return h},get BendType(){return l},get BrushType(){return d},Chord:Re,get Clef(){return r},Color:Ue,get CrescendoType(){return c},get Duration(){return u},get DynamicValue(){return p},get FermataType(){return O},Fermata:nt,get Fingers(){return f},get FontStyle(){return K},Font:Ni,get GraceType(){return g},get HarmonicType(){return m},InstrumentArticulation:ve,JsonConverter:os,get KeySignature(){return L},get KeySignatureType(){return D},Lyrics:Ae,MasterBar:Oe,get MusicFontSymbol(){return x},Note:Pe,get NoteAccidentalMode(){return y},get Ottavia(){return n},get PickStroke(){return N},PlaybackInformation:Xe,RenderStylesheet:Ge,RepeatGroup:Ve,Score:He,Section:We,get SimileMark(){return o},get SlideInType(){return b},get SlideOutType(){return S},Staff:qe,Track:Je,get TripletFeel(){return I},Tuning:Ye,TupletGroup:Ee,get VibratoType(){return _},Voice:je,get WhammyType(){return C}}),Do=Object.freeze({__proto__:null,RenderFinishedEventArgs:cs,ScoreRenderer:bs,BarBounds:us,BeatBounds:ps,Bounds:at,BoundsLookup:ys,MasterBarBounds:gs,NoteBounds:fs,StaveGroupBounds:ms}),Io=Object.freeze({__proto__:null,AlphaSynth:Si,CircularSampleBuffer:qs,PlaybackRange:Fs,get PlayerState(){return q},PlayerStateChangedEventArgs:zt,PlaybackRangeChangedEventArgs:bi,PositionChangedEventArgs:Ut,MidiEventsPlayedEventArgs:yi,ActiveBeatsChangedEventArgs:Gs,AlphaSynthWebWorkerApi:$s,AlphaSynthWebAudioOutputBase:Js,AlphaSynthScriptProcessorOutput:js,AlphaSynthAudioWorkletOutput:ta});export{aa as AlphaTabApi,pe as AlphaTabError,i as AlphaTabErrorType,fo as CoreSettings,Pi as DisplaySettings,Ws as FileLoadError,B as FingeringMode,ze as FormatError,Ei as ImporterSettings,e as LayoutMode,v as LogLevel,Be as Logger,T as NotationMode,Se as NotationSettings,Li as PlayerSettings,Qs as ProgressEventArgs,xi as RenderingResources,Os as ResizeEventArgs,ee as ScrollMode,Wi as Settings,t as StaveProfile,w as TabRhythmMode,Ci as VibratoPlaybackSettings,Fo as exporter,bo as importer,mo as meta,Lo as midi,Mo as model,Do as rendering,Io as synth};
|
|
17
|
+
var e,t,i,s,a,r,n,o,h,l,d,c,u,p,g,f,m,y,b,S,_,w,B,T,k,v,N,x,P,E,C,F,L,M,D,I,R,A,O,G,V,H,W,z,U,X,Y,q,J,j,Q,$,K,Z,ee,te,ie,se,ae,re,ne,oe,he,le,de;!function(e){e[e.Page=0]="Page",e[e.Horizontal=1]="Horizontal"}(e||(e={})),function(e){e[e.Default=0]="Default",e[e.ScoreTab=1]="ScoreTab",e[e.Score=2]="Score",e[e.Tab=3]="Tab",e[e.TabMixed=4]="TabMixed"}(t||(t={}));class ce{static getValue(e){return ce._values||(ce._values=new Map),e=e.toLowerCase().replaceAll(" ",""),ce._values.has(e)?ce._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}}ce._values=new Map([["acousticgrandpiano",0],["brightacousticpiano",1],["electricgrandpiano",2],["honkytonkpiano",3],["electricpiano1",4],["electricpiano2",5],["harpsichord",6],["clavinet",7],["celesta",8],["glockenspiel",9],["musicbox",10],["vibraphone",11],["marimba",12],["xylophone",13],["tubularbells",14],["dulcimer",15],["drawbarorgan",16],["percussiveorgan",17],["rockorgan",18],["churchorgan",19],["reedorgan",20],["accordion",21],["harmonica",22],["tangoaccordion",23],["acousticguitarnylon",24],["acousticguitarsteel",25],["electricguitarjazz",26],["electricguitarclean",27],["electricguitarmuted",28],["overdrivenguitar",29],["distortionguitar",30],["guitarharmonics",31],["acousticbass",32],["electricbassfinger",33],["electricbasspick",34],["fretlessbass",35],["slapbass1",36],["slapbass2",37],["synthbass1",38],["synthbass2",39],["violin",40],["viola",41],["cello",42],["contrabass",43],["tremolostrings",44],["pizzicatostrings",45],["orchestralharp",46],["timpani",47],["stringensemble1",48],["stringensemble2",49],["synthstrings1",50],["synthstrings2",51],["choiraahs",52],["voiceoohs",53],["synthvoice",54],["orchestrahit",55],["trumpet",56],["trombone",57],["tuba",58],["mutedtrumpet",59],["frenchhorn",60],["brasssection",61],["synthbrass1",62],["synthbrass2",63],["sopranosax",64],["altosax",65],["tenorsax",66],["baritonesax",67],["oboe",68],["englishhorn",69],["bassoon",70],["clarinet",71],["piccolo",72],["flute",73],["recorder",74],["panflute",75],["blownbottle",76],["shakuhachi",77],["whistle",78],["ocarina",79],["lead1square",80],["lead2sawtooth",81],["lead3calliope",82],["lead4chiff",83],["lead5charang",84],["lead6voice",85],["lead7fifths",86],["lead8bassandlead",87],["pad1newage",88],["pad2warm",89],["pad3polysynth",90],["pad4choir",91],["pad5bowed",92],["pad6metallic",93],["pad7halo",94],["pad8sweep",95],["fx1rain",96],["fx2soundtrack",97],["fx3crystal",98],["fx4atmosphere",99],["fx5brightness",100],["fx6goblins",101],["fx7echoes",102],["fx8scifi",103],["sitar",104],["banjo",105],["shamisen",106],["koto",107],["kalimba",108],["bagpipe",109],["fiddle",110],["shanai",111],["tinklebell",112],["agogo",113],["steeldrums",114],["woodblock",115],["taikodrum",116],["melodictom",117],["synthdrum",118],["reversecymbal",119],["guitarfretnoise",120],["breathnoise",121],["seashore",122],["birdtweet",123],["telephonering",124],["helicopter",125],["applause",126],["gunshot",127]]);class ue{init(e,t){this.data=e,this.settings=t}}!function(e){e[e.General=0]="General",e[e.Format=1]="Format",e[e.AlphaTex=2]="AlphaTex"}(i||(i={}));class pe extends Error{constructor(e,t="",i){super(null!=t?t:""),this.type=e,this.inner=null!=i?i:null,Object.setPrototypeOf(this,pe.prototype)}}class ge extends pe{constructor(e=null,t=null){super(i.Format,null!=e?e:"Unsupported format"),this.inner=t,Object.setPrototypeOf(this,ge.prototype)}}!function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy"}(s||(s={})),function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(a||(a={}));class fe{constructor(){this.isLinear=!1,this.type=a.Tempo,this.value=0,this.ratioPosition=0,this.text=""}static buildTempoAutomation(e,t,i,s){(s<1||s>5)&&(s=2);let r=new Float32Array([1,.5,1,1.5,2,3]),n=new fe;return n.type=a.Tempo,n.isLinear=e,n.ratioPosition=t,n.value=i*r[s],n}static buildInstrumentAutomation(e,t,i){let s=new fe;return s.type=a.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"}(r||(r={})),function(e){e[e._15ma=0]="_15ma",e[e._8va=1]="_8va",e[e.Regular=2]="Regular",e[e._8vb=3]="_8vb",e[e._15mb=4]="_15mb"}(n||(n={})),function(e){e[e.None=0]="None",e[e.Simple=1]="Simple",e[e.FirstOfDouble=2]="FirstOfDouble",e[e.SecondOfDouble=3]="SecondOfDouble"}(o||(o={}));class me{constructor(){this.id=me._globalBarId++,this.index=0,this.nextBar=null,this.previousBar=null,this.clef=r.G2,this.clefOttava=n.Regular,this.voices=[],this.simileMark=o.None,this.isMultiVoice=!1}get masterBar(){return this.staff.track.score.masterBars[this.index]}get isEmpty(){for(let e=0,t=this.voices.length;e<t;e++)if(!this.voices[e].isEmpty)return!1;return!0}addVoice(e){e.bar=this,e.index=this.voices.length,this.voices.push(e)}finish(e,t=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}}me._globalBarId=0;class ye{static ticksToMillis(e,t){return e*(6e4/(t*ye.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*ye.QuarterTime))|0}static toTicks(e){return ye.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),ye.QuarterTime*(4/t)|0}static applyDot(e,t){return t?e+3*(e/4|0):e+(e/2|0)}static applyTuplet(e,t,i){return e*i/t|0}static removeTuplet(e,t,i){return e*t/i|0}static dynamicToVelocity(e){return ye.MinVelocity+e*ye.VelocityIncrement}}ye.QuarterTime=960,ye.MinVelocity=15,ye.VelocityIncrement=16;class be{constructor(e=0,t=0){this.offset=e,this.value=t}}be.MaxPosition=60,be.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(h||(h={})),function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Bend=2]="Bend",e[e.Release=3]="Release",e[e.BendRelease=4]="BendRelease",e[e.Hold=5]="Hold",e[e.Prebend=6]="Prebend",e[e.PrebendBend=7]="PrebendBend",e[e.PrebendRelease=8]="PrebendRelease"}(l||(l={})),function(e){e[e.None=0]="None",e[e.BrushUp=1]="BrushUp",e[e.BrushDown=2]="BrushDown",e[e.ArpeggioUp=3]="ArpeggioUp",e[e.ArpeggioDown=4]="ArpeggioDown"}(d||(d={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(c||(c={})),function(e){e[e.QuadrupleWhole=-4]="QuadrupleWhole",e[e.DoubleWhole=-2]="DoubleWhole",e[e.Whole=1]="Whole",e[e.Half=2]="Half",e[e.Quarter=4]="Quarter",e[e.Eighth=8]="Eighth",e[e.Sixteenth=16]="Sixteenth",e[e.ThirtySecond=32]="ThirtySecond",e[e.SixtyFourth=64]="SixtyFourth",e[e.OneHundredTwentyEighth=128]="OneHundredTwentyEighth",e[e.TwoHundredFiftySixth=256]="TwoHundredFiftySixth"}(u||(u={})),function(e){e[e.PPP=0]="PPP",e[e.PP=1]="PP",e[e.P=2]="P",e[e.MP=3]="MP",e[e.MF=4]="MF",e[e.F=5]="F",e[e.FF=6]="FF",e[e.FFF=7]="FFF"}(p||(p={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(g||(g={})),function(e){e[e.Unknown=-2]="Unknown",e[e.NoOrDead=-1]="NoOrDead",e[e.Thumb=0]="Thumb",e[e.IndexFinger=1]="IndexFinger",e[e.MiddleFinger=2]="MiddleFinger",e[e.AnnularFinger=3]="AnnularFinger",e[e.LittleFinger=4]="LittleFinger"}(f||(f={})),function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Artificial=2]="Artificial",e[e.Pinch=3]="Pinch",e[e.Tap=4]="Tap",e[e.Semi=5]="Semi",e[e.Feedback=6]="Feedback"}(m||(m={})),function(e){e[e.Default=0]="Default",e[e.ForceNone=1]="ForceNone",e[e.ForceNatural=2]="ForceNatural",e[e.ForceSharp=3]="ForceSharp",e[e.ForceDoubleSharp=4]="ForceDoubleSharp",e[e.ForceFlat=5]="ForceFlat",e[e.ForceDoubleFlat=6]="ForceDoubleFlat"}(y||(y={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(b||(b={})),function(e){e[e.None=0]="None",e[e.Shift=1]="Shift",e[e.Legato=2]="Legato",e[e.OutUp=3]="OutUp",e[e.OutDown=4]="OutDown",e[e.PickSlideDown=5]="PickSlideDown",e[e.PickSlideUp=6]="PickSlideUp"}(S||(S={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(_||(_={})),function(e){e[e.Hidden=0]="Hidden",e[e.ShowWithBeams=1]="ShowWithBeams",e[e.ShowWithBars=2]="ShowWithBars"}(w||(w={})),function(e){e[e.ScoreDefault=0]="ScoreDefault",e[e.ScoreForcePiano=1]="ScoreForcePiano",e[e.SingleNoteEffectBand=2]="SingleNoteEffectBand",e[e.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano"}(B||(B={})),function(e){e[e.GuitarPro=0]="GuitarPro",e[e.SongBook=1]="SongBook"}(T||(T={})),function(e){e[e.ScoreTitle=0]="ScoreTitle",e[e.ScoreSubTitle=1]="ScoreSubTitle",e[e.ScoreArtist=2]="ScoreArtist",e[e.ScoreAlbum=3]="ScoreAlbum",e[e.ScoreWords=4]="ScoreWords",e[e.ScoreMusic=5]="ScoreMusic",e[e.ScoreWordsAndMusic=6]="ScoreWordsAndMusic",e[e.ScoreCopyright=7]="ScoreCopyright",e[e.GuitarTuning=8]="GuitarTuning",e[e.TrackNames=9]="TrackNames",e[e.ChordDiagrams=10]="ChordDiagrams",e[e.ParenthesisOnTiedBends=11]="ParenthesisOnTiedBends",e[e.TabNotesOnTiedBends=12]="TabNotesOnTiedBends",e[e.ZerosOnDiveWhammys=13]="ZerosOnDiveWhammys",e[e.EffectAlternateEndings=14]="EffectAlternateEndings",e[e.EffectCapo=15]="EffectCapo",e[e.EffectChordNames=16]="EffectChordNames",e[e.EffectCrescendo=17]="EffectCrescendo",e[e.EffectDynamics=18]="EffectDynamics",e[e.EffectFadeIn=19]="EffectFadeIn",e[e.EffectFermata=20]="EffectFermata",e[e.EffectFingering=21]="EffectFingering",e[e.EffectHarmonics=22]="EffectHarmonics",e[e.EffectLetRing=23]="EffectLetRing",e[e.EffectLyrics=24]="EffectLyrics",e[e.EffectMarker=25]="EffectMarker",e[e.EffectOttavia=26]="EffectOttavia",e[e.EffectPalmMute=27]="EffectPalmMute",e[e.EffectPickSlide=28]="EffectPickSlide",e[e.EffectPickStroke=29]="EffectPickStroke",e[e.EffectSlightBeatVibrato=30]="EffectSlightBeatVibrato",e[e.EffectSlightNoteVibrato=31]="EffectSlightNoteVibrato",e[e.EffectTap=32]="EffectTap",e[e.EffectTempo=33]="EffectTempo",e[e.EffectText=34]="EffectText",e[e.EffectTrill=35]="EffectTrill",e[e.EffectTripletFeel=36]="EffectTripletFeel",e[e.EffectWhammyBar=37]="EffectWhammyBar",e[e.EffectWideBeatVibrato=38]="EffectWideBeatVibrato",e[e.EffectWideNoteVibrato=39]="EffectWideNoteVibrato",e[e.EffectLeftHandTap=40]="EffectLeftHandTap"}(k||(k={}));class Se{constructor(){this.notationMode=T.GuitarPro,this.fingeringMode=B.ScoreDefault,this.elements=new Map,this.rhythmMode=w.Hidden,this.rhythmHeight=15,this.transpositionPitches=[],this.displayTranspositionPitches=[],this.smallGraceTabNotes=!0,this.extendBendArrowsOnTiedNotes=!0,this.extendLineEffectsToBeatEnd=!1,this.slurHeight=5}isNotationElementVisible(e){return this.elements.has(e)?this.elements.get(e):!Se.defaultElements.has(e)||Se.defaultElements.get(e)}}Se.defaultElements=new Map([[k.ZerosOnDiveWhammys,!1]]);class _e{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}!function(e){e[e.None=0]="None",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warning=3]="Warning",e[e.Error=4]="Error"}(v||(v={}));class we{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...i){console.debug(we.format(e,t),...i)}warning(e,t,...i){console.warn(we.format(e,t),...i)}info(e,t,...i){console.info(we.format(e,t),...i)}error(e,t,...i){console.error(we.format(e,t),...i)}}we.logLevel=v.Info;class Be{static shouldLog(e){return Be.logLevel!==v.None&&e>=Be.logLevel}static debug(e,t,...i){Be.shouldLog(v.Debug)&&Be.log.debug(e,t,...i)}static warning(e,t,...i){Be.shouldLog(v.Warning)&&Be.log.warning(e,t,...i)}static info(e,t,...i){Be.shouldLog(v.Info)&&Be.log.info(e,t,...i)}static error(e,t,...i){Be.shouldLog(v.Error)&&Be.log.error(e,t,...i)}}Be.logLevel=v.Info,Be.log=new we;class Te{constructor(){this.note=null,this.noteValue=0,this.octave=0}get realValue(){return 12*this.octave+this.noteValue}}class ke{static getIndex(e){return e<0?0:0|Math.log2(e)}static keySignatureIsFlat(e){return e<0}static keySignatureIsNatural(e){return 0===e}static keySignatureIsSharp(e){return e>0}static applyPitchOffsets(e,t){for(let 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(e,t,i,s){if(e.notation.fingeringMode===B.ScoreForcePiano||e.notation.fingeringMode===B.SingleNoteEffectBandForcePiano||ce.isPiano(t.voice.bar.staff.track.playbackInfo.program))switch(i){case f.Unknown:case f.NoOrDead:return null;case f.Thumb:return"1";case f.IndexFinger:return"2";case f.MiddleFinger:return"3";case f.AnnularFinger:return"4";case f.LittleFinger:return"5";default:return null}if(s)switch(i){case f.Unknown:case f.NoOrDead:return"0";case f.Thumb:return"T";case f.IndexFinger:return"1";case f.MiddleFinger:return"2";case f.AnnularFinger:return"3";case f.LittleFinger:return"4";default:return null}switch(i){case f.Unknown:case f.NoOrDead:return null;case f.Thumb:return"p";case f.IndexFinger:return"i";case f.MiddleFinger:return"m";case f.AnnularFinger:return"a";case f.LittleFinger:return"c";default:return null}}static isTuning(e){return!!ke.parseTuning(e)}static parseTuning(e){let t="",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 Te;return s.octave=parseInt(i)+1,s.note=t.toLowerCase(),s.noteValue=ke.getToneForText(s.note),s}static getTuningForText(e){let t=ke.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"}(x||(x={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(P||(P={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(E||(E={}));class ve{constructor(e="",t=0,i=0,s=x.None,a=x.None,r=x.None,n=x.None,o=E.Middle){this.elementType=e,this.outputMidiNumber=i,this.staffLine=t,this.noteHeadDefault=s,this.noteHeadHalf=a!==x.None?a:s,this.noteHeadWhole=r!==x.None?r:s,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case u.Whole:return this.noteHeadWhole;case u.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class Ne{static articulationFromElementVariation(e,t){return e<Ne.gp6ElementAndVariationToArticulation.length?(t>=Ne.gp6ElementAndVariationToArticulation.length&&(t=0),Ne.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]:Ne.getArticulationByValue(t)}static getElementAndVariation(e){const t=Ne.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<Ne.gp6ElementAndVariationToArticulation.length;e++){const i=Ne.gp6ElementAndVariationToArticulation[e];for(let s=0;s<i.length;s++){const a=Ne.getArticulationByValue(i[s]);if((null==a?void 0:a.outputMidiNumber)===t.outputMidiNumber)return[e,s]}}return[-1,-1]}static getArticulationByValue(e){return Ne.instrumentArticulations.has(e)?Ne.instrumentArticulations.get(e):null}}Ne.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]],Ne.instrumentArticulations=new Map([[38,new ve("snare",3,38,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[37,new ve("snare",3,37,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[91,new ve("snare",3,38,x.NoteheadDiamondWhite,x.NoteheadDiamondWhite,x.NoteheadDiamondWhite)],[42,new ve("hiHat",-1,42,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[92,new ve("hiHat",-1,46,x.NoteheadCircleSlash,x.NoteheadCircleSlash,x.NoteheadCircleSlash)],[46,new ve("hiHat",-1,46,x.NoteheadCircleX,x.NoteheadCircleX,x.NoteheadCircleX)],[44,new ve("hiHat",9,44,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[35,new ve("kickDrum",8,35,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[36,new ve("kickDrum",7,36,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[50,new ve("tom",1,50,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[48,new ve("tom",2,48,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[47,new ve("tom",4,47,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[45,new ve("tom",5,45,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[43,new ve("tom",6,43,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[93,new ve("ride",0,51,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack,x.PictEdgeOfCymbal,E.Bottom)],[51,new ve("ride",0,51,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[53,new ve("ride",0,53,x.NoteheadDiamondWhite,x.NoteheadDiamondWhite,x.NoteheadDiamondWhite)],[94,new ve("ride",0,51,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack,x.ArticStaccatoAbove,E.Top)],[55,new ve("splash",-2,55,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[95,new ve("splash",-2,55,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack,x.ArticStaccatoAbove,E.Bottom)],[52,new ve("china",-3,52,x.NoteheadHeavyXHat,x.NoteheadHeavyXHat,x.NoteheadHeavyXHat)],[96,new ve("china",-3,52,x.NoteheadHeavyXHat,x.NoteheadHeavyXHat,x.NoteheadHeavyXHat)],[49,new ve("crash",-2,49,x.NoteheadHeavyX,x.NoteheadHeavyX,x.NoteheadHeavyX)],[97,new ve("crash",-2,49,x.NoteheadHeavyX,x.NoteheadHeavyX,x.NoteheadHeavyX,x.ArticStaccatoAbove,E.Bottom)],[57,new ve("crash",-1,57,x.NoteheadHeavyX,x.NoteheadHeavyX,x.NoteheadHeavyX)],[98,new ve("crash",-1,57,x.NoteheadHeavyX,x.NoteheadHeavyX,x.NoteheadHeavyX,x.ArticStaccatoAbove,E.Bottom)],[99,new ve("cowbell",1,56,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpHalf,x.NoteheadTriangleUpWhole)],[100,new ve("cowbell",1,56,x.NoteheadXBlack,x.NoteheadXHalf,x.NoteheadXWhole)],[56,new ve("cowbell",0,56,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpHalf,x.NoteheadTriangleUpWhole)],[101,new ve("cowbell",0,56,x.NoteheadXBlack,x.NoteheadXHalf,x.NoteheadXWhole)],[102,new ve("cowbell",-1,56,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpHalf,x.NoteheadTriangleUpWhole)],[103,new ve("cowbell",-1,56,x.NoteheadXBlack,x.NoteheadXHalf,x.NoteheadXWhole)],[77,new ve("woodblock",-9,77,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack)],[76,new ve("woodblock",-10,76,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack)],[60,new ve("bongo",-4,60,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[104,new ve("bongo",-5,60,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.NoteheadParenthesis,E.Middle)],[105,new ve("bongo",-6,60,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[61,new ve("bongo",-7,61,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[106,new ve("bongo",-8,61,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.NoteheadParenthesis,E.Middle)],[107,new ve("bongo",-16,61,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[66,new ve("timbale",10,66,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[65,new ve("timbale",9,65,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[68,new ve("agogo",12,68,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[67,new ve("agogo",11,67,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[64,new ve("conga",17,64,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[108,new ve("conga",16,64,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[109,new ve("conga",15,64,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.NoteheadParenthesis,E.Middle)],[63,new ve("conga",14,63,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[110,new ve("conga",13,63,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[62,new ve("conga",19,62,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.NoteheadParenthesis,E.Middle)],[72,new ve("whistle",-11,72,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[71,new ve("whistle",-17,71,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[73,new ve("guiro",38,73,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[74,new ve("guiro",37,74,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[86,new ve("surdo",36,86,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[87,new ve("surdo",35,87,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadParenthesis,E.Middle)],[54,new ve("tambourine",3,54,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack)],[111,new ve("tambourine",2,54,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack,x.StringsUpBow,E.Bottom)],[112,new ve("tambourine",1,54,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack,x.NoteheadTriangleUpBlack,x.StringsDownBow,E.Bottom)],[113,new ve("tambourine",-7,54,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[79,new ve("cuica",30,79,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[78,new ve("cuica",29,78,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[58,new ve("vibraslap",28,58,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[81,new ve("triangle",27,81,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[80,new ve("triangle",26,80,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadParenthesis,E.Middle)],[114,new ve("grancassa",25,43,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[115,new ve("piatti",18,49,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[116,new ve("piatti",24,49,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[69,new ve("cabasa",23,69,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[117,new ve("cabasa",22,69,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.StringsUpBow,E.Bottom)],[85,new ve("castanets",21,85,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[75,new ve("claves",20,75,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[70,new ve("maraca",-12,70,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[118,new ve("maraca",-13,70,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.StringsUpBow,E.Bottom)],[119,new ve("maraca",-14,70,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[120,new ve("maraca",-15,70,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.StringsUpBow,E.Bottom)],[82,new ve("shaker",-23,54,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[122,new ve("shaker",-24,54,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.StringsUpBow,E.Bottom)],[84,new ve("bellTree",-18,53,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[123,new ve("bellTree",-19,53,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole,x.StringsUpBow,E.Bottom)],[83,new ve("jingleBell",-20,53,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[124,new ve("unpitched",-21,62,x.NoteheadNull,x.NoteheadNull,x.NoteheadNull,x.GuitarGolpe,E.Top)],[125,new ve("unpitched",-22,62,x.NoteheadNull,x.NoteheadNull,x.NoteheadNull,x.GuitarGolpe,E.Bottom)],[39,new ve("handClap",3,39,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[40,new ve("snare",3,40,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[31,new ve("snare",3,40,x.NoteheadSlashedBlack2,x.NoteheadSlashedBlack2,x.NoteheadSlashedBlack2)],[41,new ve("tom",5,41,x.NoteheadBlack,x.NoteheadHalf,x.NoteheadWhole)],[59,new ve("ride",2,59,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack,x.PictEdgeOfCymbal,E.Bottom)],[126,new ve("ride",2,59,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[127,new ve("ride",2,59,x.NoteheadDiamondWhite,x.NoteheadDiamondWhite,x.NoteheadDiamondWhite)],[29,new ve("ride",2,59,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack,x.ArticStaccatoAbove,E.Top)],[30,new ve("crash",-3,49,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[33,new ve("snare",3,37,x.NoteheadXBlack,x.NoteheadXBlack,x.NoteheadXBlack)],[34,new ve("snare",3,38,x.NoteheadBlack,x.NoteheadBlack,x.NoteheadBlack)]]);class xe{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1}}class Pe{constructor(){this.id=Pe.GlobalNoteId++,this.index=0,this.accentuated=s.None,this.bendType=l.None,this.bendStyle=h.Default,this.bendOrigin=null,this.isContinuedBend=!1,this.bendPoints=null,this.maxBendPoint=null,this.fret=-1,this.string=-1,this.octave=-1,this.tone=-1,this.percussionArticulation=-1,this.isVisible=!0,this.isLeftHandTapped=!1,this.isHammerPullOrigin=!1,this.hammerPullOrigin=null,this.hammerPullDestination=null,this.isSlurDestination=!1,this.slurOrigin=null,this.slurDestination=null,this.harmonicType=m.None,this.harmonicValue=0,this.isGhost=!1,this.isLetRing=!1,this.letRingDestination=null,this.isPalmMute=!1,this.palmMuteDestination=null,this.isDead=!1,this.isStaccato=!1,this.slideInType=b.None,this.slideOutType=S.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=_.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=f.Unknown,this.rightHandFinger=f.Unknown,this.isFingering=!1,this.trillValue=-1,this.trillSpeed=u.ThirtySecond,this.durationPercent=1,this.accidentalMode=y.Default,this.dynamics=p.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this._noteIdBag=null}get hasBend(){return null!==this.bendPoints&&this.bendType!==l.None}get isStringed(){return this.string>=0}get isPiano(){return!this.isStringed&&this.octave>=0&&this.tone>=0}get isPercussion(){return!this.isStringed&&this.percussionArticulation>=0}get element(){return this.isPercussion?Ne.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?Ne.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==m.None}get isTieOrigin(){return null!==this.tieDestination}get trillFret(){return this.trillValue-this.stringTuning}get isTrill(){return this.trillValue>=0}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get stringTuning(){return this.beat.voice.bar.staff.capo+Pe.getStringTuning(this.beat.voice.bar.staff,this.string)}static getStringTuning(e,t){return e.tuning.length>0?e.tuning[e.tuning.length-(t-1)-1]:0}get realValue(){let e=this.realValueWithoutHarmonic;return this.isStringed&&(this.harmonicType===m.Natural?e=this.harmonicPitch+this.stringTuning-this.beat.voice.bar.staff.transpositionPitch:e+=this.harmonicPitch),e}get realValueWithoutHarmonic(){return this.isPercussion?this.percussionArticulation:this.isStringed?this.fret+this.stringTuning-this.beat.voice.bar.staff.transpositionPitch:this.isPiano?12*this.octave+this.tone-this.beat.voice.bar.staff.transpositionPitch:0}get harmonicPitch(){if(this.harmonicType===m.None||!this.isStringed)return 0;let e=this.harmonicValue;return ke.isAlmostEqualTo(e,2.4)?36:ke.isAlmostEqualTo(e,2.7)?34:e<3?0:e<=3.5?31:e<=4?28:e<=5?24:e<=6?34:e<=7?19:e<=8.5?36:e<=9?28:e<=10?34:e<=11?0:e<=12?12:e<14?0:e<=15?34:e<=16?28:e<=17?36:e<=18?0:e<=19?19:e<=21?0:e<=22?36:e<=24?24:0}get initialBendValue(){return this.hasBend?Math.floor(this.bendPoints[0].value/2):this.bendOrigin?Math.floor(this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value/2):this.isTieDestination&&this.tieOrigin.bendOrigin?Math.floor(this.tieOrigin.bendOrigin.bendPoints[this.tieOrigin.bendOrigin.bendPoints.length-1].value/2):this.beat.hasWhammyBar?Math.floor(this.beat.whammyBarPoints[0].value/2):this.beat.isContinuedWhammy?Math.floor(this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value/2):0}get displayValue(){return this.displayValueWithoutBend+this.initialBendValue}get displayValueWithoutBend(){let e=this.realValue;switch(this.harmonicType!==m.Natural&&this.harmonicType!==m.None&&(e-=this.harmonicPitch),this.beat.ottava){case n._15ma:e-=24;break;case n._8va:e-=12;break;case n.Regular:break;case n._8vb:e+=12;break;case n._15mb:e+=24}switch(this.beat.voice.bar.clefOttava){case n._15ma:e-=24;break;case n._8va:e-=12;break;case n.Regular:break;case n._8vb:e+=12;break;case n._15mb:e+=24}return e-this.beat.voice.bar.staff.displayTranspositionPitch}get hasQuarterToneOffset(){return this.hasBend?this.bendPoints[0].value%2!=0:this.bendOrigin?this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value%2!=0:this.beat.hasWhammyBar?this.beat.whammyBarPoints[0].value%2!=0:!!this.beat.isContinuedWhammy&&this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value%2!=0}addBendPoint(e){let t=this.bendPoints;null===t&&(t=[],this.bendPoints=t),t.push(e),(!this.maxBendPoint||e.value>this.maxBendPoint.value)&&(this.maxBendPoint=e),this.bendType===l.None&&(this.bendType=l.Custom)}finish(e,t=null){let i=new _e((()=>Pe.nextNoteOnSameLine(this))),s=e&&e.notation.notationMode===T.SongBook;if(this.isTieDestination&&(this.chain(t),s&&this.tieOrigin&&this.tieOrigin.isLetRing&&(this.isLetRing=!0)),this.isLetRing&&(i.value&&i.value.isLetRing?this.letRingDestination=i.value:this.letRingDestination=this,s&&this.isTieDestination&&!this.tieOrigin.hasBend&&(this.isVisible=!1)),this.isPalmMute&&(i.value&&i.value.isPalmMute?this.palmMuteDestination=i.value:this.palmMuteDestination=this),this.isHammerPullOrigin){let e=Pe.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case S.Shift:case S.Legato:this.slideTarget=i.value,this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=S.None}let a=null;this.isHammerPullOrigin&&this.hammerPullDestination?a=this.hammerPullDestination:this.slideOutType===S.Legato&&this.slideTarget&&(a=this.slideTarget),a&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===N.None?(this.effectSlurOrigin.effectSlurDestination=a,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=a,this.effectSlurDestination.effectSlurOrigin=this));const r=this.bendPoints;if(null!=r&&r.length>0&&this.bendType===l.Custom){let e=this.isTieDestination&&this.tieOrigin.hasBend;if(this.isContinuedBend=e,4===r.length){let t=r[0],i=r[1],s=r[2],a=r[3];i.value===s.value?a.value>t.value?i.value>a.value?this.bendType=l.BendRelease:!e&&t.value>0?(this.bendType=l.PrebendBend,r.splice(2,1),r.splice(1,1)):(this.bendType=l.Bend,r.splice(2,1),r.splice(1,1)):a.value<t.value?e?(this.bendType=l.Release,r.splice(2,1),r.splice(1,1)):(this.bendType=l.PrebendRelease,r.splice(2,1),r.splice(1,1)):i.value>t.value?this.bendType=l.BendRelease:t.value>0&&!e?(this.bendType=l.Prebend,r.splice(2,1),r.splice(1,1)):(this.bendType=l.Hold,r.splice(2,1),r.splice(1,1)):Be.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===r.length){let t=r[0],i=r[1];i.value>t.value?!e&&t.value>0?this.bendType=l.PrebendBend:this.bendType=l.Bend:i.value<t.value?this.bendType=e?l.Release:l.PrebendRelease:this.bendType=l.Hold}}else null!==r&&0!==r.length||(this.bendType=l.None);this.initialBendValue>0&&(this.accidentalMode=y.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+Pe.MaxOffsetForSameLineSearch;){let 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+Pe.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-Pe.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(Pe.NoteIdLookupKey)?t=e.get(Pe.NoteIdLookupKey):(t=new Map,e.set(Pe.NoteIdLookupKey,t)),-1===this._noteIdBag.hammerPullDestinationNoteId&&-1===this._noteIdBag.tieDestinationNoteId&&-1===this._noteIdBag.slurDestinationNoteId||t.set(this.id,this),-1!==this._noteIdBag.hammerPullOriginNoteId&&(this.hammerPullOrigin=t.get(this._noteIdBag.hammerPullOriginNoteId),this.hammerPullOrigin.hammerPullDestination=this),-1!==this._noteIdBag.tieOriginNoteId&&(this.tieOrigin=t.get(this._noteIdBag.tieOriginNoteId),this.tieOrigin.tieDestination=this),-1!==this._noteIdBag.slurOriginNoteId&&(this.slurOrigin=t.get(this._noteIdBag.slurOriginNoteId),this.slurOrigin.slurDestination=this),this._noteIdBag=null}else{if(!this.isTieDestination&&null==this.tieOrigin)return;let e=Pe.findTieOrigin(this);e?(e.tieDestination=this,this.tieOrigin=e,this.fret=e.fret,this.octave=e.octave,this.tone=e.tone,e.hasBend&&(this.bendOrigin=this.tieOrigin)):this.isTieDestination=!1}}toJson(e){null!==this.tieDestination&&e.set("tiedestinationnoteid",this.tieDestination.id),null!==this.tieOrigin&&e.set("tieoriginnoteid",this.tieOrigin.id),null!==this.slurDestination&&e.set("slurdestinationnoteid",this.slurDestination.id),null!==this.slurOrigin&&e.set("sluroriginnoteid",this.slurOrigin.id),null!==this.hammerPullOrigin&&e.set("hammerpulloriginnoteid",this.hammerPullOrigin.id),null!==this.hammerPullDestination&&e.set("hammerpulldestinationnoteid",this.hammerPullDestination.id)}setProperty(e,t){switch(e){case"tiedestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new xe),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new xe),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new xe),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new xe),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new xe),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new xe),this._noteIdBag.hammerPullDestinationNoteId=t,!0}return!1}}Pe.GlobalNoteId=0,Pe.MaxOffsetForSameLineSearch=3,Pe.NoteIdLookupKey="NoteIdLookup";class Ee{constructor(e){this._isEqualLengthTuplet=!0,this.totalDuration=0,this.beats=[],this.isFull=!1,this.voice=e}check(e){if(0===this.beats.length)return this.beats.push(e),this.totalDuration+=e.playbackDuration,!0;if(e.graceType!==g.None)return!0;if(e.voice!==this.voice||this.isFull||e.tupletNumerator!==this.beats[0].tupletNumerator||e.tupletDenominator!==this.beats[0].tupletDenominator)return!1;if(e.playbackDuration!==this.beats[0].playbackDuration&&(this._isEqualLengthTuplet=!1),this.beats.push(e),this.totalDuration+=e.playbackDuration,this._isEqualLengthTuplet)this.beats.length===this.beats[0].tupletNumerator&&(this.isFull=!0);else{let e=this.beats[0].tupletNumerator/this.beats[0].tupletDenominator|0;for(let t of Ee.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}Ee.HalfTicks=1920,Ee.QuarterTicks=960,Ee.EighthTicks=480,Ee.SixteenthTicks=240,Ee.ThirtySecondTicks=120,Ee.SixtyFourthTicks=60,Ee.OneHundredTwentyEighthTicks=30,Ee.TwoHundredFiftySixthTicks=15,Ee.AllTicks=[Ee.HalfTicks,Ee.QuarterTicks,Ee.EighthTicks,Ee.SixteenthTicks,Ee.ThirtySecondTicks,Ee.SixtyFourthTicks,Ee.OneHundredTwentyEighthTicks,Ee.TwoHundredFiftySixthTicks],function(e){e[e.None=0]="None",e[e.Custom=1]="Custom",e[e.Dive=2]="Dive",e[e.Dip=3]="Dip",e[e.Hold=4]="Hold",e[e.Predive=5]="Predive",e[e.PrediveDive=6]="PrediveDive"}(C||(C={}));class Ce{static clone(e){const t=new be;return t.offset=e.offset,t.value=e.value,t}}class Fe{static clone(e){const t=new Pe;if(t.index=e.index,t.accentuated=e.accentuated,t.bendType=e.bendType,t.bendStyle=e.bendStyle,t.isContinuedBend=e.isContinuedBend,e.bendPoints){t.bendPoints=[];for(const i of e.bendPoints)t.addBendPoint(Ce.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 Le{static clone(e){const t=new fe;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class Me{static clone(e){const t=new Ie;t.index=e.index,t.notes=[];for(const i of e.notes)t.addNote(Fe.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(Le.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(Ce.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 De{constructor(){this.beats=[],this.id="empty",this.isComplete=!1}addBeat(e){e.graceIndex=this.beats.length,e.graceGroup=this,this.beats.push(e)}finish(){this.beats.length>0&&(this.id=this.beats[0].absoluteDisplayStart+"_"+this.beats[0].voice.index)}}!function(e){e[e.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext"}(F||(F={}));class Ie{constructor(){this.id=Ie._globalBeatId++,this.index=0,this.previousBeat=null,this.nextBeat=null,this.notes=[],this.noteStringLookup=new Map,this.noteValueLookup=new Map,this.isEmpty=!1,this.whammyStyle=h.Default,this.ottava=n.Regular,this.fermata=null,this.isLegatoOrigin=!1,this.minNote=null,this.maxNote=null,this.maxStringNote=null,this.minStringNote=null,this.duration=u.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fadeIn=!1,this.lyrics=null,this.hasRasgueado=!1,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.brushType=d.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=C.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=_.None,this.chordId=null,this.graceType=g.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=N.None,this.tremoloSpeed=null,this.crescendo=c.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.dynamics=p.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=F.Auto}get isLastOfVoice(){return this.index===this.voice.beats.length-1}get isLegatoDestination(){return!!this.previousBeat&&this.previousBeat.isLegatoOrigin}get isRest(){return this.isEmpty||0===this.notes.length}get isFullBarRest(){return this.isRest&&1===this.voice.beats.length&&this.duration===u.Whole}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==C.None}get hasChord(){return!!this.chordId}get chord(){return this.chordId?this.voice.bar.staff.getChord(this.chordId):null}get isTremolo(){return!!this.tremoloSpeed}get absoluteDisplayStart(){return this.voice.bar.masterBar.start+this.displayStart}get absolutePlaybackStart(){return this.voice.bar.masterBar.start+this.playbackStart}get isEffectSlurDestination(){return!!this.effectSlurOrigin}addWhammyBarPoint(e){let t=this.whammyBarPoints;null===t&&(t=[],this.whammyBarPoints=t),t.push(e),(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e),(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e),this.whammyBarType===C.None&&(this.whammyBarType=C.Custom)}removeWhammyBarPoint(e){const t=this.whammyBarPoints;if(null===t||e<0||e>=t.length)return;t.splice(e,1);let 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=ye.toTicks(this.duration);return 2===this.dots?e=ye.applyDot(e,!0):1===this.dots&&(e=ye.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=ye.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){let e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case g.BeforeBeat:case g.OnBeat:switch(this.duration){case u.Sixteenth:this.playbackDuration=ye.toTicks(u.SixtyFourth);break;case u.ThirtySecond:this.playbackDuration=ye.toTicks(u.OneHundredTwentyEighth);break;default:this.playbackDuration=ye.toTicks(u.ThirtySecond)}this.displayDuration=0;break;case g.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;let t=this.previousBeat;t&&t.graceType===g.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){let e=this.previousBeat,t=e?e.tupletGroup:null;(this.hasTuplet||this.graceType!==g.None&&t)&&(e&&t&&t.check(this)||(t=new Ee(this.voice),t.check(this)),this.tupletGroup=t)}finish(e,t=null){switch(null===this.getAutomation(a.Instrument)&&0===this.index&&0===this.voice.index&&0===this.voice.bar.index&&0===this.voice.bar.staff.index&&this.automations.push(fe.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case g.OnBeat:case g.BeforeBeat:let e=this.graceGroup.beats.length;this.duration=1===e?u.Eighth:2===e?u.Sixteenth:u.ThirtySecond}let i=e?e.notation.notationMode:T.GuitarPro,s="grad"===this.text||"grad."===this.text;s&&i===T.SongBook&&(this.text="");let r=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let n=0,o=!1;for(let a=0,d=this.notes.length;a<d;a++){let d=this.notes[a];if(d.dynamics=this.dynamics,d.finish(e,t),d.isLetRing&&(this.isLetRing=!0),d.isPalmMute&&(this.isPalmMute=!0),i===T.SongBook&&d.hasBend&&this.graceType!==g.BendGrace){if(!d.isTieOrigin)switch(d.bendType){case l.Bend:case l.PrebendRelease:case l.PrebendBend:r=!0}s||d.bendStyle===h.Gradual?(s=!0,d.bendStyle=h.Gradual,r=!1):d.bendStyle=h.Fast}d.isVisible&&(n++,(!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&&(o=!0))}if(o&&(this.effectSlurOrigin?(this.effectSlurOrigin.effectSlurDestination=this.nextBeat,this.effectSlurOrigin.effectSlurDestination&&(this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin),this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=this.nextBeat,this.effectSlurDestination&&(this.effectSlurDestination.effectSlurOrigin=this))),this.notes.length>0&&0===n&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&e&&e.notation.notationMode===T.GuitarPro&&(this.previousBeat.isLetRing&&(this.isLetRing=!0),this.previousBeat.isPalmMute&&(this.isPalmMute=!0));else{let e=this.previousBeat;for(;e&&e.isRest;)this.isLetRing||(e.isLetRing=!1),this.isPalmMute||(e.isPalmMute=!1),e=e.previousBeat}const d=this.whammyBarPoints;if(null!==d&&d.length>0&&this.whammyBarType===C.Custom){i===T.SongBook&&(this.whammyStyle=s?h.Gradual:h.Fast);let e=!!this.previousBeat&&this.previousBeat.hasWhammyBar;if(this.isContinuedWhammy=e,4===d.length){let t=d[0],s=d[1],a=d[2],r=d[3];s.value===a.value?t.value<s.value&&s.value<r.value||t.value>s.value&&s.value>r.value?(0===t.value||e?this.whammyBarType=C.Dive:this.whammyBarType=C.PrediveDive,d.splice(2,1),d.splice(1,1)):t.value>s.value&&s.value<r.value||t.value<s.value&&s.value>r.value?(this.whammyBarType=C.Dip,s.offset!==a.offset&&i!==T.SongBook||d.splice(2,1)):t.value===s.value&&s.value===r.value?(0===t.value||e?this.whammyBarType=C.Hold:this.whammyBarType=C.Predive,d.splice(2,1),d.splice(1,1)):Be.warning("Model","Unsupported whammy type detected, fallback to custom"):Be.warning("Model","Unsupported whammy type detected, fallback to custom")}}if(this.updateDurations(),r){let e=Me.clone(this);e.id=Ie._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=l.None,i.maxBendPoint=null,i.bendPoints=null,i.bendStyle=h.Default,i.id=Pe.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=Pe.findTieOrigin(s);if(e&&e.hasBend){i.bendType=l.Hold;let e=s.bendPoints[s.bendPoints.length-1];i.addBendPoint(new be(0,e.value)),i.addBendPoint(new be(be.MaxPosition,e.value))}}i.isTieDestination=!0}this.graceType=g.BendGrace,this.graceGroup=new De,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new De,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)}}Ie._globalBeatId=0;class Re{constructor(){this.name="",this.firstFret=1,this.strings=[],this.barreFrets=[],this.showName=!0,this.showDiagram=!0,this.showFingering=!0}}!function(e){e[e.Cb=-7]="Cb",e[e.Gb=-6]="Gb",e[e.Db=-5]="Db",e[e.Ab=-4]="Ab",e[e.Eb=-3]="Eb",e[e.Bb=-2]="Bb",e[e.F=-1]="F",e[e.C=0]="C",e[e.G=1]="G",e[e.D=2]="D",e[e.A=3]="A",e[e.E=4]="E",e[e.B=5]="B",e[e.FSharp=6]="FSharp",e[e.CSharp=7]="CSharp"}(L||(L={})),function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.Text=2]="Text",e[e.Comment=3]="Comment",e[e.Dash=4]="Dash"}(M||(M={}));class Ae{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=M.Begin,r=M.Begin,n=!1,o=0;for(;t<e.length;){let i=e.charCodeAt(t);switch(a){case M.IgnoreSpaces:switch(i){case Ae.CharCodeLF:case Ae.CharCodeCR:case Ae.CharCodeTab:break;case Ae.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case M.Begin:if(i!==Ae.CharCodeBrackedOpen){o=t,a=M.Text;continue}a=M.Comment;break;case M.Comment:if(i===Ae.CharCodeBrackedClose)a=M.Begin;break;case M.Text:switch(i){case Ae.CharCodeDash:a=M.Dash;break;case Ae.CharCodeCR:case Ae.CharCodeLF:case Ae.CharCodeSpace:let i=e.substr(o,t-o);this.addChunk(i,s),a=M.IgnoreSpaces,r=M.Begin}break;case M.Dash:if(i!==Ae.CharCodeDash){let i=e.substr(o,t-o);this.addChunk(i,s),n=!0,a=M.IgnoreSpaces,r=M.Begin;continue}}t+=1}a===M.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}}Ae.CharCodeLF=10,Ae.CharCodeTab=9,Ae.CharCodeCR=13,Ae.CharCodeSpace=32,Ae.CharCodeBrackedClose=93,Ae.CharCodeBrackedOpen=91,Ae.CharCodeDash=45,function(e){e[e.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"}(I||(I={}));class Oe{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=L.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=I.NoTripletFeel,this.section=null,this.tempoAutomation=null,this.fermata=null,this.start=0,this.isAnacrusis=!1}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}calculateDuration(e=!0){if(this.isAnacrusis&&e){let e=0;for(let t of this.score.tracks)for(let 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*ye.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}}Oe.MaxAlternateEndings=8;class Ge{constructor(){this.hideDynamics=!1}}class Ve{constructor(){this.masterBars=[],this.opening=null,this.closings=[],this.isClosed=!1}get openings(){const e=this.opening;return e?[e]:[]}get isOpened(){var e;return!0===(null===(e=this.opening)||void 0===e?void 0:e.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 He{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.stylesheet=new Ge}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){var t;e.isRepeatStart?((null===(t=this._currentRepeatGroup)||void 0===t?void 0:t.isClosed)&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--),this._currentRepeatGroup=new Ve,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new Ve,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 We{constructor(){this.marker="",this.text=""}}class ze extends pe{constructor(e){super(i.Format,e),Object.setPrototypeOf(this,ze.prototype)}}class Ue{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="#"+ke.toHexString(this.r,2)+ke.toHexString(this.g,2)+ke.toHexString(this.b,2):this.rgba=`rgba(${this.r},${this.g},${this.b},${this.a/255})`}get a(){return this.raw>>24&255}get r(){return this.raw>>16&255}get g(){return this.raw>>8&255}get b(){return 255&this.raw}static random(e=100){return new Ue(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){switch(typeof e){case"number":{const t=new Ue(0,0,0,0);return t.raw=e,t.updateRgba(),t}case"string":{const t=e;if(t.startsWith("#")){if(4===t.length)return new Ue(17*parseInt(t[1],16),17*parseInt(t[2],16),17*parseInt(t[3],16));if(5===t.length)return new Ue(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 Ue(parseInt(t.substring(1,3),16),parseInt(t.substring(3,5),16),parseInt(t.substring(5,7),16));if(9===t.length)return new Ue(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 ze("No values specified for rgb/rgba function");const s=t.substring(e+1,i).split(",");if(3===s.length)return new Ue(parseInt(s[0]),parseInt(s[1]),parseInt(s[2]));if(4===s.length)return new Ue(parseInt(s[0]),parseInt(s[1]),parseInt(s[2]),255*parseFloat(s[3]))}return null}}throw new ze("Unsupported format for color")}static toJson(e){return e.raw}}Ue.BlackRgb="#000000";class Xe{constructor(){this.volume=15,this.balance=8,this.port=1,this.program=0,this.primaryChannel=0,this.secondaryChannel=0,this.isMute=!1,this.isSolo=!1}}class Ye{static getTextForTuning(e,t){let i=Ye.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 Ye._defaultTunings.has(e)?Ye._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return Ye._sevenStrings;case 6:return Ye._sixStrings;case 5:return Ye._fiveStrings;case 4:return Ye._fourStrings}return[]}static initialize(){Ye._defaultTunings.set(7,new Ye("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),Ye._sevenStrings.push(Ye._defaultTunings.get(7)),Ye._defaultTunings.set(6,new Ye("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),Ye._sixStrings.push(Ye._defaultTunings.get(6)),Ye._sixStrings.push(new Ye("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),Ye._sixStrings.push(new Ye("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),Ye._sixStrings.push(new Ye("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),Ye._sixStrings.push(new Ye("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),Ye._sixStrings.push(new Ye("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),Ye._sixStrings.push(new Ye("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),Ye._sixStrings.push(new Ye("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),Ye._sixStrings.push(new Ye("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),Ye._sixStrings.push(new Ye("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),Ye._sixStrings.push(new Ye("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),Ye._defaultTunings.set(5,new Ye("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),Ye._fiveStrings.push(Ye._defaultTunings.get(5)),Ye._fiveStrings.push(new Ye("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),Ye._fiveStrings.push(new Ye("Banjo Open D Tuning",[62,57,54,50,69],!1)),Ye._fiveStrings.push(new Ye("Banjo Open G Tuning",[62,59,55,50,67],!1)),Ye._fiveStrings.push(new Ye("Banjo G Minor Tuning",[62,58,55,50,67],!1)),Ye._fiveStrings.push(new Ye("Banjo G Modal Tuning",[62,57,55,50,67],!1)),Ye._defaultTunings.set(4,new Ye("Bass Standard Tuning",[43,38,33,28],!0)),Ye._fourStrings.push(Ye._defaultTunings.get(4)),Ye._fourStrings.push(new Ye("Bass Tune down ½ step",[42,37,32,27],!1)),Ye._fourStrings.push(new Ye("Bass Tune down 1 step",[41,36,31,26],!1)),Ye._fourStrings.push(new Ye("Bass Tune down 2 step",[39,34,29,24],!1)),Ye._fourStrings.push(new Ye("Bass Dropped D Tuning",[43,38,33,26],!1)),Ye._fourStrings.push(new Ye("Ukulele C Tuning",[45,40,36,43],!1)),Ye._fourStrings.push(new Ye("Ukulele G Tuning",[52,47,43,38],!1)),Ye._fourStrings.push(new Ye("Mandolin Standard Tuning",[64,57,50,43],!1)),Ye._fourStrings.push(new Ye("Mandolin or Violin Tuning",[76,69,62,55],!1)),Ye._fourStrings.push(new Ye("Viola Tuning",[69,62,55,48],!1)),Ye._fourStrings.push(new Ye("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){let t=Ye.getPresetsFor(e.length);for(let 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=null!=t?t:[]}finish(){const e=Ye.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}Ye._sevenStrings=[],Ye._sixStrings=[],Ye._fiveStrings=[],Ye._fourStrings=[],Ye._defaultTunings=new Map,Ye.defaultAccidentals=["","#","","#","","","#","","#","","#",""],Ye.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],Ye.initialize();class qe{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new Ye("",[],!1),this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=5}get tuning(){return this.stringTuning.tunings}get tuningName(){return this.stringTuning.name}get isStringed(){return this.stringTuning.tunings.length>0}finish(e,t=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){var t,i;return null!==(i=null===(t=this.chords)||void 0===t?void 0:t.has(e))&&void 0!==i&&i}getChord(e){var t,i;return null!==(i=null===(t=this.chords)||void 0===t?void 0:t.get(e))&&void 0!==i?i:null}addBar(e){let t=this.bars;e.staff=this,e.index=t.length,t.length>0&&(e.previousBar=t[t.length-1],e.previousBar.nextBar=e),t.push(e)}}class Je{constructor(){this.index=0,this.staves=[],this.playbackInfo=new Xe,this.color=new Ue(200,0,0,255),this.name="",this.shortName="",this.percussionArticulations=[]}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new qe)}addStaff(e){e.index=this.staves.length,e.track=this,this.staves.push(e)}finish(e,t=null){this.shortName||(this.shortName=this.name,this.shortName.length>Je.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,Je.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)}}}}}Je.ShortNameMaxLength=10;class je{constructor(){this.id=je._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===g.None?(s.graceGroup=i,i&&(i.isComplete=!0),i=null):(i||(i=new De),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===g.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==g.BendGrace){let i=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case g.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 g.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}}je._globalBarId=0;class Qe{static float64ToBytes(e){return Qe._dataView.setFloat64(0,e,!0),this._conversionByteArray}static bytesToFloat64(e){throw Qe._conversionByteArray.set(e,0),Qe._dataView.getFloat64(0,!0)}static uint16ToInt16(e){return Qe._dataView.setUint16(0,e,!0),Qe._dataView.getInt16(0,!0)}static int16ToUint32(e){return Qe._dataView.setInt16(0,e,!0),Qe._dataView.getUint32(0,!0)}static int32ToUint16(e){return Qe._dataView.setInt32(0,e,!0),Qe._dataView.getUint16(0,!0)}static int32ToInt16(e){return Qe._dataView.setInt32(0,e,!0),Qe._dataView.getInt16(0,!0)}static int32ToUint32(e){return Qe._dataView.setInt32(0,e,!0),Qe._dataView.getUint32(0,!0)}static uint8ToInt8(e){return Qe._dataView.setUint8(0,e),Qe._dataView.getInt8(0)}}Qe._conversionBuffer=new ArrayBuffer(8),Qe._conversionByteArray=new Uint8Array(Qe._conversionBuffer),Qe._dataView=new DataView(Qe._conversionBuffer);class $e{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 Qe.int32ToUint16(i<<8|t)}static readInt16LE(e){let t=e.readByte(),i=e.readByte();return Qe.int32ToInt16(i<<8|t)}static readUInt32BE(e){let t=e.readByte(),i=e.readByte(),s=e.readByte(),a=e.readByte();return Qe.int32ToUint32(t<<24|i<<16|s<<8|a)}static readUInt16BE(e){let t=e.readByte(),i=e.readByte();return Qe.int32ToInt16(t<<8|i)}static readInt16BE(e){let t=e.readByte(),i=e.readByte();return Qe.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),$e.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==(8388608&i)&&(i|=255<<24),i}static readInt16(e,t){return Qe.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){let i=$e.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(t>>0&255)}static writeInt32LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255),e.writeByte(t>>16&255),e.writeByte(t>>24&255)}static writeUInt16LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255)}static writeInt16LE(e,t){e.writeByte(t>>0&255),e.writeByte(t>>8&255)}}class 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=$e.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}}!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"}(R||(R={}));class Ze extends pe{constructor(e,t,s,a,r,n,o,h=null){super(i.AlphaTex,e),this.position=t,this.line=s,this.col=a,this.nonTerm=null!=r?r:"",this.expected=null!=n?n:R.No,this.symbol=null!=o?o:R.No,this.symbolData=h,Object.setPrototypeOf(this,Ze.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 ${R[a]} found a ${R[r]}`,null!==n&&(o+=`: '${n}'`)):o+=`, invalid value: '${n}'`,new Ze(o,e,t,i,s,a,r,n)}static errorMessage(e,t,i,s){return new Ze(e=`MalFormed AlphaTex: @${t} (line ${i}, col ${s}): ${e}`,t,i,s,null,null,null,null)}}class et extends ue{constructor(){super(),this._trackChannel=0,this._input="",this._ch=et.Eof,this._curChPos=0,this._line=1,this._col=0,this._lastValidSpot=[0,1,0],this._sy=R.No,this._syData="",this._allowNegatives=!1,this._allowTuning=!1,this._currentDuration=u.QuadrupleWhole,this._currentDynamics=p.PPP,this._currentTuplet=0,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=Ke.empty(),this._input=e,this.settings=t}readScore(){try{if(this.data.length>0&&(this._input=$e.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this.createDefaultScore(),this._curChPos=0,this._line=1,this._col=0,this.saveValidSpot(),this._currentDuration=u.Quarter,this._currentDynamics=p.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===R.LowerThan)throw new ge("Unknown start sign '<' (meant to import as XML?)");if(this._sy===R.Eof)throw new ge("Unexpected end of file");const e=this.metaData(),t=this.bars();if(!e&&!t)throw new ge("No alphaTex data found");this.consolidate(),this._score.finish(this.settings),this._score.rebuildRepeatGroups();for(const[e,t]of this._lyrics)this._score.tracks[e].applyLyrics(t);return this._score}catch(e){throw e instanceof Ze?new ge(e.message,e):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 Ie;i.isEmpty=!0,e.voices[0].addBeat(i)}}error(e,t,i=!0){let s,a=!1;i?(s=this._sy,s!==R.String&&s!==R.Number&&s!==R.MetaCommand||(a=!0)):s=t;let r=Ze.symbolError(this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2],e,t,s,a?this._syData:null);throw this.logErrors&&Be.error(this.name,r.message),r}errorMessage(e){let t=Ze.errorMessage(e,this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2]);throw this.logErrors&&Be.error(this.name,t.message),t}createDefaultScore(){this._score=new He,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new Je,this._currentTrack.ensureStaveCount(1),this._currentTrack.playbackInfo.program=25,this._currentTrack.playbackInfo.primaryChannel=this._trackChannel++,this._currentTrack.playbackInfo.secondaryChannel=this._trackChannel++,this._currentStaff=this._currentTrack.staves[0],this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=Ye.getDefaultTuningFor(6).tunings,this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=p.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":default:return r.G2;case"f4":case"bass":return r.F4;case"c3":case"tenor":return r.C3;case"c4":case"alto":return r.C4;case"n":case"neutral":return r.Neutral}}parseClefFromInt(e){switch(e){case 43:default:return r.G2;case 65:return r.F4;case 48:return r.C3;case 60:return r.C4}}parseTripletFeelFromString(e){switch(e.toLowerCase()){case"no":case"none":default:return I.NoTripletFeel;case"t16":case"triplet-16th":return I.Triplet16th;case"t8":case"triplet-8th":return I.Triplet8th;case"d16":case"dotted-16th":return I.Dotted16th;case"d8":case"dotted-8th":return I.Dotted8th;case"s16":case"scottish-16th":return I.Scottish16th;case"s8":case"scottish-8th":return I.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return I.NoTripletFeel;case 1:return I.Triplet16th;case 2:return I.Triplet8th;case 3:return I.Dotted16th;case 4:return I.Dotted8th;case 5:return I.Scottish16th;case 6:return I.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":return L.Cb;case"gb":case"gbmajor":case"d#minor":return L.Gb;case"db":case"dbmajor":case"bbminor":return L.Db;case"ab":case"abmajor":case"fminor":return L.Ab;case"eb":case"ebmajor":case"cminor":return L.Eb;case"bb":case"bbmajor":case"gminor":return L.Bb;case"f":case"fmajor":case"dminor":return L.F;case"c":case"cmajor":case"aminor":default:return L.C;case"g":case"gmajor":case"eminor":return L.G;case"d":case"dmajor":case"bminor":return L.D;case"a":case"amajor":case"f#minor":return L.A;case"e":case"emajor":case"c#minor":return L.E;case"b":case"bmajor":case"g#minor":return L.B;case"f#":case"f#major":case"ebminor":return L.FSharp;case"c#":case"c#major":return L.CSharp}}nextChar(){return this._curChPos<this._input.length?(this._ch=this._input.charCodeAt(this._curChPos++),10===this._ch?(this._line++,this._col=0):this._col++):this._ch=et.Eof,this._ch}saveValidSpot(){this._lastValidSpot=[this._curChPos,this._line,this._col]}newSy(){for(this.saveValidSpot(),this._sy=R.No;this._sy===R.No;)if(this._ch===et.Eof)this._sy=R.Eof;else if(et.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!==et.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;this._ch!==et.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",R.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=R.String;this._ch!==e&&this._ch!==et.Eof;)t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._ch===et.Eof&&this.errorMessage("String opened but never closed"),this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)this._allowNegatives&&this.isDigit(this._ch)?(this._sy=R.Number,this._syData=this.readNumber()):(this._sy=R.String,this._syData=this.readName());else if(46===this._ch)this._sy=R.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=R.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=R.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=R.MetaCommand,this._syData=this.readName();else if(41===this._ch)this._sy=R.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=R.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=R.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=R.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=R.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=R.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this._sy=R.Number,this._syData=this.readNumber();else if(et.isNameLetter(this._ch)){let e=this.readName(),t=this._allowTuning?ke.parseTuning(e):null;t?(this._sy=R.Tuning,this._syData=t):(this._sy=R.String,this._syData=e)}else this.error("symbol",R.String,!1);return this._sy}static isNameLetter(e){return!et.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}readName(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(et.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 parseInt(e)}metaData(){let e=!1,t=!0;for(;this._sy===R.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!==R.String&&this.error(i,R.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._sy=this.newSy(),this._sy===R.Number?this._score.tempo=this._syData:this.error("tempo",R.Number,!0),this._sy=this.newSy(),e=!0;break;default:this.handleStaffMeta()?e=!0:e?this.error("metaDataTags",R.String,!1):t=!1}}return e?(this._sy!==R.Dot&&this.error("song",R.Dot,!0),this._sy=this.newSy()):this._sy===R.Dot&&(this._sy=this.newSy()),e}handleStaffMeta(){var e,t;switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===R.Number?this._currentStaff.capo=this._syData:this.error("capo",R.Number,!0),this._sy=this.newSy(),!0;case"tuning":this._sy=this.newSy();let i=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case R.String:let e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?(this._currentStaff.stringTuning.tunings=[],this._currentStaff.displayTranspositionPitch=0):this.error("tuning",R.Tuning,!0),this._sy=this.newSy();break;case R.Tuning:let t=[];do{let e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===R.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",R.Tuning,!0)}return i!==this._currentStaff.tuning.length&&(null!==(t=null===(e=this._currentStaff.chords)||void 0===e?void 0:e.size)&&void 0!==t?t:0)>0&&this.errorMessage("Tuning must be defined before any chord"),!0;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===R.Number){let e=this._syData;e>=0&&e<=127?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",R.Number,!1)}else if(this._sy===R.String){let e=this._syData.toLowerCase();this._currentTrack.playbackInfo.program=ce.getValue(e)}else this.error("instrument",R.Number,!0);return this._sy=this.newSy(),!0;case"lyrics":this._sy=this.newSy();let s=new Ae;return s.startBar=0,s.text="",this._sy===R.Number&&(s.startBar=this._syData,this._sy=this.newSy()),this._sy===R.String?(s.text=this._syData,this._sy=this.newSy()):this.error("lyrics",R.String,!0),this._lyrics.get(this._currentTrack.index).push(s),!0;case"chord":this._sy=this.newSy();let a=new Re;this.chordProperties(a),this._sy===R.String?(a.name=this._syData,this._sy=this.newSy()):this.error("chord-name",R.Number,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===R.Number?a.strings.push(this._syData):this._sy===R.String&&"x"===this._syData.toLowerCase()&&a.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,a.name),a),!0;default:return!1}}chordProperties(e){if(this._sy===R.LBrace){for(this._sy=this.newSy();this._sy===R.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===R.Number)e.firstFret=this._syData;else this.error("chord-firstfret",R.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case R.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case R.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",R.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case R.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case R.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",R.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case R.String:e.showName="false"!==this._syData.toLowerCase();break;case R.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",R.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===R.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",R.String,!1)}this._sy!==R.RBrace&&this.error("chord-properties",R.RBrace,!0),this._sy=this.newSy()}}bars(){let e=this.bar();for(;this._sy!==R.Eof;)if(this._sy===R.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==R.MetaCommand)break;this.bar()}return e}trackStaffMeta(){return this._sy===R.MetaCommand&&("track"===this._syData.toLowerCase()&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===R.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===R.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy())),this._sy===R.MetaCommand&&"staff"===this._syData.toLowerCase()&&(this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0&&(this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this._currentStaff=this._currentTrack.staves[this._currentTrack.staves.length-1],this._currentDynamics=p.F),this.staffProperties()),!0)}staffProperties(){if(this._sy!==R.LBrace)return;this._sy=this.newSy();let e=!1,t=!1;for(;this._sy===R.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy();break;case"tabs":t=!0,this._sy=this.newSy();break;default:this.error("staff-properties",R.String,!1)}(e||t)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t),this._sy!==R.RBrace&&this.error("staff-properties",R.RBrace,!0),this._sy=this.newSy()}bar(){const e=this.trackStaffMeta();let t=this.newBar(this._currentStaff);if(this._currentStaff.bars.length>this._score.masterBars.length){let e=new Oe;this._score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.timeSignatureDenominator=e.previousMasterBar.timeSignatureDenominator,e.timeSignatureNumerator=e.previousMasterBar.timeSignatureNumerator,e.tripletFeel=e.previousMasterBar.tripletFeel)}const 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=Ye.getDefaultTuningFor(6).tunings):e>=32&&e<=39?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):40==e||44==e||45==e||48==e||49==e||50==e||51==e?this._currentStaff.stringTuning.tunings=[52,57,50,43]:41==e?this._currentStaff.stringTuning.tunings=[57,50,43,36]:42==e?this._currentStaff.stringTuning.tunings=[45,38,31,24]:43==e?(this._currentStaff.displayTranspositionPitch=-12,this._currentStaff.stringTuning.tunings=[43,38,33,28]):105==e?this._currentStaff.stringTuning.tunings=[50,47,43,38,55]:106==e?this._currentStaff.stringTuning.tunings=[57,52,45]:107==e?this._currentStaff.stringTuning.tunings=[52,45,38,31]:110==e&&(this._currentStaff.stringTuning.tunings=[64,57,50,43]),this._staffTuningApplied=!0}let s=!1,a=t.voices[0];for(;this._sy!==R.Pipe&&this._sy!==R.Eof&&this.beat(a);)s=!0;if(0===a.beats.length){let e=new Ie;e.isEmpty=!0,a.addBeat(e)}return e||i||s}newBar(e){let t=new me;e.addBar(t),t.index>0&&(t.clef=t.previousBar.clef);let i=new je;return t.addVoice(i),t}beat(e){this.beatDuration();let t=new Ie;if(e.addBeat(t),this._sy===R.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==R.RParensis&&this._sy!==R.Eof&&this.note(t););this._sy!==R.RParensis&&this.error("note-list",R.RParensis,!0),this._sy=this.newSy()}else if(this._sy===R.String&&"r"===this._syData.toLowerCase())this._sy=this.newSy();else if(!this.note(t))return e.beats.splice(e.beats.length-1,1),!1;this._sy===R.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==R.Number&&this.error("duration",R.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._sy=this.newSy()),t.duration=this._currentDuration,t.dynamics=this._currentDynamics,1===this._currentTuplet||t.hasTuplet||et.applyTuplet(t,this._currentTuplet);let i=1;this._sy===R.Multiply&&(this._sy=this.newSy(),this._sy!==R.Number?this.error("multiplier",R.Number,!0):i=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let s=0;s<i-1;s++)e.addBeat(Me.clone(t));return!0}beatDuration(){if(this._sy===R.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==R.Number&&this.error("duration",R.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===R.LBrace)){for(this._sy=this.newSy();this._sy===R.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==R.Number&&this.error("duration-tuplet",R.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",R.String,!1)}this._sy!==R.RBrace&&this.error("beat-duration",R.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===R.LBrace){for(this._sy=this.newSy();this._sy===R.String;)this.applyBeatEffect(e)||this.error("beat-effects",R.String,!1);this._sy!==R.RBrace&&this.error("beat-effects",R.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){let t=this._syData.toLowerCase();if("f"===t)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!==R.Number)return this.error("tuplet",R.Number,!0),!1;et.applyTuplet(e,this._syData)}else if("tb"===t||"tbe"===t){let i="tbe"===t;for(this._sy=this.newSy(),this._sy!==R.LParensis&&this.error("tremolobar-effect",R.LParensis,!0),this._allowNegatives=!0,this._sy=this.newSy();this._sy!==R.RParensis&&this._sy!==R.Eof;){let t=0,s=0;i?(this._sy!==R.Number&&this.error("tremolobar-effect",R.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==R.Number&&this.error("tremolobar-effect",R.Number,!0),s=this._syData):(this._sy!==R.Number&&this.error("tremolobar-effect",R.Number,!0),t=0,s=this._syData),e.addWhammyBarPoint(new be(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!==R.RParensis&&this.error("tremolobar-effect",R.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===R.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 Re;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=g.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=g.BendGrace,this._sy=this.newSy()):e.graceType=g.BeforeBeat,!0;if("dy"===t){switch(this._sy=this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=p.PPP;break;case"pp":e.dynamics=p.PP;break;case"p":e.dynamics=p.P;break;case"mp":e.dynamics=p.MP;break;case"mf":e.dynamics=p.MF;break;case"f":e.dynamics=p.F;break;case"ff":e.dynamics=p.FF;break;case"fff":e.dynamics=p.FFF}this._currentDynamics=e.dynamics}else if("cre"===t)e.crescendo=c.Crescendo;else{if("dec"!==t){if("tp"===t){if(this._sy=this.newSy(),e.tremoloSpeed=u.Eighth,this._sy===R.Number){switch(this._syData){case 8:default:e.tremoloSpeed=u.Eighth;break;case 16:e.tremoloSpeed=u.Sixteenth;break;case 32:e.tremoloSpeed=u.ThirtySecond}this._sy=this.newSy()}return!0}return!1}e.crescendo=c.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 R.Number:s=this._syData;break;case R.String:t="x"===this._syData,i="-"===this._syData,i||t?s=0:this.error("note-fret",R.Number,!0);break;case R.Tuning:let e=this._syData;a=e.octave,r=e.noteValue;break;default:return!1}this._sy=this.newSy();let n=-1===a&&this._currentStaff.tuning.length>0,o=-1;n&&(this._sy!==R.Dot&&this.error("note",R.Dot,!0),this._sy=this.newSy(),this._sy!==R.Number&&this.error("note-string",R.Number,!0),o=this._syData,(o<1||o>this._currentStaff.tuning.length)&&this.error("note-string",R.Number,!1),this._sy=this.newSy());let h=new Pe;return n?(h.string=this._currentStaff.tuning.length-(o-1),h.isDead=t,h.isTieDestination=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===R.LBrace){for(this._sy=this.newSy();this._sy===R.String;){let t=this._syData.toLowerCase();if("b"===t||"be"===t){let i="be"===t;for(this._sy=this.newSy(),this._sy!==R.LParensis&&this.error("bend-effect",R.LParensis,!0),this._sy=this.newSy();this._sy!==R.RParensis&&this._sy!==R.Eof;){let t=0,s=0;i?(this._sy!==R.Number&&this.error("bend-effect-value",R.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==R.Number&&this.error("bend-effect-value",R.Number,!0),s=this._syData):(this._sy!==R.Number&&this.error("bend-effect-value",R.Number,!0),s=this._syData),e.addBendPoint(new be(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!==R.RParensis&&this.error("bend-effect",R.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=m.Natural,this._sy=this.newSy();else if("ah"===t)e.harmonicType=m.Artificial,this._sy=this.newSy();else if("th"===t)e.harmonicType=m.Tap,this._sy=this.newSy();else if("ph"===t)e.harmonicType=m.Pinch,this._sy=this.newSy();else if("sh"===t)e.harmonicType=m.Semi,this._sy=this.newSy();else if("tr"===t){this._sy=this.newSy(),this._sy!==R.Number&&this.error("trill-effect",R.Number,!0);let t=this._syData;this._sy=this.newSy();let i=u.Sixteenth;if(this._sy===R.Number){switch(this._syData){case 16:default:i=u.Sixteenth;break;case 32:i=u.ThirtySecond;break;case 64:i=u.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=S.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=S.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=b.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=b.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=S.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=S.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=S.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=S.PickSlideUp;else if("h"===t)this._sy=this.newSy(),e.isHammerPullOrigin=!0;else if("lht"===t)this._sy=this.newSy(),e.isLeftHandTapped=!0;else if("g"===t)this._sy=this.newSy(),e.isGhost=!0;else if("ac"===t)this._sy=this.newSy(),e.accentuated=s.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=s.Heavy;else if("pm"===t)this._sy=this.newSy(),e.isPalmMute=!0;else if("st"===t)this._sy=this.newSy(),e.isStaccato=!0;else if("lr"===t)this._sy=this.newSy(),e.isLetRing=!0;else if("x"===t)this._sy=this.newSy(),e.fret=0,e.isDead=!0;else if("-"===t||"t"===t)this._sy=this.newSy(),e.isTieDestination=!0;else if("lf"===t){this._sy=this.newSy();let t=f.Thumb;this._sy===R.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.leftHandFinger=t}else if("rf"===t){this._sy=this.newSy();let t=f.Thumb;this._sy===R.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else this.applyBeatEffect(e.beat)||this.error(t,R.String,!1)}this._sy!==R.RBrace&&this.error("note-effect",R.RBrace,!1),this._sy=this.newSy()}}toFinger(e){switch(e){case 1:return f.Thumb;case 2:return f.IndexFinger;case 3:return f.MiddleFinger;case 4:return f.AnnularFinger;case 5:return f.LittleFinger}return f.Thumb}parseDuration(e){switch(e){case-4:return u.QuadrupleWhole;case-2:return u.DoubleWhole;case 1:return u.Whole;case 2:return u.Half;case 4:return u.Quarter;case 8:return u.Eighth;case 16:return u.Sixteenth;case 32:return u.ThirtySecond;case 64:return u.SixtyFourth;case 128:return u.OneHundredTwentyEighth;case 256:return u.TwoHundredFiftySixth;default:return u.Quarter}}barMeta(e){let t=!1,i=e.masterBar;for(;this._sy===R.MetaCommand;){t=!0;let s=this._syData.toLowerCase();if("ts"===s)this._sy=this.newSy(),this._sy!==R.Number&&this.error("timesignature-numerator",R.Number,!0),i.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==R.Number&&this.error("timesignature-denominator",R.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!==R.Number&&this.error("repeatclose",R.Number,!0),this._syData>2048&&this.error("repeatclose",R.Number,!1),i.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===s)if(this._sy=this.newSy(),this._sy===R.LParensis){for(this._sy=this.newSy(),this._sy!==R.Number&&this.error("alternateending",R.Number,!0),this.applyAlternateEnding(i);this._sy===R.Number;)this.applyAlternateEnding(i);this._sy!==R.RParensis&&this.error("alternateending-list",R.RParensis,!0),this._sy=this.newSy()}else this._sy!==R.Number&&this.error("alternateending",R.Number,!0),this.applyAlternateEnding(i);else if("ks"===s)this._sy=this.newSy(),this._sy!==R.String&&this.error("keysignature",R.String,!0),i.keySignature=this.parseKeySignature(this._syData),this._sy=this.newSy();else if("clef"===s){switch(this._sy=this.newSy(),this._sy){case R.String:e.clef=this.parseClefFromString(this._syData);break;case R.Number:e.clef=this.parseClefFromInt(this._syData);break;case R.Tuning:let t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",R.String,!0)}this._sy=this.newSy()}else if("tempo"===s){this._sy=this.newSy(),this._sy!==R.Number&&this.error("tempo",R.Number,!0);let e=new fe;e.isLinear=!1,e.type=a.Tempo,e.value=this._syData,i.tempoAutomation=e,this._sy=this.newSy()}else if("section"===s){this._sy=this.newSy(),this._sy!==R.String&&this.error("section",R.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==R.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());let s=new We;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 R.String:i.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case R.Number:i.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",R.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",R.String,!1)}if(0===i.index&&!i.tempoAutomation){let e=new fe;e.isLinear=!1,e.type=a.Tempo,e.value=this._score.tempo,i.tempoAutomation=e}return t}applyAlternateEnding(e){let t=this._syData;t<1&&this.error("alternateending",R.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}}et.Eof=0;class tt extends ue{get name(){return"Guitar Pro 3-5"}constructor(){super(),this._versionNumber=0,this._globalTripletFeel=I.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 He,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=it.gpReadBool(this.data)?I.Triplet8th:I.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=it.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=$e.readInt32LE(this.data),this._versionNumber>=510&&it.gpReadBool(this.data),$e.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.data.skip(38),this.data.skip(4)),this._barCount=$e.readInt32LE(this.data),this._trackCount=$e.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0&&(this._score.masterBars[0].tempoAutomation=fe.buildTempoAutomation(!1,0,this._score.tempo,2),this._score.masterBars[0].tempoAutomation.text=this._score.tempoLabel),this._score.finish(this.settings),this._lyrics&&this._lyricsTrack>=0&&this._score.tracks[this._lyricsTrack].applyLyrics(this._lyrics),this._score}readVersion(){let e=it.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(tt.VersionString))throw new ge("Unsupported format");e=e.substr(tt.VersionString.length+1);let t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*parseInt(e.substr(0,t))+parseInt(e.substr(t+1)),Be.debug(this.name,"Guitar Pro version "+e+" detected")}readScoreInformation(){var e;this._score.title=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?it.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding);let t=$e.readInt32LE(this.data),i="";for(let s=0;s<t;s++)s>0&&(i+="\r\n"),i+=null===(e=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding))||void 0===e?void 0:e.toString();this._score.notices=i}readLyrics(){this._lyrics=[],this._lyricsTrack=$e.readInt32LE(this.data)-1;for(let e=0;e<5;e++){let e=new Ae;e.startBar=$e.readInt32LE(this.data)-1,e.text=it.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(30);for(let e=0;e<10;e++)it.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){let t=new Xe;t.primaryChannel=e,t.secondaryChannel=e,t.program=$e.readInt32LE(this.data),t.volume=this.data.readByte(),t.balance=this.data.readByte(),this.data.skip(6),this._playbackInfos.push(t)}}readMasterBars(){for(let e=0;e<this._barCount;e++)this.readMasterBar()}readMasterBar(){let e=null;this._score.masterBars.length>0&&(e=this._score.masterBars[this._score.masterBars.length-1]);let t=new Oe,i=this.data.readByte();if(0!=(1&i)?t.timeSignatureNumerator=this.data.readByte():e&&(t.timeSignatureNumerator=e.timeSignatureNumerator),0!=(2&i)?t.timeSignatureDenominator=this.data.readByte():e&&(t.timeSignatureDenominator=e.timeSignatureDenominator),t.isRepeatStart=0!=(4&i),0!=(8&i)&&(t.repeatCount=this.data.readByte()+(this._versionNumber>=500?0:1)),0!=(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&&0==(s&t)&&(a|=t)}t.alternateEndings=a}if(0!=(32&i)){let e=new We;e.text=it.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",it.gpReadColor(this.data,!1),t.section=e}if(0!=(64&i)?(t.keySignature=$e.readSInt8(this.data),t.keySignatureType=this.data.readByte()):e&&(t.keySignature=e.keySignature,t.keySignatureType=e.keySignatureType),this._versionNumber>=500&&0!=(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=I.Triplet8th;break;case 2:t.tripletFeel=I.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=0!=(128&i),this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){let e=new Je;e.ensureStaveCount(1),this._score.addTrack(e);let t=e.staves[0],i=this.data.readByte();e.name=it.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),0!=(1&i)&&(t.isPercussion=!0);let s=$e.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){let t=$e.readInt32LE(this.data);s>e&&a.push(t)}t.stringTuning.tunings=a;let r=$e.readInt32LE(this.data),n=$e.readInt32LE(this.data)-1,o=$e.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=0!=(16&i),s.isMute=0!=(32&i),s.secondaryChannel=o,ce.isGuitar(s.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=s}t.capo=$e.readInt32LE(this.data),e.color=it.gpReadColor(this.data,!1),this._versionNumber>=500&&(this.data.readByte(),this.data.readByte(),this.data.skip(43)),this._versionNumber>=510&&(this.data.skip(4),it.gpReadStringIntByte(this.data,this.settings.importer.encoding),it.gpReadStringIntByte(this.data,this.settings.importer.encoding))}readBars(){for(let e=0;e<this._barCount;e++)for(let e=0;e<this._trackCount;e++)this.readBar(this._score.tracks[e])}readBar(e){let t=new me,i=e.staves[0];i.isPercussion&&(t.clef=r.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=$e.readInt32LE(this.data);if(0===i)return;let s=new je;t.addVoice(s);for(let a=0;a<i;a++)this.readBeat(e,t,s)}readBeat(e,t,i){let s=new Ie,a=this.data.readByte();if(0!=(1&a)&&(s.dots=1),0!=(64&a)){let e=this.data.readByte();s.isEmpty=0==(2&e)}switch(i.addBeat(s),$e.readSInt8(this.data)){case-2:s.duration=u.Whole;break;case-1:s.duration=u.Half;break;case 0:s.duration=u.Quarter;break;case 1:s.duration=u.Eighth;break;case 2:s.duration=u.Sixteenth;break;case 3:s.duration=u.ThirtySecond;break;case 4:s.duration=u.SixtyFourth;break;default:s.duration=u.Quarter}if(0!=(32&a))switch(s.tupletNumerator=$e.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}0!=(2&a)&&this.readChord(s);let r=this.settings.importer.beatTextAsLyrics&&e.index!==this._lyricsTrack;if(0!=(4&a)){const t=it.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const i=new Ae;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=m.None;0!=(8&a)&&(n=this.readBeatEffects(s)),0!=(16&a)&&this.readMixTableChange(s);let o=this.data.readByte();for(let a=6;a>=0;a--)if(0!=(o&1<<a)&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,i,s,6-a);n!==m.None&&(r.harmonicType=n,r.harmonicType===m.Natural&&(r.harmonicValue=this.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){this.data.readByte(),0!=(8&this.data.readByte())&&this.data.readByte()}r&&!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 Re,i=ke.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=it.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=$e.readInt32LE(this.data);for(let i=0;i<7;i++){let s=$e.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=it.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=$e.readInt32LE(this.data);for(let i=0;i<7;i++){let s=$e.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=it.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=$e.readInt32LE(this.data);for(let i=0;i<6;i++){let s=$e.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=it.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=$e.readInt32LE(this.data),t.firstFret>0)for(let s=0;s<i;s++){let i=$e.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=0!=(16&t),(this._versionNumber<400&&0!=(1&t)||0!=(2&t))&&(e.vibrato=_.Slight),e.hasRasgueado=0!=(1&i),0!=(32&t)&&this._versionNumber>=400){switch($e.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}}else if(0!=(32&t)){switch($e.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}this.data.skip(4)}if(0!=(4&i)&&this.readTremoloBarEffect(e),0!=(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=tt.toStrokeValue(t)):i>0&&(e.brushType=d.BrushDown,e.brushDuration=tt.toStrokeValue(i))}if(0!=(2&i))switch($e.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(0!=(4&t))return m.Natural;if(0!=(8&t))return m.Artificial}return m.None}readTremoloBarEffect(e){this.data.readByte(),$e.readInt32LE(this.data);let t=$e.readInt32LE(this.data);if(t>0)for(let i=0;i<t;i++){let t=new be(0,0);t.offset=$e.readInt32LE(this.data),t.value=$e.readInt32LE(this.data)/tt.BendStep|0,it.gpReadBool(this.data),e.addWhammyBarPoint(t)}}static toStrokeValue(e){switch(e){case 1:case 2:return 30;case 3:return 60;case 4:return 120;case 5:return 240;case 6:return 480;default:return 0}}readMixTableChange(e){let t=new st;t.instrument=$e.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=$e.readSInt8(this.data),t.balance=$e.readSInt8(this.data);let i=$e.readSInt8(this.data),s=$e.readSInt8(this.data),r=$e.readSInt8(this.data),n=$e.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=it.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=$e.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(),r>=0&&this.data.readByte(),n>=0&&this.data.readByte(),t.tempo>=0&&(t.duration=$e.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500&&this.data.readByte(),this._versionNumber>=510&&(it.gpReadStringIntByte(this.data,this.settings.importer.encoding),it.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){let i=new fe;i.isLinear=!0,i.type=a.Volume,i.value=t.volume,e.automations.push(i)}if(t.balance>=0){let i=new fe;i.isLinear=!0,i.type=a.Balance,i.value=t.balance,e.automations.push(i)}if(t.instrument>=0){let i=new fe;i.isLinear=!0,i.type=a.Instrument,i.value=t.instrument,e.automations.push(i)}if(t.tempo>=0){let i=new fe;i.isLinear=!0,i.type=a.Tempo,i.value=t.tempo,e.automations.push(i),e.voice.bar.masterBar.tempoAutomation=i}}readNote(e,t,i,a,r){let n=new Pe;n.string=t.staff.tuning.length-r;let o=this.data.readByte();if(0!=(2&o)?n.accentuated=s.Heavy:0!=(64&o)&&(n.accentuated=s.Normal),n.isGhost=0!=(4&o),0!=(32&o)){let e=this.data.readByte();3===e?n.isDead=!0:2===e&&(n.isTieDestination=!0)}if(0!=(1&o)&&this._versionNumber<500&&(this.data.readByte(),this.data.readByte()),0!=(16&o)){let e=$e.readSInt8(this.data);n.dynamics=this.toDynamicValue(e),a.dynamics=n.dynamics}0!=(32&o)&&(n.fret=$e.readSInt8(this.data)),0!=(128&o)&&(n.leftHandFinger=$e.readSInt8(this.data),n.rightHandFinger=$e.readSInt8(this.data),n.isFingering=!0);let h=!1;if(this._versionNumber>=500){0!=(1&o)&&(n.durationPercent=it.gpReadDouble(this.data)),h=0!=(2&this.data.readByte())}if(a.addNote(n),0!=(8&o)&&this.readNoteEffects(e,i,a,n),t.staff.isPercussion&&(n.percussionArticulation=n.fret,n.string=-1,n.fret=-1),h){const e=Ye.defaultAccidentals[n.realValueWithoutHarmonic%12];"#"===e?n.accidentalMode=y.ForceFlat:"b"===e&&(n.accidentalMode=y.ForceSharp)}return n}toDynamicValue(e){switch(e){case 1:return p.PPP;case 2:return p.PP;case 3:return p.P;case 4:return p.MP;case 5:return p.MF;case 6:default:return p.F;case 7:return p.FF;case 8:return p.FFF}}readNoteEffects(e,t,i,s){let a=this.data.readByte(),r=0;this._versionNumber>=400&&(r=this.data.readByte()),0!=(1&a)&&this.readBend(s),0!=(16&a)&&this.readGrace(t,s),0!=(4&r)&&this.readTremoloPicking(i),0!=(8&r)?this.readSlide(s):this._versionNumber<400&&0!=(4&a)&&(s.slideOutType=S.Shift),0!=(16&r)&&this.readArtificialHarmonic(s),0!=(32&r)&&this.readTrill(s),s.isLetRing=0!=(8&a),s.isHammerPullOrigin=0!=(2&a),0!=(64&r)&&(s.vibrato=_.Slight),s.isPalmMute=0!=(2&r),s.isStaccato=0!=(1&r)}readBend(e){this.data.readByte(),$e.readInt32LE(this.data);let t=$e.readInt32LE(this.data);if(t>0)for(let i=0;i<t;i++){let t=new be(0,0);t.offset=$e.readInt32LE(this.data),t.value=$e.readInt32LE(this.data)/tt.BendStep|0,it.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){let i=new Ie,s=new Pe;switch(s.string=t.string,s.fret=$e.readSInt8(this.data),i.duration=u.ThirtySecond,i.dynamics=this.toDynamicValue($e.readSInt8(this.data)),$e.readSInt8(this.data)){case 0:case 2:break;case 1:s.slideOutType=S.Legato,s.slideTarget=t;break;case 3:s.isHammerPullOrigin=!0}if(s.dynamics=i.dynamics,this.data.skip(1),this._versionNumber<500)i.graceType=g.BeforeBeat;else{let e=this.data.readByte();s.isDead=0!=(1&e),i.graceType=0!=(2&e)?g.OnBeat:g.BeforeBeat}e.addGraceBeat(i),i.addNote(s)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=u.Eighth;break;case 2:e.tremoloSpeed=u.Sixteenth;break;case 3:e.tremoloSpeed=u.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){let t=$e.readSInt8(this.data);0!=(1&t)?e.slideOutType=S.Shift:0!=(2&t)?e.slideOutType=S.Legato:0!=(4&t)?e.slideOutType=S.OutDown:0!=(8&t)&&(e.slideOutType=S.OutUp),0!=(16&t)?e.slideInType=b.IntoFromBelow:0!=(32&t)&&(e.slideInType=b.IntoFromAbove)}else{switch($e.readSInt8(this.data)){case 1:e.slideOutType=S.Shift;break;case 2:e.slideOutType=S.Legato;break;case 3:e.slideOutType=S.OutDown;break;case 4:e.slideOutType=S.OutUp;break;case-1:e.slideInType=b.IntoFromBelow;break;case-2:e.slideInType=b.IntoFromAbove}}}readArtificialHarmonic(e){let t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=m.Natural,e.harmonicValue=this.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=m.Artificial;break;case 3:e.harmonicType=m.Tap,e.harmonicValue=this.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=m.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=m.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=m.Natural;break;case 3:e.harmonicType=m.Tap;break;case 4:e.harmonicType=m.Pinch;break;case 5:e.harmonicType=m.Semi;break;case 15:case 17:case 22:e.harmonicType=m.Artificial}}deltaFretToHarmonicValue(e){switch(e){case 2:return 2.4;case 3:return 3.2;case 4:case 5:case 7:case 9:case 12:case 16:case 17:case 19:case 24:return e;case 8:return 8.2;case 10:return 9.6;case 14:case 15:return 14.7;case 21:case 22:return 21.7;default:return 12}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=u.Sixteenth;break;case 2:e.trillSpeed=u.ThirtySecond;break;case 3:e.trillSpeed=u.SixtyFourth}}}tt.VersionString="FICHIER GUITAR PRO ",tt.BendStep=25;class it{static gpReadDouble(e){let t=new Uint8Array(8);return e.read(t,0,t.length),new Float64Array(t.buffer)[0]}static gpReadFloat(e){let t=new Uint8Array(4);return t[3]=e.readByte(),t[2]=e.readByte(),t[2]=e.readByte(),t[1]=e.readByte(),new Float32Array(t.buffer)[0]}static gpReadColor(e,t=!1){let i=e.readByte(),s=e.readByte(),a=e.readByte(),r=255;return t?r=e.readByte():e.skip(1),new Ue(i,s,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),it.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return it.gpReadString(e,$e.readInt32LE(e),t)}static gpReadStringIntByte(e,t){let i=$e.readInt32LE(e)-1;return e.readByte(),it.gpReadString(e,i,t)}static gpReadString(e,t,i){let s=new Uint8Array(t);return e.read(s,0,s.length),$e.toString(s,i)}static gpWriteString(e,t){const i=$e.stringToBytes(t);e.writeByte(t.length),e.write(i,0,i.length)}static gpReadStringByteLength(e,t,i){let s=e.readByte(),a=it.gpReadString(e,s,i);return s<t&&e.skip(t-s),a}}class st{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class at{constructor(){this.x=0,this.y=0,this.w=0,this.h=0}}!function(e){e[e.Boolean=0]="Boolean",e[e.Integer=1]="Integer",e[e.Float=2]="Float",e[e.String=3]="String",e[e.Point=4]="Point",e[e.Size=5]="Size",e[e.Rectangle=6]="Rectangle",e[e.Color=7]="Color"}(A||(A={}));class rt{constructor(e){this.raw=new Map;let t=Ke.fromBuffer(e),i=$e.readInt32BE(t);for(let e=0;e<i;e++){let e=it.gpReadString(t,t.readByte(),"utf-8");switch(t.readByte()){case A.Boolean:let i=1===t.readByte();this.addValue(e,i);break;case A.Integer:let s=$e.readInt32BE(t);this.addValue(e,s);break;case A.Float:let a=it.gpReadFloat(t);this.addValue(e,a);break;case A.String:let r=it.gpReadString(t,$e.readInt16BE(t),"utf-8");this.addValue(e,r);break;case A.Point:let n=$e.readInt32BE(t),o=$e.readInt32BE(t);this.addValue(e,new be(n,o));break;case A.Size:let h=$e.readInt32BE(t),l=$e.readInt32BE(t);this.addValue(e,new be(h,l));break;case A.Rectangle:let d=new at;d.x=$e.readInt32BE(t),d.y=$e.readInt32BE(t),d.w=$e.readInt32BE(t),d.h=$e.readInt32BE(t),this.addValue(e,d);break;case A.Color:let c=it.gpReadColor(t,!0);this.addValue(e,c)}}}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 $e.writeInt32BE(t,1),rt.writeBooleanEntry(t,"StandardNotation/hideDynamics",e.stylesheet.hideDynamics),t.toArray()}static writeBooleanEntry(e,t,i){it.gpWriteString(e,t),e.writeByte(A.Boolean),e.writeByte(i?1:0)}}!function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(O||(O={}));class nt{constructor(){this.type=O.Short,this.length=0}}!function(e){e[e.None=0]="None",e[e.Element=1]="Element",e[e.Text=2]="Text",e[e.CDATA=3]="CDATA",e[e.Document=4]="Document",e[e.DocumentType=5]="DocumentType"}(G||(G={}));class ot{constructor(){this.nodeType=G.None,this.localName=null,this.value=null,this.childNodes=[],this.attributes=new Map,this.firstChild=null,this.firstElement=null}addChild(e){this.childNodes.push(e),this.firstChild=e,e.nodeType!==G.Element&&e.nodeType!==G.CDATA||(this.firstElement=e)}getAttribute(e){return this.attributes.has(e)?this.attributes.get(e):""}getElementsByTagName(e,t=!1){let i=[];return this.searchElementsByTagName(this.childNodes,i,e,t),i}searchElementsByTagName(e,t,i,s=!1){for(let a of e)a&&a.nodeType===G.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===G.Element&&t.localName===e)return t;return null}addElement(e){const t=new ot;return t.nodeType=G.Element,t.localName=e,this.addChild(t),t}get innerText(){var e,t;if(this.nodeType===G.Element||this.nodeType===G.Document){if(this.firstElement&&this.firstElement.nodeType===G.CDATA)return this.firstElement.innerText;let t="";for(let i of this.childNodes)t+=null===(e=i.innerText)||void 0===e?void 0:e.toString();return t.trim()}return null!==(t=this.value)&&void 0!==t?t:""}set innerText(e){const t=new ot;t.nodeType=G.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new ot;t.nodeType=G.CDATA,t.value=e,this.childNodes=[t]}}class ht extends pe{constructor(e,t,s){super(i.Format,e),this.pos=0,this.xml=t,this.pos=s,Object.setPrototypeOf(this,ht.prototype)}}!function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.BeginNode=2]="BeginNode",e[e.TagName=3]="TagName",e[e.Body=4]="Body",e[e.AttribName=5]="AttribName",e[e.Equals=6]="Equals",e[e.AttvalBegin=7]="AttvalBegin",e[e.AttribVal=8]="AttribVal",e[e.Childs=9]="Childs",e[e.Close=10]="Close",e[e.WaitEnd=11]="WaitEnd",e[e.WaitEndRet=12]="WaitEndRet",e[e.Pcdata=13]="Pcdata",e[e.Header=14]="Header",e[e.Comment=15]="Comment",e[e.Doctype=16]="Doctype",e[e.Cdata=17]="Cdata",e[e.Escape=18]="Escape"}(V||(V={}));class lt{static parse(e,t,i){var s;let a=e.charCodeAt(t),r=V.Begin,n=V.Begin,o=0,h="",l=V.Begin,d=null,c=null,u=0,p=0;for(;t<e.length;){switch(a=e.charCodeAt(t),r){case V.IgnoreSpaces:switch(a){case lt.CharCodeLF:case lt.CharCodeCR:case lt.CharCodeTab:case lt.CharCodeSpace:break;default:r=n;continue}break;case V.Begin:if(a!==lt.CharCodeLowerThan){o=t,r=V.Pcdata;continue}r=V.IgnoreSpaces,n=V.BeginNode;break;case V.Pcdata:if(a===lt.CharCodeLowerThan){h+=e.substr(o,t-o);let s=new ot;s.nodeType=G.Text,s.value=h,h="",i.addChild(s),r=V.IgnoreSpaces,n=V.BeginNode}else a===lt.CharCodeAmp&&(h+=e.substr(o,t-o),r=V.Escape,l=V.Pcdata,o=t+1);break;case V.Cdata:if(a===lt.CharCodeBrackedClose&&e.charCodeAt(t+1)===lt.CharCodeBrackedClose&&e.charCodeAt(t+2)===lt.CharCodeGreaterThan){let s=new ot;s.nodeType=G.CDATA,s.value=e.substr(o,t-o),i.addChild(s),t+=2,r=V.Begin}break;case V.BeginNode:switch(a){case lt.CharCodeExclamation:if(e.charCodeAt(t+1)===lt.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new ht("Expected <![CDATA[",e,t);t+=5,r=V.Cdata,o=t+1}else if(e.charCodeAt(t+1)===lt.CharCodeUpperD||e.charCodeAt(t+1)===lt.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new ht("Expected <!DOCTYPE",e,t);t+=8,r=V.Doctype,o=t+1}else{if(e.charCodeAt(t+1)!==lt.CharCodeMinus||e.charCodeAt(t+2)!==lt.CharCodeMinus)throw new ht("Expected \x3c!--",e,t);t+=2,r=V.Comment,o=t+1}break;case lt.CharCodeQuestion:r=V.Header,o=t;break;case lt.CharCodeSlash:if(!i)throw new ht("Expected node name",e,t);o=t+1,r=V.IgnoreSpaces,n=V.Close;break;default:r=V.TagName,o=t;continue}break;case V.TagName:if(!lt.isValidChar(a)){if(t===o)throw new ht("Expected node name",e,t);d=new ot,d.nodeType=G.Element,d.localName=e.substr(o,t-o),i.addChild(d),r=V.IgnoreSpaces,n=V.Body;continue}break;case V.Body:switch(a){case lt.CharCodeSlash:r=V.WaitEnd;break;case lt.CharCodeGreaterThan:r=V.Childs;break;default:r=V.AttribName,o=t;continue}break;case V.AttribName:if(!lt.isValidChar(a)){if(o===t)throw new ht("Expected attribute name",e,t);if(c=e.substr(o,t-o),d.attributes.has(c))throw new ht(`Duplicate attribute [${c}]`,e,t);r=V.IgnoreSpaces,n=V.Equals;continue}break;case V.Equals:if(a!==lt.CharCodeEquals)throw new ht("Expected =",e,t);r=V.IgnoreSpaces,n=V.AttvalBegin;break;case V.AttvalBegin:switch(a){case lt.CharCodeDoubleQuote:case lt.CharCodeSingleQuote:h="",r=V.AttribVal,o=t+1,p=a}break;case V.AttribVal:if(a===lt.CharCodeAmp)h+=e.substr(o,t-o),r=V.Escape,l=V.AttribVal,o=t+1;else if(a===p){h+=e.substr(o,t-o);let i=h;h="",d.attributes.set(c,i),r=V.IgnoreSpaces,n=V.Body}break;case V.Childs:o=t=lt.parse(e,t,d),r=V.Begin;break;case V.WaitEnd:if(a!==lt.CharCodeGreaterThan)throw new ht("Expected >",e,t);r=V.Begin;break;case V.WaitEndRet:if(a===lt.CharCodeGreaterThan)return t;throw new ht("Expected >",e,t);case V.Close:if(!lt.isValidChar(a)){if(o===t)throw new ht("Expected node name",e,t);if(e.substr(o,t-o)!==i.localName)throw new ht("Expected </"+i.localName+">",e,t);r=V.IgnoreSpaces,n=V.WaitEndRet;continue}break;case V.Comment:a===lt.CharCodeMinus&&e.charCodeAt(t+1)===lt.CharCodeMinus&&e.charCodeAt(t+2)===lt.CharCodeGreaterThan&&(t+=2,r=V.Begin);break;case V.Doctype:if(a===lt.CharCodeBrackedOpen)u++;else if(a===lt.CharCodeBrackedClose)u--;else if(a===lt.CharCodeGreaterThan&&0===u){let s=new ot;s.nodeType=G.DocumentType,s.value=e.substr(o,t-o),i.addChild(s),r=V.Begin}break;case V.Header:a===lt.CharCodeQuestion&&e.charCodeAt(t+1)===lt.CharCodeGreaterThan&&(t++,r=V.Begin);break;case V.Escape:if(a===lt.CharCodeSemi){let i=e.substr(o,t-o);if(i.charCodeAt(0)===lt.CharCodeSharp){let e=i.charCodeAt(1)===lt.CharCodeLowerX?parseInt("0"+i.substr(1,i.length-1)):parseInt(i.substr(1,i.length-1));h+=String.fromCharCode(e)}else lt.Escapes.has(i)?h+=lt.Escapes.get(i):h+=null===(s="&"+i+";")||void 0===s?void 0:s.toString();o=t+1,r=l}else lt.isValidChar(a)||a===lt.CharCodeSharp||(h+="&",h+=e.substr(o,t-o),o=--t+1,r=l)}t++}if(r===V.Begin&&(o=t,r=V.Pcdata),r===V.Pcdata){if(t!==o){h+=e.substr(o,t-o);let s=new ot;s.nodeType=G.Text,s.value=h,i.addChild(s)}return t}if(r===V.Escape&&l===V.Pcdata){h+="&",h+=e.substr(o,t-o);let s=new ot;return s.nodeType=G.Text,s.value=h,i.addChild(s),t}throw new ht("Unexpected end",e,t)}static isValidChar(e){return e>=lt.CharCodeLowerA&&e<=lt.CharCodeLowerZ||e>=lt.CharCodeUpperA&&e<=lt.CharCodeUpperZ||e>=lt.CharCode0&&e<=lt.CharCode9||e===lt.CharCodeColon||e===lt.CharCodeDot||e===lt.CharCodeUnderscore||e===lt.CharCodeMinus}}lt.CharCodeLF=10,lt.CharCodeTab=9,lt.CharCodeCR=13,lt.CharCodeSpace=32,lt.CharCodeLowerThan=60,lt.CharCodeAmp=38,lt.CharCodeBrackedClose=93,lt.CharCodeBrackedOpen=91,lt.CharCodeGreaterThan=62,lt.CharCodeExclamation=33,lt.CharCodeUpperD=68,lt.CharCodeLowerD=100,lt.CharCodeMinus=45,lt.CharCodeQuestion=63,lt.CharCodeSlash=47,lt.CharCodeEquals=61,lt.CharCodeDoubleQuote=34,lt.CharCodeSingleQuote=39,lt.CharCodeSharp=35,lt.CharCodeLowerX=120,lt.CharCodeLowerA=97,lt.CharCodeLowerZ=122,lt.CharCodeUpperA=65,lt.CharCodeUpperZ=90,lt.CharCode0=48,lt.CharCode9=57,lt.CharCodeColon=58,lt.CharCodeDot=46,lt.CharCodeUnderscore=95,lt.CharCodeSemi=59,lt.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class dt{static write(e,t,i){const s=new dt(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 G.None:break;case G.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===G.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case G.Text:e.value&&this.write(e.value);break;case G.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case G.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case G.DocumentType:this.write(`<!DOCTYPE ${e.value}>`)}}unindend(){this._currentIndention=this._currentIndention.substr(0,this._currentIndention.length-this._indention.length)}indent(){this._currentIndention+=this._indention}writeAttributeValue(e){for(let t=0;t<e.length;t++){const i=e.charAt(t);switch(i){case"<":this._result.push("<");break;case">":this._result.push(">");break;case"&":this._result.push("&");break;case"'":this._result.push("'");break;case'"':this._result.push(""");break;default:this._result.push(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 ct extends ot{constructor(){super(),this.nodeType=G.Document}parse(e){lt.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return dt.write(this,e,t)}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(H||(H={}));class ut{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=u.Quarter}}class pt{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return this.path+";"+this.name+";"+this.role}}class gt{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1}parseXml(e,t){this._masterTrackAutomations=new Map,this._automationsPerTrackIdAndBarIndex=new Map,this._tracksMapping=[],this._tracksById=new Map,this._masterBars=[],this._barsOfMasterBar=[],this._voicesOfBar=new Map,this._barsById=new Map,this._voiceById=new Map,this._beatsOfVoice=new Map,this._beatById=new Map,this._rhythmOfBeat=new Map,this._rhythmById=new Map,this._notesOfBeat=new Map,this._noteById=new Map,this._tappedNotes=new Map,this._lyricsByTrack=new Map,this._soundsByTrack=new Map,this._skipApplyLyrics=!1;let i=new ct;try{i.parse(e)}catch(e){throw new ge("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 ge("Root node of XML was not GPIF");this.score=new He;for(let e of t.childNodes)if(e.nodeType===G.Element)switch(e.localName){case"Score":this.parseScoreNode(e);break;case"MasterTrack":this.parseMasterTrackNode(e);break;case"Tracks":this.parseTracksNode(e);break;case"MasterBars":this.parseMasterBarsNode(e);break;case"Bars":this.parseBars(e);break;case"Voices":this.parseVoices(e);break;case"Beats":this.parseBeats(e);break;case"Notes":this.parseNotes(e);break;case"Rhythms":this.parseRhythms(e)}}}parseScoreNode(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Title":this.score.title=t.firstChild.innerText;break;case"SubTitle":this.score.subTitle=t.firstChild.innerText;break;case"Artist":this.score.artist=t.firstChild.innerText;break;case"Album":this.score.album=t.firstChild.innerText;break;case"Words":this.score.words=t.firstChild.innerText;break;case"Music":this.score.music=t.firstChild.innerText;break;case"WordsAndMusic":if(t.firstChild&&""!==t.firstChild.innerText){let e=t.firstChild.innerText;e&&!this.score.words&&(this.score.words=e),e&&!this.score.music&&(this.score.music=e)}break;case"Copyright":this.score.copyright=t.firstChild.innerText;break;case"Tabber":this.score.tab=t.firstChild.innerText;break;case"Instructions":this.score.instructions=t.firstChild.innerText;break;case"Notices":this.score.notices=t.firstChild.innerText}}parseMasterTrackNode(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null);break;case"Tracks":this._tracksMapping=t.innerText.split(" ");break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,i){for(let s of e.childNodes)if(s.nodeType===G.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,d=null;for(let t of e.childNodes)if(t.nodeType===G.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===G.CDATA)h=t.innerText;else{let e=t.innerText.split(" ");1===e.length?(o=parseFloat(e[0]),l=1):(o=parseFloat(e[0]),l=parseInt(e[1]))}break;case"Text":d=t.innerText}if(!s)return;let c=null;switch(s){case"Tempo":c=fe.buildTempoAutomation(a,n,o,l);break;case"Sound":h&&i&&i.has(h)&&(c=fe.buildInstrumentAutomation(a,n,i.get(h).program))}c&&(d&&(c.text=d),r>=0&&(t.has(r)||t.set(r,[]),t.get(r).push(c)))}parseTracksNode(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;let t=new Je;t.ensureStaveCount(1),t.staves[0].showStandardNotation=!0;let i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===G.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 Ue(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"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===G.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===G.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===G.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===G.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===G.Element&&"Articulation"===s.localName)this.parseArticulation(e,s,i)}parseArticulation(e,t,i){const s=new ve;s.outputMidiNumber=-1,s.elementType=i;let a="";for(let e of t.childNodes)if(e.nodeType===G.Element){const t=e.innerText;switch(e.localName){case"Name":a=e.innerText;break;case"OutputMidiNumber":t.length>0&&(s.outputMidiNumber=parseInt(t));break;case"TechniqueSymbol":s.techniqueSymbol=this.parseTechniqueSymbol(t);break;case"TechniquePlacement":switch(t){case"outside":case"above":s.techniqueSymbolPlacement=E.Bottom;break;case"inside":s.techniqueSymbolPlacement=E.Middle;break;case"below":s.techniqueSymbolPlacement=E.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==x.None&&(s.noteHeadHalf=s.noteHeadDefault),s.noteHeadWhole==x.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 x.PictEdgeOfCymbal;case"articStaccatoAbove":return x.ArticStaccatoAbove;case"noteheadParenthesis":return x.NoteheadParenthesis;case"stringsUpBow":return x.StringsUpBow;case"stringsDownBow":return x.StringsDownBow;case"guitarGolpe":return x.GuitarGolpe;default:return x.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return x.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return x.NoteheadDoubleWhole;case"noteheadWhole":return x.NoteheadWhole;case"noteheadHalf":return x.NoteheadHalf;case"noteheadBlack":return x.NoteheadBlack;case"noteheadNull":return x.NoteheadNull;case"noteheadXOrnate":return x.NoteheadXOrnate;case"noteheadTriangleUpWhole":return x.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return x.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return x.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return x.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return x.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return x.NoteheadDiamondWhiteWide;case"noteheadCircleX":return x.NoteheadCircleX;case"noteheadXWhole":return x.NoteheadXWhole;case"noteheadXHalf":return x.NoteheadXHalf;case"noteheadXBlack":return x.NoteheadXBlack;case"noteheadParenthesis":return x.NoteheadParenthesis;case"noteheadSlashedBlack2":return x.NoteheadSlashedBlack2;case"noteheadCircleSlash":return x.NoteheadCircleSlash;case"noteheadHeavyX":return x.NoteheadHeavyX;case"noteheadHeavyXHat":return x.NoteheadHeavyXHat;default:return Be.warning("GPIF","Unknown notehead symbol",e),x.None}}parseStaves(e,t){let i=0;for(let s of t.childNodes)if(s.nodeType===G.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===G.Element&&"Properties"===i.localName)this.parseStaffProperties(e,i)}parseStaffProperties(e,t){for(let i of t.childNodes)if(i.nodeType===G.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===G.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===G.Element&&"Line"===e.localName)i.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,i)}parseLyricsLine(e){let t=new Ae;for(let i of e.childNodes)if(i.nodeType===G.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===G.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===G.Element&&"Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){let i=new Re,s=t.getAttribute("id");for(let t of e.staves)t.addChord(s,i);this.parseDiagramItemForChord(i,t)}parseDiagramItemForStaff(e,t){let i=new Re,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"),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===G.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===G.Element&&"Position"===i.localName){let t=f.Unknown,s=a+parseInt(i.getAttribute("fret"));switch(i.getAttribute("finger")){case"Index":t=f.IndexFinger;break;case"Middle":t=f.MiddleFinger;break;case"Rank":t=f.AnnularFinger;break;case"Pinky":t=f.LittleFinger;break;case"Thumb":t=f.Thumb}t!==f.Unknown&&(r.has(t)?e.barreFrets.push(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===G.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===G.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===G.Element&&"Sound"===s.localName)this.parseSound(e,t,s)}parseSound(e,t,i){const s=new pt;for(let e of i.childNodes)if(e.nodeType===G.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===G.Element&&"Program"===i.localName)e.program=parseInt(i.innerText)}parsePartSounding(e,t){for(let i of t.childNodes)if(i.nodeType===G.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===G.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===G.Element&&"ChannelStrip"===i.localName)this.parseChannelStrip(e,i)}parseChannelStrip(e,t){for(let i of t.childNodes)if(i.nodeType===G.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===G.Element&&"MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){let t=new Oe;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(let i of e.childNodes)if(i.nodeType===G.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 We,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=I.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=I.Triplet8th;break;case"Triplet16th":t.tripletFeel=I.Triplet16th;break;case"Dotted8th":t.tripletFeel=I.Dotted8th;break;case"Dotted16th":t.tripletFeel=I.Dotted16th;break;case"Scottish8th":t.tripletFeel=I.Scottish8th;break;case"Scottish16th":t.tripletFeel=I.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)}this._masterBars.push(t)}parseFermatas(e,t){for(let i of t.childNodes)if(i.nodeType===G.Element&&"Fermata"===i.localName)this.parseFermata(e,i)}parseFermata(e,t){let i=0,s=new nt;for(let e of t.childNodes)if(e.nodeType===G.Element)switch(e.localName){case"Type":switch(e.innerText){case"Short":s.type=O.Short;break;case"Medium":s.type=O.Medium;break;case"Long":s.type=O.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])*ye.QuarterTime|0}}e.addFermata(i,s)}parseBars(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"Bar"===t.localName)this.parseBar(t)}parseBar(e){let t=new me,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===G.Element)switch(s.localName){case"Voices":this._voicesOfBar.set(i,s.innerText.split(" "));break;case"Clef":switch(s.innerText){case"Neutral":t.clef=r.Neutral;break;case"G2":t.clef=r.G2;break;case"F4":t.clef=r.F4;break;case"C4":t.clef=r.C4;break;case"C3":t.clef=r.C3}break;case"Ottavia":switch(s.innerText){case"8va":t.clefOttava=n._8va;break;case"15ma":t.clefOttava=n._15ma;break;case"8vb":t.clefOttava=n._8vb;break;case"15mb":t.clefOttava=n._15mb}break;case"SimileMark":switch(s.innerText){case"Simple":t.simileMark=o.Simple;break;case"FirstOfDouble":t.simileMark=o.FirstOfDouble;break;case"SecondOfDouble":t.simileMark=o.SecondOfDouble}}this._barsById.set(i,t)}parseVoices(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"Voice"===t.localName)this.parseVoice(t)}parseVoice(e){let t=new je,i=e.getAttribute("id");for(let t of e.childNodes)if(t.nodeType===G.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===G.Element&&"Beat"===t.localName)this.parseBeat(t)}parseBeat(e){let t=new Ie,i=e.getAttribute("id");for(let s of e.childNodes)if(s.nodeType===G.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=u.Eighth;break;case"1/4":t.tremoloSpeed=u.Sixteenth;break;case"1/8":t.tremoloSpeed=u.ThirtySecond}break;case"Chord":t.chordId=s.innerText;break;case"Hairpin":switch(s.innerText){case"Crescendo":t.crescendo=c.Crescendo;break;case"Decrescendo":t.crescendo=c.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=H.Up;break;case"Downward":t.preferredBeamDirection=H.Down}break;case"Dynamic":switch(s.innerText){case"PPP":t.dynamics=p.PPP;break;case"PP":t.dynamics=p.PP;break;case"P":t.dynamics=p.P;break;case"MP":t.dynamics=p.MP;break;case"MF":t.dynamics=p.MF;break;case"F":t.dynamics=p.F;break;case"FF":t.dynamics=p.FF;break;case"FFF":t.dynamics=p.FFF}break;case"GraceNotes":switch(s.innerText){case"OnBeat":t.graceType=g.OnBeat;break;case"BeforeBeat":t.graceType=g.BeforeBeat}break;case"Legato":"true"===s.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":let e=new be(0,0);e.value=this.toBendValue(parseFloat(s.getAttribute("originValue"))),e.offset=this.toBendOffset(parseFloat(s.getAttribute("originOffset"))),t.addWhammyBarPoint(e);let a=new be(0,0);a.value=this.toBendValue(parseFloat(s.getAttribute("middleValue"))),a.offset=this.toBendOffset(parseFloat(s.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);let r=new be(0,0);r.value=this.toBendValue(parseFloat(s.getAttribute("middleValue"))),r.offset=this.toBendOffset(parseFloat(s.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);let o=new be(0,0);o.value=this.toBendValue(parseFloat(s.getAttribute("destinationValue"))),o.offset=this.toBendOffset(parseFloat(s.getAttribute("destinationOffset"))),t.addWhammyBarPoint(o);break;case"Ottavia":switch(s.innerText){case"8va":t.ottava=n._8va;break;case"8vb":t.ottava=n._8vb;break;case"15ma":t.ottava=n._15ma;break;case"15mb":t.ottava=n._15mb}break;case"Lyrics":t.lyrics=this.parseBeatLyrics(s),this._skipApplyLyrics=!0}this._beatById.set(i,t)}parseBeatLyrics(e){const t=[];for(let i of e.childNodes)if(i.nodeType===G.Element&&"Line"===i.localName)t.push(i.innerText);return t}parseBeatXProperties(e,t){for(let i of e.childNodes)if(i.nodeType===G.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}}}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===G.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 be(0,0)),s.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":s||(s=new be(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 be(be.MaxPosition,0)),o.value=this.toBendValue(parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new be(0,0)),o.offset=this.toBendOffset(parseFloat(h.findChildElement("Float").innerText))}}i&&(s||(s=new be(0,0)),o||(o=new be(be.MaxPosition,0)),t.addWhammyBarPoint(s),r&&a&&t.addWhammyBarPoint(new be(r,a)),n&&a&&t.addWhammyBarPoint(new be(n,a)),r||n||!a||t.addWhammyBarPoint(new be(be.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"Note"===t.localName)this.parseNote(t)}parseNote(e){let t=new Pe,i=e.getAttribute("id");for(let a of e.childNodes)if(a.nodeType===G.Element)switch(a.localName){case"Properties":this.parseNoteProperties(a,t,i);break;case"AntiAccent":"normal"===a.innerText.toLowerCase()&&(t.isGhost=!0);break;case"LetRing":t.isLetRing=!0;break;case"Trill":t.trillValue=parseInt(a.innerText),t.trillSpeed=u.Sixteenth;break;case"Accent":let e=parseInt(a.innerText);0!=(1&e)&&(t.isStaccato=!0),0!=(4&e)&&(t.accentuated=s.Heavy),0!=(8&e)&&(t.accentuated=s.Normal);break;case"Tie":"true"===a.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(a.innerText){case"Slight":t.vibrato=_.Slight;break;case"Wide":t.vibrato=_.Wide}break;case"LeftFingering":switch(t.isFingering=!0,a.innerText){case"P":t.leftHandFinger=f.Thumb;break;case"I":t.leftHandFinger=f.IndexFinger;break;case"M":t.leftHandFinger=f.MiddleFinger;break;case"A":t.leftHandFinger=f.AnnularFinger;break;case"C":t.leftHandFinger=f.LittleFinger}break;case"RightFingering":switch(t.isFingering=!0,a.innerText){case"P":t.rightHandFinger=f.Thumb;break;case"I":t.rightHandFinger=f.IndexFinger;break;case"M":t.rightHandFinger=f.MiddleFinger;break;case"A":t.rightHandFinger=f.AnnularFinger;break;case"C":t.rightHandFinger=f.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=parseInt(a.innerText)}this._noteById.set(i,t)}parseNoteProperties(e,t,i){let s=!1,a=null,r=null,n=null,o=null,h=null,l=-1,d=-1;for(let c of e.childNodes)if(c.nodeType===G.Element&&"Property"===c.localName){switch(c.getAttribute("name")){case"String":t.string=parseInt(c.findChildElement("String").innerText)+1;break;case"Fret":t.fret=parseInt(c.findChildElement("Fret").innerText);break;case"Element":l=parseInt(c.findChildElement("Element").innerText);break;case"Variation":d=parseInt(c.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(i,!0);break;case"HarmonicType":let e=c.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=m.None;break;case"Natural":t.harmonicType=m.Natural;break;case"Artificial":t.harmonicType=m.Artificial;break;case"Pinch":t.harmonicType=m.Pinch;break;case"Tap":t.harmonicType=m.Tap;break;case"Semi":t.harmonicType=m.Semi;break;case"Feedback":t.harmonicType=m.Feedback}break;case"HarmonicFret":let u=c.findChildElement("HFret");u&&(t.harmonicValue=parseFloat(u.innerText));break;case"Muted":c.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":c.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=parseInt(c.findChildElement("Number").innerText),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=parseInt(c.findChildElement("Step").innerText);break;case"ConcertPitch":this.parseConcertPitch(c,t);break;case"Bended":s=!0;break;case"BendOriginValue":a||(a=new be(0,0)),a.value=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new be(0,0)),a.offset=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleValue":r=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleOffset1":n=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendMiddleOffset2":o=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"BendDestinationValue":h||(h=new be(be.MaxPosition,0)),h.value=this.toBendValue(parseFloat(c.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new be(0,0)),h.offset=this.toBendOffset(parseFloat(c.findChildElement("Float").innerText));break;case"HopoOrigin":c.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":let p=parseInt(c.findChildElement("Flags").innerText);0!=(1&p)?t.slideOutType=S.Shift:0!=(2&p)?t.slideOutType=S.Legato:0!=(4&p)?t.slideOutType=S.OutDown:0!=(8&p)&&(t.slideOutType=S.OutUp),0!=(16&p)?t.slideInType=b.IntoFromBelow:0!=(32&p)&&(t.slideInType=b.IntoFromAbove),0!=(64&p)?t.slideOutType=S.PickSlideDown:0!=(128&p)&&(t.slideOutType=S.PickSlideUp)}}s&&(a||(a=new be(0,0)),h||(h=new be(be.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new be(n,r)),o&&r&&t.addBendPoint(new be(o,r)),n||o||!r||t.addBendPoint(new be(be.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==d&&(t.percussionArticulation=Ne.articulationFromElementVariation(l,d))}parseConcertPitch(e,t){const i=e.findChildElement("Pitch");if(i)for(let e of i.childNodes)if(e.nodeType===G.Element&&"Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=y.ForceDoubleSharp;break;case"#":t.accidentalMode=y.ForceSharp;break;case"b":t.accidentalMode=y.ForceFlat;break;case"bb":t.accidentalMode=y.ForceDoubleFlat}}toBendValue(e){return e*gt.BendPointValueFactor|0}toBendOffset(e){return e*gt.BendPointPositionFactor}parseRhythms(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){let t=new ut,i=e.getAttribute("id");t.id=i;for(let i of e.childNodes)if(i.nodeType===G.Element)switch(i.localName){case"NoteValue":switch(i.innerText){case"Long":t.value=u.QuadrupleWhole;break;case"DoubleWhole":t.value=u.DoubleWhole;break;case"Whole":t.value=u.Whole;break;case"Half":t.value=u.Half;break;case"Quarter":t.value=u.Quarter;break;case"Eighth":t.value=u.Eighth;break;case"16th":t.value=u.Sixteenth;break;case"32nd":t.value=u.ThirtySecond;break;case"64th":t.value=u.SixtyFourth;break;case"128th":t.value=u.OneHundredTwentyEighth;break;case"256th":t.value=u.TwoHundredFiftySixth}break;case"PrimaryTuplet":t.tupletNumerator=parseInt(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!==gt.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!==gt.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!==gt.InvalidId){let t=Me.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!==gt.InvalidId){const e=Fe.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 je;e.addVoice(t);let i=new Ie;i.isEmpty=!0,i.duration=u.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,r=t.length;s<r;s++){let r=t[s];r.type===a.Tempo&&(0===e&&(this.score.tempo=0|r.value,r.text&&(this.score.tempoLabel=r.text)),i.tempoAutomation=r)}}}}gt.InvalidId="-1",gt.BendPointPositionFactor=be.MaxPosition/100,gt.BendPointValueFactor=.04;class ft{constructor(){this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class mt{constructor(){this.isMultiRest=!1,this.tracks=[]}}class yt{apply(e){let t=0,i=0;for(let s of this.parts)for(let a of s.tracks){if(i<e.tracks.length){let s=e.tracks[i];if(t<s.staves.length){let e=s.staves[t];e.showTablature=a.showTablature,e.showStandardNotation=a.showStandardNotation}}i++,i>=e.tracks.length&&(t++,i=0)}}constructor(e){this.parts=[],this.zoomLevel=0,this.layout=0;let t=Ke.fromBuffer(e),i=$e.readInt32BE(t);for(let e=0;e<i;e++){let e=new mt;this.parts.push(e),e.isMultiRest=it.gpReadBool(t);let i=$e.readInt32BE(t);for(let s=0;s<i;s++){let i=t.readByte();0===i&&(i=1);let s=new ft;s.showStandardNotation=0!=(1&i),s.showTablature=0!=(2&i),s.showSlash=0!=(4&i),e.tracks.push(s)}}}static writeForScore(e){const t=Ke.withCapacity(128),i=[new mt];for(const t of e.tracks)for(const e of t.staves){const t=new ft;if(t.showStandardNotation=e.showStandardNotation,t.showTablature=e.showTablature,0===e.index)i[0].tracks.push(t);else{let e=new mt;e.tracks.push(t),i.push(e)}}$e.writeInt32BE(t,i.length);for(const e of i){t.writeByte(e.isMultiRest?1:0),$e.writeInt32BE(t,e.tracks.length);for(const i of e.tracks){let e=0;i.showStandardNotation&&(e|=1),i.showTablature&&(e|=2),i.showSlash&&(e|=4),t.writeByte(e)}}return t.toArray()}}class bt{}class St extends bt{constructor(e){super(),this.n=e}}class _t extends bt{constructor(e,t){super(),this.left=e,this.right=t}}class wt extends bt{constructor(e,t){super(),this.n=e,this.table=t}}class Bt{static make(e,t,i,s){let a=[],r=[];if(s>32)throw new ze("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 ze("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 Bt.treeCompress(new _t(Bt.treeMake(o,s,0,1),Bt.treeMake(o,s,1,1)))}static treeMake(e,t,i,s){if(s>t)throw new ze("Invalid huffman");let a=i<<5|s;return e.has(a)?new St(e.get(a)):(i<<=1,s+=1,new _t(Bt.treeMake(e,t,i,s),Bt.treeMake(e,t,1|i,s)))}static treeCompress(e){let t=Bt.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof _t)return new _t(Bt.treeCompress(e.left),Bt.treeCompress(e.right));throw new ze("assert")}let i=1<<t,s=[];for(let e=0;e<i;e++)s.push(new St(-1));return Bt.treeWalk(s,0,0,t,e),new wt(t,s)}static treeWalk(e,t,i,s,a){a instanceof _t&&s>0?(Bt.treeWalk(e,t,i+1,s-1,a.left),Bt.treeWalk(e,t|1<<i,i+1,s-1,a.right)):e[t]=Bt.treeCompress(a)}static treeDepth(e){if(e instanceof St)return 0;if(e instanceof wt)throw new ze("assert");if(e instanceof _t){let t=Bt.treeDepth(e.left),i=Bt.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"}(W||(W={}));class Tt{constructor(){this.buffer=new Uint8Array(Tt.BufferSize),this.pos=0}slide(){let e=new Uint8Array(Tt.BufferSize);this.pos-=Tt.Size,e.set(this.buffer.subarray(Tt.Size,Tt.Size+this.pos),0),this.buffer=e}addBytes(e,t,i){this.pos+i>Tt.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+i),this.pos),this.pos+=i}addByte(e){this.pos===Tt.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}Tt.Size=32768,Tt.BufferSize=65536;class kt{static buildFixedHuffman(){let e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return Bt.make(e,0,288,10)}constructor(e){this._nbits=0,this._bits=0,this._state=W.Block,this._isFinal=!1,this._huffman=kt._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new Tt,this._input=e;for(let e=0;e<19;e++)this._lengths.push(-1)}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 W.Head:let e=this._input.readByte();if(8!==(15&e))throw new ze("Invalid data");let t=this._input.readByte(),i=0!=(32&t);if(((e<<8)+t)%31!=0)throw new ze("Invalid data");if(i)throw new ze("Unsupported dictionary");return this._state=W.Block,!0;case W.Crc:return this._state=W.Done,!0;case W.Done:return!1;case W.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:if(this._len=$e.readUInt16LE(this._input),$e.readUInt16LE(this._input)!==65535-this._len)throw new ze("Invalid data");this._state=W.Flat;let e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=kt._fixedHuffman,this._huffdist=null,this._state=W.CData,!0;case 2:let t=this.getBits(5)+257,i=this.getBits(5)+1,s=this.getBits(4)+4;for(let e=0;e<s;e++)this._lengths[kt.CodeLengthsPos[e]]=this.getBits(3);for(let e=s;e<19;e++)this._lengths[kt.CodeLengthsPos[e]]=0;this._huffman=Bt.make(this._lengths,0,19,8);let a=[];for(let e=0;e<t+i;e++)a.push(0);return this.inflateLengths(a,t+i),this._huffdist=Bt.make(a,t,i,16),this._huffman=Bt.make(a,0,t,16),this._state=W.CData,!0;default:throw new ze("Invalid data")}case W.Flat:{let e=this._len<this._needed?this._len:this._needed,t=$e.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?W.Crc:W.Block),this._needed>0}case W.DistOne:{let e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=W.CData),this._needed>0}case W.Dist:for(;this._len>0&&this._needed>0;){let e=this._len<this._dist?this._len:this._dist,t=this._needed<e?this._needed:e;this.addDist(this._dist,t),this._len-=t}return 0===this._len&&(this._state=W.CData),this._needed>0;case W.CData:let s=this.applyHuffman(this._huffman);if(s<256)return this.addByte(s),this._needed>0;if(256===s)return this._state=this._isFinal?W.Crc:W.Block,!0;{s=s-257&255;let e=kt.LenExtraBitsTbl[s];if(-1===e)throw new ze("Invalid data");this._len=kt.LenBaseValTbl[s]+this.getBits(e);let t=this._huffdist,i=t?this.applyHuffman(t):this.getRevBits(5);if(e=kt.DistExtraBitsTbl[i],-1===e)throw new ze("Invalid data");if(this._dist=kt.DistBaseValTbl[i]+this.getBits(e),this._dist>this._window.available())throw new ze("Invalid data");return this._state=1===this._dist?W.DistOne:W.Dist,!0}}return!1}addDistOne(e){let t=this._window.getLastChar();for(let 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==(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 ze("Invalid data");for(;i<r;)e[i]=s,i++;break;case 17:if(i+=3+this.getBits(3),i>t)throw new ze("Invalid data");break;case 18:if(i+=11+this.getBits(7),i>t)throw new ze("Invalid data");break;default:throw new ze("Invalid data")}}}applyHuffman(e){if(e instanceof St)return e.n;if(e instanceof _t)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof wt)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new ze("Invalid data")}}kt.LenExtraBitsTbl=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,-1,-1],kt.LenBaseValTbl=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],kt.DistExtraBitsTbl=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,-1,-1],kt.DistBaseValTbl=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],kt.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],kt._fixedHuffman=kt.buildFixedHuffman();class vt{constructor(e,t){this.fullName=e;let i=e.lastIndexOf("/");this.fileName=-1===i||i===e.length-1?this.fullName:e.substr(i+1),this.data=t}}vt.OptionalDataDescriptorSignature=134695760,vt.CompressionMethodDeflate=8,vt.LocalFileHeaderSignature=67324752,vt.CentralFileHeaderSignature=33639248,vt.EndOfCentralDirSignature=101010256;class Nt{constructor(e){this._readable=e}read(){let e=[];for(;;){let t=this.readEntry();if(!t)break;e.push(t)}return e}readEntry(){let e=this._readable;if($e.readInt32LE(e)!==vt.LocalFileHeaderSignature)return null;$e.readUInt16LE(e);let t=$e.readUInt16LE(e),i=$e.readUInt16LE(e),s=0!==i;if(s&&i!==vt.CompressionMethodDeflate)return null;$e.readInt16LE(this._readable),$e.readInt16LE(this._readable),$e.readInt32LE(e),$e.readInt32LE(e);let a,r=$e.readInt32LE(e),n=$e.readInt16LE(e),o=$e.readInt16LE(e),h=$e.toString($e.readByteArray(e,n),"utf-8");if(e.skip(o),s){let e=Ke.empty(),t=new kt(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=$e.readByteArray(this._readable,r);if(0!=(8&t)){$e.readInt32LE(this._readable)===vt.OptionalDataDescriptorSignature&&$e.readInt32LE(this._readable),$e.readInt32LE(this._readable),$e.readInt32LE(this._readable)}return new vt(h,a)}}class xt extends ue{get name(){return"Guitar Pro 7"}constructor(){super()}readScore(){Be.debug(this.name,"Loading ZIP entries");let e,t=new Nt(this.data);try{e=t.read()}catch(e){throw new ge("No Zip archive",e)}Be.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=$e.toString(t.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=t.data;break;case"PartConfiguration":a=t.data}if(!i)throw new ge("No score.gpif found in zip archive");Be.debug(this.name,"Start Parsing score.gpif");let r=new gt;r.parseXml(i,this.settings),Be.debug(this.name,"score.gpif parsed");let n=r.score;if(s){Be.debug(this.name,"Start Parsing BinaryStylesheet"),new rt(s).apply(n),Be.debug(this.name,"BinaryStylesheet parsed")}if(a){Be.debug(this.name,"Start Parsing Part Configuration"),new yt(a).apply(n),Be.debug(this.name,"Part Configuration parsed")}return n}}class Pt extends pe{constructor(){super(i.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,Pt.prototype)}}class Et{constructor(e){this._currentByte=0,this._position=Et.ByteSize,this._source=e}readByte(){return this.readBits(8)}readBytes(e){const t=new Uint8Array(e);for(let 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 Pt;this._position=0}const e=this._currentByte>>Et.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 Pt))throw e}return e.toArray()}}Et.ByteSize=8;class Ct{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class Ft{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){let t=new Et(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){let 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 Pt))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 ge("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 Ct;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]}}Ft.HeaderBcFs="BCFS",Ft.HeaderBcFz="BCFZ",Ft.ScoreGpif="score.gpif",Ft.BinaryStylesheet="BinaryStylesheet",Ft.PartConfiguration="PartConfiguration";class Lt extends ue{get name(){return"Guitar Pro 6"}constructor(){super()}readScore(){Be.debug(this.name,"Loading GPX filesystem");let e=new Ft;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration"),e.load(this.data),Be.debug(this.name,"GPX filesystem loaded");let t=null,i=null,s=null;for(let a of e.files)switch(a.fileName){case"score.gpif":t=$e.toString(a.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=a.data;break;case"PartConfiguration":s=a.data}if(!t)throw new ge("No score.gpif found in GPX");Be.debug(this.name,"Start Parsing score.gpif");let a=new gt;a.parseXml(t,this.settings),Be.debug(this.name,"score.gpif parsed");let r=a.score;if(i){Be.debug(this.name,"Start Parsing BinaryStylesheet"),new rt(i).apply(r),Be.debug(this.name,"BinaryStylesheet parsed")}if(s){Be.debug(this.name,"Start Parsing Part Configuration"),new yt(s).apply(r),Be.debug(this.name,"Part Configuration parsed")}return r}}class Mt extends ue{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=$e.toString(this.data.readAll(),this.settings.importer.encoding),t=new ct;try{t.parse(e)}catch(e){throw new ge("Unsupported format")}return this._score=new He,this._score.tempo=120,this.parseDom(t),this.settings.importer.mergePartGroupsInMusicXml&&this.mergePartGroups(),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}mergePartGroups(){let e=!1;for(const t of this._partGroups.values())t.length>1&&(this.mergeGroup(t),e=!0);if(e)for(let e=0;e<this._score.tracks.length;e++)this._score.tracks[e].index=e}mergeGroup(e){let t=e[0];for(let 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 ge("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":break;default:throw new ge("Unsupported format")}}parsePartwise(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"work":this.parseWork(t);break;case"movement-title":this._score.title=t.innerText;break;case"identification":this.parseIdentification(t);break;case"part-list":this.parsePartList(t);break;case"part":this.parsePart(t)}}parseWork(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"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===G.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 me;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)}if(r){let i=!1;for(let s of e.childNodes)if(s.nodeType===G.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);break;case"sound":break;case"barline":this.parseBarline(s,r)}}return!0}ensureVoices(e){for(;e.voices.length<this._maxVoices;){let t=new je;e.addVoice(t);let i=new Ie;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 d=this.getOrCreateVoice(n,s);return i&&d.beats.length>0||1===d.beats.length&&d.isEmpty?o=d.beats[d.beats.length-1]:(o=new Ie,o.isEmpty=!1,d.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)*u.Quarter/this._divisionsPerQuarterNote,a=[u.SixtyFourth,u.ThirtySecond,u.Sixteenth,u.Eighth,u.Quarter,u.Half,u.Whole];for(let e of a)if(s>=e){i.duration=e,s-=e;break}i.isEmpty=!1}parseStaffDetails(e,t){for(let i of e.childNodes)if(i.nodeType===G.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===G.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=ke.getTuningForText(s+a)+r;for(let e of t.staves)e.tuning[e.tuning.length-i]=n}parseHarmony(e,t){let i=null,s="";for(let t of e.childNodes)if(t.nodeType===G.Element&&"root"===t.localName)for(let e of t.childNodes)if(e.nodeType===G.Element)switch(e.localName){case"root-step":i=e.innerText;break;case"root-alter":switch(parseInt(t.innerText)){case-2:s=" bb";break;case-1:s=" b";break;case 0:s="";break;case 1:s=" #";break;case 2:s=" ##"}}let a=new Re;a.name=i+s,this._currentChord=ke.newGuid();for(let e of t.staves)e.addChord(this._currentChord,a)}parseBarline(e,t){for(let i of e.childNodes)if(i.nodeType===G.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 Pe;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===G.Element)switch(t.localName){case"grace":s.graceType=g.BeforeBeat,s.duration=u.ThirtySecond;break;case"duration":if(s.isRest&&!r){switch(parseInt(t.innerText)){case 1:s.duration=u.Whole;break;case 2:s.duration=u.Half;break;case 4:default:s.duration=u.Quarter;break;case 8:s.duration=u.Eighth;break;case 16:s.duration=u.Sixteenth;break;case 32:s.duration=u.ThirtySecond;break;case 64:s.duration=u.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!==g.None&&s.duration<u.Sixteenth&&(s.duration=u.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=u.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 u.SixtyFourth;case"32nd":return u.ThirtySecond;case"16th":return u.Sixteenth;case"eighth":return u.Eighth;case"quarter":return u.Quarter;case"half":return u.Half;case"long":case"breve":case"whole":return u.Whole}return u.Quarter}parseLyric(e,t){for(let i of e.childNodes)if(i.nodeType===G.Element&&"text"===i.localName)t.text?t.text+=" "+i.innerText:t.text=i.innerText}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=y.ForceSharp;break;case"natural":t.accidentalMode=y.ForceNatural;break;case"flat":t.accidentalMode=y.ForceFlat}}parseTied(e,t){"start"===e.getAttribute("type")?this._tieStartIds.has(t.id)||(this._tieStartIds.set(t.id,!0),this._tieStarts.push(t)):"stop"===e.getAttribute("type")&&this._tieStarts.length>0&&!t.isTieDestination&&(t.isTieDestination=!0,t.tieOrigin=this._tieStarts[0],this._tieStarts.splice(0,1),this._tieStartIds.delete(t.id))}parseNotations(e,t,i){for(let s of e.childNodes)if(s.nodeType===G.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=S.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===G.Element&&"tremolo"===i.localName){switch(parseInt(i.innerText)){case 1:t.beat.tremoloSpeed=u.Eighth;break;case 2:t.beat.tremoloSpeed=u.Sixteenth;break;case 3:t.beat.tremoloSpeed=u.ThirtySecond}}}parseTechnical(e,t){for(let i of e.childNodes)if(i.nodeType===G.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=s.Normal;break;case"strong-accent":t.accentuated=s.Heavy;break;case"staccato":case"detached-legato":t.isStaccato=!0}}parseDynamics(e,t){for(let i of e.childNodes)if(i.nodeType===G.Element)switch(i.localName){case"p":t.dynamics=p.P;break;case"pp":t.dynamics=p.PP;break;case"ppp":t.dynamics=p.PPP;break;case"f":t.dynamics=p.F;break;case"ff":t.dynamics=p.FF;break;case"fff":t.dynamics=p.FFF;break;case"mp":t.dynamics=p.MP;break;case"mf":t.dynamics=p.MF}}parseTimeModification(e,t){for(let i of e.childNodes)if(i.nodeType===G.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===G.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+ke.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===G.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+ke.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 je);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===G.Element)switch(i.localName){case"sound":let e=i.getAttribute("tempo");if(e){let i=new fe;i.isLinear=!0,i.type=a.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=u.Quarter,s=120;for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"beat-unit":i=this.getDuration(t.innerText);break;case"per-minute":s=parseInt(t.innerText)}let r=new fe;r.type=a.Tempo,r.value=s*(i/4|0),t.tempoAutomation=r,0===t.index&&(t.score.tempo=r.value)}parseAttributes(e,t,i,s){let a=0,r=!1;for(let n of e.childNodes)if(n.nodeType===G.Element)switch(n.localName){case"divisions":this._divisionsPerQuarterNote=parseInt(n.innerText);break;case"key":this.parseKey(n,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===G.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===G.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=n._15mb;break;case-1:t.clefOttava=n._8vb;break;case 1:t.clefOttava=n._8va;break;case 2:t.clefOttava=n._15mb}}switch(i){case"g":default:t.clef=r.G2;break;case"f":t.clef=r.F4;break;case"c":t.clef=3===s?r.C3:r.C4;break;case"percussion":t.clef=r.Neutral,t.staff.isPercussion=!0;break;case"tab":t.clef=r.G2,t.staff.showTablature=!0}}parseTime(e,t){"common"===e.getAttribute("symbol")&&(t.timeSignatureCommon=!0);let i=!1,s=!1;for(let a of e.childNodes)if(a.nodeType===G.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===G.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:L.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 Oe;if(this._score.masterBars.length>0){let t=this._score.masterBars[this._score.masterBars.length-1];e.timeSignatureDenominator=t.timeSignatureDenominator,e.timeSignatureNumerator=t.timeSignatureNumerator,e.keySignature=t.keySignature,e.keySignatureType=t.keySignatureType}this._score.addMasterBar(e)}return this._score.masterBars[e]}parseIdentification(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"creator":"composer"===t.getAttribute("type")&&(this._score.music=t.innerText);break;case"rights":this._score.copyright&&(this._score.copyright+="\n"),this._score.copyright+=t.innerText}}parsePartList(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"part-group":this.parsePartGroup(t);break;case"score-part":this.parseScorePart(t)}}parsePartGroup(e){switch(e.getAttribute("type")){case"start":this._currentPartGroup=e.getAttribute("number"),this._partGroups.set(this._currentPartGroup,[]);break;case"stop":this._currentPartGroup=null}}parseScorePart(e){let t=e.getAttribute("id"),i=new Je;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===G.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===G.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.PerNotePitchBend=96]="PerNotePitchBend",e[e.NoteOff=128]="NoteOff",e[e.NoteOn=144]="NoteOn",e[e.NoteAftertouch=160]="NoteAftertouch",e[e.Controller=176]="Controller",e[e.ProgramChange=192]="ProgramChange",e[e.ChannelAftertouch=208]="ChannelAftertouch",e[e.PitchBend=224]="PitchBend",e[e.SystemExclusive=240]="SystemExclusive",e[e.SystemExclusive2=247]="SystemExclusive2",e[e.Meta=255]="Meta"}(z||(z={}));class Dt{get channel(){return 15&this.message}get command(){return 240&this.message}get data1(){return(65280&this.message)>>8}set data1(e){this.message&=-65281,this.message|=e<<8}get data2(){return(16711680&this.message)>>16}set data2(e){this.message&=-16711681,this.message|=e<<16}constructor(e,t,i,s,a){this.track=e,this.tick=t,this.message=i|s<<8|a<<16}writeTo(e){let t=new Uint8Array([this.message>>24&255,this.message>>16&255,this.message>>8&255,255&this.message]);e.write(t,0,t.length)}}!function(e){e[e.SequenceNumber=0]="SequenceNumber",e[e.TextEvent=1]="TextEvent",e[e.CopyrightNotice=2]="CopyrightNotice",e[e.SequenceOrTrackName=3]="SequenceOrTrackName",e[e.InstrumentName=4]="InstrumentName",e[e.LyricText=5]="LyricText",e[e.MarkerText=6]="MarkerText",e[e.CuePoint=7]="CuePoint",e[e.PatchName=8]="PatchName",e[e.PortName=9]="PortName",e[e.MidiChannel=32]="MidiChannel",e[e.MidiPort=33]="MidiPort",e[e.EndOfTrack=47]="EndOfTrack",e[e.Tempo=81]="Tempo",e[e.SmpteOffset=84]="SmpteOffset",e[e.TimeSignature=88]="TimeSignature",e[e.KeySignature=89]="KeySignature",e[e.SequencerSpecific=127]="SequencerSpecific"}(U||(U={}));class It extends Dt{get channel(){return-1}get command(){return 255&this.message}get metaStatus(){return this.data1}constructor(e,t,i,s,a){super(e,t,i,s,a)}}!function(e){e[e.SystemExclusive=240]="SystemExclusive",e[e.MtcQuarterFrame=241]="MtcQuarterFrame",e[e.SongPosition=242]="SongPosition",e[e.SongSelect=243]="SongSelect",e[e.TuneRequest=246]="TuneRequest",e[e.SystemExclusive2=247]="SystemExclusive2"}(X||(X={}));class Rt extends Dt{get channel(){return-1}get command(){return 255&this.message}constructor(e,t,i,s,a){super(e,t,i,s,a)}}!function(e){e[e.MetronomeTick=0]="MetronomeTick",e[e.Rest=1]="Rest"}(Y||(Y={}));class At extends Rt{get isMetronome(){return this.manufacturerId==At.AlphaTabManufacturerId&&this.data[0]==Y.MetronomeTick}get metronomeNumerator(){return this.isMetronome?this.data[1]:-1}get metronomeDurationInTicks(){return this.isMetronome?$e.decodeUInt32LE(this.data,2):-1}get metronomeDurationInMilliseconds(){return this.isMetronome?$e.decodeUInt32LE(this.data,6):-1}get isRest(){return this.manufacturerId==At.AlphaTabManufacturerId&&this.data[0]==Y.Rest}get manufacturerId(){return this.message>>8}constructor(e,t,i,s,a){super(e,t,i,255&s,s>>8&255),this.data=a}writeTo(e){e.writeByte(240);let t=this.data.length+2;e.writeByte(this.manufacturerId);let i=new Uint8Array([t>>24&255,t>>16&255,t>>8&255,255&t]);e.write(i,0,i.length),e.writeByte(247)}static encodeMetronome(e,t,i){const s=Ke.withCapacity(10);return s.writeByte(Y.MetronomeTick),s.writeByte(e),$e.writeInt32LE(s,t),$e.writeInt32LE(s,i),s.toArray()}}At.AlphaTabManufacturerId=125;class Ot{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event instanceof At&&this.event.isMetronome}static newMetronomeEvent(e,t,i,s,a){const r=new At(0,t,z.SystemExclusive2,At.AlphaTabManufacturerId,At.encodeMetronome(i,s,a));return new Ot(e,r)}}class Gt{}Gt.DefaultChannelCount=17,Gt.MetronomeChannel=Gt.DefaultChannelCount-1,Gt.AudioChannels=2,Gt.MinVolume=0,Gt.MinProgram=0,Gt.MaxProgram=127,Gt.MinPlaybackSpeed=.125,Gt.MaxPlaybackSpeed=8,Gt.MaxPitchWheel=16384,Gt.MaxPitchWheel20=4294967296,Gt.DefaultPitchWheel=Gt.MaxPitchWheel/2,Gt.MicroBufferCount=32,Gt.MicroBufferSize=64;class Vt{constructor(e,t,i){this.bpm=e,this.ticks=t,this.time=i}}class Ht{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=ye.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class Wt{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 Ht,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(Gt.MicroBufferSize);this._mainState.currentTime=i;let s=Date.now()-t;Be.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 Ht;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,d=0;for(let c of e.events){let u=new Ot(t.synthData.length,c);t.synthData.push(u);let p=c.tick-d;if(s+=p,a+=p*(6e4/(i*e.division)),u.time=a,d=c.tick,n>0)for(;h<s;){let e=Ot.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(c.command===z.Meta&&c.data1===U.Tempo){i=6e7/c.value,t.tempoChanges.push(new Vt(i,s,a)),o=n*(6e4/(i*e.division))}else if(c.command===z.Meta&&c.data1===U.TimeSignature){let s=c,a=Math.pow(2,s.data[1]);r=s.data[0],n=t.division*(4/a)|0,o=n*(6e4/(i*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=s.data[0],t.firstTimeSignatureDenominator=a)}else if(c.command===z.ProgramChange){let e=c.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=Gt.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 Ht;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 Vt(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=Ot.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"}(q||(q={}));class zt{constructor(e,t){this.state=e,this.stopped=t}}class Ut{constructor(e,t,i,s,a){this.currentTime=e,this.endTime=t,this.currentTick=i,this.endTick=s,this.isSeek=a}}class Xt{constructor(){this.id="",this.size=0}static load(e,t,i){if(e&&Xt.HeaderSize>e.size)return!1;if(i.position+Xt.HeaderSize>=i.length)return!1;if(t.id=$e.read8BitStringLength(i,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=$e.readUInt32LE(i),e&&Xt.HeaderSize+t.size>e.size)return!1;e&&(e.size-=Xt.HeaderSize+t.size);let s="RIFF"===t.id,a="LIST"===t.id;return(!s||!e)&&(!s&&!a||(t.id=$e.read8BitStringLength(i,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}Xt.HeaderSize=8;class Yt{constructor(){this.phdrs=[],this.pbags=[],this.pmods=[],this.pgens=[],this.insts=[],this.ibags=[],this.imods=[],this.igens=[],this.sHdrs=[],this.fontSamples=new Float32Array(0)}load(e){const t=new Xt,i=new Xt;if(!Xt.load(null,t,e)||"sfbk"!==t.id)throw new ze("Soundfont is not a valid Soundfont2 file");for(;Xt.load(t,i,e);){let t=new Xt;if("pdta"===i.id)for(;Xt.load(i,t,e);)switch(t.id){case"phdr":for(let i=0,s=t.size/Zt.SizeInFile|0;i<s;i++)this.phdrs.push(new Zt(e));break;case"pbag":for(let i=0,s=t.size/$t.SizeInFile|0;i<s;i++)this.pbags.push(new $t(e));break;case"pmod":for(let i=0,s=t.size/ei.SizeInFile|0;i<s;i++)this.pmods.push(new ei(e));break;case"pgen":for(let i=0,s=t.size/Kt.SizeInFile|0;i<s;i++)this.pgens.push(new Kt(e));break;case"inst":for(let i=0,s=t.size/Qt.SizeInFile|0;i<s;i++)this.insts.push(new Qt(e));break;case"ibag":for(let i=0,s=t.size/qt.SizeInFile|0;i<s;i++)this.ibags.push(new qt(e));break;case"imod":for(let i=0,s=t.size/Jt.SizeInFile|0;i<s;i++)this.imods.push(new Jt(e));break;case"igen":for(let i=0,s=t.size/jt.SizeInFile|0;i<s;i++)this.igens.push(new jt(e));break;case"shdr":for(let i=0,s=t.size/ti.SizeInFile|0;i<s;i++)this.sHdrs.push(new ti(e));break;default:e.position+=t.size}else if("sdta"===i.id)for(;Xt.load(i,t,e);)if("smpl"===t.id)this.fontSamples=Yt.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=Qe.int32ToInt16(r[2*t+1]<<8|r[2*t]);s[a+t]=e/32767}i-=e,a+=e}return s}}class qt{constructor(e){this.instGenNdx=$e.readUInt16LE(e),this.instModNdx=$e.readUInt16LE(e)}}qt.SizeInFile=4;class Jt{constructor(e){this.modSrcOper=$e.readUInt16LE(e),this.modDestOper=$e.readUInt16LE(e),this.modAmount=$e.readInt16LE(e),this.modAmtSrcOper=$e.readUInt16LE(e),this.modTransOper=$e.readUInt16LE(e)}}Jt.SizeInFile=10;class jt{constructor(e){this.genOper=$e.readUInt16LE(e),this.genAmount=new ii(e)}}jt.SizeInFile=4;class Qt{constructor(e){this.instName=$e.read8BitStringLength(e,20),this.instBagNdx=$e.readUInt16LE(e)}}Qt.SizeInFile=22;class $t{constructor(e){this.genNdx=$e.readUInt16LE(e),this.modNdx=$e.readUInt16LE(e)}}$t.SizeInFile=4;class Kt{constructor(e){this.genOper=$e.readUInt16LE(e),this.genAmount=new ii(e)}}Kt.SizeInFile=4,Kt.GenInstrument=41,Kt.GenKeyRange=43,Kt.GenVelRange=44,Kt.GenSampleId=53;class Zt{constructor(e){this.presetName=$e.read8BitStringLength(e,20),this.preset=$e.readUInt16LE(e),this.bank=$e.readUInt16LE(e),this.presetBagNdx=$e.readUInt16LE(e),this.library=$e.readUInt32LE(e),this.genre=$e.readUInt32LE(e),this.morphology=$e.readUInt32LE(e)}}Zt.SizeInFile=38;class ei{constructor(e){this.modSrcOper=$e.readUInt16LE(e),this.modDestOper=$e.readUInt16LE(e),this.modAmount=$e.readUInt16LE(e),this.modAmtSrcOper=$e.readUInt16LE(e),this.modTransOper=$e.readUInt16LE(e)}}ei.SizeInFile=10;class ti{constructor(e){this.sampleName=$e.read8BitStringLength(e,20),this.start=$e.readUInt32LE(e),this.end=$e.readUInt32LE(e),this.startLoop=$e.readUInt32LE(e),this.endLoop=$e.readUInt32LE(e),this.sampleRate=$e.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=$e.readSInt8(e),this.sampleLink=$e.readUInt16LE(e),this.sampleType=$e.readUInt16LE(e)}}ti.SizeInFile=46;class ii{get shortAmount(){return Qe.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}constructor(e){this.wordAmount=$e.readUInt16LE(e)}}class si{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 ai{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"}(J||(J={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(j||(j={}));class ri{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null,this.fontSamples=null}}class ni{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 oi{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:ni.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:ni.timecents2Secs(this.attack),this.release=this.release<-11950?0:ni.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:ni.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:ni.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?ni.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"}(Q||(Q={}));class hi{constructor(e){this.loopMode=J.None,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv=new oi,this.modEnv=new oi,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 oi(e.ampEnv),this.modEnv=new oi(e.modEnv),this.initialFilterQ=e.initialFilterQ,this.initialFilterFc=e.initialFilterFc,this.modEnvToPitch=e.modEnvToPitch,this.modEnvToFilterFc=e.modEnvToFilterFc,this.modLfoToFilterFc=e.modLfoToFilterFc,this.modLfoToVolume=e.modLfoToVolume,this.delayModLFO=e.delayModLFO,this.freqModLFO=e.freqModLFO,this.modLfoToPitch=e.modLfoToPitch,this.delayVibLFO=e.delayVibLFO,this.freqVibLFO=e.freqVibLFO,this.vibLfoToPitch=e.vibLfoToPitch)}clear(e){this.loopMode=J.None,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv.clear(),this.modEnv.clear(),this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,this.hiKey=127,this.hiVel=127,this.pitchKeyCenter=60,e||(this.pitchKeyTrack=100,this.pitchKeyCenter=-1,this.ampEnv.delay=-12e3,this.ampEnv.attack=-12e3,this.ampEnv.hold=-12e3,this.ampEnv.decay=-12e3,this.ampEnv.release=-12e3,this.modEnv.delay=-12e3,this.modEnv.attack=-12e3,this.modEnv.hold=-12e3,this.modEnv.decay=-12e3,this.modEnv.release=-12e3,this.initialFilterFc=13500,this.delayModLFO=-12e3,this.delayVibLFO=-12e3)}operator(e,t){switch(e){case Q.StartAddrsOffset:this.offset+=Qe.int16ToUint32(t.shortAmount);break;case Q.EndAddrsOffset:this.end+=Qe.int16ToUint32(t.shortAmount);break;case Q.StartloopAddrsOffset:this.loopStart+=Qe.int16ToUint32(t.shortAmount);break;case Q.EndloopAddrsOffset:this.loopEnd+=Qe.int16ToUint32(t.shortAmount);break;case Q.StartAddrsCoarseOffset:this.offset+=32768*Qe.int16ToUint32(t.shortAmount);break;case Q.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case Q.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case Q.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case Q.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case Q.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case Q.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case Q.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case Q.EndAddrsCoarseOffset:this.end+=32768*Qe.int16ToUint32(t.shortAmount);break;case Q.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case Q.Pan:this.pan=t.shortAmount/1e3;break;case Q.DelayModLFO:this.delayModLFO=t.shortAmount;break;case Q.FreqModLFO:this.freqModLFO=t.shortAmount;break;case Q.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case Q.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case Q.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case Q.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case Q.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case Q.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case Q.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case Q.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case Q.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case Q.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case Q.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case Q.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case Q.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case Q.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case Q.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case Q.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case Q.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case Q.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case Q.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case Q.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case Q.StartloopAddrsCoarseOffset:this.loopStart+=32768*Qe.int16ToUint32(t.shortAmount);break;case Q.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case Q.EndloopAddrsCoarseOffset:this.loopEnd+=32768*Qe.int16ToUint32(t.shortAmount);break;case Q.CoarseTune:this.transpose+=t.shortAmount;break;case Q.FineTune:this.tune+=t.shortAmount;break;case Q.SampleModes:this.loopMode=3==(3&t.wordAmount)?J.Sustain:1==(3&t.wordAmount)?J.Continuous:J.None;break;case Q.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case Q.ExclusiveClass:this.group=t.wordAmount;break;case Q.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"}($||($={}));class li{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=$.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case $.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=$.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=$.Delay;break;case $.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=$.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=$.Attack;break;case $.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=$.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=$.Hold;break;case $.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=$.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=$.Decay;break;case $.Decay:return this.segment=$.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case $.Sustain:if(this.segment=$.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?li.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=$.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,i,s,a){this.parameters=new oi(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:ni.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:ni.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|i,this.isAmpEnv=s,this.nextSegment($.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)}}li.FastReleaseTime=.01;class di{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,i){this.samplesUntil=e*i|0,this.delta=4*ni.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 ci{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 ui{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 li,this.modEnv=new li,this.lowPass=new ci,this.modLfo=new di,this.vibLfo=new di,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/(ni.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment($.Sustain,e),this.modEnv.nextSegment($.Sustain,e),this.region.loopMode===J.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment($.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment($.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===j.StereoUnweaved?s:-1,l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,d=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),c=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,f=r.end,m=g+1,y=this.sourceSamplePosition,b=new ci(this.lowPass),S=0!==r.modLfoToFilterFc||0!==r.modEnvToFilterFc,_=0,w=0,B=0,T=0,k=0!==r.modLfoToPitch||0!==r.modEnvToPitch||0!==r.vibLfoToPitch,v=0,N=0,x=0,P=0,E=0!==r.modLfoToVolume,C=0,F=0;for(S?(_=e.outSampleRate,w=r.initialFilterFc,B=r.modLfoToFilterFc,T=r.modEnvToFilterFc):(_=0,w=0,B=0,T=0),k?(v=0,N=r.modLfoToPitch,x=r.vibLfoToPitch,P=r.modEnvToPitch):(v=ni.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,N=0,x=0,P=0),E?F=.1*r.modLfoToVolume:(C=ni.decibelsToGain(this.noteGainDb),F=0);s>0;){let r,L,M=0,D=s>ui.RenderEffectSampleBlock?ui.RenderEffectSampleBlock:s;if(s-=D,S){let e=w+this.modLfo.level*B+this.modEnv.level*T;b.active=e<=13500,b.active&&b.setup(ni.cents2Hertz(e)/_)}switch(k&&(v=ni.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*N+this.vibLfo.level*x+this.modEnv.level*P))*this.pitchOutputFactor),E&&(C=ni.decibelsToGain(this.noteGainDb+this.modLfo.level*F)),r=C*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(D,e.outSampleRate),l&&this.modEnv.process(D,e.outSampleRate),d&&this.modLfo.process(D),c&&this.vibLfo.process(D),e.outputMode){case j.StereoInterleaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;D-- >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 j.StereoUnweaved:for(L=r*this.panFactorLeft,M=r*this.panFactorRight;D-- >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 j.Mono:for(;D-- >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===$.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}ui.RenderEffectSampleBlock=Gt.MicroBufferSize;class pi{constructor(){this._items=[],this._position=0,this.isEmpty=!0}clear(){this._items=[],this._position=0,this.isEmpty=!0}enqueue(e){this.isEmpty=!1,this._items.push(e)}peek(){return this._items[this._position]}dequeue(){const e=this._items[this._position];return this._position++,this._position>=this._items.length/2&&(this._items=this._items.slice(this._position),this._position=0),this.isEmpty=0==this._items.length,e}toArray(){const e=this._items.slice(this._position);return e.reverse(),e}}class gi{constructor(e){this._midiEventQueue=new pi,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=j.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._isAnySolo=!1}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(Gt.MetronomeChannel,33),this.channelNoteOn(Gt.MetronomeChannel,33,95/127)):e.event&&this.processMidiMessage(e.event),a.push(e)}for(const a of this._voices)if(-1!==a.playingPreset){const r=a.playingChannel,n=this._mutedChannels.has(r)||s&&r!=Gt.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,i,n):a.kill()}return a}processMidiMessage(e){const t=e.command,i=e.channel,s=e.data1,a=e.data2;switch(t){case z.NoteOff:this.channelNoteOff(i,s);break;case z.NoteOn:this.channelNoteOn(i,s,a/127);break;case z.NoteAftertouch:break;case z.Controller:this.channelMidiControl(i,s,a);break;case z.ProgramChange:this.channelSetPresetNumber(i,s,9===i);break;case z.ChannelAftertouch:break;case z.PitchBend:this.channelSetPitchWheel(i,s|a<<7);break;case z.PerNotePitchBend:const t=e;let r=t.pitch;r=r*Gt.MaxPitchWheel/Gt.MaxPitchWheel20,this.channelSetPerNotePitchWheel(i,t.noteKey,r);break;case z.Meta:switch(e.data1){case U.Tempo:this.currentTempo=6e7/e.value;break;case U.TimeSignature:this.timeSignatureNumerator=e.data[0],this.timeSignatureDenominator=Math.pow(2,e.data[1])}}}get metronomeVolume(){return this.channelGetMixVolume(Gt.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Gt.MetronomeChannel,e),e>0&&(this.channelSetVolume(Gt.MetronomeChannel,1),this.channelSetPresetNumber(Gt.MetronomeChannel,0,!0))}get masterVolume(){return ni.decibelsToGain(this.globalGainDb)}set masterVolume(e){var t=ni.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<$.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);if(this._channels)for(const e of this._channels.channelList)e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.perNotePitchWheel.clear(),e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0}get presetCount(){var e,t;return null!==(t=null===(e=this.presets)||void 0===e?void 0:e.length)&&void 0!==t?t:0}reset(){for(let e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<$.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 ui;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-ni.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!==J.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(ni.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>=$.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>=$.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<$.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 ai);for(let t=this._channels.channelList.length;t<=e;t++){let e=new si;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._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,i))}channelNoteOff(e,t){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>=$.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>=$.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<$.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<$.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=Qe.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=Qe.int32ToUint16(t)}channelSetBankPreset(e,t,i){const s=this.channelInit(e),a=this.getPresetIndex(t,i);return-1!==a&&(s.presetIndex=Qe.int32ToUint16(a),s.bank=Qe.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=ni.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=Qe.int32ToUint16(t),this.channelApplyPitch(e,i))}channelSetPerNotePitchWheel(e,t,i){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 5:case 96:case 97:case 64:case 65:case 66:case 122:case 124:case 125:case 126:case 127:return;case 38:return s.midiData=Qe.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 7:return s.midiVolume=Qe.int32ToUint16(127&s.midiVolume|i<<7),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 39:return s.midiVolume=Qe.int32ToUint16(16256&s.midiVolume|i),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 11:return s.midiExpression=Qe.int32ToUint16(127&s.midiExpression|i<<7),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 43:return s.midiExpression=Qe.int32ToUint16(16256&s.midiExpression|i),void this.channelSetVolume(e,Math.pow(s.midiVolume/16383*(s.midiExpression/16383),3));case 10:return s.midiPan=Qe.int32ToUint16(127&s.midiPan|i<<7),void this.channelSetPan(e,s.midiPan/16383);case 42:return s.midiPan=Qe.int32ToUint16(16256&s.midiPan|i),void this.channelSetPan(e,s.midiPan/16383);case 6:return s.midiData=Qe.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&&6===t&&this.channelSetTuning(e,i-64+(s.tuning-(0|s.tuning))));case 0:return void(s.bank=Qe.int32ToUint16(32768|i));case 32:return void(s.bank=Qe.int32ToUint16((0!=(32768&s.bank)?(127&s.bank)<<7:0)|i));case 101:return void(s.midiRpn=Qe.int32ToUint16(127&(65535===s.midiRpn?0:s.midiRpn)|i<<7));case 100:return void(s.midiRpn=Qe.int32ToUint16(16256&(65535===s.midiRpn?0:s.midiRpn)|i));case 98:case 99:return void(s.midiRpn=65535);case 120:return void this.channelSoundsOffAll(e);case 123:return void this.channelNoteOffAll(e);case 121: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?ni.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 ri;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!==Kt.GenKeyRange)if(i.genOper!==Kt.GenVelRange){if(i.genOper===Kt.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,d=127;for(let c=e.ibags[o].instGenNdx;c<e.ibags[o+1].instGenNdx;c++){let o=e.igens[c];o.genOper!==Kt.GenKeyRange?o.genOper!==Kt.GenVelRange?53===o.genOper&&h>=t&&i<=s&&d>=a&&l<=r&&n++:(l=o.genAmount.lowByteAmount,d=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 hi;o.clear(!0);for(let i=s.presetBagNdx;i<e.phdrs[t+1].presetBagNdx;i++){const t=e.pbags[i],n=new hi(o);let h=!1;for(let s=t.genNdx;s<e.pbags[i+1].genNdx;s++){const t=e.pgens[s];if(t.genOper===Kt.GenInstrument){let i=t.genAmount.wordAmount;if(i>=e.insts.length)continue;let s=new hi;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 hi(s),l=!1;for(let s=i.instGenNdx;s<e.ibags[t+1].instGenNdx;s++){let t=e.igens[s];if(t.genOper===Kt.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:ni.timecents2Secs(h.delayModLFO),h.delayVibLFO=h.delayVibLFO<-11950?0:ni.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 hi(h),a++,l=!0}else h.operator(t.genOper,t.genAmount)}i!==e.ibags[o.instBagNdx]||l||(s=new hi(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 fi{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 mi{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 yi{constructor(e){this.events=e}}class bi{constructor(e){this.playbackRange=e}}class Si{get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return Be.logLevel}set logLevel(e){Be.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Gt.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Gt.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Gt.MinVolume),this._countInVolume=e}get midiEventsPlayedFilter(){return Array.from(this._midiEventsPlayedFilter)}set midiEventsPlayedFilter(e){this._midiEventsPlayedFilter=new Set(e)}get playbackSpeed(){return this._sequencer.playbackSpeed}set playbackSpeed(e){e=ni.clamp(e,Gt.MinPlaybackSpeed,Gt.MaxPlaybackSpeed);let t=this._sequencer.playbackSpeed;this._sequencer.playbackSpeed=e,this.timePosition=this.timePosition*(t/e)}get tickPosition(){return this._tickPosition}set tickPosition(e){this.timePosition=this._sequencer.mainTickPositionToTimePosition(e)}get timePosition(){return this._timePosition}set timePosition(e){Be.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 bi(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){Be.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 pi,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this.isReady=!1,this.state=q.Paused,this.ready=new fi,this.readyForPlayback=new fi,this.finished=new fi,this.soundFontLoaded=new fi,this.soundFontLoadFailed=new mi,this.midiLoaded=new mi,this.midiLoadFailed=new mi,this.stateChanged=new mi,this.positionChanged=new mi,this.midiEventsPlayed=new mi,this.playbackRangeChanged=new mi,Be.debug("AlphaSynth","Initializing player"),this.state=q.Paused,Be.debug("AlphaSynth","Creating output"),this.output=e,Be.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new gi(this.output.sampleRate),this._sequencer=new Wt(this._synthesizer),Be.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this._sequencer.isFinished){let e=new Float32Array(0);this.output.addSamples(e)}else{let e=new Float32Array(Gt.MicroBufferSize*Gt.MicroBufferCount*Gt.AudioChannels),t=0;for(let i=0;i<Gt.MicroBufferCount;i++){this._sequencer.fillMidiEventQueue();const i=this._synthesizer.synthesize(e,t,Gt.MicroBufferSize);t+=Gt.MicroBufferSize*Gt.AudioChannels;for(const e of i)this._midiEventsPlayedFilter.has(e.event.command)&&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!==q.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(Be.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(Be.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),Be.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.state=q.Playing,this.stateChanged.trigger(new zt(this.state,!1))}pause(){this.state!==q.Paused&&this._isMidiLoaded&&(Be.debug("AlphaSynth","Pausing playback"),this.state=q.Paused,this.stateChanged.trigger(new zt(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===q.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(Be.debug("AlphaSynth","Stopping playback"),this.state=q.Paused,this.output.pause(),this._notPlayedSamples=0,this._sequencer.stop(),this._synthesizer.noteOffAll(!0),this.tickPosition=this._sequencer.mainPlaybackRange?this._sequencer.mainPlaybackRange.startTick:0,this.stateChanged.trigger(new zt(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{Be.debug("AlphaSynth","Loading soundfont from bytes");let e=new Yt;e.load(i),this._synthesizer.loadPresets(e,t),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),Be.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){Be.error("AlphaSynth","Could not load soundfont from bytes "+e),this.soundFontLoadFailed.trigger(e)}}checkReadyForPlayback(){this.isReadyForPlayback&&(this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this.readyForPlayback.trigger())}loadMidiFile(e){this.stop();try{Be.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new Ut(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),Be.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){Be.error("AlphaSynth","Could not load midi from model "+e),this.midiLoadFailed.trigger(e)}}setChannelMute(e,t){this._synthesizer.channelSetMute(e,t)}resetChannelStates(){this._synthesizer.resetChannelStates()}setChannelSolo(e,t){this._synthesizer.channelSetSolo(e,t)}setChannelVolume(e,t){t=Math.max(t,Gt.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;let t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*Gt.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?(Be.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(Be.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=q.Paused,this.stopOneTimeMidi()):(Be.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(Be.debug("AlphaSynth",`Position changed: (time: ${i}/${a}, tick: ${s}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new Ut(i,a,s,r,t)),t)this._playedEventsQueue.clear();else{const e=new pi;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<i;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new yi(e.toArray()))}}}class _i{constructor(){this.division=ye.QuarterTime,this.events=[]}addEvent(e){if(0===this.events.length)this.events.push(e);else{let t=this.events.length;for(;t>0;){if(!(this.events[t-1].tick>e.tick))break;t--}this.events.splice(t,0,e)}}toBinary(){let e=Ke.empty();return this.writeTo(e),e.toArray()}writeTo(e){let t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),t=new Uint8Array([0,0,0,6]),e.write(t,0,t.length),t=new Uint8Array([0,0]),e.write(t,0,t.length);let i=1;t=new Uint8Array([i>>8&255,255&i]),e.write(t,0,t.length),i=this.division,t=new Uint8Array([i>>8&255,255&i]),e.write(t,0,t.length);let s=Ke.empty(),a=0;for(let e of this.events){let t=e.tick-a;_i.writeVariableInt(s,t),e.writeTo(s),a=e.tick}t=new Uint8Array([77,84,114,107]),e.write(t,0,t.length);let r=s.toArray(),n=r.length;t=new Uint8Array([n>>24&255,n>>16&255,n>>8&255,255&n]),e.write(t,0,t.length),e.write(r,0,r.length)}static writeVariableInt(e,t){let 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])}}class wi extends It{constructor(e,t,i,s,a){super(e,t,i,s,0),this.data=a}writeTo(e){e.writeByte(255),e.writeByte(this.metaStatus);let t=this.data.length;_i.writeVariableInt(e,t),e.write(this.data,0,this.data.length)}}class Bi extends It{constructor(e,t,i,s,a){super(e,t,i,s,0),this.value=a}writeTo(e){e.writeByte(255),e.writeByte(this.metaStatus),_i.writeVariableInt(e,3);let t=new Uint8Array([this.value>>16&255,this.value>>8&255,255&this.value]);e.write(t,0,t.length)}}class Ti{static parseEnum(e,t){switch(typeof e){case"string":const i=parseInt(e);return isNaN(i)?t[Object.keys(t).find((t=>t.toLowerCase()===e.toLowerCase()))]:i;case"number":return e;case"undefined":case"object":return null}throw new pe(i.Format,`Could not parse enum value '${e}'`)}static forEach(e,t){if(e instanceof Map)e.forEach(t);else if("object"==typeof e)for(const i in e)t(e[i],i)}}class ki{constructor(e,t,i){this.text=e,this.startPos=t,this.endPos=i}}class vi{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 ki(e.substring(i,s),i,s)),i=s+1}return t}parse(){var e;if(this.reset(),1===this._tokens.length)switch(null===(e=this._currentToken)||void 0===e?void 0:e.text){case"caption":case"icon":case"menu":case"message-box":case"small-caption":case"status-bar":case"inherit":return}this.parseOnlyFamilies||(this.fontStyleVariantWeight(),this.fontSizeLineHeight()),this.fontFamily()}static parseFamilies(e){const t=new vi(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"}(K||(K={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(Z||(Z={}));class Ni{reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=vi.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===Z.Bold}get isItalic(){return this.style===K.Italic}constructor(e,t,i=K.Plain,s=Z.Regular){this._cssScale=0,this._families=vi.parseFamilies(e),this._size=t,this._style=i,this._weight=s,this._css=this.toCssString()}static withFamilyList(e,t,i=K.Plain,s=Z.Regular){const a=new Ni("",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=>vi.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=Ti.parseEnum(t.get("style"),K),r=Ti.parseEnum(t.get("weight"),Z);return Ni.withFamilyList(i,s,a,r)}case"string":{const t=new vi(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=K.Plain;"italic"===t.style&&(r=K.Italic);let n=Z.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=Z.Bold}return Ni.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 xi{constructor(){this.copyrightFont=new Ni(xi.sansFont,12,K.Plain,Z.Bold),this.titleFont=new Ni(xi.serifFont,32,K.Plain),this.subTitleFont=new Ni(xi.serifFont,20,K.Plain),this.wordsFont=new Ni(xi.serifFont,15,K.Plain),this.effectFont=new Ni(xi.serifFont,12,K.Italic),this.fretboardNumberFont=new Ni(xi.sansFont,11,K.Plain),this.tablatureFont=new Ni(xi.sansFont,13,K.Plain),this.graceFont=new Ni(xi.sansFont,11,K.Plain),this.staffLineColor=new Ue(165,165,165,255),this.barSeparatorColor=new Ue(34,34,17,255),this.barNumberFont=new Ni(xi.sansFont,11,K.Plain),this.barNumberColor=new Ue(200,0,0,255),this.fingeringFont=new Ni(xi.serifFont,14,K.Plain),this.markerFont=new Ni(xi.serifFont,14,K.Plain,Z.Bold),this.mainGlyphColor=new Ue(0,0,0,255),this.secondaryGlyphColor=new Ue(0,0,0,100),this.scoreInfoColor=new Ue(0,0,0,255)}}xi.sansFont="Arial, sans-serif",xi.serifFont="Georgia, serif";class Pi{constructor(){this.scale=1,this.stretchForce=1,this.layoutMode=e.Page,this.staveProfile=t.Default,this.barsPerRow=-1,this.startBar=1,this.barCount=-1,this.barCountPerPartial=10,this.resources=new xi,this.padding=null}}class Ei{constructor(){this.encoding="utf-8",this.mergePartGroupsInMusicXml=!1,this.beatTextAsLyrics=!1}}!function(e){e[e.Off=0]="Off",e[e.Continuous=1]="Continuous",e[e.OffScreen=2]="OffScreen"}(ee||(ee={}));class Ci{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 Fi{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}class Li{constructor(){this.soundFont=null,this.scrollElement="html,body",this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=ee.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new Ci,this.slide=new Fi,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}class Mi{static fromJson(e,t){t&&Ti.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(e,t,i){switch(t){case"scriptfile":return e.scriptFile=i,!0;case"fontdirectory":return e.fontDirectory=i,!0;case"file":return e.file=i,!0;case"tex":return e.tex=i,!0;case"tracks":return e.tracks=i,!0;case"enablelazyloading":return e.enableLazyLoading=i,!0;case"engine":return e.engine=i,!0;case"loglevel":return e.logLevel=Ti.parseEnum(i,v),!0;case"useworkers":return e.useWorkers=i,!0;case"includenotebounds":return e.includeNoteBounds=i,!0}return!1}}class Di{static fromJson(e,t){t&&Ti.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",Ni.toJson(e.copyrightFont)),t.set("titlefont",Ni.toJson(e.titleFont)),t.set("subtitlefont",Ni.toJson(e.subTitleFont)),t.set("wordsfont",Ni.toJson(e.wordsFont)),t.set("effectfont",Ni.toJson(e.effectFont)),t.set("fretboardnumberfont",Ni.toJson(e.fretboardNumberFont)),t.set("tablaturefont",Ni.toJson(e.tablatureFont)),t.set("gracefont",Ni.toJson(e.graceFont)),t.set("stafflinecolor",Ue.toJson(e.staffLineColor)),t.set("barseparatorcolor",Ue.toJson(e.barSeparatorColor)),t.set("barnumberfont",Ni.toJson(e.barNumberFont)),t.set("barnumbercolor",Ue.toJson(e.barNumberColor)),t.set("fingeringfont",Ni.toJson(e.fingeringFont)),t.set("markerfont",Ni.toJson(e.markerFont)),t.set("mainglyphcolor",Ue.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",Ue.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",Ue.toJson(e.scoreInfoColor)),t}static setProperty(e,t,i){switch(t){case"copyrightfont":return e.copyrightFont=Ni.fromJson(i),!0;case"titlefont":return e.titleFont=Ni.fromJson(i),!0;case"subtitlefont":return e.subTitleFont=Ni.fromJson(i),!0;case"wordsfont":return e.wordsFont=Ni.fromJson(i),!0;case"effectfont":return e.effectFont=Ni.fromJson(i),!0;case"fretboardnumberfont":return e.fretboardNumberFont=Ni.fromJson(i),!0;case"tablaturefont":return e.tablatureFont=Ni.fromJson(i),!0;case"gracefont":return e.graceFont=Ni.fromJson(i),!0;case"stafflinecolor":return e.staffLineColor=Ue.fromJson(i),!0;case"barseparatorcolor":return e.barSeparatorColor=Ue.fromJson(i),!0;case"barnumberfont":return e.barNumberFont=Ni.fromJson(i),!0;case"barnumbercolor":return e.barNumberColor=Ue.fromJson(i),!0;case"fingeringfont":return e.fingeringFont=Ni.fromJson(i),!0;case"markerfont":return e.markerFont=Ni.fromJson(i),!0;case"mainglyphcolor":return e.mainGlyphColor=Ue.fromJson(i),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=Ue.fromJson(i),!0;case"scoreinfocolor":return e.scoreInfoColor=Ue.fromJson(i),!0}return!1}}class Ii{static fromJson(e,t){t&&Ti.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("resources",Di.toJson(e.resources)),t.set("padding",e.padding),t}static setProperty(i,s,a){switch(s){case"scale":return i.scale=a,!0;case"stretchforce":return i.stretchForce=a,!0;case"layoutmode":return i.layoutMode=Ti.parseEnum(a,e),!0;case"staveprofile":return i.staveProfile=Ti.parseEnum(a,t),!0;case"barsperrow":return i.barsPerRow=a,!0;case"startbar":return i.startBar=a,!0;case"barcount":return i.barCount=a,!0;case"barcountperpartial":return i.barCountPerPartial=a,!0;case"padding":return i.padding=a,!0}if(["resources"].indexOf(s)>=0)return Di.fromJson(i.resources,a),!0;for(const e of["resources"])if(0===s.indexOf(e)&&Di.setProperty(i.resources,s.substring(e.length),a))return!0;return!1}}class Ri{static fromJson(e,t){t&&Ti.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(e,t,i){switch(t){case"notationmode":return e.notationMode=Ti.parseEnum(i,T),!0;case"fingeringmode":return e.fingeringMode=Ti.parseEnum(i,B),!0;case"elements":return e.elements=new Map,Ti.forEach(i,((t,i)=>{e.elements.set(Ti.parseEnum(i,k),t)})),!0;case"rhythmmode":return e.rhythmMode=Ti.parseEnum(i,w),!0;case"rhythmheight":return e.rhythmHeight=i,!0;case"transpositionpitches":return e.transpositionPitches=i,!0;case"displaytranspositionpitches":return e.displayTranspositionPitches=i,!0;case"smallgracetabnotes":return e.smallGraceTabNotes=i,!0;case"extendbendarrowsontiednotes":return e.extendBendArrowsOnTiedNotes=i,!0;case"extendlineeffectstobeatend":return e.extendLineEffectsToBeatEnd=i,!0;case"slurheight":return e.slurHeight=i,!0}return!1}}class Ai{static fromJson(e,t){t&&Ti.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 Oi{static fromJson(e,t){t&&Ti.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 Gi{static fromJson(e,t){t&&Ti.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 Vi{static fromJson(e,t){t&&Ti.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("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",Oi.toJson(e.vibrato)),t.set("slide",Gi.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t.set("buffertimeinmilliseconds",e.bufferTimeInMilliseconds),t}static setProperty(e,t,i){switch(t){case"soundfont":return e.soundFont=i,!0;case"scrollelement":return e.scrollElement=i,!0;case"enableplayer":return e.enablePlayer=i,!0;case"enablecursor":return e.enableCursor=i,!0;case"enableanimatedbeatcursor":return e.enableAnimatedBeatCursor=i,!0;case"enableelementhighlighting":return e.enableElementHighlighting=i,!0;case"enableuserinteraction":return e.enableUserInteraction=i,!0;case"scrolloffsetx":return e.scrollOffsetX=i,!0;case"scrolloffsety":return e.scrollOffsetY=i,!0;case"scrollmode":return e.scrollMode=Ti.parseEnum(i,ee),!0;case"scrollspeed":return e.scrollSpeed=i,!0;case"nativebrowsersmoothscroll":return e.nativeBrowserSmoothScroll=i,!0;case"songbookbendduration":return e.songBookBendDuration=i,!0;case"songbookdipduration":return e.songBookDipDuration=i,!0;case"playtripletfeel":return e.playTripletFeel=i,!0;case"buffertimeinmilliseconds":return e.bufferTimeInMilliseconds=i,!0}if(["vibrato"].indexOf(t)>=0)return Oi.fromJson(e.vibrato,i),!0;for(const s of["vibrato"])if(0===t.indexOf(s)&&Oi.setProperty(e.vibrato,t.substring(s.length),i))return!0;if(["slide"].indexOf(t)>=0)return Gi.fromJson(e.slide,i),!0;for(const s of["slide"])if(0===t.indexOf(s)&&Gi.setProperty(e.slide,t.substring(s.length),i))return!0;return!1}}class Hi{static fromJson(e,t){t&&Ti.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",Mi.toJson(e.core)),t.set("display",Ii.toJson(e.display)),t.set("notation",Ri.toJson(e.notation)),t.set("importer",Ai.toJson(e.importer)),t.set("player",Vi.toJson(e.player)),t}static setProperty(e,t,i){if(["core",""].indexOf(t)>=0)return Mi.fromJson(e.core,i),!0;for(const s of["core",""])if(0===t.indexOf(s)&&Mi.setProperty(e.core,t.substring(s.length),i))return!0;if(["display",""].indexOf(t)>=0)return Ii.fromJson(e.display,i),!0;for(const s of["display",""])if(0===t.indexOf(s)&&Ii.setProperty(e.display,t.substring(s.length),i))return!0;if(["notation"].indexOf(t)>=0)return Ri.fromJson(e.notation,i),!0;for(const s of["notation"])if(0===t.indexOf(s)&&Ri.setProperty(e.notation,t.substring(s.length),i))return!0;if(["importer"].indexOf(t)>=0)return Ai.fromJson(e.importer,i),!0;for(const s of["importer"])if(0===t.indexOf(s)&&Ai.setProperty(e.importer,t.substring(s.length),i))return!0;if(["player"].indexOf(t)>=0)return Vi.fromJson(e.player,i),!0;for(const s of["player"])if(0===t.indexOf(s)&&Vi.setProperty(e.player,t.substring(s.length),i))return!0;return!1}}class Wi{constructor(){this.core=new fo,this.display=new Pi,this.notation=new Se,this.importer=new Ei,this.player=new Li}setSongBookModeSettings(){this.notation.notationMode=T.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=B.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(k.ParenthesisOnTiedBends,!1),this.notation.elements.set(k.TabNotesOnTiedBends,!1),this.notation.elements.set(k.ZerosOnDiveWhammys,!0)}static get songBook(){let e=new Wi;return e.setSongBookModeSettings(),e}fillFromJson(e){Hi.fromJson(this,e)}}class zi extends Dt{constructor(e,t,i,s,a){super(e,t,i,0,0),this.noteKey=s,this.pitch=a}writeTo(e){let t=new Uint8Array([64,255&this.message,255&this.noteKey,0,this.pitch>>24&255,this.pitch>>16&255,this.pitch>>8&255,255&this.pitch]);e.write(t,0,t.length)}}class Ui{static fromJson(e,t){t&&Ti.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 Xi{static fromJson(e,t){t&&Ti.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=Ti.parseEnum(i,a),!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 Yi{static fromJson(e,t){t&&Ti.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=Ti.parseEnum(i,O),!0;case"length":return e.length=i,!0}return!1}}class qi{static fromJson(e,t){t&&Ti.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",Ui.toJson(e.section)),t.set("tempoautomation",Xi.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(),Yi.toJson(s))}return t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t}static setProperty(e,t,i){switch(t){case"alternateendings":return e.alternateEndings=i,!0;case"keysignature":return e.keySignature=Ti.parseEnum(i,L),!0;case"keysignaturetype":return e.keySignatureType=Ti.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=Ti.parseEnum(i,I),!0;case"fermata":return e.fermata=new Map,Ti.forEach(i,((t,i)=>{const s=new nt;Yi.fromJson(s,t),e.addFermata(parseInt(i),s)})),!0;case"start":return e.start=i,!0;case"isanacrusis":return e.isAnacrusis=i,!0}return["section"].indexOf(t)>=0?(i?(e.section=new We,Ui.fromJson(e.section,i)):e.section=null,!0):["tempoautomation"].indexOf(t)>=0&&(i?(e.tempoAutomation=new fe,Xi.fromJson(e.tempoAutomation,i)):e.tempoAutomation=null,!0)}}class Ji{static fromJson(e,t){t&&Ti.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 ji{static fromJson(e,t){t&&Ti.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){var t;if(!e)return null;const i=new Map;return i.set("id",e.id),i.set("accentuated",e.accentuated),i.set("bendtype",e.bendType),i.set("bendstyle",e.bendStyle),i.set("iscontinuedbend",e.isContinuedBend),null!==e.bendPoints&&i.set("bendpoints",null===(t=e.bendPoints)||void 0===t?void 0:t.map((e=>Ji.toJson(e)))),i.set("fret",e.fret),i.set("string",e.string),i.set("octave",e.octave),i.set("tone",e.tone),i.set("percussionarticulation",e.percussionArticulation),i.set("isvisible",e.isVisible),i.set("islefthandtapped",e.isLeftHandTapped),i.set("ishammerpullorigin",e.isHammerPullOrigin),i.set("isslurdestination",e.isSlurDestination),i.set("harmonictype",e.harmonicType),i.set("harmonicvalue",e.harmonicValue),i.set("isghost",e.isGhost),i.set("isletring",e.isLetRing),i.set("ispalmmute",e.isPalmMute),i.set("isdead",e.isDead),i.set("isstaccato",e.isStaccato),i.set("slideintype",e.slideInType),i.set("slideouttype",e.slideOutType),i.set("vibrato",e.vibrato),i.set("istiedestination",e.isTieDestination),i.set("lefthandfinger",e.leftHandFinger),i.set("righthandfinger",e.rightHandFinger),i.set("isfingering",e.isFingering),i.set("trillvalue",e.trillValue),i.set("trillspeed",e.trillSpeed),i.set("durationpercent",e.durationPercent),i.set("accidentalmode",e.accidentalMode),i.set("dynamics",e.dynamics),e.toJson(i),i}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"accentuated":return e.accentuated=Ti.parseEnum(i,s),!0;case"bendtype":return e.bendType=Ti.parseEnum(i,l),!0;case"bendstyle":return e.bendStyle=Ti.parseEnum(i,h),!0;case"iscontinuedbend":return e.isContinuedBend=i,!0;case"bendpoints":if(i){e.bendPoints=[];for(const t of i){const i=new be;Ji.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=Ti.parseEnum(i,m),!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=Ti.parseEnum(i,b),!0;case"slideouttype":return e.slideOutType=Ti.parseEnum(i,S),!0;case"vibrato":return e.vibrato=Ti.parseEnum(i,_),!0;case"istiedestination":return e.isTieDestination=i,!0;case"lefthandfinger":return e.leftHandFinger=Ti.parseEnum(i,f),!0;case"righthandfinger":return e.rightHandFinger=Ti.parseEnum(i,f),!0;case"isfingering":return e.isFingering=i,!0;case"trillvalue":return e.trillValue=i,!0;case"trillspeed":return e.trillSpeed=Ti.parseEnum(i,u),!0;case"durationpercent":return e.durationPercent=i,!0;case"accidentalmode":return e.accidentalMode=Ti.parseEnum(i,y),!0;case"dynamics":return e.dynamics=Ti.parseEnum(i,p),!0}return e.setProperty(t,i)}}class Qi{static fromJson(e,t){t&&Ti.forEach(t,((t,i)=>this.setProperty(e,i,t)))}static toJson(e){var t;if(!e)return null;const i=new Map;return i.set("id",e.id),i.set("notes",e.notes.map((e=>ji.toJson(e)))),i.set("isempty",e.isEmpty),i.set("whammystyle",e.whammyStyle),i.set("ottava",e.ottava),i.set("islegatoorigin",e.isLegatoOrigin),i.set("duration",e.duration),i.set("automations",e.automations.map((e=>Xi.toJson(e)))),i.set("dots",e.dots),i.set("fadein",e.fadeIn),i.set("lyrics",e.lyrics),i.set("hasrasgueado",e.hasRasgueado),i.set("pop",e.pop),i.set("slap",e.slap),i.set("tap",e.tap),i.set("text",e.text),i.set("brushtype",e.brushType),i.set("brushduration",e.brushDuration),i.set("tupletdenominator",e.tupletDenominator),i.set("tupletnumerator",e.tupletNumerator),i.set("iscontinuedwhammy",e.isContinuedWhammy),i.set("whammybartype",e.whammyBarType),null!==e.whammyBarPoints&&i.set("whammybarpoints",null===(t=e.whammyBarPoints)||void 0===t?void 0:t.map((e=>Ji.toJson(e)))),i.set("vibrato",e.vibrato),i.set("chordid",e.chordId),i.set("gracetype",e.graceType),i.set("pickstroke",e.pickStroke),i.set("tremolospeed",e.tremoloSpeed),i.set("crescendo",e.crescendo),i.set("displaystart",e.displayStart),i.set("playbackstart",e.playbackStart),i.set("displayduration",e.displayDuration),i.set("playbackduration",e.playbackDuration),i.set("dynamics",e.dynamics),i.set("invertbeamdirection",e.invertBeamDirection),i.set("preferredbeamdirection",e.preferredBeamDirection),i.set("beamingmode",e.beamingMode),i}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 Pe;ji.fromJson(i,t),e.addNote(i)}return!0;case"isempty":return e.isEmpty=i,!0;case"whammystyle":return e.whammyStyle=Ti.parseEnum(i,h),!0;case"ottava":return e.ottava=Ti.parseEnum(i,n),!0;case"islegatoorigin":return e.isLegatoOrigin=i,!0;case"duration":return e.duration=Ti.parseEnum(i,u),!0;case"automations":e.automations=[];for(const t of i){const i=new fe;Xi.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=Ti.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=Ti.parseEnum(i,C),!0;case"whammybarpoints":if(i){e.whammyBarPoints=[];for(const t of i){const i=new be;Ji.fromJson(i,t),e.addWhammyBarPoint(i)}}return!0;case"vibrato":return e.vibrato=Ti.parseEnum(i,_),!0;case"chordid":return e.chordId=i,!0;case"gracetype":return e.graceType=Ti.parseEnum(i,g),!0;case"pickstroke":return e.pickStroke=Ti.parseEnum(i,N),!0;case"tremolospeed":return e.tremoloSpeed=Ti.parseEnum(i,u),!0;case"crescendo":return e.crescendo=Ti.parseEnum(i,c),!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=Ti.parseEnum(i,p),!0;case"invertbeamdirection":return e.invertBeamDirection=i,!0;case"preferredbeamdirection":return e.preferredBeamDirection=Ti.parseEnum(i,H),!0;case"beamingmode":return e.beamingMode=Ti.parseEnum(i,F),!0}return!1}}class $i{static fromJson(e,t){t&&Ti.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=>Qi.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 Ie;Qi.fromJson(i,t),e.addBeat(i)}return!0;case"isempty":return e.isEmpty=i,!0}return!1}}class Ki{static fromJson(e,t){t&&Ti.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=>$i.toJson(e)))),t.set("similemark",e.simileMark),t}static setProperty(e,t,i){switch(t){case"id":return e.id=i,!0;case"clef":return e.clef=Ti.parseEnum(i,r),!0;case"clefottava":return e.clefOttava=Ti.parseEnum(i,n),!0;case"voices":e.voices=[];for(const t of i){const i=new je;$i.fromJson(i,t),e.addVoice(i)}return!0;case"similemark":return e.simileMark=Ti.parseEnum(i,o),!0}return!1}}class Zi{static fromJson(e,t){t&&Ti.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 es{static fromJson(e,t){t&&Ti.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 ts{static fromJson(e,t){t&&Ti.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=>Ki.toJson(e)))),null!==e.chords){const i=new Map;t.set("chords",i);for(const[t,s]of e.chords)i.set(t.toString(),Zi.toJson(s))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",es.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 me;Ki.fromJson(i,t),e.addBar(i)}return!0;case"chords":return e.chords=new Map,Ti.forEach(i,((t,i)=>{const s=new Re;Zi.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&&(es.fromJson(e.stringTuning,i),!0)}}class is{static fromJson(e,t){t&&Ti.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 ss{static fromJson(e,t){t&&Ti.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=Ti.parseEnum(i,x),!0;case"noteheadhalf":return e.noteHeadHalf=Ti.parseEnum(i,x),!0;case"noteheadwhole":return e.noteHeadWhole=Ti.parseEnum(i,x),!0;case"techniquesymbol":return e.techniqueSymbol=Ti.parseEnum(i,x),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=Ti.parseEnum(i,E),!0;case"outputmidinumber":return e.outputMidiNumber=i,!0}return!1}}class as{static fromJson(e,t){t&&Ti.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=>ts.toJson(e)))),t.set("playbackinfo",is.toJson(e.playbackInfo)),t.set("color",Ue.toJson(e.color)),t.set("name",e.name),t.set("shortname",e.shortName),t.set("percussionarticulations",e.percussionArticulations.map((e=>ss.toJson(e)))),t}static setProperty(e,t,i){switch(t){case"staves":e.staves=[];for(const t of i){const i=new qe;ts.fromJson(i,t),e.addStaff(i)}return!0;case"color":return e.color=Ue.fromJson(i),!0;case"name":return e.name=i,!0;case"shortname":return e.shortName=i,!0;case"percussionarticulations":e.percussionArticulations=[];for(const t of i){const i=new ve;ss.fromJson(i,t),e.percussionArticulations.push(i)}return!0}return["playbackinfo"].indexOf(t)>=0&&(is.fromJson(e.playbackInfo,i),!0)}}class rs{static fromJson(e,t){t&&Ti.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 ns{static fromJson(e,t){t&&Ti.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=>qi.toJson(e)))),t.set("tracks",e.tracks.map((e=>as.toJson(e)))),t.set("stylesheet",rs.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 Oe;qi.fromJson(i,t),e.addMasterBar(i)}return!0;case"tracks":e.tracks=[];for(const t of i){const i=new Je;as.fromJson(i,t),e.addTrack(i)}return!0}return["stylesheet"].indexOf(t)>=0&&(rs.fromJson(e.stylesheet,i),!0)}}class os{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=os.scoreToJsObject(e);return JSON.stringify(t,os.jsonReplacer)}static jsonToScore(e,t){return os.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return ns.toJson(e)}static jsObjectToScore(e,t){let i=new He;return ns.fromJson(i,e),i.finish(null!=t?t:new Wi),i}static settingsToJson(e){let t=os.settingsToJsObject(e);return JSON.stringify(t,os.jsonReplacer)}static jsonToSettings(e){return os.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return Hi.toJson(e)}static jsObjectToSettings(e){let t=new Wi;return Hi.fromJson(t,e),t}static jsObjectToMidiFile(e){let t=new _i;t.division=e.division;let i=e.events;for(let e of i){let i=os.jsObjectToMidiEvent(e);t.events.push(i)}return t}static jsObjectToMidiEvent(e){let t,i=e.track,s=e.tick,a=e.message;switch(e.type){case"SystemExclusiveEvent":t=new At(i,s,0,0,e.data),t.message=a;break;case"MetaDataEvent":t=new wi(i,s,0,0,e.data),t.message=a;break;case"MetaNumberEvent":t=new Bi(i,s,0,0,e.value),t.message=a;break;case"Midi20PerNotePitchBendEvent":t=new zi(i,s,0,e.noteKey,e.pitch),t.message=a;break;default:t=new Dt(i,s,0,0,0),t.message=a}return t}static midiFileToJsObject(e){let t={};t.division=e.division;let i=[];t.events=i;for(let t of e.events)i.push(os.midiEventToJsObject(t));return t}static midiEventToJsObject(e){let t={};return t.track=e.track,t.tick=e.tick,t.message=e.message,e instanceof At?(t.type="SystemExclusiveEvent",t.data=e.data):e instanceof wi?(t.type="MetaDataEvent",t.data=e.data):e instanceof Bi?(t.type="MetaNumberEvent",t.value=e.value):e instanceof zi&&(t.type="Midi20PerNotePitchBendEvent",t.noteKey=e.noteKey,t.pitch=e.pitch),t}}class hs{constructor(){this.ready=new fi,this.samplesPlayed=new mi,this.sampleRequest=new fi}get sampleRate(){return hs.preferredSampleRate}open(){Be.debug("AlphaSynth","Initializing webworker worker"),this._worker=go.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 hs.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case hs.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(){}}hs.CmdOutputPrefix="alphaSynth.output.",hs.CmdOutputAddSamples=hs.CmdOutputPrefix+"addSamples",hs.CmdOutputPlay=hs.CmdOutputPrefix+"play",hs.CmdOutputPause=hs.CmdOutputPrefix+"pause",hs.CmdOutputResetSamples=hs.CmdOutputPrefix+"resetSamples",hs.CmdOutputSampleRequest=hs.CmdOutputPrefix+"sampleRequest",hs.CmdOutputSamplesPlayed=hs.CmdOutputPrefix+"samplesPlayed",hs.preferredSampleRate=0;class ls{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new Si(new hs,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=go.globalThis;e.addEventListener("message",(t=>{let i=t.data;if("alphaSynth.initialize"===i.cmd)hs.preferredSampleRate=i.sampleRate,Be.logLevel=i.logLevel,go.globalThis.alphaSynthWebWorker=new ls(e,i.bufferTimeInMilliseconds)}))}handleMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":Be.logLevel=t.value;break;case"alphaSynth.setMasterVolume":this._player.masterVolume=t.value;break;case"alphaSynth.setMetronomeVolume":this._player.metronomeVolume=t.value;break;case"alphaSynth.setPlaybackSpeed":this._player.playbackSpeed=t.value;break;case"alphaSynth.setTickPosition":this._player.tickPosition=t.value;break;case"alphaSynth.setTimePosition":this._player.timePosition=t.value;break;case"alphaSynth.setPlaybackRange":this._player.playbackRange=t.value;break;case"alphaSynth.setIsLooping":this._player.isLooping=t.value;break;case"alphaSynth.setCountInVolume":this._player.countInVolume=t.value;break;case"alphaSynth.setMidiEventsPlayedFilter":this._player.midiEventsPlayedFilter=t.value;break;case"alphaSynth.play":this._player.play();break;case"alphaSynth.pause":this._player.pause();break;case"alphaSynth.playPause":this._player.playPause();break;case"alphaSynth.stop":this._player.stop();break;case"alphaSynth.playOneTimeMidiFile":this._player.playOneTimeMidiFile(os.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(os.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);break;case"alphaSynth.setChannelSolo":this._player.setChannelSolo(t.channel,t.solo);break;case"alphaSynth.setChannelVolume":this._player.setChannelVolume(t.channel,t.volume);break;case"alphaSynth.resetChannelStates":this._player.resetChannelStates();break;case"alphaSynth.destroy":this._player.destroy(),this._main.postMessage({cmd:"alphaSynth.destroyed"})}}onPositionChanged(e){this._main.postMessage({cmd:"alphaSynth.positionChanged",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onPlayerStateChanged(e){this._main.postMessage({cmd:"alphaSynth.playerStateChanged",state:e.state,stopped:e.stopped})}onFinished(){this._main.postMessage({cmd:"alphaSynth.finished"})}onSoundFontLoaded(){this._main.postMessage({cmd:"alphaSynth.soundFontLoaded"})}onSoundFontLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.soundFontLoadFailed",error:this.serializeException(e)})}serializeException(e){let t=JSON.parse(JSON.stringify(e));return e.message&&(t.message=e.message),e.stack&&(t.stack=e.stack),e.constructor&&e.constructor.name&&(t.type=e.constructor.name),t}onMidiLoaded(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onMidiLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.midiLoaded",error:this.serializeException(e)})}onReadyForPlayback(){this._main.postMessage({cmd:"alphaSynth.readyForPlayback"})}onMidiEventsPlayed(e){this._main.postMessage({cmd:"alphaSynth.midiEventsPlayed",events:e.events.map(os.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}class ds{static generateFontLookup(e){if(!ds.FontSizeLookupTables.has(e))if(go.isRunningInWorker)ds.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);ds.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(ds.FontSizeLookupTables.has(t[e])){n=t[e];break}ds.FontSizeLookupTables.has(n)||ds.generateFontLookup(n),r=ds.FontSizeLookupTables.get(n);let o=1;s===K.Italic&&(o*=1.2),a===Z.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}}ds.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]),ds.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]),ds.FontSizeLookupTables=new Map([["Arial",ds.Arial],["'Arial'",ds.Arial],['"Arial"',ds.Arial],["Georgia",ds.Georgia],["'Georgia'",ds.Georgia],['"Georgia"',ds.Georgia]]),ds.ControlChars=32;class cs{constructor(){this.id=ke.newGuid(),this.x=0,this.y=0,this.width=0,this.height=0,this.totalWidth=0,this.totalHeight=0,this.firstMasterBarIndex=-1,this.lastMasterBarIndex=-1,this.renderResult=null}}class us{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 ps{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 gs{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 fs{}class ms{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 ys{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 ys,s=e.staveGroups;for(let e of s){let s=new ms;s.visualBounds=e.visualBounds,s.realBounds=e.realBounds,i.addStaveGroup(s);for(let i of e.bars){let e=new gs;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 us;i.visualBounds=s.visualBounds,i.realBounds=s.realBounds,e.addBar(i);for(let e of s.beats){let s=new ps;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 fs,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){var t;this._beatLookup.has(e.beat.id)||this._beatLookup.set(e.beat.id,[]),null===(t=this._beatLookup.get(e.beat.id))||void 0===t||t.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 bs{constructor(t){this._currentLayoutMode=e.Page,this._currentRenderEngine=null,this._renderedTracks=null,this.canvas=null,this.score=null,this.tracks=null,this.layout=null,this.boundsLookup=null,this.width=0,this.preRender=new mi,this.renderFinished=new mi,this.partialRenderFinished=new mi,this.partialLayoutFinished=new mi,this.postRenderFinished=new fi,this.error=new mi,this.settings=t,this.recreateCanvas(),this.recreateLayout()}destroy(){this.score=null,this.canvas=null,this.layout=null,this.boundsLookup=null,this.tracks=null}recreateCanvas(){return this._currentRenderEngine!==this.settings.core.engine&&(this.canvas=go.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=go.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?(Be.debug("Rendering","Request render of lazy partial "+e),t.renderLazyPartial(e)):Be.warning("Rendering","Request render of lazy partial "+e+" ignored, no layout exists")}catch(e){this.error.trigger(e)}}render(){if(0!==this.width)if(this.boundsLookup=new ys,this.recreateCanvas(),this.canvas.lineWidth=this.settings.display.scale,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){Be.debug("Rendering","Rendering "+this.tracks.length+" tracks");for(let e=0;e<this.tracks.length;e++){let t=this.tracks[e];Be.debug("Rendering","Track "+e+": "+t.name)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),Be.debug("Rendering","Rendering finished")}else Be.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),Be.debug("Rendering","Clearing finished");else Be.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(Be.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(Be.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new ys,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):Be.debug("Rendering","Current layout does not support dynamic resizing, nothing was done",null),Be.debug("Rendering","Resize finished")}layoutAndRender(){Be.debug("Rendering","Rendering at scale "+this.settings.display.scale+" with layout "+this.layout.name,null),this.layout.layoutAndRender(),this._renderedTracks=this.tracks,this.onRenderFinished(),this.postRenderFinished.trigger()}onRenderFinished(){var e;null===(e=this.boundsLookup)||void 0===e||e.finish();const t=new cs;t.totalHeight=this.layout.height,t.totalWidth=this.layout.width,t.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(t)}}class Ss{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){go.globalThis.alphaTabWebWorker=new Ss(go.globalThis)}handleMessage(e){let t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":let e=os.jsObjectToSettings(t.settings);Be.logLevel=e.core.logLevel,this._renderer=new bs(e),this._renderer.partialRenderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialRenderFinished",result:e})})),this._renderer.partialLayoutFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialLayoutFinished",result:e})})),this._renderer.renderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.renderFinished",result:e})})),this._renderer.postRenderFinished.on((()=>{var e,t;this._main.postMessage({cmd:"alphaTab.postRenderFinished",boundsLookup:null!==(t=null===(e=this._renderer.boundsLookup)||void 0===e?void 0:e.toJson())&&void 0!==t?t:null})})),this._renderer.preRender.on((e=>{this._main.postMessage({cmd:"alphaTab.preRender",resize:e})})),this._renderer.error.on(this.error.bind(this));break;case"alphaTab.invalidate":this._renderer.render();break;case"alphaTab.resizeRender":this._renderer.resizeRender();break;case"alphaTab.renderResult":this._renderer.renderResult(t.resultId);break;case"alphaTab.setWidth":this._renderer.width=t.width;break;case"alphaTab.renderScore":this.updateFontSizes(t.fontSizes);let i=null==t.score?null:os.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(i,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(e){ds.FontSizeLookupTables||(ds.FontSizeLookupTables=new Map);for(let t in e)ds.FontSizeLookupTables.set(t,e[t])}}updateSettings(e){Hi.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){Be.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class _s{constructor(){this._canvas=null,this._color=new Ue(0,0,0,255),this._font=new Ni("Arial",10,K.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 Ni(i,parseFloat(t.fontSize),K.Plain),this._measureCanvas=document.createElement("canvas"),this._measureCanvas.width=10,this._measureCanvas.height=10,this._measureCanvas.style.width="10px",this._measureCanvas.style.height="10px",this._measureContext=this._measureCanvas.getContext("2d"),this._measureContext.textBaseline="hanging"}onRenderFinished(){return null}beginRender(e,t){this._canvas=document.createElement("canvas"),this._canvas.width=e*go.HighDpiFactor|0,this._canvas.height=t*go.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(go.HighDpiFactor,go.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 P.Left;case"center":return P.Center;case"right":return P.Right}}set textAlign(e){switch(e){case P.Left:this._context.textAlign="left";break;case P.Center:this._context.textAlign="center";break;case P.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return E.Top;case"middle":return E.Middle;case"bottom":return E.Bottom}}set textBaseline(e){switch(e){case E.Top:this._context.textBaseline="hanging";break;case E.Middle:this._context.textBaseline="middle";break;case E.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,i){this._context.fillText(e,t,i)}measureText(e){return this._measureContext.measureText(e).width}fillMusicFontSymbol(e,t,i,s,a=!1){s!==x.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!==x.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 ws{constructor(e){this._midiFile=e}addTimeSignature(e,t,i){let s=0;for(;(i>>=1)>0;)s++;const a=new wi(0,e,255,U.TimeSignature,new Uint8Array([255&t,255&s,48,8]));this._midiFile.addEvent(a)}addRest(e,t,i){const s=new At(e,t,X.SystemExclusive,At.AlphaTabManufacturerId,new Uint8Array([Y.Rest]));this._midiFile.addEvent(s)}addNote(e,t,i,s,a,r){const n=new Dt(e,t,this.makeCommand(z.NoteOn,r),ws.fixValue(s),ws.fixValue(a));this._midiFile.addEvent(n);const o=new Dt(e,t+i,this.makeCommand(z.NoteOff,r),ws.fixValue(s),ws.fixValue(a));this._midiFile.addEvent(o)}makeCommand(e,t){return 240&e|15&t}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,i,s,a){const r=new Dt(e,t,this.makeCommand(z.Controller,i),ws.fixValue(s),ws.fixValue(a));this._midiFile.addEvent(r)}addProgramChange(e,t,i,s){const a=new Dt(e,t,this.makeCommand(z.ProgramChange,i),ws.fixValue(s),0);this._midiFile.addEvent(a)}addTempo(e,t){const i=6e7/t|0,s=new Bi(0,e,255,U.Tempo,i);this._midiFile.addEvent(s)}addBend(e,t,i,s){s=s>=Gt.MaxPitchWheel?Gt.MaxPitchWheel:Math.floor(s);const a=new Dt(e,t,this.makeCommand(z.PitchBend,i),127&s,s>>7&127);this._midiFile.addEvent(a)}addNoteBend(e,t,i,s,a){a=(a=a>=Gt.MaxPitchWheel?Gt.MaxPitchWheel:Math.floor(a))*Gt.MaxPitchWheel20/Gt.MaxPitchWheel;const r=new zi(e,t,this.makeCommand(z.PerNotePitchBend,i),s,a);this._midiFile.addEvent(r)}finishTrack(e,t){const i=new wi(e,t,255,U.EndOfTrack,new Uint8Array(0));this._midiFile.addEvent(i)}}class Bs{constructor(){this._highlightedBeats=new Map,this.index=0,this.start=0,this.end=0,this.isEmptyBar=!1,this.beatsToHighlight=[]}highlightBeat(e){this._highlightedBeats.has(e.id)||(this._highlightedBeats.set(e.id,!0),this.beatsToHighlight.push(e))}}!function(e){e[e.BankSelectCoarse=0]="BankSelectCoarse",e[e.ModulationCoarse=1]="ModulationCoarse",e[e.DataEntryCoarse=6]="DataEntryCoarse",e[e.VolumeCoarse=7]="VolumeCoarse",e[e.PanCoarse=10]="PanCoarse",e[e.ExpressionControllerCoarse=11]="ExpressionControllerCoarse",e[e.ModulationFine=33]="ModulationFine",e[e.DataEntryFine=38]="DataEntryFine",e[e.VolumeFine=39]="VolumeFine",e[e.PanFine=42]="PanFine",e[e.ExpressionControllerFine=43]="ExpressionControllerFine",e[e.HoldPedal=64]="HoldPedal",e[e.LegatoPedal=68]="LegatoPedal",e[e.NonRegisteredParameterFine=98]="NonRegisteredParameterFine",e[e.NonRegisteredParameterCourse=99]="NonRegisteredParameterCourse",e[e.RegisteredParameterFine=100]="RegisteredParameterFine",e[e.RegisteredParameterCourse=101]="RegisteredParameterCourse",e[e.ResetControllers=121]="ResetControllers",e[e.AllNotesOff=123]="AllNotesOff"}(te||(te={}));class Ts{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 ks{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 Ts(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=0!=(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 vs{constructor(){this.start=0,this.end=0,this.tempo=0,this.beats=[],this.nextMasterBar=null}finish(){this.beats.sort(((e,t)=>e.start-t.start))}addBeat(e){e.masterBar=this,e.index=this.beats.length,this.beats.push(e)}}class Ns{constructor(){this.duration=0,this.tickDuration=0,this.nextBeatLookup=null}get currentBeat(){return this.currentBeatLookup.beat}get nextBeat(){var e,t;return null!==(t=null===(e=this.nextBeatLookup)||void 0===e?void 0:e.beat)&&void 0!==t?t:null}}class xs{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[]}finish(){let e=null,t=[];for(let i of this.masterBars){i.finish(),e&&(e.nextMasterBar=i);for(const e of i.beats){const i=[];for(let s of t)s.end>e.start&&(i.push(s),e.highlightBeat(s.beat),e.start<=s.start&&s.highlightBeat(e.beat));i.push(e),t=i}e=i}}findBeat(e,t,i=null){const s=new Map;for(const t of e)s.set(t.index,!0);let a=null;return i&&(a=this.findBeatFast(s,i,t)),a||(a=this.findBeatSlow(s,t)),a}findBeatFast(e,t,i){const s=t.currentBeatLookup.start+t.tickDuration;return i>=t.currentBeatLookup.start&&i<s?t:t.nextBeatLookup&&i>=t.nextBeatLookup.start&&i<t.nextBeatLookup.end?this.createResult(t.nextBeatLookup,e):null}findBeatSlow(e,t){const i=this.findMasterBar(t);if(!i)return null;let s=null,a=i.beats;for(let i=0;i<a.length;i++){let r=a[i];if(e.has(r.beat.voice.bar.staff.track.index))if(r.start<=t&&t<r.end)(!s||s.start<r.start)&&(s=a[i]);else if(r.end>t)break}return s?this.createResult(s,e):null}createResult(e,t){const i=this.findNextBeat(e,t),s=new Ns;return s.currentBeatLookup=e,s.nextBeatLookup=i,s.tickDuration=i?i.start-e.start:e.end-e.start,s.duration=ye.ticksToMillis(s.tickDuration,e.masterBar.tempo),s.beatsToHighlight=e.beatsToHighlight,s}findNextBeat(e,t){const i=e.masterBar;let s=i.beats,a=null;for(let i=e.index+1;i<s.length;i++){const r=s[i];if(r.start>e.start&&t.has(r.beat.voice.bar.staff.track.index)){a=r;break}}if(!a&&i.nextMasterBar){s=i.nextMasterBar.beats;for(let e=0;e<s.length;e++){const i=s[e];if(t.has(i.beat.voice.bar.staff.track.index)){a=i;break}}}return a}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 vs;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,this.masterBarLookup.has(e.masterBar.index)||this.masterBarLookup.set(e.masterBar.index,e)}addBeat(e){var t;null===(t=this._currentMasterBar)||void 0===t||t.addBeat(e)}}class Ps{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Es{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class Cs{constructor(e,t,i){this._currentTempo=0,this._currentBarRepeatLookup=null,this._programsPerChannel=new Map,this.tickLookup=new xs,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new Wi,this._currentTempo=this._score.tempo,this._handler=i}generate(){for(const e of this._score.tracks)this.generateTrack(e);Be.debug("Midi","Begin midi generation");const e=new ks(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);this.tickLookup.finish(),Be.debug("Midi","Midi generation done")}generateTrack(e){this.generateChannel(e,e.playbackInfo.primaryChannel,e.playbackInfo),e.playbackInfo.primaryChannel!==e.playbackInfo.secondaryChannel&&this.generateChannel(e,e.playbackInfo.secondaryChannel,e.playbackInfo)}addProgramChange(e,t,i,s){this._programsPerChannel.has(i)&&this._programsPerChannel.get(i)===s||(this._handler.addProgramChange(e.index,t,i,s),this._programsPerChannel.set(i,s))}generateChannel(e,t,i){let s=Cs.toChannelShort(i.volume),a=Cs.toChannelShort(i.balance);this._handler.addControlChange(e.index,0,t,te.VolumeCoarse,s),this._handler.addControlChange(e.index,0,t,te.PanCoarse,a),this._handler.addControlChange(e.index,0,t,te.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,te.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,te.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,te.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,te.DataEntryCoarse,Cs.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 vs;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);this._currentBarRepeatLookup=null;for(const s of i.voices)this.generateVoice(s,t,e)}getPlaybackBar(e){switch(e.simileMark){case o.Simple:e.previousBar&&(e=this.getPlaybackBar(e.previousBar));break;case o.FirstOfDouble:case o.SecondOfDouble:e.previousBar&&e.previousBar.previousBar&&(e=this.getPlaybackBar(e.previousBar.previousBar))}return e}generateVoice(e,t,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!==I.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(s-=this._currentTripletFeel.secondBeatStartOffset,a=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=Cs.calculateTripletFeelInfo(s,a,e),this._currentTripletFeel&&(a=this._currentTripletFeel.firstBeatDuration)));const r=new Bs;r.start=t+s;const n=e.nextBeat?e.nextBeat.absolutePlaybackStart-e.absolutePlaybackStart:a;r.end=t+s,r.highlightBeat(e),r.end+=n>a?n:a,i===e.voice.bar?(r.beat=e,this.tickLookup.addBeat(r)):(r.isEmptyBar=!0,r.beat=i.voices[0].beats[0],this._currentBarRepeatLookup?this._currentBarRepeatLookup.end=r.end:(this._currentBarRepeatLookup=r,this.tickLookup.addBeat(this._currentBarRepeatLookup)));const o=e.voice.bar.staff.track;for(const i of e.automations)this.generateAutomation(e,i,t);if(e.isRest)this._handler.addRest(o.index,t+s,o.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,o.playbackInfo.secondaryChannel,i)}))}}static calculateTripletFeelInfo(e,t,i){let s;switch(i.voice.bar.masterBar.tripletFeel){case I.Triplet8th:case I.Dotted8th:case I.Scottish8th:s=u.Eighth;break;case I.Triplet16th:case I.Dotted16th:case I.Scottish16th:s=u.Sixteenth;break;default:return null}const a=ye.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 Es;switch(i.voice.bar.masterBar.tripletFeel){case I.Triplet8th:r.firstBeatDuration=ye.applyTuplet(ye.toTicks(u.Quarter),3,2),r.secondBeatDuration=ye.applyTuplet(ye.toTicks(u.Eighth),3,2);break;case I.Dotted8th:r.firstBeatDuration=ye.applyDot(ye.toTicks(u.Eighth),!1),r.secondBeatDuration=ye.toTicks(u.Sixteenth);break;case I.Scottish8th:r.firstBeatDuration=ye.toTicks(u.Sixteenth),r.secondBeatDuration=ye.applyDot(ye.toTicks(u.Eighth),!1);break;case I.Triplet16th:r.firstBeatDuration=ye.applyTuplet(ye.toTicks(u.Eighth),3,2),r.secondBeatDuration=ye.applyTuplet(ye.toTicks(u.Sixteenth),3,2);break;case I.Dotted16th:r.firstBeatDuration=ye.applyDot(ye.toTicks(u.Sixteenth),!1),r.secondBeatDuration=ye.toTicks(u.ThirtySecond);break;case I.Scottish16th:r.firstBeatDuration=ye.toTicks(u.ThirtySecond),r.secondBeatDuration=ye.applyDot(ye.toTicks(u.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateNote(e,t,i,s){const a=e.beat.voice.bar.staff.track,r=e.beat.voice.bar.staff;let n=e.realValue;if(e.isPercussion){const t=Ne.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 d=Cs.getNoteVelocity(e),c=e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==_.None?a.playbackInfo.secondaryChannel:a.playbackInfo.primaryChannel;let u=0;if(u=e.hasBend?Cs.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?Cs.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===S.Legato?-1:Cs.getPitchWheel(0),u>=0&&this._handler.addNoteBend(a.index,h,c,n,u),e.beat.fadeIn&&this.generateFadeIn(e,h,l),!e.isTrill||r.isPercussion){if(e.beat.isTremolo)this.generateTremoloPicking(e,h,l,n,d,c);else if(e.hasBend?this.generateBend(e,h,l,n,c):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,h,l,c):e.slideInType!==b.None||e.slideOutType!==S.None?this.generateSlide(e,h,l,n,c):(e.vibrato!==_.None||e.isTieDestination&&e.tieOrigin.vibrato!==_.None)&&this.generateVibrato(e,h,l,n,c),!(e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===S.Legato)){let e=Math.max(l.untilTieOrSlideEnd,l.letRingEnd);this._handler.addNote(a.index,h,e,n,d,c)}}else this.generateTrill(e,h,l,n,d,c)}getNoteDuration(e,t){const i=new Ps;if(i.noteOnly=t,i.untilTieOrSlideEnd=t,i.letRingEnd=t,e.isDead)return i.noteOnly=this.applyStaticDuration(Cs.DefaultDurationDead,t),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isPalmMute)return i.noteOnly=this.applyStaticDuration(Cs.DefaultDurationPalmMute,t),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isStaccato)return i.noteOnly=t/2|0,i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isTieOrigin){const s=e.tieDestination;if(s)if(e.isTieDestination){const e=this.getNoteDuration(s,s.beat.playbackDuration);i.untilTieOrSlideEnd=t+e.untilTieOrSlideEnd}else{const t=e.beat.absolutePlaybackStart,a=this.getNoteDuration(s,s.beat.playbackDuration),r=s.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;i.untilTieOrSlideEnd=r-t}}else if(e.slideOutType===S.Legato){const t=e.slideTarget;if(t){const s=e.beat.absolutePlaybackStart,a=this.getNoteDuration(t,t.beat.playbackDuration),r=t.beat.absolutePlaybackStart+a.untilTieOrSlideEnd;i.untilTieOrSlideEnd=r-s}}if(e.isLetRing&&this._settings.notation.notationMode===T.GuitarPro){let s=e.beat,a=0;const r=e.beat.voice.bar.masterBar.calculateDuration();for(;s.nextBeat;){let t=s.nextBeat;if(t.isRest)break;if(e.isStringed&&t.hasNoteOnString(e.string))break;if(s=s.nextBeat,a=s.absolutePlaybackStart-e.beat.absolutePlaybackStart+s.playbackDuration,a>r){a=r;break}}s===e.beat?i.letRingEnd=t:i.letRingEnd=a}else i.letRingEnd=i.untilTieOrSlideEnd;return i}applyStaticDuration(e,t){const i=this._currentTempo*e/be.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 s.Normal:t++;break;case s.Heavy:t+=2}return ye.dynamicToVelocity(t)}generateFadeIn(e,t,i){const s=e.beat.voice.bar.staff.track,a=Cs.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,te.VolumeCoarse,o),this._handler.addControlChange(s.index,t,s.playbackInfo.secondaryChannel,te.VolumeCoarse,o)),this._handler.addControlChange(s.index,i,s.playbackInfo.primaryChannel,te.VolumeCoarse,o),this._handler.addControlChange(s.index,i,s.playbackInfo.secondaryChannel,te.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,Cs.getPitchWheel(i)),t+=r}e+=i}}static getPitchWheel(e){return Gt.DefaultPitchWheel+e/2*Cs.PitchValuePerSemitone}generateSlide(e,t,i,s,a){let r=e.slideOutType===S.Legato?i.noteOnly:i.untilTieOrSlideEnd,n=[],o=e.beat.voice.bar.staff.track;const h=this._settings.player.slide.simpleSlidePitchOffset,l=Math.floor(be.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),d=Math.floor(be.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case b.IntoFromAbove:n.push(new be(0,h)),n.push(new be(l,0));break;case b.IntoFromBelow:n.push(new be(0,-h)),n.push(new be(l,0))}switch(e.slideOutType){case S.Legato:case S.Shift:n.push(new be(d,0));const t=2*(e.slideTarget.realValue-e.realValue);n.push(new be(be.MaxPosition,t));break;case S.OutDown:n.push(new be(be.MaxPosition-l,0)),n.push(new be(be.MaxPosition,-h));break;case S.OutUp:n.push(new be(be.MaxPosition-l,0)),n.push(new be(be.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 d,c=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend;)t=t.tieDestination;d=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==g.None){switch(e.tieDestination.bendType){case l.Bend:case l.BendRelease:case l.PrebendBend:c=e.tieDestination.bendPoints[1].value;break;case l.Prebend:case l.PrebendRelease:c=e.tieDestination.bendPoints[0].value}d=Math.max(i.noteOnly,ye.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo))}else d=i.noteOnly;r[0].value>0&&!e.isContinuedBend&&t>0&&t--;const u=Math.min(d,ye.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));let p=[];switch(e.bendType){case l.Custom:p=r;break;case l.Bend:case l.Release:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),p.push(new be(be.MaxPosition,c));break;case h.Fast:return(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),void(e.beat.graceType===g.BendGrace?this.generateSongBookWhammyOrBend(t,d,!0,[e.bendPoints[0].value,c],u,o):this.generateSongBookWhammyOrBend(t,d,!1,[e.bendPoints[0].value,c],u,o))}break;case l.BendRelease:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),p.push(new be(be.MaxPosition/2|0,e.bendPoints[1].value)),p.push(new be(be.MaxPosition,e.bendPoints[2].value));break;case h.Fast:return void this.generateSongBookWhammyOrBend(t,d,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],u,o)}break;case l.Hold:case l.Prebend:p=r;break;case l.PrebendBend:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),p.push(new be(be.MaxPosition,e.bendPoints[1].value));break;case h.Fast:return o(t,0|Cs.getPitchWheel(e.bendPoints[0].value)),(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,d,!1,[e.bendPoints[0].value,c],u,o)}break;case l.PrebendRelease:switch(e.bendStyle){case h.Default:p=r;break;case h.Gradual:p.push(new be(0,e.bendPoints[0].value)),p.push(new be(be.MaxPosition,e.bendPoints[1].value));break;case h.Fast:return o(t,0|Cs.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,d,!1,[e.bendPoints[0].value,e.bendPoints[1].value],u,o)}}this.generateWhammyOrBend(t,d,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=Cs.getPitchWheel(s[e]),i=Cs.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 l=[];switch(e.whammyBarType){case C.Custom:l=a;break;case C.Dive:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new be(0,a[0].value)),l.push(new be(be.MaxPosition,a[1].value));break;case h.Fast:const e=Math.min(n,ye.millisToTicks(this._settings.player.songBookBendDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!1,[a[0].value,a[1].value],e,o)}break;case C.Dip:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new be(0,a[0].value)),l.push(new be(be.MaxPosition/2|0,a[1].value)),l.push(new be(be.MaxPosition,a[2].value));break;case h.Fast:const e=Math.min(n,ye.millisToTicks(this._settings.player.songBookDipDuration,this._currentTempo));return void this.generateSongBookWhammyOrBend(t,n,!0,[a[0].value,a[1].value,a[2].value],e,o)}break;case C.Hold:case C.Predive:l=a;break;case C.PrediveDive:switch(e.whammyStyle){case h.Default:l=a;break;case h.Gradual:l.push(new be(0,a[0].value)),l.push(new be(be.MaxPosition/2|0,a[0].value)),l.push(new be(be.MaxPosition,a[1].value));break;case h.Fast:const e=Cs.getPitchWheel(a[0].value);this._handler.addBend(r.index,t,s,0|e);const i=Math.min(n,ye.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,l,o)}generateWhammyOrBend(e,t,i,s){const a=t/be.MaxPosition;for(let t=0;t<i.length-1;t++){const r=i[t],n=i[t+1],o=Cs.getPitchWheel(r.value),h=Cs.getPitchWheel(n.value),l=a*(n.offset-r.offset),d=e+a*r.offset;this.generateBendValues(d,l,o,h,s)}}generateBendValues(e,t,i,s,a){const r=ye.ticksToMillis(t,this._currentTempo),n=Math.abs(s-i)/Cs.PitchValuePerSemitone,o=Math.max(Cs.MinBreakpointsPerSemitone*n,r/Cs.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=ye.toTicks(e.trillSpeed),l=!0,d=t,c=t+i.untilTieOrSlideEnd;for(;d+10<c;)d+h>=c&&(h=c-d),this._handler.addNote(n.index,d,h,l?o:s,a,r),l=!l,d+=h}generateTremoloPicking(e,t,i,s,a,r){const n=e.beat.voice.bar.staff.track;let o=ye.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;0!=(i&1<<n)&&(t[n]=a,a+=r)}}}return t}generateAutomation(e,t,i){switch(t.type){case a.Instrument:this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,255&(0|t.value)),this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,255&(0|t.value));break;case a.Balance:let s=Cs.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,te.PanCoarse,s),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,te.PanCoarse,s);break;case a.Volume:let r=Cs.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.primaryChannel,te.VolumeCoarse,r),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+i,e.voice.bar.staff.track.playbackInfo.secondaryChannel,te.VolumeCoarse,r)}}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 a.Instrument:i=s.value;break;case a.Tempo:t=s.value}s=s.previousBeat}const r=e.voice.bar.staff.track,n=e.voice.bar.masterBar;-1===t&&(t=n.score.tempo),-1===i&&(i=r.playbackInfo.program);const o=r.playbackInfo.volume;this.generateTrack(r),this._handler.addTimeSignature(0,n.timeSignatureNumerator,n.timeSignatureDenominator),this._handler.addTempo(0,t);let h=Cs.toChannelShort(o);this._handler.addControlChange(0,0,r.playbackInfo.primaryChannel,te.VolumeCoarse,h),this._handler.addControlChange(0,0,r.playbackInfo.secondaryChannel,te.VolumeCoarse,h)}generateSingleBeat(e){this.prepareSingleBeat(e),this.generateBeat(e,-e.playbackStart,e.voice.bar)}generateSingleNote(e){this.prepareSingleBeat(e.beat),this.generateNote(e,0,e.beat.playbackDuration,new Int32Array(e.beat.voice.bar.staff.tuning.length))}}Cs.DefaultDurationDead=30,Cs.DefaultDurationPalmMute=80,Cs.PitchBendRangeInSemitones=16,Cs.PitchValuePerSemitone=Gt.DefaultPitchWheel/Cs.PitchBendRangeInSemitones,Cs.MinBreakpointsPerSemitone=6,Cs.MillisecondsPerBreakpoint=150;class Fs{constructor(){this.startTick=0,this.endTick=0}}class Ls{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 Ms extends Ls{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Ds extends Ms{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 Is extends Ds{constructor(e,t,i,s){super(e,t,s?Is.GraceScale:1,Is.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?Is.GraceScale:1)*this.scale;switch(this._duration){case u.QuadrupleWhole:this.width=14*e;break;case u.DoubleWhole:case u.Whole:this.width=14*(this._isGrace?Is.GraceScale:1)*this.scale;break;default:this.width=Is.QuarterNoteHeadWidth*(this._isGrace?Is.GraceScale:1)*this.scale}this.height=Is.NoteHeadHeight*e}static getSymbol(e){switch(e){case u.QuadrupleWhole:return x.NoteheadDoubleWholeSquare;case u.DoubleWhole:return x.NoteheadDoubleWhole;case u.Whole:return x.NoteheadWhole;case u.Half:return x.NoteheadHalf;default:return x.NoteheadBlack}}}Is.GraceScale=.75,Is.NoteHeadHeight=8,Is.QuarterNoteHeadWidth=9;class Rs extends Ds{constructor(e,t,i,s,a){super(e,t,a?Is.GraceScale:1,Rs.getSymbol(i,s,a))}doLayout(){this.width=0}static getSymbol(e,t,i){if(i&&(e=u.Eighth),t===H.Up)switch(e){case u.Eighth:return x.FlagEighthUp;case u.Sixteenth:return x.FlagSixteenthUp;case u.ThirtySecond:return x.FlagThirtySecondUp;case u.SixtyFourth:return x.FlagSixtyFourthUp;case u.OneHundredTwentyEighth:return x.FlagOneHundredTwentyEighthUp;case u.TwoHundredFiftySixth:return x.FlagTwoHundredFiftySixthUp;default:return x.FlagEighthUp}switch(e){case u.Eighth:return x.FlagEighthDown;case u.Sixteenth:return x.FlagSixteenthDown;case u.ThirtySecond:return x.FlagThirtySecondDown;case u.SixtyFourth:return x.FlagSixtyFourthDown;case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:return x.FlagOneHundredTwentyEighthDown;default:return x.FlagEighthDown}}}Rs.FlagWidth=11;class As extends Ls{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+=As.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!==g.None)&&(i+=Rs.FlagWidth*this.scale*(this.beat.graceType!==g.None?Is.GraceScale:1));for(const e of this.ties)i+=e.width;this.beat.graceType!==g.None&&(i+=As.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+=As.GraceBeatPadding*this.renderer.scale),this.preNotes.x=t,this.preNotes.width=e.getPreBeatSize(this.beat),this.onNotes.width=e.getOnBeatSize(this.beat),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.updateBeamingHelper(),this.updateWidth()}doLayout(){this.preNotes.x=0,this.preNotes.renderer=this.renderer,this.preNotes.container=this,this.preNotes.doLayout(),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.renderer=this.renderer,this.onNotes.container=this,this.onNotes.doLayout();let e=this.beat.notes.length-1;for(;e>=0;)this.createTies(this.beat.notes[e--]);this.renderer.registerTies(this.ties),this.updateWidth()}updateWidth(){if(this.minWidth=this.preNotes.width+this.onNotes.width,!this.beat.isRest)if(1===this.onNotes.beamingHelper.beats.length)this.beat.duration>=u.Eighth&&(this.minWidth+=20*this.scale);else switch(this.beat.duration){case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:this.minWidth+=10*this.scale}let e=0;for(let t of this.ties)t.width>e&&(e=t.width);this.minWidth+=e,this.width=this.minWidth}scaleToWidth(e){this.onNotes.updateBeamingHelper(),this.width=e}createTies(e){}static getGroupId(e){return"b"+e.id}paint(e,t,i){if(this.beat.voice.isEmpty)return;if(this.preNotes.isEmpty&&this.onNotes.isEmpty&&0===this.ties.length)return;i.beginGroup(As.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 ps;a.beat=this.beat,a.visualBounds=new at,a.visualBounds.x=t+this.x+this.onNotes.x,a.visualBounds.y=e.visualBounds.y,a.visualBounds.w=this.onNotes.width,a.visualBounds.h=e.visualBounds.h,a.realBounds=new at,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,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)}}As.GraceBeatPadding=3;class Os{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new fo}causeIssue(){return this.settings=null,!0}}class Gs{constructor(e){this.activeBeats=e}}class Vs{constructor(e){this.bounds=null,this.beat=e}}class Hs{constructor(e,t){this._startTime=0,this._trackIndexes=null,this._isDestroyed=!1,this.score=null,this.tracks=[],this._tickCache=null,this.player=null,this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null,this._previousTick=0,this._playerState=q.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=q.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new mi,this.activeBeatsChanged=new mi,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new mi,this.beatMouseMove=new mi,this.beatMouseUp=new mi,this.noteMouseDown=new mi,this.noteMouseMove=new mi,this.noteMouseUp=new mi,this.scoreLoaded=new mi,this.resize=new mi,this.renderStarted=new mi,this.renderFinished=new mi,this.postRenderFinished=new fi,this.error=new mi,this.playerReady=new fi,this.playerFinished=new fi,this.soundFontLoaded=new fi,this.midiLoad=new mi,this.midiLoaded=new mi,this.playerStateChanged=new mi,this.playerPositionChanged=new mi,this.midiEventsPlayed=new mi,this.playbackRangeChanged=new mi,this.settingsUpdated=new fi,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),Be.logLevel=this.settings.core.logLevel,this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&go.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new bs(this.settings),this.container.resize.on(go.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));let i=new Os;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;Be.debug("rendering","Rendering completed in "+e+"ms"),this.onPostRenderFinished()})),this.renderer.preRender.on((e=>{this._startTime=Date.now()})),this.renderer.partialLayoutFinished.on(this.appendRenderResult.bind(this)),this.renderer.partialRenderFinished.on(this.updateRenderResult.bind(this)),this.renderer.renderFinished.on((e=>{this.appendRenderResult(e),this.appendRenderResult(null)})),this.renderer.error.on(this.onError.bind(this)),this.settings.player.enablePlayer&&this.setupPlayer(),this.setupClickHandling(),this.uiFacade.beginInvoke((()=>{this.uiFacade.initialRender()}))}destroy(){this._isDestroyed=!0,this.player&&this.player.destroy(),this.uiFacade.destroy(),this.renderer.destroy()}updateSettings(){const e=this.score;e&&ke.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?this.setupPlayer():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(e){if(e.length>0){let t=e[0].score;for(let s of e)if(s.score!==t)return void this.onError(new pe(i.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(t,e)}}internalRenderTracks(e,t){if(ke.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.onScoreLoaded(e),this.loadMidiForScore(),this.render()}else{this.tracks=t,this._trackIndexes=[];for(let e of t)this._trackIndexes.push(e.index);this.render()}}triggerResize(){if(this.container.isVisible){let e=new Os;e.oldWidth=this.renderer.width,e.newWidth=this.container.width,e.settings=this.settings,this.onResize(e),this.renderer.updateSettings(this.settings),this.renderer.width=this.container.width,this.renderer.resizeRender()}else Be.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{Be.debug("Rendering","AlphaTab container became visible, doing autosizing",null),this.triggerResize()}))}appendRenderResult(e){e?(this.canvasElement.width=e.totalWidth,this.canvasElement.height=e.totalHeight,this._cursorWrapper&&(this._cursorWrapper.width=e.totalWidth,this._cursorWrapper.height=e.totalHeight),(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 et;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:q.Paused}get masterVolume(){return this.player?this.player.masterVolume:0}set masterVolume(e){this.player&&(this.player.masterVolume=e)}get metronomeVolume(){return this.player?this.player.metronomeVolume:0}set metronomeVolume(e){this.player&&(this.player.metronomeVolume=e)}get countInVolume(){return this.player?this.player.countInVolume:0}set countInVolume(e){this.player&&(this.player.countInVolume=e)}get midiEventsPlayedFilter(){return this.player?this.player.midiEventsPlayedFilter:[]}set midiEventsPlayedFilter(e){this.player&&(this.player.midiEventsPlayedFilter=e)}get tickPosition(){return this.player?this.player.tickPosition:0}set tickPosition(e){this.player&&(this.player.tickPosition=e)}get timePosition(){return this.player?this.player.timePosition:0}set timePosition(e){this.player&&(this.player.timePosition=e)}get playbackRange(){return this.player?this.player.playbackRange:null}set playbackRange(e){this.player&&(this.player.playbackRange=e,this.settings.player.enableCursor&&this.updateSelectionCursor(e))}get playbackSpeed(){return this.player?this.player.playbackSpeed:0}set playbackSpeed(e){this.player&&(this.player.playbackSpeed=e)}get isLooping(){return!!this.player&&this.player.isLooping}set isLooping(e){this.player&&(this.player.isLooping=e)}destroyPlayer(){this.player&&(this.player.destroy(),this.player=null,this._previousTick=0,this._playerState=q.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;Be.debug("AlphaTab","Generating Midi");let e=new _i,t=new ws(e),i=new Cs(this.score,this.settings,t);i.generate(),this._tickCache=i.tickLookup,this.onMidiLoad(e),this.player.loadMidiFile(e)}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 _i,i=new ws(t);new Cs(e.voice.bar.staff.track.score,this.settings,i).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;let t=new _i,i=new ws(t);new Cs(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=q.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===q.Paused){let e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getBeatStart(e.currentBeat))}})))}cursorUpdateTick(e,t,i=!1){let s=this._tickCache;if(s){let a=this.tracks;if(a.length>0){let r=s.findBeat(a,e,this._currentBeat);r&&this.cursorUpdateBeat(r,t,i)}}}cursorUpdateBeat(e,t,i,s=!1){const a=e.currentBeat,r=e.nextBeat,n=e.duration,o=e.beatsToHighlight;if(!a)return;let h=this.renderer.boundsLookup;if(!h)return;let l=this._currentBeat,d=this._previousCursorCache,c=this._previousStateForCursor;if(!s&&a===(null==l?void 0:l.currentBeat)&&h===d&&c===this._playerState)return;let u=h.findBeat(a);u&&(this._currentBeat=e,this._previousCursorCache=h,this._previousStateForCursor=this._playerState,this.uiFacade.beginInvoke((()=>{this.internalCursorUpdateBeat(a,r,n,t,o,h,u,i)})))}scrollToCursor(){const e=this._currentBarBounds;e&&this.internalScrollToCursor(e)}internalScrollToCursor(e){let t=this.uiFacade.getScrollContainer(),i=go.getLayoutEngineFactory(this.settings.display.layoutMode).vertical,s=this.settings.player.scrollMode;if(i){let i=e.realBounds.y+this.settings.player.scrollOffsetY;if(i!==this._lastScroll)switch(this._lastScroll=i,s){case ee.Continuous:let s=this.uiFacade.getOffset(t,this.container);this.uiFacade.scrollToY(t,s.y+i,this.settings.player.scrollSpeed);break;case ee.OffScreen:let a=t.scrollTop+this.uiFacade.getOffset(null,t).h;if(e.visualBounds.y+e.visualBounds.h>=a||e.visualBounds.y<t.scrollTop){let i=e.realBounds.y+this.settings.player.scrollOffsetY;this.uiFacade.scrollToY(t,i,this.settings.player.scrollSpeed)}}}else{let i=e.visualBounds.x;if(i!==this._lastScroll)switch(this._lastScroll=i,s){case ee.Continuous:let i=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,i,this.settings.player.scrollSpeed);break;case ee.OffScreen:let s=t.scrollLeft+this.uiFacade.getOffset(null,t).w;if(e.visualBounds.x+e.visualBounds.w>=s||e.visualBounds.x<t.scrollLeft){let i=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,i,this.settings.player.scrollSpeed)}}}}internalCursorUpdateBeat(e,t,i,s,a,r,n,o){const h=this._barCursor,l=this._beatCursor;let d=n.barBounds.masterBarBounds,c=d.visualBounds;this._currentBarBounds=d,h&&h.setBounds(c.x,c.y,c.w,c.h),l&&(this.settings.player.enableAnimatedBeatCursor&&l.stopAnimation(),l.setBounds(n.visualBounds.x,c.y,1,c.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let u=!1;if(this._playerState===q.Playing&&!s){if(this.settings.player.enableElementHighlighting)for(let t of a){let i=As.getGroupId(t);this.uiFacade.highlightElements(i,e.voice.bar.index)}if(this.settings.player.enableAnimatedBeatCursor){let s=d.visualBounds.x+d.visualBounds.w;if(t&&(t.voice.bar.index===e.voice.bar.index&&t.index>e.index||t.voice.bar.index===e.voice.bar.index+1)){let e=r.findBeat(t);e&&e.barBounds.masterBarBounds.staveGroupBounds===d.staveGroupBounds&&(s=e.visualBounds.x)}this.uiFacade.beginInvoke((()=>{l&&l.transitionToX(i/this.playbackSpeed,s)}))}o=!s,u=!0}o&&!this._beatMouseDown&&this.settings.player.scrollMode!==ee.Off&&this.internalScrollToCursor(d),u&&(this.onPlayedBeatChanged(e),this.onActiveBeatsChanged(new Gs(a)))}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 Vs(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 Vs(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){var i,s,a,r;if(!this._isDestroyed){if(this.settings.player.enableUserInteraction){if(this._selectionEnd){let e=null!==(s=null===(i=this._tickCache)||void 0===i?void 0:i.getBeatStart(this._selectionStart.beat))&&void 0!==s?s:this._selectionStart.beat.absolutePlaybackStart;if((null!==(r=null===(a=this._tickCache)||void 0===a?void 0:a.getBeatStart(this._selectionEnd.beat))&&void 0!==r?r: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===q.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 Fs;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.tracks,e.startTick),i=this._tickCache.findBeat(this.tracks,e.endTick);if(t&&i){const e=new Vs(t.currentBeat),s=new Vs(i.currentBeat);this.cursorSelectRange(e,s)}}else this.cursorSelectRange(null,null)}setupClickHandling(){this.canvasElement.mouseDown.on((e=>{var t,i,s;if(!e.isLeftMouseButton)return;this.settings.player.enableUserInteraction&&e.preventDefault();let a=e.getX(this.canvasElement),r=e.getY(this.canvasElement),n=null!==(i=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(a,r))&&void 0!==i?i:null;if(n&&(this.onBeatMouseDown(e,n),this.settings.core.includeNoteBounds)){const t=null===(s=this.renderer.boundsLookup)||void 0===s?void 0:s.getNoteAtPos(n,a,r);t&&this.onNoteMouseDown(e,t)}})),this.canvasElement.mouseMove.on((e=>{var t,i,s;if(!this._beatMouseDown)return;let a=e.getX(this.canvasElement),r=e.getY(this.canvasElement),n=null!==(i=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(a,r))&&void 0!==i?i:null;if(n&&(this.onBeatMouseMove(e,n),this._noteMouseDown)){const t=null===(s=this.renderer.boundsLookup)||void 0===s?void 0:s.getNoteAtPos(n,a,r);t&&this.onNoteMouseMove(e,t)}})),this.canvasElement.mouseUp.on((e=>{var t,i,s,a;if(!this._beatMouseDown)return;this.settings.player.enableUserInteraction&&e.preventDefault();let r=e.getX(this.canvasElement),n=e.getY(this.canvasElement),o=null!==(i=null===(t=this.renderer.boundsLookup)||void 0===t?void 0:t.getBeatAtPos(r,n))&&void 0!==i?i:null;if(this.onBeatMouseUp(e,o),this._noteMouseDown)if(o){const t=null!==(a=null===(s=this.renderer.boundsLookup)||void 0===s?void 0:s.getNoteAtPos(o,r,n))&&void 0!==a?a:null;this.onNoteMouseUp(e,t)}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){var i,s,a,r;let n=this.renderer.boundsLookup;if(!n)return;let o=this._selectionWrapper;if(!o)return;if(o.clear(),!e||!t||e.beat===t.beat)return;e.bounds||(e.bounds=n.findBeat(e.beat)),t.bounds||(t.bounds=n.findBeat(t.beat));let h=null!==(s=null===(i=this._tickCache)||void 0===i?void 0:i.getBeatStart(e.beat))&&void 0!==s?s:e.beat.absolutePlaybackStart;if((null!==(r=null===(a=this._tickCache)||void 0===a?void 0:a.getBeatStart(t.beat))&&void 0!==r?r:t.beat.absolutePlaybackStart)<h){let i=e;e=t,t=i}let l=e.bounds.realBounds.x,d=t.bounds.realBounds.x+t.bounds.realBounds.w;if(t.beat.index===t.beat.voice.beats.length-1&&(d=t.bounds.barBounds.masterBarBounds.realBounds.x+t.bounds.barBounds.masterBarBounds.realBounds.w),e.bounds.barBounds.masterBarBounds.staveGroupBounds!==t.bounds.barBounds.masterBarBounds.staveGroupBounds){let i=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x,s=e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.x+e.bounds.barBounds.masterBarBounds.staveGroupBounds.visualBounds.w,a=this.uiFacade.createSelectionElement();a.setBounds(l,e.bounds.barBounds.masterBarBounds.visualBounds.y,s-l,e.bounds.barBounds.masterBarBounds.visualBounds.h),o.appendChild(a);let r=e.bounds.barBounds.masterBarBounds.staveGroupBounds.index+1,h=t.bounds.barBounds.masterBarBounds.staveGroupBounds.index;for(let e=r;e<h;e++){let t=n.staveGroups[e],a=this.uiFacade.createSelectionElement();a.setBounds(i,t.visualBounds.y,s-i,t.visualBounds.h),o.appendChild(a)}let c=this.uiFacade.createSelectionElement();c.setBounds(i,t.bounds.barBounds.masterBarBounds.visualBounds.y,d-i,t.bounds.barBounds.masterBarBounds.visualBounds.h),o.appendChild(c)}else{let t=this.uiFacade.createSelectionElement();t.setBounds(l,e.bounds.barBounds.masterBarBounds.visualBounds.y,d-l,e.bounds.barBounds.masterBarBounds.visualBounds.h),o.appendChild(t)}}onScoreLoaded(e){this._isDestroyed||(this.scoreLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"scoreLoaded",e))}onResize(e){this._isDestroyed||(this.resize.trigger(e),this.uiFacade.triggerEvent(this.container,"resize",e))}onRenderStarted(e){this._isDestroyed||(this.renderStarted.trigger(e),this.uiFacade.triggerEvent(this.container,"renderStarted",e))}onRenderFinished(e){this._isDestroyed||(this.renderFinished.trigger(e),this.uiFacade.triggerEvent(this.container,"renderFinished",e))}onPostRenderFinished(){this._isDestroyed||(this.postRenderFinished.trigger(),this.uiFacade.triggerEvent(this.container,"postRenderFinished",null))}onError(e){this._isDestroyed||(Be.error("API","An unexpected error occurred",e),this.error.trigger(e),this.uiFacade.triggerEvent(this.container,"error",e))}onPlayerReady(){this._isDestroyed||(this.playerReady.trigger(),this.uiFacade.triggerEvent(this.container,"playerReady",null))}onPlayerFinished(){this._isDestroyed||(this.playerFinished.trigger(),this.uiFacade.triggerEvent(this.container,"playerFinished",null))}onSoundFontLoaded(){this._isDestroyed||(this.soundFontLoaded.trigger(),this.uiFacade.triggerEvent(this.container,"soundFontLoaded",null))}onMidiLoad(e){this._isDestroyed||(this.midiLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"midiLoad",e))}onMidiLoaded(e){this._isDestroyed||(this.midiLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"midiFileLoaded",e))}onPlayerStateChanged(e){this._isDestroyed||(this.playerStateChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerStateChanged",e))}onPlayerPositionChanged(e){this._isDestroyed||null!==this.score&&this.tracks.length>0&&(this.playerPositionChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playerPositionChanged",e))}onMidiEventsPlayed(e){this._isDestroyed||(this.midiEventsPlayed.trigger(e),this.uiFacade.triggerEvent(this.container,"midiEventsPlayed",e))}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 Ws extends pe{constructor(e,t){super(i.General,e),this.xhr=t,Object.setPrototypeOf(this,Ws.prototype)}}class zs{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=zs.loadScoreFromBytes(i,s);t(r)}catch(e){i(e)}else 0===a.status?i(new Ws("You are offline!!\n Please Check Your Network.",a)):404===a.status?i(new Ws("Requested URL not found.",a)):500===a.status?i(new Ws("Internel Server Error.",a)):"parsererror"===a.statusText?i(new Ws("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?i(new Ws("Request Time out.",a)):i(new Ws("Unknow Error: "+a.responseText,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new Wi);let i=go.buildImporters();Be.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{Be.debug("ScoreLoader","Importing using importer "+e.name),e.init(a,t),s=e.readScore(),Be.debug("ScoreLoader","Score imported using "+e.name);break}catch(t){if(!(t instanceof ge))throw Be.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;Be.debug("ScoreLoader",e.name+" does not support the file")}}if(s)return s;throw Be.error("ScoreLoader","No compatible importer found for file"),new ge("No compatible importer found for file")}}class Us{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 Xs{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 at,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new Us(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new Us(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new Us(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&Xs.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,Xs.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=""}}Xs.resizeObserver=new _e((()=>new ResizeObserver((e=>{for(const t of e){let e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class Ys{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new mi,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(go.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0,t=window.setInterval((()=>{Be.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);Be.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);let i=e=>{this._families.length>1?(Be.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(Be.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},s=e=>{Be.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 Be.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){Be.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 qs{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 Js{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new fi,this.samplesPlayed=new mi,this.sampleRequest=new fi}get sampleRate(){return this._context?this._context.sampleRate:Js.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(Be.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{var t,i;Be.debug("WebAudio",`Audio Context resume success: state=${null===(t=this._context)||void 0===t?void 0:t.state}, sampleRate:${null===(i=this._context)||void 0===i?void 0:i.sampleRate}`),e&&e()}),(e=>{var t,i;Be.warning("WebAudio",`Audio Context resume failed: state=${null===(t=this._context)||void 0===t?void 0:t.state}, sampleRate:${null===(i=this._context)||void 0===i?void 0:i.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,Js.PreferredSampleRate),i=e.createBufferSource();i.buffer=t,i.connect(e.destination),i.start(0),i.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in go.globalThis)return new AudioContext;if("webkitAudioContext"in go.globalThis)return new webkitAudioContext;throw new pe(i.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,Js.BufferSize,e.sampleRate),this._source=e.createBufferSource(),this._source.buffer=this._buffer,this._source.loop=!0}pause(){this._source&&(this._source.stop(0),this._source.disconnect()),this._source=null}destroy(){var e;this.pause(),null===(e=this._context)||void 0===e||e.close(),this._context=null,this.unregisterResumeHandler()}onSamplesPlayed(e){this.samplesPlayed.trigger(e)}onSampleRequest(){this.sampleRequest.trigger()}onReady(){this.ready.trigger()}}Js.BufferSize=4096,Js.PreferredSampleRate=44100;class js extends Js{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/Js.BufferSize),this._circularBuffer=new qs(Js.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*Js.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*Js.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/Gt.AudioChannels),this.requestBuffers()}}class Qs{constructor(e,t){this.loaded=e,this.total=t}}class $s{get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return Be.logLevel}set logLevel(e){Be.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Gt.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Gt.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Gt.MinVolume),this._countInVolume=e,this._synth.postMessage({cmd:"alphaSynth.setCountInVolume",value:e})}get midiEventsPlayedFilter(){return this._midiEventsPlayedFilter}set midiEventsPlayedFilter(e){this._midiEventsPlayedFilter=e,this._synth.postMessage({cmd:"alphaSynth.setMidiEventsPlayedFilter",value:e})}get playbackSpeed(){return this._playbackSpeed}set playbackSpeed(e){e=ni.clamp(e,Gt.MinPlaybackSpeed,Gt.MaxPlaybackSpeed),this._playbackSpeed=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackSpeed",value:e})}get tickPosition(){return this._tickPosition}set tickPosition(e){e<0&&(e=0),this._tickPosition=e,this._synth.postMessage({cmd:"alphaSynth.setTickPosition",value:e})}get timePosition(){return this._timePosition}set timePosition(e){e<0&&(e=0),this._timePosition=e,this._synth.postMessage({cmd:"alphaSynth.setTimePosition",value:e})}get isLooping(){return this._isLooping}set isLooping(e){this._isLooping=e,this._synth.postMessage({cmd:"alphaSynth.setIsLooping",value:e})}get playbackRange(){return this._playbackRange}set playbackRange(e){e&&(e.startTick<0&&(e.startTick=0),e.endTick<0&&(e.endTick=0)),this._playbackRange=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackRange",value:e})}constructor(e,t,i,s){this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=q.Paused,this._masterVolume=0,this._metronomeVolume=0,this._countInVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._midiEventsPlayedFilter=[],this.ready=new fi,this.readyForPlayback=new fi,this.finished=new fi,this.soundFontLoaded=new fi,this.soundFontLoadFailed=new mi,this.midiLoaded=new mi,this.midiLoadFailed=new mi,this.stateChanged=new mi,this.positionChanged=new mi,this.midiEventsPlayed=new mi,this.playbackRangeChanged=new mi,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=q.Paused,this._masterVolume=0,this._metronomeVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._output=e,this._output.ready.on(this.onOutputReady.bind(this)),this._output.samplesPlayed.on(this.onOutputSamplesPlayed.bind(this)),this._output.sampleRequest.on(this.onOutputSampleRequest.bind(this)),this._output.open(s);try{this._synth=go.createAlphaTabWorker(t)}catch(e){Be.error("AlphaSynth","Failed to create WebWorker: "+e)}this._synth.addEventListener("message",this.handleWorkerMessage.bind(this),!1),this._synth.postMessage({cmd:"alphaSynth.initialize",sampleRate:this._output.sampleRate,logLevel:i,bufferTimeInMilliseconds:s}),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:os.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,i){Be.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=>{Be.error("AlphaSynth","Loading failed: "+e.message),this.soundFontLoadFailed.trigger(new Ws(e.message,s))},s.onprogress=e=>{Be.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),i(new Qs(e.loaded,e.total))},s.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:os.midiFileToJsObject(e)})}setChannelMute(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelMute",channel:e,mute:t})}resetChannelStates(){this._synth.postMessage({cmd:"alphaSynth.resetChannelStates"})}setChannelSolo(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelSolo",channel:e,solo:t})}setChannelVolume(e,t){t=Math.max(t,Gt.MinVolume),this._synth.postMessage({cmd:"alphaSynth.setChannelVolume",channel:e,volume:t})}handleWorkerMessage(e){let t=e.data;switch(t.cmd){case"alphaSynth.ready":this._workerIsReady=!0,this.checkReady();break;case"alphaSynth.destroyed":this._synth.terminate();break;case"alphaSynth.readyForPlayback":this._workerIsReadyForPlayback=!0,this.checkReadyForPlayback();break;case"alphaSynth.positionChanged":this._timePosition=t.currentTime,this._tickPosition=t.currentTick,this.positionChanged.trigger(new Ut(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new yi(t.events.map(os.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new zt(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new bi(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 Ut(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiLoadFailed":this.checkReadyForPlayback(),this.midiLoadFailed.trigger(t.error);break;case"alphaSynth.output.addSamples":this._output.addSamples(t.samples);break;case"alphaSynth.output.play":this._output.play();break;case"alphaSynth.output.pause":this._output.pause();break;case"alphaSynth.output.destroy":this._output.destroy();break;case"alphaSynth.output.resetSamples":this._output.resetSamples()}}checkReady(){this.isReady&&this.ready.trigger()}checkReadyForPlayback(){this.isReadyForPlayback&&this.readyForPlayback.trigger()}onOutputSampleRequest(){this._synth.postMessage({cmd:"alphaSynth.output.sampleRequest"})}onOutputSamplesPlayed(e){this._synth.postMessage({cmd:"alphaSynth.output.samplesPlayed",samples:e})}onOutputReady(){this._outputIsReady=!0,this.checkReady()}}class Ks{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new mi,this.partialRenderFinished=new mi,this.partialLayoutFinished=new mi,this.renderFinished=new mi,this.postRenderFinished=new fi,this.error=new mi,this._api=e;try{this._worker=go.createAlphaTabWorker(t.core.scriptFile)}catch(e){return void Be.error("Rendering",`Failed to create WebWorker: ${e}`)}this._worker.postMessage({cmd:"alphaTab.initialize",settings:this.serializeSettingsForWorker(t)}),this._worker.addEventListener("message",this.handleWorkerMessage.bind(this))}destroy(){this._worker.terminate()}updateSettings(e){this._worker.postMessage({cmd:"alphaTab.updateSettings",settings:this.serializeSettingsForWorker(e)})}serializeSettingsForWorker(e){const t=os.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=ys.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:os.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:i,trackIndexes:t,fontSizes:ds.FontSizeLookupTables})}}class Zs{constructor(e,t,i,s){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=i,this.selectionWrapper=s}}!function(e){e[e.Browser=0]="Browser",e[e.NodeJs=1]="NodeJs",e[e.BrowserModule=2]="BrowserModule"}(ie||(ie={}));class ea{static init(){var e;ea._isRegistered||(ea._isRegistered=!0,registerProcessor("alphatab",((e=class e extends AudioWorkletProcessor{constructor(t){super(t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,Be.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new qs(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){let t=e.data;switch(t.cmd){case hs.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case hs.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:hs.CmdOutputSamplesPlayed,samples:o/Gt.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:hs.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}ea._isRegistered=!1;class ta extends Js{constructor(){super(...arguments),this._worklet=null,this._bufferTimeInMilliseconds=0}open(e){super.open(e),this._bufferTimeInMilliseconds=e,this.onReady()}play(){super.play();let e=this._context;e.audioWorklet.addModule(go.scriptFile).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=>{Be.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){let t=e.data;switch(t.cmd){case hs.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case hs.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){var t;null===(t=this._worklet)||void 0===t||t.port.postMessage({cmd:hs.CmdOutputAddSamples,samples:e})}resetSamples(){var e;null===(e=this._worklet)||void 0===e||e.port.postMessage({cmd:hs.CmdOutputResetSamples})}}class ia extends Xs{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"}(se||(se={}));class sa{get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(go.bravuraFontChecker.checkForFontAvailability(),!go.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(Be.debug("Font","All fonts loaded: "+this._fontCheckers.size),!0)}onFontLoaded(e){ds.generateFontLookup(e),this.areAllFontsLoaded()&&this.canRenderChanged.trigger()}constructor(e){if(this._fontCheckers=new Map,this._contents=null,this._file=null,this._totalResultCount=0,this._initialTrackIndexes=null,this._barToElementLookup=new Map,this._resultIdToElementLookup=new Map,this.rootContainerBecameVisible=new fi,this.canRenderChanged=new fi,this._highlightedElements=[],this._scrollContainer=null,go.webPlatform!==ie.Browser&&go.webPlatform!==ie.BrowserModule)throw new pe(i.General,"Usage of AlphaTabApi is only possible in browser environments. For usage in node use the Low Level APIs");e.classList.add("alphaTab"),this.rootContainer=new Xs(e),this.areWorkersSupported="Worker"in window,go.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(e)}onElementVisibilityChanged(e){for(const t of e){const e=t.target;if(e===this.rootContainer.element)t.isIntersecting&&(this.rootContainerBecameVisible.trigger(),this._intersectionObserver.unobserve(this.rootContainer.element));else if("layoutResultId"in e&&this._api.settings.core.enableLazyLoading){const i=e;t.isIntersecting?i.renderedResultId!==i.layoutResultId?this._resultIdToElementLookup.has(i.layoutResultId)?i.resultState!==se.RenderRequested&&(Be.warning("Rendering","Outside Request render of lazy partial "+i.layoutResultId),i.resultState=se.RenderRequested,this._api.renderer.renderResult(i.layoutResultId)):e.replaceChildren():i.resultState===se.Detached&&(e.replaceChildren(...i.renderedResult),i.resultState=se.RenderDone):i.resultState===se.RenderDone&&(i.resultState=se.Detached,i.replaceChildren())}}}createWorkerRenderer(){return new Ks(this._api,this._api.settings)}initialize(e,t){let i;this._api=e,i=t instanceof Wi?t:os.jsObjectToSettings(t);let s=this.getDataAttributes();Hi.fromJson(i,s),i.notation.notationMode===T.SongBook&&i.setSongBookModeSettings(),e.settings=i,this.setupFontCheckers(i),this._initialTrackIndexes=this.parseTracks(i.core.tracks),this._contents="";let a=e.container;i.core.tex&&(this._contents=a.element.innerHTML,a.element.innerHTML=""),this.createStyleElement(i),this._file=i.core.file}setupFontCheckers(e){this.registerFontChecker(e.display.resources.copyrightFont),this.registerFontChecker(e.display.resources.effectFont),this.registerFontChecker(e.display.resources.fingeringFont),this.registerFontChecker(e.display.resources.graceFont),this.registerFontChecker(e.display.resources.markerFont),this.registerFontChecker(e.display.resources.tablatureFont),this.registerFontChecker(e.display.resources.titleFont),this.registerFontChecker(e.display.resources.wordsFont),this.registerFontChecker(e.display.resources.barNumberFont),this.registerFontChecker(e.display.resources.fretboardNumberFont),this.registerFontChecker(e.display.resources.subTitleFont)}registerFontChecker(e){if(!this._fontCheckers.has(e.families.join(", "))){let t=new Ys(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 Xs(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 He)return t(e),!0;if(e instanceof ArrayBuffer){let i=new Uint8Array(e);return t(zs.loadScoreFromBytes(i,this._api.settings)),!0}return e instanceof Uint8Array?(t(zs.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(zs.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=()=>{var e;this._api.renderer.width=0|this.rootContainer.width,this._api.renderer.updateSettings(this._api.settings),this._contents?(this._api.tex(this._contents,null!==(e=this._initialTrackIndexes)&&void 0!==e?e:void 0),this._initialTrackIndexes=null):this._file&&zs.loadScoreAsync(this._file,(e=>{var t;this._api.renderScore(e,null!==(t=this._initialTrackIndexes)&&void 0!==t?t:void 0),this._initialTrackIndexes=null}),(e=>{this._api.onError(e)}),this._api.settings)};this.rootContainer.isVisible?e():this.rootContainerBecameVisible.on(e)}createStyleElement(e){let t=this._api.container.element.ownerDocument;go.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=se.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=se.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 e=go.scriptFile;if(!e)return Be.error("Player","alphaTab script file could not be detected, player cannot initialize"),null;let t=null,i="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window&&!go.isWebPackBundled?(Be.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),t=new $s(new ta,e,this._api.settings.core.logLevel,this._api.settings.player.bufferTimeInMilliseconds)):i&&(Be.debug("Player","Will use webworkers for synthesizing and web audio api for playback"),t=new $s(new js,e,this._api.settings.core.logLevel,this._api.settings.player.bufferTimeInMilliseconds)),t?t.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):Be.error("Player","Player requires webworkers and web audio api, browser unsupported",null),t}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const 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 Zs(new Xs(t),s,a,new Xs(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 at;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 Xs(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new ia(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 aa extends Hs{constructor(e,t){super(new sa(e),t),this.soundFontLoad=new mi}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.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,d=a.offsetWidth+50,c=window.innerHeight,u=(h/2|0)-(d/2|0)+n,p=(l/2|0)-(c/2|0)+o;s.resizeTo(d,c),s.moveTo(u,p),s.focus();let g=os.jsObjectToSettings(os.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,Hi.fromJson(g,i);let f=new aa(a,g);s.onunload=()=>{f.destroy()},f.renderer.postRenderFinished.on((()=>{s.print()})),f.renderTracks(this.tracks)}downloadMidi(){if(!this.score)return;let e=new _i,t=new ws(e);new Cs(this.score,this.settings,t).generate();let i=e.toBinary(),s=this.score.title?`${this.score.title}.mid`:"File.mid",a=document.createElement("a");a.download=s;let r=new Blob([i],{type:"audio/midi"}),n=URL.createObjectURL(r);a.href=n,a.style.display="none",document.body.appendChild(a),a.click(),document.body.removeChild(a)}changeTrackMute(e,t){let 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 ra{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 Be.error("Api","Method '"+t+"' does not exist on jQuery.alphaTab"),null}init(e,t,i){if(!t){t=new aa(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 na{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.color=new Ue(255,255,255,255),this.lineWidth=1,this.font=new Ni("Arial",10,K.Plain),this.textAlign=P.Left,this.textBaseline=E.Top}beginRender(e,t){this.buffer=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${0|e}px" height="${0|t}px" class="at-surface-svg">\n`,this._currentPath="",this._currentPathIsEmpty=!0,this.textBaseline=E.Top}beginGroup(e){this.buffer+=`<g class="${e}">`}endGroup(){this.buffer+="</g>"}endRender(){return this.buffer+="</svg>",this.buffer}fillRect(e,t,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!==P.Left&&(s+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),s+=`>${na.escapeText(e)}</text>`,this.buffer+=s}static escapeText(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}getSvgTextAlignment(e){switch(e){case P.Left:return"start";case P.Center:return"middle";case P.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case E.Top:return'dominant-baseline="hanging"';case E.Bottom:return'dominant-baseline="bottom"';default:return""}}measureText(e){return e?ds.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 oa extends na{constructor(){super()}fillMusicFontSymbol(e,t,i,s,a){s!==x.None&&this.fillMusicFontSymbolText(e,t,i,`&#${s};`,a)}fillMusicFontSymbols(e,t,i,s,a){let r="";for(let e of s)e!==x.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(P.Center)+'"'),this.buffer+=`>${s}</text></g>`}}class ha{constructor(){this.isInAccolade=!0,this.isRelevantForBoundsLookup=!0,this.hideOnMultiTrack=!1,this.hideOnPercussionTrack=!1}canCreate(e,t){return!this.hideOnPercussionTrack||!t.isPercussion}}!function(e){e[e.PreNotes=0]="PreNotes",e[e.OnNotes=1]="OnNotes",e[e.MiddleNotes=2]="MiddleNotes",e[e.Stem=3]="Stem",e[e.PostNotes=4]="PostNotes",e[e.EndBeat=5]="EndBeat"}(ae||(ae={}));class la extends Ls{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 da extends la{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 ca extends la{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===g.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)+As.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)}}ca.KeySizeBeat="Beat",function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Sharp=2]="Sharp",e[e.Flat=3]="Flat",e[e.NaturalQuarterNoteUp=4]="NaturalQuarterNoteUp",e[e.SharpQuarterNoteUp=5]="SharpQuarterNoteUp",e[e.FlatQuarterNoteUp=6]="FlatQuarterNoteUp",e[e.DoubleSharp=7]="DoubleSharp",e[e.DoubleFlat=8]="DoubleFlat"}(re||(re={}));class ua{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class pa{constructor(e){this._registeredAccidentals=new Map,this._appliedScoreLines=new Map,this._appliedScoreLinesByValue=new Map,this._notesByValue=new Map,this._beatLines=new Map,this.maxLineBeat=null,this.minLineBeat=null,this.maxLine=-1e3,this.minLine=-1e3,this._barRenderer=e,this._bar=e.bar}static getPercussionLine(e,t){var i,s;return t<e.staff.track.percussionArticulations.length?e.staff.track.percussionArticulations[t].staffLine:null!==(s=null===(i=Ne.getArticulationByValue(t))||void 0===i?void 0:i.staffLine)&&void 0!==s?s:0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case y.ForceDoubleFlat:t+=2;break;case y.ForceDoubleSharp:t-=2;break;case y.ForceFlat:t+=1;break;case y.ForceSharp:t-=1}return t}applyAccidental(e){const t=pa.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=pa.getNoteValue(t);if(e.staff.isPercussion)i=pa.getPercussionLine(e,s);else{const a=t?t.accidentalMode:y.Default;i=pa.calculateNoteLine(e,s,a)}return i}getAccidental(e,t,i,s,a=null){let r=re.None,n=0;if(this._bar.staff.isPercussion)n=pa.getPercussionLine(this._bar,e);else{const i=a?a.accidentalMode:y.Default;n=pa.calculateNoteLine(this._bar,e,i);let s=this._bar.masterBar.keySignature+7,o=e%12,h=s<7?re.Flat:re.Sharp,l=pa.KeySignatureLookup[s][o],d=pa.AccidentalNotes[o];if(t)switch(r=d?h:re.Natural,r){case re.Natural:r=re.NaturalQuarterNoteUp;break;case re.Sharp:r=re.SharpQuarterNoteUp;break;case re.Flat:r=re.FlatQuarterNoteUp}else{switch(i){case y.ForceSharp:r=re.Sharp;break;case y.ForceDoubleSharp:r=re.DoubleSharp;break;case y.ForceFlat:r=re.Flat;break;case y.ForceDoubleFlat:r=re.DoubleFlat;break;default:d?r=h:l&&(r=re.Natural)}let e=!1;if(a&&a.isTieDestination&&0===a.beat.index){const t=this._barRenderer.previousRenderer;if(t){t.accidentalHelper.getNoteLine(a.tieOrigin)===n&&(e=!0)}}e?r=re.None:r!==re.None?(this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===r&&(r=re.None):l&&r===h&&(r=re.None),r!==re.None&&this._registeredAccidentals.set(n,r)):this._registeredAccidentals.has(n)?this._registeredAccidentals.get(n)===re.Natural?r=re.None:(r=re.Natural,this._registeredAccidentals.set(n,r)):this._registeredAccidentals.delete(n)}}return a?(this._appliedScoreLines.set(a.id,n),this._notesByValue.set(e,a)):this._appliedScoreLinesByValue.set(e,n),(-1e3===this.minLine||this.minLine<n)&&(this.minLine=n,this.minLineBeat=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 ua,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=pa.OctaveSteps[r];return h-=o*pa.StepsPerOctave,h-=(ke.keySignatureIsSharp(a)||ke.keySignatureIsNatural(a)?pa.SharpNoteSteps:pa.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}}pa.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]],pa.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],pa.StepsPerOctave=7,pa.OctaveSteps=[38,32,30,26,38],pa.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],pa.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class ga{constructor(){this.staffId="",this.up=0,this.down=0}}class fa{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 ma{get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}get hasLine(){return 1===this.beats.length&&this.beats[0].duration>u.Whole}get hasFlag(){return 1===this.beats.length&&!this.beats[0].isRest&&(this.beats[0].duration>u.Quarter||this.beats[0].graceType!==g.None)}constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=u.QuadrupleWhole,this.fingeringCount=0,this.hasTuplet=!1,this._firstBeatLowestNoteCompareValue=-1,this._firstBeatHighestNoteCompareValue=-1,this._lastBeatLowestNoteCompareValue=-1,this._lastBeatHighestNoteCompareValue=-1,this.lowestNoteInHelper=null,this._lowestNoteCompareValueInHelper=-1,this.highestNoteInHelper=null,this._highestNoteCompareValueInHelper=-1,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isGrace=!1,this.minRestLine=null,this.beatOfMinRestLine=null,this.maxRestLine=null,this.beatOfMaxRestLine=null,this.direction=H.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}getBeatLineX(e){return this.hasBeatLineX(e)?this.direction===H.Up?this._beatLineXPositions.get(e.index).up:this._beatLineXPositions.get(e.index).down:0}hasBeatLineX(e){return this._beatLineXPositions.has(e.index)}registerBeatLineX(e,t,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 ga),this._beatLineXPositions.get(e.index)}finish(){this.direction=this.calculateDirection()}calculateDirection(){let e=null;if(this.voice?null!==this.preferredBeamDirection?e=this.preferredBeamDirection:this.voice.index>0?e=this.invert(H.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==g.None)&&(e=this.invert(H.Up)):e=H.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){let t=this._renderer.getNoteY(this.highestNoteInHelper,ne.Center),i=this._renderer.getNoteY(this.lowestNoteInHelper,ne.Center);if(null===e){const s=(t+i)/2;e=this.invert(this._renderer.middleYPosition<s?H.Up:H.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(H.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:return[2,2];case u.Whole:return[0,1];case u.Half:return[1,0];case u.Quarter:return[3,3];case u.Eighth:return[2,2];case u.Sixteenth:return[2,4];case u.ThirtySecond:return[4,4];case u.SixtyFourth:return[4,6];case u.OneHundredTwentyEighth:return[6,6];case u.TwoHundredFiftySixth:return[6,8]}return[0,0]}applyRest(e,t){if(this._lastNonRestBeat&&e.index>=this._lastNonRestBeat.index||this._firstNonRestBeat&&e.index<=this._firstNonRestBeat.index)return;let i=t,s=t;const a=ma.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===H.Down?H.Up:H.Down:e}checkBeat(e){e.invertBeamDirection&&(this.invertBeamDirection=!0),this.voice||(this.voice=e.voice);let t=!1;if(0===this.beats.length)t=!0;else switch(this.beats[this.beats.length-1].beamingMode){case F.Auto:t=ma.canJoin(this.beats[this.beats.length-1],e);break;case F.ForceSplitToNext:t=!1;break;case F.ForceMergeWithNext:t=!0}if(t){if(null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.isRest)0===this.beats.length&&this.beats.push(e);else{this.isRestBeamHelper&&(this.beats=[]),this.beats.push(e),e.graceType!==g.None&&(this.isGrace=!0),e.hasTuplet&&(this.hasTuplet=!0);let t=0;for(let i=0;i<e.notes.length;i++){let s=e.notes[i];s.leftHandFinger===f.Unknown&&s.rightHandFinger===f.Unknown||t++}t>this.fingeringCount&&(this.fingeringCount=t),this.checkNote(e.minNote),this.checkNote(e.maxNote),this.shortestDuration<e.duration&&(this.shortestDuration=e.duration),this._firstNonRestBeat||(this._firstNonRestBeat=e),this._lastNonRestBeat=e}e.hasTuplet&&(this.hasTuplet=!0)}return t}checkNote(e){if(!e)return;let t,i;this.voice&&e.isPercussion?(t=-pa.getPercussionLine(this.voice.bar,pa.getNoteValue(e)),i=t):(t=pa.getNoteValue(e),i=t,e.harmonicType!==m.None&&e.harmonicType!==m.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===g.BendGrace||t.graceType===g.BendGrace)return!1;if(e.graceType!==g.None&&t.graceType!==g.None)return!0;let i=e.voice.bar;if(i!==t.voice.bar)return!1;let s=e.playbackStart,a=t.playbackStart;if(!ma.canJoinDuration(e.duration)||!ma.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=ye.QuarterTime;if(8===i.masterBar.timeSignatureDenominator)i.masterBar.timeSignatureNumerator%3==0&&(r+=ye.QuarterTime/2|0);return(0|(r+s)/r)===(0|(r+a)/r)}static canJoinDuration(e){switch(e){case u.Whole:case u.Half:case u.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,i){return ke.getIndex(e.duration)-2-i>0&&ke.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 ya{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class ba{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new ya(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 Sa{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 ba(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=ma.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 _a{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this._renderer=e,this.collisionHelper=new Sa}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!==g.None?n=s:(n=i,s=null),n&&n.checkBeat(o)||(n&&n.finish(),n=new ma(t.staff,e),n.checkBeat(o),o.graceType!==g.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)}}!function(e){e[e.TopWithStem=0]="TopWithStem",e[e.Top=1]="Top",e[e.Center=2]="Center",e[e.Bottom=3]="Bottom",e[e.BottomWithStem=4]="BottomWithStem"}(ne||(ne={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(oe||(oe={}));class wa{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 da,this._voiceContainers=new Map,this._postBeatGlyphs=new da,this._ties=[],this.x=0,this.y=0,this.width=0,this.height=0,this.index=0,this.topOverflow=0,this.bottomOverflow=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this._wasFirstOfLine=!1,this._appliedLayoutingInfo=0,this.isFinalized=!1,this.topPadding=0,this.bottomPadding=0,this.scoreRenderer=e,this.bar=t,t&&(this.helpers=new _a(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 isFirstOfLine(){return 0===this.index}get isLast(){return!this.bar||this.bar.index===this.scoreRenderer.layout.lastBarIndex}registerLayoutingInfo(){let e=this.layoutingInfo,t=this._preBeatGlyphs.width;e.preBeatSize<t&&(e.preBeatSize=t);for(const t of this._voiceContainers.values())t.registerLayoutingInfo(e);let 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)}return this._postBeatGlyphs.x=Math.floor(e),this._postBeatGlyphs.width=this.layoutingInfo.postBeatSize,this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),!0}finalizeRenderer(){this.isFinalized=!0;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 da,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new da,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 ca(0,0,t);i.renderer=this,this._voiceContainers.set(this.bar.voices[e].index,i)}}this.bar.simileMark===o.SecondOfDouble&&(this.canWrap=!1),this.createPreBeatGlyphs(),this.createBeatGlyphs(),this.createPostBeatGlyphs(),this.updateSizes();for(const e of this.helpers.beamHelpers)for(const t of e)t.finish()}}hasVoiceContainer(e){return!e.isEmpty||0===e.index}updateSizes(){this.staff.registerStaffTop(this.topPadding),this.staff.registerStaffBottom(this.height-this.bottomPadding);let e=this._voiceContainers,t=this.beatGlyphsStart,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){var t,i;return null===(i=null===(t=this.getVoiceContainer(e.voice))||void 0===t?void 0:t.beatGlyphs)||void 0===i?void 0:i[e.index]}getPreNotesGlyphForBeat(e){var t;return null===(t=this.getBeatContainer(e))||void 0===t?void 0:t.preNotes}getOnNotesGlyphForBeat(e){var t;return null===(t=this.getBeatContainer(e))||void 0===t?void 0:t.onNotes}paint(e,t,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 us;s.bar=this.bar,s.visualBounds=new at,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 at,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=ae.PreNotes){let i=this.getBeatContainer(e);if(i)switch(t){case ae.PreNotes:return i.voiceContainer.x+i.x;case ae.OnNotes:return i.voiceContainer.x+i.x+i.onNotes.x;case ae.MiddleNotes:return i.voiceContainer.x+i.x+i.onTimeX;case ae.Stem:const t=i.onNotes.beamingHelper?i.onNotes.beamingHelper.getBeatLineX(e):i.onNotes.x+i.onNotes.width/2;return i.voiceContainer.x+t;case ae.PostNotes:return i.voiceContainer.x+i.x+i.onNotes.x+i.onNotes.width;case ae.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 da,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()),this.updateSizes(),this.registerLayoutingInfo()}paintSimileMark(e,t,i){switch(this.bar.simileMark){case o.Simple:i.fillMusicFontSymbol(e+this.x+(this.width-20*this.scale)/2,t+this.y+this.height/2,1,x.Repeat1Bar,!1);break;case o.SecondOfDouble:i.fillMusicFontSymbol(e+this.x-28*this.scale/2,t+this.y+this.height/2,1,x.Repeat2Bars,!1)}}completeBeamingHelper(e){}}wa.LineSpacing=8,wa.StemWidth=.12*wa.LineSpacing,wa.StaffLineThickness=.13*wa.LineSpacing,wa.BeamThickness=.5*wa.LineSpacing,wa.BeamSpacing=.25*wa.LineSpacing,function(e){e[e.SinglePreBeat=0]="SinglePreBeat",e[e.SingleOnBeat=1]="SingleOnBeat",e[e.SingleOnBeatToEnd=2]="SingleOnBeatToEnd",e[e.GroupedOnBeat=3]="GroupedOnBeat",e[e.GroupedOnBeatToEnd=4]="GroupedOnBeatToEnd",e[e.FullBar=5]="FullBar"}(he||(he={}));class Ba extends Ls{constructor(e,t){super(0,0),this._uniqueEffectGlyphs=[],this._effectGlyphs=[],this.isEmpty=!0,this.previousBand=null,this.isLinkedToPrevious=!1,this.firstBeat=null,this.lastBeat=null,this.height=0,this.slot=null,this.voice=e,this.info=t}doLayout(){super.doLayout();for(let e=0;e<this.renderer.bar.voices.length;e++)this._effectGlyphs.push(new Map),this._uniqueEffectGlyphs.push([])}createGlyph(e){if(e.voice===this.voice&&this.info.shouldCreateGlyph(this.renderer.settings,e)&&(!this.info.hideOnMultiTrack||0===this.renderer.staff.trackIndex)){if(this.isEmpty=!1,this.firstBeat&&!e.isBefore(this.firstBeat)||(this.firstBeat=e),!this.lastBeat||e.isAfter(this.lastBeat))switch(this.lastBeat=e,this.info.sizingMode){case he.SingleOnBeatToEnd:case he.GroupedOnBeatToEnd:this.lastBeat.nextBeat&&(this.lastBeat=this.lastBeat.nextBeat)}let t=this.createOrResizeGlyph(this.info.sizingMode,e);t.height>this.height&&(this.height=t.height)}}createOrResizeGlyph(e,t){let i;switch(e){case he.FullBar:case he.SinglePreBeat:case he.SingleOnBeat:case he.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 he.GroupedOnBeat:case he.GroupedOnBeatToEnd:let s=e===he.GroupedOnBeat?he.SingleOnBeat:he.SingleOnBeatToEnd;if(t.index>0||this.renderer.index>0){let e=t.previousBeat;if(this.info.shouldCreateGlyph(this.renderer.settings,e)){let 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 s=this.renderer.previousRenderer.getBand(this.voice,this.info.effectId)._effectGlyphs[t.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(he.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 he.SinglePreBeat:i=a.preNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,s.width=i.width;break;case he.SingleOnBeat:case he.GroupedOnBeat:i=a.onNotes,s.x=this.renderer.beatGlyphsStart+i.x+a.x,s.width=i.width;break;case he.SingleOnBeatToEnd:case he.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 he.FullBar:s.width=this.renderer.width}}}class Ta{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class ka{constructor(){this.bands=[],this.shared=new Ta}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 va{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 ka;return this.slots.push(t),t}register(e){let t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class Na extends la{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 xa extends Na{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,i){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class Pa extends wa{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 va;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 Ba(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 As(t,this.getVoiceContainer(e));i.preNotes=new Na,i.onNotes=new xa,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 Ea extends ha{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 Pa(e,t,this._infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class Ca extends Ms{constructor(e,t,i){super(e,t),this._endingsString="",this._endings=[];for(let e=0;e<Oe.MaxAlternateEndings;e++)0!=(i&1<<e)&&this._endings.push(e)}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(Ca.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=E.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+Ca.Padding*this.scale,t+this.y*this.scale)}i.textBaseline=s}}Ca.Padding=3;class Fa{get effectId(){return this.notationElement.toString()}}class La extends Fa{get notationElement(){return k.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return he.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){return new Ca(0,0,t.voice.bar.masterBar.alternateEndings)}canExpand(e,t){return!0}}class Ma extends Ms{constructor(e,t,i,s,a=P.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 Da extends Fa{get notationElement(){return k.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Ma(0,0,"Capo. fret "+t.voice.bar.staff.capo,e.resources.effectFont,P.Left)}canExpand(e,t){return!1}}class Ia extends Fa{get notationElement(){return k.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Ma(0,0,t.chord.name,e.resources.effectFont,P.Center)}canExpand(e,t){return!1}}class Ra extends Ms{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 Aa extends Ra{constructor(e,t,i){super(ae.EndBeat),this._crescendo=c.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===c.Crescendo?(i-=Aa.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-=Aa.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()}}Aa.Padding=Is.QuarterNoteHeadWidth/2|0;class Oa extends Fa{get notationElement(){return k.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==c.None}createNewGlyph(e,t){return new Aa(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class Ga extends Ds{constructor(e,t,i){super(e,t,.6,Ga.getSymbol(i))}doLayout(){super.doLayout(),this.height=17*this.scale,this.y+=this.height/2}static getSymbol(e){switch(e){case p.PPP:return x.DynamicPPP;case p.PP:return x.DynamicPP;case p.P:return x.DynamicPiano;case p.MP:return x.DynamicMP;case p.MF:return x.DynamicMF;case p.F:return x.DynamicForte;case p.FF:return x.DynamicFF;case p.FFF:return x.DynamicFFF;default:return x.None}}}class Va extends Fa{get notationElement(){return k.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return this.internalShouldCreateGlyph(t)}internalShouldCreateGlyph(e){if(e.voice.bar.staff.track.score.stylesheet.hideDynamics||e.isEmpty||e.voice.isEmpty||e.isRest||e.graceType!==g.None)return!1;let t=this.getPreviousDynamicsBeat(e),i=0===e.voice.index&&!t||e.dynamics!==(null==t?void 0: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===g.None)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new Ga(0,0,t.dynamics)}canExpand(e,t){return!0}}class Ha extends Ms{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 Wa extends Fa{get notationElement(){return k.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.fadeIn}createNewGlyph(e,t){return new Ha}canExpand(e,t){return!0}}class za extends Ds{constructor(e,t,i){super(e,t,1,za.getSymbol(i))}static getSymbol(e){switch(e){case O.Short:return x.FermataShortAbove;case O.Medium:return x.FermataAbove;case O.Long:return x.FermataLongAbove;default:return x.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 Ua extends Fa{get notationElement(){return k.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new za(0,0,t.fermata.type)}canExpand(e,t){return!0}}class Xa extends Fa{get notationElement(){return k.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return!(0!==t.voice.index||t.isRest||e.notation.fingeringMode!==B.SingleNoteEffectBand&&e.notation.fingeringMode!==B.SingleNoteEffectBandForcePiano)&&(1===t.notes.length&&t.notes[0].isFingering)}createNewGlyph(e,t){var i;let s=f.Unknown,a=!1,r=t.notes[0];r.leftHandFinger!==f.Unknown?(s=r.leftHandFinger,a=!0):r.rightHandFinger!==f.Unknown&&(s=r.rightHandFinger);let n=null!==(i=ke.fingerToString(e.settings,t,s,a))&&void 0!==i?i:"";return new Ma(0,0,n,e.resources.fingeringFont,P.Left)}canExpand(e,t){return!0}}class Ya extends Fa{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 qa extends Ra{constructor(e){super(ae.OnNotes),this._label=e}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=ae.EndBeat,this.forceGroupedRendering=!0),super.doLayout(),this.height=this.renderer.resources.effectFont.size}paintNonGrouped(e,t,i){let s=this.renderer.resources;i.font=s.effectFont;let a=i.textAlign;i.textAlign=P.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()}}}qa.LineSpacing=3,qa.LineTopPadding=4,qa.LineTopOffset=5,qa.LineSize=8;class Ja extends Ya{get effectId(){return this._effectId}get notationElement(){return k.EffectHarmonics}constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case m.None:this._effectId="harmonics-none";break;case m.Natural:this._effectId="harmonics-natural";break;case m.Artificial:this._effectId="harmonics-artificial";break;case m.Pinch:this._effectId="harmonics-pinch";break;case m.Tap:this._effectId="harmonics-tap";break;case m.Semi:this._effectId="harmonics-semi";break;case m.Feedback:this._effectId="harmonics-feedback";break;default:this._effectId=""}}shouldCreateGlyphForNote(e){return!(!e.isHarmonic||e.harmonicType!==this._harmonicType)&&(e.beat!==this._beat&&(this._beat=e.beat),!0)}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new qa(Ja.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case m.Natural:return"N.H.";case m.Artificial:return"A.H.";case m.Pinch:return"P.H.";case m.Tap:return"T.H.";case m.Semi:return"S.H.";case m.Feedback:return"Fdbk."}return""}}class ja extends Fa{get notationElement(){return k.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new qa("LetRing")}canExpand(e,t){return!0}}class Qa extends Ms{constructor(e,t,i,s,a=P.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 $a extends Fa{get notationElement(){return k.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new Qa(0,0,t.lyrics,e.resources.effectFont,P.Center)}canExpand(e,t){return!0}}class Ka extends Fa{get notationElement(){return k.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return he.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&t.voice.bar.masterBar.isSectionStart}createNewGlyph(e,t){return new Ma(0,0,t.voice.bar.masterBar.section.marker?"["+t.voice.bar.masterBar.section.marker+"] "+t.voice.bar.masterBar.section.text:t.voice.bar.masterBar.section.text,e.resources.markerFont,P.Left)}canExpand(e,t){return!0}}class Za extends Ra{constructor(e,t){super(ae.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 n._15ma:s=37*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,x.QuindicesimaAlta,!1);break;case n._8va:s=26*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,x.OttavaAlta,!1);break;case n._8vb:s=23*this.scale,i.fillMusicFontSymbol(e+this.x-s/2,t+this.y+this.height,.8,x.OttavaBassaVb,!1);break;case n._15mb:s=36*this.scale,i.fillMusicFontSymbols(e+this.x-s/2,t+this.y+this.height,.8,[x.Quindicesima,x.OctaveBaselineM,x.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 er extends Fa{get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return k.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeat}constructor(e){super(),this._aboveStaff=e}shouldCreateGlyph(e,t){switch(t.ottava){case n._15ma:case n._8va:return this._aboveStaff;case n._8vb:case n._15mb:return!this._aboveStaff}return!1}createNewGlyph(e,t){return new Za(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class tr extends Ya{get notationElement(){return k.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new qa("P.M.")}constructor(){super()}}class ir extends Ya{get notationElement(){return k.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===S.PickSlideDown||e.slideOutType===S.PickSlideUp}get sizingMode(){return he.GroupedOnBeat}createNewGlyph(e,t){return new qa("P.S.")}constructor(){super()}}class sr extends Ds{constructor(e,t,i){super(e,t,Is.GraceScale,sr.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 x.StringsUpBow;case N.Down:return x.StringsDownBow;default:return x.None}}}class ar extends Fa{get notationElement(){return k.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==N.None}createNewGlyph(e,t){return new sr(0,0,t.pickStroke)}canExpand(e,t){return!0}}class rr extends Ra{constructor(e){super(ae.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 nr extends Fa{get notationElement(){return k.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===_.Slight}createNewGlyph(e,t){return new rr(_.Slight)}canExpand(e,t){return!0}}class or extends Ra{constructor(e,t,i,s=1.2,a=!1){super(ae.EndBeat),this._scale=0,this._symbol=x.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=x.WiggleTrill,this._symbolSize=9*this._scale,e=6*this._scale;break;case _.Wide:this._symbol=x.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 hr extends Ya{get notationElement(){return k.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===_.Slight||e.isTieDestination&&e.tieOrigin.vibrato===_.Slight}get sizingMode(){return he.GroupedOnBeatToEnd}createNewGlyph(e,t){return new or(0,0,_.Slight,1.2)}constructor(){super()}}class lr extends Fa{get notationElement(){return k.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){let i=e.resources;return t.slap?new Ma(0,0,"S",i.effectFont,P.Left):t.pop?new Ma(0,0,"P",i.effectFont,P.Left):new Ma(0,0,"T",i.effectFont,P.Left)}canExpand(e,t){return!0}}class dr extends Ms{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*Is.GraceScale,x.NoteQuarterUp,!1),i.fillText("= "+this._tempo.toString(),e+this.x+this.height/2,t+this.y+i.font.size/2)}}class cr extends Fa{get notationElement(){return k.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return he.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&(!!t.voice.bar.masterBar.tempoAutomation||0===t.voice.bar.index)}createNewGlyph(e,t){let 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 ur extends Fa{get notationElement(){return k.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Ma(0,0,t.text,e.resources.effectFont,P.Left)}canExpand(e,t){return!0}}class pr extends Ms{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,d=t+this.y+1.2*this.height;for(let t=0;t<h;t++)i.fillMusicFontSymbol(e+this.x+l,d,1.2,x.WiggleTrill,!1),l+=o}}class gr extends Ya{get notationElement(){return k.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return he.SingleOnBeat}createNewGlyph(e,t){return new pr(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(le||(le={}));class fr extends Ms{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*Is.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 I.NoTripletFeel:this.renderBarNote(a,s,fr.NoteScale,i,[le.Full]),this.renderBarNote(r,s,fr.NoteScale,i,[le.Full]);break;case I.Triplet8th:this.renderBarNote(a,s,fr.NoteScale,i,[le.Full]),i.fillMusicFontSymbol(r,s,fr.NoteScale,x.NoteQuarterUp,!1),i.fillMusicFontSymbol(r+fr.NoteSeparation*this.scale,s,fr.NoteScale,x.NoteEighthUp,!1),this.renderTriplet(r,t,i);break;case I.Triplet16th:this.renderBarNote(a,s,fr.NoteScale,i,[le.Full,le.Full]),this.renderBarNote(r,s,fr.NoteScale,i,[le.Full,le.PartialRight]),this.renderTriplet(r,t,i);break;case I.Dotted8th:this.renderBarNote(a,s,fr.NoteScale,i,[le.Full]),this.renderBarNote(r,s,fr.NoteScale,i,[le.Full,le.PartialRight]),i.fillCircle(r+9*this.scale,s,this.scale);break;case I.Dotted16th:this.renderBarNote(a,s,fr.NoteScale,i,[le.Full,le.Full]),this.renderBarNote(r,s,fr.NoteScale,i,[le.Full,le.Full,le.PartialRight]),i.fillCircle(r+9*this.scale,s,this.scale);break;case I.Scottish8th:this.renderBarNote(a,s,fr.NoteScale,i,[le.Full]),this.renderBarNote(r,s,fr.NoteScale,i,[le.Full,le.PartialLeft]),i.fillCircle(r+fr.NoteSeparation*this.scale+8*this.scale,s,this.scale);break;case I.Scottish16th:this.renderBarNote(a,s,fr.NoteScale,i,[le.Full,le.Full]),this.renderBarNote(r,s,fr.NoteScale,i,[le.Full,le.Full,le.PartialLeft]),i.fillCircle(r+fr.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,x.NoteQuarterUp,!1);let r=fr.NoteSeparation/2*this.scale;for(let i=0;i<a.length;i++)switch(a[i]){case le.Full:s.fillRect(e+4*this.scale,t-fr.NoteHeight*this.scale+fr.BarSeparation*this.scale*i,fr.NoteSeparation*this.scale,fr.BarHeight*this.scale);break;case le.PartialLeft:s.fillRect(e+4*this.scale,t-fr.NoteHeight*this.scale+fr.BarSeparation*this.scale*i,r,fr.BarHeight*this.scale);break;case le.PartialRight:s.fillRect(e+4*this.scale+r,t-fr.NoteHeight*this.scale+fr.BarSeparation*this.scale*i,r,fr.BarHeight*this.scale)}s.fillMusicFontSymbol(e+fr.NoteSeparation*this.scale,t,i,x.NoteQuarterUp,!1)}renderTriplet(e,t,i){t+=2*this.scale;let s=this.renderer.resources.effectFont;i.font=Ni.withFamilyList(s.families,.8*s.size,s.style);let a=e+fr.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}}fr.NoteScale=.4,fr.NoteHeight=12,fr.NoteSeparation=12,fr.BarHeight=2,fr.BarSeparation=3;class mr extends Fa{get notationElement(){return k.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return he.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==I.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new fr(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class yr extends Fa{get notationElement(){return k.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return he.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new qa("w/bar")}canExpand(e,t){return!0}}class br extends Fa{get notationElement(){return k.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return he.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===_.Wide}createNewGlyph(e,t){return new rr(_.Wide)}canExpand(e,t){return!0}}class Sr extends Ya{get notationElement(){return k.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===_.Wide||e.isTieDestination&&e.tieOrigin.vibrato===_.Wide}get sizingMode(){return he.GroupedOnBeatToEnd}createNewGlyph(e,t){return new or(0,0,_.Wide,1.2)}}class _r extends Ms{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=_r.FretSpacing*e:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+(_r.Frets-1)*_r.FretSpacing*e+2*_r.Padding*e,this.width=this._firstFretSpacing+(this._chord.staff.tuning.length-1)*_r.StringSpacing*e+2*_r.Padding*e}paint(e,t,i){e+=this.x+_r.Padding*this.scale+this._firstFretSpacing,t+=this.y;let s=this.width-2*_r.Padding*this.scale+this.scale-this._firstFretSpacing,a=_r.StringSpacing*this.scale,r=_r.FretSpacing*this.scale,n=this.renderer.resources,o=_r.CircleRadius*this.scale,h=i.textAlign,l=i.textBaseline;i.font=n.effectFont,i.textAlign=P.Center,i.textBaseline=E.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=E.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,x.FretboardX,!0):0===o?i.fillMusicFontSymbol(r,n,this.scale,x.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*_r.Frets+this.scale)}this._chord.firstFret>1&&(i.textAlign=P.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<=_r.Frets;a++){let n=t+a*r;i.fillRect(e,n,s,this.scale)}let d=new Map;for(let e of this._chord.barreFrets){let t=[-1,-1];d.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,d.has(n)){let e=d.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 d){let h=t+s*r+r/2+.5*this.scale,l=e+(this._chord.strings.length-n[1]-1)*a,d=e+(this._chord.strings.length-n[0]-1)*a;i.fillRect(l,h-o,d-l,2*o)}i.textAlign=h,i.textBaseline=l}}_r.Padding=5,_r.Frets=5,_r.CircleRadius=2.5,_r.StringSpacing=10,_r.FretSpacing=12;class wr extends la{constructor(e,t,i=P.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=i}doLayout(){let e=0;switch(this._align){case P.Left:e=0;break;case P.Center:e=(this.width-this._glyphWidth)/2;break;case P.Right:e=this.width-this._glyphWidth}for(let t of this.glyphs)t.x=e,e+=t.width}addGlyphToRow(e){this.glyphs.push(e),this._glyphWidth+=e.width,e.height>this.height&&(this.height=e.height)}}class Br extends la{constructor(e,t,i=P.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=i}doLayout(){let e=0,t=0,i=2*Br.Padding*this.scale;this._rows=[];let s=new wr(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 wr(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+Br.Padding*this.scale,i)}}Br.Padding=3;class Tr extends Br{constructor(e,t){super(e,t)}addChord(e){if(e.strings.length>0){let t=new _r(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}}class kr{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 wa(this.staveGroup.layout.renderer,e),i.staff=this,i.index=this.barRenderers.length,i.layoutingInfo=t,i.doLayout(),i.registerLayoutingInfo(),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=e-this.staveGroup.width,i=t/this.barRenderers.length,s=0,a=this.topOverflow;for(let e=0,r=this.barRenderers.length;e<r;e++)this.barRenderers[e].x=s,this.barRenderers[e].y=this.topSpacing+a,0!==t&&this.barRenderers[e].scaleToWidth(this.barRenderers[e].width+i),s+=this.barRenderers[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 vr{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 Nr{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 vr,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!==g.None){const a=e.graceGroup.id;this.allGraceRods.has(a)||this.allGraceRods.set(a,new Array(e.graceGroup.beats.length)),e.graceGroup.isComplete||this.incompleteGraceRods.has(a)||this.incompleteGraceRods.set(a,new Array(e.graceGroup.beats.length));let r=this.allGraceRods.get(a)[e.graceIndex];if(r)r.postSpringWidth<i&&(r.postSpringWidth=i),r.preBeatWidth<t&&(r.preBeatWidth=t);else{const r=new vr;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=ye.toTicks(u.SixtyFourth)),0===e.smallestDuration&&(e.smallestDuration=t),e.smallestDuration/t*(1/((1+.85*Math.log2(t/Nr.MinDuration))*Nr.MinDurationWidth))}spaceToForce(e){return-1!==this.totalSpringConstant?(this._timeSortedSprings.length>0&&(e-=this._timeSortedSprings[0].preSpringWidth),e-=this._incompleteGraceRodsWidth,Math.max(e,0)*this.totalSpringConstant):-1}calculateVoiceWidth(e){let t=0;return-1!==this.totalSpringConstant&&(t=this.calculateWidth(e,this.totalSpringConstant)),this._timeSortedSprings.length>0&&(t+=this._timeSortedSprings[0].preSpringWidth),t+=this._incompleteGraceRodsWidth,t}calculateWidth(e,t){return e/t}buildOnTimePositions(e){if(-1===this.totalSpringConstant)return new Map;if(ke.isAlmostEqualTo(this._onTimePositionsForce,e)&&this._onTimePositions)return this._onTimePositions;this._onTimePositionsForce=e;let t=new Map;this._onTimePositions=t;let 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}}Nr.MinDuration=30,Nr.MinDurationWidth=7;class xr{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.renderers=[]}}class Pr{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 Er{constructor(){this._allStaves=[],this._firstStaffInAccolade=null,this._lastStaffInAccolade=null,this._accoladeSpacingCalculated=!1,this.x=0,this.y=0,this.index=0,this.accoladeSpacing=0,this.isFull=!1,this.width=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[]}get firstBarIndex(){return this.masterBarsRenderers[0].masterBar.index}get lastBarIndex(){return this.masterBarsRenderers[this.masterBarsRenderers.length-1].masterBar.index}addMasterBarRenderers(e,t){if(0===e.length)return null;this.masterBarsRenderers.push(t),this.calculateAccoladeSpacing(e),t.layoutingInfo.preBeatSize=0;let 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.updateWidth(),t}addBars(e,t){if(0===e.length)return null;let i=new xr;i.layoutingInfo=new Nr,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.updateWidth(),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;for(let e=0,i=this._allStaves.length;e<i;e++){let i=this._allStaves[e].revertLastBar();t=Math.max(t,i.width)}return this.width-=t,e}return null}updateWidth(){let e=0;for(let t=0,i=this._allStaves.length;t<i;t++){let i=this._allStaves[t];i.barRenderers[i.barRenderers.length-1].applyLayoutingInfo(),i.barRenderers[i.barRenderers.length-1].width>e&&(e=i.barRenderers[i.barRenderers.length-1].width)}return this.width+=e,e}calculateAccoladeSpacing(e){if(!this._accoladeSpacingCalculated&&0===this.index)if(this._accoladeSpacingCalculated=!0,this.layout.renderer.settings.notation.isNotationElementVisible(k.TrackNames)){let t=this.layout.renderer.canvas,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*Er.AccoladeLabelSpacing*this.layout.scale,this.width+=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 Pr(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,d=r+4*o;0===this.index&&this.layout.renderer.settings.notation.isNotationElementVisible(k.TrackNames)&&i.fillText(a.track.shortName,e+Er.AccoladeLabelSpacing*this.layout.scale,s),i.fillRect(n-h-o,l,o,d-l);let c=n-h-o,u=n+2*o;i.beginPath(),i.moveTo(c,l),i.bezierCurveTo(c,l,c,l,u,l-o),i.bezierCurveTo(n,l+o,c,l+o,c,l+o),i.closePath(),i.fill(),i.beginPath(),i.moveTo(c,d),i.bezierCurveTo(c,d,n,d,u,d+o),i.bezierCurveTo(n,d-o,c,d-o,c,d-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,d=n-r,c=this.x+this._firstStaffInAccolade.x,u=new ms;u.visualBounds=new at,u.visualBounds.x=e,u.visualBounds.y=t+this.y,u.visualBounds.w=this.width,u.visualBounds.h=this.height,u.realBounds=new at,u.realBounds.x=e,u.realBounds.y=t+this.y,u.realBounds.w=this.width,u.realBounds.h=this.height,this.layout.renderer.boundsLookup.addStaveGroup(u);let p=new Map;for(let e=0;e<this.staves.length;e++)for(let 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 gs,a.index=e.bar.masterBar.index,a.isFirstOfLine=e.isFirstOfLine,a.realBounds=new at,a.realBounds.x=c+e.x,a.realBounds.y=r,a.realBounds.w=e.width,a.realBounds.h=d,a.visualBounds=new at,a.visualBounds.x=c+e.x,a.visualBounds.y=s,a.visualBounds.w=e.width,a.visualBounds.h=h,a.lineAlignedBounds=new at,a.lineAlignedBounds.x=c+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,c,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}}Er.AccoladeLabelSpacing=10;class Cr extends la{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 Ma(0,this.height,this._trackLabel,i.effectFont,P.Left)),this.height+=s),this.addGlyph(new Ma(0,this.height,e.name,i.effectFont,P.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=Cr.CircleNumberHeight*r*t;let o=0|Math.ceil(e.tunings.length/2),h=0,l=this.height;for(let d=0,c=e.tunings.length;d<c;d++){const c=x.GuitarString0+(d+1);this.addGlyph(new Ds(h,l+n/1.2,r,c));const u="= "+Ye.getTextForTuning(e.tunings[d],!1);this.addGlyph(new Ma(h+n+1*t,l,u,i.effectFont,P.Left)),l+=s,d===o-1&&(l=this.height,h+=a)}this.height+=o*s}this.width+=15*t}}Cr.CircleNumberHeight=20;class Fr extends Br{constructor(e,t){super(e,t,P.Left)}addTuning(e,t){if(e.tunings.length>0){let i=new Cr(0,0,e,t);i.renderer=this.renderer,i.doLayout(),this.glyphs.push(i)}}}class Lr{constructor(e,t){this.args=e,this.renderCallback=t}}class Mr{constructor(e){this._barRendererLookup=new Map,this.width=0,this.height=0,this.scoreInfoGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t)),this.firstBarIndex=t;let 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.partialLayoutFinished.trigger(e),this.renderer.settings.core.enableLazyLoading?this._lazyPartials.set(e.id,new Lr(e,t)):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(){Be.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(k.ScoreTitle)&&this.scoreInfoGlyphs.set(k.ScoreTitle,new Ma(0,0,t.title,i.titleFont,P.Center)),t.subTitle&&e.isNotationElementVisible(k.ScoreSubTitle)&&this.scoreInfoGlyphs.set(k.ScoreSubTitle,new Ma(0,0,t.subTitle,i.subTitleFont,P.Center)),t.artist&&e.isNotationElementVisible(k.ScoreArtist)&&this.scoreInfoGlyphs.set(k.ScoreArtist,new Ma(0,0,t.artist,i.subTitleFont,P.Center)),t.album&&e.isNotationElementVisible(k.ScoreAlbum)&&this.scoreInfoGlyphs.set(k.ScoreAlbum,new Ma(0,0,t.album,i.subTitleFont,P.Center)),t.music&&t.music===t.words&&e.isNotationElementVisible(k.ScoreWordsAndMusic)?this.scoreInfoGlyphs.set(k.ScoreWordsAndMusic,new Ma(0,0,"Music and Words by "+t.words,i.wordsFont,P.Center)):(t.music&&e.isNotationElementVisible(k.ScoreMusic)&&this.scoreInfoGlyphs.set(k.ScoreMusic,new Ma(0,0,"Music by "+t.music,i.wordsFont,P.Right)),t.words&&e.isNotationElementVisible(k.ScoreWords)&&this.scoreInfoGlyphs.set(k.ScoreWords,new Ma(0,0,"Words by "+t.words,i.wordsFont,P.Left)));const s=new wa(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);if(e.isNotationElementVisible(k.GuitarTuning)){let e=[];for(let t of this.renderer.tracks)for(let 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 Fr(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(k.ChordDiagrams)){this.chordDiagrams=new Tr(0,0),this.chordDiagrams.renderer=s;let e=new Map;for(let t of this.renderer.tracks)for(let i of t.staves){const t=i.chords;if(t)for(const[i,s]of t)e.has(i)||s.showDiagram&&(e.set(i,s),this.chordDiagrams.addChord(s))}}}get scale(){return this.renderer.settings.display.scale}createEmptyStaveGroup(){let e=new Er;e.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=t.Score;else if(this.renderer.settings.display.staveProfile!==t.Default)n=this.renderer.settings.display.staveProfile;else if(o.showTablature&&o.showStandardNotation)n=t.ScoreTab;else if(o.showTablature)n=a?t.TabMixed:t.Tab;else{if(!o.showStandardNotation)continue;n=t.Score}let h=go.staveProfiles.get(n);for(let t of h)t.canCreate(s,o)&&e.addStaff(s,new kr(i,o,t))}}return e}registerBarRenderer(e,t){this._barRendererLookup.has(e)||this._barRendererLookup.set(e,new Map),this._barRendererLookup.get(e).set(t.bar.id,t)}unregisterBarRenderer(e,t){if(this._barRendererLookup.has(e)){this._barRendererLookup.get(e).delete(t.bar.id)}}getRendererForBar(e,t){let 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 cs,n=Ni.withFamilyList(i.copyrightFont.families,s,K.Plain,Z.Bold);this.renderer.canvas.font=n;const o=go.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=P.Left,e.fillText(t,0,s)})),e+a}}class Dr{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class Ir extends Mr{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(){this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=Ir.PagePadding),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let e=this.renderer.score,t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t));let i=t,s=this.renderer.settings.display.barCount;s<=0&&(s=e.masterBars.length),s=t+s-1,s=Math.min(e.masterBars.length-1,Math.max(0,s)),this._group=this.createEmptyStaveGroup(),this._group.isLast=!0,this._group.x=this._pagePadding[0],this._group.y=this._pagePadding[1];let a=this.renderer.settings.display.barCountPerPartial,r=[],n=new Dr,o=0;for(;i<=s;){let t=this._group.addBars(this.renderer.tracks,i);if(t)if(0===n.masterBars.length&&t.isLinkedToPrevious&&r.length>0){let s=r[r.length-1];s.masterBars.push(e.masterBars[i]),s.width+=t.width,o+=t.width,n.x+=o}else n.masterBars.push(e.masterBars[i]),n.width+=t.width,n.masterBars.length>=a&&(0===r.length&&(n.width+=this._group.accoladeSpacing+this._pagePadding[0]),o+=n.width,r.push(n),Be.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null),n=new Dr,n.x=o);i++}n.masterBars.length>0&&(0===r.length&&(n.width+=this._group.accoladeSpacing+this._pagePadding[0]),r.push(n),Be.debug(this.name,"Finished partial from bar "+n.masterBars[0].index+" to "+n.masterBars[n.masterBars.length-1].index,null)),this.finalizeGroup(),this.height=Math.floor(this._group.y+this._group.height),this.width=this._group.x+this._group.width+this._pagePadding[2],i=0;let h=0;for(let e=0;e<r.length;e++){const t=r[e],s=new cs;s.x=h,s.y=0,s.totalWidth=this.width,s.totalHeight=this.height,s.width=t.width,s.height=this.height,s.firstMasterBarIndex=t.masterBars[0].index,s.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,h+=t.width;const a=i,n=e;this._group.buildBoundingsLookup(this._group.x,this._group.y),this.registerPartial(s,(e=>{let i=this._group.getBarX(t.masterBars[0].index)+this._group.accoladeSpacing;0===n&&(i-=this._group.x+this._group.accoladeSpacing),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=P.Left,Be.debug(this.name,"Rendering partial from bar "+t.masterBars[0].index+" to "+t.masterBars[t.masterBars.length-1].index,null),this._group.paintPartial(-i,this._group.y,e,a,t.masterBars.length)})),i+=t.masterBars.length}this.height=this.layoutAndRenderAnnotation(this.height)+this._pagePadding[3]}finalizeGroup(){this._group.scaleToWidth(this._group.width),this._group.finalizeGroup()}}Ir.PagePadding=[20,20,20,20],Ir.GroupSpacing=20;class Rr extends Mr{get name(){return"PageView"}constructor(e){super(e),this._groups=[],this._allMasterBarRenderers=[],this._barsFromPreviousGroup=[],this._pagePadding=null}doLayoutAndRender(){this._pagePadding=this.renderer.settings.display.padding,this._pagePadding||(this._pagePadding=Rr.PagePadding),1===this._pagePadding.length?this._pagePadding=[this._pagePadding[0],this._pagePadding[0],this._pagePadding[0],this._pagePadding[0]]:2===this._pagePadding.length&&(this._pagePadding=[this._pagePadding[0],this._pagePadding[1],this._pagePadding[0],this._pagePadding[1]]);let e=0;this.width=this.renderer.width,this._allMasterBarRenderers=[],e=this.layoutAndRenderScoreInfo(e,-1),e=this.layoutAndRenderTunings(e,-1),e=this.layoutAndRenderChordDiagrams(e,-1),e=this.layoutAndRenderScore(e),e=this.layoutAndRenderAnnotation(e),this.height=e+this._pagePadding[3]}get supportsResize(){return!0}get firstBarX(){let e=this._pagePadding[0];return this._groups.length>0&&(e+=this._groups[0].accoladeSpacing),e}doResize(){let e=0;this.width=this.renderer.width;let t=this.height;e=this.layoutAndRenderScoreInfo(e,t),e=this.layoutAndRenderTunings(e,t),e=this.layoutAndRenderChordDiagrams(e,t),e=this.resizeAndRenderScore(e,t),e=this.layoutAndRenderAnnotation(e),this.height=e+this._pagePadding[3]}layoutAndRenderTunings(e,t=-1){if(!this.tuningGlyph)return e;let 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 cs;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=P.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 cs;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=P.Center,this.chordDiagrams.paint(0,0,e)})),e+s}layoutAndRenderScoreInfo(e,t=-1){Be.debug(this.name,"Layouting score info");const i=new cs;i.x=0,i.y=e;let s=this._pagePadding[1],a=this.scale,r=this.renderer.settings.display.resources,n=[k.ScoreTitle,k.ScoreSubTitle,k.ScoreArtist,k.ScoreAlbum,k.ScoreWordsAndMusic];for(let e=0;e<n.length;e++)if(this.scoreInfoGlyphs.has(n[e])){let t=this.scoreInfoGlyphs.get(n[e]);t.x=this.width/2,t.y=s,t.textAlign=P.Center,s+=t.font.size*a}let o=!1,h=0;if(this.scoreInfoGlyphs.has(k.ScoreMusic)){let e=this.scoreInfoGlyphs.get(k.ScoreMusic);e.x=this.width-this._pagePadding[2],e.y=s,e.textAlign=P.Right,o=!0,h=e.font.size*a}if(this.scoreInfoGlyphs.has(k.ScoreWords)){let e=this.scoreInfoGlyphs.get(k.ScoreWords);e.x=this._pagePadding[0],e.y=s,e.textAlign=P.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=P.Center;for(const t of this.scoreInfoGlyphs.values())t.paint(0,0,e)})),e+s}resizeAndRenderScore(e,t){if(-1!==this.renderer.settings.display.barsPerRow)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),Be.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 cs;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=P.Left,e.paint(0,-s.y,t)})),t+=i,i}fitGroup(e){e.isFull||e.width>this.maxWidth?e.scaleToWidth(this.maxWidth):e.scaleToWidth(e.width),e.finalizeGroup()}createStaveGroup(e,t){let i=this.createEmptyStaveGroup();i.index=this._groups.length;let s=this.renderer.settings.display.barsPerRow,a=this.maxWidth,r=t+1,n=e;for(;n<r;){if(this._barsFromPreviousGroup.length>0)for(let e of this._barsFromPreviousGroup)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]}}Rr.PagePadding=[40,40,40,40],Rr.GroupSpacing=20;class Ar extends Ds{constructor(e,t,i,s=!1){super(e,t,s?Is.GraceScale:1,Ar.getMusicSymbol(i)),this._isGrace=s,this._accidentalType=i}static getMusicSymbol(e){switch(e){case re.Natural:return x.AccidentalNatural;case re.Sharp:return x.AccidentalSharp;case re.Flat:return x.AccidentalFlat;case re.NaturalQuarterNoteUp:return x.AccidentalQuarterToneNaturalArrowUp;case re.SharpQuarterNoteUp:return x.AccidentalQuarterToneSharpArrowUp;case re.FlatQuarterNoteUp:return x.AccidentalQuarterToneFlatArrowUp;case re.DoubleSharp:return x.AccidentalDoubleSharp;case re.DoubleFlat:return x.AccidentalDoubleFlat}return x.None}doLayout(){if(this._accidentalType===re.DoubleFlat)this.width=18;else this.width=8;this.width=this.width*(this._isGrace?Is.GraceScale:1)*this.scale}}class Or extends Ls{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 Gr extends Ls{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 Vr extends Ds{constructor(e,t,i,s){super(e,t,1,Vr.getSymbol(i)),this._clef=i,this._clefOttava=s}doLayout(){switch(this._clef){case r.Neutral:this.width=15*this.scale;break;case r.C3:case r.C4:case r.F4:case r.G2:this.width=28*this.scale}}static getSymbol(e){switch(e){case r.Neutral:return x.UnpitchedPercussionClef1;case r.C3:case r.C4:return x.CClef;case r.F4:return x.FClef;case r.G2:return x.GClef;default:return x.None}}paint(e,t,i){let s;super.paint(e,t,i);let a=!1;switch(this._clefOttava){case n._15ma:s=new Ds(-4*this.scale,0,.5,x.Quindicesima),a=!0;break;case n._8va:s=new Ds(-2*this.scale,0,.5,x.Ottava),a=!0;break;case n._8vb:s=new Ds(-6*this.scale,0,.5,x.Ottava);break;case n._15mb:s=new Ds(-8*this.scale,0,.5,x.Quindicesima);break;default:return}let o=0,h=0;switch(this._clef){case r.Neutral:o=a?-12:15,h=0;break;case r.C3:case r.C4:o=a?-19:27,h=0;break;case r.F4:o=a?-9:27,h=-4;break;case r.G2:o=a?-37:30,h=0;break;default:return}s.renderer=this.renderer,s.doLayout();let l=this.width/2;s.paint(e+this.x+l+h*this.scale,t+this.y+o*this.scale,i)}}class Hr extends Ls{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 Wr extends Ls{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=P.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 zr extends Ls{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 Ur extends Ds{constructor(e,t,i){super(e,t,1,Ur.getSymbol(i))}static getSymbol(e){switch(e){case s.None:return x.None;case s.Normal:return x.ArticAccentAbove;case s.Heavy:return x.ArticMarcatoAbove;default:return x.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 Xr extends Ls{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 Yr extends Ds{constructor(e,t,i){super(e,t,i?Is.GraceScale:1,x.NoteheadXOrnate),this._isGrace=i}doLayout(){this.width=9*(this._isGrace?Is.GraceScale:1)*this.scale,this.height=Is.NoteHeadHeight*this.scale}}class qr extends Ds{constructor(e,t,i,s){super(e,t,s?Is.GraceScale:1,qr.getSymbol(i)),this._isGrace=s}static getSymbol(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:case u.Whole:case u.Half:return x.NoteheadDiamondWhiteWide;default:return x.NoteheadDiamondBlackWide}}doLayout(){this.width=9*(this._isGrace?Is.GraceScale:1)*this.scale,this.height=Is.NoteHeadHeight*this.scale}}class Jr extends Ls{constructor(e,t,i){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=H.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=Jr.calculateActualTieHeight(this.renderer.scale,this._startX,this._startY,this._endX,this._endY,this.tieDirection===H.Down,this._tieHeight,4).h),this.tieDirection===H.Up&&(this.y-=this.height))}paint(e,t,i){this._shouldDraw&&(this.shouldDrawBendSlur()?Jr.drawBendSlur(i,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===H.Down,this.scale):Jr.paintTie(i,this.scale,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===H.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,i,s){return 22}getBeamDirection(e,t){return H.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=Jr.computeBezierControlPoints(e,t,i,s,a,r,n,o);t=h[0],i=h[1];const l=h[2],d=h[3];s=h[6],a=h[7];const c=(t-l)/(t-2*l+s),u=Jr.calculateExtrema(t,i,l,d,s,a,c),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-d)/(i-2*d+a),m=Jr.calculateExtrema(t,i,l,d,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 at;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,d=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=d,l/=d;let c=(s+t)/2,u=(a+i)/2;return[t,i,c+n*h,u+n*l,c+(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=Jr.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,d=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=d,l/=d;let c=(s+t)/2,u=(a+i)/2,p=Jr.BendSlurHeight*n;s-t<20&&(p/=2);let g=c+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)}}}Jr.BendSlurHeight=11;class jr extends Ls{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=jr.Size*this.scale}paint(e,t,i){this._isOpen?Jr.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):Jr.paintTie(i,this.scale,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3)}}jr.Size=6;class Qr{constructor(e,t){this.line=0,this.line=e,this.isGhost=t}}class $r extends Ls{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(k.ParenthesisOnTiedBends);this.addParenthesisOnLine(i,s)}addParenthesisOnLine(e,t){let i=new Qr(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 jr(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 Kr{constructor(e,t){this.line=0,this.glyph=e,this.line=t}}class Zr extends Ls{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new fi,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){let i=new Kr(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===H.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===H.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 en extends Ds{constructor(e,t,i){super(e,t,1,en.getSymbol(i))}doLayout(){this.width=12*this.scale}static getSymbol(e){switch(e){case u.ThirtySecond:return x.Tremolo3;case u.Sixteenth:return x.Tremolo2;case u.Eighth:return x.Tremolo1;default:return x.None}}}class tn extends Zr{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 oe.Left:break;case oe.Center:s+=i.width/2;break;case oe.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 ne.TopWithStem:s-=this.renderer.getStemSize(this.beamingHelper);break;case ne.Top:s-=i.height/2;break;case ne.Center:break;case ne.Bottom:s+=i.height/2;break;case ne.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===H.Up?this.minNote:this.maxNote,s=e===H.Up?this.displacedX:0,a=this.beat.tremoloSpeed;switch(a){case u.ThirtySecond:t=e===H.Up?-15:15;break;case u.Sixteenth:t=e===H.Up?-12:15;break;case u.Eighth:t=e===H.Up?-10:10;break;default:t=e===H.Up?-10:15}this._tremoloPicking=new en(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 fs;r.note=s,r.noteHeadBounds=new at,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===H.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 sn extends Ds{constructor(e,t,i){super(e,t,1,sn.getSymbol(i)),this._duration=i}static getSymbol(e){switch(e){case u.QuadrupleWhole:return x.RestLonga;case u.DoubleWhole:return x.RestDoubleWhole;case u.Whole:return x.RestWhole;case u.Half:return x.RestHalf;case u.Quarter:return x.RestQuarter;case u.Eighth:return x.RestEighth;case u.Sixteenth:return x.RestSixteenth;case u.ThirtySecond:return x.RestThirtySecond;case u.SixtyFourth:return x.RestSixtyFourth;case u.OneHundredTwentyEighth:return x.RestOneHundredTwentyEighth;case u.TwoHundredFiftySixth:return x.RestTwoHundredFiftySixth;default:return x.None}}static getSize(e){switch(e){case u.QuadrupleWhole:case u.DoubleWhole:case u.Whole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:return 9;case u.ThirtySecond:return 12;case u.SixtyFourth:return 14;case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:return 20}return 10}doLayout(){this.width=sn.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 an{constructor(){this.x=0,this.y=-3e3,this.width=0}}class rn extends la{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 an);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 an);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 nn extends Zr{get direction(){return H.Up}constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new rn,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new $r(!0),this._postNoteParenthesis=new $r(!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 Is(0,0,u.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!==re.None){let e=new Ar(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+nn.ElementPadding*this.scale),this._accidentals.isEmpty||(e+=this._accidentals.width+nn.ElementPadding*this.scale,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+nn.ElementPadding*this.scale),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+nn.ElementPadding*this.scale,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+nn.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)}}nn.ElementPadding=2;class on extends Ls{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,i,s,a,r,n,o){Jr.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)===H.Up?H.Down:H.Up}}on.EndPadding=8;class hn extends be{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class ln extends Ls{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 l.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 l.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 l.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 l.Prebend:i=t[0].value,(-1===this._preBendMinValue||i<this._preBendMinValue)&&(this._preBendMinValue=i);break;case l.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 l.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*ln.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 l.Bend:i[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case l.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[1].lineValue=t);break;case l.BendRelease:i[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(i[2].lineValue=t);break;case l.Prebend:i[0].lineValue=this._preBendMinValue;break;case l.PrebendBend:i[0].lineValue=this._preBendMinValue,i[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case l.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 l.Custom:for(let i of e.bendPoints)t.push(new hn(i.offset,i.value));break;case l.BendRelease:t.push(new hn(0,e.bendPoints[0].value)),t.push(new hn(be.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new hn(be.MaxPosition,e.bendPoints[3].value));break;case l.Bend:case l.Hold:case l.Prebend:case l.PrebendBend:case l.PrebendRelease:case l.Release:t.push(new hn(0,e.bendPoints[0].value)),t.push(new hn(be.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,d=!1,c=null,u=!1,p=a.bendStyle===h.Gradual?"grad.":"",g=null;for(;o.isTieOrigin;){let e=o.tieDestination;if(c=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,e.beat.voice.bar),!c||n.staff!==c.staff)break;if(o=e,d=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes){u=!0;break}}g=o.beat,c=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,g.voice.bar),g.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(g=null);let f=0,m=0,y=t+n.y;f=e+n.x,r[0].value>0||a.isContinuedBend?f+=n.getBeatX(a.beat,ae.MiddleNotes):f+=n.getNoteX(a,oe.Right),m=!g||g.isLastOfVoice&&!u?e+c.x+c.postBeatGlyphsStart:u||!g.nextBeat?e+c.x+c.getBeatX(g,ae.MiddleNotes):a.bendType===l.Hold?e+c.x+c.getBeatX(g.nextBeat,ae.OnNotes):e+c.x+c.getBeatX(g.nextBeat,ae.PreNotes),d||(m-=ln.ArrowSize*this.scale);let b=(m-f)/be.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 hn(0,0),t,f,y,b,p,i),a.bendType!==l.Prebend?(0===e&&(f+=2*this.scale),this.paintBend(a,t,s,f,y,b,p,i)):a.isTieOrigin&&a.tieDestination.hasBend&&(s=new hn(be.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,d=h.lineOffset/2,c=s+r*t.offset,u=ln.BendValueHeight*this.scale,p=a-u*t.lineValue;0===t.value?i.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,ne.Top):p+=h.getNoteY(e,ne.Center):p+=d;let g=s+r*i.offset,f=a-u*i.lineValue;0===i.lineValue?f+=h.getNoteY(e,ne.Center):f+=d;let m=0,y=ln.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=ln.DashSize*this.scale,i=c+t;if((e-c)/(2*t)<1)o.moveTo(e,p),o.lineTo(c,p);else for(;e>i;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>c?(o.moveTo(c,p),o.bezierCurveTo((c+g)/2,p,g,p,g,f+m),o.stroke()):(o.moveTo(c,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=(c+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+=ln.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"}}}ln.ArrowSize=6,ln.DashSize=3,ln.BendValueHeight=6;class dn extends Ls{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===C.Custom)return e.whammyBarPoints;let t=[];switch(e.whammyBarType){case C.Dive:case C.Hold:case C.PrediveDive:case C.Predive:t.push(new be(0,e.whammyBarPoints[0].value)),t.push(new be(be.MaxPosition,e.whammyBarPoints[1].value));break;case C.Dip:t.push(new be(0,e.whammyBarPoints[0].value)),t.push(new be(be.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new be(be.MaxPosition,e.whammyBarPoints[e.whammyBarPoints.length-1].value))}return t}doLayout(){super.doLayout(),this._isSimpleDip=this.renderer.settings.notation.notationMode===T.SongBook&&this._beat.whammyBarType===C.Dip;let e=null,t=null,i=this._beat;for(;i&&i.hasWhammyBar;)(!e||e.value>i.minWhammyPoint.value)&&(e=i.minWhammyPoint),(!t||t.value<i.maxWhammyPoint.value)&&(t=i.maxWhammyPoint),i=i.nextBeat;let s=t.value>0?Math.abs(this.getOffset(t.value)):0;(s>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys))&&(s+=2*this.renderer.resources.tablatureFont.size);let a=e.value<0?Math.abs(this.getOffset(e.value)):0;this.renderer.registerOverflowTop(s+a),s>this.renderer.staff.getSharedLayoutData(dn.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(dn.TopOffsetSharedDataKey,s)}getOffset(e){if(0===e)return 0;let t=dn.PerHalfSize*this.scale+Math.log2(Math.abs(e)/2)*dn.PerHalfSize*this.scale;return e<0&&(t=-t),t}paint(e,t,i){let s=this.renderer,a=this._beat.nextBeat,r=null,n=ae.PreNotes;a&&(r=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,a.voice.bar),r&&r.staff===s.staff&&(r===s||a.hasWhammyBar)?n=!a.hasWhammyBar||s.settings.notation.notationMode===T.SongBook&&a.whammyBarType===C.Dip?ae.PreNotes:ae.MiddleNotes:(a=null,r=null));let o=0,l=0;this._isSimpleDip?(o=e+s.x+s.getBeatX(this._beat,ae.OnNotes)-2*this.scale,l=e+s.x+s.getBeatX(this._beat,ae.PostNotes)+2*this.scale):(o=e+s.x+s.getBeatX(this._beat,ae.MiddleNotes),l=r?e+r.x+r.getBeatX(a,n):e+s.x+s.width-2*this.scale);let d=i.textAlign;if(i.textAlign=P.Center,this._renderPoints.length>=2){let e=(l-o)/be.MaxPosition;i.beginPath();let s=t+this.renderer.staff.getSharedLayoutData(dn.TopOffsetSharedDataKey,0),a=this._beat.whammyStyle===h.Gradual?"grad.":"";for(let t=0,r=this._renderPoints.length-1;t<r;t++){let n=this._renderPoints[t],h=this._renderPoints[t+1],l=t<r-2?this._renderPoints[t+2]:null,d=0===t;0!==t||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new be(0,0),n,h,o,s,e,i),d=!1),this.paintWhammy(d,n,h,l,o,s,e,i,a),a=""}i.stroke()}i.textAlign=d}paintWhammy(e,t,i,s,a,r,n,o,h){let l=a+n*t.offset,d=a+n*i.offset,c=r-this.getOffset(t.value),u=r-this.getOffset(i.value);if(t.offset===i.offset){let e=dn.DashSize*this.scale;if(Math.abs(u-c)/(2*e)<1)o.moveTo(l,c),o.lineTo(d,u);else{let t=Math.max(c,u),i=Math.min(c,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=dn.DashSize*this.scale;if(Math.abs(d-l)/(2*e)<1)o.moveTo(l,c),o.lineTo(d,u);else{let t=Math.max(l,d),i=Math.min(l,d);for(;t>i;)o.moveTo(t,c),o.lineTo(t-e,c),t-=2*e}o.stroke()}else o.moveTo(l,c),o.lineTo(d,u);let p=this.renderer.resources;if(e&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let e=c;e-=p.tablatureFont.size+2*this.scale,this.renderer.settings.notation.isNotationElementVisible(k.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2*this.scale,o.fillText(h,l,e))}let g=Math.abs(i.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(k.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+=ln.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(c,u)-p.tablatureFont.size-2*this.scale:(a=t.offset===i.offset?Math.min(c,u):u,a-=p.tablatureFont.size+2*this.scale,s&&s.value>i.value&&(a-=2*this.scale));let r=d;o.fillText(e,r,a)}}}dn.TopOffsetSharedDataKey="tab.whammy.topoffset",dn.PerHalfSize=6,dn.DashSize=3;class cn extends on{constructor(e){super(0,0),this._beat=e}doLayout(){let e=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case C.None:case C.Custom:case C.Hold:return;case C.Dive:case C.PrediveDive:{let e=new nn(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 C.Dip:if(e===T.SongBook){let e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+cn.SimpleDipHeight*this.scale+cn.SimpleDipPadding*this.scale}else{let e=new nn(this._beat,!1);if(e.renderer=this.renderer,this.renderer.settings.notation.notationMode===T.GuitarPro){let t=this._beat.whammyBarPoints[1];for(let i of this._beat.notes)e.addGlyph(this.getBendNoteValue(i,this._beat.whammyBarPoints[1]),t.value%2!=0)}e.doLayout(),this.BendNoteHeads.push(e);let t=new nn(this._beat,!1);if(t.renderer=this.renderer,this.renderer.settings.notation.notationMode===T.GuitarPro){let e=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(let i of this._beat.notes)t.addGlyph(this.getBendNoteValue(i,e),e.value%2!=0)}t.doLayout(),this.BendNoteHeads.push(t)}case C.Predive:}super.doLayout()}paint(e,t,i){let s=this._beat;switch(s.whammyBarType){case C.None:case C.Custom:return}let a=this.renderer.settings.notation.notationMode,r=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,s.voice.bar),n=e+r.x+r.getBeatX(s,ae.MiddleNotes),o=this.getTieDirection(s,r),l=1===this._beat.notes.length?o:H.Up,d=i.textAlign;for(let d=0;d<s.notes.length;d++){let c=s.notes[d],u=t+r.y;d>0&&d>=(this._beat.notes.length/2|0)&&(l=H.Down),l===H.Down?u+=r.getNoteY(c,ne.Bottom):u+=r.getNoteY(c,ne.Top);let p=e+r.x;s.isLastOfVoice?p+=r.width:p+=r.getBeatX(s,ae.EndBeat),p-=8*this.scale;let g=s.whammyStyle===h.Gradual&&0===d?"grad.":"",f=null;c.isTieOrigin&&(f=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,c.tieDestination.beat.voice.bar),f&&f.staff===r.staff?p=e+f.x+f.getBeatX(c.tieDestination.beat,ae.MiddleNotes):f=null);let m=Is.NoteHeadHeight*this.scale*Is.GraceScale*.5;l===H.Up&&(m=-m);let y=s.whammyBarPoints.length>0?this.getBendNoteValue(c,s.whammyBarPoints[s.whammyBarPoints.length-1]):0,b=0,S=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(y)?(b=this.BendNoteHeads[0].getNoteValueY(y)+m,S=!0):f&&(c.isTieOrigin&&c.tieDestination.beat.hasWhammyBar||c.beat.isContinuedWhammy)?(b=t+f.y+f.getNoteY(c.tieDestination,ne.Top),S=!0,l===H.Down&&(b+=Is.NoteHeadHeight*this.scale)):c.isTieOrigin&&(b=f?t+f.y+f.getNoteY(c.tieDestination,ne.Top):u,l===H.Down&&(b+=Is.NoteHeadHeight*this.scale)),s.whammyBarType){case C.Hold:c.isTieOrigin&&Jr.paintTie(i,this.scale,n,u,p,b,o===H.Down,22,4);break;case C.Dive:0===d&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,i),this.BendNoteHeads[0].containsNoteValue(y)&&(b+=this.BendNoteHeads[0].y)),S?this.drawBendSlur(i,n,u,p,b,l===H.Down,this.scale,g):c.isTieOrigin&&Jr.paintTie(i,this.scale,n,u,p,b,o===H.Down,22,4);break;case C.Dip:if(a===T.SongBook){if(0===d){let s=e+r.x+r.getBeatX(this._beat,ae.OnNotes)-2*this.scale,a=e+r.x+r.getBeatX(this._beat,ae.PostNotes)+2*this.scale,n=(s+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();i.font=this.renderer.resources.tablatureFont,i.fillText(o,n,t+this.y);let h=t+this.y+i.font.size+2*this.scale,l=h+cn.SimpleDipHeight*this.scale;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(i.moveTo(s,l),i.lineTo(n,h),i.lineTo(a,l)):(i.moveTo(s,h),i.lineTo(n,l),i.lineTo(a,h)),i.stroke()}c.isTieOrigin&&Jr.paintTie(i,this.scale,n,u,p,b,o===H.Down,22,4)}else{let e=(n+p)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,i);let a=this.getBendNoteValue(c,s.whammyBarPoints[1]),o=this.BendNoteHeads[0].getNoteValueY(a)+m;this.drawBendSlur(i,n,u,e,o,l===H.Down,this.scale,g),this.BendNoteHeads[1].x=p-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=t+r.y,this.BendNoteHeads[1].paint(0,0,i),b=this.BendNoteHeads[1].getNoteValueY(y)+m,this.drawBendSlur(i,e,o,p,b,l===H.Down,this.scale,g)}break;case C.PrediveDive:case C.Predive:let h=e+r.x+r.getBeatX(c.beat,ae.PreNotes);h+=r.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;let f=t+r.y+r.getScoreY(r.accidentalHelper.getNoteLineForValue(c.displayValue-(c.beat.whammyBarPoints[0].value/2|0),!1))+m;this.drawBendSlur(i,h,f,n,u,l===H.Down,this.scale,g),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,i),this.drawBendSlur(i,n,u,p,b,l===H.Down,this.scale,g))}}i.textAlign=d}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}cn.SimpleDipHeight=2*dn.PerHalfSize,cn.SimpleDipPadding=2;class un extends Ls{constructor(e,t,i){super(e,t),this.width=i}}class pn extends Ds{constructor(e,t,i,s,a){super(e,t,a?Is.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!==x.None&&this._articulation.techniqueSymbolPlacement===E.Middle&&i.fillMusicFontSymbol(e+this.x,t+this.y+s,this.glyphScale*this.scale,this._articulation.techniqueSymbol,!1)}doLayout(){let e=(this._isGrace?Is.GraceScale:1)*this.scale;switch(this.symbol){case x.NoteheadWhole:this.width=14;break;case x.NoteheadCircleX:case x.NoteheadDiamondWhite:this.width=9;break;case x.NoteheadHeavyXHat:case x.NoteheadHeavyX:this.width=13;break;default:this.width=10}this.width=this.width*(this._isGrace?Is.GraceScale:1)*this.scale,this.height=Is.NoteHeadHeight*e}}class gn extends Ds{constructor(e,t){super(e,t,Is.GraceScale,x.ArticStaccatoAbove)}doLayout(){this.width=Is.QuarterNoteHeadWidth*this.scale,this.height=7*this.scale}paint(e,t,i){super.paint(e+3*this.scale,t+5*this.scale,i)}}class fn extends Ds{constructor(e,t){super(e,t,.5,x.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 mn extends Ds{constructor(e,t){super(e,t,Is.GraceScale,x.GuitarGolpe)}doLayout(){this.width=9*this.scale,this.height=10*this.scale}paint(e,t,i){super.paint(e,t+this.height,i)}}class yn extends xa{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===u.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const i=new sn(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=ma.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 un(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++){let e=new la(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addGlyph(e)}}}else{const t=new tn;this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper;let i=new $r(!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 un(0,0,4*(this.container.beat.graceType!==g.None?Is.GraceScale:1)*this.scale)),this.addGlyph(i)),this.container.beat.hasWhammyBar){let e=new cn(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addGlyph(new un(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++){let t=new la(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 Xr(0,i.getScoreY(e),1.5*this.scale))}createNoteHeadGlyph(e){let t=this.container.beat.graceType!==g.None;if(e.beat.voice.bar.staff.isPercussion){const i=Ne.getArticulation(e);if(i)return new pn(0,0,i,e.beat.duration,t);Be.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new Yr(0,0,t):e.beat.graceType===g.BendGrace?new Is(0,0,u.Quarter,!0):e.harmonicType===m.Natural?new qr(0,0,e.beat.duration,t):new Is(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===g.BendGrace&&!e.hasBend)return;let t=this.renderer,i=this.createNoteHeadGlyph(e),a=t.getNoteLine(e);if(i.y=t.getScoreY(a),this.noteHeads.addNoteGlyph(i,e,a),e.harmonicType!==m.None&&e.harmonicType!==m.Natural){let s=e.displayValue+e.harmonicPitch;i=new qr(0,0,e.beat.duration,this.container.beat.graceType!==g.None),a=t.accidentalHelper.getNoteLineForValue(s,!1),i.y=t.getScoreY(a),this.noteHeads.addNoteGlyph(i,e,a)}if(e.isStaccato&&!this.noteHeads.aboveBeatEffects.has("Staccato")&&this.noteHeads.belowBeatEffects.set("Staccato",new gn(0,0)),e.accentuated!==s.Normal||this.noteHeads.aboveBeatEffects.has("Accent")||this.noteHeads.belowBeatEffects.set("Accent",new Ur(0,0,s.Normal)),e.accentuated!==s.Heavy||this.noteHeads.aboveBeatEffects.has("HAccent")||this.noteHeads.belowBeatEffects.set("HAccent",new Ur(0,0,s.Heavy)),e.isPercussion){const t=Ne.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==E.Middle){const e=t.techniqueSymbolPlacement===E.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case x.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new fn(0,0));break;case x.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new gn(0,0));break;case x.StringsUpBow:e.set("StringsUpBow",new sr(0,0,N.Up));break;case x.StringsDownBow:e.set("StringsDownBow",new sr(0,0,N.Down));break;case x.GuitarGolpe:e.set("GuitarGolpe",new mn(0,0))}}}}}class bn extends Ls{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,ne.Bottom)-a),n=t+this.y+s.getNoteY(this._beat.minNote,ne.Top)+a,o=e+this.x+this.width/2,h=8*this.scale,l=new or(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 Sn extends Na{get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}doLayout(){if(!this.container.beat.isRest){let e=new rn;e.renderer=this.renderer;let t=new $r(!0);t.renderer=this.renderer;const i=new nn(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 l.PrebendBend:case l.Prebend:case l.PrebendRelease:i.addGlyph(s.displayValue-(s.bendPoints[0].value/2|0),!1)}else if(s.beat.hasWhammyBar)switch(s.beat.whammyBarType){case C.PrediveDive:case C.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 un(0,0,4*(this.container.beat.graceType!==g.None?Is.GraceScale:1)*this.scale))),this.container.beat.brushType!==d.None&&(this.addGlyph(new bn(this.container.beat)),this.addGlyph(new un(0,0,4*this.scale))),t.isEmpty||(this.addGlyph(t),this.addGlyph(new un(0,0,4*(this.container.beat.graceType!==g.None?Is.GraceScale:1)*this.scale))),e.isEmpty||(this.accidentals=e,this.addGlyph(new un(0,0,2*(this.container.beat.graceType!==g.None?Is.GraceScale:1)*this.scale)),this.addGlyph(e),this.addGlyph(new un(0,0,2*(this.container.beat.graceType!==g.None?Is.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!==g.None;if(s!==re.None){let e=new Ar(0,i.getScoreY(a),s,r);e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==m.None&&e.harmonicType!==m.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 Ar(0,i.getScoreY(a),s,r);o.renderer=this.renderer,t.addGlyph(o)}}constructor(){super(),this._prebends=null,this.accidentals=null}}class _n extends Ds{constructor(e,t,i,s){super(e,t,s,_n.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 x.TimeSig0;case 1:return x.TimeSig1;case 2:return x.TimeSig2;case 3:return x.TimeSig3;case 4:return x.TimeSig4;case 5:return x.TimeSig5;case 6:return x.TimeSig6;case 7:return x.TimeSig7;case 8:return x.TimeSig8;case 9:return x.TimeSig9;default:return x.None}}}class wn extends la{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 _n(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}}}wn.numberHeight=18;class Bn extends la{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 Ds(0,0,this.commonScale,x.TimeSigCutCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){let e=new Ds(0,0,this.commonScale,x.TimeSigCommon);e.width=14*this.scale,this.addGlyph(e),super.doLayout()}else{const e=wn.numberHeight*this.scale;let t=new wn(0,-e/2,this._numerator,this.numberScale),i=new wn(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 Tn extends Bn{get commonScale(){return 1}get numberScale(){return 1}}class kn extends on{constructor(e){super(0,0),this._notes=[],this._endNoteGlyph=null,this._middleNoteGlyph=null,this._beat=e}addBends(e){if(this._notes.push(e),!e.isTieOrigin)switch(e.bendType){case l.Bend:case l.PrebendRelease:case l.PrebendBend:{let t=this._endNoteGlyph;t||(t=new nn(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 l.Release:if(!e.isTieOrigin){let t=this._endNoteGlyph;t||(t=new nn(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 l.BendRelease:{let t=this._middleNoteGlyph;t||(t=new nn(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 nn(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,ae.MiddleNotes),r=e+s.x;this._beat.isLastOfVoice?r+=s.postBeatGlyphsStart:r+=s.getBeatX(this._beat.nextBeat,ae.PreNotes),r-=8*this.scale;let n=(a+r)/2;this._middleNoteGlyph&&(this._middleNoteGlyph.x=n-this._middleNoteGlyph.noteHeadOffset,this._middleNoteGlyph.y=t+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===g.BendGrace?this._beat.nextBeat:this._beat,d=1===this._notes.length?this.getTieDirection(o,s):H.Up;for(let o=0;o<this._notes.length;o++){let c=this._notes[o];o>0&&o>=(this._notes.length/2|0)&&(d=H.Down);let u=t+s.y+s.getNoteY(c,ne.Top),p=Is.NoteHeadHeight*this.scale*Is.GraceScale*.5;d===H.Down&&(u+=Is.NoteHeadHeight*this.scale);let g=c.bendStyle===h.Gradual?"grad.":"";if(c.isTieOrigin){let r=c.tieDestination,n=r?this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.beat.voice.bar):null;if(n&&n.staff===s.staff){let s=e+n.x+n.getBeatX(r.beat,ae.MiddleNotes),o=t+n.y+n.getNoteY(r,ne.Top);d===H.Down&&(o+=Is.NoteHeadHeight*this.scale),c.bendType===l.Hold||c.bendType===l.Prebend?Jr.paintTie(i,this.scale,a,u,s,o,d===H.Down,22,4):this.drawBendSlur(i,a,u,s,o,d===H.Down,this.scale,g)}else{let r=e+s.x+s.width,n=c.tieDestination.realValue;s.accidentalHelper.applyAccidentalForValue(c.beat,n,!1,!0);let o=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(n,!1));c.bendType===l.Hold||c.bendType===l.Prebend?Jr.paintTie(i,this.scale,a,u,r,o,d===H.Down,22,4):this.drawBendSlur(i,a,u,r,o,d===H.Down,this.scale,g)}switch(c.bendType){case l.Prebend:case l.PrebendBend:case l.PrebendRelease:let r=e+s.x+s.getBeatX(c.beat,ae.PreNotes);r+=s.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;let n=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(i,r,n,a,u,d===H.Down,this.scale)}}else{d===H.Up&&(p=-p);let o=0,h=0;switch(c.bendType){case l.Bend:o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),h=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,h,d===H.Down,this.scale,g);break;case l.BendRelease:let f=this.getBendNoteValue(c,c.bendPoints[1]),m=this._middleNoteGlyph.getNoteValueY(f)+p;this.drawBendSlur(i,a,u,n,m,d===H.Down,this.scale,g),o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),h=this._endNoteGlyph.getNoteValueY(o)+p,this.drawBendSlur(i,n,m,r,h,d===H.Down,this.scale,g);break;case l.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),h=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,h,d===H.Down,this.scale,g));break;case l.Prebend:case l.PrebendBend:case l.PrebendRelease:let y=e+s.x+s.getBeatX(c.beat,ae.PreNotes);y+=s.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;let b=t+s.y+s.getScoreY(s.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+p;this.drawBendSlur(i,y,b,a,u,d===H.Down,this.scale),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),h=this.BendNoteHeads[0].getNoteValueY(o)+p,this.drawBendSlur(i,a,u,r,h,d===H.Down,this.scale,g))}}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class vn extends Jr{constructor(e,t,i=!1){super(e,t,i)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?H.Up:t.getBeatDirection(e)===H.Up?H.Down:H.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===H.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,ne.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,ne.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===H.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===g.None?i===this.tieDirection?this.tieDirection===H.Up?e.getNoteY(this.endBeat.maxNote,ne.TopWithStem):e.getNoteY(this.endBeat.minNote,ne.BottomWithStem):this.tieDirection===H.Up?e.getNoteY(this.endBeat.maxNote,ne.BottomWithStem):e.getNoteY(this.endBeat.minNote,ne.TopWithStem):this.tieDirection===H.Up?e.getNoteY(this.endBeat.maxNote,ne.Top):e.getNoteY(this.endBeat.minNote,ne.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,ae.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>u.Whole&&e===this.tieDirection?ae.Stem:ae.MiddleNotes)}}class Nn extends Ls{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,oe.Left)-2*this.scale,n=t+s.y+s.getNoteY(this._startNote,ne.Center),o=r-a,h=t+s.y;switch(this._inType){case b.IntoFromBelow:h+=s.getNoteY(this._startNote,ne.Bottom);break;case b.IntoFromAbove:h+=s.getNoteY(this._startNote,ne.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,d=0,c=!1;switch(this._outType){case S.Shift:case S.Legato:if(o=e+s.x+s.getBeatX(this._startNote.beat,ae.PostNotes),h=t+s.y+s.getNoteY(this._startNote,ne.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,ae.PreNotes)-r,d=t+i.y+i.getNoteY(this._startNote.slideTarget,ne.Center)):(l=e+s.x+s.width,d=h),this._startNote.slideTarget.realValue>this._startNote.realValue?(h+=n,d-=n):(h-=n,d+=n)}else l=e+s.x+this._parent.x,d=h;break;case S.OutUp:o=e+s.x+s.getNoteX(this._startNote,oe.Right),h=t+s.y+s.getNoteY(this._startNote,ne.Center),l=o+a,d=t+s.y+s.getNoteY(this._startNote,ne.Top);break;case S.OutDown:o=e+s.x+s.getNoteX(this._startNote,oe.Right),h=t+s.y+s.getNoteY(this._startNote,ne.Center),l=o+a,d=t+s.y+s.getNoteY(this._startNote,ne.Bottom);break;case S.PickSlideUp:o=e+s.x+s.getNoteX(this._startNote,oe.Right),h=t+s.y+s.getNoteY(this._startNote,ne.Center),d=t+s.y+s.getNoteY(this._startNote,ne.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,ae.PreNotes)),c=!0;break;case S.PickSlideDown:o=e+s.x+s.getNoteX(this._startNote,oe.Right),h=t+s.y+s.getNoteY(this._startNote,ne.Center),d=t+s.y+s.getNoteY(this._startNote,ne.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,ae.PreNotes)),c=!0;break;default:return}this.paintSlideLine(i,c,o,l,h,d)}paintSlideLine(e,t,i,s,a,r){if(t){let t=new or(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 xn extends vn{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===H.Up?this.startNoteRenderer.getNoteY(this._startNote,ne.Top):this.startNoteRenderer.getNoteY(this._startNote,ne.Bottom):this.startNoteRenderer.getNoteY(this._startNote,ne.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===H.Up?this.endNoteRenderer.getNoteY(this._endNote,ne.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,ne.BottomWithStem):this.tieDirection===H.Up?this.endNoteRenderer.getNoteY(this._endNote,ne.Top):this.endNoteRenderer.getNoteY(this._endNote,ne.Bottom):this.endNoteRenderer.getNoteY(this._endNote,ne.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===H.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===H.Down}isEndCentered(){return this._startNote.beat.graceType===g.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===H.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===H.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===g.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,ae.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,oe.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,ae.Stem):this.endNoteRenderer.getNoteX(this._endNote,oe.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,ae.PreNotes)}}class Pn extends Jr{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)===H.Up?H.Down:H.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===H.Up?this.startNoteRenderer.getNoteY(this.startNote,ne.Top):this.startNoteRenderer.getNoteY(this.startNote,ne.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===H.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===H.Up?e.getNoteY(this.endNote,ne.Top):e.getNoteY(this.endNote,ne.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,ae.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,ae.PreNotes)}}class En extends As{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 vn(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 vn(e,this.beat,!0))}this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(e.isVisible){if(e.isTieOrigin&&!e.hasBend&&!e.beat.hasWhammyBar&&e.beat.graceType!==g.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){let t=new Pn(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){let t=new Pn(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==b.None||e.slideOutType!==S.None){let t=new Nn(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){let t=new xn(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){let t=new xn(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new xn(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===H.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,s=t===H.Up?e.beat.minNote:e.beat.maxNote;const a=new xn(i,s,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new kn(e.beat);this._bend=t,t.renderer=this.renderer,this.addTie(t)}this._bend.addBends(e)}}}}class Cn extends wa{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._firstLineY=0,this._startSpacing=!1,this.accidentalHelper=new pa(this)}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}get lineOffset(){return(wa.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===H.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===H.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=P.Center,i.textBaseline=E.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 d=10*this.scale,c=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,_=this.calculateBeamYWithDirection(y,f,S),w=this.calculateBeamYWithDirection(b,m,S);u&&(_=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,N=k+B/2+T,x=(w-_)/(m-f),P=_-x*f,E=x*v+P,C=x*k+P,F=x*N+P;S===H.Down&&(d*=-1,c*=-1),i.beginPath(),i.moveTo(e+this.x+f,t+this.y+_-d|0),i.lineTo(e+this.x+f,t+this.y+_-d-c|0),i.lineTo(e+this.x+v,t+this.y+E-d-c|0),i.stroke(),i.beginPath(),i.moveTo(e+this.x+N,t+this.y+F-d-c|0),i.lineTo(e+this.x+m,t+this.y+w-d-c|0),i.lineTo(e+this.x+m,t+this.y+w-d|0),i.stroke(),i.fillText(a,e+this.x+k,t+this.y+C-d-c)}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===H.Down&&(d*=-1,c*=-1),i.font=r.effectFont,i.fillText(a,e+this.x+u,t+this.y+p-d-c)}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*=Is.GraceScale),t}getBarStemSize(e){let t=0;switch(e){case u.QuadrupleWhole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:t=6;break;case u.ThirtySecond:t=8;break;case u.SixtyFourth:case u.OneHundredTwentyEighth:t=9;break;case u.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}getFlagStemSize(e){let t=0;switch(e){case u.QuadrupleWhole:case u.Half:case u.Quarter:case u.Eighth:case u.Sixteenth:case u.ThirtySecond:case u.SixtyFourth:case u.OneHundredTwentyEighth:case u.TwoHundredFiftySixth:t=6;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){let i=super.getNoteY(e,t);if(isNaN(i)){const t=pa.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 fa;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===H.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):i===H.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===H.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):i===H.Up?this.getScoreY(this.accidentalHelper.getMinLine(r))-s:this.getScoreY(this.accidentalHelper.getMaxLine(r))+s;let o=10*this.scale;if(i===H.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),i===H.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),i===H.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),i===H.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(i===H.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=ke.getIndex(e.shortestDuration)-2;let a=e.isGrace?Is.GraceScale:1,r=s*(wa.BeamSpacing+wa.BeamThickness)*this.scale*a;if(r+=wa.BeamSpacing,i===H.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===H.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!==g.None?Is.GraceScale:1,o=s.getBeatLineX(r),h=s.direction,l=t+this.y;l+=h===H.Up?this.getScoreY(this.accidentalHelper.getMaxLine(r)):this.getScoreY(this.accidentalHelper.getMinLine(r));let d=t+this.y;d+=this.calculateBeamY(s,o),i.lineWidth=wa.StemWidth*this.scale,i.beginPath(),i.moveTo(e+this.x+o,l),i.lineTo(e+this.x+o,d),i.stroke(),i.lineWidth=this.scale;let c=d;h===H.Down?c+=2*i.font.size:0!==a&&(c-=1.5*i.font.size),this.paintFingering(i,r,e+this.x+o,h,c);let u=6*this.scale*n,p=(wa.BeamSpacing+wa.BeamThickness)*this.scale*n,f=wa.BeamThickness*this.scale*n,m=ke.getIndex(r.duration)-2,y=t+this.y;h===H.Down&&(p=-p,f=-f);for(let t=0;t<m;t++){let n=0,h=0,l=0,d=0,c=y+t*p;if(a<s.beats.length-1){if(ma.isFullBarJoin(r,s.beats[a+1],t))n=o,h=s.getBeatLineX(s.beats[a+1]);else{if(0!==a&&ma.isFullBarJoin(s.beats[a-1],r,t))continue;n=o,h=n+u}l=c+this.calculateBeamY(s,n),d=c+this.calculateBeamY(s,h),Cn.paintSingleBar(i,e+this.x+n,l,e+this.x+h,d,f)}else a>0&&!ma.isFullBarJoin(r,s.beats[a-1],t)&&(n=o-u,h=o,l=c+this.calculateBeamY(s,n),d=c+this.calculateBeamY(s,h),Cn.paintSingleBar(i,e+this.x+n,l,e+this.x+h,d,f))}}}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(e,t,i,s){let a=s.beats[0];if(a.graceType===g.BendGrace||a.graceType!==g.None&&this.settings.notation.notationMode===T.SongBook)return;let r=a.graceType!==g.None,n=r?Is.GraceScale:1,o=this.getFlagStemSize(s.shortestDuration),h=s.getBeatLineX(a),l=s.direction,d=this.getScoreY(this.accidentalHelper.getMinLine(a)),c=this.getScoreY(this.accidentalHelper.getMaxLine(a)),u=0,p=0;if(l===H.Down?(c+=o*n,u=c,p=t+this.y+c):(d-=o*n,u=d,p=t+this.y+d),this.paintFingering(i,a,e+this.x+h,l,p),s.hasLine){if(i.lineWidth=wa.StemWidth*this.scale,i.beginPath(),i.moveTo(e+this.x+h,t+this.y+d),i.lineTo(e+this.x+h,t+this.y+c),i.stroke(),i.lineWidth=this.scale,a.graceType===g.BeforeBeat){let s=15*this.scale,a=12*this.scale;i.beginPath(),l===H.Down?(i.moveTo(e+this.x+h-a/2,t+this.y+c-s),i.lineTo(e+this.x+h+a/2,t+this.y+c)):(i.moveTo(e+this.x+h-a/2,t+this.y+d+s),i.lineTo(e+this.x+h+a/2,t+this.y+d)),i.stroke()}if(s.hasFlag){let s=new Rs(h-this.scale/2,u,a.duration,l,r);s.renderer=this,s.doLayout(),s.paint(e+this.x,t+this.y,i)}}}paintFingering(e,t,i,s,a){let r=this.settings;if(r.notation.fingeringMode!==B.ScoreDefault&&r.notation.fingeringMode!==B.ScoreForcePiano)return;s===H.Up?i-=10*this.scale:i+=3*this.scale;let n=t.notes.slice(0);n.sort(((e,t)=>e.realValue-t.realValue));for(let s=0;s<n.length;s++){let o=n[s],h=null;o.leftHandFinger!==f.Unknown?h=ke.fingerToString(r,t,o.leftHandFinger,!0):o.rightHandFinger!==f.Unknown&&(h=ke.fingerToString(r,t,o.rightHandFinger,!1)),h&&(e.fillText(h,i,a),a-=0|e.font.size)}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new zr(0,0,1.5,3)),this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let e=0;switch(this.bar.clef){case r.Neutral:e=this.bar.staff.standardNotationLineCount-1;break;case r.F4:e=2;break;case r.C3:e=4;break;case r.C4:e=2;break;case r.G2:e=6}this.createStartSpacing(),this.addPreBeatGlyph(new Vr(0,this.getScoreY(e)+.5*wa.StaffLineThickness,this.bar.clef,this.bar.clefOttava))}(0===this.index&&this.bar.masterBar.keySignature!==L.C||this.bar.previousBar&&this.bar.masterBar.keySignature!==this.bar.previousBar.masterBar.keySignature)&&(this.createStartSpacing(),this.createKeySignatureGlyphs()),(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs()),this.addPreBeatGlyph(new Or(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 Hr(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Wr(0,this.getScoreHeight(-.5),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new Gr(0,0))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new un(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 r.Neutral:e=0;break;case r.G2:e=1;break;case r.F4:e=3;break;case r.C3:e=2;break;case r.C4:e=0}let s=new Map,a=[];if(ke.keySignatureIsSharp(t))for(let i=0;i<Math.abs(t);i++){let t=Cn.SharpKsSteps[i]+e;a.push(new Ar(0,this.getScoreY(t),re.Sharp,!1)),s.set(t,!0)}else for(let i=0;i<Math.abs(t);i++){let t=Cn.FlatKsSteps[i]+e;a.push(new Ar(0,this.getScoreY(t),re.Flat,!1)),s.set(t,!0)}let n=Math.abs(i),o=ke.keySignatureIsSharp(i)?Cn.SharpKsSteps:Cn.FlatKsSteps;for(let t=0;t<n;t++){let i=o[t]+e;s.has(i)||this.addPreBeatGlyph(new Ar(0,this.getScoreY(o[t]+e),re.Natural,!1))}for(let e of a)this.addPreBeatGlyph(e)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new un(0,0,5*this.scale));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new Tn(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 En(i,this.getVoiceContainer(e));s.preNotes=new Sn,s.onNotes=new yn,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*wa.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,ne.Center),i=this.getNoteY(e.lowestNoteInHelper,ne.Center),s=this.getStemSize(e);e.hasTuplet&&(s+=2*this.resources.effectFont.size),e.direction==H.Up?t-=s:i+=s;for(const s of e.beats)this.helpers.collisionHelper.reserveBeatSlot(s,t,i)}}}Cn.StaffId="score",Cn.SharpKsSteps=[-1,2,-2,1,4,0,3],Cn.FlatKsSteps=[3,0,4,1,5,2,6];class Fn extends ha{get staffId(){return Cn.StaffId}create(e,t){return new Cn(e,t)}constructor(){super()}}class Ln extends Ls{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 b.IntoFromBelow:h=e+s.x+s.getNoteX(this._startNote,oe.Left),l=t+s.y+s.getNoteY(this._startNote,ne.Center),n=h-a,o=t+s.y+s.getNoteY(this._startNote,ne.Center)+r;break;case b.IntoFromAbove:h=e+s.x+s.getNoteX(this._startNote,oe.Left),l=t+s.y+s.getNoteY(this._startNote,ne.Center),n=h-a,o=t+s.y+s.getNoteY(this._startNote,ne.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,d=!1;const c=2*this.scale;switch(this._outType){case S.Shift:case S.Legato:if(n=e+s.x+s.getBeatX(this._startNote.beat,ae.PostNotes),o=t+s.y+s.getNoteY(this._startNote,ne.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,ae.OnNotes)-c,l=t+i.y+i.getNoteY(this._startNote.slideTarget,ne.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 S.OutUp:n=e+s.x+s.getNoteX(this._startNote,oe.Right),o=t+s.y+s.getNoteY(this._startNote,ne.Center),h=n+a-c,l=t+s.y+s.getNoteY(this._startNote,ne.Center)-r;break;case S.OutDown:n=e+s.x+s.getNoteX(this._startNote,oe.Right),o=t+s.y+s.getNoteY(this._startNote,ne.Center),h=n+a-c,l=t+s.y+s.getNoteY(this._startNote,ne.Center)+r;break;case S.PickSlideDown:n=e+s.x+s.getNoteX(this._startNote,oe.Right),o=t+s.y+s.getNoteY(this._startNote,ne.Center),h=e+s.x+s.getBeatX(this._startNote.beat,ae.EndBeat),l=o+3*r,d=!0;break;case S.PickSlideUp:n=e+s.x+s.getNoteX(this._startNote,oe.Right),o=t+s.y+s.getNoteY(this._startNote,ne.Center),h=e+s.x+s.getBeatX(this._startNote.beat,ae.EndBeat),l=o-3*r,d=!0;break;default:return}this.paintSlideLine(i,d,n,h,o,l)}paintSlideLine(e,t,i,s,a,r){if(t){let t=new or(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 Mn extends Jr{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?H.Up:Mn.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?H.Up:H.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,ne.Center):this.tieDirection===H.Up?this.startNoteRenderer.getNoteY(this.startNote,ne.Top):this.startNoteRenderer.getNoteY(this.startNote,ne.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20*this.scale:this.startNoteRenderer.getNoteX(this.startNote,oe.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,oe.Left):this.endNoteRenderer.getNoteX(this.endNote,oe.Center)}}class Dn extends Mn{constructor(e,t,i,s=!1){super(e,t,s),this._direction=Mn.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!==Mn.getBeamDirectionForNote(e))return!1;switch(this._direction){case H.Up:e.realValue>this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue>this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat);break;case H.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,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 In extends As{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 Mn(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){let t=new Mn(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){let t=new Mn(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 Dn(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 Dn(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==b.None||e.slideOutType!==S.None){let t=new Ln(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new ln;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class Rn extends Ls{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 e=this._note,t=e.fret-e.beat.voice.bar.staff.transpositionPitch;if(e.harmonicType===m.Natural&&0!==e.harmonicValue&&(t=e.harmonicValue-e.beat.voice.bar.staff.transpositionPitch),e.isTieDestination)0===e.beat.index&&this.renderer.settings.notation.notationMode==T.GuitarPro||(e.bendType===l.Bend||e.bendType===l.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(k.TabNotesOnTiedBends)?this._noteString="("+(e.tieOrigin.fret-e.beat.voice.bar.staff.transpositionPitch).toString()+")":this._noteString="";else if(this._noteString=e.isDead?"x":t.toString(),e.isGhost)this._noteString="("+this._noteString+")";else if(e.harmonicType===m.Natural){let e=this._noteString.indexOf(String.fromCharCode(46));e>=0&&(this._noteString=this._noteString.substr(0,e+2)),this._noteString="<"+this._noteString+">"}if(e.isTrill)this._trillNoteString="("+(e.trillFret-e.beat.voice.bar.staff.transpositionPitch).toString()+")";else if(ke.isAlmostEqualTo(e.harmonicValue,0))this._trillNoteString="";else switch(e.harmonicType){case m.Artificial:case m.Pinch:case m.Tap:case m.Semi:case m.Feedback:let i=(t+e.harmonicValue).toString(),s=i.indexOf(String.fromCharCode(46));s>=0&&(i=i.substr(0,s+2)),this._trillNoteString="<"+i+">";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 fs;s.note=this._note,s.noteHeadBounds=new at,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 An extends Ls{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 oe.Left:break;case oe.Center:s+=i.noteStringWidth/2;break;case oe.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 ne.Top:case ne.TopWithStem:s-=i.height/2+2*this.scale;break;case ne.Center:break;case ne.Bottom:case ne.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,ne.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=E.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 On extends Ds{constructor(e,t,i,s){super(e,t,1,sn.getSymbol(s)),this._isVisibleRest=i,this._duration=s}doLayout(){this._isVisibleRest?this.width=sn.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 Gn extends xa{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 e=this.renderer;if(this.container.beat.isRest){let t=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),i=e.getTabY(t);const s=new On(0,i,e.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&&e.showRests){this.addGlyph(new un(0,0,5*this.scale));for(let e=0;e<this.container.beat.dots;e++)this.addGlyph(new Xr(0,i,1.5*this.scale))}}else{let t=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==g.None;const i=new An(0,0,t);this.noteNumbers=i,i.beat=this.container.beat,i.beamingHelper=this.beamingHelper;for(let e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);if(this.addGlyph(i),this.container.beat.hasWhammyBar){let e=new dn(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!this.noteNumbers.beatEffects.has("tremolo")){let e=0,t=this.container.beat.tremoloSpeed;switch(t){case u.ThirtySecond:e=10;break;case u.Sixteenth:e=5;break;case u.Eighth:e=0}this.noteNumbers.beatEffects.set("tremolo",new en(5*this.scale,e*this.scale,t))}if(this.container.beat.dots>0&&e.settings.notation.rhythmMode!==w.Hidden){this.addGlyph(new un(0,0,5*this.scale));for(let t=0;t<this.container.beat.dots;t++)this.addGlyph(new Xr(0,e.lineOffset*e.bar.staff.tuning.length+e.settings.notation.rhythmHeight*e.scale,1.5*this.scale))}}if(!this.glyphs)return;let t=0;for(let e=0,i=this.glyphs.length;e<i;e++){let i=this.glyphs[e];i.x=t,i.renderer=this.renderer,i.doLayout(),t+=i.width}this.width=t,this.computedWidth=t,this.container.beat.isEmpty?this.centerX=this.width/2:this.container.beat.isRest?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.centerX=this.noteNumbers.x+this.noteNumbers.noteStringWidth/2}updateBeamingHelper(){this.container.beat.isRest?this.restGlyph.updateBeamingHelper(this.container.x+this.x):this.noteNumbers.updateBeamingHelper(this.container.x+this.x)}createNoteGlyph(e){let t=this.renderer,i=new Rn(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 Vn extends Ls{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,ne.Top),r=t+this.y+s.getNoteY(this._beat.minStringNote,ne.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 or(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 or(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 Hn extends Na{doLayout(){this.container.beat.brushType===d.None||this.container.beat.isRest||(this.addGlyph(new Vn(this.container.beat)),this.addGlyph(new un(0,0,4*this.scale))),super.doLayout()}constructor(){super()}}class Wn extends Ls{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?x.FourStringTabClef:x.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 zn extends Bn{get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?Is.GraceScale:1}}class Un extends wa{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(Un.TabLineSpacing+1)*this.scale}updateSizes(){let e=this.resources,t=(e.tablatureFont.size/2+.2*e.tablatureFont.size)*this.scale;this.topPadding=t,this.bottomPadding=t,this.height=this.lineOffset*(this.bar.staff.tuning.length-1)+2*t,this.settings.notation.rhythmMode!==w.Hidden&&(this.height+=this.settings.notation.rhythmHeight*this.settings.display.scale,this.bottomPadding+=this.settings.notation.rhythmHeight*this.settings.display.scale),this.updateFirstLineY(),super.updateSizes()}updateFirstLineY(){let e=this.resources;this._firstLineY=(e.tablatureFont.size/2+.2*e.tablatureFont.size)*this.scale}doLayout(){if(this.updateFirstLineY(),super.doLayout(),this.settings.notation.rhythmMode!==w.Hidden){let e=!1;for(let t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}e&&(this._tupletSize=.8*this.resources.effectFont.size,this.registerOverflowBottom(this._tupletSize))}}createPreBeatGlyphs(){if(super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new zr(0,0,1.5,3)),this.isFirstOfLine){let e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new Wn(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 Or(0,this.getTabHeight(-.5),this.bar.index+1))}createStartSpacing(){this._startSpacing||(this.addPreBeatGlyph(new un(0,0,2*this.scale)),this._startSpacing=!0)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new un(0,0,5*this.scale));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new zn(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon))}createVoiceGlyphs(e){for(let t=0,i=e.beats.length;t<i;t++){let i=e.beats[t],s=new In(i,this.getVoiceContainer(e));s.preNotes=new Hn,s.onNotes=new Gn,this.addBeatGlyph(s)}}createPostBeatGlyphs(){super.createPostBeatGlyphs(),this.bar.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new Hr(this.x,0)),this.bar.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Wr(0,this.getTabY(-1),this.bar.masterBar.repeatCount))):this.addPostBeatGlyph(new Gr(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*wa.StaffLineThickness),n=o[0]+o[1];i.fillRect(e+this.x+n,t+this.y+a|0,this.width-n,this.scale*wa.StaffLineThickness)}i.color=s.mainGlyphColor,this.paintSimileMark(e,t,i)}paint(e,t,i){super.paint(e,t,i),this.settings.notation.rhythmMode!==w.Hidden&&(this.paintBeams(e,t,i),this.paintTuplets(e,t,i))}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(e,t,i,s){i.color=0===s.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.isRestBeamHelper||(1===s.beats.length||this.settings.notation.rhythmMode===w.ShowWithBeams?this.paintFooter(e,t,i,s):this.paintBar(e,t,i,s))}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!==u.Half?o+=l.noteNumbers.getNoteY(l.noteNumbers.minStringNote,ne.Bottom)+this.lineOffset/2:o+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(r,t+this.y,e+this.x+n,o,h,i);let d=6*this.scale,c=-6*this.scale,p=3*this.scale,g=ke.getIndex(r.duration)-2,f=h;for(let t=0;t<g;t++){let o=0,h=0,l=0,u=0,g=f+t*c;if(1===s.beats.length)o=n,h=n+d,l=g,u=g,Un.paintSingleBar(i,e+this.x+o,l,e+this.x+h,u,p);else if(a<s.beats.length-1){if(ma.isFullBarJoin(r,s.beats[a+1],t))o=n,h=s.getBeatLineX(s.beats[a+1]);else{if(0!==a&&ma.isFullBarJoin(s.beats[a-1],r,t))continue;o=n,h=o+d}l=g,u=g,Un.paintSingleBar(i,e+this.x+o,l,e+this.x+h,u,p)}else a>0&&!ma.isFullBarJoin(r,s.beats[a-1],t)&&(o=n-d,h=n,l=g,u=g,Un.paintSingleBar(i,e+this.x+o,l,e+this.x+h,u,p))}}}}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=P.Center,i.textBaseline=E.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),d=l.getBeatLineX(o);i.font=r.effectFont;let c=i.measureText(a),u=3*this.scale,p=(s+d)/2,g=p-c/2-u,f=p+c/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+d,m-y-b|0),i.lineTo(e+this.x+d,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),d=t+this.y+this.height-this._tupletSize+.5*r.effectFont.size;i.font=r.effectFont,i.fillText(a,e+this.x+l,d)}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!==g.None||a.duration===u.Whole||a.duration===u.DoubleWhole||a.duration===u.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!==u.Half?n+=h.noteNumbers.getNoteY(h.noteNumbers.minStringNote,ne.Bottom):n+=this.height-this.settings.notation.rhythmHeight*this.settings.display.scale-this._tupletSize,this.paintBeamingStem(a,t+this.y,e+this.x+r,n,o,i),a.duration>u.Quarter){let t=new Rs(0,0,a.duration,H.Down,!1);t.renderer=this,t.doLayout(),t.paint(e+this.x+r,o,i)}}}}Un.StaffId="tab",Un.TabLineSpacing=10;class Xn extends ha{get staffId(){return Un.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 Un(e,t);return i.showRests=this._showRests,i.showTimeSignature=this._showTimeSignature,i.showTiedNotes=this._showTiedNotes,i}}class Yn extends Ms{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+Yn.Padding*this.scale}paint(e,t,i){let s=this.renderer.resources;i.font=s.effectFont;let a=i.textAlign;i.textAlign=P.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+(Yn.Padding-1)*this.scale,i.font.size/1.6)}}Yn.Padding=4;class qn extends Ya{get notationElement(){return k.EffectTap}get sizingMode(){return he.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new Yn}}class Jn{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"}(de||(de={}));class jn extends Jn{constructor(){super(...arguments),this.align=P.Left,this.frame=de.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class Qn extends Jn{constructor(){super(...arguments),this.chord=new Re}}class $n extends Jn{}class Kn extends Jn{}class Zn extends Jn{constructor(){super(...arguments),this.number=0}}class eo extends Jn{constructor(){super(...arguments),this.decrescendo=!1}}class to extends Jn{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class io extends Jn{constructor(){super(...arguments),this.octave=1}}class so extends Jn{}class ao{constructor(){this.defaultClef=r.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class ro{constructor(){this.from=0,this.to=0,this.curly=!1}}class no{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class oo{constructor(){this._trackChannel=0,this._beamingMode=F.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new Oe,this._voiceStates=new Map}parseXml(e,t){this._galleryObjects=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._voiceCounts=new Map,this._slurs=new Map,this._crescendo=new Map,this._isFirstSystem=!0;let i=new ct;try{i.parse(e)}catch(e){throw new ge("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 je);for(const e of t.voices)if(0===e.beats.length){const t=new Ie;t.isEmpty=!0,e.addBeat(t)}const s=t.masterBar;s.tempoAutomation&&(s.tempoAutomation.value!==e?e=s.tempoAutomation.value:s.tempoAutomation=null)}}}oo.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),oo.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?c.Decrescendo:c.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 ge("No valid XML");if("score"!==t.localName)throw new ge('Root node of XML was not "score"');this.score=new He,this.score.tempo=120;for(let e of t.childNodes)if(e.nodeType===G.Element)switch(e.localName){case"info":this.parseInfo(e);break;case"layout":this.parseLayout(e);break;case"gallery":this.parseGallery(e);break;case"pageObjects":this.parsePageObjects(e);break;case"systems":this.parseSystems(e)}}parseLayout(e){for(let t of e.childNodes)if(t.nodeType===G.Element)switch(t.localName){case"staves":this.parseLayoutStaves(t);break;case"brackets":this.parseBrackets(t)}const t=this._brackets.filter((e=>!!e.curly));t.sort(((e,t)=>e.from-t.from));let 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 Je,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===G.Element&&"bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new ro;t.from=parseInt(e.getAttribute("from")),t.to=parseInt(e.getAttribute("to")),e.attributes.has("curly")&&(t.curly="true"===e.attributes.get("curly")),this._brackets.push(t)}parseLayoutStaves(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new ao;t.description=e.getAttribute("description");for(let i of e.childNodes)if(i.nodeType===G.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 r.G2;case"bass":return r.F4;case"alto":case"tenor":return r.C4}return r.G2}parseClefOttava(e){return e.endsWith("-")?n._8vb:e.endsWith("+")?n._8va:n.Regular}parseSystems(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"system"===t.localName)this.parseSystem(t)}parseSystem(e){e.attributes.has("tempo")&&0===this.score.masterBars.length&&(this.score.tempo=parseInt(e.attributes.get("tempo"))),"0"===e.getAttribute("beamGrouping")&&(this._beamingMode=F.ForceSplitToNext);for(let t of e.childNodes)if(t.nodeType===G.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===G.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===G.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===G.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 me;if(e.bars.length>0?(t.clef=e.bars[e.bars.length-1].clef,t.clefOttava=e.bars[e.bars.length-1].clefOttava):t.clef=this._currentStaffLayout.defaultClef,e.addBar(t),e.bars.length>this.score.masterBars.length){let e=new Oe;this.score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.tripletFeel=e.previousMasterBar.tripletFeel),e.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,e.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,e.timeSignatureCommon=this._timeSignature.timeSignatureCommon}return t}newBar(e,t){this._currentVoiceState.currentBarIndex++,this._currentBar=this.getOrCreateBar(e,this._currentVoiceState.currentBarIndex),this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1),this._currentVoiceState.currentBarComplete=!1,this._currentVoiceState.currentPosition=0,this.ensureVoice(e,t)}parseVoice(e,t,i,s,r,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 no,this._currentVoiceState.currentBarIndex=r-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=H.Up;break;case"down":this._currentVoiceState.voiceStemDir=H.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const h=n.findChildElement("noteObjects");if(i.attributes.has("tempo")&&(this._currentBar.masterBar.tempoAutomation=new fe,this._currentBar.masterBar.tempoAutomation.isLinear=!0,this._currentBar.masterBar.tempoAutomation.type=a.Tempo,this._currentBar.masterBar.tempoAutomation.value=parseInt(i.attributes.get("tempo"))),h)for(let e of h.childNodes)if(e.nodeType===G.Element)switch(this._currentVoiceState.currentBarComplete&&"barline"!==e.localName&&this.newBar(t,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 Ie;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 je);(!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 Pe;for(let a of t.childNodes)if(a.nodeType===G.Element)switch(a.localName){case"stem":switch(a.getAttribute("dir")){case"up":e.preferredBeamDirection=H.Up;break;case"down":e.preferredBeamDirection=H.Down}break;case"articulation":switch(a.getAttribute("type")){case"staccato":i.isStaccato=!0;break;case"normalAccent":i.accentuated=s.Normal;break;case"strongAccent":i.accentuated=s.Heavy}break;case"lyric":this.parseLyric(e,a);break;case"drawObjects":this.parseBeatDrawObject(e,a);break;case"heads":this.parseHeads(e,i,a);break;case"beam":switch(a.getAttribute("group")){case"force":e.beamingMode=F.ForceMergeWithNext;break;case"divide":e.beamingMode=F.ForceSplitToNext}}}parseHeads(e,t,i){for(let s of i.childNodes)if(s.nodeType===G.Element&&"head"===s.localName)this.parseHead(e,t,s)}parseHead(e,t,i){const s=new Pe,a=ke.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===G.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===G.Element&&"drawObj"===i.localName){const t=this.parseDrawObj(i);if(t)if(t instanceof jn)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new nt,e.fermata.type=O.Medium):"f"===t.text?e.dynamics=p.F:"j"===t.text&&(e.dynamics=p.MF):this._isFirstSystem&&""===this.score.title&&t.align===P.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===P.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===P.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof Qn);else if(t instanceof Kn)e.vibrato=_.Slight;else if(t instanceof eo)e.crescendo=t.decrescendo?c.Decrescendo:c.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof $n){const i=t;this._slurs.set(e,i)}else t instanceof to&&this.applyVolta(t)}}parseBarDrawObject(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof to&&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===G.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 Ie;return i.beamingMode=this._beamingMode,this.parseDuration(e,i,t),i}if(1===parseInt(i)){let e=new Ie;return e.beamingMode=this._beamingMode,e.duration=u.Whole,e}return Be.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return u.DoubleWhole;case"1/1":return u.Whole;case"1/2":return u.Half;case"1/4":return u.Quarter;case"1/8":return u.Eighth;case"1/16":return u.Sixteenth;case"1/32":return u.ThirtySecond;case"1/64":return u.SixtyFourth;case"1/128":return u.OneHundredTwentyEighth;default:return Be.warning("Importer","Unsupported duration"),u.Quarter}}parseDuration(e,t,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===G.Element&&"drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof jn)switch(e.align){case P.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case P.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(let t of e.childNodes)if(t.nodeType===G.Element&&"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===G.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 so}parseOctaveClef(e){const t=new io;return e.attributes.has("octave")&&(t.octave=parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new to;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 eo;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new Zn;return e.attributes.has("number")&&(t.number=parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new Kn}parseSlur(e){return new $n}parseGuitar(e){const t=new Qn,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 jn;switch(e.attributes.has("x")&&(t.x=parseFloat(e.attributes.get("x"))),e.attributes.has("x")&&(t.y=parseFloat(e.attributes.get("y"))),e.getAttribute("align")){case"left":t.align=P.Left;break;case"center":t.align=P.Center;break;case"right":t.align=P.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=de.Rectangle;break;case"ellipse":t.frame=de.Ellipse;break;case"circle":t.frame=de.Circle;break;case"none":t.frame=de.None}if(e.firstElement){for(let i of e.childNodes)if(i.nodeType===G.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===G.Element)switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class ho extends ue{get name(){return"Capella"}constructor(){super()}readScore(){Be.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new Nt(this.data).read(),Be.debug(this.name,"Zip entries loaded"),e.length>0){for(let i of e)if("score.xml"===i.fileName)t=$e.toString(i.data,this.settings.importer.encoding)}else this.data.reset(),t=$e.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new ge("No valid capella file");Be.debug(this.name,"Start Parsing score.xml");try{let e=new oo;return e.parseXml(t,this.settings),Be.debug(this.name,"score.xml parsed"),e.score}catch(e){throw new ge("Failed to parse CapXML",e)}}}class lo{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 co{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)}}class uo{constructor(e,t){this.vertical=e,this.createLayout=t}}class po{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class go{static createStyleElement(e,t){let i=e.getElementById("alphaTabStyle");if(!i){if(!t)return void Be.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: ${go.MusicFontSize}px;\n overflow: visible !important;\n }`;i.innerHTML=s,e.getElementsByTagName("head").item(0).appendChild(i),go.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===go._globalThis){try{go._globalThis=globalThis}catch(e){}void 0===go._globalThis&&(go._globalThis=self),void 0===go._globalThis&&(go._globalThis=global),void 0===go._globalThis&&(go._globalThis=window),void 0===go._globalThis&&(go._globalThis=Function("return this")())}return this._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in go.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in go.globalThis}static createAlphaTabWorker(e){if(go.isWebPackBundled)return new Worker(new URL("@coderline/alphatab",import.meta.url));if(!e)throw new pe(i.General,"Could not detect alphaTab script file, cannot initialize renderer");try{if(go.webPlatform===ie.BrowserModule){const t=`import * as alphaTab from '${e}'`,i=new Blob([t],{type:"text/javascript"});return new Worker(URL.createObjectURL(i),{type:"module"})}{const t=`importScripts('${e}')`,i=new Blob([t]);return new Worker(URL.createObjectURL(i))}}catch(t){return Be.warning("Rendering","Could not create inline worker, fallback to normal worker"),new Worker(e)}}static throttle(e,t){let i=0;return()=>{go.globalThis.clearTimeout(i),i=go.globalThis.setTimeout(e,t)}}static detectScriptFile(){try{const e=import.meta.url;if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in go.globalThis&&document.currentScript?document.currentScript.src:null}static registerJQueryPlugin(){if(!go.isRunningInWorker&&go.globalThis&&"jQuery"in go.globalThis){let e=go.globalThis.jQuery,t=new ra;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:ra.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&go.renderEngines.has(e)?go.renderEngines.get(e):go.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&go.layoutEngines.has(t)?go.layoutEngines.get(t):go.layoutEngines.get(e.Page)}static buildImporters(){return[new tt,new Lt,new xt,new Mt,new ho,new et]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new po(!0,(()=>new oa))),e.set("default",e.get("svg")),go.createPlatformSpecificRenderEngines(e),e}static createPlatformSpecificRenderEngines(e){e.set("html5",new po(!1,(()=>new _s)))}static createDefaultStaveProfiles(){const e=new Map;e.set(t.ScoreTab,[new Ea("score-effects",[new cr,new mr,new Ka,new ur,new Ia,new Ua,new yr,new gr,new er(!0),new br,new nr,new Sr,new hr,new qn,new La]),new Fn,new Ea("tab-effects",[new Oa,new er(!1),new Va,new $a,new gr,new br,new nr,new Sr,new hr,new lr,new Wa,new Ja(m.Natural),new Ja(m.Artificial),new Ja(m.Pinch),new Ja(m.Tap),new Ja(m.Semi),new Ja(m.Feedback),new ja,new Da,new Xa,new tr,new ar,new ir,new qn]),new Xn(!1,!1,!1)]),e.set(t.Score,[new Ea("score-effects",[new cr,new mr,new Ka,new ur,new Ia,new Ua,new yr,new gr,new er(!0),new br,new nr,new Sr,new hr,new Wa,new ja,new tr,new ar,new ir,new qn,new La]),new Fn,new Ea("score-bottom-effects",[new Oa,new er(!1),new Va,new $a])]);let i=[new cr,new mr,new Ka,new ur,new Ia,new Ua,new gr,new br,new nr,new Sr,new hr,new lr,new Wa,new Ja(m.Artificial),new Ja(m.Pinch),new Ja(m.Tap),new Ja(m.Semi),new Ja(m.Feedback),new ja,new Da,new Xa,new tr,new ar,new ir,new qn,new La];return e.set(t.Tab,[new Ea("tab-effects",i),new Xn(!0,!0,!0),new Ea("tab-bottom-effects",[new $a])]),e.set(t.TabMixed,[new Ea("tab-effects",i),new Xn(!1,!1,!1),new Ea("tab-bottom-effects",[new $a])]),e}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.Page,new uo(!0,(e=>new Rr(e)))),t.set(e.Horizontal,new uo(!1,(e=>new Ir(e)))),t}static platformInit(){go.isRunningInAudioWorklet?ea.init():go.isRunningInWorker?(Ss.init(),ls.init()):go.webPlatform!==ie.Browser&&go.webPlatform!==ie.BrowserModule||(go.registerJQueryPlugin(),go.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in go.globalThis||(go.globalThis.ResizeObserver=lo),"IntersectionObserver"in go.globalThis||(go.globalThis.IntersectionObserver=co),"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)}))}static detectWebPack(){try{if("function"==typeof __webpack_require__)return!0}catch(e){}return!1}static detectWebPlatform(){try{if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return ie.NodeJs}catch(e){}try{const e=import.meta.url;if(e&&"string"==typeof e&&!e.startsWith("file://"))return ie.BrowserModule}catch(e){}return ie.Browser}}go.MusicFontSize=34,go.HighDpiFactor=1,go._globalThis=void 0,go.webPlatform=go.detectWebPlatform(),go.isWebPackBundled=go.detectWebPack(),go.scriptFile=go.detectScriptFile(),go.bravuraFontChecker=new Ys(["alphaTab"]),go.renderEngines=go.createDefaultRenderEngines(),go.layoutEngines=go.createDefaultLayoutEngines(),go.staveProfiles=go.createDefaultStaveProfiles(),go.platformInit();class fo{constructor(){if(this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=v.Info,this.useWorkers=!0,this.includeNoteBounds=!1,!go.isRunningInWorker&&go.globalThis.ALPHATAB_ROOT?(this.scriptFile=go.globalThis.ALPHATAB_ROOT,this.scriptFile=fo.ensureFullUrl(this.scriptFile),this.scriptFile=fo.appendScriptName(this.scriptFile)):this.scriptFile=go.scriptFile,!go.isRunningInWorker&&go.globalThis.ALPHATAB_FONT)this.fontDirectory=go.globalThis.ALPHATAB_FONT,this.fontDirectory=fo.ensureFullUrl(this.fontDirectory);else if(this.fontDirectory=this.scriptFile,this.fontDirectory){let e=this.fontDirectory.lastIndexOf(String.fromCharCode(47));e>=0&&(this.fontDirectory=this.fontDirectory.substr(0,e)+"/font/")}}static ensureFullUrl(e){var t,i,s;if(!e)return"";if(!e.startsWith("http")&&!e.startsWith("https")&&!e.startsWith("file")){let a="",r=go.globalThis.location;if(a+=null===(t=r.protocol)||void 0===t?void 0:t.toString(),a+="//".toString(),r.hostname&&(a+=null===(i=r.hostname)||void 0===i?void 0:i.toString()),r.port&&(a+=":".toString(),a+=null===(s=r.port)||void 0===s?void 0:s.toString()),!e.startsWith("/")){let e=r.pathname.split("/").slice(0,-1).join("/");e.length>0&&(e.startsWith("/")||(a+="/".toString()),a+=null==e?void 0:e.toString())}return e.startsWith("/")||(a+="/".toString()),a+=null==e?void 0:e.toString(),a}return e}static appendScriptName(e){return e&&!e.endsWith(".js")&&(e.endsWith("/")||(e+="/"),e+="alphaTab.js"),e}}class mo{}mo.version="1.3.0-alpha.607",mo.date="2023-04-12T09:02:19.552Z";var yo,bo=Object.freeze({__proto__:null,ScoreImporter:ue,ScoreLoader:zs,UnsupportedFormatError:ge});class So{init(e,t){this.data=e,this.settings=t}export(e,t=null){const i=Ke.withCapacity(1024);return this.init(i,null!=t?t:new Wi),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"}(yo||(yo={}));class _o{constructor(e,t,i=null){if(this.icon=yo.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 wo{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new ct;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 a=0;switch(t.isStaccato&&(a|=1),t.accentuated){case s.Normal:a|=8;break;case s.Heavy:a|=4}if(a>0&&(i.addElement("Accent").innerText=a.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 f.Thumb:i.addElement("LeftFingering").innerText="P";break;case f.IndexFinger:i.addElement("LeftFingering").innerText="I";break;case f.MiddleFinger:i.addElement("LeftFingering").innerText="M";break;case f.AnnularFinger:i.addElement("LeftFingering").innerText="A";break;case f.LittleFinger:i.addElement("LeftFingering").innerText="C"}switch(t.rightHandFinger){case f.Thumb:i.addElement("RightFingering").innerText="P";break;case f.IndexFinger:i.addElement("RightFingering").innerText="I";break;case f.MiddleFinger:i.addElement("RightFingering").innerText="M";break;case f.AnnularFinger:i.addElement("RightFingering").innerText="A";break;case f.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!==m.None){switch(t.harmonicType){case m.Natural:this.writeSimplePropertyNode(i,"HarmonicType","HType","Natural");break;case m.Artificial:this.writeSimplePropertyNode(i,"HarmonicType","HType","Artificial");break;case m.Pinch:this.writeSimplePropertyNode(i,"HarmonicType","HType","Pinch");break;case m.Tap:this.writeSimplePropertyNode(i,"HarmonicType","HType","Tap");break;case m.Semi:this.writeSimplePropertyNode(i,"HarmonicType","HType","Semi");break;case m.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 b.IntoFromAbove:s|=32;break;case b.IntoFromBelow:s|=16}switch(t.slideOutType){case S.Shift:s|=1;break;case S.Legato:s|=2;break;case S.OutDown:s|=4;break;case S.OutUp:s|=8;break;case S.PickSlideDown:s|=64;break;case S.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=Ye.defaultSteps[a],o=Ye.defaultAccidentals[a]};switch(h(),s){case y.Default:break;case y.ForceNone:case y.ForceNatural:o="";break;case y.ForceSharp:o="#";break;case y.ForceDoubleSharp:"#"===o&&(i-=2,h()),o="x";break;case y.ForceFlat:"#"===o&&(i+=1,h()),o="b";break;case y.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 be((a.offset+r.offset)/2,(a.value+r.value)/2)}this.writeSimplePropertyNode(e,"BendDestinationOffset","Float",this.toBendOffset(r.offset).toString()),this.writeSimplePropertyNode(e,"BendDestinationValue","Float",this.toBendValue(r.value).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset1","Float",this.toBendOffset(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/be.MaxPosition*100}writeBeatNode(e,t,i){const s=e.addElement("Beat");if(s.attributes.set("id",t.id.toString()),s.addElement("Dynamic").innerText=p[t.dynamics],t.fadeIn&&(s.addElement("Fadding").innerText="FadeIn"),t.isTremolo)switch(t.tremoloSpeed){case u.Eighth:s.addElement("Tremolo").innerText="1/2";break;case u.Sixteenth:s.addElement("Tremolo").innerText="1/4";break;case u.ThirtySecond:s.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&s.addElement("Chord").setCData(t.chordId),t.crescendo!==c.None&&(s.addElement("Hairpin").innerText=c[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 g.OnBeat:case g.BeforeBeat:s.addElement("GraceNotes").innerText=g[t.graceType]}if(t.ottava!==n.Regular&&(s.addElement("Ottavia").innerText=n[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 H.Up:s.addElement("TransposedPitchStemOrientation").innerText="Upward";break;case H.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 u.QuadrupleWhole:r="Long";break;case u.DoubleWhole:r="DoubleWhole";break;case u.Whole:r="Whole";break;case u.Half:r="Half";break;case u.Quarter:r="Quarter";break;case u.Eighth:r="Eighth";break;case u.Sixteenth:r="16th";break;case u.ThirtySecond:r="32nd";break;case u.SixtyFourth:r="64th";break;case u.OneHundredTwentyEighth:r="128th";break;case u.TwoHundredFiftySixth:r="256th"}e.addElement("NoteValue").innerText=r}e.addElement("Rhythm").attributes.set("ref",a)}writeWhammyNode(e,t){t.hasWhammyBar&&t.whammyBarPoints.length<=4&&this.writeStandardWhammy(e,t.whammyBarPoints)}writeStandardWhammy(e,t){const 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 be((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("4"),i.addElement("ScoreSystemsLayout").setCData("4"),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="3",i.addElement("SystemsLayout").innerText="1",i.addElement("AutoBrush"),i.addElement("PalmMute").innerText="0",i.addElement("PlayingStyle").innerText=ce.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",i.addElement("UseOneChannelPerString"),i.addElement("IconId").innerText=wo.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?wo.DrumKitProgramInfo.icon:wo.MidiProgramInfoLookup.has(e.program)?wo.MidiProgramInfoLookup.get(e.program).icon:yo.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 d=t.addElement("Automation");d.addElement("Type").innerText="Sound",d.addElement("Linear").innerText="false",d.addElement("Bar").innerText=r.toString(),d.addElement("Position").innerText=o.toString(),d.addElement("Visible").innerText="true",d.addElement("Value").setCData(`${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`,r=`Midi/${t.playbackInfo.program}`,n="Factory";let o=!1;for(const h of t.staves)for(const l of h.bars)for(const h of l.voices)for(const d of h.beats){const h=d.getAutomation(a.Instrument),c=0===l.index&&0===d.index;if(h){const a=c?e:`ProgramChange_${d.id}`,u=c?r:`Midi/${h.value}`,p=c?n:"User";c||o||(this.writeSoundAndAutomation(i,s,e,r,n,t.staves[0].bars[0].index,t.playbackInfo.program),o=!0),this.writeSoundAndAutomation(i,s,a,u,p,l.index,h.value,h.ratioPosition),c&&(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=[f.LittleFinger,f.AnnularFinger,f.MiddleFinger,f.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():f.IndexFinger;for(const e of s){const s=o.addElement("Position");switch(a){case f.LittleFinger:s.attributes.set("finger","Pinky");break;case f.AnnularFinger:s.attributes.set("finger","Ring");break;case f.MiddleFinger:s.attributes.set("finger","Middle");break;case f.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 d=s.addElement("Property");d.attributes.set("name","ShowFingering"),d.attributes.set("type","bool"),d.attributes.set("value",t.showFingering?"true":"false");const c=s.addElement("Chord"),u=c.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=c.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=c.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const m=c.addElement("Degree");m.attributes.set("interval","Fifth"),m.attributes.set("alteration","Perfect"),m.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,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 Ae;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(Ne.instrumentArticulations.values());i.addElement("Name").innerText=wo.DrumKitProgramInfo.instrumentSetName,i.addElement("Type").innerText=wo.DrumKitProgramInfo.instrumentSetType;let s="",r=new ot,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 E.Top:e.addElement("TechniquePlacement").innerText="below";break;case E.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case E.Bottom:e.addElement("TechniquePlacement").innerText="above"}e.addElement("TechniqueSymbol").innerText=this.mapMusicSymbol(t.techniqueSymbol),e.addElement("InputMidiNumbers").innerText="",e.addElement("OutputMidiNumber").innerText=t.outputMidiNumber.toString()}}else{const e=wo.MidiProgramInfoLookup.has(t.playbackInfo.program)?wo.MidiProgramInfoLookup.get(t.playbackInfo.program):wo.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===x.None)return"";let t=x[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!==I.NoTripletFeel&&(i.addElement("TripletFeel").innerText=I[t.tripletFeel]),this.writeFermatas(i,t)}writeFermatas(e,t){var i,s;const a=null!==(s=null===(i=t.fermata)||void 0===i?void 0:i.size)&&void 0!==s?s:0;if(0!==a&&a>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/ye.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=O[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=r[t.clef],t.clefOttava!==n.Regular&&(i.addElement("Ottavia").innerText=n[t.clefOttava].substr(1)),t.simileMark!==o.None&&(i.addElement("SimileMark").innerText=o[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(" ")}}wo.MidiProgramInfoLookup=new Map([[0,new _o(yo.Piano,"Acoustic Piano")],[1,new _o(yo.Piano,"Acoustic Piano")],[2,new _o(yo.Piano,"Electric Piano")],[3,new _o(yo.Piano,"Acoustic Piano")],[4,new _o(yo.Piano,"Electric Piano")],[5,new _o(yo.Piano,"Electric Piano")],[6,new _o(yo.Piano,"Harpsichord")],[7,new _o(yo.Piano,"Harpsichord")],[8,new _o(yo.PitchedIdiophone,"Celesta")],[9,new _o(yo.PitchedIdiophone,"Vibraphone")],[10,new _o(yo.PitchedIdiophone,"Vibraphone")],[11,new _o(yo.PitchedIdiophone,"Vibraphone")],[12,new _o(yo.PitchedIdiophone,"Xylophone")],[13,new _o(yo.PitchedIdiophone,"Xylophone")],[14,new _o(yo.PitchedIdiophone,"Vibraphone")],[15,new _o(yo.Banjo,"Banjo")],[16,new _o(yo.Piano,"Electric Organ")],[17,new _o(yo.Piano,"Electric Organ")],[18,new _o(yo.Piano,"Electric Organ")],[19,new _o(yo.Piano,"Electric Organ")],[20,new _o(yo.Piano,"Electric Organ")],[21,new _o(yo.Piano,"Electric Organ")],[22,new _o(yo.Woodwind,"Recorder")],[23,new _o(yo.Piano,"Electric Organ")],[24,new _o(yo.ClassicalGuitar,"Nylon Guitar")],[25,new _o(yo.SteelGuitar,"Steel Guitar")],[26,new _o(yo.SteelGuitar,"Electric Guitar")],[27,new _o(yo.ElectricGuitar,"Electric Guitar")],[28,new _o(yo.ElectricGuitar,"Electric Guitar")],[29,new _o(yo.ElectricGuitar,"Electric Guitar")],[30,new _o(yo.SteelGuitar,"Electric Guitar")],[31,new _o(yo.SteelGuitar,"Electric Guitar")],[32,new _o(yo.Bass,"Acoustic Bass")],[33,new _o(yo.Bass,"Electric Bass")],[34,new _o(yo.Bass,"Electric Bass")],[35,new _o(yo.Bass,"Acoustic Bass")],[36,new _o(yo.Bass,"Electric Bass")],[37,new _o(yo.Bass,"Electric Bass")],[38,new _o(yo.Synth,"Synth Bass")],[39,new _o(yo.Synth,"Synth Bass")],[40,new _o(yo.Strings,"Violin")],[41,new _o(yo.Strings,"Viola")],[42,new _o(yo.Strings,"Cello")],[43,new _o(yo.Strings,"Contrabass")],[44,new _o(yo.Strings,"Violin")],[45,new _o(yo.Strings,"Violin")],[46,new _o(yo.Piano,"Harp")],[47,new _o(yo.Membraphone,"Timpani")],[48,new _o(yo.Strings,"Violin")],[49,new _o(yo.Strings,"Violin")],[50,new _o(yo.Strings,"Violin")],[51,new _o(yo.Strings,"Violin")],[52,new _o(yo.Vocal,"Voice")],[53,new _o(yo.Vocal,"Voice")],[54,new _o(yo.Vocal,"Voice")],[55,new _o(yo.Synth,"Pad Synthesizer")],[56,new _o(yo.Brass,"Trumpet")],[57,new _o(yo.Brass,"Trombone")],[58,new _o(yo.Brass,"Tuba")],[59,new _o(yo.Brass,"Trumpet")],[60,new _o(yo.Brass,"French Horn")],[61,new _o(yo.Brass,"Trumpet")],[62,new _o(yo.Brass,"Trumpet")],[63,new _o(yo.Brass,"Trumpet")],[64,new _o(yo.Reed,"Saxophone")],[65,new _o(yo.Reed,"Saxophone")],[66,new _o(yo.Reed,"Saxophone")],[67,new _o(yo.Reed,"Saxophone")],[68,new _o(yo.Reed,"Oboe")],[69,new _o(yo.Reed,"English Horn")],[70,new _o(yo.Reed,"Bassoon")],[71,new _o(yo.Reed,"Clarinet")],[72,new _o(yo.Reed,"Piccolo")],[73,new _o(yo.Woodwind,"Flute")],[74,new _o(yo.Woodwind,"Recorder")],[75,new _o(yo.Woodwind,"Flute")],[76,new _o(yo.Woodwind,"Recorder")],[77,new _o(yo.Woodwind,"Flute")],[78,new _o(yo.Woodwind,"Recorder")],[79,new _o(yo.Woodwind,"Flute")],[80,new _o(yo.Synth,"Lead Synthesizer")],[81,new _o(yo.Synth,"Lead Synthesizer")],[82,new _o(yo.Synth,"Lead Synthesizer")],[83,new _o(yo.Synth,"Lead Synthesizer")],[84,new _o(yo.Synth,"Lead Synthesizer")],[85,new _o(yo.Synth,"Lead Synthesizer")],[86,new _o(yo.Synth,"Lead Synthesizer")],[87,new _o(yo.Synth,"Lead Synthesizer")],[88,new _o(yo.Synth,"Pad Synthesizer")],[89,new _o(yo.Synth,"Pad Synthesizer")],[90,new _o(yo.Synth,"Pad Synthesizer")],[91,new _o(yo.Synth,"Pad Synthesizer")],[92,new _o(yo.Synth,"Pad Synthesizer")],[93,new _o(yo.Synth,"Pad Synthesizer")],[94,new _o(yo.Synth,"Pad Synthesizer")],[95,new _o(yo.Synth,"Pad Synthesizer")],[96,new _o(yo.Fx,"Pad Synthesizer")],[97,new _o(yo.Fx,"Pad Synthesizer")],[98,new _o(yo.Fx,"Pad Synthesizer")],[99,new _o(yo.Fx,"Pad Synthesizer")],[100,new _o(yo.Fx,"Lead Synthesizer")],[101,new _o(yo.Fx,"Lead Synthesizer")],[102,new _o(yo.Fx,"Lead Synthesizer")],[103,new _o(yo.Fx,"Trumpet")],[104,new _o(yo.ElectricGuitar,"Banjo")],[105,new _o(yo.Banjo,"Banjo")],[106,new _o(yo.Ukulele,"Ukulele")],[107,new _o(yo.Banjo,"Banjo")],[108,new _o(yo.PitchedIdiophone,"Xylophone")],[109,new _o(yo.Reed,"Bassoon")],[110,new _o(yo.Strings,"Violin")],[111,new _o(yo.Woodwind,"Flute")],[112,new _o(yo.PitchedIdiophone,"Xylophone")],[113,new _o(yo.Idiophone,"Celesta")],[114,new _o(yo.PitchedIdiophone,"Vibraphone")],[115,new _o(yo.Idiophone,"Xylophone")],[116,new _o(yo.Membraphone,"Xylophone")],[117,new _o(yo.Membraphone,"Xylophone")],[118,new _o(yo.Membraphone,"Xylophone")],[119,new _o(yo.Idiophone,"Celesta")],[120,new _o(yo.Fx,"Steel Guitar")],[121,new _o(yo.Fx,"Recorder")],[122,new _o(yo.Fx,"Recorder")],[123,new _o(yo.Fx,"Recorder")],[124,new _o(yo.Fx,"Recorder")],[125,new _o(yo.Fx,"Recorder")],[126,new _o(yo.Fx,"Recorder")],[127,new _o(yo.Fx,"Timpani")]]),wo.DrumKitProgramInfo=new _o(yo.PercussionKit,"Drums","drumKit");class Bo{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==(1&i)?i>>>1^3988292384:i>>>1;e[t]=i}return e}get value(){return~this._checkValue}constructor(){this._checkValue=Bo.CrcInit,this.reset()}update(e,t,i){for(let s=0;s<i;s++)this._checkValue=Bo.Crc32Lookup[255&(this._checkValue^e[t+s])]^this._checkValue>>>8}reset(){this._checkValue=Bo.CrcInit}}Bo.Crc32Lookup=Bo.buildCrc32Lookup(),Bo.CrcInit=4294967295;class To{}To.MAX_WBITS=15,To.WSIZE=1<<To.MAX_WBITS,To.WMASK=To.WSIZE-1,To.MIN_MATCH=3,To.MAX_MATCH=258,To.DEFAULT_MEM_LEVEL=8,To.PENDING_BUF_SIZE=1<<To.DEFAULT_MEM_LEVEL+8,To.HASH_BITS=To.DEFAULT_MEM_LEVEL+7,To.HASH_SIZE=1<<To.HASH_BITS,To.HASH_SHIFT=(To.HASH_BITS+To.MIN_MATCH-1)/To.MIN_MATCH,To.HASH_MASK=To.HASH_SIZE-1,To.MIN_LOOKAHEAD=To.MAX_MATCH+To.MIN_MATCH+1,To.MAX_DIST=To.WSIZE-To.MIN_LOOKAHEAD;class ko{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 d=t[0];s=o++,r[2*s]=e,r[2*s+1]=d;let c=Math.min(255&n[e],255&n[d]);for(l=n[e]+n[d]-c+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[ko.Repeat3To6]++:s<=10?e.freqs[ko.Repeat3To10]++:e.freqs[ko.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(ko.Repeat3To6),this.huffman.pending.writeBits(s-3,2)):s<=10?(e.writeSymbol(ko.Repeat3To10),this.huffman.pending.writeBits(s-3,3)):(e.writeSymbol(ko.Repeat11To138),this.huffman.pending.writeBits(s-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}ko.Repeat3To6=16,ko.Repeat3To10=17,ko.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 ko(this,vo.LITERAL_NUM,257,15),this.distTree=new ko(this,vo.DIST_NUM,1,15),this.blTree=new ko(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<<To.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 No{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 Bo,this.window=new Uint8Array(2*To.WSIZE),this.head=new Int16Array(To.HASH_SIZE),this.prev=new Int16Array(To.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=To.MIN_MATCH-1;for(let e=0;e<To.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<To.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<To.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<To.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=To.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*To.WSIZE-To.MIN_LOOKAHEAD&&this.slideWindow();let e=this.matchStart,i=this.matchLen;if(this.lookahead>=To.MIN_MATCH){let e=this.insertString();0!=e&&this.strstart-e<=To.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen==To.MIN_MATCH&&this.strstart-this.matchStart>No.TooFar&&(this.matchLen=To.MIN_MATCH-1)}if(i>=To.MIN_MATCH&&this.matchLen<=i){this.huffman.tallyDist(this.strstart-1-e,i),i-=2;do{this.strstart++,this.lookahead--,this.lookahead>=To.MIN_MATCH&&this.insertString()}while(--i>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=To.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(To.MAX_MATCH,this.lookahead)-1,a=Math.max(i-To.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,To.MIN_MATCH-1),i+this.matchLen>s)return!1;let l=r[i+this.matchLen-1],d=r[i+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,i=this.strstart,r[t+this.matchLen]==d&&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],d=r[i]}e=65535&n[e&To.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=To.MIN_MATCH}insertString(){let e,t=(this.insertHashIndex<<To.HASH_SHIFT^this.window[this.strstart+(To.MIN_MATCH-1)])&To.HASH_MASK;return e=this.head[t],this.prev[this.strstart&To.WMASK]=e,this.head[t]=this.strstart,this.insertHashIndex=t,65535&e}fillWindow(){if(this.strstart>=To.WSIZE+To.MAX_DIST&&this.slideWindow(),this.lookahead<To.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*To.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>=To.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(To.WSIZE,To.WSIZE+To.WSIZE),0),this.matchStart-=To.WSIZE,this.strstart-=To.WSIZE,this.blockStart-=To.WSIZE;for(let e=0;e<To.HASH_SIZE;++e){let t=65535&this.head[e];this.head[e]=t>=To.WSIZE?t-To.WSIZE:0}for(let e=0;e<To.WSIZE;e++){let t=65535&this.prev[e];this.prev[e]=t>=To.WSIZE?t-To.WSIZE:0}}}No.TooFar=4096;class xo{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 Po{get inputCrc(){return this._engine.inputCrc.value}constructor(){this._state=0,this._pending=new xo(To.PENDING_BUF_SIZE),this._engine=new No(this._pending),this.reset()}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state==Po.FinishedState&&this._pending.isFlushed}reset(){this._state=Po.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==Po.FinishedState)break;if(!this._engine.deflate(0!=(this._state&Po.IsFlushing),0!=(this._state&Po.IsFinishing)))switch(this._state){case Po.BusyState:return s-i;case Po.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=Po.BusyState;break;case Po.FinishingState:this._pending.alignToByte(),this._state=Po.FinishedState}}return s-i}finish(){this._state|=Po.IsFlushing|Po.IsFinishing}}Po.IsFlushing=4,Po.IsFinishing=8,Po.BusyState=16,Po.FlushingState=20,Po.FinishingState=28,Po.FinishedState=30;class Eo{constructor(e,t,i,s,a){this.entry=e,this.crc32=t,this.localHeaderOffset=i,this.compressionMode=s,this.compressedSize=a}}class Co{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new Po,this._data=e}writeEntry(e){const t=vt.CompressionMethodDeflate,i=Ke.empty(),s=this.compress(i,e.data,t),a=i.toArray(),r=new Eo(e,s,this._data.bytesWritten,t,i.length);this._centralDirectoryHeaders.push(r),$e.writeInt32LE(this._data,vt.LocalFileHeaderSignature),$e.writeUInt16LE(this._data,10),$e.writeUInt16LE(this._data,2048),$e.writeUInt16LE(this._data,t),$e.writeInt16LE(this._data,0),$e.writeInt16LE(this._data,0),$e.writeInt32LE(this._data,s),$e.writeInt32LE(this._data,a.length),$e.writeInt32LE(this._data,e.data.length),$e.writeInt16LE(this._data,e.fullName.length),$e.writeInt16LE(this._data,0);const n=$e.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,i){if(i!=vt.CompressionMethodDeflate){const i=new Bo;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){$e.writeInt32LE(this._data,vt.EndOfCentralDirSignature),$e.writeInt16LE(this._data,0),$e.writeInt16LE(this._data,0),$e.writeInt16LE(this._data,this._centralDirectoryHeaders.length),$e.writeInt16LE(this._data,this._centralDirectoryHeaders.length),$e.writeInt32LE(this._data,t-e),$e.writeInt32LE(this._data,e),$e.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){$e.writeInt32LE(this._data,vt.CentralFileHeaderSignature),$e.writeUInt16LE(this._data,10),$e.writeUInt16LE(this._data,10),$e.writeUInt16LE(this._data,2048),$e.writeUInt16LE(this._data,e.compressionMode),$e.writeInt16LE(this._data,0),$e.writeInt16LE(this._data,0),$e.writeInt32LE(this._data,e.crc32),$e.writeInt32LE(this._data,e.compressedSize),$e.writeInt32LE(this._data,e.entry.data.length),$e.writeInt16LE(this._data,e.entry.fullName.length),$e.writeInt16LE(this._data,0),$e.writeInt16LE(this._data,0),$e.writeInt16LE(this._data,0),$e.writeInt16LE(this._data,0),$e.writeInt32LE(this._data,0),$e.writeInt32LE(this._data,e.localHeaderOffset);const t=$e.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}var Fo=Object.freeze({__proto__:null,ScoreExporter:So,Gp7Exporter:class extends So{get name(){return"Guitar Pro 7"}constructor(){super()}writeScore(e){Be.debug(this.name,"Writing data entries");const t=(new wo).writeXml(e),i=rt.writeForScore(e),s=yt.writeForScore(e);Be.debug(this.name,"Writing ZIP entries");let a=new Co(this.data);a.writeEntry(new vt("VERSION",$e.stringToBytes("7.0"))),a.writeEntry(new vt("Content/",new Uint8Array(0))),a.writeEntry(new vt("Content/BinaryStylesheet",i)),a.writeEntry(new vt("Content/PartConfiguration",s)),a.writeEntry(new vt("Content/score.gpif",$e.stringToBytes(t))),a.end()}}}),Lo=Object.freeze({__proto__:null,BeatTickLookup:Bs,MasterBarTickLookup:vs,MidiTickLookup:xs,MidiTickLookupFindBeatResult:Ns,MidiFile:_i,get ControllerType(){return te},MetaDataEvent:wi,MetaEvent:It,get MetaEventType(){return U},MetaNumberEvent:Bi,MidiEvent:Dt,get MidiEventType(){return z},Midi20PerNotePitchBendEvent:zi,SystemCommonEvent:Rt,get SystemCommonType(){return X},SystemExclusiveEvent:At,MidiFileGenerator:Cs,AlphaSynthMidiFileHandler:ws}),Mo=Object.freeze({__proto__:null,get AccentuationType(){return s},get AccidentalType(){return re},get AutomationType(){return a},Automation:fe,Bar:me,Beat:Ie,BendPoint:be,get BendStyle(){return h},get BendType(){return l},get BrushType(){return d},Chord:Re,get Clef(){return r},Color:Ue,get CrescendoType(){return c},get Duration(){return u},get DynamicValue(){return p},get FermataType(){return O},Fermata:nt,get Fingers(){return f},get FontStyle(){return K},Font:Ni,get GraceType(){return g},get HarmonicType(){return m},InstrumentArticulation:ve,JsonConverter:os,get KeySignature(){return L},get KeySignatureType(){return D},Lyrics:Ae,MasterBar:Oe,get MusicFontSymbol(){return x},Note:Pe,get NoteAccidentalMode(){return y},get Ottavia(){return n},get PickStroke(){return N},PlaybackInformation:Xe,RenderStylesheet:Ge,RepeatGroup:Ve,Score:He,Section:We,get SimileMark(){return o},get SlideInType(){return b},get SlideOutType(){return S},Staff:qe,Track:Je,get TripletFeel(){return I},Tuning:Ye,TupletGroup:Ee,get VibratoType(){return _},Voice:je,get WhammyType(){return C}}),Do=Object.freeze({__proto__:null,RenderFinishedEventArgs:cs,ScoreRenderer:bs,BarBounds:us,BeatBounds:ps,Bounds:at,BoundsLookup:ys,MasterBarBounds:gs,NoteBounds:fs,StaveGroupBounds:ms}),Io=Object.freeze({__proto__:null,AlphaSynth:Si,CircularSampleBuffer:qs,PlaybackRange:Fs,get PlayerState(){return q},PlayerStateChangedEventArgs:zt,PlaybackRangeChangedEventArgs:bi,PositionChangedEventArgs:Ut,MidiEventsPlayedEventArgs:yi,ActiveBeatsChangedEventArgs:Gs,AlphaSynthWebWorkerApi:$s,AlphaSynthWebAudioOutputBase:Js,AlphaSynthScriptProcessorOutput:js,AlphaSynthAudioWorkletOutput:ta});export{aa as AlphaTabApi,pe as AlphaTabError,i as AlphaTabErrorType,fo as CoreSettings,Pi as DisplaySettings,Ws as FileLoadError,B as FingeringMode,ze as FormatError,Ei as ImporterSettings,e as LayoutMode,v as LogLevel,Be as Logger,T as NotationMode,Se as NotationSettings,Li as PlayerSettings,Qs as ProgressEventArgs,xi as RenderingResources,Os as ResizeEventArgs,ee as ScrollMode,Wi as Settings,t as StaveProfile,w as TabRhythmMode,Ci as VibratoPlaybackSettings,Fo as exporter,bo as importer,mo as meta,Lo as midi,Mo as model,Do as rendering,Io as synth};
|