@coderline/alphatab 1.5.0-alpha.1376 → 1.5.0-alpha.1377

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var e,t,s,i,a,r,n,o,h,l,c,d,u,p,g,m,f,y,b,S,_,w,B,k,T,N,x,v,P,C,E,F,D,M,L,I,A,R,O,H,W,V,G,U,z,X,J,Y,$;!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 q{static getValue(e){return q._values||(q._values=new Map),e=e.toLowerCase().replaceAll(" ",""),q._values.has(e)?q._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}}q._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]]),function(e){e[e.NoBrackets=0]="NoBrackets",e[e.GroupStaves=1]="GroupStaves",e[e.GroupSimilarInstruments=2]="GroupSimilarInstruments"}(s||(s={})),function(e){e[e.Hidden=0]="Hidden",e[e.FirstSystem=1]="FirstSystem",e[e.AllSystems=2]="AllSystems"}(i||(i={})),function(e){e[e.FullName=0]="FullName",e[e.ShortName=1]="ShortName"}(a||(a={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical"}(r||(r={}));class K{constructor(){this.hideDynamics=!1,this.bracketExtendMode=s.GroupStaves,this.useSystemSignSeparator=!1,this.globalDisplayTuning=!0,this.perTrackDisplayTuning=null,this.globalDisplayChordDiagramsOnTop=!0,this.perTrackChordDiagramsOnTop=null,this.singleTrackTrackNamePolicy=i.FirstSystem,this.multiTrackTrackNamePolicy=i.FirstSystem,this.firstSystemTrackNameMode=a.ShortName,this.otherSystemsTrackNameMode=a.ShortName,this.firstSystemTrackNameOrientation=r.Vertical,this.otherSystemsTrackNameOrientation=r.Vertical,this.multiTrackMultiBarRest=!1,this.perTrackMultiBarRest=null}}class j{constructor(){this.masterBars=[],this.opening=null,this.closings=[],this.isClosed=!1}get openings(){const e=this.opening;return e?[e]:[]}get isOpened(){return!0===this.opening?.isRepeatStart}addMasterBar(e){null===this.opening&&(this.opening=e),this.masterBars.push(e),e.repeatGroup=this,e.isRepeatEnd&&(this.closings.push(e),this.isClosed=!0)}}class Q{constructor(){this.colors=new Map}}!function(e){e[e.Neutral=0]="Neutral",e[e.C3=1]="C3",e[e.C4=2]="C4",e[e.F4=3]="F4",e[e.G2=4]="G2"}(n||(n={})),function(e){e[e._15ma=0]="_15ma",e[e._8va=1]="_8va",e[e.Regular=2]="Regular",e[e._8vb=3]="_8vb",e[e._15mb=4]="_15mb"}(o||(o={})),function(e){e[e.None=0]="None",e[e.Simple=1]="Simple",e[e.FirstOfDouble=2]="FirstOfDouble",e[e.SecondOfDouble=3]="SecondOfDouble"}(h||(h={})),function(e){e[e.Down=0]="Down",e[e.Hold=1]="Hold",e[e.Up=2]="Up"}(l||(l={}));class Z{constructor(){this.ratioPosition=0,this.pedalType=l.Down,this.nextPedalMarker=null,this.previousPedalMarker=null}}!function(e){e[e.StandardNotationRepeats=0]="StandardNotationRepeats",e[e.GuitarTabsRepeats=1]="GuitarTabsRepeats",e[e.SlashRepeats=2]="SlashRepeats",e[e.NumberedRepeats=3]="NumberedRepeats",e[e.StandardNotationBarNumber=4]="StandardNotationBarNumber",e[e.GuitarTabsBarNumber=5]="GuitarTabsBarNumber",e[e.SlashBarNumber=6]="SlashBarNumber",e[e.NumberedBarNumber=7]="NumberedBarNumber",e[e.StandardNotationBarSeparator=8]="StandardNotationBarSeparator",e[e.GuitarTabsBarSeparator=9]="GuitarTabsBarSeparator",e[e.SlashBarSeparator=10]="SlashBarSeparator",e[e.NumberedBarSeparator=11]="NumberedBarSeparator",e[e.StandardNotationClef=12]="StandardNotationClef",e[e.GuitarTabsClef=13]="GuitarTabsClef",e[e.StandardNotationKeySignature=14]="StandardNotationKeySignature",e[e.NumberedKeySignature=15]="NumberedKeySignature",e[e.StandardNotationTimeSignature=16]="StandardNotationTimeSignature",e[e.GuitarTabsTimeSignature=17]="GuitarTabsTimeSignature",e[e.SlashTimeSignature=18]="SlashTimeSignature",e[e.NumberedTimeSignature=19]="NumberedTimeSignature",e[e.StandardNotationStaffLine=20]="StandardNotationStaffLine",e[e.GuitarTabsStaffLine=21]="GuitarTabsStaffLine",e[e.SlashStaffLine=22]="SlashStaffLine",e[e.NumberedStaffLine=23]="NumberedStaffLine"}(c||(c={}));class ee extends Q{}class te{constructor(){this.id=te._globalBarId++,this.index=0,this.nextBar=null,this.previousBar=null,this.clef=n.G2,this.clefOttava=o.Regular,this.voices=[],this.simileMark=h.None,this.isMultiVoice=!1,this.displayScale=1,this.displayWidth=-1,this.sustainPedals=[],this._isEmpty=!0,this._isRestOnly=!0}static resetIds(){te._globalBarId=0}get masterBar(){return this.staff.track.score.masterBars[this.index]}get isEmpty(){return this._isEmpty}get isRestOnly(){return this._isRestOnly}addVoice(e){e.bar=this,e.index=this.voices.length,this.voices.push(e)}finish(e,t=null){this.isMultiVoice=!1,this._isEmpty=!0,this._isRestOnly=!0;for(let s=0,i=this.voices.length;s<i;s++){const i=this.voices[s];i.finish(e,t),s>0&&!i.isEmpty&&(this.isMultiVoice=!0),i.isEmpty||(this._isEmpty=!1),i.isRestOnly||(this._isRestOnly=!1)}const s=this.sustainPedals;if(s.length>0){let e=null;this.sustainPedals=[],this.previousBar&&this.previousBar.sustainPedals.length>0&&(e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1]);const t=null!==e&&e.pedalType!==l.Up;for(const i of s){if(e&&e.pedalType!==l.Up){if(e.bar===this&&i.ratioPosition<=e.ratioPosition)continue;e.nextPedalMarker=i,i.previousPedalMarker=e}t&&i.pedalType===l.Down&&(i.pedalType=l.Hold),i.bar=this,this.sustainPedals.push(i),e=i}}else if(this.previousBar&&this.previousBar.sustainPedals.length>0){const e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1];if(e.pedalType!==l.Up){const t=new Z;t.ratioPosition=0,t.bar=this,t.pedalType=l.Hold,this.sustainPedals.push(t),e.nextPedalMarker=t,t.previousPedalMarker=e}}}calculateDuration(){let e=0;for(const t of this.voices){const s=t.calculateDuration();s>e&&(e=s)}return e}}te._globalBarId=0;class se{static ticksToMillis(e,t){return e*(6e4/(t*se.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*se.QuarterTime))|0}static toTicks(e){return se.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),se.QuarterTime*(4/t)|0}static applyDot(e,t){return t?e+3*(e/4|0):e+(e/2|0)}static applyTuplet(e,t,s){return e*s/t|0}static removeTuplet(e,t,s){return e*t/s|0}static dynamicToVelocity(e){return se.MinVelocity+e*se.VelocityIncrement}}se.QuarterTime=960,se.MinVelocity=15,se.VelocityIncrement=16,function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(d||(d={}));class ie{constructor(){this.isLinear=!1,this.type=d.Tempo,this.value=0,this.ratioPosition=0,this.text=""}static buildTempoAutomation(e,t,s,i){(i<1||i>5)&&(i=2);const a=new Float32Array([1,.5,1,1.5,2,3]),r=new ie;return r.type=d.Tempo,r.isLinear=e,r.ratioPosition=t,r.value=s*a[i],r}static buildInstrumentAutomation(e,t,s){const i=new ie;return i.type=d.Instrument,i.isLinear=e,i.ratioPosition=t,i.value=s,i}}class ae{constructor(e=0,t=0){this.offset=e,this.value=t}}ae.MaxPosition=60,ae.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(u||(u={})),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"}(p||(p={})),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"}(g||(g={})),function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(m||(m={})),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"}(f||(f={})),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"}(y||(y={})),function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(b||(b={})),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy",e[e.Tenuto=3]="Tenuto"}(S||(S={})),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"}(_||(_={})),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"}(w||(w={})),function(e){e[e.Default=0]="Default",e[e.ForceNone=1]="ForceNone",e[e.ForceNatural=2]="ForceNatural",e[e.ForceSharp=3]="ForceSharp",e[e.ForceDoubleSharp=4]="ForceDoubleSharp",e[e.ForceFlat=5]="ForceFlat",e[e.ForceDoubleFlat=6]="ForceDoubleFlat"}(B||(B={})),function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(k||(k={})),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"}(T||(T={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(N||(N={})),function(e){e[e.Hidden=0]="Hidden",e[e.ShowWithBeams=1]="ShowWithBeams",e[e.ShowWithBars=2]="ShowWithBars",e[e.Automatic=3]="Automatic"}(x||(x={})),function(e){e[e.ScoreDefault=0]="ScoreDefault",e[e.ScoreForcePiano=1]="ScoreForcePiano",e[e.SingleNoteEffectBand=2]="SingleNoteEffectBand",e[e.SingleNoteEffectBandForcePiano=3]="SingleNoteEffectBandForcePiano"}(v||(v={})),function(e){e[e.GuitarPro=0]="GuitarPro",e[e.SongBook=1]="SongBook"}(P||(P={})),function(e){e[e.ScoreTitle=0]="ScoreTitle",e[e.ScoreSubTitle=1]="ScoreSubTitle",e[e.ScoreArtist=2]="ScoreArtist",e[e.ScoreAlbum=3]="ScoreAlbum",e[e.ScoreWords=4]="ScoreWords",e[e.ScoreMusic=5]="ScoreMusic",e[e.ScoreWordsAndMusic=6]="ScoreWordsAndMusic",e[e.ScoreCopyright=7]="ScoreCopyright",e[e.GuitarTuning=8]="GuitarTuning",e[e.TrackNames=9]="TrackNames",e[e.ChordDiagrams=10]="ChordDiagrams",e[e.ParenthesisOnTiedBends=11]="ParenthesisOnTiedBends",e[e.TabNotesOnTiedBends=12]="TabNotesOnTiedBends",e[e.ZerosOnDiveWhammys=13]="ZerosOnDiveWhammys",e[e.EffectAlternateEndings=14]="EffectAlternateEndings",e[e.EffectCapo=15]="EffectCapo",e[e.EffectChordNames=16]="EffectChordNames",e[e.EffectCrescendo=17]="EffectCrescendo",e[e.EffectDynamics=18]="EffectDynamics",e[e.EffectFadeIn=19]="EffectFadeIn",e[e.EffectFermata=20]="EffectFermata",e[e.EffectFingering=21]="EffectFingering",e[e.EffectHarmonics=22]="EffectHarmonics",e[e.EffectLetRing=23]="EffectLetRing",e[e.EffectLyrics=24]="EffectLyrics",e[e.EffectMarker=25]="EffectMarker",e[e.EffectOttavia=26]="EffectOttavia",e[e.EffectPalmMute=27]="EffectPalmMute",e[e.EffectPickSlide=28]="EffectPickSlide",e[e.EffectPickStroke=29]="EffectPickStroke",e[e.EffectSlightBeatVibrato=30]="EffectSlightBeatVibrato",e[e.EffectSlightNoteVibrato=31]="EffectSlightNoteVibrato",e[e.EffectTap=32]="EffectTap",e[e.EffectTempo=33]="EffectTempo",e[e.EffectText=34]="EffectText",e[e.EffectTrill=35]="EffectTrill",e[e.EffectTripletFeel=36]="EffectTripletFeel",e[e.EffectWhammyBar=37]="EffectWhammyBar",e[e.EffectWideBeatVibrato=38]="EffectWideBeatVibrato",e[e.EffectWideNoteVibrato=39]="EffectWideNoteVibrato",e[e.EffectLeftHandTap=40]="EffectLeftHandTap",e[e.EffectFreeTime=41]="EffectFreeTime",e[e.EffectSustainPedal=42]="EffectSustainPedal",e[e.EffectGolpe=43]="EffectGolpe",e[e.EffectWahPedal=44]="EffectWahPedal",e[e.EffectBeatBarre=45]="EffectBeatBarre",e[e.EffectNoteOrnament=46]="EffectNoteOrnament",e[e.EffectRasgueado=47]="EffectRasgueado",e[e.EffectDirections=48]="EffectDirections",e[e.EffectBeatTimer=49]="EffectBeatTimer"}(C||(C={}));class re{constructor(){this.notationMode=P.GuitarPro,this.fingeringMode=v.ScoreDefault,this.elements=new Map,this.rhythmMode=x.Automatic,this.rhythmHeight=15,this.transpositionPitches=[],this.displayTranspositionPitches=[],this.smallGraceTabNotes=!0,this.extendBendArrowsOnTiedNotes=!0,this.extendLineEffectsToBeatEnd=!1,this.slurHeight=5}isNotationElementVisible(e){return this.elements.has(e)?this.elements.get(e):!re.defaultElements.has(e)||re.defaultElements.get(e)}}re.defaultElements=new Map([[C.ZerosOnDiveWhammys,!1]]);class ne{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"}(E||(E={}));class oe{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...s){console.debug(oe.format(e,t),...s)}warning(e,t,...s){console.warn(oe.format(e,t),...s)}info(e,t,...s){console.info(oe.format(e,t),...s)}error(e,t,...s){console.error(oe.format(e,t),...s)}}oe.logLevel=E.Info;class he{static shouldLog(e){return he.logLevel!==E.None&&e>=he.logLevel}static debug(e,t,...s){he.shouldLog(E.Debug)&&he.log.debug(e,t,...s)}static warning(e,t,...s){he.shouldLog(E.Warning)&&he.log.warning(e,t,...s)}static info(e,t,...s){he.shouldLog(E.Info)&&he.log.info(e,t,...s)}static error(e,t,...s){he.shouldLog(E.Error)&&he.log.error(e,t,...s)}}he.logLevel=E.Info,he.log=new oe,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"}(F||(F={})),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"}(M||(M={}));class le{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=F.C,this.keySignatureType=D.Major,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.isFreeTime=!1,this.tripletFeel=M.NoTripletFeel,this.section=null,this.tempoAutomations=[],this.fermata=null,this.start=0,this.isAnacrusis=!1,this.displayScale=1,this.displayWidth=-1,this.directions=null}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}get tempoAutomation(){return this.tempoAutomations.length>0?this.tempoAutomations[0]:null}calculateDuration(e=!0){if(this.isAnacrusis&&e){let e=0;for(const t of this.score.tracks)for(const s of t.staves){const t=this.index<s.bars.length?s.bars[this.index].calculateDuration():0;t>e&&(e=t)}return e}return this.timeSignatureNumerator*se.valueToTicks(this.timeSignatureDenominator)}addFermata(e,t){let s=this.fermata;null===s&&(s=new Map,this.fermata=s),s.set(e,t)}addDirection(e){null==this.directions&&(this.directions=new Set),this.directions.add(e)}getFermata(e){const t=this.fermata;return null===t?null:t.has(e.playbackStart)?t.get(e.playbackStart):null}}le.MaxAlternateEndings=8;class ce{constructor(){this.note=null,this.tone=new de,this.octave=0}get realValue(){return 12*this.octave+this.tone.noteValue}}class de{constructor(e=0,t=B.Default){this.noteValue=e,this.accidentalMode=t}}class ue{static getIndex(e){return e<0?0:0|Math.log2(e)}static keySignatureIsFlat(e){return e<0}static keySignatureIsNatural(e){return 0===e}static keySignatureIsSharp(e){return e>0}static applyPitchOffsets(e,t){for(let s=0;s<t.tracks.length;s++){if(s<e.notation.displayTranspositionPitches.length)for(const i of t.tracks[s].staves)i.displayTranspositionPitch=-e.notation.displayTranspositionPitches[s];if(s<e.notation.transpositionPitches.length)for(const i of t.tracks[s].staves)i.transpositionPitch=-e.notation.transpositionPitches[s]}}static fingerToString(e,t,s,i){if(e.notation.fingeringMode===v.ScoreForcePiano||e.notation.fingeringMode===v.SingleNoteEffectBandForcePiano||q.isPiano(t.voice.bar.staff.track.playbackInfo.program))switch(s){case _.Unknown:case _.NoOrDead:return null;case _.Thumb:return"1";case _.IndexFinger:return"2";case _.MiddleFinger:return"3";case _.AnnularFinger:return"4";case _.LittleFinger:return"5";default:return null}if(i)switch(s){case _.Unknown:return null;case _.NoOrDead:return"0";case _.Thumb:return"t";case _.IndexFinger:return"1";case _.MiddleFinger:return"2";case _.AnnularFinger:return"3";case _.LittleFinger:return"4";default:return null}switch(s){case _.Unknown:case _.NoOrDead:return null;case _.Thumb:return"p";case _.IndexFinger:return"i";case _.MiddleFinger:return"m";case _.AnnularFinger:return"a";case _.LittleFinger:return"c";default:return null}}static isTuning(e){return!!ue.parseTuning(e)}static parseTuning(e){let t="",s="";for(let i=0;i<e.length;i++){const a=e.charCodeAt(i);if(a>=48&&a<=57){if(!t)return null;s+=String.fromCharCode(a)}else{if(!ue.TuningLetters.has(a))return null;t+=String.fromCharCode(a)}}if(!s||!t)return null;const i=new ce;return i.octave=Number.parseInt(s)+1,i.note=t.toLowerCase(),i.tone=ue.getToneForText(i.note),i.tone.noteValue<0&&(i.octave--,i.tone.noteValue+=12),i}static getTuningForText(e){const t=ue.parseTuning(e);return t?t.realValue:-1}static getToneForText(e){const t=e.substring(0,1),s=e.substring(1);let i,a;switch(t.toLowerCase()){case"c":default:i=0;break;case"d":i=2;break;case"e":i=4;break;case"f":i=5;break;case"g":i=7;break;case"a":i=9;break;case"b":i=11}switch(a=ue.parseAccidentalMode(s),a){case B.Default:case B.ForceNone:case B.ForceNatural:break;case B.ForceSharp:i++;break;case B.ForceDoubleSharp:i+=2;break;case B.ForceFlat:i--;break;case B.ForceDoubleFlat:i-=2}return new de(i,a)}static parseAccidentalMode(e){const t=e.toLowerCase();return ue.accidentalModeMapping.has(t)?ue.accidentalModeMapping.get(t):B.Default}static newGuid(){return`${Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}`}static isAlmostEqualTo(e,t){return Math.abs(e-t)<1e-5}static toHexString(e,t=0){let s="";do{s=String.fromCharCode("0123456789ABCDEF".charCodeAt(15&e))+s,e>>=4}while(e>0);for(;s.length<t;)s=`0${s}`;return s}static getAlternateEndingsList(e){const t=[];for(let s=0;s<le.MaxAlternateEndings;s++)e&1<<s&&t.push(s);return t}static deltaFretToHarmonicValue(e){switch(e){case 2:return 2.4;case 3:return 3.2;case 4:case 5:case 7:case 9:case 12:case 16:case 17:case 19:case 24:return e;case 8:return 8.2;case 10:return 9.6;case 14:case 15:return 14.7;case 21:case 22:return 21.7;default:return 12}}static clamp(e,t,s){return e<=t?t:e>=s?s:e}static buildMultiBarRestInfo(e,t,s){if(!e)return null;const i=e[0].score.stylesheet;if(!(e.length>1?i.multiTrackMultiBarRest:!0===i.perTrackMultiBarRest?.has(e[0].index)))return null;const a=new Map,r=e[0].score;let n=t;for(;n<=s;){const i=n;let o=null;for(;n<=s;){const s=r.masterBars[n];if(s.alternateEndings||s.isRepeatStart&&s.index!==i||s.isDoubleBar||s.isFreeTime||s.isAnacrusis||null!==s.section||s.index!==i&&s.tempoAutomations.length>0||null!==s.fermata&&s.fermata.size>0||null!==s.directions&&s.directions.size>0)break;if(i>t&&s.previousMasterBar&&(s.timeSignatureCommon!==s.previousMasterBar.timeSignatureCommon||s.timeSignatureNumerator!==s.previousMasterBar.timeSignatureNumerator||s.timeSignatureDenominator!==s.previousMasterBar.timeSignatureDenominator||s.tripletFeel!==s.previousMasterBar.tripletFeel||s.keySignature!==s.previousMasterBar.keySignature||s.keySignatureType!==s.previousMasterBar.keySignatureType))break;let a=!0;for(const t of e){for(const e of t.staves){if(!e.bars[s.index].isRestOnly){a=!1;break}}if(!a)break}if(!a)break;if(n++,s.index>i&&(null===o?o=[s.index]:o.push(s.index)),s.isRepeatEnd)break}o?a.set(i,o):n++}return a}static computeFirstDisplayedBarIndex(e,t){let s=t.display.startBar;return s--,s=Math.min(e.masterBars.length-1,Math.max(0,s)),s}static computeLastDisplayedBarIndex(e,t,s){let i=t.display.barCount;return i<0&&(i=e.masterBars.length),i=s+i-1,i=Math.min(e.masterBars.length-1,Math.max(0,i)),i}static getOrCreateHeaderFooterStyle(e,t){let s,i=e.style;if(e.style||(i=new ht,e.style=i),i.headerAndFooter.has(t))s=i.headerAndFooter.get(t);else{if(s=new ot,ht.defaultHeaderAndFooter.has(t)){const e=ht.defaultHeaderAndFooter.get(t);s.template=e.template,s.textAlign=e.textAlign}i.headerAndFooter.set(t,s)}return s}}ue.TuningLetters=new Set([67,68,69,70,71,65,66,99,100,101,102,103,97,98,35]),ue.accidentalModeMapping=new Map([["default",B.Default],["d",B.Default],["forcenone",B.ForceNone],["-",B.ForceNone],["forcenatural",B.ForceNatural],["n",B.ForceNatural],["forcesharp",B.ForceSharp],["#",B.ForceSharp],["forcedoublesharp",B.ForceDoubleSharp],["##",B.ForceDoubleSharp],["x",B.ForceDoubleSharp],["forceflat",B.ForceFlat],["b",B.ForceFlat],["forcedoubleflat",B.ForceDoubleFlat],["bb",B.ForceDoubleFlat]]),function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(L||(L={})),function(e){e[e.None=-1]="None",e[e.Space=32]="Space",e[e.Brace=57344]="Brace",e[e.BracketTop=57347]="BracketTop",e[e.BracketBottom=57348]="BracketBottom",e[e.SystemDivider=57351]="SystemDivider",e[e.GClef=57424]="GClef",e[e.CClef=57436]="CClef",e[e.FClef=57442]="FClef",e[e.UnpitchedPercussionClef1=57449]="UnpitchedPercussionClef1",e[e.SixStringTabClef=57453]="SixStringTabClef",e[e.FourStringTabClef=57454]="FourStringTabClef",e[e.TimeSig0=57472]="TimeSig0",e[e.TimeSig1=57473]="TimeSig1",e[e.TimeSig2=57474]="TimeSig2",e[e.TimeSig3=57475]="TimeSig3",e[e.TimeSig4=57476]="TimeSig4",e[e.TimeSig5=57477]="TimeSig5",e[e.TimeSig6=57478]="TimeSig6",e[e.TimeSig7=57479]="TimeSig7",e[e.TimeSig8=57480]="TimeSig8",e[e.TimeSig9=57481]="TimeSig9",e[e.TimeSigCommon=57482]="TimeSigCommon",e[e.TimeSigCutCommon=57483]="TimeSigCutCommon",e[e.NoteheadDoubleWholeSquare=57505]="NoteheadDoubleWholeSquare",e[e.NoteheadDoubleWhole=57504]="NoteheadDoubleWhole",e[e.NoteheadWhole=57506]="NoteheadWhole",e[e.NoteheadHalf=57507]="NoteheadHalf",e[e.NoteheadBlack=57508]="NoteheadBlack",e[e.NoteheadNull=57509]="NoteheadNull",e[e.NoteheadXOrnate=57514]="NoteheadXOrnate",e[e.NoteheadPlusDoubleWhole=57516]="NoteheadPlusDoubleWhole",e[e.NoteheadPlusWhole=57517]="NoteheadPlusWhole",e[e.NoteheadPlusHalf=57518]="NoteheadPlusHalf",e[e.NoteheadPlusBlack=57519]="NoteheadPlusBlack",e[e.NoteheadSquareWhite=57528]="NoteheadSquareWhite",e[e.NoteheadSquareBlack=57529]="NoteheadSquareBlack",e[e.NoteheadTriangleUpDoubleWhole=57530]="NoteheadTriangleUpDoubleWhole",e[e.NoteheadTriangleUpWhole=57531]="NoteheadTriangleUpWhole",e[e.NoteheadTriangleUpHalf=57532]="NoteheadTriangleUpHalf",e[e.NoteheadTriangleUpBlack=57534]="NoteheadTriangleUpBlack",e[e.NoteheadTriangleRightWhite=57537]="NoteheadTriangleRightWhite",e[e.NoteheadTriangleRightBlack=57538]="NoteheadTriangleRightBlack",e[e.NoteheadTriangleDownDoubleWhole=57548]="NoteheadTriangleDownDoubleWhole",e[e.NoteheadTriangleDownWhole=57540]="NoteheadTriangleDownWhole",e[e.NoteheadTriangleDownHalf=57541]="NoteheadTriangleDownHalf",e[e.NoteheadTriangleDownBlack=57543]="NoteheadTriangleDownBlack",e[e.NoteheadDiamondDoubleWhole=57559]="NoteheadDiamondDoubleWhole",e[e.NoteheadDiamondWhole=57560]="NoteheadDiamondWhole",e[e.NoteheadDiamondHalf=57561]="NoteheadDiamondHalf",e[e.NoteheadDiamondBlack=57563]="NoteheadDiamondBlack",e[e.NoteheadDiamondBlackWide=57564]="NoteheadDiamondBlackWide",e[e.NoteheadDiamondWhite=57565]="NoteheadDiamondWhite",e[e.NoteheadDiamondWhiteWide=57566]="NoteheadDiamondWhiteWide",e[e.NoteheadCircleXDoubleWhole=57520]="NoteheadCircleXDoubleWhole",e[e.NoteheadCircleXWhole=57521]="NoteheadCircleXWhole",e[e.NoteheadCircleXHalf=57522]="NoteheadCircleXHalf",e[e.NoteheadCircleX=57523]="NoteheadCircleX",e[e.NoteheadXDoubleWhole=57510]="NoteheadXDoubleWhole",e[e.NoteheadXWhole=57511]="NoteheadXWhole",e[e.NoteheadXHalf=57512]="NoteheadXHalf",e[e.NoteheadXBlack=57513]="NoteheadXBlack",e[e.NoteheadParenthesis=57550]="NoteheadParenthesis",e[e.NoteheadSlashedBlack1=57551]="NoteheadSlashedBlack1",e[e.NoteheadSlashedBlack2=57552]="NoteheadSlashedBlack2",e[e.NoteheadSlashedHalf1=57553]="NoteheadSlashedHalf1",e[e.NoteheadSlashedHalf2=57554]="NoteheadSlashedHalf2",e[e.NoteheadSlashedWhole1=57555]="NoteheadSlashedWhole1",e[e.NoteheadSlashedWhole2=57556]="NoteheadSlashedWhole2",e[e.NoteheadSlashedDoubleWhole1=57557]="NoteheadSlashedDoubleWhole1",e[e.NoteheadSlashedDoubleWhole2=57558]="NoteheadSlashedDoubleWhole2",e[e.NoteheadCircledBlack=57572]="NoteheadCircledBlack",e[e.NoteheadCircledHalf=57573]="NoteheadCircledHalf",e[e.NoteheadCircledWhole=57574]="NoteheadCircledWhole",e[e.NoteheadCircledDoubleWhole=57575]="NoteheadCircledDoubleWhole",e[e.NoteheadCircleSlash=57591]="NoteheadCircleSlash",e[e.NoteheadHeavyX=57592]="NoteheadHeavyX",e[e.NoteheadHeavyXHat=57593]="NoteheadHeavyXHat",e[e.NoteheadSlashVerticalEnds=57600]="NoteheadSlashVerticalEnds",e[e.NoteheadSlashWhiteWhole=57602]="NoteheadSlashWhiteWhole",e[e.NoteheadSlashWhiteHalf=57603]="NoteheadSlashWhiteHalf",e[e.NoteheadRoundWhiteWithDot=57621]="NoteheadRoundWhiteWithDot",e[e.NoteheadSquareBlackLarge=57626]="NoteheadSquareBlackLarge",e[e.NoteheadSquareBlackWhite=57627]="NoteheadSquareBlackWhite",e[e.NoteheadClusterDoubleWhole3rd=57640]="NoteheadClusterDoubleWhole3rd",e[e.NoteheadClusterWhole3rd=57641]="NoteheadClusterWhole3rd",e[e.NoteheadClusterHalf3rd=57642]="NoteheadClusterHalf3rd",e[e.NoteheadClusterQuarter3rd=57643]="NoteheadClusterQuarter3rd",e[e.NoteShapeRoundWhite=57776]="NoteShapeRoundWhite",e[e.NoteShapeRoundBlack=57777]="NoteShapeRoundBlack",e[e.NoteShapeSquareWhite=57778]="NoteShapeSquareWhite",e[e.NoteShapeSquareBlack=57779]="NoteShapeSquareBlack",e[e.NoteShapeTriangleRightWhite=57780]="NoteShapeTriangleRightWhite",e[e.NoteShapeTriangleRightBlack=57781]="NoteShapeTriangleRightBlack",e[e.NoteShapeTriangleLeftWhite=57782]="NoteShapeTriangleLeftWhite",e[e.NoteShapeTriangleLeftBlack=57783]="NoteShapeTriangleLeftBlack",e[e.NoteShapeDiamondWhite=57784]="NoteShapeDiamondWhite",e[e.NoteShapeDiamondBlack=57785]="NoteShapeDiamondBlack",e[e.NoteShapeTriangleUpWhite=57786]="NoteShapeTriangleUpWhite",e[e.NoteShapeTriangleUpBlack=57787]="NoteShapeTriangleUpBlack",e[e.NoteShapeMoonWhite=57788]="NoteShapeMoonWhite",e[e.NoteShapeMoonBlack=57789]="NoteShapeMoonBlack",e[e.NoteShapeTriangleRoundWhite=57790]="NoteShapeTriangleRoundWhite",e[e.NoteShapeTriangleRoundBlack=57791]="NoteShapeTriangleRoundBlack",e[e.NoteQuarterUp=57813]="NoteQuarterUp",e[e.NoteEighthUp=57815]="NoteEighthUp",e[e.TextBlackNoteLongStem=57841]="TextBlackNoteLongStem",e[e.TextBlackNoteFrac8thLongStem=57843]="TextBlackNoteFrac8thLongStem",e[e.TextBlackNoteFrac16thLongStem=57845]="TextBlackNoteFrac16thLongStem",e[e.TextBlackNoteFrac32ndLongStem=57846]="TextBlackNoteFrac32ndLongStem",e[e.TextCont8thBeamLongStem=57848]="TextCont8thBeamLongStem",e[e.TextCont16thBeamLongStem=57850]="TextCont16thBeamLongStem",e[e.TextCont32ndBeamLongStem=57851]="TextCont32ndBeamLongStem",e[e.TextAugmentationDot=57852]="TextAugmentationDot",e[e.TextTupletBracketStartLongStem=57857]="TextTupletBracketStartLongStem",e[e.TextTuplet3LongStem=57858]="TextTuplet3LongStem",e[e.TextTupletBracketEndLongStem=57859]="TextTupletBracketEndLongStem",e[e.Tremolo3=57890]="Tremolo3",e[e.Tremolo2=57889]="Tremolo2",e[e.Tremolo1=57888]="Tremolo1",e[e.FlagEighthUp=57920]="FlagEighthUp",e[e.FlagEighthDown=57921]="FlagEighthDown",e[e.FlagSixteenthUp=57922]="FlagSixteenthUp",e[e.FlagSixteenthDown=57923]="FlagSixteenthDown",e[e.FlagThirtySecondUp=57924]="FlagThirtySecondUp",e[e.FlagThirtySecondDown=57925]="FlagThirtySecondDown",e[e.FlagSixtyFourthUp=57926]="FlagSixtyFourthUp",e[e.FlagSixtyFourthDown=57927]="FlagSixtyFourthDown",e[e.FlagOneHundredTwentyEighthUp=57928]="FlagOneHundredTwentyEighthUp",e[e.FlagOneHundredTwentyEighthDown=57929]="FlagOneHundredTwentyEighthDown",e[e.FlagTwoHundredFiftySixthUp=57930]="FlagTwoHundredFiftySixthUp",e[e.FlagTwoHundredFiftySixthDown=57931]="FlagTwoHundredFiftySixthDown",e[e.AccidentalFlat=57952]="AccidentalFlat",e[e.AccidentalNatural=57953]="AccidentalNatural",e[e.AccidentalSharp=57954]="AccidentalSharp",e[e.AccidentalDoubleSharp=57955]="AccidentalDoubleSharp",e[e.AccidentalDoubleFlat=57956]="AccidentalDoubleFlat",e[e.AccidentalQuarterToneFlatArrowUp=57968]="AccidentalQuarterToneFlatArrowUp",e[e.AccidentalQuarterToneSharpArrowUp=57972]="AccidentalQuarterToneSharpArrowUp",e[e.AccidentalQuarterToneNaturalArrowUp=57970]="AccidentalQuarterToneNaturalArrowUp",e[e.Segno=57415]="Segno",e[e.Coda=57416]="Coda",e[e.ArticAccentAbove=58528]="ArticAccentAbove",e[e.ArticAccentBelow=58529]="ArticAccentBelow",e[e.ArticStaccatoAbove=58530]="ArticStaccatoAbove",e[e.ArticStaccatoBelow=58531]="ArticStaccatoBelow",e[e.ArticTenutoAbove=58532]="ArticTenutoAbove",e[e.ArticTenutoBelow=58533]="ArticTenutoBelow",e[e.ArticMarcatoAbove=58540]="ArticMarcatoAbove",e[e.ArticMarcatoBelow=58541]="ArticMarcatoBelow",e[e.FermataAbove=58560]="FermataAbove",e[e.FermataShortAbove=58564]="FermataShortAbove",e[e.FermataLongAbove=58566]="FermataLongAbove",e[e.RestLonga=58593]="RestLonga",e[e.RestDoubleWhole=58594]="RestDoubleWhole",e[e.RestWhole=58595]="RestWhole",e[e.RestHalf=58596]="RestHalf",e[e.RestQuarter=58597]="RestQuarter",e[e.RestEighth=58598]="RestEighth",e[e.RestSixteenth=58599]="RestSixteenth",e[e.RestThirtySecond=58600]="RestThirtySecond",e[e.RestSixtyFourth=58601]="RestSixtyFourth",e[e.RestOneHundredTwentyEighth=58602]="RestOneHundredTwentyEighth",e[e.RestTwoHundredFiftySixth=58603]="RestTwoHundredFiftySixth",e[e.RestHBarLeft=58607]="RestHBarLeft",e[e.RestHBarMiddle=58608]="RestHBarMiddle",e[e.RestHBarRight=58609]="RestHBarRight",e[e.Repeat1Bar=58624]="Repeat1Bar",e[e.Repeat2Bars=58625]="Repeat2Bars",e[e.Ottava=58640]="Ottava",e[e.OttavaAlta=58641]="OttavaAlta",e[e.OttavaBassaVb=58652]="OttavaBassaVb",e[e.Quindicesima=58644]="Quindicesima",e[e.QuindicesimaAlta=58645]="QuindicesimaAlta",e[e.DynamicPPP=58666]="DynamicPPP",e[e.DynamicPP=58667]="DynamicPP",e[e.DynamicPiano=58656]="DynamicPiano",e[e.DynamicMP=58668]="DynamicMP",e[e.DynamicMF=58669]="DynamicMF",e[e.DynamicForte=58658]="DynamicForte",e[e.DynamicFF=58671]="DynamicFF",e[e.DynamicFFF=58672]="DynamicFFF",e[e.OrnamentTrill=58726]="OrnamentTrill",e[e.OrnamentTurn=58727]="OrnamentTurn",e[e.OrnamentTurnInverted=58728]="OrnamentTurnInverted",e[e.OrnamentShortTrill=58732]="OrnamentShortTrill",e[e.OrnamentMordent=58733]="OrnamentMordent",e[e.StringsDownBow=58896]="StringsDownBow",e[e.StringsUpBow=58898]="StringsUpBow",e[e.KeyboardPedalPed=58960]="KeyboardPedalPed",e[e.KeyboardPedalUp=58965]="KeyboardPedalUp",e[e.PictEdgeOfCymbal=59177]="PictEdgeOfCymbal",e[e.GuitarString0=59443]="GuitarString0",e[e.GuitarString1=59444]="GuitarString1",e[e.GuitarString2=59445]="GuitarString2",e[e.GuitarString3=59446]="GuitarString3",e[e.GuitarString4=59447]="GuitarString4",e[e.GuitarString5=59448]="GuitarString5",e[e.GuitarString6=59449]="GuitarString6",e[e.GuitarString7=59450]="GuitarString7",e[e.GuitarString8=59451]="GuitarString8",e[e.GuitarString9=59452]="GuitarString9",e[e.GuitarOpenPedal=59453]="GuitarOpenPedal",e[e.GuitarClosePedal=59455]="GuitarClosePedal",e[e.GuitarGolpe=59458]="GuitarGolpe",e[e.GuitarFadeIn=59459]="GuitarFadeIn",e[e.GuitarFadeOut=59460]="GuitarFadeOut",e[e.GuitarVolumeSwell=59461]="GuitarVolumeSwell",e[e.FretboardX=59481]="FretboardX",e[e.FretboardO=59482]="FretboardO",e[e.WiggleTrill=60068]="WiggleTrill",e[e.WiggleVibratoMediumFast=60126]="WiggleVibratoMediumFast",e[e.OctaveBaselineM=60565]="OctaveBaselineM",e[e.OctaveBaselineB=60563]="OctaveBaselineB"}(I||(I={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(A||(A={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(R||(R={}));class pe{constructor(e,t){this.width=e,this.height=t}}class ge{constructor(e="",t=0,s=0,i=I.None,a=I.None,r=I.None,n=I.None,o=R.Middle){this.elementType=e,this.outputMidiNumber=s,this.staffLine=t,this.noteHeadDefault=i,this.noteHeadHalf=a!==I.None?a:i,this.noteHeadWhole=r!==I.None?r:i,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case f.Whole:return this.noteHeadWhole;case f.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class me{static articulationFromElementVariation(e,t){return e<me.gp6ElementAndVariationToArticulation.length?(t>=me.gp6ElementAndVariationToArticulation.length&&(t=0),me.gp6ElementAndVariationToArticulation[e][t]):38}static getArticulation(e){const t=e.percussionArticulation;if(t<0)return null;const s=e.beat.voice.bar.staff.track.percussionArticulations;return t<s.length?s[t]:me.getArticulationByValue(t)}static getElementAndVariation(e){const t=me.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<me.gp6ElementAndVariationToArticulation.length;e++){const s=me.gp6ElementAndVariationToArticulation[e];for(let i=0;i<s.length;i++){const a=me.getArticulationByValue(s[i]);if(a?.outputMidiNumber===t.outputMidiNumber)return[e,i]}}return[-1,-1]}static getArticulationByValue(e){return me.instrumentArticulations.has(e)?me.instrumentArticulations.get(e):null}}me.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]],me.instrumentArticulations=new Map([[38,new ge("snare",3,38,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[37,new ge("snare",3,37,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[91,new ge("snare",3,38,I.NoteheadDiamondWhite,I.NoteheadDiamondWhite,I.NoteheadDiamondWhite)],[42,new ge("hiHat",-1,42,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[92,new ge("hiHat",-1,46,I.NoteheadCircleSlash,I.NoteheadCircleSlash,I.NoteheadCircleSlash)],[46,new ge("hiHat",-1,46,I.NoteheadCircleX,I.NoteheadCircleX,I.NoteheadCircleX)],[44,new ge("hiHat",9,44,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[35,new ge("kickDrum",8,35,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[36,new ge("kickDrum",7,36,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[50,new ge("tom",1,50,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[48,new ge("tom",2,48,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[47,new ge("tom",4,47,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[45,new ge("tom",5,45,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[43,new ge("tom",6,43,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[93,new ge("ride",0,51,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack,I.PictEdgeOfCymbal,R.Bottom)],[51,new ge("ride",0,51,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[53,new ge("ride",0,53,I.NoteheadDiamondWhite,I.NoteheadDiamondWhite,I.NoteheadDiamondWhite)],[94,new ge("ride",0,51,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack,I.ArticStaccatoAbove,R.Top)],[55,new ge("splash",-2,55,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[95,new ge("splash",-2,55,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack,I.ArticStaccatoAbove,R.Bottom)],[52,new ge("china",-3,52,I.NoteheadHeavyXHat,I.NoteheadHeavyXHat,I.NoteheadHeavyXHat)],[96,new ge("china",-3,52,I.NoteheadHeavyXHat,I.NoteheadHeavyXHat,I.NoteheadHeavyXHat)],[49,new ge("crash",-2,49,I.NoteheadHeavyX,I.NoteheadHeavyX,I.NoteheadHeavyX)],[97,new ge("crash",-2,49,I.NoteheadHeavyX,I.NoteheadHeavyX,I.NoteheadHeavyX,I.ArticStaccatoAbove,R.Bottom)],[57,new ge("crash",-1,57,I.NoteheadHeavyX,I.NoteheadHeavyX,I.NoteheadHeavyX)],[98,new ge("crash",-1,57,I.NoteheadHeavyX,I.NoteheadHeavyX,I.NoteheadHeavyX,I.ArticStaccatoAbove,R.Bottom)],[99,new ge("cowbell",1,56,I.NoteheadTriangleUpBlack,I.NoteheadTriangleUpHalf,I.NoteheadTriangleUpWhole)],[100,new ge("cowbell",1,56,I.NoteheadXBlack,I.NoteheadXHalf,I.NoteheadXWhole)],[56,new ge("cowbell",0,56,I.NoteheadTriangleUpBlack,I.NoteheadTriangleUpHalf,I.NoteheadTriangleUpWhole)],[101,new ge("cowbell",0,56,I.NoteheadXBlack,I.NoteheadXHalf,I.NoteheadXWhole)],[102,new ge("cowbell",-1,56,I.NoteheadTriangleUpBlack,I.NoteheadTriangleUpHalf,I.NoteheadTriangleUpWhole)],[103,new ge("cowbell",-1,56,I.NoteheadXBlack,I.NoteheadXHalf,I.NoteheadXWhole)],[77,new ge("woodblock",-9,77,I.NoteheadTriangleUpBlack,I.NoteheadTriangleUpBlack,I.NoteheadTriangleUpBlack)],[76,new ge("woodblock",-10,76,I.NoteheadTriangleUpBlack,I.NoteheadTriangleUpBlack,I.NoteheadTriangleUpBlack)],[60,new ge("bongo",-4,60,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[104,new ge("bongo",-5,60,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole,I.NoteheadParenthesis,R.Middle)],[105,new ge("bongo",-6,60,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[61,new ge("bongo",-7,61,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[106,new ge("bongo",-8,61,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole,I.NoteheadParenthesis,R.Middle)],[107,new ge("bongo",-16,61,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[66,new ge("timbale",10,66,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[65,new ge("timbale",9,65,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[68,new ge("agogo",12,68,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[67,new ge("agogo",11,67,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[64,new ge("conga",17,64,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[108,new ge("conga",16,64,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[109,new ge("conga",15,64,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole,I.NoteheadParenthesis,R.Middle)],[63,new ge("conga",14,63,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[110,new ge("conga",13,63,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[62,new ge("conga",19,62,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole,I.NoteheadParenthesis,R.Middle)],[72,new ge("whistle",-11,72,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[71,new ge("whistle",-17,71,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[73,new ge("guiro",38,73,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[74,new ge("guiro",37,74,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[86,new ge("surdo",36,86,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[87,new ge("surdo",35,87,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadParenthesis,R.Middle)],[54,new ge("tambourine",3,54,I.NoteheadTriangleUpBlack,I.NoteheadTriangleUpBlack,I.NoteheadTriangleUpBlack)],[111,new ge("tambourine",2,54,I.NoteheadTriangleUpBlack,I.NoteheadTriangleUpBlack,I.NoteheadTriangleUpBlack,I.StringsUpBow,R.Bottom)],[112,new ge("tambourine",1,54,I.NoteheadTriangleUpBlack,I.NoteheadTriangleUpBlack,I.NoteheadTriangleUpBlack,I.StringsDownBow,R.Bottom)],[113,new ge("tambourine",-7,54,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[79,new ge("cuica",30,79,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[78,new ge("cuica",29,78,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[58,new ge("vibraslap",28,58,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[81,new ge("triangle",27,81,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[80,new ge("triangle",26,80,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadParenthesis,R.Middle)],[114,new ge("grancassa",25,43,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[115,new ge("piatti",18,49,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[116,new ge("piatti",24,49,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[69,new ge("cabasa",23,69,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[117,new ge("cabasa",22,69,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole,I.StringsUpBow,R.Bottom)],[85,new ge("castanets",21,85,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[75,new ge("claves",20,75,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[70,new ge("maraca",-12,70,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[118,new ge("maraca",-13,70,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole,I.StringsUpBow,R.Bottom)],[119,new ge("maraca",-14,70,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[120,new ge("maraca",-15,70,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole,I.StringsUpBow,R.Bottom)],[82,new ge("shaker",-23,54,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[122,new ge("shaker",-24,54,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole,I.StringsUpBow,R.Bottom)],[84,new ge("bellTree",-18,53,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[123,new ge("bellTree",-19,53,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole,I.StringsUpBow,R.Bottom)],[83,new ge("jingleBell",-20,53,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[124,new ge("unpitched",-21,62,I.NoteheadNull,I.NoteheadNull,I.NoteheadNull,I.GuitarGolpe,R.Top)],[125,new ge("unpitched",-22,62,I.NoteheadNull,I.NoteheadNull,I.NoteheadNull,I.GuitarGolpe,R.Bottom)],[39,new ge("handClap",3,39,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[40,new ge("snare",3,40,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[31,new ge("snare",3,40,I.NoteheadSlashedBlack2,I.NoteheadSlashedBlack2,I.NoteheadSlashedBlack2)],[41,new ge("tom",5,41,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole)],[59,new ge("ride",2,59,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack,I.PictEdgeOfCymbal,R.Bottom)],[126,new ge("ride",2,59,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[127,new ge("ride",2,59,I.NoteheadDiamondWhite,I.NoteheadDiamondWhite,I.NoteheadDiamondWhite)],[29,new ge("ride",2,59,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack,I.ArticStaccatoAbove,R.Top)],[30,new ge("crash",-3,49,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[33,new ge("snare",3,37,I.NoteheadXBlack,I.NoteheadXBlack,I.NoteheadXBlack)],[34,new ge("snare",3,38,I.NoteheadBlack,I.NoteheadBlack,I.NoteheadBlack)]]),me.instrumentArticulationNames=new Map([["Ride (choke)",29],["Cymbal (hit)",30],["Snare (side stick)",31],["Snare (side stick) 2",33],["Snare (hit)",34],["Kick (hit)",35],["Kick (hit) 2",36],["Snare (side stick) 3",37],["Snare (hit) 2",38],["Hand Clap (hit)",39],["Snare (hit) 3",40],["Low Floor Tom (hit)",41],["Hi-Hat (closed)",42],["Very Low Tom (hit)",43],["Pedal Hi-Hat (hit)",44],["Low Tom (hit)",45],["Hi-Hat (open)",46],["Mid Tom (hit)",47],["High Tom (hit)",48],["Crash high (hit)",49],["High Floor Tom (hit)",50],["Ride (middle)",51],["China (hit)",52],["Ride (bell)",53],["Tambourine (hit)",54],["Splash (hit)",55],["Cowbell medium (hit)",56],["Crash medium (hit)",57],["Vibraslap (hit)",58],["Ride (edge)",59],["Hand (hit)",60],["Hand (hit)",61],["Conga high (mute)",62],["Conga high (hit)",63],["Conga low (hit)",64],["Timbale high (hit)",65],["Timbale low (hit)",66],["Agogo high (hit)",67],["Agogo tow (hit)",68],["Cabasa (hit)",69],["Left Maraca (hit)",70],["Whistle high (hit)",71],["Whistle low (hit)",72],["Guiro (hit)",73],["Guiro (scrap-return)",74],["Claves (hit)",75],["Woodblock high (hit)",76],["Woodblock low (hit)",77],["Cuica (mute)",78],["Cuica (open)",79],["Triangle (rnute)",80],["Triangle (hit)",81],["Shaker (hit)",82],["Tinkle Bell (hat)",83],["Jingle Bell (hit)",83],["Bell Tree (hit)",84],["Castanets (hit)",85],["Surdo (hit)",86],["Surdo (mute)",87],["Snare (rim shot)",91],["Hi-Hat (half)",92],["Ride (edge) 2",93],["Ride (choke) 2",94],["Splash (choke)",95],["China (choke)",96],["Crash high (choke)",97],["Crash medium (choke)",98],["Cowbell low (hit)",99],["Cowbell low (tip)",100],["Cowbell medium (tip)",101],["Cowbell high (hit)",102],["Cowbell high (tip)",103],["Hand (mute)",104],["Hand (slap)",105],["Hand (mute) 2",106],["Hand (slap) 2",107],["Conga low (slap)",108],["Conga low (mute)",109],["Conga high (slap)",110],["Tambourine (return)",111],["Tambourine (roll)",112],["Tambourine (hand)",113],["Grancassa (hit)",114],["Piatti (hat)",115],["Piatti (hand)",116],["Cabasa (return)",117],["Left Maraca (return)",118],["Right Maraca (hit)",119],["Right Maraca (return)",120],["Shaker (return)",122],["Bell Tee (return)",123],["Golpe (thumb)",124],["Golpe (finger)",125],["Ride (middle) 2",126],["Ride (bell) 2",127]]),function(e){e[e.None=0]="None",e[e.InvertedTurn=1]="InvertedTurn",e[e.Turn=2]="Turn",e[e.UpperMordent=3]="UpperMordent",e[e.LowerMordent=4]="LowerMordent"}(O||(O={}));class fe{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1,this.slideTargetNoteId=-1,this.slideOriginNoteId=-1}}!function(e){e[e.Effects=0]="Effects",e[e.StandardNotationNoteHead=1]="StandardNotationNoteHead",e[e.StandardNotationAccidentals=2]="StandardNotationAccidentals",e[e.StandardNotationEffects=3]="StandardNotationEffects",e[e.GuitarTabFretNumber=4]="GuitarTabFretNumber",e[e.GuitarTabEffects=5]="GuitarTabEffects",e[e.SlashNoteHead=6]="SlashNoteHead",e[e.SlashEffects=7]="SlashEffects",e[e.NumberedNumber=8]="NumberedNumber",e[e.NumberedAccidentals=9]="NumberedAccidentals",e[e.NumberedEffects=10]="NumberedEffects"}(H||(H={}));class ye extends Q{}class be{constructor(){this.id=be.GlobalNoteId++,this.index=0,this.accentuated=S.None,this.bendType=p.None,this.bendStyle=u.Default,this.bendOrigin=null,this.isContinuedBend=!1,this.bendPoints=null,this.maxBendPoint=null,this.fret=-1,this.string=-1,this.showStringNumber=!1,this.octave=-1,this.tone=-1,this.percussionArticulation=-1,this.isVisible=!0,this.isLeftHandTapped=!1,this.isHammerPullOrigin=!1,this.hammerPullOrigin=null,this.hammerPullDestination=null,this.isSlurDestination=!1,this.slurOrigin=null,this.slurDestination=null,this.harmonicType=w.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=k.None,this.slideOutType=T.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=N.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=_.Unknown,this.rightHandFinger=_.Unknown,this.trillValue=-1,this.trillSpeed=f.ThirtySecond,this.durationPercent=1,this.accidentalMode=B.Default,this.dynamics=y.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.ornament=O.None,this._noteIdBag=null}static resetIds(){be.GlobalNoteId=0}get hasBend(){return null!==this.bendPoints&&this.bendType!==p.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?me.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?me.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==w.None}get isTieOrigin(){return null!==this.tieDestination}get isFingering(){return this.leftHandFinger!==_.Unknown||this.rightHandFinger!==_.Unknown}get trillFret(){return this.trillValue-this.stringTuning}get isTrill(){return this.trillValue>=0}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get stringTuning(){return this.beat.voice.bar.staff.capo+be.getStringTuning(this.beat.voice.bar.staff,this.string)}static getStringTuning(e,t){return e.tuning.length>0?e.tuning[e.tuning.length-(t-1)-1]:0}get realValue(){return this.calculateRealValue(!0,!0)}get realValueWithoutHarmonic(){return this.calculateRealValue(!0,!1)}calculateRealValue(e,t){const s=e?this.beat.voice.bar.staff.transpositionPitch:0;if(t){let t=this.calculateRealValue(e,!1);return this.isStringed&&(this.harmonicType===w.Natural?t=this.harmonicPitch+this.stringTuning-s:t+=this.harmonicPitch),t}return this.isPercussion?this.percussionArticulation:this.isStringed?this.fret+this.stringTuning-s:this.isPiano?12*this.octave+this.tone-s:0}get harmonicPitch(){if(this.harmonicType===w.None||!this.isStringed)return 0;const e=this.harmonicValue;return ue.isAlmostEqualTo(e,2.4)?36:ue.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!==w.Natural&&this.harmonicType!==w.None&&(e-=this.harmonicPitch),this.beat.ottava){case o._15ma:e-=24;break;case o._8va:e-=12;break;case o.Regular:break;case o._8vb:e+=12;break;case o._15mb:e+=24}switch(this.beat.voice.bar.clefOttava){case o._15ma:e-=24;break;case o._8va:e-=12;break;case o.Regular:break;case o._8vb:e+=12;break;case o._15mb:e+=24}return e-this.beat.voice.bar.staff.displayTranspositionPitch}get hasQuarterToneOffset(){return this.hasBend?this.bendPoints[0].value%2!=0:this.bendOrigin?this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value%2!=0:this.beat.hasWhammyBar?this.beat.whammyBarPoints[0].value%2!=0:!!this.beat.isContinuedWhammy&&this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value%2!=0}addBendPoint(e){let t=this.bendPoints;null===t&&(t=[],this.bendPoints=t),t.push(e),(!this.maxBendPoint||e.value>this.maxBendPoint.value)&&(this.maxBendPoint=e),this.bendType===p.None&&(this.bendType=p.Custom)}finish(e,t=null){const s=new ne((()=>be.nextNoteOnSameLine(this))),i=e&&e.notation.notationMode===P.SongBook;if(this.isTieDestination&&(this.chain(t),i&&this.tieOrigin&&this.tieOrigin.isLetRing&&(this.isLetRing=!0)),this.isLetRing&&(s.value&&s.value.isLetRing?this.letRingDestination=s.value:this.letRingDestination=this,i&&this.isTieDestination&&!this.tieOrigin.hasBend&&(this.isVisible=!1)),this.isPalmMute&&(s.value&&s.value.isPalmMute?this.palmMuteDestination=s.value:this.palmMuteDestination=this),this.isHammerPullOrigin){const e=be.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case T.Shift:case T.Legato:this.slideTarget||(this.slideTarget=s.value),this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=T.None}let a=null;this.isHammerPullOrigin&&this.hammerPullDestination?a=this.hammerPullDestination:this.slideOutType===T.Legato&&this.slideTarget&&(a=this.slideTarget),a&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===L.None?(this.effectSlurOrigin.effectSlurDestination=a,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=a,this.effectSlurDestination.effectSlurOrigin=this));const r=this.bendPoints,n=null!=r&&r.length>0;if(n){const e=this.isTieDestination&&this.tieOrigin.hasBend;this.isContinuedBend=e}else this.bendType=p.None;if(n&&this.bendType===p.Custom)if(4===r.length){const e=r[0],t=r[1],s=r[2],i=r[3];t.value===s.value?i.value>e.value?t.value>i.value?this.bendType=p.BendRelease:!this.isContinuedBend&&e.value>0?(this.bendType=p.PrebendBend,r.splice(2,1),r.splice(1,1)):(this.bendType=p.Bend,r.splice(2,1),r.splice(1,1)):i.value<e.value?this.isContinuedBend?(this.bendType=p.Release,r.splice(2,1),r.splice(1,1)):(this.bendType=p.PrebendRelease,r.splice(2,1),r.splice(1,1)):t.value>e.value?this.bendType=p.BendRelease:e.value>0&&!this.isContinuedBend?(this.bendType=p.Prebend,r.splice(2,1),r.splice(1,1)):(this.bendType=p.Hold,r.splice(2,1),r.splice(1,1)):he.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===r.length){const e=r[0],t=r[1];t.value>e.value?!this.isContinuedBend&&e.value>0?this.bendType=p.PrebendBend:this.bendType=p.Bend:t.value<e.value?this.isContinuedBend?this.bendType=p.Release:this.bendType=p.PrebendRelease:e.value>0&&!this.isContinuedBend?this.bendType=p.Prebend:this.bendType=p.Hold}this.initialBendValue>0&&(this.accidentalMode=B.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+be.MaxOffsetForSameLineSearch;){const s=t.getNoteOnString(e.string);if(s)return s;t=t.nextBeat}return null}static findHammerPullDestination(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+be.MaxOffsetForSameLineSearch;){let s=t.getNoteOnString(e.string);if(s)return s;for(let i=e.string;i>0;i--)if(s=t.getNoteOnString(i),s){if(s.isLeftHandTapped)return s;break}for(let i=e.string;i<=e.beat.voice.bar.staff.tuning.length;i++)if(s=t.getNoteOnString(i),s){if(s.isLeftHandTapped)return s;break}t=t.nextBeat}return null}static findTieOrigin(e){let t=e.beat.previousBeat;for(;t&&t.voice.bar.index>=e.beat.voice.bar.index-be.MaxOffsetForSameLineSearch;){if(e.isStringed){const s=t.getNoteOnString(e.string);if(s)return s}else if(-1===e.octave&&-1===e.tone){if(e.index<t.notes.length)return t.notes[e.index]}else{const s=t.getNoteWithRealValue(e.realValue);if(s)return s}t=t.previousBeat}return null}chain(e=null){if(null!==e)if(null!==this._noteIdBag){let t;e.has(be.NoteIdLookupKey)?t=e.get(be.NoteIdLookupKey):(t=new Map,e.set(be.NoteIdLookupKey,t)),-1===this._noteIdBag.hammerPullDestinationNoteId&&-1===this._noteIdBag.tieDestinationNoteId&&-1===this._noteIdBag.slurDestinationNoteId&&-1===this._noteIdBag.slideTargetNoteId||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),-1!==this._noteIdBag.slideOriginNoteId&&(this.slideOrigin=t.get(this._noteIdBag.slideOriginNoteId),this.slideOrigin.slideTarget=this),this._noteIdBag=null}else{if(!this.isTieDestination&&null===this.tieOrigin)return;const e=this.tieOrigin??be.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),null!==this.slideTarget&&e.set("slidetargetnoteid",this.slideTarget.id),null!==this.slideOrigin&&e.set("slideoriginnoteid",this.slideOrigin.id)}setProperty(e,t){switch(e){case"tiedestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new fe),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new fe),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new fe),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new fe),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new fe),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new fe),this._noteIdBag.hammerPullDestinationNoteId=t,!0;case"slidetargetnoteid":return null==this._noteIdBag&&(this._noteIdBag=new fe),this._noteIdBag.slideTargetNoteId=t,!0;case"slideoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new fe),this._noteIdBag.slideOriginNoteId=t,!0}return!1}}be.GlobalNoteId=0,be.MaxOffsetForSameLineSearch=3,be.NoteIdLookupKey="NoteIdLookup";class Se{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!==b.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{const e=this.beats[0].tupletNumerator/this.beats[0].tupletDenominator|0;for(const t of Se.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}Se.HalfTicks=1920,Se.QuarterTicks=960,Se.EighthTicks=480,Se.SixteenthTicks=240,Se.ThirtySecondTicks=120,Se.SixtyFourthTicks=60,Se.OneHundredTwentyEighthTicks=30,Se.TwoHundredFiftySixthTicks=15,Se.AllTicks=[Se.HalfTicks,Se.QuarterTicks,Se.EighthTicks,Se.SixteenthTicks,Se.ThirtySecondTicks,Se.SixtyFourthTicks,Se.OneHundredTwentyEighthTicks,Se.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"}(W||(W={}));class _e{static clone(e){const t=new ae;return t.offset=e.offset,t.value=e.value,t}}class we{static clone(e){const t=new be;if(t.index=e.index,t.accentuated=e.accentuated,t.bendType=e.bendType,t.bendStyle=e.bendStyle,t.isContinuedBend=e.isContinuedBend,e.bendPoints){t.bendPoints=[];for(const s of e.bendPoints)t.addBendPoint(_e.clone(s))}return t.fret=e.fret,t.string=e.string,t.showStringNumber=e.showStringNumber,t.octave=e.octave,t.tone=e.tone,t.percussionArticulation=e.percussionArticulation,t.isVisible=e.isVisible,t.isLeftHandTapped=e.isLeftHandTapped,t.isHammerPullOrigin=e.isHammerPullOrigin,t.isSlurDestination=e.isSlurDestination,t.harmonicType=e.harmonicType,t.harmonicValue=e.harmonicValue,t.isGhost=e.isGhost,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.isDead=e.isDead,t.isStaccato=e.isStaccato,t.slideInType=e.slideInType,t.slideOutType=e.slideOutType,t.vibrato=e.vibrato,t.isTieDestination=e.isTieDestination,t.leftHandFinger=e.leftHandFinger,t.rightHandFinger=e.rightHandFinger,t.trillValue=e.trillValue,t.trillSpeed=e.trillSpeed,t.durationPercent=e.durationPercent,t.accidentalMode=e.accidentalMode,t.dynamics=e.dynamics,t.ornament=e.ornament,t}}class Be{static clone(e){const t=new ie;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class ke{static clone(e){const t=new xe;t.index=e.index,t.notes=[];for(const s of e.notes)t.addNote(we.clone(s));t.isEmpty=e.isEmpty,t.whammyStyle=e.whammyStyle,t.ottava=e.ottava,t.isLegatoOrigin=e.isLegatoOrigin,t.duration=e.duration,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.automations=[];for(const s of e.automations)t.automations.push(Be.clone(s));if(t.dots=e.dots,t.fade=e.fade,t.lyrics=e.lyrics?e.lyrics.slice():null,t.pop=e.pop,t.slap=e.slap,t.tap=e.tap,t.text=e.text,t.slashed=e.slashed,t.deadSlapped=e.deadSlapped,t.brushType=e.brushType,t.brushDuration=e.brushDuration,t.tupletDenominator=e.tupletDenominator,t.tupletNumerator=e.tupletNumerator,t.isContinuedWhammy=e.isContinuedWhammy,t.whammyBarType=e.whammyBarType,e.whammyBarPoints){t.whammyBarPoints=[];for(const s of e.whammyBarPoints)t.addWhammyBarPoint(_e.clone(s))}return t.vibrato=e.vibrato,t.chordId=e.chordId,t.graceType=e.graceType,t.pickStroke=e.pickStroke,t.tremoloSpeed=e.tremoloSpeed,t.crescendo=e.crescendo,t.displayStart=e.displayStart,t.playbackStart=e.playbackStart,t.displayDuration=e.displayDuration,t.playbackDuration=e.playbackDuration,t.overrideDisplayDuration=e.overrideDisplayDuration,t.golpe=e.golpe,t.dynamics=e.dynamics,t.invertBeamDirection=e.invertBeamDirection,t.preferredBeamDirection=e.preferredBeamDirection,t.isEffectSlurOrigin=e.isEffectSlurOrigin,t.beamingMode=e.beamingMode,t.wahPedal=e.wahPedal,t.barreFret=e.barreFret,t.barreShape=e.barreShape,t.rasgueado=e.rasgueado,t.showTimer=e.showTimer,t.timer=e.timer,t}}class Te{constructor(){this.beats=[],this.id="empty",this.isComplete=!1}addBeat(e){e.graceIndex=this.beats.length,e.graceGroup=this,this.beats.push(e)}finish(){this.beats.length>0&&(this.id=`${this.beats[0].absoluteDisplayStart}_${this.beats[0].voice.index}`)}}!function(e){e[e.None=0]="None",e[e.Thumb=1]="Thumb",e[e.Finger=2]="Finger"}(V||(V={})),function(e){e[e.None=0]="None",e[e.FadeIn=1]="FadeIn",e[e.FadeOut=2]="FadeOut",e[e.VolumeSwell=3]="VolumeSwell"}(G||(G={})),function(e){e[e.None=0]="None",e[e.Open=1]="Open",e[e.Closed=2]="Closed"}(U||(U={})),function(e){e[e.None=0]="None",e[e.Full=1]="Full",e[e.Half=2]="Half"}(z||(z={})),function(e){e[e.None=0]="None",e[e.Ii=1]="Ii",e[e.Mi=2]="Mi",e[e.MiiTriplet=3]="MiiTriplet",e[e.MiiAnapaest=4]="MiiAnapaest",e[e.PmpTriplet=5]="PmpTriplet",e[e.PmpAnapaest=6]="PmpAnapaest",e[e.PeiTriplet=7]="PeiTriplet",e[e.PeiAnapaest=8]="PeiAnapaest",e[e.PaiTriplet=9]="PaiTriplet",e[e.PaiAnapaest=10]="PaiAnapaest",e[e.AmiTriplet=11]="AmiTriplet",e[e.AmiAnapaest=12]="AmiAnapaest",e[e.Ppp=13]="Ppp",e[e.Amii=14]="Amii",e[e.Amip=15]="Amip",e[e.Eami=16]="Eami",e[e.Eamii=17]="Eamii",e[e.Peami=18]="Peami"}(X||(X={})),function(e){e[e.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext",e[e.ForceSplitOnSecondaryToNext=3]="ForceSplitOnSecondaryToNext"}(J||(J={})),function(e){e[e.Effects=0]="Effects",e[e.StandardNotationStem=1]="StandardNotationStem",e[e.StandardNotationFlags=2]="StandardNotationFlags",e[e.StandardNotationBeams=3]="StandardNotationBeams",e[e.StandardNotationTuplet=4]="StandardNotationTuplet",e[e.StandardNotationEffects=5]="StandardNotationEffects",e[e.StandardNotationRests=6]="StandardNotationRests",e[e.GuitarTabStem=7]="GuitarTabStem",e[e.GuitarTabFlags=8]="GuitarTabFlags",e[e.GuitarTabBeams=9]="GuitarTabBeams",e[e.GuitarTabTuplet=10]="GuitarTabTuplet",e[e.GuitarTabEffects=11]="GuitarTabEffects",e[e.GuitarTabRests=12]="GuitarTabRests",e[e.SlashStem=13]="SlashStem",e[e.SlashFlags=14]="SlashFlags",e[e.SlashBeams=15]="SlashBeams",e[e.SlashTuplet=16]="SlashTuplet",e[e.SlashRests=17]="SlashRests",e[e.SlashEffects=18]="SlashEffects",e[e.NumberedDuration=19]="NumberedDuration",e[e.NumberedEffects=20]="NumberedEffects",e[e.NumberedRests=21]="NumberedRests",e[e.NumberedTuplet=22]="NumberedTuplet"}(Y||(Y={}));class Ne extends Q{}class xe{constructor(){this.id=xe._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=u.Default,this.ottava=o.Regular,this.fermata=null,this.isLegatoOrigin=!1,this.minNote=null,this.maxNote=null,this.maxStringNote=null,this.minStringNote=null,this.duration=f.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fade=G.None,this.lyrics=null,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.slashed=!1,this.deadSlapped=!1,this.brushType=g.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=W.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=N.None,this.chordId=null,this.graceType=b.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=L.None,this.tremoloSpeed=null,this.crescendo=m.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.golpe=V.None,this.dynamics=y.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=J.Auto,this.wahPedal=U.None,this.barreFret=-1,this.barreShape=z.None,this.rasgueado=X.None,this.showTimer=!1,this.timer=null}static resetIds(){xe._globalBeatId=0}get isLastOfVoice(){return this.index===this.voice.beats.length-1}get isLegatoDestination(){return!!this.previousBeat&&this.previousBeat.isLegatoOrigin}get isRest(){return this.isEmpty||!this.deadSlapped&&0===this.notes.length}get isFullBarRest(){return this.isRest&&1===this.voice.beats.length&&this.duration===f.Whole}get fadeIn(){return this.fade===G.FadeIn}set fadeIn(e){this.fade=e?G.FadeIn:G.None}get hasRasgueado(){return this.rasgueado!==X.None}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==W.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 displayEnd(){return this.displayStart+this.displayDuration}get absoluteDisplayStart(){return this.voice.bar.masterBar.start+this.displayStart}get absolutePlaybackStart(){return this.voice.bar.masterBar.start+this.playbackStart}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get isBarre(){return this.barreShape!==z.None&&this.barreFret>=0}addWhammyBarPoint(e){let t=this.whammyBarPoints;null===t&&(t=[],this.whammyBarPoints=t),t.push(e),(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e),(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e),this.whammyBarType===W.None&&(this.whammyBarType=W.Custom)}removeWhammyBarPoint(e){const t=this.whammyBarPoints;if(null===t||e<0||e>=t.length)return;t.splice(e,1);const s=t[e];if(s===this.maxWhammyPoint){this.maxWhammyPoint=null;for(const e of t)(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e)}if(s===this.minWhammyPoint){this.minWhammyPoint=null;for(const 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){const t=this.notes.indexOf(e);t>=0&&(this.notes.splice(t,1),e.isStringed&&this.noteStringLookup.delete(e.string))}getAutomation(e){for(let t=0,s=this.automations.length;t<s;t++){const s=this.automations[t];if(s.type===e)return s}return null}getNoteOnString(e){return this.noteStringLookup.has(e)?this.noteStringLookup.get(e):null}calculateDuration(){if(void 0!==this.overrideDisplayDuration)return this.overrideDisplayDuration;if(this.isFullBarRest)return this.voice.bar.masterBar.calculateDuration();let e=se.toTicks(this.duration);return 2===this.dots?e=se.applyDot(e,!0):1===this.dots&&(e=se.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=se.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){const e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case b.BeforeBeat:case b.OnBeat:switch(this.duration){case f.Sixteenth:this.playbackDuration=se.toTicks(f.SixtyFourth);break;case f.ThirtySecond:this.playbackDuration=se.toTicks(f.OneHundredTwentyEighth);break;default:this.playbackDuration=se.toTicks(f.ThirtySecond)}this.displayDuration=0;break;case b.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;const t=this.previousBeat;t&&t.graceType===b.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){const e=this.previousBeat;let t=e?e.tupletGroup:null;if((this.hasTuplet||this.graceType!==b.None&&t)&&(e&&t&&t.check(this)||(t=new Se(this.voice),t.check(this)),this.tupletGroup=t),this.index>0){const e=this.voice.bar.masterBar.calculateDuration(),t=[];for(const s of this.automations)0===s.ratioPosition&&(s.ratioPosition=this.playbackStart/e),s.type!==d.Volume&&t.push(s);this.automations=t}}finish(e,t=null){switch(null===this.getAutomation(d.Instrument)&&0===this.index&&0===this.voice.index&&0===this.voice.bar.index&&0===this.voice.bar.staff.index&&this.automations.push(ie.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case b.OnBeat:case b.BeforeBeat:const e=this.graceGroup.beats.length;this.duration=1===e?f.Eighth:2===e?f.Sixteenth:f.ThirtySecond}const s=e?e.notation.notationMode:P.GuitarPro;let i="grad"===this.text||"grad."===this.text;i&&s===P.SongBook&&(this.text="");let a=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let r=0,n=!1;for(let o=0,h=this.notes.length;o<h;o++){const h=this.notes[o];if(h.dynamics=this.dynamics,h.finish(e,t),h.isLetRing&&(this.isLetRing=!0),h.isPalmMute&&(this.isPalmMute=!0),s===P.SongBook&&h.hasBend&&this.graceType!==b.BendGrace){if(!h.isTieOrigin)switch(h.bendType){case p.Bend:case p.PrebendRelease:case p.PrebendBend:a=!0}i||h.bendStyle===u.Gradual?(i=!0,h.bendStyle=u.Gradual,a=!1):h.bendStyle=u.Fast}h.isVisible&&(r++,(!this.minNote||h.realValue<this.minNote.realValue)&&(this.minNote=h),(!this.maxNote||h.realValue>this.maxNote.realValue)&&(this.maxNote=h),(!this.minStringNote||h.string<this.minStringNote.string)&&(this.minStringNote=h),(!this.maxStringNote||h.string>this.maxStringNote.string)&&(this.maxStringNote=h),h.hasEffectSlur&&(n=!0))}if(n&&(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===r&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&e&&e.notation.notationMode===P.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 o=this.whammyBarPoints,h=null!==o&&o.length>0;if(h){const e=!!this.previousBeat&&this.previousBeat.hasWhammyBar;this.isContinuedWhammy=e}else this.whammyBarType=W.None;if(h&&this.whammyBarType===W.Custom&&(s===P.SongBook&&(this.whammyStyle=i?u.Gradual:u.Fast),4===o.length)){const e=o[0],t=o[1],i=o[2],a=o[3];t.value===i.value&&(e.value<t.value&&t.value<a.value||e.value>t.value&&t.value>a.value?(0===e.value||this.isContinuedWhammy?this.whammyBarType=W.Dive:this.whammyBarType=W.PrediveDive,o.splice(2,1),o.splice(1,1)):e.value>t.value&&t.value<a.value||e.value<t.value&&t.value>a.value?(this.whammyBarType=W.Dip,t.offset!==i.offset&&s!==P.SongBook||o.splice(2,1)):e.value===t.value&&t.value===a.value&&(0===e.value||this.isContinuedWhammy?this.whammyBarType=W.Hold:this.whammyBarType=W.Predive,o.splice(2,1),o.splice(1,1)))}if(this.updateDurations(),a){const e=ke.clone(this);e.id=xe._globalBeatId++,e.pickStroke=L.None;for(let t=0,s=e.notes.length;t<s;t++){const s=e.notes[t],i=this.notes[t];if(s.bendType=p.None,s.maxBendPoint=null,s.bendPoints=null,s.bendStyle=u.Default,s.id=be.GlobalNoteId++,i.isTieOrigin&&(s.tieDestination=i.tieDestination,i.tieDestination.tieOrigin=s),i.isTieDestination&&(s.tieOrigin=i.tieOrigin?i.tieOrigin:null,i.tieOrigin.tieDestination=s),i.hasBend&&i.isTieOrigin){const e=be.findTieOrigin(i);if(e&&e.hasBend){s.bendType=p.Hold;const e=i.bendPoints[i.bendPoints.length-1];s.addBendPoint(new ae(0,e.value)),s.addBendPoint(new ae(ae.MaxPosition,e.value))}}s.isTieDestination=!0}this.graceType=b.BendGrace,this.graceGroup=new Te,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new Te,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)}}xe._globalBeatId=0,function(e){e[e.Glyphs=0]="Glyphs"}($||($={}));class ve extends Q{}let Pe=class e{constructor(){this._isEmpty=!0,this._isRestOnly=!0,this.id=e._globalVoiceId++,this.index=0,this.beats=[]}static resetIds(){e._globalVoiceId=0}get isEmpty(){return this._isEmpty}forceNonEmpty(){this._isEmpty=!1}get isRestOnly(){return this._isRestOnly}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),e.isRest||(this._isRestOnly=!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){const 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);const t=this.beats[this.beats.length-1];this.beats.splice(this.beats.length-1,1),this.addBeat(e),this.addBeat(t),this._isEmpty=!1,this._isRestOnly=!1}getBeatAtPlaybackStart(e){return this._beatLookup.has(e)?this._beatLookup.get(e):null}finish(e,t=null){this._isEmpty=!0,this._isRestOnly=!0,this._beatLookup=new Map;let s=null;for(let e=0;e<this.beats.length;e++){const i=this.beats[e];i.index=e,this.chain(i,t),i.graceType===b.None?(i.graceGroup=s,s&&(s.isComplete=!0),s=null):(s||(s=new Te),s.addBeat(i)),i.isEmpty||(this._isEmpty=!1),i.isRest||(this._isRestOnly=!1)}let i=0,a=0;for(let s=0;s<this.beats.length;s++){const r=this.beats[s];if(r.index=s,r.finish(e,t),r.graceType===b.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==b.BendGrace){const s=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case b.BeforeBeat:e.previousBeat?(e.previousBeat.playbackDuration-=s,a=e.previousBeat.voice===this?e.previousBeat.playbackStart+e.previousBeat.playbackDuration:-s):a=-s;for(const e of r.graceGroup.beats)this._beatLookup.delete(e.playbackStart),e.playbackStart=a,this._beatLookup.set(e.playbackStart,r),a+=e.playbackDuration;break;case b.OnBeat:r.playbackDuration-=s,a=t.voice===this?t.playbackStart+t.playbackDuration:-s}}}r.displayStart=i,r.playbackStart=a,r.fermata?this.bar.masterBar.addFermata(r.playbackStart,r.fermata):r.fermata=this.bar.masterBar.getFermata(r),this._beatLookup.set(r.playbackStart,r)}else r.displayStart=i,r.playbackStart=a;r.finishTuplet(),r.graceGroup&&r.graceGroup.finish(),i+=r.displayDuration,a+=r.playbackDuration}}calculateDuration(){if(this.isEmpty||0===this.beats.length)return 0;const e=this.beats[this.beats.length-1],t=this.beats[0];return e.playbackStart+e.playbackDuration-t.playbackStart}};Pe._globalVoiceId=0;class Ce{constructor(e,t,s,i){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=s,this.selectionWrapper=i}}var Ee,Fe,De,Me;!function(e){e[e.General=0]="General",e[e.Format=1]="Format",e[e.AlphaTex=2]="AlphaTex"}(Ee||(Ee={}));class Le extends Error{constructor(e,t="",s){super(t??"",{cause:s}),this.type=e,Object.setPrototypeOf(this,Le.prototype)}}class Ie extends Le{constructor(e){super(Ee.Format,e),Object.setPrototypeOf(this,Ie.prototype)}}class Ae{constructor(e,t,s,i=255){this.raw=0,this.raw=(255&i)<<24|(255&e)<<16|(255&t)<<8|255&s,this.updateRgba()}updateRgba(){255===this.a?this.rgba=`#${ue.toHexString(this.r,2)}${ue.toHexString(this.g,2)}${ue.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 Ae(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){if(e instanceof Ae)return e;switch(typeof e){case"number":{const t=new Ae(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 Ae(17*Number.parseInt(t[1],16),17*Number.parseInt(t[2],16),17*Number.parseInt(t[3],16));if(5===t.length)return new Ae(17*Number.parseInt(t[1],16),17*Number.parseInt(t[2],16),17*Number.parseInt(t[3],16),17*Number.parseInt(t[4],16));if(7===t.length)return new Ae(Number.parseInt(t.substring(1,3),16),Number.parseInt(t.substring(3,5),16),Number.parseInt(t.substring(5,7),16));if(9===t.length)return new Ae(Number.parseInt(t.substring(1,3),16),Number.parseInt(t.substring(3,5),16),Number.parseInt(t.substring(5,7),16),Number.parseInt(t.substring(7,9),16))}else if(t.startsWith("rgba")||t.startsWith("rgb")){const e=t.indexOf("("),s=t.lastIndexOf(")");if(-1===e||-1===s)throw new Ie("No values specified for rgb/rgba function");const i=t.substring(e+1,s).split(",");if(3===i.length)return new Ae(Number.parseInt(i[0]),Number.parseInt(i[1]),Number.parseInt(i[2]));if(4===i.length)return new Ae(Number.parseInt(i[0]),Number.parseInt(i[1]),Number.parseInt(i[2]),255*Number.parseFloat(i[3]))}return null}}throw new Ie("Unsupported format for color")}static toJson(e){return null===e?null:e.raw}}Ae.BlackRgb="#000000";class Re{static parseEnum(e,t){switch(typeof e){case"string":const s=Number.parseInt(e);return Number.isNaN(s)?t[Object.keys(t).find((t=>t.toLowerCase()===e.toLowerCase()))]:s;case"number":return e;case"undefined":case"object":return}throw new Le(Ee.Format,`Could not parse enum value '${e}'`)}static forEach(e,t){if(e instanceof Map)e.forEach(t);else if("object"==typeof e)for(const s in e)t(e[s],s)}static getValue(e,t){return e instanceof Map?e.get(t):"object"==typeof e?e[t]:null}}class Oe{constructor(e,t,s){this.text=e,this.startPos=t,this.endPos=s}}class He{constructor(e){this.style="normal",this.variant="normal",this.weight="normal",this.stretch="normal",this.lineHeight="normal",this.size="1rem",this.families=[],this.parseOnlyFamilies=!1,this._currentTokenIndex=-1,this._input="",this._currentToken=null,this._input=e,this._tokens=this.splitToTokens(e)}splitToTokens(e){const t=[];let s=0;for(;s<e.length;){let i=s;for(;i<e.length&&" "!==e.charAt(i);)i++;i>s&&t.push(new Oe(e.substring(s,i),s,i)),s=i+1}return t}parse(){if(this.reset(),1===this._tokens.length)switch(this._currentToken?.text){case"caption":case"icon":case"menu":case"message-box":case"small-caption":case"status-bar":case"inherit":return}this.parseOnlyFamilies||(this.fontStyleVariantWeight(),this.fontSizeLineHeight()),this.fontFamily()}static parseFamilies(e){const t=new He(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;){const s=e.charAt(t);if(" "===s||","===s)t++;else if('"'===s||"'"===s){const i=this.findEndOfQuote(e,t+1,s);this.families.push(e.substring(t+1,i).split(`\\${s}`).join(s)),t=i+1}else{const s=this.findEndOfQuote(e,t+1,",");this.families.push(e.substring(t,s).trim()),t=s+1}}}findEndOfQuote(e,t,s){let i=!1;for(;t<e.length;){const a=e.charAt(t);if(!i&&a===s)return t;i=!i&&"\\"===a,t+=1}return e.length}fontSizeLineHeight(){if(!this._currentToken)throw new Error("Missing font size");const e=this._currentToken.text.split("/");if(e.length>=3)throw new Error(`Invalid font size '${this._currentToken}' specified`);if(this.nextToken(),e.length>=2)if("/"===e[1]){if(!this._currentToken)throw new Error("Missing line-height after font size");this.lineHeight=this._currentToken.text,this.nextToken()}else this.size=e[0],this.lineHeight=e[1];else{if(!(e.length>=1))throw new Error("Missing font size");if(this.size=e[0],this._currentToken&&0===this._currentToken.text.indexOf("/"))if("/"===this._currentToken.text){if(this.nextToken(),!this._currentToken)throw new Error("Missing line-height after font size");this.lineHeight=this._currentToken.text,this.nextToken()}else this.lineHeight=this._currentToken.text.substr(1),this.nextToken()}}nextToken(){this._currentTokenIndex++,this._currentTokenIndex<this._tokens.length?this._currentToken=this._tokens[this._currentTokenIndex]:this._currentToken=null}fontStyleVariantWeight(){let e=!1,t=!1,s=!1,i=3;const a=[];for(;;){if(!this._currentToken)return;const r=this._currentToken.text;switch(r){case"normal":case"inherit":a.push(r),i--,this.nextToken();break;case"italic":case"oblique":this.style=r,e=!0,i--,this.nextToken();break;case"small-caps":this.variant=r,t=!0,i--,this.nextToken();break;case"bold":case"bolder":case"lighter":case"100":case"200":case"300":case"400":case"500":case"600":case"700":case"800":case"900":this.weight=r,s=!0,i--,this.nextToken();break;default:return}if(0===i)break}for(;a.length>0;){const i=a.pop();s?t?e||(this.style=i):this.variant=i:this.weight=i}}reset(){this._currentTokenIndex=-1,this.nextToken()}static quoteFont(e){if(-1===e.indexOf(" "))return e;return`"${e.replaceAll('"','\\"')}"`}}!function(e){e[e.Plain=0]="Plain",e[e.Italic=1]="Italic"}(Fe||(Fe={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(De||(De={}));class We{reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=He.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===De.Bold}get isItalic(){return this.style===Fe.Italic}constructor(e,t,s=Fe.Plain,i=De.Regular){this._cssScale=0,this._families=He.parseFamilies(e),this._size=t,this._style=s,this._weight=i,this._css=this.toCssString()}withSize(e){return We.withFamilyList(this._families,e,this._style,this._weight)}static withFamilyList(e,t,s=Fe.Plain,i=De.Regular){const a=new We("",t,s,i);return a.families=e,a}toCssString(e=1){if(!(this._css&&Math.abs(e-this._cssScale)<.01)){let t="";this.isBold&&(t+="bold "),this.isItalic&&(t+="italic "),t+=this.size*e,t+="px ",t+=this.families.map((e=>He.quoteFont(e))).join(", "),this._css=t,this._cssScale=e}return this._css}static fromJson(e){if(e instanceof We)return e;switch(typeof e){case"undefined":default:return null;case"object":{const t=e,s=t.get("families"),i=t.get("size"),a=Re.parseEnum(t.get("style"),Fe),r=Re.parseEnum(t.get("weight"),De);return We.withFamilyList(s,i,a,r)}case"string":{const t=new He(e);t.parse();const s=t.families,i=t.size.toLowerCase();let a=0;switch(i){case"xx-small":a=7;break;case"x-small":a=10;break;case"small":case"smaller":a=13;break;case"medium":a=16;break;case"large":case"larger":a=18;break;case"x-large":a=24;break;case"xx-large":a=32;break;default:try{a=i.endsWith("em")?16*Number.parseFloat(i.substr(0,i.length-2)):i.endsWith("pt")?16*Number.parseFloat(i.substr(0,i.length-2))/12:i.endsWith("px")?Number.parseFloat(i.substr(0,i.length-2)):12}catch(e){a=12}}let r=Fe.Plain;"italic"===t.style&&(r=Fe.Italic);let n=De.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=De.Bold}return We.withFamilyList(s,a,r,n)}}}static toJson(e){const t=new Map;return t.set("families",e.families),t.set("size",e.size),t.set("style",e.style),t.set("weight",e.weight),t}}!function(e){e[e.Browser=0]="Browser",e[e.NodeJs=1]="NodeJs",e[e.BrowserModule=2]="BrowserModule"}(Me||(Me={}));class Ve{constructor(e,t){this.characterWidths=e,this.fontSizeToHeight=t}}class Ge{static generateFontLookup(e){if(!Ge.FontSizeLookupTables.has(e))if(ic.isRunningInWorker||ic.webPlatform===Me.NodeJs){const t=new Ve(new Uint8Array([8]),1.2);Ge.FontSizeLookupTables.set(e,t)}else{const t=document.createElement("canvas").getContext("2d"),s=11;t.font=`${s}px ${e}`;const i=[];let a="";for(let e=Ge.ControlChars;e<255;e++){const s=String.fromCharCode(e);a+=s;const r=t.measureText(s);i.push(r.width)}const r=t.measureText(`${a}ÄÖÜÁÈ`),n=0-Math.abs(r.fontBoundingBoxAscent),o=0+Math.abs(r.fontBoundingBoxDescent)-n,h=new Ve(new Uint8Array(i),o/s);Ge.FontSizeLookupTables.set(e,h)}}static measureString(e,t,s,i,a){let r;let n=t[0];for(let e=0;e<t.length;e++)if(Ge.FontSizeLookupTables.has(t[e])){n=t[e];break}Ge.FontSizeLookupTables.has(n)||Ge.generateFontLookup(n),r=Ge.FontSizeLookupTables.get(n);let o=1;i===Fe.Italic&&(o*=1.1),a===De.Bold&&(o*=1.1);let h=0;for(let t=0;t<e.length;t++){const i=Math.min(r.characterWidths.length-1,e.charCodeAt(t)-Ge.ControlChars);i>=0&&(h+=r.characterWidths[i]*s/11)}return o*=1.07,new pe(h*o,s*r.fontSizeToHeight)}}Ge.FontSizeLookupTables=new Map,Ge.ControlChars=32;class Ue{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.scale=1,this.color=new Ae(255,255,255,255),this.lineWidth=1,this.font=new We("Arial",10,Fe.Plain),this.textAlign=A.Left,this.textBaseline=R.Top}destroy(){}beginRender(e,t){this.scale=this.settings.display.scale,this.buffer=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${0|e}px" height="${0|t}px" class="at-surface-svg">\n`,this._currentPath="",this._currentPathIsEmpty=!0,this.textBaseline=R.Top}beginGroup(e){this.buffer+=`<g class="${e}">`}endGroup(){this.buffer+="</g>"}endRender(){return this.buffer+="</svg>",this.buffer}fillRect(e,t,s,i){s>0&&(this.buffer+=`<rect x="${e*this.scale|0}" y="${t*this.scale|0}" width="${s*this.scale}" height="${i*this.scale}" fill="${this.color.rgba}" />\n`)}strokeRect(e,t,s,i){const a=this.lineWidth*this.scale%2==0?0:.5;this.buffer+=`<rect x="${(e*this.scale|0)+a}" y="${(t*this.scale|0)+a}" width="${s*this.scale}" height="${i*this.scale}" stroke="${this.color.rgba}"`,1!==this.lineWidth&&(this.buffer+=` stroke-width="${this.lineWidth*this.scale}"`),this.buffer+=' fill="transparent" />\n'}beginPath(){}closePath(){this._currentPath+=" z"}moveTo(e,t){this._currentPath+=` M${e*this.scale},${t*this.scale}`}lineTo(e,t){this._currentPathIsEmpty=!1,this._currentPath+=` L${e*this.scale},${t*this.scale}`}quadraticCurveTo(e,t,s,i){this._currentPathIsEmpty=!1,this._currentPath+=` Q${e*this.scale},${t*this.scale},${s*this.scale},${i*this.scale}`}bezierCurveTo(e,t,s,i,a,r){this._currentPathIsEmpty=!1,this._currentPath+=` C${e*this.scale},${t*this.scale},${s*this.scale},${i*this.scale},${a*this.scale},${r*this.scale}`}fillCircle(e,t,s){this._currentPathIsEmpty=!1,e*=this.scale,t*=this.scale,s*=this.scale,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.fill()}strokeCircle(e,t,s){this._currentPathIsEmpty=!1,e*=this.scale,t*=this.scale,s*=this.scale,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.stroke()}fill(){this._currentPathIsEmpty||(this.buffer+=`<path d="${this._currentPath}"`,"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),this.buffer+=' style="stroke: none"/>'),this._currentPath="",this._currentPathIsEmpty=!0}stroke(){if(!this._currentPathIsEmpty){let e=`<path d="${this._currentPath}" stroke="${this.color.rgba}"`;1===this.lineWidth&&1===this.scale||(e+=` stroke-width="${this.lineWidth*this.scale}"`),e+=' style="fill: none" />',this.buffer+=e}this._currentPath="",this._currentPathIsEmpty=!0}fillText(e,t,s){if(""===e)return;let i=`<text x="${t*this.scale|0}" y="${s*this.scale|0}" style='stroke: none; font:${this.font.toCssString(this.settings.display.scale)}; ${this.getSvgBaseLine()}'`;"#000000"!==this.color.rgba&&(i+=` fill="${this.color.rgba}"`),this.textAlign!==A.Left&&(i+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),i+=`>${Ue.escapeText(e)}</text>`,this.buffer+=i}static escapeText(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}getSvgTextAlignment(e){switch(e){case A.Left:return"start";case A.Center:return"middle";case A.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case R.Top:return"dominant-baseline: hanging";case R.Bottom:return"dominant-baseline: ideographic";default:return""}}measureText(e){return e?Ge.measureString(e,this.font.families,this.font.size*this.scale,this.font.style,this.font.weight):new pe(0,0)}onRenderFinished(){return null}beginRotate(e,t,s){this.buffer+=`<g transform="translate(${e*this.scale} ,${t*this.scale}) rotate( ${s})">`}endRotate(){this.buffer+="</g>"}}class ze extends Ue{fillMusicFontSymbol(e,t,s,i,a){i!==I.None&&this.fillMusicFontSymbolText(e,t,s,`&#${i};`,a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(const e of i)e!==I.None&&(r+=`&#${e};`);this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){e*=this.scale,t*=this.scale,this.buffer+=`<g transform="translate(${e} ${t})" class="at" ><text`;const r=this.scale*s;this.buffer+=1!==r?` style="font-size: ${100*r}%; stroke:none"`:' style="stroke:none"',"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),a&&(this.buffer+=` text-anchor="${this.getSvgTextAlignment(A.Center)}"`),this.buffer+=`>${i}</text></g>`}}const Xe=Object.freeze(Object.defineProperty({__proto__:null,CssFontSvgCanvas:ze,Cursors:Ce,FontSizeDefinition:Ve,FontSizes:Ge,MeasuredText:pe,SvgCanvas:Ue,get TextAlign(){return A},get TextBaseline(){return R}},Symbol.toStringTag,{value:"Module"}));var Je,Ye,$e,qe,Ke,je,Qe,Ze,et,tt,st,it,at,rt,nt;!function(e){e[e.Title=0]="Title",e[e.SubTitle=1]="SubTitle",e[e.Artist=2]="Artist",e[e.Album=3]="Album",e[e.Words=4]="Words",e[e.Music=5]="Music",e[e.WordsAndMusic=6]="WordsAndMusic",e[e.Transcriber=7]="Transcriber",e[e.Copyright=8]="Copyright",e[e.CopyrightSecondLine=9]="CopyrightSecondLine",e[e.ChordDiagramList=10]="ChordDiagramList"}(Je||(Je={}));class ot{constructor(e="",t=void 0,s=A.Left){this.template=e,this.isVisible=t,this.textAlign=s}buildText(e){let t=!1,s=!1;const i=this.template.replace(ot.PlaceholderPattern,((i,a)=>{s=!0;let r="";switch(a){case"TITLE":r=e.title;break;case"SUBTITLE":r=e.subTitle;break;case"ARTIST":r=e.artist;break;case"ALBUM":r=e.album;break;case"WORDS":case"WORDSMUSIC":r=e.words;break;case"MUSIC":r=e.music;break;case"TABBER":r=e.tab;break;case"COPYRIGHT":r=e.copyright;break;default:r=""}return r&&(t=!0),r}));return s&&!t?"":i}}ot.PlaceholderPattern=/%([^%]+)%/g;class ht extends Q{constructor(){super(...arguments),this.headerAndFooter=new Map}}ht.defaultHeaderAndFooter=new Map([[Je.Title,new ot("%TITLE%",void 0,A.Center)],[Je.SubTitle,new ot("%SUBTITLE%",void 0,A.Center)],[Je.Artist,new ot("%ARTIST%",void 0,A.Center)],[Je.Album,new ot("%ALBUM%",void 0,A.Center)],[Je.Words,new ot("Words by %WORDS%",void 0,A.Left)],[Je.Music,new ot("Music by %MUSIC%",void 0,A.Right)],[Je.WordsAndMusic,new ot("Words & Music by %MUSIC%",void 0,A.Right)],[Je.Transcriber,new ot("Tabbed by %TABBER%",!1,A.Right)],[Je.Copyright,new ot("%COPYRIGHT%",void 0,A.Center)],[Je.CopyrightSecondLine,new ot("All Rights Reserved - International Copyright Secured",!0,A.Center)]]);class lt{constructor(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0,this.album="",this.artist="",this.copyright="",this.instructions="",this.music="",this.notices="",this.subTitle="",this.title="",this.words="",this.tab="",this.tempo=120,this.tempoLabel="",this.masterBars=[],this.tracks=[],this.defaultSystemsLayout=3,this.systemsLayout=[],this.stylesheet=new K}static resetIds(){te.resetIds(),xe.resetIds(),Pe.resetIds(),be.resetIds()}rebuildRepeatGroups(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0;for(const e of this.masterBars)this.addMasterBarToRepeatGroups(e)}addMasterBar(e){e.score=this,e.index=this.masterBars.length,0!==this.masterBars.length&&(e.previousMasterBar=this.masterBars[this.masterBars.length-1],e.previousMasterBar.nextMasterBar=e,e.start=e.previousMasterBar.start+(e.previousMasterBar.isAnacrusis?0:e.previousMasterBar.calculateDuration())),this.addMasterBarToRepeatGroups(e),this.masterBars.push(e)}addMasterBarToRepeatGroups(e){e.isRepeatStart?(this._currentRepeatGroup?.isClosed&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--),this._currentRepeatGroup=new j,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new j,this._openedRepeatGroups.push(this._currentRepeatGroup)),this._currentRepeatGroup.addMasterBar(e),e.isRepeatEnd&&this._properlyOpenedRepeatGroups>1&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--,this._currentRepeatGroup=this._openedRepeatGroups.length>0?this._openedRepeatGroups[this._openedRepeatGroups.length-1]:null)}addTrack(e){e.score=this,e.index=this.tracks.length,this.tracks.push(e)}finish(e){const t=new Map;for(let s=0,i=this.tracks.length;s<i;s++)this.tracks[s].finish(e,t)}}class ct{init(e,t){this.data=e,this.settings=t,lt.resetIds()}}class dt extends Le{constructor(e=null,t){super(Ee.Format,e??"Unsupported format",t),Object.setPrototypeOf(this,dt.prototype)}}class ut{constructor(){this.name="",this.firstFret=1,this.strings=[],this.barreFrets=[],this.showName=!0,this.showDiagram=!0,this.showFingering=!0}get uniqueId(){return[this.name,this.firstFret.toString(),this.strings.join(","),this.barreFrets.join(","),this.showDiagram.toString(),this.showFingering.toString(),this.showName.toString()].join("|")}}!function(e){e[e.IgnoreSpaces=0]="IgnoreSpaces",e[e.Begin=1]="Begin",e[e.Text=2]="Text",e[e.Comment=3]="Comment",e[e.Dash=4]="Dash"}(Ye||(Ye={}));class pt{constructor(){this.startBar=0,this.text=""}finish(e=!1){this.chunks=[],this.parse(this.text,0,this.chunks,e)}parse(e,t,s,i){if(!e)return;let a=Ye.Begin,r=Ye.Begin,n=!1,o=0;for(;t<e.length;){const s=e.charCodeAt(t);switch(a){case Ye.IgnoreSpaces:switch(s){case pt.CharCodeLF:case pt.CharCodeCR:case pt.CharCodeTab:break;case pt.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case Ye.Begin:if(s!==pt.CharCodeBrackedOpen){o=t,a=Ye.Text;continue}a=Ye.Comment;break;case Ye.Comment:if(s===pt.CharCodeBrackedClose)a=Ye.Begin;break;case Ye.Text:switch(s){case pt.CharCodeDash:a=Ye.Dash;break;case pt.CharCodeCR:case pt.CharCodeLF:case pt.CharCodeSpace:const s=e.substr(o,t-o);this.addChunk(s,i),a=Ye.IgnoreSpaces,r=Ye.Begin}break;case Ye.Dash:if(s!==pt.CharCodeDash){const s=e.substr(o,t-o);this.addChunk(s,i),n=!0,a=Ye.IgnoreSpaces,r=Ye.Begin;continue}}t+=1}a===Ye.Text&&t!==o&&this.addChunk(e.substr(o,t-o),i)}addChunk(e,t){e=this.prepareChunk(e),(!t||e.length>0&&"-"!==e)&&this.chunks.push(e)}prepareChunk(e){const t=e.split("+").join(" ");let s=t.length;for(;s>0&&"_"===t.charAt(s-1);)s--;return s!==t.length?t.substr(0,s):t}}pt.CharCodeLF=10,pt.CharCodeTab=9,pt.CharCodeCR=13,pt.CharCodeSpace=32,pt.CharCodeBrackedClose=93,pt.CharCodeBrackedOpen=91,pt.CharCodeDash=45;class gt{constructor(){this.marker="",this.text=""}}class mt{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 ft{static getTextForTuning(e,t){const s=ft.getTextPartsForTuning(e);return t?s.join(""):s[0]}static getTextPartsForTuning(e,t=-1){return[["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"][e%12],((e/12|0)+t).toString()]}static getDefaultTuningFor(e){return ft._defaultTunings.has(e)?ft._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return ft._sevenStrings;case 6:return ft._sixStrings;case 5:return ft._fiveStrings;case 4:return ft._fourStrings}return[]}static initialize(){ft._defaultTunings.set(7,new ft("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),ft._sevenStrings.push(ft._defaultTunings.get(7)),ft._defaultTunings.set(6,new ft("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),ft._sixStrings.push(ft._defaultTunings.get(6)),ft._sixStrings.push(new ft("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),ft._sixStrings.push(new ft("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),ft._sixStrings.push(new ft("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),ft._sixStrings.push(new ft("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),ft._sixStrings.push(new ft("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),ft._sixStrings.push(new ft("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),ft._sixStrings.push(new ft("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),ft._sixStrings.push(new ft("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),ft._sixStrings.push(new ft("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),ft._sixStrings.push(new ft("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),ft._sixStrings.push(new ft("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),ft._sixStrings.push(new ft("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),ft._sixStrings.push(new ft("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),ft._sixStrings.push(new ft("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),ft._sixStrings.push(new ft("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),ft._sixStrings.push(new ft("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),ft._sixStrings.push(new ft("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),ft._sixStrings.push(new ft("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),ft._sixStrings.push(new ft("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),ft._sixStrings.push(new ft("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),ft._sixStrings.push(new ft("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),ft._sixStrings.push(new ft("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),ft._sixStrings.push(new ft("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),ft._sixStrings.push(new ft("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),ft._sixStrings.push(new ft("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),ft._sixStrings.push(new ft("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),ft._sixStrings.push(new ft("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),ft._sixStrings.push(new ft("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),ft._sixStrings.push(new ft("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),ft._sixStrings.push(new ft("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),ft._defaultTunings.set(5,new ft("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),ft._fiveStrings.push(ft._defaultTunings.get(5)),ft._fiveStrings.push(new ft("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),ft._fiveStrings.push(new ft("Banjo Open D Tuning",[62,57,54,50,69],!1)),ft._fiveStrings.push(new ft("Banjo Open G Tuning",[62,59,55,50,67],!1)),ft._fiveStrings.push(new ft("Banjo G Minor Tuning",[62,58,55,50,67],!1)),ft._fiveStrings.push(new ft("Banjo G Modal Tuning",[62,57,55,50,67],!1)),ft._defaultTunings.set(4,new ft("Bass Standard Tuning",[43,38,33,28],!0)),ft._fourStrings.push(ft._defaultTunings.get(4)),ft._fourStrings.push(new ft("Bass Tune down ½ step",[42,37,32,27],!1)),ft._fourStrings.push(new ft("Bass Tune down 1 step",[41,36,31,26],!1)),ft._fourStrings.push(new ft("Bass Tune down 2 step",[39,34,29,24],!1)),ft._fourStrings.push(new ft("Bass Dropped D Tuning",[43,38,33,26],!1)),ft._fourStrings.push(new ft("Ukulele C Tuning",[45,40,36,43],!1)),ft._fourStrings.push(new ft("Ukulele G Tuning",[52,47,43,38],!1)),ft._fourStrings.push(new ft("Mandolin Standard Tuning",[64,57,50,43],!1)),ft._fourStrings.push(new ft("Mandolin or Violin Tuning",[76,69,62,55],!1)),ft._fourStrings.push(new ft("Viola Tuning",[69,62,55,48],!1)),ft._fourStrings.push(new ft("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){const t=ft.getPresetsFor(e.length);for(let s=0,i=t.length;s<i;s++){const i=t[s];let a=!0;for(let t=0,s=e.length;t<s;t++)if(e[t]!==i.tunings[t]){a=!1;break}if(a)return i}return null}constructor(e="",t=null,s=!1){this.isStandard=s,this.name=e,this.tunings=t??[]}finish(){const e=ft.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}ft._sevenStrings=[],ft._sixStrings=[],ft._fiveStrings=[],ft._fourStrings=[],ft._defaultTunings=new Map,ft.defaultAccidentals=["","#","","#","","","#","","#","","#",""],ft.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],ft.initialize();class yt{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new ft("",[],!1),this.showSlash=!1,this.showNumbered=!1,this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=yt.DefaultStandardNotationLineCount}get tuning(){return this.stringTuning.tunings}get tuningName(){return this.stringTuning.name}get isStringed(){return this.stringTuning.tunings.length>0}finish(e,t=null){this.stringTuning.finish();for(let s=0,i=this.bars.length;s<i;s++)this.bars[s].finish(e,t)}addChord(e,t){t.staff=this;let s=this.chords;null===s&&(s=new Map,this.chords=s),s.set(e,t)}hasChord(e){return this.chords?.has(e)??!1}getChord(e){return this.chords?.get(e)??null}addBar(e){const 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)}}yt.DefaultStandardNotationLineCount=5,function(e){e[e.TrackName=0]="TrackName",e[e.BracesAndBrackets=1]="BracesAndBrackets",e[e.SystemSeparator=2]="SystemSeparator",e[e.StringTuning=3]="StringTuning"}($e||($e={}));class bt extends Q{}class St{constructor(){this.index=0,this.staves=[],this.playbackInfo=new mt,this.color=new Ae(200,0,0,255),this.name="",this.isVisibleOnMultiTrack=!0,this.shortName="",this.defaultSystemsLayout=3,this.systemsLayout=[],this.percussionArticulations=[]}addLineBreaks(e){this.lineBreaks||(this.lineBreaks=new Set),this.lineBreaks.add(e)}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new yt)}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>St.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,St.ShortNameMaxLength)));for(let s=0,i=this.staves.length;s<i;s++)this.staves[s].finish(e,t)}applyLyrics(e){for(const t of e)t.finish();const t=this.staves[0];for(let s=0;s<e.length;s++){const i=e[s];if(i.startBar>=0&&i.startBar<t.bars.length){let a=t.bars[i.startBar].voices[0].beats[0];for(let t=0;t<i.chunks.length&&a;t++){for(;a&&(a.isEmpty||a.isRest);)a=a.nextBeat;a&&(a.lyrics||(a.lyrics=new Array(e.length),a.lyrics.fill("")),a.lyrics[s]=i.chunks[t],a=a.nextBeat)}}}}}St.ShortNameMaxLength=10;class _t{static float64ToBytes(e){return _t._dataView.setFloat64(0,e,!0),_t._conversionByteArray}static bytesToInt64LE(e){_t._conversionByteArray.set(e,0);const t=_t._dataView.getBigInt64(0,!0);return t<=Number.MAX_SAFE_INTEGER&&t>=Number.MIN_SAFE_INTEGER?Number(t):Number.MAX_SAFE_INTEGER}static bytesToFloat64LE(e){return _t._conversionByteArray.set(e,0),_t._dataView.getFloat64(0,!0)}static bytesToFloat32LE(e){return _t._conversionByteArray.set(e,0),_t._dataView.getFloat32(0,!0)}static float32BEToBytes(e){return _t._dataView.setFloat32(0,e,!1),_t._conversionByteArray.slice(0,4)}static uint16ToInt16(e){return _t._dataView.setUint16(0,e,!0),_t._dataView.getInt16(0,!0)}static int16ToUint32(e){return _t._dataView.setInt16(0,e,!0),_t._dataView.getUint32(0,!0)}static int32ToUint16(e){return _t._dataView.setInt32(0,e,!0),_t._dataView.getUint16(0,!0)}static int32ToInt16(e){return _t._dataView.setInt32(0,e,!0),_t._dataView.getInt16(0,!0)}static int32ToUint32(e){return _t._dataView.setInt32(0,e,!0),_t._dataView.getUint32(0,!0)}static uint8ToInt8(e){return _t._dataView.setUint8(0,e),_t._dataView.getInt8(0)}}_t._conversionBuffer=new ArrayBuffer(8),_t._conversionByteArray=new Uint8Array(_t._conversionBuffer),_t._dataView=new DataView(_t._conversionBuffer);class wt{static readInt32BE(e){return e.readByte()<<24|e.readByte()<<16|e.readByte()<<8|e.readByte()}static readFloat32BE(e){const t=new Uint8Array(4);return e.read(t,0,t.length),t.reverse(),_t.bytesToFloat32LE(t)}static readFloat64BE(e){const t=new Uint8Array(8);return e.read(t,0,t.length),t.reverse(),_t.bytesToFloat64LE(t)}static readInt32LE(e){const t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static readInt64LE(e){const t=new Uint8Array(8);return e.read(t,0,t.length),_t.bytesToInt64LE(t)}static readUInt32LE(e){const t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static decodeUInt32LE(e,t){const s=e[t],i=e[t+1],a=e[t+2];return e[t+3]<<24|a<<16|i<<8|s}static readUInt16LE(e){const t=e.readByte(),s=e.readByte();return _t.int32ToUint16(s<<8|t)}static readInt16LE(e){const t=e.readByte(),s=e.readByte();return _t.int32ToInt16(s<<8|t)}static readUInt32BE(e){const t=e.readByte(),s=e.readByte(),i=e.readByte(),a=e.readByte();return _t.int32ToUint32(t<<24|s<<16|i<<8|a)}static readUInt16BE(e){const t=e.readByte(),s=e.readByte();return _t.int32ToInt16(t<<8|s)}static readInt16BE(e){const t=e.readByte(),s=e.readByte();return _t.int32ToInt16(t<<8|s)}static readByteArray(e,t){const s=new Uint8Array(t);return e.read(s,0,t),s}static read8BitChars(e,t){const s=new Uint8Array(t);return e.read(s,0,s.length),wt.toString(s,"utf-8")}static read8BitString(e){let t="",s=e.readByte();for(;0!==s;)t+=String.fromCharCode(s),s=e.readByte();return t}static read8BitStringLength(e,t){let s="",i=-1;for(let a=0;a<t;a++){const t=e.readByte();0===t&&-1===i&&(i=a),s+=String.fromCharCode(t)}const a=s;return i>=0?a.substr(0,i):a}static readSInt8(e){const t=e.readByte();return-256*((255&t)>>7)+(255&t)}static readInt24(e,t){let s=e[t]|e[t+1]<<8|e[t+2]<<16;return 8388608&~s||(s|=255<<24),s}static readInt16(e,t){return _t.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){const s=wt.detectEncoding(e);s&&(t=s),t||(t="utf-8");return new TextDecoder(t).decode(e.buffer)}static detectEncoding(e){return e.length>2&&254===e[0]&&255===e[1]?"utf-16be":e.length>2&&255===e[0]&&254===e[1]?"utf-16le":e.length>4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3]?"utf-32be":e.length>4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3]?"utf-32le":null}static stringToBytes(e){return(new TextEncoder).encode(e)}static writeInt32BE(e,t){e.writeByte(t>>24&255),e.writeByte(t>>16&255),e.writeByte(t>>8&255),e.writeByte(255&t)}static writeInt32LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255),e.writeByte(t>>16&255),e.writeByte(t>>24&255)}static writeUInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16BE(e,t){e.writeByte(t>>8&255),e.writeByte(255&t)}static writeFloat32BE(e,t){const s=_t.float32BEToBytes(t);e.write(s,0,s.length)}}class Bt{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return Bt.withCapacity(0)}static withCapacity(e){const t=new Bt;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){const t=new Bt;return t._buffer=e,t.length=e.length,t}static fromString(e){const t=wt.stringToBytes(e);return Bt.fromBuffer(t)}reset(){this.position=0}skip(e){this.position+=e}readByte(){return this.length-this.position<=0?-1:this._buffer[this.position++]}read(e,t,s){let i=this.length-this.position;return i>s&&(i=s),i<=0?0:(e.set(this._buffer.subarray(this.position,this.position+i),t),this.position+=i,i)}writeByte(e){const t=this.position+1;this.ensureCapacity(t),this._buffer[this.position]=255&e,t>this.length&&(this.length=t),this.position=t}write(e,t,s){const i=this.position+s;this.ensureCapacity(i);const a=Math.min(s,e.length-t);this._buffer.set(e.subarray(t,t+a),this.position),i>this.length&&(this.length=i),this.position=i}ensureCapacity(e){if(e>this._buffer.length){let t=e;t<256&&(t=256),t<2*this._buffer.length&&(t=2*this._buffer.length);const s=new Uint8Array(t);this.length>0&&s.set(this._buffer.subarray(0,0+this.length),0),this._buffer=s}}readAll(){return this.toArray()}toArray(){const e=new Uint8Array(this.length);return e.set(this._buffer.subarray(0,0+this.length),0),e}copyTo(e){e.write(this._buffer,0,this.length)}}class kt{}kt.DefaultChannelCount=17,kt.MetronomeChannel=kt.DefaultChannelCount-1,kt.MetronomeKey=33,kt.AudioChannels=2,kt.MinVolume=0,kt.MinProgram=0,kt.MaxProgram=127,kt.MinPlaybackSpeed=.125,kt.MaxPlaybackSpeed=8,kt.PercussionChannel=9,kt.PercussionBank=128,kt.MaxPitchWheel=16384,kt.MaxPitchWheel20=4294967296,kt.DefaultPitchWheel=kt.MaxPitchWheel/2,kt.MicroBufferCount=32,kt.MicroBufferSize=64,function(e){e[e.TargetFine=0]="TargetFine",e[e.TargetSegno=1]="TargetSegno",e[e.TargetSegnoSegno=2]="TargetSegnoSegno",e[e.TargetCoda=3]="TargetCoda",e[e.TargetDoubleCoda=4]="TargetDoubleCoda",e[e.JumpDaCapo=5]="JumpDaCapo",e[e.JumpDaCapoAlCoda=6]="JumpDaCapoAlCoda",e[e.JumpDaCapoAlDoubleCoda=7]="JumpDaCapoAlDoubleCoda",e[e.JumpDaCapoAlFine=8]="JumpDaCapoAlFine",e[e.JumpDalSegno=9]="JumpDalSegno",e[e.JumpDalSegnoAlCoda=10]="JumpDalSegnoAlCoda",e[e.JumpDalSegnoAlDoubleCoda=11]="JumpDalSegnoAlDoubleCoda",e[e.JumpDalSegnoAlFine=12]="JumpDalSegnoAlFine",e[e.JumpDalSegnoSegno=13]="JumpDalSegnoSegno",e[e.JumpDalSegnoSegnoAlCoda=14]="JumpDalSegnoSegnoAlCoda",e[e.JumpDalSegnoSegnoAlDoubleCoda=15]="JumpDalSegnoSegnoAlDoubleCoda",e[e.JumpDalSegnoSegnoAlFine=16]="JumpDalSegnoSegnoAlFine",e[e.JumpDaCoda=17]="JumpDaCoda",e[e.JumpDaDoubleCoda=18]="JumpDaDoubleCoda"}(qe||(qe={})),function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(Ke||(Ke={}));class Tt{constructor(){this.type=Ke.Short,this.length=0}}!function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(je||(je={})),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"}(Qe||(Qe={})),function(e){e[e.KnownStaffMeta=0]="KnownStaffMeta",e[e.UnknownStaffMeta=1]="UnknownStaffMeta",e[e.EndOfMetaDetected=2]="EndOfMetaDetected"}(Ze||(Ze={}));class Nt extends Le{constructor(e,t,s,i,a,r,n,o=null){super(Ee.AlphaTex,e),this.position=t,this.line=s,this.col=i,this.nonTerm=a??"",this.expected=r??Qe.No,this.symbol=n??Qe.No,this.symbolData=o,Object.setPrototypeOf(this,Nt.prototype)}static symbolError(e,t,s,i,a,r,n=null){let o=`MalFormed AlphaTex: @${e} (line ${t}, col ${s}): Error on block ${i}`;return a!==r?(o+=`, expected a ${Qe[a]} found a ${Qe[r]}`,null!==n&&(o+=`: '${n}'`)):o+=`, invalid value: '${n}'`,new Nt(o,e,t,s,i,a,r,n)}static errorMessage(e,t,s,i){return new Nt(e=`MalFormed AlphaTex: @${t} (line ${s}, col ${i}): ${e}`,t,s,i,null,null,null,null)}}!function(e){e[e.Auto=0]="Auto",e[e.Explicit=1]="Explicit"}(et||(et={}));class xt extends ct{constructor(){super(...arguments),this._trackChannel=0,this._barIndex=0,this._voiceIndex=0,this._input="",this._ch=xt.Eof,this._curChPos=0,this._line=1,this._col=0,this._lastValidSpot=[0,1,0],this._sy=Qe.No,this._syData="",this._allowNegatives=!1,this._allowFloat=!1,this._allowTuning=!1,this._currentDuration=f.QuadrupleWhole,this._currentDynamics=y.PPP,this._currentTuplet=0,this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._percussionArticulationNames=new Map,this._sustainPedalToBeat=new Map,this._slurs=new Map,this._accidentalMode=et.Explicit,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=Bt.empty(),this._input=e,this.settings=t}readScore(){try{if(this.data.length>0&&(this._input=wt.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this._sustainPedalToBeat=new Map,this.createDefaultScore(),this._curChPos=0,this._line=1,this._col=0,this.saveValidSpot(),this._currentDuration=f.Quarter,this._currentDynamics=y.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===Qe.LowerThan)throw new dt("Unknown start sign '<' (meant to import as XML?)");if(this._sy!==Qe.Eof){const e=this.metaData(),t=this.bars();if(!e&&!t)throw new dt("No alphaTex data found")}this.consolidate(),this._score.finish(this.settings),this._score.rebuildRepeatGroups();for(const[e,t]of this._lyrics)this._score.tracks[e].applyLyrics(t);for(const[e,t]of this._sustainPedalToBeat){const s=t.voice.bar.masterBar.calculateDuration();e.ratioPosition=t.playbackStart/s}return this._score}catch(e){if(e instanceof Nt)throw new dt(e.message,e);throw e}}consolidate(){if(0===this._score.masterBars.length){const e=new le;this._score.addMasterBar(e);const t=new ie;t.isLinear=!1,t.type=d.Tempo,t.value=this._score.tempo,e.tempoAutomations.push(t);const s=new te;this._score.tracks[0].staves[0].addBar(s);const i=new Pe;s.addVoice(i);const a=new xe;return a.isEmpty=!0,void i.addBeat(a)}for(const e of this._score.tracks)for(const t of e.staves){for(const e of t.bars)for(const t of e.voices)if(t.isEmpty&&0===t.beats.length){const e=new xe;e.isEmpty=!0,t.addBeat(e)}const e=0===t.bars.length?1:t.bars[0].voices.length;for(;t.bars.length<this._score.masterBars.length;){const s=new te;t.addBar(s);for(let t=0;t<e;t++){const e=new Pe;s.addVoice(e);const t=new xe;t.isEmpty=!0,e.addBeat(t)}}}}error(e,t,s=!0){let i,a=!1;s?(i=this._sy,i!==Qe.String&&i!==Qe.Number&&i!==Qe.MetaCommand||(a=!0)):i=t;const r=Nt.symbolError(this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2],e,t,i,a?this._syData:null);throw this.logErrors&&he.error(this.name,r.message),r}errorMessage(e){const t=Nt.errorMessage(e,this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2]);throw this.logErrors&&he.error(this.name,t.message),t}createDefaultScore(){this._score=new lt,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new St,this._currentTrack.ensureStaveCount(1),this._currentTrack.playbackInfo.program=25,this._currentTrack.playbackInfo.primaryChannel=this._trackChannel++,this._currentTrack.playbackInfo.secondaryChannel=this._trackChannel++;const e=this._currentTrack.staves[0];e.displayTranspositionPitch=0,e.stringTuning.tunings=ft.getDefaultTuningFor(6).tunings,this.beginStaff(e),this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=y.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":default:return n.G2;case"f4":case"bass":return n.F4;case"c3":case"tenor":return n.C3;case"c4":case"alto":return n.C4;case"n":case"neutral":return n.Neutral}}parseClefFromInt(e){switch(e){case 43:default:return n.G2;case 65:return n.F4;case 48:return n.C3;case 60:return n.C4}}parseTripletFeelFromString(e){switch(e.toLowerCase()){case"no":case"none":default:return M.NoTripletFeel;case"t16":case"triplet-16th":return M.Triplet16th;case"t8":case"triplet-8th":return M.Triplet8th;case"d16":case"dotted-16th":return M.Dotted16th;case"d8":case"dotted-8th":return M.Dotted8th;case"s16":case"scottish-16th":return M.Scottish16th;case"s8":case"scottish-8th":return M.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return M.NoTripletFeel;case 1:return M.Triplet16th;case 2:return M.Triplet8th;case 3:return M.Dotted16th;case 4:return M.Dotted8th;case 5:return M.Scottish16th;case 6:return M.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":case"abminor":return F.Cb;case"gb":case"gbmajor":case"ebminor":return F.Gb;case"db":case"dbmajor":case"bbminor":return F.Db;case"ab":case"abmajor":case"fminor":return F.Ab;case"eb":case"ebmajor":case"cminor":return F.Eb;case"bb":case"bbmajor":case"gminor":return F.Bb;case"f":case"fmajor":case"dminor":return F.F;case"c":case"cmajor":case"aminor":default:return F.C;case"g":case"gmajor":case"eminor":return F.G;case"d":case"dmajor":case"bminor":return F.D;case"a":case"amajor":case"f#minor":return F.A;case"e":case"emajor":case"c#minor":return F.E;case"b":case"bmajor":case"g#minor":return F.B;case"f#":case"f#major":case"d#minor":return F.FSharp;case"c#":case"c#major":case"a#minor":return F.CSharp}}parseKeySignatureType(e){return e.toLowerCase().endsWith("minor")?D.Minor:D.Major}nextChar(){return this._curChPos<this._input.length?(this._ch=this._input.charCodeAt(this._curChPos++),10===this._ch?(this._line++,this._col=0):this._col++):this._ch=xt.Eof,this._ch}saveValidSpot(){this._lastValidSpot=[this._curChPos,this._line,this._col]}newSy(){for(this.saveValidSpot(),this._sy=Qe.No;this._sy===Qe.No;)if(this._ch===xt.Eof)this._sy=Qe.Eof;else if(xt.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!==xt.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;this._ch!==xt.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",Qe.String,!1);this.saveValidSpot()}else if(34===this._ch||39===this._ch){const e=this._ch;this._ch=this.nextChar();let t="";for(this._sy=Qe.String;this._ch!==e&&this._ch!==xt.Eof;)92===this._ch?(this._ch=this.nextChar(),92===this._ch?t+="\\":this._ch===e?t+=String.fromCharCode(this._ch):82===this._ch||114===this._ch?t+="\r":78===this._ch||110===this._ch?t+="\n":84===this._ch||116===this._ch?t+="\t":this.errorMessage("Unsupported escape sequence")):t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._ch===xt.Eof&&this.errorMessage("String opened but never closed"),this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)this._allowNegatives?this.readNumberOrName():(this._sy=Qe.String,this._syData=this.readName());else if(46===this._ch)this._sy=Qe.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=Qe.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=Qe.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=Qe.MetaCommand,92===this._ch&&(this._ch=this.nextChar()),this._syData=this.readName();else if(41===this._ch)this._sy=Qe.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=Qe.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=Qe.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=Qe.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=Qe.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=Qe.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this.readNumberOrName();else if(xt.isNameLetter(this._ch)){const e=this.readName(),t=this._allowTuning?ue.parseTuning(e):null;t?(this._sy=Qe.Tuning,this._syData=t):(this._sy=Qe.String,this._syData=e)}else this.error("symbol",Qe.String,!1);return this._sy}readNumberOrName(){let e="",t=!0;do{e+=String.fromCharCode(this._ch),this.isDigit(this._ch)||(t=!1),this._ch=this.nextChar()}while(this.isDigit(this._ch)||xt.isNameLetter(this._ch));t?(this._sy=Qe.Number,this._syData=this._allowFloat?Number.parseFloat(e):Number.parseInt(e)):(this._sy=Qe.String,this._syData=e)}static isNameLetter(e){return!xt.isTerminal(e)&&(33<=e&&e<=47||58<=e&&e<=126||128<=e)}static isTerminal(e){return 46===e||123===e||125===e||91===e||93===e||40===e||41===e||124===e||39===e||34===e||42===e||92===e}static isWhiteSpace(e){return 9===e||10===e||11===e||13===e||32===e}isDigit(e){return e>=48&&e<=57||this._allowNegatives&&45===e||this._allowFloat&&46===e}readName(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(xt.isNameLetter(this._ch)||this.isDigit(this._ch));return e}metaData(){let e=!1,t=!1,s=!0;for(;this._sy===Qe.MetaCommand&&s;){const i=this._syData.toLowerCase();switch(i){case"title":case"subtitle":case"artist":case"album":case"words":case"music":case"copyright":case"instructions":case"notices":case"tab":this._sy=this.newSy(),this._sy!==Qe.String&&this.error(i,Qe.String,!0);const a=this._syData;this._sy=this.newSy(),e=!0;let r=Je.ChordDiagramList;switch(i){case"title":this._score.title=a,r=Je.Title;break;case"subtitle":this._score.subTitle=a,r=Je.SubTitle;break;case"artist":this._score.artist=a,r=Je.Artist;break;case"album":this._score.album=a,r=Je.Album;break;case"words":this._score.words=a,r=Je.Words;break;case"music":this._score.music=a,r=Je.Music;break;case"copyright":this._score.copyright=a,r=Je.Copyright;break;case"instructions":this._score.instructions=a;break;case"notices":this._score.notices=a;break;case"tab":this._score.tab=a,r=Je.Transcriber}r!==Je.ChordDiagramList&&this.headerFooterStyle(r);break;case"copyright2":this._sy=this.newSy(),this._sy!==Qe.String&&this.error(i,Qe.String,!0),this.headerFooterStyle(Je.CopyrightSecondLine),e=!0;break;case"wordsandmusic":this._sy=this.newSy(),this._sy!==Qe.String&&this.error(i,Qe.String,!0),this.headerFooterStyle(Je.WordsAndMusic),e=!0;break;case"tempo":this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy===Qe.Number?this._score.tempo=this._syData:this.error("tempo",Qe.Number,!0),this._sy=this.newSy(),this._sy===Qe.String&&(this._score.tempoLabel=this._syData,this._sy=this.newSy()),e=!0;break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===Qe.Number?(this._score.defaultSystemsLayout=this._syData,this._sy=this.newSy(),e=!0):this.error("default-systems-layout",Qe.Number,!0);break;case"systemslayout":for(this._sy=this.newSy(),e=!0;this._sy===Qe.Number;)this._score.systemsLayout.push(this._syData),this._sy=this.newSy();break;case"hidedynamics":this._score.stylesheet.hideDynamics=!0,this._sy=this.newSy(),e=!0;break;case"showdynamics":this._score.stylesheet.hideDynamics=!1,this._sy=this.newSy(),e=!0;break;case"bracketextendmode":this._sy=this.newSy(),this._sy!==Qe.String&&this.error("bracketExtendMode",Qe.String,!0),this._score.stylesheet.bracketExtendMode=this.parseBracketExtendMode(this._syData),this._sy=this.newSy(),e=!0;break;case"usesystemsignseparator":this._score.stylesheet.useSystemSignSeparator=!0,this._sy=this.newSy(),e=!0;break;case"multibarrest":this._score.stylesheet.multiTrackMultiBarRest=!0,this._sy=this.newSy(),e=!0;break;case"singletracktracknamepolicy":this._sy=this.newSy(),this._sy!==Qe.String&&this.error("singleTrackTrackNamePolicy",Qe.String,!0),this._score.stylesheet.singleTrackTrackNamePolicy=this.parseTrackNamePolicy(this._syData),this._sy=this.newSy(),e=!0;break;case"multitracktracknamepolicy":this._sy=this.newSy(),this._sy!==Qe.String&&this.error("multiTrackTrackNamePolicy",Qe.String,!0),this._score.stylesheet.multiTrackTrackNamePolicy=this.parseTrackNamePolicy(this._syData),this._sy=this.newSy(),e=!0;break;case"firstsystemtracknamemode":this._sy=this.newSy(),this._sy!==Qe.String&&this.error("firstSystemTrackNameMode",Qe.String,!0),this._score.stylesheet.firstSystemTrackNameMode=this.parseTrackNameMode(this._syData),this._sy=this.newSy(),e=!0;break;case"othersystemstracknamemode":this._sy=this.newSy(),this._sy!==Qe.String&&this.error("otherSystemsTrackNameMode",Qe.String,!0),this._score.stylesheet.otherSystemsTrackNameMode=this.parseTrackNameMode(this._syData),this._sy=this.newSy(),e=!0;break;case"firstsystemtracknameorientation":this._sy=this.newSy(),this._sy!==Qe.String&&this.error("firstSystemTrackNameOrientation",Qe.String,!0),this._score.stylesheet.firstSystemTrackNameOrientation=this.parseTrackNameOrientation(this._syData),this._sy=this.newSy(),e=!0;break;case"othersystemstracknameorientation":this._sy=this.newSy(),this._sy!==Qe.String&&this.error("otherSystemsTrackNameOrientation",Qe.String,!0),this._score.stylesheet.otherSystemsTrackNameOrientation=this.parseTrackNameOrientation(this._syData),this._sy=this.newSy(),e=!0;break;default:switch(this.handleStaffMeta()){case Ze.KnownStaffMeta:t=!0;break;case Ze.UnknownStaffMeta:e||t?this.error("metaDataTags",Qe.String,!1):s=!1;break;case Ze.EndOfMetaDetected:s=!1}}}return e?(this._sy!==Qe.Dot&&this.error("song",Qe.Dot,!0),this._sy=this.newSy()):this._sy===Qe.Dot&&(this._sy=this.newSy(),e=!0),e||t}headerFooterStyle(e){const t=ue.getOrCreateHeaderFooterStyle(this._score,e);if(void 0===t.isVisible&&(t.isVisible=!0),this._sy===Qe.String){const e=this._syData;e?t.template=e:t.isVisible=!1,this._sy=this.newSy()}if(this._sy===Qe.String){switch(this._syData.toLowerCase()){case"left":t.textAlign=A.Left;break;case"center":t.textAlign=A.Center;break;case"right":t.textAlign=A.Right}this._sy=this.newSy()}}parseTrackNamePolicy(e){switch(e.toLowerCase()){case"hidden":return i.Hidden;case"allsystems":return i.AllSystems;default:return i.FirstSystem}}parseTrackNameMode(e){return"fullname"===e.toLowerCase()?a.FullName:a.ShortName}parseTrackNameOrientation(e){return"horizontal"===e.toLowerCase()?r.Horizontal:r.Vertical}handleStaffMeta(){switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===Qe.Number?this._currentStaff.capo=this._syData:this.error("capo",Qe.Number,!0),this._sy=this.newSy(),Ze.KnownStaffMeta;case"tuning":this._sy=this.newSy();const e=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case Qe.String:const e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?this.makeCurrentStaffPitched():this.error("tuning",Qe.Tuning,!0),this._sy=this.newSy();break;case Qe.Tuning:const t=[];do{const e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===Qe.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",Qe.Tuning,!0)}return this._sy===Qe.String&&"hide"===this._syData.toLowerCase()&&(this._score.stylesheet.perTrackDisplayTuning||(this._score.stylesheet.perTrackDisplayTuning=new Map),this._score.stylesheet.perTrackDisplayTuning.set(this._currentTrack.index,!1),this._sy=this.newSy()),e!==this._currentStaff.tuning.length&&(this._currentStaff.chords?.size??0)>0&&this.errorMessage("Tuning must be defined before any chord"),Ze.KnownStaffMeta;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===Qe.Number){const e=this._syData;e>=0&&e<=127?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",Qe.Number,!1)}else if(this._sy===Qe.String){const e=this._syData.toLowerCase();if("percussion"===e){for(const e of this._currentTrack.staves)this.applyPercussionStaff(e);this._currentTrack.playbackInfo.primaryChannel=kt.PercussionChannel,this._currentTrack.playbackInfo.secondaryChannel=kt.PercussionChannel}else this._currentTrack.playbackInfo.program=q.getValue(e)}else this.error("instrument",Qe.Number,!0);return this._sy=this.newSy(),Ze.KnownStaffMeta;case"lyrics":this._sy=this.newSy();const t=new pt;return t.startBar=0,t.text="",this._sy===Qe.Number&&(t.startBar=this._syData,this._sy=this.newSy()),this._sy===Qe.String?(t.text=this._syData,this._sy=this.newSy()):this.error("lyrics",Qe.String,!0),this._lyrics.get(this._currentTrack.index).push(t),Ze.KnownStaffMeta;case"chord":this._sy=this.newSy();const s=new ut;this.chordProperties(s),this._sy===Qe.String?(s.name=this._syData,this._sy=this.newSy()):this.error("chord-name",Qe.String,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===Qe.Number?s.strings.push(this._syData):this._sy===Qe.String&&"x"===this._syData.toLowerCase()&&s.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,s.name),s),Ze.KnownStaffMeta;case"articulation":this._sy=this.newSy();let i="";if(this._sy===Qe.String?(i=this._syData,this._sy=this.newSy()):this.error("articulation-name",Qe.String,!0),"defaults"===i){for(const[e,t]of me.instrumentArticulationNames)this._percussionArticulationNames.set(e.toLowerCase(),t),this._percussionArticulationNames.set(xt.toArticulationId(e),t);return Ze.KnownStaffMeta}let a=0;return this._sy===Qe.Number?(a=this._syData,this._sy=this.newSy()):this.error("articulation-number",Qe.Number,!0),me.instrumentArticulations.has(a)||this.errorMessage(`Unknown articulation ${a}. Refer to https://www.alphatab.net/docs/alphatex/percussion for available ids`),this._percussionArticulationNames.set(i.toLowerCase(),a),Ze.KnownStaffMeta;case"accidentals":return this.handleAccidentalMode(),Ze.KnownStaffMeta;case"displaytranspose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===Qe.Number?(this._currentStaff.displayTranspositionPitch=-1*this._syData,this._staffHasExplicitDisplayTransposition=!0):this.error("displaytranspose",Qe.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),Ze.KnownStaffMeta;case"transpose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===Qe.Number?this._currentStaff.transpositionPitch=-1*this._syData:this.error("transpose",Qe.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),Ze.KnownStaffMeta;case"track":case"staff":return Ze.EndOfMetaDetected;case"voice":return this._sy=this.newSy(),this.handleNewVoice()?Ze.EndOfMetaDetected:Ze.KnownStaffMeta;default:return Ze.UnknownStaffMeta}}handleAccidentalMode(){switch(this._sy=this.newSy(),this._sy!==Qe.String&&this.error("accidental-mode",Qe.String,!0),this._syData){case"auto":this._accidentalMode=et.Auto;break;case"explicit":this._accidentalMode=et.Explicit}this._sy=this.newSy()}makeCurrentStaffPitched(){this._currentStaff.stringTuning.tunings=[],this._staffHasExplicitDisplayTransposition||(this._currentStaff.displayTranspositionPitch=0)}static toArticulationId(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}applyPercussionStaff(e){e.isPercussion=!0,e.showTablature=!1}chordProperties(e){if(this._sy===Qe.LBrace){for(this._sy=this.newSy();this._sy===Qe.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===Qe.Number)e.firstFret=this._syData;else this.error("chord-firstfret",Qe.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case Qe.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case Qe.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",Qe.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case Qe.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case Qe.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",Qe.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case Qe.String:e.showName="false"!==this._syData.toLowerCase();break;case Qe.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",Qe.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===Qe.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",Qe.String,!1)}this._sy!==Qe.RBrace&&this.error("chord-properties",Qe.RBrace,!0),this._sy=this.newSy()}}bars(){const e=this.bar();for(;this._sy!==Qe.Eof;)if(this._sy===Qe.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==Qe.MetaCommand)break;this.bar()}return e}trackStaffMeta(){if(this._sy!==Qe.MetaCommand)return!1;if("track"===this._syData.toLowerCase()&&(this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===Qe.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===Qe.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy()),this.trackProperties()),this._sy===Qe.MetaCommand&&"staff"===this._syData.toLowerCase()){if(this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0){const e=this._currentStaff.isPercussion;this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this.beginStaff(this._currentTrack.staves[this._currentTrack.staves.length-1]),e&&this.applyPercussionStaff(this._currentStaff),this._currentDynamics=y.F}this.staffProperties()}return this._sy===Qe.MetaCommand&&"voice"===this._syData.toLowerCase()&&(this._sy=this.newSy(),this.handleNewVoice()),!0}handleNewVoice(){if(0===this._voiceIndex&&(0===this._currentStaff.bars.length||1===this._currentStaff.bars.length&&this._currentStaff.bars[0].isEmpty))return!1;for(const e of this._currentStaff.bars){const t=new Pe;e.addVoice(t)}return this._voiceIndex++,this._barIndex=0,!0}beginStaff(e){this._currentStaff=e,this._slurs.clear(),this._barIndex=0,this._voiceIndex=0}trackProperties(){if(this._sy===Qe.LBrace){for(this._sy=this.newSy();this._sy===Qe.String;)switch(this._syData.toLowerCase()){case"color":this._sy=this.newSy(),this._sy!==Qe.String&&this.error("track-color",Qe.String,!0),this._currentTrack.color=Ae.fromJson(this._syData),this._sy=this.newSy();break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===Qe.Number?(this._currentTrack.defaultSystemsLayout=this._syData,this._sy=this.newSy()):this.error("default-systems-layout",Qe.Number,!0);break;case"systemslayout":for(this._sy=this.newSy();this._sy===Qe.Number;)this._currentTrack.systemsLayout.push(this._syData),this._sy=this.newSy();break;case"volume":this._sy=this.newSy(),this._sy!==Qe.Number&&this.error("track-volume",Qe.Number,!0),this._currentTrack.playbackInfo.volume=ue.clamp(this._syData,0,16),this._sy=this.newSy();break;case"balance":this._sy=this.newSy(),this._sy!==Qe.Number&&this.error("track-balance",Qe.Number,!0),this._currentTrack.playbackInfo.balance=ue.clamp(this._syData,0,16),this._sy=this.newSy();break;case"mute":this._sy=this.newSy(),this._currentTrack.playbackInfo.isMute=!0;break;case"solo":this._sy=this.newSy(),this._currentTrack.playbackInfo.isSolo=!0;break;case"multibarrest":this._sy=this.newSy(),this._score.stylesheet.perTrackMultiBarRest||(this._score.stylesheet.perTrackMultiBarRest=new Set),this._score.stylesheet.perTrackMultiBarRest.add(this._currentTrack.index);break;default:this.error("track-properties",Qe.String,!1)}this._sy!==Qe.RBrace&&this.error("track-properties",Qe.RBrace,!0),this._sy=this.newSy()}}staffProperties(){if(this._sy!==Qe.LBrace)return;this._sy=this.newSy();let e=!1,t=!1,s=!1,i=!1;for(;this._sy===Qe.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy(),this._sy===Qe.Number&&(this._currentStaff.standardNotationLineCount=this._syData,this._sy=this.newSy());break;case"tabs":t=!0,this._sy=this.newSy();break;case"slash":s=!0,this._sy=this.newSy();break;case"numbered":i=!0,this._sy=this.newSy();break;default:this.error("staff-properties",Qe.String,!1)}(e||t||s||i)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t,this._currentStaff.showSlash=s,this._currentStaff.showNumbered=i),this._sy!==Qe.RBrace&&this.error("staff-properties",Qe.RBrace,!0),this._sy=this.newSy()}bar(){const e=this.trackStaffMeta(),t=this.newBar(this._currentStaff);if(this._currentStaff.bars.length>this._score.masterBars.length){const e=new le;this._score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.timeSignatureDenominator=e.previousMasterBar.timeSignatureDenominator,e.timeSignatureNumerator=e.previousMasterBar.timeSignatureNumerator,e.tripletFeel=e.previousMasterBar.tripletFeel)}const s=this.barMeta(t),i=this._currentTrack.playbackInfo.program;this._staffTuningApplied||this._staffHasExplicitTuning||(this._currentStaff.stringTuning.tunings=[],15===i||i>=24&&i<=31?this._currentStaff.stringTuning.tunings=ft.getDefaultTuningFor(6).tunings:i>=32&&i<=39?this._currentStaff.stringTuning.tunings=[43,38,33,28]:40===i||44===i||45===i||48===i||49===i||50===i||51===i?this._currentStaff.stringTuning.tunings=[52,57,50,43]:41===i?this._currentStaff.stringTuning.tunings=[57,50,43,36]:42===i?this._currentStaff.stringTuning.tunings=[45,38,31,24]:43===i?this._currentStaff.stringTuning.tunings=[43,38,33,28]:105===i?this._currentStaff.stringTuning.tunings=[50,47,43,38,55]:106===i?this._currentStaff.stringTuning.tunings=[57,52,45]:107===i?this._currentStaff.stringTuning.tunings=[52,45,38,31]:110===i&&(this._currentStaff.stringTuning.tunings=[64,57,50,43]),this._staffTuningApplied=!0),this._staffHasExplicitDisplayTransposition||(this._currentStaff.displayTranspositionPitch=i>=24&&i<=31||i>=32&&i<=39||43===i?-12:0);let a=!1;const r=t.voices[this._voiceIndex];if(!(this._sy===Qe.MetaCommand&&("track"===this._syData.toLowerCase()||"staff"===this._syData.toLowerCase())))for(;this._sy!==Qe.Pipe&&this._sy!==Qe.Eof&&this.beat(r);)a=!0;if(0===r.beats.length){const e=new xe;e.isEmpty=!0,r.addBeat(e)}return e||s||a}newBar(e){if(this._barIndex<e.bars.length){const t=e.bars[this._barIndex];return this._barIndex++,t}const t=0===e.bars.length?1:e.bars[0].voices.length,s=new te;e.addBar(s),s.previousBar&&(s.clef=s.previousBar.clef,s.clefOttava=s.previousBar.clefOttava),this._barIndex++;for(let e=0;e<t;e++){const e=new Pe;s.addVoice(e)}return s}beat(e){this.beatDuration();const t=new xe;if(e.addBeat(t),this._allowTuning=!this._currentStaff.isPercussion,this._sy===Qe.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==Qe.RParensis&&this._sy!==Qe.Eof&&(this._allowTuning=!this._currentStaff.isPercussion,this.note(t)););this._sy!==Qe.RParensis&&this.error("note-list",Qe.RParensis,!0),this._sy=this.newSy()}else if(this._sy===Qe.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===Qe.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==Qe.Number&&this.error("duration",Qe.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||xt.applyTuplet(t,this._currentTuplet);let s=1;this._sy===Qe.Multiply&&(this._sy=this.newSy(),this._sy!==Qe.Number?this.error("multiplier",Qe.Number,!0):s=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let i=0;i<s-1;i++)e.addBeat(ke.clone(t));return!0}beatDuration(){if(this._sy===Qe.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==Qe.Number&&this.error("duration",Qe.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===Qe.LBrace)){for(this._sy=this.newSy();this._sy===Qe.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==Qe.Number&&this.error("duration-tuplet",Qe.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",Qe.String,!1)}this._sy!==Qe.RBrace&&this.error("beat-duration",Qe.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===Qe.LBrace){for(this._sy=this.newSy();this._sy===Qe.String;)this.applyBeatEffect(e)||this.error("beat-effects",Qe.String,!1);this._sy!==Qe.RBrace&&this.error("beat-effects",Qe.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){const t=this._syData.toLowerCase();if("f"===t)e.fade=G.FadeIn;else if("fo"===t)e.fade=G.FadeOut;else if("vs"===t)e.fade=G.VolumeSwell;else if("v"===t)e.vibrato=N.Slight;else if("vw"===t)e.vibrato=N.Wide;else if("s"===t)e.slap=!0;else if("p"===t)e.pop=!0;else if("tt"===t)e.tap=!0;else if("txt"===t){if(this._sy=this.newSy(),this._sy!==Qe.String)return this.error("beat-text",Qe.String,!0),!1;e.text=this._syData}else if("dd"===t)e.dots=2;else if("d"===t)e.dots=1;else if("su"===t)e.pickStroke=L.Up;else if("sd"===t)e.pickStroke=L.Down;else{if("tu"===t){if(this._sy=this.newSy(),this._sy!==Qe.Number)return this.error("tuplet",Qe.Number,!0),!1;const t=this._syData;if(this._sy=this.newSy(),this._sy===Qe.Number){const s=this._syData;this._sy=this.newSy(),e.tupletNumerator=t,e.tupletDenominator=s}else xt.applyTuplet(e,t);return!0}if("tb"===t||"tbe"===t){this._sy=this.newSy();const s="tbe"===t;for(this._sy===Qe.String&&(e.whammyBarType=this.parseWhammyType(this._syData),this._sy=this.newSy()),this._sy===Qe.String&&(e.whammyStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==Qe.LParensis&&this.error("tremolobar-effect",Qe.LParensis,!0),this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy();this._sy!==Qe.RParensis&&this._sy!==Qe.Eof;){let t=0,i=0;s?(this._sy!==Qe.Number&&this.error("tremolobar-effect",Qe.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==Qe.Number&&this.error("tremolobar-effect",Qe.Number,!0),i=this._syData):(this._sy!==Qe.Number&&this.error("tremolobar-effect",Qe.Number,!0),t=0,i=this._syData),e.addWhammyBarPoint(new ae(t,i)),this._sy=this.newSy()}if(null!=e.whammyBarPoints){for(;e.whammyBarPoints.length>60;)e.removeWhammyBarPoint(e.whammyBarPoints.length-1);if(s)e.whammyBarPoints.sort(((e,t)=>e.offset-t.offset));else{const t=e.whammyBarPoints.length,s=60/t|0;let i=0;for(;i<t;)e.whammyBarPoints[i].offset=Math.min(60,i*s),i++}}this._allowNegatives=!1,this._allowFloat=!1,this._sy!==Qe.RParensis&&this.error("tremolobar-effect",Qe.RParensis,!0)}else{if("bu"===t||"bd"===t||"au"===t||"ad"===t){switch(t){case"bu":e.brushType=g.BrushUp;break;case"bd":e.brushType=g.BrushDown;break;case"au":e.brushType=g.ArpeggioUp;break;case"ad":e.brushType=g.ArpeggioDown}return this._sy=this.newSy(),this._sy===Qe.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();const t=this._syData,s=this.getChordId(this._currentStaff,t);if(!this._currentStaff.hasChord(s)){const e=new ut;e.showDiagram=!1,e.name=t,this._currentStaff.addChord(s,e)}e.chordId=s}else{if("gr"===t)return this._sy=this.newSy(),"ob"===this._syData.toLowerCase()?(e.graceType=b.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=b.BendGrace,this._sy=this.newSy()):e.graceType=b.BeforeBeat,!0;if("dy"===t){switch(this._sy=this.newSy(),this._syData.toLowerCase()){case"ppp":e.dynamics=y.PPP;break;case"pp":e.dynamics=y.PP;break;case"p":e.dynamics=y.P;break;case"mp":e.dynamics=y.MP;break;case"mf":e.dynamics=y.MF;break;case"f":e.dynamics=y.F;break;case"ff":e.dynamics=y.FF;break;case"fff":e.dynamics=y.FFF}this._currentDynamics=e.dynamics}else if("cre"===t)e.crescendo=m.Crescendo;else if("dec"===t)e.crescendo=m.Decrescendo;else{if("tempo"===t){const t=this.readTempoAutomation();return e.automations.push(t),e.voice.bar.masterBar.tempoAutomations.push(t),!0}if("tp"===t){if(this._sy=this.newSy(),e.tremoloSpeed=f.Eighth,this._sy===Qe.Number){switch(this._syData){case 8:default:e.tremoloSpeed=f.Eighth;break;case 16:e.tremoloSpeed=f.Sixteenth;break;case 32:e.tremoloSpeed=f.ThirtySecond}this._sy=this.newSy()}return!0}if("spd"===t){const t=new Z;return t.pedalType=l.Down,t.ratioPosition=e.voice.bar.sustainPedals.length,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spu"===t){const t=new Z;return t.pedalType=l.Up,t.ratioPosition=e.voice.bar.sustainPedals.length,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spe"===t){const t=new Z;return t.pedalType=l.Up,t.ratioPosition=1,e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("slashed"===t)return e.slashed=!0,this._sy=this.newSy(),!0;if("ds"===t)return e.deadSlapped=!0,this._sy=this.newSy(),!0;if("glpf"===t)return this._sy=this.newSy(),e.golpe=V.Finger,!0;if("glpt"===t)return this._sy=this.newSy(),e.golpe=V.Thumb,!0;if("waho"===t)return this._sy=this.newSy(),e.wahPedal=U.Open,!0;if("wahc"===t)return this._sy=this.newSy(),e.wahPedal=U.Closed,!0;if("barre"===t){if(this._sy=this.newSy(),this._sy!==Qe.Number&&this.error("beat-barre",Qe.Number,!0),e.barreFret=this._syData,e.barreShape=z.Full,this._sy=this.newSy(),this._sy===Qe.String)switch(this._syData.toLowerCase()){case"full":e.barreShape=z.Full,this._sy=this.newSy();break;case"half":e.barreShape=z.Half,this._sy=this.newSy()}return!0}if("rasg"===t){switch(this._sy=this.newSy(),this._sy!==Qe.String&&this.error("rasgueado",Qe.String,!0),this._syData.toLowerCase()){case"ii":e.rasgueado=X.Ii;break;case"mi":e.rasgueado=X.Mi;break;case"miitriplet":e.rasgueado=X.MiiTriplet;break;case"miianapaest":e.rasgueado=X.MiiAnapaest;break;case"pmptriplet":e.rasgueado=X.PmpTriplet;break;case"pmpanapaest":e.rasgueado=X.PmpAnapaest;break;case"peitriplet":e.rasgueado=X.PeiTriplet;break;case"peianapaest":e.rasgueado=X.PeiAnapaest;break;case"paitriplet":e.rasgueado=X.PaiTriplet;break;case"paianapaest":e.rasgueado=X.PaiAnapaest;break;case"amitriplet":e.rasgueado=X.AmiTriplet;break;case"amianapaest":e.rasgueado=X.AmiAnapaest;break;case"ppp":e.rasgueado=X.Ppp;break;case"amii":e.rasgueado=X.Amii;break;case"amip":e.rasgueado=X.Amip;break;case"eami":e.rasgueado=X.Eami;break;case"eamii":e.rasgueado=X.Eamii;break;case"peami":e.rasgueado=X.Peami}return this._sy=this.newSy(),!0}if("ot"===t)this._sy=this.newSy(),this._sy!==Qe.String&&this.error("beat-ottava",Qe.String,!0),e.ottava=this.parseClefOttavaFromString(this._syData);else if("legatoorigin"===t)e.isLegatoOrigin=!0;else{if("instrument"!==t){if("fermata"===t){this._sy=this.newSy(),this._sy!==Qe.String&&this.error("fermata",Qe.Number,!0);const t=new Tt;return t.type=this.parseFermataFromString(this._syData),this._allowFloat=!0,this._sy=this.newSy(),this._sy===Qe.Number&&(t.length=this._syData,this._sy=this.newSy()),this._allowFloat=!1,e.fermata=t,!0}if("beam"===t){switch(this._sy=this.newSy(),this._sy!==Qe.String&&this.error("beam",Qe.Number,!0),this._syData.toLowerCase()){case"invert":e.invertBeamDirection=!0;break;case"up":e.preferredBeamDirection=je.Up;break;case"down":e.preferredBeamDirection=je.Down;break;case"auto":e.beamingMode=J.Auto;break;case"split":e.beamingMode=J.ForceSplitToNext;break;case"merge":e.beamingMode=J.ForceMergeWithNext;break;case"splitsecondary":e.beamingMode=J.ForceSplitOnSecondaryToNext}return this._sy=this.newSy(),!0}return"timer"===t&&(e.showTimer=!0,this._sy=this.newSy(),!0)}{this._sy=this.newSy();let t=0;this._sy===Qe.Number?t=this._syData:this._sy===Qe.String?t=q.getValue(this._syData):this.error("instrument-change",Qe.Number,!0);const s=new ie;s.isLinear=!1,s.type=d.Instrument,s.value=t,e.automations.push(s)}}}}}}return this._sy=this.newSy(),!0}parseBracketExtendMode(e){switch(e.toLowerCase()){case"nobrackets":return s.NoBrackets;case"groupstaves":default:return s.GroupStaves;case"groupsimilarinstruments":return s.GroupSimilarInstruments}}parseFermataFromString(e){switch(e.toLowerCase()){case"short":return Ke.Short;case"medium":default:return Ke.Medium;case"long":return Ke.Long}}parseClefOttavaFromString(e){switch(e.toLowerCase()){case"15ma":return o._15ma;case"8va":return o._8va;case"regular":default:return o.Regular;case"8vb":return o._8vb;case"15mb":return o._15mb}}getChordId(e,t){return t.toLowerCase()+e.index+e.track.index}static applyTuplet(e,t){switch(t){case 3:e.tupletNumerator=3,e.tupletDenominator=2;break;case 5:e.tupletNumerator=5,e.tupletDenominator=4;break;case 6:e.tupletNumerator=6,e.tupletDenominator=4;break;case 7:e.tupletNumerator=7,e.tupletDenominator=4;break;case 9:e.tupletNumerator=9,e.tupletDenominator=8;break;case 10:e.tupletNumerator=10,e.tupletDenominator=8;break;case 11:e.tupletNumerator=11,e.tupletDenominator=8;break;case 12:e.tupletNumerator=12,e.tupletDenominator=8;break;default:e.tupletNumerator=1,e.tupletDenominator=1}}isNoteText(e){return"x"===e||"-"===e||"r"===e}note(e){let t=!1,s=!1,i=-1,a=-1,r=-1,n=B.Default;switch(this._sy){case Qe.Number:i=this._syData,this._currentStaff.isPercussion&&!me.instrumentArticulations.has(i)&&this.errorMessage(`Unknown percussion articulation ${i}`);break;case Qe.String:if(this._currentStaff.isPercussion){const e=this._syData.toLowerCase();this._percussionArticulationNames.has(e)?i=this._percussionArticulationNames.get(e):this.errorMessage(`Unknown percussion articulation '${this._syData}'`)}else t="x"===this._syData,s="-"===this._syData,s||t?i=0:this.error("note-fret",Qe.Number,!0);break;case Qe.Tuning:0===e.index&&0===e.voice.index&&0===e.voice.bar.index&&this.makeCurrentStaffPitched();const o=this._syData;a=o.octave,r=o.tone.noteValue,this._accidentalMode===et.Explicit&&(n=o.tone.accidentalMode);break;default:return!1}this._sy=this.newSy();const o=-1===a&&this._currentStaff.tuning.length>0&&!this._currentStaff.isPercussion;let h=-1;o&&(this._sy!==Qe.Dot&&this.error("note",Qe.Dot,!0),this._sy=this.newSy(),this._sy!==Qe.Number&&this.error("note-string",Qe.Number,!0),h=this._syData,(h<1||h>this._currentStaff.tuning.length)&&this.error("note-string",Qe.Number,!1),this._sy=this.newSy());const l=new be;return o?(l.string=this._currentStaff.tuning.length-(h-1),l.isDead=t,l.isTieDestination=s,s||(l.fret=i)):this._currentStaff.isPercussion?l.percussionArticulation=i:(l.octave=a,l.tone=r,l.accidentalMode=n,l.isTieDestination=s),e.addNote(l),this.noteEffects(l),!0}noteEffects(e){if(this._sy===Qe.LBrace){for(this._sy=this.newSy();this._sy===Qe.String;){const t=this._syData.toLowerCase();if("b"===t||"be"===t){this._sy=this.newSy();const s="be"===t;for(this._sy===Qe.String&&(e.bendType=this.parseBendType(this._syData),this._sy=this.newSy()),this._sy===Qe.String&&(e.bendStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==Qe.LParensis&&this.error("bend-effect",Qe.LParensis,!0),this._sy=this.newSy();this._sy!==Qe.RParensis&&this._sy!==Qe.Eof;){let t=0,i=0;s?(this._sy!==Qe.Number&&this.error("bend-effect-value",Qe.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==Qe.Number&&this.error("bend-effect-value",Qe.Number,!0),i=this._syData):(this._sy!==Qe.Number&&this.error("bend-effect-value",Qe.Number,!0),i=this._syData),e.addBendPoint(new ae(t,i)),this._sy=this.newSy()}const i=e.bendPoints;if(null!=i){for(;i.length>60;)i.splice(i.length-1,1);if(s)i.sort(((e,t)=>e.offset-t.offset));else{const e=i.length,t=60/(e-1)|0;let s=0;for(;s<e;)i[s].offset=Math.min(60,s*t),s++}}this._sy!==Qe.RParensis&&this.error("bend-effect",Qe.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=w.Natural,e.harmonicValue=ue.deltaFretToHarmonicValue(e.fret),this._sy=this.newSy();else if("ah"===t)e.harmonicType=w.Artificial,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("th"===t)e.harmonicType=w.Tap,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("ph"===t)e.harmonicType=w.Pinch,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("sh"===t)e.harmonicType=w.Semi,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("fh"===t)e.harmonicType=w.Feedback,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("tr"===t){this._sy=this.newSy(),this._sy!==Qe.Number&&this.error("trill-effect",Qe.Number,!0);const t=this._syData;this._sy=this.newSy();let s=f.Sixteenth;if(this._sy===Qe.Number){switch(this._syData){case 16:default:s=f.Sixteenth;break;case 32:s=f.ThirtySecond;break;case 64:s=f.SixtyFourth}this._sy=this.newSy()}e.trillValue=t+e.stringTuning,e.trillSpeed=s}else if("v"===t)this._sy=this.newSy(),e.vibrato=N.Slight;else if("sl"===t)this._sy=this.newSy(),e.slideOutType=T.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=T.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=k.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=k.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=T.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=T.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=T.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=T.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("ten"===t)this._sy=this.newSy(),e.accentuated=S.Tenuto;else if("pm"===t)this._sy=this.newSy(),e.isPalmMute=!0;else if("st"===t)this._sy=this.newSy(),e.isStaccato=!0;else if("lr"===t)this._sy=this.newSy(),e.isLetRing=!0;else if("x"===t)this._sy=this.newSy(),e.fret=0,e.isDead=!0;else if("-"===t||"t"===t)this._sy=this.newSy(),e.isTieDestination=!0;else if("lf"===t){this._sy=this.newSy();let t=_.Thumb;this._sy===Qe.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.leftHandFinger=t}else if("rf"===t){this._sy=this.newSy();let t=_.Thumb;this._sy===Qe.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else if("acc"===t)this._sy=this.newSy(),this._sy!==Qe.String&&this.error("note-accidental",Qe.String,!0),e.accidentalMode=ue.parseAccidentalMode(this._syData),this._sy=this.newSy();else if("turn"===t)this._sy=this.newSy(),e.ornament=O.Turn;else if("iturn"===t)this._sy=this.newSy(),e.ornament=O.InvertedTurn;else if("umordent"===t)this._sy=this.newSy(),e.ornament=O.UpperMordent;else if("lmordent"===t)this._sy=this.newSy(),e.ornament=O.LowerMordent;else if("string"===t)this._sy=this.newSy(),e.showStringNumber=!0;else if("hide"===t)this._sy=this.newSy(),e.isVisible=!1;else if("slur"===t){this._sy=this.newSy(),this._sy!==Qe.String&&this.error("slur",Qe.String,!0);const t=this._syData;if(this._slurs.has(t)){const s=this._slurs.get(t);s.slurDestination=e,e.slurOrigin=s,e.isSlurDestination=!0}else this._slurs.set(t,e);this._sy=this.newSy()}else this.applyBeatEffect(e.beat)||this.error(t,Qe.String,!1)}this._sy!==Qe.RBrace&&this.error("note-effect",Qe.RBrace,!1),this._sy=this.newSy()}}harmonicValue(e){return this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy(),this._sy===Qe.Number&&(e=this._syData,this._sy=this.newSy()),this._allowNegatives=!1,this._allowFloat=!1,e}toFinger(e){switch(e){case 1:return _.Thumb;case 2:return _.IndexFinger;case 3:return _.MiddleFinger;case 4:return _.AnnularFinger;case 5:return _.LittleFinger}return _.Thumb}parseDuration(e){switch(e){case-4:return f.QuadrupleWhole;case-2:return f.DoubleWhole;case 1:return f.Whole;case 2:return f.Half;case 4:return f.Quarter;case 8:return f.Eighth;case 16:return f.Sixteenth;case 32:return f.ThirtySecond;case 64:return f.SixtyFourth;case 128:return f.OneHundredTwentyEighth;case 256:return f.TwoHundredFiftySixth;default:return f.Quarter}}parseBendStyle(e){switch(e.toLowerCase()){case"gradual":return u.Gradual;case"fast":return u.Fast;default:return u.Default}}parseBendType(e){switch(e.toLowerCase()){case"none":return p.None;case"custom":default:return p.Custom;case"bend":return p.Bend;case"release":return p.Release;case"bendrelease":return p.BendRelease;case"hold":return p.Hold;case"prebend":return p.Prebend;case"prebendbend":return p.PrebendBend;case"prebendrelease":return p.PrebendRelease}}barMeta(e){let t=!1;const s=e.masterBar;let i=!1;for(;!i&&this._sy===Qe.MetaCommand;){t=!0;const a=this._syData.toLowerCase();if("ts"===a)this._sy=this.newSy(),this._sy===Qe.String?"common"===this._syData.toLowerCase()?(s.timeSignatureCommon=!0,s.timeSignatureNumerator=4,s.timeSignatureDenominator=4,this._sy=this.newSy()):this.error("timesignature-numerator",Qe.String,!0):(this._sy!==Qe.Number&&this.error("timesignature-numerator",Qe.Number,!0),s.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==Qe.Number&&this.error("timesignature-denominator",Qe.Number,!0),s.timeSignatureDenominator=this._syData,this._sy=this.newSy());else if("ft"===a)s.isFreeTime=!0,this._sy=this.newSy();else if("ro"===a)s.isRepeatStart=!0,this._sy=this.newSy();else if("rc"===a)this._sy=this.newSy(),this._sy!==Qe.Number&&this.error("repeatclose",Qe.Number,!0),this._syData>2048&&this.error("repeatclose",Qe.Number,!1),s.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===a)if(this._sy=this.newSy(),this._sy===Qe.LParensis){for(this._sy=this.newSy(),this._sy!==Qe.Number&&this.error("alternateending",Qe.Number,!0),this.applyAlternateEnding(s);this._sy===Qe.Number;)this.applyAlternateEnding(s);this._sy!==Qe.RParensis&&this.error("alternateending-list",Qe.RParensis,!0),this._sy=this.newSy()}else this._sy!==Qe.Number&&this.error("alternateending",Qe.Number,!0),this.applyAlternateEnding(s);else if("ks"===a)this._sy=this.newSy(),this._sy!==Qe.String&&this.error("keysignature",Qe.String,!0),s.keySignature=this.parseKeySignature(this._syData),s.keySignatureType=this.parseKeySignatureType(this._syData),this._sy=this.newSy();else if("clef"===a){switch(this._sy=this.newSy(),this._sy){case Qe.String:e.clef=this.parseClefFromString(this._syData);break;case Qe.Number:e.clef=this.parseClefFromInt(this._syData);break;case Qe.Tuning:const t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",Qe.String,!0)}this._sy=this.newSy()}else if("tempo"===a){const e=this.readTempoAutomation();s.tempoAutomations.push(e)}else if("section"===a){this._sy=this.newSy(),this._sy!==Qe.String&&this.error("section",Qe.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==Qe.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());const i=new gt;i.marker=t,i.text=e,s.section=i}else if("tf"===a){switch(this._allowTuning=!1,this._sy=this.newSy(),this._allowTuning=!0,this._sy){case Qe.String:s.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case Qe.Number:s.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",Qe.String,!0)}this._sy=this.newSy()}else if("ac"===a)s.isAnacrusis=!0,this._sy=this.newSy();else if("db"===a)s.isDoubleBar=!0,this._sy=this.newSy();else if("accidentals"===a)this.handleAccidentalMode();else if("jump"===a)this.handleDirections(s);else if("ottava"===a)this._sy=this.newSy(),this._sy!==Qe.String&&this.error("ottava",Qe.String,!0),e.clefOttava=this.parseClefOttavaFromString(this._syData),this._sy=this.newSy();else if("simile"===a)this._sy=this.newSy(),this._sy!==Qe.String&&this.error("simile",Qe.String,!0),e.simileMark=this.parseSimileMarkFromString(this._syData),this._sy=this.newSy();else if("scale"===a)this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==Qe.Number&&this.error("scale",Qe.Number,!0),s.displayScale=this._syData,e.displayScale=this._syData,this._sy=this.newSy();else if("width"===a)this._sy=this.newSy(),this._sy!==Qe.Number&&this.error("width",Qe.Number,!0),s.displayWidth=this._syData,e.displayWidth=this._syData,this._sy=this.newSy();else if(0===e.index)switch(this.handleStaffMeta()){case Ze.KnownStaffMeta:break;case Ze.UnknownStaffMeta:this.error("measure-effects",Qe.String,!1);break;case Ze.EndOfMetaDetected:i=!0}else this.error("measure-effects",Qe.String,!1)}if(0===s.index&&0===s.tempoAutomations.length){const e=new ie;e.isLinear=!1,e.type=d.Tempo,e.value=this._score.tempo,e.text=this._score.tempoLabel,s.tempoAutomations.push(e)}return t}parseSimileMarkFromString(e){switch(e.toLowerCase()){case"none":default:return h.None;case"simple":return h.Simple;case"firstofdouble":return h.FirstOfDouble;case"secondofdouble":return h.SecondOfDouble}}handleDirections(e){switch(this._sy=this.newSy(),this._sy!==Qe.String&&this.error("direction",Qe.String,!0),this._syData.toLowerCase()){case"fine":e.addDirection(qe.TargetFine);break;case"segno":e.addDirection(qe.TargetSegno);break;case"segnosegno":e.addDirection(qe.TargetSegnoSegno);break;case"coda":e.addDirection(qe.TargetCoda);break;case"doublecoda":e.addDirection(qe.TargetDoubleCoda);break;case"dacapo":e.addDirection(qe.JumpDaCapo);break;case"dacapoalcoda":e.addDirection(qe.JumpDaCapoAlCoda);break;case"dacapoaldoublecoda":e.addDirection(qe.JumpDaCapoAlDoubleCoda);break;case"dacapoalfine":e.addDirection(qe.JumpDaCapoAlFine);break;case"dalsegno":e.addDirection(qe.JumpDalSegno);break;case"dalsegnoalcoda":e.addDirection(qe.JumpDalSegnoAlCoda);break;case"dalsegnoaldoublecoda":e.addDirection(qe.JumpDalSegnoAlDoubleCoda);break;case"dalsegnoalfine":e.addDirection(qe.JumpDalSegnoAlFine);break;case"dalsegnosegno":e.addDirection(qe.JumpDalSegnoSegno);break;case"dalsegnosegnoalcoda":e.addDirection(qe.JumpDalSegnoSegnoAlCoda);break;case"dalsegnosegnoaldoublecoda":e.addDirection(qe.JumpDalSegnoSegnoAlDoubleCoda);break;case"dalsegnosegnoalfine":e.addDirection(qe.JumpDalSegnoSegnoAlFine);break;case"dacoda":e.addDirection(qe.JumpDaCoda);break;case"dadoublecoda":e.addDirection(qe.JumpDaDoubleCoda);break;default:return void this.errorMessage(`Unexpected direction value: '${this._syData}'`)}this._sy=this.newSy()}readTempoAutomation(){this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==Qe.Number&&this.error("tempo",Qe.Number,!0);const e=new ie;return e.isLinear=!1,e.type=d.Tempo,e.value=this._syData,this._sy=this.newSy(),this._sy===Qe.String&&(e.text=this._syData,this._sy=this.newSy()),e}applyAlternateEnding(e){const t=this._syData;t<1&&this.error("alternateending",Qe.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}parseWhammyType(e){switch(e.toLowerCase()){case"none":return W.None;case"custom":default:return W.Custom;case"dive":return W.Dive;case"dip":return W.Dip;case"hold":return W.Hold;case"predive":return W.Predive;case"predivedive":return W.PrediveDive}}}xt.Eof=0,function(e){e[e.None=0]="None",e[e.Natural=1]="Natural",e[e.Sharp=2]="Sharp",e[e.Flat=3]="Flat",e[e.NaturalQuarterNoteUp=4]="NaturalQuarterNoteUp",e[e.SharpQuarterNoteUp=5]="SharpQuarterNoteUp",e[e.FlatQuarterNoteUp=6]="FlatQuarterNoteUp",e[e.DoubleSharp=7]="DoubleSharp",e[e.DoubleFlat=8]="DoubleFlat"}(tt||(tt={})),function(e){e[e.SingleTrackMultiChannel=0]="SingleTrackMultiChannel",e[e.MultiTrack=1]="MultiTrack"}(st||(st={}));class vt{constructor(){this.events=[]}addEvent(e){if(0===this.events.length||e.tick>=this.events[this.events.length-1].tick)this.events.push(e);else{let t=this.events.length;for(;t>0;){if(!(this.events[t-1].tick>e.tick))break;t--}this.events.splice(t,0,e)}}writeTo(e){const t=Bt.empty();let s=0;for(const e of this.events){const i=e.tick-s;Pt.writeVariableInt(t,i),e.writeTo(t),s=e.tick}const i=new Uint8Array([77,84,114,107]);e.write(i,0,i.length);const a=t.toArray();wt.writeInt32BE(e,a.length),e.write(a,0,a.length)}}class Pt{constructor(){this.format=st.SingleTrackMultiChannel,this.division=se.QuarterTime,this.tracks=[]}get events(){if(1===this.tracks.length)return this.tracks[0].events;const e=[];for(const e of this.tracks)this.events.push(...e.events);return e.sort(((e,t)=>e.tick-t.tick)),e}ensureTracks(e){for(;this.tracks.length<e;)this.tracks.push(new vt)}addEvent(e){this.format===st.SingleTrackMultiChannel?(this.ensureTracks(1),this.tracks[0].addEvent(e)):(this.ensureTracks(e.track+1),this.tracks[e.track].addEvent(e))}toBinary(){const e=Bt.empty();return this.writeTo(e),e.toArray()}writeTo(e){const t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),wt.writeInt32BE(e,6),wt.writeInt16BE(e,this.format),wt.writeInt16BE(e,this.tracks.length),wt.writeInt16BE(e,this.division);for(const t of this.tracks)t.writeTo(e)}static writeVariableInt(e,t){const s=new Uint8Array(4);let i=0;do{s[i++]=127&t,t>>=7}while(t>0);for(;i>0;)i--,i>0?e.writeByte(128|s[i]):e.writeByte(s[i])}}!function(e){e[e.TimeSignature=88]="TimeSignature",e[e.NoteOn=128]="NoteOn",e[e.NoteOff=144]="NoteOff",e[e.ControlChange=176]="ControlChange",e[e.ProgramChange=192]="ProgramChange",e[e.TempoChange=81]="TempoChange",e[e.PitchBend=224]="PitchBend",e[e.PerNotePitchBend=96]="PerNotePitchBend",e[e.EndOfTrack=47]="EndOfTrack",e[e.AlphaTabRest=241]="AlphaTabRest",e[e.AlphaTabMetronome=242]="AlphaTabMetronome",e[e.SystemExclusive=240]="SystemExclusive",e[e.SystemExclusive2=247]="SystemExclusive2",e[e.Meta=255]="Meta"}(it||(it={}));class Ct{constructor(e,t,s){this.track=e,this.tick=t,this.type=s}get command(){return this.type}get message(){return 0}get data1(){return 0}get data2(){return 0}}class Et extends Ct{constructor(e,t,s,i,a,r){super(e,t,it.TimeSignature),this.track=e,this.tick=t,this.numerator=s,this.denominatorIndex=i,this.midiClocksPerMetronomeClick=a,this.thirtySecondNodesInQuarter=r}writeTo(e){e.writeByte(255),e.writeByte(88),Pt.writeVariableInt(e,4),e.writeByte(255&this.numerator),e.writeByte(255&this.denominatorIndex),e.writeByte(255&this.midiClocksPerMetronomeClick),e.writeByte(255&this.thirtySecondNodesInQuarter)}}class Ft extends Ct{writeTo(e){e.writeByte(240);const t=Bt.withCapacity(16);t.writeByte(Ft.AlphaTabManufacturerId),this.writeEventData(t),t.writeByte(247),Pt.writeVariableInt(e,t.length),t.copyTo(e)}}Ft.AlphaTabManufacturerId=125,Ft.MetronomeEventId=0,Ft.RestEventId=1;class Dt extends Ft{constructor(e,t,s,i,a){super(e,t,it.AlphaTabMetronome),this.isMetronome=!0,this.metronomeNumerator=s,this.metronomeDurationInMilliseconds=a,this.metronomeDurationInTicks=i}writeEventData(e){e.writeByte(Ft.MetronomeEventId),e.writeByte(this.metronomeNumerator),wt.writeInt32LE(e,this.metronomeDurationInTicks),wt.writeInt32LE(e,this.metronomeDurationInMilliseconds)}}class Mt extends Ft{constructor(e,t,s){super(e,t,it.AlphaTabRest),this.channel=s}writeEventData(e){e.writeByte(Ft.RestEventId),e.writeByte(this.channel)}}class Lt extends Ct{constructor(e,t,s,i,a,r){super(e,t,s),this.channel=i,this.noteKey=a,this.noteVelocity=r}get data1(){return this.noteKey}get data2(){return this.noteVelocity}}class It extends Lt{constructor(e,t,s,i,a){super(e,t,it.NoteOn,s,i,a)}writeTo(e){e.writeByte(15&this.channel|144),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class At extends Lt{constructor(e,t,s,i,a){super(e,t,it.NoteOff,s,i,a)}writeTo(e){e.writeByte(15&this.channel|128),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class Rt extends Ct{constructor(e,t,s,i,a){super(e,t,it.ControlChange),this.channel=s,this.controller=i,this.value=a}writeTo(e){e.writeByte(15&this.channel|176),e.writeByte(255&this.controller),e.writeByte(255&this.value)}get data1(){return this.controller}get data2(){return this.value}}class Ot extends Ct{constructor(e,t,s,i){super(e,t,it.ProgramChange),this.channel=s,this.program=i}writeTo(e){e.writeByte(15&this.channel|192),e.writeByte(255&this.program)}get data1(){return this.program}}class Ht extends Ct{constructor(e,t){super(0,e,it.TempoChange),this.microSecondsPerQuarterNote=t}writeTo(e){e.writeByte(255),e.writeByte(81),e.writeByte(3),e.writeByte(this.microSecondsPerQuarterNote>>16&255),e.writeByte(this.microSecondsPerQuarterNote>>8&255),e.writeByte(255&this.microSecondsPerQuarterNote)}}class Wt extends Ct{constructor(e,t,s,i){super(e,t,it.PitchBend),this.channel=s,this.value=i}writeTo(e){e.writeByte(15&this.channel|224),e.writeByte(127&this.value),e.writeByte(this.value>>7&127)}get data1(){return 127&this.value}get data2(){return this.value>>7&127}}class Vt extends Ct{constructor(e,t,s,i,a){super(e,t,it.PerNotePitchBend),this.channel=s,this.noteKey=i,this.value=a}writeTo(e){throw new Le(Ee.General,"Note Bend (Midi2.0) events cannot be exported to SMF1.0")}}class Gt extends Ct{constructor(e,t){super(e,t,it.EndOfTrack)}writeTo(e){e.writeByte(255),e.writeByte(47),e.writeByte(0)}}class Ut{constructor(){this.copyrightFont=new We(Ut.sansFont,12,Fe.Plain,De.Bold),this.titleFont=new We(Ut.serifFont,32,Fe.Plain),this.subTitleFont=new We(Ut.serifFont,20,Fe.Plain),this.wordsFont=new We(Ut.serifFont,15,Fe.Plain),this.effectFont=new We(Ut.serifFont,12,Fe.Italic),this.timerFont=new We(Ut.serifFont,12,Fe.Plain),this.directionsFont=new We(Ut.serifFont,14,Fe.Plain),this.fretboardNumberFont=new We(Ut.sansFont,11,Fe.Plain),this.numberedNotationFont=new We(Ut.sansFont,16,Fe.Plain),this.numberedNotationGraceFont=new We(Ut.sansFont,14,Fe.Plain),this.tablatureFont=new We(Ut.sansFont,13,Fe.Plain),this.graceFont=new We(Ut.sansFont,11,Fe.Plain),this.staffLineColor=new Ae(165,165,165,255),this.barSeparatorColor=new Ae(34,34,17,255),this.barNumberFont=new We(Ut.sansFont,11,Fe.Plain),this.barNumberColor=new Ae(200,0,0,255),this.fingeringFont=new We(Ut.serifFont,14,Fe.Plain),this.inlineFingeringFont=new We(Ut.serifFont,12,Fe.Plain),this.markerFont=new We(Ut.serifFont,14,Fe.Plain,De.Bold),this.mainGlyphColor=new Ae(0,0,0,255),this.secondaryGlyphColor=new Ae(0,0,0,100),this.scoreInfoColor=new Ae(0,0,0,255)}getFontForElement(e){switch(e){case Je.Title:return this.titleFont;case Je.SubTitle:case Je.Artist:case Je.Album:return this.subTitleFont;case Je.Words:case Je.Music:case Je.WordsAndMusic:case Je.Transcriber:return this.wordsFont;case Je.Copyright:case Je.CopyrightSecondLine:return this.copyrightFont}return this.wordsFont}}Ut.sansFont="Arial, sans-serif",Ut.serifFont="Georgia, serif",function(e){e[e.Automatic=0]="Automatic",e[e.UseModelLayout=1]="UseModelLayout"}(at||(at={}));class zt{constructor(){this.scale=1,this.stretchForce=1,this.layoutMode=e.Page,this.staveProfile=t.Default,this.barsPerRow=-1,this.startBar=1,this.barCount=-1,this.barCountPerPartial=10,this.justifyLastSystem=!1,this.resources=new Ut,this.padding=[35,35],this.firstSystemPaddingTop=5,this.systemPaddingTop=10,this.systemPaddingBottom=20,this.lastSystemPaddingBottom=0,this.systemLabelPaddingLeft=0,this.systemLabelPaddingRight=5,this.accoladeBarPaddingRight=3,this.notationStaffPaddingTop=5,this.notationStaffPaddingBottom=5,this.effectStaffPaddingTop=0,this.effectStaffPaddingBottom=0,this.firstStaffPaddingLeft=6,this.staffPaddingLeft=2,this.systemsLayoutMode=at.Automatic}}class Xt{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"}(rt||(rt={}));class Jt{constructor(){this.noteWideLength=240,this.noteWideAmplitude=1,this.noteSlightLength=360,this.noteSlightAmplitude=.5,this.beatWideLength=480,this.beatWideAmplitude=2,this.beatSlightLength=480,this.beatSlightAmplitude=2}}class Yt{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}!function(e){e[e.WebAudioAudioWorklets=0]="WebAudioAudioWorklets",e[e.WebAudioScriptProcessor=1]="WebAudioScriptProcessor"}(nt||(nt={}));class $t{constructor(){this.soundFont=null,this.scrollElement="html,body",this.outputMode=nt.WebAudioAudioWorklets,this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=rt.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new Jt,this.slide=new Yt,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}class qt{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>qt.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scriptfile",e.scriptFile),t.set("fontdirectory",e.fontDirectory),t.set("file",e.file),t.set("tex",e.tex),t.set("tracks",e.tracks),t.set("enablelazyloading",e.enableLazyLoading),t.set("engine",e.engine),t.set("loglevel",e.logLevel),t.set("useworkers",e.useWorkers),t.set("includenotebounds",e.includeNoteBounds),t}static setProperty(e,t,s){switch(t){case"scriptfile":return e.scriptFile=s,!0;case"fontdirectory":return e.fontDirectory=s,!0;case"file":return e.file=s,!0;case"tex":return e.tex=s,!0;case"tracks":return e.tracks=s,!0;case"enablelazyloading":return e.enableLazyLoading=s,!0;case"engine":return e.engine=s,!0;case"loglevel":return e.logLevel=Re.parseEnum(s,E),!0;case"useworkers":return e.useWorkers=s,!0;case"includenotebounds":return e.includeNoteBounds=s,!0}return!1}}class Kt{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>Kt.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("copyrightfont",We.toJson(e.copyrightFont)),t.set("titlefont",We.toJson(e.titleFont)),t.set("subtitlefont",We.toJson(e.subTitleFont)),t.set("wordsfont",We.toJson(e.wordsFont)),t.set("effectfont",We.toJson(e.effectFont)),t.set("timerfont",We.toJson(e.timerFont)),t.set("directionsfont",We.toJson(e.directionsFont)),t.set("fretboardnumberfont",We.toJson(e.fretboardNumberFont)),t.set("numberednotationfont",We.toJson(e.numberedNotationFont)),t.set("numberednotationgracefont",We.toJson(e.numberedNotationGraceFont)),t.set("tablaturefont",We.toJson(e.tablatureFont)),t.set("gracefont",We.toJson(e.graceFont)),t.set("stafflinecolor",Ae.toJson(e.staffLineColor)),t.set("barseparatorcolor",Ae.toJson(e.barSeparatorColor)),t.set("barnumberfont",We.toJson(e.barNumberFont)),t.set("barnumbercolor",Ae.toJson(e.barNumberColor)),t.set("fingeringfont",We.toJson(e.fingeringFont)),t.set("inlinefingeringfont",We.toJson(e.inlineFingeringFont)),t.set("markerfont",We.toJson(e.markerFont)),t.set("mainglyphcolor",Ae.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",Ae.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",Ae.toJson(e.scoreInfoColor)),t}static setProperty(e,t,s){switch(t){case"copyrightfont":return e.copyrightFont=We.fromJson(s),!0;case"titlefont":return e.titleFont=We.fromJson(s),!0;case"subtitlefont":return e.subTitleFont=We.fromJson(s),!0;case"wordsfont":return e.wordsFont=We.fromJson(s),!0;case"effectfont":return e.effectFont=We.fromJson(s),!0;case"timerfont":return e.timerFont=We.fromJson(s),!0;case"directionsfont":return e.directionsFont=We.fromJson(s),!0;case"fretboardnumberfont":return e.fretboardNumberFont=We.fromJson(s),!0;case"numberednotationfont":return e.numberedNotationFont=We.fromJson(s),!0;case"numberednotationgracefont":return e.numberedNotationGraceFont=We.fromJson(s),!0;case"tablaturefont":return e.tablatureFont=We.fromJson(s),!0;case"gracefont":return e.graceFont=We.fromJson(s),!0;case"stafflinecolor":return e.staffLineColor=Ae.fromJson(s),!0;case"barseparatorcolor":return e.barSeparatorColor=Ae.fromJson(s),!0;case"barnumberfont":return e.barNumberFont=We.fromJson(s),!0;case"barnumbercolor":return e.barNumberColor=Ae.fromJson(s),!0;case"fingeringfont":return e.fingeringFont=We.fromJson(s),!0;case"inlinefingeringfont":return e.inlineFingeringFont=We.fromJson(s),!0;case"markerfont":return e.markerFont=We.fromJson(s),!0;case"mainglyphcolor":return e.mainGlyphColor=Ae.fromJson(s),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=Ae.fromJson(s),!0;case"scoreinfocolor":return e.scoreInfoColor=Ae.fromJson(s),!0}return!1}}class jt{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>jt.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scale",e.scale),t.set("stretchforce",e.stretchForce),t.set("layoutmode",e.layoutMode),t.set("staveprofile",e.staveProfile),t.set("barsperrow",e.barsPerRow),t.set("startbar",e.startBar),t.set("barcount",e.barCount),t.set("barcountperpartial",e.barCountPerPartial),t.set("justifylastsystem",e.justifyLastSystem),t.set("resources",Kt.toJson(e.resources)),t.set("padding",e.padding),t.set("firstsystempaddingtop",e.firstSystemPaddingTop),t.set("systempaddingtop",e.systemPaddingTop),t.set("systempaddingbottom",e.systemPaddingBottom),t.set("lastsystempaddingbottom",e.lastSystemPaddingBottom),t.set("systemlabelpaddingleft",e.systemLabelPaddingLeft),t.set("systemlabelpaddingright",e.systemLabelPaddingRight),t.set("accoladebarpaddingright",e.accoladeBarPaddingRight),t.set("notationstaffpaddingtop",e.notationStaffPaddingTop),t.set("notationstaffpaddingbottom",e.notationStaffPaddingBottom),t.set("effectstaffpaddingtop",e.effectStaffPaddingTop),t.set("effectstaffpaddingbottom",e.effectStaffPaddingBottom),t.set("firststaffpaddingleft",e.firstStaffPaddingLeft),t.set("staffpaddingleft",e.staffPaddingLeft),t.set("systemslayoutmode",e.systemsLayoutMode),t}static setProperty(s,i,a){switch(i){case"scale":return s.scale=a,!0;case"stretchforce":return s.stretchForce=a,!0;case"layoutmode":return s.layoutMode=Re.parseEnum(a,e),!0;case"staveprofile":return s.staveProfile=Re.parseEnum(a,t),!0;case"barsperrow":return s.barsPerRow=a,!0;case"startbar":return s.startBar=a,!0;case"barcount":return s.barCount=a,!0;case"barcountperpartial":return s.barCountPerPartial=a,!0;case"justifylastsystem":return s.justifyLastSystem=a,!0;case"padding":return s.padding=a,!0;case"firstsystempaddingtop":return s.firstSystemPaddingTop=a,!0;case"systempaddingtop":return s.systemPaddingTop=a,!0;case"systempaddingbottom":return s.systemPaddingBottom=a,!0;case"lastsystempaddingbottom":return s.lastSystemPaddingBottom=a,!0;case"systemlabelpaddingleft":return s.systemLabelPaddingLeft=a,!0;case"systemlabelpaddingright":return s.systemLabelPaddingRight=a,!0;case"accoladebarpaddingright":return s.accoladeBarPaddingRight=a,!0;case"notationstaffpaddingtop":return s.notationStaffPaddingTop=a,!0;case"notationstaffpaddingbottom":return s.notationStaffPaddingBottom=a,!0;case"effectstaffpaddingtop":return s.effectStaffPaddingTop=a,!0;case"effectstaffpaddingbottom":return s.effectStaffPaddingBottom=a,!0;case"firststaffpaddingleft":return s.firstStaffPaddingLeft=a,!0;case"staffpaddingleft":return s.staffPaddingLeft=a,!0;case"systemslayoutmode":return s.systemsLayoutMode=Re.parseEnum(a,at),!0}if(["resources"].indexOf(i)>=0)return Kt.fromJson(s.resources,a),!0;for(const e of["resources"])if(0===i.indexOf(e)&&Kt.setProperty(s.resources,i.substring(e.length),a))return!0;return!1}}class Qt{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>Qt.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("notationmode",e.notationMode),t.set("fingeringmode",e.fingeringMode);{const s=new Map;t.set("elements",s);for(const[t,i]of e.elements)s.set(t.toString(),i)}return t.set("rhythmmode",e.rhythmMode),t.set("rhythmheight",e.rhythmHeight),t.set("transpositionpitches",e.transpositionPitches),t.set("displaytranspositionpitches",e.displayTranspositionPitches),t.set("smallgracetabnotes",e.smallGraceTabNotes),t.set("extendbendarrowsontiednotes",e.extendBendArrowsOnTiedNotes),t.set("extendlineeffectstobeatend",e.extendLineEffectsToBeatEnd),t.set("slurheight",e.slurHeight),t}static setProperty(e,t,s){switch(t){case"notationmode":return e.notationMode=Re.parseEnum(s,P),!0;case"fingeringmode":return e.fingeringMode=Re.parseEnum(s,v),!0;case"elements":return e.elements=new Map,Re.forEach(s,((t,s)=>{e.elements.set(Re.parseEnum(s,C),t)})),!0;case"rhythmmode":return e.rhythmMode=Re.parseEnum(s,x),!0;case"rhythmheight":return e.rhythmHeight=s,!0;case"transpositionpitches":return e.transpositionPitches=s,!0;case"displaytranspositionpitches":return e.displayTranspositionPitches=s,!0;case"smallgracetabnotes":return e.smallGraceTabNotes=s,!0;case"extendbendarrowsontiednotes":return e.extendBendArrowsOnTiedNotes=s,!0;case"extendlineeffectstobeatend":return e.extendLineEffectsToBeatEnd=s,!0;case"slurheight":return e.slurHeight=s,!0}return!1}}class Zt{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>Zt.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("encoding",e.encoding),t.set("mergepartgroupsinmusicxml",e.mergePartGroupsInMusicXml),t.set("beattextaslyrics",e.beatTextAsLyrics),t}static setProperty(e,t,s){switch(t){case"encoding":return e.encoding=s,!0;case"mergepartgroupsinmusicxml":return e.mergePartGroupsInMusicXml=s,!0;case"beattextaslyrics":return e.beatTextAsLyrics=s,!0}return!1}}class es{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>es.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("notewidelength",e.noteWideLength),t.set("notewideamplitude",e.noteWideAmplitude),t.set("noteslightlength",e.noteSlightLength),t.set("noteslightamplitude",e.noteSlightAmplitude),t.set("beatwidelength",e.beatWideLength),t.set("beatwideamplitude",e.beatWideAmplitude),t.set("beatslightlength",e.beatSlightLength),t.set("beatslightamplitude",e.beatSlightAmplitude),t}static setProperty(e,t,s){switch(t){case"notewidelength":return e.noteWideLength=s,!0;case"notewideamplitude":return e.noteWideAmplitude=s,!0;case"noteslightlength":return e.noteSlightLength=s,!0;case"noteslightamplitude":return e.noteSlightAmplitude=s,!0;case"beatwidelength":return e.beatWideLength=s,!0;case"beatwideamplitude":return e.beatWideAmplitude=s,!0;case"beatslightlength":return e.beatSlightLength=s,!0;case"beatslightamplitude":return e.beatSlightAmplitude=s,!0}return!1}}class ts{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>ts.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("simpleslidepitchoffset",e.simpleSlidePitchOffset),t.set("simpleslidedurationratio",e.simpleSlideDurationRatio),t.set("shiftslidedurationratio",e.shiftSlideDurationRatio),t}static setProperty(e,t,s){switch(t){case"simpleslidepitchoffset":return e.simpleSlidePitchOffset=s,!0;case"simpleslidedurationratio":return e.simpleSlideDurationRatio=s,!0;case"shiftslidedurationratio":return e.shiftSlideDurationRatio=s,!0}return!1}}class ss{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>ss.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("soundfont",e.soundFont),t.set("outputmode",e.outputMode),t.set("enableplayer",e.enablePlayer),t.set("enablecursor",e.enableCursor),t.set("enableanimatedbeatcursor",e.enableAnimatedBeatCursor),t.set("enableelementhighlighting",e.enableElementHighlighting),t.set("enableuserinteraction",e.enableUserInteraction),t.set("scrolloffsetx",e.scrollOffsetX),t.set("scrolloffsety",e.scrollOffsetY),t.set("scrollmode",e.scrollMode),t.set("scrollspeed",e.scrollSpeed),t.set("nativebrowsersmoothscroll",e.nativeBrowserSmoothScroll),t.set("songbookbendduration",e.songBookBendDuration),t.set("songbookdipduration",e.songBookDipDuration),t.set("vibrato",es.toJson(e.vibrato)),t.set("slide",ts.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t.set("buffertimeinmilliseconds",e.bufferTimeInMilliseconds),t}static setProperty(e,t,s){switch(t){case"soundfont":return e.soundFont=s,!0;case"scrollelement":return e.scrollElement=s,!0;case"outputmode":return e.outputMode=Re.parseEnum(s,nt),!0;case"enableplayer":return e.enablePlayer=s,!0;case"enablecursor":return e.enableCursor=s,!0;case"enableanimatedbeatcursor":return e.enableAnimatedBeatCursor=s,!0;case"enableelementhighlighting":return e.enableElementHighlighting=s,!0;case"enableuserinteraction":return e.enableUserInteraction=s,!0;case"scrolloffsetx":return e.scrollOffsetX=s,!0;case"scrolloffsety":return e.scrollOffsetY=s,!0;case"scrollmode":return e.scrollMode=Re.parseEnum(s,rt),!0;case"scrollspeed":return e.scrollSpeed=s,!0;case"nativebrowsersmoothscroll":return e.nativeBrowserSmoothScroll=s,!0;case"songbookbendduration":return e.songBookBendDuration=s,!0;case"songbookdipduration":return e.songBookDipDuration=s,!0;case"playtripletfeel":return e.playTripletFeel=s,!0;case"buffertimeinmilliseconds":return e.bufferTimeInMilliseconds=s,!0}if(["vibrato"].indexOf(t)>=0)return es.fromJson(e.vibrato,s),!0;for(const i of["vibrato"])if(0===t.indexOf(i)&&es.setProperty(e.vibrato,t.substring(i.length),s))return!0;if(["slide"].indexOf(t)>=0)return ts.fromJson(e.slide,s),!0;for(const i of["slide"])if(0===t.indexOf(i)&&ts.setProperty(e.slide,t.substring(i.length),s))return!0;return!1}}class is{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>is.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("core",qt.toJson(e.core)),t.set("display",jt.toJson(e.display)),t.set("notation",Qt.toJson(e.notation)),t.set("importer",Zt.toJson(e.importer)),t.set("player",ss.toJson(e.player)),t}static setProperty(e,t,s){if(["core",""].indexOf(t)>=0)return qt.fromJson(e.core,s),!0;for(const i of["core",""])if(0===t.indexOf(i)&&qt.setProperty(e.core,t.substring(i.length),s))return!0;if(["display",""].indexOf(t)>=0)return jt.fromJson(e.display,s),!0;for(const i of["display",""])if(0===t.indexOf(i)&&jt.setProperty(e.display,t.substring(i.length),s))return!0;if(["notation"].indexOf(t)>=0)return Qt.fromJson(e.notation,s),!0;for(const i of["notation"])if(0===t.indexOf(i)&&Qt.setProperty(e.notation,t.substring(i.length),s))return!0;if(["importer"].indexOf(t)>=0)return Zt.fromJson(e.importer,s),!0;for(const i of["importer"])if(0===t.indexOf(i)&&Zt.setProperty(e.importer,t.substring(i.length),s))return!0;if(["player"].indexOf(t)>=0)return ss.fromJson(e.player,s),!0;for(const i of["player"])if(0===t.indexOf(i)&&ss.setProperty(e.player,t.substring(i.length),s))return!0;return!1}}class as{constructor(){this.core=new ac,this.display=new zt,this.notation=new re,this.importer=new Xt,this.player=new $t}setSongBookModeSettings(){this.notation.notationMode=P.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=v.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(C.ParenthesisOnTiedBends,!1),this.notation.elements.set(C.TabNotesOnTiedBends,!1),this.notation.elements.set(C.ZerosOnDiveWhammys,!0)}static get songBook(){const e=new as;return e.setSongBookModeSettings(),e}fillFromJson(e){is.fromJson(this,e)}}class rs{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>rs.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("marker",e.marker),t.set("text",e.text),t}static setProperty(e,t,s){switch(t){case"marker":return e.marker=s,!0;case"text":return e.text=s,!0}return!1}}class ns{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>ns.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("islinear",e.isLinear),t.set("type",e.type),t.set("value",e.value),t.set("ratioposition",e.ratioPosition),t.set("text",e.text),t}static setProperty(e,t,s){switch(t){case"islinear":return e.isLinear=s,!0;case"type":return e.type=Re.parseEnum(s,d),!0;case"value":return e.value=s,!0;case"ratioposition":return e.ratioPosition=s,!0;case"text":return e.text=s,!0}return!1}}class os{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>os.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("type",e.type),t.set("length",e.length),t}static setProperty(e,t,s){switch(t){case"type":return e.type=Re.parseEnum(s,Ke),!0;case"length":return e.length=s,!0}return!1}}class hs{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>hs.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("alternateendings",e.alternateEndings),t.set("keysignature",e.keySignature),t.set("keysignaturetype",e.keySignatureType),t.set("isdoublebar",e.isDoubleBar),t.set("isrepeatstart",e.isRepeatStart),t.set("repeatcount",e.repeatCount),t.set("timesignaturenumerator",e.timeSignatureNumerator),t.set("timesignaturedenominator",e.timeSignatureDenominator),t.set("timesignaturecommon",e.timeSignatureCommon),t.set("isfreetime",e.isFreeTime),t.set("tripletfeel",e.tripletFeel),e.section&&t.set("section",rs.toJson(e.section)),t.set("tempoautomations",e.tempoAutomations.map((e=>ns.toJson(e)))),null!==e.fermata){const s=new Map;t.set("fermata",s);for(const[t,i]of e.fermata)s.set(t.toString(),os.toJson(i))}if(t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),null!==e.directions){const s=[];t.set("directions",s);for(const t of e.directions)s.push(t)}return t}static setProperty(e,t,s){switch(t){case"alternateendings":return e.alternateEndings=s,!0;case"keysignature":return e.keySignature=Re.parseEnum(s,F),!0;case"keysignaturetype":return e.keySignatureType=Re.parseEnum(s,D),!0;case"isdoublebar":return e.isDoubleBar=s,!0;case"isrepeatstart":return e.isRepeatStart=s,!0;case"repeatcount":return e.repeatCount=s,!0;case"timesignaturenumerator":return e.timeSignatureNumerator=s,!0;case"timesignaturedenominator":return e.timeSignatureDenominator=s,!0;case"timesignaturecommon":return e.timeSignatureCommon=s,!0;case"isfreetime":return e.isFreeTime=s,!0;case"tripletfeel":return e.tripletFeel=Re.parseEnum(s,M),!0;case"section":return s?(e.section=new gt,rs.fromJson(e.section,s)):e.section=null,!0;case"tempoautomations":e.tempoAutomations=[];for(const t of s){const s=new ie;ns.fromJson(s,t),e.tempoAutomations.push(s)}return!0;case"fermata":return e.fermata=new Map,Re.forEach(s,((t,s)=>{const i=new Tt;os.fromJson(i,t),e.addFermata(Number.parseInt(s),i)})),!0;case"start":return e.start=s,!0;case"isanacrusis":return e.isAnacrusis=s,!0;case"displayscale":return e.displayScale=s,!0;case"displaywidth":return e.displayWidth=s,!0;case"directions":for(const t of s)e.addDirection(Re.parseEnum(t,qe));return!0}return!1}}class ls{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>ls.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("offset",e.offset),t.set("value",e.value),t}static setProperty(e,t,s){switch(t){case"offset":return e.offset=s,!0;case"value":return e.value=s,!0}return!1}}class cs{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>cs.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("notehead",e.noteHead),t.set("noteheadcenteronstem",e.noteHeadCenterOnStem);{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),Ae.toJson(i))}return t}static setProperty(e,t,s){switch(t){case"notehead":return e.noteHead=Re.parseEnum(s,I),!0;case"noteheadcenteronstem":return e.noteHeadCenterOnStem=s,!0;case"colors":return e.colors=new Map,Re.forEach(s,((t,s)=>{e.colors.set(Re.parseEnum(s,H),Ae.fromJson(t))})),!0}return!1}}class ds{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>ds.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("accentuated",e.accentuated),t.set("bendtype",e.bendType),t.set("bendstyle",e.bendStyle),t.set("iscontinuedbend",e.isContinuedBend),null!==e.bendPoints&&t.set("bendpoints",e.bendPoints?.map((e=>ls.toJson(e)))),t.set("fret",e.fret),t.set("string",e.string),t.set("showstringnumber",e.showStringNumber),t.set("octave",e.octave),t.set("tone",e.tone),t.set("percussionarticulation",e.percussionArticulation),t.set("isvisible",e.isVisible),t.set("islefthandtapped",e.isLeftHandTapped),t.set("ishammerpullorigin",e.isHammerPullOrigin),t.set("isslurdestination",e.isSlurDestination),t.set("harmonictype",e.harmonicType),t.set("harmonicvalue",e.harmonicValue),t.set("isghost",e.isGhost),t.set("isletring",e.isLetRing),t.set("ispalmmute",e.isPalmMute),t.set("isdead",e.isDead),t.set("isstaccato",e.isStaccato),t.set("slideintype",e.slideInType),t.set("slideouttype",e.slideOutType),t.set("vibrato",e.vibrato),t.set("istiedestination",e.isTieDestination),t.set("lefthandfinger",e.leftHandFinger),t.set("righthandfinger",e.rightHandFinger),t.set("trillvalue",e.trillValue),t.set("trillspeed",e.trillSpeed),t.set("durationpercent",e.durationPercent),t.set("accidentalmode",e.accidentalMode),t.set("dynamics",e.dynamics),t.set("ornament",e.ornament),e.style&&t.set("style",cs.toJson(e.style)),e.toJson(t),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"accentuated":return e.accentuated=Re.parseEnum(s,S),!0;case"bendtype":return e.bendType=Re.parseEnum(s,p),!0;case"bendstyle":return e.bendStyle=Re.parseEnum(s,u),!0;case"iscontinuedbend":return e.isContinuedBend=s,!0;case"bendpoints":if(s){e.bendPoints=[];for(const t of s){const s=new ae;ls.fromJson(s,t),e.addBendPoint(s)}}return!0;case"fret":return e.fret=s,!0;case"string":return e.string=s,!0;case"showstringnumber":return e.showStringNumber=s,!0;case"octave":return e.octave=s,!0;case"tone":return e.tone=s,!0;case"percussionarticulation":return e.percussionArticulation=s,!0;case"isvisible":return e.isVisible=s,!0;case"islefthandtapped":return e.isLeftHandTapped=s,!0;case"ishammerpullorigin":return e.isHammerPullOrigin=s,!0;case"isslurdestination":return e.isSlurDestination=s,!0;case"harmonictype":return e.harmonicType=Re.parseEnum(s,w),!0;case"harmonicvalue":return e.harmonicValue=s,!0;case"isghost":return e.isGhost=s,!0;case"isletring":return e.isLetRing=s,!0;case"ispalmmute":return e.isPalmMute=s,!0;case"isdead":return e.isDead=s,!0;case"isstaccato":return e.isStaccato=s,!0;case"slideintype":return e.slideInType=Re.parseEnum(s,k),!0;case"slideouttype":return e.slideOutType=Re.parseEnum(s,T),!0;case"vibrato":return e.vibrato=Re.parseEnum(s,N),!0;case"istiedestination":return e.isTieDestination=s,!0;case"lefthandfinger":return e.leftHandFinger=Re.parseEnum(s,_),!0;case"righthandfinger":return e.rightHandFinger=Re.parseEnum(s,_),!0;case"trillvalue":return e.trillValue=s,!0;case"trillspeed":return e.trillSpeed=Re.parseEnum(s,f),!0;case"durationpercent":return e.durationPercent=s,!0;case"accidentalmode":return e.accidentalMode=Re.parseEnum(s,B),!0;case"dynamics":return e.dynamics=Re.parseEnum(s,y),!0;case"ornament":return e.ornament=Re.parseEnum(s,O),!0;case"style":return s?(e.style=new ye,cs.fromJson(e.style,s)):e.style=void 0,!0}return e.setProperty(t,s)}}class us{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>us.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),Ae.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,Re.forEach(s,((t,s)=>{e.colors.set(Re.parseEnum(s,Y),Ae.fromJson(t))})),!0)}}class ps{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>ps.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("notes",e.notes.map((e=>ds.toJson(e)))),t.set("isempty",e.isEmpty),t.set("whammystyle",e.whammyStyle),t.set("ottava",e.ottava),t.set("islegatoorigin",e.isLegatoOrigin),t.set("duration",e.duration),t.set("automations",e.automations.map((e=>ns.toJson(e)))),t.set("dots",e.dots),t.set("fade",e.fade),t.set("lyrics",e.lyrics),t.set("pop",e.pop),t.set("slap",e.slap),t.set("tap",e.tap),t.set("text",e.text),t.set("slashed",e.slashed),t.set("deadslapped",e.deadSlapped),t.set("brushtype",e.brushType),t.set("brushduration",e.brushDuration),t.set("tupletdenominator",e.tupletDenominator),t.set("tupletnumerator",e.tupletNumerator),t.set("iscontinuedwhammy",e.isContinuedWhammy),t.set("whammybartype",e.whammyBarType),null!==e.whammyBarPoints&&t.set("whammybarpoints",e.whammyBarPoints?.map((e=>ls.toJson(e)))),t.set("vibrato",e.vibrato),t.set("chordid",e.chordId),t.set("gracetype",e.graceType),t.set("pickstroke",e.pickStroke),t.set("tremolospeed",e.tremoloSpeed),t.set("crescendo",e.crescendo),t.set("displaystart",e.displayStart),t.set("playbackstart",e.playbackStart),t.set("displayduration",e.displayDuration),t.set("playbackduration",e.playbackDuration),t.set("overridedisplayduration",e.overrideDisplayDuration),t.set("golpe",e.golpe),t.set("dynamics",e.dynamics),t.set("invertbeamdirection",e.invertBeamDirection),t.set("preferredbeamdirection",e.preferredBeamDirection),t.set("beamingmode",e.beamingMode),t.set("wahpedal",e.wahPedal),t.set("barrefret",e.barreFret),t.set("barreshape",e.barreShape),t.set("rasgueado",e.rasgueado),t.set("showtimer",e.showTimer),t.set("timer",e.timer),e.style&&t.set("style",us.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"notes":e.notes=[];for(const t of s){const s=new be;ds.fromJson(s,t),e.addNote(s)}return!0;case"isempty":return e.isEmpty=s,!0;case"whammystyle":return e.whammyStyle=Re.parseEnum(s,u),!0;case"ottava":return e.ottava=Re.parseEnum(s,o),!0;case"islegatoorigin":return e.isLegatoOrigin=s,!0;case"duration":return e.duration=Re.parseEnum(s,f),!0;case"automations":e.automations=[];for(const t of s){const s=new ie;ns.fromJson(s,t),e.automations.push(s)}return!0;case"dots":return e.dots=s,!0;case"fade":return e.fade=Re.parseEnum(s,G),!0;case"lyrics":return e.lyrics=s,!0;case"pop":return e.pop=s,!0;case"slap":return e.slap=s,!0;case"tap":return e.tap=s,!0;case"text":return e.text=s,!0;case"slashed":return e.slashed=s,!0;case"deadslapped":return e.deadSlapped=s,!0;case"brushtype":return e.brushType=Re.parseEnum(s,g),!0;case"brushduration":return e.brushDuration=s,!0;case"tupletdenominator":return e.tupletDenominator=s,!0;case"tupletnumerator":return e.tupletNumerator=s,!0;case"iscontinuedwhammy":return e.isContinuedWhammy=s,!0;case"whammybartype":return e.whammyBarType=Re.parseEnum(s,W),!0;case"whammybarpoints":if(s){e.whammyBarPoints=[];for(const t of s){const s=new ae;ls.fromJson(s,t),e.addWhammyBarPoint(s)}}return!0;case"vibrato":return e.vibrato=Re.parseEnum(s,N),!0;case"chordid":return e.chordId=s,!0;case"gracetype":return e.graceType=Re.parseEnum(s,b),!0;case"pickstroke":return e.pickStroke=Re.parseEnum(s,L),!0;case"tremolospeed":return e.tremoloSpeed=Re.parseEnum(s,f)??null,!0;case"crescendo":return e.crescendo=Re.parseEnum(s,m),!0;case"displaystart":return e.displayStart=s,!0;case"playbackstart":return e.playbackStart=s,!0;case"displayduration":return e.displayDuration=s,!0;case"playbackduration":return e.playbackDuration=s,!0;case"overridedisplayduration":return e.overrideDisplayDuration=s,!0;case"golpe":return e.golpe=Re.parseEnum(s,V),!0;case"dynamics":return e.dynamics=Re.parseEnum(s,y),!0;case"invertbeamdirection":return e.invertBeamDirection=s,!0;case"preferredbeamdirection":return e.preferredBeamDirection=Re.parseEnum(s,je)??null,!0;case"beamingmode":return e.beamingMode=Re.parseEnum(s,J),!0;case"wahpedal":return e.wahPedal=Re.parseEnum(s,U),!0;case"barrefret":return e.barreFret=s,!0;case"barreshape":return e.barreShape=Re.parseEnum(s,z),!0;case"rasgueado":return e.rasgueado=Re.parseEnum(s,X),!0;case"showtimer":return e.showTimer=s,!0;case"timer":return e.timer=s,!0;case"style":return s?(e.style=new Ne,us.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class gs{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>gs.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),Ae.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,Re.forEach(s,((t,s)=>{e.colors.set(Re.parseEnum(s,$),Ae.fromJson(t))})),!0)}}class ms{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>ms.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("beats",e.beats.map((e=>ps.toJson(e)))),e.style&&t.set("style",gs.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"beats":e.beats=[];for(const t of s){const s=new xe;ps.fromJson(s,t),e.addBeat(s)}return!0;case"style":return s?(e.style=new ve,gs.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class fs{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>fs.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("ratioposition",e.ratioPosition),t.set("pedaltype",e.pedalType),t}static setProperty(e,t,s){switch(t){case"ratioposition":return e.ratioPosition=s,!0;case"pedaltype":return e.pedalType=Re.parseEnum(s,l),!0}return!1}}class ys{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>ys.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),Ae.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,Re.forEach(s,((t,s)=>{e.colors.set(Re.parseEnum(s,c),Ae.fromJson(t))})),!0)}}class bs{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>bs.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("clef",e.clef),t.set("clefottava",e.clefOttava),t.set("voices",e.voices.map((e=>ms.toJson(e)))),t.set("similemark",e.simileMark),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t.set("sustainpedals",e.sustainPedals.map((e=>fs.toJson(e)))),e.style&&t.set("style",ys.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"clef":return e.clef=Re.parseEnum(s,n),!0;case"clefottava":return e.clefOttava=Re.parseEnum(s,o),!0;case"voices":e.voices=[];for(const t of s){const s=new Pe;ms.fromJson(s,t),e.addVoice(s)}return!0;case"similemark":return e.simileMark=Re.parseEnum(s,h),!0;case"displayscale":return e.displayScale=s,!0;case"displaywidth":return e.displayWidth=s,!0;case"sustainpedals":e.sustainPedals=[];for(const t of s){const s=new Z;fs.fromJson(s,t),e.sustainPedals.push(s)}return!0;case"style":return s?(e.style=new ee,ys.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class Ss{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>Ss.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("name",e.name),t.set("firstfret",e.firstFret),t.set("strings",e.strings),t.set("barrefrets",e.barreFrets),t.set("showname",e.showName),t.set("showdiagram",e.showDiagram),t.set("showfingering",e.showFingering),t}static setProperty(e,t,s){switch(t){case"name":return e.name=s,!0;case"firstfret":return e.firstFret=s,!0;case"strings":return e.strings=s,!0;case"barrefrets":return e.barreFrets=s,!0;case"showname":return e.showName=s,!0;case"showdiagram":return e.showDiagram=s,!0;case"showfingering":return e.showFingering=s,!0}return!1}}class _s{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>_s.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("isstandard",e.isStandard),t.set("name",e.name),t.set("tunings",e.tunings),t}static setProperty(e,t,s){switch(t){case"isstandard":return e.isStandard=s,!0;case"name":return e.name=s,!0;case"tunings":return e.tunings=s,!0}return!1}}class ws{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>ws.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("bars",e.bars.map((e=>bs.toJson(e)))),null!==e.chords){const s=new Map;t.set("chords",s);for(const[t,i]of e.chords)s.set(t.toString(),Ss.toJson(i))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",_s.toJson(e.stringTuning)),t.set("showslash",e.showSlash),t.set("shownumbered",e.showNumbered),t.set("showtablature",e.showTablature),t.set("showstandardnotation",e.showStandardNotation),t.set("ispercussion",e.isPercussion),t.set("standardnotationlinecount",e.standardNotationLineCount),t}static setProperty(e,t,s){switch(t){case"bars":e.bars=[];for(const t of s){const s=new te;bs.fromJson(s,t),e.addBar(s)}return!0;case"chords":return e.chords=new Map,Re.forEach(s,((t,s)=>{const i=new ut;Ss.fromJson(i,t),e.addChord(s,i)})),!0;case"capo":return e.capo=s,!0;case"transpositionpitch":return e.transpositionPitch=s,!0;case"displaytranspositionpitch":return e.displayTranspositionPitch=s,!0;case"stringtuning":return _s.fromJson(e.stringTuning,s),!0;case"showslash":return e.showSlash=s,!0;case"shownumbered":return e.showNumbered=s,!0;case"showtablature":return e.showTablature=s,!0;case"showstandardnotation":return e.showStandardNotation=s,!0;case"ispercussion":return e.isPercussion=s,!0;case"standardnotationlinecount":return e.standardNotationLineCount=s,!0}return!1}}class Bs{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>Bs.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("volume",e.volume),t.set("balance",e.balance),t.set("port",e.port),t.set("program",e.program),t.set("primarychannel",e.primaryChannel),t.set("secondarychannel",e.secondaryChannel),t.set("ismute",e.isMute),t.set("issolo",e.isSolo),t}static setProperty(e,t,s){switch(t){case"volume":return e.volume=s,!0;case"balance":return e.balance=s,!0;case"port":return e.port=s,!0;case"program":return e.program=s,!0;case"primarychannel":return e.primaryChannel=s,!0;case"secondarychannel":return e.secondaryChannel=s,!0;case"ismute":return e.isMute=s,!0;case"issolo":return e.isSolo=s,!0}return!1}}class ks{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>ks.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("elementtype",e.elementType),t.set("staffline",e.staffLine),t.set("noteheaddefault",e.noteHeadDefault),t.set("noteheadhalf",e.noteHeadHalf),t.set("noteheadwhole",e.noteHeadWhole),t.set("techniquesymbol",e.techniqueSymbol),t.set("techniquesymbolplacement",e.techniqueSymbolPlacement),t.set("outputmidinumber",e.outputMidiNumber),t}static setProperty(e,t,s){switch(t){case"elementtype":return e.elementType=s,!0;case"staffline":return e.staffLine=s,!0;case"noteheaddefault":return e.noteHeadDefault=Re.parseEnum(s,I),!0;case"noteheadhalf":return e.noteHeadHalf=Re.parseEnum(s,I),!0;case"noteheadwhole":return e.noteHeadWhole=Re.parseEnum(s,I),!0;case"techniquesymbol":return e.techniqueSymbol=Re.parseEnum(s,I),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=Re.parseEnum(s,R),!0;case"outputmidinumber":return e.outputMidiNumber=s,!0}return!1}}class Ts{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>Ts.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),Ae.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,Re.forEach(s,((t,s)=>{e.colors.set(Re.parseEnum(s,$e),Ae.fromJson(t))})),!0)}}class Ns{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>Ns.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("staves",e.staves.map((e=>ws.toJson(e)))),t.set("playbackinfo",Bs.toJson(e.playbackInfo)),t.set("color",Ae.toJson(e.color)),t.set("name",e.name),t.set("isvisibleonmultitrack",e.isVisibleOnMultiTrack),t.set("shortname",e.shortName),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),void 0!==e.lineBreaks){const s=[];t.set("linebreaks",s);for(const t of e.lineBreaks)s.push(t)}return t.set("percussionarticulations",e.percussionArticulations.map((e=>ks.toJson(e)))),e.style&&t.set("style",Ts.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"staves":e.staves=[];for(const t of s){const s=new yt;ws.fromJson(s,t),e.addStaff(s)}return!0;case"playbackinfo":return Bs.fromJson(e.playbackInfo,s),!0;case"color":return e.color=Ae.fromJson(s),!0;case"name":return e.name=s,!0;case"isvisibleonmultitrack":return e.isVisibleOnMultiTrack=s,!0;case"shortname":return e.shortName=s,!0;case"defaultsystemslayout":return e.defaultSystemsLayout=s,!0;case"systemslayout":return e.systemsLayout=s,!0;case"linebreaks":for(const t of s)e.addLineBreaks(t);return!0;case"percussionarticulations":e.percussionArticulations=[];for(const t of s){const s=new ge;ks.fromJson(s,t),e.percussionArticulations.push(s)}return!0;case"style":return s?(e.style=new bt,Ts.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class xs{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>xs.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("hidedynamics",e.hideDynamics),t.set("bracketextendmode",e.bracketExtendMode),t.set("usesystemsignseparator",e.useSystemSignSeparator),t.set("globaldisplaytuning",e.globalDisplayTuning),null!==e.perTrackDisplayTuning){const s=new Map;t.set("pertrackdisplaytuning",s);for(const[t,i]of e.perTrackDisplayTuning)s.set(t.toString(),i)}if(t.set("globaldisplaychorddiagramsontop",e.globalDisplayChordDiagramsOnTop),null!==e.perTrackChordDiagramsOnTop){const s=new Map;t.set("pertrackchorddiagramsontop",s);for(const[t,i]of e.perTrackChordDiagramsOnTop)s.set(t.toString(),i)}if(t.set("singletracktracknamepolicy",e.singleTrackTrackNamePolicy),t.set("multitracktracknamepolicy",e.multiTrackTrackNamePolicy),t.set("firstsystemtracknamemode",e.firstSystemTrackNameMode),t.set("othersystemstracknamemode",e.otherSystemsTrackNameMode),t.set("firstsystemtracknameorientation",e.firstSystemTrackNameOrientation),t.set("othersystemstracknameorientation",e.otherSystemsTrackNameOrientation),t.set("multitrackmultibarrest",e.multiTrackMultiBarRest),null!==e.perTrackMultiBarRest){const s=[];t.set("pertrackmultibarrest",s);for(const t of e.perTrackMultiBarRest)s.push(t)}return t}static setProperty(e,t,n){switch(t){case"hidedynamics":return e.hideDynamics=n,!0;case"bracketextendmode":return e.bracketExtendMode=Re.parseEnum(n,s),!0;case"usesystemsignseparator":return e.useSystemSignSeparator=n,!0;case"globaldisplaytuning":return e.globalDisplayTuning=n,!0;case"pertrackdisplaytuning":return e.perTrackDisplayTuning=new Map,Re.forEach(n,((t,s)=>{e.perTrackDisplayTuning.set(Number.parseInt(s),t)})),!0;case"globaldisplaychorddiagramsontop":return e.globalDisplayChordDiagramsOnTop=n,!0;case"pertrackchorddiagramsontop":return e.perTrackChordDiagramsOnTop=new Map,Re.forEach(n,((t,s)=>{e.perTrackChordDiagramsOnTop.set(Number.parseInt(s),t)})),!0;case"singletracktracknamepolicy":return e.singleTrackTrackNamePolicy=Re.parseEnum(n,i),!0;case"multitracktracknamepolicy":return e.multiTrackTrackNamePolicy=Re.parseEnum(n,i),!0;case"firstsystemtracknamemode":return e.firstSystemTrackNameMode=Re.parseEnum(n,a),!0;case"othersystemstracknamemode":return e.otherSystemsTrackNameMode=Re.parseEnum(n,a),!0;case"firstsystemtracknameorientation":return e.firstSystemTrackNameOrientation=Re.parseEnum(n,r),!0;case"othersystemstracknameorientation":return e.otherSystemsTrackNameOrientation=Re.parseEnum(n,r),!0;case"multitrackmultibarrest":return e.multiTrackMultiBarRest=n,!0;case"pertrackmultibarrest":return e.perTrackMultiBarRest=new Set(n),!0}return!1}}class vs{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>vs.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("template",e.template),t.set("isvisible",e.isVisible),t.set("textalign",e.textAlign),t}static setProperty(e,t,s){switch(t){case"template":return e.template=s,!0;case"isvisible":return e.isVisible=s,!0;case"textalign":return e.textAlign=Re.parseEnum(s,A),!0}return!1}}class Ps{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>Ps.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("headerandfooter",s);for(const[t,i]of e.headerAndFooter)s.set(t.toString(),vs.toJson(i))}{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),Ae.toJson(i))}return t}static setProperty(e,t,s){switch(t){case"headerandfooter":return e.headerAndFooter=new Map,Re.forEach(s,((t,s)=>{const i=new ot;vs.fromJson(i,t),e.headerAndFooter.set(Re.parseEnum(s,Je),i)})),!0;case"colors":return e.colors=new Map,Re.forEach(s,((t,s)=>{e.colors.set(Re.parseEnum(s,Je),Ae.fromJson(t))})),!0}return!1}}class Cs{static fromJson(e,t){t&&Re.forEach(t,((t,s)=>Cs.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("album",e.album),t.set("artist",e.artist),t.set("copyright",e.copyright),t.set("instructions",e.instructions),t.set("music",e.music),t.set("notices",e.notices),t.set("subtitle",e.subTitle),t.set("title",e.title),t.set("words",e.words),t.set("tab",e.tab),t.set("tempo",e.tempo),t.set("tempolabel",e.tempoLabel),t.set("masterbars",e.masterBars.map((e=>hs.toJson(e)))),t.set("tracks",e.tracks.map((e=>Ns.toJson(e)))),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("stylesheet",xs.toJson(e.stylesheet)),e.style&&t.set("style",Ps.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"album":return e.album=s,!0;case"artist":return e.artist=s,!0;case"copyright":return e.copyright=s,!0;case"instructions":return e.instructions=s,!0;case"music":return e.music=s,!0;case"notices":return e.notices=s,!0;case"subtitle":return e.subTitle=s,!0;case"title":return e.title=s,!0;case"words":return e.words=s,!0;case"tab":return e.tab=s,!0;case"tempo":return e.tempo=s,!0;case"tempolabel":return e.tempoLabel=s,!0;case"masterbars":e.masterBars=[];for(const t of s){const s=new le;hs.fromJson(s,t),e.addMasterBar(s)}return!0;case"tracks":e.tracks=[];for(const t of s){const s=new St;Ns.fromJson(s,t),e.addTrack(s)}return!0;case"defaultsystemslayout":return e.defaultSystemsLayout=s,!0;case"systemslayout":return e.systemsLayout=s,!0;case"stylesheet":return xs.fromJson(e.stylesheet,s),!0;case"style":return s?(e.style=new ht,Ps.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class Es{static jsonReplacer(e,t){if(t instanceof Map){if("fromEntries"in Object)return Object.fromEntries(t);const e={};for(const[s,i]of t)e[s]=i;return e}return ArrayBuffer.isView(t)?Array.apply([],[t]):t}static scoreToJson(e){const t=Es.scoreToJsObject(e);return JSON.stringify(t,Es.jsonReplacer)}static jsonToScore(e,t){return Es.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return Cs.toJson(e)}static jsObjectToScore(e,t){const s=new lt;return Cs.fromJson(s,e),s.finish(t??new as),s}static settingsToJson(e){const t=Es.settingsToJsObject(e);return JSON.stringify(t,Es.jsonReplacer)}static jsonToSettings(e){return Es.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return is.toJson(e)}static jsObjectToSettings(e){const t=new as;return is.fromJson(t,e),t}static jsObjectToMidiFile(e){const t=new Pt;return Re.forEach(e,((e,s)=>{switch(s){case"division":t.division=e;break;case"tracks":for(const s of e){const e=Es.jsObjectToMidiTrack(s);t.tracks.push(e)}}})),t}static jsObjectToMidiTrack(e){const t=new vt;return Re.forEach(e,((e,s)=>{if("events"===s)for(const s of e){const e=Es.jsObjectToMidiEvent(s);t.events.push(e)}})),t}static jsObjectToMidiEvent(e){const t=Re.getValue(e,"track"),s=Re.getValue(e,"tick"),i=Re.getValue(e,"type");switch(i){case it.TimeSignature:return new Et(t,s,Re.getValue(e,"numerator"),Re.getValue(e,"denominatorIndex"),Re.getValue(e,"midiClocksPerMetronomeClick"),Re.getValue(e,"thirdySecondNodesInQuarter"));case it.AlphaTabRest:return new Mt(t,s,Re.getValue(e,"channel"));case it.AlphaTabMetronome:return new Dt(t,s,Re.getValue(e,"metronomeNumerator"),Re.getValue(e,"metronomeDurationInTicks"),Re.getValue(e,"metronomeDurationInMilliseconds"));case it.NoteOn:return new It(t,s,Re.getValue(e,"channel"),Re.getValue(e,"noteKey"),Re.getValue(e,"noteVelocity"));case it.NoteOff:return new At(t,s,Re.getValue(e,"channel"),Re.getValue(e,"noteKey"),Re.getValue(e,"noteVelocity"));case it.ControlChange:return new Rt(t,s,Re.getValue(e,"channel"),Re.getValue(e,"controller"),Re.getValue(e,"value"));case it.ProgramChange:return new Ot(t,s,Re.getValue(e,"channel"),Re.getValue(e,"program"));case it.TempoChange:return new Ht(s,Re.getValue(e,"microSecondsPerQuarterNote"));case it.PitchBend:return new Wt(t,s,Re.getValue(e,"channel"),Re.getValue(e,"value"));case it.PerNotePitchBend:return new Vt(t,s,Re.getValue(e,"channel"),Re.getValue(e,"noteKey"),Re.getValue(e,"value"));case it.EndOfTrack:return new Gt(t,s)}throw new Le(Ee.Format,`Unknown Midi Event type: ${i}`)}static midiFileToJsObject(e){const t=new Map;t.set("division",e.division);const s=[];for(const t of e.tracks)s.push(Es.midiTrackToJsObject(t));return t.set("tracks",s),t}static midiTrackToJsObject(e){const t=new Map,s=[];for(const t of e.events)s.push(Es.midiEventToJsObject(t));return t.set("events",s),t}static midiEventToJsObject(e){const t=new Map;switch(t.set("track",e.track),t.set("tick",e.tick),t.set("type",e.type),e.type){case it.TimeSignature:t.set("numerator",e.numerator),t.set("denominatorIndex",e.denominatorIndex),t.set("midiClocksPerMetronomeClick",e.midiClocksPerMetronomeClick),t.set("thirdySecondNodesInQuarter",e.thirtySecondNodesInQuarter);break;case it.AlphaTabRest:t.set("channel",e.channel);break;case it.AlphaTabMetronome:t.set("metronomeNumerator",e.metronomeNumerator),t.set("metronomeDurationInMilliseconds",e.metronomeDurationInMilliseconds),t.set("metronomeDurationInTicks",e.metronomeDurationInTicks);break;case it.NoteOn:case it.NoteOff:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("noteVelocity",e.noteVelocity);break;case it.ControlChange:t.set("channel",e.channel),t.set("controller",e.controller),t.set("value",e.value);break;case it.ProgramChange:t.set("channel",e.channel),t.set("program",e.program);break;case it.TempoChange:t.set("microSecondsPerQuarterNote",e.microSecondsPerQuarterNote);break;case it.PitchBend:t.set("channel",e.channel),t.set("value",e.value);break;case it.PerNotePitchBend:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("value",e.value);case it.EndOfTrack:}return t}}const Fs=Object.freeze(Object.defineProperty({__proto__:null,get AccentuationType(){return S},get AccidentalType(){return tt},Automation:ie,get AutomationType(){return d},Bar:te,BarStyle:ee,get BarSubElement(){return c},get BarreShape(){return z},Beat:xe,get BeatBeamingMode(){return J},BeatStyle:Ne,get BeatSubElement(){return Y},BendPoint:ae,get BendStyle(){return u},get BendType(){return p},get BracketExtendMode(){return s},get BrushType(){return g},Chord:ut,get Clef(){return n},Color:Ae,get CrescendoType(){return m},get Direction(){return qe},get Duration(){return f},get DynamicValue(){return y},ElementStyle:Q,get FadeType(){return G},Fermata:Tt,get FermataType(){return Ke},get Fingers(){return _},Font:We,get FontStyle(){return Fe},get FontWeight(){return De},get GolpeType(){return V},GraceGroup:Te,get GraceType(){return b},get HarmonicType(){return w},InstrumentArticulation:ge,JsonConverter:Es,get KeySignature(){return F},get KeySignatureType(){return D},Lyrics:pt,MasterBar:le,get MusicFontSymbol(){return I},Note:be,get NoteAccidentalMode(){return B},get NoteOrnament(){return O},NoteStyle:ye,get NoteSubElement(){return H},get Ottavia(){return o},get PickStroke(){return L},PlaybackInformation:mt,get Rasgueado(){return X},RenderStylesheet:K,RepeatGroup:j,Score:lt,ScoreStyle:ht,get ScoreSubElement(){return Je},Section:gt,get SimileMark(){return h},get SlideInType(){return k},get SlideOutType(){return T},Staff:yt,SustainPedalMarker:Z,get SustainPedalMarkerType(){return l},Track:St,get TrackNameMode(){return a},get TrackNameOrientation(){return r},get TrackNamePolicy(){return i},TrackStyle:bt,get TrackSubElement(){return $e},get TripletFeel(){return M},Tuning:ft,TupletGroup:Se,get VibratoType(){return N},Voice:Pe,VoiceStyle:ve,get VoiceSubElement(){return $},get WahPedal(){return U},get WhammyType(){return W}},Symbol.toStringTag,{value:"Module"}));class Ds extends ct{constructor(){super(...arguments),this._versionNumber=0,this._globalTripletFeel=M.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._beatTextChunksByTrack=new Map,this._directionLookup=new Map}get name(){return"Guitar Pro 3-5"}readScore(){if(this._directionLookup.clear(),this.readVersion(),this._score=new lt,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=Ms.gpReadBool(this.data)?M.Triplet8th:M.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=wt.readInt32LE(this.data),this._versionNumber>=510&&Ms.gpReadBool(this.data),wt.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.readDirection(qe.TargetCoda),this.readDirection(qe.TargetDoubleCoda),this.readDirection(qe.TargetSegno),this.readDirection(qe.TargetSegnoSegno),this.readDirection(qe.TargetFine),this.readDirection(qe.JumpDaCapo),this.readDirection(qe.JumpDaCapoAlCoda),this.readDirection(qe.JumpDaCapoAlDoubleCoda),this.readDirection(qe.JumpDaCapoAlFine),this.readDirection(qe.JumpDalSegno),this.readDirection(qe.JumpDalSegnoAlCoda),this.readDirection(qe.JumpDalSegnoAlDoubleCoda),this.readDirection(qe.JumpDalSegnoAlFine),this.readDirection(qe.JumpDalSegnoSegno),this.readDirection(qe.JumpDalSegnoSegnoAlCoda),this.readDirection(qe.JumpDalSegnoSegnoAlDoubleCoda),this.readDirection(qe.JumpDalSegnoSegnoAlFine),this.readDirection(qe.JumpDaCoda),this.readDirection(qe.JumpDaDoubleCoda),this.data.skip(4)),this._barCount=wt.readInt32LE(this.data),this._trackCount=wt.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0){const e=ie.buildTempoAutomation(!1,0,this._score.tempo,2);e.text=this._score.tempoLabel,this._score.masterBars[0].tempoAutomations.push(e)}return this._score.finish(this.settings),this._lyrics&&this._lyricsTrack>=0&&this._score.tracks[this._lyricsTrack].applyLyrics(this._lyrics),this._score}readDirection(e){let t,s=wt.readInt16LE(this.data);-1!==s&&(s--,this._directionLookup.has(s)?t=this._directionLookup.get(s):(t=[],this._directionLookup.set(s,t)),t.push(e))}readVersion(){let e=Ms.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(Ds.VersionString))throw new dt("Unsupported format");e=e.substr(Ds.VersionString.length+1);const t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*Number.parseInt(e.substr(0,t))+Number.parseInt(e.substr(t+1)),he.debug(this.name,`Guitar Pro version ${e} detected`)}readScoreInformation(){this._score.title=Ms.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=Ms.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=Ms.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=Ms.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=Ms.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?Ms.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=Ms.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=Ms.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=Ms.gpReadStringIntUnused(this.data,this.settings.importer.encoding);const e=wt.readInt32LE(this.data);let t="";for(let s=0;s<e;s++)s>0&&(t+="\r\n"),t+=Ms.gpReadStringIntUnused(this.data,this.settings.importer.encoding)?.toString();this._score.notices=t}readLyrics(){this._lyrics=[],this._lyricsTrack=wt.readInt32LE(this.data)-1;for(let e=0;e<5;e++){const e=new pt;e.startBar=wt.readInt32LE(this.data)-1,e.text=Ms.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(28);const e=wt.readInt16LE(this.data);ue.getOrCreateHeaderFooterStyle(this._score,Je.Title).isVisible=!!(1&e),ue.getOrCreateHeaderFooterStyle(this._score,Je.Title).template=Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding),ue.getOrCreateHeaderFooterStyle(this._score,Je.SubTitle).isVisible=!!(2&e),ue.getOrCreateHeaderFooterStyle(this._score,Je.SubTitle).template=Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding),ue.getOrCreateHeaderFooterStyle(this._score,Je.Artist).isVisible=!!(4&e),ue.getOrCreateHeaderFooterStyle(this._score,Je.Artist).template=Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding),ue.getOrCreateHeaderFooterStyle(this._score,Je.Album).isVisible=!!(8&e),ue.getOrCreateHeaderFooterStyle(this._score,Je.Album).template=Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding),ue.getOrCreateHeaderFooterStyle(this._score,Je.Words).isVisible=!!(16&e),ue.getOrCreateHeaderFooterStyle(this._score,Je.Words).template=Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding),ue.getOrCreateHeaderFooterStyle(this._score,Je.Music).isVisible=!!(32&e),ue.getOrCreateHeaderFooterStyle(this._score,Je.Music).template=Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding),ue.getOrCreateHeaderFooterStyle(this._score,Je.WordsAndMusic).isVisible=!!(64&e),ue.getOrCreateHeaderFooterStyle(this._score,Je.WordsAndMusic).template=Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding),ue.getOrCreateHeaderFooterStyle(this._score,Je.Copyright).isVisible=!!(128&e),ue.getOrCreateHeaderFooterStyle(this._score,Je.Copyright).template=Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding),ue.getOrCreateHeaderFooterStyle(this._score,Je.CopyrightSecondLine).isVisible=!!(128&e),ue.getOrCreateHeaderFooterStyle(this._score,Je.CopyrightSecondLine).template=Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding),Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){const t=new mt;t.primaryChannel=e,t.secondaryChannel=e,t.program=wt.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]);const t=new le,s=this.data.readByte();if(1&s?t.timeSignatureNumerator=this.data.readByte():e&&(t.timeSignatureNumerator=e.timeSignatureNumerator),2&s?t.timeSignatureDenominator=this.data.readByte():e&&(t.timeSignatureDenominator=e.timeSignatureDenominator),t.isRepeatStart=!!(4&s),8&s&&(t.repeatCount=this.data.readByte()+(this._versionNumber>=500?0:1)),16&s&&this._versionNumber<500){let s=e,i=0;for(;s&&(!s.isRepeatEnd||s===e)&&!s.isRepeatStart;)i|=s.alternateEndings,s=s.previousMasterBar;let a=0;const r=this.data.readByte();for(let e=0;e<8;e++){const t=1<<e;r>e&&!(i&t)&&(a|=t)}t.alternateEndings=a}if(32&s){const e=new gt;e.text=Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",Ms.gpReadColor(this.data,!1),t.section=e}if(64&s?(t.keySignature=wt.readSInt8(this.data),t.keySignatureType=this.data.readByte()):e&&(t.keySignature=e.keySignature,t.keySignatureType=e.keySignatureType),this._versionNumber>=500&&3&s&&this.data.skip(4),this._versionNumber>=500&&(t.alternateEndings=this.data.readByte()),this._versionNumber>=500){switch(this.data.readByte()){case 1:t.tripletFeel=M.Triplet8th;break;case 2:t.tripletFeel=M.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;t.isDoubleBar=!!(128&s);const i=this._score.masterBars.length;if(this._directionLookup.has(i))for(const e of this._directionLookup.get(i))t.addDirection(e);this._score.addMasterBar(t)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){const e=new St;e.ensureStaveCount(1),this._score.addTrack(e);const t=e.staves[0],s=this.data.readByte();e.name=Ms.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),1&s&&(t.isPercussion=!0),this._versionNumber>=500&&(e.isVisibleOnMultiTrack=!!(8&s)),null===this._score.stylesheet.perTrackDisplayTuning&&(this._score.stylesheet.perTrackDisplayTuning=new Map),this._score.stylesheet.perTrackDisplayTuning.set(e.index,!!(128&s));const i=wt.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){const t=wt.readInt32LE(this.data);i>e&&a.push(t)}t.stringTuning.tunings=a;const r=wt.readInt32LE(this.data),n=wt.readInt32LE(this.data)-1,o=wt.readInt32LE(this.data)-1;if(this.data.skip(4),n>=0&&n<this._playbackInfos.length){const i=this._playbackInfos[n];i.port=r,i.isSolo=!!(16&s),i.isMute=!!(32&s),i.secondaryChannel=o,q.isGuitar(i.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=i}if(t.capo=wt.readInt32LE(this.data),e.color=Ms.gpReadColor(this.data,!1),this._versionNumber>=500){const s=this.data.readByte();t.showTablature=!!(1&s),t.showStandardNotation=!!(2&s);const i=!!(100&s);null===this._score.stylesheet.perTrackChordDiagramsOnTop&&(this._score.stylesheet.perTrackChordDiagramsOnTop=new Map),this._score.stylesheet.perTrackChordDiagramsOnTop.set(e.index,i),this.data.readByte(),this.data.skip(43)}this._versionNumber>=510&&(this.data.skip(4),Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding),Ms.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){const t=new te,s=e.staves[0];s.isPercussion&&(t.clef=n.Neutral),s.addBar(t);let i=1;this._versionNumber>=500&&(this.data.readByte(),i=2);for(let s=0;s<i;s++)this.readVoice(e,t)}readVoice(e,t){const s=wt.readInt32LE(this.data);if(0===s)return;const i=new Pe;t.addVoice(i);for(let a=0;a<s;a++)this.readBeat(e,t,i)}readBeat(e,t,s){const i=new xe,a=this.data.readByte();if(1&a&&(i.dots=1),64&a){const e=this.data.readByte();i.isEmpty=!(2&e)}s.addBeat(i);switch(wt.readSInt8(this.data)){case-2:i.duration=f.Whole;break;case-1:i.duration=f.Half;break;case 0:i.duration=f.Quarter;break;case 1:i.duration=f.Eighth;break;case 2:i.duration=f.Sixteenth;break;case 3:i.duration=f.ThirtySecond;break;case 4:i.duration=f.SixtyFourth;break;default:i.duration=f.Quarter}if(32&a)switch(i.tupletNumerator=wt.readInt32LE(this.data),i.tupletNumerator){case 1:i.tupletDenominator=1;break;case 3:i.tupletDenominator=2;break;case 5:case 6:case 7:i.tupletDenominator=4;break;case 9:case 10:case 11:case 12:case 13:i.tupletDenominator=8;break;case 2:case 4:case 8:break;default:i.tupletNumerator=1,i.tupletDenominator=1}2&a&&this.readChord(i);const r=this.settings.importer.beatTextAsLyrics&&e.index!==this._lyricsTrack;if(4&a){const t=Ms.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const s=new pt;s.text=t.trim(),s.finish(!0);const i=[];for(let e=s.chunks.length-1;e>=0;e--)i.push(s.chunks[e]);this._beatTextChunksByTrack.set(e.index,i)}else i.text=t}let n=w.None;8&a&&(n=this.readBeatEffects(i)),16&a&&this.readMixTableChange(i);const h=this.data.readByte();for(let a=6;a>=0;a--)if(h&1<<a&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,s,i,6-a);n!==w.None&&(r.harmonicType=n,r.harmonicType===w.Natural&&(r.harmonicValue=ue.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){const e=wt.readInt16LE(this.data);if(1&e&&i.index>0&&(s.beats[i.index-1].beamingMode=J.ForceSplitToNext),2&e&&(i.preferredBeamDirection=je.Down),4&e&&i.index>0&&(s.beats[i.index-1].beamingMode=J.ForceMergeWithNext),8&e&&(i.preferredBeamDirection=je.Up),16&e&&(i.ottava=o._8va),32&e&&(i.ottava=o._8vb),64&e&&(i.ottava=o._15ma),256&e&&(i.ottava=o._15mb),2048&e){const e=0!==this.data.readByte();i.index>0&&e&&(s.beats[i.index-1].beamingMode=J.ForceSplitOnSecondaryToNext)}}r&&!i.isRest&&this._beatTextChunksByTrack.has(e.index)&&this._beatTextChunksByTrack.get(e.index).length>0&&(i.lyrics=[this._beatTextChunksByTrack.get(e.index).pop()])}readChord(e){const t=new ut,s=ue.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=Ms.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=wt.readInt32LE(this.data);for(let s=0;s<7;s++){const i=wt.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}const s=this.data.readByte(),i=new Uint8Array(5);this.data.read(i,0,i.length);for(let e=0;e<s;e++)t.barreFrets.push(i[e]);this.data.skip(26)}else if(0!==this.data.readByte())if(this._versionNumber>=400){this.data.skip(16),t.name=Ms.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=wt.readInt32LE(this.data);for(let s=0;s<7;s++){const i=wt.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}const s=this.data.readByte(),i=new Uint8Array(5);this.data.read(i,0,i.length);for(let e=0;e<s;e++)t.barreFrets.push(i[e]);this.data.skip(26)}else{this.data.skip(25),t.name=Ms.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=wt.readInt32LE(this.data);for(let s=0;s<6;s++){const i=wt.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}this.data.skip(36)}else{const s=this._versionNumber>=406?7:6;if(t.name=Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=wt.readInt32LE(this.data),t.firstFret>0)for(let i=0;i<s;i++){const s=wt.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}}t.name&&(e.chordId=s,e.voice.bar.staff.addChord(e.chordId,t))}readBeatEffects(e){const t=this.data.readByte();let s=0;if(this._versionNumber>=400&&(s=this.data.readByte()),16&t&&(e.fade=G.FadeIn),(this._versionNumber<400&&1&t||2&t)&&(e.vibrato=N.Slight),1&s&&(e.rasgueado=X.Ii),32&t&&this._versionNumber>=400){switch(wt.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}}else if(32&t){switch(wt.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}this.data.skip(4)}if(4&s&&this.readTremoloBarEffect(e),64&t){let t=0,s=0;this._versionNumber<500?(s=this.data.readByte(),t=this.data.readByte()):(t=this.data.readByte(),s=this.data.readByte()),t>0?(e.brushType=g.BrushUp,e.brushDuration=Ds.toStrokeValue(t)):s>0&&(e.brushType=g.BrushDown,e.brushDuration=Ds.toStrokeValue(s))}if(2&s)switch(wt.readSInt8(this.data)){case 0:e.pickStroke=L.None;break;case 1:e.pickStroke=L.Up;break;case 2:e.pickStroke=L.Down}if(this._versionNumber<400){if(4&t)return w.Natural;if(8&t)return w.Artificial}return w.None}readTremoloBarEffect(e){this.data.readByte(),wt.readInt32LE(this.data);const t=wt.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){const t=new ae(0,0);t.offset=wt.readInt32LE(this.data),t.value=wt.readInt32LE(this.data)/Ds.BendStep|0,Ms.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){const t=new Ls;t.instrument=wt.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=wt.readSInt8(this.data),t.balance=wt.readSInt8(this.data);const s=wt.readSInt8(this.data),i=wt.readSInt8(this.data),a=wt.readSInt8(this.data),r=wt.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=wt.readInt32LE(this.data),t.volume>=0&&this.data.readByte(),t.balance>=0&&this.data.readByte(),s>=0&&this.data.readByte(),i>=0&&this.data.readByte(),a>=0&&this.data.readByte(),r>=0&&this.data.readByte(),t.tempo>=0&&(t.duration=wt.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500){const t=wt.readSInt8(this.data);t>=100?e.wahPedal=U.Closed:t>=0&&(e.wahPedal=U.Open)}if(this._versionNumber>=510&&(Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding),Ms.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){const s=new ie;s.isLinear=!0,s.type=d.Volume,s.value=t.volume,e.automations.push(s)}if(t.balance>=0){const s=new ie;s.isLinear=!0,s.type=d.Balance,s.value=t.balance,e.automations.push(s)}if(t.instrument>=0){const s=new ie;s.isLinear=!0,s.type=d.Instrument,s.value=t.instrument,e.automations.push(s)}if(t.tempo>=0){const s=new ie;s.isLinear=!0,s.type=d.Tempo,s.value=t.tempo,e.automations.push(s),e.voice.bar.masterBar.tempoAutomations.push(s)}}readNote(e,t,s,i,a){const r=new be;r.string=t.staff.tuning.length-a;const n=this.data.readByte();if(2&n?r.accentuated=S.Heavy:64&n&&(r.accentuated=S.Normal),r.isGhost=!!(4&n),32&n){const e=this.data.readByte();3===e?r.isDead=!0:2===e&&(r.isTieDestination=!0)}if(1&n&&this._versionNumber<500&&(this.data.readByte(),this.data.readByte()),16&n){const e=wt.readSInt8(this.data);r.dynamics=this.toDynamicValue(e),i.dynamics=r.dynamics}32&n&&(r.fret=wt.readSInt8(this.data)),128&n&&(r.leftHandFinger=wt.readSInt8(this.data),r.rightHandFinger=wt.readSInt8(this.data));let o=!1;if(this._versionNumber>=500){1&n&&(r.durationPercent=wt.readFloat64BE(this.data));o=!!(2&this.data.readByte())}if(i.addNote(r),8&n&&this.readNoteEffects(e,s,i,r),t.staff.isPercussion&&(r.percussionArticulation=r.fret,r.string=-1,r.fret=-1),o){const e=ft.defaultAccidentals[r.realValueWithoutHarmonic%12];"#"===e?r.accidentalMode=B.ForceFlat:"b"===e&&(r.accidentalMode=B.ForceSharp)}return r}toDynamicValue(e){switch(e){case 1:return y.PPP;case 2:return y.PP;case 3:return y.P;case 4:return y.MP;case 5:return y.MF;case 6:default:return y.F;case 7:return y.FF;case 8:return y.FFF}}readNoteEffects(e,t,s,i){const a=this.data.readByte();let r=0;this._versionNumber>=400&&(r=this.data.readByte()),1&a&&this.readBend(i),16&a&&this.readGrace(t,i),4&r&&this.readTremoloPicking(s),8&r?this.readSlide(i):this._versionNumber<400&&4&a&&(i.slideOutType=T.Shift),16&r&&this.readArtificialHarmonic(i),32&r&&this.readTrill(i),i.isLetRing=!!(8&a),i.isHammerPullOrigin=!!(2&a),64&r&&(i.vibrato=N.Slight),i.isPalmMute=!!(2&r),i.isStaccato=!!(1&r)}readBend(e){this.data.readByte(),wt.readInt32LE(this.data);const t=wt.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){const t=new ae(0,0);t.offset=wt.readInt32LE(this.data),t.value=wt.readInt32LE(this.data)/Ds.BendStep|0,Ms.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){const s=new xe,i=new be;i.string=t.string,i.fret=wt.readSInt8(this.data),s.duration=f.ThirtySecond,s.dynamics=this.toDynamicValue(wt.readSInt8(this.data));switch(wt.readSInt8(this.data)){case 0:case 2:break;case 1:i.slideOutType=T.Legato,i.slideTarget=t;break;case 3:i.isHammerPullOrigin=!0}if(i.dynamics=s.dynamics,this.data.skip(1),this._versionNumber<500)s.graceType=b.BeforeBeat;else{const e=this.data.readByte();i.isDead=!!(1&e),s.graceType=2&e?b.OnBeat:b.BeforeBeat}e.addGraceBeat(s),s.addNote(i)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=f.Eighth;break;case 2:e.tremoloSpeed=f.Sixteenth;break;case 3:e.tremoloSpeed=f.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){const t=wt.readSInt8(this.data);1&t?e.slideOutType=T.Shift:2&t?e.slideOutType=T.Legato:4&t?e.slideOutType=T.OutDown:8&t&&(e.slideOutType=T.OutUp),16&t?e.slideInType=k.IntoFromBelow:32&t&&(e.slideInType=k.IntoFromAbove)}else{switch(wt.readSInt8(this.data)){case 1:e.slideOutType=T.Shift;break;case 2:e.slideOutType=T.Legato;break;case 3:e.slideOutType=T.OutDown;break;case 4:e.slideOutType=T.OutUp;break;case-1:e.slideInType=k.IntoFromBelow;break;case-2:e.slideInType=k.IntoFromAbove}}}readArtificialHarmonic(e){const t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=w.Natural,e.harmonicValue=ue.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=w.Artificial;break;case 3:e.harmonicType=w.Tap,e.harmonicValue=ue.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=w.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=w.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=w.Natural;break;case 3:e.harmonicType=w.Tap;break;case 4:e.harmonicType=w.Pinch;break;case 5:e.harmonicType=w.Semi;break;case 15:case 17:case 22:e.harmonicType=w.Artificial}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=f.Sixteenth;break;case 2:e.trillSpeed=f.ThirtySecond;break;case 3:e.trillSpeed=f.SixtyFourth}}}Ds.VersionString="FICHIER GUITAR PRO ",Ds.BendStep=25;class Ms{static gpReadColor(e,t=!1){const s=e.readByte(),i=e.readByte(),a=e.readByte();let r=255;return t?r=e.readByte():e.skip(1),new Ae(s,i,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),Ms.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return Ms.gpReadString(e,wt.readInt32LE(e),t)}static gpReadStringIntByte(e,t){const s=wt.readInt32LE(e)-1;return e.readByte(),Ms.gpReadString(e,s,t)}static gpReadString(e,t,s){const i=new Uint8Array(t);return e.read(i,0,i.length),wt.toString(i,s)}static gpWriteString(e,t){const s=wt.stringToBytes(t);e.writeByte(t.length),e.write(s,0,s.length)}static gpReadStringByteLength(e,t,s){const i=e.readByte(),a=Ms.gpReadString(e,i,s);return i<t&&e.skip(t-i),a}}class Ls{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class Is{constructor(){this.x=0,this.y=0,this.w=0,this.h=0}scaleWith(e){this.x*=e,this.y*=e,this.w*=e,this.h*=e}}var As,Rs,Os;!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"}(As||(As={}));class Hs{constructor(e){this._types=new Map,this.raw=new Map,e&&this.read(e)}read(e){const t=Bt.fromBuffer(e),s=wt.readInt32BE(t);for(let e=0;e<s;e++){const e=Ms.gpReadString(t,t.readByte(),"utf-8"),s=t.readByte();switch(this._types.set(e,s),s){case As.Boolean:const s=1===t.readByte();this.addValue(e,s);break;case As.Integer:const i=wt.readInt32BE(t);this.addValue(e,i);break;case As.Float:const a=wt.readFloat32BE(t);this.addValue(e,a);break;case As.String:const r=Ms.gpReadString(t,wt.readInt16BE(t),"utf-8");this.addValue(e,r);break;case As.Point:const n=wt.readInt32BE(t),o=wt.readInt32BE(t);this.addValue(e,new ae(n,o));break;case As.Size:const h=wt.readInt32BE(t),l=wt.readInt32BE(t);this.addValue(e,new ae(h,l));break;case As.Rectangle:const c=new Is;c.x=wt.readInt32BE(t),c.y=wt.readInt32BE(t),c.w=wt.readInt32BE(t),c.h=wt.readInt32BE(t),this.addValue(e,c);break;case As.Color:const d=Ms.gpReadColor(t,!0);this.addValue(e,d)}}}apply(e){for(const[t,s]of this.raw)switch(t){case"StandardNotation/hideDynamics":e.stylesheet.hideDynamics=s;break;case"System/bracketExtendMode":e.stylesheet.bracketExtendMode=s;break;case"Global/useSystemSignSeparator":e.stylesheet.useSystemSignSeparator=s;break;case"Global/DisplayTuning":e.stylesheet.globalDisplayTuning=s;break;case"Global/DrawChords":e.stylesheet.globalDisplayChordDiagramsOnTop=s;break;case"System/showTrackNameSingle":s||(e.stylesheet.singleTrackTrackNamePolicy=i.Hidden);break;case"System/showTrackNameMulti":s||(e.stylesheet.multiTrackTrackNamePolicy=i.Hidden);break;case"System/trackNameModeSingle":if(e.stylesheet.singleTrackTrackNamePolicy!==i.Hidden)switch(s){case 0:case 1:e.stylesheet.singleTrackTrackNamePolicy=i.FirstSystem;break;case 2:e.stylesheet.singleTrackTrackNamePolicy=i.AllSystems}break;case"System/trackNameModeMulti":if(e.stylesheet.multiTrackTrackNamePolicy!==i.Hidden)switch(s){case 0:case 1:e.stylesheet.multiTrackTrackNamePolicy=i.FirstSystem;break;case 2:e.stylesheet.multiTrackTrackNamePolicy=i.AllSystems}break;case"System/shortTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameMode=s?a.ShortName:a.FullName;break;case"System/shortTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameMode=s?a.ShortName:a.FullName;break;case"System/horizontalTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameOrientation=s?r.Horizontal:r.Vertical;break;case"System/horizontalTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameOrientation=s?r.Horizontal:r.Vertical;break;case"Header/Title":ue.getOrCreateHeaderFooterStyle(e,Je.Title).template=s;break;case"Header/TitleAlignment":ue.getOrCreateHeaderFooterStyle(e,Je.Title).textAlign=this.toTextAlign(s);break;case"Header/drawTitle":ue.getOrCreateHeaderFooterStyle(e,Je.Title).isVisible=s;break;case"Header/Subtitle":ue.getOrCreateHeaderFooterStyle(e,Je.SubTitle).template=s;break;case"Header/SubtitleAlignment":ue.getOrCreateHeaderFooterStyle(e,Je.SubTitle).textAlign=this.toTextAlign(s);break;case"Header/drawSubtitle":ue.getOrCreateHeaderFooterStyle(e,Je.SubTitle).isVisible=s;break;case"Header/Artist":ue.getOrCreateHeaderFooterStyle(e,Je.Artist).template=s;break;case"Header/ArtistAlignment":ue.getOrCreateHeaderFooterStyle(e,Je.Artist).textAlign=this.toTextAlign(s);break;case"Header/drawArtist":ue.getOrCreateHeaderFooterStyle(e,Je.Artist).isVisible=s;break;case"Header/Album":ue.getOrCreateHeaderFooterStyle(e,Je.Album).template=s;break;case"Header/AlbumAlignment":ue.getOrCreateHeaderFooterStyle(e,Je.Album).textAlign=this.toTextAlign(s);break;case"Header/drawAlbum":ue.getOrCreateHeaderFooterStyle(e,Je.Album).isVisible=s;break;case"Header/Words":ue.getOrCreateHeaderFooterStyle(e,Je.Words).template=s;break;case"Header/WordsAlignment":ue.getOrCreateHeaderFooterStyle(e,Je.Words).textAlign=this.toTextAlign(s);break;case"Header/drawWords":ue.getOrCreateHeaderFooterStyle(e,Je.Words).isVisible=s;break;case"Header/Music":ue.getOrCreateHeaderFooterStyle(e,Je.Music).template=s;break;case"Header/MusicAlignment":ue.getOrCreateHeaderFooterStyle(e,Je.Music).textAlign=this.toTextAlign(s);break;case"Header/drawMusic":ue.getOrCreateHeaderFooterStyle(e,Je.Music).isVisible=s;break;case"Header/WordsAndMusic":ue.getOrCreateHeaderFooterStyle(e,Je.WordsAndMusic).template=s;break;case"Header/WordsAndMusicAlignment":ue.getOrCreateHeaderFooterStyle(e,Je.WordsAndMusic).textAlign=this.toTextAlign(s);break;case"Header/drawWordsAndMusic":ue.getOrCreateHeaderFooterStyle(e,Je.WordsAndMusic).isVisible=s;break;case"Header/Tabber":ue.getOrCreateHeaderFooterStyle(e,Je.Transcriber).template=s;break;case"Header/TabberAlignment":ue.getOrCreateHeaderFooterStyle(e,Je.Transcriber).textAlign=this.toTextAlign(s);break;case"Header/drawTabber":ue.getOrCreateHeaderFooterStyle(e,Je.Transcriber).isVisible=s;break;case"Footer/Copyright":ue.getOrCreateHeaderFooterStyle(e,Je.Copyright).template=s;break;case"Footer/CopyrightAlignment":ue.getOrCreateHeaderFooterStyle(e,Je.Copyright).textAlign=this.toTextAlign(s);break;case"Footer/drawCopyright":ue.getOrCreateHeaderFooterStyle(e,Je.Copyright).isVisible=s;break;case"Footer/Copyright2":ue.getOrCreateHeaderFooterStyle(e,Je.CopyrightSecondLine).template=s;break;case"Footer/Copyright2Alignment":ue.getOrCreateHeaderFooterStyle(e,Je.CopyrightSecondLine).textAlign=this.toTextAlign(s);break;case"Footer/drawCopyright2":ue.getOrCreateHeaderFooterStyle(e,Je.CopyrightSecondLine).isVisible=s}}toTextAlign(e){switch(e){case 0:return A.Left;case 1:return A.Center;case 2:return A.Right}return A.Left}addValue(e,t,s){this.raw.set(e,t),void 0!==s&&this._types.set(e,s)}writeTo(e){wt.writeInt32BE(e,this.raw.size);for(const[t,s]of this.raw){const i=this.getDataType(t,s);switch(Ms.gpWriteString(e,t),e.writeByte(i),i){case As.Boolean:e.writeByte(s?1:0);break;case As.Integer:wt.writeInt32BE(e,s);break;case As.Float:wt.writeFloat32BE(e,s);break;case As.String:const t=wt.stringToBytes(s);wt.writeInt16BE(e,t.length),e.write(t,0,t.length);break;case As.Point:case As.Size:wt.writeInt32BE(e,s.offset),wt.writeInt32BE(e,s.value);break;case As.Rectangle:wt.writeInt32BE(e,s.x),wt.writeInt32BE(e,s.y),wt.writeInt32BE(e,s.w),wt.writeInt32BE(e,s.h);break;case As.Color:e.writeByte(s.r),e.writeByte(s.g),e.writeByte(s.b),e.writeByte(s.a)}}}getDataType(e,t){if(this._types.has(e))return this._types.get(e);const s=typeof t;switch(typeof t){case"string":return As.String;case"number":return t===(0|t)?As.Integer:As.Float;case"object":if(t instanceof ae)return As.Point;if(t instanceof Is)return As.Rectangle;if(t instanceof Ae)return As.Color}throw new Le(Ee.General,`Unknown value type in BinaryStylesheet: ${s}`)}static writeForScore(e){const t=new Hs;switch(t.addValue("StandardNotation/hideDynamics",e.stylesheet.hideDynamics,As.Boolean),t.addValue("System/bracketExtendMode",e.stylesheet.bracketExtendMode,As.Integer),t.addValue("Global/useSystemSignSeparator",e.stylesheet.useSystemSignSeparator,As.Boolean),t.addValue("Global/DisplayTuning",e.stylesheet.globalDisplayTuning,As.Boolean),t.addValue("Global/DrawChords",e.stylesheet.globalDisplayChordDiagramsOnTop,As.Boolean),e.stylesheet.singleTrackTrackNamePolicy){case i.Hidden:t.addValue("System/showTrackNameSingle",!1,As.Boolean);break;case i.FirstSystem:t.addValue("System/trackNameModeSingle",0,As.Integer);break;case i.AllSystems:t.addValue("System/trackNameModeSingle",2,As.Integer)}switch(e.stylesheet.multiTrackTrackNamePolicy){case i.Hidden:t.addValue("System/trackNameModeMulti",!1,As.Boolean);break;case i.FirstSystem:t.addValue("System/trackNameModeMulti",0,As.Integer);break;case i.AllSystems:t.addValue("System/trackNameModeMulti",2,As.Integer)}switch(e.stylesheet.firstSystemTrackNameMode){case a.FullName:t.addValue("System/shortTrackNameOnFirstSystem",!1,As.Boolean);break;case a.ShortName:t.addValue("System/shortTrackNameOnFirstSystem",!0,As.Boolean)}switch(e.stylesheet.otherSystemsTrackNameMode){case a.FullName:t.addValue("System/shortTrackNameOnOtherSystems",!1,As.Boolean);break;case a.ShortName:t.addValue("System/shortTrackNameOnOtherSystems",!0,As.Boolean)}switch(e.stylesheet.firstSystemTrackNameOrientation){case r.Horizontal:t.addValue("System/horizontalTrackNameOnFirstSystem",!0,As.Boolean);break;case r.Vertical:t.addValue("System/horizontalTrackNameOnFirstSystem",!1,As.Boolean)}switch(e.stylesheet.otherSystemsTrackNameOrientation){case r.Horizontal:t.addValue("System/horizontalTrackNameOnOtherSystems",!0,As.Boolean);break;case r.Vertical:t.addValue("System/horizontalTrackNameOnOtherSystems",!1,As.Boolean)}const s=e.style;if(s)for(const[e,i]of s.headerAndFooter)switch(e){case Je.Title:Hs.addHeaderAndFooter(t,i,"Header/","Title");break;case Je.SubTitle:Hs.addHeaderAndFooter(t,i,"Header/","Subtitle");break;case Je.Artist:Hs.addHeaderAndFooter(t,i,"Header/","Artist");break;case Je.Album:Hs.addHeaderAndFooter(t,i,"Header/","Album");break;case Je.Words:Hs.addHeaderAndFooter(t,i,"Header/","Words");break;case Je.Music:Hs.addHeaderAndFooter(t,i,"Header/","Music");break;case Je.WordsAndMusic:Hs.addHeaderAndFooter(t,i,"Header/","WordsAndMusic");break;case Je.Transcriber:Hs.addHeaderAndFooter(t,i,"Header/","Tabber");break;case Je.Copyright:Hs.addHeaderAndFooter(t,i,"Footer/","Copyright");break;case Je.CopyrightSecondLine:Hs.addHeaderAndFooter(t,i,"Footer/","Copyright2")}const n=Bt.withCapacity(128);return t.writeTo(n),n.toArray()}static addHeaderAndFooter(e,t,s,i){void 0!==t.template&&e.addValue(`${s}${i}`,t.template,As.String),e.addValue(`${s}${i}Alignment`,t.textAlign,As.Integer),void 0!==t.isVisible&&e.addValue(`${s}draw${i}`,t.isVisible,As.Boolean)}}!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"}(Rs||(Rs={}));class Ws{constructor(){this.nodeType=Rs.None,this.localName=null,this.value=null,this.childNodes=[],this.attributes=new Map,this.firstChild=null,this.firstElement=null}*childElements(){for(const e of this.childNodes)e.nodeType===Rs.Element&&(yield e)}addChild(e){this.childNodes.push(e),this.firstChild=e,e.nodeType!==Rs.Element&&e.nodeType!==Rs.CDATA||(this.firstElement=e)}getAttribute(e,t=""){return this.attributes.has(e)?this.attributes.get(e):t}getElementsByTagName(e,t=!1){const s=[];return this.searchElementsByTagName(this.childNodes,s,e,t),s}searchElementsByTagName(e,t,s,i=!1){for(const a of e)a&&a.nodeType===Rs.Element&&a.localName===s&&t.push(a),i&&this.searchElementsByTagName(a.childNodes,t,s,!0)}findChildElement(e){for(const t of this.childNodes)if(t&&t.nodeType===Rs.Element&&t.localName===e)return t;return null}addElement(e){const t=new Ws;return t.nodeType=Rs.Element,t.localName=e,this.addChild(t),t}get innerText(){if(this.nodeType===Rs.Element||this.nodeType===Rs.Document){if(this.firstElement&&this.firstElement.nodeType===Rs.CDATA)return this.firstElement.innerText;let e="";for(const t of this.childNodes)e+=t.innerText?.toString();return e.trim()}return this.value??""}set innerText(e){const t=new Ws;t.nodeType=Rs.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new Ws;t.nodeType=Rs.CDATA,t.value=e,this.childNodes=[t]}}class Vs extends Le{constructor(e,t,s){super(Ee.Format,e),this.pos=0,this.xml=t,this.pos=s,Object.setPrototypeOf(this,Vs.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"}(Os||(Os={}));class Gs{static parse(e,t,s){let i=e.charCodeAt(t),a=Os.Begin,r=Os.Begin,n=0,o="",h=Os.Begin,l=null,c=null,d=0,u=0;for(;t<e.length;){switch(i=e.charCodeAt(t),a){case Os.IgnoreSpaces:switch(i){case Gs.CharCodeLF:case Gs.CharCodeCR:case Gs.CharCodeTab:case Gs.CharCodeSpace:break;default:a=r;continue}break;case Os.Begin:if(i!==Gs.CharCodeLowerThan){n=t,a=Os.Pcdata;continue}a=Os.IgnoreSpaces,r=Os.BeginNode;break;case Os.Pcdata:if(i===Gs.CharCodeLowerThan){o+=e.substr(n,t-n);const i=new Ws;i.nodeType=Rs.Text,i.value=o,o="",s.addChild(i),a=Os.IgnoreSpaces,r=Os.BeginNode}else i===Gs.CharCodeAmp&&(o+=e.substr(n,t-n),a=Os.Escape,h=Os.Pcdata,n=t+1);break;case Os.Cdata:if(i===Gs.CharCodeBrackedClose&&e.charCodeAt(t+1)===Gs.CharCodeBrackedClose&&e.charCodeAt(t+2)===Gs.CharCodeGreaterThan){const i=new Ws;i.nodeType=Rs.CDATA,i.value=e.substr(n,t-n),s.addChild(i),t+=2,a=Os.Begin}break;case Os.BeginNode:switch(i){case Gs.CharCodeExclamation:if(e.charCodeAt(t+1)===Gs.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new Vs("Expected <![CDATA[",e,t);t+=5,a=Os.Cdata,n=t+1}else if(e.charCodeAt(t+1)===Gs.CharCodeUpperD||e.charCodeAt(t+1)===Gs.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new Vs("Expected <!DOCTYPE",e,t);t+=8,a=Os.Doctype,n=t+1}else{if(e.charCodeAt(t+1)!==Gs.CharCodeMinus||e.charCodeAt(t+2)!==Gs.CharCodeMinus)throw new Vs("Expected \x3c!--",e,t);t+=2,a=Os.Comment,n=t+1}break;case Gs.CharCodeQuestion:a=Os.Header,n=t;break;case Gs.CharCodeSlash:if(!s)throw new Vs("Expected node name",e,t);n=t+1,a=Os.IgnoreSpaces,r=Os.Close;break;default:a=Os.TagName,n=t;continue}break;case Os.TagName:if(!Gs.isValidChar(i)){if(t===n)throw new Vs("Expected node name",e,t);l=new Ws,l.nodeType=Rs.Element,l.localName=e.substr(n,t-n),s.addChild(l),a=Os.IgnoreSpaces,r=Os.Body;continue}break;case Os.Body:switch(i){case Gs.CharCodeSlash:a=Os.WaitEnd;break;case Gs.CharCodeGreaterThan:a=Os.Childs;break;default:a=Os.AttribName,n=t;continue}break;case Os.AttribName:if(!Gs.isValidChar(i)){if(n===t)throw new Vs("Expected attribute name",e,t);if(c=e.substr(n,t-n),l.attributes.has(c))throw new Vs(`Duplicate attribute [${c}]`,e,t);a=Os.IgnoreSpaces,r=Os.Equals;continue}break;case Os.Equals:if(i!==Gs.CharCodeEquals)throw new Vs("Expected =",e,t);a=Os.IgnoreSpaces,r=Os.AttvalBegin;break;case Os.AttvalBegin:switch(i){case Gs.CharCodeDoubleQuote:case Gs.CharCodeSingleQuote:o="",a=Os.AttribVal,n=t+1,u=i}break;case Os.AttribVal:if(i===Gs.CharCodeAmp)o+=e.substr(n,t-n),a=Os.Escape,h=Os.AttribVal,n=t+1;else if(i===u){o+=e.substr(n,t-n);const s=o;o="",l.attributes.set(c,s),a=Os.IgnoreSpaces,r=Os.Body}break;case Os.Childs:n=t=Gs.parse(e,t,l),a=Os.Begin;break;case Os.WaitEnd:if(i!==Gs.CharCodeGreaterThan)throw new Vs("Expected >",e,t);a=Os.Begin;break;case Os.WaitEndRet:if(i===Gs.CharCodeGreaterThan)return t;throw new Vs("Expected >",e,t);case Os.Close:if(!Gs.isValidChar(i)){if(n===t)throw new Vs("Expected node name",e,t);if(e.substr(n,t-n)!==s.localName)throw new Vs(`Expected </${s.localName}>`,e,t);a=Os.IgnoreSpaces,r=Os.WaitEndRet;continue}break;case Os.Comment:i===Gs.CharCodeMinus&&e.charCodeAt(t+1)===Gs.CharCodeMinus&&e.charCodeAt(t+2)===Gs.CharCodeGreaterThan&&(t+=2,a=Os.Begin);break;case Os.Doctype:if(i===Gs.CharCodeBrackedOpen)d++;else if(i===Gs.CharCodeBrackedClose)d--;else if(i===Gs.CharCodeGreaterThan&&0===d){const i=new Ws;i.nodeType=Rs.DocumentType,i.value=e.substr(n,t-n),s.addChild(i),a=Os.Begin}break;case Os.Header:i===Gs.CharCodeQuestion&&e.charCodeAt(t+1)===Gs.CharCodeGreaterThan&&(t++,a=Os.Begin);break;case Os.Escape:if(i===Gs.CharCodeSemi){const s=e.substr(n,t-n);if(s.charCodeAt(0)===Gs.CharCodeSharp){const e=s.charCodeAt(1)===Gs.CharCodeLowerX?Number.parseInt(`0${s.substr(1,s.length-1)}`):Number.parseInt(s.substr(1,s.length-1));o+=String.fromCharCode(e)}else Gs.Escapes.has(s)?o+=Gs.Escapes.get(s):o+=`&${s};`?.toString();n=t+1,a=h}else Gs.isValidChar(i)||i===Gs.CharCodeSharp||(o+="&",o+=e.substr(n,t-n),n=--t+1,a=h)}t++}if(a===Os.Begin&&(n=t,a=Os.Pcdata),a===Os.Pcdata){if(t!==n){o+=e.substr(n,t-n);const i=new Ws;i.nodeType=Rs.Text,i.value=o,s.addChild(i)}return t}if(a===Os.Escape&&h===Os.Pcdata){o+="&",o+=e.substr(n,t-n);const i=new Ws;return i.nodeType=Rs.Text,i.value=o,s.addChild(i),t}throw new Vs("Unexpected end",e,t)}static isValidChar(e){return e>=Gs.CharCodeLowerA&&e<=Gs.CharCodeLowerZ||e>=Gs.CharCodeUpperA&&e<=Gs.CharCodeUpperZ||e>=Gs.CharCode0&&e<=Gs.CharCode9||e===Gs.CharCodeColon||e===Gs.CharCodeDot||e===Gs.CharCodeUnderscore||e===Gs.CharCodeMinus}}Gs.CharCodeLF=10,Gs.CharCodeTab=9,Gs.CharCodeCR=13,Gs.CharCodeSpace=32,Gs.CharCodeLowerThan=60,Gs.CharCodeAmp=38,Gs.CharCodeBrackedClose=93,Gs.CharCodeBrackedOpen=91,Gs.CharCodeGreaterThan=62,Gs.CharCodeExclamation=33,Gs.CharCodeUpperD=68,Gs.CharCodeLowerD=100,Gs.CharCodeMinus=45,Gs.CharCodeQuestion=63,Gs.CharCodeSlash=47,Gs.CharCodeEquals=61,Gs.CharCodeDoubleQuote=34,Gs.CharCodeSingleQuote=39,Gs.CharCodeSharp=35,Gs.CharCodeLowerX=120,Gs.CharCodeLowerA=97,Gs.CharCodeLowerZ=122,Gs.CharCodeUpperA=65,Gs.CharCodeUpperZ=90,Gs.CharCode0=48,Gs.CharCode9=57,Gs.CharCodeColon=58,Gs.CharCodeDot=46,Gs.CharCodeUnderscore=95,Gs.CharCodeSemi=59,Gs.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class Us{static write(e,t,s){const i=new Us(t,s);return i.writeNode(e),i.toString()}constructor(e,t){this._result=[],this._indention=e,this._xmlHeader=t,this._currentIndention="",this._isStartOfLine=!0}writeNode(e){switch(e.nodeType){case Rs.None:break;case Rs.Element:this._result.length>0&&this.writeLine(),this.write(`<${e.localName}`);for(const[t,s]of e.attributes)this.write(` ${t}="`),this.writeAttributeValue(s),this.write('"');if(0===e.childNodes.length)this.write("/>");else{if(this.write(">"),1!==e.childNodes.length||e.firstElement){this.indent();for(const t of e.childNodes)t.nodeType===Rs.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case Rs.Text:e.value&&this.write(e.value);break;case Rs.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case Rs.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case Rs.DocumentType:this.write(`<!DOCTYPE ${e.value}>`)}}unindend(){this._currentIndention=this._currentIndention.substr(0,this._currentIndention.length-this._indention.length)}indent(){this._currentIndention+=this._indention}writeAttributeValue(e){for(let t=0;t<e.length;t++){const s=e.charAt(t);switch(s){case"<":this._result.push("&lt;");break;case">":this._result.push("&gt;");break;case"&":this._result.push("&amp;");break;case"'":this._result.push("&apos;");break;case'"':this._result.push("&quot;");break;default:this._result.push(s)}}}write(e){this._isStartOfLine&&this._result.push(this._currentIndention),this._result.push(e),this._isStartOfLine=!1}writeLine(e=null){e&&this.write(e),this._indention.length>0&&!this._isStartOfLine&&(this._result.push("\n"),this._isStartOfLine=!0)}toString(){return this._result.join("").trimRight()}}class zs extends Ws{constructor(){super(),this.nodeType=Rs.Document}parse(e){Gs.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return Us.write(this,e,t)}}class Xs{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=f.Quarter}}class Js{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return`${this.path};${this.name};${this.role}`}}class Ys{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1}parseXml(e,t){this._masterTrackAutomations=new Map,this._automationsPerTrackIdAndBarIndex=new Map,this._sustainPedalsPerTrackIdAndBarIndex=new Map,this._tracksMapping=[],this._tracksById=new Map,this._masterBars=[],this._barsOfMasterBar=[],this._voicesOfBar=new Map,this._barsById=new Map,this._voiceById=new Map,this._beatsOfVoice=new Map,this._beatById=new Map,this._rhythmOfBeat=new Map,this._rhythmById=new Map,this._notesOfBeat=new Map,this._noteById=new Map,this._tappedNotes=new Map,this._lyricsByTrack=new Map,this._soundsByTrack=new Map,this._skipApplyLyrics=!1;const s=new zs;try{s.parse(e)}catch(e){throw new dt("Could not parse XML",e)}if(this.parseDom(s),this.buildModel(),this.score.finish(t),!this._skipApplyLyrics&&this._lyricsByTrack.size>0)for(const[e,t]of this._lyricsByTrack){this._tracksById.get(e).applyLyrics(t)}}parseDom(e){const t=e.firstElement;if(t){if("GPIF"!==t.localName)throw new dt("Root node of XML was not GPIF");this.score=new lt;for(const e of t.childElements())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(const t of e.childElements())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){const e=t.firstChild.innerText;e&&!this.score.words&&(this.score.words=e),e&&!this.score.music&&(this.score.music=e)}break;case"Copyright":this.score.copyright=t.firstChild.innerText;break;case"Tabber":this.score.tab=t.firstChild.innerText;break;case"Instructions":this.score.instructions=t.firstChild.innerText;break;case"Notices":this.score.notices=t.firstChild.innerText;break;case"ScoreSystemsDefaultLayout":this.score.defaultSystemsLayout=Number.parseInt(t.innerText);break;case"ScoreSystemsLayout":this.score.systemsLayout=t.innerText.split(" ").map((e=>Number.parseInt(e)))}}parseMasterTrackNode(e){for(const t of e.childElements())switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null,null);break;case"Tracks":this._tracksMapping=t.innerText.split(" ");break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,s,i){for(const a of e.childElements())if("Automation"===a.localName)this.parseAutomation(a,t,s,i)}parseAutomation(e,t,s,i){let a=null,r=!1,n=-1,o=0,h=0,c=null,d=0,u=null;for(const t of e.childElements())switch(t.localName){case"Type":a=t.innerText;break;case"Linear":r="true"===t.innerText.toLowerCase();break;case"Bar":n=Number.parseInt(t.innerText);break;case"Position":o=Number.parseFloat(t.innerText);break;case"Value":if(t.firstElement&&t.firstElement.nodeType===Rs.CDATA)c=t.innerText;else{const e=t.innerText.split(" ");1===e.length?(h=Number.parseFloat(e[0]),d=1):(h=Number.parseFloat(e[0]),d=Number.parseInt(e[1]))}break;case"Text":u=t.innerText}if(!a)return;let p=null;switch(a){case"Tempo":p=ie.buildTempoAutomation(r,o,h,d);break;case"Sound":c&&s&&s.has(c)&&(p=ie.buildInstrumentAutomation(r,o,s.get(c).program));break;case"SustainPedal":if(i){let e;i.has(n)?e=i.get(n):(e=[],i.set(n,e));const t=new Z;switch(t.ratioPosition=o,d){case 1:t.pedalType=l.Down;break;case 3:t.pedalType=l.Up}e.push(t)}}p&&(u&&(p.text=u),n>=0&&(t.has(n)||t.set(n,[]),t.get(n).push(p)))}parseTracksNode(e){for(const t of e.childElements())if("Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;const t=new St;t.ensureStaveCount(1);t.staves[0].showStandardNotation=!0;const s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Name":t.name=i.innerText;break;case"Color":const e=i.innerText.split(" ");if(e.length>=3){const s=Number.parseInt(e[0]),i=Number.parseInt(e[1]),a=Number.parseInt(e[2]);t.color=new Ae(s,i,a,255)}break;case"Instrument":const a=i.getAttribute("ref");(a.endsWith("-gs")||a.endsWith("GrandStaff"))&&(t.ensureStaveCount(2),t.staves[1].showStandardNotation=!0);break;case"InstrumentSet":this.parseInstrumentSet(t,i);break;case"NotationPatch":this.parseNotationPatch(t,i);break;case"ShortName":t.shortName=i.innerText;break;case"SystemsDefautLayout":t.defaultSystemsLayout=Number.parseInt(i.innerText);break;case"SystemsLayout":t.systemsLayout=i.innerText.split(" ").map((e=>Number.parseInt(e)));break;case"Lyrics":this.parseLyrics(s,i);break;case"Properties":this.parseTrackProperties(t,i);break;case"GeneralMidi":case"MidiConnection":case"MIDISettings":this.parseGeneralMidi(t,i);break;case"Sounds":this.parseSounds(s,t,i);break;case"PlaybackState":const r=i.innerText;t.playbackInfo.isSolo="Solo"===r,t.playbackInfo.isMute="Mute"===r;break;case"PartSounding":this.parsePartSounding(t,i);break;case"Staves":this.parseStaves(t,i);break;case"Transpose":this.parseTranspose(t,i);break;case"RSE":this.parseRSE(t,i);break;case"Automations":this.parseTrackAutomations(s,i)}this._tracksById.set(s,t)}parseTrackAutomations(e,t){const s=new Map;this._automationsPerTrackIdAndBarIndex.set(e,s);const i=new Map;this._sustainPedalsPerTrackIdAndBarIndex.set(e,i),this.parseAutomations(t,s,this._soundsByTrack.get(e),i)}parseNotationPatch(e,t){for(const s of t.childElements())switch(s.localName){case"LineCount":const t=Number.parseInt(s.innerText);for(const s of e.staves)s.standardNotationLineCount=t;break;case"Elements":this.parseElements(e,s)}}parseInstrumentSet(e,t){for(const s of t.childElements())switch(s.localName){case"Type":if("drumKit"===s.innerText)for(const t of e.staves)t.isPercussion=!0;if("drumKit"===s.innerText)for(const t of e.staves)t.isPercussion=!0;break;case"Elements":this.parseElements(e,s);break;case"LineCount":const t=Number.parseInt(s.innerText);for(const s of e.staves)s.standardNotationLineCount=t}}parseElements(e,t){for(const s of t.childElements())if("Element"===s.localName)this.parseElement(e,s)}parseElement(e,t){const s=t.findChildElement("Type"),i=s?s.innerText:"";for(const s of t.childElements())switch(s.localName){case"Name":case"Articulations":this.parseArticulations(e,s,i)}}parseArticulations(e,t,s){for(const i of t.childElements())if("Articulation"===i.localName)this.parseArticulation(e,i,s)}parseArticulation(e,t,s){const i=new ge;i.outputMidiNumber=-1,i.elementType=s;let a="";for(const e of t.childElements()){const t=e.innerText;switch(e.localName){case"Name":a=e.innerText;break;case"OutputMidiNumber":t.length>0&&(i.outputMidiNumber=Number.parseInt(t));break;case"TechniqueSymbol":i.techniqueSymbol=this.parseTechniqueSymbol(t);break;case"TechniquePlacement":switch(t){case"outside":case"above":i.techniqueSymbolPlacement=R.Bottom;break;case"inside":i.techniqueSymbolPlacement=R.Middle;break;case"below":i.techniqueSymbolPlacement=R.Top}break;case"Noteheads":const s=t.split(" ");s.length>=1&&(i.noteHeadDefault=this.parseNoteHead(s[0])),s.length>=2&&(i.noteHeadHalf=this.parseNoteHead(s[1])),s.length>=3&&(i.noteHeadWhole=this.parseNoteHead(s[2])),i.noteHeadHalf===I.None&&(i.noteHeadHalf=i.noteHeadDefault),i.noteHeadWhole===I.None&&(i.noteHeadWhole=i.noteHeadDefault);break;case"StaffLine":t.length>0&&(i.staffLine=Number.parseInt(t))}}-1!==i.outputMidiNumber?(e.percussionArticulations.push(i),a.length>0&&this._articulationByName.set(a,i)):a.length>0&&this._articulationByName.has(a)&&(this._articulationByName.get(a).staffLine=i.staffLine)}parseTechniqueSymbol(e){switch(e){case"pictEdgeOfCymbal":return I.PictEdgeOfCymbal;case"articStaccatoAbove":return I.ArticStaccatoAbove;case"noteheadParenthesis":return I.NoteheadParenthesis;case"stringsUpBow":return I.StringsUpBow;case"stringsDownBow":return I.StringsDownBow;case"guitarGolpe":return I.GuitarGolpe;default:return I.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return I.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return I.NoteheadDoubleWhole;case"noteheadWhole":return I.NoteheadWhole;case"noteheadHalf":return I.NoteheadHalf;case"noteheadBlack":return I.NoteheadBlack;case"noteheadNull":return I.NoteheadNull;case"noteheadXOrnate":return I.NoteheadXOrnate;case"noteheadTriangleUpWhole":return I.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return I.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return I.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return I.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return I.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return I.NoteheadDiamondWhiteWide;case"noteheadCircleX":return I.NoteheadCircleX;case"noteheadXWhole":return I.NoteheadXWhole;case"noteheadXHalf":return I.NoteheadXHalf;case"noteheadXBlack":return I.NoteheadXBlack;case"noteheadParenthesis":return I.NoteheadParenthesis;case"noteheadSlashedBlack2":return I.NoteheadSlashedBlack2;case"noteheadCircleSlash":return I.NoteheadCircleSlash;case"noteheadHeavyX":return I.NoteheadHeavyX;case"noteheadHeavyXHat":return I.NoteheadHeavyXHat;default:return he.warning("GPIF","Unknown notehead symbol",e),I.None}}parseStaves(e,t){let s=0;for(const i of t.childElements())if("Staff"===i.localName){e.ensureStaveCount(s+1);const t=e.staves[s];this.parseStaff(t,i),s++}}parseStaff(e,t){for(const s of t.childElements())if("Properties"===s.localName)this.parseStaffProperties(e,s)}parseStaffProperties(e,t){for(const s of t.childElements())if("Property"===s.localName)this.parseStaffProperty(e,s)}parseStaffProperty(e,t){switch(t.getAttribute("name")){case"Tuning":for(const s of t.childElements())switch(s.localName){case"Pitches":const i=t.findChildElement("Pitches").innerText.split(" "),a=new Array(i.length);for(let e=0;e<a.length;e++)a[a.length-1-e]=Number.parseInt(i[e]);e.stringTuning.tunings=a;break;case"Label":e.stringTuning.name=s.innerText}e.isPercussion||(e.showTablature=!0);break;case"DiagramCollection":case"ChordCollection":this.parseDiagramCollectionForStaff(e,t);break;case"CapoFret":const s=Number.parseInt(t.findChildElement("Fret").innerText);e.capo=s}}parseLyrics(e,t){const s=[];for(const e of t.childElements())if("Line"===e.localName)s.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,s)}parseLyricsLine(e){const t=new pt;for(const s of e.childElements())switch(s.localName){case"Offset":t.startBar=Number.parseInt(s.innerText);break;case"Text":t.text=s.innerText}return t}parseDiagramCollectionForTrack(e,t){const s=t.findChildElement("Items");for(const t of s.childElements())if("Item"===t.localName)this.parseDiagramItemForTrack(e,t)}parseDiagramCollectionForStaff(e,t){const s=t.findChildElement("Items");for(const t of s.childElements())if("Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){const s=new ut,i=t.getAttribute("id");for(const t of e.staves)t.addChord(i,s);this.parseDiagramItemForChord(s,t)}parseDiagramItemForStaff(e,t){const s=new ut,i=t.getAttribute("id");e.addChord(i,s),this.parseDiagramItemForChord(s,t)}parseDiagramItemForChord(e,t){e.name=t.getAttribute("name");const s=t.findChildElement("Diagram");if(!s)return e.showDiagram=!1,void(e.showFingering=!1);const i=Number.parseInt(s.getAttribute("stringCount")),a=s.attributes.has("baseFret")?Number.parseInt(s.getAttribute("baseFret")):0;e.firstFret=a+1;for(let t=0;t<i;t++)e.strings.push(-1);for(const t of s.childElements())switch(t.localName){case"Fret":const s=Number.parseInt(t.getAttribute("string"));e.strings[i-s-1]=a+Number.parseInt(t.getAttribute("fret"));break;case"Fingering":const r=new Map;for(const s of t.childElements())if("Position"===s.localName){let t=_.Unknown;const i=a+Number.parseInt(s.getAttribute("fret"));switch(s.getAttribute("finger")){case"Index":t=_.IndexFinger;break;case"Middle":t=_.MiddleFinger;break;case"Rank":t=_.AnnularFinger;break;case"Pinky":t=_.LittleFinger;break;case"Thumb":t=_.Thumb}t!==_.Unknown&&(r.has(t)?e.barreFrets.push(i):r.set(t,!0))}break;case"Property":switch(t.getAttribute("name")){case"ShowName":e.showName="true"===t.getAttribute("value");break;case"ShowDiagram":e.showDiagram="true"===t.getAttribute("value");break;case"ShowFingering":e.showFingering="true"===t.getAttribute("value")}}}parseTrackProperties(e,t){for(const s of t.childElements())if("Property"===s.localName)this.parseTrackProperty(e,s)}parseTrackProperty(e,t){switch(t.getAttribute("name")){case"Tuning":const s=t.findChildElement("Pitches").innerText.split(" "),i=new Array(s.length);for(let e=0;e<i.length;e++)i[i.length-1-e]=Number.parseInt(s[e]);for(const t of e.staves)t.stringTuning.tunings=i,t.showStandardNotation=!0,t.showTablature=!0;break;case"DiagramCollection":case"ChordCollection":this.parseDiagramCollectionForTrack(e,t);break;case"CapoFret":const a=Number.parseInt(t.findChildElement("Fret").innerText);for(const t of e.staves)t.capo=a}}parseGeneralMidi(e,t){for(const s of t.childElements())switch(s.localName){case"Program":e.playbackInfo.program=Number.parseInt(s.innerText);break;case"Port":e.playbackInfo.port=Number.parseInt(s.innerText);break;case"PrimaryChannel":e.playbackInfo.primaryChannel=Number.parseInt(s.innerText);break;case"SecondaryChannel":e.playbackInfo.secondaryChannel=Number.parseInt(s.innerText)}if("Percussion"===t.getAttribute("table"))for(const t of e.staves)t.isPercussion=!0}parseSounds(e,t,s){for(const i of s.childElements())if("Sound"===i.localName)this.parseSound(e,t,i)}parseSound(e,t,s){const i=new Js;for(const e of s.childElements())switch(e.localName){case"Name":i.name=e.innerText;break;case"Path":i.path=e.innerText;break;case"Role":i.role=e.innerText;break;case"MIDI":this.parseSoundMidi(i,e)}"Factory"!==i.role&&0!==t.playbackInfo.program||(t.playbackInfo.program=i.program),this._soundsByTrack.has(e)||this._soundsByTrack.set(e,new Map),this._soundsByTrack.get(e).set(i.uniqueId,i)}parseSoundMidi(e,t){for(const s of t.childElements())if("Program"===s.localName)e.program=Number.parseInt(s.innerText)}parsePartSounding(e,t){for(const s of t.childElements())if("TranspositionPitch"===s.localName)for(const t of e.staves)t.displayTranspositionPitch=Number.parseInt(s.innerText)}parseTranspose(e,t){let s=0,i=0;for(const e of t.childElements())switch(e.localName){case"Chromatic":i=Number.parseInt(e.innerText);break;case"Octave":s=Number.parseInt(e.innerText)}for(const t of e.staves)t.displayTranspositionPitch=12*s+i}parseRSE(e,t){for(const s of t.childElements())if("ChannelStrip"===s.localName)this.parseChannelStrip(e,s)}parseChannelStrip(e,t){for(const s of t.childElements())if("Parameters"===s.localName)this.parseChannelStripParameters(e,s)}parseChannelStripParameters(e,t){if(t.firstChild&&t.firstChild.value){const s=t.firstChild.value.split(" ");s.length>=12&&(e.playbackInfo.balance=Math.floor(16*Number.parseFloat(s[11])),e.playbackInfo.volume=Math.floor(16*Number.parseFloat(s[12])))}}parseMasterBarsNode(e){for(const t of e.childElements())if("MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){const t=new le;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(const s of e.childElements())switch(s.localName){case"Time":const e=s.innerText.split("/");t.timeSignatureNumerator=Number.parseInt(e[0]),t.timeSignatureDenominator=Number.parseInt(e[1]);break;case"FreeTime":t.isFreeTime=!0;break;case"DoubleBar":t.isDoubleBar=!0;break;case"Section":t.section=new gt,t.section.marker=s.findChildElement("Letter").innerText,t.section.text=s.findChildElement("Text").innerText;break;case"Repeat":"true"===s.getAttribute("start").toLowerCase()&&(t.isRepeatStart=!0),"true"===s.getAttribute("end").toLowerCase()&&s.getAttribute("count")&&(t.repeatCount=Number.parseInt(s.getAttribute("count")));break;case"AlternateEndings":const i=s.innerText.split(" ");let a=0;for(let e=0;e<i.length;e++)a|=1<<-1+Number.parseInt(i[e]);t.alternateEndings=a;break;case"Bars":this._barsOfMasterBar.push(s.innerText.split(" "));break;case"TripletFeel":switch(s.innerText){case"NoTripletFeel":t.tripletFeel=M.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=M.Triplet8th;break;case"Triplet16th":t.tripletFeel=M.Triplet16th;break;case"Dotted8th":t.tripletFeel=M.Dotted8th;break;case"Dotted16th":t.tripletFeel=M.Dotted16th;break;case"Scottish8th":t.tripletFeel=M.Scottish8th;break;case"Scottish16th":t.tripletFeel=M.Scottish16th}break;case"Key":t.keySignature=Number.parseInt(s.findChildElement("AccidentalCount").innerText);const r=s.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,s);break;case"XProperties":this.parseMasterBarXProperties(t,s);break;case"Directions":this.parseDirections(t,s)}this._masterBars.push(t)}parseDirections(e,t){for(const s of t.childElements())switch(s.localName){case"Target":switch(s.innerText){case"Coda":e.addDirection(qe.TargetCoda);break;case"DoubleCoda":e.addDirection(qe.TargetDoubleCoda);break;case"Segno":e.addDirection(qe.TargetSegno);break;case"SegnoSegno":e.addDirection(qe.TargetSegnoSegno);break;case"Fine":e.addDirection(qe.TargetFine)}break;case"Jump":switch(s.innerText){case"DaCapo":e.addDirection(qe.JumpDaCapo);break;case"DaCapoAlCoda":e.addDirection(qe.JumpDaCapoAlCoda);break;case"DaCapoAlDoubleCoda":e.addDirection(qe.JumpDaCapoAlDoubleCoda);break;case"DaCapoAlFine":e.addDirection(qe.JumpDaCapoAlFine);break;case"DaSegno":e.addDirection(qe.JumpDalSegno);break;case"DaSegnoAlCoda":e.addDirection(qe.JumpDalSegnoAlCoda);break;case"DaSegnoAlDoubleCoda":e.addDirection(qe.JumpDalSegnoAlDoubleCoda);break;case"DaSegnoAlFine":e.addDirection(qe.JumpDalSegnoAlFine);break;case"DaSegnoSegno":e.addDirection(qe.JumpDalSegnoSegno);break;case"DaSegnoSegnoAlCoda":e.addDirection(qe.JumpDalSegnoSegnoAlCoda);break;case"DaSegnoSegnoAlDoubleCoda":e.addDirection(qe.JumpDalSegnoSegnoAlDoubleCoda);break;case"DaSegnoSegnoAlFine":e.addDirection(qe.JumpDalSegnoSegnoAlFine);break;case"DaCoda":e.addDirection(qe.JumpDaCoda);break;case"DaDoubleCoda":e.addDirection(qe.JumpDaDoubleCoda)}}}parseFermatas(e,t){for(const s of t.childElements())if("Fermata"===s.localName)this.parseFermata(e,s)}parseFermata(e,t){let s=0;const i=new Tt;for(const e of t.childElements())switch(e.localName){case"Type":switch(e.innerText){case"Short":i.type=Ke.Short;break;case"Medium":i.type=Ke.Medium;break;case"Long":i.type=Ke.Long}break;case"Length":i.length=Number.parseFloat(e.innerText);break;case"Offset":const t=e.innerText.split("/");if(2===t.length){s=Number.parseInt(t[0])/Number.parseInt(t[1])*se.QuarterTime|0}}e.addFermata(s,i)}parseBars(e){for(const t of e.childElements())if("Bar"===t.localName)this.parseBar(t)}parseBar(e){const t=new te,s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Voices":this._voicesOfBar.set(s,i.innerText.split(" "));break;case"Clef":switch(i.innerText){case"Neutral":t.clef=n.Neutral;break;case"G2":t.clef=n.G2;break;case"F4":t.clef=n.F4;break;case"C4":t.clef=n.C4;break;case"C3":t.clef=n.C3}break;case"Ottavia":switch(i.innerText){case"8va":t.clefOttava=o._8va;break;case"15ma":t.clefOttava=o._15ma;break;case"8vb":t.clefOttava=o._8vb;break;case"15mb":t.clefOttava=o._15mb}break;case"SimileMark":switch(i.innerText){case"Simple":t.simileMark=h.Simple;break;case"FirstOfDouble":t.simileMark=h.FirstOfDouble;break;case"SecondOfDouble":t.simileMark=h.SecondOfDouble}break;case"XProperties":this.parseBarXProperties(i,t)}this._barsById.set(s,t)}parseVoices(e){for(const t of e.childElements())if("Voice"===t.localName)this.parseVoice(t)}parseVoice(e){const t=new Pe,s=e.getAttribute("id");for(const t of e.childElements())if("Beats"===t.localName)this._beatsOfVoice.set(s,t.innerText.split(" "));this._voiceById.set(s,t)}parseBeats(e){for(const t of e.childElements())if("Beat"===t.localName)this.parseBeat(t)}parseBeat(e){const t=new xe,s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Notes":this._notesOfBeat.set(s,i.innerText.split(" "));break;case"Rhythm":this._rhythmOfBeat.set(s,i.getAttribute("ref"));break;case"Fadding":switch(i.innerText){case"FadeIn":t.fade=G.FadeIn;break;case"FadeOut":t.fade=G.FadeOut;break;case"VolumeSwell":t.fade=G.VolumeSwell}break;case"Tremolo":switch(i.innerText){case"1/2":t.tremoloSpeed=f.Eighth;break;case"1/4":t.tremoloSpeed=f.Sixteenth;break;case"1/8":t.tremoloSpeed=f.ThirtySecond}break;case"Chord":t.chordId=i.innerText;break;case"Hairpin":switch(i.innerText){case"Crescendo":t.crescendo=m.Crescendo;break;case"Decrescendo":t.crescendo=m.Decrescendo}break;case"Arpeggio":"Up"===i.innerText?t.brushType=g.ArpeggioUp:t.brushType=g.ArpeggioDown;break;case"Properties":this.parseBeatProperties(i,t);break;case"XProperties":this.parseBeatXProperties(i,t);break;case"FreeText":t.text=i.innerText;break;case"TransposedPitchStemOrientation":switch(i.innerText){case"Upward":t.preferredBeamDirection=je.Up;break;case"Downward":t.preferredBeamDirection=je.Down}break;case"Dynamic":switch(i.innerText){case"PPP":t.dynamics=y.PPP;break;case"PP":t.dynamics=y.PP;break;case"P":t.dynamics=y.P;break;case"MP":t.dynamics=y.MP;break;case"MF":t.dynamics=y.MF;break;case"F":t.dynamics=y.F;break;case"FF":t.dynamics=y.FF;break;case"FFF":t.dynamics=y.FFF}break;case"GraceNotes":switch(i.innerText){case"OnBeat":t.graceType=b.OnBeat;break;case"BeforeBeat":t.graceType=b.BeforeBeat}break;case"Legato":"true"===i.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":const e=new ae(0,0);e.value=this.toBendValue(Number.parseFloat(i.getAttribute("originValue"))),e.offset=this.toBendOffset(Number.parseFloat(i.getAttribute("originOffset"))),t.addWhammyBarPoint(e);const a=new ae(0,0);a.value=this.toBendValue(Number.parseFloat(i.getAttribute("middleValue"))),a.offset=this.toBendOffset(Number.parseFloat(i.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);const r=new ae(0,0);r.value=this.toBendValue(Number.parseFloat(i.getAttribute("middleValue"))),r.offset=this.toBendOffset(Number.parseFloat(i.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);const n=new ae(0,0);n.value=this.toBendValue(Number.parseFloat(i.getAttribute("destinationValue"))),n.offset=this.toBendOffset(Number.parseFloat(i.getAttribute("destinationOffset"))),t.addWhammyBarPoint(n);break;case"Ottavia":switch(i.innerText){case"8va":t.ottava=o._8va;break;case"8vb":t.ottava=o._8vb;break;case"15ma":t.ottava=o._15ma;break;case"15mb":t.ottava=o._15mb}break;case"Lyrics":t.lyrics=this.parseBeatLyrics(i),this._skipApplyLyrics=!0;break;case"Slashed":t.slashed=!0;break;case"DeadSlapped":t.deadSlapped=!0;break;case"Golpe":switch(i.innerText){case"Finger":t.golpe=V.Finger;break;case"Thumb":t.golpe=V.Thumb}break;case"Wah":switch(i.innerText){case"Open":t.wahPedal=U.Open;break;case"Closed":t.wahPedal=U.Closed}break;case"UserTransposedPitchStemOrientation":switch(i.innerText){case"Downward":t.preferredBeamDirection=je.Down;break;case"Upward":t.preferredBeamDirection=je.Up}break;case"Timer":t.showTimer=!0,i.innerText.length>0&&(t.timer=Number.parseInt(i.innerText))}this._beatById.set(s,t)}parseBeatLyrics(e){const t=[];for(const s of e.childElements())if("Line"===s.localName)t.push(s.innerText);return t}parseBeatXProperties(e,t){for(const s of e.childElements())if("XProperty"===s.localName){let e=0;switch(s.getAttribute("id")){case"1124204546":switch(e=Number.parseInt(s.findChildElement("Int").innerText),e){case 1:t.beamingMode=J.ForceMergeWithNext;break;case 2:t.beamingMode=J.ForceSplitToNext}break;case"1124204552":if(e=Number.parseInt(s.findChildElement("Int").innerText),1===e)t.beamingMode!==J.ForceSplitToNext&&(t.beamingMode=J.ForceSplitOnSecondaryToNext);break;case"1124204545":e=Number.parseInt(s.findChildElement("Int").innerText),t.invertBeamDirection=1===e;break;case"687935489":e=Number.parseInt(s.findChildElement("Int").innerText),t.brushDuration=e}}}parseBarXProperties(e,t){for(const s of e.childElements())if("XProperty"===s.localName){if("1124139520"===s.getAttribute("id")){const e=s.findChildElement("Double")??s.findChildElement("Float");t.displayScale=Number.parseFloat(e.innerText)}}}parseMasterBarXProperties(e,t){for(const s of t.childElements())if("XProperty"===s.localName){if("1124073984"===s.getAttribute("id"))e.displayScale=Number.parseFloat(s.findChildElement("Double").innerText)}}parseBeatProperties(e,t){let s=!1,i=null,a=null,r=null,n=null,o=null;for(const h of e.childElements())if("Property"===h.localName){switch(h.getAttribute("name")){case"Brush":"Up"===h.findChildElement("Direction").innerText?t.brushType=g.BrushUp:t.brushType=g.BrushDown;break;case"PickStroke":"Up"===h.findChildElement("Direction").innerText?t.pickStroke=L.Up:t.pickStroke=L.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=N.Wide;break;case"Slight":t.vibrato=N.Slight}break;case"WhammyBar":s=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":i||(i=new ae(0,0)),i.value=this.toBendValue(Number.parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":i||(i=new ae(0,0)),i.offset=this.toBendOffset(Number.parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleValue":a=this.toBendValue(Number.parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleOffset1":r=this.toBendOffset(Number.parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleOffset2":n=this.toBendOffset(Number.parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationValue":o||(o=new ae(ae.MaxPosition,0)),o.value=this.toBendValue(Number.parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new ae(0,0)),o.offset=this.toBendOffset(Number.parseFloat(h.findChildElement("Float").innerText));break;case"BarreFret":t.barreFret=Number.parseInt(h.findChildElement("Fret").innerText);break;case"BarreString":switch(h.findChildElement("String").innerText){case"0":t.barreShape=z.Full;break;case"1":t.barreShape=z.Half}break;case"Rasgueado":switch(h.findChildElement("Rasgueado").innerText){case"ii_1":t.rasgueado=X.Ii;break;case"mi_1":t.rasgueado=X.Mi;break;case"mii_1":t.rasgueado=X.MiiTriplet;break;case"mii_2":t.rasgueado=X.MiiAnapaest;break;case"pmp_1":t.rasgueado=X.PmpTriplet;break;case"pmp_2":t.rasgueado=X.PmpAnapaest;break;case"pei_1":t.rasgueado=X.PeiTriplet;break;case"pei_2":t.rasgueado=X.PeiAnapaest;break;case"pai_1":t.rasgueado=X.PaiTriplet;break;case"pai_2":t.rasgueado=X.PaiAnapaest;break;case"ami_1":t.rasgueado=X.AmiTriplet;break;case"ami_2":t.rasgueado=X.AmiAnapaest;break;case"ppp_1":t.rasgueado=X.Ppp;break;case"amii_1":t.rasgueado=X.Amii;break;case"amip_1":t.rasgueado=X.Amip;break;case"eami_1":t.rasgueado=X.Eami;break;case"eamii_1":t.rasgueado=X.Eamii;break;case"peami_1":t.rasgueado=X.Peami}}}s&&(i||(i=new ae(0,0)),o||(o=new ae(ae.MaxPosition,0)),t.addWhammyBarPoint(i),r&&a&&t.addWhammyBarPoint(new ae(r,a)),n&&a&&t.addWhammyBarPoint(new ae(n,a)),r||n||!a||t.addWhammyBarPoint(new ae(ae.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(const t of e.childElements())if("Note"===t.localName)this.parseNote(t)}parseNote(e){const t=new be,s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Properties":this.parseNoteProperties(i,t,s);break;case"AntiAccent":"normal"===i.innerText.toLowerCase()&&(t.isGhost=!0);break;case"LetRing":t.isLetRing=!0;break;case"Trill":t.trillValue=Number.parseInt(i.innerText),t.trillSpeed=f.Sixteenth;break;case"Accent":const e=Number.parseInt(i.innerText);1&e&&(t.isStaccato=!0),4&e&&(t.accentuated=S.Heavy),8&e&&(t.accentuated=S.Normal),16&e&&(t.accentuated=S.Tenuto);break;case"Tie":"true"===i.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(i.innerText){case"Slight":t.vibrato=N.Slight;break;case"Wide":t.vibrato=N.Wide}break;case"LeftFingering":switch(i.innerText){case"P":t.leftHandFinger=_.Thumb;break;case"I":t.leftHandFinger=_.IndexFinger;break;case"M":t.leftHandFinger=_.MiddleFinger;break;case"A":t.leftHandFinger=_.AnnularFinger;break;case"C":t.leftHandFinger=_.LittleFinger}break;case"RightFingering":switch(i.innerText){case"P":t.rightHandFinger=_.Thumb;break;case"I":t.rightHandFinger=_.IndexFinger;break;case"M":t.rightHandFinger=_.MiddleFinger;break;case"A":t.rightHandFinger=_.AnnularFinger;break;case"C":t.rightHandFinger=_.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=Number.parseInt(i.innerText);break;case"Ornament":switch(i.innerText){case"Turn":t.ornament=O.Turn;break;case"InvertedTurn":t.ornament=O.InvertedTurn;break;case"UpperMordent":t.ornament=O.UpperMordent;break;case"LowerMordent":t.ornament=O.LowerMordent}}this._noteById.set(s,t)}parseNoteProperties(e,t,s){let i=!1,a=null,r=null,n=null,o=null,h=null,l=-1,c=-1;for(const d of e.childElements())if("Property"===d.localName){switch(d.getAttribute("name")){case"ShowStringNumber":d.findChildElement("Enable")&&(t.showStringNumber=!0);break;case"String":t.string=Number.parseInt(d.findChildElement("String").innerText)+1;break;case"Fret":t.fret=Number.parseInt(d.findChildElement("Fret").innerText);break;case"Element":l=Number.parseInt(d.findChildElement("Element").innerText);break;case"Variation":c=Number.parseInt(d.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(s,!0);break;case"HarmonicType":const e=d.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=w.None;break;case"Natural":t.harmonicType=w.Natural;break;case"Artificial":t.harmonicType=w.Artificial;break;case"Pinch":t.harmonicType=w.Pinch;break;case"Tap":t.harmonicType=w.Tap;break;case"Semi":t.harmonicType=w.Semi;break;case"Feedback":t.harmonicType=w.Feedback}break;case"HarmonicFret":const u=d.findChildElement("HFret");u&&(t.harmonicValue=Number.parseFloat(u.innerText));break;case"Muted":d.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":d.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=Number.parseInt(d.findChildElement("Number").innerText),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=Number.parseInt(d.findChildElement("Step").innerText);break;case"ConcertPitch":this.parseConcertPitch(d,t);break;case"Bended":i=!0;break;case"BendOriginValue":a||(a=new ae(0,0)),a.value=this.toBendValue(Number.parseFloat(d.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new ae(0,0)),a.offset=this.toBendOffset(Number.parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleValue":r=this.toBendValue(Number.parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleOffset1":n=this.toBendOffset(Number.parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleOffset2":o=this.toBendOffset(Number.parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationValue":h||(h=new ae(ae.MaxPosition,0)),h.value=this.toBendValue(Number.parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new ae(0,0)),h.offset=this.toBendOffset(Number.parseFloat(d.findChildElement("Float").innerText));break;case"HopoOrigin":d.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":const p=Number.parseInt(d.findChildElement("Flags").innerText);1&p?t.slideOutType=T.Shift:2&p?t.slideOutType=T.Legato:4&p?t.slideOutType=T.OutDown:8&p&&(t.slideOutType=T.OutUp),16&p?t.slideInType=k.IntoFromBelow:32&p&&(t.slideInType=k.IntoFromAbove),64&p?t.slideOutType=T.PickSlideDown:128&p&&(t.slideOutType=T.PickSlideUp)}}i&&(a||(a=new ae(0,0)),h||(h=new ae(ae.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new ae(n,r)),o&&r&&t.addBendPoint(new ae(o,r)),n||o||!r||t.addBendPoint(new ae(ae.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==c&&(t.percussionArticulation=me.articulationFromElementVariation(l,c))}parseConcertPitch(e,t){const s=e.findChildElement("Pitch");if(s)for(const e of s.childElements())if("Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=B.ForceDoubleSharp;break;case"#":t.accidentalMode=B.ForceSharp;break;case"b":t.accidentalMode=B.ForceFlat;break;case"bb":t.accidentalMode=B.ForceDoubleFlat}}toBendValue(e){return e*Ys.BendPointValueFactor|0}toBendOffset(e){return e*Ys.BendPointPositionFactor}parseRhythms(e){for(const t of e.childElements())if("Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){const t=new Xs,s=e.getAttribute("id");t.id=s;for(const s of e.childElements())switch(s.localName){case"NoteValue":switch(s.innerText){case"Long":t.value=f.QuadrupleWhole;break;case"DoubleWhole":t.value=f.DoubleWhole;break;case"Whole":t.value=f.Whole;break;case"Half":t.value=f.Half;break;case"Quarter":t.value=f.Quarter;break;case"Eighth":t.value=f.Eighth;break;case"16th":t.value=f.Sixteenth;break;case"32nd":t.value=f.ThirtySecond;break;case"64th":t.value=f.SixtyFourth;break;case"128th":t.value=f.OneHundredTwentyEighth;break;case"256th":t.value=f.TwoHundredFiftySixth}break;case"PrimaryTuplet":t.tupletNumerator=Number.parseInt(s.getAttribute("num")),t.tupletDenominator=Number.parseInt(s.getAttribute("den"));break;case"AugmentationDot":t.dots=Number.parseInt(s.getAttribute("count"))}this._rhythmById.set(s,t)}buildModel(){for(let e=0,t=this._masterBars.length;e<t;e++){const t=this._masterBars[e];this.score.addMasterBar(t)}for(const e of this._tracksMapping){if(!e)continue;const t=this._tracksById.get(e);this.score.addTrack(t)}for(const e of this._barsOfMasterBar){let t=0;for(let s=0,i=0;s<e.length&&i<this.score.tracks.length;s++){const a=e[s];if(a!==Ys.InvalidId){const e=this._barsById.get(a),s=this.score.tracks[i],r=s.staves[t];if(r.addBar(e),this._voicesOfBar.has(a))for(const t of this._voicesOfBar.get(a))if(t!==Ys.InvalidId){const s=this._voiceById.get(t);if(e.addVoice(s),this._beatsOfVoice.has(t))for(const e of this._beatsOfVoice.get(t))if(e!==Ys.InvalidId){const t=ke.clone(this._beatById.get(e));s.addBeat(t);const i=this._rhythmOfBeat.get(e),a=this._rhythmById.get(i);if(t.duration=a.value,t.dots=a.dots,t.tupletNumerator=a.tupletNumerator,t.tupletDenominator=a.tupletDenominator,this._notesOfBeat.has(e))for(const s of this._notesOfBeat.get(e))if(s!==Ys.InvalidId){const e=we.clone(this._noteById.get(s));r.isPercussion?(e.fret=-1,e.string=-1):e.percussionArticulation=-1,t.addNote(e),this._tappedNotes.has(s)&&(t.tap=!0)}}}else{const t=new Pe;e.addVoice(t);const s=new xe;s.isEmpty=!0,s.duration=f.Quarter,t.addBeat(s)}t===s.staves.length-1?(i++,t=0):t++}else i++}}for(const e of this._tracksMapping){if(!e)continue;const t=this._tracksById.get(e);let s=!1;for(const e of t.staves)if(e.isPercussion){s=!0;break}if(s||(t.percussionArticulations=[]),this._automationsPerTrackIdAndBarIndex.has(e)){const s=this._automationsPerTrackIdAndBarIndex.get(e);for(const[e,i]of s)if(t.staves.length>0&&e<t.staves[0].bars.length){const s=t.staves[0].bars[e];if(s.voices.length>0&&s.voices[0].beats.length>0){const e=s.voices[0].beats[0];for(const t of i)e.automations.push(t)}}}if(this._sustainPedalsPerTrackIdAndBarIndex.has(e)){const s=this._sustainPedalsPerTrackIdAndBarIndex.get(e);for(const[e,i]of s)if(t.staves.length>0&&e<t.staves[0].bars.length){t.staves[0].bars[e].sustainPedals=i}}}for(const[e,t]of this._masterTrackAutomations){const s=this.score.masterBars[e];for(let i=0,a=t.length;i<a;i++){const a=t[i];a.type===d.Tempo&&(0===e&&(this.score.tempo=0|a.value,a.text&&(this.score.tempoLabel=a.text)),s.tempoAutomations.push(a))}}}}Ys.InvalidId="-1",Ys.BendPointPositionFactor=ae.MaxPosition/100,Ys.BendPointValueFactor=.04;class $s{constructor(){this.isMultiRest=!1,this.trackViewGroups=[]}}class qs{constructor(){this.showNumbered=!1,this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class Ks{apply(e){if(this.scoreViews.length>0){let t=0;e.stylesheet.multiTrackMultiBarRest=this.scoreViews[0].isMultiRest;for(const s of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){const i=e.tracks[t];for(const e of i.staves)e.showTablature=s.showTablature,e.showStandardNotation=s.showStandardNotation,e.showSlash=s.showSlash,e.showNumbered=s.showNumbered}t++}for(let s=1;s<this.scoreViews.length;s++)this.scoreViews[s].isMultiRest&&(e.stylesheet.perTrackMultiBarRest||(e.stylesheet.perTrackMultiBarRest=new Set),t=s-1,e.stylesheet.perTrackMultiBarRest.add(t))}}constructor(e){this.scoreViews=[];const t=Bt.fromBuffer(e),s=wt.readInt32BE(t);for(let e=0;e<s;e++){const e=new $s;this.scoreViews.push(e),e.isMultiRest=Ms.gpReadBool(t);const s=wt.readInt32BE(t);for(let i=0;i<s;i++){let s=t.readByte();0===s&&(s=1);const i=new qs;i.showStandardNotation=!!(1&s),i.showTablature=!!(2&s),i.showSlash=!!(4&s),i.showNumbered=!!(8&s),e.trackViewGroups.push(i)}}}static writeForScore(e){const t=Bt.withCapacity(128),s=[new $s];s[0].isMultiRest=e.stylesheet.multiTrackMultiBarRest;for(const t of e.tracks){const i=new qs;i.showStandardNotation=t.staves[0].showStandardNotation,i.showTablature=t.staves[0].showTablature,i.showSlash=t.staves[0].showSlash,i.showNumbered=t.staves[0].showNumbered,s[0].trackViewGroups.push(i);const a=new $s;a.isMultiRest=!0===e.stylesheet.perTrackMultiBarRest?.has(t.index),a.trackViewGroups.push(i),s.push(a)}wt.writeInt32BE(t,s.length);for(const e of s){t.writeByte(e.isMultiRest?1:0),wt.writeInt32BE(t,e.trackViewGroups.length);for(const s of e.trackViewGroups){let e=0;s.showStandardNotation&&(e|=1),s.showTablature&&(e|=2),s.showSlash&&(e|=4),s.showNumbered&&(e|=8),t.writeByte(e)}}return wt.writeInt32BE(t,1),t.toArray()}}let js=class{};class Qs extends js{constructor(e){super(),this.n=e}}class Zs extends js{constructor(e,t){super(),this.left=e,this.right=t}}class ei extends js{constructor(e,t){super(),this.n=e,this.table=t}}class ti{static make(e,t,s,i){const a=[],r=[];if(i>32)throw new Ie("Invalid huffman");for(let e=0;e<i;e++)a.push(0),r.push(0);for(let r=0;r<s;r++){const s=e[r+t];if(s>=i)throw new Ie("Invalid huffman");a[s]++}let n=0;for(let e=1;e<i-1;e++)n=n+a[e]<<1,r[e]=n;const o=new Map;for(let i=0;i<s;i++){const s=e[i+t];if(0!==s){const e=r[s-1];r[s-1]=e+1,o.set(e<<5|s,i)}}return ti.treeCompress(new Zs(ti.treeMake(o,i,0,1),ti.treeMake(o,i,1,1)))}static treeMake(e,t,s,i){if(i>t)throw new Ie("Invalid huffman");const a=s<<5|i;return e.has(a)?new Qs(e.get(a)):(s<<=1,i+=1,new Zs(ti.treeMake(e,t,s,i),ti.treeMake(e,t,1|s,i)))}static treeCompress(e){const t=ti.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof Zs)return new Zs(ti.treeCompress(e.left),ti.treeCompress(e.right));throw new Ie("assert")}const s=1<<t,i=[];for(let e=0;e<s;e++)i.push(new Qs(-1));return ti.treeWalk(i,0,0,t,e),new ei(t,i)}static treeWalk(e,t,s,i,a){a instanceof Zs&&i>0?(ti.treeWalk(e,t,s+1,i-1,a.left),ti.treeWalk(e,t|1<<s,s+1,i-1,a.right)):e[t]=ti.treeCompress(a)}static treeDepth(e){if(e instanceof Qs)return 0;if(e instanceof ei)throw new Ie("assert");if(e instanceof Zs){const t=ti.treeDepth(e.left),s=ti.treeDepth(e.right);return 1+(t<s?t:s)}return 0}}var si,ii;!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"}(si||(si={}));class ai{constructor(){this.buffer=new Uint8Array(ai.BufferSize),this.pos=0}slide(){const e=new Uint8Array(ai.BufferSize);this.pos-=ai.Size,e.set(this.buffer.subarray(ai.Size,ai.Size+this.pos),0),this.buffer=e}addBytes(e,t,s){this.pos+s>ai.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+s),this.pos),this.pos+=s}addByte(e){this.pos===ai.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}ai.Size=32768,ai.BufferSize=65536;class ri{static buildFixedHuffman(){const e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return ti.make(e,0,288,10)}constructor(e){this._nbits=0,this._bits=0,this._state=si.Block,this._isFinal=!1,this._huffman=ri._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new ai,this._input=e;for(let e=0;e<19;e++)this._lengths.push(-1)}readBytes(e,t,s){if(this._needed=s,this._outpos=t,this._output=e,s>0)for(;this.inflateLoop(););return s-this._needed}inflateLoop(){switch(this._state){case si.Head:const e=this._input.readByte();if(8!==(15&e))throw new Ie("Invalid data");const t=this._input.readByte(),s=!!(32&t);if(((e<<8)+t)%31!=0)throw new Ie("Invalid data");if(s)throw new Ie("Unsupported dictionary");return this._state=si.Block,!0;case si.Crc:return this._state=si.Done,!0;case si.Done:return!1;case si.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:this._len=wt.readUInt16LE(this._input);if(wt.readUInt16LE(this._input)!==65535-this._len)throw new Ie("Invalid data");this._state=si.Flat;const e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=ri._fixedHuffman,this._huffdist=null,this._state=si.CData,!0;case 2:const t=this.getBits(5)+257,s=this.getBits(5)+1,i=this.getBits(4)+4;for(let e=0;e<i;e++)this._lengths[ri.CodeLengthsPos[e]]=this.getBits(3);for(let e=i;e<19;e++)this._lengths[ri.CodeLengthsPos[e]]=0;this._huffman=ti.make(this._lengths,0,19,8);const a=[];for(let e=0;e<t+s;e++)a.push(0);return this.inflateLengths(a,t+s),this._huffdist=ti.make(a,t,s,16),this._huffman=ti.make(a,0,t,16),this._state=si.CData,!0;default:throw new Ie("Invalid data")}case si.Flat:{const e=this._len<this._needed?this._len:this._needed,t=wt.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?si.Crc:si.Block),this._needed>0}case si.DistOne:{const e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=si.CData),this._needed>0}case si.Dist:for(;this._len>0&&this._needed>0;){const 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=si.CData),this._needed>0;case si.CData:let i=this.applyHuffman(this._huffman);if(i<256)return this.addByte(i),this._needed>0;if(256===i)return this._state=this._isFinal?si.Crc:si.Block,!0;i=i-257&255;let a=ri.LenExtraBitsTbl[i];if(-1===a)throw new Ie("Invalid data");this._len=ri.LenBaseValTbl[i]+this.getBits(a);const r=this._huffdist,n=r?this.applyHuffman(r):this.getRevBits(5);if(a=ri.DistExtraBitsTbl[n],-1===a)throw new Ie("Invalid data");if(this._dist=ri.DistBaseValTbl[n]+this.getBits(a),this._dist>this._window.available())throw new Ie("Invalid data");return this._state=1===this._dist?si.DistOne:si.Dist,!0}return!1}addDistOne(e){const t=this._window.getLastChar();for(let s=0;s<e;s++)this.addByte(t)}addByte(e){this._window.addByte(e),this._output[this._outpos]=e,this._needed--,this._outpos++}addDist(e,t){this.addBytes(this._window.buffer,this._window.pos-e,t)}getBit(){0===this._nbits&&(this._nbits=8,this._bits=this._input.readByte());const e=!(1&~this._bits);return this._nbits--,this._bits=this._bits>>1,e}getBits(e){for(;this._nbits<e;)this._bits=this._bits|this._input.readByte()<<this._nbits,this._nbits+=8;const t=this._bits&(1<<e)-1;return this._nbits-=e,this._bits=this._bits>>e,t}getRevBits(e){return 0===e?0:this.getBit()?1<<e-1|this.getRevBits(e-1):this.getRevBits(e-1)}resetBits(){this._bits=0,this._nbits=0}addBytes(e,t,s){this._window.addBytes(e,t,s),this._output.set(e.subarray(t,t+s),this._outpos),this._needed-=s,this._outpos+=s}inflateLengths(e,t){let s=0,i=0;for(;s<t;){const a=this.applyHuffman(this._huffman);switch(a){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:case 15:i=a,e[s]=a,s++;break;case 16:const r=s+3+this.getBits(2);if(r>t)throw new Ie("Invalid data");for(;s<r;)e[s]=i,s++;break;case 17:if(s+=3+this.getBits(3),s>t)throw new Ie("Invalid data");break;case 18:if(s+=11+this.getBits(7),s>t)throw new Ie("Invalid data");break;default:throw new Ie("Invalid data")}}}applyHuffman(e){if(e instanceof Qs)return e.n;if(e instanceof Zs)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof ei)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new Ie("Invalid data")}}ri.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],ri.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],ri.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],ri.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],ri.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],ri._fixedHuffman=ri.buildFixedHuffman();class ni{constructor(e,t){this.fullName=e;const s=e.lastIndexOf("/");this.fileName=-1===s||s===e.length-1?this.fullName:e.substr(s+1),this.data=t}}ni.OptionalDataDescriptorSignature=134695760,ni.CompressionMethodDeflate=8,ni.LocalFileHeaderSignature=67324752,ni.CentralFileHeaderSignature=33639248,ni.EndOfCentralDirSignature=101010256;class oi{constructor(e){this._readable=e}read(){const e=[];for(;;){const t=this.readEntry();if(!t)break;e.push(t)}return e}readEntry(){const e=this._readable;if(wt.readInt32LE(e)!==ni.LocalFileHeaderSignature)return null;wt.readUInt16LE(e);const t=wt.readUInt16LE(e),s=wt.readUInt16LE(e),i=0!==s;if(i&&s!==ni.CompressionMethodDeflate)return null;wt.readInt16LE(this._readable),wt.readInt16LE(this._readable),wt.readInt32LE(e),wt.readInt32LE(e);const a=wt.readInt32LE(e),r=wt.readInt16LE(e),n=wt.readInt16LE(e),o=wt.toString(wt.readByteArray(e,r),"utf-8");let h;if(e.skip(n),i){const e=Bt.empty(),t=new ri(this._readable),s=new Uint8Array(65536);for(;;){const i=t.readBytes(s,0,s.length);if(e.write(s,0,i),i<s.length)break}h=e.toArray()}else h=wt.readByteArray(this._readable,a);if(8&t){wt.readInt32LE(this._readable)===ni.OptionalDataDescriptorSignature&&wt.readInt32LE(this._readable),wt.readInt32LE(this._readable),wt.readInt32LE(this._readable)}return new ni(o,h)}}class hi{constructor(){this.trackViewGroups=[]}}class li{constructor(){this.isVisible=!1}}!function(e){e[e.PageVertical=0]="PageVertical",e[e.PageGrid=1]="PageGrid",e[e.PageParchment=2]="PageParchment",e[e.ScreenVertical=3]="ScreenVertical",e[e.ScreenHorizontal=4]="ScreenHorizontal",e[e.PageHorizontal=5]="PageHorizontal"}(ii||(ii={}));class ci{constructor(e,t){this.zoomLevel=4,this.view=ii.PageVertical,this.muiltiVoiceCursor=!1,this.scoreViews=[];const s=Bt.fromBuffer(t);this.zoomLevel=wt.readInt32BE(s),this.view=s.readByte(),this.muiltiVoiceCursor=0!==s.readByte();const i=e.scoreViews.length;for(let t=0;t<i;t++){const i=new hi;this.scoreViews.push(i);const a=e.scoreViews[t];for(let e=0;e<a.trackViewGroups.length;e++){const e=new li;e.isVisible=0!==s.readByte(),i.trackViewGroups.push(e)}}}apply(e){if(this.scoreViews.length>0){let t=0;for(const s of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){e.tracks[t].isVisibleOnMultiTrack=s.isVisible}t++}}}static writeForScore(e){const t=Bt.withCapacity(128);wt.writeInt32BE(t,4),t.writeByte(0);const s=e.tracks.length>0&&e.tracks[0].staves[0].bars[0].isMultiVoice;t.writeByte(s?255:0);for(const s of e.tracks)t.writeByte(s.isVisibleOnMultiTrack?255:0);for(const s of e.tracks)t.writeByte(255);return t.toArray()}}class di extends ct{get name(){return"Guitar Pro 7-8"}readScore(){he.debug(this.name,"Loading ZIP entries");const e=new oi(this.data);let t;try{t=e.read()}catch(e){throw new dt("No Zip archive",e)}he.debug(this.name,"Zip entries loaded");let s=null,i=null,a=null,r=null;for(const e of t)switch(e.fileName){case"score.gpif":s=wt.toString(e.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=e.data;break;case"PartConfiguration":a=e.data;break;case"LayoutConfiguration":r=e.data}if(!s)throw new dt("No score.gpif found in zip archive");he.debug(this.name,"Start Parsing score.gpif");const n=new Ys;n.parseXml(s,this.settings),he.debug(this.name,"score.gpif parsed");const o=n.score;if(i){he.debug(this.name,"Start Parsing BinaryStylesheet");new Hs(i).apply(o),he.debug(this.name,"BinaryStylesheet parsed")}let h=null;if(a&&(he.debug(this.name,"Start Parsing Part Configuration"),h=new Ks(a),h.apply(o),he.debug(this.name,"Part Configuration parsed")),r&&null!=h){he.debug(this.name,"Start Parsing Layout Configuration");new ci(h,r).apply(o),he.debug(this.name,"Layout Configuration parsed")}return o}}class ui extends Le{constructor(){super(Ee.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,ui.prototype)}}class pi{constructor(e){this._currentByte=0,this._position=pi.ByteSize,this._source=e}readByte(){return this.readBits(8)}readBytes(e){const t=new Uint8Array(e);for(let s=0;s<e;s++)t[s]=255&this.readByte();return t}readBits(e){let t=0,s=e-1;for(;s>=0;)t|=this.readBit()<<s,s--;return t}readBitsReversed(e){let t=0;for(let s=0;s<e;s++)t|=this.readBit()<<s;return t}readBit(){if(this._position>=8){if(this._currentByte=this._source.readByte(),-1===this._currentByte)throw new ui;this._position=0}const e=this._currentByte>>pi.ByteSize-this._position-1&1;return this._position++,e}readAll(){const e=Bt.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof ui))throw e}return e.toArray()}}pi.ByteSize=8;class gi{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class mi{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){const t=new pi(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){const s=Bt.empty();let i;const a=this.getInteger(e.readBytes(4),0);try{for(;s.length<a;){if(1===e.readBits(1)){const 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{const t=e.readBitsReversed(2);for(let i=0;i<t;i++)s.writeByte(e.readByte())}}}catch(e){if(!(e instanceof ui))throw e}i=s.getBuffer();const 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){const t=this.readHeader(e);if("BCFZ"===t)this.readUncompressedBlock(this.decompress(e,!0));else{if("BCFS"!==t)throw new dt("Unsupported format");this.readUncompressedBlock(e.readAll())}}readUncompressedBlock(e){const t=4096;let s=t;for(;s+3<e.length;){if(2===this.getInteger(e,s)){const i=new gi;i.fileName=this.getString(e,s+4,127),i.fileSize=this.getInteger(e,s+140);const a=!this.fileFilter||this.fileFilter(i.fileName);a&&this.files.push(i);const r=s+148;let n=0,o=0;const h=a?Bt.withCapacity(i.fileSize):null;for(;n=this.getInteger(e,r+4*o++),0!==n;)s=n*t,a&&h.write(e,s,t);if(a){i.data=new Uint8Array(Math.min(i.fileSize,h.length));const e=h.toArray();i.data.set(e.subarray(0,0+i.data.length),0)}}s+=t}}getString(e,t,s){let i="";for(let a=0;a<s;a++){const s=255&e[t+a];if(0===s)break;i+=String.fromCharCode(s)}return i}getInteger(e,t){return e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}}mi.HeaderBcFs="BCFS",mi.HeaderBcFz="BCFZ";class fi extends ct{get name(){return"Guitar Pro 6"}readScore(){he.debug(this.name,"Loading GPX filesystem");const e=new mi;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration")||e.endsWith("LayoutConfiguration"),e.load(this.data),he.debug(this.name,"GPX filesystem loaded");let t=null,s=null,i=null,a=null;for(const r of e.files)switch(r.fileName){case"score.gpif":t=wt.toString(r.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=r.data;break;case"PartConfiguration":i=r.data;break;case"LayoutConfiguration":a=r.data}if(!t)throw new dt("No score.gpif found in GPX");he.debug(this.name,"Start Parsing score.gpif");const r=new Ys;r.parseXml(t,this.settings),he.debug(this.name,"score.gpif parsed");const n=r.score;if(s){he.debug(this.name,"Start Parsing BinaryStylesheet");new Hs(s).apply(n),he.debug(this.name,"BinaryStylesheet parsed")}let o=null;if(i&&(he.debug(this.name,"Start Parsing Part Configuration"),o=new Ks(i),o.apply(n),he.debug(this.name,"Part Configuration parsed")),a&&null!=o){he.debug(this.name,"Start Parsing Layout Configuration");new ci(o,a).apply(n),he.debug(this.name,"Layout Configuration parsed")}return n}}class yi{constructor(){this.id=ue.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 bi{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 Si{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 _i{constructor(){this.beats=[]}addBeat(e){e.barBounds=this,this.beats.push(e),this.masterBarBounds.addBeat(e)}findBeatAtPos(e){let t=null;for(const s of this.beats)if(!t||s.realBounds.x<e)t=s;else if(s.realBounds.x>e)break;return t}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.beats.sort(((e,t)=>e.realBounds.x-t.realBounds.x));for(const t of this.beats)t.finish(e)}}class wi{constructor(){this.onNotesX=0,this.notes=null}addNote(e){this.notes||(this.notes=[]),e.beatBounds=this,this.notes.push(e)}findNoteAtPos(e,t){const s=this.notes;if(!s)return null;for(const i of s){const s=i.noteHeadBounds.y+i.noteHeadBounds.h,a=i.noteHeadBounds.x+i.noteHeadBounds.w;if(i.noteHeadBounds.x<=e&&i.noteHeadBounds.y<=t&&e<=a&&t<=s)return i.note}return null}finish(e=1){if(this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.onNotesX*=e,this.notes)for(const t of this.notes)t.finish(e)}}class Bi{constructor(){this.index=0,this.isFirstOfLine=!1,this.bars=[],this.staffSystemBounds=null}get staveGroupBounds(){return this.staffSystemBounds}addBar(e){e.masterBarBounds=this,this.bars.push(e)}findBeatAtPos(e,t){let s=null;for(const t of this.bars){const i=t.findBeatAtPos(e);if(i&&(!s||s.realBounds.x<i.realBounds.x)){const t=Math.abs(i.realBounds.x-e);(!s||t<1e7)&&(s=i)}}return s?s.beat:null}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.lineAlignedBounds.scaleWith(e),this.bars.sort(((e,t)=>e.realBounds.y<t.realBounds.y?-1:e.realBounds.y>t.realBounds.y?1:e.realBounds.x<t.realBounds.x?-1:e.realBounds.x>t.realBounds.x?1:0));for(const t of this.bars)t.finish(e)}addBeat(e){this.staffSystemBounds.boundsLookup.addBeat(e)}}class ki{finish(e=1){this.noteHeadBounds.scaleWith(e)}}class Ti{constructor(){this.index=0,this.bars=[]}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e);for(const t of this.bars)t.finish(e)}addBar(e){this.boundsLookup.addMasterBar(e),e.staffSystemBounds=this,this.bars.push(e)}findBarAtPos(e){let t=null;for(const s of this.bars)if(!t||s.realBounds.x<e)t=s;else if(e>s.realBounds.x+s.realBounds.w)break;return t}}class Ni{constructor(){this._beatLookup=new Map,this._masterBarLookup=new Map,this._currentStaffSystem=null,this.staffSystems=[],this.isFinished=!1}toJson(){const e={},t=[];e.staffSystems=t;for(const e of this.staffSystems){const s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.bars=[];for(const t of e.bars){const 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(const s of t.bars){const t={};t.visualBounds=this.boundsToJson(s.visualBounds),t.realBounds=this.boundsToJson(s.realBounds),t.beats=[];for(const e of s.beats){const s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.onNotesX=e.onNotesX;const i=s;if(i.beatIndex=e.beat.index,i.voiceIndex=e.beat.voice.index,i.barIndex=e.beat.voice.bar.index,i.staffIndex=e.beat.voice.bar.staff.index,i.trackIndex=e.beat.voice.bar.staff.track.index,e.notes){const t=[];s.notes=t;for(const s of e.notes){const e={};e.index=s.note.index,e.noteHeadBounds=this.boundsToJson(s.noteHeadBounds),t.push(e)}}t.beats.push(s)}e.bars.push(t)}s.bars.push(e)}t.push(s)}return e}static fromJson(e,t){const s=new Ni,i=e.staffSystems;for(const e of i){const i=new Ti;i.visualBounds=Ni.boundsFromJson(e.visualBounds),i.realBounds=Ni.boundsFromJson(e.realBounds),s.addStaffSystem(i);for(const s of e.bars){const e=new Bi;e.index=s.index,e.isFirstOfLine=s.isFirstOfLine,e.lineAlignedBounds=Ni.boundsFromJson(s.lineAlignedBounds),e.visualBounds=Ni.boundsFromJson(s.visualBounds),e.realBounds=Ni.boundsFromJson(s.realBounds),i.addBar(e);for(const i of s.bars){const s=new _i;s.visualBounds=Ni.boundsFromJson(i.visualBounds),s.realBounds=Ni.boundsFromJson(i.realBounds),e.addBar(s);for(const e of i.beats){const i=new wi;i.visualBounds=Ni.boundsFromJson(e.visualBounds),i.realBounds=Ni.boundsFromJson(e.realBounds),i.onNotesX=e.onNotesX;const a=e;if(i.beat=t.tracks[a.trackIndex].staves[a.staffIndex].bars[a.barIndex].voices[a.voiceIndex].beats[a.beatIndex],e.notes){i.notes=[];for(const t of e.notes){const e=new ki,s=t;e.note=i.beat.notes[s.index],e.noteHeadBounds=Ni.boundsFromJson(t.noteHeadBounds),i.addNote(e)}}s.addBeat(i)}}}}return s}static boundsFromJson(e){const t=new Is;return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}boundsToJson(e){const t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(e=1){for(const t of this.staffSystems)t.finish(e);this.isFinished=!0}addStaffSystem(e){e.index=this.staffSystems.length,e.boundsLookup=this,this.staffSystems.push(e),this._currentStaffSystem=e}addMasterBar(e){e.staffSystemBounds?this._masterBarLookup.set(e.index,e):(e.staffSystemBounds=this._currentStaffSystem,this._masterBarLookup.set(e.index,e),this._currentStaffSystem.addBar(e))}addBeat(e){this._beatLookup.has(e.beat.id)||this._beatLookup.set(e.beat.id,[]),this._beatLookup.get(e.beat.id)?.push(e)}findMasterBarByIndex(e){return this._masterBarLookup.has(e)?this._masterBarLookup.get(e):null}findMasterBar(e){const 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){const t=e.id;return this._beatLookup.has(t)?this._beatLookup.get(t):null}getBeatAtPos(e,t){let s=0,i=this.staffSystems.length-1,a=-1;for(;s<=i;){const e=(i+s)/2|0,r=this.staffSystems[e];if(t>=r.realBounds.y&&t<=r.realBounds.y+r.realBounds.h){a=e;break}t<r.realBounds.y?i=e-1:s=e+1}if(-1===a)return null;const r=this.staffSystems[a].findBarAtPos(e);return r?r.findBeatAtPos(e,t):null}getNoteAtPos(e,t,s){const i=this.findBeats(e);if(i)for(const e of i){const i=e.findNoteAtPos(t,s);if(i)return i}return null}}class xi{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 Si,this.renderFinished=new Si,this.partialRenderFinished=new Si,this.partialLayoutFinished=new Si,this.postRenderFinished=new bi,this.error=new Si,this.settings=t,this.recreateCanvas(),this.recreateLayout()}destroy(){this.score=null,this.canvas?.destroy(),this.canvas=null,this.layout=null,this.boundsLookup=null,this.tracks=null}recreateCanvas(){return this._currentRenderEngine!==this.settings.core.engine&&(this.canvas?.destroy(),this.canvas=ic.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=ic.getLayoutEngineFactory(this.settings.display.layoutMode).createLayout(this),this._currentLayoutMode=this.settings.display.layoutMode,!0)}renderScore(e,t){try{this.score=e;let s=null;if(null!=e&&null!=t){if(t){s=[];for(const i of t)i>=0&&i<e.tracks.length&&s.push(e.tracks[i])}else s=e.tracks.slice(0);0===s.length&&e.tracks.length>0&&s.push(e.tracks[0])}this.tracks=s,this.render()}catch(e){this.error.trigger(e)}}renderTracks(e){0===e.length?this.score=null:this.score=e[0].score,this.tracks=e,this.render()}updateSettings(e){this.settings=e}renderResult(e){try{const t=this.layout;t?(he.debug("Rendering",`Request render of lazy partial ${e}`),t.renderLazyPartial(e)):he.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 Ni,this.recreateCanvas(),this.canvas.lineWidth=1,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){he.debug("Rendering",`Rendering ${this.tracks.length} tracks`);for(let e=0;e<this.tracks.length;e++){const t=this.tracks[e];he.debug("Rendering",`Track ${e}: ${t.name}`)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),he.debug("Rendering","Rendering finished")}else he.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),he.debug("Rendering","Clearing finished");else he.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(he.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(he.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new Ni,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):he.debug("Rendering","Current layout does not support dynamic resizing, nothing was done",null),he.debug("Rendering","Resize finished")}layoutAndRender(){he.debug("Rendering",`Rendering at scale ${this.settings.display.scale} with layout ${this.layout.name}`,null),this.layout.layoutAndRender(),this._renderedTracks=this.tracks,this.onRenderFinished(),this.postRenderFinished.trigger()}onRenderFinished(){this.boundsLookup?.finish(this.settings.display.scale);const e=new yi;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}const vi=Object.freeze(Object.defineProperty({__proto__:null,BarBounds:_i,get BeamDirection(){return je},BeatBounds:wi,Bounds:Is,BoundsLookup:Ni,MasterBarBounds:Bi,NoteBounds:ki,RenderFinishedEventArgs:yi,ScoreRenderer:xi,StaffSystemBounds:Ti},Symbol.toStringTag,{value:"Module"}));class Pi{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class Ci{constructor(e){this._registeredAccidentals=new Map,this._appliedScoreLines=new Map,this._appliedScoreLinesByValue=new Map,this._notesByValue=new Map,this._beatLines=new Map,this.maxLineBeat=null,this.minLineBeat=null,this.maxLine=-1e3,this.minLine=-1e3,this._barRenderer=e,this._bar=e.bar}static getPercussionLine(e,t){return t<e.staff.track.percussionArticulations.length?e.staff.track.percussionArticulations[t].staffLine:me.getArticulationByValue(t)?.staffLine??0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case B.ForceDoubleFlat:t+=2;break;case B.ForceDoubleSharp:t-=2;break;case B.ForceFlat:t+=1;break;case B.ForceSharp:t-=1}return t}applyAccidental(e){const t=Ci.getNoteValue(e),s=e.hasQuarterToneOffset;return this.getAccidental(t,s,e.beat,!1,e)}applyAccidentalForValue(e,t,s,i){return this.getAccidental(t,s,e,i,null)}static computeLineWithoutAccidentals(e,t){let s=0;const i=Ci.getNoteValue(t);return s=t.isPercussion?Ci.getPercussionLine(e,i):Ci.calculateNoteSteps(e.masterBar.keySignature,e.clef,i),s}static computeAccidental(e,t,s,i,a=null){const r=e+7,n=s%12,o=r<7?tt.Flat:tt.Sharp,h=Ci.KeySignatureLookup[r][n],l=Ci.AccidentalNotes[n];let c=tt.None;if(i)switch(c=l?o:tt.Natural,c){case tt.Natural:c=tt.NaturalQuarterNoteUp;break;case tt.Sharp:c=tt.SharpQuarterNoteUp;break;case tt.Flat:c=tt.FlatQuarterNoteUp}else{switch(t){case B.ForceSharp:c=tt.Sharp;break;case B.ForceDoubleSharp:c=tt.DoubleSharp;break;case B.ForceFlat:c=tt.Flat;break;case B.ForceDoubleFlat:c=tt.DoubleFlat;break;default:l?c=o:h&&(c=tt.Natural)}c!==tt.None?null!=a?a===c&&(c=tt.None):h&&c===o&&(c=tt.None):null!==a&&(c=a===tt.Natural?tt.None:tt.Natural)}return c}getAccidental(e,t,s,i,a=null){let r=0,n=tt.None;if(null!=a?a.isPercussion:this._bar.staff.isPercussion)r=Ci.getPercussionLine(this._bar,e);else{const s=a?a.accidentalMode:B.Default;r=Ci.calculateNoteSteps(this._bar.masterBar.keySignature,this._bar.clef,e);const i=this._registeredAccidentals.has(r)?this._registeredAccidentals.get(r):null;n=Ci.computeAccidental(this._bar.masterBar.keySignature,s,e,t,i);let o=!1;switch(n){case tt.NaturalQuarterNoteUp:case tt.SharpQuarterNoteUp:case tt.FlatQuarterNoteUp:break;default:if(a&&a.isTieDestination&&0===a.beat.index){const e=this._barRenderer.scoreRenderer.layout?.getRendererForBar(this._barRenderer.staff.staveId,a.tieOrigin.beat.voice.bar);if(e&&e.staff===this._barRenderer.staff){e.accidentalHelper.getNoteLine(a.tieOrigin)===r&&(o=!0)}}o?n=tt.None:n!==tt.None&&this._registeredAccidentals.set(r,n)}}return a?(this._appliedScoreLines.set(a.id,r),this._notesByValue.set(e,a)):this._appliedScoreLinesByValue.set(e,r),(-1e3===this.minLine||this.minLine<r)&&(this.minLine=r,this.minLineBeat=s),(-1e3===this.maxLine||this.maxLine>r)&&(this.maxLine=r,this.maxLineBeat=s),i||this.registerLine(s,r),n}registerLine(e,t){let s;this._beatLines.has(e.id)?s=this._beatLines.get(e.id):(s=new Pi,this._beatLines.set(e.id,s)),(-1e3===s.minLine||t<s.minLine)&&(s.minLine=t),(-1e3===s.minLine||t>s.maxLine)&&(s.maxLine=t)}getMaxLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).maxLine:0}getMinLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).minLine:0}static calculateNoteSteps(e,t,s){const i=e,a=t,r=s%12,n=(s/12|0)-1;let o=Ci.OctaveSteps[a];o-=n*Ci.StepsPerOctave;return o-=(ue.keySignatureIsSharp(i)||ue.keySignatureIsNatural(i)?Ci.SharpNoteSteps:Ci.FlatNoteSteps)[r],o}getNoteLine(e){return this._appliedScoreLines.get(e.id)}getNoteLineForValue(e,t=!1){return this._appliedScoreLinesByValue.has(e)?this._appliedScoreLinesByValue.get(e):t&&this._notesByValue.has(e)?this.getNoteLine(this._notesByValue.get(e)):0}}Ci.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]],Ci.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],Ci.StepsPerOctave=7,Ci.OctaveSteps=[38,32,30,26,38],Ci.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],Ci.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class Ei{constructor(){this.currentDynamics=y.F,this.slideOrigins=new Map,this.transpose=0,this.tieStarts=new Set,this.tieStartIds=new Map,this.slideOrigins=new Map,this.slurStarts=new Map}}class Fi extends ge{constructor(){super(...arguments),this.outputMidiChannel=-1,this.outputMidiProgram=-1,this.outputVolume=-1,this.outputBalance=-1}}class Di{constructor(e){this.instruments=new Map,this._instrumentIdToArticulationIndex=new Map,this._lyricsLine=0,this._lyricsLines=new Map,this.track=e}getLyricLine(e){if(this._lyricsLines.has(e))return this._lyricsLines.get(e);const t=this._lyricsLine;return this._lyricsLines.set(e,t),this._lyricsLine++,t}getOrCreateArticulation(e,t){const s=12*t.octave+t.tone,i=`${e}_${s}`;if(this._instrumentIdToArticulationIndex.has(i))return this._instrumentIdToArticulationIndex.get(i);let a;a=this.instruments.has(e)?this.instruments.get(e):Di.defaultNoteArticulation;const r=this.track.percussionArticulations.length,n=t.beat.voice.bar;let o;o=0===s?4:Ci.calculateNoteSteps(n.masterBar.keySignature,n.clef,s);const h=o-(9-(2*t.beat.voice.bar.staff.standardNotationLineCount-1)),l=new ge(a.elementType,h,a.outputMidiNumber,a.noteHeadDefault,a.noteHeadHalf,a.noteHeadWhole,a.techniqueSymbol,a.techniqueSymbolPlacement);return this._instrumentIdToArticulationIndex.set(i,r),this.track.percussionArticulations.push(l),r}}Di.defaultNoteArticulation=new ge("Default",0,0,I.NoteheadBlack,I.NoteheadHalf,I.NoteheadWhole);class Mi extends ct{constructor(){super(...arguments),this._idToTrackInfo=new Map,this._indexToTrackInfo=new Map,this._staffToContext=new Map,this._previousMasterBarNumber=-1,this._implicitBars=0,this._divisionsPerQuarterNote=1,this._currentDynamics=y.F,this._musicalPosition=0,this._lastBeat=null,this._nextMasterBarRepeatEnding=0,this._nextBeatAutomations=null,this._nextBeatChord=null,this._nextBeatCrescendo=null,this._nextBeatLetRing=!1,this._nextBeatPalmMute=!1,this._nextBeatOttavia=null,this._nextBeatText=null,this._simileMarkAllStaves=null,this._simileMarkPerStaff=null,this._isBeatSlash=!1,this._currentTrillStep=-1}get name(){return"MusicXML"}readScore(){const e=this.extractMusicXml(),t=new zs;try{t.parse(e)}catch(e){throw new dt("Unsupported format",e)}return this._score=new lt,this._score.tempo=120,this._score.stylesheet.hideDynamics=!0,this.parseDom(t),this.consolidate(),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}consolidate(){const e=new Set([kt.PercussionChannel]);for(const t of this._score.tracks){if(t.playbackInfo.primaryChannel!==kt.PercussionChannel)for(;e.has(t.playbackInfo.primaryChannel);)t.playbackInfo.primaryChannel++;if(e.add(t.playbackInfo.primaryChannel),t.playbackInfo.secondaryChannel!==kt.PercussionChannel)for(;e.has(t.playbackInfo.secondaryChannel);)t.playbackInfo.secondaryChannel++;e.add(t.playbackInfo.secondaryChannel);for(const e of t.staves){for(const t of e.bars)for(const e of t.voices)if(e.isEmpty&&0===e.beats.length){const t=new xe;t.isEmpty=!0,e.addBeat(t)}const t=0===e.bars.length?1:e.bars[0].voices.length;for(;e.bars.length<this._score.masterBars.length;){const s=new te;e.addBar(s);const i=s.previousBar;i&&(s.clef=i.clef,s.clefOttava=i.clefOttava);for(let e=0;e<t;e++){const e=new Pe;s.addVoice(e);const t=new xe;t.isEmpty=!0,e.addBeat(t)}}}}}extractMusicXml(){const e=new oi(this.data);let t;try{t=e.read()}catch(e){t=[]}if(0===t.length)return this.data.reset(),wt.toString(this.data.readAll(),this.settings.importer.encoding);const s=t.find((e=>"META-INF/container.xml"===e.fullName));if(!s)throw new dt("No compressed MusicXML");const i=new zs;try{i.parse(wt.toString(s.data,this.settings.importer.encoding))}catch(e){throw new dt("Malformed container.xml, could not parse as XML",e)}const a=i.firstElement;if(!a||"container"!==a.localName)throw new dt("Malformed container.xml, root element not 'container'");const r=a.findChildElement("rootfiles");if(!r)throw new dt("Malformed container.xml, 'container/rootfiles' not found");let n="";for(const e of r.childElements())if("rootfile"===e.localName){n=e.getAttribute("full-path");break}if(!n)throw new dt("Unsupported compressed MusicXML, missing rootfile");const o=t.find((e=>e.fullName===n));if(!o)throw new dt(`Malformed container.xml, '${n}' not contained in zip`);return wt.toString(o.data,this.settings.importer.encoding)}parseDom(e){const t=e.firstElement;if(!t)throw new dt("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":this.parseTimewise(t);break;default:throw new dt("Unsupported format")}}parsePartwise(e){for(const t of e.childElements())switch(t.localName){case"credit":this.parseCredit(t);break;case"identification":this.parseIdentification(t);break;case"movement-title":this.parseMovementTitle(t);break;case"part":this.parsePartwisePart(t);break;case"part-list":this.parsePartList(t);break;case"work":this.parseWork(t)}}parseTimewise(e){for(const t of e.childElements())switch(t.localName){case"credit":this.parseCredit(t);break;case"identification":this.parseIdentification(t);break;case"movement-title":this.parseMovementTitle(t);break;case"part-list":this.parsePartList(t);break;case"work":this.parseWork(t);break;case"measure":this.parseTimewiseMeasure(t)}}parseCredit(e){if("1"!==e.getAttribute("page","1"))return;const t=[];let s=null,i="";for(const a of e.childElements())switch(a.localName){case"credit-type":t.push(a.innerText);break;case"credit-words":null===s&&(s=a),i+=a.innerText}if(t.length>0)for(const e of t)switch(e){case"title":this._score.title=Mi.sanitizeDisplay(i);break;case"subtitle":this._score.subTitle=Mi.sanitizeDisplay(i);break;case"composer":case"arranger":this._score.artist=Mi.sanitizeDisplay(i);break;case"lyricist":this._score.words=Mi.sanitizeDisplay(i);break;case"rights":this._score.copyright=Mi.sanitizeDisplay(i)}else if(s){const e=s.getAttribute("font-size","0"),t=s.getAttribute("font-size","top"),a=s.getAttribute("halign","left");if("top"===t){if(i.includes("copyright")||i.includes("Copyright")||i.includes("©")||i.includes("(c)")||i.includes("(C)"))return void(this._score.copyright=Mi.sanitizeDisplay(i));if("center"===a||"center"===e){if(0===this._score.title.length)return void(this._score.title=Mi.sanitizeDisplay(i));if(0===this._score.subTitle.length)return void(this._score.subTitle=Mi.sanitizeDisplay(i));if(0===this._score.album.length)return void(this._score.album=Mi.sanitizeDisplay(i))}else if(("right"===a||"right"===e)&&0===this._score.music.length)return void(this._score.music=Mi.sanitizeDisplay(i));if(0===this._score.artist.length)return void(this._score.artist=Mi.sanitizeDisplay(i));if(0===this._score.words.length)return void(this._score.words=Mi.sanitizeDisplay(i))}}}static sanitizeDisplay(e){return e.replaceAll("\r","").replaceAll("\n"," ").replaceAll("\t","  ").replaceAll(" "," ")}parseIdentification(e){for(const t of e.childElements())switch(t.localName){case"creator":if(t.attributes.has("type"))switch(t.attributes.get("type")){case"composer":this._score.artist=Mi.sanitizeDisplay(t.innerText);break;case"lyricist":this._score.words=Mi.sanitizeDisplay(t.innerText);break;case"arranger":this._score.music=Mi.sanitizeDisplay(t.innerText)}else this._score.artist=Mi.sanitizeDisplay(t.innerText);break;case"rights":this._score.copyright.length>0&&(this._score.copyright+=", "),this._score.copyright+=t.innerText,t.attributes.has("type")&&(this._score.copyright+=` (${t.attributes.get("type")})`);break;case"encoding":this.parseEncoding(t)}}parseEncoding(e){for(const t of e.childElements())switch(t.localName){case"encoder":this._score.tab.length>0&&(this._score.tab+=", "),this._score.tab+=t.innerText,t.attributes.has("type")&&(this._score.tab+=` (${t.attributes.get("type")})`);break;case"encoding-description":this._score.notices+=Mi.sanitizeDisplay(t.innerText)}}parseMovementTitle(e){0===this._score.title.length?this._score.title=Mi.sanitizeDisplay(e.innerText):this._score.subTitle=Mi.sanitizeDisplay(e.innerText)}parsePartList(e){for(const t of e.childElements())if("score-part"===t.localName)this.parseScorePart(t)}parseScorePart(e){const t=new St;t.ensureStaveCount(1),this._score.addTrack(t);const s=e.attributes.get("id"),i=new Di(t);this._idToTrackInfo.set(s,i),this._indexToTrackInfo.set(t.index,i);for(const s of e.childElements())switch(s.localName){case"part-name":t.name=Mi.sanitizeDisplay(s.innerText);break;case"part-name-display":t.name=this.parsePartDisplayAsText(s);break;case"part-abbreviation":t.shortName=Mi.sanitizeDisplay(s.innerText);break;case"part-abbreviation-display":t.shortName=this.parsePartDisplayAsText(s);break;case"score-instrument":this.parseScoreInstrument(s,i);break;case"midi-device":s.attributes.has("port")&&(t.playbackInfo.port=Number.parseInt(s.attributes.get("port"),10));break;case"midi-instrument":this.parseScorePartMidiInstrument(s,i)}i.firstArticulation&&(i.firstArticulation.outputMidiProgram>=0&&(t.playbackInfo.program=i.firstArticulation.outputMidiProgram),i.firstArticulation.outputBalance>=0&&(t.playbackInfo.balance=i.firstArticulation.outputBalance),i.firstArticulation.outputVolume>=0&&(t.playbackInfo.volume=i.firstArticulation.outputVolume),i.firstArticulation.outputMidiChannel>=0&&(t.playbackInfo.primaryChannel=i.firstArticulation.outputMidiChannel,t.playbackInfo.secondaryChannel=i.firstArticulation.outputMidiChannel))}parseScoreInstrument(e,t){const s=new Fi;t.firstArticulation||(t.firstArticulation=s),t.instruments.set(e.getAttribute("id",""),s)}parseScorePartMidiInstrument(e,t){const s=e.getAttribute("id","");if(!t.instruments.has(s))return;const i=t.instruments.get(s);for(const t of e.childElements())switch(t.localName){case"midi-channel":i.outputMidiChannel=Number.parseInt(t.innerText)-1;break;case"midi-program":i.outputMidiProgram=Number.parseInt(t.innerText)-1;break;case"midi-unpitched":i.outputMidiNumber=Number.parseInt(t.innerText)-1;break;case"volume":i.outputVolume=Mi.interpolatePercent(Number.parseFloat(t.innerText));break;case"pan":i.outputBalance=Mi.interpolatePan(Number.parseFloat(t.innerText))}}static interpolatePercent(e){return 0|Mi.interpolate(0,100,0,16,e)}static interpolatePan(e){return 0|Mi.interpolate(-90,90,0,16,e)}static interpolate(e,t,s,i,a){return s+(i-s)*((a-e)/(t-e))}parsePartDisplayAsText(e){let t="";for(const s of e.childElements())switch(s.localName){case"display-text":t+=s.innerText;break;case"accidental-text":switch(s.innerText){case"sharp":t+="♯";break;case"natural":t+="♮";break;case"flat":t+="♭";break;case"double-sharp":t+="𝄪";break;case"sharp-sharp":t+="♯♯";break;case"flat-flat":t+="𝄫";break;case"natural-sharp":t+="♮♯";break;case"natural-flat":t+="♮♭";break;case"sharp-down":t+="𝄱";break;case"sharp-up":t+="𝄰";break;case"natural-down":t+="𝄯";break;case"natural-up":t+="𝄮";break;case"flat-down":t+="𝄭";break;case"flat-up":t+="𝄬";break;case"arrow-down":t+="↓";break;case"arrow-up":t+="↑";break;case"triple-sharp":t+="♯𝄪";break;case"triple-flat":t+="𝄬𝄬𝄬";break;case"sharp-1":t+="♯¹";break;case"sharp-2":t+="♯²";break;case"sharp-3":t+="♯³";break;case"sharp-4":t+="♯⁴";break;case"sharp-5":t+="♯⁵";break;case"flat-1":t+="♭¹";break;case"flat-2":t+="♭²";break;case"flat-3":t+="♭³";break;case"flat-4":t+="♭⁴";break;case"flat-5":t+="♭⁵"}}return Mi.sanitizeDisplay(t)}parseWork(e){for(const t of e.childElements())if("work-title"===t.localName)this._score.title=Mi.sanitizeDisplay(t.innerText)}parsePartwisePart(e){const t=e.attributes.get("id");if(!t||!this._idToTrackInfo.has(t))return;const s=this._idToTrackInfo.get(t).track;this._previousMasterBarNumber=-1;for(const t of e.childElements())if("measure"===t.localName)this.parsePartwiseMeasure(t,s)}parsePartwiseMeasure(e,t){const s=this.getOrCreateMasterBar(e);this.parsePartMeasure(e,s,t)}parseTimewiseMeasure(e){const t=this.getOrCreateMasterBar(e);for(const s of e.childElements())if("part"===s.localName)this.parseTimewisePart(s,t)}getOrCreateMasterBar(e){let t=Number.parseInt(e.attributes.get("number"));const s="yes"===e.attributes.get("implicit");for(Number.isNaN(t)?t=-1===this._previousMasterBarNumber?1:this._previousMasterBarNumber+1:0===t?t++:t+=this._implicitBars;this._score.masterBars.length<t;){const e=new le;s&&(e.isAnacrusis=!0,this._implicitBars++),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)}this._previousMasterBarNumber=t;return this._score.masterBars[t-1]}parseTimewisePart(e,t){const s=e.attributes.get("id");if(!s||!this._idToTrackInfo.has(s))return;const i=this._idToTrackInfo.get(s).track;this.parsePartMeasure(e,t,i)}parsePartMeasure(e,t,s){this._musicalPosition=0,this._lastBeat=null;const i=this.getOrCreateStaff(s,0);this.getOrCreateBar(i,t),t.alternateEndings=this._nextMasterBarRepeatEnding;for(const i of e.childElements())switch(i.localName){case"note":this.parseNote(i,t,s);break;case"backup":this.parseBackup(i);break;case"forward":this.parseForward(i);break;case"direction":this.parseDirection(i,t,s);break;case"attributes":this.parseAttributes(i,t,s);break;case"harmony":this.parseHarmony(i,s);break;case"print":this.parsePrint(i,t,s);break;case"sound":this.parseSound(i,t,s);break;case"barline":this.parseBarLine(i,t)}this.applySimileMarks(t,s)}parsePrint(e,t,s){("yes"===e.getAttribute("new-system","no")||"yes"===e.getAttribute("new-page","no"))&&s.addLineBreaks(t.index)}applySimileMarks(e,t){if(null!==this._simileMarkAllStaves){for(const s of t.staves){const t=this.getOrCreateBar(s,e);t.simileMark=this._simileMarkAllStaves,t.simileMark!==h.None&&this.clearBar(t)}this._simileMarkAllStaves===h.FirstOfDouble?this._simileMarkAllStaves=h.SecondOfDouble:this._simileMarkAllStaves=null}if(null!==this._simileMarkPerStaff){const s=Array.from(this._simileMarkPerStaff.keys());for(const i of s){const s=this.getOrCreateStaff(t,i),a=this.getOrCreateBar(s,e);a.simileMark=this._simileMarkPerStaff.get(i),a.simileMark!==h.None&&this.clearBar(a),a.simileMark===h.FirstOfDouble?this._simileMarkPerStaff.set(i,h.SecondOfDouble):this._simileMarkPerStaff.delete(i)}0===this._simileMarkPerStaff.size&&(this._simileMarkPerStaff=null)}}clearBar(e){for(const t of e.voices){const e=new xe;e.isEmpty=!0,t.addBeat(e)}}parseBarLine(e,t){for(const s of e.childElements())switch(s.localName){case"bar-style":this.parseBarStyle(s,t);break;case"ending":this.parseEnding(s,t);break;case"repeat":this.parseRepeat(s,t)}}parseRepeat(e,t){const s=e.getAttribute("direction");let i=Number.parseInt(e.getAttribute("times"));(i<0||Number.isNaN(i))&&(i=2),"backward"===s?t.repeatCount=i:"forward"===s&&(t.isRepeatStart=!0)}parseEnding(e,t){const s=e.getAttribute("number").split(",").map((e=>Number.parseInt(e)));let i=0;for(const e of s)i|=1<<e-1&255;switch(t.alternateEndings=i,e.getAttribute("type","")){case"start":this._nextMasterBarRepeatEnding=this._nextMasterBarRepeatEnding|i;break;case"stop":case"discontinue":this._nextMasterBarRepeatEnding=this._nextMasterBarRepeatEnding&~i}}parseBarStyle(e,t){if("light-light"===e.innerText)t.isDoubleBar=!0}parseSound(e,t,s){for(const s of e.childElements())switch(s.localName){case"midi-instrument":this.parseSoundMidiInstrument(s,t);break;case"swing":this.parseSwing(s,t)}if(e.attributes.has("coda")&&t.addDirection(qe.TargetCoda),e.attributes.has("tocoda")&&t.addDirection(qe.JumpDaCoda),e.attributes.has("dacapo")&&t.addDirection(qe.JumpDaCapo),e.attributes.has("dalsegno")&&t.addDirection(qe.JumpDalSegno),e.attributes.has("fine")&&t.addDirection(qe.TargetFine),e.attributes.has("segno")&&t.addDirection(qe.TargetSegno),e.attributes.has("pan")){this._nextBeatAutomations||(this._nextBeatAutomations=[]);const t=new ie;t.type=d.Balance,t.value=Mi.interpolatePan(Number.parseFloat(e.attributes.get("pan"))),this._nextBeatAutomations.push(t)}if(e.attributes.has("tempo")){this._nextBeatAutomations||(this._nextBeatAutomations=[]);const t=new ie;t.type=d.Tempo,t.value=Mi.interpolatePercent(Number.parseFloat(e.attributes.get("tempo"))),this._nextBeatAutomations.push(t)}}parseSwing(e,t){let s=0,i=0,a=null;for(const r of e.childElements())switch(r.localName){case"straight":return void(t.tripletFeel=M.NoTripletFeel);case"first":s=Number.parseInt(r.innerText);break;case"second":i=Number.parseInt(r.innerText);break;case"swing-type":a=this.parseBeatDuration(r)}a||(a=f.Eighth),a===f.Eighth?2===s&&1===i?t.tripletFeel=M.Triplet8th:3===s&&1===i?t.tripletFeel=M.Dotted8th:1===s&&3===i&&(t.tripletFeel=M.Scottish8th):a===f.Sixteenth&&(2===s&&1===i?t.tripletFeel=M.Triplet16th:3===s&&1===i?t.tripletFeel=M.Dotted16th:1===s&&3===i&&(t.tripletFeel=M.Scottish16th))}parseSoundMidiInstrument(e,t){let s;for(const t of e.childElements())switch(t.localName){case"midi-program":this._nextBeatAutomations||(this._nextBeatAutomations=[]),s=new ie,s.type=d.Instrument,s.value=Number.parseInt(t.innerText)-1,this._nextBeatAutomations.push(s);break;case"volume":this._nextBeatAutomations||(this._nextBeatAutomations=[]),s=new ie,s.type=d.Volume,s.value=Mi.interpolatePercent(Number.parseFloat(t.innerText)),this._nextBeatAutomations.push(s);break;case"pan":this._nextBeatAutomations||(this._nextBeatAutomations=[]),s=new ie,s.type=d.Balance,s.value=Mi.interpolatePan(Number.parseFloat(t.innerText)),this._nextBeatAutomations.push(s)}}parseHarmony(e,t){const s=new ut;let i=!1,a="";for(const t of e.childElements())switch(t.localName){case"root":s.name=this.parseHarmonyRoot(t);break;case"kind":s.name=s.name+this.parseHarmonyKind(t),"yes"===t.getAttribute("parentheses-degrees","no")&&(i=!0);break;case"frame":this.parseHarmonyFrame(t,s);break;case"degree":a+=this.parseDegree(t)}a&&(s.name+=i?`(${a})`:a),null===this._nextBeatChord&&(this._nextBeatChord=s)}parseDegree(e){let t="",s="",i="";for(const a of e.childElements())switch(a.localName){case"degree-value":t=a.innerText;break;case"degree-alter":switch(a.innerText){case"-1":s="♭";break;case"1":s="♯"}break;case"degree-type":i+=a.getAttribute("text","")}return`${i}${s}${t}`}parseHarmonyRoot(e){let t="",s="";for(const i of e.childElements())switch(i.localName){case"root-step":t=i.innerText;break;case"root-alter":switch(Number.parseFloat(i.innerText)){case-2:s="bb";break;case-1:s="b";break;case 0:s="";break;case 1:s="#";break;case 2:s="##"}}return t+s}parseHarmonyKind(e){const t=e.getAttribute("text");let s="";if(t)s=t;else{const t=e.innerText;switch(t){case"major":s="";break;case"minor":s="m";break;case"augmented":s="+";break;case"diminished":s="○";break;case"dominant":s="7";break;case"major-seventh":s="7M";break;case"minor-seventh":s="m7";break;case"diminished-seventh":s="○7";break;case"augmented-seventh":s="+7";break;case"half-diminished":s="⍉";break;case"major-minor":s="mMaj";break;case"major-sixth":s="maj6";break;case"minor-sixth":s="m6";break;case"dominant-ninth":s="9";break;case"major-ninth":s="maj9";break;case"minor-ninth":s="m9";break;case"dominant-11th":s="11";break;case"major-11th":s="maj11";break;case"minor-11th":s="m11";break;case"dominant-13th":s="13";break;case"major-13th":s="maj13";break;case"minor-13th":s="m13";break;case"suspended-second":s="sus2";break;case"suspended-fourth":s="sus4";break;case"Neapolitan":s="♭II";break;case"Italian":s="It⁺⁶";break;case"French":case"German":s="Fr⁺⁶";break;default:s=t}}return s}parseHarmonyFrame(e,t){for(const s of e.childElements())switch(s.localName){case"frame-strings":const e=Number.parseInt(s.innerText);t.strings=new Array(e);for(let s=0;s<e;s++)t.strings[s]=-1;break;case"first-fret":t.firstFret=Number.parseInt(s.innerText);break;case"frame-note":let i=null,a=null;for(const e of s.childElements())switch(e.localName){case"string":i=Number.parseInt(e.innerText);break;case"fret":a=Number.parseInt(e.innerText),i&&a>=0&&(t.strings[i-1]=a);break;case"barre":i&&a&&"start"===e.getAttribute("type")&&t.barreFrets.push(a)}}}parseAttributes(e,t,s){let i,a,r;if(null==this._lastBeat)for(const n of e.childElements())switch(n.localName){case"divisions":this._divisionsPerQuarterNote=Number.parseFloat(n.innerText);break;case"key":this.parseKey(n,t);break;case"time":this.parseTime(n,t);break;case"staves":s.ensureStaveCount(Number.parseInt(n.innerText));break;case"clef":i=Number.parseInt(n.getAttribute("number","1"))-1,a=this.getOrCreateStaff(s,i),r=this.getOrCreateBar(a,t),this.parseClef(n,r);break;case"staff-details":i=Number.parseInt(n.getAttribute("number","1"))-1,a=this.getOrCreateStaff(s,i),this.parseStaffDetails(n,a);break;case"transpose":this.parseTranspose(n,s);break;case"measure-style":this.parseMeasureStyle(n,s,!1)}else for(const t of e.childElements())switch(t.localName){case"divisions":this._divisionsPerQuarterNote=Number.parseFloat(t.innerText);break;case"measure-style":this.parseMeasureStyle(t,s,!0)}}parseMeasureStyle(e,t,s){for(const t of e.childElements())switch(t.localName){case"measure-repeat":if(!s){let s=null;switch(t.getAttribute("type")){case"start":switch(Number.parseInt(t.getAttribute("slashes","1"))){case 1:s=h.Simple;break;case 2:s=h.FirstOfDouble}break;case"stop":s=null}if(e.attributes.has("number")){this._simileMarkPerStaff=this._simileMarkPerStaff??new Map;const t=Number.parseInt(e.attributes.get("number"))-1;null==s?this._simileMarkPerStaff.delete(t):this._simileMarkPerStaff.set(t,s)}else this._simileMarkAllStaves=s}break;case"slash":switch(t.getAttribute("type")){case"start":this._isBeatSlash=!0;break;case"stop":this._isBeatSlash=!1}}}parseTranspose(e,t){let s=0;for(const t of e.childElements())switch(t.localName){case"chromatic":s+=Number.parseFloat(t.innerText);break;case"octave-change":s+=12*Number.parseFloat(t.innerText)}if(e.attributes.has("number")){const i=this.getOrCreateStaff(t,Number.parseInt(e.attributes.get("number"))-1);this.getStaffContext(i).transpose=s,i.displayTranspositionPitch=s}else for(const e of t.staves)this.getStaffContext(e).transpose=s,e.displayTranspositionPitch=s}parseStaffDetails(e,t){for(const s of e.childElements())switch(s.localName){case"staff-lines":t.standardNotationLineCount=Number.parseInt(s.innerText);break;case"staff-tuning":this.parseStaffTuning(s,t);break;case"capo":t.capo=Number.parseInt(s.innerText)}}parseStaffTuning(e,t){0===t.stringTuning.tunings.length&&(t.showTablature=!0,t.showStandardNotation=!1,t.stringTuning.tunings=new Array(t.standardNotationLineCount).fill(0));const s=Number.parseInt(e.getAttribute("line"));let i="C",a="",r=0;for(const t of e.childElements())switch(t.localName){case"tuning-step":i=t.innerText;break;case"tuning-alter":r=Number.parseFloat(t.innerText);break;case"tuning-octave":a=t.innerText}const n=ue.getTuningForText(i+a)+r;t.tuning[t.tuning.length-s]=n}parseClef(e,t){let s="s",i=0;for(const a of e.childElements())switch(a.localName){case"sign":s=a.innerText.toLowerCase();break;case"line":i=Number.parseInt(a.innerText);break;case"clef-octave-change":switch(Number.parseInt(a.innerText)){case-2:t.clefOttava=o._15mb;break;case-1:t.clefOttava=o._8vb;break;case 1:t.clefOttava=o._8va;break;case 2:t.clefOttava=o._15mb}}switch(s){case"g":default:t.clef=n.G2;break;case"f":t.clef=n.F4;break;case"c":t.clef=3===i?n.C3:n.C4;break;case"percussion":t.clef=n.Neutral,t.staff.isPercussion=!0;break;case"tab":t.clef=n.G2,t.staff.showTablature=!0}}parseTime(e,t){let s=!1,i=!1;for(const a of e.childElements()){const e=a.innerText;switch(a.localName){case"beats":s||(-1===e.indexOf("+")?t.timeSignatureNumerator=Number.parseInt(e):t.timeSignatureNumerator=e.split("+").map((e=>Number.parseInt(e))).reduce(((e,t)=>t+e),0),s=!0);break;case"beat-type":i||(-1===e.indexOf("+")?t.timeSignatureDenominator=Number.parseInt(e):t.timeSignatureDenominator=e.split("+").map((e=>Number.parseInt(e))).reduce(((e,t)=>t+e),0),i=!0)}}switch(e.getAttribute("symbol","")){case"common":case"cut":t.timeSignatureCommon=!0}}parseKey(e,t){let s=-F.C,i="";for(const t of e.childElements())switch(t.localName){case"fifths":s=Number.parseInt(t.innerText);break;case"mode":i=t.innerText}t.keySignature=-7<=s&&s<=7?s:F.C,t.keySignatureType="minor"===i?D.Minor:D.Major}parseDirection(e,t,s){const i=[];let a=null,r=-1,n=-1;for(const t of e.childElements())switch(t.localName){case"direction-type":i.push(t.firstElement);break;case"offset":a=Number.parseFloat(t.innerText);break;case"voice":break;case"staff":r=Number.parseInt(t.innerText)-1;break;case"sound":t.attributes.has("tempo")&&(n=Number.parseFloat(t.attributes.get("tempo")))}let o=null;o=r>=0?this.getOrCreateStaff(s,r):null!==this._lastBeat?this._lastBeat.voice.bar.staff:this.getOrCreateStaff(s,0);const h=o?this.getOrCreateBar(o,t):null,c=()=>{let e=this._musicalPosition;null!==a&&(e+=a);return e/t.calculateDuration(!1)};if(n>0){const e=new ie;e.type=d.Tempo,e.value=n,e.ratioPosition=c(),this.hasSameTempo(t,e)||(t.tempoAutomations.push(e),0===t.index&&(t.score.tempo=e.value))}let u="";for(const e of i)switch(e.localName){case"rehearsal":t.section=new gt,t.section.marker=e.innerText;break;case"segno":t.addDirection(qe.TargetSegno);break;case"coda":t.addDirection(qe.TargetCoda);break;case"words":u=e.innerText;break;case"wedge":switch(e.getAttribute("type")){case"crescendo":this._nextBeatCrescendo=m.Crescendo;break;case"diminuendo":this._nextBeatCrescendo=m.Decrescendo;break;case"stop":this._nextBeatCrescendo=null}break;case"dynamics":const s=this.parseDynamics(e);null!==s&&(this._currentDynamics=s,this._score.stylesheet.hideDynamics=!1);break;case"dashes":const i=e.getAttribute("type","start");switch(u){case"LetRing":this._nextBeatLetRing="start"===i||"continue"===i;break;case"P.M.":this._nextBeatPalmMute="start"===i||"continue"===i}u="";break;case"pedal":const a=this.parsePedal(e);if(a&&h){a.ratioPosition=c();const e=h.sustainPedals.length>0&&h.sustainPedals[h.sustainPedals.length-1].pedalType!==l.Up;(a.pedalType!==l.Up||e)&&h.sustainPedals.push(a)}break;case"metronome":this.parseMetronome(e,t,c());break;case"octave-shift":this._nextBeatOttavia=this.parseOctaveShift(e)}u&&(this._nextBeatText=u)}parseOctaveShift(e){const t=e.getAttribute("type");switch(Number.parseInt(e.getAttribute("size","8"))){case 15:switch(t){case"up":return o._15mb;case"down":return o._15ma;case"stop":return o.Regular;case"continue":return this._nextBeatOttavia}break;case 8:switch(t){case"up":return o._8vb;case"down":return o._8va;case"stop":return o.Regular;case"continue":return this._nextBeatOttavia}}return null}parseMetronome(e,t,s){let i=null,a=-1;for(const t of e.childElements())switch(t.localName){case"beat-unit":i=this.parseBeatDuration(t);break;case"per-minute":a=Number.parseFloat(t.innerText)}if(null!==i&&a>0){const e=new ie;e.type=d.Tempo,e.value=a*(i/4)|0,e.ratioPosition=s,this.hasSameTempo(t,e)||(t.tempoAutomations.push(e),0===t.index&&(t.score.tempo=e.value))}}hasSameTempo(e,t){for(const s of e.tempoAutomations)if(t.ratioPosition===s.ratioPosition&&t.value===s.value)return!0;return!1}parsePedal(e){const t=new Z;switch(e.getAttribute("type")){case"start":t.pedalType=l.Down;break;case"stop":t.pedalType=l.Up;break;case"continue":t.pedalType=l.Hold;break;default:return null}return t}parseDynamics(e){for(const t of e.childElements())switch(t.localName){case"p":return y.P;case"pp":return y.PP;case"ppp":return y.PPP;case"f":return y.F;case"ff":return y.FF;case"fff":return y.FFF;case"mp":return y.MP;case"mf":return y.MF}return null}parseForward(e){for(const t of e.childElements())if("duration"===t.localName)this._musicalPosition+=this.musicXmlDivisionsToAlphaTabTicks(Number.parseFloat(t.innerText))}parseBackup(e){for(const t of e.childElements())if("duration"===t.localName){if(this._lastBeat){let e=this._musicalPosition;e-=this.musicXmlDivisionsToAlphaTabTicks(Number.parseFloat(t.innerText)),e<0&&(e=0),this._musicalPosition=e}}}getOrCreateStaff(e,t){for(;e.staves.length<=t;){const t=new yt;e.addStaff(t),this._score.masterBars.length>0&&this.getOrCreateBar(t,this._score.masterBars[this._score.masterBars.length-1])}return e.staves[t]}getOrCreateBar(e,t){const s=0===e.bars.length?1:e.bars[0].voices.length;for(;e.bars.length<=t.index;){const t=new te;e.addBar(t),t.previousBar&&(t.clef=t.previousBar.clef,t.clefOttava=t.previousBar.clefOttava);for(let e=0;e<s;e++){const e=new Pe;t.addVoice(e)}}return e.bars[t.index]}getOrCreateVoice(e,t){let s=!1;for(;e.voices.length<=t;)e.addVoice(new Pe),s=!0;if(s)for(const s of e.staff.bars)for(;s.voices.length<=t;)s.addVoice(new Pe);return e.voices[t]}parseNote(e,t,s){let i=null,a=b.None,r=0,n=J.ForceSplitToNext,o=!1,h=0,l=0,c=-1,d=null,u=0,p=-1,g=-1,m=null,y=null,S=!1,_=null;const w="no"!==e.getAttribute("print-object","yes"),B=()=>{if(null!==i)return;o&&!this._lastBeat&&(he.warning("MusicXML","Malformed MusicXML, <chord /> cannot be set on the first note of a measure"),o=!1),o&&!y&&(he.warning("MusicXML","Cannot mix <chord /> and <rest />"),o=!1);const e=this.getOrCreateStaff(s,h);if(o)return i=this._lastBeat,void i.addNote(y);const B=this.getOrCreateBar(e,t),k=this.getOrCreateVoice(B,l),T=0===k.beats.length?0:k.beats[k.beats.length-1].displayEnd;let N=this._musicalPosition-T;if(N>0){if(this._lastBeat&&this._lastBeat.beamingMode===J.ForceMergeWithNext&&this._lastBeat.voice.bar.staff.index!==h&&k.beats.length>0&&k.beats[k.beats.length-1].beamingMode===J.ForceMergeWithNext){const e=k.beats[k.beats.length-1].duration;for(;N>0;){const t=this.createRestForGap(N,e);if(null===t)break;this.insertBeatToVoice(t,k),N-=t.playbackDuration}}if(N>0){const e=new xe;e.dynamics=this._currentDynamics,e.isEmpty=!0,e.duration=f.TwoHundredFiftySixth,e.overrideDisplayDuration=N,e.updateDurations(),this.insertBeatToVoice(e,k)}}else N<0&&he.error("MusicXML","Unsupported forward/backup detected. Cannot fill new beats into already filled area of voice");c<0&&null!==d&&(c=se.toTicks(d),u>0&&(c=se.applyDot(c,2===u)));const x=new xe;i=x,x.beamingMode=n,x.isEmpty=!1,x.dynamics=this._currentDynamics,this._isBeatSlash&&(x.slashed=!0);const v=this._nextBeatAutomations;if(this._nextBeatAutomations=null,null!==v)for(const e of v)x.automations.push(e);const P=this._nextBeatChord;this._nextBeatChord=null,null!==P&&(x.chordId=P.uniqueId,k.bar.staff.hasChord(P.uniqueId)||k.bar.staff.addChord(x.chordId,P));const C=this._nextBeatCrescendo;null!==C&&(x.crescendo=C);const E=this._nextBeatOttavia;if(null!==E&&(x.ottava=E),x.isLetRing=this._nextBeatLetRing,x.isPalmMute=this._nextBeatPalmMute,this._nextBeatText&&(x.text=this._nextBeatText,this._nextBeatText=null),null!==y&&x.addNote(y),this.insertBeatToVoice(x,k),null!==y){y.isVisible=w;const e=this._indexToTrackInfo.get(s.index);null!==_?y.percussionArticulation=e.getOrCreateArticulation(_,y):S||(y.percussionArticulation=e.getOrCreateArticulation("",y))}a!==b.None?(x.graceType=a,this.applyBeatDurationFromTicks(x,r,null,!1)):(x.tupletNumerator=p,x.tupletDenominator=g,x.dots=u,x.preferredBeamDirection=m,this.applyBeatDurationFromTicks(x,c,d,!0)),this._musicalPosition=x.displayEnd,this._lastBeat=x};for(const t of e.childElements())switch(t.localName){case"grace":const e=Number.parseFloat(t.getAttribute("make-time","-1"));e>=0?(r=this.musicXmlDivisionsToAlphaTabTicks(e),a=b.BeforeBeat):a=b.OnBeat,"yes"===t.getAttribute("slash")&&(a=b.BeforeBeat);break;case"chord":o=!0;break;case"cue":return;case"pitch":y=this.parsePitch(t),S=!0;break;case"unpitched":y=this.parseUnpitched(t,s);break;case"rest":y=null,null===d&&(d=f.Whole);break;case"duration":c=this.parseDuration(t);break;case"instrument":null===y?he.warning("MusicXML","Malformed MusicXML, missing pitch or unpitched for note"):_=t.getAttribute("id","");break;case"voice":l=Number.parseInt(t.innerText),Number.isNaN(l)?(he.warning("MusicXML","Voices need to be specified as numbers"),l=0):l-=1;break;case"type":d=this.parseBeatDuration(t);break;case"dot":u++;break;case"accidental":null===y?he.warning("MusicXML","Malformed MusicXML, missing pitch or unpitched for note"):this.parseAccidental(t,y);break;case"time-modification":for(const e of t.childElements())switch(e.localName){case"actual-notes":p=Number.parseInt(e.innerText);break;case"normal-notes":g=Number.parseInt(e.innerText)}break;case"stem":m=this.parseStem(t);break;case"notehead":null===y?he.warning("MusicXML","Malformed MusicXML, missing pitch or unpitched for note"):this.parseNoteHead(t,y,d??f.Quarter,m??this.estimateBeamDirection(y));break;case"staff":h=Number.parseInt(t.innerText)-1;break;case"beam":if("1"===t.getAttribute("number","1"))switch(t.innerText){case"begin":case"continue":n=J.ForceMergeWithNext;break;case"end":n=J.ForceSplitToNext}break;case"notations":B(),this.parseNotations(t,y,i);break;case"lyric":B(),this.parseLyric(t,i,s)}if(S){const e=this.getOrCreateStaff(s,h),t=this.getStaffContext(e).transpose;if(0!==t){const e=12*y.octave+y.tone+t;y.octave=e/12|0,y.tone=e-12*y.octave}}B()}estimateBeamDirection(e){return e.calculateRealValue(!1,!1)<Mi.B4Value?je.Down:je.Up}parseNoteHead(e,t,s,i){"yes"===e.getAttribute("parentheses","no")&&(t.isGhost=!0);const a=e.getAttribute("filled","");let r;switch("yes"===a?r=!0:"no"===a&&(r=!1),t.style=new ye,e.innerText){case"arrow down":t.style.noteHeadCenterOnStem=!0,this.applyNoteHead(t,s,r,I.NoteheadTriangleDownDoubleWhole,I.NoteheadTriangleDownWhole,I.NoteheadTriangleDownHalf,I.NoteheadTriangleDownBlack);break;case"arrow up":t.style.noteHeadCenterOnStem=!0,this.applyNoteHead(t,s,r,I.NoteheadTriangleUpDoubleWhole,I.NoteheadTriangleUpWhole,I.NoteheadTriangleUpHalf,I.NoteheadTriangleUpBlack);break;case"back slashed":this.applyNoteHead(t,s,r,I.NoteheadSlashedDoubleWhole2,I.NoteheadSlashedWhole2,I.NoteheadSlashedHalf2,I.NoteheadSlashedBlack2);break;case"circle dot":t.style.noteHead=I.NoteheadRoundWhiteWithDot;break;case"circle-x":this.applyNoteHead(t,s,r,I.NoteheadCircleXDoubleWhole,I.NoteheadCircleXWhole,I.NoteheadCircleXHalf,I.NoteheadCircleX);break;case"circled":this.applyNoteHead(t,s,r,I.NoteheadCircledDoubleWhole,I.NoteheadCircledWhole,I.NoteheadCircledHalf,I.NoteheadCircledBlack);break;case"cluster":this.applyNoteHead(t,s,r,I.NoteheadClusterDoubleWhole3rd,I.NoteheadClusterWhole3rd,I.NoteheadClusterHalf3rd,I.NoteheadClusterQuarter3rd);break;case"cross":this.applyNoteHead(t,s,r,I.NoteheadPlusDoubleWhole,I.NoteheadPlusWhole,I.NoteheadPlusHalf,I.NoteheadPlusBlack);break;case"diamond":this.applyNoteHead(t,s,r,I.NoteheadDiamondDoubleWhole,I.NoteheadDiamondWhole,I.NoteheadDiamondHalf,I.NoteheadDiamondBlack);break;case"do":this.applyNoteHead(t,s,r,I.NoteShapeTriangleUpWhite,I.NoteShapeTriangleUpWhite,I.NoteShapeTriangleUpWhite,I.NoteShapeTriangleUpBlack);break;case"fa":i===je.Up?this.applyNoteHead(t,s,r,I.NoteShapeTriangleRightWhite,I.NoteShapeTriangleRightWhite,I.NoteShapeTriangleRightWhite,I.NoteShapeTriangleRightBlack):this.applyNoteHead(t,s,r,I.NoteShapeTriangleLeftWhite,I.NoteShapeTriangleLeftWhite,I.NoteShapeTriangleLeftWhite,I.NoteShapeTriangleLeftBlack);break;case"fa up":this.applyNoteHead(t,s,r,I.NoteShapeTriangleLeftWhite,I.NoteShapeTriangleLeftWhite,I.NoteShapeTriangleLeftWhite,I.NoteShapeTriangleLeftBlack);break;case"inverted triangle":this.applyNoteHead(t,s,r,I.NoteheadTriangleDownDoubleWhole,I.NoteheadTriangleDownWhole,I.NoteheadTriangleDownHalf,I.NoteheadTriangleDownBlack);break;case"la":case"square":this.applyNoteHead(t,s,r,I.NoteShapeSquareWhite,I.NoteShapeSquareWhite,I.NoteShapeSquareWhite,I.NoteShapeSquareBlack);break;case"left triangle":this.applyNoteHead(t,s,r,I.NoteheadTriangleRightWhite,I.NoteheadTriangleRightWhite,I.NoteheadTriangleRightWhite,I.NoteheadTriangleRightBlack);break;case"mi":this.applyNoteHead(t,s,r,I.NoteShapeDiamondWhite,I.NoteShapeDiamondWhite,I.NoteShapeDiamondWhite,I.NoteShapeDiamondBlack);break;case"none":t.style.noteHead=I.NoteheadNull;break;case"normal":this.applyNoteHead(t,s,r,I.NoteheadDoubleWhole,I.NoteheadWhole,I.NoteheadHalf,I.NoteheadBlack);break;case"re":this.applyNoteHead(t,s,r,I.NoteShapeMoonWhite,I.NoteShapeMoonWhite,I.NoteShapeMoonWhite,I.NoteShapeMoonBlack);break;case"rectangle":this.applyNoteHead(t,s,r,I.NoteheadSquareWhite,I.NoteheadSquareWhite,I.NoteheadSquareWhite,I.NoteheadSquareBlack);break;case"slash":this.applyNoteHead(t,s,r,I.NoteheadSlashWhiteWhole,I.NoteheadSlashWhiteWhole,I.NoteheadSlashWhiteHalf,I.NoteheadSlashVerticalEnds);break;case"slashed":this.applyNoteHead(t,s,r,I.NoteheadSlashedDoubleWhole1,I.NoteheadSlashedWhole1,I.NoteheadSlashedHalf1,I.NoteheadSlashedBlack1);break;case"so":this.applyNoteHead(t,s,r,I.NoteShapeRoundWhite,I.NoteShapeRoundWhite,I.NoteShapeRoundWhite,I.NoteShapeRoundBlack);break;case"ti":this.applyNoteHead(t,s,r,I.NoteShapeTriangleRoundWhite,I.NoteShapeTriangleRoundWhite,I.NoteShapeTriangleRoundWhite,I.NoteShapeTriangleRoundBlack);break;case"triangle":this.applyNoteHead(t,s,r,I.NoteheadTriangleUpDoubleWhole,I.NoteheadTriangleUpWhole,I.NoteheadTriangleUpHalf,I.NoteheadTriangleUpBlack);break;case"x":this.applyNoteHead(t,s,r,I.NoteheadXDoubleWhole,I.NoteheadXWhole,I.NoteheadXHalf,I.NoteheadXBlack)}}createRestForGap(e,t){let s=se.toTicks(t);for(;s>e;){if(t===f.TwoHundredFiftySixth)return null;t*=2,s=se.toTicks(t)}const i=new xe;return i.dynamics=this._currentDynamics,i.isEmpty=!1,i.duration=t,i.overrideDisplayDuration=s,i.updateDurations(),i}insertBeatToVoice(e,t){if(t.beats.length>0){const s=t.beats[t.beats.length-1];s.nextBeat=e,e.previousBeat=s;let i=s;for(;null!==i&&i.graceType!==b.None;)i=i.index>0?i.previousBeat:null;null!==i&&(e.displayStart=i.displayEnd)}t.addBeat(e)}musicXmlDivisionsToAlphaTabTicks(e){return e*se.QuarterTime/this._divisionsPerQuarterNote}parseBeatDuration(e){switch(e.innerText){case"1024th":case"512th":case"256th":return f.TwoHundredFiftySixth;case"128th":return f.OneHundredTwentyEighth;case"64th":return f.SixtyFourth;case"32nd":return f.ThirtySecond;case"16th":return f.Sixteenth;case"eighth":return f.Eighth;case"quarter":return f.Quarter;case"half":return f.Half;case"whole":return f.Whole;case"breve":return f.DoubleWhole;case"long":return f.QuadrupleWhole}return null}applyBeatDurationFromTicks(e,t,s,i){if(!s)for(let e=0;e<Mi.allDurations.length;e++){if(!(t>=Mi.allDurationTicks[e]))break;s=Mi.allDurations[e]}e.duration=s??f.Sixteenth,i&&(e.overrideDisplayDuration=t),e.updateDurations()}parseLyric(e,t,s){const i=this._indexToTrackInfo.get(s.index).getLyricLine(e.getAttribute("number",""));for(null===t.lyrics&&(t.lyrics=[]);t.lyrics.length<=i;)t.lyrics.push("");for(const s of e.childElements())switch(s.localName){case"text":t.lyrics[i]?t.lyrics[i]+=` ${s.innerText}`:t.lyrics[i]=s.innerText;break;case"elision":t.lyrics[i]+=s.innerText}}parseNotations(e,t,s){for(const i of e.childElements())switch(i.localName){case"tied":t&&this.parseTied(i,t,s.voice.bar.staff);break;case"slur":t&&this.parseSlur(i,t);break;case"glissando":t&&this.parseGlissando(i,t);break;case"slide":t&&this.parseSlide(i,t);break;case"ornaments":t&&this.parseOrnaments(i,t);break;case"technical":this.parseTechnical(i,t,s);break;case"articulations":t&&this.parseArticulations(i,t);break;case"dynamics":const e=this.parseDynamics(i);null!==e&&(s.dynamics=e,this._currentDynamics=e);break;case"fermata":this.parseFermata(i,s);break;case"arpeggiate":this.parseArpeggiate(i,s)}}getStaffContext(e){if(!this._staffToContext.has(e)){const t=new Ei;return this._staffToContext.set(e,t),t}return this._staffToContext.get(e)}parseGlissando(e,t){const s=e.getAttribute("type"),i=e.getAttribute("number","1"),a=this.getStaffContext(t.beat.voice.bar.staff);switch(s){case"start":a.slideOrigins.set(i,t);break;case"stop":if(a.slideOrigins.has(i)){const e=a.slideOrigins.get(i);e.slideTarget=t,t.slideOrigin=e,e.slideOutType=T.Shift}}}parseSlur(e,t){const s=e.getAttribute("number","1"),i=this.getStaffContext(t.beat.voice.bar.staff);switch(e.getAttribute("type")){case"start":i.slurStarts.set(s,t);break;case"stop":if(i.slurStarts.has(s)){t.isSlurDestination=!0;const e=i.slurStarts.get(s);e.slurDestination=t,t.slurOrigin=e,i.slurStarts.delete(s)}}}parseArpeggiate(e,t){switch(e.getAttribute("direction","down")){case"down":t.brushType=g.ArpeggioDown;break;case"up":t.brushType=g.ArpeggioUp}}parseFermata(e,t){let s;switch(e.innerText){case"normal":default:s=Ke.Medium;break;case"angled":s=Ke.Short;break;case"square":s=Ke.Long}t.fermata=new Tt,t.fermata.type=s}parseArticulations(e,t){for(const s of e.childElements())switch(s.localName){case"accent":t.accentuated=S.Normal;break;case"strong-accent":t.accentuated=S.Heavy;break;case"staccato":t.isStaccato=!0;break;case"tenuto":t.accentuated=S.Tenuto}}parseTechnical(e,t,s){const i=[];for(const a of e.childElements())switch(a.localName){case"up-bow":s.pickStroke=L.Up;break;case"down-bow":s.pickStroke=L.Down;break;case"harmonic":break;case"fingering":t&&(t.leftHandFinger=this.parseFingering(a));break;case"pluck":t&&(t.rightHandFinger=this.parseFingering(a));break;case"fret":t&&(t.fret=Number.parseInt(a.innerText));break;case"string":t&&(t.string=s.voice.bar.staff.tuning.length-Number.parseInt(a.innerText)+1);break;case"hammer-on":case"pull-off":t&&(t.isHammerPullOrigin=!0);break;case"bend":i.push(a);break;case"tap":s.tap=!0;break;case"smear":t&&(t.vibrato=N.Slight);break;case"golpe":switch(a.getAttribute("placement","above")){case"above":s.golpe=V.Finger;break;case"below":s.golpe=V.Thumb}}t&&i.length>0&&this.parseBends(i,t)}parseBends(e,t){const s=ae.MaxPosition/e.length;let i=0,a=0,r=!0;for(const n of e){const e=n.findChildElement("bend-alter");if(e){const o=Math.round(2*Math.abs(Number.parseFloat(e.innerText)));n.findChildElement("pre-bend")?r?(i+=o,t.addBendPoint(new ae(a,i)),a+=s,t.addBendPoint(new ae(a,i)),r=!1):a+=s:n.findChildElement("release")?(r&&(i+=o),t.addBendPoint(new ae(a,i)),a+=s,i-=o,t.addBendPoint(new ae(a,i)),r=!1):(t.addBendPoint(new ae(a,i)),i+=o,a+=s,t.addBendPoint(new ae(a,i)),r=!1)}}}parseFingering(e){switch(e.innerText){case"0":return _.NoOrDead;case"1":case"p":case"t":return _.Thumb;case"2":case"i":return _.IndexFinger;case"3":case"m":return _.MiddleFinger;case"4":case"a":return _.AnnularFinger;case"5":case"c":return _.LittleFinger}return _.Unknown}parseOrnaments(e,t){let s=-1;for(const i of e.childElements())switch(i.localName){case"trill-mark":s=Number.parseInt(i.getAttribute("trill-step","2")),t.isStringed?t.trillValue=t.stringTuning+s:t.isPercussion||(t.trillValue=t.calculateRealValue(!1,!1)+s);break;case"turn":t.ornament=O.Turn;break;case"inverted-turn":t.ornament=O.InvertedTurn;break;case"wavy-line":s>0?"start"===i.getAttribute("type")&&(this._currentTrillStep=s):this._currentTrillStep>0?"stop"===i.getAttribute("type")?this._currentTrillStep=-1:t.isStringed?t.trillValue=t.stringTuning+this._currentTrillStep:t.isPercussion||(t.trillValue=t.calculateRealValue(!1,!1)+this._currentTrillStep):t.vibrato=N.Slight;break;case"mordent":t.ornament=O.LowerMordent;break;case"inverted-mordent":t.ornament=O.UpperMordent;break;case"tremolo":switch(i.innerText){case"1":t.beat.tremoloSpeed=f.Eighth;break;case"2":t.beat.tremoloSpeed=f.Sixteenth;break;case"3":t.beat.tremoloSpeed=f.ThirtySecond}}}parseSlide(e,t){const s=e.getAttribute("type"),i=e.getAttribute("number","1"),a=this.getStaffContext(t.beat.voice.bar.staff);switch(s){case"start":a.slideOrigins.set(i,t);break;case"stop":if(a.slideOrigins.has(i)){const e=a.slideOrigins.get(i);e.slideTarget=t,t.slideOrigin=e,e.slideOutType=T.Shift}}}parseTied(e,t,s){const i=e.getAttribute("type"),a=e.getAttribute("number",""),r=this.getStaffContext(s);if("start"===i){if(a){if(r.tieStartIds.has(a)){const e=r.tieStartIds.get(a);r.tieStarts.delete(e)}r.tieStartIds.set(a,t)}r.tieStarts.add(t)}else if("stop"===i&&!t.isTieDestination){let e=null;if(a){if(!r.tieStartIds.has(a))return;e=r.tieStartIds.get(a),r.tieStartIds.delete(a),r.tieStarts.delete(t)}else{const s=this.calculatePitchedNoteValue(t);for(const t of r.tieStarts)if(this.calculatePitchedNoteValue(t)===s){e=t,r.tieStarts.delete(e);break}}if(!e)return;t.isTieDestination=!0,t.tieOrigin=e}}parseStem(e){switch(e.innerText){case"down":return je.Down;case"up":return je.Up;default:return null}}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=B.ForceSharp;break;case"natural":t.accidentalMode=B.ForceNatural;break;case"flat":t.accidentalMode=B.ForceFlat;break;case"double-sharp":t.accidentalMode=B.ForceDoubleSharp;break;case"flat-flat":t.accidentalMode=B.ForceDoubleFlat}}calculatePitchedNoteValue(e){return 12*e.octave+e.tone}parseDuration(e){return this.musicXmlDivisionsToAlphaTabTicks(Number.parseFloat(e.innerText))}parseUnpitched(e,t){let s="",i=0;for(const t of e.childElements())switch(t.localName){case"display-step":s=t.innerText;break;case"display-octave":i=Number.parseInt(t.innerText)+1}const a=new be;if(""===s)a.octave=0,a.tone=0;else{const e=12*i+ue.getToneForText(s).noteValue;a.octave=e/12|0,a.tone=e-12*a.octave}return a}parsePitch(e){let t="",s=0,i=0;for(const a of e.childElements())switch(a.localName){case"step":t=a.innerText;break;case"alter":s=Number.parseFloat(a.innerText),Number.isNaN(s)&&(s=0);break;case"octave":i=Number.parseInt(a.innerText)+1}s|=0;const a=12*i+ue.getToneForText(t).noteValue+s,r=new be;return r.octave=a/12|0,r.tone=a-12*r.octave,r}applyNoteHead(e,t,s,i,a,r,n){if(void 0===s)switch(t){case f.QuadrupleWhole:case f.DoubleWhole:e.style.noteHead=i;break;case f.Whole:e.style.noteHead=a;break;case f.Half:e.style.noteHead=r;break;default:e.style.noteHead=n}else if(!0===s)e.style.noteHead=n;else switch(t){case f.QuadrupleWhole:case f.DoubleWhole:e.style.noteHead=i;break;case f.Whole:e.style.noteHead=a;break;case f.Half:default:e.style.noteHead=r}}}Mi.B4Value=71,Mi.allDurations=[f.TwoHundredFiftySixth,f.OneHundredTwentyEighth,f.SixtyFourth,f.ThirtySecond,f.Sixteenth,f.Eighth,f.Quarter,f.Half,f.Whole,f.DoubleWhole,f.QuadrupleWhole],Mi.allDurationTicks=Mi.allDurations.map((e=>se.toTicks(e)));class Li{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event.type===it.AlphaTabMetronome}static newMetronomeEvent(e,t,s,i,a){const r=new Dt(0,t,s,i,a);return new Li(e,r)}}class Ii{constructor(e,t,s){this.bpm=e,this.ticks=t,this.time=s}}class Ai{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=se.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class Ri{get isPlayingMain(){return this._currentState===this._mainState}get isPlayingOneTimeMidi(){return this._currentState===this._oneTimeState}get isPlayingCountIn(){return this._currentState===this._countInState}constructor(e){this._oneTimeState=null,this._countInState=null,this.isLooping=!1,this.playbackSpeed=1,this.instrumentPrograms=new Set,this.percussionKeys=new Set,this._synthesizer=e,this._mainState=new Ai,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){const e=this._synthesizer.metronomeVolume;this._synthesizer.noteOffAll(!0),this._synthesizer.resetSoft(),this._synthesizer.setupMetronomeChannel(e)}this.mainSilentProcess(e)}}mainSilentProcess(e){if(e<=0)return;const t=Date.now(),s=this._mainState.currentTime+e;if(this.isPlayingMain)for(;this._mainState.currentTime<s;)this.fillMidiEventQueueLimited(s-this._mainState.currentTime)&&this._synthesizer.synthesizeSilent(kt.MicroBufferSize);this._mainState.currentTime=s;const i=Date.now()-t;he.debug("Sequencer",`Silent seek finished in ${i}ms (main)`)}loadOneTimeMidi(e){this._oneTimeState=this.createStateFromFile(e),this._currentState=this._oneTimeState}loadMidi(e){this.instrumentPrograms.clear(),this.percussionKeys.clear(),this._mainState=this.createStateFromFile(e),this._currentState=this._mainState}createStateFromFile(e){const t=new Ai;this.percussionKeys.add(kt.MetronomeKey),t.tempoChanges=[],t.division=e.division,t.eventIndex=0,t.currentTime=0,t.synthData=[];let s=120,i=0,a=0,r=0,n=0,o=0,h=0,l=0,c=0;for(const d of e.events){const u=new Li(t.synthData.length,d);t.synthData.push(u);const p=d.tick-c;if(i+=p,a+=p*(6e4/(s*e.division)),u.time=a,c=d.tick,n>0)for(;h<i;){const e=Li.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(d.type===it.TempoChange){s=6e7/d.microSecondsPerQuarterNote,t.tempoChanges.push(new Ii(s,i,a)),o=n*(6e4/(s*e.division))}else if(d.type===it.TimeSignature){const i=d,a=Math.pow(2,i.denominatorIndex);r=i.numerator,n=t.division*(4/a)|0,o=n*(6e4/(s*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=i.numerator,t.firstTimeSignatureDenominator=a)}else if(d.type===it.ProgramChange){const e=d,s=e.channel;t.firstProgramEventPerChannel.has(s)||t.firstProgramEventPerChannel.set(s,u);s===kt.PercussionChannel||this.instrumentPrograms.add(e.program)}else if(d.type===it.NoteOn){const e=d;e.channel===kt.PercussionChannel&&this.percussionKeys.add(e.noteKey)}}return t.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),t.endTime=a,t.endTick=i,t}fillMidiEventQueue(){return this.fillMidiEventQueueLimited(-1)}fillMidiEventQueueLimited(e){let t=kt.MicroBufferSize/this._synthesizer.outSampleRate*1e3*this.playbackSpeed,s=this.internalEndTime;e>0&&(e<t&&(t=e),s=Math.min(this.internalEndTime,this._currentState.currentTime+e));let i=!1;for(this._currentState.currentTime+=t;this._currentState.eventIndex<this._currentState.synthData.length&&this._currentState.synthData[this._currentState.eventIndex].time<this._currentState.currentTime&&this._currentState.currentTime<s;)this._synthesizer.dispatchEvent(this._currentState.synthData[this._currentState.eventIndex]),this._currentState.eventIndex++,i=!0;return i}mainTickPositionToTimePosition(e){return this.tickPositionToTimePositionWithSpeed(this._mainState,e,this.playbackSpeed)}mainTimePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(this._mainState,e,this.playbackSpeed)}currentTimePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(this._currentState,e,this.playbackSpeed)}tickPositionToTimePositionWithSpeed(e,t,s){let i=0,a=120,r=0;for(const s of e.tempoChanges){if(t<s.ticks)break;i=s.time,a=s.bpm,r=s.ticks}return i+=(t-=r)*(6e4/(a*e.division)),i/s}timePositionToTickPositionWithSpeed(e,t,s){t*=s;let i=0,a=120,r=0;for(const s of e.tempoChanges){if(t<s.time)break;i=s.ticks,a=s.bpm,r=s.time}return i+=(t-=r)/(6e4/(a*e.division))|0,i+1}get internalEndTime(){return this.isPlayingMain&&this.mainPlaybackRange?this._currentState.playbackRangeEndTime:this._currentState.endTime}get isFinished(){return this._currentState.currentTime>=this.internalEndTime}stop(){this.isPlayingMain&&this.mainPlaybackRange?this._currentState.currentTime=this.mainPlaybackRange.startTick:this._currentState.currentTime=0,this._currentState.eventIndex=0}resetOneTimeMidi(){this._oneTimeState=null,this._currentState=this._mainState}resetCountIn(){this._countInState=null,this._currentState=this._mainState}startCountIn(){this.generateCountInMidi(),this._currentState=this._countInState,this.stop(),this._synthesizer.noteOffAll(!0)}generateCountInMidi(){const e=new Ai;e.division=this._mainState.division;let t=120,s=4,i=4;0===this._mainState.eventIndex?(t=this._mainState.tempoChanges[0].bpm,s=this._mainState.firstTimeSignatureNumerator,i=this._mainState.firstTimeSignatureDenominator):(t=this._synthesizer.currentTempo,s=this._synthesizer.timeSignatureNumerator,i=this._synthesizer.timeSignatureDenominator),e.tempoChanges.push(new Ii(t,0,0));const a=e.division*(4/i)|0,r=a*(6e4/(t*this._mainState.division));let n=0,o=0;for(let t=0;t<s;t++){const s=Li.newMetronomeEvent(e.synthData.length,n,t,a,r);e.synthData.push(s),s.time=o,n+=a,o+=r}e.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),e.endTime=o,e.endTick=n,this._countInState=e}}var Oi,Hi,Wi,Vi,Gi,Ui,zi,Xi,Ji,Yi,$i;!function(e){e[e.Paused=0]="Paused",e[e.Playing=1]="Playing"}(Oi||(Oi={}));class qi{constructor(e,t){this.state=e,this.stopped=t}}class Ki{constructor(e,t,s,i,a){this.currentTime=e,this.endTime=t,this.currentTick=s,this.endTick=i,this.isSeek=a}}class ji{constructor(){this.id="",this.size=0}static load(e,t,s){if(e&&ji.HeaderSize>e.size)return!1;if(s.position+ji.HeaderSize>=s.length)return!1;if(t.id=wt.read8BitStringLength(s,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=wt.readUInt32LE(s),e&&ji.HeaderSize+t.size>e.size)return!1;e&&(e.size-=ji.HeaderSize+t.size);const i="RIFF"===t.id,a="LIST"===t.id;return(!i||!e)&&(!i&&!a||(t.id=wt.read8BitStringLength(s,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}ji.HeaderSize=8;class Qi{constructor(e,t,s,i){this.packetData=e,this.isBeginningOfStream=t,this.isEndOfStream=s,this.granulePosition=s?i:null}addData(e){const t=this.packetData,s=new Uint8Array(t.length+e.length);s.set(t,0),s.set(e,t.length)}}!function(e){e[e.ContinuesPacket=1]="ContinuesPacket",e[e.BeginningOfStream=2]="BeginningOfStream",e[e.EndOfStream=4]="EndOfStream"}(Hi||(Hi={}));class Zi{constructor(e){this._readable=e}read(){const e=[];for(;this.findAndReadPage(e););return e}findAndReadPage(e){return!!this.seekPageHeader()&&this.readPage(e)}seekPageHeader(){for(let e=0;e<65536;e++){if(1399285583===wt.readInt32LE(this._readable))return!0;this._readable.position-=3}return!1}readPage(e){const t=this._readable.readByte();if(-1===t||0!==t)return!1;const s=this._readable.readByte(),i=wt.readInt64LE(this._readable);this._readable.skip(4),this._readable.skip(4),this._readable.skip(4);const a=this._readable.readByte();if(-1===a)return!1;const r=[];let n=0;for(let e=0;e<a;e++){const e=this._readable.readByte();n===r.length&&r.push(0),r[n]+=e,e<255&&n++}for(let t=0;t<r.length;t++){const a=new Uint8Array(r[t]);if(this._readable.read(a,0,a.length)!==a.length)return!1;if(s&Hi.ContinuesPacket){if(0===e.length)throw new Le(Ee.Format,"OGG: Continuation page without any previous packets");e[e.length-1].addData(a)}else{const n=new Qi(a,!!(s&Hi.BeginningOfStream)&&0===t,!!(s&Hi.EndOfStream)&&t===r.length-1,i);e.push(n)}}return!0}}class ea{constructor(){this.audioChannels=0,this.audioSampleRate=0,this.samples=new Float32Array(0),this.bitrateMaximum=0,this.bitrateNominal=0,this.bitrateMinimum=0,this.blocksize0=0,this.blocksize1=0}}class ta{constructor(){this.value=0,this.bitsRead=0}}class sa{constructor(e){this._bitBucket=0n,this._bitCount=0n,this._overflowBits=0n,this._source=e}readByte(){return this.readBits(sa.ByteSize)}readBit(){return 1===this.readBits(1)}readBytes(e){const t=new Uint8Array(e);for(let s=0;s<e;s++)t[s]=255&this.readByte();return t}readBits(e){if(0===e)return 0;const t=this.tryPeekBits(e);return this.skipBits(e),t.value}tryPeekBits(e){if(e<0||e>32)throw new Le(Ee.General,"IO: Cannot read more than 32 bits in one go");if(0===e)return new ta;const t=new ta;for(;this._bitCount<e;){const e=BigInt(this._source.readByte());if(-1n===e)return t.bitsRead=Number(this._bitCount),t.value=Number(this._bitBucket),this._bitBucket=0n,this._bitCount=0n,t;this._bitBucket=(0xffn&e)<<this._bitCount|this._bitBucket,this._bitCount+=8n,this._bitCount>32&&(this._overflowBits=e>>40n-this._bitCount&0xffn)}let s=this._bitBucket;return e<64&&(s&=(1n<<BigInt(e))-1n),t.value=Number(s),t.bitsRead=e,t}skipBits(e){let t=BigInt(e);if(0===e);else if(this._bitCount>t){if(this._bitBucket=e>31?0n:this._bitBucket>>t,this._bitCount>32){const s=this._bitCount-32n;this._bitBucket=this._bitBucket|this._overflowBits<<this._bitCount-t-s,s>e&&(this._overflowBits=this._overflowBits>>t&0xffn)}this._bitCount-=t}else if(this._bitCount===t)this._bitBucket=0n,this._bitCount=0n;else{for(t-=this._bitCount,this._bitCount=0n,this._bitBucket=0n;t>8;){if(-1===this._source.readByte()){t=0n;break}t-=8n}if(t>0){const e=BigInt(this._source.readByte());-1n===e||(this._bitBucket=e>>t,this._bitCount=8n-t)}}}}sa.ByteSize=8;class ia{constructor(){this.codebooks=[],this.timeDomainTransforms=[],this.floors=[],this.residues=[],this.mappings=[],this.modes=[]}}class aa{static ilog(e){let t=0;for(;e>0;)++t,e>>=1;return t}static bitReverse(e,t=32){let s=BigInt(e);s=(s&BigInt(2863311530))>>1n|(s&BigInt(1431655765))<<1n,s=(s&BigInt(3435973836))>>2n|(s&BigInt(858993459))<<2n,s=(s&BigInt(4042322160))>>4n|(s&BigInt(252645135))<<4n,s=(s&BigInt(4278255360))>>8n|(s&BigInt(16711935))<<8n,s=(s>>16n|s<<16n)>>32n-BigInt(t);return Number(BigInt.asUintN(32,s))}static convertFromVorbisFloat32(e){const t=BigInt(e);let s=t&BigInt(2097151);const i=t&BigInt(2147483648),a=(t&BigInt(2145386496))>>21n;return 0n!==i&&(s=-s),Number(s)*Math.pow(2,Number(a)-788)}}class ra{constructor(e){this._data=e}get(e){return this._data[e]}}class na{get(e){return e}}na.instance=new na;class oa{constructor(e,t){this._maxBits=0,this._overflowList=null,this._prefixList=null,this._prefixBitLength=0,this.dimensions=0,this.entries=0,this.mapType=0;if(5653314!==e.readBits(24))throw new Le(Ee.Format,"Vorbis: Book header had invalid signature!");this.dimensions=e.readBits(16),this.entries=e.readBits(24),this._lengths=new Int32Array(this.entries),this.initTree(e,t),this.initLookupTable(e)}get(e,t){return this._lookupTable[e*this.dimensions+t]}decodeScalar(e){let t=e.tryPeekBits(this._prefixBitLength);if(0===t.bitsRead)return-1;let s=this._prefixList[t.value];if(null!=s)return e.skipBits(s.length),s.value;if(t=e.tryPeekBits(this._maxBits),null!==this._overflowList)for(let i=0;i<this._overflowList.length;i++){s=this._overflowList[i];const a=t.value&s.mask;if(s.bits===a)return e.skipBits(s.length),s.value}return-1}initTree(e,t){let s,i,a=0;if(e.readBit()){let t=e.readBits(5)+1;for(let s=0;s<this.entries;){let i=e.readBits(aa.ilog(this.entries-s));for(;--i>=0;)this._lengths[s++]=t;++t}a=0,s=!1,i=t}else{i=-1,s=e.readBit();for(let t=0;t<this.entries;t++)!s||e.readBit()?(this._lengths[t]=e.readBits(5)+1,++a):this._lengths[t]=-1,this._lengths[t]>i&&(i=this._lengths[t])}if(this._maxBits=i,i>-1){let e,i=null;s&&a>=this.entries>>2&&(i=new Int32Array(this.entries),i.set(this._lengths.subarray(0,this.entries),0),s=!1),e=s?a:0;let r=null,n=null;if(s?0!==e&&(i=new Int32Array(e),n=new Int32Array(e),r=new Int32Array(e)):n=new Int32Array(this.entries),!this.computeCodewords(s,n,i,this._lengths,this.entries,r))throw new Le(Ee.Format,"Vorbis: Failed to compute codewords");const o=null==r?na.instance:new ra(r);t.generateTable(o,i??this._lengths,n),this._prefixList=t.prefixTree,this._prefixBitLength=t.tableBits,this._overflowList=t.overflowList}}computeCodewords(e,t,s,i,a,r){const n=new Uint32Array(32);let o=0,h=0;for(o=0;o<a&&!(i[o]>0);++o);if(o===a)return!0;this.addEntry(e,t,s,0,o,h++,i[o],r);for(let e=1;e<=i[o];++e)n[e]=1<<32-e;for(let l=o+1;l<a;++l){let a=i[l];if(a<=0)continue;for(;a>0&&0===n[a];)--a;if(0===a)return!1;const o=n[a];if(n[a]=0,this.addEntry(e,t,s,aa.bitReverse(o),l,h++,i[l],r),a!==i[l])for(let e=i[l];e>a;--e)n[e]=o+(1<<32-e)}return!0}addEntry(e,t,s,i,a,r,n,o){e?(t[r]=i,s[r]=n,o[r]=a):t[a]=i}initLookupTable(e){if(this.mapType=e.readBits(4),0===this.mapType)return;const t=aa.convertFromVorbisFloat32(e.readBits(32)),s=aa.convertFromVorbisFloat32(e.readBits(32)),i=e.readBits(4)+1,a=e.readBit();let r=this.entries*this.dimensions;const n=new Float32Array(r);1===this.mapType&&(r=this.lookup1Values());const o=new Uint32Array(r);for(let t=0;t<r;t++)o[t]=e.readBits(i);if(1===this.mapType)for(let e=0;e<this.entries;e++){let i=0,h=1;for(let l=0;l<this.dimensions;l++){const c=o[e/h%r|0]*s+t+i;n[e*this.dimensions+l]=c,a&&(i=c),h*=r}}else for(let e=0;e<this.entries;e++){let i=0,r=e*this.dimensions;for(let h=0;h<this.dimensions;h++){const l=o[r]*s+t+i;n[e*this.dimensions+h]=l,a&&(i=l),++r}}this._lookupTable=n}lookup1Values(){let e=Math.floor(Math.exp(Math.log(this.entries)/this.dimensions));return Math.floor(Math.pow(e+1,this.dimensions))<=this.entries&&++e,e}}class ha{constructor(){this.value=0,this.length=0,this.bits=0,this.mask=0}}class la{constructor(){this.tableBits=0,this.prefixTree=[],this.overflowList=null}generateTable(e,t,s){const i=new Array(t.length);let a=0;for(let r=0;r<i.length;r++){const n=new ha;n.value=e.get(r),n.length=t[r]<=0?99999:t[r],n.bits=s[r],n.mask=(1<<t[r])-1,i[r]=n,t[r]>0&&a<t[r]&&(a=t[r])}i.sort(((e,t)=>{const s=e.length-t.length;return 0===s?e.bits-t.bits:s}));const r=a>la.MAX_TABLE_BITS?la.MAX_TABLE_BITS:a,n=[];let o=null;for(let e=0;e<i.length&&i[e].length<99999;e++){const t=i[e].length;if(t>r)for(o=[];e<i.length&&i[e].length<99999;e++)o.push(i[e]);else{const s=1<<r-t,a=i[e];for(let e=0;e<s;e++){const s=e<<t|a.bits;for(;n.length<=s;)n.push(null);n[s]=a}}}for(;n.length<1<<r;)n.push(null);this.tableBits=r,this.prefixTree=n,this.overflowList=o}}la.MAX_TABLE_BITS=10;class ca{constructor(e){e.readBits(16)}}class da{get executeChannel(){return(this.forceEnergy||this.amp>0)&&!this.forceNoEnergy}constructor(e){this.amp=0,this.forceEnergy=!1,this.forceNoEnergy=!1,this.coeff=e}}class ua{constructor(e,t,s,i){if(this._order=e.readBits(8),this._rate=e.readBits(16),this._bark_map_size=e.readBits(16),this._ampBits=e.readBits(6),this._ampOfs=e.readBits(8),this._books=new Array(e.readBits(4)+1),this._order<1||this._rate<1||this._bark_map_size<1||0===this._books.length)throw new Le(Ee.Format,"Vorbis: Invalid Floor0 Data");this._ampDiv=(1<<this._ampBits)-1;for(let t=0;t<this._books.length;t++){const s=e.readBits(8);if(s<0||s>=i.length)throw new Le(Ee.Format,"Vorbis: Invalid Floor0 Data");const a=i[s];if(0===a.mapType||a.dimensions<1)throw new Le(Ee.Format,"Vorbis: Invalid Floor0 Data");this._books[t]=a}this._bookBits=aa.ilog(this._books.length),this._barkMaps=new Map([[t,this.synthesizeBarkCurve(t/2)],[s,this.synthesizeBarkCurve(s/2)]]),this._wMap=new Map([[t,this.synthesizeWDelMap(t/2)],[s,this.synthesizeWDelMap(s/2)]])}synthesizeBarkCurve(e){const t=this._bark_map_size/ua.toBARK(this._rate/2),s=new Int32Array(e+1);for(let i=0;i<e-1;i++)s[i]=Math.min(this._bark_map_size-1,Math.floor(ua.toBARK(this._rate/2/e*i)*t));return s[e]=-1,s}static toBARK(e){return 13.1*Math.atan(74e-5*e)+2.24*Math.atan(1.85e-8*e*e)+1e-4*e}synthesizeWDelMap(e){const t=Math.PI/this._bark_map_size,s=new Float32Array(e);for(let i=0;i<e;i++)s[i]=2*Math.cos(t*i);return s}unpack(e,t,s){const i=new da(new Float32Array(this._order+1));if(i.amp=e.readBits(this._ampBits),i.amp>0){i.amp=i.amp/this._ampDiv*this._ampOfs;const t=e.readBits(this._bookBits);if(t>=this._books.length)return i.amp=0,i;const s=this._books[t];for(let t=0;t<this._order;){const a=s.decodeScalar(e);if(-1===a)return i.amp=0,i;for(let e=0;t<this._order&&e<s.dimensions;e++,t++)i.coeff[t]=s.get(a,e)}let a=0;for(let e=0;e<this._order;){for(let t=0;e<this._order&&t<s.dimensions;e++,t++)i.coeff[e]+=a;a=i.coeff[e-1]}}return i}apply(e,t,s){const i=e,a=t/2;if(i.amp>0){const e=this._barkMaps.get(t),r=this._wMap.get(t);let n=0;for(n=0;n<this._order;n++)i.coeff[n]=2*Math.cos(i.coeff[n]);for(n=0;n<a;){let t=0;const a=e[n];let o=.5,h=.5;const l=r[a];for(t=1;t<this._order;t+=2)h*=l-i.coeff[t-1],o*=l-i.coeff[t];for(t===this._order?(h*=l-i.coeff[t-1],o*=o*(4-l*l),h*=h):(o*=o*(2-l),h*=h*(2+l)),h=i.amp/Math.sqrt(o+h)-this._ampOfs,h=Math.exp(.11512925*h),s[n]*=h;e[++n]===a;)s[n]*=h}}else s.fill(0,0,a)}}class pa{constructor(){this.posts=new Int32Array(64),this.postCount=0,this.forceEnergy=!1,this.forceNoEnergy=!1}get executeChannel(){return(this.forceEnergy||this.postCount>0)&&!this.forceNoEnergy}}class ga{constructor(e,t){let s=-1;this._partitionClass=new Int32Array(e.readBits(5));for(let t=0;t<this._partitionClass.length;t++)this._partitionClass[t]=e.readBits(4),this._partitionClass[t]>s&&(s=this._partitionClass[t]);++s,this._classDimensions=new Int32Array(s),this._classSubclasses=new Int32Array(s),this._classMasterbooks=new Array(s),this._classMasterBookIndex=new Int32Array(s),this._subclassBooks=new Array(s),this._subclassBookIndex=new Array(s);for(let i=0;i<s;i++){this._classDimensions[i]=e.readBits(3)+1,this._classSubclasses[i]=e.readBits(2),this._classSubclasses[i]>0&&(this._classMasterBookIndex[i]=e.readBits(8),this._classMasterbooks[i]=t[this._classMasterBookIndex[i]]),this._subclassBooks[i]=new Array(1<<this._classSubclasses[i]),this._subclassBookIndex[i]=new Int32Array(this._subclassBooks[i].length);for(let s=0;s<this._subclassBooks[i].length;s++){const a=e.readBits(8)-1;a>=0&&(this._subclassBooks[i][s]=t[a]),this._subclassBookIndex[i][s]=a}}this._multiplier=e.readBits(2),this._range=ga._rangeLookup[this._multiplier],this._yBits=ga._yBitsLookup[this._multiplier],++this._multiplier;const i=e.readBits(4),a=[];a.push(0),a.push(1<<i);for(let t=0;t<this._partitionClass.length;t++){const s=this._partitionClass[t];for(let t=0;t<this._classDimensions[s];t++)a.push(e.readBits(i))}this._xList=new Int32Array(a),this._lNeigh=new Int32Array(a.length),this._hNeigh=new Int32Array(a.length),this._sortIdx=new Int32Array(a.length),this._sortIdx[0]=0,this._sortIdx[1]=1;for(let e=2;e<this._lNeigh.length;e++){this._lNeigh[e]=0,this._hNeigh[e]=1,this._sortIdx[e]=e;for(let t=2;t<e;t++){const s=this._xList[t];s<this._xList[e]?s>this._xList[this._lNeigh[e]]&&(this._lNeigh[e]=t):s<this._xList[this._hNeigh[e]]&&(this._hNeigh[e]=t)}}for(let e=0;e<this._sortIdx.length-1;e++)for(let t=e+1;t<this._sortIdx.length;t++){if(this._xList[e]===this._xList[t])throw new Le(Ee.Format,"Vorbis: Invalid Floor1 Data");if(this._xList[this._sortIdx[e]]>this._xList[this._sortIdx[t]]){const s=this._sortIdx[e];this._sortIdx[e]=this._sortIdx[t],this._sortIdx[t]=s}}}unpack(e,t,s){const i=new pa;if(e.readBit()){let t=2;i.posts[0]=e.readBits(this._yBits),i.posts[1]=e.readBits(this._yBits);for(let s=0;s<this._partitionClass.length;s++){const a=this._partitionClass[s],r=this._classDimensions[a],n=this._classSubclasses[a],o=(1<<n)-1;let h=0;if(n>0&&(h=this._classMasterbooks[a].decodeScalar(e),-1===h)){t=0;break}for(let l=0;l<r;l++){const r=this._subclassBooks[a][h&o];if(h>>=n,null!=r&&(i.posts[t]=r.decodeScalar(e),-1===i.posts[t])){t=0,s=this._partitionClass.length;break}++t}}i.postCount=t}return i}apply(e,t,s){const i=e,a=t/2;if(i.postCount>0){const e=this.unwrapPosts(i);let t=0,r=i.posts[0]*this._multiplier;for(let n=1;n<i.postCount;n++){const o=this._sortIdx[n];if(e[o]){const e=this._xList[o],n=i.posts[o]*this._multiplier;t<a&&this.renderLineMulti(t,r,Math.min(e,a),n,s),t=e,r=n}if(t>=a)break}t<a&&this.renderLineMulti(t,r,a,r,s)}else s.fill(0,0,a)}unwrapPosts(e){const t=new Array(64);t.fill(!1),t[0]=!0,t[1]=!0;const s=new Int32Array(64);s[0]=e.posts[0],s[1]=e.posts[1];for(let i=2;i<e.postCount;i++){const a=this._lNeigh[i],r=this._hNeigh[i],n=this.renderPoint(this._xList[a],s[a],this._xList[r],s[r],this._xList[i]),o=e.posts[i],h=this._range-n,l=n;let c;c=h<l?2*h:2*l,0!==o?(t[a]=!0,t[r]=!0,t[i]=!0,s[i]=o>=c?h>l?o-l+n:n-o+h-1:o%2==1?n-(o+1)/2:n+o/2):(t[i]=!1,s[i]=n)}for(let t=0;t<e.postCount;t++)e.posts[t]=s[t];return t}renderPoint(e,t,s,i,a){const r=i-t,n=s-e,o=Math.abs(r)*(a-e)/n|0;return r<0?t-o:t+o}renderLineMulti(e,t,s,i,a){const r=i-t,n=s-e;let o=Math.abs(r);const h=1-2*(r>>31&1),l=r/n|0;let c=e,d=t,u=-n;for(a[e]*=ga.inverse_dB_table[t],o-=Math.abs(l)*n;++c<s;)d+=l,u+=o,u>=0&&(u-=n,d+=h),a[c]*=ga.inverse_dB_table[d]}}ga._rangeLookup=[256,128,86,64],ga._yBitsLookup=[8,7,7,6],ga.inverse_dB_table=new Float32Array([1.0649863e-7,1.1341951e-7,1.2079015e-7,1.2863978e-7,1.3699951e-7,1.4590251e-7,1.5538408e-7,1.6548181e-7,1.7623575e-7,1.8768855e-7,1.9988561e-7,2.128753e-7,2.2670913e-7,2.4144197e-7,2.5713223e-7,2.7384213e-7,2.9163793e-7,3.1059021e-7,3.3077411e-7,3.5226968e-7,3.7516214e-7,3.9954229e-7,4.255068e-7,4.5315863e-7,4.8260743e-7,5.1396998e-7,5.4737065e-7,5.8294187e-7,6.2082472e-7,6.6116941e-7,7.0413592e-7,7.4989464e-7,7.9862701e-7,8.505263e-7,9.0579828e-7,9.6466216e-7,10273513e-13,10941144e-13,11652161e-13,12409384e-13,13215816e-13,14074654e-13,14989305e-13,15963394e-13,17000785e-13,18105592e-13,19282195e-13,20535261e-13,21869758e-13,23290978e-13,24804557e-13,26416497e-13,2813319e-12,29961443e-13,31908506e-13,33982101e-13,36190449e-13,38542308e-13,41047004e-13,4371447e-12,46555282e-13,49580707e-13,5280274e-12,5623416e-12,59888572e-13,63780469e-13,67925283e-13,72339451e-13,77040476e-13,82047e-10,87378876e-13,93057248e-13,99104632e-13,10554501e-12,11240392e-12,11970856e-12,12748789e-12,13577278e-12,14459606e-12,15399272e-12,16400004e-12,17465768e-12,18600792e-12,19809576e-12,21096914e-12,22467911e-12,23928002e-12,25482978e-12,27139006e-12,28902651e-12,30780908e-12,32781225e-12,34911534e-12,37180282e-12,39596466e-12,42169667e-12,4491009e-11,47828601e-12,50936773e-12,54246931e-12,57772202e-12,61526565e-12,65524908e-12,69783085e-12,74317983e-12,79147585e-12,8429104e-11,89768747e-12,95602426e-12,.00010181521,.00010843174,.00011547824,.00012298267,.00013097477,.00013948625,.00014855085,.00015820453,.00016848555,.00017943469,.00019109536,.00020351382,.00021673929,.00023082423,.00024582449,.00026179955,.00027881276,.00029693158,.00031622787,.00033677814,.00035866388,.00038197188,.00040679456,.00043323036,.00046138411,.00049136745,.00052329927,.00055730621,.00059352311,.00063209358,.00067317058,716917e-9,.0007635063,.00081312324,.00086596457,.00092223983,.00098217216,.0010459992,.0011139742,.0011863665,.0012634633,.0013455702,.0014330129,.0015261382,.0016253153,.0017309374,.0018434235,.0019632195,.0020908006,.0022266726,.0023713743,.0025254795,.0026895994,.0028643847,.0030505286,.0032487691,.0034598925,.0036847358,.0039241906,.0041792066,.004450795,.0047400328,.0050480668,.0053761186,.0057254891,.0060975636,.0064938176,.0069158225,.0073652516,.0078438871,.0083536271,.0088964928,.009474637,.010090352,.01074608,.011444421,.012188144,.012980198,.013823725,.014722068,.015678791,.016697687,.017782797,.018938423,.020169149,.021479854,.022875735,.02436233,.025945531,.027631618,.029427276,.031339626,.033376252,.035545228,.037855157,.040315199,.042935108,.045725273,.048696758,.051861348,.055231591,.05882085,.062643361,.066714279,.071049749,.075666962,.080584227,.085821044,.091398179,.097337747,.1036633,.11039993,.11757434,.12521498,.13335215,.14201813,.15124727,.16107617,.1715438,.18269168,.19456402,.20720788,.22067342,.23501402,.25028656,.26655159,.28387361,.30232132,.32196786,.34289114,.36517414,.38890521,.41417847,.44109412,.4697589,.50028648,.53279791,.56742212,.6042964,.64356699,.68538959,.72993007,.77736504,.8278826,.88168307,.9389798,1]);class ma{constructor(e,t,s,i){const a=e.readBits(16);switch(a){case 0:this.floor=new ua(e,t,s,i);break;case 1:this.floor=new ga(e,i);break;default:throw new Le(Ee.Format,`Vorbis: Invalid Floor type: ${a}`)}}apply(e,t,s){this.floor.apply(e,t,s)}unpack(e,t,s){return this.floor.unpack(e,t,s)}}class fa{constructor(e,t,s){this._begin=e.readBits(24),this._end=e.readBits(24),this._partitionSize=e.readBits(24)+1,this._classifications=e.readBits(6)+1,this._classBook=s[e.readBits(8)],this._cascade=new Int32Array(this._classifications);let i=0;for(let t=0;t<this._classifications;t++){const s=e.readBits(3);e.readBit()?this._cascade[t]=e.readBits(5)<<3|s:this._cascade[t]=s,i+=fa.icount(this._cascade[t])}const a=new Int32Array(i);for(let t=0;t<i;t++)if(a[t]=e.readBits(8),0===s[a[t]].mapType)throw new Le(Ee.Format,"Vorbis: Invalid Residue 0");const r=this._classBook.entries;let n=this._classBook.dimensions,o=1;for(;n>0;){if(o*=this._classifications,o>r)throw new Le(Ee.Format,"Vorbis: Invalid Residue 0");--n}this._books=new Array(this._classifications),i=0;let h,l=0;for(let e=0;e<this._classifications;e++)if(h=aa.ilog(this._cascade[e]),this._books[e]=new Array(h),h>0){l=Math.max(l,h);for(let t=0;t<h;t++)(this._cascade[e]&1<<t)>0&&(this._books[e][t]=s[a[i++]])}this._maxStages=l,this._decodeMap=new Array(o);for(let e=0;e<o;e++){let t=e,s=o/this._classifications|0;this._decodeMap[e]=new Int32Array(this._classBook.dimensions);for(let i=0;i<this._classBook.dimensions;i++){const a=t/s|0;t-=a*s,s=s/this._classifications|0,this._decodeMap[e][i]=a}}this._channels=t}static icount(e){let t=0;for(;0!==e;)t+=1&e,e>>=1;return t}decode(e,t,s,i){const a=(this._end<s/2?this._end:s/2)-this._begin;if(a>0&&-1!==t.indexOf(!1)){const t=a/this._partitionSize,s=(t+this._classBook.dimensions-1)/this._classBook.dimensions|0,r=[];for(let e=0;e<this._channels;e++)r.push(new Array(s));for(let s=0;s<this._maxStages;s++)for(let a=0,n=0;a<t;n++){if(0===s)for(let i=0;i<this._channels;i++){const o=this._classBook.decodeScalar(e);if(!(o>=0&&o<this._decodeMap.length)){a=t,s=this._maxStages;break}r[i][n]=this._decodeMap[o]}for(let o=0;a<t&&o<this._classBook.dimensions;o++,a++){const h=this._begin+a*this._partitionSize;for(let l=0;l<this._channels;l++){const c=r[l][n][o];if(this._cascade[c]&1<<s){const r=this._books[c][s];if(r&&this.writeVectors(r,e,i,l,h,this._partitionSize)){a=t,s=this._maxStages;break}}}}}}}writeVectors(e,t,s,i,a,r){const n=s[i],o=r/e.dimensions,h=new Int32Array(o);for(let s=0;s<o;s++)if(h[s]=e.decodeScalar(t),-1===h[s])return!0;for(let t=0;t<e.dimensions;t++)for(let s=0;s<o;s++,a++)n[a]+=e.get(h[s],t);return!1}}class ya extends fa{writeVectors(e,t,s,i,a,r){const n=s[i];for(let s=0;s<r;){const i=e.decodeScalar(t);if(-1===i)return!0;for(let t=0;t<e.dimensions;s++,t++)n[a+s]+=e.get(i,t)}return!1}}class ba extends fa{constructor(e,t,s){super(e,1,s),this._realChannels=t}decode(e,t,s,i){super.decode(e,t,s*this._realChannels,i)}writeVectors(e,t,s,i,a,r){let n=0;a/=this._realChannels;for(let i=0;i<r;){const r=e.decodeScalar(t);if(-1===r)return!0;for(let t=0;t<e.dimensions;t++,i++)s[n][a]+=e.get(r,t),++n===this._realChannels&&(n=0,a++)}return!1}}class Sa{constructor(e,t,s){const i=e.readBits(16);switch(i){case 0:this.residue=new fa(e,t,s);break;case 1:this.residue=new ya(e,t,s);break;case 2:this.residue=new ba(e,t,s);break;default:throw new Le(Ee.Format,`Vorbis: Invalid Residue type: ${i}`)}}decode(e,t,s,i){this.residue.decode(e,t,s,i)}}class _a{constructor(e,t,s,i,a){if(0!==e.readBits(16))throw new Le(Ee.Format,"Vorbis: Invalid mapping type!");let r=1;e.readBit()&&(r+=e.readBits(4));let n=0;e.readBit()&&(n=e.readBits(8)+1);const o=aa.ilog(t-1);this._couplingAngle=new Int32Array(n),this._couplingMangitude=new Int32Array(n);for(let s=0;s<n;s++){const i=e.readBits(o),a=e.readBits(o);if(i===a||i>t-1||a>t-1)throw new Le(Ee.Format,"Vorbis: Invalid magnitude or angle in mapping header!");this._couplingAngle[s]=a,this._couplingMangitude[s]=i}if(0!==e.readBits(2))throw new Le(Ee.Format,"Vorbis: Reserved bits not 0 in mapping header.");const h=new Int32Array(t);if(r>1)for(let s=0;s<t;s++)if(h[s]=e.readBits(4),h[s]>r)throw new Le(Ee.Format,"Vorbis: Invalid channel mux submap index in mapping header!");this._submapFloor=new Array(r),this._submapResidue=new Array(r);for(let t=0;t<r;t++){e.skipBits(8);const a=e.readBits(8);if(a>=s.length)throw new Le(Ee.Format,"Vorbis: Invalid floor number in mapping header!");const r=e.readBits(8);if(r>=i.length)throw new Le(Ee.Format,"Vorbis: Invalid residue number in mapping header!");this._submapFloor[t]=s[a],this._submapResidue[t]=i[r]}this._channelFloor=new Array(t),this._channelResidue=new Array(t);for(let e=0;e<t;e++)this._channelFloor[e]=this._submapFloor[h[e]],this._channelResidue[e]=this._submapResidue[h[e]];this._mdct=a}decodePacket(e,t,s){const i=t>>1,a=new Array(this._channelFloor.length),r=new Array(this._channelFloor.length);r.fill(!1);for(let n=0;n<this._channelFloor.length;n++)a[n]=this._channelFloor[n].unpack(e,t,n),r[n]=!a[n].executeChannel,s[n].fill(0,0,i);for(let e=0;e<this._couplingAngle.length;e++)(a[this._couplingAngle[e]].executeChannel||a[this._couplingMangitude[e]].executeChannel)&&(a[this._couplingAngle[e]].forceEnergy=!0,a[this._couplingMangitude[e]].forceEnergy=!0);for(let i=0;i<this._submapFloor.length;i++){for(let e=0;e<this._channelFloor.length;e++)this._submapFloor[i]===this._channelFloor[e]&&this._submapResidue[i]===this._channelResidue[e]||(a[e].forceNoEnergy=!0);this._submapResidue[i].decode(e,r,t,s)}for(let e=this._couplingAngle.length-1;e>=0;e--)if(a[this._couplingAngle[e]].executeChannel||a[this._couplingMangitude[e]].executeChannel){const t=s[this._couplingMangitude[e]],a=s[this._couplingAngle[e]];for(let e=0;e<i;e++){let s,i;const r=t[e],n=a[e];r>0?n>0?(s=r,i=r-n):(i=r,s=r+n):n>0?(s=r,i=r+n):(i=r,s=r-n),t[e]=s,a[e]=i}}for(let e=0;e<this._channelFloor.length;e++)a[e].executeChannel?(this._channelFloor[e].apply(a[e],t,s[e]),this._mdct.reverse(s[e],t)):s[e].fill(0,i,2*i)}}class wa{constructor(){this.packetStartIndex=0,this.packetTotalLength=0,this.packetValidLength=0}}class Ba{constructor(){this.overlapInfo=new wa,this.windowIndex=0}}class ka{constructor(e=null){this.samplePosition=null,this.samplePosition=e}}class Ta{constructor(e,t,s,i,a){if(this._overlapInfo=null,this._channels=t,this._blockFlag=e.readBit(),0!==e.readBits(32))throw new Le(Ee.Format,"Vorbis: Mode header had invalid window or transform type!");const r=e.readBits(8);if(r>=a.length)throw new Le(Ee.Format,"Vorbis: Mode header had invalid mapping index!");this._mapping=a[r],this._blockFlag?(this._blockSize=i,this._windows=[Ta.calcWindow(s,i,s),Ta.calcWindow(i,i,s),Ta.calcWindow(s,i,i),Ta.calcWindow(i,i,i)],this._overlapInfo=[Ta.calcOverlap(s,i,s),Ta.calcOverlap(i,i,s),Ta.calcOverlap(s,i,i),Ta.calcOverlap(i,i,i)]):(this._blockSize=s,this._windows=[Ta.calcWindow(s,s,s)])}decode(e,t){const s=this.getPacketInfo(e);this._mapping.decodePacket(e,this._blockSize,t);const i=this._windows[s.windowIndex];for(let e=0;e<this._blockSize;e++)for(let s=0;s<this._channels;s++)t[s][e]*=i[e];return s.overlapInfo}getPacketInfo(e){const t=new Ba;if(this._blockFlag){const s=e.readBit(),i=e.readBit();t.windowIndex=(s?1:0)+(i?2:0);const a=this._overlapInfo[t.windowIndex];t.overlapInfo.packetStartIndex=a.packetStartIndex,t.overlapInfo.packetValidLength=a.packetValidLength,t.overlapInfo.packetTotalLength=a.packetTotalLength}else t.windowIndex=0,t.overlapInfo.packetStartIndex=0,t.overlapInfo.packetValidLength=this._blockSize/2,t.overlapInfo.packetTotalLength=this._blockSize;return t}static calcWindow(e,t,s){const i=new Float32Array(t),a=e/2,r=s/2,n=t/4-a/2,o=t-t/4-r/2;for(let e=0;e<a;e++){let t=Math.sin((e+.5)/a*Ta.M_PI2);t*=t,i[n+e]=Math.sin(t*Ta.M_PI2)}for(let e=n+a;e<o;e++)i[e]=1;for(let e=0;e<r;e++){let t=Math.sin((r-e-.5)/r*Ta.M_PI2);t*=t,i[o+e]=Math.sin(t*Ta.M_PI2)}return i}static calcOverlap(e,t,s){const i=s/4,a=t/4-e/4,r=t/4*3+i,n=r-2*i,o=new wa;return o.packetStartIndex=a,o.packetValidLength=n,o.packetTotalLength=r,o}}Ta.M_PI2=1.57079632695;class Na{constructor(e){this._n=e,this._n2=e>>1,this._n4=this._n2>>1,this._n8=this._n4>>1,this._ld=aa.ilog(e)-1,this._a=new Float32Array(this._n2),this._b=new Float32Array(this._n2),this._c=new Float32Array(this._n4);let t=0,s=0;for(;t<this._n4;++t,s+=2)this._a[s]=Math.cos(4*t*Na.M_PI/e),this._a[s+1]=-Math.sin(4*t*Na.M_PI/e),this._b[s]=.5*Math.cos((s+1)*Na.M_PI/e/2),this._b[s+1]=.5*Math.sin((s+1)*Na.M_PI/e/2);for(t=0,s=0;t<this._n8;++t,s+=2)this._c[s]=Math.cos(2*(s+1)*Na.M_PI/e),this._c[s+1]=-Math.sin(2*(s+1)*Na.M_PI/e);this._bitrev=new Uint16Array(this._n8);for(let e=0;e<this._n8;++e)this._bitrev[e]=_t.int32ToUint16(aa.bitReverse(e,this._ld-3)<<2)}calcReverse(e){let t,s;const i=new Float32Array(this._n2);{let t=this._n2-2,s=0,a=0;const r=this._n2;for(;a!==r;)i[t+1]=e[a]*this._a[s]-e[a+2]*this._a[s+1],i[t]=e[a]*this._a[s+1]+e[a+2]*this._a[s],t-=2,s+=2,a+=4;for(a=this._n2-3;t>=0;)i[t+1]=-e[a+2]*this._a[s]- -e[a]*this._a[s+1],i[t]=-e[a+2]*this._a[s+1]+-e[a]*this._a[s],t-=2,s+=2,a-=4}t=e,s=i;{let e=this._n2-8,i=this._n4,a=0,r=this._n4,n=0;for(;e>=0;){let o,h;h=s[i+1]-s[a+1],o=s[i]-s[a],t[r+1]=s[i+1]+s[a+1],t[r]=s[i]+s[a],t[n+1]=h*this._a[e+4]-o*this._a[e+5],t[n]=o*this._a[e+4]+h*this._a[e+5],h=s[i+3]-s[a+3],o=s[i+2]-s[a+2],t[r+3]=s[i+3]+s[a+3],t[r+2]=s[i+2]+s[a+2],t[n+3]=h*this._a[e]-o*this._a[e+1],t[n+2]=o*this._a[e]+h*this._a[e+1],e-=8,r+=4,n+=4,i+=4,a+=4}}this.step3_iter0_loop(this._n>>4,t,this._n2-1-0*this._n4,-this._n8),this.step3_iter0_loop(this._n>>4,t,this._n2-1-1*this._n4,-this._n8),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-0*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-1*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-2*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-3*this._n8,-(this._n>>4),16);let a=2;for(;a<this._ld-3>>1;++a){const e=this._n>>a+2,s=e>>1,i=1<<a+1;for(let r=0;r<i;++r)this.step3_inner_r_loop(this._n>>a+4,t,this._n2-1-e*r,-s,1<<a+3)}for(;a<this._ld-6;++a){const e=this._n>>a+2,s=1<<a+3,i=e>>1,r=this._n>>a+6,n=1<<a+1;let o=this._n2-1,h=0;for(let a=r;a>0;--a)this.step3_inner_s_loop(n,t,o,-i,h,s,e),h+=4*s,o-=8}this.step3_inner_s_loop_ld654(this._n>>5,t,this._n2-1,this._n);{let e=0,i=this._n4-4,a=this._n2-4;for(;i>=0;){let r;r=this._bitrev[e],s[a+3]=t[r],s[a+2]=t[r+1],s[i+3]=t[r+2],s[i+2]=t[r+3],r=this._bitrev[e+1],s[a+1]=t[r],s[a]=t[r+1],s[i+1]=t[r+2],s[i]=t[r+3],i-=4,a-=4,e+=2}}{let e=0,t=0,i=this._n2-4;for(;t<i;){let a,r,n,o,h,l;a=s[t]-s[i+2],r=s[t+1]+s[i+3],n=this._c[e+1]*a+this._c[e]*r,o=this._c[e+1]*r-this._c[e]*a,h=s[t]+s[i+2],l=s[t+1]-s[i+3],s[t]=h+n,s[t+1]=l+o,s[i+2]=h-n,s[i+3]=o-l,a=s[t+2]-s[i],r=s[t+3]+s[i+1],n=this._c[e+3]*a+this._c[e+2]*r,o=this._c[e+3]*r-this._c[e+2]*a,h=s[t+2]+s[i],l=s[t+3]-s[i+1],s[t+2]=h+n,s[t+3]=l+o,s[i]=h-n,s[i+1]=o-l,e+=4,t+=4,i-=4}}{let t=this._n2-8,s=this._n2-8,a=0,r=this._n2-4,n=this._n2,o=this._n-4;for(;s>=0;){let h,l,c,d;d=i[s+6]*this._b[t+7]-i[s+7]*this._b[t+6],c=-i[s+6]*this._b[t+6]-i[s+7]*this._b[t+7],e[a]=d,e[r+3]=-d,e[n]=c,e[o+3]=c,l=i[s+4]*this._b[t+5]-i[s+5]*this._b[t+4],h=-i[s+4]*this._b[t+4]-i[s+5]*this._b[t+5],e[a+1]=l,e[r+2]=-l,e[n+1]=h,e[o+2]=h,d=i[s+2]*this._b[t+3]-i[s+3]*this._b[t+2],c=-i[s+2]*this._b[t+2]-i[s+3]*this._b[t+3],e[a+2]=d,e[r+1]=-d,e[n+2]=c,e[o+1]=c,l=i[s]*this._b[t+1]-i[s+1]*this._b[t],h=-i[s]*this._b[t]-i[s+1]*this._b[t+1],e[a+3]=l,e[r]=-l,e[n+3]=h,e[o]=h,t-=8,s-=8,a+=4,n+=4,r-=4,o-=4}}}step3_inner_r_loop(e,t,s,i,a){let r,n,o=s,h=o+i,l=0;for(let s=e>>2;s>0;--s)r=t[o]-t[h],n=t[o-1]-t[h-1],t[o]+=t[h],t[o-1]+=t[h-1],t[h]=r*this._a[l]-n*this._a[l+1],t[h-1]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-2]-t[h-2],n=t[o-3]-t[h-3],t[o-2]+=t[h-2],t[o-3]+=t[h-3],t[h-2]=r*this._a[l]-n*this._a[l+1],t[h-3]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-4]-t[h-4],n=t[o-5]-t[h-5],t[o-4]+=t[h-4],t[o-5]+=t[h-5],t[h-4]=r*this._a[l]-n*this._a[l+1],t[h-5]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-6]-t[h-6],n=t[o-7]-t[h-7],t[o-6]+=t[h-6],t[o-7]+=t[h-7],t[h-6]=r*this._a[l]-n*this._a[l+1],t[h-7]=n*this._a[l]+r*this._a[l+1],l+=a,o-=8,h-=8}step3_iter0_loop(e,t,s,i){let a=s,r=a+i,n=0;for(let s=e>>2;s>0;--s){let e,s;e=t[a]-t[r],s=t[a-1]-t[r-1],t[a]+=t[r],t[a-1]+=t[r-1],t[r]=e*this._a[n]-s*this._a[n+1],t[r-1]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-2]-t[r-2],s=t[a-3]-t[r-3],t[a-2]+=t[r-2],t[a-3]+=t[r-3],t[r-2]=e*this._a[n]-s*this._a[n+1],t[r-3]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-4]-t[r-4],s=t[a-5]-t[r-5],t[a-4]+=t[r-4],t[a-5]+=t[r-5],t[r-4]=e*this._a[n]-s*this._a[n+1],t[r-5]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-6]-t[r-6],s=t[a-7]-t[r-7],t[a-6]+=t[r-6],t[a-7]+=t[r-7],t[r-6]=e*this._a[n]-s*this._a[n+1],t[r-7]=s*this._a[n]+e*this._a[n+1],n+=8,a-=8,r-=8}}step3_inner_s_loop(e,t,s,i,a,r,n){const o=this._a[a],h=this._a[a+1],l=this._a[a+r],c=this._a[a+r+1],d=this._a[a+2*r],u=this._a[a+2*r+1],p=this._a[a+3*r],g=this._a[a+3*r+1];let m,f,y=s,b=y+i;for(let s=e;s>0;--s)m=t[y]-t[b],f=t[y-1]-t[b-1],t[y]+=t[b],t[y-1]+=t[b-1],t[b]=m*o-f*h,t[b-1]=f*o+m*h,m=t[y-2]-t[b-2],f=t[y-3]-t[b-3],t[y-2]+=t[b-2],t[y-3]+=t[b-3],t[b-2]=m*l-f*c,t[b-3]=f*l+m*c,m=t[y-4]-t[b-4],f=t[y-5]-t[b-5],t[y-4]+=t[b-4],t[y-5]+=t[b-5],t[b-4]=m*d-f*u,t[b-5]=f*d+m*u,m=t[y-6]-t[b-6],f=t[y-7]-t[b-7],t[y-6]+=t[b-6],t[y-7]+=t[b-7],t[b-6]=m*p-f*g,t[b-7]=f*p+m*g,y-=n,b-=n}step3_inner_s_loop_ld654(e,t,s,i){const a=i>>3,r=this._a[a];let n=s;const o=n-16*e;for(;n>o;){let e,s;e=t[n]-t[n-8],s=t[n-1]-t[n-9],t[n]+=t[n-8],t[n-1]+=t[n-9],t[n-8]=e,t[n-9]=s,e=t[n-2]-t[n-10],s=t[n-3]-t[n-11],t[n-2]+=t[n-10],t[n-3]+=t[n-11],t[n-10]=(e+s)*r,t[n-11]=(s-e)*r,e=t[n-12]-t[n-4],s=t[n-5]-t[n-13],t[n-4]+=t[n-12],t[n-5]+=t[n-13],t[n-12]=s,t[n-13]=e,e=t[n-14]-t[n-6],s=t[n-7]-t[n-15],t[n-6]+=t[n-14],t[n-7]+=t[n-15],t[n-14]=(e+s)*r,t[n-15]=(e-s)*r,this.iter_54(t,n),this.iter_54(t,n-8),n-=16}}iter_54(e,t){const s=e[t]-e[t-4],i=e[t]+e[t-4],a=e[t-2]+e[t-6],r=e[t-2]-e[t-6];e[t]=i+a,e[t-2]=i-a;const n=e[t-3]-e[t-7];e[t-4]=s+n,e[t-6]=s-n;const o=e[t-1]-e[t-5],h=e[t-1]+e[t-5],l=e[t-3]+e[t-7];e[t-1]=h+l,e[t-3]=h-l,e[t-5]=o-r,e[t-7]=o+r}}Na.M_PI=3.141592653589793;class xa{constructor(){this._setupCache=new Map}reverse(e,t){let s;this._setupCache.has(t)?s=this._setupCache.get(t):(s=new Na(t),this._setupCache.set(t,s)),s.calcReverse(e)}}class va{constructor(e,t,s){this._packetIndex=0,this._stream=e,this._setup=t,this._packets=s,this._currentPosition=0,this._prevPacketBuf=null,this._prevPacketStart=0,this._prevPacketEnd=0,this._prevPacketStop=0,this._nextPacketBuf=null,this._eosFound=!1,this._hasPosition=!1,this._modeFieldBits=aa.ilog(t.modes.length-1)}decode(){let e=new Float32Array(this._packets[this._packets.length-1].granulePosition*this._stream.audioChannels);const t=new Float32Array(.2*this._stream.audioSampleRate*this._stream.audioChannels);let s=0,i=0;for(;s=this.read(t,0,t.length),0!==s;){if(i+s>=e.length){const s=new Float32Array(e.length+t.length);s.set(e,0),e=s}e.set(t.subarray(0,s),i),i+=s}return e.subarray(0,i)}read(e,t,s){if(0===s)return 0;let i=t;const a=t+s;for(;i<a;){if(this._prevPacketStart===this._prevPacketEnd){if(this._eosFound){this._nextPacketBuf=null,this._prevPacketBuf=null;break}const e=this.readNextPacket((i-t)/this._stream.audioChannels);null===e&&(this._prevPacketEnd=this._prevPacketStop),null===e||null===e.samplePosition||this._hasPosition||(this._hasPosition=!0,this._currentPosition=e.samplePosition-(this._prevPacketEnd-this._prevPacketStart)-(i-t)/this._stream.audioChannels)}const s=Math.min((a-i)/this._stream.audioChannels,this._prevPacketEnd-this._prevPacketStart);s>0&&(i+=this.copyBuffer(e,i,s))}return s=i-t,this._currentPosition+=s/this._stream.audioChannels,s}copyBuffer(e,t,s){let i=t;for(;s>0;this._prevPacketStart++,s--)for(let t=0;t<this._stream.audioChannels;t++)e[i++]=this._prevPacketBuf[t][this._prevPacketStart];return i-t}readNextPacket(e){const t=this.decodeNextPacket();if(this._eosFound=this._eosFound||t.isEndOfStream,null==t.curPacket)return null;if(null!==t.samplePosition&&t.isEndOfStream){const s=this._currentPosition+e+t.validLen-t.startIndex,i=t.samplePosition-s;i<0&&(t.validLen+=i,t.validLen<0&&(t.validLen=0))}return this._prevPacketEnd>0?(va.overlapBuffers(this._prevPacketBuf,t.curPacket,this._prevPacketStart,this._prevPacketStop,t.startIndex,this._stream.audioChannels),this._prevPacketStart=t.startIndex):null==this._prevPacketBuf&&(this._prevPacketStart=t.validLen),this._nextPacketBuf=this._prevPacketBuf,this._prevPacketEnd=t.validLen,this._prevPacketStop=t.totalLen,this._prevPacketBuf=t.curPacket,new ka(t.samplePosition)}static overlapBuffers(e,t,s,i,a,r){for(;s<i;s++,a++)for(let i=0;i<r;i++)t[i][a]+=e[i][s]}decodeNextPacket(){const e=new Pa;let t=null;if(this._packetIndex>=this._packets.length)e.isEndOfStream=!0;else{t=this._packets[this._packetIndex++];const s=new sa(Bt.fromBuffer(t.packetData));if(e.isEndOfStream=t.isEndOfStream,!s.readBit()){const i=this._setup.modes[s.readBits(this._modeFieldBits)];if(null==this._nextPacketBuf){this._nextPacketBuf=new Array(this._stream.audioChannels);for(let e=0;e<this._stream.audioChannels;e++)this._nextPacketBuf[e]=new Float32Array(this._stream.blocksize1)}const a=i.decode(s,this._nextPacketBuf);return e.startIndex=a.packetStartIndex,e.validLen=a.packetValidLength,e.totalLen=a.packetTotalLength,e.samplePosition=t.granulePosition,e.curPacket=this._nextPacketBuf,e}}return e}}class Pa{constructor(){this.curPacket=null,this.startIndex=0,this.validLen=0,this.totalLen=0,this.isEndOfStream=!1,this.samplePosition=null}}!function(e){e[e.IdentificationHeader=1]="IdentificationHeader",e[e.Comment=3]="Comment",e[e.SetupHeader=5]="SetupHeader"}(Wi||(Wi={}));class Ca{constructor(e){this._packetIndex=-1,this._packets=e}read(){let e;for(;;){if(e=this.nextPacket(),null==e)return null;if(e.isBeginningOfStream){const t=this.readStream(e);if(null!=t)return t}}}nextPacket(){return this._packetIndex++,this._packetIndex<this._packets.length?this._packets[this._packetIndex]:null}readStream(e){const t=new ea;if(!this.readIdentificationHeader(t,e))return null;if(!this.readComments(this.nextPacket()))return null;const s=new ia;if(!this.readSetupHeader(t,s,this.nextPacket()))return null;const i=[];let a;for(;a=this.nextPacket(),null!=a&&(i.push(a),!a.isEndOfStream););const r=new va(t,s,i);return t.samples=r.decode(),t}comonHeaderDecode(e,t){const s=new Uint8Array(7);if(t.read(s,0,s.length),s[0]!==e)return!1;for(let e=0;e<Ca.VorbisHeaderMarker.length;e++)if(s[1+e]!==Ca.VorbisHeaderMarker[e])return!1;return!0}comonHeaderDecodeBit(e,t){const s=t.readBytes(7);if(s[0]!==e)return!1;for(let e=0;e<Ca.VorbisHeaderMarker.length;e++)if(s[1+e]!==Ca.VorbisHeaderMarker[e])return!1;return!0}readIdentificationHeader(e,t){const s=Bt.fromBuffer(t.packetData);if(!this.comonHeaderDecode(Wi.IdentificationHeader,s))return!1;if(0!==wt.readUInt32LE(s))return!1;if(e.audioChannels=s.readByte(),e.audioSampleRate=wt.readUInt32LE(s),e.audioChannels<=0||e.audioSampleRate<=0)return!1;e.bitrateMaximum=wt.readInt32LE(s),e.bitrateNominal=wt.readInt32LE(s),e.bitrateMinimum=wt.readInt32LE(s);const i=s.readByte();if(e.blocksize0=1<<(15&i),e.blocksize1=1<<(i>>4),e.blocksize0>e.blocksize1||!Ca.isAllowedBlockSize(e.blocksize0)||!Ca.isAllowedBlockSize(e.blocksize0))return!1;return 0!==s.readByte()}static isAllowedBlockSize(e){switch(e){case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:return!0;default:return!1}}readComments(e){if(null==e)return!1;const t=Bt.fromBuffer(e.packetData);if(!this.comonHeaderDecode(Wi.Comment,t))return!1;const s=wt.readUInt32LE(t);t.skip(s);const i=wt.readUInt32LE(t);for(let e=0;e<i;e++){const e=wt.readUInt32LE(t);t.skip(e)}return 0!==t.readByte()}readSetupHeader(e,t,s){if(null==s)return!1;const i=new sa(Bt.fromBuffer(s.packetData)),a=new xa,r=new la;if(!this.comonHeaderDecodeBit(Wi.SetupHeader,i))return!1;let n=i.readByte()+1;for(let e=0;e<n;e++)t.codebooks.push(new oa(i,r));n=i.readBits(6)+1;for(let e=0;e<n;e++)t.timeDomainTransforms.push(new ca(i));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.floors.push(new ma(i,e.blocksize0,e.blocksize1,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.residues.push(new Sa(i,e.audioChannels,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.mappings.push(new _a(i,e.audioChannels,t.floors,t.residues,a));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.modes.push(new Ta(i,e.audioChannels,e.blocksize0,e.blocksize1,t.mappings));return!!i.readBit()}}Ca.VorbisHeaderMarker=new Uint8Array(["v".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"b".charCodeAt(0),"i".charCodeAt(0),"s".charCodeAt(0)]);class Ea{constructor(e){this.streams=[];const t=new Zi(e).read(),s=new Ca(t);for(;;){const e=s.read();if(null==e)break;this.streams.push(e)}}}class Fa{constructor(){this.phdrs=[],this.pbags=[],this.pmods=[],this.pgens=[],this.insts=[],this.ibags=[],this.imods=[],this.igens=[],this.sHdrs=[],this.sampleData=new Uint8Array(0),this._sampleCache=new Map}decodeSamples(e,t,s){const i=`${e}_${t}_${s}`;if(!this._sampleCache.has(i)){let a;const r=this.sampleData.slice(e,t);if(s){a=new Ea(Bt.fromBuffer(r)).streams[0].samples}else{const e=new DataView(r.buffer,r.byteOffset,r.length);a=new Float32Array(r.length/2);for(let t=0;t<a.length;t++)a[t]=e.getInt16(2*t,!0)/32767}return this._sampleCache.set(i,a),a}return this._sampleCache.get(i)}load(e){const t=new ji,s=new ji;if(!ji.load(null,t,e)||"sfbk"!==t.id)throw new Ie("Soundfont is not a valid Soundfont2 file");for(;ji.load(t,s,e);){const t=new ji;if("pdta"===s.id)for(;ji.load(s,t,e);)switch(t.id){case"phdr":for(let s=0,i=t.size/Oa.SizeInFile|0;s<i;s++)this.phdrs.push(new Oa(e));break;case"pbag":for(let s=0,i=t.size/Aa.SizeInFile|0;s<i;s++)this.pbags.push(new Aa(e));break;case"pmod":for(let s=0,i=t.size/Ha.SizeInFile|0;s<i;s++)this.pmods.push(new Ha(e));break;case"pgen":for(let s=0,i=t.size/Ra.SizeInFile|0;s<i;s++)this.pgens.push(new Ra(e));break;case"inst":for(let s=0,i=t.size/Ia.SizeInFile|0;s<i;s++)this.insts.push(new Ia(e));break;case"ibag":for(let s=0,i=t.size/Da.SizeInFile|0;s<i;s++)this.ibags.push(new Da(e));break;case"imod":for(let s=0,i=t.size/Ma.SizeInFile|0;s<i;s++)this.imods.push(new Ma(e));break;case"igen":for(let s=0,i=t.size/La.SizeInFile|0;s<i;s++)this.igens.push(new La(e));break;case"shdr":for(let s=0,i=t.size/Wa.SizeInFile|0;s<i;s++)this.sHdrs.push(new Wa(e));break;default:e.position+=t.size}else if("sdta"===s.id)for(;ji.load(s,t,e);)if("smpl"===t.id)this.sampleData=new Uint8Array(t.size),e.read(this.sampleData,0,t.size);else e.position+=t.size;else e.position+=s.size}}}class Da{constructor(e){this.instGenNdx=wt.readUInt16LE(e),this.instModNdx=wt.readUInt16LE(e)}}Da.SizeInFile=4;class Ma{constructor(e){this.modSrcOper=wt.readUInt16LE(e),this.modDestOper=wt.readUInt16LE(e),this.modAmount=wt.readInt16LE(e),this.modAmtSrcOper=wt.readUInt16LE(e),this.modTransOper=wt.readUInt16LE(e)}}Ma.SizeInFile=10;class La{constructor(e){this.genOper=wt.readUInt16LE(e),this.genAmount=new Va(e)}}La.SizeInFile=4;class Ia{constructor(e){this.instName=wt.read8BitStringLength(e,20),this.instBagNdx=wt.readUInt16LE(e)}}Ia.SizeInFile=22;class Aa{constructor(e){this.genNdx=wt.readUInt16LE(e),this.modNdx=wt.readUInt16LE(e)}}Aa.SizeInFile=4;class Ra{constructor(e){this.genOper=wt.readUInt16LE(e),this.genAmount=new Va(e)}}Ra.SizeInFile=4,Ra.GenInstrument=41,Ra.GenKeyRange=43,Ra.GenVelRange=44,Ra.GenSampleId=53;class Oa{constructor(e){this.presetName=wt.read8BitStringLength(e,20),this.preset=wt.readUInt16LE(e),this.bank=wt.readUInt16LE(e),this.presetBagNdx=wt.readUInt16LE(e),this.library=wt.readUInt32LE(e),this.genre=wt.readUInt32LE(e),this.morphology=wt.readUInt32LE(e)}}Oa.SizeInFile=38;class Ha{constructor(e){this.modSrcOper=wt.readUInt16LE(e),this.modDestOper=wt.readUInt16LE(e),this.modAmount=wt.readUInt16LE(e),this.modAmtSrcOper=wt.readUInt16LE(e),this.modTransOper=wt.readUInt16LE(e)}}Ha.SizeInFile=10;class Wa{constructor(e){this.sampleName=wt.read8BitStringLength(e,20),this.start=wt.readUInt32LE(e),this.end=wt.readUInt32LE(e),this.startLoop=wt.readUInt32LE(e),this.endLoop=wt.readUInt32LE(e),this.sampleRate=wt.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=wt.readSInt8(e),this.sampleLink=wt.readUInt16LE(e),this.sampleType=wt.readUInt16LE(e)}}Wa.SizeInFile=46;class Va{get shortAmount(){return _t.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}constructor(e){this.wordAmount=wt.readUInt16LE(e)}}class Ga{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 Ua{constructor(){this.activeChannel=0,this.channelList=[]}setupVoice(e,t){const s=this.channelList[this.activeChannel],i=t.region.pan+s.panOffset;t.playingChannel=this.activeChannel,t.mixVolume=s.mixVolume,t.noteGainDb+=s.gainDb,t.updatePitchRatio(s,e.outSampleRate),i<=-.5?(t.panFactorLeft=1,t.panFactorRight=0):i>=.5?(t.panFactorLeft=0,t.panFactorRight=1):(t.panFactorLeft=Math.sqrt(.5-i),t.panFactorRight=Math.sqrt(.5+i))}}!function(e){e[e.None=0]="None",e[e.Continuous=1]="Continuous",e[e.Sustain=2]="Sustain"}(Vi||(Vi={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(Gi||(Gi={}));class za{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null}}class Xa{static timecents2Secs(e){return Math.pow(2,e/1200)}static decibelsToGain(e){return e>-100?Math.pow(10,.05*e):0}static gainToDecibels(e){return e<=1e-5?-100:20*Math.log10(e)}static cents2Hertz(e){return 8.176*Math.pow(2,e/1200)}}class Ja{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:Xa.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:Xa.timecents2Secs(this.attack),this.release=this.release<-11950?0:Xa.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:Xa.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:Xa.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?Xa.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"}(Ui||(Ui={}));class Ya{constructor(e){this.loopMode=Vi.None,this.samples=Ya.NoSamples,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv=new Ja,this.modEnv=new Ja,this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,e&&(this.loopMode=e.loopMode,this.samples=e.samples,this.sampleRate=e.sampleRate,this.loKey=e.loKey,this.hiKey=e.hiKey,this.loVel=e.loVel,this.hiVel=e.hiVel,this.group=e.group,this.offset=e.offset,this.end=e.end,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this.transpose=e.transpose,this.tune=e.tune,this.pitchKeyCenter=e.pitchKeyCenter,this.pitchKeyTrack=e.pitchKeyTrack,this.attenuation=e.attenuation,this.pan=e.pan,this.ampEnv=new Ja(e.ampEnv),this.modEnv=new Ja(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=Vi.None,this.samples=Ya.NoSamples,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv.clear(),this.modEnv.clear(),this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,this.hiKey=127,this.hiVel=127,this.pitchKeyCenter=60,e||(this.pitchKeyTrack=100,this.pitchKeyCenter=-1,this.ampEnv.delay=-12e3,this.ampEnv.attack=-12e3,this.ampEnv.hold=-12e3,this.ampEnv.decay=-12e3,this.ampEnv.release=-12e3,this.modEnv.delay=-12e3,this.modEnv.attack=-12e3,this.modEnv.hold=-12e3,this.modEnv.decay=-12e3,this.modEnv.release=-12e3,this.initialFilterFc=13500,this.delayModLFO=-12e3,this.delayVibLFO=-12e3)}operator(e,t){switch(e){case Ui.StartAddrsOffset:this.offset+=_t.int16ToUint32(t.shortAmount);break;case Ui.EndAddrsOffset:this.end+=_t.int16ToUint32(t.shortAmount);break;case Ui.StartloopAddrsOffset:this.loopStart+=_t.int16ToUint32(t.shortAmount);break;case Ui.EndloopAddrsOffset:this.loopEnd+=_t.int16ToUint32(t.shortAmount);break;case Ui.StartAddrsCoarseOffset:this.offset+=32768*_t.int16ToUint32(t.shortAmount);break;case Ui.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case Ui.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case Ui.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case Ui.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case Ui.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case Ui.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case Ui.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case Ui.EndAddrsCoarseOffset:this.end+=32768*_t.int16ToUint32(t.shortAmount);break;case Ui.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case Ui.Pan:this.pan=t.shortAmount/1e3;break;case Ui.DelayModLFO:this.delayModLFO=t.shortAmount;break;case Ui.FreqModLFO:this.freqModLFO=t.shortAmount;break;case Ui.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case Ui.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case Ui.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case Ui.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case Ui.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case Ui.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case Ui.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case Ui.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case Ui.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case Ui.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case Ui.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case Ui.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case Ui.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case Ui.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case Ui.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case Ui.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case Ui.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case Ui.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case Ui.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case Ui.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case Ui.StartloopAddrsCoarseOffset:this.loopStart+=32768*_t.int16ToUint32(t.shortAmount);break;case Ui.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case Ui.EndloopAddrsCoarseOffset:this.loopEnd+=32768*_t.int16ToUint32(t.shortAmount);break;case Ui.CoarseTune:this.transpose+=t.shortAmount;break;case Ui.FineTune:this.tune+=t.shortAmount;break;case Ui.SampleModes:this.loopMode=3&~t.wordAmount?1==(3&t.wordAmount)?Vi.Continuous:Vi.None:Vi.Sustain;break;case Ui.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case Ui.ExclusiveClass:this.group=t.wordAmount;break;case Ui.OverridingRootKey:this.pitchKeyCenter=t.shortAmount}}}Ya.NoSamples=new Float32Array(0),function(e){e[e.None=0]="None",e[e.Delay=1]="Delay",e[e.Attack=2]="Attack",e[e.Hold=3]="Hold",e[e.Decay=4]="Decay",e[e.Sustain=5]="Sustain",e[e.Release=6]="Release",e[e.Done=7]="Done"}(zi||(zi={}));class $a{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=zi.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case zi.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=zi.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=zi.Delay;break;case zi.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=zi.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=zi.Attack;break;case zi.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=zi.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=zi.Hold;break;case zi.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=zi.Decay,this.level=1,this.isAmpEnv){const 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=zi.Decay;break;case zi.Decay:return this.segment=zi.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case zi.Sustain:if(this.segment=zi.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?$a.FastReleaseTime:this.parameters.release)*t|0,this.isAmpEnv){const 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=zi.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,s,i,a){this.parameters=new Ja(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:Xa.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:Xa.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|s,this.isAmpEnv=i,this.nextSegment(zi.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)}}$a.FastReleaseTime=.01;class qa{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,s){this.samplesUntil=e*s|0,this.delta=4*Xa.cents2Hertz(t)/s,this.level=0}process(e){this.samplesUntil>e?this.samplesUntil-=e:(this.level+=this.delta*e,this.level>1?(this.delta=-this.delta,this.level=2-this.level):this.level<-1&&(this.delta=-this.delta,this.level=-2-this.level))}}class Ka{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){const t=Math.tan(Math.PI*e),s=t*t,i=1/(1+t*this.qInv+s);this.a0=s*i,this.a1=2*this.a0,this.b1=2*(s-1)*i,this.b2=(1-t*this.qInv+s)*i}process(e){const 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 ja{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 $a,this.modEnv=new $a,this.lowPass=new Ka,this.modLfo=new qa,this.vibLfo=new qa,this.mixVolume=0,this.mute=!1}updatePitchRatio(e,t){let s=e.pitchWheel;e.perNotePitchWheel.has(this.playingKey)&&(s+=e.perNotePitchWheel.get(this.playingKey)-8192);const i=8192===s?e.tuning:s/16383*e.pitchRange*2-e.pitchRange+e.tuning;this.calcPitchRatio(i,t)}calcPitchRatio(e,t){if(!this.region)return;const s=this.playingKey+this.region.transpose+this.region.tune/100;let i=this.region.pitchKeyCenter+(s-this.region.pitchKeyCenter)*(this.region.pitchKeyTrack/100);0!==e&&(i+=e),this.pitchInputTimecents=100*i,this.pitchOutputFactor=this.region.sampleRate/(Xa.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(zi.Sustain,e),this.modEnv.nextSegment(zi.Sustain,e),this.region.loopMode===Vi.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(zi.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(zi.Sustain,e)}render(e,t,s,i,a){if(!this.region)return;const r=this.region,n=r.samples;let o=0,h=e.outputMode===Gi.StereoUnweaved?i:-1;const l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,c=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),d=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,m=r.end,f=g+1;let y=this.sourceSamplePosition;const b=new Ka(this.lowPass),S=0!==r.modLfoToFilterFc||0!==r.modEnvToFilterFc;let _=0,w=0,B=0,k=0;const T=0!==r.modLfoToPitch||0!==r.modEnvToPitch||0!==r.vibLfoToPitch;let N=0,x=0,v=0,P=0;const C=0!==r.modLfoToVolume;let E=0,F=0;for(S?(_=e.outSampleRate,w=r.initialFilterFc,B=r.modLfoToFilterFc,k=r.modEnvToFilterFc):(_=0,w=0,B=0,k=0),T?(N=0,x=r.modLfoToPitch,v=r.vibLfoToPitch,P=r.modEnvToPitch):(N=Xa.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,x=0,v=0,P=0),C?F=.1*r.modLfoToVolume:(E=Xa.decibelsToGain(this.noteGainDb),F=0);i>0;){let r,D,M=0,L=i>ja.RenderEffectSampleBlock?ja.RenderEffectSampleBlock:i;if(i-=L,S){const e=w+this.modLfo.level*B+this.modEnv.level*k;b.active=e<=13500,b.active&&b.setup(Xa.cents2Hertz(e)/_)}switch(T&&(N=Xa.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*x+this.vibLfo.level*v+this.modEnv.level*P))*this.pitchOutputFactor),C&&(E=Xa.decibelsToGain(this.noteGainDb+this.modLfo.level*F)),r=E*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(L,e.outSampleRate),l&&this.modEnv.process(L,e.outSampleRate),c&&this.modLfo.process(L),d&&this.vibLfo.process(L),e.outputMode){case Gi.StereoInterleaved:for(D=r*this.panFactorLeft,M=r*this.panFactorRight;L-- >0&&y<m;){const e=0|y,i=e>=g&&u?p:e+1,a=y-e;let r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*D,o++,t[s+o]+=r*M,o++,y+=N,y>=f&&u&&(y-=g-p+1)}break;case Gi.StereoUnweaved:for(D=r*this.panFactorLeft,M=r*this.panFactorRight;L-- >0&&y<m;){const e=0|y,i=e>=g&&u?p:e+1,a=y-e;let r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*D,o++,t[s+h]+=r*M,h++,y+=N,y>=f&&u&&(y-=g-p+1)}break;case Gi.Mono:for(;L-- >0&&y<m;){const e=0|y,i=e>=g&&u?p:e+1,a=y-e;let h=n[e]*(1-a)+n[i]*a;b.active&&(h=b.process(h)),t[s+o]=h*r,o++,y+=N,y>=f&&u&&(y-=g-p+1)}}if(y>=m||this.ampEnv.segment===zi.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}ja.RenderEffectSampleBlock=kt.MicroBufferSize;class Qa{constructor(){this._items=[],this._position=0,this.isEmpty=!0}clear(){this._items=[],this._position=0,this.isEmpty=!0}enqueue(e){this.isEmpty=!1,this._items.push(e)}peek(){return this._items[this._position]}dequeue(){const e=this._items[this._position];return this._position++,this._position>=this._items.length/2&&(this._items=this._items.slice(this._position),this._position=0),this.isEmpty=0===this._items.length,e}toArray(){const e=this._items.slice(this._position);return e.reverse(),e}}!function(e){e[e.BankSelectCoarse=0]="BankSelectCoarse",e[e.ModulationCoarse=1]="ModulationCoarse",e[e.DataEntryCoarse=6]="DataEntryCoarse",e[e.VolumeCoarse=7]="VolumeCoarse",e[e.PanCoarse=10]="PanCoarse",e[e.ExpressionControllerCoarse=11]="ExpressionControllerCoarse",e[e.BankSelectFine=32]="BankSelectFine",e[e.ModulationFine=33]="ModulationFine",e[e.DataEntryFine=38]="DataEntryFine",e[e.VolumeFine=39]="VolumeFine",e[e.PanFine=42]="PanFine",e[e.ExpressionControllerFine=43]="ExpressionControllerFine",e[e.HoldPedal=64]="HoldPedal",e[e.LegatoPedal=68]="LegatoPedal",e[e.NonRegisteredParameterFine=98]="NonRegisteredParameterFine",e[e.NonRegisteredParameterCourse=99]="NonRegisteredParameterCourse",e[e.RegisteredParameterFine=100]="RegisteredParameterFine",e[e.RegisteredParameterCourse=101]="RegisteredParameterCourse",e[e.AllSoundOff=120]="AllSoundOff",e[e.ResetControllers=121]="ResetControllers",e[e.AllNotesOff=123]="AllNotesOff"}(Xi||(Xi={}));class Za{constructor(e){this._midiEventQueue=new Qa,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this._transpositionPitches=new Map,this._liveTranspositionPitches=new Map,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=Gi.StereoInterleaved,this.outSampleRate=0,this.globalGainDb=0,this.outSampleRate=e}synthesize(e,t,s){return this.fillWorkingBuffer(e,t,s)}synthesizeSilent(e){this.fillWorkingBuffer(null,0,e)}channelGetMixVolume(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].mixVolume:1}channelSetMixVolume(e,t){const s=this.channelInit(e);for(const s of this._voices)s.playingChannel===e&&-1!==s.playingPreset&&(s.mixVolume=t);s.mixVolume=t}channelSetMute(e,t){t?this._mutedChannels.set(e,!0):this._mutedChannels.delete(e)}channelSetSolo(e,t){t?this._soloChannels.set(e,!0):this._soloChannels.delete(e),this._isAnySolo=this._soloChannels.size>0}resetChannelStates(){this._mutedChannels=new Map,this._soloChannels=new Map,this._liveTranspositionPitches=new Map,this.applyTranspositionPitches(new Map),this._isAnySolo=!1}setChannelTranspositionPitch(e,t){let s=0;this._liveTranspositionPitches.has(e)&&(s=this._liveTranspositionPitches.get(e)),0===t?this._liveTranspositionPitches.delete(e):this._liveTranspositionPitches.set(e,t);for(const i of this._voices)if(i.playingChannel===e&&9!==i.playingChannel){let e=0;e-=s,e+=t,i.playingKey+=e,this._channels&&i.updatePitchRatio(this._channels.channelList[i.playingChannel],this.outSampleRate)}}applyTranspositionPitches(e){const t=this._transpositionPitches;for(const s of this._voices)if(s.playingChannel>=0&&9!==s.playingChannel){let i=0;t.has(s.playingChannel)&&(i-=t.get(s.playingChannel)),e.has(s.playingChannel)&&(i+=e.get(s.playingChannel)),s.playingKey+=i,this._channels&&s.updatePitchRatio(this._channels.channelList[s.playingChannel],this.outSampleRate)}this._transpositionPitches=e}dispatchEvent(e){this._midiEventQueue.enqueue(e)}fillWorkingBuffer(e,t,s){const i=this._isAnySolo,a=[];for(;!this._midiEventQueue.isEmpty;){const e=this._midiEventQueue.dequeue();e.isMetronome&&this.metronomeVolume>0?(this.channelNoteOff(kt.MetronomeChannel,kt.MetronomeKey),this.channelNoteOn(kt.MetronomeChannel,kt.MetronomeKey,95/127)):e.event&&this.processMidiMessage(e.event),a.push(e)}for(const a of this._voices)if(-1!==a.playingPreset){const r=a.playingChannel,n=this._mutedChannels.has(r)||i&&r!==kt.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,s,n):a.kill()}return a}processMidiMessage(e){he.debug("Midi",`Processing Midi message ${it[e.type]}/${e.tick}`);switch(e.type){case it.TimeSignature:const t=e;this.timeSignatureNumerator=t.numerator,this.timeSignatureDenominator=Math.pow(2,t.denominatorIndex);break;case it.NoteOn:const s=e;this.channelNoteOn(s.channel,s.noteKey,s.noteVelocity/127);break;case it.NoteOff:const i=e;this.channelNoteOff(i.channel,i.noteKey);break;case it.ControlChange:const a=e;this.channelMidiControl(a.channel,a.controller,a.value);break;case it.ProgramChange:const r=e;this.channelSetPresetNumber(r.channel,r.program,9===r.channel);break;case it.TempoChange:const n=e;this.currentTempo=6e7/n.microSecondsPerQuarterNote;break;case it.PitchBend:const o=e;this.channelSetPitchWheel(o.channel,o.value);break;case it.PerNotePitchBend:const h=e;let l=h.value;l=l*kt.MaxPitchWheel/kt.MaxPitchWheel20,this.channelSetPerNotePitchWheel(h.channel,h.noteKey,l)}}get metronomeVolume(){return this.channelGetMixVolume(kt.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(kt.MetronomeChannel,e),e>0&&(this.channelSetVolume(kt.MetronomeChannel,1),this.channelSetPresetNumber(kt.MetronomeChannel,0,!0))}get masterVolume(){return Xa.decibelsToGain(this.globalGainDb)}set masterVolume(e){const t=Xa.gainToDecibels(e),s=t-this.globalGainDb;if(0!==s){for(const e of this._voices)-1!==e.playingPreset&&(e.noteGainDb+=s);this.globalGainDb=t}}resetSoft(){for(const e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<zi.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);if(this._channels)for(const e of this._channels.channelList)e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.perNotePitchWheel.clear(),e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0}get presetCount(){return this.presets?.length??0}reset(){for(const e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<zi.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);this._channels=null}setOutput(e,t,s){this.outputMode=e,this.outSampleRate=t>=1?t:44100,this.globalGainDb=s}noteOn(e,t,s){if(!this.presets)return;const i=127*s|0;if(e<0||e>=this.presets.length)return;if(s<=0)return void this.noteOff(e,t);const a=this._voicePlayIndex++;for(const r of this.presets[e].regions){if(t<r.loKey||t>r.hiKey||i<r.loVel||i>r.hiVel)continue;let n=null;if(0!==r.group)for(const t of this._voices)t.playingPreset===e&&t.region.group===r.group?t.endQuick(this.outSampleRate):-1!==t.playingPreset||n||(n=t);else for(const e of this._voices)-1===e.playingPreset&&(n=e);if(!n){for(let e=0;e<4;e++){const e=new ja;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-Xa.gainToDecibels(1/s),this._channels?this._channels.setupVoice(this,n):(n.calcPitchRatio(0,this.outSampleRate),n.panFactorLeft=Math.sqrt(.5-r.pan),n.panFactorRight=Math.sqrt(.5+r.pan)),n.sourceSamplePosition=r.offset;const o=r.loopMode!==Vi.None&&r.loopStart<r.loopEnd;n.loopStart=o?r.loopStart:0,n.loopEnd=o?r.loopEnd:0,n.ampEnv.setup(r.ampEnv,t,i,!0,this.outSampleRate),n.modEnv.setup(r.modEnv,t,i,!1,this.outSampleRate);const h=r.initialFilterQ/10;n.lowPass.qInv=1/Math.pow(10,h/20),n.lowPass.z1=0,n.lowPass.z2=0,n.lowPass.active=r.initialFilterFc<=13500,n.lowPass.active&&n.lowPass.setup(Xa.cents2Hertz(r.initialFilterFc)/this.outSampleRate),n.modLfo.setup(r.delayModLFO,r.freqModLFO,this.outSampleRate),n.vibLfo.setup(r.delayVibLFO,r.freqVibLFO,this.outSampleRate)}}bankNoteOn(e,t,s,i){const a=this.getPresetIndex(e,t);return-1!==a&&(this.noteOn(a,s,i),!0)}noteOff(e,t){let s=null,i=null;const a=[];for(const r of this._voices)r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=zi.Release||(!s||r.playIndex<s.playIndex?(s=r,i=r,a.push(r)):r.playIndex===s.playIndex&&(i=r,a.push(r)));if(s)for(const r of a)r!==s&&r!==i&&(r.playIndex!==s.playIndex||r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=zi.Release)||r.end(this.outSampleRate)}bankNoteOff(e,t,s){const i=this.getPresetIndex(e,t);return-1!==i&&(this.noteOff(i,s),!0)}noteOffAll(e){for(const t of this._voices)-1!==t.playingPreset&&(e?t.endQuick(this.outSampleRate):t.ampEnv.segment<zi.Release&&t.end(this.outSampleRate))}get activeVoiceCount(){let e=0;for(const t of this._voices)-1!==t.playingPreset&&e++;return e}channelInit(e){if(this._channels&&e<this._channels.channelList.length)return this._channels.channelList[e];this._channels||(this._channels=new Ua);for(let t=this._channels.channelList.length;t<=e;t++){const e=new Ga;e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0,e.mixVolume=1,this._channels.channelList.push(e)}return this._channels.channelList[e]}getPresetIndex(e,t){if(!this.presets)return-1;for(let s=this.presets.length-1;s>=0;s--){const i=this.presets[s];if(i.presetNumber===t&&i.bank===e)return s}return-1}getPresetName(e){return this.presets?e<0||e>=this.presets.length?null:this.presets[e].name:null}bankGetPresetName(e,t){return this.getPresetName(this.getPresetIndex(e,t))}channelNoteOn(e,t,s){!this._channels||e>this._channels.channelList.length||(this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e)),this._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,s))}channelNoteOff(e,t){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e));const s=[];let i=null,a=null;for(const r of this._voices)-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=zi.Release||(!i||r.playIndex<i.playIndex?(i=r,a=r,s.push(r)):r.playIndex===i.playIndex&&(a=r,s.push(r)));if(this.channelInit(e).perNotePitchWheel.delete(t),i)for(const r of s)r!==i&&r!==a&&(r.playIndex!==i.playIndex||-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=zi.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<zi.Release&&t.end(this.outSampleRate)}channelSoundsOffAll(e){this.channelInit(e).perNotePitchWheel.clear();for(const t of this._voices)-1!==t.playingPreset&&t.playingChannel===e&&(t.ampEnv.segment<zi.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=_t.int32ToUint16(t)}channelSetPresetNumber(e,t,s=!1){const i=this.channelInit(e);let a=0;return s?(a=this.getPresetIndex(128|32767&i.bank,t),-1===a&&(a=this.getPresetIndex(128,t)),-1===a&&(a=this.getPresetIndex(128,0)),-1===a&&(a=this.getPresetIndex(2047&i.bank,t))):a=this.getPresetIndex(2047&i.bank,t),i.presetIndex=a,-1!==a}channelSetBank(e,t){this.channelInit(e).bank=_t.int32ToUint16(t)}channelSetBankPreset(e,t,s){const i=this.channelInit(e),a=this.getPresetIndex(t,s);return-1!==a&&(i.presetIndex=_t.int32ToUint16(a),i.bank=_t.int32ToUint16(t),!0)}channelSetPan(e,t){for(const s of this._voices)if(s.playingChannel===e&&-1!==s.playingPreset){const e=s.region.pan+t-.5;e<=-.5?(s.panFactorLeft=1,s.panFactorRight=0):e>=.5?(s.panFactorLeft=0,s.panFactorRight=1):(s.panFactorLeft=Math.sqrt(.5-e),s.panFactorRight=Math.sqrt(.5+e))}this.channelInit(e).panOffset=t-.5}channelSetVolume(e,t){const s=this.channelInit(e),i=Xa.gainToDecibels(t),a=i-s.gainDb;if(0!==a){for(const t of this._voices)t.playingChannel===e&&-1!==t.playingPreset&&(t.noteGainDb+=a);s.gainDb=i}}channelSetPitchWheel(e,t){const s=this.channelInit(e);s.pitchWheel!==t&&(s.pitchWheel=_t.int32ToUint16(t),this.channelApplyPitch(e,s))}channelSetPerNotePitchWheel(e,t,s){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e));const i=this.channelInit(e);i.perNotePitchWheel.has(t)&&i.perNotePitchWheel.get(t)===s||(i.perNotePitchWheel.set(t,s),this.channelApplyPitch(e,i,t))}channelApplyPitch(e,t,s=-1){for(const i of this._voices)i.playingChannel!==e||-1===i.playingPreset||-1!==s&&i.playingKey!==s||i.updatePitchRatio(t,this.outSampleRate)}channelSetPitchRange(e,t){const s=this.channelInit(e);s.pitchRange!==t&&(s.pitchRange=t,8192!==s.pitchWheel&&this.channelApplyPitch(e,s))}channelSetTuning(e,t){const s=this.channelInit(e);s.tuning!==t&&(s.tuning=t,this.channelApplyPitch(e,s))}channelMidiControl(e,t,s){const i=this.channelInit(e);switch(t){case Xi.DataEntryFine:return i.midiData=_t.int32ToUint16(16256&i.midiData|s),void(0===i.midiRpn?this.channelSetPitchRange(e,(i.midiData>>7)+.01*(127&i.midiData)):1===i.midiRpn?this.channelSetTuning(e,(0|i.tuning)+(i.midiData-8192)/8192):2===i.midiRpn&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Xi.VolumeCoarse:return i.midiVolume=_t.int32ToUint16(127&i.midiVolume|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Xi.VolumeFine:return i.midiVolume=_t.int32ToUint16(16256&i.midiVolume|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Xi.ExpressionControllerCoarse:return i.midiExpression=_t.int32ToUint16(127&i.midiExpression|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Xi.ExpressionControllerFine:return i.midiExpression=_t.int32ToUint16(16256&i.midiExpression|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Xi.PanCoarse:return i.midiPan=_t.int32ToUint16(127&i.midiPan|s<<7),void this.channelSetPan(e,i.midiPan/16383);case Xi.PanFine:return i.midiPan=_t.int32ToUint16(16256&i.midiPan|s),void this.channelSetPan(e,i.midiPan/16383);case Xi.DataEntryCoarse:return i.midiData=_t.int32ToUint16(127&i.midiData|s<<7),void(0===i.midiRpn?this.channelSetPitchRange(e,(i.midiData>>7)+.01*(127&i.midiData)):1===i.midiRpn?this.channelSetTuning(e,(0|i.tuning)+(i.midiData-8192)/8192):2===i.midiRpn&&t===Xi.DataEntryCoarse&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Xi.BankSelectCoarse:return void(i.bank=_t.int32ToUint16(32768|s));case Xi.BankSelectFine:return void(i.bank=_t.int32ToUint16((32768&i.bank?(127&i.bank)<<7:0)|s));case Xi.RegisteredParameterCourse:return void(i.midiRpn=_t.int32ToUint16(127&(65535===i.midiRpn?0:i.midiRpn)|s<<7));case Xi.RegisteredParameterFine:return void(i.midiRpn=_t.int32ToUint16(16256&(65535===i.midiRpn?0:i.midiRpn)|s));case Xi.NonRegisteredParameterFine:case Xi.NonRegisteredParameterCourse:return void(i.midiRpn=65535);case Xi.AllSoundOff:return void this.channelSoundsOffAll(e);case Xi.AllNotesOff:return void this.channelNoteOffAll(e);case Xi.ResetControllers:return i.midiVolume=16383,i.midiExpression=16383,i.midiPan=8192,i.bank=0,this.channelSetVolume(e,1),this.channelSetPan(e,.5),void this.channelSetPitchRange(e,2)}}channelGetPresetIndex(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].presetIndex:0}channelGetPresetBank(e){return this._channels&&e<this._channels.channelList.length?32767&this._channels.channelList[e].bank:0}channelGetPan(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].panOffset-.5:.5}channelGetVolume(e){return this._channels&&e<this._channels.channelList.length?Xa.decibelsToGain(this._channels.channelList[e].gainDb):1}channelGetPitchWheel(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchWheel:8192}channelGetPitchRange(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchRange:2}channelGetTuning(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].tuning:0}resetPresets(){this.presets=[]}loadPresets(e,t,s,i){const a=[];for(let i=0;i<e.phdrs.length-1;i++){const r=e.phdrs[i];let n=0;const o=new za;a.push(o),o.name=r.presetName,o.bank=r.bank,o.presetNumber=r.preset;let h=0;for(let t=r.presetBagNdx;t<e.phdrs[i+1].presetBagNdx;t++){let s=0,i=127,a=0,r=127;for(let n=e.pbags[t].genNdx;n<e.pbags[t+1].genNdx;n++){const t=e.pgens[n];if(t.genOper===Ra.GenKeyRange){s=t.genAmount.lowByteAmount,i=t.genAmount.highByteAmount;continue}if(t.genOper===Ra.GenVelRange){a=t.genAmount.lowByteAmount,r=t.genAmount.highByteAmount;continue}if(t.genOper!==Ra.GenInstrument)continue;if(t.genAmount.wordAmount>=e.insts.length)continue;for(let n=e.insts[t.genAmount.wordAmount].instBagNdx;n<e.insts[t.genAmount.wordAmount+1].instBagNdx;n++){let t=0,o=127,l=0,c=127;for(let d=e.ibags[n].instGenNdx;d<e.ibags[n+1].instGenNdx;d++){const n=e.igens[d];n.genOper!==Ra.GenKeyRange?n.genOper!==Ra.GenVelRange?53===n.genOper&&o>=s&&t<=i&&c>=a&&l<=r&&h++:(l=n.genAmount.lowByteAmount,c=n.genAmount.highByteAmount):(t=n.genAmount.lowByteAmount,o=n.genAmount.highByteAmount)}}}}o.regions=new Array(h);let l=new Ya;l.clear(!0);for(let a=r.presetBagNdx;a<e.phdrs[i+1].presetBagNdx;a++){const i=e.pbags[a],h=new Ya(l);let c=!1;for(let l=i.genNdx;l<e.pbags[a+1].genNdx;l++){const i=e.pgens[l];if(i.genOper===Ra.GenInstrument){const a=i.genAmount.wordAmount;if(a>=e.insts.length)continue;let l=new Ya;l.clear(!1);const d=e.insts[a];for(let i=d.instBagNdx;i<e.insts[a+1].instBagNdx;i++){const a=e.ibags[i],c=new Ya(l);let u=!1;for(let l=a.instGenNdx;l<e.ibags[i+1].instGenNdx;l++){const i=e.igens[l];if(i.genOper===Ra.GenSampleId){if(c.hiKey<h.loKey||c.loKey>h.hiKey)continue;if(c.hiVel<h.loVel||c.loVel>h.hiVel)continue;h.loKey>c.loKey&&(c.loKey=h.loKey),h.hiKey<c.hiKey&&(c.hiKey=h.hiKey),h.loVel>c.loVel&&(c.loVel=h.loVel),h.hiVel<c.hiVel&&(c.hiVel=h.hiVel),c.offset+=h.offset,c.end+=h.end,c.loopStart+=h.loopStart,c.loopEnd+=h.loopEnd,c.transpose+=h.transpose,c.tune+=h.tune,c.pitchKeyTrack+=h.pitchKeyTrack,c.attenuation+=h.attenuation,c.pan+=h.pan,c.ampEnv.delay+=h.ampEnv.delay,c.ampEnv.attack+=h.ampEnv.attack,c.ampEnv.hold+=h.ampEnv.hold,c.ampEnv.decay+=h.ampEnv.decay,c.ampEnv.sustain+=h.ampEnv.sustain,c.ampEnv.release+=h.ampEnv.release,c.modEnv.delay+=h.modEnv.delay,c.modEnv.attack+=h.modEnv.attack,c.modEnv.hold+=h.modEnv.hold,c.modEnv.decay+=h.modEnv.decay,c.modEnv.sustain+=h.modEnv.sustain,c.modEnv.release+=h.modEnv.release,c.initialFilterQ+=h.initialFilterQ,c.initialFilterFc+=h.initialFilterFc,c.modEnvToPitch+=h.modEnvToPitch,c.modEnvToFilterFc+=h.modEnvToFilterFc,c.delayModLFO+=h.delayModLFO,c.freqModLFO+=h.freqModLFO,c.modLfoToPitch+=h.modLfoToPitch,c.modLfoToFilterFc+=h.modLfoToFilterFc,c.modLfoToVolume+=h.modLfoToVolume,c.delayVibLFO+=h.delayVibLFO,c.freqVibLFO+=h.freqVibLFO,c.vibLfoToPitch+=h.vibLfoToPitch,c.ampEnv.envToSecs(!0),c.modEnv.envToSecs(!1),c.delayModLFO=c.delayModLFO<-11950?0:Xa.timecents2Secs(c.delayModLFO),c.delayVibLFO=c.delayVibLFO<-11950?0:Xa.timecents2Secs(c.delayVibLFO),c.pan<-.5?c.pan=-.5:c.pan>.5&&(c.pan=.5),(c.initialFilterQ<1500||c.initialFilterQ>13500)&&(c.initialFilterQ=0);const a=e.sHdrs[i.genAmount.wordAmount];c.offset+=a.start,c.end+=a.end,c.loopStart+=a.startLoop,c.loopEnd+=a.endLoop,a.endLoop>0&&(c.loopEnd-=1),-1===c.pitchKeyCenter&&(c.pitchKeyCenter=a.originalPitch),c.tune+=a.pitchCorrection,c.sampleRate=a.sampleRate;const l=r.bank===kt.PercussionBank;if(l&&Za.setContainsRange(s,c.loKey,c.hiKey)||!l&&t.has(r.preset))if(1&a.sampleType){he.debug("AlphaSynth",`Loading of used sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`);!!(16&a.sampleType)?c.samples=e.decodeSamples(a.start,a.end,!0):(c.samples=e.decodeSamples(2*c.offset,2*c.end,!1),c.loopStart>0&&(c.loopStart-=c.offset),c.loopEnd>0&&(c.loopEnd-=c.offset)),c.offset=0,c.end=c.samples.length-1}else he.warning("AlphaSynth",`Skipping load of unsupported sample ${a.sampleName} for preset ${r.presetName}, sample type ${a.sampleType} is not supported (bank ${o.bank} program ${o.presetNumber})`),c.samples=new Float32Array(0);else he.debug("AlphaSynth",`Skipping load of unused sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`),c.samples=new Float32Array(0);o.regions[n]=new Ya(c),n++,u=!0}else c.operator(i.genOper,i.genAmount)}a!==e.ibags[d.instBagNdx]||u||(l=new Ya(c))}c=!0}else h.operator(i.genOper,i.genAmount)}i!==e.pbags[r.presetBagNdx]||c||(l=h)}}if(i&&this.presets)for(const e of a)this.presets.push(e);else this.presets=a}static setContainsRange(e,t,s){for(let i=t;i<=s;i++)if(e.has(i))return!0;return!1}hasSamplesForProgram(e){const t=this.presets;if(!t)return!1;for(const s of t)if(s.presetNumber===e)for(const e of s.regions)if(e.samples.length>0)return!0;return!1}hasSamplesForPercussion(e){const t=this.presets;if(!t)return!1;for(const s of t)if(s.bank===kt.PercussionBank)for(const t of s.regions)if(t.loKey>=e&&t.hiKey<=e&&t.samples.length>0)return!0;return!1}}class er{constructor(e){this.events=e}}class tr{constructor(e){this.playbackRange=e}}class sr{get output(){return this._output}get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return he.logLevel}set logLevel(e){he.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,kt.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,kt.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,kt.MinVolume),this._countInVolume=e}get midiEventsPlayedFilter(){return Array.from(this._midiEventsPlayedFilter)}set midiEventsPlayedFilter(e){this._midiEventsPlayedFilter=new Set(e)}get playbackSpeed(){return this._sequencer.playbackSpeed}set playbackSpeed(e){e=ue.clamp(e,kt.MinPlaybackSpeed,kt.MaxPlaybackSpeed);const 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){he.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 tr(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){he.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 Qa,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this._synthStopping=!1,this.isReady=!1,this.state=Oi.Paused,this._loadedSoundFonts=[],this.ready=new bi,this.readyForPlayback=new bi,this.finished=new bi,this.soundFontLoaded=new bi,this.soundFontLoadFailed=new Si,this.midiLoaded=new Si,this.midiLoadFailed=new Si,this.stateChanged=new Si,this.positionChanged=new Si,this.midiEventsPlayed=new Si,this.playbackRangeChanged=new Si,he.debug("AlphaSynth","Initializing player"),this.state=Oi.Paused,he.debug("AlphaSynth","Creating output"),this._output=e,he.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new Za(this.output.sampleRate),this._sequencer=new Ri(this._synthesizer),he.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this.state===Oi.Playing&&(!this._sequencer.isFinished||this._synthesizer.activeVoiceCount>0)){let e=new Float32Array(kt.MicroBufferSize*kt.MicroBufferCount*kt.AudioChannels),t=0;for(let s=0;s<kt.MicroBufferCount;s++){this._sequencer.fillMidiEventQueue();const s=this._synthesizer.synthesize(e,t,kt.MicroBufferSize);t+=kt.MicroBufferSize*kt.AudioChannels;for(const e of s)this._midiEventsPlayedFilter.has(e.event.type)&&this._playedEventsQueue.enqueue(e);if(this._sequencer.isFinished)break}t<e.length&&(e=e.subarray(0,t)),this._notPlayedSamples+=e.length,this.output.addSamples(e)}else{const e=new Float32Array(0);this.output.addSamples(e)}})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open(t)}play(){return!(this.state!==Oi.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(he.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(he.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),he.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this._synthStopping=!1,this.state=Oi.Playing,this.stateChanged.trigger(new qi(this.state,!1))}pause(){this.state!==Oi.Paused&&this._isMidiLoaded&&(he.debug("AlphaSynth","Pausing playback"),this.state=Oi.Paused,this.stateChanged.trigger(new qi(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===Oi.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(he.debug("AlphaSynth","Stopping playback"),this.state=Oi.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 qi(this.state,!0)))}playOneTimeMidiFile(e){this._sequencer.isPlayingOneTimeMidi?this.stopOneTimeMidi():this.pause(),this._sequencer.loadOneTimeMidi(e),this._synthesizer.noteOffAll(!0),this.updateTimePosition(0,!0),this._notPlayedSamples=0,this.output.resetSamples(),this.output.play()}resetSoundFonts(){this.stop(),this._synthesizer.resetPresets(),this._loadedSoundFonts=[],this._isSoundFontLoaded=!1,this.soundFontLoaded.trigger()}loadSoundFont(e,t){this.pause();const s=Bt.fromBuffer(e);try{he.debug("AlphaSynth","Loading soundfont from bytes");const e=new Fa;e.load(s),t||(this._loadedSoundFonts=[]),this._loadedSoundFonts.push(e),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),he.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){he.error("AlphaSynth",`Could not load soundfont from bytes ${e}`),this.soundFontLoadFailed.trigger(e)}}checkReadyForPlayback(){if(this.isReadyForPlayback){this._synthesizer.setupMetronomeChannel(this.metronomeVolume);const e=this._sequencer.instrumentPrograms,t=this._sequencer.percussionKeys;let s=!1;for(const i of this._loadedSoundFonts)this._synthesizer.loadPresets(i,e,t,s),s=!0;this.readyForPlayback.trigger()}}loadMidiFile(e){this.stop();try{he.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new Ki(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),he.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){he.error("AlphaSynth",`Could not load midi from model ${e}`),this.midiLoadFailed.trigger(e)}}applyTranspositionPitches(e){this._synthesizer.applyTranspositionPitches(e)}setChannelTranspositionPitch(e,t){this._synthesizer.setChannelTranspositionPitch(e,t)}setChannelMute(e,t){this._synthesizer.channelSetMute(e,t)}resetChannelStates(){this._synthesizer.resetChannelStates()}setChannelSolo(e,t){this._synthesizer.channelSetSolo(e,t)}setChannelVolume(e,t){t=Math.max(t,kt.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;const t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*kt.AudioChannels,this.updateTimePosition(this._timePosition+t,!1),this.checkForFinish()}checkForFinish(){let e=0,t=0;this.playbackRange&&this._sequencer.isPlayingMain?(e=this.playbackRange.startTick,t=this.playbackRange.endTick):t=this._sequencer.currentEndTick,this._tickPosition>=t&&this._notPlayedSamples<=0&&(this._notPlayedSamples=0,this._sequencer.isPlayingCountIn?(he.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(he.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=Oi.Paused,this.stopOneTimeMidi()):this.isLooping?(he.debug("AlphaSynth","Finished playback (main looping)"),this.finished.trigger(),this.tickPosition=e,this._synthStopping=!1):this._synthesizer.activeVoiceCount>0?this._synthStopping||(this._synthesizer.noteOffAll(!0),this._synthStopping=!0):(this._synthStopping=!1,he.debug("AlphaSynth","Finished playback (main)"),this.finished.trigger(),this.stop()))}stopOneTimeMidi(){this.output.pause(),this._synthesizer.noteOffAll(!0),this._sequencer.resetOneTimeMidi(),this.timePosition=this._sequencer.currentTime}updateTimePosition(e,t){let s=e;this._timePosition=s;let i=this._sequencer.currentTimePositionToTickPosition(s);this._tickPosition=i;const a=this._sequencer.currentEndTime,r=this._sequencer.currentEndTick;s>a&&(s=a,i=r);const n=this._sequencer.isPlayingMain?"main":this._sequencer.isPlayingCountIn?"count-in":"one-time";if(he.debug("AlphaSynth",`Position changed: (time: ${s}/${a}, tick: ${i}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new Ki(s,a,i,r,t)),t)this._playedEventsQueue.clear();else{const e=new Qa;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<s;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new er(e.toArray()))}}hasSamplesForProgram(e){return this._synthesizer.hasSamplesForProgram(e)}hasSamplesForPercussion(e){return this._synthesizer.hasSamplesForPercussion(e)}}class ir{constructor(){this.ready=new bi,this.samplesPlayed=new Si,this.sampleRequest=new bi}get sampleRate(){return ir.preferredSampleRate}open(){he.debug("AlphaSynth","Initializing synth worker"),this._worker=ic.globalThis,this._worker.addEventListener("message",this.handleMessage.bind(this)),this.ready.trigger()}destroy(){this._worker.postMessage({cmd:"alphaSynth.output.destroy"})}handleMessage(e){const t=e.data;switch(t.cmd){case ir.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case ir.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(){}async enumerateOutputDevices(){return[]}async setOutputDevice(e){}async getOutputDevice(){return null}}ir.CmdOutputPrefix="alphaSynth.output.",ir.CmdOutputAddSamples=`${ir.CmdOutputPrefix}addSamples`,ir.CmdOutputPlay=`${ir.CmdOutputPrefix}play`,ir.CmdOutputPause=`${ir.CmdOutputPrefix}pause`,ir.CmdOutputResetSamples=`${ir.CmdOutputPrefix}resetSamples`,ir.CmdOutputStop=`${ir.CmdOutputPrefix}stop`,ir.CmdOutputSampleRequest=`${ir.CmdOutputPrefix}sampleRequest`,ir.CmdOutputSamplesPlayed=`${ir.CmdOutputPrefix}samplesPlayed`,ir.preferredSampleRate=0;class ar{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new sr(new ir,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(){const e=ic.globalThis;e.addEventListener("message",(t=>{const s=t.data;if("alphaSynth.initialize"===s.cmd)ir.preferredSampleRate=s.sampleRate,he.logLevel=s.logLevel,ic.globalThis.alphaSynthWebWorker=new ar(e,s.bufferTimeInMilliseconds)}))}handleMessage(e){const t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":he.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(Es.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(Es.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);break;case"alphaSynth.setChannelTranspositionPitch":this._player.setChannelTranspositionPitch(t.channel,t.semitones);break;case"alphaSynth.setChannelSolo":this._player.setChannelSolo(t.channel,t.solo);break;case"alphaSynth.setChannelVolume":this._player.setChannelVolume(t.channel,t.volume);break;case"alphaSynth.resetChannelStates":this._player.resetChannelStates();break;case"alphaSynth.destroy":this._player.destroy(),this._main.postMessage({cmd:"alphaSynth.destroyed"});break;case"alphaSynth.applyTranspositionPitches":this._player.applyTranspositionPitches(new Map(JSON.parse(t.transpositionPitches)))}}onPositionChanged(e){this._main.postMessage({cmd:"alphaSynth.positionChanged",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onPlayerStateChanged(e){this._main.postMessage({cmd:"alphaSynth.playerStateChanged",state:e.state,stopped:e.stopped})}onFinished(){this._main.postMessage({cmd:"alphaSynth.finished"})}onSoundFontLoaded(){this._main.postMessage({cmd:"alphaSynth.soundFontLoaded"})}onSoundFontLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.soundFontLoadFailed",error:this.serializeException(e)})}serializeException(e){const 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(Es.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}class rr{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){ic.globalThis.alphaTabWebWorker=new rr(ic.globalThis)}handleMessage(e){const t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":const e=Es.jsObjectToSettings(t.settings);he.logLevel=e.core.logLevel,this._renderer=new xi(e),this._renderer.partialRenderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialRenderFinished",result:e})})),this._renderer.partialLayoutFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialLayoutFinished",result:e})})),this._renderer.renderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.renderFinished",result:e})})),this._renderer.postRenderFinished.on((()=>{this._main.postMessage({cmd:"alphaTab.postRenderFinished",boundsLookup:this._renderer.boundsLookup?.toJson()??null})})),this._renderer.preRender.on((e=>{this._main.postMessage({cmd:"alphaTab.preRender",resize:e})})),this._renderer.error.on(this.error.bind(this));break;case"alphaTab.invalidate":this._renderer.render();break;case"alphaTab.resizeRender":this._renderer.resizeRender();break;case"alphaTab.renderResult":this._renderer.renderResult(t.resultId);break;case"alphaTab.setWidth":this._renderer.width=t.width;break;case"alphaTab.renderScore":this.updateFontSizes(t.fontSizes);const s=null==t.score?null:Es.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(s,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(!(e instanceof Map)){const t=e;e=new Map;for(const s in t)e.set(s,t[s])}if(e){Ge.FontSizeLookupTables||(Ge.FontSizeLookupTables=new Map);for(const[t,s]of e)Ge.FontSizeLookupTables.set(t,s)}}updateSettings(e){is.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){he.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class nr{constructor(){this._canvas=null,this._color=new Ae(0,0,0,255),this._font=new We("Arial",10,Fe.Plain),this._lineWidth=0;const e=document.createElement("span");e.classList.add("at"),document.body.appendChild(e);const t=window.getComputedStyle(e);let s=t.fontFamily;(s.startsWith('"')||s.startsWith("'"))&&(s=s.substr(1,s.length-2)),this._musicFont=new We(s,Number.parseFloat(t.fontSize),Fe.Plain),this._measureCanvas=document.createElement("canvas"),this._measureCanvas.width=10,this._measureCanvas.height=10,this._measureCanvas.style.width="10px",this._measureCanvas.style.height="10px",this._measureContext=this._measureCanvas.getContext("2d"),this._measureContext.textBaseline="hanging"}destroy(){}onRenderFinished(){return null}beginRender(e,t){const s=this.settings.display.scale;this._canvas=document.createElement("canvas"),this._canvas.width=e*ic.HighDpiFactor|0,this._canvas.height=t*ic.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(ic.HighDpiFactor*s,ic.HighDpiFactor*s),this._context.lineWidth=this._lineWidth}endRender(){const e=this._canvas;return this._canvas=null,e}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._context.strokeStyle=e.rgba,this._context.fillStyle=e.rgba)}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._context&&(this._context.lineWidth=e)}fillRect(e,t,s,i){s>0&&this._context.fillRect(0|e,0|t,s,i)}strokeRect(e,t,s,i){const a=this.lineWidth%2==0?0:.5;this._context.strokeRect((0|e)+a,(0|t)+a,s,i)}beginPath(){this._context.beginPath()}closePath(){this._context.closePath()}moveTo(e,t){this._context.moveTo(e,t)}lineTo(e,t){this._context.lineTo(e,t)}quadraticCurveTo(e,t,s,i){this._context.quadraticCurveTo(e,t,s,i)}bezierCurveTo(e,t,s,i,a,r){this._context.bezierCurveTo(e,t,s,i,a,r)}fillCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.fill()}strokeCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.stroke()}fill(){this._context.fill(),this._context.beginPath()}stroke(){this._context.stroke(),this._context.beginPath()}get font(){return this._font}set font(e){this._font=e,this._context&&(this._context.font=e.toCssString(1)),this._measureContext.font=e.toCssString(1)}get textAlign(){switch(this._context.textAlign){case"left":default:return A.Left;case"center":return A.Center;case"right":return A.Right}}set textAlign(e){switch(e){case A.Left:this._context.textAlign="left";break;case A.Center:this._context.textAlign="center";break;case A.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return R.Top;case"middle":return R.Middle;case"bottom":return R.Bottom}}set textBaseline(e){switch(e){case R.Top:this._context.textBaseline="hanging";break;case R.Middle:this._context.textBaseline="middle";break;case R.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,s){this._context.fillText(e,t,s)}measureText(e){const t=this._measureContext.measureText(e);return new pe(t.width,t.actualBoundingBoxDescent-t.actualBoundingBoxAscent)}fillMusicFontSymbol(e,t,s,i,a=!1){i!==I.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a=!1){let r="";for(const e of i)e!==I.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){const r=this._context.textAlign,n=this._context.textBaseline,o=this._context.font;this._context.font=this._musicFont.toCssString(s),this._context.textBaseline="middle",this._context.textAlign=a?"center":"left",this._context.fillText(i,e,t),this._context.textBaseline=n,this._context.font=o,this._context.textAlign=r}beginRotate(e,t,s){this._context.save(),this._context.translate(e,t),this._context.rotate(s*Math.PI/180)}endRotate(){this._context.restore()}}class or{constructor(e,t=!1){this._midiFile=e,this._smf1Mode=t}addTimeSignature(e,t,s){let i=0,a=s;for(;a>>=1,a>0;)i++;this._midiFile.addEvent(new Et(0,e,t,i,48,8))}addRest(e,t,s){this._smf1Mode||this._midiFile.addEvent(new Mt(e,t,s))}addNote(e,t,s,i,a,r){this._midiFile.addEvent(new It(e,t,r,or.fixValue(i),or.fixValue(a))),this._midiFile.addEvent(new At(e,t+s,r,or.fixValue(i),or.fixValue(a)))}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,s,i,a){this._midiFile.addEvent(new Rt(e,t,s,i,or.fixValue(a)))}addProgramChange(e,t,s,i){this._midiFile.addEvent(new Ot(e,t,s,i))}addTempo(e,t){const s=6e7/t|0;this._midiFile.addEvent(new Ht(e,s))}addBend(e,t,s,i){i=i>=kt.MaxPitchWheel?kt.MaxPitchWheel:Math.floor(i),this._midiFile.addEvent(new Wt(e,t,s,i))}addNoteBend(e,t,s,i,a){this._smf1Mode?this.addBend(e,t,s,a):(a=a*kt.MaxPitchWheel20/kt.MaxPitchWheel,this._midiFile.addEvent(new Vt(e,t,s,i,a)))}finishTrack(e,t){this._midiFile.format!==st.MultiTrack&&0!==e||this._midiFile.addEvent(new Gt(e,t))}}class hr{constructor(e,t){this.closingIndex=0,this.group=e,this.opening=t,e.closings=e.closings.sort(((e,t)=>e.index-t.index)),this.iterations=e.closings.map((e=>0))}}!function(e){e[e.PlayingNormally=0]="PlayingNormally",e[e.DirectionJumped=1]="DirectionJumped",e[e.DirectionJumpedAlCoda=2]="DirectionJumpedAlCoda",e[e.DirectionJumpedAlDoubleCoda=3]="DirectionJumpedAlDoubleCoda",e[e.DirectionJumpedAlFine=4]="DirectionJumpedAlFine"}(Ji||(Ji={}));class lr{get finished(){return this.index>=this._score.masterBars.length}constructor(e){this._repeatStack=[],this._groupsOnStack=new Set,this._previousAlternateEndings=0,this._state=Ji.PlayingNormally,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}processCurrent(){const e=this._score.masterBars[this.index];if(this._state===Ji.PlayingNormally){let t=e.alternateEndings;if(0===t&&(t=this._previousAlternateEndings),e===e.repeatGroup.opening&&e.repeatGroup.isClosed&&!this._groupsOnStack.has(e.repeatGroup)){const s=new hr(e.repeatGroup,e);this._repeatStack.push(s),this._groupsOnStack.add(e.repeatGroup),this._previousAlternateEndings=0,t=e.alternateEndings}if(0===this._repeatStack.length||0===t)this.shouldPlay=!0;else{const e=this._repeatStack[this._repeatStack.length-1],s=e.iterations[e.closingIndex];this._previousAlternateEndings=t,this.shouldPlay=!!(t&1<<s)}}else this.shouldPlay=!0;this.shouldPlay&&(this.currentTick+=e.calculateDuration())}moveNext(){this.moveNextWithDirections()||this.moveNextWithNormalRepeats()}resetRepeats(){this._groupsOnStack.clear(),this._previousAlternateEndings=0,this._repeatStack=[]}handleDaCapo(e,t,s){return!!e.has(t)&&(this.index=0,this._state=s,this.resetRepeats(),!0)}handleDalSegno(e,t,s,i){if(e.has(t)){const e=this.findJumpTarget(i,this.index,!0);return-1!==e&&(this.index=e,this._state=s,this.resetRepeats(),!0)}return!1}handleDaCoda(e,t,s){if(e.has(t)){const e=this.findJumpTarget(s,this.index,!1);return-1===e?(this.index++,!0):(this.index=e,this._state=Ji.PlayingNormally,!0)}return!1}moveNextWithDirections(){const e=this._score.masterBars[this.index],t=null!==e.directions&&e.directions.size>0;if(this._state===Ji.PlayingNormally&&!t)return!1;if(!t)return this.index++,!0;switch(this._state){case Ji.PlayingNormally:return!!(this.handleDaCapo(e.directions,qe.JumpDaCapo,Ji.DirectionJumped)||this.handleDaCapo(e.directions,qe.JumpDaCapoAlCoda,Ji.DirectionJumpedAlCoda)||this.handleDaCapo(e.directions,qe.JumpDaCapoAlDoubleCoda,Ji.DirectionJumpedAlDoubleCoda)||this.handleDaCapo(e.directions,qe.JumpDaCapoAlFine,Ji.DirectionJumpedAlFine))||(!!(this.handleDalSegno(e.directions,qe.JumpDalSegno,Ji.DirectionJumped,qe.TargetSegno)||this.handleDalSegno(e.directions,qe.JumpDalSegnoAlCoda,Ji.DirectionJumpedAlCoda,qe.TargetSegno)||this.handleDalSegno(e.directions,qe.JumpDalSegnoAlDoubleCoda,Ji.DirectionJumpedAlDoubleCoda,qe.TargetSegno)||this.handleDalSegno(e.directions,qe.JumpDalSegnoAlFine,Ji.DirectionJumpedAlFine,qe.TargetSegno))||!!(this.handleDalSegno(e.directions,qe.JumpDalSegnoSegno,Ji.DirectionJumped,qe.TargetSegnoSegno)||this.handleDalSegno(e.directions,qe.JumpDalSegnoSegnoAlCoda,Ji.DirectionJumpedAlCoda,qe.TargetSegnoSegno)||this.handleDalSegno(e.directions,qe.JumpDalSegnoSegnoAlDoubleCoda,Ji.DirectionJumpedAlDoubleCoda,qe.TargetSegnoSegno)||this.handleDalSegno(e.directions,qe.JumpDalSegnoSegnoAlFine,Ji.DirectionJumpedAlFine,qe.TargetSegnoSegno)));case Ji.DirectionJumped:return this.index++,!0;case Ji.DirectionJumpedAlCoda:return this.handleDaCoda(e.directions,qe.JumpDaCoda,qe.TargetCoda)||this.index++,!0;case Ji.DirectionJumpedAlDoubleCoda:return this.handleDaCoda(e.directions,qe.JumpDaDoubleCoda,qe.TargetDoubleCoda)||this.index++,!0;case Ji.DirectionJumpedAlFine:return e.directions.has(qe.TargetFine)?(this.index=this._score.masterBars.length,!0):(this.index++,!0)}return!0}findJumpTarget(e,t,s){let i;return s?(i=this.findJumpTargetBackwards(e,t),-1===i&&(i=this.findJumpTargetForwards(e,t)),i):(i=this.findJumpTargetForwards(e,t),-1===i&&(i=this.findJumpTargetBackwards(e,t)),i)}findJumpTargetForwards(e,t){let s=t;for(;s<this._score.masterBars.length;){const t=this._score.masterBars[s].directions;if(t&&t.has(e))return s;s++}return-1}findJumpTargetBackwards(e,t){let s=t;for(;s>=0;){const t=this._score.masterBars[s].directions;if(t&&t.has(e))return s;s--}return-1}moveNextWithNormalRepeats(){const e=this._score.masterBars[this.index].repeatCount-1;if(this._repeatStack.length>0&&e>0){const t=this._repeatStack[this._repeatStack.length-1];if(t.iterations[t.closingIndex]<e){this.index=t.opening.index,t.iterations[t.closingIndex]++;for(let e=0;e<t.closingIndex;e++)t.iterations[e]=0;t.closingIndex=0,this._previousAlternateEndings=0}else t.closingIndex<t.group.closings.length-1?(t.closingIndex++,this.index++):(this._repeatStack.pop(),this._groupsOnStack.delete(t.group),this.index++)}else this.index++}}class cr{constructor(e,t){this.beat=e,this.playbackStart=t}}class dr{get duration(){return this.end-this.start}constructor(e,t){this._highlightedBeats=new Map,this.highlightedBeats=[],this.nextBeat=null,this.previousBeat=null,this.start=e,this.end=t}highlightBeat(e,t){e.isEmpty&&!e.voice.isEmpty||this._highlightedBeats.has(e.id)||(this._highlightedBeats.set(e.id,!0),this.highlightedBeats.push(new cr(e,t)))}getVisibleBeatAtStart(e){for(const t of this.highlightedBeats)if(t.playbackStart===this.start&&e.has(t.beat.voice.bar.staff.track.index))return t.beat;return null}}class ur{constructor(e,t){this.tick=e,this.tempo=t}}class pr{constructor(){this.start=0,this.end=0,this.tempoChanges=[],this.firstBeat=null,this.lastBeat=null,this.nextMasterBar=null,this.previousMasterBar=null}get tempo(){return this.tempoChanges[0].tempo}insertAfter(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.nextBeat=e.nextBeat,t.previousBeat=e,e.nextBeat&&(e.nextBeat.previousBeat=t),e.nextBeat=t,e===this.lastBeat&&(this.lastBeat=t))}insertBefore(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.previousBeat=e.previousBeat,t.nextBeat=e,e.previousBeat&&(e.previousBeat.nextBeat=t),e.previousBeat=t,e===this.firstBeat&&(this.firstBeat=t))}addBeat(e,t,s,i){const a=s+i;if(null==this.firstBeat){const i=new dr(s,a);i.highlightBeat(e,t),this.insertAfter(this.firstBeat,i)}else if(s>=this.lastBeat.end){const s=new dr(this.lastBeat.end,a);s.highlightBeat(e,t),this.insertAfter(this.lastBeat,s)}else{let i=null;if(s<this.firstBeat.start)i=this.firstBeat;else{let e=this.firstBeat;for(;null!=e;){if(s>=e.start&&s<e.end){i=e;break}e=e.nextBeat}if(null===i)throw new Le(Ee.General,"Error on building lookup, unknown variant")}if(s<i.start)if(a===i.start){const a=new dr(s,i.start);a.highlightBeat(e,t),this.insertBefore(this.firstBeat,a)}else if(a<i.end){const r=new dr(s,i.start);r.highlightBeat(e,t),this.insertBefore(i,r);const n=new dr(i.start,a);for(const e of i.highlightedBeats)n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(e,t),this.insertBefore(i,n),i.start=a}else if(a===i.end){const a=new dr(s,i.start);a.highlightBeat(e,t),i.highlightBeat(e,t),this.insertBefore(i,a)}else{const r=new dr(s,i.start);r.highlightBeat(e,t),i.highlightBeat(e,t),this.insertBefore(i,r),this.addBeat(e,t,i.end,a-i.end)}else if(s>i.start)if(a===i.end){const a=new dr(i.start,s);for(const e of i.highlightedBeats)a.highlightBeat(e.beat,e.playbackStart);i.start=s,i.highlightBeat(e,t),this.insertBefore(i,a)}else if(a<i.end){const r=new dr(i.start,s);this.insertBefore(i,r);const n=new dr(s,a);this.insertBefore(i,n);for(const e of i.highlightedBeats)r.highlightBeat(e.beat,e.playbackStart),n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(e,t),i.start=a}else{const r=new dr(i.start,s);for(const e of i.highlightedBeats)r.highlightBeat(e.beat,e.playbackStart);i.start=s,i.highlightBeat(e,t),this.insertBefore(i,r),this.addBeat(e,t,i.end,a-i.end)}else if(a===i.end)i.highlightBeat(e,t);else if(a<i.end){const s=new dr(i.start,a);for(const e of i.highlightedBeats)s.highlightBeat(e.beat,e.playbackStart);s.highlightBeat(e,t),i.start=a,this.insertBefore(i,s)}else i.highlightBeat(e,t),this.addBeat(e,t,i.end,a-i.end)}}}!function(e){e[e.Unknown=0]="Unknown",e[e.ToNextBext=1]="ToNextBext",e[e.ToEndOfBar=2]="ToEndOfBar"}(Yi||(Yi={}));class gr{get start(){return this.masterBar.start+this.beatLookup.start}get end(){return this.start+this.tickDuration}constructor(e){this.nextBeat=null,this.tickDuration=0,this.duration=0,this.cursorMode=Yi.Unknown,this.masterBar=e}calculateDuration(){if(1===this.masterBar.tempoChanges.length)this.duration=se.ticksToMillis(this.tickDuration,this.masterBar.tempoChanges[0].tempo);else{let e=0,t=this.start,s=this.masterBar.tempoChanges[0].tempo;const i=this.end;for(const a of this.masterBar.tempoChanges)if(a.tick<t)s=a.tempo;else{if(a.tick>i)break;e+=se.ticksToMillis(a.tick-t,s),s=a.tempo,t=a.tick}i>t&&(e+=se.ticksToMillis(i-t,s)),this.duration=e}}}class mr{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[],this.multiBarRestInfo=null}findBeat(e,t,s=null){let i=null;return s&&(i=this.findBeatFast(e,s,t)),i||(i=this.findBeatSlow(e,s,t,!1)),i}findBeatFast(e,t,s){if(s>=t.start&&s<t.end)return t;if(t.nextBeat&&s>=t.nextBeat.start&&s<t.nextBeat.end){const s=t.nextBeat;return this.fillNextBeat(s,e),s}return null}fillNextBeatMultiBarRest(e,t){const s=this.multiBarRestInfo.get(e.masterBar.masterBar.index);let i=e.masterBar;for(let e=0;e<s.length&&i;e++)i=i.nextMasterBar;i?i.nextMasterBar?(e.nextBeat=this.firstBeatInMasterBar(t,i.nextMasterBar,i.nextMasterBar.start,!0),e.nextBeat?(e.tickDuration=e.nextBeat.start-e.start,e.cursorMode=Yi.ToNextBext,e.nextBeat.masterBar.masterBar.index!==i.masterBar.index+1&&(e.nextBeat.masterBar.masterBar.index!==i.masterBar.index||e.nextBeat.beat.playbackStart<=e.beat.playbackStart)&&(e.cursorMode=Yi.ToEndOfBar)):(e.tickDuration=i.nextMasterBar.end-e.start,e.cursorMode=Yi.ToEndOfBar)):(e.tickDuration=i.end-e.start,e.cursorMode=Yi.ToEndOfBar):(he.warning("Synth","MultiBar Rest Info and the nextMasterBar are out of sync, this is an unexpected error. Please report it as bug. (broken chain fill-next)"),e.tickDuration=(e.masterBar.end-e.masterBar.start)*(s.length+1),e.cursorMode=Yi.ToEndOfBar),e.calculateDuration()}fillNextBeat(e,t){this.isMultiBarRestResult(e)?this.fillNextBeatMultiBarRest(e,t):this.fillNextBeatDefault(e,t)}fillNextBeatDefault(e,t){e.nextBeat=this.findBeatInMasterBar(e.masterBar,e.beatLookup.nextBeat,e.end,t,!0),null==e.nextBeat&&(e.nextBeat=this.findBeatSlow(t,e,e.end,!0)),e.nextBeat?(e.tickDuration=e.nextBeat.start-e.start,e.cursorMode=Yi.ToNextBext,e.calculateDuration()):(e.tickDuration=e.masterBar.end-e.start,e.cursorMode=Yi.ToEndOfBar,e.calculateDuration()),e.nextBeat&&e.nextBeat.masterBar.masterBar.index!==e.masterBar.masterBar.index+1&&(e.nextBeat.masterBar.masterBar.index!==e.masterBar.masterBar.index||e.nextBeat.beat.playbackStart<=e.beat.playbackStart)&&(e.cursorMode=Yi.ToEndOfBar)}isMultiBarRestResult(e){return this.internalIsMultiBarRestResult(e.masterBar.masterBar.index,e.beat)}internalIsMultiBarRestResult(e,t){return this.multiBarRestInfo&&this.multiBarRestInfo.has(e)&&t.isRest&&t.voice.bar.isRestOnly}findBeatSlow(e,t,s,i){let a=null;return null!=t&&(t.masterBar.start<=s&&t.masterBar.end>s?a=t.masterBar:t.masterBar.nextMasterBar&&t.masterBar.nextMasterBar.start<=s&&t.masterBar.nextMasterBar.end>s&&(a=t.masterBar.nextMasterBar)),a||(a=this.findMasterBar(s)),a?this.firstBeatInMasterBar(e,a,s,i):null}firstBeatInMasterBar(e,t,s,i){let a=t;for(;a;){if(a.firstBeat){const t=this.findBeatInMasterBar(a,a.firstBeat,s,e,i);if(t)return t}a=a.nextMasterBar}return null}findBeatInMasterBar(e,t,s,i,a){if(!t)return null;let r=null,n=null;const o=s-e.start;for(;null!=t&&null==n;){if((t.start<=o||a&&o<0)&&o<t.end){if(r=t,n=t.getVisibleBeatAtStart(i),!n)if(a){let s=e;for(;null!=s&&null==n;){for(;null!=t;){if(n=t.getVisibleBeatAtStart(i),n){r=t,e=s;break}t=t.nextBeat}n&&r||(s=s.nextMasterBar,t=s?.firstBeat??null)}}else{let s=e;for(;null!=s&&null==n;){for(;null!=t;){if(n=t.getVisibleBeatAtStart(i),n){r=t,e=s;break}t=t.previousBeat}n&&r||(s=s.previousMasterBar,t=s?.firstBeat??null)}}}else if(t.end>o)break;t=t?.nextBeat??null}if(null==n)return null;return this.createResult(e,r,n,a,i)}createResult(e,t,s,i,a){const r=new gr(e);if(r.beat=s,r.beatLookup=t,r.tickDuration=t.end-t.start,i){if(this.isMultiBarRestResult(r)){const s=this.multiBarRestInfo.get(e.masterBar.index);let i=e;for(let e=0;e<s.length&&i;e++)i=i.nextMasterBar;i?i.nextMasterBar?r.tickDuration=i.nextMasterBar.start-t.start:r.tickDuration=i.end-t.start:he.warning("Synth","MultiBar Rest Info and the nextMasterBar are out of sync, this is an unexpected error. Please report it as bug. (broken chain stretch-result)")}}else this.fillNextBeat(r,a);return r.calculateDuration(),r}findMasterBar(e){const t=this.masterBars;let s=0,i=t.length-1;for(;s<=i;){const a=(i+s)/2|0,r=t[a];if(e>=r.start&&e<r.end)return r;e<r.start?i=a-1:s=a+1}return null}getMasterBar(e){if(!this.masterBarLookup.has(e.index)){const t=new pr;return t.masterBar=e,t}return this.masterBarLookup.get(e.index)}getMasterBarStart(e){return this.masterBarLookup.has(e.index)?this.masterBarLookup.get(e.index).start:0}getBeatStart(e){return this.masterBarLookup.has(e.voice.bar.index)?this.masterBarLookup.get(e.voice.bar.index).start+e.playbackStart:0}addMasterBar(e){this.masterBars.push(e),this._currentMasterBar&&(e.previousMasterBar=this._currentMasterBar,this._currentMasterBar.nextMasterBar=e),this._currentMasterBar=e,this.masterBarLookup.has(e.masterBar.index)||this.masterBarLookup.set(e.masterBar.index,e)}addBeat(e,t,s){const i=this._currentMasterBar;if(i)if(t<0&&i.previousMasterBar){const a=i.previousMasterBar.end-i.previousMasterBar.start,r=a+t,n=r+s;if(i.previousMasterBar.addBeat(e,r,r,s),n>a){const a=s+t;i.addBeat(e,t,0,a)}}else i.addBeat(e,t,t,s)}}class fr{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class yr{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class br{constructor(){this.durations=[],this.brushInfos=[]}}class Sr{constructor(e,t,s){this._programsPerChannel=new Map,this._currentTime=0,this._calculatedBeatTimers=new Set,this.tickLookup=new mr,this.applyTranspositionPitches=!0,this.transpositionPitches=new Map,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new as,this._handler=s}generate(){this.transpositionPitches.clear(),this._calculatedBeatTimers.clear(),this._currentTime=0;for(const e of this._score.tracks)this.generateTrack(e);he.debug("Midi","Begin midi generation");const e=new lr(this._score);let t=null,s=this._score.tempo;for(;!e.finished;){const i=e.index,a=this._score.masterBars[i],r=e.currentTick;if(e.processCurrent(),e.shouldPlay){this.generateMasterBar(a,t,r,s),a.tempoAutomations.length>0&&(s=a.tempoAutomations[0].value);for(const e of this._score.tracks)for(const t of e.staves)i<t.bars.length&&this.generateBar(t.bars[i],r,s);a.tempoAutomations.length>0&&(s=a.tempoAutomations[a.tempoAutomations.length-1].value)}e.moveNext(),t=a}for(const t of this._score.tracks)this._handler.finishTrack(t.index,e.currentTick);he.debug("Midi","Midi generation done")}generateTrack(e){this.generateChannel(e,e.playbackInfo.primaryChannel,e.playbackInfo),e.playbackInfo.primaryChannel!==e.playbackInfo.secondaryChannel&&this.generateChannel(e,e.playbackInfo.secondaryChannel,e.playbackInfo)}addProgramChange(e,t,s,i){this._programsPerChannel.has(s)&&this._programsPerChannel.get(s)===i||(this._handler.addProgramChange(e.index,t,s,i),this._programsPerChannel.set(s,i))}static buildTranspositionPitches(e,t){const s=new Map;for(const i of e.tracks){const e=i.index<t.notation.transpositionPitches.length?t.notation.transpositionPitches[i.index]:-i.staves[0].transpositionPitch;s.set(i.playbackInfo.primaryChannel,e),s.set(i.playbackInfo.secondaryChannel,e)}return s}generateChannel(e,t,s){const i=e.index<this._settings.notation.transpositionPitches.length?this._settings.notation.transpositionPitches[e.index]:-e.staves[0].transpositionPitch;this.transpositionPitches.set(t,i);const a=Sr.toChannelShort(s.volume),r=Sr.toChannelShort(s.balance);this._handler.addControlChange(e.index,0,t,Xi.VolumeCoarse,a),this._handler.addControlChange(e.index,0,t,Xi.PanCoarse,r),this._handler.addControlChange(e.index,0,t,Xi.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,Xi.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,Xi.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,Xi.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,Xi.DataEntryCoarse,Sr.PitchBendRangeInSemitones),this.addProgramChange(e,0,t,s.program)}static toChannelShort(e){const t=Math.max(-32768,Math.min(32767,8*e-1));return Math.max(t,-1)+1}generateMasterBar(e,t,s,i){t&&t.timeSignatureDenominator===e.timeSignatureDenominator&&t.timeSignatureNumerator===e.timeSignatureNumerator||this._handler.addTimeSignature(s,e.timeSignatureNumerator,e.timeSignatureDenominator);const a=e.calculateDuration(),r=new pr;if(e.tempoAutomations.length>0){e.tempoAutomations[0].ratioPosition>0&&r.tempoChanges.push(new ur(s,i));for(const t of e.tempoAutomations){const e=s+a*t.ratioPosition;this._handler.addTempo(e,t.value),r.tempoChanges.push(new ur(e,t.value))}}else t?r.tempoChanges.push(new ur(s,i)):(this._handler.addTempo(s,e.score.tempo),r.tempoChanges.push(new ur(s,e.score.tempo)));r.masterBar=e,r.start=s,r.end=r.start+a,this.tickLookup.addMasterBar(r)}generateBar(e,t,s){const i=this.getPlaybackBar(e),a=this._currentTime;for(const r of i.voices)this._currentTime=a,this.generateVoice(r,t,e,s);const r=i.masterBar,n=r.calculateDuration(),o=r.tempoAutomations.slice();if(0===o.length)this._currentTime=a+se.ticksToMillis(n,s);else{this._currentTime=a;let e=t,i=s;const r=t+n;for(const t of o){const s=n*t.ratioPosition-e;s>0&&(this._currentTime+=se.ticksToMillis(s,i)),i=t.value,e+=s}const h=r-e;h>0&&(this._currentTime+=se.ticksToMillis(h,i))}i.id!==e.id&&this.tickLookup.addBeat(e.voices[0].beats[0],0,n)}getPlaybackBar(e){switch(e.simileMark){case h.Simple:e.previousBar&&(e=this.getPlaybackBar(e.previousBar));break;case h.FirstOfDouble:case h.SecondOfDouble:e.previousBar&&e.previousBar.previousBar&&(e=this.getPlaybackBar(e.previousBar.previousBar))}return e}generateVoice(e,t,s,i){if(e.isEmpty&&(!e.bar.isEmpty||0!==e.index))return;const a=s.masterBar.tempoAutomations.slice();let r=i;const n=s.masterBar.calculateDuration();for(const i of e.beats){const e=i.playbackStart/n;for(;a.length>0&&a[0].ratioPosition<=e;)r=a.shift().value;this.generateBeat(i,t,s,r)}}generateBeat(e,t,s,i){let a=e.playbackStart,r=e.playbackDuration;const n=e.voice.bar.masterBar.calculateDuration();e.voice.bar.isEmpty?r=n:e.voice.bar.masterBar.tripletFeel!==M.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(a-=this._currentTripletFeel.secondBeatStartOffset,r=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=Sr.calculateTripletFeelInfo(a,r,e),this._currentTripletFeel&&(r=this._currentTripletFeel.firstBeatDuration))),e.showTimer&&!this._calculatedBeatTimers.has(e.id)&&(e.timer=this._currentTime,this._calculatedBeatTimers.add(e.id)),this._currentTime+=se.ticksToMillis(r,i),s===e.voice.bar&&this.tickLookup.addBeat(e,a,r);const o=e.voice.bar.staff.track;for(const s of e.automations)this.generateNonTempoAutomation(e,s,t);if(e.isRest)this._handler.addRest(o.index,t+a,o.playbackInfo.primaryChannel);else if(e.deadSlapped)this.generateDeadSlap(e,t+a);else{const s=this.getBrushInfo(e),n=this.getRasgueadoInfo(e,r);for(const o of e.notes)this.generateNote(o,t+a,r,i,s,n)}if(e.fade!==G.None&&this.generateFade(e,t+a,r),e.vibrato!==N.None){let s=240,i=3;switch(e.vibrato){case N.Slight:s=this._settings.player.vibrato.beatSlightLength,i=this._settings.player.vibrato.beatSlightAmplitude;break;case N.Wide:s=this._settings.player.vibrato.beatWideLength,i=this._settings.player.vibrato.beatWideAmplitude}this.generateVibratorWithParams(t+a,e.playbackDuration,s,0,i,((t,s)=>{this._handler.addBend(e.voice.bar.staff.track.index,t,o.playbackInfo.secondaryChannel,s)}))}}static calculateTripletFeelInfo(e,t,s){let i;switch(s.voice.bar.masterBar.tripletFeel){case M.Triplet8th:case M.Dotted8th:case M.Scottish8th:i=f.Eighth;break;case M.Triplet16th:case M.Dotted16th:case M.Scottish16th:i=f.Sixteenth;break;default:return null}const a=se.toTicks(i);if(t!==a)return null;if(e%a!=0)return null;if(!s.nextBeat||s.nextBeat.voice!==s.voice||s.playbackDuration!==a)return null;const r=new yr;switch(s.voice.bar.masterBar.tripletFeel){case M.Triplet8th:r.firstBeatDuration=se.applyTuplet(se.toTicks(f.Quarter),3,2),r.secondBeatDuration=se.applyTuplet(se.toTicks(f.Eighth),3,2);break;case M.Dotted8th:r.firstBeatDuration=se.applyDot(se.toTicks(f.Eighth),!1),r.secondBeatDuration=se.toTicks(f.Sixteenth);break;case M.Scottish8th:r.firstBeatDuration=se.toTicks(f.Sixteenth),r.secondBeatDuration=se.applyDot(se.toTicks(f.Eighth),!1);break;case M.Triplet16th:r.firstBeatDuration=se.applyTuplet(se.toTicks(f.Eighth),3,2),r.secondBeatDuration=se.applyTuplet(se.toTicks(f.Sixteenth),3,2);break;case M.Dotted16th:r.firstBeatDuration=se.applyDot(se.toTicks(f.Sixteenth),!1),r.secondBeatDuration=se.toTicks(f.ThirtySecond);break;case M.Scottish16th:r.firstBeatDuration=se.toTicks(f.ThirtySecond),r.secondBeatDuration=se.applyDot(se.toTicks(f.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateDeadSlap(e,t){const s=se.toTicks(f.SixtyFourth),i=e.voice.bar.staff;if(i.tuning.length>0)for(const e of i.tuning)this._handler.addNote(i.track.index,t,s,e,se.dynamicToVelocity(y.F),i.track.playbackInfo.primaryChannel)}needsSecondaryChannel(e){return e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==N.None}determineChannel(e,t){if(this.needsSecondaryChannel(t))return e.playbackInfo.secondaryChannel;let s=t;for(;s.isTieDestination;)if(s=s.tieOrigin,this.needsSecondaryChannel(s))return e.playbackInfo.secondaryChannel;for(s=t;s.isTieOrigin;)if(s=s.tieDestination,this.needsSecondaryChannel(s))return e.playbackInfo.secondaryChannel;return e.playbackInfo.primaryChannel}generateNote(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.beat.voice.bar.staff;let h=e.calculateRealValue(this.applyTranspositionPitches,!0);if(e.isPercussion){const t=me.getArticulation(e);t&&(h=t.outputMidiNumber)}const l=null==r&&e.isStringed&&e.string<=a.length?a[e.string-1]:0,c=t+l,d=this.getNoteDuration(e,s,i);d.untilTieOrSlideEnd-=l,d.noteOnly-=l,d.letRingEnd-=l;const u=Sr.getNoteVelocity(e),p=this.determineChannel(n,e);let g=0;const m=Math.max(d.untilTieOrSlideEnd,d.letRingEnd);g=e.hasBend?Sr.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?Sr.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===T.Legato?-1:Sr.getPitchWheel(0),g>=0&&this._handler.addNoteBend(n.index,c,p,h,g),e.beat.hasRasgueado?this.generateRasgueado(n,e,c,h,u,p,r):e.ornament===O.None?!e.isTrill||o.isPercussion?e.beat.isTremolo?this.generateTremoloPicking(e,c,d,h,u,p):(e.hasBend?this.generateBend(e,c,d,h,p,i):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,c,d,p,i):e.slideInType!==k.None||e.slideOutType!==T.None?this.generateSlide(e,c,d,h,p,i):(e.vibrato!==N.None||e.isTieDestination&&e.tieOrigin.vibrato!==N.None)&&this.generateVibrato(e,c,d,h,p),e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===T.Legato||this._handler.addNote(n.index,c,m,h,u,p)):this.generateTrill(e,c,d,h,u,p):this.generateOrnament(n,e,c,m,h,u,p)}generateOrnament(e,t,s,i,a,r,n){let o,h;const l=a%12,c=1/3;switch(t.ornament){case O.Turn:o=[a+Sr.OrnamentKeysUp[l],a,a+Sr.OrnamentKeysDown[l]],h=[se.toTicks(f.Sixteenth)*c,se.toTicks(f.Sixteenth)*c,se.toTicks(f.Sixteenth)*c];break;case O.InvertedTurn:o=[a+Sr.OrnamentKeysDown[l],a,a+Sr.OrnamentKeysUp[l]],h=[se.toTicks(f.Sixteenth)*c,se.toTicks(f.Sixteenth)*c,se.toTicks(f.Sixteenth)*c];break;case O.UpperMordent:o=[a,a+Sr.OrnamentKeysUp[l]],h=[se.toTicks(f.ThirtySecond),se.toTicks(f.ThirtySecond)];break;case O.LowerMordent:o=[a,a+Sr.OrnamentKeysDown[l]],h=[se.toTicks(f.ThirtySecond),se.toTicks(f.ThirtySecond)];break;default:return}let d=1;i<se.QuarterTime&&(d=i/se.QuarterTime),r-=se.VelocityIncrement;let u=0;for(let t=0;t<o.length;t++){const i=h[t]*d;this._handler.addNote(e.index,s,i,o[t],r,n),s+=i,u+=i}const p=i-u;this._handler.addNote(e.index,s,p,a,r,n)}getNoteDuration(e,t,s){const i=new fr;if(i.noteOnly=t,i.untilTieOrSlideEnd=t,i.letRingEnd=t,e.isDead)return i.noteOnly=this.applyStaticDuration(Sr.DefaultDurationDead,t,s),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isPalmMute)return i.noteOnly=this.applyStaticDuration(Sr.DefaultDurationPalmMute,t,s),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isStaccato)return i.noteOnly=t/2|0,i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isTieOrigin){const a=e.tieDestination;if(a)if(e.isTieDestination){const e=this.getNoteDuration(a,a.beat.playbackDuration,s);i.untilTieOrSlideEnd=t+e.untilTieOrSlideEnd}else{const t=e.beat.absolutePlaybackStart,r=this.getNoteDuration(a,a.beat.playbackDuration,s),n=a.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;i.untilTieOrSlideEnd=n-t}}else if(e.slideOutType===T.Legato){const t=e.slideTarget;if(t){const a=e.beat.absolutePlaybackStart,r=this.getNoteDuration(t,t.beat.playbackDuration,s),n=t.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;i.untilTieOrSlideEnd=n-a}}if(e.isLetRing&&this._settings.notation.notationMode===P.GuitarPro){let s=e.beat,a=0;const r=e.beat.voice.bar.masterBar.calculateDuration();for(;s.nextBeat;){const t=s.nextBeat;if(t.isRest)break;if(e.isStringed&&t.hasNoteOnString(e.string))break;if(s=s.nextBeat,a=s.absolutePlaybackStart-e.beat.absolutePlaybackStart+s.playbackDuration,a>r){a=r;break}}s===e.beat?i.letRingEnd=t:i.letRingEnd=a}else i.letRingEnd=i.untilTieOrSlideEnd;return i}applyStaticDuration(e,t,s){const i=s*e/ae.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 se.dynamicToVelocity(t)}generateFade(e,t,s){const i=e.voice.bar.staff.track;switch(e.fade){case G.FadeIn:this.generateFadeSteps(i,t,s,0,Sr.toChannelShort(i.playbackInfo.volume));break;case G.FadeOut:this.generateFadeSteps(i,t,s,Sr.toChannelShort(i.playbackInfo.volume),0);break;case G.VolumeSwell:const e=s/2|0;this.generateFadeSteps(i,t,e,0,Sr.toChannelShort(i.playbackInfo.volume)),this.generateFadeSteps(i,t+e,e,Sr.toChannelShort(i.playbackInfo.volume),0)}}generateFadeSteps(e,t,s,i,a){const r=(a-i)/(s=.8*s|0),n=s/120+1|0,o=t+s;for(let s=0;s<n;s++){const h=s===n-1,l=h?o:t+120*s,c=h?a:Math.round(i+(l-t)*r);this._handler.addControlChange(e.index,l,e.playbackInfo.primaryChannel,Xi.VolumeCoarse,c),this._handler.addControlChange(e.index,l,e.playbackInfo.secondaryChannel,Xi.VolumeCoarse,c)}}generateVibrato(e,t,s,i,a){let r=0,n=0;switch(e.vibrato!==N.None?e.vibrato:e.isTieDestination?e.tieOrigin.vibrato:N.Slight){case N.Slight:r=this._settings.player.vibrato.noteSlightLength,n=this._settings.player.vibrato.noteSlightAmplitude;break;case N.Wide:r=this._settings.player.vibrato.noteWideLength,n=this._settings.player.vibrato.noteWideAmplitude;break;default:return}const o=e.beat.voice.bar.staff.track;let h=0;if(e.isTieDestination&&e.tieOrigin.hasBend){const t=e.tieOrigin.bendPoints;h=t[t.length-1].value}this.generateVibratorWithParams(t,s.noteOnly,r,h,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)}))}generateVibratorWithParams(e,t,s,i,a,r){const n=this.vibratoResolution,o=s/2|0,h=e+t;for(;e<h;){let t=0;const l=e+s<h?s:h-e;for(;t<l;){const s=i+a*Math.sin(t*Math.PI/o);r(e+t|0,Sr.getPitchWheel(s)),t+=n}e+=s}r(0|h,Sr.getPitchWheel(i))}static getPitchWheel(e){return kt.DefaultPitchWheel+e/2*Sr.PitchValuePerSemitone}generateSlide(e,t,s,i,a,r){const n=e.slideOutType===T.Legato?s.noteOnly:s.untilTieOrSlideEnd,o=[],h=e.beat.voice.bar.staff.track,l=this._settings.player.slide.simpleSlidePitchOffset,c=Math.floor(ae.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),d=Math.floor(ae.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case k.IntoFromAbove:o.push(new ae(0,l)),o.push(new ae(c,0));break;case k.IntoFromBelow:o.push(new ae(0,-l)),o.push(new ae(c,0))}switch(e.slideOutType){case T.Legato:case T.Shift:o.push(new ae(d,0));const t=2*(e.slideTarget.calculateRealValue(this.applyTranspositionPitches,!0)-e.calculateRealValue(this.applyTranspositionPitches,!0));o.push(new ae(ae.MaxPosition,t));break;case T.OutDown:o.push(new ae(ae.MaxPosition-c,0)),o.push(new ae(ae.MaxPosition,-l));break;case T.OutUp:o.push(new ae(ae.MaxPosition-c,0)),o.push(new ae(ae.MaxPosition,l))}this.generateWhammyOrBend(t,n,o,r,((e,t)=>{this._handler.addNoteBend(h.index,e,a,i,t)}))}generateBend(e,t,s,i,a,r){const n=e.bendPoints,o=e.beat.voice.bar.staff.track,h=(e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)};let l,c=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend&&t.tieDestination.vibrato===N.None;)t=t.tieDestination;l=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration,r).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==b.None){switch(e.tieDestination.bendType){case p.Bend:case p.BendRelease:case p.PrebendBend:c=e.tieDestination.bendPoints[1].value;break;case p.Prebend:case p.PrebendRelease:c=e.tieDestination.bendPoints[0].value}l=Math.max(s.noteOnly,se.millisToTicks(this._settings.player.songBookBendDuration,r))}else l=s.noteOnly;n[0].value>0&&!e.isContinuedBend&&t>0&&t--;const d=Math.min(l,se.millisToTicks(this._settings.player.songBookBendDuration,r));let g=[];switch(e.bendType){case p.Custom:g=n;break;case p.Bend:case p.Release:switch(e.bendStyle){case u.Default:g=n;break;case u.Gradual:g.push(new ae(0,e.bendPoints[0].value)),(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),g.push(new ae(ae.MaxPosition,c));break;case u.Fast:return(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),void(e.beat.graceType===b.BendGrace?this.generateSongBookWhammyOrBend(t,l,!0,[e.bendPoints[0].value,c],d,r,h):this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,c],d,r,h))}break;case p.BendRelease:switch(e.bendStyle){case u.Default:g=n;break;case u.Gradual:g.push(new ae(0,e.bendPoints[0].value)),g.push(new ae(ae.MaxPosition/2|0,e.bendPoints[1].value)),g.push(new ae(ae.MaxPosition,e.bendPoints[2].value));break;case u.Fast:return void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],d,r,h)}break;case p.Hold:case p.Prebend:g=n;break;case p.PrebendBend:switch(e.bendStyle){case u.Default:g=n;break;case u.Gradual:g.push(new ae(0,e.bendPoints[0].value)),g.push(new ae(ae.MaxPosition,e.bendPoints[1].value));break;case u.Fast:return h(t,0|Sr.getPitchWheel(e.bendPoints[0].value)),(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,c],d,r,h)}break;case p.PrebendRelease:switch(e.bendStyle){case u.Default:g=n;break;case u.Gradual:g.push(new ae(0,e.bendPoints[0].value)),g.push(new ae(ae.MaxPosition,e.bendPoints[1].value));break;case u.Fast:return h(t,0|Sr.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,e.bendPoints[1].value],d,r,h)}}this.generateWhammyOrBend(t,l,g,r,h)}generateSongBookWhammyOrBend(e,t,s,i,a,r,n){const o=s?e:e+t-a,h=a/(i.length-1);for(let e=0;e<i.length-1;e++){const t=Sr.getPitchWheel(i[e]),s=Sr.getPitchWheel(i[e+1]),a=o+h*e;this.generateBendValues(a,h,t,s,r,n)}}generateWhammy(e,t,s,i,a){const r=e.whammyBarPoints,n=e.voice.bar.staff.track,o=s.noteOnly;r[0].value>0&&!e.isContinuedWhammy&&t--;const h=(e,t)=>{this._handler.addBend(n.index,e,i,t)};let l=[];switch(e.whammyBarType){case W.Custom:l=r;break;case W.Dive:switch(e.whammyStyle){case u.Default:l=r;break;case u.Gradual:l.push(new ae(0,r[0].value)),l.push(new ae(ae.MaxPosition,r[1].value));break;case u.Fast:const e=Math.min(o,se.millisToTicks(this._settings.player.songBookBendDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!1,[r[0].value,r[1].value],e,a,h)}break;case W.Dip:switch(e.whammyStyle){case u.Default:l=r;break;case u.Gradual:l.push(new ae(0,r[0].value)),l.push(new ae(ae.MaxPosition/2|0,r[1].value)),l.push(new ae(ae.MaxPosition,r[2].value));break;case u.Fast:const e=Math.min(o,se.millisToTicks(this._settings.player.songBookDipDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!0,[r[0].value,r[1].value,r[2].value],e,a,h)}break;case W.Hold:case W.Predive:l=r;break;case W.PrediveDive:switch(e.whammyStyle){case u.Default:l=r;break;case u.Gradual:l.push(new ae(0,r[0].value)),l.push(new ae(ae.MaxPosition/2|0,r[0].value)),l.push(new ae(ae.MaxPosition,r[1].value));break;case u.Fast:const e=Sr.getPitchWheel(r[0].value);this._handler.addBend(n.index,t,i,0|e);const s=Math.min(o,se.millisToTicks(this._settings.player.songBookBendDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!1,[r[0].value,r[1].value],s,a,h)}}this.generateWhammyOrBend(t,o,l,a,h)}generateWhammyOrBend(e,t,s,i,a){const r=t/ae.MaxPosition;for(let t=0;t<s.length-1;t++){const n=s[t],o=s[t+1],h=Sr.getPitchWheel(n.value),l=Sr.getPitchWheel(o.value),c=r*(o.offset-n.offset),d=e+r*n.offset;this.generateBendValues(d,c,h,l,i,a)}}generateBendValues(e,t,s,i,a,r){const n=se.ticksToMillis(t,a),o=Math.abs(i-s)/Sr.PitchValuePerSemitone,h=Math.max(Sr.MinBreakpointsPerSemitone*o,n/Sr.MillisecondsPerBreakpoint),l=t/h,c=(i-s)/h,d=e+t;for(let t=0;t<h;t++)r(0|e,Math.round(s)),s+=c,e+=l;r(0|d,i)}generateRasgueado(e,t,s,i,a,r,n){let o=s;for(let s=0;s<n.durations.length;s++){const h=n.brushInfos[s],l=t.isStringed&&t.string<=h.length?h[t.string-1]:0,c=n.durations[s];this._handler.addNote(e.index,o+l,c-l,i,a,r),o+=c}}generateTrill(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=se.toTicks(e.trillSpeed),l=!0,c=t;const d=t+s.untilTieOrSlideEnd;for(;c+10<d;)c+h>=d&&(h=d-c),this._handler.addNote(n.index,c,h,l?o:i,a,r),l=!l,c+=h}generateTremoloPicking(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track;let o=se.toTicks(e.beat.tremoloSpeed),h=t;const l=t+s.untilTieOrSlideEnd;for(;h+10<l;)h+o>=l&&(o=l-h),this._handler.addNote(n.index,h,o,i,a,r),h+=o}getRasgueadoInfo(e,t){if(!e.hasRasgueado)return null;const s=new br,i=Sr.RasgueadoDurations.get(e.rasgueado).reduce(((e,t)=>e+t),0);s.durations=Sr.RasgueadoDurations.get(e.rasgueado).map((e=>t*e/i)),s.brushInfos=new Array(s.durations.length);const a=se.toTicks(f.Sixteenth);let r=0,n=0;for(const t of e.notes)t.isTieDestination||(r|=1<<t.string-1,n++);const o=Sr.RasgueadoDirections.get(e.rasgueado);for(let t=0;t<s.durations.length;t++){const i=s.durations[t]*a/se.QuarterTime,h=new Int32Array(e.voice.bar.staff.tuning.length);s.brushInfos[t]=h;const l=o[t];l!==g.None&&this.fillBrushInfo(e,h,l===g.ArpeggioDown||l===g.BrushDown,r,n,i)}return s}getBrushInfo(e){const t=new Int32Array(e.voice.bar.staff.tuning.length);if(e.brushType){let s=0,i=0;for(const t of e.notes)t.isTieDestination||(s|=1<<t.string-1,i++);this.fillBrushInfo(e,t,e.brushType===g.ArpeggioDown||e.brushType===g.BrushDown,s,i,e.brushDuration)}return t}fillBrushInfo(e,t,s,i,a,r){if(e.notes.length>0){let n=0;const o=r/(a-1)|0;for(let a=0;a<e.voice.bar.staff.tuning.length;a++){const e=s?a:t.length-1-a;i&1<<e&&(t[e]=n,n+=o)}}return t}generateNonTempoAutomation(e,t,s){switch(t.type){case d.Instrument:this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,255&t.value),this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,255&t.value);break;case d.Balance:const i=Sr.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Xi.PanCoarse,i),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Xi.PanCoarse,i);break;case d.Volume:const a=Sr.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Xi.VolumeCoarse,a),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Xi.VolumeCoarse,a)}}prepareSingleBeat(e){let t=-1,s=-1,i=e;for(;i&&(-1===t||-1===s);){for(const i of e.automations)switch(i.type){case d.Instrument:s=i.value;break;case d.Tempo:t=i.value}i=i.previousBeat}const a=e.voice.bar.staff.track,r=e.voice.bar.masterBar;-1===t&&(t=r.score.tempo);const n=e.playbackStart/r.calculateDuration();for(const e of r.tempoAutomations){if(!(e.ratioPosition<=n))break;t=e.value}-1===s&&(s=a.playbackInfo.program);const o=a.playbackInfo.volume;this.generateTrack(a),this._handler.addTimeSignature(0,r.timeSignatureNumerator,r.timeSignatureDenominator),this._handler.addTempo(0,t);const h=Sr.toChannelShort(o);return this._handler.addControlChange(0,0,a.playbackInfo.primaryChannel,Xi.VolumeCoarse,h),this._handler.addControlChange(0,0,a.playbackInfo.secondaryChannel,Xi.VolumeCoarse,h),t}generateSingleBeat(e){const t=this.prepareSingleBeat(e);this.generateBeat(e,-e.playbackStart,e.voice.bar,t)}generateSingleNote(e){const t=this.prepareSingleBeat(e.beat);this.generateNote(e,0,e.beat.playbackDuration,t,new Int32Array(e.beat.voice.bar.staff.tuning.length),null)}}Sr.DefaultDurationDead=30,Sr.DefaultDurationPalmMute=80,Sr.OrnamentKeysUp=[2,2,2,1,1,2,2,2,2,2,1,1],Sr.OrnamentKeysDown=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],Sr.PitchBendRangeInSemitones=16,Sr.PitchValuePerSemitone=kt.DefaultPitchWheel/Sr.PitchBendRangeInSemitones,Sr.MinBreakpointsPerSemitone=6,Sr.MillisecondsPerBreakpoint=150,Sr.RasgueadoDirections=new Map([[X.Ii,[g.BrushDown,g.BrushUp]],[X.Mi,[g.BrushDown,g.BrushDown]],[X.MiiTriplet,[g.BrushDown,g.BrushDown,g.BrushUp]],[X.MiiAnapaest,[g.BrushDown,g.BrushDown,g.BrushUp]],[X.PmpTriplet,[g.BrushUp,g.BrushDown,g.BrushDown]],[X.PmpAnapaest,[g.BrushUp,g.BrushDown,g.BrushDown]],[X.PeiTriplet,[g.BrushUp,g.BrushDown,g.BrushDown]],[X.PeiAnapaest,[g.BrushUp,g.BrushDown,g.BrushDown]],[X.PaiTriplet,[g.BrushUp,g.BrushDown,g.BrushDown]],[X.PaiAnapaest,[g.BrushUp,g.BrushDown,g.BrushDown]],[X.AmiTriplet,[g.BrushDown,g.BrushDown,g.BrushDown]],[X.AmiAnapaest,[g.BrushDown,g.BrushDown,g.BrushDown]],[X.Ppp,[g.None,g.BrushDown,g.BrushUp]],[X.Amii,[g.BrushDown,g.BrushDown,g.BrushDown,g.BrushUp]],[X.Amip,[g.BrushDown,g.BrushDown,g.BrushDown,g.BrushUp]],[X.Eami,[g.BrushDown,g.BrushDown,g.BrushDown,g.BrushDown]],[X.Eamii,[g.BrushDown,g.BrushDown,g.BrushDown,g.BrushDown,g.BrushUp]],[X.Peami,[g.BrushDown,g.BrushDown,g.BrushDown,g.BrushDown,g.BrushUp]]]),Sr.RasgueadoDurations=new Map([[X.Ii,[se.toTicks(f.Eighth),se.toTicks(f.Eighth)]],[X.Mi,[se.toTicks(f.Eighth),se.toTicks(f.Eighth)]],[X.MiiTriplet,[se.toTicks(f.Eighth)/3,se.toTicks(f.Eighth)/3,se.toTicks(f.Eighth)/3]],[X.MiiAnapaest,[se.toTicks(f.Sixteenth),se.toTicks(f.Sixteenth),se.toTicks(f.Eighth)]],[X.PmpTriplet,[se.toTicks(f.Eighth)/3,se.toTicks(f.Eighth)/3,se.toTicks(f.Eighth)/3]],[X.PmpAnapaest,[se.toTicks(f.Sixteenth)/3,se.toTicks(f.Sixteenth)/3,se.toTicks(f.Eighth)/3]],[X.PeiTriplet,[se.toTicks(f.Eighth)/3,se.toTicks(f.Eighth)/3,se.toTicks(f.Eighth)/3]],[X.PeiAnapaest,[se.toTicks(f.Sixteenth),se.toTicks(f.Sixteenth),se.toTicks(f.Eighth)]],[X.PaiTriplet,[se.toTicks(f.Eighth)/3,se.toTicks(f.Eighth)/3,se.toTicks(f.Eighth)/3]],[X.PaiAnapaest,[se.toTicks(f.Sixteenth),se.toTicks(f.Sixteenth),se.toTicks(f.Eighth)]],[X.AmiTriplet,[se.toTicks(f.Eighth)/3,se.toTicks(f.Eighth)/3,se.toTicks(f.Eighth)/3]],[X.AmiAnapaest,[se.toTicks(f.Sixteenth)/3,se.toTicks(f.Sixteenth)/3,se.toTicks(f.Eighth)/3]],[X.Ppp,[se.toTicks(f.Sixteenth)/3,se.toTicks(f.Sixteenth)/3,se.toTicks(f.Eighth)/3]],[X.Amii,[se.toTicks(f.Sixteenth)/3,se.toTicks(f.Sixteenth)/3,se.toTicks(f.Sixteenth)/3,se.toTicks(f.Eighth)]],[X.Amip,[se.toTicks(f.Sixteenth)/3,se.toTicks(f.Sixteenth)/3,se.toTicks(f.Sixteenth)/3,se.toTicks(f.Eighth)]],[X.Eami,[se.toTicks(f.Sixteenth),se.toTicks(f.Sixteenth),se.toTicks(f.Sixteenth),se.toTicks(f.Sixteenth)]],[X.Eamii,[se.toTicks(f.Sixteenth)/5,se.toTicks(f.Sixteenth)/5,se.toTicks(f.Sixteenth)/5,se.toTicks(f.Sixteenth)/5,se.toTicks(f.Sixteenth)/5]],[X.Peami,[se.toTicks(f.Sixteenth)/5,se.toTicks(f.Sixteenth)/5,se.toTicks(f.Sixteenth)/5,se.toTicks(f.Sixteenth)/5,se.toTicks(f.Sixteenth)/5]]]);class _r{constructor(){this.startTick=0,this.endTick=0}}class wr{constructor(e,t){this.width=0,this.height=0,this.x=e,this.y=t}doLayout(){}paint(e,t,s){}}class Br extends wr{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class kr{}kr.Widths=new Map([[I.Brace,3],[I.BracketTop,0],[I.BracketBottom,0],[I.SystemDivider,0],[I.GClef,28],[I.CClef,28],[I.FClef,28],[I.UnpitchedPercussionClef1,15],[I.SixStringTabClef,28],[I.FourStringTabClef,28],[I.TimeSig0,14],[I.TimeSig1,10],[I.TimeSig2,14],[I.TimeSig3,14],[I.TimeSig4,14],[I.TimeSig5,14],[I.TimeSig6,14],[I.TimeSig7,14],[I.TimeSig8,14],[I.TimeSig9,14],[I.TimeSigCommon,14],[I.TimeSigCutCommon,14],[I.NoteheadDoubleWholeSquare,14],[I.NoteheadDoubleWhole,14],[I.NoteheadWhole,14],[I.NoteheadHalf,9],[I.NoteheadBlack,9],[I.NoteheadNull,9],[I.NoteheadXOrnate,9],[I.NoteheadPlusDoubleWhole,16],[I.NoteheadPlusWhole,10],[I.NoteheadPlusHalf,10],[I.NoteheadPlusBlack,10],[I.NoteheadSquareWhite,11],[I.NoteheadSquareBlack,11],[I.NoteheadTriangleUpDoubleWhole,16],[I.NoteheadTriangleUpWhole,11],[I.NoteheadTriangleUpHalf,11],[I.NoteheadTriangleUpBlack,11],[I.NoteheadTriangleRightWhite,11],[I.NoteheadTriangleRightBlack,11],[I.NoteheadTriangleDownDoubleWhole,16],[I.NoteheadTriangleDownWhole,11],[I.NoteheadTriangleDownHalf,11],[I.NoteheadTriangleDownBlack,11],[I.NoteheadDiamondDoubleWhole,16],[I.NoteheadDiamondWhole,9],[I.NoteheadDiamondHalf,9],[I.NoteheadDiamondBlack,9],[I.NoteheadDiamondBlackWide,10],[I.NoteheadDiamondWhite,9],[I.NoteheadDiamondWhiteWide,9],[I.NoteheadCircleXDoubleWhole,16],[I.NoteheadCircleXWhole,9],[I.NoteheadCircleXHalf,9],[I.NoteheadCircleX,9],[I.NoteheadXDoubleWhole,16],[I.NoteheadXWhole,9],[I.NoteheadXHalf,9],[I.NoteheadXBlack,9],[I.NoteheadParenthesis,9],[I.NoteheadSlashedBlack1,9],[I.NoteheadSlashedBlack2,9],[I.NoteheadSlashedHalf1,9],[I.NoteheadSlashedHalf2,9],[I.NoteheadSlashedWhole1,9],[I.NoteheadSlashedWhole2,9],[I.NoteheadSlashedDoubleWhole1,16],[I.NoteheadSlashedDoubleWhole2,16],[I.NoteheadCircledBlack,9],[I.NoteheadCircledHalf,9],[I.NoteheadCircledWhole,9],[I.NoteheadCircledDoubleWhole,16],[I.NoteheadCircleSlash,9],[I.NoteheadHeavyX,13],[I.NoteheadHeavyXHat,13],[I.NoteheadSlashVerticalEnds,12],[I.NoteheadSlashWhiteWhole,32],[I.NoteheadSlashWhiteHalf,25],[I.NoteheadRoundWhiteWithDot,9],[I.NoteheadSquareBlackLarge,9],[I.NoteheadSquareBlackWhite,9],[I.NoteheadClusterDoubleWhole3rd,16],[I.NoteheadClusterWhole3rd,12],[I.NoteheadClusterHalf3rd,12],[I.NoteheadClusterQuarter3rd,12],[I.NoteShapeRoundWhite,9],[I.NoteShapeRoundBlack,9],[I.NoteShapeSquareWhite,12],[I.NoteShapeSquareBlack,12],[I.NoteShapeTriangleRightWhite,12],[I.NoteShapeTriangleRightBlack,12],[I.NoteShapeTriangleLeftWhite,12],[I.NoteShapeTriangleLeftBlack,12],[I.NoteShapeDiamondWhite,9],[I.NoteShapeDiamondBlack,9],[I.NoteShapeTriangleUpWhite,12],[I.NoteShapeTriangleUpBlack,12],[I.NoteShapeMoonWhite,12],[I.NoteShapeMoonBlack,12],[I.NoteShapeTriangleRoundWhite,12],[I.NoteShapeTriangleRoundBlack,12],[I.NoteQuarterUp,10],[I.NoteEighthUp,10],[I.TextBlackNoteLongStem,0],[I.TextBlackNoteFrac8thLongStem,0],[I.TextBlackNoteFrac16thLongStem,0],[I.TextBlackNoteFrac32ndLongStem,0],[I.TextCont8thBeamLongStem,0],[I.TextCont16thBeamLongStem,0],[I.TextCont32ndBeamLongStem,0],[I.TextAugmentationDot,0],[I.TextTupletBracketStartLongStem,0],[I.TextTuplet3LongStem,0],[I.TextTupletBracketEndLongStem,0],[I.Tremolo3,12],[I.Tremolo2,12],[I.Tremolo1,12],[I.FlagEighthUp,0],[I.FlagEighthDown,0],[I.FlagSixteenthUp,0],[I.FlagSixteenthDown,0],[I.FlagThirtySecondUp,0],[I.FlagThirtySecondDown,0],[I.FlagSixtyFourthUp,0],[I.FlagSixtyFourthDown,0],[I.FlagOneHundredTwentyEighthUp,0],[I.FlagOneHundredTwentyEighthDown,0],[I.FlagTwoHundredFiftySixthUp,0],[I.FlagTwoHundredFiftySixthDown,0],[I.AccidentalFlat,8],[I.AccidentalNatural,8],[I.AccidentalSharp,8],[I.AccidentalDoubleSharp,8],[I.AccidentalDoubleFlat,18],[I.AccidentalQuarterToneFlatArrowUp,8],[I.AccidentalQuarterToneSharpArrowUp,8],[I.AccidentalQuarterToneNaturalArrowUp,8],[I.Segno,0],[I.Coda,0],[I.ArticAccentAbove,9],[I.ArticAccentBelow,9],[I.ArticStaccatoAbove,9],[I.ArticStaccatoBelow,9],[I.ArticTenutoAbove,9],[I.ArticTenutoBelow,9],[I.ArticMarcatoAbove,9],[I.ArticMarcatoBelow,9],[I.FermataAbove,23],[I.FermataShortAbove,23],[I.FermataLongAbove,23],[I.RestLonga,9],[I.RestDoubleWhole,9],[I.RestWhole,9],[I.RestHalf,9],[I.RestQuarter,9],[I.RestEighth,9],[I.RestSixteenth,9],[I.RestThirtySecond,12],[I.RestSixtyFourth,14],[I.RestOneHundredTwentyEighth,14],[I.RestTwoHundredFiftySixth,14],[I.RestHBarLeft,0],[I.RestHBarMiddle,0],[I.RestHBarRight,0],[I.Repeat1Bar,0],[I.Repeat2Bars,0],[I.Ottava,0],[I.OttavaAlta,32],[I.OttavaBassaVb,29],[I.Quindicesima,23],[I.QuindicesimaAlta,46],[I.DynamicPPP,0],[I.DynamicPP,0],[I.DynamicPiano,0],[I.DynamicMP,0],[I.DynamicMF,0],[I.DynamicForte,0],[I.DynamicFF,0],[I.DynamicFFF,0],[I.OrnamentTrill,20],[I.OrnamentTurn,26],[I.OrnamentTurnInverted,26],[I.OrnamentShortTrill,0],[I.OrnamentMordent,26],[I.StringsDownBow,9],[I.StringsUpBow,9],[I.KeyboardPedalPed,35],[I.KeyboardPedalUp,16],[I.PictEdgeOfCymbal,44],[I.GuitarString0,20],[I.GuitarString1,20],[I.GuitarString2,20],[I.GuitarString3,20],[I.GuitarString4,20],[I.GuitarString5,20],[I.GuitarString6,20],[I.GuitarString7,20],[I.GuitarString8,20],[I.GuitarString9,20],[I.GuitarOpenPedal,11],[I.GuitarClosePedal,11],[I.GuitarGolpe,13.4],[I.GuitarFadeIn,13],[I.GuitarFadeOut,13],[I.GuitarVolumeSwell,26],[I.FretboardX,0],[I.FretboardO,0],[I.WiggleTrill,9],[I.WiggleVibratoMediumFast,10],[I.OctaveBaselineM,13],[I.OctaveBaselineB,9]]),kr.Heights=new Map([[I.Brace,34],[I.BracketTop,0],[I.BracketBottom,0],[I.SystemDivider,0],[I.GClef,0],[I.CClef,0],[I.FClef,0],[I.UnpitchedPercussionClef1,0],[I.SixStringTabClef,0],[I.FourStringTabClef,0],[I.TimeSig0,0],[I.TimeSig1,0],[I.TimeSig2,0],[I.TimeSig3,0],[I.TimeSig4,0],[I.TimeSig5,0],[I.TimeSig6,0],[I.TimeSig7,0],[I.TimeSig8,0],[I.TimeSig9,0],[I.TimeSigCommon,0],[I.TimeSigCutCommon,0],[I.NoteheadDoubleWholeSquare,8],[I.NoteheadDoubleWhole,8],[I.NoteheadWhole,8],[I.NoteheadHalf,8],[I.NoteheadBlack,8],[I.NoteheadNull,8],[I.NoteheadXOrnate,8],[I.NoteheadPlusDoubleWhole,8],[I.NoteheadPlusWhole,8],[I.NoteheadPlusHalf,8],[I.NoteheadPlusBlack,8],[I.NoteheadSquareWhite,8],[I.NoteheadSquareBlack,8],[I.NoteheadTriangleUpDoubleWhole,8],[I.NoteheadTriangleUpWhole,8],[I.NoteheadTriangleUpHalf,8],[I.NoteheadTriangleUpBlack,8],[I.NoteheadTriangleRightWhite,8],[I.NoteheadTriangleRightBlack,8],[I.NoteheadTriangleDownDoubleWhole,8],[I.NoteheadTriangleDownWhole,8],[I.NoteheadTriangleDownHalf,8],[I.NoteheadTriangleDownBlack,8],[I.NoteheadDiamondDoubleWhole,8],[I.NoteheadDiamondWhole,8],[I.NoteheadDiamondHalf,8],[I.NoteheadDiamondBlack,8],[I.NoteheadDiamondBlackWide,9],[I.NoteheadDiamondWhite,9],[I.NoteheadDiamondWhiteWide,9],[I.NoteheadCircleXDoubleWhole,8],[I.NoteheadCircleXWhole,8],[I.NoteheadCircleXHalf,8],[I.NoteheadCircleX,8],[I.NoteheadXDoubleWhole,8],[I.NoteheadXWhole,8],[I.NoteheadXHalf,8],[I.NoteheadXBlack,8],[I.NoteheadParenthesis,8],[I.NoteheadSlashedBlack1,8],[I.NoteheadSlashedBlack2,8],[I.NoteheadSlashedHalf1,8],[I.NoteheadSlashedHalf2,8],[I.NoteheadSlashedWhole1,8],[I.NoteheadSlashedWhole2,8],[I.NoteheadSlashedDoubleWhole1,8],[I.NoteheadSlashedDoubleWhole2,8],[I.NoteheadCircledBlack,8],[I.NoteheadCircledHalf,8],[I.NoteheadCircledWhole,8],[I.NoteheadCircledDoubleWhole,8],[I.NoteheadCircleSlash,8],[I.NoteheadHeavyX,8],[I.NoteheadHeavyXHat,8],[I.NoteheadSlashVerticalEnds,17],[I.NoteheadSlashWhiteWhole,17],[I.NoteheadSlashWhiteHalf,17],[I.NoteheadRoundWhiteWithDot,8],[I.NoteheadSquareBlackLarge,8],[I.NoteheadSquareBlackWhite,8],[I.NoteheadClusterDoubleWhole3rd,8],[I.NoteheadClusterWhole3rd,8],[I.NoteheadClusterHalf3rd,8],[I.NoteheadClusterQuarter3rd,8],[I.NoteShapeRoundWhite,8],[I.NoteShapeRoundBlack,8],[I.NoteShapeSquareWhite,8],[I.NoteShapeSquareBlack,8],[I.NoteShapeTriangleRightWhite,8],[I.NoteShapeTriangleRightBlack,8],[I.NoteShapeTriangleLeftWhite,8],[I.NoteShapeTriangleLeftBlack,8],[I.NoteShapeDiamondWhite,8],[I.NoteShapeDiamondBlack,8],[I.NoteShapeTriangleUpWhite,8],[I.NoteShapeTriangleUpBlack,8],[I.NoteShapeMoonWhite,8],[I.NoteShapeMoonBlack,8],[I.NoteShapeTriangleRoundWhite,8],[I.NoteShapeTriangleRoundBlack,8],[I.NoteQuarterUp,8],[I.NoteEighthUp,8],[I.TextBlackNoteLongStem,0],[I.TextBlackNoteFrac8thLongStem,0],[I.TextBlackNoteFrac16thLongStem,0],[I.TextBlackNoteFrac32ndLongStem,0],[I.TextCont8thBeamLongStem,0],[I.TextCont16thBeamLongStem,0],[I.TextCont32ndBeamLongStem,0],[I.TextAugmentationDot,0],[I.TextTupletBracketStartLongStem,0],[I.TextTuplet3LongStem,0],[I.TextTupletBracketEndLongStem,0],[I.Tremolo3,0],[I.Tremolo2,0],[I.Tremolo1,0],[I.FlagEighthUp,0],[I.FlagEighthDown,0],[I.FlagSixteenthUp,0],[I.FlagSixteenthDown,0],[I.FlagThirtySecondUp,0],[I.FlagThirtySecondDown,0],[I.FlagSixtyFourthUp,0],[I.FlagSixtyFourthDown,0],[I.FlagOneHundredTwentyEighthUp,0],[I.FlagOneHundredTwentyEighthDown,0],[I.FlagTwoHundredFiftySixthUp,0],[I.FlagTwoHundredFiftySixthDown,0],[I.AccidentalFlat,0],[I.AccidentalNatural,0],[I.AccidentalSharp,0],[I.AccidentalDoubleSharp,0],[I.AccidentalDoubleFlat,0],[I.AccidentalQuarterToneFlatArrowUp,0],[I.AccidentalQuarterToneSharpArrowUp,0],[I.AccidentalQuarterToneNaturalArrowUp,0],[I.Segno,0],[I.Coda,0],[I.ArticAccentAbove,9],[I.ArticAccentBelow,9],[I.ArticStaccatoAbove,9],[I.ArticStaccatoBelow,9],[I.ArticTenutoAbove,9],[I.ArticTenutoBelow,9],[I.ArticMarcatoAbove,9],[I.ArticMarcatoBelow,9],[I.FermataAbove,12],[I.FermataShortAbove,12],[I.FermataLongAbove,12],[I.RestLonga,0],[I.RestDoubleWhole,0],[I.RestWhole,0],[I.RestHalf,0],[I.RestQuarter,0],[I.RestEighth,0],[I.RestSixteenth,0],[I.RestThirtySecond,0],[I.RestSixtyFourth,0],[I.RestOneHundredTwentyEighth,0],[I.RestTwoHundredFiftySixth,0],[I.RestHBarLeft,0],[I.RestHBarMiddle,0],[I.RestHBarRight,0],[I.Repeat1Bar,0],[I.Repeat2Bars,0],[I.Ottava,13],[I.OttavaAlta,13],[I.OttavaBassaVb,13],[I.Quindicesima,13],[I.QuindicesimaAlta,13],[I.DynamicPPP,28.4],[I.DynamicPP,28.4],[I.DynamicPiano,28.4],[I.DynamicMP,28.4],[I.DynamicMF,28.4],[I.DynamicForte,28.4],[I.DynamicFF,28.4],[I.DynamicFFF,28.4],[I.OrnamentTrill,24],[I.OrnamentTurn,18],[I.OrnamentTurnInverted,18],[I.OrnamentShortTrill,18],[I.OrnamentMordent,18],[I.StringsDownBow,13/.75],[I.StringsUpBow,13/.75],[I.KeyboardPedalPed,19],[I.KeyboardPedalUp,16],[I.PictEdgeOfCymbal,30],[I.GuitarString0,20],[I.GuitarString1,20],[I.GuitarString2,20],[I.GuitarString3,20],[I.GuitarString4,20],[I.GuitarString5,20],[I.GuitarString6,20],[I.GuitarString7,20],[I.GuitarString8,20],[I.GuitarString9,20],[I.GuitarOpenPedal,11],[I.GuitarClosePedal,11],[I.GuitarGolpe,13.4],[I.GuitarFadeIn,13],[I.GuitarFadeOut,13],[I.GuitarVolumeSwell,13],[I.FretboardX,0],[I.FretboardO,0],[I.WiggleTrill,6],[I.WiggleVibratoMediumFast,10],[I.OctaveBaselineM,0],[I.OctaveBaselineB,0]]);class Tr extends Br{constructor(e,t,s,i){super(e,t),this.glyphScale=0,this.center=!1,this.glyphScale=s,this.symbol=i}doLayout(){this.width=kr.Widths.has(this.symbol)?kr.Widths.get(this.symbol)*this.glyphScale:0,this.height=kr.Heights.has(this.symbol)?kr.Heights.get(this.symbol)*this.glyphScale:0}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride),s.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale,this.symbol,this.center),s.color=i}}class Nr extends Tr{constructor(e,t,s,i){super(e,t,i?Nr.GraceScale:1,Nr.getSymbol(s)),this.centerOnStem=!1,this._isGrace=i}paint(e,t,s){const i=this._isGrace?1:0;this.centerOnStem&&(this.center=!0),super.paint(e,t+i,s)}static getSymbol(e){switch(e){case f.QuadrupleWhole:return I.NoteheadDoubleWholeSquare;case f.DoubleWhole:return I.NoteheadDoubleWhole;case f.Whole:return I.NoteheadWhole;case f.Half:return I.NoteheadHalf;default:return I.NoteheadBlack}}}Nr.GraceScale=.75;class xr extends Tr{constructor(e,t,s,i,a){super(e,t,a?Nr.GraceScale:1,xr.getSymbol(s,i,a))}static getSymbol(e,t,s){if(s&&(e=f.Eighth),t===je.Up)switch(e){case f.Eighth:return I.FlagEighthUp;case f.Sixteenth:return I.FlagSixteenthUp;case f.ThirtySecond:return I.FlagThirtySecondUp;case f.SixtyFourth:return I.FlagSixtyFourthUp;case f.OneHundredTwentyEighth:return I.FlagOneHundredTwentyEighthUp;case f.TwoHundredFiftySixth:return I.FlagTwoHundredFiftySixthUp;default:return I.FlagEighthUp}switch(e){case f.Eighth:return I.FlagEighthDown;case f.Sixteenth:return I.FlagSixteenthDown;case f.ThirtySecond:return I.FlagThirtySecondDown;case f.SixtyFourth:return I.FlagSixtyFourthDown;case f.OneHundredTwentyEighth:case f.TwoHundredFiftySixth:return I.FlagOneHundredTwentyEighthDown;default:return I.FlagEighthDown}}}xr.FlagWidth=11;class vr extends wr{get onTimeX(){return this.onNotes.x+this.onNotes.centerX}constructor(e,t){super(0,0),this.ties=[],this.minWidth=0,this.beat=e,this.ties=[],this.voiceContainer=t}addTie(e){e.renderer=this.renderer,this.ties.push(e)}drawBeamHelperAsFlags(e){return e.hasFlag(!1,void 0)}registerLayoutingInfo(e){const t=this.preNotes.computedWidth+this.onNotes.centerX;let s=this.onNotes.computedWidth-this.onNotes.centerX;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);this.beat.graceType!==b.None?1===this.beat.graceGroup.beats.length?s+=xr.FlagWidth*Nr.GraceScale:this.beat.graceIndex<this.beat.graceGroup.beats.length-1?s+=7:s+=vr.GraceBeatPadding:i&&this.drawBeamHelperAsFlags(i)&&(s+=xr.FlagWidth);for(const e of this.ties)s+=e.width;e.addBeatSpring(this.beat,t,s)}applyLayoutingInfo(e){this.onNotes.updateBeamingHelper(),this.updateWidth()}doLayout(){this.preNotes.x=0,this.preNotes.renderer=this.renderer,this.preNotes.container=this,this.preNotes.doLayout(),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.renderer=this.renderer,this.onNotes.container=this,this.onNotes.doLayout();let e=this.beat.notes.length-1;for(;e>=0;)this.createTies(this.beat.notes[e--]);this.renderer.registerTies(this.ties),this.updateWidth()}updateWidth(){if(this.minWidth=this.preNotes.width+this.onNotes.width,!this.beat.isRest)if(1===this.onNotes.beamingHelper.beats.length)this.beat.duration>=f.Eighth&&(this.minWidth+=20);else switch(this.beat.duration){case f.OneHundredTwentyEighth:case f.TwoHundredFiftySixth:this.minWidth+=10}let e=0;for(const t of this.ties)t.width>e&&(e=t.width);this.minWidth+=e,this.width=this.minWidth}scaleToWidth(e){this.onNotes.updateBeamingHelper(),this.width=e}createTies(e){}static getGroupId(e){return`b${e.id}`}paint(e,t,s){if(this.preNotes.isEmpty&&this.onNotes.isEmpty&&0===this.ties.length)return;s.beginGroup(vr.getGroupId(this.beat)),this.preNotes.paint(e+this.x,t+this.y,s),this.onNotes.paint(e+this.x,t+this.y,s);const i=e-this.voiceContainer.x-this.renderer.x,a=t-this.voiceContainer.y-this.renderer.y;for(let e=0,t=this.ties.length;e<t;e++){const t=this.ties[e];t.renderer=this.renderer,t.paint(i,a,s)}s.endGroup()}buildBoundingsLookup(e,t,s,i){const a=new wi;if(a.beat=this.beat,this.beat.isEmpty)a.visualBounds=new Is,a.visualBounds.x=t+this.x,a.visualBounds.y=e.visualBounds.y,a.visualBounds.w=this.width,a.visualBounds.h=e.visualBounds.h,a.realBounds=new Is,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,a.onNotesX=t+this.x+this.onNotes.centerX;else{a.visualBounds=new Is,a.visualBounds.x=t+this.x,this.preNotes.isEmpty?this.onNotes.isEmpty?a.visualBounds.x=t+this.x:a.visualBounds.x=t+this.x+this.onNotes.x:a.visualBounds.x=t+this.x+this.preNotes.x;let s=0;s=this.onNotes.isEmpty?this.preNotes.isEmpty?t+this.x+this.width:t+this.x+this.preNotes.x+this.preNotes.width:t+this.x+this.onNotes.x+this.onNotes.width,a.visualBounds.w=s-a.visualBounds.x;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);(i&&this.drawBeamHelperAsFlags(i)||this.beat.graceType!==b.None)&&(a.visualBounds.w+=xr.FlagWidth*(this.beat.graceType!==b.None?Nr.GraceScale:1)),a.visualBounds.y=e.visualBounds.y,a.visualBounds.h=e.visualBounds.h,a.realBounds=new Is,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,a.onNotesX=t+this.x+this.onNotes.x+this.onNotes.centerX}e.addBeat(a),this.renderer.settings.core.includeNoteBounds&&this.onNotes.buildBoundingsLookup(a,t+this.x,s+this.y)}}vr.GraceBeatPadding=3;class Pr{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new ac}causeIssue(){return this.settings=null,!0}}class Cr{constructor(e){this.activeBeats=e}}class Er{constructor(e){this.bounds=null,this.beat=e}}class Fr{get score(){return this._score}get tracks(){return this._tracks}constructor(e,t){this._startTime=0,this._trackIndexes=null,this._trackIndexLookup=null,this._isDestroyed=!1,this._score=null,this._tracks=[],this._tickCache=null,this.player=null,this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null,this._previousTick=0,this._playerState=Oi.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=Oi.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new Si,this.activeBeatsChanged=new Si,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new Si,this.beatMouseMove=new Si,this.beatMouseUp=new Si,this.noteMouseDown=new Si,this.noteMouseMove=new Si,this.noteMouseUp=new Si,this.scoreLoaded=new Si,this.resize=new Si,this.renderStarted=new Si,this.renderFinished=new Si,this.postRenderFinished=new bi,this.error=new Si,this.playerReady=new bi,this.playerFinished=new bi,this.soundFontLoaded=new bi,this.midiLoad=new Si,this.midiLoaded=new Si,this.playerStateChanged=new Si,this.playerPositionChanged=new Si,this.midiEventsPlayed=new Si,this.playbackRangeChanged=new Si,this.settingsUpdated=new bi,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),he.logLevel=this.settings.core.logLevel,ic.printEnvironmentInfo(!1),this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&ic.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new xi(this.settings),this.container.resize.on(ic.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));const s=new Pr;s.oldWidth=this.renderer.width,s.newWidth=0|this.container.width,s.settings=this.settings,this.onResize(s),this.renderer.preRender.on(this.onRenderStarted.bind(this)),this.renderer.renderFinished.on((e=>{this.onRenderFinished(e)})),this.renderer.postRenderFinished.on((()=>{const e=Date.now()-this._startTime;he.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&&ue.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?(this.setupPlayer(),e&&this.player?.applyTranspositionPitches(Sr.buildTranspositionPitches(e,this.settings))):this.destroyPlayer(),this.onSettingsUpdated()}load(e,t){try{return this.uiFacade.load(e,(e=>{this.renderScore(e,t)}),(e=>{this.onError(e)}))}catch(e){return this.onError(e),!1}}renderScore(e,t){const s=[];if(t)if(0===t.length)e.tracks.length>0&&s.push(e.tracks[0]);else if(1===t.length&&-1===t[0])for(const t of e.tracks)s.push(t);else for(const i of t)i>=0&&i<=e.tracks.length&&s.push(e.tracks[i]);else e.tracks.length>0&&s.push(e.tracks[0]);this.internalRenderTracks(e,s)}renderTracks(e){if(e.length>0){const t=e[0].score;for(const s of e)if(s.score!==t)return void this.onError(new Le(Ee.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(t,e)}}internalRenderTracks(e,t){if(ue.applyPitchOffsets(this.settings,e),e!==this.score){this._score=e,this._tracks=t,this._tickCache=null,this._trackIndexes=[];for(const e of t)this._trackIndexes.push(e.index);this._trackIndexLookup=new Set(this._trackIndexes),this.onScoreLoaded(e),this.loadMidiForScore(),this.render()}else{this._tracks=t;const s=ue.computeFirstDisplayedBarIndex(e,this.settings),i=ue.computeLastDisplayedBarIndex(e,this.settings,s);this._tickCache&&(this._tickCache.multiBarRestInfo=ue.buildMultiBarRestInfo(this.tracks,s,i)),this._trackIndexes=[];for(const e of t)this._trackIndexes.push(e.index);this._trackIndexLookup=new Set(this._trackIndexes),this.render()}}triggerResize(){if(this.container.isVisible){const e=new Pr;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 he.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{he.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{const s=new xt;s.logErrors=!0,s.initFromString(e,this.settings);const i=s.readScore();this.renderScore(i,t)}catch(e){this.onError(e)}}loadSoundFont(e,t=!1){return!!this.player&&this.uiFacade.loadSoundFont(e,t)}resetSoundFonts(){this.player&&this.player.resetSoundFonts()}render(){this.renderer&&(this.uiFacade.canRender?(this.renderer.width=this.container.width,this.renderer.renderScore(this.score,this._trackIndexes)):this.uiFacade.canRenderChanged.on((()=>this.render())))}get tickCache(){return this._tickCache}get boundsLookup(){return this.renderer.boundsLookup}get isReadyForPlayback(){return!!this.player&&this.player.isReadyForPlayback}get playerState(){return this.player?this.player.state:Oi.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=Oi.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(const e of this.tracks){const t=e.playbackInfo.volume/16;this.player.setChannelVolume(e.playbackInfo.primaryChannel,t),this.player.setChannelVolume(e.playbackInfo.secondaryChannel,t)}})),this.player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this.player.soundFontLoadFailed.on((e=>{this.onError(e)})),this.player.midiLoaded.on(this.onMidiLoaded.bind(this)),this.player.midiLoadFailed.on((e=>{this.onError(e)})),this.player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this.player.positionChanged.on(this.onPlayerPositionChanged.bind(this)),this.player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this.player.playbackRangeChanged.on(this.onPlaybackRangeChanged.bind(this)),this.player.finished.on(this.onPlayerFinished.bind(this)),this.setupPlayerEvents()))}loadMidiForScore(){if(!this.score)return;const e=this.score;he.debug("AlphaTab","Generating Midi");const t=new Pt,s=new or(t),i=new Sr(e,this.settings,s),a=ue.computeFirstDisplayedBarIndex(e,this.settings),r=ue.computeLastDisplayedBarIndex(e,this.settings,a);i.tickLookup.multiBarRestInfo=ue.buildMultiBarRestInfo(this.tracks,a,r),i.applyTranspositionPitches=!1,i.generate(),this._tickCache=i.tickLookup,this.onMidiLoad(t);const n=this.player;n&&(n.loadMidiFile(t),n.applyTranspositionPitches(i.transpositionPitches))}changeTrackVolume(e,t){if(this.player)for(const s of e)this.player.setChannelVolume(s.playbackInfo.primaryChannel,t),this.player.setChannelVolume(s.playbackInfo.secondaryChannel,t)}changeTrackSolo(e,t){if(this.player)for(const s of e)this.player.setChannelSolo(s.playbackInfo.primaryChannel,t),this.player.setChannelSolo(s.playbackInfo.secondaryChannel,t)}changeTrackMute(e,t){if(this.player)for(const s of e)this.player.setChannelMute(s.playbackInfo.primaryChannel,t),this.player.setChannelMute(s.playbackInfo.secondaryChannel,t)}changeTrackTranspositionPitch(e,t){if(this.player)for(const s of e)this.player.setChannelTranspositionPitch(s.playbackInfo.primaryChannel,t),this.player.setChannelTranspositionPitch(s.playbackInfo.secondaryChannel,t)}play(){return!!this.player&&this.player.play()}pause(){this.player&&this.player.pause()}playPause(){this.player&&this.player.playPause()}stop(){this.player&&this.player.stop()}playBeat(e){if(!this.player)return;const t=new Pt,s=new or(t);new Sr(e.voice.bar.staff.track.score,this.settings,s).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;const t=new Pt,s=new or(t);new Sr(e.beat.voice.bar.staff.track.score,this.settings,s).generateSingleNote(e),this.player.playOneTimeMidiFile(t)}destroyCursors(){this._cursorWrapper&&(this.uiFacade.destroyCursors(),this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null)}updateCursors(){if(this.settings.player.enableCursor&&!this._cursorWrapper){const 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=Oi.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,!1,e.isSeek)}))})),this.player.stateChanged.on((e=>{if(this._playerState=e.state,!e.stopped&&e.state===Oi.Paused){const e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getBeatStart(e.beat))}})))}cursorUpdateTick(e,t,s=!1,i=!1){const a=this._tickCache;if(a){const r=this._trackIndexLookup;if(null!=r&&r.size>0){const n=a.findBeat(r,e,this._currentBeat);n&&this.cursorUpdateBeat(n,t,s,i||this.playerState===Oi.Paused)}}}cursorUpdateBeat(e,t,s,i=!1){const a=e.beat,r=e.nextBeat?.beat??null,n=e.duration,o=e.beatLookup.highlightedBeats;if(!a)return;const h=this.renderer.boundsLookup;if(!h)return;const l=this._currentBeat,c=this._previousCursorCache,d=this._previousStateForCursor;if(!i&&a===l?.beat&&h===c&&d===this._playerState&&l?.start===e.start)return;const u=h.findBeat(a);u&&(this._currentBeat=e,this._previousCursorCache=h,this._previousStateForCursor=this._playerState,this.uiFacade.beginInvoke((()=>{this.internalCursorUpdateBeat(a,r,n,t,o,h,u,s,e.cursorMode)})))}scrollToCursor(){const e=this._currentBarBounds;e&&this.internalScrollToCursor(e)}internalScrollToCursor(e){const t=this.uiFacade.getScrollContainer(),s=ic.getLayoutEngineFactory(this.settings.display.layoutMode).vertical,i=this.settings.player.scrollMode;if(s){const s=e.realBounds.y+this.settings.player.scrollOffsetY;if(s!==this._lastScroll)switch(this._lastScroll=s,i){case rt.Continuous:const i=this.uiFacade.getOffset(t,this.container);this.uiFacade.scrollToY(t,i.y+s,this.settings.player.scrollSpeed);break;case rt.OffScreen:const a=t.scrollTop+this.uiFacade.getOffset(null,t).h;if(e.visualBounds.y+e.visualBounds.h>=a||e.visualBounds.y<t.scrollTop){const s=e.realBounds.y+this.settings.player.scrollOffsetY;this.uiFacade.scrollToY(t,s,this.settings.player.scrollSpeed)}}}else{const s=e.visualBounds.x;if(s!==this._lastScroll)switch(this._lastScroll=s,i){case rt.Continuous:const s=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,s,this.settings.player.scrollSpeed);break;case rt.OffScreen:const i=t.scrollLeft+this.uiFacade.getOffset(null,t).w;if(e.visualBounds.x+e.visualBounds.w>=i||e.visualBounds.x<t.scrollLeft){const s=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,s,this.settings.player.scrollSpeed)}}}}internalCursorUpdateBeat(e,t,s,i,a,r,n,o,h){const l=this._barCursor,c=this._beatCursor,d=n.barBounds.masterBarBounds,u=d.visualBounds;this._currentBarBounds=d,l&&l.setBounds(u.x,u.y,u.w,u.h),c&&(this.settings.player.enableAnimatedBeatCursor&&c.stopAnimation(),c.setBounds(n.onNotesX,u.y,1,u.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let p=!1;const g=this._playerState===Oi.Playing&&!i;if(g){if(this.settings.player.enableElementHighlighting)for(const t of a){const s=vr.getGroupId(t.beat);this.uiFacade.highlightElements(s,e.voice.bar.index)}o=!i,p=!0}if(this.settings.player.enableAnimatedBeatCursor&&c){let e=d.visualBounds.x+d.visualBounds.w;if(t&&h===Yi.ToNextBext){const s=r.findBeat(t);s&&s.barBounds.masterBarBounds.staffSystemBounds===d.staffSystemBounds&&(e=s.onNotesX)}g&&this.uiFacade.beginInvoke((()=>{c.transitionToX(s/this.playbackSpeed,e)}))}o&&!this._beatMouseDown&&this.settings.player.scrollMode!==rt.Off&&this.internalScrollToCursor(d),p&&(this.onPlayedBeatChanged(e),this.onActiveBeatsChanged(new Cr(a.map((e=>e.beat)))))}onPlayedBeatChanged(e){this._isDestroyed||(this.playedBeatChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playedBeatChanged",e))}onActiveBeatsChanged(e){this._isDestroyed||(this.activeBeatsChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"activeBeatsChanged",e))}onBeatMouseDown(e,t){this._isDestroyed||(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&(this._selectionStart=new Er(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 Er(t),this.cursorSelectRange(this._selectionStart,this._selectionEnd))),this.beatMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseMove",t,e))}onNoteMouseMove(e,t){this._isDestroyed||(this.noteMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseMove",t,e))}onBeatMouseUp(e,t){if(!this._isDestroyed){if(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction){if(this._selectionEnd){const e=this._tickCache?.getBeatStart(this._selectionStart.beat)??this._selectionStart.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(this._selectionEnd.beat)??this._selectionEnd.beat.absolutePlaybackStart)<e){const e=this._selectionStart;this._selectionStart=this._selectionEnd,this._selectionEnd=e}}if(this._selectionStart&&this._tickCache){const e=this._tickCache,t=e.getMasterBarStart(this._selectionStart.beat.voice.bar.masterBar);if(this._currentBeat=null,this._playerState===Oi.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){const s=e.getMasterBarStart(this._selectionEnd.beat.voice.bar.masterBar),i=new _r;i.startTick=t+this._selectionStart.beat.playbackStart,i.endTick=s+this._selectionEnd.beat.playbackStart+this._selectionEnd.beat.playbackDuration-50,this.playbackRange=i}else this._selectionStart=null,this.playbackRange=null,this.cursorSelectRange(this._selectionStart,this._selectionEnd)}}this.beatMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseUp",t,e),this._beatMouseDown=!1}}onNoteMouseUp(e,t){this._isDestroyed||(this.noteMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseUp",t,e),this._noteMouseDown=!1)}updateSelectionCursor(e){if(this._tickCache)if(e){const t=this._tickCache.findBeat(this._trackIndexLookup,e.startTick),s=this._tickCache.findBeat(this._trackIndexLookup,e.endTick);if(t&&s){const e=new Er(t.beat),i=new Er(s.beat);this.cursorSelectRange(e,i)}}else this.cursorSelectRange(null,null)}setupClickHandling(){this.canvasElement.mouseDown.on((e=>{if(!e.isLeftMouseButton)return;this.settings.player.enableUserInteraction&&e.preventDefault();const t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(i&&(this.onBeatMouseDown(e,i),this.settings.core.includeNoteBounds)){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s);a&&this.onNoteMouseDown(e,a)}})),this.canvasElement.mouseMove.on((e=>{if(!this._beatMouseDown)return;const t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(i&&(this.onBeatMouseMove(e,i),this._noteMouseDown)){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s);a&&this.onNoteMouseMove(e,a)}})),this.canvasElement.mouseUp.on((e=>{if(!this._beatMouseDown)return;this.settings.player.enableUserInteraction&&e.preventDefault();const t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(this.onBeatMouseUp(e,i),this._noteMouseDown)if(i){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s)??null;this.onNoteMouseUp(e,a)}else this.onNoteMouseUp(e,null)})),this.renderer.postRenderFinished.on((()=>{this._selectionStart&&this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&this.cursorSelectRange(this._selectionStart,this._selectionEnd)}))}cursorSelectRange(e,t){const s=this.renderer.boundsLookup;if(!s)return;const i=this._selectionWrapper;if(!i)return;if(i.clear(),!e||!t||e.beat===t.beat)return;e.bounds||(e.bounds=s.findBeat(e.beat)),t.bounds||(t.bounds=s.findBeat(t.beat));const a=this._tickCache?.getBeatStart(e.beat)??e.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(t.beat)??t.beat.absolutePlaybackStart)<a){const s=e;e=t,t=s}const r=e.bounds.realBounds.x;let n=t.bounds.realBounds.x+t.bounds.realBounds.w;if(t.beat.index===t.beat.voice.beats.length-1&&(n=t.bounds.barBounds.masterBarBounds.realBounds.x+t.bounds.barBounds.masterBarBounds.realBounds.w),e.bounds.barBounds.masterBarBounds.staffSystemBounds!==t.bounds.barBounds.masterBarBounds.staffSystemBounds){const a=e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.x,o=e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.x+e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.w,h=this.uiFacade.createSelectionElement();h.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,o-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(h);const l=e.bounds.barBounds.masterBarBounds.staffSystemBounds.index+1,c=t.bounds.barBounds.masterBarBounds.staffSystemBounds.index;for(let e=l;e<c;e++){const t=s.staffSystems[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),i.appendChild(r)}const d=this.uiFacade.createSelectionElement();d.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(d)}else{const t=this.uiFacade.createSelectionElement();t.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,n-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(t)}}onScoreLoaded(e){this._isDestroyed||(this.scoreLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"scoreLoaded",e))}onResize(e){this._isDestroyed||(this.resize.trigger(e),this.uiFacade.triggerEvent(this.container,"resize",e))}onRenderStarted(e){this._isDestroyed||(this.renderStarted.trigger(e),this.uiFacade.triggerEvent(this.container,"renderStarted",e))}onRenderFinished(e){this._isDestroyed||(this.renderFinished.trigger(e),this.uiFacade.triggerEvent(this.container,"renderFinished",e))}onPostRenderFinished(){this._isDestroyed||(this.postRenderFinished.trigger(),this.uiFacade.triggerEvent(this.container,"postRenderFinished",null))}onError(e){this._isDestroyed||(he.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))}async enumerateOutputDevices(){return this.player?await this.player.output.enumerateOutputDevices():[]}async setOutputDevice(e){this.player&&await this.player.output.setOutputDevice(e)}async getOutputDevice(){return this.player?await this.player.output.getOutputDevice():null}}class Dr extends Le{constructor(e,t){super(Ee.General,e),this.xhr=t,Object.setPrototypeOf(this,Dr.prototype)}}class Mr{static loadScoreAsync(e,t,s,i){const a=new XMLHttpRequest;a.open("GET",e,!0,null,null),a.responseType="arraybuffer",a.onreadystatechange=()=>{if(a.readyState===XMLHttpRequest.DONE){const e=a.response;if(200===a.status||0===a.status&&e)try{const e=a.response,s=new Uint8Array(e),r=Mr.loadScoreFromBytes(s,i);t(r)}catch(e){s(e)}else 0===a.status?s(new Dr("You are offline!!\n Please Check Your Network.",a)):404===a.status?s(new Dr("Requested URL not found.",a)):500===a.status?s(new Dr("Internel Server Error.",a)):"parsererror"===a.statusText?s(new Dr("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?s(new Dr("Request Time out.",a)):s(new Dr(`Unknow Error: ${a.responseText}`,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new as);const s=ic.buildImporters();he.debug("ScoreLoader",`Loading score from ${e.length} bytes using ${s.length} importers`);let i=null;const a=Bt.fromBuffer(e);for(const e of s){a.reset();try{he.debug("ScoreLoader",`Importing using importer ${e.name}`),e.init(a,t),i=e.readScore(),he.debug("ScoreLoader",`Score imported using ${e.name}`);break}catch(t){if(!(t instanceof dt))throw he.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;he.debug("ScoreLoader",`${e.name} does not support the file`)}}if(i)return i;throw new dt("No compatible importer found for file")}}class Lr{get isLeftMouseButton(){return 0===this.mouseEvent.button}getX(e){const t=e.element,s=t.getBoundingClientRect().left+t.ownerDocument.defaultView.pageXOffset;return this.mouseEvent.pageX-s}getY(e){const t=e.element,s=t.getBoundingClientRect().top+t.ownerDocument.defaultView.pageYOffset;return this.mouseEvent.pageY-s}preventDefault(){this.mouseEvent.preventDefault()}constructor(e){this.mouseEvent=e}}class Ir{get width(){return this.element.offsetWidth}set width(e){this.element.style.width=`${e}px`}get scrollLeft(){return this.element.scrollLeft}set scrollLeft(e){this.element.scrollLeft=e}get scrollTop(){return this.element.scrollTop}set scrollTop(e){this.element.scrollTop=e}get height(){return this.element.offsetHeight}set height(e){this.element.style.height=e>=0?`${e}px`:"100%"}get isVisible(){return!!this.element.offsetWidth||!!this.element.offsetHeight||!!this.element.getClientRects().length}constructor(e){this._resizeListeners=0,this.lastBounds=new Is,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new Lr(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new Lr(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new Lr(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&Ir.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,Ir.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,Number.NaN,Number.NaN,Number.NaN)}setBounds(e,t,s,i){Number.isNaN(e)&&(e=this.lastBounds.x),Number.isNaN(t)&&(t=this.lastBounds.y),Number.isNaN(s)&&(s=this.lastBounds.w),Number.isNaN(i)&&(i=this.lastBounds.h),this.element.style.transform=`translate(${e}px, ${t}px) scale(${s}, ${i})`,this.element.style.transformOrigin="top left",this.lastBounds.x=e,this.lastBounds.y=t,this.lastBounds.w=s,this.lastBounds.h=i}appendChild(e){this.element.appendChild(e.element)}clear(){this.element.innerHTML=""}}Ir.resizeObserver=new ne((()=>new ResizeObserver((e=>{for(const t of e){const e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class Ar{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new Si,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(ic.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0;const t=window.setInterval((()=>{he.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);he.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);const s=e=>{this._families.length>1?(he.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(he.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},i=e=>{he.debug("Font",`[${e}] Font API signaled available`),this.isFontLoaded=!0,window.clearInterval(t),this.fontLoaded.trigger(this._families[0])},a=async()=>{for(const e of this._families)if(await this.isFontAvailable(e,!1))return void i(e);try{await document.fonts.load(`1em ${this._families[0]}`)}catch(e){s(e)}return he.debug("Font",`[${this._families[0]}] Font API signaled loaded`),await this.isFontAvailable(this._families[0],!0)?i(this._families[0]):s("Font not available"),!0};document.fonts.ready.then((()=>{a()}))}isFontAvailable(e,t){return new Promise((s=>{const i=`1em ${e}`;if(document.fonts.check(i))s(!0);else if(t){he.debug("Font",`Font ${e} not available, creating test element to trigger load`);const t=document.createElement("div");t.style.font=i,t.style.opacity="0",t.style.position="absolute",t.style.top="0",t.style.left="0",t.innerText=`Trigger ${e} load`,document.body.appendChild(t),setTimeout((()=>{document.body.removeChild(t),document.fonts.check(i)?s(!0):s(!1)}),200)}else s(!1)}))}}class Rr{constructor(e){this._writePosition=0,this._readPosition=0,this.count=0,this._buffer=new Float32Array(e)}clear(){this._readPosition=0,this._writePosition=0,this.count=0,this._buffer=new Float32Array(this._buffer.length)}write(e,t,s){let i=0;s>this._buffer.length-this.count&&(s=this._buffer.length-this.count);const a=Math.min(this._buffer.length-this._writePosition,s);return this._buffer.set(e.subarray(t,t+a),this._writePosition),this._writePosition+=a,this._writePosition%=this._buffer.length,i+=a,i<s&&(this._buffer.set(e.subarray(t+i,t+i+s-i),this._writePosition),this._writePosition+=s-i,i=s),this.count+=i,i}read(e,t,s){s>this.count&&(s=this.count);let i=0;const a=Math.min(this._buffer.length-this._readPosition,s);return e.set(this._buffer.subarray(this._readPosition,this._readPosition+a),t),i+=a,this._readPosition+=a,this._readPosition%=this._buffer.length,i<s&&(e.set(this._buffer.subarray(this._readPosition,this._readPosition+s-i),t+i),this._readPosition+=s-i,i=s),this.count-=i,i}}class Or{constructor(e){this.isDefault=!1,this.device=e}get deviceId(){return this.device.deviceId}get label(){return this.device.label}}class Hr{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new bi,this.samplesPlayed=new Si,this.sampleRequest=new bi,this._knownDevices=[]}get sampleRate(){return this._context?this._context.sampleRate:Hr.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(he.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{he.debug("WebAudio",`Audio Context resume success: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}`),e&&e()}),(e=>{he.warning("WebAudio",`Audio Context resume failed: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}, reason=${e}`)})))}patchIosSampleRate(){const e=navigator.userAgent;if(-1!==e.indexOf("iPhone")||-1!==e.indexOf("iPad")){const e=this.createAudioContext(),t=e.createBuffer(1,1,Hr.PreferredSampleRate),s=e.createBufferSource();s.buffer=t,s.connect(e.destination),s.start(0),s.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in ic.globalThis)return new AudioContext;if("webkitAudioContext"in ic.globalThis)return new webkitAudioContext;throw new Le(Ee.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(){const e=this._context;this.activate(),this._buffer=e.createBuffer(2,Hr.BufferSize,e.sampleRate),this._source=e.createBufferSource(),this._source.buffer=this._buffer,this._source.loop=!0}pause(){this._source&&(this._source.stop(0),this._source.disconnect()),this._source=null}destroy(){this.pause(),this._context?.close(),this._context=null,this.unregisterResumeHandler()}onSamplesPlayed(e){this.samplesPlayed.trigger(e)}onSampleRequest(){this.sampleRequest.trigger()}onReady(){this.ready.trigger()}async checkSinkIdSupport(){return"setSinkId"in(this._context??this.createAudioContext())||(he.warning("WebAudio","Browser does not support changing the output device"),!1)}async enumerateOutputDevices(){try{if(!await this.checkSinkIdSupport())return[];try{await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){he.warning("WebAudio","Output device permission rejected",e)}const e=await navigator.mediaDevices.enumerateDevices();let t="",s="";const i=new Map;for(const a of e)"audiooutput"===a.kind&&(i.set(a.groupId,new Or(a)),"default"!==a.deviceId&&""!==a.deviceId||(t=a.groupId,s=a.deviceId));const a=Array.from(i.values());let r=a.find((e=>e.deviceId===s));return r||(r=a.find((e=>e.device.groupId===t))),!r&&a.length>0&&(r=a[0]),r&&(r.isDefault=!0),this._knownDevices=a,a}catch(e){return he.error("WebAudio","Failed to enumerate output devices",e),[]}}async setOutputDevice(e){await this.checkSinkIdSupport()&&(e?await this._context.setSinkId(e.deviceId):await this._context.setSinkId(""))}async getOutputDevice(){if(!await this.checkSinkIdSupport())return null;const e=this._context.sinkId;if("string"!=typeof e||""===e||"default"===e)return null;let t=this._knownDevices.find((t=>t.deviceId===e));if(t)return t;const s=await this.enumerateOutputDevices();return t=s.find((t=>t.deviceId===e)),t||(he.warning("WebAudio","Could not find output device in device list",e,s),null)}}Hr.BufferSize=4096,Hr.PreferredSampleRate=44100;class Wr extends Hr{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/Hr.BufferSize),this._circularBuffer=new Rr(Hr.BufferSize*this._bufferCount),this.onReady()}play(){super.play();const 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,t=e*Hr.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*Hr.BufferSize<t){for(let t=0;t<e;t++)this.onSampleRequest();this._requestedBufferCount+=e}}generateSound(e){const t=e.outputBuffer.getChannelData(0),s=e.outputBuffer.getChannelData(1),i=t.length+s.length;let a=this._outputBuffer;a.length!==i&&(a=new Float32Array(i),this._outputBuffer=a);const r=this._circularBuffer.read(a,0,Math.min(a.length,this._circularBuffer.count));let n=0;const o=Math.min(t.length,r);for(let e=0;e<o;e++)t[e]=a[n++],s[e]=a[n++];if(r<t.length)for(let e=r;e<t.length;e++)t[e]=0,s[e]=0;this.onSamplesPlayed(r/kt.AudioChannels),this.requestBuffers()}}class Vr{constructor(e,t){this.loaded=e,this.total=t}}class Gr{get output(){return this._output}get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return he.logLevel}set logLevel(e){he.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,kt.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,kt.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,kt.MinVolume),this._countInVolume=e,this._synth.postMessage({cmd:"alphaSynth.setCountInVolume",value:e})}get midiEventsPlayedFilter(){return this._midiEventsPlayedFilter}set midiEventsPlayedFilter(e){this._midiEventsPlayedFilter=e,this._synth.postMessage({cmd:"alphaSynth.setMidiEventsPlayedFilter",value:e})}get playbackSpeed(){return this._playbackSpeed}set playbackSpeed(e){e=ue.clamp(e,kt.MinPlaybackSpeed,kt.MaxPlaybackSpeed),this._playbackSpeed=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackSpeed",value:e})}get tickPosition(){return this._tickPosition}set tickPosition(e){e<0&&(e=0),this._tickPosition=e,this._synth.postMessage({cmd:"alphaSynth.setTickPosition",value:e})}get timePosition(){return this._timePosition}set timePosition(e){e<0&&(e=0),this._timePosition=e,this._synth.postMessage({cmd:"alphaSynth.setTimePosition",value:e})}get isLooping(){return this._isLooping}set isLooping(e){this._isLooping=e,this._synth.postMessage({cmd:"alphaSynth.setIsLooping",value:e})}get playbackRange(){return this._playbackRange}set playbackRange(e){e&&(e.startTick<0&&(e.startTick=0),e.endTick<0&&(e.endTick=0)),this._playbackRange=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackRange",value:e})}constructor(e,t){this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Oi.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 bi,this.readyForPlayback=new bi,this.finished=new bi,this.soundFontLoaded=new bi,this.soundFontLoadFailed=new Si,this.midiLoaded=new Si,this.midiLoadFailed=new Si,this.stateChanged=new Si,this.positionChanged=new Si,this.midiEventsPlayed=new Si,this.playbackRangeChanged=new Si,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Oi.Paused,this._masterVolume=0,this._metronomeVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._output=e,this._output.ready.on(this.onOutputReady.bind(this)),this._output.samplesPlayed.on(this.onOutputSamplesPlayed.bind(this)),this._output.sampleRequest.on(this.onOutputSampleRequest.bind(this)),this._output.open(t.player.bufferTimeInMilliseconds);try{this._synth=ic.createWebWorker(t)}catch(e){he.error("AlphaSynth",`Failed to create WebWorker: ${e}`)}this._synth.addEventListener("message",this.handleWorkerMessage.bind(this),!1),this._synth.postMessage({cmd:"alphaSynth.initialize",sampleRate:this._output.sampleRate,logLevel:t.core.logLevel,bufferTimeInMilliseconds:t.player.bufferTimeInMilliseconds}),this.masterVolume=1,this.playbackSpeed=1,this.metronomeVolume=0}destroy(){this._synth.postMessage({cmd:"alphaSynth.destroy"})}play(){return this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.play"}),!0}pause(){this._synth.postMessage({cmd:"alphaSynth.pause"})}playPause(){this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.playPause"})}stop(){this._synth.postMessage({cmd:"alphaSynth.stop"})}playOneTimeMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.playOneTimeMidiFile",midi:Es.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,s){he.debug("AlphaSynth",`Start loading Soundfont from url ${e}`);const i=new XMLHttpRequest;i.open("GET",e,!0,null,null),i.responseType="arraybuffer",i.onload=e=>{const s=new Uint8Array(i.response);this.loadSoundFont(s,t)},i.onerror=e=>{he.error("AlphaSynth",`Loading failed: ${e.message}`),this.soundFontLoadFailed.trigger(new Dr(e.message,i))},i.onprogress=e=>{he.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),s(new Vr(e.loaded,e.total))},i.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:Es.midiFileToJsObject(e)})}applyTranspositionPitches(e){this._synth.postMessage({cmd:"alphaSynth.applyTranspositionPitches",transpositionPitches:JSON.stringify(Array.from(e.entries()))})}setChannelTranspositionPitch(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelTranspositionPitch",channel:e,semitones:t})}setChannelMute(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelMute",channel:e,mute:t})}resetChannelStates(){this._synth.postMessage({cmd:"alphaSynth.resetChannelStates"})}setChannelSolo(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelSolo",channel:e,solo:t})}setChannelVolume(e,t){t=Math.max(t,kt.MinVolume),this._synth.postMessage({cmd:"alphaSynth.setChannelVolume",channel:e,volume:t})}handleWorkerMessage(e){const 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 Ki(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new er(t.events.map(Es.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new qi(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new tr(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 Ki(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 Ur{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new Si,this.partialRenderFinished=new Si,this.partialLayoutFinished=new Si,this.renderFinished=new Si,this.postRenderFinished=new bi,this.error=new Si,this._api=e;try{this._worker=ic.createWebWorker(t)}catch(e){return void he.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=Es.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){const 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=Ni.fromJson(t.boundsLookup,this._api.score),this.boundsLookup.finish(),this.postRenderFinished.trigger();break;case"alphaTab.error":this.error.trigger(t.error)}}renderScore(e,t){const s=null==e?null:Es.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:s,trackIndexes:t,fontSizes:Ge.FontSizeLookupTables})}}class zr{static init(){var e;zr._isRegistered||(zr._isRegistered=!0,registerProcessor("alphatab",((e=class extends AudioWorkletProcessor{constructor(t){super(t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,this._isStopped=!1,he.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new Rr(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){const t=e.data;switch(t.cmd){case ir.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case ir.CmdOutputResetSamples:this._circularBuffer.clear();break;case ir.CmdOutputStop:this._isStopped=!0}}process(e,t,s){if(1!==t.length&&2!==t[0].length)return!1;const i=t[0][0],a=t[0][1];if(!i||!a)return!0;const r=i.length+a.length;let n=this._outputBuffer;n.length!==r&&(n=new Float32Array(r),this._outputBuffer=n);const o=this._circularBuffer.read(n,0,Math.min(n.length,this._circularBuffer.count));let h=0;const l=Math.min(i.length,o);for(let e=0;e<l;e++)i[e]=n[h++],a[e]=n[h++];if(o<i.length)for(let e=o;e<i.length;e++)i[e]=0,a[e]=0;return this.port.postMessage({cmd:ir.CmdOutputSamplesPlayed,samples:o/kt.AudioChannels}),this.requestBuffers(),this._circularBuffer.count>0||!this._isStopped}requestBuffers(){const t=this._bufferCount/2|0,s=t*e.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*e.BufferSize<s){for(let e=0;e<t;e++)this.port.postMessage({cmd:ir.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}zr._isRegistered=!1;class Xr extends Hr{constructor(e){super(),this._worklet=null,this._bufferTimeInMilliseconds=0,this._settings=e}open(e){super.open(e),this._bufferTimeInMilliseconds=e,this.onReady()}play(){super.play();const e=this._context;ic.createAudioWorklet(e,this._settings).then((()=>{this._worklet=new AudioWorkletNode(e,"alphatab",{numberOfOutputs:1,outputChannelCount:[2],processorOptions:{bufferTimeInMilliseconds:this._bufferTimeInMilliseconds}}),this._worklet.port.onmessage=this.handleMessage.bind(this),this._source.connect(this._worklet),this._source.start(0),this._worklet.connect(e.destination)}),(e=>{he.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){const t=e.data;switch(t.cmd){case ir.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case ir.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.postMessage({cmd:ir.CmdOutputStop}),this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){this._worklet?.port.postMessage({cmd:ir.CmdOutputAddSamples,samples:e})}resetSamples(){this._worklet?.port.postMessage({cmd:ir.CmdOutputResetSamples})}}class Jr extends Ir{constructor(e,t,s){super(e),this._xscale=t,this._yscale=s}get width(){return this.element.offsetWidth/this._xscale}set width(e){this.element.style.width=e*this._xscale+"px"}get height(){return this.element.offsetHeight/this._yscale}set height(e){this.element.style.height=e>=0?e*this._yscale+"px":"100%"}setBounds(e,t,s,i){Number.isNaN(e)&&(e=this.lastBounds.x),Number.isNaN(t)&&(t=this.lastBounds.y),Number.isNaN(s)?s=this.lastBounds.w:s/=this._xscale,Number.isNaN(i)?i=this.lastBounds.h:i/=this._yscale,this.element.style.transform=`translate(${e}px, ${t}px) scale(${s}, ${i})`,this.element.style.transformOrigin="top left",this.lastBounds.x=e,this.lastBounds.y=t,this.lastBounds.w=s,this.lastBounds.h=i}}!function(e){e[e.LayoutDone=0]="LayoutDone",e[e.RenderRequested=1]="RenderRequested",e[e.RenderDone=2]="RenderDone",e[e.Detached=3]="Detached"}($i||($i={}));class Yr{get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(ic.bravuraFontChecker.checkForFontAvailability(),!ic.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(he.debug("Font",`All fonts loaded: ${this._fontCheckers.size}`),!0)}onFontLoaded(e){Ge.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 bi,this.canRenderChanged=new bi,this._highlightedElements=[],this._scrollContainer=null,ic.webPlatform!==Me.Browser&&ic.webPlatform!==Me.BrowserModule)throw new Le(Ee.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 Ir(e),this.areWorkersSupported="Worker"in window,ic.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(e)}onElementVisibilityChanged(e){for(const t of e){const e=t.target;if(e===this.rootContainer.element)t.isIntersecting&&(this.rootContainerBecameVisible.trigger(),this._intersectionObserver.unobserve(this.rootContainer.element));else if("layoutResultId"in e&&this._api.settings.core.enableLazyLoading){const s=e;t.isIntersecting?s.renderedResultId!==s.layoutResultId?this._resultIdToElementLookup.has(s.layoutResultId)?s.resultState!==$i.RenderRequested&&(s.resultState=$i.RenderRequested,this._api.renderer.renderResult(s.layoutResultId)):e.replaceChildren():s.resultState===$i.Detached&&(e.replaceChildren(...s.renderedResult),s.resultState=$i.RenderDone):s.resultState===$i.RenderDone&&(s.resultState=$i.Detached,s.replaceChildren())}}}createWorkerRenderer(){return new Ur(this._api,this._api.settings)}initialize(e,t){let s;this._api=e,s=t instanceof as?t:Es.jsObjectToSettings(t);const i=this.getDataAttributes();is.fromJson(s,i),s.notation.notationMode===P.SongBook&&s.setSongBookModeSettings(),e.settings=s,this.setupFontCheckers(s),this._initialTrackIndexes=this.parseTracks(s.core.tracks),this._contents="";const a=e.container;s.core.tex&&(this._contents=a.element.innerHTML,a.element.innerHTML=""),this.createStyleElement(s),this._file=s.core.file}setupFontCheckers(e){this.registerFontChecker(e.display.resources.copyrightFont),this.registerFontChecker(e.display.resources.effectFont),this.registerFontChecker(e.display.resources.fingeringFont),this.registerFontChecker(e.display.resources.graceFont),this.registerFontChecker(e.display.resources.markerFont),this.registerFontChecker(e.display.resources.tablatureFont),this.registerFontChecker(e.display.resources.titleFont),this.registerFontChecker(e.display.resources.wordsFont),this.registerFontChecker(e.display.resources.barNumberFont),this.registerFontChecker(e.display.resources.fretboardNumberFont),this.registerFontChecker(e.display.resources.subTitleFont)}registerFontChecker(e){if(!this._fontCheckers.has(e.families.join(", "))){const t=new Ar(e.families);this._fontCheckers.set(e.families.join(", "),t),t.fontLoaded.on(this.onFontLoaded.bind(this)),t.checkForFontAvailability()}}destroy(){this.rootContainer.element.innerHTML=""}createCanvasElement(){const 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 Ir(e)}triggerEvent(e,t,s=null,i){const a=e.element;t=`alphaTab.${t}`;const r=document.createEvent("CustomEvent"),n=i?i.mouseEvent:null;if(r.initCustomEvent(t,!1,!1,s),n&&(r.originalEvent=n),a.dispatchEvent(r),window&&"jQuery"in window){const e=window.jQuery,i=[];i.push(s),n&&i.push(n),e(a).trigger(t,i)}}load(e,t,s){if(e instanceof lt)return t(e),!0;if(e instanceof ArrayBuffer){const s=new Uint8Array(e);return t(Mr.loadScoreFromBytes(s,this._api.settings)),!0}return e instanceof Uint8Array?(t(Mr.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(Mr.loadScoreAsync(e,t,s,this._api.settings),!0)}loadSoundFont(e,t){return!!this._api.player&&(e instanceof ArrayBuffer?(this._api.player.loadSoundFont(new Uint8Array(e),t),!0):e instanceof Uint8Array?(this._api.player.loadSoundFont(e,t),!0):"string"==typeof e&&(this._api.loadSoundFontFromUrl(e,t),!0))}initialRender(){this._api.renderer.preRender.on((e=>{this._totalResultCount=0,this._resultIdToElementLookup.clear(),this._barToElementLookup.clear()}));const e=()=>{this._api.renderer.width=0|this.rootContainer.width,this._api.renderer.updateSettings(this._api.settings),this._contents?(this._api.tex(this._contents,this._initialTrackIndexes??void 0),this._initialTrackIndexes=null):this._file&&Mr.loadScoreAsync(this._file,(e=>{this._api.renderScore(e,this._initialTrackIndexes??void 0),this._initialTrackIndexes=null}),(e=>{this._api.onError(e)}),this._api.settings)};this.rootContainer.isVisible?e():this.rootContainerBecameVisible.on(e)}createStyleElement(e){const t=this._api.container.element.ownerDocument;ic.createStyleElement(t,e.core.fontDirectory)}parseTracks(e){if(!e)return[];const 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){const s=e.length,i=e;for(let e=0;e<s;e++){const s=i[e];let a=0;a="number"==typeof s?s:"index"in s?s.index:Number.parseInt(s.toString()),(a>=0||-1===a)&&t.push(a)}}else"index"in e&&t.push(e.index);return t}getDataAttributes(){const e=new Map,t=this._api.container.element;if(t.dataset)for(const s of Object.keys(t.dataset)){let i=t.dataset[s];try{const e=i;i=JSON.parse(e)}catch(e){""===i&&(i=null)}e.set(s,i)}else for(let s=0;s<t.attributes.length;s++){const i=t.attributes.item(s),a=i.nodeName;if(a.startsWith("data-")){const t=a.substr(5).split("-");let s=t[0];for(let e=1;e<t.length;e++)s+=t[e].substr(0,1).toUpperCase()+t[e].substr(1);let r=i.nodeValue;try{r=JSON.parse(r)}catch(e){""===r&&(r=null)}e.set(s,r)}}return e}beginUpdateRenderResults(e){if(!this._resultIdToElementLookup.has(e.id))return;const t=this._resultIdToElementLookup.get(e.id),s=e.renderResult;"string"==typeof s?t.innerHTML=s:"nodeType"in s&&t.replaceChildren(s),t.resultState=$i.RenderDone,t.renderedResultId=e.id,t.renderedResult=Array.from(t.children)}beginAppendRenderResults(e){const t=this._api.canvasElement.element;if(e){let s;this._totalResultCount<t.childElementCount?s=t.childNodes.item(this._totalResultCount):(s=document.createElement("div"),t.appendChild(s)),s.style.zIndex="1",s.style.position="absolute",s.style.left=`${e.x}px`,s.style.top=`${e.y}px`,s.style.width=`${e.width}px`,s.style.height=`${e.height}px`,s.style.display="inline-block",s.layoutResultId=e.id,s.resultState=$i.LayoutDone,s.renderedResultId=void 0,s.renderedResult=void 0,this._resultIdToElementLookup.set(e.id,s);for(let t=e.firstMasterBarIndex;t<=e.lastMasterBarIndex;t++)t>=0&&this._barToElementLookup.set(t,s);this._api.settings.core.enableLazyLoading&&(this._intersectionObserver.unobserve(s),this._intersectionObserver.observe(s)),this._totalResultCount++}else for(;t.childElementCount>this._totalResultCount;)this._api.settings.core.enableLazyLoading&&this._intersectionObserver.unobserve(t.lastChild),t.removeChild(t.lastElementChild)}createWorkerPlayer(){let e=null;const t="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window&&this._api.settings.player.outputMode===nt.WebAudioAudioWorklets?(he.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),e=new Gr(new Xr(this._api.settings),this._api.settings)):t&&(he.debug("Player","Will use webworkers for synthesizing and web audio api with ScriptProcessor for playback"),e=new Gr(new Wr,this._api.settings)),e?e.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):he.error("Player","Player requires webworkers and web audio api, browser unsupported",null),e}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const s=this._barToElementLookup.get(t);if(s){const t=s.getElementsByClassName(e);for(let e=0;e<t.length;e++)t.item(e).classList.add("at-highlight"),this._highlightedElements.push(t.item(e))}}removeHighlights(){const e=this._highlightedElements;if(e){for(const t of e)t.classList.remove("at-highlight");this._highlightedElements=[]}}destroyCursors(){const e=this._api.container.element,t=e.querySelector(".at-cursors");e.removeChild(t)}createCursors(){const e=this._api.container.element,t=document.createElement("div");t.classList.add("at-cursors");const s=document.createElement("div");s.classList.add("at-selection");const i=this.createScalingElement(),a=this.createScalingElement(),r=i.element;r.classList.add("at-cursor-bar");const n=a.element;return n.classList.add("at-cursor-beat"),e.style.position="relative",e.style.textAlign="left",t.style.position="absolute",t.style.zIndex="1000",t.style.display="inline",t.style.pointerEvents="none",s.style.position="absolute",r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.willChange="transform",i.width=1,i.height=1,i.setBounds(0,0,1,1),n.style.position="absolute",n.style.transition="all 0s linear",n.style.left="0",n.style.top="0",n.style.willChange="transform",a.width=3,a.height=1,a.setBounds(0,0,1,1),e.insertBefore(t,e.firstChild),t.appendChild(s),t.appendChild(r),t.appendChild(n),new Ce(new Ir(t),i,a,new Ir(s))}getOffset(e,t){const s=t.element,i=s.getBoundingClientRect();let a=i.top+s.ownerDocument.defaultView.pageYOffset,r=i.left+s.ownerDocument.defaultView.pageXOffset;if(e){const t=e.element,s=t.nodeName.toLowerCase();if("html"!==s&&"body"!==s){const s=this.getOffset(null,e);a=a+t.scrollTop-s.y,r=r+t.scrollLeft-s.x}}const n=new Is;return n.x=r,n.y=a,n.w=i.width,n.h=i.height,n}getScrollContainer(){if(this._scrollContainer)return this._scrollContainer;let e="string"==typeof this._api.settings.player.scrollElement?document.querySelector(this._api.settings.player.scrollElement):this._api.settings.player.scrollElement;const 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 Ir(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new Jr(e,100,100);return t.width=1,t.height=1,t.setBounds(0,0,1,1),t}scrollToY(e,t,s){this.internalScrollToY(e.element,t,s)}scrollToX(e,t,s){this.internalScrollToX(e.element,t,s)}internalScrollToY(e,t,s){if(this._api.settings.player.nativeBrowserSmoothScroll)e.scrollTo({top:t,behavior:"smooth"});else{const i=e.scrollTop,a=t-i;let r=0;const n=t=>{0===r&&(r=t);const o=t-r,h=Math.min(o/s,1);e.scrollTop=i+a*h|0,o<s&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}internalScrollToX(e,t,s){if(this._api.settings.player.nativeBrowserSmoothScroll)e.scrollTo({left:t,behavior:"smooth"});else{const i=e.scrollLeft,a=t-i;let r=0;const n=t=>{0===r&&(r=t);const o=t-r,h=Math.min(o/s,1);e.scrollLeft=i+a*h|0,o<s&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}}class $r extends Fr{constructor(e,t){super(new Yr(e),t),this.soundFontLoad=new Si}tex(e,t){const s=this.uiFacade;super.tex(e,s.parseTracks(t))}print(t,s=null){const i=window.open("","","width=0,height=0"),a=i.document.createElement("div");t?a.style.width=t:this.settings.display.layoutMode===e.Horizontal?a.style.width="297mm":a.style.width="210mm",i.document.write("\n <!DOCTYPE html>\n <html>\n <head>\n <style>\n .at-surface {\n width: auto !important;\n height: auto !important;\n }\n .at-surface > div {\n position: relative!important;\n left: auto !important;\n top: auto !important;\n break-inside: avoid;\n }\n </style>\n </head>\n <body></body>\n </html>\n ");const r=this.score;r&&(r.artist&&r.title?i.document.title=`${r.title} - ${r.artist}`:r.title&&(i.document.title=`${r.title}`)),i.document.body.appendChild(a);const n=void 0!==window.screenLeft?window.screenLeft:window.left,o=void 0!==window.screenTop?window.screenTop:window.top,h="innerWidth"in window?window.innerWidth:"clientWidth"in document.documentElement?document.documentElement.clientWidth:window.screen.width,l="innerHeight"in window?window.innerHeight:"clientHeight"in document.documentElement?document.documentElement.clientHeight:window.screen.height,c=a.offsetWidth+50,d=window.innerHeight,u=(h/2|0)-(c/2|0)+n,p=(l/2|0)-(d/2|0)+o;i.resizeTo(c,d),i.moveTo(u,p),i.focus();const g=Es.jsObjectToSettings(Es.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,is.fromJson(g,s);const m=new $r(a,g);i.onunload=()=>{m.destroy()},m.renderer.postRenderFinished.on((()=>{i.print()})),m.renderTracks(this.tracks)}downloadMidi(e=st.SingleTrackMultiChannel){if(!this.score)return;const t=new Pt;t.format=e;const s=new or(t,!0);new Sr(this.score,this.settings,s).generate();const i=t.toBinary(),a=this.score.title?`${this.score.title}.mid`:"File.mid",r=document.createElement("a");r.download=a;const n=new Blob([i],{type:"audio/midi"}),o=URL.createObjectURL(n);r.href=o,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}changeTrackMute(e,t){const s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackMute(s,t)}changeTrackSolo(e,t){const s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackSolo(s,t)}changeTrackVolume(e,t){const s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackVolume(s,t)}trackIndexesToTracks(e){if(!this.score)return[];const t=[];if(1===e.length&&-1===e[0])for(const e of this.score.tracks)t.push(e);else for(const s of e)s>=0&&s<this.score.tracks.length&&t.push(this.score.tracks[s]);return t}loadSoundFontFromUrl(e,t){this.player&&this.player.loadSoundFontFromUrl(e,t,(e=>{this.soundFontLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"soundFontLoad",e)}))}}class qr{constructor(){this._initListeners=[]}exec(e,t,s){if("string"!=typeof t&&(s=[t],t="init"),95===t.charCodeAt(0)||"exec"===t)return null;const i=new jQuery(e),a=i.data("alphaTab");if("destroy"===t&&!a)return null;if("init"!==t&&!a)throw new Error("alphaTab not initialized");const r=this[t];if(r){const e=[i,a].concat(s);return r.apply(this,e)}return he.error("Api",`Method '${t}' does not exist on jQuery.alphaTab`),null}init(e,t,s){if(!t){t=new $r(e[0],s),e.data("alphaTab",t);for(const i of this._initListeners)i(e,t,s)}}destroy(e,t){e.removeData("alphaTab"),t.destroy()}print(e,t,s,i){t.print(s,i)}load(e,t,s,i){return t.load(s,i)}render(e,t){t.render()}renderScore(e,t,s,i){t.renderScore(s,i)}renderTracks(e,t,s){t.renderTracks(s)}invalidate(e,t){t.render()}tex(e,t,s,i){t.tex(s,i)}muteTrack(e,t,s,i){t.changeTrackMute(s,i)}soloTrack(e,t,s,i){t.changeTrackSolo(s,i)}trackVolume(e,t,s,i){t.changeTrackVolume(s,i)}loadSoundFont(e,t,s,i){t.loadSoundFont(s,i)}resetSoundFonts(e,t){t.resetSoundFonts()}pause(e,t){t.pause()}play(e,t){return t.play()}playPause(e,t){t.playPause()}stop(e,t){t.stop()}api(e,t){return t}player(e,t){return t.player}isReadyForPlayback(e,t){return t.isReadyForPlayback}playerState(e,t){return t.playerState}masterVolume(e,t,s){return"number"==typeof s&&(t.masterVolume=s),t.masterVolume}metronomeVolume(e,t,s){return"number"==typeof s&&(t.metronomeVolume=s),t.metronomeVolume}countInVolume(e,t,s){return"number"==typeof s&&(t.countInVolume=s),t.countInVolume}midiEventsPlayedFilter(e,t,s){return Array.isArray(s)&&(t.midiEventsPlayedFilter=s),t.midiEventsPlayedFilter}playbackSpeed(e,t,s){return"number"==typeof s&&(t.playbackSpeed=s),t.playbackSpeed}tickPosition(e,t,s){return"number"==typeof s&&(t.tickPosition=s),t.tickPosition}timePosition(e,t,s){return"number"==typeof s&&(t.timePosition=s),t.timePosition}loop(e,t,s){return"boolean"==typeof s&&(t.isLooping=s),t.isLooping}renderer(e,t){return t.renderer}score(e,t){return t.score}settings(e,t){return t.settings}tracks(e,t){return t.tracks}_oninit(e){this._initListeners.push(e)}static restore(e){new jQuery(e).empty().removeData("alphaTab")}}class Kr{constructor(){this.isInsideBracket=!0,this.isRelevantForBoundsLookup=!0,this.hideOnMultiTrack=!1,this.hideOnPercussionTrack=!1}canCreate(e,t){return!this.hideOnPercussionTrack||!t.isPercussion}}function jr(e,t,s){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var i,a;if(s){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=t[Symbol.asyncDispose]}if(void 0===i){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=t[Symbol.dispose],s&&(a=i)}if("function"!=typeof i)throw new TypeError("Object not disposable.");a&&(i=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:i,async:s})}else s&&e.stack.push({async:!0});return t}var Qr,Zr,en,tn,sn,an,rn,nn="function"==typeof SuppressedError?SuppressedError:function(e,t,s){var i=new Error(s);return i.name="SuppressedError",i.error=e,i.suppressed=t,i};function on(e){function t(t){e.error=e.hasError?new nn(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var s,i=0;return function a(){for(;s=e.stack.pop();)try{if(!s.async&&1===i)return i=0,e.stack.push(s),Promise.resolve().then(a);if(s.dispose){var r=s.dispose.call(s.value);if(s.async)return i|=2,Promise.resolve(r).then(a,(function(e){return t(e),a()}))}else i|=1}catch(e){t(e)}if(1===i)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}!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"}(Qr||(Qr={}));class hn extends wr{constructor(){super(...arguments),this.glyphs=null}get isEmpty(){return!this.glyphs||0===this.glyphs.length}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);let e=0;for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t];s.renderer=this.renderer,s.doLayout(),e=Math.max(e,s.width)}this.width=e}addGlyph(e){this.glyphs||(this.glyphs=[]),this.renderer&&(e.renderer=this.renderer),this.glyphs.push(e)}paint(e,t,s){const i=this.glyphs;if(i&&0!==i.length)for(const a of i)a.paint(e+this.x,t+this.y,s)}}class ln extends hn{constructor(){super(0,0),this.glyphs=[]}doLayout(){}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 cn{static score(e,t,s,i=!1){if(!s.style&&!i)return;const a=cn.scoreDefaultColor(e.settings.display.resources,t);return new dn(e,t,s.style,a)}static scoreColor(e,t,s){const i=cn.scoreDefaultColor(e,t);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static scoreDefaultColor(e,t){return e.mainGlyphColor}static bar(e,t,s,i=!1){if(!s.style&&!i)return;let a=e.settings.display.resources.mainGlyphColor;switch(t){case c.StandardNotationRepeats:case c.GuitarTabsRepeats:case c.SlashRepeats:case c.NumberedRepeats:case c.StandardNotationClef:case c.GuitarTabsClef:case c.StandardNotationKeySignature:case c.NumberedKeySignature:case c.StandardNotationTimeSignature:case c.GuitarTabsTimeSignature:case c.SlashTimeSignature:case c.NumberedTimeSignature:break;case c.StandardNotationBarSeparator:case c.GuitarTabsBarSeparator:case c.SlashBarSeparator:case c.NumberedBarSeparator:a=e.settings.display.resources.barSeparatorColor;break;case c.StandardNotationBarNumber:case c.SlashBarNumber:case c.NumberedBarNumber:case c.GuitarTabsBarNumber:a=e.settings.display.resources.barNumberColor;break;case c.StandardNotationStaffLine:case c.GuitarTabsStaffLine:case c.SlashStaffLine:case c.NumberedStaffLine:a=e.settings.display.resources.staffLineColor}return new dn(e,t,s.style,a)}static voice(e,t,s,i=!1){if(!s.style&&!i)return;const a=0===s.index?e.settings.display.resources.mainGlyphColor:e.settings.display.resources.secondaryGlyphColor;return new dn(e,t,s.style,a)}static trackColor(e,t,s){const i=cn.trackDefaultColor(e,t);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static trackDefaultColor(e,t){let s=e.mainGlyphColor;switch(t){case $e.TrackName:case $e.SystemSeparator:case $e.StringTuning:break;case $e.BracesAndBrackets:s=e.barSeparatorColor}return s}static track(e,t,s,i=!1){if(!s.style&&!i)return;const a=cn.trackDefaultColor(e.settings.display.resources,t);return new dn(e,t,s.style,a)}static beatColor(e,t,s){const i=cn.beatDefaultColor(e,t,s);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static beatDefaultColor(e,t,s){return 0===s.voice.index?e.mainGlyphColor:e.secondaryGlyphColor}static beat(e,t,s,i=!1){if(!s.style&&!i)return;const a=cn.beatDefaultColor(e.settings.display.resources,t,s);return new dn(e,t,s.style,a)}static noteColor(e,t,s){const i=cn.noteDefaultColor(e,t,s);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static noteDefaultColor(e,t,s){return 0===s.beat.voice.index?e.mainGlyphColor:e.secondaryGlyphColor}static note(e,t,s,i=!1){if(!s.style&&!i)return;const a=0===s.beat.voice.index?e.settings.display.resources.mainGlyphColor:e.settings.display.resources.secondaryGlyphColor;return new dn(e,t,s.style,a)}}class dn{constructor(e,t,s,i){this._canvas=e,s&&s.colors.has(t)?(this._previousColor=e.color,e.color=s.colors.get(t)??i):s||(this._previousColor=e.color,e.color=i)}[Symbol.dispose](){this._previousColor&&(this._canvas.color=this._previousColor)}}class un extends hn{constructor(e,t,s){super(e,t),this.voice=s,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){const t=this.renderer.layoutingInfo.spaceToForce(e);this.scaleToForce(t)}scaleToForce(e){this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e);const t=this.renderer.layoutingInfo.buildOnTimePositions(e),s=this.beatGlyphs;for(let e=0,i=s.length;e<i;e++){const a=s[e];if(a.beat.graceType===b.None)a.x=t.get(a.beat.absoluteDisplayStart)-a.onTimeX;else{const i=a.beat.graceGroup.beats[0].absoluteDisplayStart,r=a.beat.graceGroup.id;if(a.beat.graceGroup.isComplete&&t.has(i)){a.x=t.get(i)-a.onTimeX;const e=this.renderer.layoutingInfo.allGraceRods.get(r),s=a.beat.graceGroup.beats[a.beat.graceGroup.beats.length-1].nextBeat,n=s?this.renderer.layoutingInfo.getPreBeatSize(s)+vr.GraceBeatPadding:0;a.x-=n,a.x-=e[a.beat.graceIndex].postSpringWidth,a.x+=e[a.beat.graceIndex].graceBeatWidth;const o=e[a.beat.graceGroup.beats.length-1];a.x-=o.graceBeatWidth}else{const t=this.renderer.layoutingInfo.incompleteGraceRods.get(r),i=t[a.beat.graceIndex].postSpringWidth-t[a.beat.graceIndex].preSpringWidth;e>0?0===a.beat.graceIndex?a.x=s[e-1].x+s[e-1].width:a.x=s[e-1].x+t[a.beat.graceIndex-1].postSpringWidth-t[a.beat.graceIndex-1].preSpringWidth-i:a.x=-i}}if(e>0){const t=a.x-s[e-1].x;s[e-1].scaleToWidth(t)}if(e===i-1){const e=this.width-s[s.length-1].x;a.scaleToWidth(e)}}}registerLayoutingInfo(e){const t=this.beatGlyphs;for(const s of t)s.registerLayoutingInfo(e)}applyLayoutingInfo(e){const t=this.beatGlyphs;for(const s of t)s.applyLayoutingInfo(e);this.scaleToForce(Math.max(this.renderer.settings.display.stretchForce,e.minStretchForce))}addGlyph(e){const t=e;e.x=0===this.beatGlyphs.length?0:this.beatGlyphs[this.beatGlyphs.length-1].x+this.beatGlyphs[this.beatGlyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.beatGlyphs.push(t),this.width=e.x+e.width,t.beat.hasTuplet&&t.beat.tupletGroup.beats[0].id===t.beat.id&&this.tupletGroups.push(t.beat.tupletGroup)}doLayout(){}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.voice(s,$.Glyphs,this.voice,!0),!1);for(let i=0,a=this.beatGlyphs.length;i<a;i++)this.beatGlyphs[i].paint(e+this.x,t+this.y,s)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}un.KeySizeBeat="Beat";class pn{constructor(){this.staffId="",this.up=0,this.down=0}}class gn{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 mn{get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}hasLine(e,t){return e&&this.beatHasLine(t)||!e&&1===this.beats.length&&this.beatHasLine(t)}beatHasLine(e){return e.duration>f.Whole}hasFlag(e,t){return e&&this.beatHasFlag(t)||!e&&1===this.beats.length&&this.beatHasFlag(this.beats[0])}beatHasFlag(e){return!e.deadSlapped&&!e.isRest&&(e.duration>f.Quarter||e.graceType!==b.None)}constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=f.QuadrupleWhole,this.hasTuplet=!1,this.slashBeats=[],this._firstBeatLowestNoteCompareValue=-1,this._firstBeatHighestNoteCompareValue=-1,this._lastBeatLowestNoteCompareValue=-1,this._lastBeatHighestNoteCompareValue=-1,this.lowestNoteInHelper=null,this._lowestNoteCompareValueInHelper=-1,this.highestNoteInHelper=null,this._highestNoteCompareValueInHelper=-1,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isGrace=!1,this.minRestLine=null,this.beatOfMinRestLine=null,this.maxRestLine=null,this.beatOfMaxRestLine=null,this.direction=je.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}getBeatLineX(e,t){return t=t??this.direction,this.hasBeatLineX(e)?t===je.Up?this._beatLineXPositions.get(e.index).up:this._beatLineXPositions.get(e.index).down:0}hasBeatLineX(e){return this._beatLineXPositions.has(e.index)}registerBeatLineX(e,t,s,i){const a=this.getOrCreateBeatPositions(t);a.staffId=e,a.up=s,a.down=i;for(const e of this.drawingInfos.values())e.startBeat===t?e.startX=this.getBeatLineX(t):e.endBeat===t&&(e.endX=this.getBeatLineX(t))}getOrCreateBeatPositions(e){return this._beatLineXPositions.has(e.index)||this._beatLineXPositions.set(e.index,new pn),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(je.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==b.None)&&(e=this.invert(je.Up)):e=je.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){const t=this._renderer.getNoteY(this.highestNoteInHelper,en.Center),s=this._renderer.getNoteY(this.lowestNoteInHelper,en.Center);if(null===e){const i=(t+s)/2;e=this.invert(this._renderer.middleYPosition<i?je.Up:je.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(je.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case f.QuadrupleWhole:case f.DoubleWhole:return[2,2];case f.Whole:return[0,1];case f.Half:return[1,0];case f.Quarter:return[3,3];case f.Eighth:return[2,2];case f.Sixteenth:return[2,4];case f.ThirtySecond:return[4,4];case f.SixtyFourth:return[4,6];case f.OneHundredTwentyEighth:return[6,6];case f.TwoHundredFiftySixth:return[6,8]}return[0,0]}applyRest(e,t){if(this._lastNonRestBeat&&e.index>=this._lastNonRestBeat.index||this._firstNonRestBeat&&e.index<=this._firstNonRestBeat.index)return;let s=t,i=t;const a=mn.computeLineHeightsForRest(e.duration);s-=a[0],i+=a[1];const r=this.minRestLine,n=this.maxRestLine;(null===r||r>s)&&(this.minRestLine=s,this.beatOfMinRestLine=e),(null===n||n<i)&&(this.maxRestLine=i,this.beatOfMaxRestLine=e)}invert(e){return this.invertBeamDirection?e===je.Down?je.Up:je.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 J.Auto:case J.ForceSplitOnSecondaryToNext:t=mn.canJoin(this.beats[this.beats.length-1],e);break;case J.ForceSplitToNext:t=!1;break;case J.ForceMergeWithNext:t=!0}return t&&(null==this.preferredBeamDirection&&null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.hasTuplet&&(this.hasTuplet=!0),e.graceType!==b.None&&(this.isGrace=!0),e.isRest?0===this.beats.length&&this.beats.push(e):(this.isRestBeamHelper&&(this.beats=[]),this.beats.push(e),this.checkNote(e.minNote),this.checkNote(e.maxNote),this.shortestDuration<e.duration&&(this.shortestDuration=e.duration),this._firstNonRestBeat||(this._firstNonRestBeat=e),this._lastNonRestBeat=e),e.slashed&&this.slashBeats.push(e)),t}checkNote(e){if(!e)return;let t,s;this.voice&&e.isPercussion?(t=-Ci.getPercussionLine(this.voice.bar,Ci.getNoteValue(e)),s=t):(t=Ci.getNoteValue(e),s=t,e.harmonicType!==w.None&&e.harmonicType!==w.Natural&&(s=e.realValue-this._staff.displayTranspositionPitch)),1===this.beats.length&&this.beats[0]===e.beat&&((-1===this._firstBeatLowestNoteCompareValue||t<this._firstBeatLowestNoteCompareValue)&&(this._firstBeatLowestNoteCompareValue=t),(-1===this._firstBeatHighestNoteCompareValue||s>this._firstBeatHighestNoteCompareValue)&&(this._firstBeatHighestNoteCompareValue=s)),(-1===this._lastBeatLowestNoteCompareValue||t<this._lastBeatLowestNoteCompareValue)&&(this._lastBeatLowestNoteCompareValue=t),(-1===this._lastBeatHighestNoteCompareValue||s>this._lastBeatHighestNoteCompareValue)&&(this._lastBeatHighestNoteCompareValue=s),(!this.lowestNoteInHelper||t<this._lowestNoteCompareValueInHelper)&&(this.lowestNoteInHelper=e,this._lowestNoteCompareValueInHelper=t),(!this.highestNoteInHelper||s>this._highestNoteCompareValueInHelper)&&(this.highestNoteInHelper=e,this._highestNoteCompareValueInHelper=s)}static canJoin(e,t){if(!e||!t||e.graceType!==t.graceType||e.graceType===b.BendGrace||t.graceType===b.BendGrace||e.deadSlapped||t.deadSlapped)return!1;if(e.graceType!==b.None&&t.graceType!==b.None)return!0;const s=e.voice.bar;if(s!==t.voice.bar)return!1;const i=e.playbackStart,a=t.playbackStart;if(!mn.canJoinDuration(e.duration)||!mn.canJoinDuration(t.duration))return i===a;if(e.tupletGroup!==t.tupletGroup)return!1;if(e.hasTuplet&&t.hasTuplet&&e.tupletGroup===t.tupletGroup&&e.tupletGroup.isFull)return!0;let r=se.QuarterTime;if(8===s.masterBar.timeSignatureDenominator)s.masterBar.timeSignatureNumerator%3==0&&(r+=se.QuarterTime/2|0);return((r+i)/r|0)===((r+a)/r|0)}static canJoinDuration(e){switch(e){case f.Whole:case f.Half:case f.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,s){return ue.getIndex(e.duration)-2-s>0&&ue.getIndex(t.duration)-2-s>0}get beatOfLowestNote(){return this.lowestNoteInHelper.beat}get beatOfHighestNote(){return this.highestNoteInHelper.beat}isPositionFrom(e,t){return!this._beatLineXPositions.has(t.index)||(this._beatLineXPositions.get(t.index).staffId===e||!this._beatLineXPositions.get(t.index).staffId)}}class fn{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class yn{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new fn(e,t)),-1e3===this.topY)this.topY=e,this.bottomY=t;else{const s=Math.min(e,t),i=Math.max(e,t);s<this.topY&&(this.topY=s),i>this.bottomY&&(this.bottomY=i)}}}class bn{constructor(){this.reservedLayoutAreasByDisplayTime=new Map,this.restDurationsByDisplayTime=new Map}getBeatMinMaxY(){let e=-1e3,t=-1e3;for(const s of this.reservedLayoutAreasByDisplayTime.values())-1e3===e?(e=s.topY,t=s.bottomY):(e>s.topY&&(e=s.topY),t<s.bottomY&&(t=s.bottomY));return-1e3===e?[0,0]:[e,t]}reserveBeatSlot(e,t,s){t!==s&&(this.reservedLayoutAreasByDisplayTime.has(e.displayStart)||this.reservedLayoutAreasByDisplayTime.set(e.displayStart,new yn(e)),this.reservedLayoutAreasByDisplayTime.get(e.displayStart).addSlot(t,s),e.isRest&&this.registerRest(e))}registerRest(e){this.restDurationsByDisplayTime.has(e.displayStart)||this.restDurationsByDisplayTime.set(e.displayStart,new Map),this.restDurationsByDisplayTime.get(e.displayStart).has(e.playbackDuration)||this.restDurationsByDisplayTime.get(e.displayStart).set(e.playbackDuration,e.id)}applyRestCollisionOffset(e,t,s){if(e.voice.index>0&&this.reservedLayoutAreasByDisplayTime.has(e.playbackStart)){const i=mn.computeLineHeightsForRest(e.duration).map((e=>e*s)),a=t-i[0],r=t+i[1];let n=a;const o=this.reservedLayoutAreasByDisplayTime.get(e.playbackStart);let h=!1;for(const e of o.slots)if(a>=e.topY&&a<=e.bottomY||r>=e.topY&&r<=e.bottomY){h=!0;break}if(h){n=1===e.voice.index?o.topY-i[1]-i[0]:o.bottomY;const t=n+i[0]+i[1],r=2*s,h=Math.ceil(Math.abs(n-a)/r);return o.addSlot(n,t),n<a?h*-r:h*r}}return 0}}class Sn{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this.preferredBeamDirection=null,this._renderer=e,this.collisionHelper=new bn}initialize(){const e=this._renderer,t=this._renderer.bar;let s=null,i=null;for(let a=0,r=t.voices.length;a<r;a++){const r=t.voices[a];this.beamHelpers.push([]),this.beamHelperLookup.push(new Map);for(let a=0,n=r.beats.length;a<n;a++){const n=r.beats[a];let o;n.graceType!==b.None?o=i:(o=s,i=null),o&&o.checkBeat(n)||(o&&o.finish(),o=new mn(t.staff,e),o.preferredBeamDirection=this.preferredBeamDirection,o.checkBeat(n),n.graceType!==b.None?i=o:s=o,this.beamHelpers[r.index].push(o)),this.beamHelperLookup[r.index].set(n.index,o)}s&&s.finish(),i&&i.finish(),s=null,i=null}}getBeamingHelperForBeat(e){return this.beamHelperLookup[e.voice.index].get(e.index)}}class _n extends Br{constructor(e,t,s){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=s}doLayout(){super.doLayout();const e=this.renderer.resources;this._textRow=1.5*e.effectFont.size,this._fretRow=1.5*e.effectFont.size,this._chord.firstFret>1?this._firstFretSpacing=_n.FretSpacing:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+_n.Frets*_n.FretSpacing+2*_n.Padding[1],this.width=this._firstFretSpacing+(this._chord.strings.length-1)*_n.StringSpacing+2*_n.Padding[0]}paint(e,t,s){e+=this.x+_n.Padding[0]+this._firstFretSpacing,t+=this.y;const i=_n.StringSpacing,a=_n.FretSpacing,r=this.renderer.resources,n=_n.CircleRadius,o=this.width-2*_n.Padding[0]-this._firstFretSpacing,h=s.textAlign,l=s.textBaseline;s.font=r.effectFont,s.textAlign=A.Center,s.textBaseline=R.Top,this._chord.showName&&s.fillText(this._chord.name,e+o/2,t+r.effectFont.size/2),t+=this._textRow,s.font=r.fretboardNumberFont,s.textBaseline=R.Middle;for(let a=0;a<this._chord.strings.length;a++){const r=e+a*i,n=t+this._fretRow/2;let o=this._chord.strings[this._chord.strings.length-a-1];o<0?s.fillMusicFontSymbol(r,n,1,I.FretboardX,!0):0===o?s.fillMusicFontSymbol(r,n,1,I.FretboardO,!0):(o-=this._chord.firstFret-1,s.fillText(o.toString(),r,n))}t+=this._fretRow;for(let r=0;r<this._chord.strings.length;r++){const n=e+r*i;s.fillRect(n,t,1,a*_n.Frets+1)}this._chord.firstFret>1&&(s.textAlign=A.Left,s.fillText(this._chord.firstFret.toString(),e-this._firstFretSpacing,t+a/2)),s.fillRect(e,t-1,o,2);for(let i=0;i<=_n.Frets;i++){const r=t+i*a;s.fillRect(e,r,o,1)}const c=new Map;for(const e of this._chord.barreFrets){const t=[-1,-1];c.set(e-this._chord.firstFret,t)}for(let r=0;r<this._chord.strings.length;r++){let o=this._chord.strings[r];if(o>0){if(o-=this._chord.firstFret,c.has(o)){const e=c.get(o);(-1===e[0]||r<e[0])&&(e[0]=r),(-1===e[1]||r>e[1])&&(e[1]=r)}const h=t+o*a+a/2+.5,l=e+(this._chord.strings.length-r-1)*i;s.fillCircle(l,h,n)}}for(const[r,o]of c){const h=t+r*a+a/2+.5,l=e+(this._chord.strings.length-o[1]-1)*i,c=e+(this._chord.strings.length-o[0]-1)*i;s.fillRect(l,h-n,c-l,2*n)}s.textAlign=h,s.textBaseline=l}}_n.Padding=[5,2],_n.Frets=5,_n.CircleRadius=2.5,_n.StringSpacing=10,_n.FretSpacing=12;class wn extends hn{constructor(e,t,s=A.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=s}doLayout(){let e=0;switch(this._align){case A.Left:e=0;break;case A.Center:e=(this.width-this._glyphWidth)/2;break;case A.Right:e=this.width-this._glyphWidth}for(const 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 Bn extends hn{constructor(e,t,s=A.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=s}doLayout(){let e=0,t=0;const s=Bn.Padding;this._rows=[];let i=new wn(e,t,this._align);i.width=this.width;for(const a of this.glyphs)e+a.width<this.width?(i.addGlyphToRow(a),e+=a.width):(i.isEmpty||(i.doLayout(),this._rows.push(i),t+=i.height+s),e=0,i=new wn(e,t,this._align),i.width=this.width,i.addGlyphToRow(a),e+=a.width);i.isEmpty||(i.doLayout(),this._rows.push(i),t+=i.height+s),this.height=t}paint(e,t,s){for(const i of this._rows)i.paint(e+this.x,t+this.y,s)}}Bn.Padding=3;class kn extends Bn{addChord(e){if(e.strings.length>0){const t=new _n(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}paint(e,t,s){if(this.glyphs.length>0){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.score(s,Je.ChordDiagramList,this.renderer.scoreRenderer.score),!1);super.paint(e,t,s)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}}class Tn extends Br{constructor(e,t,s,i,a=A.Left,r=null,n){super(e,t),this._lineHeights=null,this._lines=s.split("\n"),this.font=i,this.textAlign=a,this.textBaseline=r,this.colorOverride=n}doLayout(){super.doLayout(),this._lineHeights=[];const e=this.renderer.scoreRenderer.canvas;for(const t of this._lines){e.font=this.font;const s=e.measureText(t),i=s.height;this._lineHeights.push(i),this.height+=i,this.width=Math.max(this.width,s.width)}}paint(e,t,s){const i=s.color;s.color=this.colorOverride??i,s.font=this.font;const a=s.textAlign,r=s.textBaseline;s.textAlign=this.textAlign,null!==this.textBaseline&&(s.textBaseline=this.textBaseline);let n=t+this.y;for(let t=0;t<this._lines.length;t++)s.fillText(this._lines[t],e+this.x,n),n+=this._lineHeights[t];s.textAlign=a,s.textBaseline=r,s.color=i}}class Nn{get staveId(){return this._factory.staffId}get contentTop(){return this.y+this.staveTop+this.topSpacing+this.topOverflow}get contentBottom(){return this.y+this.topSpacing+this.topOverflow+this.staveBottom}constructor(e,t,s){this._sharedLayoutData=new Map,this.barRenderers=[],this.x=0,this.y=0,this.height=0,this.index=0,this.staffIndex=0,this.isFirstInSystem=!1,this.trackIndex=0,this.staveTop=0,this.topSpacing=0,this.bottomSpacing=0,this.staveBottom=0,this._factory=s,this.trackIndex=e,this.modelStaff=t}getSharedLayoutData(e,t){return this._sharedLayoutData.has(e)?this._sharedLayoutData.get(e):t}setSharedLayoutData(e,t){this._sharedLayoutData.set(e,t)}get isInsideBracket(){return this._factory.isInsideBracket}get isRelevantForBoundsLookup(){return this._factory.isRelevantForBoundsLookup}registerStaffTop(e){this.staveTop=e}registerStaffBottom(e){this.staveBottom=e}addBarRenderer(e){e.staff=this,e.index=this.barRenderers.length,e.reLayout(),this.barRenderers.push(e),this.system.layout.registerBarRenderer(this.staveId,e)}addBar(e,t,s){const i=this._factory.create(this.system.layout.renderer,e);i.additionalMultiRestBars=s,i.staff=this,i.index=this.barRenderers.length,i.layoutingInfo=t,i.doLayout(),i.registerLayoutingInfo();const a=i.barDisplayWidth;a>0&&this.system.layout.systemsLayoutMode===Zr.FromModelWithWidths&&(i.width=a),this.barRenderers.push(i),e&&this.system.layout.registerBarRenderer(this.staveId,i)}revertLastBar(){const e=this.barRenderers[this.barRenderers.length-1];this.barRenderers.splice(this.barRenderers.length-1,1),this.system.layout.unregisterBarRenderer(this.staveId,e);for(const e of this.barRenderers)e.applyLayoutingInfo();return e}scaleToWidth(e){this._sharedLayoutData=new Map;const t=this.topOverflow;let s=0;switch(this.system.layout.systemsLayoutMode){case Zr.Automatic:const i=(e-this.system.computedWidth)/this.barRenderers.length;for(const e of this.barRenderers){e.x=s,e.y=this.topSpacing+t;const a=e.computedWidth+i;e.scaleToWidth(a),s+=e.width}break;case Zr.FromModelWithScale:e-=this.system.accoladeWidth;const a=this.system.totalBarDisplayScale;for(const i of this.barRenderers){i.x=s,i.y=this.topSpacing+t;const r=i.barDisplayScale*e/a;i.scaleToWidth(r),s+=i.width}break;case Zr.FromModelWithWidths:for(const e of this.barRenderers){e.x=s,e.y=this.topSpacing+t;const i=e.barDisplayWidth;i>0?e.scaleToWidth(i):e.scaleToWidth(e.computedWidth),s+=e.width}}}get topOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){const s=this.barRenderers[t];s.topOverflow>e&&(e=s.topOverflow)}return e}get bottomOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){const s=this.barRenderers[t];s.bottomOverflow>e&&(e=s.bottomOverflow)}return e}calculateHeightForAccolade(){this.topSpacing=this._factory.getStaffPaddingTop(this),this.bottomSpacing=this._factory.getStaffPaddingBottom(this),this.height=this.barRenderers.length>0?this.barRenderers[0].height:0,this.height>0&&(this.height+=this.topSpacing+this.topOverflow+this.bottomOverflow+this.bottomSpacing)}finalizeStaff(){this.topSpacing=this._factory.getStaffPaddingTop(this),this.bottomSpacing=this._factory.getStaffPaddingBottom(this),this.height=0;let e=!1,t=this.topOverflow;for(let s=0;s<this.barRenderers.length;s++)this.barRenderers[s].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[s].height),this.barRenderers[s].finalizeRenderer()&&(e=!0);if(e){t=this.topOverflow;for(let e=0;e<this.barRenderers.length;e++)this.barRenderers[e].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[e].height),this.barRenderers[e].finalizeRenderer()}this.height>0&&(this.height+=this.topSpacing+t+this.bottomOverflow+this.bottomSpacing)}paint(e,t,s,i,a){if(0!==this.height&&0!==a)for(let r=i,n=Math.min(i+a,this.barRenderers.length);r<n;r++)this.barRenderers[r].paint(e+this.x,t+this.y,s)}}class xn{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 vn{constructor(){this._timeSortedSprings=[],this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,this._minDuration=vn.MinDuration,this.version=0,this.preBeatSize=0,this.postBeatSize=0,this.minStretchForce=0,this.totalSpringConstant=0,this.incompleteGraceRods=new Map,this.allGraceRods=new Map,this.springs=new Map,this.height=0}updateMinStretchForce(e){this.minStretchForce<e&&(this.minStretchForce=e)}getPreBeatSize(e){if(e.graceType!==b.None){const t=e.graceGroup.id;return this.allGraceRods.get(t)[e.graceIndex].preBeatWidth}const t=e.absoluteDisplayStart;return this.springs.has(t)?this.springs.get(t).preBeatWidth:0}getPostBeatSize(e){if(e.graceType!==b.None){const t=e.graceGroup.id;return this.allGraceRods.get(t)[e.graceIndex].postSpringWidth}const t=e.absoluteDisplayStart;return this.springs.has(t)?this.springs.get(t).postSpringWidth:0}addSpring(e,t,s,i,a){let r;if(this.version++,this.springs.has(e))r=this.springs.get(e),r.postSpringWidth<a&&(r.postSpringWidth=a),r.graceBeatWidth<s&&(r.graceBeatWidth=s),r.preBeatWidth<i&&(r.preBeatWidth=i),t<r.smallestDuration&&(r.smallestDuration=t),t>r.longestDuration&&(r.longestDuration=t),r.allDurations.add(t);else{if(r=new xn,r.timePosition=e,r.allDurations.add(t),this._timeSortedSprings.length>0){const e=this._timeSortedSprings[this._timeSortedSprings.length-1];for(const t of e.allDurations)e.timePosition;t<this._minDuration&&(this._minDuration=t)}r.longestDuration=t,r.postSpringWidth=a,r.graceBeatWidth=s,r.preBeatWidth=i,this.springs.set(e,r);const n=this._timeSortedSprings;let o=n.length-1;for(;o>0&&n[o].timePosition>e;)o--;this._timeSortedSprings.splice(o+1,0,r)}return(-1===this._minTime||this._minTime>e)&&(this._minTime=e),r}addBeatSpring(e,t,s){const i=e.absoluteDisplayStart;if(e.graceType!==b.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));const r=this.allGraceRods.get(a)[e.graceIndex];if(r)r.postSpringWidth<s&&(r.postSpringWidth=s),r.preBeatWidth<t&&(r.preBeatWidth=t);else{const r=new xn;r.timePosition=i,r.postSpringWidth=s,r.preBeatWidth=t,e.graceGroup.isComplete||(this.incompleteGraceRods.get(a)[e.graceIndex]=r),this.allGraceRods.get(a)[e.graceIndex]=r}}else{let a=0;if(e.graceGroup&&this.allGraceRods.has(e.graceGroup.id))for(const t of this.allGraceRods.get(e.graceGroup.id))a+=t.springWidth;this.addSpring(i,e.displayDuration,a,t,s)}}finish(){for(const[e,t]of this.allGraceRods){let e=0;for(const s of t)e+=s.preBeatWidth,s.graceBeatWidth=e,e+=s.postSpringWidth}this._incompleteGraceRodsWidth=0;for(const e of this.incompleteGraceRods.values())for(const t of e)this._incompleteGraceRodsWidth+=t.preBeatWidth+t.postSpringWidth;this.calculateSpringConstants(),this.version++}calculateSpringConstants(){let e=0;const t=this._timeSortedSprings;if(0===t.length)return this.totalSpringConstant=-1,void(this.minStretchForce=-1);for(let s=0;s<t.length;s++){const i=t[s];let a=0;if(s===t.length-1)a=i.longestDuration;else{const e=t[s+1];a=Math.abs(e.timePosition-i.timePosition)}i.springConstant=this.calculateSpringConstant(i,a),e+=1/i.springConstant}this.totalSpringConstant=1/e,this.minStretchForce=0;for(let e=0;e<t.length;e++){const s=t[e];let i=0;if(e===t.length-1)i=s.postSpringWidth;else{const a=t[e+1];i=s.postSpringWidth+a.preSpringWidth}0===e&&(i+=s.preSpringWidth);const a=i*s.springConstant;this.updateMinStretchForce(a)}}paint(e,t,s){}calculateSpringConstant(e,t){t<=0&&(t=se.toTicks(f.TwoHundredFiftySixth)),0===e.smallestDuration&&(e.smallestDuration=t);const s=e.smallestDuration,i=this._minDuration,a=vn.MinDurationWidth;return s/t*(1/((1+.85*Math.log2(t/i))*a))}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(ue.isAlmostEqualTo(this._onTimePositionsForce,e)&&this._onTimePositions)return this._onTimePositions;this._onTimePositionsForce=e;const t=new Map;this._onTimePositions=t;const s=this._timeSortedSprings;if(0===s.length)return t;let i=s[0].preSpringWidth;for(let a=0;a<s.length;a++)t.set(s[a].timePosition,i),i+=this.calculateWidth(e,s[a].springConstant);return t}}vn.MinDuration=30,vn.MinDurationWidth=7;class Pn{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.additionalMultiBarRestIndexes=null,this.renderers=[]}get lastMasterBarIndex(){return this.additionalMultiBarRestIndexes?this.additionalMultiBarRestIndexes[this.additionalMultiBarRestIndexes.length-1]:this.masterBar.index}}class Cn{constructor(e,t){this.staves=[],this.stavesRelevantForBoundsLookup=[],this.firstStaffInBracket=null,this.lastStaffInBracket=null,this.bracket=null,this.staffSystem=e,this.track=t}addStaff(e){this.staves.push(e),e.isRelevantForBoundsLookup&&this.stavesRelevantForBoundsLookup.push(e)}}class En{constructor(){this.firstStaffInBracket=null,this.lastStaffInBracket=null,this.drawAsBrace=!1,this.braceScale=1,this.width=0,this.index=0}finalizeBracket(){if(this.firstStaffInBracket===this.lastStaffInBracket)return void(this.width=0);const e=kr.Heights.get(I.Brace),t=kr.Widths.get(I.Brace);if(this.width=t,!this.drawAsBrace||!this.firstStaffInBracket||!this.lastStaffInBracket)return;const s=this.firstStaffInBracket.contentTop,i=(this.lastStaffInBracket.contentBottom-s)/e;this.braceScale=i,this.width=t*this.braceScale}}class Fn extends En{constructor(e){super(),this.track=e,this.drawAsBrace=Fn.isTrackDrawAsBrace(e)}includesStaff(e){return e.modelStaff.track===this.track}static isTrackDrawAsBrace(e){return e.staves.filter((e=>e.showStandardNotation)).length>1}}class Dn extends Fn{includesStaff(e){return e.modelStaff.track===this.track||!this.drawAsBrace&&this.track.playbackInfo.program===e.modelStaff.track.playbackInfo.program}}class Mn{constructor(e){this._allStaves=[],this._firstStaffInBrackets=null,this._lastStaffInBrackets=null,this._accoladeSpacingCalculated=!1,this._brackets=[],this._hasSystemSeparator=!1,this.x=0,this.y=0,this.index=0,this.accoladeWidth=0,this.isFull=!1,this.width=0,this.computedWidth=0,this.totalBarDisplayScale=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[],this.layout=e,this.topPadding=e.renderer.settings.display.systemPaddingTop,this.bottomPadding=e.renderer.settings.display.systemPaddingBottom}get firstBarIndex(){return this.masterBarsRenderers[0].masterBar.index}get lastBarIndex(){return this.masterBarsRenderers[this.masterBarsRenderers.length-1].masterBar.index}addMasterBarRenderers(e,t){if(0===e.length)return null;this.masterBarsRenderers.push(t),t.layoutingInfo.preBeatSize=0;let s=0;for(let e=0,i=this.staves.length;e<i;e++){const i=this.staves[e];for(let e=0,a=i.staves.length;e<a;e++){const a=i.staves[e],r=t.renderers[s++];a.addBarRenderer(r)}}return this.calculateAccoladeSpacing(e),this.updateWidthFromLastBar(),t}addBars(e,t,s){const i=new Pn;i.additionalMultiBarRestIndexes=s,i.layoutingInfo=new vn,i.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(i);const a=i.layoutingInfo;for(const e of this.staves)for(const r of e.staves){const n=e.track.staves[r.modelStaff.index].bars[t],o=null==s?null:s.map((t=>e.track.staves[r.modelStaff.index].bars[t]));r.addBar(n,a,o);const h=r.barRenderers[r.barRenderers.length-1];i.renderers.push(h),h.isLinkedToPrevious&&(i.isLinkedToPrevious=!0),h.canWrap||(i.canWrap=!1)}return this.calculateAccoladeSpacing(e),a.finish(),i.width=this.updateWidthFromLastBar(),i}revertLastBar(){if(this.masterBarsRenderers.length>1){const e=this.masterBarsRenderers[this.masterBarsRenderers.length-1];this.masterBarsRenderers.splice(this.masterBarsRenderers.length-1,1);let t=0,s=0;for(let e=0,i=this._allStaves.length;e<i;e++){const i=this._allStaves[e].revertLastBar(),a=i.computedWidth;a>t&&(t=a);const r=i.barDisplayScale;r>s&&(s=r)}return this.width-=t,this.computedWidth-=t,this.totalBarDisplayScale-=s,e}return null}updateWidthFromLastBar(){let e=0,t=0;for(let s=0,i=this._allStaves.length;s<i;s++){const i=this._allStaves[s],a=i.barRenderers[i.barRenderers.length-1];a.applyLayoutingInfo(),a.computedWidth>e&&(e=a.computedWidth);const r=a.barDisplayScale;r>t&&(t=r)}return this.width+=e,this.computedWidth+=e,this.totalBarDisplayScale+=t,e}calculateAccoladeSpacing(e){const t=this.layout.renderer.settings;if(!this._accoladeSpacingCalculated){this._accoladeSpacingCalculated=!0,this.accoladeWidth=0;const s=this.layout.renderer.score.stylesheet;if(this.layout.renderer.settings.notation.isNotationElementVisible(C.TrackNames)){const n=1===this.layout.renderer.tracks.length?s.singleTrackTrackNamePolicy:s.multiTrackTrackNamePolicy,o=0===this.index?s.firstSystemTrackNameMode:s.otherSystemsTrackNameMode,h=0===this.index?s.firstSystemTrackNameOrientation:s.otherSystemsTrackNameOrientation;let l=!1;switch(n){case i.Hidden:break;case i.FirstSystem:l=0===this.index;break;case i.AllSystems:l=!0}let c=!1;if(l){const s=this.layout.renderer.canvas,i=t.display.resources.effectFont;s.font=i;for(const t of e){let e="";switch(o){case a.FullName:e=t.name;break;case a.ShortName:e=t.shortName}if(e.length>0){c=!0;const t=s.measureText(e);switch(h){case r.Horizontal:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,t.width));break;case r.Vertical:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,t.height))}}}c&&(this.accoladeWidth+=t.display.systemLabelPaddingLeft,this.accoladeWidth+=t.display.systemLabelPaddingRight)}}let n=0;for(const e of this._allStaves)e.y=n,e.calculateHeightForAccolade(),n+=e.height;let o=0;for(const e of this._brackets)e.finalizeBracket(),o=Math.max(o,e.width);this.accoladeWidth+=o,this.width+=this.accoladeWidth,this.computedWidth+=this.accoladeWidth}}getStaffTrackGroup(e){for(let t=0,s=this.staves.length;t<s;t++){const s=this.staves[t];if(s.track===e)return s}return null}addStaff(e,t){let i=this.getStaffTrackGroup(e);if(i||(i=new Cn(this,e),this.staves.push(i)),t.staffTrackGroup=i,t.system=this,t.index=this._allStaves.length,this._allStaves.push(t),i.addStaff(t),t.isInsideBracket){this._firstStaffInBrackets||(this._firstStaffInBrackets=t,t.isFirstInSystem=!0),i.firstStaffInBracket||(i.firstStaffInBracket=t),this._lastStaffInBrackets=t,i.lastStaffInBracket=t;let a=this._brackets.find((e=>e.includesStaff(t)));if(!a)switch(e.score.stylesheet.bracketExtendMode){case s.NoBrackets:break;case s.GroupStaves:a=new Fn(e),a.index=this._brackets.length,this._brackets.push(a);break;case s.GroupSimilarInstruments:a=new Dn(e),a.index=this._brackets.length,this._brackets.push(a)}a&&(a.firstStaffInBracket||(a.firstStaffInBracket=t),a.lastStaffInBracket=t,i.bracket=a)}}get height(){return 0===this._allStaves.length?0:this._allStaves[this._allStaves.length-1].y+this._allStaves[this._allStaves.length-1].height+this.topPadding+this.bottomPadding}scaleToWidth(e){for(let t=0,s=this._allStaves.length;t<s;t++)this._allStaves[t].scaleToWidth(e);this.width=e}paint(e,t,s){if(t+=this.topPadding,this.paintPartial(e+this.x,t+this.y,s,0,this.masterBarsRenderers.length),this._hasSystemSeparator){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.track(s,$e.SystemSeparator,this._allStaves[0].modelStaff.track),!1);s.fillMusicFontSymbol(e+this.x,t+this.y+this.height-10,1,I.SystemDivider,!1),s.fillMusicFontSymbol(e+this.x+this.width-Mn.SystemSignSeparatorWidth,t+this.y+this.height-Mn.SystemSignSeparatorPadding,1,I.SystemDivider,!1)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}paintPartial(e,t,s,n,o){for(let i=0,a=this._allStaves.length;i<a;i++)this._allStaves[i].paint(e,t,s,n,o);const h=this.layout.renderer.settings.display.resources;if(this.staves.length>0&&0===n){const n={stack:[],error:void 0,hasError:!1};try{s.color=h.barSeparatorColor;const o=this._firstStaffInBrackets,l=this._lastStaffInBrackets,c=this.layout.renderer.settings,d=this.layout.renderer.settings.notation.isNotationElementVisible(C.TrackNames);if(s.font=h.effectFont,d){const n=this.layout.renderer.score.stylesheet,o=1===this.layout.renderer.tracks.length?n.singleTrackTrackNamePolicy:n.multiTrackTrackNamePolicy,h=0===this.index?n.firstSystemTrackNameMode:n.otherSystemsTrackNameMode,l=0===this.index?n.firstSystemTrackNameOrientation:n.otherSystemsTrackNameOrientation;let d=!1;switch(o){case i.Hidden:break;case i.FirstSystem:d=0===this.index;break;case i.AllSystems:d=!0}if(d){const i=s.textBaseline,n=s.textAlign;for(const i of this.staves)if(i.firstStaffInBracket&&i.lastStaffInBracket){const n={stack:[],error:void 0,hasError:!1};try{const o=t+i.firstStaffInBracket.contentTop,d=t+i.lastStaffInBracket.contentBottom;let u="";switch(h){case a.FullName:u=i.track.name;break;case a.ShortName:u=i.track.shortName}jr(n,cn.track(s,$e.TrackName,i.track),!1);if(u.length>0){const t=e+i.firstStaffInBracket.x-c.display.accoladeBarPaddingRight-(i.bracket?.width??0)-c.display.systemLabelPaddingRight;switch(l){case r.Horizontal:s.textBaseline=R.Middle,s.textAlign=A.Right,s.fillText(u,t,(o+d)/2);break;case r.Vertical:s.textBaseline=R.Bottom,s.textAlign=A.Center;const e=.1;s.beginRotate(t,(o+d)/2,-90-e),s.fillText(u,0,0),s.endRotate()}}}catch(e){n.error=e,n.hasError=!0}finally{on(n)}}s.textBaseline=i,s.textAlign=n}}jr(n,cn.track(s,$e.BracesAndBrackets,this.staves[0].track),!1);if(o&&l){const i=t+o.contentTop,a=t+l.contentBottom,r=e+o.x;s.beginPath(),s.moveTo(r,i),s.lineTo(r,a),s.stroke()}for(const i of this._brackets)if(i.firstStaffInBracket&&i.lastStaffInBracket){const a=e+i.firstStaffInBracket.x,r=i.width,n=c.display.accoladeBarPaddingRight,o=t+i.firstStaffInBracket.contentTop,h=t+i.lastStaffInBracket.contentBottom;let l=o,d=h;if(i.drawAsBrace)s.fillMusicFontSymbol(a-n-r,d,i.braceScale,I.Brace);else if(i.firstStaffInBracket!==i.lastStaffInBracket){const e=r/2;l-=e,d+=2*e,s.fillRect(a-n-r,l,r,Math.ceil(d-l));const t=a-n-r-.5;s.fillMusicFontSymbol(t,l,1,I.BracketTop),s.fillMusicFontSymbol(t,Math.floor(d),1,I.BracketBottom)}}}catch(e){n.error=e,n.hasError=!0}finally{on(n)}}}finalizeSystem(){const e=this.layout.renderer.settings;0===this.index&&(this.topPadding=e.display.firstSystemPaddingTop),this.isLast?this.bottomPadding=e.display.lastSystemPaddingBottom:this.layout.renderer.score.stylesheet.useSystemSignSeparator&&this.layout.renderer.tracks.length>1&&(this.bottomPadding+=Mn.SystemSignSeparatorHeight,this._hasSystemSeparator=!0);let t=0;for(const e of this._allStaves)e.x=this.accoladeWidth,e.y=t,e.finalizeStaff(),t+=e.height;for(const e of this._brackets)e.finalizeBracket()}buildBoundingsLookup(e,t){if(this.layout.renderer.boundsLookup.isFinished)return;const s=this._firstStaffInBrackets,i=this._lastStaffInBrackets;if(!s||!i)return;t+=this.topPadding;const a=this._allStaves[this._allStaves.length-1],r=t+this.y+s.y,n=t+this.y+i.y+i.height,o=t+this.y+this._allStaves[0].y,h=t+this.y+a.y+a.height,l=t+this.y+s.y+s.topSpacing+s.topOverflow+(s.barRenderers.length>0?s.barRenderers[0].topPadding:0),c=n-r,d=t+this.y+a.y+a.height-a.bottomSpacing-a.bottomOverflow-(a.barRenderers.length>0?a.barRenderers[0].bottomPadding:0)-l,u=h-o,p=this.x+s.x,g=new Ti;g.visualBounds=new Is,g.visualBounds.x=e+this.x,g.visualBounds.y=t+this.y,g.visualBounds.w=this.width,g.visualBounds.h=this.height-this.topPadding-this.bottomPadding,g.realBounds=new Is,g.realBounds.x=e+this.x,g.realBounds.y=t+this.y,g.realBounds.w=this.width,g.realBounds.h=this.height,this.layout.renderer.boundsLookup.addStaffSystem(g);const m=new Map;for(let e=0;e<this.staves.length;e++)for(const s of this.staves[e].stavesRelevantForBoundsLookup)for(const e of s.barRenderers){let i;m.has(e.bar.masterBar.index)?i=m.get(e.bar.masterBar.index):(i=new Bi,i.index=e.bar.masterBar.index,i.isFirstOfLine=e.isFirstOfLine,i.realBounds=new Is,i.realBounds.x=p+e.x,i.realBounds.y=o,i.realBounds.w=e.width,i.realBounds.h=u,i.visualBounds=new Is,i.visualBounds.x=p+e.x,i.visualBounds.y=r,i.visualBounds.w=e.width,i.visualBounds.h=c,i.lineAlignedBounds=new Is,i.lineAlignedBounds.x=p+e.x,i.lineAlignedBounds.y=l,i.lineAlignedBounds.w=e.width,i.lineAlignedBounds.h=d,this.layout.renderer.boundsLookup.addMasterBar(i),m.set(i.index,i)),e.buildBoundingsLookup(i,p,t+this.y+s.y)}}getBarX(e){if(!this._firstStaffInBrackets||0===this.layout.renderer.tracks.length)return 0;const t=this.layout.renderer.tracks[0].staves[0].bars[e];return this.layout.getRendererForBar(this._firstStaffInBrackets.staveId,t).x}}Mn.SystemSignSeparatorHeight=40,Mn.SystemSignSeparatorPadding=10,Mn.SystemSignSeparatorWidth=36;class Ln extends Bn{constructor(e,t){super(e,t,A.Left)}}class In extends hn{constructor(e,t,s,i){super(e,t),this._tuning=s,this._trackLabel=i,this.glyphs=[]}doLayout(){if(!(this.glyphs.length>0)){this.createGlyphs(this._tuning);for(const e of this.glyphs)e.renderer=this.renderer,e.doLayout()}}paint(e,t,s){s.textBaseline=R.Middle;const i=s.color;this.colorOverride&&(s.color=this.colorOverride),super.paint(e,t,s),s.color=i}createGlyphs(e){const t=this.renderer.resources;this.height=0;if(this._trackLabel.length>0){const e=new Tn(0,this.height,this._trackLabel,t.effectFont,A.Left);e.renderer=this.renderer,e.doLayout(),this.height+=e.height,e.y+=e.height/2,this.addGlyph(e)}const s=new Tn(0,this.height,e.name,t.effectFont,A.Left);s.renderer=this.renderer,s.doLayout(),this.height+=s.height,s.y+=s.height/2,this.addGlyph(s);if(this.renderer.scoreRenderer.canvas.font=t.effectFont,this.width=Math.max(this.renderer.scoreRenderer.canvas.measureText(this._trackLabel).width,Math.max(this.renderer.scoreRenderer.canvas.measureText(e.name).width,128)),!e.isStandard){this.height+=15;const s=In.CircleNumberScale,i=kr.Heights.get(I.GuitarString0)*s,a=0|Math.ceil(e.tunings.length/2);let r=0,n=this.height;for(let o=0,h=e.tunings.length;o<h;o++){const h=I.GuitarString0+(o+1);this.addGlyph(new Tr(r,n+i/2.5,s,h));const l=`= ${ft.getTextForTuning(e.tunings[o],!1)}`;this.addGlyph(new Tn(r+i+1,n,l,t.effectFont,A.Left)),n+=15,o===a-1&&(n=this.height,r+=64)}this.height+=15*a}this.width+=15}}In.CircleNumberScale=.7;class An{constructor(e,t){this.args=e,this.renderCallback=t}}!function(e){e[e.Automatic=0]="Automatic",e[e.FromModelWithScale=1]="FromModelWithScale",e[e.FromModelWithWidths=2]="FromModelWithWidths"}(Zr||(Zr={}));class Rn{get scaledWidth(){return Math.round(this.width/this.renderer.settings.display.scale)}constructor(e){this._barRendererLookup=new Map,this.pagePadding=null,this.width=0,this.height=0,this.multiBarRestInfo=null,this.headerGlyphs=new Map,this.footerGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this.systemsLayoutMode=Zr.Automatic,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();const e=this.renderer.score;this.firstBarIndex=ue.computeFirstDisplayedBarIndex(e,this.renderer.settings),this.lastBarIndex=ue.computeLastDisplayedBarIndex(e,this.renderer.settings,this.firstBarIndex),this.multiBarRestInfo=ue.buildMultiBarRestInfo(this.renderer.tracks,this.firstBarIndex,this.lastBarIndex),this.pagePadding=this.renderer.settings.display.padding.map((e=>e/this.renderer.settings.display.scale)),this.pagePadding||(this.pagePadding=[0,0,0,0]),1===this.pagePadding.length?this.pagePadding=[this.pagePadding[0],this.pagePadding[0],this.pagePadding[0],this.pagePadding[0]]:2===this.pagePadding.length&&(this.pagePadding=[this.pagePadding[0],this.pagePadding[1],this.pagePadding[0],this.pagePadding[1]]),this.createScoreInfoGlyphs(),this.doLayoutAndRender()}registerPartial(e,t){if(0===e.height)return;const s=this.renderer.settings.display.scale;e.x*=s,e.y*=s,e.width*=s,e.height*=s,e.totalWidth*=s,e.totalHeight*=s,this.renderer.settings.core.enableLazyLoading?(this._lazyPartials.set(e.id,new An(e,t)),this.renderer.partialLayoutFinished.trigger(e)):(this.renderer.partialLayoutFinished.trigger(e),this.internalRenderLazyPartial(e,t))}internalRenderLazyPartial(e,t){const s=this.renderer.canvas;s.beginRender(e.width,e.height),t(s),e.renderResult=s.endRender(),this.renderer.partialRenderFinished.trigger(e)}renderLazyPartial(e){if(this._lazyPartials.has(e)){const t=this._lazyPartials.get(e);this.internalRenderLazyPartial(t.args,t.renderCallback)}}createHeaderFooterGlyph(e,t,s,i){switch(s){case Je.WordsAndMusic:if(t.words!==t.music)return;break;case Je.Words:case Je.Music:if(t.words===t.music)return;break;case Je.CopyrightSecondLine:if(!this.headerGlyphs.has(Je.Copyright))return}const a=e.display.resources,r=e.notation,n=t.style&&t.style.headerAndFooter.has(s)?t.style.headerAndFooter.get(s):ht.defaultHeaderAndFooter.get(s);let o=void 0===n.isVisible||n.isVisible;if(void 0!==i&&(o=r.isNotationElementVisible(i)),!o)return;const h=n.buildText(t);return h?new Tn(0,0,h,a.getFontForElement(s),n.textAlign,void 0,cn.scoreColor(a,s,t)):void 0}createScoreInfoGlyphs(){he.debug("ScoreLayout","Creating score info glyphs");const e=this.renderer.settings,t=this.renderer.score;this.headerGlyphs=new Map,this.footerGlyphs=new Map;const s=new Un(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);for(const[i,a]of Rn.HeaderElements.value){const r=this.createHeaderFooterGlyph(e,t,i,a);r&&(r.renderer=s,r.doLayout(),this.headerGlyphs.set(i,r))}for(const[i,a]of Rn.FooterElements.value){const r=this.createHeaderFooterGlyph(e,t,i,a);r&&(r.renderer=s,r.doLayout(),this.footerGlyphs.set(i,r))}const i=e.notation,a=e.display.resources;if(i.isNotationElementVisible(C.GuitarTuning)){const e=[];for(const s of this.renderer.tracks)for(const i of s.staves){let a=!i.isPercussion&&i.isStringed&&i.tuning.length>0&&i.showTablature;if(t.stylesheet.perTrackDisplayTuning&&t.stylesheet.perTrackDisplayTuning.has(s.index)&&!1===t.stylesheet.perTrackDisplayTuning.get(s.index)&&(a=!1),a){e.push(i);break}}if(e.length>0&&t.stylesheet.globalDisplayTuning){this.tuningGlyph=new Ln(0,0),this.tuningGlyph.renderer=s;for(const t of e)if(t.stringTuning.tunings.length>0){const i=e.length>1?t.track.name:"",r=new In(0,0,t.stringTuning,i);r.colorOverride=cn.trackColor(a,$e.StringTuning,t.track),r.renderer=s,r.doLayout(),this.tuningGlyph.addGlyph(r)}}}if(i.isNotationElementVisible(C.ChordDiagrams)){this.chordDiagrams=new kn(0,0),this.chordDiagrams.renderer=s;const e=new Set;for(const s of this.renderer.tracks){if(t.stylesheet.globalDisplayChordDiagramsOnTop&&(null==t.stylesheet.perTrackChordDiagramsOnTop||!t.stylesheet.perTrackChordDiagramsOnTop.has(s.index)||t.stylesheet.perTrackChordDiagramsOnTop.get(s.index)))for(const t of s.staves){const s=t.chords;if(s)for(const[,t]of s)e.has(t.uniqueId)||t.showDiagram&&(e.add(t.uniqueId),this.chordDiagrams.addChord(t))}}}}createEmptyStaffSystem(){const e=new Mn(this);for(let t=0;t<this.renderer.tracks.length;t++){const s=this.renderer.tracks[t];for(let i=0;i<s.staves.length;i++){const a=s.staves[i],r=ic.staveProfiles.get(this.renderer.settings.display.staveProfile);for(const i of r)i.canCreate(s,a)&&e.addStaff(s,new Nn(t,a,i))}}return e}registerBarRenderer(e,t){if(this._barRendererLookup.has(e)||this._barRendererLookup.set(e,new Map),this._barRendererLookup.get(e).set(t.bar.id,t),t.additionalMultiRestBars)for(const s of t.additionalMultiRestBars)this._barRendererLookup.get(e).set(s.id,t)}unregisterBarRenderer(e,t){if(this._barRendererLookup.has(e)){const s=this._barRendererLookup.get(e);if(s.delete(t.bar.id),t.additionalMultiRestBars)for(const e of t.additionalMultiRestBars)s.delete(e.id)}}getRendererForBar(e,t){const s=t.id;return this._barRendererLookup.has(e)&&this._barRendererLookup.get(e).has(s)?this._barRendererLookup.get(e).get(s):null}layoutAndRenderBottomScoreInfo(e){e=Math.round(e);const t=new yi;t.x=0,t.y=e;let s=0;const i=this.renderer.settings.display.resources,a=[];let r=0;for(const[e,t]of Rn.FooterElements.value)if(this.footerGlyphs.has(e)){const t=this.footerGlyphs.get(e);t.y=s,this.alignScoreInfoGlyph(t),s+=1.2*t.font.size,a.push(t),r=Math.max(r,Math.round(t.x+t.width))}return s=Math.round(s),a.length>0&&(t.width=r,t.height=s,t.totalWidth=this.scaledWidth,t.totalHeight=e+t.height,this.registerPartial(t,(e=>{e.color=i.scoreInfoColor,e.textAlign=A.Left,e.textBaseline=R.Top;for(const t of a)t.paint(0,0,e)}))),e+s}alignScoreInfoGlyph(e){if(ic.getLayoutEngineFactory(this.renderer.settings.display.layoutMode).vertical)switch(e.textAlign){case A.Left:e.x=this.pagePadding[0];break;case A.Center:e.x=this.scaledWidth/2;break;case A.Right:e.x=this.scaledWidth-this.pagePadding[2]}else e.x=this.firstBarX,e.textAlign=A.Left}layoutAndRenderAnnotation(e){const t=this.renderer.settings.display.resources,s=We.withFamilyList(t.copyrightFont.families,12,Fe.Plain,De.Bold),i=new Un(this.renderer,this.renderer.tracks[0].staves[0].bars[0]),a=new Tn(0,0,"rendered by alphaTab",s,A.Center,void 0,t.mainGlyphColor);a.renderer=i,a.doLayout(),this.alignScoreInfoGlyph(a);const r=new yi;return r.width=a.x+a.width,r.x=0,r.height=12,r.y=e,r.totalWidth=this.scaledWidth,r.totalHeight=e+12,r.firstMasterBarIndex=-1,r.lastMasterBarIndex=-1,this.registerPartial(r,(e=>{e.color=t.mainGlyphColor,e.font=s,e.textAlign=A.Left,e.textBaseline=R.Top,a.paint(0,0,e)})),e+12}}Rn.HeaderElements=new ne((()=>new Map([[Je.Title,C.ScoreTitle],[Je.SubTitle,C.ScoreSubTitle],[Je.Artist,C.ScoreArtist],[Je.Album,C.ScoreAlbum],[Je.Words,C.ScoreWords],[Je.Music,C.ScoreMusic],[Je.WordsAndMusic,C.ScoreWordsAndMusic],[Je.Transcriber,void 0]]))),Rn.FooterElements=new ne((()=>new Map([[Je.Copyright,C.ScoreCopyright],[Je.CopyrightSecondLine,void 0]])));class On extends hn{constructor(){super(0,0),this._effectGlyphs=[],this._normalGlyphs=[],this.computedWidth=0}doLayout(){let e=0;if(this.glyphs)for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t];s.x=e,s.renderer=this.renderer,s.doLayout(),e+=s.width}this.width=e,this.computedWidth=e}noteLoop(e){for(let t=this.container.beat.notes.length-1;t>=0;t--)e(this.container.beat.notes[t])}addEffect(e){super.addGlyph(e),this._effectGlyphs.push(e)}addNormal(e){super.addGlyph(e),this._normalGlyphs.push(e)}get effectElement(){}paint(e,t,s){this.paintEffects(e,t,s),this.paintNormal(e,t,s)}paintNormal(e,t,s){for(const i of this._normalGlyphs)i.paint(e+this.x,t+this.y,s)}paintEffects(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,this.effectElement?cn.beat(s,this.effectElement,this.container.beat):void 0,!1);for(const i of this._effectGlyphs)i.paint(e+this.x,t+this.y,s)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}class Hn extends On{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,s){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class Wn extends wr{constructor(e,t,s,i=1){super(e,t),this._scale=0,this._symbols=[],this._symbols=Wn.getSymbols(s),this._scale=i}static getSymbols(e){const t=[];for(;e>0;){const s=e%10;t.unshift(Wn.getSymbol(s)),e=e/10|0}return t}static getSymbol(e){switch(e){case 0:return I.TimeSig0;case 1:return I.TimeSig1;case 2:return I.TimeSig2;case 3:return I.TimeSig3;case 4:return I.TimeSig4;case 5:return I.TimeSig5;case 6:return I.TimeSig6;case 7:return I.TimeSig7;case 8:return I.TimeSig8;case 9:return I.TimeSig9;default:return I.None}}doLayout(){let e=0;for(const t of this._symbols)e+=kr.Widths.get(t);this.width=e}paint(e,t,s){s.fillMusicFontSymbols(e+this.x,t+this.y,this._scale,this._symbols)}}Wn.numberHeight=18;class Vn extends wr{constructor(){super(0,0),this._numberGlyph=[]}doLayout(){this.width=70,this.renderer.registerOverflowTop(this.renderer.getLineHeight(1));const e=this.renderer.additionalMultiRestBars.length+1;this._numberGlyph=Wn.getSymbols(e)}paint(e,t,s){s.fillMusicFontSymbols(e+this.x,t+this.y+this.renderer.height/2,1,[I.RestHBarLeft,I.RestHBarMiddle,I.RestHBarMiddle,I.RestHBarMiddle,I.RestHBarRight]);const i=this.renderer.getLineY(-1.5);s.fillMusicFontSymbols(e+this.x+Vn.BarWidth/2,t+this.y+i|0,1,this._numberGlyph,!0)}}Vn.BarWidth=60;class Gn extends vr{constructor(e){super(Gn.getOrCreatePlaceholderBeat(e),e),this.preNotes=new On,this.onNotes=new Hn}doLayout(){this.renderer.showMultiBarRest&&this.onNotes.addNormal(new Vn),super.doLayout()}static getOrCreatePlaceholderBeat(e){if(e.voice.beats.length>1)return e.voice.beats[0];const t=new xe;return t.voice=e.voice,t}}!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"}(en||(en={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(tn||(tn={}));class Un{get nextRenderer(){return this.bar&&this.bar.nextBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.nextBar):null}get previousRenderer(){return this.bar&&this.bar.previousBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.previousBar):null}get lastBar(){return this.additionalMultiRestBars?this.additionalMultiRestBars[this.additionalMultiRestBars.length-1]:this.bar}get showMultiBarRest(){return!1}constructor(e,t){this._preBeatGlyphs=new ln,this._voiceContainers=new Map,this._postBeatGlyphs=new ln,this._ties=[],this.additionalMultiRestBars=null,this.x=0,this.y=0,this.width=0,this.computedWidth=0,this.height=0,this.index=0,this.topOverflow=0,this.bottomOverflow=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.wasFirstOfLine=!1,this._appliedLayoutingInfo=0,this.isFinalized=!1,this.topPadding=0,this.bottomPadding=0,this.scoreRenderer=e,this.bar=t,t&&(this.helpers=new Sn(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){const t=e-this._preBeatGlyphs.width-this._postBeatGlyphs.width;for(const e of this._voiceContainers.values())e.scaleToWidth(t);this._postBeatGlyphs.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width+t,this.width=e}get resources(){return this.settings.display.resources}get settings(){return this.scoreRenderer.settings}get barDisplayScale(){return this.staff.system.staves.length>1?this.bar.masterBar.displayScale:this.bar.displayScale}get barDisplayWidth(){return this.staff.system.staves.length>1?this.bar.masterBar.displayWidth:this.bar.displayWidth}get isFirstOfLine(){return 0===this.index}get isLast(){return!this.bar||this.bar.index===this.scoreRenderer.layout.lastBarIndex}registerLayoutingInfo(){const e=this.layoutingInfo,t=this._preBeatGlyphs.width;e.preBeatSize<t&&(e.preBeatSize=t);for(const t of this._voiceContainers.values())t.registerLayoutingInfo(e),t.x,t.width;const s=this._postBeatGlyphs.width;e.postBeatSize<s&&(e.postBeatSize=s)}applyLayoutingInfo(){if(this._appliedLayoutingInfo>=this.layoutingInfo.version)return!1;this._appliedLayoutingInfo=this.layoutingInfo.version,this._preBeatGlyphs.width=this.layoutingInfo.preBeatSize;let e=this._preBeatGlyphs.x+this._preBeatGlyphs.width;for(const t of this._voiceContainers.values()){t.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width,t.applyLayoutingInfo(this.layoutingInfo);const s=t.x+t.width;e<s&&(e=s)}this._postBeatGlyphs.x=Math.floor(e),this._postBeatGlyphs.width=this.layoutingInfo.postBeatSize,this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.computedWidth=this.width;const t=this.barDisplayWidth;return t>0&&this.scoreRenderer.layout.systemsLayoutMode===Zr.FromModelWithWidths&&(this.width=t,this.computedWidth=t),!0}finalizeRenderer(){this.isFinalized=!0;let e=!1;const t=this.y-this.staff.topSpacing,s=this.y+this.height+this.staff.bottomSpacing;for(const i of this._ties)if(i.doLayout(),i.height>0){const a=i.y+i.height-s;a>0&&this.registerOverflowBottom(a)&&(e=!0);const r=i.y-t;r<0&&this.registerOverflowTop(-1*r)&&(e=!0)}return e}doLayout(){if(this.bar){this.helpers.initialize(),this._ties=[],this._preBeatGlyphs=new ln,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new ln,this._postBeatGlyphs.renderer=this;for(let e=0;e<this.bar.voices.length;e++){const t=this.bar.voices[e];if(this.hasVoiceContainer(t)){const s=new un(0,0,t);s.renderer=this,this._voiceContainers.set(this.bar.voices[e].index,s)}}if(this.bar.simileMark===h.SecondOfDouble&&(this.canWrap=!1),this.createPreBeatGlyphs(),this.additionalMultiRestBars){const e=new Gn(this.getVoiceContainer(this.bar.voices[0]));this.addBeatGlyph(e)}else this.createBeatGlyphs();this.createPostBeatGlyphs(),this.updateSizes();for(const e of this.helpers.beamHelpers)for(const t of e)t.finish();this.computedWidth=this.width}}hasVoiceContainer(e){return!(!this.additionalMultiRestBars&&0!==e.index)||!e.isEmpty}updateSizes(){this.staff.registerStaffTop(this.topPadding),this.staff.registerStaffBottom(this.height-this.bottomPadding);const e=this._voiceContainers,t=this.beatGlyphsStart;let s=t;for(const i of e.values()){i.x=t,i.doLayout();const e=i.x+i.width;s<e&&(s=e)}this._postBeatGlyphs.x=Math.floor(s),this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.height+=this.layoutingInfo.height}addPreBeatGlyph(e){e.renderer=this,this._preBeatGlyphs.addGlyph(e)}addBeatGlyph(e){e.renderer=this,e.preNotes.renderer=this,e.onNotes.renderer=this,e.onNotes.beamingHelper=this.helpers.beamHelperLookup[e.beat.voice.index].get(e.beat.index),this.getVoiceContainer(e.beat.voice).addGlyph(e)}getVoiceContainer(e){return this._voiceContainers.has(e.index)?this._voiceContainers.get(e.index):void 0}getBeatContainer(e){return this.getVoiceContainer(e.voice)?.beatGlyphs?.[e.index]}getPreNotesGlyphForBeat(e){return this.getBeatContainer(e)?.preNotes}getOnNotesGlyphForBeat(e){return this.getBeatContainer(e)?.onNotes}paint(e,t,s){this.paintBackground(e,t,s),s.color=this.resources.mainGlyphColor,this._preBeatGlyphs.paint(e+this.x,t+this.y,s);for(const i of this._voiceContainers.values())i.paint(e+this.x,t+this.y,s);s.color=this.resources.mainGlyphColor,this._postBeatGlyphs.paint(e+this.x,t+this.y,s)}paintBackground(e,t,s){this.layoutingInfo.paint(e+this.x+this._preBeatGlyphs.x+this._preBeatGlyphs.width,t+this.y+this.height,s)}buildBoundingsLookup(e,t,s){const i=new _i;i.bar=this.bar,i.visualBounds=new Is,i.visualBounds.x=t+this.x,i.visualBounds.y=s+this.y+this.topPadding,i.visualBounds.w=this.width,i.visualBounds.h=this.height-this.topPadding-this.bottomPadding,i.realBounds=new Is,i.realBounds.x=t+this.x,i.realBounds.y=s+this.y,i.realBounds.w=this.width,i.realBounds.h=this.height,e.addBar(i);for(const[e,a]of this._voiceContainers){const r=this.bar.isEmpty&&0===e;if(!a.voice.isEmpty||r)for(let e=0,n=a.beatGlyphs.length;e<n;e++){a.beatGlyphs[e].buildBoundingsLookup(i,t+this.x+a.x,s+this.y+a.y,r)}}}addPostBeatGlyph(e){this._postBeatGlyphs.addGlyph(e)}createPreBeatGlyphs(){this.wasFirstOfLine=this.isFirstOfLine}createBeatGlyphs(){for(const e of this.bar.voices)this.hasVoiceContainer(e)&&this.createVoiceGlyphs(e)}createVoiceGlyphs(e){}createPostBeatGlyphs(){}get beatGlyphsStart(){return this._preBeatGlyphs.x+this._preBeatGlyphs.width}get postBeatGlyphsStart(){return this._postBeatGlyphs.x}getBeatX(e,t=Qr.PreNotes){const s=this.getBeatContainer(e);if(s)switch(t){case Qr.PreNotes:return s.voiceContainer.x+s.x;case Qr.OnNotes:return s.voiceContainer.x+s.x+s.onNotes.x;case Qr.MiddleNotes:return s.voiceContainer.x+s.x+s.onTimeX;case Qr.Stem:const t=s.onNotes.beamingHelper?s.onNotes.beamingHelper.getBeatLineX(e):s.onNotes.x+s.onNotes.width/2;return s.voiceContainer.x+t;case Qr.PostNotes:return s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.width;case Qr.EndBeat:return s.voiceContainer.x+s.x+s.width}return 0}getRatioPositionX(e){const t=this.bar.isEmpty?this.beatGlyphsStart:this.getBeatX(this.bar.voices[0].beats[0],Qr.OnNotes);return t+(this.postBeatGlyphsStart-t)*e}getNoteX(e,t){const s=this.getBeatContainer(e.beat);return s?s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.getNoteX(e,t):0}getNoteY(e,t){const s=this.getOnNotesGlyphForBeat(e.beat);return s?s.getNoteY(e,t):Number.NaN}reLayout(){(this.wasFirstOfLine&&!this.isFirstOfLine||!this.wasFirstOfLine&&this.isFirstOfLine)&&this.recreatePreBeatGlyphs(),this.updateSizes(),this.registerLayoutingInfo()}recreatePreBeatGlyphs(){this._preBeatGlyphs=new ln,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()}paintSimileMark(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.voice(s,$.Glyphs,this.bar.voices[0],!0),!1);switch(this.bar.simileMark){case h.Simple:s.beginGroup(vr.getGroupId(this.bar.voices[0].beats[0])),s.fillMusicFontSymbol(e+this.x+(this.width-20)/2,t+this.y+this.height/2,1,I.Repeat1Bar,!1),s.endGroup();break;case h.SecondOfDouble:s.beginGroup(vr.getGroupId(this.bar.voices[0].beats[0])),s.beginGroup(vr.getGroupId(this.bar.previousBar.voices[0].beats[0])),s.fillMusicFontSymbol(e+this.x-14,t+this.y+this.height/2,1,I.Repeat2Bars,!1),s.endGroup(),s.endGroup()}}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}completeBeamingHelper(e){}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}}Un.RawLineSpacing=8,Un.StemWidth=.12*Un.RawLineSpacing,Un.StaffLineThickness=.13*Un.RawLineSpacing,Un.BeamThickness=.5*Un.RawLineSpacing,Un.BeamSpacing=.25*Un.RawLineSpacing,function(e){e[e.SinglePreBeat=0]="SinglePreBeat",e[e.SingleOnBeat=1]="SingleOnBeat",e[e.SingleOnBeatToEnd=2]="SingleOnBeatToEnd",e[e.GroupedOnBeat=3]="GroupedOnBeat",e[e.GroupedOnBeatToEnd=4]="GroupedOnBeatToEnd",e[e.FullBar=5]="FullBar"}(sn||(sn={}));class zn extends wr{constructor(e,t){super(0,0),this._uniqueEffectGlyphs=[],this._effectGlyphs=[],this.isEmpty=!0,this.previousBand=null,this.isLinkedToPrevious=!1,this.firstBeat=null,this.lastBeat=null,this.height=0,this.originalHeight=0,this.slot=null,this.voice=e,this.info=t}doLayout(){super.doLayout();for(let e=0;e<this.renderer.bar.voices.length;e++)this._effectGlyphs.push(new Map),this._uniqueEffectGlyphs.push([])}createGlyph(e){if(e.voice===this.voice&&this.info.shouldCreateGlyph(this.renderer.settings,e)&&(!this.info.hideOnMultiTrack||0===this.renderer.staff.trackIndex)){if(this.isEmpty=!1,this.firstBeat&&!e.isBefore(this.firstBeat)||(this.firstBeat=e),!this.lastBeat||e.isAfter(this.lastBeat))switch(this.lastBeat=e,this.info.sizingMode){case sn.SingleOnBeatToEnd:case sn.GroupedOnBeatToEnd:this.lastBeat.nextBeat&&(this.lastBeat=this.lastBeat.nextBeat)}const t=this.createOrResizeGlyph(this.info.sizingMode,e);t.height>this.height&&(this.height=t.height,this.originalHeight=t.height)}}resetHeight(){this.height=this.originalHeight}createOrResizeGlyph(e,t){let s;switch(e){case sn.FullBar:case sn.SinglePreBeat:case sn.SingleOnBeat:case sn.SingleOnBeatToEnd:return s=this.info.createNewGlyph(this.renderer,t),s.renderer=this.renderer,s.beat=t,s.doLayout(),this._effectGlyphs[t.voice.index].set(t.index,s),this._uniqueEffectGlyphs[t.voice.index].push(s),s;case sn.GroupedOnBeat:case sn.GroupedOnBeatToEnd:const i=e===sn.GroupedOnBeat?sn.SingleOnBeat:sn.SingleOnBeatToEnd;if(t.index>0||this.renderer.index>0){const e=t.previousBeat;if(this.info.shouldCreateGlyph(this.renderer.settings,e)){let s=null;if(t.index>0&&this._effectGlyphs[t.voice.index].has(e.index))s=this._effectGlyphs[t.voice.index].get(e.index);else if(this.renderer.index>0){const t=this.renderer.previousRenderer.getBand(e.voice,this.info.effectId);if(t){const i=t._effectGlyphs[e.voice.index];i.has(e.index)&&(s=i.get(e.index))}}const a=this.createOrResizeGlyph(i,t);return s&&this.info.canExpand(e,t)&&(s.nextGlyph=a,a.previousGlyph=s,this.isLinkedToPrevious=!0),a}return this.createOrResizeGlyph(i,t)}return this.createOrResizeGlyph(i,t);default:return this.createOrResizeGlyph(sn.SingleOnBeat,t)}}paint(e,t,s){super.paint(e,t,s);for(let i=0,a=this._uniqueEffectGlyphs.length;i<a;i++){const a=this._uniqueEffectGlyphs[i];for(let i=0,r=a.length;i<r;i++){const r={stack:[],error:void 0,hasError:!1};try{const n=a[i];jr(r,cn.beat(s,Y.Effects,n.beat,!1),!1);n.paint(e+this.x,t+this.y,s)}catch(e){r.error=e,r.hasError=!0}finally{on(r)}}}}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){const s=this._effectGlyphs[t.voice.index].get(t.index),i=this.renderer.getBeatContainer(t);switch(e){case sn.SinglePreBeat:const e=this.renderer.layoutingInfo.getPreBeatSize(t);s.x=this.renderer.beatGlyphsStart+i.x-e;break;case sn.SingleOnBeat:case sn.GroupedOnBeat:s.x=this.renderer.beatGlyphsStart+i.x;break;case sn.SingleOnBeatToEnd:case sn.GroupedOnBeatToEnd:if(s.x=this.renderer.beatGlyphsStart+i.x,i.beat.isLastOfVoice)s.width=this.renderer.width-s.x;else{const e=this.renderer.layoutingInfo.getPostBeatSize(t);s.width=e}break;case sn.FullBar:s.width=this.renderer.width}}}class Xn{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class Jn{constructor(){this.bands=[],this.shared=new Xn}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 Yn{constructor(){this.slots=[],this._effectSlot=new Map}getOrCreateSlot(e){if(this._effectSlot.has(e.info.effectId)){const t=this._effectSlot.get(e.info.effectId);if(t.canBeUsed(e))return t}for(const t of this.slots)if(t.canBeUsed(e))return t;const t=new Jn;return this.slots.push(t),t}register(e){const t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class $n extends Un{constructor(e,t,s){super(e,t),this._bands=[],this._bandLookup=new Map,this.sizingInfo=null,this._infos=s}updateSizes(){this.topOverflow=0,this.bottomOverflow=0,this.topPadding=0,this.bottomPadding=0,this.updateHeight(),super.updateSizes()}finalizeRenderer(){let e=super.finalizeRenderer();return this.updateHeight()&&(e=!0),e}updateHeight(){if(!this.sizingInfo)return!1;let e=0;for(const t of this.sizingInfo.slots){t.shared.y=e;for(const s of t.bands)s.y=e,s.height=t.shared.height;e+=t.shared.height}return e!==this.height&&(this.height=e,!0)}applyLayoutingInfo(){const e=!super.applyLayoutingInfo();if(this.index>0){const e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new Yn;for(const e of this._bands)e.resetHeight(),e.alignGlyphs(),e.isEmpty||this.sizingInfo.register(e);return this.updateHeight(),e}scaleToWidth(e){super.scaleToWidth(e);for(const e of this._bands)e.alignGlyphs()}createBeatGlyphs(){this._bands=[],this._bandLookup=new Map;for(const e of this.bar.voices)if(this.hasVoiceContainer(e))for(const t of this._infos){const s=new zn(e,t);s.renderer=this,s.doLayout(),this._bands.push(s),this._bandLookup.set(`${e.index}.${t.effectId}`,s)}super.createBeatGlyphs();for(const e of this._bands)e.isLinkedToPrevious&&(this.isLinkedToPrevious=!0)}createVoiceGlyphs(e){for(const t of e.beats){const s=new vr(t,this.getVoiceContainer(e));s.preNotes=new On,s.onNotes=new Hn,this.addBeatGlyph(s);for(const e of this._bands)e.createGlyph(t)}}paint(e,t,s){this.paintBackground(e,t,s);for(const i of this._bands)s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isEmpty||i.paint(e+this.x,t+this.y,s)}getBand(e,t){const s=`${e.index}.${t}`;return this._bandLookup.has(s)?this._bandLookup.get(s):null}}class qn extends Kr{get staffId(){return this._staffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.effectStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.effectStaffPaddingBottom}constructor(e,t,s=null){super(),this.infos=t,this._staffId=e,this.isInsideBracket=!1,this.isRelevantForBoundsLookup=!1,this.shouldShow=s}canCreate(e,t){const s=this.shouldShow;return super.canCreate(e,t)&&(!s||s(e,t))}create(e,t){return new $n(e,t,this.infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class Kn extends Br{constructor(e,t,s,i,a){super(e,t),this._endingsString="",this._endings=ue.getAlternateEndingsList(s),this._openLine=i,this._closeLine=a}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+(Kn.Padding+2);let e="";for(let t=0,s=this._endings.length;t<s;t++)e+=this._endings[t]+1,e+=". ";this._endingsString=e}paint(e,t,s){const i=this._closeLine?this.width-4:this.width;if(e=.5+(0|e),t=.5+(0|t),this._openLine?(s.moveTo(e+this.x,t+this.y+this.height),s.lineTo(e+this.x,t+this.y)):s.moveTo(e+this.x,t+this.y),s.lineTo(e+this.x+i,t+this.y),this._closeLine&&s.lineTo(e+this.x+i,t+this.y+this.height),s.stroke(),this._openLine){const i=s.textBaseline;s.textBaseline=R.Top;const a=this.renderer.resources;s.font=a.wordsFont,s.fillText(this._endingsString,e+this.x+Kn.Padding,t+this.y),s.textBaseline=i}}}Kn.Padding=3;class jn{get effectId(){return this.notationElement.toString()}}class Qn extends jn{get notationElement(){return C.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return sn.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){const s=t.voice.bar.masterBar,i=null===s.previousMasterBar||s.alternateEndings!==s.previousMasterBar.alternateEndings;let a=s.isRepeatEnd||null===s.nextMasterBar||s.alternateEndings!==s.nextMasterBar.alternateEndings;return s.repeatGroup.closings.some((e=>e.index>=s.index))||(a=!1),new Kn(0,0,s.alternateEndings,i,a)}canExpand(e,t){return!0}}class Zn extends jn{get notationElement(){return C.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return sn.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Tn(0,0,`Capo. fret ${t.voice.bar.staff.capo}`,e.resources.effectFont,A.Left)}canExpand(e,t){return!1}}class eo extends jn{get notationElement(){return C.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return sn.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Tn(0,0,t.chord.name,e.resources.effectFont,A.Center)}canExpand(e,t){return!1}}class to extends Br{constructor(e){super(),this.forceGroupedRendering=!1,this.endOnBarLine=!1,this.endPosition=e}get isLinkedWithPrevious(){return!!this.previousGlyph&&this.previousGlyph.renderer.staff.system===this.renderer.staff.system}get isLinkedWithNext(){return!!this.nextGlyph&&this.nextGlyph.renderer.isFinalized&&this.nextGlyph.renderer.staff.system===this.renderer.staff.system}paint(e,t,s){if(this.isLinkedWithPrevious)return;if(!this.isLinkedWithNext&&!this.forceGroupedRendering)return void this.paintNonGrouped(e,t,s);let i;if(!this.isLinkedWithNext&&this.forceGroupedRendering)i=this;else for(i=this.nextGlyph;i.isLinkedWithNext;)i=i.nextGlyph;const a=i.renderer,r=i.beat,n=this.endPosition,o=e-this.renderer.x,h=this.calculateEndX(a,r,o,n);this.paintGrouped(e,t,h,s)}calculateEndX(e,t,s,i){return t?s+e.x+e.getBeatX(t,i):s+e.x+this.x+this.width}paintNonGrouped(e,t,s){const i=e-this.renderer.x,a=this.calculateEndX(this.renderer,this.beat,i,this.endPosition);this.paintGrouped(e,t,a,s)}}class so extends to{constructor(e,t,s){super(Qr.EndBeat),this._crescendo=m.None,this._crescendo=s,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17}paintGrouped(e,t,s,i){const a=e+this.x,r=this.height,n=kr.Widths.get(I.NoteheadBlack)/2;i.beginPath(),this._crescendo===m.Crescendo?(s-=n,i.moveTo(s,t+this.y),i.lineTo(a,t+this.y+r/2),i.lineTo(s,t+this.y+r)):(s-=n,i.moveTo(a,t+this.y),i.lineTo(s,t+this.y+r/2),i.lineTo(a,t+this.y+r)),i.stroke()}}class io extends jn{get notationElement(){return C.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return sn.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==m.None}createNewGlyph(e,t){return new so(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class ao extends Tr{constructor(e,t,s){super(e,t,.6,ao.getSymbol(s)),this.center=!0}doLayout(){super.doLayout(),this.y+=this.height/2}static getSymbol(e){switch(e){case y.PPP:return I.DynamicPPP;case y.PP:return I.DynamicPP;case y.P:return I.DynamicPiano;case y.MP:return I.DynamicMP;case y.MF:return I.DynamicMF;case y.F:return I.DynamicForte;case y.FF:return I.DynamicFF;case y.FFF:return I.DynamicFFF;default:return I.None}}}class ro extends jn{get notationElement(){return C.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return sn.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)return!1;const t=this.getPreviousDynamicsBeat(e);let s=0===e.voice.index&&!t||e.dynamics!==t?.dynamics;if(s&&e.voice.index>0)for(const t of e.voice.bar.voices)if(t.index<e.voice.index){const i=t.getBeatAtPlaybackStart(e.playbackStart);i&&e.dynamics===i.dynamics&&this.internalShouldCreateGlyph(i)&&(s=!1)}return s}getPreviousDynamicsBeat(e){let t=e.previousBeat;for(;null!=t;){if(!t.isRest)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new ao(0,0,t.dynamics)}canExpand(e,t){return!0}}class no extends Tr{constructor(e){super(0,0,1,no.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case G.FadeIn:return I.GuitarFadeIn;case G.FadeOut:return I.GuitarFadeOut;case G.VolumeSwell:return I.GuitarVolumeSwell}return I.None}paint(e,t,s){super.paint(e,t+this.height,s)}}class oo extends jn{get notationElement(){return C.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return sn.SingleOnBeat}shouldCreateGlyph(e,t){return t.fade!==G.None}createNewGlyph(e,t){return new no(t.fade)}canExpand(e,t){return!0}}class ho extends Tr{constructor(e,t,s){super(e,t,1,ho.getSymbol(s))}static getSymbol(e){switch(e){case Ke.Short:return I.FermataShortAbove;case Ke.Medium:return I.FermataAbove;case Ke.Long:return I.FermataLongAbove;default:return I.None}}paint(e,t,s){super.paint(e-this.width/2,t+this.height,s)}}class lo extends jn{get notationElement(){return C.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return sn.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new ho(0,0,t.fermata.type)}canExpand(e,t){return!0}}class co extends jn{get notationElement(){return C.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return sn.SingleOnBeat}shouldCreateGlyph(e,t){return!(0!==t.voice.index||t.isRest||e.notation.fingeringMode!==v.SingleNoteEffectBand&&e.notation.fingeringMode!==v.SingleNoteEffectBandForcePiano)&&(1===t.notes.length&&t.notes[0].isFingering)}createNewGlyph(e,t){let s=_.Unknown,i=!1;const a=t.notes[0];a.leftHandFinger!==_.Unknown?(s=a.leftHandFinger,i=!0):a.rightHandFinger!==_.Unknown&&(s=a.rightHandFinger);const r=ue.fingerToString(e.settings,t,s,i)??"";return new Tn(0,0,r,e.resources.fingeringFont,A.Left)}canExpand(e,t){return!0}}class uo extends jn{constructor(){super(...arguments),this.lastCreateInfo=null}shouldCreateGlyph(e,t){this.lastCreateInfo=[];for(let e=0,s=t.notes.length;e<s;e++){const s=t.notes[e];this.shouldCreateGlyphForNote(s)&&this.lastCreateInfo.push(s)}return this.lastCreateInfo.length>0}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}canExpand(e,t){return!0}}class po extends to{constructor(e,t=!0){super(Qr.OnNotes),this._label=e,this._dashed=t}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=Qr.EndBeat,this.forceGroupedRendering=!0),super.doLayout(),this.height=this.renderer.resources.effectFont.size}paintNonGrouped(e,t,s){const i=this.renderer.resources;s.font=i.effectFont;const a=s.textAlign;s.textAlign=A.Center,s.fillText(this._label,e+this.x,t+this.y),s.textAlign=a}paintGrouped(e,t,s,i){this.paintNonGrouped(e,t,i);const a=i.measureText(this._label).width,r=e+this.x+a/2+3,n=t+this.y+4;if(this._dashed){if(s>r){let e=r;for(;e<s;)i.beginPath(),i.moveTo(e,0|n),i.lineTo(Math.min(e+8,s),0|n),e+=11,i.stroke();i.beginPath(),i.moveTo(s,n-5|0),i.lineTo(s,n+5|0),i.stroke()}}else i.beginPath(),i.moveTo(r,0|n),i.lineTo(s,0|n),i.lineTo(s,n+5|0),i.stroke()}}po.LineSpacing=3,po.LineTopPadding=4,po.LineTopOffset=5,po.LineSize=8;class go extends uo{get effectId(){return this._effectId}get notationElement(){return C.EffectHarmonics}constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case w.None:this._effectId="harmonics-none";break;case w.Natural:this._effectId="harmonics-natural";break;case w.Artificial:this._effectId="harmonics-artificial";break;case w.Pinch:this._effectId="harmonics-pinch";break;case w.Tap:this._effectId="harmonics-tap";break;case w.Semi:this._effectId="harmonics-semi";break;case w.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 sn.GroupedOnBeat}createNewGlyph(e,t){return new po(go.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case w.Natural:return"N.H.";case w.Artificial:return"A.H.";case w.Pinch:return"P.H.";case w.Tap:return"T.H.";case w.Semi:return"S.H.";case w.Feedback:return"Fdbk."}return""}}class mo extends jn{get notationElement(){return C.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return sn.GroupedOnBeat}createNewGlyph(e,t){return new po("LetRing")}canExpand(e,t){return!0}}class fo extends Br{constructor(e,t,s,i,a=A.Center){super(e,t),this._lines=s,this.font=i,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,s){s.font=this.font;const i=s.textAlign;s.textAlign=this.textAlign;for(let i=0;i<this._lines.length;i++)this._lines[i]&&s.fillText(this._lines[i],e+this.x,t+this.y+i*this.font.size);s.textAlign=i}}class yo extends jn{get notationElement(){return C.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return sn.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new fo(0,0,t.lyrics,e.resources.effectFont,A.Center)}canExpand(e,t){return!0}}class bo extends jn{get notationElement(){return C.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return sn.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 Tn(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,A.Left)}canExpand(e,t){return!0}}class So extends to{constructor(e,t){super(Qr.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=kr.Heights.get(I.QuindicesimaAlta)}paintNonGrouped(e,t,s){this.paintOttava(e,t,s)}paintOttava(e,t,s){let i=0;switch(this._ottava){case o._15ma:i=.8*kr.Widths.get(I.QuindicesimaAlta),s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,I.QuindicesimaAlta,!1);break;case o._8va:i=.8*kr.Widths.get(I.OttavaAlta),s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,I.OttavaAlta,!1);break;case o._8vb:i=.8*kr.Widths.get(I.OttavaBassaVb),s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,I.OttavaBassaVb,!1);break;case o._15mb:i=.8*(kr.Widths.get(I.Quindicesima)+kr.Widths.get(I.OctaveBaselineM)+kr.Widths.get(I.OctaveBaselineB)),s.fillMusicFontSymbols(e+this.x-i/2,t+this.y+this.height,.8,[I.Quindicesima,I.OctaveBaselineM,I.OctaveBaselineB],!1)}return i/2}paintGrouped(e,t,s,i){const a=this.paintOttava(e,t,i),r=e+this.x+a+3;let n=t+this.y;n+=this._aboveStaff?2:this.height-2;if(s>r){let e=r;for(;e<s;)i.beginPath(),i.moveTo(e,0|n),i.lineTo(Math.min(e+8,s),0|n),e+=11,i.stroke();i.beginPath(),this._aboveStaff?(i.moveTo(s,n),i.lineTo(s,t+this.y+this.height)):(i.moveTo(s,n),i.lineTo(s,t+this.y)),i.stroke()}}}class _o extends jn{get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return C.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return sn.GroupedOnBeat}constructor(e){super(),this._aboveStaff=e}shouldCreateGlyph(e,t){switch(t.ottava){case o._15ma:case o._8va:return this._aboveStaff;case o._8vb:case o._15mb:return!this._aboveStaff}return!1}createNewGlyph(e,t){return new So(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class wo extends uo{get notationElement(){return C.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return sn.GroupedOnBeat}createNewGlyph(e,t){return new po("P.M.")}}class Bo extends uo{get notationElement(){return C.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===T.PickSlideDown||e.slideOutType===T.PickSlideUp}get sizingMode(){return sn.GroupedOnBeat}createNewGlyph(e,t){return new po("P.S.")}}class ko extends Tr{constructor(e,t,s){super(e,t,Nr.GraceScale,ko.getSymbol(s))}paint(e,t,s){super.paint(e,t+this.height,s)}static getSymbol(e){switch(e){case L.Up:return I.StringsUpBow;case L.Down:return I.StringsDownBow;default:return I.None}}}class To extends jn{get notationElement(){return C.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return sn.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==L.None}createNewGlyph(e,t){return new ko(0,0,t.pickStroke)}canExpand(e,t){return!0}}class No extends to{constructor(e){super(Qr.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case N.Slight:this._stepSize=12;break;case N.Wide:this._stepSize=23}this.height=18}paintGrouped(e,t,s,i){let a=e+this.x;const r=s-a,n=Math.max(1,r/this._stepSize);i.beginPath(),i.moveTo(a,t+this.y);for(let e=0;e<n;e++)i.lineTo(a+this._stepSize/2,t+this.y+this.height),i.lineTo(a+this._stepSize,t+this.y),a+=this._stepSize;i.stroke()}}class xo extends jn{get notationElement(){return C.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return sn.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===N.Slight}createNewGlyph(e,t){return new No(N.Slight)}canExpand(e,t){return!0}}class vo extends to{constructor(e,t,s,i=1.2,a=!1){super(Qr.EndBeat),this._scale=0,this._symbol=I.None,this._symbolSize=0,this._type=s,this._scale=i,this.x=e,this.y=t,this._partialWaves=a}doLayout(){switch(super.doLayout(),this._type){case N.Slight:this._symbol=I.WiggleTrill;break;case N.Wide:this._symbol=I.WiggleVibratoMediumFast}this._symbolSize=kr.Widths.get(this._symbol)*this._scale,this.height=kr.Heights.get(this._symbol)*this._scale}paintGrouped(e,t,s,i){const a=s-(e+this.x),r=this._symbolSize;let n=a/r;this._partialWaves||(n=Math.floor(n)),n<1&&(n=1);let o=0;for(let s=0;s<n;s++)i.fillMusicFontSymbol(e+this.x+o,t+this.y+2*this.height,this._scale,this._symbol,!1),o+=r}}class Po extends uo{get notationElement(){return C.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){let t=e.vibrato===N.Slight||e.isTieDestination&&e.tieOrigin.vibrato===N.Slight;return this._hideOnTiedBend&&t&&e.isTieDestination&&e.tieOrigin.hasBend&&(t=!1),t}get sizingMode(){return sn.GroupedOnBeatToEnd}createNewGlyph(e,t){return new vo(0,0,N.Slight,1.2)}constructor(e){super(),this._hideOnTiedBend=e}}class Co extends jn{get notationElement(){return C.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return sn.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){const s=e.resources;return t.slap?new Tn(0,0,"S",s.effectFont,A.Left):t.pop?new Tn(0,0,"P",s.effectFont,A.Left):new Tn(0,0,"T",s.effectFont,A.Left)}canExpand(e,t){return!0}}class Eo extends Br{constructor(e){super(0,0),this.tempoAutomations=e}doLayout(){super.doLayout(),this.height=25}paint(e,t,s){for(const i of this.tempoAutomations){let a=e+this.renderer.getRatioPositionX(i.ratioPosition);const r=this.renderer.resources;if(s.font=r.markerFont,s.textBaseline=R.Top,i.text){const e=s.measureText(i.text);s.fillText(i.text,a,t+this.y+s.font.size/2),a+=e.width+.7*s.font.size}s.fillMusicFontSymbol(a,t+this.y+.8*this.height,.5,I.NoteQuarterUp,!0),s.fillText(`= ${i.value.toString()}`,a+.5*kr.Widths.get(I.NoteQuarterUp)+3,t+this.y+s.font.size/2)}}}class Fo extends jn{get notationElement(){return C.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return sn.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&t.voice.bar.masterBar.tempoAutomations.length>0}createNewGlyph(e,t){return new Eo(t.voice.bar.masterBar.tempoAutomations)}canExpand(e,t){return!0}}class Do extends jn{get notationElement(){return C.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return sn.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Tn(0,0,t.text,e.resources.effectFont,A.Left)}canExpand(e,t){return!0}}class Mo extends to{constructor(e,t){super(Qr.EndBeat),this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=kr.Heights.get(I.OrnamentTrill)/2}paintGrouped(e,t,s,i){let a=e+this.x;i.fillMusicFontSymbol(a,t+this.y+this.height,1,I.OrnamentTrill,!0),a+=kr.Widths.get(I.OrnamentTrill)/2;const r=1.2*kr.Widths.get(I.WiggleTrill),n=Math.floor((s-a)/r),o=t+this.y+1.37*this.height;let h=a;for(let e=0;e<n;e++)i.fillMusicFontSymbol(h,o,1.2,I.WiggleTrill,!1),h+=r}}class Lo extends uo{get notationElement(){return C.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return sn.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Mo(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(an||(an={}));class Io extends Br{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25}paint(e,t,s){e+=this.x;const i=(t+=this.y)+this.height*Nr.GraceScale,a=i+8;s.font=this.renderer.resources.effectFont,s.fillText("(",e,t+.3*this.height);const r=e+10,n=e+40;let o=[],h=[],l=[],c=[];switch(this._tripletFeel){case M.NoTripletFeel:o=[I.TextBlackNoteLongStem,I.TextCont8thBeamLongStem,I.TextBlackNoteFrac8thLongStem],l=[I.TextBlackNoteLongStem,I.TextCont8thBeamLongStem,I.TextBlackNoteFrac8thLongStem];break;case M.Triplet8th:o=[I.TextBlackNoteLongStem,I.TextCont8thBeamLongStem,I.TextBlackNoteFrac8thLongStem],l=[I.TextBlackNoteLongStem,I.Space,I.NoteEighthUp],c=[I.TextTupletBracketStartLongStem,I.TextTuplet3LongStem,I.TextTupletBracketEndLongStem];break;case M.Triplet16th:o=[I.TextBlackNoteLongStem,I.TextCont8thBeamLongStem,I.TextBlackNoteFrac8thLongStem],l=[I.TextBlackNoteLongStem,I.TextCont8thBeamLongStem,I.TextBlackNoteFrac16thLongStem],c=[I.TextTupletBracketStartLongStem,I.TextTuplet3LongStem,I.TextTupletBracketEndLongStem];break;case M.Dotted8th:o=[I.TextBlackNoteLongStem,I.TextCont8thBeamLongStem,I.TextBlackNoteFrac8thLongStem],h=[I.TextAugmentationDot],l=[I.TextBlackNoteLongStem,I.TextCont8thBeamLongStem,I.TextBlackNoteFrac16thLongStem];break;case M.Dotted16th:o=[I.TextBlackNoteLongStem,I.TextCont16thBeamLongStem,I.TextBlackNoteFrac16thLongStem],h=[I.TextAugmentationDot],l=[I.TextBlackNoteLongStem,I.TextCont16thBeamLongStem,I.TextBlackNoteFrac32ndLongStem],s.fillCircle(n+9,i,1);break;case M.Scottish8th:o=[I.TextBlackNoteLongStem,I.TextCont8thBeamLongStem,I.TextBlackNoteFrac8thLongStem],l=[I.TextBlackNoteLongStem,I.TextCont16thBeamLongStem,I.TextBlackNoteFrac8thLongStem,I.TextAugmentationDot];break;case M.Scottish16th:o=[I.TextBlackNoteLongStem,I.TextCont16thBeamLongStem,I.TextBlackNoteFrac16thLongStem],l=[I.TextBlackNoteLongStem,I.TextCont32ndBeamLongStem,I.TextBlackNoteFrac16thLongStem,I.TextAugmentationDot]}s.fillMusicFontSymbols(r,i,Io.NoteScale,o,!1),s.fillText("=",e+32,t+5),s.fillMusicFontSymbols(n,i,Io.NoteScale,l,!1),h.length>0&&s.fillMusicFontSymbols(n+7,i,Io.NoteScale,h,!1),c.length>0&&s.fillMusicFontSymbols(n,a,Io.TupletScale,c,!1),s.fillText(")",e+65,t+.3*this.height)}}Io.NoteScale=.5,Io.TupletScale=.7;class Ao extends jn{get notationElement(){return C.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return sn.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==M.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new Io(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class Ro extends jn{get notationElement(){return C.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return sn.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new po("w/bar")}canExpand(e,t){return!0}}class Oo extends jn{get notationElement(){return C.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return sn.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===N.Wide}createNewGlyph(e,t){return new No(N.Wide)}canExpand(e,t){return!0}}class Ho extends uo{get notationElement(){return C.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===N.Wide||e.isTieDestination&&e.tieOrigin.vibrato===N.Wide}get sizingMode(){return sn.GroupedOnBeatToEnd}createNewGlyph(e,t){return new vo(0,0,N.Wide,1.2)}}class Wo{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class Vo extends Rn{constructor(){super(...arguments),this._system=null}get name(){return"HorizontalScreen"}get supportsResize(){return!1}get firstBarX(){let e=this.pagePadding[0];return this._system&&(e+=this._system.accoladeWidth),e}doResize(){}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case at.Automatic:this.systemsLayoutMode=Zr.Automatic;break;case at.UseModelLayout:this.systemsLayoutMode=Zr.FromModelWithWidths}const e=this.renderer.score;let t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t));let s=t,i=this.renderer.settings.display.barCount;i<=0&&(i=e.masterBars.length),i=t+i-1,i=Math.min(e.masterBars.length-1,Math.max(0,i)),this._system=this.createEmptyStaffSystem(),this._system.isLast=!0,this._system.x=this.pagePadding[0],this._system.y=this.pagePadding[1];const a=this.renderer.settings.display.barCountPerPartial,r=[];let n=new Wo,o=0;for(;s<=i;){const t=this.multiBarRestInfo,i=null!==t&&t.has(s)?t.get(s):null,h=this._system.addBars(this.renderer.tracks,s,i);if(0===n.masterBars.length&&h.isLinkedToPrevious&&r.length>0){const t=r[r.length-1];t.masterBars.push(e.masterBars[s]),t.width+=h.width,o+=h.width,n.x+=o}else n.masterBars.push(e.masterBars[s]),n.width+=h.width,n.masterBars.length>=a&&(0===r.length&&(n.width+=this._system.accoladeWidth+this.pagePadding[0]),o+=n.width,r.push(n),he.debug(this.name,`Finished partial from bar ${n.masterBars[0].index} to ${n.masterBars[n.masterBars.length-1].index}`,null),n=new Wo,n.x=o);s++}n.masterBars.length>0&&(0===r.length&&(n.width+=this._system.accoladeWidth+this.pagePadding[0]),r.push(n),he.debug(this.name,`Finished partial from bar ${n.masterBars[0].index} to ${n.masterBars[n.masterBars.length-1].index}`,null)),this.finalizeStaffSystem();const h=this.renderer.settings.display.scale;this.height=Math.floor(this._system.y+this._system.height)*h,this.width=(this._system.x+this._system.width+this.pagePadding[2])*h,s=0;let l=0;for(let e=0;e<r.length;e++){const t=r[e],i=new yi;i.x=l,i.y=0,i.totalWidth=this.width/h,i.totalHeight=this.height/h,i.width=t.width,i.height=this.height/h,i.firstMasterBarIndex=t.masterBars[0].index,i.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,l+=t.width;const a=s,n=e;this._system.buildBoundingsLookup(0,0),this.registerPartial(i,(e=>{let s=this._system.getBarX(t.masterBars[0].index)+this._system.accoladeWidth;0===n&&(s-=this._system.x+this._system.accoladeWidth),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=A.Left,he.debug(this.name,`Rendering partial from bar ${t.masterBars[0].index} to ${t.masterBars[t.masterBars.length-1].index}`,null),this._system.paintPartial(-s,this._system.y,e,a,t.masterBars.length)})),s+=t.masterBars.length}this.height=this.layoutAndRenderBottomScoreInfo(this.height),this.height=this.layoutAndRenderAnnotation(this.height),this.height+=this.pagePadding[3]}finalizeStaffSystem(){this._system.scaleToWidth(this._system.width),this._system.finalizeSystem()}}class Go extends Rn{constructor(){super(...arguments),this._systems=[],this._allMasterBarRenderers=[],this._barsFromPreviousSystem=[]}get name(){return"PageView"}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case at.Automatic:this.systemsLayoutMode=Zr.Automatic;break;case at.UseModelLayout:this.systemsLayoutMode=Zr.FromModelWithScale}let e=this.pagePadding[1];this.width=this.renderer.width,this._allMasterBarRenderers=[],e=this.layoutAndRenderScoreInfo(e,-1),e=this.layoutAndRenderTunings(e,-1),e=this.layoutAndRenderChordDiagrams(e,-1),e=this.layoutAndRenderScore(e),e=this.layoutAndRenderBottomScoreInfo(e),e=this.layoutAndRenderAnnotation(e),this.height=(e+this.pagePadding[3])*this.renderer.settings.display.scale}get supportsResize(){return!0}get firstBarX(){let e=this.pagePadding[0];return this._systems.length>0&&(e+=this._systems[0].accoladeWidth),e}doResize(){let e=this.pagePadding[1];this.width=this.renderer.width;const 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.layoutAndRenderBottomScoreInfo(e),e=this.layoutAndRenderAnnotation(e),this.height=(e+this.pagePadding[3])*this.renderer.settings.display.scale}layoutAndRenderTunings(e,t=-1){if(!this.tuningGlyph)return e;const s=this.renderer.settings.display.resources;this.tuningGlyph.x=this.pagePadding[0],this.tuningGlyph.width=this.scaledWidth,this.tuningGlyph.doLayout();const i=Math.round(this.tuningGlyph.height),a=new yi;return a.x=0,a.y=e,a.width=this.scaledWidth,a.height=i,a.totalWidth=this.scaledWidth,a.totalHeight=t<0?e+a.height:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=A.Center,this.tuningGlyph.paint(0,0,e)})),e+i}layoutAndRenderChordDiagrams(e,t=-1){if(!this.chordDiagrams)return e;const s=this.renderer.settings.display.resources;this.chordDiagrams.width=this.scaledWidth,this.chordDiagrams.doLayout();const i=Math.round(this.chordDiagrams.height),a=new yi;return a.x=0,a.y=e,a.width=this.scaledWidth,a.height=i,a.totalWidth=this.scaledWidth,a.totalHeight=t<0?e+i:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=A.Center,this.chordDiagrams.paint(0,0,e)})),e+i}layoutAndRenderScoreInfo(e,t=-1){he.debug(this.name,"Layouting score info");const s=new yi;s.x=0,s.y=e;let i=0;const a=this.renderer.settings.display.resources,r=[];for(const[e,t]of Rn.HeaderElements.value)if(this.headerGlyphs.has(e)){const t=this.headerGlyphs.get(e);t.y=i,this.alignScoreInfoGlyph(t);let s=t.font.size;if(e===Je.Words&&this.headerGlyphs.has(Je.Music)){this.headerGlyphs.get(Je.Music).textAlign!==t.textAlign&&(s=0)}i+=s,r.push(t)}return r.length>0&&(i=Math.floor(i+17),s.width=this.scaledWidth,s.height=i,s.totalWidth=this.scaledWidth,s.totalHeight=t<0?e+s.height:t,this.registerPartial(s,(e=>{e.color=a.scoreInfoColor,e.textAlign=A.Center;for(const t of r)t.paint(0,0,e)}))),e+i}resizeAndRenderScore(e,t){if(this.renderer.settings.display.barsPerRow>0||this.systemsLayoutMode===Zr.FromModelWithScale)for(let s=0;s<this._systems.length;s++){const i=this._systems[s];this.fitSystem(i),e+=this.paintSystem(i,t)}else{this._systems=[];let s=0;const i=this.maxWidth;let a=this.createEmptyStaffSystem();for(a.index=this._systems.length,a.x=this.pagePadding[0],a.y=e;s<this._allMasterBarRenderers.length;){let r=this._allMasterBarRenderers[s];if(a.width+r.width<=i||0===a.masterBarsRenderers.length)a.addMasterBarRenderers(this.renderer.tracks,r),s++;else{for(;r&&!r.canWrap&&a.masterBarsRenderers.length>1;)r=a.revertLastBar(),s--;a.isFull=!0,a.isLast=this.lastBarIndex===a.lastBarIndex,this._systems.push(a),this.fitSystem(a),e+=this.paintSystem(a,t),a=this.createEmptyStaffSystem(),a.index=this._systems.length,a.x=this.pagePadding[0],a.y=e}}a.isLast=this.lastBarIndex===a.lastBarIndex,this.fitSystem(a),e+=this.paintSystem(a,t)}return e}layoutAndRenderScore(e){let t=this.firstBarIndex;const s=this.lastBarIndex;for(this._systems=[];t<=s;){const i=this.createStaffSystem(t,s);this._systems.push(i),i.x=this.pagePadding[0],i.y=e,t=i.lastBarIndex+1,this.fitSystem(i),he.debug(this.name,`Rendering partial from bar ${i.firstBarIndex} to ${i.lastBarIndex}`,null),e+=this.paintSystem(i,e)}return e}paintSystem(e,t){const s=Math.floor(e.height),i=new yi;return i.x=0,i.y=e.y,i.totalWidth=this.scaledWidth,i.totalHeight=t,i.width=this.scaledWidth,i.height=s,i.firstMasterBarIndex=e.firstBarIndex,i.lastMasterBarIndex=e.lastBarIndex,e.buildBoundingsLookup(0,0),this.registerPartial(i,(t=>{this.renderer.canvas.color=this.renderer.settings.display.resources.mainGlyphColor,this.renderer.canvas.textAlign=A.Left,e.paint(0,-i.y/this.renderer.settings.display.scale,t)})),s}fitSystem(e){e.isFull||e.width>this.maxWidth||this.renderer.settings.display.justifyLastSystem?e.scaleToWidth(this.maxWidth):e.scaleToWidth(e.width),e.finalizeSystem()}getBarsPerSystem(e){let t=this.renderer.settings.display.barsPerRow;if(this.systemsLayoutMode===Zr.FromModelWithScale){let s,i;this.renderer.tracks.length>1?(s=this.renderer.score.defaultSystemsLayout,i=this.renderer.score.systemsLayout):(s=this.renderer.tracks[0].defaultSystemsLayout,i=this.renderer.tracks[0].systemsLayout),t=e<i.length?i[e]:s}return t}createStaffSystem(e,t){const s=this.createEmptyStaffSystem();s.index=this._systems.length;const i=this.getBarsPerSystem(s.index),a=this.maxWidth,r=t+1;let n=e;for(;n<r;){if(this._barsFromPreviousSystem.length>0)for(const e of this._barsFromPreviousSystem)s.addMasterBarRenderers(this.renderer.tracks,e),n=e.lastMasterBarIndex;else{const e=this.multiBarRestInfo,t=null!==e&&e.has(n)?e.get(n):null,i=s.addBars(this.renderer.tracks,n,t);this._allMasterBarRenderers.push(i),n=i.lastMasterBarIndex}this._barsFromPreviousSystem=[];let e=!1;if((-1===i&&s.width>=a&&0!==s.masterBarsRenderers.length||s.masterBarsRenderers.length===i+1)&&(e=!0),e){let e=s.revertLastBar();if(e)for(this._barsFromPreviousSystem.push(e);e&&!e.canWrap&&s.masterBarsRenderers.length>1;)e=s.revertLastBar(),e&&this._barsFromPreviousSystem.push(e);return s.isFull=!0,s.isLast=!1,this._barsFromPreviousSystem.reverse(),s}let t=!1,r=!0;for(const e of this.renderer.tracks)e.lineBreaks&&e.lineBreaks.has(n+1)?t=!0:r=!1;if(t&&r)return s.isFull=!0,s.isLast=!1,s;s.x=0,n++}return s.isLast=t===s.lastBarIndex,s}get maxWidth(){return this.scaledWidth-this.pagePadding[0]-this.pagePadding[2]}}class Uo extends Tr{constructor(e,t,s,i){super(e,t,i,Uo.getMusicSymbol(s))}static getMusicSymbol(e){switch(e){case tt.Natural:return I.AccidentalNatural;case tt.Sharp:return I.AccidentalSharp;case tt.Flat:return I.AccidentalFlat;case tt.NaturalQuarterNoteUp:return I.AccidentalQuarterToneNaturalArrowUp;case tt.SharpQuarterNoteUp:return I.AccidentalQuarterToneSharpArrowUp;case tt.FlatQuarterNoteUp:return I.AccidentalQuarterToneFlatArrowUp;case tt.DoubleSharp:return I.AccidentalDoubleSharp;case tt.DoubleFlat:return I.AccidentalDoubleFlat}return I.None}}class zo extends Tr{constructor(e,t,s,i){super(e,t,1,zo.getSymbol(s)),this._clef=s,this._clefOttava=i}static getSymbol(e){switch(e){case n.Neutral:return I.UnpitchedPercussionClef1;case n.C3:case n.C4:return I.CClef;case n.F4:return I.FClef;case n.G2:return I.GClef;default:return I.None}}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.bar(s,c.StandardNotationClef,this.renderer.bar),!1);let a;super.paint(e,t,s);let r=!1;switch(this._clefOttava){case o._15ma:a=new Tr(-4,0,.5,I.Quindicesima),r=!0;break;case o._8va:a=new Tr(-2,0,.5,I.Ottava),r=!0;break;case o._8vb:a=new Tr(-6,0,.5,I.Ottava);break;case o._15mb:a=new Tr(-8,0,.5,I.Quindicesima);break;default:return}let h=0,l=0;switch(this._clef){case n.Neutral:h=r?-12:15,l=0;break;case n.C3:case n.C4:h=r?-19:27,l=0;break;case n.F4:h=r?-9:27,l=-4;break;case n.G2:h=r?-37:30,l=0;break;default:return}a.renderer=this.renderer,a.doLayout();const d=this.width/2;a.paint(e+this.x+d+l,t+this.y+h,s)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}class Xo extends Br{constructor(e,t,s){super(e,t),this._note=s}static getSymbol(e,t){switch(e){case S.None:return I.None;case S.Normal:return t?I.ArticAccentAbove:I.ArticAccentBelow;case S.Heavy:return t?I.ArticMarcatoAbove:I.ArticMarcatoBelow;case S.Tenuto:return t?I.ArticTenutoAbove:I.ArticTenutoBelow;default:return I.None}}doLayout(){this.width=kr.Widths.get(I.ArticAccentAbove),this.height=kr.Heights.get(I.ArticAccentAbove)}paint(e,t,s){const i=this.renderer.getBeatDirection(this._note.beat),a=Xo.getSymbol(this._note.accentuated,i===je.Down),r=i===je.Up?t+this.y:t+this.y+this.height-2;s.fillMusicFontSymbol(e+this.x-2,r,1,a,!1)}}class Jo extends wr{constructor(e,t,s){super(e,t),this._size=0,this._size=s}doLayout(){this.width=this._size+3}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride),s.fillCircle(e+this.x,t+this.y,this._size),s.color=i}}class Yo extends Tr{constructor(e,t,s){super(e,t,s?Nr.GraceScale:1,I.NoteheadXOrnate)}}class $o extends Tr{constructor(e,t,s,i){super(e,t,i?Nr.GraceScale:1,$o.getSymbol(s))}static getSymbol(e){switch(e){case f.QuadrupleWhole:case f.DoubleWhole:case f.Whole:case f.Half:return I.NoteheadDiamondWhiteWide;default:return I.NoteheadDiamondBlackWide}}}class qo extends wr{constructor(e,t,s){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=je.Up,this._startX=0,this._startY=0,this._endX=0,this._endY=0,this._tieHeight=0,this._shouldDraw=!1,this.startBeat=e,this.endBeat=t,this.forEnd=s}doLayout(){if(this.width=0,!this.endBeat)return void(this._shouldDraw=!1);const e=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar);this.startNoteRenderer=e;const 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=qo.calculateActualTieHeight(1,this._startX,this._startY,this._endX,this._endY,this.tieDirection===je.Down,this._tieHeight,4).h),this.tieDirection===je.Up&&(this.y-=this.height))}paint(e,t,s){this._shouldDraw&&(this.shouldDrawBendSlur()?qo.drawBendSlur(s,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===je.Down,1):qo.paintTie(s,1,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===je.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,s,i){return 22}getBeamDirection(e,t){return je.Down}getStartY(){return 0}getEndY(){return 0}getStartX(){return 0}getEndX(){return 0}static calculateActualTieHeight(e,t,s,i,a,r,n,o){const h=qo.computeBezierControlPoints(e,t,s,i,a,r,n,o);t=h[0],s=h[1];const l=h[2],c=h[3];i=h[6],a=h[7];const d=(t-l)/(t-2*l+i),u=qo.calculateExtrema(t,s,l,c,i,a,d),p=u.length>0?Math.min(t,i,u[0]):Math.min(t,i),g=u.length>0?Math.max(t,i,u[0]):Math.max(t,i),m=(s-c)/(s-2*c+a),f=qo.calculateExtrema(t,s,l,c,i,a,m),y=f.length>0?Math.min(s,a,f[1]):Math.min(s,a),b=f.length>0?Math.max(s,a,f[1]):Math.max(s,a),S=new Is;return S.x=p,S.y=y,S.w=g-p,S.h=b-y,S}static calculateExtrema(e,t,s,i,a,r,n){if(n<=0||1<=n)return[];const o=e+(s-e)*n,h=t+(i-t)*n;return[o+(s+(a-s)*n-o)*n,h+(i+(r-i)*n-h)*n]}static computeBezierControlPoints(e,t,s,i,a,r,n,o){if(t===i&&s===a)return[];if(i<t){let e=t;t=i,i=e,e=s,s=a,a=e}n*=e,o*=e;let h=a-s,l=i-t;const c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;const d=(i+t)/2,u=(a+s)/2;return[t,s,d+n*h,u+n*l,d+(n-o)*h,u+(n-o)*l,i,a]}static paintTie(e,t,s,i,a,r,n=!1,o=22,h=4){const l=qo.computeBezierControlPoints(t,s,i,a,r,n,o,h);e.beginPath(),e.moveTo(l[0],l[1]),e.quadraticCurveTo(l[2],l[3],l[6],l[7]),e.quadraticCurveTo(l[4],l[5],l[0],l[1]),e.closePath(),e.fill()}static drawBendSlur(e,t,s,i,a,r,n,o){let h=a-s,l=i-t;const c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;const d=(i+t)/2,u=(a+s)/2;let p=qo.BendSlurHeight*n;i-t<20&&(p/=2);const g=d+p*h,m=u+p*l;if(e.beginPath(),e.moveTo(t,s),e.lineTo(g,m),e.lineTo(i,a),e.stroke(),o){const t=e.measureText(o).width,s=r?0:-e.font.size;e.fillText(o,g-t/2,m+s)}}}qo.BendSlurHeight=11;class Ko extends wr{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=Ko.Size}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride),this._isOpen?qo.paintTie(s,1,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):qo.paintTie(s,1,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3),s.color=i}}Ko.Size=6;class jo{constructor(e,t,s){this.line=0,this.line=e,this.isGhost=t,this.color=s}}class Qo extends wr{constructor(e){super(0,0),this._infos=[],this._glyphs=[],this.isEmpty=!0,this._isOpen=e}addParenthesis(e){const t=this.renderer,s=t.getNoteLine(e),i=e.isGhost||this.isTiedBend(e)&&t.settings.notation.isNotationElementVisible(C.ParenthesisOnTiedBends),a=cn.noteColor(t.resources,H.Effects,e);this.add(new jo(s,i,a))}addParenthesisOnLine(e,t){const s=new jo(e,t,void 0);this.add(s)}add(e){this._infos.push(e),e.isGhost&&(this.isEmpty=!1)}isTiedBend(e){return!!e.isTieDestination&&(!!e.tieOrigin.hasBend||this.isTiedBend(e.tieOrigin))}doLayout(){const e=this.renderer;this._infos.sort(((e,t)=>e.line-t.line));let t=null;const s=e.getScoreHeight(1);for(let i=0,a=this._infos.length;i<a;i++){let a;if(this._infos[i].isGhost)if(t){const a=e.getScoreY(this._infos[i].line)+s;t.height=a-t.y}else a=new Ko(this._isOpen),a.colorOverride=this._infos[i].color,a.renderer=this.renderer,a.y=e.getScoreY(this._infos[i].line)-s,a.height=2*s,a.doLayout(),this._glyphs.push(a),t=a;else t=null}this.width=this._glyphs.length>0?this._glyphs[0].width:0}paint(e,t,s){super.paint(e,t,s);for(const i of this._glyphs)i.paint(e+this.x,t+this.y,s)}}class Zo{constructor(e,t){this.steps=0,this.glyph=e,this.steps=t}}class eh extends wr{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new bi,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){const s=new Zo(e,t);this._infos.push(s),(!this.minNote||this.minNote.steps>s.steps)&&(this.minNote=s),(!this.maxNote||this.maxNote.steps<s.steps)&&(this.maxNote=s)}doLayout(){this._infos.sort(((e,t)=>t.steps-e.steps));let e=0,t=!1,s=0,i=!1;const a=this.direction;let r=0;for(let n=0,o=this._infos.length;n<o;n++){const o=this._infos[n].glyph;o.renderer=this.renderer,o.doLayout();let h=!1;0===n?e=o.width:Math.abs(s-this._infos[n].steps)<=1?t?t=!1:(h=!0,o.x=e,i=!0,t=!0):t=!1,a===je.Down?o.x=h?0:e:o.x=h?e:0,o.x+=this.noteStartX,s=this._infos[n].steps,r=Math.max(r,o.x+o.width),o instanceof Nr&&o.centerOnStem&&(o.x=e)}i?(this._noteHeadPadding=0,this.upLineX=e,this.downLineX=e):(this._noteHeadPadding=a===je.Down?-e:0,r+=this._noteHeadPadding,this.upLineX=r,this.downLineX=0),this.displacedX=e,this.width=r}paint(e,t,s){e+=this.x,t+=this.y,this.paintLedgerLines(e,t,s);const i=this._infos,a=e+this._noteHeadPadding;for(const e of i)e.glyph.renderer=this.renderer,e.glyph.paint(a,t,s)}paintLedgerLines(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{if(!this.minNote)return;const a=this.renderer,r=(jr(i,cn.bar(s,c.StandardNotationStaffLine,a.bar,!0),!1),3),n=this.width-this.noteStartX+2*r,o=a.getLineHeight(1),h=a.getLineY(-1),l=a.getLineY(a.drawnLineCount),d=a.getLineY(this.minNote.steps/2),u=a.getLineY(this.maxNote.steps/2);let p=h;for(;p>=d;)s.fillRect(e-r+this.noteStartX,t+p|0,n,Un.StaffLineThickness),p-=o;for(p=l;p<=u;)s.fillRect(e-r+this.noteStartX,t+p|0,n,Un.StaffLineThickness),p+=o}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}class th extends Tr{constructor(e,t,s){super(e,t,1,th.getSymbol(s))}static getSymbol(e){switch(e){case f.ThirtySecond:return I.Tremolo3;case f.Sixteenth:return I.Tremolo2;case f.Eighth:return I.Tremolo1;default:return I.None}}}class sh extends wr{constructor(){super(0,0)}doLayout(){this.width=26}paint(e,t,s){const i=this.renderer,a=i.getLineHeight(i.heightLineCount-1),r=i.getLineY(0)+i.getLineHeight(i.drawnLineCount-1)/2-a/2,n=s.lineWidth;s.lineWidth=2,s.moveTo(e+this.x,t+r),s.lineTo(e+this.x+this.width,t+r+a),s.moveTo(e+this.x,t+r+a),s.lineTo(e+this.x+this.width,t+r),s.stroke(),s.lineWidth=n}}class ih extends eh{constructor(){super(...arguments),this._noteGlyphLookup=new Map,this._notes=[],this._deadSlapped=null,this._tremoloPicking=null,this.aboveBeatEffects=new Map,this.belowBeatEffects=new Map}get direction(){return this.beamingHelper.direction}getNoteX(e,t){if(this._noteGlyphLookup.has(e.id)){const s=this._noteGlyphLookup.get(e.id);let i=this.x+s.x+this._noteHeadPadding;switch(t){case tn.Left:break;case tn.Center:i+=s.width/2;break;case tn.Right:i+=s.width}return i}return 0}getNoteY(e,t){if(this._noteGlyphLookup.has(e.id)){const s=this._noteGlyphLookup.get(e.id);let i=this.y+s.y;switch(t){case en.TopWithStem:i-=this.renderer.getStemSize(this.beamingHelper);break;case en.Top:i-=s.height/2;break;case en.Center:break;case en.Bottom:i+=s.height/2;break;case en.BottomWithStem:i+=this.renderer.getStemSize(this.beamingHelper)}return i}return 0}addNoteGlyph(e,t,s){super.add(e,s),this._noteGlyphLookup.set(t.id,e),this._notes.push(t)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.upLineX,e+this.x+this.downLineX)}doLayout(){super.doLayout();const e=this.renderer;this.beat.deadSlapped&&(this._deadSlapped=new sh,this._deadSlapped.renderer=this.renderer,this._deadSlapped.doLayout(),this.width=this._deadSlapped.width);const t=this.direction;let s=0,i=0,a=1,r=-a,n=!1,o=!1;this.beat.deadSlapped?(i=e.getScoreY(0),s=e.getScoreY(e.heightLineCount)):this.direction===je.Up?(n=!1,o=!0,i=e.getScoreY(this.maxNote.steps+2),s=e.getScoreY(this.minNote.steps)-e.getStemSize(this.beamingHelper,!0)):(n=!0,o=!1,i=e.getScoreY(this.minNote.steps-1),a*=-1,r*=-1,s=e.getScoreY(this.maxNote.steps)+e.getStemSize(this.beamingHelper,!0));let h=null,l=null;for(const e of this.aboveBeatEffects.values())e.renderer=this.renderer,e.doLayout(),o&&(s+=r*e.height),e.y=s,(null===h||h>s)&&(h=s),(null===l||l<s)&&(l=s),o||(s+=r*e.height);for(const e of this.belowBeatEffects.values())e.renderer=this.renderer,e.doLayout(),n&&(i+=a*e.height),e.y=i,(null===h||h>i)&&(h=i),(null===l||l<i)&&(l=i),n||(i+=a*e.height);if(null!==h&&e.registerBeatEffectOverflows(h,l??0),this.beat.isTremolo&&!this.beat.deadSlapped){let e=0;const s=t===je.Up?this.minNote:this.maxNote;let i=t===je.Up?this.upLineX:this.downLineX;const a=this.beat.tremoloSpeed;switch(a){case f.ThirtySecond:e=t===je.Up?-15:15;break;case f.Sixteenth:e=t===je.Up?-12:15;break;case f.Eighth:e=t===je.Up?-10:10;break;default:e=t===je.Up?-10:15}this.beat.duration<f.Half&&(i=this.width/2),this._tremoloPicking=new th(i,s.glyph.y+e,a),this._tremoloPicking.renderer=this.renderer,this._tremoloPicking.doLayout()}}buildBoundingsLookup(e,t,s){for(const i of this._notes)if(this._noteGlyphLookup.has(i.id)){const a=this._noteGlyphLookup.get(i.id),r=new ki;r.note=i,r.noteHeadBounds=new Is,r.noteHeadBounds.x=t+this.x+this._noteHeadPadding+a.x,r.noteHeadBounds.y=s+this.y+a.y-a.height/2,r.noteHeadBounds.w=a.width,r.noteHeadBounds.h=a.height,e.addNote(r)}}paint(e,t,s){this.paintEffects(e,t,s),super.paint(e,t,s)}paintEffects(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.beat(s,Y.StandardNotationEffects,this.beat),!1);for(const i of this.aboveBeatEffects.values())i.paint(e+this.x+2,t+this.y,s);for(const i of this.belowBeatEffects.values())i.paint(e+this.x+2,t+this.y,s);this._tremoloPicking&&this._tremoloPicking.paint(e,t,s),this._deadSlapped&&this._deadSlapped.paint(e,t,s)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}class ah extends Tr{constructor(e,t,s){super(e,t,1,ah.getSymbol(s))}static getSymbol(e){switch(e){case f.QuadrupleWhole:return I.RestLonga;case f.DoubleWhole:return I.RestDoubleWhole;case f.Whole:return I.RestWhole;case f.Half:return I.RestHalf;case f.Quarter:return I.RestQuarter;case f.Eighth:return I.RestEighth;case f.Sixteenth:return I.RestSixteenth;case f.ThirtySecond:return I.RestThirtySecond;case f.SixtyFourth:return I.RestSixtyFourth;case f.OneHundredTwentyEighth:return I.RestOneHundredTwentyEighth;case f.TwoHundredFiftySixth:return I.RestTwoHundredFiftySixth;default:return I.None}}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){this.internalPaint(e,t,s,Y.StandardNotationRests)}internalPaint(e,t,s,i){const a={stack:[],error:void 0,hasError:!1};try{jr(a,cn.beat(s,i,this.beat),!1);super.paint(e,t,s)}catch(e){a.error=e,a.hasError=!0}finally{on(a)}}}class rh{constructor(){this.x=0,this.y=-3e3,this.width=0}}class nh extends hn{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));const e=[];e.push(new rh);for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t];s.renderer=this.renderer,s.doLayout();let i=0;for(;e[i].y>s.y;)i++,i===e.length&&e.push(new rh);s.x=i,e[i].y=s.y+21,e[i].width<s.width&&(e[i].width=s.width)}this.width=0;for(const t of e)this.width+=t.width,t.x=this.width;for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t],i=e[s.x];s.x=this.width-i.x}}}class oh extends eh{get direction(){return je.Up}constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new nh,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new Qo(!0),this._postNoteParenthesis=new Qo(!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,s){const i=this.renderer,a=new Nr(0,0,f.Quarter,!0),r=i.accidentalHelper.applyAccidentalForValue(this._beat,e,t,!0),n=i.accidentalHelper.getNoteLineForValue(e,!1);if(a.y=i.getScoreY(n),this._showParenthesis&&(this._preNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.addParenthesisOnLine(n,!0),this._postNoteParenthesis.addParenthesisOnLine(n,!0)),r!==tt.None){const e=new Uo(0,a.y,r,Nr.GraceScale);e.renderer=this.renderer,this._accidentals.renderer=this.renderer,this._accidentals.addGlyph(e)}this._noteValueLookup.set(e,a),this.add(a,n),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+oh.ElementPadding),this._accidentals.isEmpty||(e+=this._accidentals.width+oh.ElementPadding,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+oh.ElementPadding),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+oh.ElementPadding,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+oh.ElementPadding)}paint(e,t,s){this._accidentals.isEmpty||this._accidentals.paint(e+this.x,t+this.y,s),this._showParenthesis&&(this._preNoteParenthesis.paint(e+this.x,t+this.y,s),this._postNoteParenthesis.paint(e+this.x,t+this.y,s)),super.paint(e,t,s)}}oh.ElementPadding=2;class hh extends wr{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,s,i,a,r,n,o){qo.drawBendSlur(e,t,s,i,a,r,n,o)}doLayout(){super.doLayout(),this.width=0;for(const e of this.BendNoteHeads)e.doLayout(),this.width+=e.width+10}getTieDirection(e,t){return t.getBeatDirection(e)===je.Up?je.Down:je.Up}}hh.EndPadding=8;class lh extends ae{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class ch extends wr{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);const t=this.createRenderingPoints(e);this._renderPoints.set(e.id,t),(-1===this._maxBendValue||this._maxBendValue<e.maxBendPoint.value)&&(this._maxBendValue=e.maxBendPoint.value);let s=0;switch(e.bendType){case p.Bend:s=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||s<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=s):(-1===this._bendEndMinValue||s<this._bendEndMinValue)&&(this._bendEndMinValue=s);break;case p.Release:s=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s);break;case p.BendRelease:s=t[1].value,(-1===this._bendMiddleMinValue||s<this._bendMiddleMinValue)&&(this._bendMiddleMinValue=s),s=t[2].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s);break;case p.Prebend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s);break;case p.PrebendBend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s),s=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||s<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=s):(-1===this._bendEndMinValue||s<this._bendEndMinValue)&&(this._bendEndMinValue=s);break;case p.PrebendRelease:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s),s=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s)}}doLayout(){super.doLayout();const e=this._maxBendValue*ch.BendValueHeight;this.renderer.registerOverflowTop(e);let t=0;for(const e of this._notes){const s=this._renderPoints.get(e.id);switch(e.bendType){case p.Bend:s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case p.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t);break;case p.BendRelease:s[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[2].lineValue=t);break;case p.Prebend:s[0].lineValue=this._preBendMinValue;break;case p.PrebendBend:s[0].lineValue=this._preBendMinValue,s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case p.PrebendRelease:s[0].lineValue=this._preBendMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t)}}this.width=0,this._notes.sort(((e,t)=>e.isStringed?e.string-t.string:e.realValue-t.realValue))}createRenderingPoints(e){const t=[];switch(e.bendType){case p.Custom:for(const s of e.bendPoints)t.push(new lh(s.offset,s.value));break;case p.BendRelease:t.push(new lh(0,e.bendPoints[0].value)),t.push(new lh(ae.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new lh(ae.MaxPosition,e.bendPoints[3].value));break;case p.Bend:case p.Hold:case p.Prebend:case p.PrebendBend:case p.PrebendRelease:case p.Release:t.push(new lh(0,e.bendPoints[0].value)),t.push(new lh(ae.MaxPosition,e.bendPoints[1].value))}return t}paint(e,t,s){const i=s.color;this._notes.length>1&&(s.color=this.renderer.resources.secondaryGlyphColor);for(const a of this._notes){const r=this._renderPoints.get(a.id),n=this.renderer;let o=a,h=!1,l=null,c=!1;const d=a.bendStyle===u.Gradual?"grad.":"";let g=null;for(;o.isTieOrigin;){const e=o.tieDestination;if(l=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,e.beat.voice.bar),!l||n.staff!==l.staff)break;if(o=e,h=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes||o.vibrato!==N.None){c=!0;break}}g=o.beat,l=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,g.voice.bar),g.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(g=null);let m=0,f=0;const y=t+n.y;m=e+n.x,r[0].value>0||a.isContinuedBend?m+=n.getBeatX(a.beat,Qr.MiddleNotes):m+=n.getNoteX(a,tn.Right),f=!g||g.isLastOfVoice&&!c?e+l.x+l.postBeatGlyphsStart:c||!g.nextBeat?e+l.x+l.getBeatX(g,Qr.MiddleNotes):a.bendType===p.Hold?e+l.x+l.getBeatX(g.nextBeat,Qr.OnNotes):e+l.x+l.getBeatX(g.nextBeat,Qr.PreNotes),h||(f-=ch.ArrowSize);const b=(f-m)/ae.MaxPosition;s.beginPath();for(let e=0,t=r.length-1;e<t;e++){const t=r[e];let i=r[e+1];0!==e||0===t.value||a.isTieDestination||this.paintBend(a,new lh(0,0),t,m,y,b,d,s),a.bendType!==p.Prebend?(0===e&&(m+=2),this.paintBend(a,t,i,m,y,b,d,s)):a.isTieOrigin&&a.tieDestination.hasBend&&(i=new lh(ae.MaxPosition,t.value),i.lineValue=t.lineValue,this.paintBend(a,t,i,m,y,b,d,s))}if(o.vibrato!==N.None){const i=f-e+ch.ArrowSize-l.x,a=y-t-ch.BendValueHeight*r[r.length-1].lineValue,n=new vo(i,a,o.vibrato,1.2);n.beat=o.beat,n.renderer=l,n.doLayout(),n.paint(e+l.x,t,s)}s.color=i}}paintBend(e,t,s,i,a,r,n,o){const h=this.renderer,l=this.renderer.resources,c=h.lineOffset/2,d=i+r*t.offset,u=ch.BendValueHeight;let p=a-u*t.lineValue;0===t.value?s.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,en.Top):p+=h.getNoteY(e,en.Center):p+=c;const g=i+r*s.offset;let m=a-u*s.lineValue;0===s.lineValue?m+=h.getNoteY(e,en.Center):m+=c;let f=0;const y=ch.ArrowSize;if(s.value>t.value?(m+y>p&&(m=p-y),o.beginPath(),o.moveTo(g,m),o.lineTo(g-.5*y,m+y),o.lineTo(g+.5*y,m+y),o.closePath(),o.fill(),f=y):s.value!==t.value&&(m<p&&(m=p+y),o.beginPath(),o.moveTo(g,m),o.lineTo(g-.5*y,m-y),o.lineTo(g+.5*y,m-y),o.closePath(),o.fill(),f=-y),o.beginPath(),t.value===s.value){if(t.lineValue>0){let e=g;const t=ch.DashSize,s=d+t;if((e-d)/(2*t)<1)o.moveTo(e,p),o.lineTo(d,p);else for(;e>s;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>d?(o.moveTo(d,p),o.bezierCurveTo((d+g)/2,p,g,p,g,m+f),o.stroke()):(o.moveTo(d,p),o.lineTo(g,m),o.stroke());if(n&&t.offset<s.offset){o.font=l.graceFont;const e=o.measureText(n).width;let t=0,s=0;if(p>m){const i=Math.abs(p-m);t=i>1.3*o.font.size?p-i/2:p,s=(d+g-e)/2}else t=p,s=g-e;o.fillText(n,s,t)}if(0!==s.value&&t.value!==s.value){let e=s.value;const i=s.value>t.value;e=Math.abs(e);let r="";if(4===e)r="full",e-=4;else if(e>=4||e<=-4){const t=e/4|0;r+=t,e-=4*t}if(e>0&&(r+=ch.getFractionSign(e)),""!==r){m=a-u*s.value;let e=m;i||(e=p+1*Math.abs(m-p)/3),o.font=l.tablatureFont;const t=o.measureText(r).width,n=e-.5*l.tablatureFont.size-2,h=g-t/2;o.fillText(r,h,n)}}}static getFractionSign(e){switch(e){case 1:return"¼";case 2:return"½";case 3:return"¾";default:return`${e}/ 4`}}}ch.ArrowSize=6,ch.DashSize=3,ch.BendValueHeight=6;class dh extends wr{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===W.Custom)return e.whammyBarPoints;const t=[];switch(e.whammyBarType){case W.Dive:case W.Hold:case W.PrediveDive:case W.Predive:t.push(new ae(0,e.whammyBarPoints[0].value)),t.push(new ae(ae.MaxPosition,e.whammyBarPoints[1].value));break;case W.Dip:t.push(new ae(0,e.whammyBarPoints[0].value)),t.push(new ae(ae.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new ae(ae.MaxPosition,e.whammyBarPoints[e.whammyBarPoints.length-1].value))}return t}doLayout(){super.doLayout(),this._isSimpleDip=this.renderer.settings.notation.notationMode===P.SongBook&&this._beat.whammyBarType===W.Dip;let e=null,t=null,s=this._beat;for(;s&&s.hasWhammyBar;)(!e||e.value>s.minWhammyPoint.value)&&(e=s.minWhammyPoint),(!t||t.value<s.maxWhammyPoint.value)&&(t=s.maxWhammyPoint),s=s.nextBeat;let i=t.value>0?Math.abs(this.getOffset(t.value)):0;(i>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(C.ZerosOnDiveWhammys))&&(i+=2*this.renderer.resources.tablatureFont.size);const a=e.value<0?Math.abs(this.getOffset(e.value)):0;this.renderer.registerOverflowTop(i+a);i>this.renderer.staff.getSharedLayoutData(dh.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(dh.TopOffsetSharedDataKey,i)}getOffset(e){if(0===e)return 0;let t=dh.PerHalfSize+Math.log2(Math.abs(e)/2)*dh.PerHalfSize;return e<0&&(t=-t),t}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.beat(s,Y.StandardNotationEffects,this._beat),!1);const a=this.renderer;let r=this._beat.nextBeat,n=null,o=Qr.PreNotes;r&&(n=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.voice.bar),n&&n.staff===a.staff&&(n===a||r.hasWhammyBar)?o=!r.hasWhammyBar||a.settings.notation.notationMode===P.SongBook&&r.whammyBarType===W.Dip?Qr.PreNotes:Qr.MiddleNotes:(r=null,n=null));let h=0,l=0;this._isSimpleDip?(h=e+a.x+a.getBeatX(this._beat,Qr.OnNotes)-2,l=e+a.x+a.getBeatX(this._beat,Qr.PostNotes)+2):(h=e+a.x+a.getBeatX(this._beat,Qr.MiddleNotes),l=n?e+n.x+n.getBeatX(r,o):e+a.x+a.width-2);const c=s.textAlign;if(s.textAlign=A.Center,this._renderPoints.length>=2){const e=(l-h)/ae.MaxPosition;s.beginPath();const i=t+this.renderer.staff.getSharedLayoutData(dh.TopOffsetSharedDataKey,0);let a=this._beat.whammyStyle===u.Gradual?"grad.":"";for(let t=0,r=this._renderPoints.length-1;t<r;t++){const n=this._renderPoints[t],o=this._renderPoints[t+1],l=t<r-2?this._renderPoints[t+2]:null;let c=0===t;0!==t||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new ae(0,0),n,o,h,i,e,s),c=!1),this.paintWhammy(c,n,o,l,h,i,e,s,a),a=""}s.stroke()}s.textAlign=c}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}paintWhammy(e,t,s,i,a,r,n,o,h){const l=a+n*t.offset,c=a+n*s.offset,d=r-this.getOffset(t.value),u=r-this.getOffset(s.value);if(t.offset===s.offset){const e=dh.DashSize;if(Math.abs(u-d)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{const t=Math.max(d,u);let s=Math.min(d,u);for(;t>s;)o.moveTo(l,s),o.lineTo(l,s+e),s+=2*e}o.stroke()}else if(t.value===s.value){const e=dh.DashSize;if(Math.abs(c-l)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(l,c);const s=Math.min(l,c);for(;t>s;)o.moveTo(t,d),o.lineTo(t-e,d),t-=2*e}o.stroke()}else o.moveTo(l,d),o.lineTo(c,u);const p=this.renderer.resources;if(e&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let e=d;e-=p.tablatureFont.size+2,this.renderer.settings.notation.isNotationElementVisible(C.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2,o.fillText(h,l,e))}let g=Math.abs(s.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(C.ZerosOnDiveWhammys)&&!this._isSimpleDip)&&t.value!==s.value){let e="";if(s.value<0&&(e+="-"),g>=4){const t=g/4|0;e+=t,g-=4*t}else 0===g&&(e+="0");g>0&&(e+=ch.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(d,u)-p.tablatureFont.size-2:(a=t.offset===s.offset?Math.min(d,u):u,a-=p.tablatureFont.size+2,i&&i.value>s.value&&(a-=2));const r=c;o.fillText(e,r,a)}}}dh.TopOffsetSharedDataKey="tab.whammy.topoffset",dh.PerHalfSize=6,dh.DashSize=3;class uh extends hh{constructor(e){super(0,0),this._beat=e}doLayout(){const e=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case W.None:case W.Custom:case W.Hold:return;case W.Dive:case W.PrediveDive:{const e=new oh(this._beat,!1);e.renderer=this.renderer;const t=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(const s of this._beat.notes)s.isTieOrigin||e.addGlyph(this.getBendNoteValue(s,t),t.value%2!=0,void 0);e.doLayout(),this.BendNoteHeads.push(e)}break;case W.Dip:if(e===P.SongBook){const e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+uh.SimpleDipHeight+uh.SimpleDipPadding}else{const e=new oh(this._beat,!1);if(e.renderer=this.renderer,this.renderer.settings.notation.notationMode===P.GuitarPro){const t=this._beat.whammyBarPoints[1];for(const s of this._beat.notes)e.addGlyph(this.getBendNoteValue(s,this._beat.whammyBarPoints[1]),t.value%2!=0,void 0)}e.doLayout(),this.BendNoteHeads.push(e);const t=new oh(this._beat,!1);if(t.renderer=this.renderer,this.renderer.settings.notation.notationMode===P.GuitarPro){const e=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(const s of this._beat.notes)t.addGlyph(this.getBendNoteValue(s,e),e.value%2!=0,void 0)}t.doLayout(),this.BendNoteHeads.push(t)}case W.Predive:}super.doLayout()}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{const a=this._beat;switch(a.whammyBarType){case W.None:case W.Custom:return}const r=this.renderer.settings.notation.notationMode,n=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,a.voice.bar),o=(jr(i,cn.beat(s,Y.StandardNotationEffects,a),!1),e+n.x+n.getBeatX(a,Qr.MiddleNotes)),h=this.getTieDirection(a,n);let l=1===this._beat.notes.length?h:je.Up;const c=s.textAlign,d=kr.Heights.get(I.NoteheadBlack);for(let i=0;i<a.notes.length;i++){const c={stack:[],error:void 0,hasError:!1};try{const p=a.notes[i];jr(c,cn.note(s,H.StandardNotationEffects,p),!1);let g=t+n.y;i>0&&i>=(this._beat.notes.length/2|0)&&(l=je.Down),l===je.Down?g+=n.getNoteY(p,en.Bottom):g+=n.getNoteY(p,en.Top);let m=e+n.x;a.isLastOfVoice?m+=n.width:m+=n.getBeatX(a,Qr.EndBeat),m-=8;const f=a.whammyStyle===u.Gradual&&0===i?"grad.":"";let y=null;p.isTieOrigin&&(y=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,p.tieDestination.beat.voice.bar),y&&y.staff===n.staff?m=e+y.x+y.getBeatX(p.tieDestination.beat,Qr.MiddleNotes):y=null);let b=d*Nr.GraceScale*.5;l===je.Up&&(b=-b);const S=a.whammyBarPoints.length>0?this.getBendNoteValue(p,a.whammyBarPoints[a.whammyBarPoints.length-1]):0;let _=0,w=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(S)?(_=this.BendNoteHeads[0].getNoteValueY(S)+b,w=!0):y&&(p.isTieOrigin&&p.tieDestination.beat.hasWhammyBar||p.beat.isContinuedWhammy)?(_=t+y.y+y.getNoteY(p.tieDestination,en.Top),w=!0,l===je.Down&&(_+=d)):p.isTieOrigin&&(_=y?t+y.y+y.getNoteY(p.tieDestination,en.Top):g,l===je.Down&&(_+=d)),a.whammyBarType){case W.Hold:p.isTieOrigin&&qo.paintTie(s,1,o,g,m,_,h===je.Down,22,4);break;case W.Dive:if(0===i){this.BendNoteHeads[0].x=m-this.BendNoteHeads[0].noteHeadOffset;const e=this.BendNoteHeads[0].y;this.BendNoteHeads[0].y=t+n.y,this.BendNoteHeads[0].paint(0,0,s),this.BendNoteHeads[0].containsNoteValue(S)&&(_-=e,_+=this.BendNoteHeads[0].y)}w?this.drawBendSlur(s,o,g,m,_,l===je.Down,1,f):p.isTieOrigin&&qo.paintTie(s,1,o,g,m,_,h===je.Down,22,4);break;case W.Dip:if(r===P.SongBook){if(0===i){const i=e+n.x+n.getBeatX(this._beat,Qr.OnNotes)-2,a=e+n.x+n.getBeatX(this._beat,Qr.PostNotes)+2,r=(i+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();s.font=this.renderer.resources.tablatureFont,s.fillText(o,r,t+this.y);const h=t+this.y+s.font.size+2,l=h+uh.SimpleDipHeight;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(s.moveTo(i,l),s.lineTo(r,h),s.lineTo(a,l)):(s.moveTo(i,h),s.lineTo(r,l),s.lineTo(a,h)),s.stroke()}p.isTieOrigin&&qo.paintTie(s,1,o,g,m,_,h===je.Down,22,4)}else{const e=(o+m)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+n.y,this.BendNoteHeads[0].paint(0,0,s);const i=this.getBendNoteValue(p,a.whammyBarPoints[1]),r=this.BendNoteHeads[0].getNoteValueY(i)+b;this.drawBendSlur(s,o,g,e,r,l===je.Down,1,f),this.BendNoteHeads[1].x=m-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=t+n.y,this.BendNoteHeads[1].paint(0,0,s),_=this.BendNoteHeads[1].getNoteValueY(S)+b,this.drawBendSlur(s,e,r,m,_,l===je.Down,1,f)}break;case W.PrediveDive:case W.Predive:let c=e+n.x+n.getBeatX(p.beat,Qr.PreNotes);c+=n.getPreNotesGlyphForBeat(p.beat).prebendNoteHeadOffset;const d=t+n.y+n.getScoreY(n.accidentalHelper.getNoteLineForValue(p.displayValue-(p.beat.whammyBarPoints[0].value/2|0),!1))+b;this.drawBendSlur(s,c,d,o,g,l===je.Down,1,f),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=m-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+n.y,this.BendNoteHeads[0].paint(0,0,s),this.drawBendSlur(s,o,g,m,_,l===je.Down,1,f))}}catch(e){c.error=e,c.hasError=!0}finally{on(c)}}s.textAlign=c}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}uh.SimpleDipHeight=2*dh.PerHalfSize,uh.SimpleDipPadding=2;class ph extends wr{constructor(e,t,s){super(e,t),this.width=s}}class gh extends Tr{constructor(e,t,s,i,a){super(e,t,a?Nr.GraceScale:1,s.getSymbol(i)),this._isGrace=a,this._articulation=s}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride);const a=this._isGrace?1:0;s.fillMusicFontSymbol(e+this.x,t+this.y+a,this.glyphScale,this.symbol,!1),this._articulation.techniqueSymbol!==I.None&&this._articulation.techniqueSymbolPlacement===R.Middle&&s.fillMusicFontSymbol(e+this.x,t+this.y+a,this.glyphScale,this._articulation.techniqueSymbol,!1),s.color=i}doLayout(){super.doLayout(),0===this.width&&(this.height=kr.Widths.get(I.NoteheadBlack)),0===this.height&&(this.height=kr.Heights.get(I.NoteheadBlack))}}class mh extends Tr{constructor(e,t){super(e,t,Nr.GraceScale,I.ArticStaccatoAbove)}paint(e,t,s){super.paint(e+3,t+5,s)}}class fh extends Tr{constructor(e,t){super(e,t,.5,I.PictEdgeOfCymbal)}paint(e,t,s){super.paint(e-3,t+this.height,s)}}class yh extends Tr{constructor(e,t,s=!1){super(e,t,Nr.GraceScale,I.GuitarGolpe),this.center=s}paint(e,t,s){super.paint(e,t+this.height,s)}}class bh extends Br{constructor(){super(...arguments),this._strings=new Set}addString(e){this._strings.add(e)}doLayout(){const e=kr.Widths.get(I.GuitarString0)*In.CircleNumberScale;this.height=(e+3)*this._strings.size,this.width=e}paint(e,t,s){const i=this.renderer.bar.staff.tuning.length;let a=0;const r=kr.Widths.get(I.GuitarString0)*In.CircleNumberScale,n=kr.Heights.get(I.NoteheadBlack);for(const o of this._strings){const h=i-o,l=I.GuitarString1+h;s.fillMusicFontSymbol(e+this.x+n/2,t+this.y+r+a,In.CircleNumberScale,l,!0),a+=r+3}}}class Sh extends Br{constructor(e,t,s,i,a){super(e,t),this.beatEffects=new Map,this.noteHeadElement=H.SlashNoteHead,this.effectElement=Y.SlashEffects,this._isGrace=i,this._symbol=Sh.getSymbol(s),this.beat=a}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,0===this.beat.notes.length?void 0:cn.note(s,this.noteHeadElement,this.beat.notes[0]),!1);const a=this._isGrace?1:0,r=this._isGrace?Nr.GraceScale:1;s.fillMusicFontSymbol(e+this.x,t+this.y+a,r,this._symbol,!1),this.paintEffects(e,t,s)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}paintEffects(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.beat(s,this.effectElement,this.beat),!1);for(const i of this.beatEffects.values())i.paint(e+this.x,t+this.y,s)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}doLayout(){const e=this._isGrace?Nr.GraceScale:1;this.width=kr.Widths.get(this._symbol)*e,this.height=kr.Heights.get(this._symbol)*e;let t=kr.Heights.get(this._symbol);for(const e of this.beatEffects.values())e.y+=t,e.x+=this.width/2,e.renderer=this.renderer,t+=7,e.doLayout()}static getSymbol(e){switch(e){case f.QuadrupleWhole:case f.DoubleWhole:case f.Whole:return I.NoteheadSlashWhiteWhole;case f.Half:return I.NoteheadSlashWhiteHalf;default:return I.NoteheadSlashVerticalEnds}}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width,e+this.x)}}class _h extends Hn{constructor(){super(...arguments),this._collisionOffset=-1e3,this._skipPaint=!1,this.slash=null,this.noteHeads=null,this.restGlyph=null}get effectElement(){return Y.StandardNotationEffects}getNoteX(e,t){return this.noteHeads?this.noteHeads.getNoteX(e,t):0}buildBoundingsLookup(e,t,s){this.noteHeads&&this.noteHeads.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteY(e,t){return this.noteHeads?this.noteHeads.getNoteY(e,t):0}updateBeamingHelper(){if(this.noteHeads)this.noteHeads.updateBeamingHelper(this.container.x+this.x);else if(this.restGlyph){if(this.restGlyph.updateBeamingHelper(this.container.x+this.x),this.renderer.bar.isMultiVoice&&-1e3===this._collisionOffset){this._collisionOffset=this.renderer.helpers.collisionHelper.applyRestCollisionOffset(this.container.beat,this.restGlyph.y,this.renderer.getScoreHeight(1)),this.y+=this._collisionOffset;const e=this.renderer.helpers.collisionHelper.restDurationsByDisplayTime;e.has(this.container.beat.playbackStart)&&e.get(this.container.beat.playbackStart).has(this.container.beat.playbackDuration)&&e.get(this.container.beat.playbackStart).get(this.container.beat.playbackDuration)!==this.container.beat.id&&(this._skipPaint=!0)}}else this.slash&&this.slash.updateBeamingHelper(this.container.x+this.x)}paint(e,t,s){this._skipPaint||super.paint(e,t,s)}doLayout(){const 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===f.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const s=new ah(0,e.getScoreY(t),this.container.beat.duration);if(this.restGlyph=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper,this.addNormal(s),this.renderer.bar.isMultiVoice)if(0===this.container.beat.voice.index){const t=mn.computeLineHeightsForRest(this.container.beat.duration),i=s.y-e.getScoreHeight(t[0]),a=s.y+e.getScoreHeight(t[1]);this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,i,a)}else this.renderer.helpers.collisionHelper.registerRest(this.container.beat);if(this.beamingHelper&&this.beamingHelper.applyRest(this.container.beat,t),this.container.beat.dots>0){this.addNormal(new ph(0,0,5));for(let e=0;e<this.container.beat.dots;e++){const e=new hn(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addEffect(e)}}}else{if(this.container.beat.slashed){const t=this.container.beat.graceType!==b.None,s=(e.heightLineCount-1)/2,i=e.getLineY(s),a=new Sh(0,i,this.container.beat.duration,t,this.container.beat);a.noteHeadElement=H.StandardNotationNoteHead,a.effectElement=Y.StandardNotationEffects,this.slash=a,a.beat=this.container.beat,a.beamingHelper=this.beamingHelper,this.addNormal(a)}else{const e=new ih;this.noteHeads=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;const t=new Qo(!1);t.renderer=this.renderer;for(const e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),t.addParenthesis(e));this.addNormal(e),t.isEmpty||(this.addNormal(new ph(0,0,4*(this.container.beat.graceType!==b.None?Nr.GraceScale:1))),this.addEffect(t))}if(this.container.beat.hasWhammyBar){const e=new uh(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addNormal(new ph(0,0,5));for(let t=0;t<this.container.beat.dots;t++){const t=new hn(0,0);t.renderer=this.renderer;for(const s of this.container.beat.notes){this.createBeatDot(e.getNoteLine(s),t).colorOverride=cn.noteColor(e.resources,H.StandardNotationEffects,s)}this.addEffect(t)}}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.slash&&(this.centerX=this.slash.x+this.slash.width/2)}createBeatDot(e,t){const s=this.renderer,i=new Jo(0,s.getScoreY(e),1.5);return t.addGlyph(i),i}createNoteHeadGlyph(e){const t=this.container.beat.graceType!==b.None,s=e.style;if(void 0!==s?.noteHead){const i=new Nr(0,0,e.beat.duration,t);return i.symbol=s.noteHead,s.noteHeadCenterOnStem&&(i.centerOnStem=!0),i}if(e.beat.voice.bar.staff.isPercussion){const s=me.getArticulation(e);if(s)return new gh(0,0,s,e.beat.duration,t);he.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new Yo(0,0,t):e.beat.graceType===b.BendGrace?new Nr(0,0,f.Quarter,!0):e.harmonicType===w.Natural?new $o(0,0,e.beat.duration,t):new Nr(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===b.BendGrace&&!e.hasBend)return;const t=this.renderer,s=this.createNoteHeadGlyph(e);s.colorOverride=cn.noteColor(t.resources,H.StandardNotationNoteHead,e);let i=t.getNoteLine(e);if(s.y=t.getScoreY(i),this.noteHeads.addNoteGlyph(s,e,i),e.harmonicType!==w.None&&e.harmonicType!==w.Natural){const a=e.displayValue+e.harmonicPitch,r=new $o(0,0,e.beat.duration,this.container.beat.graceType!==b.None);r.colorOverride=s.colorOverride,i=t.accidentalHelper.getNoteLineForValue(a,!1),r.y=t.getScoreY(i),this.noteHeads.addNoteGlyph(r,e,i)}const a=this.noteHeads.belowBeatEffects,r=this.noteHeads.aboveBeatEffects;if(e.isStaccato&&!a.has("Staccato")&&a.set("Staccato",new mh(0,0)),e.accentuated!==S.Normal||a.has("Accent")||a.set("Accent",new Xo(0,0,e)),e.accentuated!==S.Heavy||a.has("HAccent")||a.set("HAccent",new Xo(0,0,e)),e.accentuated!==S.Tenuto||a.has("Tenuto")||a.set("Tenuto",new Xo(0,0,e)),e.showStringNumber&&e.isStringed){let t;r.has("StringNumber")?t=r.get("StringNumber"):(t=new bh(0,0),r.set("StringNumber",t)),t.addString(e.string)}if(e.isPercussion){const t=me.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==R.Middle){const e=t.techniqueSymbolPlacement===R.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case I.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new fh(0,0));break;case I.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new mh(0,0));break;case I.StringsUpBow:e.set("StringsUpBow",new ko(0,0,L.Up));break;case I.StringsDownBow:e.set("StringsDownBow",new ko(0,0,L.Down));break;case I.GuitarGolpe:e.set("GuitarGolpe",new yh(0,0))}}}}}class wh extends wr{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=this._beat.brushType===g.ArpeggioUp||this._beat.brushType===g.ArpeggioDown?10:0}paint(e,t,s){if(this._beat.brushType===g.ArpeggioUp||this._beat.brushType===g.ArpeggioDown){const i=this.renderer,a=i.lineOffset,r=t+this.y+(i.getNoteY(this._beat.maxNote,en.Bottom)-a),n=t+this.y+i.getNoteY(this._beat.minNote,en.Top)+a,o=e+this.x+this.width/2,h=8,l=new vo(0,0,N.Slight,1.2,!0);l.renderer=this.renderer,l.doLayout();const c=-l.height/2;if(this._beat.brushType===g.ArpeggioUp){const t=r+h,i=n-h;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5,i,-90),l.paint(0,c,s),s.endRotate(),s.beginPath(),s.moveTo(o,n),s.lineTo(o+h/2,n-h),s.lineTo(o-h/2,n-h),s.closePath(),s.fill()}else if(this._beat.brushType===g.ArpeggioDown){const t=r+h,i=n;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5,t,90),l.paint(0,c,s),s.endRotate(),s.beginPath(),s.moveTo(o,r),s.lineTo(o+h/2,r+h),s.lineTo(o-h/2,r+h),s.closePath(),s.fill()}}}}class Bh{constructor(e,t){this.line=0,this.line=e,this.text=t}}class kh extends hn{constructor(){super(0,0),this._infos=new Map}get isEmpty(){return 0===this._infos.size}addFingers(e){const t=this.renderer.settings;if(t.notation.fingeringMode!==v.ScoreDefault&&t.notation.fingeringMode!==v.ScoreForcePiano)return;const s=ue.fingerToString(this.renderer.settings,e.beat,e.leftHandFinger,!0);s&&this.addFinger(e,s);const i=ue.fingerToString(this.renderer.settings,e.beat,e.rightHandFinger,!1);i&&this.addFinger(e,i)}addFinger(e,t){const s=this.renderer,i=s.getNoteLine(e);if(this._infos.has(i)){this._infos.get(i).text+=t}else{const a=new Bh(i,t);a.color=cn.noteColor(s.resources,H.StandardNotationEffects,e),this._infos.set(i,a)}}doLayout(){const e=this.renderer;for(const[t,s]of this._infos){const t=new Tn(0,0,s.text,e.resources.inlineFingeringFont,A.Left,R.Middle);t.colorOverride=s.color,t.renderer=e,t.y=e.getScoreY(s.line),t.doLayout(),this.addGlyph(t),this.width=Math.max(this.width,t.width)}}}class Th extends On{constructor(){super(...arguments),this._prebends=null,this.accidentals=null}get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}get effectElement(){return Y.StandardNotationEffects}doLayout(){if(!this.container.beat.isRest){const e=new nh;e.renderer=this.renderer;const t=new kh;t.renderer=this.renderer;const s=new Qo(!0);s.renderer=this.renderer;const i=new oh(this.container.beat,!0);this._prebends=i,i.renderer=this.renderer;for(const a of this.container.beat.notes){const r=cn.noteColor(this.renderer.resources,H.StandardNotationEffects,a);if(a.isVisible){if(a.hasBend)switch(a.bendType){case p.PrebendBend:case p.Prebend:case p.PrebendRelease:i.addGlyph(a.displayValue-(a.bendPoints[0].value/2|0),!1,r)}else if(a.beat.hasWhammyBar)switch(a.beat.whammyBarType){case W.PrediveDive:case W.Predive:this._prebends.addGlyph(a.displayValue-(a.beat.whammyBarPoints[0].value/2|0),!1,r)}this.createAccidentalGlyph(a,e),s.addParenthesis(a),t.addFingers(a)}}i.isEmpty||(this.addEffect(i),this.addNormal(new ph(0,0,4*(this.container.beat.graceType!==b.None?Nr.GraceScale:1)))),this.container.beat.brushType!==g.None&&(this.addEffect(new wh(this.container.beat)),this.addNormal(new ph(0,0,4))),t.isEmpty||(this.isEmpty||this.addNormal(new ph(0,0,2*(this.container.beat.graceType!==b.None?Nr.GraceScale:1))),this.addEffect(t),this.addNormal(new ph(0,0,2*(this.container.beat.graceType!==b.None?Nr.GraceScale:1)))),s.isEmpty||(this.addEffect(s),this.addNormal(new ph(0,0,4*(this.container.beat.graceType!==b.None?Nr.GraceScale:1)))),e.isEmpty||(this.accidentals=e,this.isEmpty||this.addNormal(new ph(0,0,2*(this.container.beat.graceType!==b.None?Nr.GraceScale:1))),this.addNormal(e),this.addNormal(new ph(0,0,2*(this.container.beat.graceType!==b.None?Nr.GraceScale:1))))}super.doLayout()}createAccidentalGlyph(e,t){const s=this.renderer;let i=s.accidentalHelper.applyAccidental(e),a=s.getNoteLine(e);const r=this.container.beat.graceType!==b.None,n=cn.noteColor(s.resources,H.StandardNotationAccidentals,e),o=r?Nr.GraceScale:1;if(i!==tt.None){const e=new Uo(0,s.getScoreY(a),i,o);e.colorOverride=n,e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==w.None&&e.harmonicType!==w.Natural){const h=e.displayValue+e.harmonicPitch;i=s.accidentalHelper.applyAccidentalForValue(e.beat,h,r,!1),a=s.accidentalHelper.getNoteLineForValue(h,!1);const l=new Uo(0,s.getScoreY(a),i,o);l.colorOverride=n,l.renderer=this.renderer,t.addGlyph(l)}}}class Nh extends hn{constructor(e,t,s,i,a,r){super(e,t),this._numerator=0,this._denominator=0,this.barSubElement=c.StandardNotationTimeSignature,this._numerator=s,this._denominator=i,this._isCommon=a,this._isFreeTime=r}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.bar(s,this.barSubElement,this.renderer.bar),!1);super.paint(e,t,s)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}doLayout(){let e=0;const t=Wn.numberHeight;if(this._isFreeTime){const s=new Ko(!0);s.renderer=this.renderer,s.y=-t,s.height=2*t,s.doLayout(),this.addGlyph(s),e+=s.width+10}if(this._isCommon&&2===this._numerator&&2===this._denominator){const t=new Tr(e,0,this.commonScale,I.TimeSigCutCommon);this.addGlyph(t),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){const t=new Tr(e,0,this.commonScale,I.TimeSigCommon);this.addGlyph(t),super.doLayout()}else{const s=new Wn(e,-t/2,this._numerator,this.numberScale),i=new Wn(e,t/2,this._denominator,this.numberScale);this.addGlyph(s),this.addGlyph(i),super.doLayout();const a=this.width-e;s.x=e+(a-s.width)/2,i.x=e+(a-i.width)/2}if(this._isFreeTime){const e=new Ko(!1);e.renderer=this.renderer,e.x=this.width+13,e.y=-t,e.height=2*t,e.doLayout(),this.addGlyph(e),this.width=e.x+e.width}}}class xh extends Nh{get commonScale(){return 1}get numberScale(){return 1}}class vh extends hh{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)return;const t=cn.noteColor(this.renderer.resources,H.StandardNotationEffects,e);switch(e.bendType){case p.Bend:case p.PrebendRelease:case p.PrebendBend:{let s=this._endNoteGlyph;s||(s=new oh(e.beat,!1),s.renderer=this.renderer,this._endNoteGlyph=s,this.BendNoteHeads.push(s));const i=e.bendPoints[e.bendPoints.length-1];s.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0,t)}break;case p.Release:if(!e.isTieOrigin){let s=this._endNoteGlyph;s||(s=new oh(e.beat,!1),s.renderer=this.renderer,this._endNoteGlyph=s,this.BendNoteHeads.push(s));const i=e.bendPoints[e.bendPoints.length-1];s.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0,t)}break;case p.BendRelease:{let s=this._middleNoteGlyph;s||(s=new oh(e.beat,!1),this._middleNoteGlyph=s,s.renderer=this.renderer,this.BendNoteHeads.push(s));const i=e.bendPoints[1];s.addGlyph(this.getBendNoteValue(e,e.bendPoints[1]),i.value%2!=0,t);let a=this._endNoteGlyph;a||(a=new oh(e.beat,!1),a.renderer=this.renderer,this._endNoteGlyph=a,this.BendNoteHeads.push(a));const r=e.bendPoints[e.bendPoints.length-1];a.addGlyph(this.getBendNoteValue(e,r),r.value%2!=0,t)}}}paint(e,t,s){const i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._beat.voice.bar),a=e+i.x+i.getBeatX(this._beat,Qr.MiddleNotes);let r=e+i.x;this._beat.isLastOfVoice?r+=i.postBeatGlyphsStart:r+=i.getBeatX(this._beat.nextBeat,Qr.PreNotes),r-=8;const n=(a+r)/2;this._middleNoteGlyph&&(this._middleNoteGlyph.x=n-this._middleNoteGlyph.noteHeadOffset,this._middleNoteGlyph.y=t+i.y,this._middleNoteGlyph.paint(0,0,s)),this._endNoteGlyph&&(this._endNoteGlyph.x=r-this._endNoteGlyph.noteHeadOffset,this._endNoteGlyph.y=t+i.y,this._endNoteGlyph.paint(0,0,s)),this._notes.sort(((e,t)=>t.displayValue-e.displayValue));const o=this._beat.graceType===b.BendGrace?this._beat.nextBeat:this._beat;let h=1===this._notes.length?this.getTieDirection(o,i):je.Up;const l=kr.Heights.get(I.NoteheadBlack);for(let o=0;o<this._notes.length;o++){const c={stack:[],error:void 0,hasError:!1};try{const d=this._notes[o];jr(c,cn.note(s,H.StandardNotationEffects,d),!1);o>0&&o>=(this._notes.length/2|0)&&(h=je.Down);let g=t+i.y+i.getNoteY(d,en.Top),m=l*Nr.GraceScale*.5;h===je.Down&&(g+=l);const f=d.bendStyle===u.Gradual?"grad.":"";if(d.isTieOrigin){const r=d.tieDestination,n=r?this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.beat.voice.bar):null;if(n&&n.staff===i.staff){const i=e+n.x+n.getBeatX(r.beat,Qr.MiddleNotes);let o=t+n.y+n.getNoteY(r,en.Top);h===je.Down&&(o+=l),d.bendType===p.Hold||d.bendType===p.Prebend?qo.paintTie(s,1,a,g,i,o,h===je.Down,22,4):this.drawBendSlur(s,a,g,i,o,h===je.Down,1,f)}else{const r=e+i.x+i.width,n=d.tieDestination.realValue;i.accidentalHelper.applyAccidentalForValue(d.beat,n,!1,!0);const o=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(n,!1));d.bendType===p.Hold||d.bendType===p.Prebend?qo.paintTie(s,1,a,g,r,o,h===je.Down,22,4):this.drawBendSlur(s,a,g,r,o,h===je.Down,1,f)}switch(d.bendType){case p.Prebend:case p.PrebendBend:case p.PrebendRelease:let r=e+i.x+i.getBeatX(d.beat,Qr.PreNotes);r+=i.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;const n=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(d.displayValue-(d.bendPoints[0].value/2|0),!1))+m;this.drawBendSlur(s,r,n,a,g,h===je.Down,1)}}else{h===je.Up&&(m=-m);let o=0,l=0;switch(d.bendType){case p.Bend:o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+m,this.drawBendSlur(s,a,g,r,l,h===je.Down,1,f);break;case p.BendRelease:const c=this.getBendNoteValue(d,d.bendPoints[1]),u=this._middleNoteGlyph.getNoteValueY(c)+m;this.drawBendSlur(s,a,g,n,u,h===je.Down,1,f),o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+m,this.drawBendSlur(s,n,u,r,l,h===je.Down,1,f);break;case p.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+m,this.drawBendSlur(s,a,g,r,l,h===je.Down,1,f));break;case p.Prebend:case p.PrebendBend:case p.PrebendRelease:let y=e+i.x+i.getBeatX(d.beat,Qr.PreNotes);y+=i.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;const b=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(d.displayValue-(d.bendPoints[0].value/2|0),!1))+m;this.drawBendSlur(s,y,b,a,g,h===je.Down,1),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(d,d.bendPoints[d.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+m,this.drawBendSlur(s,a,g,r,l,h===je.Down,1,f))}}}catch(e){c.error=e,c.hasError=!0}finally{on(c)}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class Ph extends qo{constructor(e,t,s=!1){super(e,t,s)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?je.Up:t.getBeatDirection(e)===je.Up?je.Down:je.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===je.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,en.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,en.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===je.Up?e.getScoreY(9):e.getScoreY(0);const t=this.startNoteRenderer.getBeatDirection(this.startBeat),s=e.getBeatDirection(this.endBeat);return t!==s&&this.startBeat.graceType===b.None?s===this.tieDirection?this.tieDirection===je.Up?e.getNoteY(this.endBeat.maxNote,en.TopWithStem):e.getNoteY(this.endBeat.minNote,en.BottomWithStem):this.tieDirection===je.Up?e.getNoteY(this.endBeat.maxNote,en.BottomWithStem):e.getNoteY(this.endBeat.minNote,en.TopWithStem):this.tieDirection===je.Up?e.getNoteY(this.endBeat.maxNote,en.Top):e.getNoteY(this.endBeat.minNote,en.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,Qr.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>f.Whole&&e===this.tieDirection?Qr.Stem:Qr.MiddleNotes)}}class Ch extends wr{constructor(e,t,s,i){super(0,0),this._outType=t,this._inType=e,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.drawSlideOut(e,t,s)}paintSlideIn(e,t,s){const i=this.renderer;let a=e+i.x+i.getNoteX(this._startNote,tn.Left)-2;const r=t+i.y+i.getNoteY(this._startNote,en.Center);let n=a-12,o=t+i.y;switch(this._inType){case k.IntoFromBelow:o+=i.getNoteY(this._startNote,en.Bottom);break;case k.IntoFromAbove:o+=i.getNoteY(this._startNote,en.Top);break;default:return}const h=this.getAccidentalsWidth(i,this._startNote.beat);n-=h,a-=h,this.paintSlideLine(s,!1,n,a,o,r)}getAccidentalsWidth(e,t){const s=e.getPreNotesGlyphForBeat(t);return s&&s.accidentals?s.accidentals.width:0}drawSlideOut(e,t,s){const i=this.renderer;let a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case T.Shift:case T.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,Qr.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,en.Center),this._startNote.slideTarget){const s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,Qr.PreNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,en.Center)):(n=e+i.x+i.width,o=r),this._startNote.slideTarget.realValue>this._startNote.realValue?(r+=2,o-=2):(r-=2,o+=2)}else n=e+i.x+this._parent.x,o=r;break;case T.OutUp:a=e+i.x+i.getNoteX(this._startNote,tn.Right)+2,r=t+i.y+i.getNoteY(this._startNote,en.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,en.Top);break;case T.OutDown:a=e+i.x+i.getNoteX(this._startNote,tn.Right)+2,r=t+i.y+i.getNoteY(this._startNote,en.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,en.Bottom);break;case T.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,tn.Right)+4,r=t+i.y+i.getNoteY(this._startNote,en.Center),o=t+i.y+i.getNoteY(this._startNote,en.Top),n=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Qr.PreNotes)),h=!0;break;case T.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,tn.Right)+4,r=t+i.y+i.getNoteY(this._startNote,en.Center),o=t+i.y+i.getNoteY(this._startNote,en.Bottom),n=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Qr.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){const t=new vo(0,0,N.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;const n=i-s,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;const l=Math.asin(o/h)*(180/Math.PI);e.beginRotate(s,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(s,a),e.lineTo(i,r),e.stroke()}}class Eh extends Ph{constructor(e,t,s=!1){super(e.beat,t.beat,s),this._startNote=e,this._endNote=t}getTieHeight(e,t,s,i){return Math.log2(s-e+1)*this.renderer.settings.notation.slurHeight}getStartY(){return this.isStartCentered()?this.tieDirection===je.Up?this.startNoteRenderer.getNoteY(this._startNote,en.Top):this.startNoteRenderer.getNoteY(this._startNote,en.Bottom):this.startNoteRenderer.getNoteY(this._startNote,en.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===je.Up?this.endNoteRenderer.getNoteY(this._endNote,en.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,en.BottomWithStem):this.tieDirection===je.Up?this.endNoteRenderer.getNoteY(this._endNote,en.Top):this.endNoteRenderer.getNoteY(this._endNote,en.Bottom):this.endNoteRenderer.getNoteY(this._endNote,en.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===je.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===je.Down}isEndCentered(){return this._startNote.beat.graceType===b.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===je.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===je.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===b.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,Qr.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,tn.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,Qr.Stem):this.endNoteRenderer.getNoteX(this._endNote,tn.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,Qr.PreNotes)}}class Fh extends qo{constructor(e,t,s=!1){super(e?e.beat:null,t?t.beat:null,s),this.startNote=e,this.endNote=t}shouldDrawBendSlur(){return this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&!!this.startNote.bendOrigin&&this.startNote.isTieOrigin}doLayout(){super.doLayout()}getBeamDirection(e,t){return t.getBeatDirection(e)===je.Up?je.Down:je.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===je.Up?this.startNoteRenderer.getNoteY(this.startNote,en.Top):this.startNoteRenderer.getNoteY(this.startNote,en.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===je.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===je.Up?e.getNoteY(this.endNote,en.Top):e.getNoteY(this.endNote,en.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,Qr.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,Qr.PreNotes)}}class Dh extends vr{constructor(){super(...arguments),this._bend=null,this._effectSlur=null,this._effectEndSlur=null}doLayout(){this._effectSlur=null,this._effectEndSlur=null,super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(e.isVisible){if(e.isTieOrigin&&!e.hasBend&&!e.beat.hasWhammyBar&&e.beat.graceType!==b.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){const t=new Fh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){const t=new Fh(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==k.None||e.slideOutType!==T.None){const t=new Ch(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){const t=new Eh(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){const t=new Eh(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new Eh(e,e.effectSlurDestination,!1);this._effectSlur=t,this.addTie(t)}if(!this._effectEndSlur&&e.beat.isEffectSlurDestination&&e.beat.effectSlurOrigin){const t=this.onNotes.beamingHelper.direction,s=t===je.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,i=t===je.Up?e.beat.minNote:e.beat.maxNote,a=new Eh(s,i,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new vh(e.beat);this._bend=t,t.renderer=this.renderer,this.addTie(t)}this._bend.addBends(e)}if(this.beat.isLegatoOrigin){if(!this.beat.previousBeat||!this.beat.previousBeat.isLegatoOrigin){let e=this.beat.nextBeat;for(;e.nextBeat&&e.nextBeat.isLegatoDestination;)e=e.nextBeat;this.addTie(new Ph(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 Ph(e,this.beat,!0))}}}}class Mh extends wr{constructor(e,t,s,i){super(e,t),this._dotOffset=0,this._circleSize=0,this._dotOffset=0,this._circleSize=0,this._dotOffset=i,this._circleSize=s}doLayout(){this.width=13}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.bar(s,this.renderer.repeatsBarSubElement,this.renderer.bar),!1);const a=4,r=t+this.y+this.renderer.topPadding,n=t+this.y+this.renderer.height-this.renderer.bottomPadding;let o=e+this.x+.5;const h=n-r;s.fillRect(o,r,a,h),o+=2*a-.5,s.beginPath(),s.moveTo(o,r),s.lineTo(o,n),s.stroke(),o+=3;const l=this._circleSize,c=(r+n)/2;s.fillCircle(o,c-l*this._dotOffset,l),s.fillCircle(o,c+l*this._dotOffset,l)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}class Lh extends wr{doLayout(){this.renderer.isLast?this.width=15:this.renderer.nextRenderer&&this.renderer.nextRenderer.staff===this.renderer.staff&&this.renderer.nextRenderer.bar.masterBar.isRepeatStart?this.width=2:(this.width=2,this.renderer.bar.masterBar.isDoubleBar&&(this.width+=2))}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{const a=this.renderer;if(a.nextRenderer&&a.nextRenderer.bar.masterBar.isRepeatStart)return;jr(i,cn.bar(s,a.barSeparatorBarSubElement,this.renderer.bar,!0),!1);const r=4,n=t+this.y+this.renderer.topPadding,o=t+this.y+this.renderer.height-this.renderer.bottomPadding,h=e+this.x,l=o-n;if(this.renderer.isLast)s.fillRect(h+this.width-r-r,n,1,l),s.fillRect(h+this.width-r,n,r,l);else if(!this.renderer.nextRenderer||this.renderer.nextRenderer.staff!==this.renderer.staff||!this.renderer.nextRenderer.bar.masterBar.isRepeatStart)if(this.renderer.bar.masterBar.isFreeTime){const e=Lh.DashSize,t=.5+(h+this.width-1|0),i=Math.ceil(l/2/e);if(s.beginPath(),i<1)s.moveTo(t,n),s.lineTo(t,o);else{let a=n;const r=(l-i*e)/(i-1);for(;a<o;)s.moveTo(t,a),s.lineTo(t,a+e),a+=e+r}s.stroke()}else s.fillRect(h+this.width-1,n,1,l),this.renderer.bar.masterBar.isDoubleBar&&s.fillRect(h+this.width-5,n,1,l)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}Lh.DashSize=4;class Ih extends wr{doLayout(){this.width=11}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.bar(s,this.renderer.repeatsBarSubElement,this.renderer.bar),!1);const a=4,r=t+this.y+this.renderer.topPadding,n=t+this.y+this.renderer.height-this.renderer.bottomPadding;let o=e+this.x;const h=n-r,l=1.5,c=(r+n)/2,d=3;s.fillCircle(o,c-l*d,l),s.fillCircle(o,c+l*d,l),o+=4,s.beginPath(),s.moveTo(o,r),s.lineTo(o,n),s.stroke(),o+=3.5,s.fillRect(o,r,a,h)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}class Ah extends wr{constructor(e,t,s){super(e,t),this._count=0,this._count=0,this._count=s}doLayout(){this.width=0}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.bar(s,this.renderer.repeatsBarSubElement,this.renderer.bar),!1);const a=this.renderer.resources,r=s.textAlign;s.font=a.barNumberFont,s.textAlign=A.Right;const n=`x${this._count}`,o=s.measureText(n).width/1.5;s.fillText(n,e+this.x-o,t+this.y),s.textAlign=r}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}class Rh extends wr{constructor(e,t,s){super(e,t),this._number=0,this._number=s}doLayout(){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.barNumberFont,this.width=this.renderer.scoreRenderer.canvas.measureText(this._number.toString()).width+5}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{if(!this.renderer.staff.isFirstInSystem)return;jr(i,cn.bar(s,this.renderer.barNumberBarSubElement,this.renderer.bar,!0),!1);const a=this.renderer.resources,r=s.textBaseline;s.textBaseline=R.Top,s.font=a.barNumberFont,s.fillText(this._number.toString(),e+this.x,t+this.y),s.textBaseline=r}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}class Oh extends Un{constructor(){super(...arguments),this.firstLineY=0,this._startSpacing=!1,this.tupletSize=0}get lineOffset(){return this.lineSpacing+1}get tupletOffset(){return 10}get topGlyphOverflow(){const e=this.resources;return e.tablatureFont.size/2+.2*e.tablatureFont.size}get bottomGlyphOverflow(){const e=this.resources;return e.tablatureFont.size/2+.2*e.tablatureFont.size}initLineBasedSizes(){this.topPadding=this.topGlyphOverflow,this.bottomPadding=this.bottomGlyphOverflow,this.height=this.lineOffset*(this.heightLineCount-1)+this.topPadding+this.bottomPadding}updateSizes(){this.initLineBasedSizes(),this.adjustSizes(),this.updateFirstLineY(),super.updateSizes()}adjustSizes(){}updateFirstLineY(){const e=this.lineOffset*(this.heightLineCount-1),t=(this.drawnLineCount-1)*this.lineOffset;this.firstLineY=this.topPadding+(e-t)/2}doLayout(){this.initLineBasedSizes(),this.updateFirstLineY(),this.tupletSize=15+.3*this.resources.effectFont.size,super.doLayout()}getLineY(e){return this.firstLineY+this.getLineHeight(e)}getLineHeight(e){return this.lineOffset*e}paintBackground(e,t,s){super.paintBackground(e,t,s),this.paintStaffLines(e,t,s),this.paintSimileMark(e,t,s)}paintStaffLines(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.bar(s,this.staffLineBarSubElement,this.bar,!0),!1);const a=[];for(let e=0,t=this.drawnLineCount;e<t;e++)a.push([]);this.additionalMultiRestBars||this.collectSpaces(a);for(const e of a)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));for(let i=0;i<this.drawnLineCount;i++){const r=this.getLineY(i);let n=0;for(const o of a[i])s.fillRect(e+this.x+n,t+this.y+r|0,o[0]-n,Un.StaffLineThickness),n=o[0]+o[1];s.fillRect(e+this.x+n,t+this.y+r|0,this.width-n,Un.StaffLineThickness)}}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}collectSpaces(e){}createStartSpacing(){if(this._startSpacing)return;const e=0===this.index?this.settings.display.firstStaffPaddingLeft:this.settings.display.staffPaddingLeft;this.addPreBeatGlyph(new ph(0,0,e)),this._startSpacing=!0}paintTuplets(e,t,s,i,a=!1){for(const r of this.bar.voices)if(this.hasVoiceContainer(r)){const n=this.getVoiceContainer(r);for(const r of n.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,r,i,a)}}getTupletBeamDirection(e){return this.getBeamDirection(e)}paintTupletHelper(e,t,s,i,a,r){const n={stack:[],error:void 0,hasError:!1};try{const o=this.resources,h=s.textAlign,l=s.textBaseline;let c;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=A.Center,s.textBaseline=R.Middle;const d=i.beats[0].tupletNumerator,u=i.beats[0].tupletDenominator;c=2===d&&3===u?"2":3===d&&2===u?"3":4===d&&6===u?"4":5===d&&4===u?"5":6===d&&4===u?"6":7===d&&4===u?"7":9===d&&8===u?"9":10===d&&8===u?"10":11===d&&8===u?"11":12===d&&8===u?"12":13===d&&8===u?"13":`${d}:${u}`;let p=this.tupletOffset,g=5;jr(n,cn.beat(s,a,i.beats[0]),!1);if(1!==i.beats.length&&i.isFull){const a=i.beats[0],n=i.beats[i.beats.length-1];let h=null,l=null;for(let e=0;e<i.beats.length;e++)if(!i.beats[e].isRest){h=i.beats[e];break}for(let e=i.beats.length-1;e>=0;e--)if(!i.beats[e].isRest){l=i.beats[e];break}let d=!1;h||(h=a,d=!0),l||(l=n);const u=this.helpers.beamHelperLookup[i.voice.index].get(a.index),m=this.helpers.beamHelperLookup[i.voice.index].get(n.index),f=u.getBeatLineX(a),y=m.getBeatLineX(n),b=this.helpers.beamHelperLookup[i.voice.index].get(h.index),S=this.helpers.beamHelperLookup[i.voice.index].get(l.index),_=this.getTupletBeamDirection(u);let w=this.calculateBeamYWithDirection(b,f,_),B=this.calculateBeamYWithDirection(S,y,_);d&&(w=Math.max(w,B),B=w),s.font=o.effectFont;const k=s.measureText(c).width,T=3,N=(f+y)/2,x=N-k/2-T,v=N+k/2+T,P=(B-w)/(y-f),C=w-P*f,E=P*x+C,F=P*N+C,D=P*v+C;_===je.Down&&(p*=-1,g*=-1),s.beginPath(),s.moveTo(e+this.x+f,t+this.y+w-p|0),r?s.quadraticCurveTo(e+this.x+(x+f)/2,t+this.y+E-p-g|0,e+this.x+x,t+this.y+E-p-g|0):(s.lineTo(e+this.x+f,t+this.y+w-p-g|0),s.lineTo(e+this.x+x,t+this.y+E-p-g|0)),s.stroke(),s.beginPath(),s.moveTo(e+this.x+v,t+this.y+D-p-g|0),r?s.quadraticCurveTo(e+this.x+(y+v)/2,t+this.y+D-p-g|0,e+this.x+y,t+this.y+B-p|0):(s.lineTo(e+this.x+y,t+this.y+B-p-g|0),s.lineTo(e+this.x+y,t+this.y+B-p|0)),s.stroke(),s.fillText(c,e+this.x+N,t+this.y+F-p-g)}else for(const a of i.beats){const r=this.helpers.beamHelperLookup[i.voice.index].get(a.index);if(!r)continue;const n=this.getTupletBeamDirection(r),h=r.getBeatLineX(a);let l=this.calculateBeamYWithDirection(r,h,n);n===je.Down?l+=p+g:l-=p+g,s.font=o.effectFont,s.fillText(c,e+this.x+h,t+this.y+l)}s.textAlign=h,s.textBaseline=l}catch(e){n.error=e,n.hasError=!0}finally{on(n)}}paintBeams(e,t,s,i,a){for(const r of this.helpers.beamHelpers)for(const n of r)this.paintBeamHelper(e+this.beatGlyphsStart,t,s,n,i,a)}drawBeamHelperAsFlags(e){return 1===e.beats.length}paintBeamHelper(e,t,s,i,a,r){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(this.drawBeamHelperAsFlags(i)?this.paintFlag(e,t,s,i,a):this.paintBar(e,t,s,i,r))}shouldPaintFlag(e,t){return e.graceType!==b.BendGrace&&(!e.deadSlapped&&(!!t.hasBeatLineX(e)&&((e.graceType===b.None||this.settings.notation.notationMode!==P.SongBook)&&(e.duration!==f.Whole&&e.duration!==f.DoubleWhole&&e.duration!==f.QuadrupleWhole))))}paintFlag(e,t,s,i,a){for(const r of i.beats){const n={stack:[],error:void 0,hasError:!1};try{if(!this.shouldPaintFlag(r,i))continue;const o=r.graceType!==b.None,h=o?Nr.GraceScale:1,l=this.getFlagStemSize(i.shortestDuration),c=i.getBeatLineX(r),d=this.getBeamDirection(i);let u=this.getFlagTopY(r,d),p=this.getFlagBottomY(r,d),g=0;if(d===je.Down?(p+=l*h,g=p):(u-=l*h,g=u),!i.hasLine(!0,r))continue;this.paintBeamingStem(r,t+this.y,e+this.x+c,t+this.y+u,t+this.y+p,s);jr(n,cn.beat(s,a,r),!1);if(r.graceType===b.BeforeBeat){const i=15,a=12;s.beginPath(),d===je.Down?(s.moveTo(e+this.x+c-a/2,t+this.y+p-i),s.lineTo(e+this.x+c+a/2,t+this.y+p)):(s.moveTo(e+this.x+c-a/2,t+this.y+u+i),s.lineTo(e+this.x+c+a/2,t+this.y+u)),s.stroke()}if(i.hasFlag(!0,r)){const i=new xr(c-.5,g,r.duration,d,o);i.renderer=this,i.doLayout(),i.paint(e+this.x,t+this.y,s)}}catch(e){n.error=e,n.hasError=!0}finally{on(n)}}}getFlagStemSize(e,t=!1){let s=0;switch(e){case f.QuadrupleWhole:case f.Half:case f.Quarter:case f.Eighth:case f.Sixteenth:case f.ThirtySecond:case f.SixtyFourth:case f.OneHundredTwentyEighth:case f.TwoHundredFiftySixth:s=3;break;default:s=t?3:0}return this.getLineHeight(s)}recreatePreBeatGlyphs(){this._startSpacing=!1,super.recreatePreBeatGlyphs()}calculateBeamY(e,t){return this.calculateBeamYWithDirection(e,t,this.getBeamDirection(e))}createPreBeatGlyphs(){super.createPreBeatGlyphs(),this.bar.masterBar.isRepeatStart&&this.addPreBeatGlyph(new Mh(0,0,1.5,3)),this.createLinePreBeatGlyphs(),this.addPreBeatGlyph(new Rh(0,this.getLineHeight(-.25),this.bar.index+1))}createPostBeatGlyphs(){super.createPostBeatGlyphs();const e=this.lastBar;e.masterBar.isRepeatEnd?(this.addPostBeatGlyph(new Ih(this.x,0)),e.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Ah(0,this.getLineHeight(-.25),this.bar.masterBar.repeatCount))):this.lastBar&&this.addPostBeatGlyph(new Lh(0,0))}paintBar(e,t,s,i,a){for(let r=0,n=i.beats.length;r<n;r++){const n={stack:[],error:void 0,hasError:!1};try{const o=i.beats[r];if(!i.hasBeatLineX(o)||o.deadSlapped)continue;const h=o.graceType!==b.None?Nr.GraceScale:1,l=i.getBeatLineX(o),c=this.getBeamDirection(i),d=t+this.y+this.getBarLineStart(o,c),u=t+this.y+this.calculateBeamY(i,l);this.paintBeamingStem(o,t+this.y,e+this.x+l,d,u,s);jr(n,cn.beat(s,a,o),!1);let p=u;c===je.Down?p+=2*s.font.size:0!==r&&(p-=1.5*s.font.size);const g=6*h;let m=(Un.BeamSpacing+Un.BeamThickness)*h,f=Un.BeamThickness*h;const y=ue.getIndex(o.duration)-2,S=t+this.y;c===je.Down&&(m=-m,f=-f);for(let t=0;t<y;t++){let a=0,n=0,h=0,c=0;const d=S+t*m;if(r<i.beats.length-1){const u=mn.isFullBarJoin(o,i.beats[r+1],t);if(t===y-1&&u&&o.beamingMode===J.ForceSplitOnSecondaryToNext)a=l,n=a+g,h=d+this.calculateBeamY(i,a),c=d+this.calculateBeamY(i,n),Oh.paintSingleBar(s,e+this.x+a,h,e+this.x+n,c,f),n=i.getBeatLineX(i.beats[r+1]),a=n-g,h=d+this.calculateBeamY(i,a),c=d+this.calculateBeamY(i,n),Oh.paintSingleBar(s,e+this.x+a,h,e+this.x+n,c,f);else{if(u)a=l,n=i.getBeatLineX(i.beats[r+1]);else{if(0!==r&&mn.isFullBarJoin(i.beats[r-1],o,t))continue;a=l,n=a+g}h=d+this.calculateBeamY(i,a),c=d+this.calculateBeamY(i,n),Oh.paintSingleBar(s,e+this.x+a,h,e+this.x+n,c,f)}}else r>0&&!mn.isFullBarJoin(o,i.beats[r-1],t)&&(a=l-g,n=l,h=d+this.calculateBeamY(i,a),c=d+this.calculateBeamY(i,n),Oh.paintSingleBar(s,e+this.x+a,h,e+this.x+n,c,f))}}catch(e){n.error=e,n.hasError=!0}finally{on(n)}}}static paintSingleBar(e,t,s,i,a,r){e.beginPath(),e.moveTo(t,s),e.lineTo(i,a),e.lineTo(i,a+r),e.lineTo(t,s+r),e.closePath(),e.fill()}}class Hh extends ln{paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.bar(s,c.StandardNotationKeySignature,this.renderer.bar),!1);super.paint(e,t,s)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}class Wh extends Oh{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.beatEffectsMinY=null,this.beatEffectsMaxY=null,this.accidentalHelper=new Ci(this)}get repeatsBarSubElement(){return c.StandardNotationRepeats}get barNumberBarSubElement(){return c.StandardNotationBarNumber}get barSeparatorBarSubElement(){return c.StandardNotationBarSeparator}get staffLineBarSubElement(){return c.StandardNotationStaffLine}get showMultiBarRest(){return!0}get lineSpacing(){return Un.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return this.bar.staff.standardNotationLineCount}registerBeatEffectOverflows(e,t){const s=this.beatEffectsMinY;(null==s||e<s)&&(this.beatEffectsMinY=e);const i=this.beatEffectsMaxY;(null==i||t>i)&&(this.beatEffectsMaxY=t)}getScoreY(e){return super.getLineY(e/2)}getScoreHeight(e){return super.getLineHeight(e/2)}doLayout(){if(super.doLayout(),!this.bar.isEmpty&&this.accidentalHelper.maxLineBeat){const e=this.getScoreY(-2),t=this.getScoreY(10),s=this.simpleWhammyOverflow,i=this.beatEffectsMinY;if(null!==i){const t=e-i;t>0&&this.registerOverflowTop(t)}const a=this.beatEffectsMaxY;if(null!==a){const e=a-t;e>0&&this.registerOverflowBottom(e)}this.registerOverflowTop(s);let r=this.getScoreY(this.accidentalHelper.maxLine);const n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);n.direction===je.Up&&(r-=this.getStemSize(n),n.hasTuplet&&(r-=this.tupletSize)),r<e&&this.registerOverflowTop(Math.abs(r)+s);let o=this.getScoreY(this.accidentalHelper.minLine);const h=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);h.direction===je.Down&&(o+=this.getStemSize(h),h.hasTuplet&&(o+=this.tupletSize)),o>t&&this.registerOverflowBottom(Math.abs(o)-t)}}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s,Y.StandardNotationFlags,Y.StandardNotationBeams),this.paintTuplets(e,t,s,Y.StandardNotationTuplet)}getSlashFlagY(e,t){let s=(this.heightLineCount-1)/2,i=0;switch(e){case f.QuadrupleWhole:case f.DoubleWhole:case f.Whole:i+=2;break;default:i+=1}t===je.Down?s+=i:s-=i;return this.getLineY(s)}getFlagTopY(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):this.getScoreY(this.accidentalHelper.getMinLine(e))}getFlagBottomY(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):this.getScoreY(this.accidentalHelper.getMaxLine(e))}getBeamDirection(e){return e.direction}getStemSize(e,t=!1){let s=1===e.beats.length?this.getFlagStemSize(e.shortestDuration,t):this.getBarStemSize(e.shortestDuration);return e.isGrace&&(s*=Nr.GraceScale),s}getBarStemSize(e){let t=0;switch(e){case f.QuadrupleWhole:case f.Half:case f.Quarter:case f.Eighth:case f.Sixteenth:t=6;break;case f.ThirtySecond:t=8;break;case f.SixtyFourth:case f.OneHundredTwentyEighth:t=9;break;case f.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){if(e.beat.slashed){const e=(this.heightLineCount-1)/2;return this.getLineY(e)}let s=super.getNoteY(e,t);if(Number.isNaN(s)){const t=Ci.computeLineWithoutAccidentals(this.bar,e);s=this.getScoreY(t)}return s}applyLayoutingInfo(){const e=super.applyLayoutingInfo();if(e&&this.bar.isMultiVoice){const e=this.getScoreY(-2),t=this.getScoreY(10),s=this.helpers.collisionHelper.getBeatMinMaxY();s[0]<e&&this.registerOverflowTop(Math.abs(s[0])),s[1]>t&&this.registerOverflowBottom(Math.abs(s[1])-t)}return e}calculateBeamYWithDirection(e,t,s){const i=this.getStemSize(e);if(!e.drawingInfos.has(s)){const t=new gn;e.drawingInfos.set(s,t);const a=e.beats[0],r=e.beats[e.beats.length-1],n=e.isRestBeamHelper;t.startBeat=a,t.startX=e.getBeatLineX(a),t.startY=n?s===je.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===je.Up?this.getFlagTopY(a,s)-i:this.getFlagBottomY(a,s)+i,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?s===je.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===je.Up?this.getFlagTopY(r,s)-i:this.getFlagBottomY(r,s)+i;const o=10;if(s===je.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),s===je.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),s===je.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),s===je.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(s===je.Up){const s=this.getScoreY(this.accidentalHelper.getMinLine(e.beatOfHighestNote))-i,a=t.calcY(e.getBeatLineX(e.beatOfHighestNote))-s;a>0&&(t.startY-=a,t.endY-=a)}else{const s=this.getScoreY(this.accidentalHelper.getMaxLine(e.beatOfLowestNote))+i-t.calcY(e.getBeatLineX(e.beatOfLowestNote));s>0&&(t.startY+=s,t.endY+=s)}if(null!==e.minRestLine||null!==e.maxRestLine){const i=ue.getIndex(e.shortestDuration)-2,a=e.isGrace?Nr.GraceScale:1;let r=i*(Un.BeamSpacing+Un.BeamThickness)*a;if(r+=Un.BeamSpacing,s===je.Up&&null!==e.minRestLine){const s=this.getScoreY(e.minRestLine)-r,i=t.calcY(e.getBeatLineX(e.beatOfMinRestLine))-s;i>0&&(t.startY-=i,t.endY-=i)}else if(s===je.Down&&null!==e.maxRestLine){const s=this.getScoreY(e.maxRestLine)+r-t.calcY(e.getBeatLineX(e.beatOfMaxRestLine));s>0&&(t.startY+=s,t.endY+=s)}}if(e.slashBeats.length>0)for(const a of e.slashBeats){const r=t.calcY(e.getBeatLineX(a));let n=this.getSlashFlagY(a.duration,s);s===je.Up?n-=i:s===je.Down&&(n+=i);const o=n-r;o>0&&(t.startY+=o,t.endY+=o)}}}return e.drawingInfos.get(s).calcY(t)}getBarLineStart(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):t===je.Up?this.getScoreY(this.accidentalHelper.getMaxLine(e)):this.getScoreY(this.accidentalHelper.getMinLine(e))}createLinePreBeatGlyphs(){let e=!1;if(this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let t=0;switch(this.bar.clef){case n.Neutral:t=this.bar.staff.standardNotationLineCount-1;break;case n.F4:t=2;break;case n.C3:t=4;break;case n.C4:t=2;break;case n.G2:t=6}this.createStartSpacing(),this.addPreBeatGlyph(new zo(0,this.getScoreY(t)+.5*Un.StaffLineThickness,this.bar.clef,this.bar.clefOttava)),e=!0}(e||0===this.index&&this.bar.masterBar.keySignature!==F.C||this.bar.previousBar&&this.bar.masterBar.keySignature!==this.bar.previousBar.masterBar.keySignature)&&(this.createStartSpacing(),this.createKeySignatureGlyphs()),(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createKeySignatureGlyphs(){let e=0;const t=this.bar.masterBar.keySignature,s=this.bar.previousBar?this.bar.previousBar.masterBar.keySignature:0;switch(this.bar.clef){case n.Neutral:e=0;break;case n.G2:e=1;break;case n.F4:e=3;break;case n.C3:e=2;break;case n.C4:e=0}const i=new Hh;i.renderer=this;const a=new Map,r=[];if(ue.keySignatureIsSharp(t))for(let s=0;s<Math.abs(t);s++){const t=Wh.SharpKsSteps[s]+e;r.push(new Uo(0,this.getScoreY(t),tt.Sharp,1)),a.set(t,!0)}else for(let s=0;s<Math.abs(t);s++){const t=Wh.FlatKsSteps[s]+e;r.push(new Uo(0,this.getScoreY(t),tt.Flat,1)),a.set(t,!0)}if(this.bar.masterBar.keySignature===F.C){const t=Math.abs(s),r=ue.keySignatureIsSharp(s)?Wh.SharpKsSteps:Wh.FlatKsSteps;for(let s=0;s<t;s++){const t=r[s]+e;a.has(t)||i.addGlyph(new Uo(0,this.getScoreY(r[s]+e),tt.Natural,1))}}for(const e of r)i.addGlyph(e);this.addPreBeatGlyph(i)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new ph(0,0,5));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new xh(0,this.getScoreY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon,this.bar.masterBar.isFreeTime))}createVoiceGlyphs(e){for(const t of e.beats){const s=new Dh(t,this.getVoiceContainer(e));s.preNotes=new Th,s.onNotes=new _h,this.addBeatGlyph(s)}}getNoteLine(e){return this.accidentalHelper.getNoteLine(e)}completeBeamingHelper(e){if(this.bar.isMultiVoice&&e.highestNoteInHelper&&e.lowestNoteInHelper){let t=this.getNoteY(e.highestNoteInHelper,en.Center),s=this.getNoteY(e.lowestNoteInHelper,en.Center),i=this.getStemSize(e);e.hasTuplet&&(i+=2*this.resources.effectFont.size),e.direction===je.Up?t-=i:s+=i;for(const i of e.beats)this.helpers.collisionHelper.reserveBeatSlot(i,t,s)}}paintBeamingStem(e,t,s,i,a,r){const n={stack:[],error:void 0,hasError:!1};try{jr(n,cn.beat(r,Y.StandardNotationStem,e),!1);r.lineWidth=Un.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}catch(e){n.error=e,n.hasError=!0}finally{on(n)}}}Wh.StaffId="score",Wh.SharpKsSteps=[-1,2,-2,1,4,0,3],Wh.FlatKsSteps=[3,0,4,1,5,2,6];class Vh extends Kr{get staffId(){return Wh.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new Wh(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showStandardNotation}}class Gh extends wr{constructor(e,t,s,i){super(0,0),this._inType=e,this._outType=t,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.paintSlideOut(e,t,s)}paintSlideIn(e,t,s){const i=this.renderer;let a=0,r=0,n=0,o=0;switch(this._inType){case k.IntoFromBelow:n=e+i.x+i.getNoteX(this._startNote,tn.Left)-2,o=t+i.y+i.getNoteY(this._startNote,en.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,en.Center)+3;break;case k.IntoFromAbove:n=e+i.x+i.getNoteX(this._startNote,tn.Left)-2,o=t+i.y+i.getNoteY(this._startNote,en.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,en.Center)-3;break;default:return}this.paintSlideLine(s,!1,a,n,r,o)}paintSlideOut(e,t,s){const i=this.renderer;let a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case T.Shift:case T.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,Qr.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,en.Center),this._startNote.slideTarget){const s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,Qr.OnNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,en.Center)):(n=e+i.x+i.width,o=r),this._startNote.slideTarget.fret>this._startNote.fret?(r+=3,o-=3):(r-=3,o+=3)}else n=e+i.x+this._parent.x,o=r;break;case T.OutUp:a=e+i.x+i.getNoteX(this._startNote,tn.Right)+2,r=t+i.y+i.getNoteY(this._startNote,en.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,en.Center)-3;break;case T.OutDown:a=e+i.x+i.getNoteX(this._startNote,tn.Right)+2,r=t+i.y+i.getNoteY(this._startNote,en.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,en.Center)+3;break;case T.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,tn.Right)+4,r=t+i.y+i.getNoteY(this._startNote,en.Center),n=e+i.x+i.width,o=r+9,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Qr.PreNotes)),h=!0;break;case T.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,tn.Right)+4,r=t+i.y+i.getNoteY(this._startNote,en.Center),n=e+i.x+i.width,o=r-9,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Qr.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){const t=new vo(0,0,N.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;const n=i-s,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;const l=Math.asin(o/h)*(180/Math.PI);e.beginRotate(s,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(s,a),e.lineTo(i,r),e.stroke()}}class Uh extends qo{constructor(e,t,s=!1){super(e.beat,t.beat,s),this.startNote=e,this.endNote=t}getTieHeight(e,t,s,i){return this.startNote===this.endNote?15:super.getTieHeight(e,t,s,i)}getBeamDirection(e,t){return this.startNote===this.endNote?je.Up:Uh.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?je.Up:je.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,en.Center):this.tieDirection===je.Up?this.startNoteRenderer.getNoteY(this.startNote,en.Top):this.startNoteRenderer.getNoteY(this.startNote,en.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,tn.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,tn.Left):this.endNoteRenderer.getNoteX(this.endNote,tn.Center)}}class zh extends Uh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=Uh.getBeamDirectionForNote(e),this._forSlide=s}getTieHeight(e,t,s,i){return Math.log(s-e+1)*this.renderer.settings.notation.slurHeight}tryExpand(e,t,s,i){if(this._forSlide!==s)return!1;if(this.forEnd!==i)return!1;if(this.startNote.beat.id!==e.beat.id)return!1;if(this.endNote.beat.id!==t.beat.id)return!1;if(this._direction!==Uh.getBeamDirectionForNote(e))return!1;switch(this._direction){case je.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 je.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,s){const i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar),a=this.getBeamDirection(this.startBeat,i),r=`tab.slur.${this.startNote.beat.id}.${this.endNote.beat.id}.${a}`,n=this.renderer;n.staff.getSharedLayoutData(r,!1)||(n.staff.setSharedLayoutData(r,!0),super.paint(e,t,s))}}class Xh extends vr{constructor(){super(...arguments),this._bend=null,this._effectSlurs=[]}drawBeamHelperAsFlags(e){return e.hasFlag(this.renderer.drawBeamHelperAsFlags(e),this.beat)}doLayout(){this._effectSlurs=[],super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(!e.isVisible)return;const t=this.renderer;if(e.isTieOrigin&&t.showTiedNotes&&e.tieDestination.isVisible){const t=new Uh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){const t=new Uh(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){const t=new Uh(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){const t=new zh(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){const t=new zh(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==k.None||e.slideOutType!==T.None){const t=new Gh(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new ch;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class Jh extends wr{constructor(e,t,s){super(e,t),this._noteString=null,this._trillNoteString=null,this._trillNoteStringWidth=0,this.isEmpty=!1,this.noteStringWidth=0,this._note=s}doLayout(){const e=this._note;let t=e.fret-e.beat.voice.bar.staff.transpositionPitch;if(e.harmonicType===w.Natural&&0!==e.harmonicValue&&(t=e.harmonicValue-e.beat.voice.bar.staff.transpositionPitch),e.isTieDestination)0===e.beat.index&&this.renderer.settings.notation.notationMode===P.GuitarPro||(e.bendType===p.Bend||e.bendType===p.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(C.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===w.Natural){const 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(ue.isAlmostEqualTo(e.harmonicValue,0))this._trillNoteString="";else switch(e.harmonicType){case w.Artificial:case w.Pinch:case w.Tap:case w.Semi:case w.Feedback:let s=(t+e.harmonicValue).toString();const i=s.indexOf(String.fromCharCode(46));i>=0&&(s=s.substr(0,i+2)),this._trillNoteString=`<${s}>`;break;default:this._trillNoteString=""}if(this.isEmpty=!this._noteString,!this.isEmpty){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.tablatureFont,this.noteStringWidth=this.renderer.scoreRenderer.canvas.measureText(this._noteString).width,this.width=this.noteStringWidth,this.height=this.renderer.scoreRenderer.canvas.font.size;!!this._trillNoteString&&(this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,this._trillNoteStringWidth=3+this.renderer.scoreRenderer.canvas.measureText(this._trillNoteString).width,this.width+=this._trillNoteStringWidth)}}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{if(this.isEmpty)return;const a=this.noteStringWidth+this._trillNoteStringWidth,r=e+this.x+(this.width-a)/2;this.paintTrill(r,t,s);jr(i,cn.note(s,H.GuitarTabFretNumber,this._note),!1);s.fillText(this._noteString,r,t+this.y)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}paintTrill(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.note(s,H.GuitarTabFretNumber,this._note),!1);const a=this.renderer.scoreRenderer.canvas.font;this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,s.fillText(this._trillNoteString,e+this.noteStringWidth+3,t+this.y),this.renderer.scoreRenderer.canvas.font=a}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}buildBoundingsLookup(e,t,s){const i=new ki;i.note=this._note,i.noteHeadBounds=new Is,i.noteHeadBounds.x=t+this.x,i.noteHeadBounds.y=s+this.y-this.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}class Yh extends wr{constructor(e,t,s){super(e,t),this._notes=[],this._deadSlapped=null,this.minStringNote=null,this.beatEffects=new Map,this.notesPerString=new Map,this.noteStringWidth=0,this._isGrace=s}buildBoundingsLookup(e,t,s){for(const i of this._notes)i.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteX(e,t){if(this.notesPerString.has(e.string)){const s=this.notesPerString.get(e.string);let i=this.x+s.x;switch(t){case tn.Left:break;case tn.Center:i+=s.noteStringWidth/2;break;case tn.Right:i+=s.width}return i}return 0}getNoteY(e,t){if(this.notesPerString.has(e.string)){const s=this.notesPerString.get(e.string);let i=this.y+s.y;switch(t){case en.Top:case en.TopWithStem:i-=s.height/2+2;break;case en.Center:break;case en.Bottom:case en.BottomWithStem:i+=s.height/2}return i}return 0}doLayout(){let e=0;if(this.beat.deadSlapped)this._deadSlapped=new sh,this._deadSlapped.renderer=this.renderer,this._deadSlapped.doLayout(),e=this._deadSlapped.width,this.noteStringWidth=e;else{let t=0;for(let s=0,i=this._notes.length;s<i;s++){const i=this._notes[s];i.renderer=this.renderer,i.doLayout(),i.width>e&&(e=i.width),i.noteStringWidth>t&&(t=i.noteStringWidth)}this.noteStringWidth=t;const s=this.renderer.resources.tablatureFont.size;let i=this.getNoteY(this.minStringNote,en.Center)+s/2;const a=7;for(const e of this.beatEffects.values())e.y+=i,e.x+=this.width/2,e.renderer=this.renderer,i+=a,e.doLayout()}this.width=e}addNoteGlyph(e,t){this._notes.push(e),this.notesPerString.set(t.string,e),(!this.minStringNote||t.string<this.minStringNote.string)&&(this.minStringNote=t)}paint(e,t,s){if(e+=this.x,t+=this.y,this.beat.deadSlapped)this._deadSlapped?.paint(e,t,s);else{const i={stack:[],error:void 0,hasError:!1};try{const a=this.renderer.resources,r=s.textBaseline;s.textBaseline=R.Middle,s.font=this._isGrace?a.graceFont:a.tablatureFont;const n=this._notes,o=this.width;for(const i of n)i.renderer=this.renderer,i.width=o,i.paint(e,t,s);s.textBaseline=r;jr(i,cn.beat(s,Y.GuitarTabEffects,this.beat),!1);for(const i of this.beatEffects.values())i.paint(e,t,s)}catch(e){i.error=e,i.hasError=!0}finally{on(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 $h extends Tr{constructor(e,t,s,i){super(e,t,1,ah.getSymbol(i)),this._isVisibleRest=s}doLayout(){super.doLayout(),this._isVisibleRest||(this.width=10)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){if(this._isVisibleRest){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.beat(s,Y.GuitarTabRests,this.beat),!1);super.paint(e,t,s)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}}class qh extends Hn{constructor(){super(...arguments),this.slash=null,this.noteNumbers=null,this.restGlyph=null}get effectElement(){return Y.GuitarTabEffects}getNoteX(e,t){return this.noteNumbers?this.noteNumbers.getNoteX(e,t):0}getNoteY(e,t){return this.noteNumbers?this.noteNumbers.getNoteY(e,t):0}buildBoundingsLookup(e,t,s){this.noteNumbers&&this.noteNumbers.buildBoundingsLookup(e,t+this.x,s+this.y)}doLayout(){const e=this.renderer;if(this.container.beat.isRest){const t=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),s=e.getTabY(t),i=new $h(0,s,e.showRests,this.container.beat.duration);if(this.restGlyph=i,i.beat=this.container.beat,i.beamingHelper=this.beamingHelper,this.addNormal(i),this.container.beat.dots>0&&e.showRests){this.addNormal(new ph(0,0,5));for(let e=0;e<this.container.beat.dots;e++)this.addEffect(new Jo(0,s,1.5))}}else{const t=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==b.None;let s;if(this.container.beat.slashed&&!this.container.beat.notes.some((e=>e.isTieDestination))){const i=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),a=e.getLineY(i),r=new Sh(0,a,this.container.beat.duration,t,this.container.beat);r.noteHeadElement=H.GuitarTabFretNumber,r.effectElement=Y.GuitarTabEffects,this.slash=r,r.beat=this.container.beat,r.beamingHelper=this.beamingHelper,this.addNormal(r),s=r.beatEffects}else{const e=new Yh(0,0,t);this.noteNumbers=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;for(const e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);this.addNormal(e),s=e.beatEffects}if(this.container.beat.hasWhammyBar){const e=new dh(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!s.has("tremolo")){let e=0;const t=this.container.beat.tremoloSpeed;let i=5;switch(t){case f.ThirtySecond:e=10;break;case f.Sixteenth:e=5;break;case f.Eighth:e=0}this.container.beat.duration<f.Half&&(i=0),s.set("tremolo",new th(i,e,t))}if(this.container.beat.dots>0&&e.rhythmMode!==x.Hidden){this.addNormal(new ph(0,0,5));for(let t=0;t<this.container.beat.dots;t++)this.addEffect(new Jo(0,e.lineOffset*e.bar.staff.tuning.length+e.settings.notation.rhythmHeight,1.5))}}if(this.isEmpty)return;let t=0;for(let e=0,s=this.glyphs.length;e<s;e++){const s=this.glyphs[e];s.x=t,s.renderer=this.renderer,s.doLayout(),t+=s.width}this.width=t,this.computedWidth=t,this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteNumbers?this.centerX=this.noteNumbers.x+this.noteNumbers.noteStringWidth/2:this.slash&&(this.centerX=this.slash.x+this.slash.width/2)}updateBeamingHelper(){this.noteNumbers?this.noteNumbers.updateBeamingHelper(this.container.x+this.x):this.restGlyph?this.restGlyph.updateBeamingHelper(this.container.x+this.x):this.slash&&this.slash.updateBeamingHelper(this.container.x+this.x)}createNoteGlyph(e){const t=this.renderer,s=new Jh(0,0,e),i=e.beat.voice.bar.staff.tuning.length-e.string;s.y=t.getTabY(i),s.renderer=this.renderer,s.doLayout(),this.noteNumbers.addNoteGlyph(s,e);const a=s.y-s.height/2,r=a+s.height;this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,a,r)}}class Kh extends wr{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10}paint(e,t,s){const i=this.renderer,a=t+this.x+i.getNoteY(this._beat.maxStringNote,en.Top),r=t+this.y+i.getNoteY(this._beat.minStringNote,en.Bottom),n=e+this.x+this.width/2|0;if(this._beat.brushType!==g.None){if(this._beat.brushType===g.BrushUp||this._beat.brushType===g.BrushDown)s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke();else if(this._beat.brushType===g.ArpeggioUp){const t=new vo(0,0,N.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();const i=a,n=r-8;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4,n,-90),t.paint(0,-t.height/2,s),s.endRotate()}else if(this._beat.brushType===g.ArpeggioDown){const t=new vo(0,0,N.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();const i=a+8,n=r;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4,i,90),t.paint(0,-t.height/2,s),s.endRotate()}this._beat.brushType===g.BrushUp||this._beat.brushType===g.ArpeggioUp?(s.beginPath(),s.moveTo(n,r),s.lineTo(n+4,r-8),s.lineTo(n-4,r-8),s.closePath(),s.fill()):(s.beginPath(),s.moveTo(n,a),s.lineTo(n+4,a+8),s.lineTo(n-4,a+8),s.closePath(),s.fill())}}}class jh extends On{doLayout(){this.container.beat.brushType===g.None||this.container.beat.isRest||(this.addEffect(new Kh(this.container.beat)),this.addNormal(new ph(0,0,4))),super.doLayout()}get effectElement(){return Y.GuitarTabEffects}}class Qh extends wr{doLayout(){this.width=kr.Widths.get(I.SixStringTabClef)}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.bar(s,c.GuitarTabsClef,this.renderer.bar),!1);const a=this.renderer.bar.staff.tuning.length,r=a<=4?I.FourStringTabClef:I.SixStringTabClef,n=a<=4?a/4.5:a/6.5;s.fillMusicFontSymbol(e+this.x+5,t+this.y,n,r,!1)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}class Zh extends Nh{doLayout(){this.barSubElement=c.GuitarTabsTimeSignature,super.doLayout()}get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?Nr.GraceScale:1}}class el extends Oh{get showMultiBarRest(){return this._showMultiBarRest}get repeatsBarSubElement(){return c.GuitarTabsRepeats}get barNumberBarSubElement(){return c.GuitarTabsBarNumber}get barSeparatorBarSubElement(){return c.GuitarTabsBarSeparator}get staffLineBarSubElement(){return c.GuitarTabsStaffLine}constructor(e,t){super(e,t),this._hasTuplets=!1,this.showTimeSignature=!1,this.showRests=!1,this.showTiedNotes=!1,this._showMultiBarRest=!1,t.staff.showStandardNotation||(this.showTimeSignature=!0,this.showRests=!0,this.showTiedNotes=!0,this._showMultiBarRest=!0)}get lineSpacing(){return el.TabLineSpacing}get heightLineCount(){return this.bar.staff.tuning.length}get drawnLineCount(){return this.bar.staff.tuning.length}get rhythmMode(){let e=this.settings.notation.rhythmMode;return e===x.Automatic&&(e=this.bar.staff.showStandardNotation?x.Hidden:x.ShowWithBars),e}getTabY(e){return super.getLineY(e)}getTabHeight(e){return super.getLineHeight(e)}collectSpaces(e){for(const t of this.bar.voices)if(this.hasVoiceContainer(t)){const s=this.getVoiceContainer(t);for(const t of s.beatGlyphs){const i=t.onNotes,a=i.noteNumbers;if(a)for(const[r,n]of a.notesPerString)n.isEmpty||e[this.bar.staff.tuning.length-r].push(new Float32Array([s.x+t.x+i.x+a.x,a.width+1]))}}}adjustSizes(){this.rhythmMode!==x.Hidden&&(this.height+=this.settings.notation.rhythmHeight,this.bottomPadding+=this.settings.notation.rhythmHeight)}doLayout(){if(super.doLayout(),this.rhythmMode!==x.Hidden){this._hasTuplets=!1;for(const e of this.bar.voices)if(this.hasVoiceContainer(e)){if(this.getVoiceContainer(e).tupletGroups.length>0){this._hasTuplets=!0;break}}this._hasTuplets&&this.registerOverflowBottom(this.tupletSize)}}createLinePreBeatGlyphs(){if(this.isFirstOfLine){const e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new Qh(5,this.getTabY(e)))}this.showTimeSignature&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new ph(0,0,5));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new Zh(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon,this.bar.masterBar.isFreeTime))}createVoiceGlyphs(e){if(this.additionalMultiRestBars){const t=new Gn(this.getVoiceContainer(e));this.addBeatGlyph(t)}else for(const t of e.beats){const s=new Xh(t,this.getVoiceContainer(e));s.preNotes=new jh,s.onNotes=new qh,this.addBeatGlyph(s)}}paint(e,t,s){super.paint(e,t,s),this.rhythmMode!==x.Hidden&&(this.paintBeams(e,t,s,Y.GuitarTabFlags,Y.GuitarTabBeams),this.paintTuplets(e,t,s,Y.GuitarTabTuplet))}drawBeamHelperAsFlags(e){return super.drawBeamHelperAsFlags(e)||this.rhythmMode===x.ShowWithBeams}getFlagTopY(e,t){const s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==f.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,en.Bottom):this.height-this.settings.notation.rhythmHeight-this.tupletSize}getFlagBottomY(e,t){return this.getFlagAndBarPos()}getFlagStemSize(e,t=!1){return 0}getBarLineStart(e,t){const s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==f.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,en.Bottom)+this.lineOffset/2:this.height-this.settings.notation.rhythmHeight-this.tupletSize}getBeamDirection(e){return je.Down}getFlagAndBarPos(){return this.height-(this._hasTuplets?this.tupletSize/2:0)}calculateBeamYWithDirection(e,t,s){return this.getFlagAndBarPos()}shouldPaintFlag(e,t){return!!super.shouldPaintFlag(e,t)&&(e.graceType===b.None&&this.drawBeamHelperAsFlags(t))}paintBeamingStem(e,t,s,i,a,r){const n={stack:[],error:void 0,hasError:!1};try{if(a<i){const e=a;a=i,i=e}jr(n,cn.beat(r,Y.GuitarTabStem,e),!1);r.lineWidth=Un.StemWidth,r.beginPath();let o=[];this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.has(e.displayStart)&&(o=this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.get(e.displayStart).slots.slice(),o.sort(((e,t)=>e.topY-t.topY)));let h=a;for(;h>i;){r.moveTo(s,h);let e=i;if(!(o.length>0&&o[o.length-1].bottomY>e)){r.lineTo(s,e);break}{const i=o.pop();e=t+i.bottomY,r.lineTo(s,e),h=t+i.topY}}r.stroke(),r.lineWidth=1}catch(e){n.error=e,n.hasError=!0}finally{on(n)}}}el.StaffId="tab",el.TabLineSpacing=10;class tl extends Kr{get staffId(){return el.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}constructor(){super(),this.showTimeSignature=null,this.showRests=null,this.showTiedNotes=null,this.hideOnPercussionTrack=!0}canCreate(e,t){return t.showTablature&&t.tuning.length>0&&super.canCreate(e,t)}create(e,t){const s=new el(e,t);return null!==this.showRests&&(s.showRests=this.showRests),null!==this.showTimeSignature&&(s.showTimeSignature=this.showTimeSignature),null!==this.showTiedNotes&&(s.showTiedNotes=this.showTiedNotes),s}}class sl extends Br{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+sl.Padding}paint(e,t,s){const i=this.renderer.resources;s.font=i.effectFont;const a=s.textAlign;s.textAlign=A.Center,s.fillText("T",e+this.x,t+this.y+s.font.size/2),s.textAlign=a,s.strokeCircle(e+this.x,t+this.y+s.font.size/2+(sl.Padding-1),s.font.size/1.6)}}sl.Padding=4;class il extends uo{get notationElement(){return C.EffectTap}get sizingMode(){return sn.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new sl}}class al{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"}(rn||(rn={}));class rl extends al{constructor(){super(...arguments),this.align=A.Left,this.frame=rn.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class nl extends al{constructor(){super(...arguments),this.chord=new ut}}class ol extends al{}class hl extends al{}class ll extends al{constructor(){super(...arguments),this.number=0}}class cl extends al{constructor(){super(...arguments),this.decrescendo=!1}}class dl extends al{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class ul extends al{constructor(){super(...arguments),this.octave=1}}class pl extends al{}class gl{constructor(){this.defaultClef=n.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class ml{constructor(){this.from=0,this.to=0,this.curly=!1}}class fl{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class yl{constructor(){this._trackChannel=0,this._beamingMode=J.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new le,this._voiceStates=new Map}parseXml(e,t){this._galleryObjects=new Map,this._tieStarts=[],this._tieStartIds=new Map,this._voiceCounts=new Map,this._slurs=new Map,this._crescendo=new Map,this._isFirstSystem=!0;const s=new zs;try{s.parse(e)}catch(e){throw new dt("Could not parse XML",e)}this.parseDom(s),this.consolidate(),this.score.finish(t)}consolidate(){for(const e of this.score.tracks){const t=this._voiceCounts.get(e.index);for(const s of e.staves){for(;s.bars.length<this.score.masterBars.length;)this.addNewBar(s);for(const e of s.bars){for(;e.voices.length<t;)e.addVoice(new Pe);for(const t of e.voices)if(0===t.beats.length){const e=new xe;e.isEmpty=!0,t.addBeat(e)}}}}yl.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),yl.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?m.Decrescendo:m.Crescendo}))}static applyEffectRange(e,t){for(const[s,i]of e){const e=i.noteRange;let a=s;for(let s=0;s<e;s++)if(t(i,a),a.index+1<a.voice.beats.length)a=a.voice.beats[a.index+1];else{if(!(a.voice.bar.index+1<a.voice.bar.staff.bars.length))break;a=a.voice.bar.staff.bars[a.voice.bar.index+1].voices[a.voice.index].beats[0]}}}parseDom(e){const t=e.firstElement;if(!t)throw new dt("No valid XML");if("score"!==t.localName)throw new dt('Root node of XML was not "score"');this.score=new lt,this.score.tempo=120;for(const e of t.childElements())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(const t of e.childElements())switch(t.localName){case"staves":this.parseLayoutStaves(t);break;case"brackets":this.parseBrackets(t)}const t=this._brackets.filter((e=>!!e.curly));t.sort(((e,t)=>e.from-t.from));let s=0,i=null;for(let e=0;e<this._staffLayouts.length;e++){const a=this._staffLayouts[e];for(;s<t.length&&e>t[s].to;)s++;i&&s<t.length&&e>t[s].from&&e<=t[s].to?i.ensureStaveCount(i.staves.length+1):(i=new St,i.ensureStaveCount(1),i.name=a.description,i.playbackInfo.volume=Math.floor(a.volume/128*16),i.playbackInfo.program=a.instrument,a.percussion?(i.playbackInfo.primaryChannel=9,i.playbackInfo.secondaryChannel=9):(i.playbackInfo.primaryChannel=this._trackChannel++,i.playbackInfo.secondaryChannel=this._trackChannel++),this.score.addTrack(i));const r=i.staves[i.staves.length-1];r.isPercussion=a.percussion,r.transpositionPitch=a.transpose,r.displayTranspositionPitch=0,r.showTablature=!1,this._staffLookup.set(a.index,r)}}parseBrackets(e){for(const t of e.childElements())if("bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new ml;t.from=Number.parseInt(e.getAttribute("from")),t.to=Number.parseInt(e.getAttribute("to")),e.attributes.has("curly")&&(t.curly="true"===e.attributes.get("curly")),this._brackets.push(t)}parseLayoutStaves(e){for(const t of e.childElements())if("staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new gl;t.description=e.getAttribute("description");for(const s of e.childElements())switch(s.localName){case"notation":s.attributes.has("defaultClef")&&(t.defaultClef=this.parseClef(s.attributes.get("defaultClef")));break;case"sound":s.attributes.has("percussion")&&(t.percussion="true"===s.attributes.get("percussion")),s.attributes.has("instr")&&(t.instrument=Number.parseInt(s.attributes.get("instr"))),s.attributes.has("volume")&&(t.volume=Number.parseInt(s.attributes.get("volume"))),s.attributes.has("transpose")&&(t.transpose=Number.parseInt(s.attributes.get("transpose")))}this._staffLayoutLookup.set(t.description,t),t.index=this._staffLayouts.length,this._staffLayouts.push(t)}parseClef(e){switch(e){case"treble":return n.G2;case"bass":return n.F4;case"alto":case"tenor":return n.C4}return n.G2}parseClefOttava(e){return e.endsWith("-")?o._8vb:e.endsWith("+")?o._8va:o.Regular}parseSystems(e){for(const t of e.childElements())if("system"===t.localName)this.parseSystem(t)}parseSystem(e){e.attributes.has("tempo")&&0===this.score.masterBars.length&&(this.score.tempo=Number.parseInt(e.attributes.get("tempo"))),"0"===e.getAttribute("beamGrouping")&&(this._beamingMode=J.ForceSplitToNext);for(const t of e.childElements())if("staves"===t.localName)this.parseStaves(e,t);this._isFirstSystem=!1}parseStaves(e,t){const s=this.score.masterBars.length;for(const i of t.childElements())if("staff"===i.localName)this.parseStaff(e,s,i)}parseStaff(e,t,s){const i=s.getAttribute("layout");this._currentStaffLayout=this._staffLayoutLookup.get(i),this._timeSignature.timeSignatureNumerator=4,this._timeSignature.timeSignatureDenominator=4,this._timeSignature.timeSignatureCommon=!1,this.parseTime(s.getAttribute("defaultTime"));const a=this._staffLookup.get(this._currentStaffLayout.index);for(;a.bars.length<t;)this.addNewBar(a);for(const r of s.childElements())if("voices"===r.localName)this.parseVoices(i,a,e,t,r)}parseTime(e){switch(e){case"allaBreve":case"C":this._timeSignature.timeSignatureNumerator=2,this._timeSignature.timeSignatureDenominator=2,this._timeSignature.timeSignatureCommon=!0;break;case"longAllaBreve":this._timeSignature.timeSignatureNumerator=4,this._timeSignature.timeSignatureDenominator=4,this._timeSignature.timeSignatureCommon=!0;break;default:if(e.indexOf("/")>0){const t=e.split("/");this._timeSignature.timeSignatureNumerator=Number.parseInt(t[0]),this._timeSignature.timeSignatureDenominator=Number.parseInt(t[1]),this._timeSignature.timeSignatureCommon=!1}}}parseVoices(e,t,s,i,a){let r=0;for(const n of a.childElements())if("voice"===n.localName)this.parseVoice(e,t,s,r,i,n),r++}getOrCreateBar(e,t){return t<e.bars.length?e.bars[t]:this.addNewBar(e)}addNewBar(e){const t=new te;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){const e=new le;this.score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.tripletFeel=e.previousMasterBar.tripletFeel),e.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,e.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,e.timeSignatureCommon=this._timeSignature.timeSignatureCommon}return t}newBar(e,t){this._currentVoiceState.currentBarIndex++,this._currentBar=this.getOrCreateBar(e,this._currentVoiceState.currentBarIndex),this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1),this._currentVoiceState.currentBarComplete=!1,this._currentVoiceState.currentPosition=0,this.ensureVoice(e,t)}parseVoice(e,t,s,i,a,r){const n=`${e}_${i}`;if(this._currentVoiceState&&!this._currentVoiceState.currentBarComplete&&(this._currentBar.masterBar.isAnacrusis=!0),this._voiceStates.has(n)?(this._currentVoiceState=this._voiceStates.get(n),this._currentBar=this.getOrCreateBar(t,this._currentVoiceState.currentBarIndex),this.ensureVoice(t,i)):(this._currentVoiceState=new fl,this._currentVoiceState.currentBarIndex=a-1,this._voiceStates.set(n,this._currentVoiceState),this.newBar(t,i)),r.attributes.has("stemDir"))switch(r.attributes.get("stemDir")){case"up":this._currentVoiceState.voiceStemDir=je.Up;break;case"down":this._currentVoiceState.voiceStemDir=je.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const o=r.findChildElement("noteObjects");if(s.attributes.has("tempo")){const e=new ie;e.isLinear=!0,e.type=d.Tempo,e.value=Number.parseInt(s.attributes.get("tempo")),e.ratioPosition=this._currentVoiceState.currentPosition/this._currentVoiceState.currentBarDuration,this._currentBar.masterBar.tempoAutomations.push(e)}if(o)for(const e of o.childElements())switch(this._currentVoiceState.currentBarComplete&&"barline"!==e.localName&&this.newBar(t,i),e.localName){case"clefSign":this._currentBar.clef=this.parseClef(e.getAttribute("clef")),this._currentBar.clefOttava=this.parseClefOttava(e.getAttribute("clef"));break;case"keySign":this._currentBar.masterBar.keySignature=Number.parseInt(e.getAttribute("fifths"));break;case"timeSign":this.parseTime(e.getAttribute("time")),this._currentBar.masterBar.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,this._currentBar.masterBar.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,this._currentBar.masterBar.timeSignatureCommon=this._timeSignature.timeSignatureCommon,this._currentVoiceState.currentPosition=0,this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1);break;case"barline":switch(e.getAttribute("type")){case"double":this._currentBar.masterBar.isDoubleBar=!0,this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0;break;case"end":this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0);break;case"repEnd":this._currentVoiceState.repeatEnd=this._currentBar.masterBar,this._currentBar.masterBar.repeatCount<this._currentVoiceState.repeatCount&&(this._currentBar.masterBar.repeatCount=this._currentVoiceState.repeatCount),this.parseBarDrawObject(e),this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0;break;case"repBegin":this.newBar(t,i),this._currentBar.masterBar.isRepeatStart=!0,this._currentVoiceState.repeatEnd=null,this._currentVoiceState.repeatCount=0;break;case"repEndBegin":this._currentVoiceState.repeatEnd=this._currentBar.masterBar,this._currentBar.masterBar.repeatCount<this._currentVoiceState.repeatCount&&(this._currentBar.masterBar.repeatCount=this._currentVoiceState.repeatCount),this.parseBarDrawObject(e),this.newBar(t,i),this._currentBar.masterBar.isRepeatStart=!0;break;default:this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0}break;case"chord":const s=new xe;this.initFromPreviousBeat(s,this._currentVoice),s.beamingMode=this._beamingMode,this._currentVoiceState.voiceStemDir&&(s.preferredBeamDirection=this._currentVoiceState.voiceStemDir),this.parseDuration(this._currentBar,s,e.findChildElement("duration")),s.updateDurations(),this._currentVoiceState.currentPosition+=s.playbackDuration,this._currentVoice.addBeat(s),this.parseChord(s,e),this._currentVoiceState.currentPosition>=this._currentVoiceState.currentBarDuration&&(this._currentVoiceState.currentBarComplete=!0);break;case"rest":const a=this.parseRestDurations(this._currentBar,e.findChildElement("duration"));a&&(this.initFromPreviousBeat(a,this._currentVoice),a.updateDurations(),this._currentVoiceState.currentPosition+=a.playbackDuration,this._currentVoice.addBeat(a),this._currentVoiceState.currentPosition>=this._currentVoiceState.currentBarDuration&&(this._currentVoiceState.currentBarComplete=!0))}}initFromPreviousBeat(e,t){const s=this.getLastBeat(t);s&&(e.dynamics=s.dynamics)}getLastBeat(e){if(e.beats.length>0)return e.beats[e.beats.length-1];if(e.bar.index>0){const t=e.bar.staff.bars[e.bar.index-1];if(e.index<t.voices.length){const s=t.voices[e.index];return this.getLastBeat(s)}}return null}ensureVoice(e,t){for(;this._currentBar.voices.length<t+1;)this._currentBar.addVoice(new Pe);(!this._voiceCounts.has(e.track.index)||this._voiceCounts.get(e.track.index)<this._currentBar.voices.length)&&this._voiceCounts.set(e.track.index,this._currentBar.voices.length),this._currentVoice=this._currentBar.voices[t]}parseChord(e,t){const s=new be;for(const i of t.childElements())switch(i.localName){case"stem":switch(i.getAttribute("dir")){case"up":e.preferredBeamDirection=je.Up;break;case"down":e.preferredBeamDirection=je.Down}break;case"articulation":switch(i.getAttribute("type")){case"staccato":s.isStaccato=!0;break;case"normalAccent":s.accentuated=S.Normal;break;case"strongAccent":s.accentuated=S.Heavy}break;case"lyric":this.parseLyric(e,i);break;case"drawObjects":this.parseBeatDrawObject(e,i);break;case"heads":this.parseHeads(e,s,i);break;case"beam":switch(i.getAttribute("group")){case"force":e.beamingMode=J.ForceMergeWithNext;break;case"divide":e.beamingMode=J.ForceSplitToNext}}}parseHeads(e,t,s){for(const i of s.childElements())if("head"===i.localName)this.parseHead(e,t,i)}parseHead(e,t,s){const i=new be,a=ue.parseTuning(s.getAttribute("pitch"));i.octave=a.octave-1,i.tone=a.tone.noteValue,i.isStaccato=t.isStaccato,i.accentuated=t.accentuated,e.addNote(i);for(const e of s.childElements())switch(e.localName){case"alter":e.attributes.has("step")&&(i.tone+=Number.parseInt(e.attributes.get("step")));break;case"tie":e.attributes.has("begin")?this._tieStartIds.has(i.id)||(this._tieStartIds.set(i.id,!0),this._tieStarts.push(i)):e.attributes.has("end")&&this._tieStarts.length>0&&!i.isTieDestination&&(i.isTieDestination=!0,i.tieOrigin=this._tieStarts[0],this._tieStarts.splice(0,1),this._tieStartIds.delete(i.id))}}parseBeatDrawObject(e,t){for(const s of t.childElements())if("drawObj"===s.localName){const t=this.parseDrawObj(s);if(t)if(t instanceof rl)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new Tt,e.fermata.type=Ke.Medium):"f"===t.text?e.dynamics=y.F:"j"===t.text&&(e.dynamics=y.MF):this._isFirstSystem&&""===this.score.title&&t.align===A.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===A.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===A.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof nl);else if(t instanceof hl)e.vibrato=N.Slight;else if(t instanceof cl)e.crescendo=t.decrescendo?m.Decrescendo:m.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof ol){const s=t;this._slurs.set(e,s)}else t instanceof dl&&this.applyVolta(t)}}parseBarDrawObject(e){for(const t of e.childElements())if("drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof dl&&this.applyVolta(e)}}applyVolta(e){if(e.lastNumber>0?(this._currentVoiceState.repeatCount=e.lastNumber,this._currentVoiceState.repeatEnd&&this._currentVoiceState.repeatEnd.repeatCount<this._currentVoiceState.repeatCount&&(this._currentVoiceState.repeatEnd.repeatCount=this._currentVoiceState.repeatCount)):e.firstNumber>0&&(this._currentVoiceState.repeatCount=e.firstNumber,this._currentVoiceState.repeatEnd&&this._currentVoiceState.repeatEnd.repeatCount<this._currentVoiceState.repeatCount&&(this._currentVoiceState.repeatEnd.repeatCount=this._currentVoiceState.repeatCount)),e.lastNumber>0&&e.firstNumber>0){let t=0;for(let s=e.firstNumber;s<=e.lastNumber;s++)t|=1<<s-1;this._currentBar.masterBar.alternateEndings=t}else e.lastNumber>0?this._currentBar.masterBar.alternateEndings=1<<e.lastNumber-1:e.firstNumber>0&&(this._currentBar.masterBar.alternateEndings=1<<e.firstNumber-1)}parseLyric(e,t){for(const s of t.childElements())if("verse"===s.localName){e.lyrics||(e.lyrics=[]);let t=s.innerText;"true"===s.getAttribute("hyphen")&&(t+="-"),e.lyrics.push(t)}}parseRestDurations(e,t){const s=t.getAttribute("base");if(-1!==s.indexOf("/")){const s=new xe;return s.beamingMode=this._beamingMode,this.parseDuration(e,s,t),s}if(1===Number.parseInt(s)){const e=new xe;return e.beamingMode=this._beamingMode,e.duration=f.Whole,e}return he.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return f.DoubleWhole;case"1/1":return f.Whole;case"1/2":return f.Half;case"1/4":return f.Quarter;case"1/8":return f.Eighth;case"1/16":return f.Sixteenth;case"1/32":return f.ThirtySecond;case"1/64":return f.SixtyFourth;case"1/128":return f.OneHundredTwentyEighth;default:return he.warning("Importer","Unsupported duration"),f.Quarter}}parseDuration(e,t,s){const i=s.getAttribute("base");t.duration=this.parseDurationValue(i),s.attributes.has("dots")&&(t.dots=Number.parseInt(s.attributes.get("dots")));const a=s.findChildElement("tuplet");if(a){t.tupletNumerator=Number.parseInt(a.getAttribute("count"));const e="true"===a.getAttribute("tripartite")?3:1,s="true"===a.getAttribute("prolong")?0:1;let i=0;for(;e*Math.pow(2,i+s)<t.tupletNumerator;)i++;t.tupletDenominator=e*Math.pow(2,i)}}parsePageObjects(e){for(const t of e.childElements())if("drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof rl)switch(e.align){case A.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case A.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(const t of e.childElements())if("drawObj"===t.localName){const e=this.parseDrawObj(t);e&&this._galleryObjects.set(t.getAttribute("name"),e)}}parseDrawObj(e){let t=null,s=1;for(const i of e.childElements())switch(i.localName){case"text":t=this.parseText(i);break;case"guitar":t=this.parseGuitar(i);break;case"slur":t=this.parseSlur(i);break;case"wavyLine":t=this.parseWavyLine(i);break;case"bracket":t=this.parseTupletBracket(i);break;case"wedge":t=this.parseWedge(i);break;case"volta":t=this.parseVolta(i);break;case"octaveClef":t=this.parseOctaveClef(i);break;case"trill":t=this.parseTrill(i);break;case"basic":i.attributes.has("noteRange")&&(s=Number.parseInt(i.attributes.get("noteRange")))}return t&&(t.noteRange=s),t}parseTrill(e){return new pl}parseOctaveClef(e){const t=new ul;return e.attributes.has("octave")&&(t.octave=Number.parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new dl;return t.allNumbers="true"===e.attributes.get("allNumbers"),e.attributes.has("firstNumber")&&(t.firstNumber=Number.parseInt(e.attributes.get("firstNumber"))),e.attributes.has("lastNumber")&&(t.lastNumber=Number.parseInt(e.attributes.get("lastNumber"))),t}parseWedge(e){const t=new cl;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new ll;return e.attributes.has("number")&&(t.number=Number.parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new hl}parseSlur(e){return new ol}parseGuitar(e){const t=new nl,s=e.innerText.trim();for(let e=0;e<s.length;e++)"/"===s.charAt(e)?t.chord.strings.push(0):t.chord.strings.push(Number.parseInt(s.charAt(e)));return t}parseText(e){const t=new rl;switch(e.attributes.has("x")&&(t.x=Number.parseFloat(e.attributes.get("x"))),e.attributes.has("x")&&(t.y=Number.parseFloat(e.attributes.get("y"))),e.getAttribute("align")){case"left":t.align=A.Left;break;case"center":t.align=A.Center;break;case"right":t.align=A.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=rn.Rectangle;break;case"ellipse":t.frame=rn.Ellipse;break;case"circle":t.frame=rn.Circle;break;case"none":t.frame=rn.None}if(e.firstElement)for(const s of e.childElements())switch(s.localName){case"font":t.fontFace=s.getAttribute("face"),s.attributes.has("weight")&&(t.weight=Number.parseInt(s.attributes.get("weight"))),s.attributes.has("height")&&(t.height=Number.parseInt(s.attributes.get("height")));break;case"content":t.text=s.innerText}else t.text=e.innerText;return t}parseInfo(e){for(const t of e.childElements())switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class bl extends ct{get name(){return"Capella"}readScore(){he.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new oi(this.data).read(),he.debug(this.name,"Zip entries loaded"),e.length>0){for(const s of e)if("score.xml"===s.fileName)t=wt.toString(s.data,this.settings.importer.encoding)}else this.data.reset(),t=wt.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new dt("No valid capella file");he.debug(this.name,"Start Parsing score.xml");try{const e=new yl;e.parseXml(t,this.settings),he.debug(this.name,"score.xml parsed");return e.score}catch(e){throw new dt("Failed to parse CapXML",e)}}}class Sl{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 _l{constructor(e){this._elements=[];let t=null;const s=this.check.bind(this);this.check=()=>{t||(t=setTimeout((()=>{s(),t=null}),100))},this._callback=e,window.addEventListener("resize",this.check,!0),document.addEventListener("scroll",this.check,!0)}observe(e){this._elements.indexOf(e)>=0||(this._elements.push(e),this.check())}unobserve(e){this._elements=this._elements.filter((t=>t!==e))}check(){const e=[];for(const t of this._elements){const s=t.getBoundingClientRect();s.top+s.height>=0&&s.top<=window.innerHeight&&s.left+s.width>=0&&s.left<=window.innerWidth&&e.push({target:t,isIntersecting:!0})}e.length&&this._callback(e,this)}}class wl{static enable(e,t){wl.alphaSkia=t,wl.initializeMusicFont(wl.alphaSkia.AlphaSkiaTypeface.register(e))}static initializeMusicFont(e){wl.musicFont=e}static registerFont(e,t){const s=wl.alphaSkia.AlphaSkiaTypeface.register(e.buffer);t||(t=We.withFamilyList([s.familyName],12,s.isItalic?Fe.Italic:Fe.Plain,s.isBold?De.Bold:De.Regular));for(const e of t.families)wl.customTypeFaces.set(wl.customTypefaceKey(e,t.isBold,t.isItalic),s);return t}static customTypefaceKey(e,t,s){return`${e.toLowerCase()}_${t}_${s}`}getTypeFace(){if(this._typeFaceCache!==this.font.toCssString(this._scale)){if(this._typeFaceIsSystem){const e={stack:[],error:void 0,hasError:!1};try{jr(e,this._typeFace,!1)}catch(t){e.error=t,e.hasError=!0}finally{on(e)}}for(const e of this.font.families){const t=wl.customTypefaceKey(e,this.font.isBold,this.font.isItalic);wl.customTypeFaces.has(t)?(this._typeFaceIsSystem=!1,this._typeFace=wl.customTypeFaces.get(t)):(this._typeFaceIsSystem=!0,this._typeFace=wl.alphaSkia.AlphaSkiaTypeface.create(e,this.font.isBold,this.font.isItalic))}this._typeFaceCache=this.font.toCssString(this._scale)}return this._typeFace}constructor(){this._color=new Ae(0,0,0,0),this._lineWidth=0,this._typeFaceCache="",this._typeFaceIsSystem=!1,this._typeFace=null,this._scale=1,this.font=new We("Arial",10,Fe.Plain),this.textAlign=A.Left,this.textBaseline=R.Top,this._initialMeasure=!0,this._canvas=new wl.alphaSkia.AlphaSkiaCanvas,this.color=new Ae(0,0,0,255)}destroy(){const e={stack:[],error:void 0,hasError:!1};try{jr(e,this._canvas,!1)}catch(t){e.error=t,e.hasError=!0}finally{on(e)}}onRenderFinished(){return null}beginRender(e,t){this._scale=this.settings.display.scale,this._canvas.beginRender(e,t,ic.HighDpiFactor)}endRender(){return this._canvas.endRender()}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._canvas.color=wl.alphaSkia.AlphaSkiaCanvas.rgbaToColor(e.r,e.g,e.b,e.a))}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._canvas.lineWidth=e}fillRect(e,t,s,i){s>0&&this._canvas.fillRect(e*this._scale|0,t*this._scale|0,s*this._scale,i*this._scale)}strokeRect(e,t,s,i){const a=this.lineWidth%2==0?0:.5;this._canvas.strokeRect((e*this._scale|0)+a,(t*this._scale|0)+a,s*this._scale,i*this._scale)}beginPath(){this._canvas.beginPath()}closePath(){this._canvas.closePath()}moveTo(e,t){this._canvas.moveTo(e*this._scale,t*this._scale)}lineTo(e,t){this._canvas.lineTo(e*this._scale,t*this._scale)}quadraticCurveTo(e,t,s,i){this._canvas.quadraticCurveTo(e*this._scale,t*this._scale,s*this._scale,i*this._scale)}bezierCurveTo(e,t,s,i,a,r){this._canvas.bezierCurveTo(e*this._scale,t*this._scale,s*this._scale,i*this._scale,a*this._scale,r*this._scale)}fillCircle(e,t,s){this._canvas.fillCircle(e*this._scale,t*this._scale,s*this._scale)}strokeCircle(e,t,s){this._canvas.strokeCircle(e*this._scale,t*this._scale,s*this._scale)}fill(){this._canvas.fill()}stroke(){this._canvas.stroke()}beginGroup(e){}endGroup(){}fillText(e,t,s){if(0===e.length)return;let i=wl.alphaSkia.AlphaSkiaTextAlign.Left;switch(this.textAlign){case A.Left:i=wl.alphaSkia.AlphaSkiaTextAlign.Left;break;case A.Center:i=wl.alphaSkia.AlphaSkiaTextAlign.Center;break;case A.Right:i=wl.alphaSkia.AlphaSkiaTextAlign.Right}let a=wl.alphaSkia.AlphaSkiaTextBaseline.Top;switch(this.textBaseline){case R.Top:a=wl.alphaSkia.AlphaSkiaTextBaseline.Top;break;case R.Middle:a=wl.alphaSkia.AlphaSkiaTextBaseline.Middle;break;case R.Bottom:a=wl.alphaSkia.AlphaSkiaTextBaseline.Bottom}this._canvas.fillText(e,this.getTypeFace(),this.font.size*this._scale,t*this._scale|0,s*this._scale|0,i,a)}measureText(e){return this._initialMeasure&&(this._canvas.measureText(e,this.getTypeFace(),this.font.size),this._initialMeasure=!1),new pe(this._canvas.measureText(e,this.getTypeFace(),this.font.size),this.font.size*wl.FontSizeToLineHeight)}fillMusicFontSymbol(e,t,s,i,a){i!==I.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(const e of i)e!==I.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){this._canvas.fillText(i,wl.musicFont,ic.MusicFontSize*this._scale*s,e*this._scale,t*this._scale,a?wl.alphaSkia.AlphaSkiaTextAlign.Center:wl.alphaSkia.AlphaSkiaTextAlign.Left,wl.alphaSkia.AlphaSkiaTextBaseline.Alphabetic)}beginRotate(e,t,s){this._canvas.beginRotate(e*this._scale,t*this._scale,s)}endRotate(){this._canvas.endRotate()}}wl.musicFont=null,wl.customTypeFaces=new Map,wl.FontSizeToLineHeight=1.2;class Bl extends qo{constructor(e,t,s=!1){super(e.beat,t.beat,s),this.startNote=e,this.endNote=t}getTieHeight(e,t,s,i){return this.startNote===this.endNote?15:super.getTieHeight(e,t,s,i)}getBeamDirection(e,t){return je.Down}static getBeamDirectionForNote(e){return je.Down}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,en.Center)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,tn.Right)}getEndX(){return this.endNoteRenderer.getNoteX(this.endNote,tn.Left)}}class kl extends vr{constructor(){super(...arguments),this._tiedNoteTie=null}createTies(e){if(e.isVisible){if(!this._tiedNoteTie&&e.isTieOrigin&&e.tieDestination.isVisible){const t=new Bl(e,e.tieDestination,!1);this._tiedNoteTie=t,this.addTie(t)}if(!this._tiedNoteTie&&e.isTieDestination){const t=new Bl(e.tieOrigin,e,!0);this._tiedNoteTie=t,this.addTie(t)}}}}class Tl extends ah{updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){super.internalPaint(e,t,s,Y.SlashRests)}}class Nl extends Hn{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.restGlyph=null}get effectElement(){return Y.SlashEffects}getNoteX(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=s.x;switch(t){case tn.Left:break;case tn.Center:e+=s.width/2;break;case tn.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new ki;i.note=this.container.beat.notes[0],i.noteHeadBounds=new Is,i.noteHeadBounds.x=t+this.x+this.noteHeads.x,i.noteHeadBounds.y=s+this.y+this.noteHeads.y-this.noteHeads.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}getNoteY(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=this.y+s.y;switch(t){case en.Top:case en.TopWithStem:e-=s.height/2+2;break;case en.Center:break;case en.Bottom:case en.BottomWithStem:e+=s.height/2}return e}return 0}updateBeamingHelper(){this.noteHeads?this.noteHeads.updateBeamingHelper(this.container.x+this.x):this.deadSlapped?this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.container.beat,this.container.x+this.x+this.deadSlapped.x+this.width,this.container.x+this.x+this.deadSlapped.x):this.restGlyph&&this.restGlyph.updateBeamingHelper(this.container.x+this.x)}doLayout(){const e=this.renderer,t=e.getNoteLine(),s=e.getLineY(t);if(this.container.beat.deadSlapped){const e=new sh;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addEffect(e)}else if(!this.container.beat.isEmpty)if(this.container.beat.isRest){const e=new Tl(0,s,this.container.beat.duration);this.restGlyph=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper,this.addNormal(e),this.beamingHelper&&this.beamingHelper.applyRest(this.container.beat,0)}else{const e=this.container.beat.graceType!==b.None,t=new Sh(0,s,this.container.beat.duration,e,this.container.beat);this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper,this.addNormal(t)}if(this.container.beat.dots>0){this.addNormal(new ph(0,0,5));for(let t=0;t<this.container.beat.dots;t++)this.addEffect(new Jo(0,e.getLineY(e.getNoteLine())-e.getLineHeight(.5),1.5))}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.deadSlapped&&(this.centerX=this.deadSlapped.x+this.deadSlapped.width/2)}}class xl extends Oh{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._isOnlySlash=!t.staff.showTablature&&!t.staff.showStandardNotation,this.helpers.preferredBeamDirection=je.Up}get repeatsBarSubElement(){return c.SlashRepeats}get barNumberBarSubElement(){return c.SlashBarNumber}get barSeparatorBarSubElement(){return c.SlashBarSeparator}get staffLineBarSubElement(){return c.SlashStaffLine}get lineSpacing(){return Un.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return 1}get bottomGlyphOverflow(){return 0}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s,Y.SlashFlags,Y.SlashBeams),this.paintTuplets(e,t,s,Y.SlashTuplet)}doLayout(){super.doLayout();let e=!1;for(const t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}e&&this.registerOverflowTop(this.tupletSize)}getNoteLine(){return 0}getFlagTopY(e,t){const s=kr.Heights.get(I.NoteheadSlashWhiteHalf);return this.getLineY(0)-s/2}getFlagBottomY(e,t){const s=kr.Heights.get(I.NoteheadSlashWhiteHalf);return this.getLineY(0)-s/2}getBeamDirection(e){return je.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return Number.isNaN(s)&&(s=this.getLineY(0)),s}calculateBeamYWithDirection(e,t,s){return this.getLineY(0)-this.getFlagStemSize(e.shortestDuration)}getBarLineStart(e,t){const s=kr.Heights.get(I.NoteheadSlashWhiteHalf);return this.getLineY(0)-s/2}createLinePreBeatGlyphs(){this._isOnlySlash&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new ph(0,0,5));const e=this.bar.masterBar,t=new xh(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime));t.barSubElement=c.SlashTimeSignature,this.addPreBeatGlyph(t)}createVoiceGlyphs(e){for(const t of e.beats){const s=new kl(t,this.getVoiceContainer(e));s.preNotes=new On,s.onNotes=0===e.index?new Nl:new Hn,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){const n={stack:[],error:void 0,hasError:!1};try{jr(n,cn.beat(r,Y.SlashStem,e),!1);r.lineWidth=Un.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}catch(e){n.error=e,n.hasError=!0}finally{on(n)}}}xl.StaffId="slash";class vl extends Kr{get staffId(){return xl.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new xl(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showSlash}}class Pl extends qo{constructor(e,t,s=!1){super(e?e.beat:null,t?t.beat:null,s),this.startNote=e,this.endNote=t}shouldDrawBendSlur(){return this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&!!this.startNote.bendOrigin&&this.startNote.isTieOrigin}doLayout(){super.doLayout()}getBeamDirection(e,t){return je.Up}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,en.Top)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,tn.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,tn.Left):this.endNoteRenderer.getNoteX(this.endNote,tn.Center)}}class Cl extends Uh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=je.Up,this._forSlide=s}getTieHeight(e,t,s,i){return Math.log(s-e+1)*this.renderer.settings.notation.slurHeight}tryExpand(e,t,s,i){if(this._forSlide!==s)return!1;if(this.forEnd!==i)return!1;if(this.startNote.beat.id!==e.beat.id)return!1;if(this.endNote.beat.id!==t.beat.id)return!1;switch(this._direction){case je.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 je.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,s){const i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar),a=this.getBeamDirection(this.startBeat,i),r=`numbered.slur.${this.startNote.beat.id}.${this.endNote.beat.id}.${a}`,n=this.renderer;n.staff.getSharedLayoutData(r,!1)||(n.staff.setSharedLayoutData(r,!0),super.paint(e,t,s))}}class El extends vr{constructor(){super(...arguments),this._effectSlurs=[]}createTies(e){if(e.isVisible){if(e.isTieOrigin&&e.tieDestination.isVisible){const t=new Pl(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination){const t=new Pl(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){const t=new Pl(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){const t=new Cl(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){const t=new Cl(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}}}}class Fl extends wr{constructor(e,t,s,i,a){super(e,t),this._isGrace=i,this._number=s,this._beat=a}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,this._beat.isRest?cn.beat(s,Y.NumberedRests,this._beat):this._beat.notes.length>0?cn.note(s,H.NumberedNumber,this._beat.notes[0]):void 0,!1);const a=this.renderer.resources;s.font=this._isGrace?a.numberedNotationGraceFont:a.numberedNotationFont,s.textBaseline=R.Middle,s.textAlign=A.Left,s.fillText(this._number.toString(),e+this.x,t+this.y)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}doLayout(){const e=this._isGrace?Nr.GraceScale:1;this.width=Fl.NoteHeadWidth*e,this.height=Fl.NoteHeadHeight*e}}Fl.NoteHeadHeight=17,Fl.NoteHeadWidth=12;class Dl extends wr{constructor(e,t,s){super(e,t),this._beat=s}doLayout(){this.width=14+Dl.Padding,this.height=Al.BarSize}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.beat(s,Y.NumberedDuration,this._beat),!1);const a=Dl.Padding;s.fillRect(e+this.x,t+this.y,this.width-a,this.height)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}Dl.Padding=3;class Ml extends On{constructor(){super(...arguments),this.isNaturalizeAccidental=!1,this.accidental=tt.None}get effectElement(){return Y.NumberedEffects}doLayout(){if(!this.container.beat.isRest&&!this.container.beat.isEmpty){const e=new nh;if(e.renderer=this.renderer,this.container.beat.notes.length>0){const t=this.container.beat.notes[0],s=t?t.accidentalMode:B.Default,i=Ci.getNoteValue(t);let a=Ci.computeAccidental(this.renderer.bar.masterBar.keySignature,s,i,t.hasQuarterToneOffset);if(a===tt.Natural){a=this.renderer.bar.masterBar.keySignature+7<7?tt.Sharp:tt.Flat,this.isNaturalizeAccidental=!0}if(a!==tt.None){this.accidental=a;const s=this.renderer,i=cn.noteColor(s.resources,H.NumberedAccidentals,t),r=new Uo(0,s.getLineY(0),a,t.beat.graceType!==b.None?Nr.GraceScale*Nr.GraceScale:Nr.GraceScale);r.colorOverride=i,r.renderer=this.renderer,e.addGlyph(r),this.addNormal(e),this.addNormal(new ph(0,0,4))}}}super.doLayout()}}class Ll extends Hn{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.octaveDots=0}get effectElement(){return Y.NumberedEffects}getNoteX(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=s.x;switch(t){case tn.Left:break;case tn.Center:e+=s.width/2;break;case tn.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new ki;i.note=this.container.beat.notes[0],i.noteHeadBounds=new Is,i.noteHeadBounds.x=t+this.x+this.noteHeads.x,i.noteHeadBounds.y=s+this.y+this.noteHeads.y-this.noteHeads.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}getNoteY(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=this.y+s.y;switch(t){case en.Top:case en.TopWithStem:e-=s.height/2+2;break;case en.Center:break;case en.Bottom:case en.BottomWithStem:e+=s.height/2}return e}return 0}updateBeamingHelper(){if(this.beamingHelper){let e=null;this.noteHeads?e=this.noteHeads:this.deadSlapped&&(e=this.deadSlapped),e&&this.beamingHelper.registerBeatLineX("numbered",this.container.beat,this.container.x+this.x+e.x,this.container.x+this.x+e.x+e.width)}}doLayout(){const e=this.renderer;e.shortestDuration<this.container.beat.duration&&(e.shortestDuration=this.container.beat.duration);const t=e.getLineY(e.getNoteLine());if(!this.container.beat.isEmpty){let s="0";if(this.container.beat.notes.length>0){const t=this.renderer.bar.masterBar.keySignatureType,i=this.renderer.bar.masterBar.keySignature,a=i+7,r=(t===D.Minor?Ll.MinorKeySignatureOneValues:Ll.MajorKeySignatureOneValues)[a],n=this.container.beat.notes[0];if(n.isDead)s="X";else{const t=n.displayValue-r,o=t<0?(t%12+12)%12:t%12;let h=t<0?(Math.abs(t)+12)/12|0:t/12|0;t<0&&(h*=-1),this.octaveDots=h,e.registerOctave(h);let l=(ue.keySignatureIsSharp(i)||ue.keySignatureIsNatural(i)?Ci.FlatNoteSteps:Ci.SharpNoteSteps)[o]+1;Ci.AccidentalNotes[o]&&!this.container.preNotes.isNaturalizeAccidental&&(a<7?l++:l--),s=l.toString()}}if(this.container.beat.deadSlapped){const e=new sh;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addEffect(e)}else{const e=this.container.beat.graceType!==b.None,i=new Fl(0,t,s,e,this.container.beat);this.noteHeads=i,this.addNormal(i)}if(this.container.beat.dots>0&&this.container.beat.duration>=f.Quarter){this.addNormal(new ph(0,0,5));for(let t=0;t<this.container.beat.dots;t++){const t=new Jo(0,e.getLineY(0),1.5);t.renderer=this.renderer,this.addEffect(t)}}let i=0;switch(this.container.beat.duration){case f.QuadrupleWhole:i=16;break;case f.DoubleWhole:i=8;break;case f.Whole:i=4;break;case f.Half:i=2}let a=i;for(let e=0;e<this.container.beat.dots;e++)a=a/2|0,i+=a;for(let t=0;t<i-1;t++){const t=new Dl(0,e.getLineY(0),this.container.beat);t.renderer=this.renderer,this.addNormal(t)}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.deadSlapped&&(this.centerX=this.deadSlapped.x+this.deadSlapped.width/2)}}Ll.MajorKeySignatureOneValues=[59,66,61,68,63,58,65,60,67,62,69,64,71,66,61],Ll.MinorKeySignatureOneValues=[71,66,73,68,63,70,65,72,67,74,69,64,71,66,73];class Il extends wr{constructor(e,t,s,i){super(e,t),this._text="",this._accidental=tt.None,this._accidentalOffset=0,this._keySignature=s,this._keySignatureType=i}doLayout(){super.doLayout();const e="1 = ";let t="",s=tt.None;switch(this._keySignatureType){case D.Major:switch(this._keySignature){case F.Cb:t=" C",s=tt.Flat;break;case F.Gb:t=" G",s=tt.Flat;break;case F.Db:t=" D",s=tt.Flat;break;case F.Ab:t=" A",s=tt.Flat;break;case F.Eb:t=" E",s=tt.Flat;break;case F.Bb:t=" B",s=tt.Flat;break;case F.F:t="F";break;case F.C:t="C",s=tt.None;break;case F.G:t="G",s=tt.None;break;case F.D:t="D",s=tt.None;break;case F.A:t="A",s=tt.None;break;case F.E:t="E",s=tt.None;break;case F.B:t="B",s=tt.None;break;case F.FSharp:t=" F",s=tt.Sharp;break;case F.CSharp:t=" C",s=tt.Sharp}break;case D.Minor:switch(this._keySignature){case F.Cb:t=" a",s=tt.Flat;break;case F.Gb:t=" e",s=tt.Flat;break;case F.Db:t=" b",s=tt.Flat;break;case F.Ab:t="f",s=tt.None;break;case F.Eb:t="c",s=tt.None;break;case F.Bb:t="g",s=tt.None;break;case F.F:t="d";break;case F.C:t="a",s=tt.None;break;case F.G:t="e",s=tt.None;break;case F.D:t="b",s=tt.None;break;case F.A:t=" f",s=tt.Sharp;break;case F.E:t=" c",s=tt.Sharp;break;case F.B:t=" g",s=tt.Sharp;break;case F.FSharp:t=" d",s=tt.Sharp;break;case F.CSharp:t=" a",s=tt.Sharp}}this._text=e+t,this._accidental=s;const i=this.renderer.scoreRenderer.canvas,a=this.renderer.resources;i.font=a.numberedNotationFont,this._accidentalOffset=i.measureText(e).width,this.width=i.measureText(e+t).width}paint(e,t,s){const i={stack:[],error:void 0,hasError:!1};try{jr(i,cn.bar(s,c.NumberedKeySignature,this.renderer.bar),!1);const a=this.renderer.resources;s.font=a.numberedNotationFont,s.textBaseline=R.Middle,s.fillText(this._text,e+this.x,t+this.y),this._accidental!==tt.None&&s.fillMusicFontSymbol(e+this.x+this._accidentalOffset,t+this.y,.7,Uo.getMusicSymbol(this._accidental),!1)}catch(e){i.error=e,i.hasError=!0}finally{on(i)}}}class Al extends Oh{registerOctave(e){null===this.lowestOctave?(this.lowestOctave=e,this.highestOctave=e):(e<this.lowestOctave&&(this.lowestOctave=e),e>this.highestOctave&&(this.highestOctave=e))}get repeatsBarSubElement(){return c.NumberedRepeats}get barNumberBarSubElement(){return c.NumberedBarNumber}get barSeparatorBarSubElement(){return c.NumberedBarSeparator}get staffLineBarSubElement(){return c.NumberedStaffLine}constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.shortestDuration=f.QuadrupleWhole,this.lowestOctave=null,this.highestOctave=null,this._isOnlyNumbered=!t.staff.showSlash&&!t.staff.showTablature&&!t.staff.showStandardNotation}get lineSpacing(){return Un.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return 0}get bottomGlyphOverflow(){return 0}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s,Y.NumberedDuration,Y.NumberedDuration),this.paintTuplets(e,t,s,Y.NumberedTuplet,!0)}doLayout(){super.doLayout();let e=!1;for(const t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}if(e&&this.registerOverflowTop(this.tupletSize),!this.bar.isEmpty){const e=ue.getIndex(this.shortestDuration)-2;if(e>0){const t=(e-1)*Al.BarSpacing+Al.BarSize;let s=0;const i=this.lowestOctave;null!==i&&(s=Math.abs(i)*Al.DotSpacing+Al.DotSize),this.registerOverflowBottom(t+s)}const t=this.highestOctave;if(null!==t){const e=Math.abs(t)*Al.DotSpacing+Al.DotSize;this.registerOverflowTop(e)}}}paintFlag(e,t,s,i,a){this.paintBar(e,t,s,i,a)}paintBar(e,t,s,i,a){if(0===i.beats.length)return;const r=this.resources;for(let n=0,o=i.beats.length;n<o;n++){const o={stack:[],error:void 0,hasError:!1};try{const h=i.beats[n],l=(jr(o,cn.beat(s,a,h),!1),Al.BarSpacing),c=Al.BarSize,d=ue.getIndex(h.duration)-2,u=t+this.y,p=this.getBeatX(h,Qr.PreNotes)-this.beatGlyphsStart,g=this.calculateBeamY(i,p);for(let t=0;t<d;t++){let a=0,r=0,o=0;const d=u+t*l;n===i.beats.length-1?(a=p,r=this.getBeatX(h,Qr.PostNotes)-this.beatGlyphsStart):(a=p,r=this.getBeatX(i.beats[n+1],Qr.PreNotes)-this.beatGlyphsStart),o=d+g|0,Oh.paintSingleBar(s,e+this.x+a,o,e+this.x+r,o,c)}const m=this.getBeatContainer(h).onNotes;let f=m instanceof Ll?m.octaveDots:0,y=0,b=0;f>0?(y=u+this.getLineY(0)-r.numberedNotationFont.size/1.5,b=-1*Al.DotSpacing):f<0&&(y=u+g+d*l,b=Al.DotSpacing);const S=this.getBeatX(h,Qr.OnNotes)+4-this.beatGlyphsStart;f=Math.abs(f);for(let t=0;t<f;t++)s.fillCircle(e+this.x+S,y,Al.DotSize),y+=b}catch(e){o.error=e,o.hasError=!0}finally{on(o)}}}getNoteLine(){return 0}get tupletOffset(){return super.tupletOffset+this.resources.numberedNotationFont.size}getFlagTopY(e,t){const s=kr.Heights.get(I.NoteheadBlack);return this.getLineY(0)-s/2}getFlagBottomY(e,t){const s=kr.Heights.get(I.NoteheadBlack);return this.getLineY(0)-s/2}getBeamDirection(e){return je.Down}getTupletBeamDirection(e){return je.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return Number.isNaN(s)&&(s=this.getLineY(0)),s}calculateBeamYWithDirection(e,t,s){const i=this.resources.numberedNotationFont;return this.getLineY(0)+i.size}getBarLineStart(e,t){const s=kr.Heights.get(I.NoteheadBlack);return this.getLineY(0)-s/2}createPreBeatGlyphs(){this.wasFirstOfLine=this.isFirstOfLine,this.bar.masterBar.isRepeatStart&&this._isOnlyNumbered&&this.addPreBeatGlyph(new Mh(0,0,1.5,3)),this.createLinePreBeatGlyphs(),this.addPreBeatGlyph(new Rh(0,this.getLineHeight(-.25),this.bar.index+1))}createLinePreBeatGlyphs(){this.bar.previousBar&&this.bar.masterBar.keySignature===this.bar.previousBar.masterBar.keySignature||(this.createStartSpacing(),this.createKeySignatureGlyphs()),this._isOnlyNumbered&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createKeySignatureGlyphs(){this.addPreBeatGlyph(new Il(0,this.getLineY(0),this.bar.masterBar.keySignature,this.bar.masterBar.keySignatureType))}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new ph(0,0,5));const e=this.bar.masterBar,t=new xh(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime));t.barSubElement=c.NumberedTimeSignature,this.addPreBeatGlyph(t)}createPostBeatGlyphs(){this._isOnlyNumbered&&super.createPostBeatGlyphs()}createVoiceGlyphs(e){for(const t of e.beats){const s=new El(t,this.getVoiceContainer(e));s.preNotes=0===e.index?new Ml:new On,s.onNotes=0===e.index?new Ll:new Hn,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){}}Al.StaffId="numbered",Al.BarSpacing=Un.BeamSpacing+Un.BeamThickness,Al.BarSize=2,Al.DotSpacing=5,Al.DotSize=2;class Rl extends Kr{get staffId(){return xl.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new Al(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showNumbered}}class Ol extends jn{get notationElement(){return C.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return sn.SinglePreBeat}shouldCreateGlyph(e,t){const s=t.voice.bar.masterBar;return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&s.isFreeTime&&(0===s.index||s.isFreeTime!==s.previousMasterBar.isFreeTime)}createNewGlyph(e,t){return new Tn(0,0,"Free time",e.resources.effectFont,A.Left)}canExpand(e,t){return!0}}class Hl extends Br{constructor(){super(0,0)}doLayout(){super.doLayout(),this.height=kr.Heights.get(I.KeyboardPedalPed)}paint(e,t,s){const i=this.renderer,a=t+this.y,r=this.height,n=i.bar.sustainPedals,o=kr.Widths.get(I.KeyboardPedalPed),h=kr.Widths.get(I.KeyboardPedalUp);let c=0;for(;c<n.length;){let t=n[c];for(;null!=t;){const i=e+this.renderer.getRatioPositionX(t.ratioPosition);let d=0;if(t.pedalType===l.Down?(s.fillMusicFontSymbol(i,a+r,1,I.KeyboardPedalPed,!0),d=o/2+Hl.TextLinePadding):t.pedalType===l.Up&&(s.fillMusicFontSymbol(i,a+r,1,I.KeyboardPedalUp,!0),d=h/2+Hl.StarLinePadding),t.nextPedalMarker)if(t.nextPedalMarker.bar===t.bar){let n=e+this.renderer.getRatioPositionX(t.nextPedalMarker.ratioPosition);switch(t.nextPedalMarker.pedalType){case l.Down:n-=o/2;break;case l.Hold:break;case l.Up:n-=h/2}const c=i+d;n>c&&s.fillRect(c,a+r-1,n-c,1)}else{const t=e+this.x+this.width,n=i+d;s.fillRect(n,a+r-1,t-n,1)}if(0===c&&t.previousPedalMarker){const t=e+this.x,n=i-d;s.fillRect(t,a+r-1,n-t,1)}c++,null!=t.nextPedalMarker&&t.nextPedalMarker.bar!==t.bar?(t=null,c=n.length):t=t.nextPedalMarker}}}}Hl.TextLinePadding=3,Hl.StarLinePadding=3;class Wl extends jn{get notationElement(){return C.EffectSustainPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return sn.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&t.voice.bar.sustainPedals.length>0}createNewGlyph(e,t){return new Hl}canExpand(e,t){return!0}}class Vl extends jn{constructor(e,t){super(),this._type=e,this._shouldCreate=t}get notationElement(){return C.EffectGolpe}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return sn.SingleOnBeat}shouldCreateGlyph(e,t){const s=this._shouldCreate;return t.golpe===this._type&&(!s||s(e,t))}createNewGlyph(e,t){return new yh(0,0,!0)}canExpand(e,t){return!1}}class Gl extends Tr{constructor(e){super(0,0,1,Gl.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case U.Open:return I.GuitarOpenPedal;case U.Closed:return I.GuitarClosePedal}return I.None}paint(e,t,s){super.paint(e,t+this.height,s)}}class Ul extends jn{get notationElement(){return C.EffectWahPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return sn.SingleOnBeat}shouldCreateGlyph(e,t){return t.wahPedal!==U.None}createNewGlyph(e,t){return new Gl(t.wahPedal)}canExpand(e,t){return!1}}class zl extends jn{get notationElement(){return C.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isBarre}get sizingMode(){return sn.GroupedOnBeat}createNewGlyph(e,t){let s="";switch(t.barreShape){case z.None:case z.Full:break;case z.Half:s+="1/2"}return s+=`B ${zl.toRoman(t.barreFret)}`,new po(s,!1)}static toRoman(e){let t="";if(e>0)for(const[s,i]of zl.RomanLetters){const a=Math.floor(e/i);e-=a*i,t+=s.repeat(a)}return t}canExpand(e,t){return e.barreFret===t.barreFret&&e.barreShape===t.barreShape}}zl.RomanLetters=new Map([["L",50],["XL",40],["X",10],["IX",9],["V",5],["IV",4],["I",1]]);class Xl extends Tr{constructor(e){super(0,0,1,Xl.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case O.InvertedTurn:return I.OrnamentTurnInverted;case O.Turn:return I.OrnamentTurn;case O.UpperMordent:return I.OrnamentShortTrill;case O.LowerMordent:return I.OrnamentMordent}return I.None}paint(e,t,s){super.paint(e,t+this.height-4,s)}}class Jl extends jn{get notationElement(){return C.EffectNoteOrnament}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return sn.SingleOnBeat}shouldCreateGlyph(e,t){return t.notes.some((e=>e.ornament!==O.None))}createNewGlyph(e,t){return new Xl(t.notes.find((e=>e.ornament!==O.None)).ornament)}canExpand(e,t){return!1}}class Yl extends jn{get notationElement(){return C.EffectRasgueado}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.hasRasgueado}get sizingMode(){return sn.GroupedOnBeat}createNewGlyph(e,t){return new po("rasg.")}canExpand(e,t){return!0}}class $l extends wr{constructor(e){super(0,0),this._symbols=e}doLayout(){this.height=27}paint(e,t,s){s.fillMusicFontSymbols(e+this.x,t+this.y+this.height,.8,this._symbols,!0)}}class ql extends wr{constructor(e){super(0,0),this._text=e}doLayout(){this.height=1.5*this.renderer.resources.directionsFont.size}paint(e,t,s){const i=s.font,a=s.textBaseline,r=s.textAlign;s.font=this.renderer.resources.directionsFont,s.textBaseline=R.Middle,s.textAlign=A.Right,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=i,s.textBaseline=a,s.textAlign=r}}class Kl extends Br{constructor(e,t,s){super(e,t),this._barBeginGlyphs=[],this._barEndGlyphs=[],this._directions=s}doLayout(){const e=this._directions;e.has(qe.TargetSegnoSegno)&&this._barBeginGlyphs.push(new $l([I.Segno,I.Segno])),e.has(qe.TargetSegno)&&this._barBeginGlyphs.push(new $l([I.Segno])),e.has(qe.TargetDoubleCoda)&&this._barBeginGlyphs.push(new $l([I.Coda,I.Coda])),e.has(qe.TargetCoda)&&this._barBeginGlyphs.push(new $l([I.Coda])),e.has(qe.TargetFine)&&this._barEndGlyphs.push(new ql("Fine")),e.has(qe.JumpDaDoubleCoda)&&this._barEndGlyphs.push(new ql("To Double Coda")),e.has(qe.JumpDaCoda)&&this._barEndGlyphs.push(new ql("To Coda")),e.has(qe.JumpDalSegnoSegno)&&this._barEndGlyphs.push(new ql("D.S.S.")),e.has(qe.JumpDalSegnoSegnoAlCoda)&&this._barEndGlyphs.push(new ql("D.S.S. al Coda")),e.has(qe.JumpDalSegnoSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new ql("D.S.S. al Double Coda")),e.has(qe.JumpDalSegnoSegnoAlFine)&&this._barEndGlyphs.push(new ql("D.S.S. al Fine")),e.has(qe.JumpDalSegno)&&this._barEndGlyphs.push(new ql("D.S.")),e.has(qe.JumpDalSegnoAlCoda)&&this._barEndGlyphs.push(new ql("D.S. al Coda")),e.has(qe.JumpDalSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new ql("D.S. al Double Coda")),e.has(qe.JumpDalSegnoAlFine)&&this._barEndGlyphs.push(new ql("D.S. al Fine")),e.has(qe.JumpDaCapo)&&this._barEndGlyphs.push(new ql("D.C.")),e.has(qe.JumpDaCapoAlCoda)&&this._barEndGlyphs.push(new ql("D.C. al Coda")),e.has(qe.JumpDaCapoAlDoubleCoda)&&this._barEndGlyphs.push(new ql("D.C. al Double Coda")),e.has(qe.JumpDaCapoAlFine)&&this._barEndGlyphs.push(new ql("D.C. al Fine"));const t=this.doSideLayout(this._barBeginGlyphs),s=this.doSideLayout(this._barEndGlyphs);this.height=Math.max(t,s)}doSideLayout(e){let t=0;for(const s of e)s.y=t,s.renderer=this.renderer,s.doLayout(),t+=s.height+3;return t}paint(e,t,s){for(const i of this._barBeginGlyphs)i.paint(e+this.x,t+this.y,s);for(const i of this._barEndGlyphs)i.paint(e+this.x+this.width,t+this.y,s)}}class jl extends jn{get notationElement(){return C.EffectDirections}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return sn.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&null!==t.voice.bar.masterBar.directions&&t.voice.bar.masterBar.directions.size>0}createNewGlyph(e,t){return new Kl(0,0,t.voice.bar.masterBar.directions)}canExpand(e,t){return!0}}class Ql extends Br{constructor(e){super(0,0),this._text="",this._textWidth=0,this._textHeight=0,this._timer=e}doLayout(){const e=this._timer/6e4|0,t=(this._timer-6e4*e)/1e3|0;this._text=`${e}:${t.toString().padStart(2,"0")}`;const s=this.renderer.scoreRenderer.canvas;s.font=this.renderer.resources.timerFont;const i=s.measureText(this._text);this._textHeight=s.font.size+2*Ql.PaddingY,this._textWidth=i.width+2*Ql.PaddingX,this.height=this._textHeight+2*Ql.MarginY}paint(e,t,s){const i=this._textWidth/2|0;s.strokeRect(e+this.x-i,t+this.y+Ql.MarginY,this._textWidth,this._textHeight);const a=s.font,r=s.textBaseline,n=s.textAlign;s.font=this.renderer.resources.timerFont,s.textBaseline=R.Middle,s.textAlign=A.Center,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=a,s.textBaseline=r,s.textAlign=n}}Ql.PaddingX=2,Ql.PaddingY=2,Ql.MarginY=2;class Zl extends jn{get notationElement(){return C.EffectBeatTimer}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return sn.SingleOnBeat}shouldCreateGlyph(e,t){return t.showTimer}createNewGlyph(e,t){return new Ql(t.timer??0)}canExpand(e,t){return!0}}class ec{static print(e){e(`alphaTab ${ec.version}`),e(`commit: ${ec.commit}`),e(`build date: ${ec.date}`)}}ec.version="1.5.0-alpha.1376",ec.date="2025-04-15T02:03:41.099Z",ec.commit="345fc017a40d2cc22f57fa857af6f2dd0ef13aa4";class tc{constructor(e,t){this.vertical=e,this.createLayout=t}}class sc{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class ic{static createStyleElement(e,t){let s=e.getElementById("alphaTabStyle");if(!s){if(!t)return void he.error("AlphaTab","Font directory could not be detected, cannot create style element");s=e.createElement("style"),s.id="alphaTabStyle";const i=`\n @font-face {\n font-display: block;\n font-family: 'alphaTab';\n src: url('${t}Bravura.eot');\n src: url('${t}Bravura.eot?#iefix') format('embedded-opentype')\n , url('${t}Bravura.woff') format('woff')\n , url('${t}Bravura.otf') format('opentype')\n , url('${t}Bravura.svg#Bravura') format('svg');\n font-weight: normal;\n font-style: normal;\n }\n .at-surface * {\n cursor: default;\n vertical-align: top;\n overflow: visible;\n }\n .at-surface-svg text {\n dominant-baseline: central;\n white-space:pre;\n }\n .at {\n font-family: 'alphaTab';\n speak: none;\n font-style: normal;\n font-weight: normal;\n font-variant: normal;\n text-transform: none;\n line-height: 1;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n font-size: ${ic.MusicFontSize}px;\n overflow: visible !important;\n }`;s.innerHTML=i,e.getElementsByTagName("head").item(0).appendChild(s),ic.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===ic._globalThis){try{ic._globalThis=globalThis}catch(e){}void 0===ic._globalThis&&(ic._globalThis=self),void 0===ic._globalThis&&(ic._globalThis=global),void 0===ic._globalThis&&(ic._globalThis=window),void 0===ic._globalThis&&(ic._globalThis=Function("return this")())}return ic._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in ic.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in ic.globalThis}static throttle(e,t){let s=0;return()=>{ic.globalThis.clearTimeout(s),s=ic.globalThis.setTimeout(e,t)}}static detectScriptFile(){if(!ic.isRunningInWorker&&ic.globalThis.ALPHATAB_ROOT){let e=ic.globalThis.ALPHATAB_ROOT;return e=ic.ensureFullUrl(e),e=ic.appendScriptName(e),e}try{const e=import.meta.url;if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in ic.globalThis&&document.currentScript?document.currentScript.src:null}static ensureFullUrl(e){if(!e)return"";if(!e.startsWith("http")&&!e.startsWith("https")&&!e.startsWith("file")){let t="";const s=ic.globalThis.location;if(t+=s.protocol?.toString(),t+="//"?.toString(),s.hostname&&(t+=s.hostname?.toString()),s.port&&(t+=":"?.toString(),t+=s.port?.toString()),!e.startsWith("/")){const e=s.pathname.split("/").slice(0,-1).join("/");e.length>0&&(e.startsWith("/")||(t+="/"?.toString()),t+=e?.toString())}return e.startsWith("/")||(t+="/"?.toString()),t+=e?.toString(),t}return e}static appendScriptName(e){return e&&!e.endsWith(".js")&&(e.endsWith("/")||(e+="/"),e+="alphaTab.js"),e}static detectFontDirectory(){if(!ic.isRunningInWorker&&ic.globalThis.ALPHATAB_FONT)return ic.ensureFullUrl(ic.globalThis.ALPHATAB_FONT);const e=ic.scriptFile;if(e){const t=e.lastIndexOf(String.fromCharCode(47));if(t>=0)return`${e.substr(0,t)}/font/`}return null}static registerJQueryPlugin(){if(!ic.isRunningInWorker&&ic.globalThis&&"jQuery"in ic.globalThis){const e=ic.globalThis.jQuery,t=new qr;e.fn.alphaTab=function(e){const s=Array.prototype.slice.call(arguments,1);return 1===this.length?t.exec(this[0],e,s):this.each(((i,a)=>{t.exec(a,e,s)}))},e.alphaTab={restore:qr.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&ic.renderEngines.has(e)?ic.renderEngines.get(e):ic.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&ic.layoutEngines.has(t)?ic.layoutEngines.get(t):ic.layoutEngines.get(e.Page)}static buildImporters(){return[new Ds,new fi,new di,new Mi,new bl,new xt]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new sc(!0,(()=>new ze))),e.set("default",e.get("svg")),e.set("skia",new sc(!1,(()=>new wl))),ic.createPlatformSpecificRenderEngines(e),e}static enableAlphaSkia(e,t){wl.enable(e,t)}static registerAlphaSkiaCustomFont(e,t){return wl.registerFont(e,t)}static createPlatformSpecificRenderEngines(e){e.set("html5",new sc(!1,(()=>new nr)))}static createDefaultRenderers(){return[new qn(ic.StaffIdBeforeSlashAlways,[new Fo,new Ao,new bo,new jl,new Qn,new Ol,new Do,new Zl,new eo]),new vl,new qn(ic.StaffIdBeforeScoreAlways,[new lo,new zl,new Jl,new Yl,new Ul]),new qn(ic.StaffIdBeforeScoreHideable,[new Ro,new Lo,new _o(!0),new Oo,new xo,new Ho,new Po(!1),new il,new Vl(V.Finger)],((e,t)=>t.showStandardNotation)),new Vh,new qn(ic.StaffIdBeforeNumberedAlways,[new io,new _o(!1),new ro,new Vl(V.Thumb,((e,t)=>t.voice.bar.staff.showStandardNotation)),new Wl]),new Rl,new qn(ic.StaffIdBeforeTabAlways,[new yo]),new qn(ic.StaffIdBeforeTabHideable,[new Lo,new Oo,new xo,new Ho,new Po(!0),new Co,new oo,new go(w.Natural),new go(w.Artificial),new go(w.Pinch),new go(w.Tap),new go(w.Semi),new go(w.Feedback),new mo,new Zn,new co,new wo,new To,new Bo,new il,new Vl(V.Finger,((e,t)=>!t.voice.bar.staff.showStandardNotation))],((e,t)=>t.showTablature)),new tl,new qn(ic.StaffIdBeforeEndAlways,[new Vl(V.Thumb,((e,t)=>!t.voice.bar.staff.showStandardNotation))])]}static createDefaultStaveProfiles(){const e=new Map,s=ic.createDefaultRenderers();e.set(t.Default,s),e.set(t.ScoreTab,s);const i=new Set([ic.StaffIdBeforeSlashAlways,ic.StaffIdBeforeScoreAlways,ic.StaffIdBeforeNumberedAlways,ic.StaffIdBeforeTabAlways,Wh.StaffId,ic.StaffIdBeforeEndAlways]);e.set(t.Score,s.filter((e=>i.has(e.staffId))));const a=new Set([ic.StaffIdBeforeSlashAlways,ic.StaffIdBeforeScoreAlways,ic.StaffIdBeforeNumberedAlways,ic.StaffIdBeforeTabAlways,el.StaffId,ic.StaffIdBeforeEndAlways]);return e.set(t.Tab,ic.createDefaultRenderers().filter((e=>{if(e instanceof tl){const t=e;t.showTimeSignature=!0,t.showRests=!0,t.showTiedNotes=!0}return a.has(e.staffId)}))),e.set(t.TabMixed,ic.createDefaultRenderers().filter((e=>{if(e instanceof tl){const t=e;t.showTimeSignature=!1,t.showRests=!1,t.showTiedNotes=!1}return a.has(e.staffId)}))),e}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.Page,new tc(!0,(e=>new Go(e)))),t.set(e.Horizontal,new tc(!1,(e=>new Vo(e)))),t}static initializeMain(e,t){ic.isRunningInWorker||ic.isRunningInAudioWorklet||(ic.webPlatform!==Me.Browser&&ic.webPlatform!==Me.BrowserModule||(ic.registerJQueryPlugin(),ic.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in ic.globalThis||(ic.globalThis.ResizeObserver=Sl),"IntersectionObserver"in ic.globalThis||(ic.globalThis.IntersectionObserver=_l),"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)})),ic.createWebWorker=e,ic.createAudioWorklet=t)}static get alphaTabWorker(){return ic.globalThis.Worker}static get alphaTabUrl(){return ic.globalThis.URL}static initializeWorker(){if(!ic.isRunningInWorker)throw new Le(Ee.General,"Not running in worker, cannot run worker initialization");rr.init(),ar.init(),ic.createWebWorker=e=>{throw new Le(Ee.General,"Nested workers are not supported")}}static initializeAudioWorklet(){if(!ic.isRunningInAudioWorklet)throw new Le(Ee.General,"Not running in audio worklet, cannot run worklet initialization");zr.init()}static detectWebPack(){try{if("function"==typeof __webpack_require__)return!0}catch(e){}return!1}static detectVite(){try{if("string"==typeof __BASE__)return!0}catch(e){}return!1}static detectWebPlatform(){try{if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return Me.NodeJs}catch(e){}try{const e=import.meta.url;if(e&&"string"==typeof e&&!e.startsWith("file://"))return Me.BrowserModule}catch(e){}return Me.Browser}static printEnvironmentInfo(e=!0){const t=e?e=>{he.log.debug("VersionInfo",e)}:e=>{he.debug("VersionInfo",e)};ec.print(t),t(`High DPI: ${ic.HighDpiFactor}`),ic.printPlatformInfo(t)}static printPlatformInfo(e){e(`Browser: ${navigator.userAgent}`),e(`Platform: ${Me[ic.webPlatform]}`),e(`WebPack: ${ic.isWebPackBundled}`),e(`Vite: ${ic.isViteBundled}`),ic.webPlatform!==Me.NodeJs&&(e(`Window Size: ${window.outerWidth}x${window.outerHeight}`),e(`Screen Size: ${window.screen.width}x${window.screen.height}`))}}ic.StaffIdBeforeSlashAlways="before-slash-always",ic.StaffIdBeforeScoreAlways="before-score-always",ic.StaffIdBeforeScoreHideable="before-score-hideable",ic.StaffIdBeforeNumberedAlways="before-numbered-always",ic.StaffIdBeforeTabAlways="before-tab-always",ic.StaffIdBeforeTabHideable="before-tab-hideable",ic.StaffIdBeforeEndAlways="before-end-always",ic.MusicFontSize=34,ic.HighDpiFactor=1,ic._globalThis=void 0,ic.webPlatform=ic.detectWebPlatform(),ic.isWebPackBundled=ic.detectWebPack(),ic.isViteBundled=ic.detectVite(),ic.scriptFile=ic.detectScriptFile(),ic.fontDirectory=ic.detectFontDirectory(),ic.bravuraFontChecker=new Ar(["alphaTab"]),ic.renderEngines=ic.createDefaultRenderEngines(),ic.layoutEngines=ic.createDefaultLayoutEngines(),ic.staveProfiles=ic.createDefaultStaveProfiles();class ac{constructor(){this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=E.Info,this.useWorkers=!0,this.includeNoteBounds=!1,this.scriptFile=ic.scriptFile,this.fontDirectory=ic.fontDirectory}}const rc=Object.freeze(Object.defineProperty({__proto__:null,ScoreImporter:ct,ScoreLoader:Mr,UnsupportedFormatError:dt},Symbol.toStringTag,{value:"Module"})),nc=Object.freeze(Object.defineProperty({__proto__:null,ByteBuffer:Bt,IOHelper:wt},Symbol.toStringTag,{value:"Module"}));class oc{init(e,t){this.data=e,this.settings=t}export(e,t=null){const s=Bt.withCapacity(1024);return this.init(s,t??new as),this.writeScore(e),s.toArray()}}var hc;!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"}(hc||(hc={}));class lc{constructor(e,t,s=null){if(this.icon=hc.Piano,this.icon=e,this.instrumentSetName=t,s)this.instrumentSetType=s;else{const e=t.split(" ");e[0]=e[0].substr(0,1).toLowerCase()+e[0].substr(1),this.instrumentSetType=e.join("")}}}class cc{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new zs;return this._rhythmIdLookup=new Map,this.writeDom(t,e),t.toFormattedString("",!0)}writeDom(e,t){const s=e.addElement("GPIF");s.addElement("GPVersion").innerText="7";const i=s.addElement("GPRevision");i.innerText="7",i.attributes.set("required","12021"),i.attributes.set("recommended","12023"),i.innerText="12025",s.addElement("Encoding").addElement("EncodingDescription").innerText="GP7",this.writeScoreNode(s,t),this.writeMasterTrackNode(s,t),this.writeAudioTracksNode(s,t),this.writeTracksNode(s,t),this.writeMasterBarsNode(s,t);const a=s.addElement("Bars"),r=s.addElement("Voices"),n=s.addElement("Beats"),o=s.addElement("Notes"),h=s.addElement("Rhythms");for(const e of t.tracks)for(const t of e.staves)for(const e of t.bars){this.writeBarNode(a,e);for(const t of e.voices){this.writeVoiceNode(r,t);for(const e of t.beats){this.writeBeatNode(n,e,h);for(const t of e.notes)this.writeNoteNode(o,t)}}}}writeNoteNode(e,t){const s=e.addElement("Note");s.attributes.set("id",t.id.toString()),this.writeNoteProperties(s,t),t.isGhost&&(s.addElement("AntiAccent").innerText="normal"),t.isLetRing&&s.addElement("LetRing"),t.isTrill&&(s.addElement("Trill").innerText=t.trillValue.toString());let i=0;switch(t.isStaccato&&(i|=1),t.accentuated){case S.Normal:i|=8;break;case S.Heavy:i|=4;break;case S.Tenuto:i|=16}if(i>0&&(s.addElement("Accent").innerText=i.toString()),t.isTieOrigin||t.isTieDestination){const e=s.addElement("Tie");e.attributes.set("origin",t.isTieOrigin?"true":"false"),e.attributes.set("destination",t.isTieDestination?"true":"false")}switch(t.vibrato){case N.Slight:s.addElement("Vibrato").innerText="Slight";break;case N.Wide:s.addElement("Vibrato").innerText="Wide"}if(t.isFingering){switch(t.leftHandFinger){case _.Thumb:s.addElement("LeftFingering").innerText="P";break;case _.IndexFinger:s.addElement("LeftFingering").innerText="I";break;case _.MiddleFinger:s.addElement("LeftFingering").innerText="M";break;case _.AnnularFinger:s.addElement("LeftFingering").innerText="A";break;case _.LittleFinger:s.addElement("LeftFingering").innerText="C"}switch(t.rightHandFinger){case _.Thumb:s.addElement("RightFingering").innerText="P";break;case _.IndexFinger:s.addElement("RightFingering").innerText="I";break;case _.MiddleFinger:s.addElement("RightFingering").innerText="M";break;case _.AnnularFinger:s.addElement("RightFingering").innerText="A";break;case _.LittleFinger:s.addElement("RightFingering").innerText="C"}}t.percussionArticulation>=0?s.addElement("InstrumentArticulation").innerText=t.percussionArticulation.toString():s.addElement("InstrumentArticulation").innerText="0",t.ornament!==O.None&&(s.addElement("Ornament").innerText=O[t.ornament])}writeNoteProperties(e,t){const s=e.addElement("Properties");if(this.writeConcertPitch(s,t),this.writeTransposedPitch(s,t),t.isStringed&&(this.writeSimplePropertyNode(s,"String","String",(t.string-1).toString()),this.writeSimplePropertyNode(s,"Fret","Fret",t.fret.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString()),t.showStringNumber&&this.writeSimplePropertyNode(s,"ShowStringNumber","Enable",null)),t.isPiano&&(this.writeSimplePropertyNode(s,"Octave","Number",t.octave.toString()),this.writeSimplePropertyNode(s,"Tone","Step",t.tone.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString())),t.beat.tap&&this.writeSimplePropertyNode(s,"Tapped","Enable",null),t.harmonicType!==w.None){switch(t.harmonicType){case w.Natural:this.writeSimplePropertyNode(s,"HarmonicType","HType","Natural");break;case w.Artificial:this.writeSimplePropertyNode(s,"HarmonicType","HType","Artificial");break;case w.Pinch:this.writeSimplePropertyNode(s,"HarmonicType","HType","Pinch");break;case w.Tap:this.writeSimplePropertyNode(s,"HarmonicType","HType","Tap");break;case w.Semi:this.writeSimplePropertyNode(s,"HarmonicType","HType","Semi");break;case w.Feedback:this.writeSimplePropertyNode(s,"HarmonicType","HType","Feedback")}0!==t.harmonicValue&&this.writeSimplePropertyNode(s,"HarmonicFret","HFret",t.harmonicValue.toString())}t.isDead&&this.writeSimplePropertyNode(s,"Muted","Enable",null),t.isPalmMute&&this.writeSimplePropertyNode(s,"PalmMuted","Enable",null),t.hasBend&&this.writeBend(s,t),t.isHammerPullOrigin&&this.writeSimplePropertyNode(s,"HopoOrigin","Enable",null),t.isHammerPullDestination&&this.writeSimplePropertyNode(s,"HopoDestination","Enable",null),t.isLeftHandTapped&&this.writeSimplePropertyNode(s,"LeftHandTapped","Enable",null);let i=0;switch(t.slideInType){case k.IntoFromAbove:i|=32;break;case k.IntoFromBelow:i|=16}switch(t.slideOutType){case T.Shift:i|=1;break;case T.Legato:i|=2;break;case T.OutDown:i|=4;break;case T.OutUp:i|=8;break;case T.PickSlideDown:i|=64;break;case T.PickSlideUp:i|=128}i>0&&this.writeSimplePropertyNode(s,"Slide","Flags",i.toString())}writeTransposedPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"TransposedPitch",t.displayValueWithoutBend,t.accidentalMode)}writeConcertPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"ConcertPitch",t.realValueWithoutHarmonic,t.accidentalMode)}writePitchForValue(e,t,s,i){let a=0,r=0,n="",o="";const h=()=>{a=s%12,r=s/12|0,n=ft.defaultSteps[a],o=ft.defaultAccidentals[a]};switch(h(),i){case B.Default:break;case B.ForceNone:case B.ForceNatural:o="";break;case B.ForceSharp:o="#";break;case B.ForceDoubleSharp:"#"===o&&(s-=2,h()),o="x";break;case B.ForceFlat:"#"===o&&(s+=1,h()),o="b";break;case B.ForceDoubleFlat:"#"===o&&(s+=2,h()),o="bb"}this.writePitch(e,t,n,r.toString(),o)}writePitch(e,t,s,i,a){const r=e.addElement("Property");r.attributes.set("name",t);const n=r.addElement("Pitch");n.addElement("Step").innerText=s,n.addElement("Accidental").innerText=a,n.addElement("Octave").innerText=i}writeBend(e,t){t.hasBend&&t.bendPoints.length<=4&&this.writeStandardBend(e,t.bendPoints)}writeStandardBend(e,t){this.writeSimplePropertyNode(e,"Bended","Enable",null);const s=t[0],i=t[t.length-1];let a,r;switch(t.length){case 4:a=t[1],r=t[2];break;case 3:a=t[1],r=t[1];break;default:a=new ae((s.offset+i.offset)/2,(s.value+i.value)/2),r=a}this.writeSimplePropertyNode(e,"BendDestinationOffset","Float",this.toBendOffset(i.offset).toString()),this.writeSimplePropertyNode(e,"BendDestinationValue","Float",this.toBendValue(i.value).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset1","Float",this.toBendOffset(a.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset2","Float",this.toBendOffset(r.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleValue","Float",this.toBendValue(a.value).toString()),this.writeSimplePropertyNode(e,"BendOriginOffset","Float",this.toBendOffset(s.offset).toString()),this.writeSimplePropertyNode(e,"BendOriginValue","Float",this.toBendValue(s.value).toString())}toBendValue(e){return 25*e}toBendOffset(e){return e/ae.MaxPosition*100}writeBeatNode(e,t,s){const i=e.addElement("Beat");if(i.attributes.set("id",t.id.toString()),i.addElement("Dynamic").innerText=y[t.dynamics],t.fade!==G.None&&(i.addElement("Fadding").innerText=G[t.fade]),t.isTremolo)switch(t.tremoloSpeed){case f.Eighth:i.addElement("Tremolo").innerText="1/2";break;case f.Sixteenth:i.addElement("Tremolo").innerText="1/4";break;case f.ThirtySecond:i.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&i.addElement("Chord").setCData(t.chordId),t.crescendo!==m.None&&(i.addElement("Hairpin").innerText=m[t.crescendo]),t.brushType){case g.ArpeggioUp:i.addElement("Arpeggio").innerText="Up";break;case g.ArpeggioDown:i.addElement("Arpeggio").innerText="Down"}switch(t.text&&i.addElement("FreeText").setCData(t.text),t.graceType){case b.OnBeat:case b.BeforeBeat:i.addElement("GraceNotes").innerText=b[t.graceType]}if(t.ottava!==o.Regular&&(i.addElement("Ottavia").innerText=o[t.ottava].substr(1)),t.hasWhammyBar&&this.writeWhammyNode(i,t),t.isLegatoOrigin||t.isLegatoDestination){const e=i.addElement("Legato");e.attributes.set("origin",t.isLegatoOrigin?"true":"false"),e.attributes.set("destination",t.isLegatoDestination?"true":"false")}if(this.writeRhythm(i,t,s),null!==t.preferredBeamDirection)switch(t.preferredBeamDirection){case je.Up:i.addElement("TransposedPitchStemOrientation").innerText="Upward",i.addElement("UserTransposedPitchStemOrientation").innerText="Upward";break;case je.Down:i.addElement("TransposedPitchStemOrientation").innerText="Downward",i.addElement("UserTransposedPitchStemOrientation").innerText="Downward"}i.addElement("ConcertPitchStemOrientation").innerText="Undefined",t.slashed&&i.addElement("Slashed"),t.deadSlapped&&i.addElement("DeadSlapped"),t.notes.length>0&&(i.addElement("Notes").innerText=t.notes.map((e=>e.id)).join(" ")),t.golpe!==V.None&&(i.addElement("Golpe").innerText=V[t.golpe]),t.wahPedal!==U.None&&(i.addElement("Wah").innerText=U[t.wahPedal]),t.showTimer&&(i.addElement("Timer").innerText=(t.timer??0).toString()),this.writeBeatProperties(i,t),this.writeBeatXProperties(i,t),t.lyrics&&t.lyrics.length>0&&this.writeBeatLyrics(i,t.lyrics)}writeBeatLyrics(e,t){const s=e.addElement("Lyrics");for(const e of t){s.addElement("Line").setCData(e)}}writeBeatXProperties(e,t){const s=e.addElement("XProperties");switch(t.brushDuration>0&&this.writeSimpleXPropertyNode(s,"687935489","Int",t.brushDuration.toString()),t.beamingMode){case J.ForceSplitToNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","2");break;case J.ForceMergeWithNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","1");break;case J.ForceSplitOnSecondaryToNext:this.writeSimpleXPropertyNode(s,"1124204552","Int","1")}}writeBeatProperties(e,t){const s=e.addElement("Properties");switch(t.brushType){case g.BrushUp:this.writeSimplePropertyNode(s,"Brush","Direction","Up");break;case g.BrushDown:this.writeSimplePropertyNode(s,"Brush","Direction","Down")}switch(t.pickStroke){case L.Up:this.writeSimplePropertyNode(s,"PickStroke","Direction","Up");break;case L.Down:this.writeSimplePropertyNode(s,"PickStroke","Direction","Down")}switch(t.slap&&this.writeSimplePropertyNode(s,"Slapped","Enable",null),t.pop&&this.writeSimplePropertyNode(s,"Popped","Enable",null),t.vibrato){case N.Wide:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Wide");break;case N.Slight:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Slight")}if(t.isBarre)switch(this.writeSimplePropertyNode(s,"BarreFret","Fret",t.barreFret.toString()),t.barreShape){case z.Full:this.writeSimplePropertyNode(s,"BarreString","String","0");break;case z.Half:this.writeSimplePropertyNode(s,"BarreString","String","1")}if(t.rasgueado!==X.None){let e="";switch(t.rasgueado){case X.Ii:e="ii_1";break;case X.Mi:e="mi_1";break;case X.MiiTriplet:e="mii_1";break;case X.MiiAnapaest:e="mii_2";break;case X.PmpTriplet:e="pmp_1";break;case X.PmpAnapaest:e="pmp_2";break;case X.PeiTriplet:e="pei_1";break;case X.PeiAnapaest:e="pei_2";break;case X.PaiTriplet:e="pai_1";break;case X.PaiAnapaest:e="pai_2";break;case X.AmiTriplet:e="ami_1";break;case X.AmiAnapaest:e="ami_2";break;case X.Ppp:e="ppp_1";break;case X.Amii:e="amii_1";break;case X.Amip:e="amip_1";break;case X.Eami:e="eami_1";break;case X.Eamii:e="eamii_1";break;case X.Peami:e="peami_1"}this.writeSimplePropertyNode(s,"Rasgueado","Rasgueado",e)}}writeRhythm(e,t,s){const i=`${t.duration}_${t.dots}_${t.tupletNumerator}_${t.tupletDenominator}';`;let a;if(this._rhythmIdLookup.has(i))a=this._rhythmIdLookup.get(i);else{a=this._rhythmIdLookup.size.toString(),this._rhythmIdLookup.set(i,a);const e=s.addElement("Rhythm");if(e.attributes.set("id",a),t.hasTuplet){const s=e.addElement("PrimaryTuplet");s.attributes.set("num",t.tupletNumerator.toString()),s.attributes.set("den",t.tupletDenominator.toString())}t.dots>0&&e.addElement("AugmentationDot").attributes.set("count",t.dots.toString());let r="Quarter";switch(t.duration){case f.QuadrupleWhole:r="Long";break;case f.DoubleWhole:r="DoubleWhole";break;case f.Whole:r="Whole";break;case f.Half:r="Half";break;case f.Quarter:r="Quarter";break;case f.Eighth:r="Eighth";break;case f.Sixteenth:r="16th";break;case f.ThirtySecond:r="32nd";break;case f.SixtyFourth:r="64th";break;case f.OneHundredTwentyEighth:r="128th";break;case f.TwoHundredFiftySixth:r="256th"}e.addElement("NoteValue").innerText=r}e.addElement("Rhythm").attributes.set("ref",a)}writeWhammyNode(e,t){t.hasWhammyBar&&t.whammyBarPoints.length<=4&&this.writeStandardWhammy(e,t.whammyBarPoints)}writeStandardWhammy(e,t){const s=e.addElement("Whammy"),i=t[0],a=t[t.length-1];let r,n;switch(t.length){case 4:r=t[1],n=t[2];break;case 3:r=t[1],n=t[1];break;default:r=new ae((i.offset+a.offset)/2,(i.value+a.value)/2),n=r}s.attributes.set("destinationOffset",this.toBendOffset(a.offset).toString()),s.attributes.set("destinationValue",this.toBendValue(a.value).toString()),s.attributes.set("middleOffset1",this.toBendOffset(r.offset).toString()),s.attributes.set("middleOffset2",this.toBendOffset(n.offset).toString()),s.attributes.set("middleValue",this.toBendValue(r.value).toString()),s.attributes.set("originOffset",this.toBendOffset(i.offset).toString()),s.attributes.set("originValue",this.toBendValue(i.value).toString())}writeScoreNode(e,t){const s=e.addElement("Score");s.addElement("Title").setCData(t.title),s.addElement("SubTitle").setCData(t.subTitle),s.addElement("Artist").setCData(t.artist),s.addElement("Album").setCData(t.album),s.addElement("Words").setCData(t.words),s.addElement("Music").setCData(t.music),s.addElement("WordsAndMusic").setCData(t.words===t.music?t.words:""),s.addElement("Copyright").setCData(t.copyright),s.addElement("Tabber").setCData(t.tab),s.addElement("Instructions").setCData(t.instructions),s.addElement("Notices").setCData(t.notices),s.addElement("FirstPageHeader").setCData(""),s.addElement("FirstPageFooter").setCData(""),s.addElement("PageHeader").setCData(""),s.addElement("PageFooter").setCData(""),s.addElement("ScoreSystemsDefaultLayout").setCData(t.defaultSystemsLayout.toString()),s.addElement("ScoreSystemsLayout").setCData(t.systemsLayout.join(" ")),s.addElement("ScoreZoomPolicy").innerText="Value",s.addElement("ScoreZoom").innerText="1",s.addElement("MultiVoice").innerText="1>"}writeMasterTrackNode(e,t){const s=e.addElement("MasterTrack");s.addElement("Tracks").innerText=t.tracks.map((e=>e.index)).join(" ");const i=s.addElement("Automations");if(t.masterBars.length>0&&t.masterBars[0].isAnacrusis&&s.addElement("Anacrusis"),0===t.masterBars[0].tempoAutomations.length){const e=i.addElement("Automation");e.addElement("Type").innerText="Tempo",e.addElement("Linear").innerText="false",e.addElement("Bar").innerText="0",e.addElement("Position").innerText="0",e.addElement("Visible").innerText="true",e.addElement("Value").innerText=`${t.tempo} 2`,t.tempoLabel&&(e.addElement("Text").innerText=t.tempoLabel)}for(const e of t.masterBars)for(const t of e.tempoAutomations){const s=i.addElement("Automation");s.addElement("Type").innerText="Tempo",s.addElement("Linear").innerText=t.isLinear?"true":"false",s.addElement("Bar").innerText=e.index.toString(),s.addElement("Position").innerText=t.ratioPosition.toString(),s.addElement("Visible").innerText="true",s.addElement("Value").innerText=`${t.value} 2`,t.text&&(s.addElement("Text").innerText=t.text)}}writeAudioTracksNode(e,t){e.addElement("AudioTracks")}writeTracksNode(e,t){const s=e.addElement("Tracks");for(const e of t.tracks)this.writeTrackNode(s,e)}writeTrackNode(e,t){const s=e.addElement("Track");s.attributes.set("id",t.index.toString()),s.addElement("Name").setCData(t.name),s.addElement("ShortName").setCData(t.shortName),s.addElement("Color").innerText=`${t.color.r} ${t.color.g} ${t.color.b}`,s.addElement("SystemsDefautLayout").innerText=t.defaultSystemsLayout.toString(),s.addElement("SystemsLayout").innerText=t.systemsLayout.join(" "),s.addElement("AutoBrush"),s.addElement("PalmMute").innerText="0",s.addElement("PlayingStyle").innerText=q.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",s.addElement("UseOneChannelPerString"),s.addElement("IconId").innerText=cc.getIconId(t.playbackInfo).toString(),this.writeInstrumentSetNode(s,t),this.writeTransposeNode(s,t),this.writeRseNode(s,t),s.addElement("ForcedSound").innerText="-1",this.writeMidiConnectionNode(s,t),t.playbackInfo.isSolo?s.addElement("PlaybackState").innerText="Solo":t.playbackInfo.isMute?s.addElement("PlaybackState").innerText="Mute":s.addElement("PlaybackState").innerText="Default",s.addElement("AudioEngineState").innerText="MIDI",this.writeLyricsNode(s,t),this.writeStavesNode(s,t),this.writeSoundsAndAutomations(s,t)}static getIconId(e){return 9===e.primaryChannel?cc.DrumKitProgramInfo.icon:cc.MidiProgramInfoLookup.has(e.program)?cc.MidiProgramInfoLookup.get(e.program).icon:hc.SteelGuitar}writeSoundAndAutomation(e,t,s,i,a,r,n,o=0){const h=e.addElement("Sound");h.addElement("Name").setCData(s),h.addElement("Label").setCData(s),h.addElement("Path").setCData(i),h.addElement("Role").setCData(a);const l=h.addElement("MIDI");l.addElement("LSB").innerText="0",l.addElement("MSB").innerText="0",l.addElement("Program").innerText=n.toString();const c=t.addElement("Automation");c.addElement("Type").innerText="Sound",c.addElement("Linear").innerText="false",c.addElement("Bar").innerText=r.toString(),c.addElement("Position").innerText=o.toString(),c.addElement("Visible").innerText="true",c.addElement("Value").setCData(`${i};${s};${a}`)}writeSoundsAndAutomations(e,t){const s=e.addElement("Sounds"),i=e.addElement("Automations");if(t.staves.length>0&&t.staves[0].bars.length>0){const e=`Track_${t.index}_Initial`,a=`Midi/${t.playbackInfo.program}`,r="Factory";let n=!1;for(const o of t.staves)for(const h of o.bars)for(const o of h.voices)for(const l of o.beats){const o=l.getAutomation(d.Instrument),c=0===h.index&&0===l.index;if(o){const d=c?e:`ProgramChange_${l.id}`,u=c?a:`Midi/${o.value}`,p=c?r:"User";c||n||(this.writeSoundAndAutomation(s,i,e,a,r,t.staves[0].bars[0].index,t.playbackInfo.program),n=!0),this.writeSoundAndAutomation(s,i,d,u,p,h.index,o.value,o.ratioPosition),c&&(n=!0)}}}for(const e of t.staves)for(const t of e.bars)for(const e of t.sustainPedals)if(e.pedalType!==l.Hold){const s=i.addElement("Automation");switch(s.addElement("Type").innerText="SustainPedal",s.addElement("Linear").innerText="false",s.addElement("Bar").innerText=t.index.toString(),s.addElement("Position").innerText=e.ratioPosition.toString(),s.addElement("Visible").innerText="true",e.pedalType){case l.Down:s.addElement("Value").innerText="0 1";break;case l.Up:s.addElement("Value").innerText="0 3"}}}writeMidiConnectionNode(e,t){const s=e.addElement("MidiConnection");s.addElement("Port").innerText=t.playbackInfo.port.toString(),s.addElement("PrimaryChannel").innerText=t.playbackInfo.primaryChannel.toString(),s.addElement("SecondaryChannel").innerText=t.playbackInfo.secondaryChannel.toString(),s.addElement("ForeOneChannelPerString").innerText="false"}writeRseNode(e,t){const s=e.addElement("RSE").addElement("ChannelStrip");s.attributes.set("version","E56");s.addElement("Parameters").innerText=`0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1 0.5 ${t.playbackInfo.balance/16} ${t.playbackInfo.volume/16} 0.5 0.5 0.5`}writeStavesNode(e,t){const s=e.addElement("Staves");for(const e of t.staves)this.writeStaffNode(s,e)}writeStaffNode(e,t){const s=e.addElement("Staff").addElement("Properties");if(this.writeSimplePropertyNode(s,"CapoFret","Fret",t.capo.toString()),this.writeSimplePropertyNode(s,"FretCount","Fret","24"),t.tuning.length>0){const e=s.addElement("Property");switch(e.attributes.set("name","Tuning"),e.addElement("Pitches").innerText=t.tuning.slice().reverse().join(" "),e.addElement("Label").setCData(t.tuningName),e.addElement("LabelVisible").innerText=t.tuningName?"true":"false",e.addElement("Flat"),t.tuning.length){case 3:e.addElement("Instrument").innerText="Shamisen";break;case 4:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":42===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Cello":43===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Contrabass":40===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Violin":41===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Viola":e.addElement("Instrument").innerText="Bass";break;case 5:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":e.addElement("Instrument").innerText="Bass";break;case 6:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;case 7:t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;default:e.addElement("Instrument").innerText="Guitar"}}this.writeSimplePropertyNode(s,"PartialCapoFret","Fret","0"),this.writeSimplePropertyNode(s,"PartialCapoStringFlags","Bitset",t.tuning.map((e=>"0")).join("")),this.writeSimplePropertyNode(s,"TuningFlat","Enable",null),this.writeDiagramCollection(s,t,"DiagramCollection"),this.writeDiagramCollection(s,t,"DiagramWorkingSet")}writeDiagramCollection(e,t,s){const i=e.addElement("Property");i.attributes.set("name",s);const a=i.addElement("Items"),r=t.chords;if(r)for(const[e,t]of r){const s=a.addElement("Item");s.attributes.set("id",e),s.attributes.set("name",t.name);const i=s.addElement("Diagram");i.attributes.set("stringCount",t.strings.length.toString()),i.attributes.set("fretCount","5"),i.attributes.set("baseFret",(t.firstFret-1).toString()),i.attributes.set("barStates",t.strings.map((e=>"1")).join(" "));const r=[],n=new Map;for(let e=0;e<t.strings.length;e++){const s=t.strings[e];if(-1!==s){const a=i.addElement("Fret"),o=t.strings.length-1-e;a.attributes.set("string",o.toString()),a.attributes.set("fret",(s-t.firstFret+1).toString()),n.has(s)||(n.set(s,[]),r.push(s)),n.get(s).push(o)}}r.sort();const o=i.addElement("Fingering");if(t.barreFrets.length>0){const e=[_.LittleFinger,_.AnnularFinger,_.MiddleFinger,_.IndexFinger];for(const s of r){const i=n.get(s);if(i.length>1&&t.barreFrets.indexOf(s)>=0){const a=e.length>0?e.pop():_.IndexFinger;for(const e of i){const i=o.addElement("Position");switch(a){case _.LittleFinger:i.attributes.set("finger","Pinky");break;case _.AnnularFinger:i.attributes.set("finger","Ring");break;case _.MiddleFinger:i.attributes.set("finger","Middle");break;case _.IndexFinger:i.attributes.set("finger","Index")}i.attributes.set("fret",(s-t.firstFret+1).toString()),i.attributes.set("string",e.toString())}}}}const h=i.addElement("Property");h.attributes.set("name","ShowName"),h.attributes.set("type","bool"),h.attributes.set("value",t.showName?"true":"false");const l=i.addElement("Property");l.attributes.set("name","ShowDiagram"),l.attributes.set("type","bool"),l.attributes.set("value",t.showDiagram?"true":"false");const c=i.addElement("Property");c.attributes.set("name","ShowFingering"),c.attributes.set("type","bool"),c.attributes.set("value",t.showFingering?"true":"false");const d=i.addElement("Chord"),u=d.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=d.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=d.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const m=d.addElement("Degree");m.attributes.set("interval","Fifth"),m.attributes.set("alteration","Perfect"),m.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,s,i){const a=e.addElement("Property");a.attributes.set("name",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeSimpleXPropertyNode(e,t,s,i){const a=e.addElement("XProperty");a.attributes.set("id",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeLyricsNode(e,t){const s=e.addElement("Lyrics");s.attributes.set("dispatched","true");const i=[];for(const e of t.staves[0].bars)for(const t of e.voices)if(!t.isEmpty)for(const s of t.beats)if(s.lyrics)for(let t=0;t<s.lyrics.length;t++){for(;t>=i.length;){const t=new pt;t.startBar=e.index,t.text="[Empty]",i.push(t)}const a=i[t];a.text="[Empty]"===a.text?s.lyrics[t]:`${a.text} ${s.lyrics[t].split(" ").join("+")}`}for(let e=0;e<i.length;e++){const t=s.addElement("Line");t.addElement("Text").setCData(i[e].text),t.addElement("Offset").innerText=i[e].startBar.toString()}}writeTransposeNode(e,t){const s=e.addElement("Transpose"),i=Math.floor(t.staves[0].displayTranspositionPitch/12),a=t.staves[0].displayTranspositionPitch-12*i;s.addElement("Chromatic").innerText=a.toString(),s.addElement("Octave").innerText=i.toString()}writeInstrumentSetNode(e,t){const s=e.addElement("InstrumentSet"),i=t.staves[0];if(s.addElement("LineCount").innerText=i.standardNotationLineCount.toString(),t.percussionArticulations.length>0||i.isPercussion){const e=t.percussionArticulations.length>0?t.percussionArticulations:Array.from(me.instrumentArticulations.values());s.addElement("Name").innerText=cc.DrumKitProgramInfo.instrumentSetName,s.addElement("Type").innerText=cc.DrumKitProgramInfo.instrumentSetType;let i="",a=new Ws;const r=new Map,n=s.addElement("Elements");for(const t of e){{const e=n.addElement("Element");let s=t.elementType;if(r.has(s)){const e=r.get(s);s+=` ${e}`,r.set(s,e+1)}else r.set(s,1);i=s,e.addElement("Name").innerText=s,e.addElement("Type").innerText=t.elementType,a=e.addElement("Articulations")}const e=a.addElement("Articulation");switch(e.addElement("Name").innerText=`${i} ${a.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 R.Top:e.addElement("TechniquePlacement").innerText="below";break;case R.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case R.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=cc.MidiProgramInfoLookup.has(t.playbackInfo.program)?cc.MidiProgramInfoLookup.get(t.playbackInfo.program):cc.MidiProgramInfoLookup.get(0);s.addElement("Name").innerText=e.instrumentSetName,s.addElement("Type").innerText=e.instrumentSetType;const i=s.addElement("Elements").addElement("Element");i.addElement("Pitched").innerText="Pitched",i.addElement("Type").innerText="pitched",i.addElement("SoundbankName").innerText="";const a=i.addElement("Articulations").addElement("Articulation");a.addElement("Name").innerText="",a.addElement("StaffLine").innerText="0",a.addElement("Noteheads").innerText="noteheadBlack noteheadHalf noteheadWhole",a.addElement("TechniquePlacement").innerText="outside",a.addElement("TechniqueSymbol").innerText="",a.addElement("InputMidiNumbers").innerText="",a.addElement("OutputRSESound").innerText="",a.addElement("OutputMidiNumber").innerText="0"}}mapMusicSymbol(e){if(e===I.None)return"";const t=I[e];return t.substring(0,1).toLowerCase()+t.substring(1)}writeMasterBarsNode(e,t){const s=e.addElement("MasterBars");for(const e of t.masterBars)this.writeMasterBarNode(s,e)}writeMasterBarNode(e,t){const s=e.addElement("MasterBar"),i=s.addElement("Key");i.addElement("AccidentalCount").innerText=t.keySignature.toString(),i.addElement("Mode").innerText=D[t.keySignatureType],i.addElement("Sharps").innerText="Sharps",s.addElement("Time").innerText=`${t.timeSignatureNumerator}/${t.timeSignatureDenominator}`,t.isFreeTime&&s.addElement("FreeTime");const a=[];for(const e of t.score.tracks)for(const s of e.staves)a.push(s.bars[t.index].id.toString());if(s.addElement("Bars").innerText=a.join(" "),t.isDoubleBar&&s.addElement("DoubleBar"),t.isSectionStart){const e=s.addElement("Section");e.addElement("Letter").setCData(t.section.marker),e.addElement("Text").setCData(t.section.text)}if(t.isRepeatStart||t.isRepeatEnd){const e=s.addElement("Repeat");e.attributes.set("start",t.isRepeatStart?"true":"false"),e.attributes.set("end",t.isRepeatEnd?"true":"false"),t.isRepeatEnd&&e.attributes.set("count",t.repeatCount.toString())}if(t.alternateEndings>0){let e=t.alternateEndings;const i=[];let a=0;for(;e>0;)1==(e>>a&1)&&(i.push(a+1),e&=~(1<<a)),a++;s.addElement("AlternateEndings").innerText=i.join(" ")}if(t.tripletFeel!==M.NoTripletFeel&&(s.addElement("TripletFeel").innerText=M[t.tripletFeel]),t.directions&&t.directions.size>0){const e=s.addElement("Directions");for(const s of t.directions)switch(s){case qe.TargetFine:e.addElement("Target").innerText="Fine";break;case qe.TargetSegno:e.addElement("Target").innerText="Segno";break;case qe.TargetSegnoSegno:e.addElement("Target").innerText="SegnoSegno";break;case qe.TargetCoda:e.addElement("Target").innerText="Coda";break;case qe.TargetDoubleCoda:e.addElement("Target").innerText="DoubleCoda";break;case qe.JumpDaCapo:e.addElement("Jump").innerText="DaCapo";break;case qe.JumpDaCapoAlCoda:e.addElement("Jump").innerText="DaCapoAlCoda";break;case qe.JumpDaCapoAlDoubleCoda:e.addElement("Jump").innerText="DaCapoAlDoubleCoda";break;case qe.JumpDaCapoAlFine:e.addElement("Jump").innerText="DaCapoAlFine";break;case qe.JumpDalSegno:e.addElement("Jump").innerText="DaSegno";break;case qe.JumpDalSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoAlCoda";break;case qe.JumpDalSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoAlDoubleCoda";break;case qe.JumpDalSegnoAlFine:e.addElement("Jump").innerText="DaSegnoAlFine";break;case qe.JumpDalSegnoSegno:e.addElement("Jump").innerText="DaSegnoSegno";break;case qe.JumpDalSegnoSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlCoda";break;case qe.JumpDalSegnoSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlDoubleCoda";break;case qe.JumpDalSegnoSegnoAlFine:e.addElement("Jump").innerText="DaSegnoSegnoAlFine";break;case qe.JumpDaCoda:e.addElement("Jump").innerText="DaCoda";break;case qe.JumpDaDoubleCoda:e.addElement("Jump").innerText="DaDoubleCoda"}}this.writeFermatas(s,t)}writeFermatas(e,t){const s=t.fermata?.size??0;if(0!==s&&s>0){const s=e.addElement("Fermatas");for(const[e,i]of t.fermata)this.writeFermata(s,e,i)}}writeFermata(e,t,s){let i=-1,a=1;if(t>0)for(;a<10&&(i=t/se.QuarterTime*a,i!==Math.floor(i));)i=-1,a++;else i=0,a=1;if(-1===i)return;const r=e.addElement("Fermata");r.addElement("Type").innerText=Ke[s.type],r.addElement("Length").innerText=s.length.toString(),r.addElement("Offset").innerText=`${i}/${a}`}writeBarNode(e,t){const s=e.addElement("Bar");s.attributes.set("id",t.id.toString()),s.addElement("Voices").innerText=t.voices.map((e=>e.isEmpty?"-1":e.id.toString())).join(" "),s.addElement("Clef").innerText=n[t.clef],t.clefOttava!==o.Regular&&(s.addElement("Ottavia").innerText=o[t.clefOttava].substr(1)),t.simileMark!==h.None&&(s.addElement("SimileMark").innerText=h[t.simileMark])}writeVoiceNode(e,t){if(t.isEmpty)return;const s=e.addElement("Voice");s.attributes.set("id",t.id.toString()),s.addElement("Beats").innerText=t.beats.map((e=>e.id)).join(" ")}}cc.MidiProgramInfoLookup=new Map([[0,new lc(hc.Piano,"Acoustic Piano")],[1,new lc(hc.Piano,"Acoustic Piano")],[2,new lc(hc.Piano,"Electric Piano")],[3,new lc(hc.Piano,"Acoustic Piano")],[4,new lc(hc.Piano,"Electric Piano")],[5,new lc(hc.Piano,"Electric Piano")],[6,new lc(hc.Piano,"Harpsichord")],[7,new lc(hc.Piano,"Harpsichord")],[8,new lc(hc.PitchedIdiophone,"Celesta")],[9,new lc(hc.PitchedIdiophone,"Vibraphone")],[10,new lc(hc.PitchedIdiophone,"Vibraphone")],[11,new lc(hc.PitchedIdiophone,"Vibraphone")],[12,new lc(hc.PitchedIdiophone,"Xylophone")],[13,new lc(hc.PitchedIdiophone,"Xylophone")],[14,new lc(hc.PitchedIdiophone,"Vibraphone")],[15,new lc(hc.Banjo,"Banjo")],[16,new lc(hc.Piano,"Electric Organ")],[17,new lc(hc.Piano,"Electric Organ")],[18,new lc(hc.Piano,"Electric Organ")],[19,new lc(hc.Piano,"Electric Organ")],[20,new lc(hc.Piano,"Electric Organ")],[21,new lc(hc.Piano,"Electric Organ")],[22,new lc(hc.Woodwind,"Recorder")],[23,new lc(hc.Piano,"Electric Organ")],[24,new lc(hc.ClassicalGuitar,"Nylon Guitar")],[25,new lc(hc.SteelGuitar,"Steel Guitar")],[26,new lc(hc.SteelGuitar,"Electric Guitar")],[27,new lc(hc.ElectricGuitar,"Electric Guitar")],[28,new lc(hc.ElectricGuitar,"Electric Guitar")],[29,new lc(hc.ElectricGuitar,"Electric Guitar")],[30,new lc(hc.SteelGuitar,"Electric Guitar")],[31,new lc(hc.SteelGuitar,"Electric Guitar")],[32,new lc(hc.Bass,"Acoustic Bass")],[33,new lc(hc.Bass,"Electric Bass")],[34,new lc(hc.Bass,"Electric Bass")],[35,new lc(hc.Bass,"Acoustic Bass")],[36,new lc(hc.Bass,"Electric Bass")],[37,new lc(hc.Bass,"Electric Bass")],[38,new lc(hc.Synth,"Synth Bass")],[39,new lc(hc.Synth,"Synth Bass")],[40,new lc(hc.Strings,"Violin")],[41,new lc(hc.Strings,"Viola")],[42,new lc(hc.Strings,"Cello")],[43,new lc(hc.Strings,"Contrabass")],[44,new lc(hc.Strings,"Violin")],[45,new lc(hc.Strings,"Violin")],[46,new lc(hc.Piano,"Harp")],[47,new lc(hc.Membraphone,"Timpani")],[48,new lc(hc.Strings,"Violin")],[49,new lc(hc.Strings,"Violin")],[50,new lc(hc.Strings,"Violin")],[51,new lc(hc.Strings,"Violin")],[52,new lc(hc.Vocal,"Voice")],[53,new lc(hc.Vocal,"Voice")],[54,new lc(hc.Vocal,"Voice")],[55,new lc(hc.Synth,"Pad Synthesizer")],[56,new lc(hc.Brass,"Trumpet")],[57,new lc(hc.Brass,"Trombone")],[58,new lc(hc.Brass,"Tuba")],[59,new lc(hc.Brass,"Trumpet")],[60,new lc(hc.Brass,"French Horn")],[61,new lc(hc.Brass,"Trumpet")],[62,new lc(hc.Brass,"Trumpet")],[63,new lc(hc.Brass,"Trumpet")],[64,new lc(hc.Reed,"Saxophone")],[65,new lc(hc.Reed,"Saxophone")],[66,new lc(hc.Reed,"Saxophone")],[67,new lc(hc.Reed,"Saxophone")],[68,new lc(hc.Reed,"Oboe")],[69,new lc(hc.Reed,"English Horn")],[70,new lc(hc.Reed,"Bassoon")],[71,new lc(hc.Reed,"Clarinet")],[72,new lc(hc.Reed,"Piccolo")],[73,new lc(hc.Woodwind,"Flute")],[74,new lc(hc.Woodwind,"Recorder")],[75,new lc(hc.Woodwind,"Flute")],[76,new lc(hc.Woodwind,"Recorder")],[77,new lc(hc.Woodwind,"Flute")],[78,new lc(hc.Woodwind,"Recorder")],[79,new lc(hc.Woodwind,"Flute")],[80,new lc(hc.Synth,"Lead Synthesizer")],[81,new lc(hc.Synth,"Lead Synthesizer")],[82,new lc(hc.Synth,"Lead Synthesizer")],[83,new lc(hc.Synth,"Lead Synthesizer")],[84,new lc(hc.Synth,"Lead Synthesizer")],[85,new lc(hc.Synth,"Lead Synthesizer")],[86,new lc(hc.Synth,"Lead Synthesizer")],[87,new lc(hc.Synth,"Lead Synthesizer")],[88,new lc(hc.Synth,"Pad Synthesizer")],[89,new lc(hc.Synth,"Pad Synthesizer")],[90,new lc(hc.Synth,"Pad Synthesizer")],[91,new lc(hc.Synth,"Pad Synthesizer")],[92,new lc(hc.Synth,"Pad Synthesizer")],[93,new lc(hc.Synth,"Pad Synthesizer")],[94,new lc(hc.Synth,"Pad Synthesizer")],[95,new lc(hc.Synth,"Pad Synthesizer")],[96,new lc(hc.Fx,"Pad Synthesizer")],[97,new lc(hc.Fx,"Pad Synthesizer")],[98,new lc(hc.Fx,"Pad Synthesizer")],[99,new lc(hc.Fx,"Pad Synthesizer")],[100,new lc(hc.Fx,"Lead Synthesizer")],[101,new lc(hc.Fx,"Lead Synthesizer")],[102,new lc(hc.Fx,"Lead Synthesizer")],[103,new lc(hc.Fx,"Trumpet")],[104,new lc(hc.ElectricGuitar,"Banjo")],[105,new lc(hc.Banjo,"Banjo")],[106,new lc(hc.Ukulele,"Ukulele")],[107,new lc(hc.Banjo,"Banjo")],[108,new lc(hc.PitchedIdiophone,"Xylophone")],[109,new lc(hc.Reed,"Bassoon")],[110,new lc(hc.Strings,"Violin")],[111,new lc(hc.Woodwind,"Flute")],[112,new lc(hc.PitchedIdiophone,"Xylophone")],[113,new lc(hc.Idiophone,"Celesta")],[114,new lc(hc.PitchedIdiophone,"Vibraphone")],[115,new lc(hc.Idiophone,"Xylophone")],[116,new lc(hc.Membraphone,"Xylophone")],[117,new lc(hc.Membraphone,"Xylophone")],[118,new lc(hc.Membraphone,"Xylophone")],[119,new lc(hc.Idiophone,"Celesta")],[120,new lc(hc.Fx,"Steel Guitar")],[121,new lc(hc.Fx,"Recorder")],[122,new lc(hc.Fx,"Recorder")],[123,new lc(hc.Fx,"Recorder")],[124,new lc(hc.Fx,"Recorder")],[125,new lc(hc.Fx,"Recorder")],[126,new lc(hc.Fx,"Recorder")],[127,new lc(hc.Fx,"Timpani")]]),cc.DrumKitProgramInfo=new lc(hc.PercussionKit,"Drums","drumKit");class dc{static buildCrc32Lookup(){const e=new Uint32Array(256);for(let t=0;t<e.length;t++){let s=t;for(let e=0;e<8;e++)s=1&~s?s>>>1:s>>>1^3988292384;e[t]=s}return e}get value(){return~this._checkValue}constructor(){this._checkValue=dc.CrcInit,this.reset()}update(e,t,s){for(let i=0;i<s;i++)this._checkValue=dc.Crc32Lookup[255&(this._checkValue^e[t+i])]^this._checkValue>>>8}reset(){this._checkValue=dc.CrcInit}}dc.Crc32Lookup=dc.buildCrc32Lookup(),dc.CrcInit=4294967295;class uc{}uc.MAX_WBITS=15,uc.WSIZE=1<<uc.MAX_WBITS,uc.WMASK=uc.WSIZE-1,uc.MIN_MATCH=3,uc.MAX_MATCH=258,uc.DEFAULT_MEM_LEVEL=8,uc.PENDING_BUF_SIZE=1<<uc.DEFAULT_MEM_LEVEL+8,uc.HASH_BITS=uc.DEFAULT_MEM_LEVEL+7,uc.HASH_SIZE=1<<uc.HASH_BITS,uc.HASH_SHIFT=(uc.HASH_BITS+uc.MIN_MATCH-1)/uc.MIN_MATCH,uc.HASH_MASK=uc.HASH_SIZE-1,uc.MIN_LOOKAHEAD=uc.MAX_MATCH+uc.MIN_MATCH+1,uc.MAX_DIST=uc.WSIZE-uc.MIN_LOOKAHEAD;class pc{constructor(e,t,s,i){this.length=null,this.numCodes=0,this.codes=null,this.huffman=e,this.minNumCodes=s,this.maxLength=i,this.freqs=new Int16Array(t),this.bitLengthCounts=new Int32Array(i)}reset(){for(let e=0;e<this.freqs.length;e++)this.freqs[e]=0;this.codes=null,this.length=null}buildTree(){const e=this.freqs.length,t=new Int32Array(e);let s=0,i=0;for(let a=0;a<e;a++){const e=this.freqs[a];if(0!==e){let r=s++;for(;r>0;){const s=Math.floor((r-1)/2);if(!(this.freqs[t[s]]>e))break;t[r]=t[s],r=s}t[r]=a,i=a}}for(;s<2;){const e=i<2?++i:0;t[s++]=e}this.numCodes=Math.max(i+1,this.minNumCodes);const a=s,r=new Int32Array(4*s-2),n=new Int32Array(2*s-1);let o=a;for(let e=0;e<s;e++){const s=t[e];r[2*e]=s,r[2*e+1]=-1,n[e]=this.freqs[s]<<8,t[e]=e}do{const e=t[0];let i=t[--s],a=0,h=1;for(;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*h+1;let l=n[i];for(;h=a,a>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i;const c=t[0];i=o++,r[2*i]=e,r[2*i+1]=c;const d=Math.min(255&n[e],255&n[c]);for(l=n[e]+n[c]-d+1,n[i]=l,a=0,h=1;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*a+1;for(;h=a,h>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i}while(s>1);this.buildLength(r)}buildLength(e){this.length=new Uint8Array(this.freqs.length);const t=Math.floor(e.length/2),s=Math.floor((t+1)/2);let i=0;for(let e=0;e<this.maxLength;e++)this.bitLengthCounts[e]=0;const a=new Int32Array(t);a[t-1]=0;for(let s=t-1;s>=0;s--)if(-1!==e[2*s+1]){let t=a[s]+1;t>this.maxLength&&(t=this.maxLength,i++),a[e[2*s]]=t,a[e[2*s+1]]=t}else{const t=a[s];this.bitLengthCounts[t-1]++,this.length[e[2*s]]=a[s]}if(0===i)return;let r=this.maxLength-1;do{for(;0===this.bitLengthCounts[--r];);do{this.bitLengthCounts[r]--,this.bitLengthCounts[++r]++,i-=1<<this.maxLength-1-r}while(i>0&&r<this.maxLength-1)}while(i>0);this.bitLengthCounts[this.maxLength-1]+=i,this.bitLengthCounts[this.maxLength-2]-=i;let n=2*s;for(let t=this.maxLength;0!==t;t--){let s=this.bitLengthCounts[t-1];for(;s>0;){const i=2*e[n++];-1===e[i+1]&&(this.length[e[i]]=t,s--)}}}getEncodedLength(){let e=0;for(let t=0;t<this.freqs.length;t++)e+=this.freqs[t]*this.length[t];return e}calcBLFreq(e){let t,s,i,a=-1,r=0;for(;r<this.numCodes;){i=1;const n=this.length[r];for(0===n?(t=138,s=3):(t=6,s=3,a!==n&&(e.freqs[n]++,i=0)),a=n,r++;r<this.numCodes&&a===this.length[r]&&(r++,!(++i>=t)););i<s?e.freqs[a]+=i:0!==a?e.freqs[pc.Repeat3To6]++:i<=10?e.freqs[pc.Repeat3To10]++:e.freqs[pc.Repeat11To138]++}}setStaticCodes(e,t){this.codes=e,this.length=t}buildCodes(){const e=new Int32Array(this.maxLength);let t=0;this.codes=new Int16Array(this.freqs.length);for(let s=0;s<this.maxLength;s++)e[s]=t,t+=this.bitLengthCounts[s]<<15-s;for(let t=0;t<this.numCodes;t++){const s=this.length[t];s>0&&(this.codes[t]=gc.bitReverse(e[s-1]),e[s-1]+=1<<16-s)}}writeTree(e){let t,s,i,a=-1,r=0;for(;r<this.numCodes;){i=1;const n=this.length[r];for(0===n?(t=138,s=3):(t=6,s=3,a!==n&&(e.writeSymbol(n),i=0)),a=n,r++;r<this.numCodes&&a===this.length[r]&&(r++,!(++i>=t)););if(i<s)for(;i-- >0;)e.writeSymbol(a);else 0!==a?(e.writeSymbol(pc.Repeat3To6),this.huffman.pending.writeBits(i-3,2)):i<=10?(e.writeSymbol(pc.Repeat3To10),this.huffman.pending.writeBits(i-3,3)):(e.writeSymbol(pc.Repeat11To138),this.huffman.pending.writeBits(i-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}pc.Repeat3To6=16,pc.Repeat3To10=17,pc.Repeat11To138=18;class gc{static staticInit(){let e=0;for(;e<144;)gc.staticLCodes[e]=gc.bitReverse(48+e<<8),gc.staticLLength[e++]=8;for(;e<256;)gc.staticLCodes[e]=gc.bitReverse(256+e<<7),gc.staticLLength[e++]=9;for(;e<280;)gc.staticLCodes[e]=gc.bitReverse(-256+e<<9),gc.staticLLength[e++]=7;for(;e<gc.LITERAL_NUM;)gc.staticLCodes[e]=gc.bitReverse(-88+e<<8),gc.staticLLength[e++]=8;for(e=0;e<gc.DIST_NUM;e++)gc.staticDCodes[e]=gc.bitReverse(e<<11),gc.staticDLength[e]=5}static bitReverse(e){return gc.bit4Reverse[15&e]<<12|gc.bit4Reverse[e>>4&15]<<8|gc.bit4Reverse[e>>8&15]<<4|gc.bit4Reverse[e>>12]}constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new pc(this,gc.LITERAL_NUM,257,15),this.distTree=new pc(this,gc.DIST_NUM,1,15),this.blTree=new pc(this,gc.BITLEN_NUM,4,7),this.d_buf=new Int16Array(gc.BUFSIZE),this.l_buf=new Uint8Array(gc.BUFSIZE)}isFull(){return this.last_lit>=gc.BUFSIZE}reset(){this.last_lit=0,this.extra_bits=0,this.literalTree.reset(),this.distTree.reset(),this.blTree.reset()}flushStoredBlock(e,t,s,i){this.pending.writeBits((gc.STORED_BLOCK<<1)+(i?1:0),3),this.pending.alignToByte(),this.pending.writeShort(s),this.pending.writeShort(~s),this.pending.writeBlock(e,t,s),this.reset()}flushBlock(e,t,s,i){this.literalTree.freqs[gc.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[gc.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<gc.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*gc.staticLLength[e];for(let e=0;e<gc.DIST_NUM;e++)n+=this.distTree.freqs[e]*gc.staticDLength[e];r>=n&&(r=n),t>=0&&s+4<r>>3?this.flushStoredBlock(e,t,s,i):r===n?(this.pending.writeBits((gc.STATIC_TREES<<1)+(i?1:0),3),this.literalTree.setStaticCodes(gc.staticLCodes,gc.staticLLength),this.distTree.setStaticCodes(gc.staticDCodes,gc.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((gc.DYN_TREES<<1)+(i?1:0),3),this.sendAllTrees(a),this.compressBlock(),this.reset())}sendAllTrees(e){this.blTree.buildCodes(),this.literalTree.buildCodes(),this.distTree.buildCodes(),this.pending.writeBits(this.literalTree.numCodes-257,5),this.pending.writeBits(this.distTree.numCodes-1,5),this.pending.writeBits(e-4,4);for(let t=0;t<e;t++)this.pending.writeBits(this.blTree.length[gc.BL_ORDER[t]],3);this.literalTree.writeTree(this.blTree),this.distTree.writeTree(this.blTree)}compressBlock(){for(let e=0;e<this.last_lit;e++){const t=255&this.l_buf[e];let s=this.d_buf[e];if(0!=s--){const e=gc.Lcode(t);this.literalTree.writeSymbol(e);let i=Math.floor((e-261)/4);i>0&&i<=5&&this.pending.writeBits(t&(1<<i)-1,i);const a=gc.Dcode(s);this.distTree.writeSymbol(a),i=Math.floor(a/2)-1,i>0&&this.pending.writeBits(s&(1<<i)-1,i)}else this.literalTree.writeSymbol(t)}this.literalTree.writeSymbol(gc.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;const s=gc.Lcode(t-3);this.literalTree.freqs[s]++,s>=265&&s<285&&(this.extra_bits+=Math.floor((s-261)/4));const i=gc.Dcode(e-1);return this.distTree.freqs[i]++,i>=4&&(this.extra_bits+=Math.floor(i/2)-1),this.isFull()}tallyLit(e){return this.d_buf[this.last_lit]=0,this.l_buf[this.last_lit++]=e,this.literalTree.freqs[e]++,this.isFull()}static Lcode(e){if(255===e)return 285;let t=257;for(;e>=8;)t+=4,e>>=1;return t+e}static Dcode(e){let t=0;for(;e>=4;)t+=2,e>>=1;return t+e}}gc.BUFSIZE=1<<uc.DEFAULT_MEM_LEVEL+6,gc.LITERAL_NUM=286,gc.STORED_BLOCK=0,gc.STATIC_TREES=1,gc.DYN_TREES=2,gc.DIST_NUM=30,gc.staticLCodes=new Int16Array(gc.LITERAL_NUM),gc.staticLLength=new Uint8Array(gc.LITERAL_NUM),gc.staticDCodes=new Int16Array(gc.DIST_NUM),gc.staticDLength=new Uint8Array(gc.DIST_NUM),gc.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],gc.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),gc.BITLEN_NUM=19,gc.EOF_SYMBOL=256,gc.staticInit();class mc{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 gc(e),this.inputCrc=new dc,this.window=new Uint8Array(2*uc.WSIZE),this.head=new Int16Array(uc.HASH_SIZE),this.prev=new Int16Array(uc.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=uc.MIN_MATCH-1;for(let e=0;e<uc.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<uc.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<uc.HASH_SHIFT^this.window[this.strstart+1]}needsInput(){return this.inputEnd===this.inputOff}setInput(e,t,s){const i=t+s;this.inputBuf=e,this.inputOff=t,this.inputEnd=i}deflate(e,t){let s;do{this.fillWindow();const i=e&&this.inputOff===this.inputEnd;s=this.deflateSlow(i,t)}while(this.pending.isFlushed&&s);return s}deflateSlow(e,t){if(this.lookahead<uc.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=uc.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*uc.WSIZE-uc.MIN_LOOKAHEAD&&this.slideWindow();const e=this.matchStart;let s=this.matchLen;if(this.lookahead>=uc.MIN_MATCH){const e=this.insertString();0!==e&&this.strstart-e<=uc.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen===uc.MIN_MATCH&&this.strstart-this.matchStart>mc.TooFar&&(this.matchLen=uc.MIN_MATCH-1)}if(s>=uc.MIN_MATCH&&this.matchLen<=s){this.huffman.tallyDist(this.strstart-1-e,s),s-=2;do{this.strstart++,this.lookahead--,this.lookahead>=uc.MIN_MATCH&&this.insertString()}while(--s>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=uc.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--;const s=t&&0===this.lookahead&&!this.prevAvailable;return this.huffman.flushBlock(this.window,this.blockStart,e,s),this.blockStart+=e,!s}}return!0}findLongestMatch(e){let t,s=this.strstart;const i=s+Math.min(uc.MAX_MATCH,this.lookahead)-1,a=Math.max(s-uc.MAX_DIST,0),r=this.window,n=this.prev;let o=this.maxChain;const h=Math.min(this.niceLength,this.lookahead);if(this.matchLen=Math.max(this.matchLen,uc.MIN_MATCH-1),s+this.matchLen>i)return!1;let l=r[s+this.matchLen-1],c=r[s+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,s=this.strstart,r[t+this.matchLen]===c&&r[t+this.matchLen-1]===l&&r[t]===r[s]&&r[++t]===r[++s]){switch((i-s)%8){case 1:if(r[++s]===r[++t])break;break;case 2:if(r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 3:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 4:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 5:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 6:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 7:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break}if(r[s]===r[t])do{if(s===i){++s,++t;break}}while(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]);if(s-this.strstart>this.matchLen){if(this.matchStart=e,this.matchLen=s-this.strstart,this.matchLen>=h)break;l=r[s-1],c=r[s]}e=65535&n[e&uc.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=uc.MIN_MATCH}insertString(){const e=(this.insertHashIndex<<uc.HASH_SHIFT^this.window[this.strstart+(uc.MIN_MATCH-1)])&uc.HASH_MASK,t=this.head[e];return this.prev[this.strstart&uc.WMASK]=t,this.head[e]=this.strstart,this.insertHashIndex=e,65535&t}fillWindow(){if(this.strstart>=uc.WSIZE+uc.MAX_DIST&&this.slideWindow(),this.lookahead<uc.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*uc.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>=uc.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(uc.WSIZE,uc.WSIZE+uc.WSIZE),0),this.matchStart-=uc.WSIZE,this.strstart-=uc.WSIZE,this.blockStart-=uc.WSIZE;for(let e=0;e<uc.HASH_SIZE;++e){const t=65535&this.head[e];this.head[e]=t>=uc.WSIZE?t-uc.WSIZE:0}for(let e=0;e<uc.WSIZE;e++){const t=65535&this.prev[e];this.prev[e]=t>=uc.WSIZE?t-uc.WSIZE:0}}}mc.TooFar=4096;class fc{get isFlushed(){return 0===this._end}constructor(e){this._start=0,this._end=0,this._bits=0,this.bitCount=0,this._buffer=new Uint8Array(e)}reset(){this._start=0,this._end=0,this.bitCount=0}writeShortMSB(e){this._buffer[this._end++]=e>>8&255,this._buffer[this._end++]=255&e}writeShort(e){this._buffer[this._end++]=e,this._buffer[this._end++]=e>>8}writeBlock(e,t,s){this._buffer.set(e.subarray(t,t+s),this._end),this._end+=s}flush(e,t,s){return this.bitCount>=8&&(this._buffer[this._end++]=255&this._bits,this._bits>>=8,this.bitCount-=8),s>this._end-this._start?(s=this._end-this._start,e.set(this._buffer.subarray(this._start,this._start+s),t),this._start=0,this._end=0):(e.set(this._buffer.subarray(this._start,this._start+s),t),this._start+=s),s}writeBits(e,t){this._bits|=e<<this.bitCount,this.bitCount+=t,this.bitCount>=16&&(this._buffer[this._end++]=255&this._bits,this._buffer[this._end++]=this._bits>>8&255,this._bits>>=16,this.bitCount-=16)}alignToByte(){this.bitCount>0&&(this._buffer[this._end++]=255&this._bits,this.bitCount>8&&(this._buffer[this._end++]=this._bits>>8&255)),this._bits=0,this.bitCount=0}}class yc{get inputCrc(){return this._engine.inputCrc.value}constructor(){this._state=0,this._pending=new fc(uc.PENDING_BUF_SIZE),this._engine=new mc(this._pending),this.reset()}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state===yc.FinishedState&&this._pending.isFlushed}reset(){this._state=yc.BusyState,this._pending.reset(),this._engine.reset()}setInput(e,t,s){this._engine.setInput(e,t,s)}deflate(e,t,s){const i=s;for(;;){const a=this._pending.flush(e,t,s);if(t+=a,0===(s-=a)||this._state===yc.FinishedState)break;if(!this._engine.deflate(!!(this._state&yc.IsFlushing),!!(this._state&yc.IsFinishing)))switch(this._state){case yc.BusyState:return i-s;case yc.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=yc.BusyState;break;case yc.FinishingState:this._pending.alignToByte(),this._state=yc.FinishedState}}return i-s}finish(){this._state|=yc.IsFlushing|yc.IsFinishing}}yc.IsFlushing=4,yc.IsFinishing=8,yc.BusyState=16,yc.FlushingState=20,yc.FinishingState=28,yc.FinishedState=30;class bc{constructor(e,t,s,i,a){this.entry=e,this.crc32=t,this.localHeaderOffset=s,this.compressionMode=i,this.compressedSize=a}}class Sc{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new yc,this._data=e}writeEntry(e){const t=ni.CompressionMethodDeflate,s=Bt.empty(),i=this.compress(s,e.data,t),a=s.toArray(),r=new bc(e,i,this._data.bytesWritten,t,s.length);this._centralDirectoryHeaders.push(r),wt.writeInt32LE(this._data,ni.LocalFileHeaderSignature),wt.writeUInt16LE(this._data,10),wt.writeUInt16LE(this._data,2048),wt.writeUInt16LE(this._data,t),wt.writeInt16LE(this._data,0),wt.writeInt16LE(this._data,0),wt.writeInt32LE(this._data,i),wt.writeInt32LE(this._data,a.length),wt.writeInt32LE(this._data,e.data.length),wt.writeInt16LE(this._data,e.fullName.length),wt.writeInt16LE(this._data,0);const n=wt.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,s){if(s!==ni.CompressionMethodDeflate){const s=new dc;return s.update(t,0,t.length),e.write(t,0,t.length),s.value}const 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){wt.writeInt32LE(this._data,ni.EndOfCentralDirSignature),wt.writeInt16LE(this._data,0),wt.writeInt16LE(this._data,0),wt.writeInt16LE(this._data,this._centralDirectoryHeaders.length),wt.writeInt16LE(this._data,this._centralDirectoryHeaders.length),wt.writeInt32LE(this._data,t-e),wt.writeInt32LE(this._data,e),wt.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){wt.writeInt32LE(this._data,ni.CentralFileHeaderSignature),wt.writeUInt16LE(this._data,10),wt.writeUInt16LE(this._data,10),wt.writeUInt16LE(this._data,2048),wt.writeUInt16LE(this._data,e.compressionMode),wt.writeInt16LE(this._data,0),wt.writeInt16LE(this._data,0),wt.writeInt32LE(this._data,e.crc32),wt.writeInt32LE(this._data,e.compressedSize),wt.writeInt32LE(this._data,e.entry.data.length),wt.writeInt16LE(this._data,e.entry.fullName.length),wt.writeInt16LE(this._data,0),wt.writeInt16LE(this._data,0),wt.writeInt16LE(this._data,0),wt.writeInt16LE(this._data,0),wt.writeInt32LE(this._data,0),wt.writeInt32LE(this._data,e.localHeaderOffset);const t=wt.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}const _c=Object.freeze(Object.defineProperty({__proto__:null,Gp7Exporter:class extends oc{get name(){return"Guitar Pro 7"}writeScore(e){he.debug(this.name,"Writing data entries");const t=(new cc).writeXml(e),s=Hs.writeForScore(e),i=Ks.writeForScore(e),a=ci.writeForScore(e);he.debug(this.name,"Writing ZIP entries");const r=new Sc(this.data);r.writeEntry(new ni("VERSION",wt.stringToBytes("7.0"))),r.writeEntry(new ni("Content/",new Uint8Array(0))),r.writeEntry(new ni("Content/BinaryStylesheet",s)),r.writeEntry(new ni("Content/PartConfiguration",i)),r.writeEntry(new ni("Content/LayoutConfiguration",a)),r.writeEntry(new ni("Content/score.gpif",wt.stringToBytes(t))),r.end()}},ScoreExporter:oc},Symbol.toStringTag,{value:"Module"}));class wc extends Ct{constructor(){super(0,0,it.EndOfTrack)}writeTo(e){throw new Le(Ee.General,"Deprecated event, serialization not supported")}}var Bc,kc,Tc;!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"}(Bc||(Bc={}));class Nc extends wc{get metaStatus(){return Bc.EndOfTrack}}!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"}(kc||(kc={}));class xc extends wc{}!function(e){e[e.MetronomeTick=0]="MetronomeTick",e[e.Rest=1]="Rest"}(Tc||(Tc={}));class vc extends xc{constructor(){super(...arguments),this.data=new Uint8Array}get isMetronome(){return!1}get metronomeNumerator(){return-1}get metronomeDurationInTicks(){return-1}get metronomeDurationInMilliseconds(){return-1}get isRest(){return!1}get manufacturerId(){return 0}}vc.AlphaTabManufacturerId=125;const Pc=Object.freeze(Object.defineProperty({__proto__:null,AlphaSynthMidiFileHandler:or,AlphaTabMetronomeEvent:Dt,AlphaTabRestEvent:Mt,AlphaTabSysExEvent:Ft,get AlphaTabSystemExclusiveEvents(){return Tc},BeatTickLookup:dr,BeatTickLookupItem:cr,ControlChangeEvent:Rt,get ControllerType(){return Xi},DeprecatedMidiEvent:wc,EndOfTrackEvent:Gt,MasterBarTickLookup:pr,MasterBarTickLookupTempoChange:ur,MetaDataEvent:class extends Nc{constructor(){super(...arguments),this.data=new Uint8Array}},MetaEvent:Nc,get MetaEventType(){return Bc},MetaNumberEvent:class extends Nc{constructor(){super(...arguments),this.value=0}},Midi20PerNotePitchBendEvent:class extends wc{constructor(){super(...arguments),this.noteKey=0,this.pitch=0}},MidiEvent:Ct,get MidiEventType(){return it},MidiFile:Pt,get MidiFileFormat(){return st},MidiFileGenerator:Sr,MidiTickLookup:mr,MidiTickLookupFindBeatResult:gr,get MidiTickLookupFindBeatResultCursorMode(){return Yi},MidiTrack:vt,NoteBendEvent:Vt,NoteEvent:Lt,NoteOffEvent:At,NoteOnEvent:It,PitchBendEvent:Wt,ProgramChangeEvent:Ot,SystemCommonEvent:xc,get SystemCommonType(){return kc},SystemExclusiveEvent:vc,TempoChangeEvent:Ht,TimeSignatureEvent:Et},Symbol.toStringTag,{value:"Module"})),Cc=Object.freeze(Object.defineProperty({__proto__:null,ActiveBeatsChangedEventArgs:Cr,AlphaSynth:sr,AlphaSynthAudioWorkletOutput:Xr,AlphaSynthScriptProcessorOutput:Wr,AlphaSynthWebAudioOutputBase:Hr,AlphaSynthWebWorkerApi:Gr,CircularSampleBuffer:Rr,MidiEventsPlayedEventArgs:er,PlaybackRange:_r,PlaybackRangeChangedEventArgs:tr,get PlayerState(){return Oi},PlayerStateChangedEventArgs:qi,PositionChangedEventArgs:Ki},Symbol.toStringTag,{value:"Module"})),Ec=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{$r as AlphaTabApi,Fr as AlphaTabApiBase,Le as AlphaTabError,Ee as AlphaTabErrorType,oe as ConsoleLogger,ac as CoreSettings,zt as DisplaySettings,ic as Environment,Dr as FileLoadError,v as FingeringMode,Ie as FormatError,Xt as ImporterSettings,e as LayoutMode,E as LogLevel,he as Logger,C as NotationElement,P as NotationMode,re as NotationSettings,nt as PlayerOutputMode,$t as PlayerSettings,Vr as ProgressEventArgs,sc as RenderEngineFactory,Ut as RenderingResources,Pr as ResizeEventArgs,rt as ScrollMode,as as Settings,Yt as SlidePlaybackSettings,t as StaveProfile,at as SystemsLayoutMode,x as TabRhythmMode,Jt as VibratoPlaybackSettings,Me as WebPlatform,_c as exporter,rc as importer,nc as io,Ec as json,ec as meta,Pc as midi,Fs as model,Xe as platform,vi as rendering,Cc as synth};
1
+ var e,t,s,i,a,r,n,o,h,l,c,d,u,p,g,m,f,y,b,S,_,w,B,k,T,N,x,v,P,F,C,D,E,L,M,I,A,R,O,H,W,V,G,z,U,X,J,Y,$,q,K,j,Q,Z,ee,te,se,ie,ae,re;!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 ne{static getValue(e){return ne._values||(ne._values=new Map),e=e.toLowerCase().replaceAll(" ",""),ne._values.has(e)?ne._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}}ne._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]]),function(e){e[e.NoBrackets=0]="NoBrackets",e[e.GroupStaves=1]="GroupStaves",e[e.GroupSimilarInstruments=2]="GroupSimilarInstruments"}(s||(s={})),function(e){e[e.Hidden=0]="Hidden",e[e.FirstSystem=1]="FirstSystem",e[e.AllSystems=2]="AllSystems"}(i||(i={})),function(e){e[e.FullName=0]="FullName",e[e.ShortName=1]="ShortName"}(a||(a={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical"}(r||(r={}));class oe{constructor(){this.hideDynamics=!1,this.bracketExtendMode=s.GroupStaves,this.useSystemSignSeparator=!1,this.globalDisplayTuning=!0,this.perTrackDisplayTuning=null,this.globalDisplayChordDiagramsOnTop=!0,this.perTrackChordDiagramsOnTop=null,this.singleTrackTrackNamePolicy=i.FirstSystem,this.multiTrackTrackNamePolicy=i.FirstSystem,this.firstSystemTrackNameMode=a.ShortName,this.otherSystemsTrackNameMode=a.ShortName,this.firstSystemTrackNameOrientation=r.Vertical,this.otherSystemsTrackNameOrientation=r.Vertical,this.multiTrackMultiBarRest=!1,this.perTrackMultiBarRest=null}}class he{constructor(){this.masterBars=[],this.opening=null,this.closings=[],this.isClosed=!1}get openings(){const e=this.opening;return e?[e]:[]}get isOpened(){return!0===this.opening?.isRepeatStart}addMasterBar(e){null===this.opening&&(this.opening=e),this.masterBars.push(e),e.repeatGroup=this,e.isRepeatEnd&&(this.closings.push(e),this.isClosed=!0)}}class le{constructor(){this.colors=new Map}}!function(e){e[e.Neutral=0]="Neutral",e[e.C3=1]="C3",e[e.C4=2]="C4",e[e.F4=3]="F4",e[e.G2=4]="G2"}(n||(n={})),function(e){e[e._15ma=0]="_15ma",e[e._8va=1]="_8va",e[e.Regular=2]="Regular",e[e._8vb=3]="_8vb",e[e._15mb=4]="_15mb"}(o||(o={})),function(e){e[e.None=0]="None",e[e.Simple=1]="Simple",e[e.FirstOfDouble=2]="FirstOfDouble",e[e.SecondOfDouble=3]="SecondOfDouble"}(h||(h={})),function(e){e[e.Down=0]="Down",e[e.Hold=1]="Hold",e[e.Up=2]="Up"}(l||(l={}));class ce{constructor(){this.ratioPosition=0,this.pedalType=l.Down,this.nextPedalMarker=null,this.previousPedalMarker=null}}!function(e){e[e.StandardNotationRepeats=0]="StandardNotationRepeats",e[e.GuitarTabsRepeats=1]="GuitarTabsRepeats",e[e.SlashRepeats=2]="SlashRepeats",e[e.NumberedRepeats=3]="NumberedRepeats",e[e.StandardNotationBarNumber=4]="StandardNotationBarNumber",e[e.GuitarTabsBarNumber=5]="GuitarTabsBarNumber",e[e.SlashBarNumber=6]="SlashBarNumber",e[e.NumberedBarNumber=7]="NumberedBarNumber",e[e.StandardNotationBarLines=8]="StandardNotationBarLines",e[e.GuitarTabsBarLines=9]="GuitarTabsBarLines",e[e.SlashBarLines=10]="SlashBarLines",e[e.NumberedBarLines=11]="NumberedBarLines",e[e.StandardNotationClef=12]="StandardNotationClef",e[e.GuitarTabsClef=13]="GuitarTabsClef",e[e.StandardNotationKeySignature=14]="StandardNotationKeySignature",e[e.NumberedKeySignature=15]="NumberedKeySignature",e[e.StandardNotationTimeSignature=16]="StandardNotationTimeSignature",e[e.GuitarTabsTimeSignature=17]="GuitarTabsTimeSignature",e[e.SlashTimeSignature=18]="SlashTimeSignature",e[e.NumberedTimeSignature=19]="NumberedTimeSignature",e[e.StandardNotationStaffLine=20]="StandardNotationStaffLine",e[e.GuitarTabsStaffLine=21]="GuitarTabsStaffLine",e[e.SlashStaffLine=22]="SlashStaffLine",e[e.NumberedStaffLine=23]="NumberedStaffLine"}(c||(c={}));class de extends le{}!function(e){e[e.Automatic=0]="Automatic",e[e.Dashed=1]="Dashed",e[e.Dotted=2]="Dotted",e[e.Heavy=3]="Heavy",e[e.HeavyHeavy=4]="HeavyHeavy",e[e.HeavyLight=5]="HeavyLight",e[e.LightHeavy=6]="LightHeavy",e[e.LightLight=7]="LightLight",e[e.None=8]="None",e[e.Regular=9]="Regular",e[e.Short=10]="Short",e[e.Tick=11]="Tick"}(d||(d={}));class ue{constructor(){this.id=ue._globalBarId++,this.index=0,this.nextBar=null,this.previousBar=null,this.clef=n.G2,this.clefOttava=o.Regular,this.voices=[],this.simileMark=h.None,this.isMultiVoice=!1,this.displayScale=1,this.displayWidth=-1,this.sustainPedals=[],this._isEmpty=!0,this._isRestOnly=!0,this.barLineLeft=d.Automatic,this.barLineRight=d.Automatic}static resetIds(){ue._globalBarId=0}get masterBar(){return this.staff.track.score.masterBars[this.index]}get isEmpty(){return this._isEmpty}get isRestOnly(){return this._isRestOnly}getActualBarLineLeft(e){return ue.actualBarLine(this,!1,e)}getActualBarLineRight(){return ue.actualBarLine(this,!0,!1)}static automaticToActualType(e,t,s){let i;return i=t?e.isRepeatEnd?d.LightHeavy:e.nextMasterBar?e.isFreeTime?d.Dashed:e.isDoubleBar?d.LightLight:d.Regular:d.LightHeavy:e.isRepeatStart?d.HeavyLight:s?d.Regular:d.None,i}static actualBarLine(e,t,s){const i=e.masterBar,a=t?e.barLineRight:e.barLineLeft;let r;return r=a===d.Automatic?ue.automaticToActualType(i,t,s):a,r}addVoice(e){e.bar=this,e.index=this.voices.length,this.voices.push(e)}finish(e,t=null){this.isMultiVoice=!1,this._isEmpty=!0,this._isRestOnly=!0;for(let s=0,i=this.voices.length;s<i;s++){const i=this.voices[s];i.finish(e,t),s>0&&!i.isEmpty&&(this.isMultiVoice=!0),i.isEmpty||(this._isEmpty=!1),i.isRestOnly||(this._isRestOnly=!1)}const s=this.sustainPedals;if(s.length>0){let e=null;this.sustainPedals=[],this.previousBar&&this.previousBar.sustainPedals.length>0&&(e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1]);const t=null!==e&&e.pedalType!==l.Up;for(const i of s){if(e&&e.pedalType!==l.Up){if(e.bar===this&&i.ratioPosition<=e.ratioPosition)continue;e.nextPedalMarker=i,i.previousPedalMarker=e}t&&i.pedalType===l.Down&&(i.pedalType=l.Hold),i.bar=this,this.sustainPedals.push(i),e=i}}else if(this.previousBar&&this.previousBar.sustainPedals.length>0){const e=this.previousBar.sustainPedals[this.previousBar.sustainPedals.length-1];if(e.pedalType!==l.Up){const t=new ce;t.ratioPosition=0,t.bar=this,t.pedalType=l.Hold,this.sustainPedals.push(t),e.nextPedalMarker=t,t.previousPedalMarker=e}}}calculateDuration(){let e=0;for(const t of this.voices){const s=t.calculateDuration();s>e&&(e=s)}return e}}ue._globalBarId=0,function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heavy=2]="Heavy",e[e.Tenuto=3]="Tenuto"}(u||(u={})),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"}(p||(p={})),function(e){e[e.Tempo=0]="Tempo",e[e.Volume=1]="Volume",e[e.Instrument=2]="Instrument",e[e.Balance=3]="Balance"}(g||(g={}));class pe{constructor(){this.isLinear=!1,this.type=g.Tempo,this.value=0,this.ratioPosition=0,this.text=""}static buildTempoAutomation(e,t,s,i){(i<1||i>5)&&(i=2);const a=new Float32Array([1,.5,1,1.5,2,3]),r=new pe;return r.type=g.Tempo,r.isLinear=e,r.ratioPosition=t,r.value=s*a[i],r}static buildInstrumentAutomation(e,t,s){const i=new pe;return i.type=g.Instrument,i.isLinear=e,i.ratioPosition=t,i.value=s,i}}!function(e){e[e.None=0]="None",e[e.Full=1]="Full",e[e.Half=2]="Half"}(m||(m={}));class ge{constructor(e=0,t=0){this.offset=e,this.value=t}}ge.MaxPosition=60,ge.MaxValue=12,function(e){e[e.Default=0]="Default",e[e.Gradual=1]="Gradual",e[e.Fast=2]="Fast"}(f||(f={})),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"}(y||(y={})),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"}(b||(b={}));class me{constructor(){this.name="",this.firstFret=1,this.strings=[],this.barreFrets=[],this.showName=!0,this.showDiagram=!0,this.showFingering=!0}get uniqueId(){return[this.name,this.firstFret.toString(),this.strings.join(","),this.barreFrets.join(","),this.showDiagram.toString(),this.showFingering.toString(),this.showName.toString()].join("|")}}!function(e){e[e.General=0]="General",e[e.Format=1]="Format",e[e.AlphaTex=2]="AlphaTex"}(S||(S={}));class fe extends Error{constructor(e,t="",s){super(t??"",{cause:s}),this.type=e,Object.setPrototypeOf(this,fe.prototype)}}class ye extends fe{constructor(e){super(S.Format,e),Object.setPrototypeOf(this,ye.prototype)}}!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"}(_||(_={})),function(e){e[e.Hidden=0]="Hidden",e[e.ShowWithBeams=1]="ShowWithBeams",e[e.ShowWithBars=2]="ShowWithBars",e[e.Automatic=3]="Automatic"}(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"}(k||(k={})),function(e){e[e.ScoreTitle=0]="ScoreTitle",e[e.ScoreSubTitle=1]="ScoreSubTitle",e[e.ScoreArtist=2]="ScoreArtist",e[e.ScoreAlbum=3]="ScoreAlbum",e[e.ScoreWords=4]="ScoreWords",e[e.ScoreMusic=5]="ScoreMusic",e[e.ScoreWordsAndMusic=6]="ScoreWordsAndMusic",e[e.ScoreCopyright=7]="ScoreCopyright",e[e.GuitarTuning=8]="GuitarTuning",e[e.TrackNames=9]="TrackNames",e[e.ChordDiagrams=10]="ChordDiagrams",e[e.ParenthesisOnTiedBends=11]="ParenthesisOnTiedBends",e[e.TabNotesOnTiedBends=12]="TabNotesOnTiedBends",e[e.ZerosOnDiveWhammys=13]="ZerosOnDiveWhammys",e[e.EffectAlternateEndings=14]="EffectAlternateEndings",e[e.EffectCapo=15]="EffectCapo",e[e.EffectChordNames=16]="EffectChordNames",e[e.EffectCrescendo=17]="EffectCrescendo",e[e.EffectDynamics=18]="EffectDynamics",e[e.EffectFadeIn=19]="EffectFadeIn",e[e.EffectFermata=20]="EffectFermata",e[e.EffectFingering=21]="EffectFingering",e[e.EffectHarmonics=22]="EffectHarmonics",e[e.EffectLetRing=23]="EffectLetRing",e[e.EffectLyrics=24]="EffectLyrics",e[e.EffectMarker=25]="EffectMarker",e[e.EffectOttavia=26]="EffectOttavia",e[e.EffectPalmMute=27]="EffectPalmMute",e[e.EffectPickSlide=28]="EffectPickSlide",e[e.EffectPickStroke=29]="EffectPickStroke",e[e.EffectSlightBeatVibrato=30]="EffectSlightBeatVibrato",e[e.EffectSlightNoteVibrato=31]="EffectSlightNoteVibrato",e[e.EffectTap=32]="EffectTap",e[e.EffectTempo=33]="EffectTempo",e[e.EffectText=34]="EffectText",e[e.EffectTrill=35]="EffectTrill",e[e.EffectTripletFeel=36]="EffectTripletFeel",e[e.EffectWhammyBar=37]="EffectWhammyBar",e[e.EffectWideBeatVibrato=38]="EffectWideBeatVibrato",e[e.EffectWideNoteVibrato=39]="EffectWideNoteVibrato",e[e.EffectLeftHandTap=40]="EffectLeftHandTap",e[e.EffectFreeTime=41]="EffectFreeTime",e[e.EffectSustainPedal=42]="EffectSustainPedal",e[e.EffectGolpe=43]="EffectGolpe",e[e.EffectWahPedal=44]="EffectWahPedal",e[e.EffectBeatBarre=45]="EffectBeatBarre",e[e.EffectNoteOrnament=46]="EffectNoteOrnament",e[e.EffectRasgueado=47]="EffectRasgueado",e[e.EffectDirections=48]="EffectDirections",e[e.EffectBeatTimer=49]="EffectBeatTimer"}(T||(T={}));class be{constructor(){this.notationMode=k.GuitarPro,this.fingeringMode=B.ScoreDefault,this.elements=new Map,this.rhythmMode=w.Automatic,this.rhythmHeight=15,this.transpositionPitches=[],this.displayTranspositionPitches=[],this.smallGraceTabNotes=!0,this.extendBendArrowsOnTiedNotes=!0,this.extendLineEffectsToBeatEnd=!1,this.slurHeight=5}isNotationElementVisible(e){return this.elements.has(e)?this.elements.get(e):!be.defaultElements.has(e)||be.defaultElements.get(e)}}be.defaultElements=new Map([[T.ZerosOnDiveWhammys,!1]]),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"}(N||(N={})),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"}(x||(x={})),function(e){e[e.Major=0]="Major",e[e.Minor=1]="Minor"}(v||(v={})),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"}(P||(P={}));class Se{constructor(){this.alternateEndings=0,this.nextMasterBar=null,this.previousMasterBar=null,this.index=0,this.keySignature=x.C,this.keySignatureType=v.Major,this.isDoubleBar=!1,this.isRepeatStart=!1,this.repeatCount=0,this.timeSignatureNumerator=4,this.timeSignatureDenominator=4,this.timeSignatureCommon=!1,this.isFreeTime=!1,this.tripletFeel=P.NoTripletFeel,this.section=null,this.tempoAutomations=[],this.fermata=null,this.start=0,this.isAnacrusis=!1,this.displayScale=1,this.displayWidth=-1,this.directions=null}get isRepeatEnd(){return this.repeatCount>0}get isSectionStart(){return!!this.section}get tempoAutomation(){return this.tempoAutomations.length>0?this.tempoAutomations[0]:null}calculateDuration(e=!0){if(this.isAnacrusis&&e){let e=0;for(const t of this.score.tracks)for(const s of t.staves){const t=this.index<s.bars.length?s.bars[this.index].calculateDuration():0;t>e&&(e=t)}return e}return this.timeSignatureNumerator*rs.valueToTicks(this.timeSignatureDenominator)}addFermata(e,t){let s=this.fermata;null===s&&(s=new Map,this.fermata=s),s.set(e,t)}addDirection(e){null==this.directions&&(this.directions=new Set),this.directions.add(e)}getFermata(e){const t=this.fermata;return null===t?null:t.has(e.playbackStart)?t.get(e.playbackStart):null}}Se.MaxAlternateEndings=8;class _e{constructor(){this.note=null,this.tone=new we,this.octave=0}get realValue(){return 12*this.octave+this.tone.noteValue}}class we{constructor(e=0,t=N.Default){this.noteValue=e,this.accidentalMode=t}}class Be{static getIndex(e){return e<0?0:0|Math.log2(e)}static keySignatureIsFlat(e){return e<0}static keySignatureIsNatural(e){return 0===e}static keySignatureIsSharp(e){return e>0}static applyPitchOffsets(e,t){for(let s=0;s<t.tracks.length;s++){if(s<e.notation.displayTranspositionPitches.length)for(const i of t.tracks[s].staves)i.displayTranspositionPitch=-e.notation.displayTranspositionPitches[s];if(s<e.notation.transpositionPitches.length)for(const i of t.tracks[s].staves)i.transpositionPitch=-e.notation.transpositionPitches[s]}}static fingerToString(e,t,s,i){if(e.notation.fingeringMode===B.ScoreForcePiano||e.notation.fingeringMode===B.SingleNoteEffectBandForcePiano||ne.isPiano(t.voice.bar.staff.track.playbackInfo.program))switch(s){case _.Unknown:case _.NoOrDead:return null;case _.Thumb:return"1";case _.IndexFinger:return"2";case _.MiddleFinger:return"3";case _.AnnularFinger:return"4";case _.LittleFinger:return"5";default:return null}if(i)switch(s){case _.Unknown:return null;case _.NoOrDead:return"0";case _.Thumb:return"t";case _.IndexFinger:return"1";case _.MiddleFinger:return"2";case _.AnnularFinger:return"3";case _.LittleFinger:return"4";default:return null}switch(s){case _.Unknown:case _.NoOrDead:return null;case _.Thumb:return"p";case _.IndexFinger:return"i";case _.MiddleFinger:return"m";case _.AnnularFinger:return"a";case _.LittleFinger:return"c";default:return null}}static isTuning(e){return!!Be.parseTuning(e)}static parseTuning(e){let t="",s="";for(let i=0;i<e.length;i++){const a=e.charCodeAt(i);if(a>=48&&a<=57){if(!t)return null;s+=String.fromCharCode(a)}else{if(!Be.TuningLetters.has(a))return null;t+=String.fromCharCode(a)}}if(!s||!t)return null;const i=new _e;return i.octave=Number.parseInt(s)+1,i.note=t.toLowerCase(),i.tone=Be.getToneForText(i.note),i.tone.noteValue<0&&(i.octave--,i.tone.noteValue+=12),i}static getTuningForText(e){const t=Be.parseTuning(e);return t?t.realValue:-1}static getToneForText(e){const t=e.substring(0,1),s=e.substring(1);let i,a;switch(t.toLowerCase()){case"c":default:i=0;break;case"d":i=2;break;case"e":i=4;break;case"f":i=5;break;case"g":i=7;break;case"a":i=9;break;case"b":i=11}switch(a=Be.parseAccidentalMode(s),a){case N.Default:case N.ForceNone:case N.ForceNatural:break;case N.ForceSharp:i++;break;case N.ForceDoubleSharp:i+=2;break;case N.ForceFlat:i--;break;case N.ForceDoubleFlat:i-=2}return new we(i,a)}static parseAccidentalMode(e){const t=e.toLowerCase();return Be.accidentalModeMapping.has(t)?Be.accidentalModeMapping.get(t):N.Default}static newGuid(){return`${Math.floor(65536*(1+Math.random())).toString(16).substring(1)+Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}-${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}${Math.floor(65536*(1+Math.random())).toString(16).substring(1)}`}static isAlmostEqualTo(e,t){return Math.abs(e-t)<1e-5}static toHexString(e,t=0){let s="";do{s=String.fromCharCode("0123456789ABCDEF".charCodeAt(15&e))+s,e>>=4}while(e>0);for(;s.length<t;)s=`0${s}`;return s}static getAlternateEndingsList(e){const t=[];for(let s=0;s<Se.MaxAlternateEndings;s++)e&1<<s&&t.push(s);return t}static deltaFretToHarmonicValue(e){switch(e){case 2:return 2.4;case 3:return 3.2;case 4:case 5:case 7:case 9:case 12:case 16:case 17:case 19:case 24:return e;case 8:return 8.2;case 10:return 9.6;case 14:case 15:return 14.7;case 21:case 22:return 21.7;default:return 12}}static clamp(e,t,s){return e<=t?t:e>=s?s:e}static buildMultiBarRestInfo(e,t,s){if(!e)return null;const i=e[0].score.stylesheet;if(!(e.length>1?i.multiTrackMultiBarRest:!0===i.perTrackMultiBarRest?.has(e[0].index)))return null;const a=new Map,r=e[0].score;let n=t;for(;n<=s;){const i=n;let o=null;for(;n<=s;){const s=r.masterBars[n];if(s.alternateEndings||s.isRepeatStart&&s.index!==i||s.isFreeTime||s.isAnacrusis||null!==s.section||s.index!==i&&s.tempoAutomations.length>0||null!==s.fermata&&s.fermata.size>0||null!==s.directions&&s.directions.size>0)break;if(i>t&&s.previousMasterBar&&(s.timeSignatureCommon!==s.previousMasterBar.timeSignatureCommon||s.timeSignatureNumerator!==s.previousMasterBar.timeSignatureNumerator||s.timeSignatureDenominator!==s.previousMasterBar.timeSignatureDenominator||s.tripletFeel!==s.previousMasterBar.tripletFeel||s.keySignature!==s.previousMasterBar.keySignature||s.keySignatureType!==s.previousMasterBar.keySignatureType))break;let a=!0;for(const t of e){for(const e of t.staves){if(!e.bars[s.index].isRestOnly){a=!1;break}}if(!a)break}if(!a)break;if(n++,s.index>i&&(null===o?o=[s.index]:o.push(s.index)),s.isRepeatEnd)break}o?a.set(i,o):n++}return a}static computeFirstDisplayedBarIndex(e,t){let s=t.display.startBar;return s--,s=Math.min(e.masterBars.length-1,Math.max(0,s)),s}static computeLastDisplayedBarIndex(e,t,s){let i=t.display.barCount;return i<0&&(i=e.masterBars.length),i=s+i-1,i=Math.min(e.masterBars.length-1,Math.max(0,i)),i}static getOrCreateHeaderFooterStyle(e,t){let s,i=e.style;if(e.style||(i=new Fs,e.style=i),i.headerAndFooter.has(t))s=i.headerAndFooter.get(t);else{if(s=new Ps,Fs.defaultHeaderAndFooter.has(t)){const e=Fs.defaultHeaderAndFooter.get(t);s.template=e.template,s.textAlign=e.textAlign}i.headerAndFooter.set(t,s)}return s}}Be.TuningLetters=new Set([67,68,69,70,71,65,66,99,100,101,102,103,97,98,35]),Be.accidentalModeMapping=new Map([["default",N.Default],["d",N.Default],["forcenone",N.ForceNone],["-",N.ForceNone],["forcenatural",N.ForceNatural],["n",N.ForceNatural],["forcesharp",N.ForceSharp],["#",N.ForceSharp],["forcedoublesharp",N.ForceDoubleSharp],["##",N.ForceDoubleSharp],["x",N.ForceDoubleSharp],["forceflat",N.ForceFlat],["b",N.ForceFlat],["forcedoubleflat",N.ForceDoubleFlat],["bb",N.ForceDoubleFlat]]);class ke{constructor(e,t,s,i=255){this.raw=0,this.raw=(255&i)<<24|(255&e)<<16|(255&t)<<8|255&s,this.updateRgba()}updateRgba(){255===this.a?this.rgba=`#${Be.toHexString(this.r,2)}${Be.toHexString(this.g,2)}${Be.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 ke(255*Math.random()|0,255*Math.random()|0,255*Math.random()|0,e)}static fromJson(e){if(e instanceof ke)return e;switch(typeof e){case"number":{const t=new ke(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 ke(17*Number.parseInt(t[1],16),17*Number.parseInt(t[2],16),17*Number.parseInt(t[3],16));if(5===t.length)return new ke(17*Number.parseInt(t[1],16),17*Number.parseInt(t[2],16),17*Number.parseInt(t[3],16),17*Number.parseInt(t[4],16));if(7===t.length)return new ke(Number.parseInt(t.substring(1,3),16),Number.parseInt(t.substring(3,5),16),Number.parseInt(t.substring(5,7),16));if(9===t.length)return new ke(Number.parseInt(t.substring(1,3),16),Number.parseInt(t.substring(3,5),16),Number.parseInt(t.substring(5,7),16),Number.parseInt(t.substring(7,9),16))}else if(t.startsWith("rgba")||t.startsWith("rgb")){const e=t.indexOf("("),s=t.lastIndexOf(")");if(-1===e||-1===s)throw new ye("No values specified for rgb/rgba function");const i=t.substring(e+1,s).split(",");if(3===i.length)return new ke(Number.parseInt(i[0]),Number.parseInt(i[1]),Number.parseInt(i[2]));if(4===i.length)return new ke(Number.parseInt(i[0]),Number.parseInt(i[1]),Number.parseInt(i[2]),255*Number.parseFloat(i[3]))}return null}}throw new ye("Unsupported format for color")}static toJson(e){return null===e?null:e.raw}}ke.BlackRgb="#000000",function(e){e[e.None=0]="None",e[e.Crescendo=1]="Crescendo",e[e.Decrescendo=2]="Decrescendo"}(F||(F={})),function(e){e[e.TargetFine=0]="TargetFine",e[e.TargetSegno=1]="TargetSegno",e[e.TargetSegnoSegno=2]="TargetSegnoSegno",e[e.TargetCoda=3]="TargetCoda",e[e.TargetDoubleCoda=4]="TargetDoubleCoda",e[e.JumpDaCapo=5]="JumpDaCapo",e[e.JumpDaCapoAlCoda=6]="JumpDaCapoAlCoda",e[e.JumpDaCapoAlDoubleCoda=7]="JumpDaCapoAlDoubleCoda",e[e.JumpDaCapoAlFine=8]="JumpDaCapoAlFine",e[e.JumpDalSegno=9]="JumpDalSegno",e[e.JumpDalSegnoAlCoda=10]="JumpDalSegnoAlCoda",e[e.JumpDalSegnoAlDoubleCoda=11]="JumpDalSegnoAlDoubleCoda",e[e.JumpDalSegnoAlFine=12]="JumpDalSegnoAlFine",e[e.JumpDalSegnoSegno=13]="JumpDalSegnoSegno",e[e.JumpDalSegnoSegnoAlCoda=14]="JumpDalSegnoSegnoAlCoda",e[e.JumpDalSegnoSegnoAlDoubleCoda=15]="JumpDalSegnoSegnoAlDoubleCoda",e[e.JumpDalSegnoSegnoAlFine=16]="JumpDalSegnoSegnoAlFine",e[e.JumpDaCoda=17]="JumpDaCoda",e[e.JumpDaDoubleCoda=18]="JumpDaDoubleCoda"}(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"}(D||(D={})),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",e[e.PPPP=8]="PPPP",e[e.PPPPP=9]="PPPPP",e[e.PPPPPP=10]="PPPPPP",e[e.FFFF=11]="FFFF",e[e.FFFFF=12]="FFFFF",e[e.FFFFFF=13]="FFFFFF",e[e.SF=14]="SF",e[e.SFP=15]="SFP",e[e.SFPP=16]="SFPP",e[e.FP=17]="FP",e[e.RF=18]="RF",e[e.RFZ=19]="RFZ",e[e.SFZ=20]="SFZ",e[e.SFFZ=21]="SFFZ",e[e.FZ=22]="FZ",e[e.N=23]="N",e[e.PF=24]="PF",e[e.SFZP=25]="SFZP"}(E||(E={})),function(e){e[e.None=0]="None",e[e.FadeIn=1]="FadeIn",e[e.FadeOut=2]="FadeOut",e[e.VolumeSwell=3]="VolumeSwell"}(L||(L={})),function(e){e[e.Short=0]="Short",e[e.Medium=1]="Medium",e[e.Long=2]="Long"}(M||(M={}));class Te{constructor(){this.type=M.Short,this.length=0}}class Ne{static parseEnum(e,t){switch(typeof e){case"string":const s=Number.parseInt(e);return Number.isNaN(s)?t[Object.keys(t).find((t=>t.toLowerCase()===e.toLowerCase()))]:s;case"number":return e;case"undefined":case"object":return}throw new fe(S.Format,`Could not parse enum value '${e}'`)}static forEach(e,t){if(e instanceof Map)e.forEach(t);else if("object"==typeof e)for(const s in e)t(e[s],s)}static getValue(e,t){return e instanceof Map?e.get(t):"object"==typeof e?e[t]:null}}class xe{constructor(e,t,s){this.text=e,this.startPos=t,this.endPos=s}}class ve{constructor(e){this.style="normal",this.variant="normal",this.weight="normal",this.stretch="normal",this.lineHeight="normal",this.size="1rem",this.families=[],this.parseOnlyFamilies=!1,this._currentTokenIndex=-1,this._input="",this._currentToken=null,this._input=e,this._tokens=this.splitToTokens(e)}splitToTokens(e){const t=[];let s=0;for(;s<e.length;){let i=s;for(;i<e.length&&" "!==e.charAt(i);)i++;i>s&&t.push(new xe(e.substring(s,i),s,i)),s=i+1}return t}parse(){if(this.reset(),1===this._tokens.length)switch(this._currentToken?.text){case"caption":case"icon":case"menu":case"message-box":case"small-caption":case"status-bar":case"inherit":return}this.parseOnlyFamilies||(this.fontStyleVariantWeight(),this.fontSizeLineHeight()),this.fontFamily()}static parseFamilies(e){const t=new ve(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;){const s=e.charAt(t);if(" "===s||","===s)t++;else if('"'===s||"'"===s){const i=this.findEndOfQuote(e,t+1,s);this.families.push(e.substring(t+1,i).split(`\\${s}`).join(s)),t=i+1}else{const s=this.findEndOfQuote(e,t+1,",");this.families.push(e.substring(t,s).trim()),t=s+1}}}findEndOfQuote(e,t,s){let i=!1;for(;t<e.length;){const a=e.charAt(t);if(!i&&a===s)return t;i=!i&&"\\"===a,t+=1}return e.length}fontSizeLineHeight(){if(!this._currentToken)throw new Error("Missing font size");const e=this._currentToken.text.split("/");if(e.length>=3)throw new Error(`Invalid font size '${this._currentToken}' specified`);if(this.nextToken(),e.length>=2)if("/"===e[1]){if(!this._currentToken)throw new Error("Missing line-height after font size");this.lineHeight=this._currentToken.text,this.nextToken()}else this.size=e[0],this.lineHeight=e[1];else{if(!(e.length>=1))throw new Error("Missing font size");if(this.size=e[0],this._currentToken&&0===this._currentToken.text.indexOf("/"))if("/"===this._currentToken.text){if(this.nextToken(),!this._currentToken)throw new Error("Missing line-height after font size");this.lineHeight=this._currentToken.text,this.nextToken()}else this.lineHeight=this._currentToken.text.substr(1),this.nextToken()}}nextToken(){this._currentTokenIndex++,this._currentTokenIndex<this._tokens.length?this._currentToken=this._tokens[this._currentTokenIndex]:this._currentToken=null}fontStyleVariantWeight(){let e=!1,t=!1,s=!1,i=3;const a=[];for(;;){if(!this._currentToken)return;const r=this._currentToken.text;switch(r){case"normal":case"inherit":a.push(r),i--,this.nextToken();break;case"italic":case"oblique":this.style=r,e=!0,i--,this.nextToken();break;case"small-caps":this.variant=r,t=!0,i--,this.nextToken();break;case"bold":case"bolder":case"lighter":case"100":case"200":case"300":case"400":case"500":case"600":case"700":case"800":case"900":this.weight=r,s=!0,i--,this.nextToken();break;default:return}if(0===i)break}for(;a.length>0;){const i=a.pop();s?t?e||(this.style=i):this.variant=i:this.weight=i}}reset(){this._currentTokenIndex=-1,this.nextToken()}static quoteFont(e){if(-1===e.indexOf(" "))return e;return`"${e.replaceAll('"','\\"')}"`}}!function(e){e[e.Plain=0]="Plain",e[e.Italic=1]="Italic"}(I||(I={})),function(e){e[e.Regular=0]="Regular",e[e.Bold=1]="Bold"}(A||(A={}));class Pe{reset(){this._cssScale=0,this._css=this.toCssString()}get family(){return this._families[0]}set family(e){this.families=ve.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===A.Bold}get isItalic(){return this.style===I.Italic}constructor(e,t,s=I.Plain,i=A.Regular){this._cssScale=0,this._families=ve.parseFamilies(e),this._size=t,this._style=s,this._weight=i,this._css=this.toCssString()}withSize(e){return Pe.withFamilyList(this._families,e,this._style,this._weight)}static withFamilyList(e,t,s=I.Plain,i=A.Regular){const a=new Pe("",t,s,i);return a.families=e,a}toCssString(e=1){if(!(this._css&&Math.abs(e-this._cssScale)<.01)){let t="";this.isBold&&(t+="bold "),this.isItalic&&(t+="italic "),t+=this.size*e,t+="px ",t+=this.families.map((e=>ve.quoteFont(e))).join(", "),this._css=t,this._cssScale=e}return this._css}static fromJson(e){if(e instanceof Pe)return e;switch(typeof e){case"undefined":default:return null;case"object":{const t=e,s=t.get("families"),i=t.get("size"),a=Ne.parseEnum(t.get("style"),I),r=Ne.parseEnum(t.get("weight"),A);return Pe.withFamilyList(s,i,a,r)}case"string":{const t=new ve(e);t.parse();const s=t.families,i=t.size.toLowerCase();let a=0;switch(i){case"xx-small":a=7;break;case"x-small":a=10;break;case"small":case"smaller":a=13;break;case"medium":a=16;break;case"large":case"larger":a=18;break;case"x-large":a=24;break;case"xx-large":a=32;break;default:try{a=i.endsWith("em")?16*Number.parseFloat(i.substr(0,i.length-2)):i.endsWith("pt")?16*Number.parseFloat(i.substr(0,i.length-2))/12:i.endsWith("px")?Number.parseFloat(i.substr(0,i.length-2)):12}catch(e){a=12}}let r=I.Plain;"italic"===t.style&&(r=I.Italic);let n=A.Regular;switch(t.weight.toLowerCase()){case"normal":case"lighter":break;default:n=A.Bold}return Pe.withFamilyList(s,a,r,n)}}}static toJson(e){const t=new Map;return t.set("families",e.families),t.set("size",e.size),t.set("style",e.style),t.set("weight",e.weight),t}}!function(e){e[e.None=0]="None",e[e.OnBeat=1]="OnBeat",e[e.BeforeBeat=2]="BeforeBeat",e[e.BendGrace=3]="BendGrace"}(R||(R={}));class Fe{constructor(){this.beats=[],this.id="empty",this.isComplete=!1}addBeat(e){e.graceIndex=this.beats.length,e.graceGroup=this,this.beats.push(e)}finish(){this.beats.length>0&&(this.id=`${this.beats[0].absoluteDisplayStart}_${this.beats[0].voice.index}`)}}!function(e){e[e.None=0]="None",e[e.Thumb=1]="Thumb",e[e.Finger=2]="Finger"}(O||(O={})),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"}(H||(H={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(W||(W={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(V||(V={}));class Ce{constructor(e,t){this.width=e,this.height=t}}!function(e){e[e.None=-1]="None",e[e.Space=32]="Space",e[e.Brace=57344]="Brace",e[e.BracketTop=57347]="BracketTop",e[e.BracketBottom=57348]="BracketBottom",e[e.SystemDivider=57351]="SystemDivider",e[e.GClef=57424]="GClef",e[e.CClef=57436]="CClef",e[e.FClef=57442]="FClef",e[e.UnpitchedPercussionClef1=57449]="UnpitchedPercussionClef1",e[e.SixStringTabClef=57453]="SixStringTabClef",e[e.FourStringTabClef=57454]="FourStringTabClef",e[e.TimeSig0=57472]="TimeSig0",e[e.TimeSig1=57473]="TimeSig1",e[e.TimeSig2=57474]="TimeSig2",e[e.TimeSig3=57475]="TimeSig3",e[e.TimeSig4=57476]="TimeSig4",e[e.TimeSig5=57477]="TimeSig5",e[e.TimeSig6=57478]="TimeSig6",e[e.TimeSig7=57479]="TimeSig7",e[e.TimeSig8=57480]="TimeSig8",e[e.TimeSig9=57481]="TimeSig9",e[e.TimeSigCommon=57482]="TimeSigCommon",e[e.TimeSigCutCommon=57483]="TimeSigCutCommon",e[e.NoteheadDoubleWholeSquare=57505]="NoteheadDoubleWholeSquare",e[e.NoteheadDoubleWhole=57504]="NoteheadDoubleWhole",e[e.NoteheadWhole=57506]="NoteheadWhole",e[e.NoteheadHalf=57507]="NoteheadHalf",e[e.NoteheadBlack=57508]="NoteheadBlack",e[e.NoteheadNull=57509]="NoteheadNull",e[e.NoteheadXOrnate=57514]="NoteheadXOrnate",e[e.NoteheadPlusDoubleWhole=57516]="NoteheadPlusDoubleWhole",e[e.NoteheadPlusWhole=57517]="NoteheadPlusWhole",e[e.NoteheadPlusHalf=57518]="NoteheadPlusHalf",e[e.NoteheadPlusBlack=57519]="NoteheadPlusBlack",e[e.NoteheadSquareWhite=57528]="NoteheadSquareWhite",e[e.NoteheadSquareBlack=57529]="NoteheadSquareBlack",e[e.NoteheadTriangleUpDoubleWhole=57530]="NoteheadTriangleUpDoubleWhole",e[e.NoteheadTriangleUpWhole=57531]="NoteheadTriangleUpWhole",e[e.NoteheadTriangleUpHalf=57532]="NoteheadTriangleUpHalf",e[e.NoteheadTriangleUpBlack=57534]="NoteheadTriangleUpBlack",e[e.NoteheadTriangleRightWhite=57537]="NoteheadTriangleRightWhite",e[e.NoteheadTriangleRightBlack=57538]="NoteheadTriangleRightBlack",e[e.NoteheadTriangleDownDoubleWhole=57548]="NoteheadTriangleDownDoubleWhole",e[e.NoteheadTriangleDownWhole=57540]="NoteheadTriangleDownWhole",e[e.NoteheadTriangleDownHalf=57541]="NoteheadTriangleDownHalf",e[e.NoteheadTriangleDownBlack=57543]="NoteheadTriangleDownBlack",e[e.NoteheadDiamondDoubleWhole=57559]="NoteheadDiamondDoubleWhole",e[e.NoteheadDiamondWhole=57560]="NoteheadDiamondWhole",e[e.NoteheadDiamondHalf=57561]="NoteheadDiamondHalf",e[e.NoteheadDiamondBlack=57563]="NoteheadDiamondBlack",e[e.NoteheadDiamondBlackWide=57564]="NoteheadDiamondBlackWide",e[e.NoteheadDiamondWhite=57565]="NoteheadDiamondWhite",e[e.NoteheadDiamondWhiteWide=57566]="NoteheadDiamondWhiteWide",e[e.NoteheadCircleXDoubleWhole=57520]="NoteheadCircleXDoubleWhole",e[e.NoteheadCircleXWhole=57521]="NoteheadCircleXWhole",e[e.NoteheadCircleXHalf=57522]="NoteheadCircleXHalf",e[e.NoteheadCircleX=57523]="NoteheadCircleX",e[e.NoteheadXDoubleWhole=57510]="NoteheadXDoubleWhole",e[e.NoteheadXWhole=57511]="NoteheadXWhole",e[e.NoteheadXHalf=57512]="NoteheadXHalf",e[e.NoteheadXBlack=57513]="NoteheadXBlack",e[e.NoteheadParenthesis=57550]="NoteheadParenthesis",e[e.NoteheadSlashedBlack1=57551]="NoteheadSlashedBlack1",e[e.NoteheadSlashedBlack2=57552]="NoteheadSlashedBlack2",e[e.NoteheadSlashedHalf1=57553]="NoteheadSlashedHalf1",e[e.NoteheadSlashedHalf2=57554]="NoteheadSlashedHalf2",e[e.NoteheadSlashedWhole1=57555]="NoteheadSlashedWhole1",e[e.NoteheadSlashedWhole2=57556]="NoteheadSlashedWhole2",e[e.NoteheadSlashedDoubleWhole1=57557]="NoteheadSlashedDoubleWhole1",e[e.NoteheadSlashedDoubleWhole2=57558]="NoteheadSlashedDoubleWhole2",e[e.NoteheadCircledBlack=57572]="NoteheadCircledBlack",e[e.NoteheadCircledHalf=57573]="NoteheadCircledHalf",e[e.NoteheadCircledWhole=57574]="NoteheadCircledWhole",e[e.NoteheadCircledDoubleWhole=57575]="NoteheadCircledDoubleWhole",e[e.NoteheadCircleSlash=57591]="NoteheadCircleSlash",e[e.NoteheadHeavyX=57592]="NoteheadHeavyX",e[e.NoteheadHeavyXHat=57593]="NoteheadHeavyXHat",e[e.NoteheadSlashVerticalEnds=57600]="NoteheadSlashVerticalEnds",e[e.NoteheadSlashWhiteWhole=57602]="NoteheadSlashWhiteWhole",e[e.NoteheadSlashWhiteHalf=57603]="NoteheadSlashWhiteHalf",e[e.NoteheadRoundWhiteWithDot=57621]="NoteheadRoundWhiteWithDot",e[e.NoteheadSquareBlackLarge=57626]="NoteheadSquareBlackLarge",e[e.NoteheadSquareBlackWhite=57627]="NoteheadSquareBlackWhite",e[e.NoteheadClusterDoubleWhole3rd=57640]="NoteheadClusterDoubleWhole3rd",e[e.NoteheadClusterWhole3rd=57641]="NoteheadClusterWhole3rd",e[e.NoteheadClusterHalf3rd=57642]="NoteheadClusterHalf3rd",e[e.NoteheadClusterQuarter3rd=57643]="NoteheadClusterQuarter3rd",e[e.NoteShapeRoundWhite=57776]="NoteShapeRoundWhite",e[e.NoteShapeRoundBlack=57777]="NoteShapeRoundBlack",e[e.NoteShapeSquareWhite=57778]="NoteShapeSquareWhite",e[e.NoteShapeSquareBlack=57779]="NoteShapeSquareBlack",e[e.NoteShapeTriangleRightWhite=57780]="NoteShapeTriangleRightWhite",e[e.NoteShapeTriangleRightBlack=57781]="NoteShapeTriangleRightBlack",e[e.NoteShapeTriangleLeftWhite=57782]="NoteShapeTriangleLeftWhite",e[e.NoteShapeTriangleLeftBlack=57783]="NoteShapeTriangleLeftBlack",e[e.NoteShapeDiamondWhite=57784]="NoteShapeDiamondWhite",e[e.NoteShapeDiamondBlack=57785]="NoteShapeDiamondBlack",e[e.NoteShapeTriangleUpWhite=57786]="NoteShapeTriangleUpWhite",e[e.NoteShapeTriangleUpBlack=57787]="NoteShapeTriangleUpBlack",e[e.NoteShapeMoonWhite=57788]="NoteShapeMoonWhite",e[e.NoteShapeMoonBlack=57789]="NoteShapeMoonBlack",e[e.NoteShapeTriangleRoundWhite=57790]="NoteShapeTriangleRoundWhite",e[e.NoteShapeTriangleRoundBlack=57791]="NoteShapeTriangleRoundBlack",e[e.NoteQuarterUp=57813]="NoteQuarterUp",e[e.NoteEighthUp=57815]="NoteEighthUp",e[e.TextBlackNoteLongStem=57841]="TextBlackNoteLongStem",e[e.TextBlackNoteFrac8thLongStem=57843]="TextBlackNoteFrac8thLongStem",e[e.TextBlackNoteFrac16thLongStem=57845]="TextBlackNoteFrac16thLongStem",e[e.TextBlackNoteFrac32ndLongStem=57846]="TextBlackNoteFrac32ndLongStem",e[e.TextCont8thBeamLongStem=57848]="TextCont8thBeamLongStem",e[e.TextCont16thBeamLongStem=57850]="TextCont16thBeamLongStem",e[e.TextCont32ndBeamLongStem=57851]="TextCont32ndBeamLongStem",e[e.TextAugmentationDot=57852]="TextAugmentationDot",e[e.TextTupletBracketStartLongStem=57857]="TextTupletBracketStartLongStem",e[e.TextTuplet3LongStem=57858]="TextTuplet3LongStem",e[e.TextTupletBracketEndLongStem=57859]="TextTupletBracketEndLongStem",e[e.Tremolo3=57890]="Tremolo3",e[e.Tremolo2=57889]="Tremolo2",e[e.Tremolo1=57888]="Tremolo1",e[e.FlagEighthUp=57920]="FlagEighthUp",e[e.FlagEighthDown=57921]="FlagEighthDown",e[e.FlagSixteenthUp=57922]="FlagSixteenthUp",e[e.FlagSixteenthDown=57923]="FlagSixteenthDown",e[e.FlagThirtySecondUp=57924]="FlagThirtySecondUp",e[e.FlagThirtySecondDown=57925]="FlagThirtySecondDown",e[e.FlagSixtyFourthUp=57926]="FlagSixtyFourthUp",e[e.FlagSixtyFourthDown=57927]="FlagSixtyFourthDown",e[e.FlagOneHundredTwentyEighthUp=57928]="FlagOneHundredTwentyEighthUp",e[e.FlagOneHundredTwentyEighthDown=57929]="FlagOneHundredTwentyEighthDown",e[e.FlagTwoHundredFiftySixthUp=57930]="FlagTwoHundredFiftySixthUp",e[e.FlagTwoHundredFiftySixthDown=57931]="FlagTwoHundredFiftySixthDown",e[e.AccidentalFlat=57952]="AccidentalFlat",e[e.AccidentalNatural=57953]="AccidentalNatural",e[e.AccidentalSharp=57954]="AccidentalSharp",e[e.AccidentalDoubleSharp=57955]="AccidentalDoubleSharp",e[e.AccidentalDoubleFlat=57956]="AccidentalDoubleFlat",e[e.AccidentalQuarterToneFlatArrowUp=57968]="AccidentalQuarterToneFlatArrowUp",e[e.AccidentalQuarterToneSharpArrowUp=57972]="AccidentalQuarterToneSharpArrowUp",e[e.AccidentalQuarterToneNaturalArrowUp=57970]="AccidentalQuarterToneNaturalArrowUp",e[e.Segno=57415]="Segno",e[e.Coda=57416]="Coda",e[e.ArticAccentAbove=58528]="ArticAccentAbove",e[e.ArticAccentBelow=58529]="ArticAccentBelow",e[e.ArticStaccatoAbove=58530]="ArticStaccatoAbove",e[e.ArticStaccatoBelow=58531]="ArticStaccatoBelow",e[e.ArticTenutoAbove=58532]="ArticTenutoAbove",e[e.ArticTenutoBelow=58533]="ArticTenutoBelow",e[e.ArticMarcatoAbove=58540]="ArticMarcatoAbove",e[e.ArticMarcatoBelow=58541]="ArticMarcatoBelow",e[e.FermataAbove=58560]="FermataAbove",e[e.FermataShortAbove=58564]="FermataShortAbove",e[e.FermataLongAbove=58566]="FermataLongAbove",e[e.RestLonga=58593]="RestLonga",e[e.RestDoubleWhole=58594]="RestDoubleWhole",e[e.RestWhole=58595]="RestWhole",e[e.RestHalf=58596]="RestHalf",e[e.RestQuarter=58597]="RestQuarter",e[e.RestEighth=58598]="RestEighth",e[e.RestSixteenth=58599]="RestSixteenth",e[e.RestThirtySecond=58600]="RestThirtySecond",e[e.RestSixtyFourth=58601]="RestSixtyFourth",e[e.RestOneHundredTwentyEighth=58602]="RestOneHundredTwentyEighth",e[e.RestTwoHundredFiftySixth=58603]="RestTwoHundredFiftySixth",e[e.RestHBarLeft=58607]="RestHBarLeft",e[e.RestHBarMiddle=58608]="RestHBarMiddle",e[e.RestHBarRight=58609]="RestHBarRight",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.DynamicPPPPPP=58663]="DynamicPPPPPP",e[e.DynamicPPPPP=58664]="DynamicPPPPP",e[e.DynamicPPPP=58665]="DynamicPPPP",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.DynamicPF=58670]="DynamicPF",e[e.DynamicForte=58658]="DynamicForte",e[e.DynamicFF=58671]="DynamicFF",e[e.DynamicFFF=58672]="DynamicFFF",e[e.DynamicFFFF=58673]="DynamicFFFF",e[e.DynamicFFFFF=58674]="DynamicFFFFF",e[e.DynamicFFFFFF=58675]="DynamicFFFFFF",e[e.DynamicFortePiano=58676]="DynamicFortePiano",e[e.DynamicNiente=58662]="DynamicNiente",e[e.DynamicSforzando1=58678]="DynamicSforzando1",e[e.DynamicSforzandoPiano=58679]="DynamicSforzandoPiano",e[e.DynamicSforzandoPianissimo=58680]="DynamicSforzandoPianissimo",e[e.DynamicSforzato=58681]="DynamicSforzato",e[e.DynamicSforzatoPiano=58682]="DynamicSforzatoPiano",e[e.DynamicSforzatoFF=58683]="DynamicSforzatoFF",e[e.DynamicRinforzando1=58684]="DynamicRinforzando1",e[e.DynamicRinforzando2=58685]="DynamicRinforzando2",e[e.DynamicForzando=58677]="DynamicForzando",e[e.OrnamentTrill=58726]="OrnamentTrill",e[e.OrnamentTurn=58727]="OrnamentTurn",e[e.OrnamentTurnInverted=58728]="OrnamentTurnInverted",e[e.OrnamentShortTrill=58732]="OrnamentShortTrill",e[e.OrnamentMordent=58733]="OrnamentMordent",e[e.StringsDownBow=58896]="StringsDownBow",e[e.StringsUpBow=58898]="StringsUpBow",e[e.KeyboardPedalPed=58960]="KeyboardPedalPed",e[e.KeyboardPedalUp=58965]="KeyboardPedalUp",e[e.PictEdgeOfCymbal=59177]="PictEdgeOfCymbal",e[e.GuitarString0=59443]="GuitarString0",e[e.GuitarString1=59444]="GuitarString1",e[e.GuitarString2=59445]="GuitarString2",e[e.GuitarString3=59446]="GuitarString3",e[e.GuitarString4=59447]="GuitarString4",e[e.GuitarString5=59448]="GuitarString5",e[e.GuitarString6=59449]="GuitarString6",e[e.GuitarString7=59450]="GuitarString7",e[e.GuitarString8=59451]="GuitarString8",e[e.GuitarString9=59452]="GuitarString9",e[e.GuitarOpenPedal=59453]="GuitarOpenPedal",e[e.GuitarClosePedal=59455]="GuitarClosePedal",e[e.GuitarGolpe=59458]="GuitarGolpe",e[e.GuitarFadeIn=59459]="GuitarFadeIn",e[e.GuitarFadeOut=59460]="GuitarFadeOut",e[e.GuitarVolumeSwell=59461]="GuitarVolumeSwell",e[e.FretboardX=59481]="FretboardX",e[e.FretboardO=59482]="FretboardO",e[e.WiggleTrill=60068]="WiggleTrill",e[e.WiggleVibratoMediumFast=60126]="WiggleVibratoMediumFast",e[e.OctaveBaselineM=60565]="OctaveBaselineM",e[e.OctaveBaselineB=60563]="OctaveBaselineB"}(G||(G={}));class De{constructor(e="",t=0,s=0,i=G.None,a=G.None,r=G.None,n=G.None,o=V.Middle){this.elementType=e,this.outputMidiNumber=s,this.staffLine=t,this.noteHeadDefault=i,this.noteHeadHalf=a!==G.None?a:i,this.noteHeadWhole=r!==G.None?r:i,this.techniqueSymbol=n,this.techniqueSymbolPlacement=o}getSymbol(e){switch(e){case D.Whole:return this.noteHeadWhole;case D.Half:return this.noteHeadHalf;default:return this.noteHeadDefault}}}class Ee{static float64ToBytes(e){return Ee._dataView.setFloat64(0,e,!0),Ee._conversionByteArray}static bytesToInt64LE(e){Ee._conversionByteArray.set(e,0);const t=Ee._dataView.getBigInt64(0,!0);return t<=Number.MAX_SAFE_INTEGER&&t>=Number.MIN_SAFE_INTEGER?Number(t):Number.MAX_SAFE_INTEGER}static bytesToFloat64LE(e){return Ee._conversionByteArray.set(e,0),Ee._dataView.getFloat64(0,!0)}static bytesToFloat32LE(e){return Ee._conversionByteArray.set(e,0),Ee._dataView.getFloat32(0,!0)}static float32BEToBytes(e){return Ee._dataView.setFloat32(0,e,!1),Ee._conversionByteArray.slice(0,4)}static uint16ToInt16(e){return Ee._dataView.setUint16(0,e,!0),Ee._dataView.getInt16(0,!0)}static int16ToUint32(e){return Ee._dataView.setInt16(0,e,!0),Ee._dataView.getUint32(0,!0)}static int32ToUint16(e){return Ee._dataView.setInt32(0,e,!0),Ee._dataView.getUint16(0,!0)}static int32ToInt16(e){return Ee._dataView.setInt32(0,e,!0),Ee._dataView.getInt16(0,!0)}static int32ToUint32(e){return Ee._dataView.setInt32(0,e,!0),Ee._dataView.getUint32(0,!0)}static uint8ToInt8(e){return Ee._dataView.setUint8(0,e),Ee._dataView.getInt8(0)}}Ee._conversionBuffer=new ArrayBuffer(8),Ee._conversionByteArray=new Uint8Array(Ee._conversionBuffer),Ee._dataView=new DataView(Ee._conversionBuffer);class Le{static readInt32BE(e){return e.readByte()<<24|e.readByte()<<16|e.readByte()<<8|e.readByte()}static readFloat32BE(e){const t=new Uint8Array(4);return e.read(t,0,t.length),t.reverse(),Ee.bytesToFloat32LE(t)}static readFloat64BE(e){const t=new Uint8Array(8);return e.read(t,0,t.length),t.reverse(),Ee.bytesToFloat64LE(t)}static readInt32LE(e){const t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static readInt64LE(e){const t=new Uint8Array(8);return e.read(t,0,t.length),Ee.bytesToInt64LE(t)}static readUInt32LE(e){const t=e.readByte(),s=e.readByte(),i=e.readByte();return e.readByte()<<24|i<<16|s<<8|t}static decodeUInt32LE(e,t){const s=e[t],i=e[t+1],a=e[t+2];return e[t+3]<<24|a<<16|i<<8|s}static readUInt16LE(e){const t=e.readByte(),s=e.readByte();return Ee.int32ToUint16(s<<8|t)}static readInt16LE(e){const t=e.readByte(),s=e.readByte();return Ee.int32ToInt16(s<<8|t)}static readUInt32BE(e){const t=e.readByte(),s=e.readByte(),i=e.readByte(),a=e.readByte();return Ee.int32ToUint32(t<<24|s<<16|i<<8|a)}static readUInt16BE(e){const t=e.readByte(),s=e.readByte();return Ee.int32ToInt16(t<<8|s)}static readInt16BE(e){const t=e.readByte(),s=e.readByte();return Ee.int32ToInt16(t<<8|s)}static readByteArray(e,t){const s=new Uint8Array(t);return e.read(s,0,t),s}static read8BitChars(e,t){const s=new Uint8Array(t);return e.read(s,0,s.length),Le.toString(s,"utf-8")}static read8BitString(e){let t="",s=e.readByte();for(;0!==s;)t+=String.fromCharCode(s),s=e.readByte();return t}static read8BitStringLength(e,t){let s="",i=-1;for(let a=0;a<t;a++){const t=e.readByte();0===t&&-1===i&&(i=a),s+=String.fromCharCode(t)}const a=s;return i>=0?a.substr(0,i):a}static readSInt8(e){const t=e.readByte();return-256*((255&t)>>7)+(255&t)}static readInt24(e,t){let s=e[t]|e[t+1]<<8|e[t+2]<<16;return 8388608&~s||(s|=255<<24),s}static readInt16(e,t){return Ee.int32ToInt16(e[t]|e[t+1]<<8)}static toString(e,t){const s=Le.detectEncoding(e);s&&(t=s),t||(t="utf-8");return new TextDecoder(t).decode(e.buffer)}static detectEncoding(e){return e.length>2&&254===e[0]&&255===e[1]?"utf-16be":e.length>2&&255===e[0]&&254===e[1]?"utf-16le":e.length>4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3]?"utf-32be":e.length>4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3]?"utf-32le":null}static stringToBytes(e){return(new TextEncoder).encode(e)}static writeInt32BE(e,t){e.writeByte(t>>24&255),e.writeByte(t>>16&255),e.writeByte(t>>8&255),e.writeByte(255&t)}static writeInt32LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255),e.writeByte(t>>16&255),e.writeByte(t>>24&255)}static writeUInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16LE(e,t){e.writeByte(255&t),e.writeByte(t>>8&255)}static writeInt16BE(e,t){e.writeByte(t>>8&255),e.writeByte(255&t)}static writeFloat32BE(e,t){const s=Ee.float32BEToBytes(t);e.write(s,0,s.length)}}class Me{constructor(){this.length=0,this.position=0}get bytesWritten(){return this.position}getBuffer(){return this._buffer}static empty(){return Me.withCapacity(0)}static withCapacity(e){const t=new Me;return t._buffer=new Uint8Array(e),t}static fromBuffer(e){const t=new Me;return t._buffer=e,t.length=e.length,t}static fromString(e){const t=Le.stringToBytes(e);return Me.fromBuffer(t)}reset(){this.position=0}skip(e){this.position+=e}readByte(){return this.length-this.position<=0?-1:this._buffer[this.position++]}read(e,t,s){let i=this.length-this.position;return i>s&&(i=s),i<=0?0:(e.set(this._buffer.subarray(this.position,this.position+i),t),this.position+=i,i)}writeByte(e){const t=this.position+1;this.ensureCapacity(t),this._buffer[this.position]=255&e,t>this.length&&(this.length=t),this.position=t}write(e,t,s){const i=this.position+s;this.ensureCapacity(i);const a=Math.min(s,e.length-t);this._buffer.set(e.subarray(t,t+a),this.position),i>this.length&&(this.length=i),this.position=i}ensureCapacity(e){if(e>this._buffer.length){let t=e;t<256&&(t=256),t<2*this._buffer.length&&(t=2*this._buffer.length);const s=new Uint8Array(t);this.length>0&&s.set(this._buffer.subarray(0,0+this.length),0),this._buffer=s}}readAll(){return this.toArray()}toArray(){const e=new Uint8Array(this.length);return e.set(this._buffer.subarray(0,0+this.length),0),e}copyTo(e){e.write(this._buffer,0,this.length)}}!function(e){e[e.SingleTrackMultiChannel=0]="SingleTrackMultiChannel",e[e.MultiTrack=1]="MultiTrack"}(z||(z={}));class Ie{constructor(){this.events=[]}addEvent(e){if(0===this.events.length||e.tick>=this.events[this.events.length-1].tick)this.events.push(e);else{let t=this.events.length;for(;t>0;){if(!(this.events[t-1].tick>e.tick))break;t--}this.events.splice(t,0,e)}}writeTo(e){const t=Me.empty();let s=0;for(const e of this.events){const i=e.tick-s;Ae.writeVariableInt(t,i),e.writeTo(t),s=e.tick}const i=new Uint8Array([77,84,114,107]);e.write(i,0,i.length);const a=t.toArray();Le.writeInt32BE(e,a.length),e.write(a,0,a.length)}}class Ae{constructor(){this.format=z.SingleTrackMultiChannel,this.division=rs.QuarterTime,this.tracks=[]}get events(){if(1===this.tracks.length)return this.tracks[0].events;const e=[];for(const e of this.tracks)this.events.push(...e.events);return e.sort(((e,t)=>e.tick-t.tick)),e}ensureTracks(e){for(;this.tracks.length<e;)this.tracks.push(new Ie)}addEvent(e){this.format===z.SingleTrackMultiChannel?(this.ensureTracks(1),this.tracks[0].addEvent(e)):(this.ensureTracks(e.track+1),this.tracks[e.track].addEvent(e))}toBinary(){const e=Me.empty();return this.writeTo(e),e.toArray()}writeTo(e){const t=new Uint8Array([77,84,104,100]);e.write(t,0,t.length),Le.writeInt32BE(e,6),Le.writeInt16BE(e,this.format),Le.writeInt16BE(e,this.tracks.length),Le.writeInt16BE(e,this.division);for(const t of this.tracks)t.writeTo(e)}static writeVariableInt(e,t){const s=new Uint8Array(4);let i=0;do{s[i++]=127&t,t>>=7}while(t>0);for(;i>0;)i--,i>0?e.writeByte(128|s[i]):e.writeByte(s[i])}}!function(e){e[e.TimeSignature=88]="TimeSignature",e[e.NoteOn=128]="NoteOn",e[e.NoteOff=144]="NoteOff",e[e.ControlChange=176]="ControlChange",e[e.ProgramChange=192]="ProgramChange",e[e.TempoChange=81]="TempoChange",e[e.PitchBend=224]="PitchBend",e[e.PerNotePitchBend=96]="PerNotePitchBend",e[e.EndOfTrack=47]="EndOfTrack",e[e.AlphaTabRest=241]="AlphaTabRest",e[e.AlphaTabMetronome=242]="AlphaTabMetronome",e[e.SystemExclusive=240]="SystemExclusive",e[e.SystemExclusive2=247]="SystemExclusive2",e[e.Meta=255]="Meta"}(U||(U={}));class Re{constructor(e,t,s){this.track=e,this.tick=t,this.type=s}get command(){return this.type}get message(){return 0}get data1(){return 0}get data2(){return 0}}class Oe extends Re{constructor(e,t,s,i,a,r){super(e,t,U.TimeSignature),this.track=e,this.tick=t,this.numerator=s,this.denominatorIndex=i,this.midiClocksPerMetronomeClick=a,this.thirtySecondNodesInQuarter=r}writeTo(e){e.writeByte(255),e.writeByte(88),Ae.writeVariableInt(e,4),e.writeByte(255&this.numerator),e.writeByte(255&this.denominatorIndex),e.writeByte(255&this.midiClocksPerMetronomeClick),e.writeByte(255&this.thirtySecondNodesInQuarter)}}class He extends Re{writeTo(e){e.writeByte(240);const t=Me.withCapacity(16);t.writeByte(He.AlphaTabManufacturerId),this.writeEventData(t),t.writeByte(247),Ae.writeVariableInt(e,t.length),t.copyTo(e)}}He.AlphaTabManufacturerId=125,He.MetronomeEventId=0,He.RestEventId=1;class We extends He{constructor(e,t,s,i,a){super(e,t,U.AlphaTabMetronome),this.isMetronome=!0,this.metronomeNumerator=s,this.metronomeDurationInMilliseconds=a,this.metronomeDurationInTicks=i}writeEventData(e){e.writeByte(He.MetronomeEventId),e.writeByte(this.metronomeNumerator),Le.writeInt32LE(e,this.metronomeDurationInTicks),Le.writeInt32LE(e,this.metronomeDurationInMilliseconds)}}class Ve extends He{constructor(e,t,s){super(e,t,U.AlphaTabRest),this.channel=s}writeEventData(e){e.writeByte(He.RestEventId),e.writeByte(this.channel)}}class Ge extends Re{constructor(e,t,s,i,a,r){super(e,t,s),this.channel=i,this.noteKey=a,this.noteVelocity=r}get data1(){return this.noteKey}get data2(){return this.noteVelocity}}class ze extends Ge{constructor(e,t,s,i,a){super(e,t,U.NoteOn,s,i,a)}writeTo(e){e.writeByte(15&this.channel|144),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class Ue extends Ge{constructor(e,t,s,i,a){super(e,t,U.NoteOff,s,i,a)}writeTo(e){e.writeByte(15&this.channel|128),e.writeByte(255&this.noteKey),e.writeByte(255&this.noteVelocity)}}class Xe extends Re{constructor(e,t,s,i,a){super(e,t,U.ControlChange),this.channel=s,this.controller=i,this.value=a}writeTo(e){e.writeByte(15&this.channel|176),e.writeByte(255&this.controller),e.writeByte(255&this.value)}get data1(){return this.controller}get data2(){return this.value}}class Je extends Re{constructor(e,t,s,i){super(e,t,U.ProgramChange),this.channel=s,this.program=i}writeTo(e){e.writeByte(15&this.channel|192),e.writeByte(255&this.program)}get data1(){return this.program}}class Ye extends Re{constructor(e,t){super(0,e,U.TempoChange),this.microSecondsPerQuarterNote=t}writeTo(e){e.writeByte(255),e.writeByte(81),e.writeByte(3),e.writeByte(this.microSecondsPerQuarterNote>>16&255),e.writeByte(this.microSecondsPerQuarterNote>>8&255),e.writeByte(255&this.microSecondsPerQuarterNote)}}class $e extends Re{constructor(e,t,s,i){super(e,t,U.PitchBend),this.channel=s,this.value=i}writeTo(e){e.writeByte(15&this.channel|224),e.writeByte(127&this.value),e.writeByte(this.value>>7&127)}get data1(){return 127&this.value}get data2(){return this.value>>7&127}}class qe extends Re{constructor(e,t,s,i,a){super(e,t,U.PerNotePitchBend),this.channel=s,this.noteKey=i,this.value=a}writeTo(e){throw new fe(S.General,"Note Bend (Midi2.0) events cannot be exported to SMF1.0")}}class Ke extends Re{constructor(e,t){super(e,t,U.EndOfTrack)}writeTo(e){e.writeByte(255),e.writeByte(47),e.writeByte(0)}}class je{constructor(){this.copyrightFont=new Pe(je.sansFont,12,I.Plain,A.Bold),this.titleFont=new Pe(je.serifFont,32,I.Plain),this.subTitleFont=new Pe(je.serifFont,20,I.Plain),this.wordsFont=new Pe(je.serifFont,15,I.Plain),this.effectFont=new Pe(je.serifFont,12,I.Italic),this.timerFont=new Pe(je.serifFont,12,I.Plain),this.directionsFont=new Pe(je.serifFont,14,I.Plain),this.fretboardNumberFont=new Pe(je.sansFont,11,I.Plain),this.numberedNotationFont=new Pe(je.sansFont,16,I.Plain),this.numberedNotationGraceFont=new Pe(je.sansFont,14,I.Plain),this.tablatureFont=new Pe(je.sansFont,13,I.Plain),this.graceFont=new Pe(je.sansFont,11,I.Plain),this.staffLineColor=new ke(165,165,165,255),this.barSeparatorColor=new ke(34,34,17,255),this.barNumberFont=new Pe(je.sansFont,11,I.Plain),this.barNumberColor=new ke(200,0,0,255),this.fingeringFont=new Pe(je.serifFont,14,I.Plain),this.inlineFingeringFont=new Pe(je.serifFont,12,I.Plain),this.markerFont=new Pe(je.serifFont,14,I.Plain,A.Bold),this.mainGlyphColor=new ke(0,0,0,255),this.secondaryGlyphColor=new ke(0,0,0,100),this.scoreInfoColor=new ke(0,0,0,255)}getFontForElement(e){switch(e){case ws.Title:return this.titleFont;case ws.SubTitle:case ws.Artist:case ws.Album:return this.subTitleFont;case ws.Words:case ws.Music:case ws.WordsAndMusic:case ws.Transcriber:return this.wordsFont;case ws.Copyright:case ws.CopyrightSecondLine:return this.copyrightFont}return this.wordsFont}}je.sansFont="Arial, sans-serif",je.serifFont="Georgia, serif",function(e){e[e.Automatic=0]="Automatic",e[e.UseModelLayout=1]="UseModelLayout"}(X||(X={}));class Qe{constructor(){this.scale=1,this.stretchForce=1,this.layoutMode=e.Page,this.staveProfile=t.Default,this.barsPerRow=-1,this.startBar=1,this.barCount=-1,this.barCountPerPartial=10,this.justifyLastSystem=!1,this.resources=new je,this.padding=[35,35],this.firstSystemPaddingTop=5,this.systemPaddingTop=10,this.systemPaddingBottom=20,this.lastSystemPaddingBottom=0,this.systemLabelPaddingLeft=0,this.systemLabelPaddingRight=3,this.accoladeBarPaddingRight=3,this.notationStaffPaddingTop=5,this.notationStaffPaddingBottom=5,this.effectStaffPaddingTop=0,this.effectStaffPaddingBottom=0,this.firstStaffPaddingLeft=6,this.staffPaddingLeft=2,this.systemsLayoutMode=X.Automatic}}class Ze{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"}(J||(J={}));class et{constructor(){this.noteWideLength=240,this.noteWideAmplitude=1,this.noteSlightLength=360,this.noteSlightAmplitude=.5,this.beatWideLength=480,this.beatWideAmplitude=2,this.beatSlightLength=480,this.beatSlightAmplitude=2}}class tt{constructor(){this.simpleSlidePitchOffset=6,this.simpleSlideDurationRatio=.25,this.shiftSlideDurationRatio=.5}}!function(e){e[e.WebAudioAudioWorklets=0]="WebAudioAudioWorklets",e[e.WebAudioScriptProcessor=1]="WebAudioScriptProcessor"}(Y||(Y={}));class st{constructor(){this.soundFont=null,this.scrollElement="html,body",this.outputMode=Y.WebAudioAudioWorklets,this.enablePlayer=!1,this.enableCursor=!0,this.enableAnimatedBeatCursor=!0,this.enableElementHighlighting=!0,this.enableUserInteraction=!0,this.scrollOffsetX=0,this.scrollOffsetY=0,this.scrollMode=J.Continuous,this.scrollSpeed=300,this.nativeBrowserSmoothScroll=!0,this.songBookBendDuration=75,this.songBookDipDuration=150,this.vibrato=new et,this.slide=new tt,this.playTripletFeel=!0,this.bufferTimeInMilliseconds=500}}!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"}($||($={}));class it{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>it.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scriptfile",e.scriptFile),t.set("fontdirectory",e.fontDirectory),t.set("file",e.file),t.set("tex",e.tex),t.set("tracks",e.tracks),t.set("enablelazyloading",e.enableLazyLoading),t.set("engine",e.engine),t.set("loglevel",e.logLevel),t.set("useworkers",e.useWorkers),t.set("includenotebounds",e.includeNoteBounds),t}static setProperty(e,t,s){switch(t){case"scriptfile":return e.scriptFile=s,!0;case"fontdirectory":return e.fontDirectory=s,!0;case"file":return e.file=s,!0;case"tex":return e.tex=s,!0;case"tracks":return e.tracks=s,!0;case"enablelazyloading":return e.enableLazyLoading=s,!0;case"engine":return e.engine=s,!0;case"loglevel":return e.logLevel=Ne.parseEnum(s,$),!0;case"useworkers":return e.useWorkers=s,!0;case"includenotebounds":return e.includeNoteBounds=s,!0}return!1}}class at{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>at.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("copyrightfont",Pe.toJson(e.copyrightFont)),t.set("titlefont",Pe.toJson(e.titleFont)),t.set("subtitlefont",Pe.toJson(e.subTitleFont)),t.set("wordsfont",Pe.toJson(e.wordsFont)),t.set("effectfont",Pe.toJson(e.effectFont)),t.set("timerfont",Pe.toJson(e.timerFont)),t.set("directionsfont",Pe.toJson(e.directionsFont)),t.set("fretboardnumberfont",Pe.toJson(e.fretboardNumberFont)),t.set("numberednotationfont",Pe.toJson(e.numberedNotationFont)),t.set("numberednotationgracefont",Pe.toJson(e.numberedNotationGraceFont)),t.set("tablaturefont",Pe.toJson(e.tablatureFont)),t.set("gracefont",Pe.toJson(e.graceFont)),t.set("stafflinecolor",ke.toJson(e.staffLineColor)),t.set("barseparatorcolor",ke.toJson(e.barSeparatorColor)),t.set("barnumberfont",Pe.toJson(e.barNumberFont)),t.set("barnumbercolor",ke.toJson(e.barNumberColor)),t.set("fingeringfont",Pe.toJson(e.fingeringFont)),t.set("inlinefingeringfont",Pe.toJson(e.inlineFingeringFont)),t.set("markerfont",Pe.toJson(e.markerFont)),t.set("mainglyphcolor",ke.toJson(e.mainGlyphColor)),t.set("secondaryglyphcolor",ke.toJson(e.secondaryGlyphColor)),t.set("scoreinfocolor",ke.toJson(e.scoreInfoColor)),t}static setProperty(e,t,s){switch(t){case"copyrightfont":return e.copyrightFont=Pe.fromJson(s),!0;case"titlefont":return e.titleFont=Pe.fromJson(s),!0;case"subtitlefont":return e.subTitleFont=Pe.fromJson(s),!0;case"wordsfont":return e.wordsFont=Pe.fromJson(s),!0;case"effectfont":return e.effectFont=Pe.fromJson(s),!0;case"timerfont":return e.timerFont=Pe.fromJson(s),!0;case"directionsfont":return e.directionsFont=Pe.fromJson(s),!0;case"fretboardnumberfont":return e.fretboardNumberFont=Pe.fromJson(s),!0;case"numberednotationfont":return e.numberedNotationFont=Pe.fromJson(s),!0;case"numberednotationgracefont":return e.numberedNotationGraceFont=Pe.fromJson(s),!0;case"tablaturefont":return e.tablatureFont=Pe.fromJson(s),!0;case"gracefont":return e.graceFont=Pe.fromJson(s),!0;case"stafflinecolor":return e.staffLineColor=ke.fromJson(s),!0;case"barseparatorcolor":return e.barSeparatorColor=ke.fromJson(s),!0;case"barnumberfont":return e.barNumberFont=Pe.fromJson(s),!0;case"barnumbercolor":return e.barNumberColor=ke.fromJson(s),!0;case"fingeringfont":return e.fingeringFont=Pe.fromJson(s),!0;case"inlinefingeringfont":return e.inlineFingeringFont=Pe.fromJson(s),!0;case"markerfont":return e.markerFont=Pe.fromJson(s),!0;case"mainglyphcolor":return e.mainGlyphColor=ke.fromJson(s),!0;case"secondaryglyphcolor":return e.secondaryGlyphColor=ke.fromJson(s),!0;case"scoreinfocolor":return e.scoreInfoColor=ke.fromJson(s),!0}return!1}}class rt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>rt.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("scale",e.scale),t.set("stretchforce",e.stretchForce),t.set("layoutmode",e.layoutMode),t.set("staveprofile",e.staveProfile),t.set("barsperrow",e.barsPerRow),t.set("startbar",e.startBar),t.set("barcount",e.barCount),t.set("barcountperpartial",e.barCountPerPartial),t.set("justifylastsystem",e.justifyLastSystem),t.set("resources",at.toJson(e.resources)),t.set("padding",e.padding),t.set("firstsystempaddingtop",e.firstSystemPaddingTop),t.set("systempaddingtop",e.systemPaddingTop),t.set("systempaddingbottom",e.systemPaddingBottom),t.set("lastsystempaddingbottom",e.lastSystemPaddingBottom),t.set("systemlabelpaddingleft",e.systemLabelPaddingLeft),t.set("systemlabelpaddingright",e.systemLabelPaddingRight),t.set("accoladebarpaddingright",e.accoladeBarPaddingRight),t.set("notationstaffpaddingtop",e.notationStaffPaddingTop),t.set("notationstaffpaddingbottom",e.notationStaffPaddingBottom),t.set("effectstaffpaddingtop",e.effectStaffPaddingTop),t.set("effectstaffpaddingbottom",e.effectStaffPaddingBottom),t.set("firststaffpaddingleft",e.firstStaffPaddingLeft),t.set("staffpaddingleft",e.staffPaddingLeft),t.set("systemslayoutmode",e.systemsLayoutMode),t}static setProperty(s,i,a){switch(i){case"scale":return s.scale=a,!0;case"stretchforce":return s.stretchForce=a,!0;case"layoutmode":return s.layoutMode=Ne.parseEnum(a,e),!0;case"staveprofile":return s.staveProfile=Ne.parseEnum(a,t),!0;case"barsperrow":return s.barsPerRow=a,!0;case"startbar":return s.startBar=a,!0;case"barcount":return s.barCount=a,!0;case"barcountperpartial":return s.barCountPerPartial=a,!0;case"justifylastsystem":return s.justifyLastSystem=a,!0;case"padding":return s.padding=a,!0;case"firstsystempaddingtop":return s.firstSystemPaddingTop=a,!0;case"systempaddingtop":return s.systemPaddingTop=a,!0;case"systempaddingbottom":return s.systemPaddingBottom=a,!0;case"lastsystempaddingbottom":return s.lastSystemPaddingBottom=a,!0;case"systemlabelpaddingleft":return s.systemLabelPaddingLeft=a,!0;case"systemlabelpaddingright":return s.systemLabelPaddingRight=a,!0;case"accoladebarpaddingright":return s.accoladeBarPaddingRight=a,!0;case"notationstaffpaddingtop":return s.notationStaffPaddingTop=a,!0;case"notationstaffpaddingbottom":return s.notationStaffPaddingBottom=a,!0;case"effectstaffpaddingtop":return s.effectStaffPaddingTop=a,!0;case"effectstaffpaddingbottom":return s.effectStaffPaddingBottom=a,!0;case"firststaffpaddingleft":return s.firstStaffPaddingLeft=a,!0;case"staffpaddingleft":return s.staffPaddingLeft=a,!0;case"systemslayoutmode":return s.systemsLayoutMode=Ne.parseEnum(a,X),!0}if(["resources"].indexOf(i)>=0)return at.fromJson(s.resources,a),!0;for(const e of["resources"])if(0===i.indexOf(e)&&at.setProperty(s.resources,i.substring(e.length),a))return!0;return!1}}class nt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>nt.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("notationmode",e.notationMode),t.set("fingeringmode",e.fingeringMode);{const s=new Map;t.set("elements",s);for(const[t,i]of e.elements)s.set(t.toString(),i)}return t.set("rhythmmode",e.rhythmMode),t.set("rhythmheight",e.rhythmHeight),t.set("transpositionpitches",e.transpositionPitches),t.set("displaytranspositionpitches",e.displayTranspositionPitches),t.set("smallgracetabnotes",e.smallGraceTabNotes),t.set("extendbendarrowsontiednotes",e.extendBendArrowsOnTiedNotes),t.set("extendlineeffectstobeatend",e.extendLineEffectsToBeatEnd),t.set("slurheight",e.slurHeight),t}static setProperty(e,t,s){switch(t){case"notationmode":return e.notationMode=Ne.parseEnum(s,k),!0;case"fingeringmode":return e.fingeringMode=Ne.parseEnum(s,B),!0;case"elements":return e.elements=new Map,Ne.forEach(s,((t,s)=>{e.elements.set(Ne.parseEnum(s,T),t)})),!0;case"rhythmmode":return e.rhythmMode=Ne.parseEnum(s,w),!0;case"rhythmheight":return e.rhythmHeight=s,!0;case"transpositionpitches":return e.transpositionPitches=s,!0;case"displaytranspositionpitches":return e.displayTranspositionPitches=s,!0;case"smallgracetabnotes":return e.smallGraceTabNotes=s,!0;case"extendbendarrowsontiednotes":return e.extendBendArrowsOnTiedNotes=s,!0;case"extendlineeffectstobeatend":return e.extendLineEffectsToBeatEnd=s,!0;case"slurheight":return e.slurHeight=s,!0}return!1}}class ot{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>ot.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("encoding",e.encoding),t.set("mergepartgroupsinmusicxml",e.mergePartGroupsInMusicXml),t.set("beattextaslyrics",e.beatTextAsLyrics),t}static setProperty(e,t,s){switch(t){case"encoding":return e.encoding=s,!0;case"mergepartgroupsinmusicxml":return e.mergePartGroupsInMusicXml=s,!0;case"beattextaslyrics":return e.beatTextAsLyrics=s,!0}return!1}}class ht{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>ht.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("notewidelength",e.noteWideLength),t.set("notewideamplitude",e.noteWideAmplitude),t.set("noteslightlength",e.noteSlightLength),t.set("noteslightamplitude",e.noteSlightAmplitude),t.set("beatwidelength",e.beatWideLength),t.set("beatwideamplitude",e.beatWideAmplitude),t.set("beatslightlength",e.beatSlightLength),t.set("beatslightamplitude",e.beatSlightAmplitude),t}static setProperty(e,t,s){switch(t){case"notewidelength":return e.noteWideLength=s,!0;case"notewideamplitude":return e.noteWideAmplitude=s,!0;case"noteslightlength":return e.noteSlightLength=s,!0;case"noteslightamplitude":return e.noteSlightAmplitude=s,!0;case"beatwidelength":return e.beatWideLength=s,!0;case"beatwideamplitude":return e.beatWideAmplitude=s,!0;case"beatslightlength":return e.beatSlightLength=s,!0;case"beatslightamplitude":return e.beatSlightAmplitude=s,!0}return!1}}class lt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>lt.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("simpleslidepitchoffset",e.simpleSlidePitchOffset),t.set("simpleslidedurationratio",e.simpleSlideDurationRatio),t.set("shiftslidedurationratio",e.shiftSlideDurationRatio),t}static setProperty(e,t,s){switch(t){case"simpleslidepitchoffset":return e.simpleSlidePitchOffset=s,!0;case"simpleslidedurationratio":return e.simpleSlideDurationRatio=s,!0;case"shiftslidedurationratio":return e.shiftSlideDurationRatio=s,!0}return!1}}class ct{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>ct.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("soundfont",e.soundFont),t.set("outputmode",e.outputMode),t.set("enableplayer",e.enablePlayer),t.set("enablecursor",e.enableCursor),t.set("enableanimatedbeatcursor",e.enableAnimatedBeatCursor),t.set("enableelementhighlighting",e.enableElementHighlighting),t.set("enableuserinteraction",e.enableUserInteraction),t.set("scrolloffsetx",e.scrollOffsetX),t.set("scrolloffsety",e.scrollOffsetY),t.set("scrollmode",e.scrollMode),t.set("scrollspeed",e.scrollSpeed),t.set("nativebrowsersmoothscroll",e.nativeBrowserSmoothScroll),t.set("songbookbendduration",e.songBookBendDuration),t.set("songbookdipduration",e.songBookDipDuration),t.set("vibrato",ht.toJson(e.vibrato)),t.set("slide",lt.toJson(e.slide)),t.set("playtripletfeel",e.playTripletFeel),t.set("buffertimeinmilliseconds",e.bufferTimeInMilliseconds),t}static setProperty(e,t,s){switch(t){case"soundfont":return e.soundFont=s,!0;case"scrollelement":return e.scrollElement=s,!0;case"outputmode":return e.outputMode=Ne.parseEnum(s,Y),!0;case"enableplayer":return e.enablePlayer=s,!0;case"enablecursor":return e.enableCursor=s,!0;case"enableanimatedbeatcursor":return e.enableAnimatedBeatCursor=s,!0;case"enableelementhighlighting":return e.enableElementHighlighting=s,!0;case"enableuserinteraction":return e.enableUserInteraction=s,!0;case"scrolloffsetx":return e.scrollOffsetX=s,!0;case"scrolloffsety":return e.scrollOffsetY=s,!0;case"scrollmode":return e.scrollMode=Ne.parseEnum(s,J),!0;case"scrollspeed":return e.scrollSpeed=s,!0;case"nativebrowsersmoothscroll":return e.nativeBrowserSmoothScroll=s,!0;case"songbookbendduration":return e.songBookBendDuration=s,!0;case"songbookdipduration":return e.songBookDipDuration=s,!0;case"playtripletfeel":return e.playTripletFeel=s,!0;case"buffertimeinmilliseconds":return e.bufferTimeInMilliseconds=s,!0}if(["vibrato"].indexOf(t)>=0)return ht.fromJson(e.vibrato,s),!0;for(const i of["vibrato"])if(0===t.indexOf(i)&&ht.setProperty(e.vibrato,t.substring(i.length),s))return!0;if(["slide"].indexOf(t)>=0)return lt.fromJson(e.slide,s),!0;for(const i of["slide"])if(0===t.indexOf(i)&&lt.setProperty(e.slide,t.substring(i.length),s))return!0;return!1}}class dt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>dt.setProperty(e,s.toLowerCase(),t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("core",it.toJson(e.core)),t.set("display",rt.toJson(e.display)),t.set("notation",nt.toJson(e.notation)),t.set("importer",ot.toJson(e.importer)),t.set("player",ct.toJson(e.player)),t}static setProperty(e,t,s){if(["core",""].indexOf(t)>=0)return it.fromJson(e.core,s),!0;for(const i of["core",""])if(0===t.indexOf(i)&&it.setProperty(e.core,t.substring(i.length),s))return!0;if(["display",""].indexOf(t)>=0)return rt.fromJson(e.display,s),!0;for(const i of["display",""])if(0===t.indexOf(i)&&rt.setProperty(e.display,t.substring(i.length),s))return!0;if(["notation"].indexOf(t)>=0)return nt.fromJson(e.notation,s),!0;for(const i of["notation"])if(0===t.indexOf(i)&&nt.setProperty(e.notation,t.substring(i.length),s))return!0;if(["importer"].indexOf(t)>=0)return ot.fromJson(e.importer,s),!0;for(const i of["importer"])if(0===t.indexOf(i)&&ot.setProperty(e.importer,t.substring(i.length),s))return!0;if(["player"].indexOf(t)>=0)return ct.fromJson(e.player,s),!0;for(const i of["player"])if(0===t.indexOf(i)&&ct.setProperty(e.player,t.substring(i.length),s))return!0;return!1}}class ut{constructor(){this.core=new dc,this.display=new Qe,this.notation=new be,this.importer=new Ze,this.player=new st}setSongBookModeSettings(){this.notation.notationMode=k.SongBook,this.notation.smallGraceTabNotes=!1,this.notation.fingeringMode=B.SingleNoteEffectBand,this.notation.extendBendArrowsOnTiedNotes=!1,this.notation.elements.set(T.ParenthesisOnTiedBends,!1),this.notation.elements.set(T.TabNotesOnTiedBends,!1),this.notation.elements.set(T.ZerosOnDiveWhammys,!0)}static get songBook(){const e=new ut;return e.setSongBookModeSettings(),e}fillFromJson(e){dt.fromJson(this,e)}}class pt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>pt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("marker",e.marker),t.set("text",e.text),t}static setProperty(e,t,s){switch(t){case"marker":return e.marker=s,!0;case"text":return e.text=s,!0}return!1}}class gt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>gt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("islinear",e.isLinear),t.set("type",e.type),t.set("value",e.value),t.set("ratioposition",e.ratioPosition),t.set("text",e.text),t}static setProperty(e,t,s){switch(t){case"islinear":return e.isLinear=s,!0;case"type":return e.type=Ne.parseEnum(s,g),!0;case"value":return e.value=s,!0;case"ratioposition":return e.ratioPosition=s,!0;case"text":return e.text=s,!0}return!1}}class mt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>mt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("type",e.type),t.set("length",e.length),t}static setProperty(e,t,s){switch(t){case"type":return e.type=Ne.parseEnum(s,M),!0;case"length":return e.length=s,!0}return!1}}class ft{constructor(){this.marker="",this.text=""}}class yt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>yt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("alternateendings",e.alternateEndings),t.set("keysignature",e.keySignature),t.set("keysignaturetype",e.keySignatureType),t.set("isdoublebar",e.isDoubleBar),t.set("isrepeatstart",e.isRepeatStart),t.set("repeatcount",e.repeatCount),t.set("timesignaturenumerator",e.timeSignatureNumerator),t.set("timesignaturedenominator",e.timeSignatureDenominator),t.set("timesignaturecommon",e.timeSignatureCommon),t.set("isfreetime",e.isFreeTime),t.set("tripletfeel",e.tripletFeel),e.section&&t.set("section",pt.toJson(e.section)),t.set("tempoautomations",e.tempoAutomations.map((e=>gt.toJson(e)))),null!==e.fermata){const s=new Map;t.set("fermata",s);for(const[t,i]of e.fermata)s.set(t.toString(),mt.toJson(i))}if(t.set("start",e.start),t.set("isanacrusis",e.isAnacrusis),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),null!==e.directions){const s=[];t.set("directions",s);for(const t of e.directions)s.push(t)}return t}static setProperty(e,t,s){switch(t){case"alternateendings":return e.alternateEndings=s,!0;case"keysignature":return e.keySignature=Ne.parseEnum(s,x),!0;case"keysignaturetype":return e.keySignatureType=Ne.parseEnum(s,v),!0;case"isdoublebar":return e.isDoubleBar=s,!0;case"isrepeatstart":return e.isRepeatStart=s,!0;case"repeatcount":return e.repeatCount=s,!0;case"timesignaturenumerator":return e.timeSignatureNumerator=s,!0;case"timesignaturedenominator":return e.timeSignatureDenominator=s,!0;case"timesignaturecommon":return e.timeSignatureCommon=s,!0;case"isfreetime":return e.isFreeTime=s,!0;case"tripletfeel":return e.tripletFeel=Ne.parseEnum(s,P),!0;case"section":return s?(e.section=new ft,pt.fromJson(e.section,s)):e.section=null,!0;case"tempoautomations":e.tempoAutomations=[];for(const t of s){const s=new pe;gt.fromJson(s,t),e.tempoAutomations.push(s)}return!0;case"fermata":return e.fermata=new Map,Ne.forEach(s,((t,s)=>{const i=new Te;mt.fromJson(i,t),e.addFermata(Number.parseInt(s),i)})),!0;case"start":return e.start=s,!0;case"isanacrusis":return e.isAnacrusis=s,!0;case"displayscale":return e.displayScale=s,!0;case"displaywidth":return e.displayWidth=s,!0;case"directions":for(const t of s)e.addDirection(Ne.parseEnum(t,C));return!0}return!1}}class bt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>bt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("offset",e.offset),t.set("value",e.value),t}static setProperty(e,t,s){switch(t){case"offset":return e.offset=s,!0;case"value":return e.value=s,!0}return!1}}!function(e){e[e.None=0]="None",e[e.IntoFromBelow=1]="IntoFromBelow",e[e.IntoFromAbove=2]="IntoFromAbove"}(q||(q={})),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"}(K||(K={})),function(e){e[e.None=0]="None",e[e.Slight=1]="Slight",e[e.Wide=2]="Wide"}(j||(j={}));class St{constructor(e){this._value=void 0,this._factory=e}get value(){return void 0===this._value&&(this._value=this._factory()),this._value}}class _t{static format(e,t){return`[AlphaTab][${e}] ${t}`}debug(e,t,...s){console.debug(_t.format(e,t),...s)}warning(e,t,...s){console.warn(_t.format(e,t),...s)}info(e,t,...s){console.info(_t.format(e,t),...s)}error(e,t,...s){console.error(_t.format(e,t),...s)}}_t.logLevel=$.Info;class wt{static shouldLog(e){return wt.logLevel!==$.None&&e>=wt.logLevel}static debug(e,t,...s){wt.shouldLog($.Debug)&&wt.log.debug(e,t,...s)}static warning(e,t,...s){wt.shouldLog($.Warning)&&wt.log.warning(e,t,...s)}static info(e,t,...s){wt.shouldLog($.Info)&&wt.log.info(e,t,...s)}static error(e,t,...s){wt.shouldLog($.Error)&&wt.log.error(e,t,...s)}}wt.logLevel=$.Info,wt.log=new _t,function(e){e[e.None=0]="None",e[e.Up=1]="Up",e[e.Down=2]="Down"}(Q||(Q={}));class Bt{static articulationFromElementVariation(e,t){return e<Bt.gp6ElementAndVariationToArticulation.length?(t>=Bt.gp6ElementAndVariationToArticulation.length&&(t=0),Bt.gp6ElementAndVariationToArticulation[e][t]):38}static getArticulation(e){const t=e.percussionArticulation;if(t<0)return null;const s=e.beat.voice.bar.staff.track.percussionArticulations;return t<s.length?s[t]:Bt.getArticulationByValue(t)}static getElementAndVariation(e){const t=Bt.getArticulation(e);if(!t)return[-1,-1];for(let e=0;e<Bt.gp6ElementAndVariationToArticulation.length;e++){const s=Bt.gp6ElementAndVariationToArticulation[e];for(let i=0;i<s.length;i++){const a=Bt.getArticulationByValue(s[i]);if(a?.outputMidiNumber===t.outputMidiNumber)return[e,i]}}return[-1,-1]}static getArticulationByValue(e){return Bt.instrumentArticulations.has(e)?Bt.instrumentArticulations.get(e):null}}Bt.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]],Bt.instrumentArticulations=new Map([[38,new De("snare",3,38,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[37,new De("snare",3,37,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[91,new De("snare",3,38,G.NoteheadDiamondWhite,G.NoteheadDiamondWhite,G.NoteheadDiamondWhite)],[42,new De("hiHat",-1,42,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[92,new De("hiHat",-1,46,G.NoteheadCircleSlash,G.NoteheadCircleSlash,G.NoteheadCircleSlash)],[46,new De("hiHat",-1,46,G.NoteheadCircleX,G.NoteheadCircleX,G.NoteheadCircleX)],[44,new De("hiHat",9,44,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[35,new De("kickDrum",8,35,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[36,new De("kickDrum",7,36,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[50,new De("tom",1,50,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[48,new De("tom",2,48,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[47,new De("tom",4,47,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[45,new De("tom",5,45,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[43,new De("tom",6,43,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[93,new De("ride",0,51,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack,G.PictEdgeOfCymbal,V.Bottom)],[51,new De("ride",0,51,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[53,new De("ride",0,53,G.NoteheadDiamondWhite,G.NoteheadDiamondWhite,G.NoteheadDiamondWhite)],[94,new De("ride",0,51,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack,G.ArticStaccatoAbove,V.Top)],[55,new De("splash",-2,55,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[95,new De("splash",-2,55,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack,G.ArticStaccatoAbove,V.Bottom)],[52,new De("china",-3,52,G.NoteheadHeavyXHat,G.NoteheadHeavyXHat,G.NoteheadHeavyXHat)],[96,new De("china",-3,52,G.NoteheadHeavyXHat,G.NoteheadHeavyXHat,G.NoteheadHeavyXHat)],[49,new De("crash",-2,49,G.NoteheadHeavyX,G.NoteheadHeavyX,G.NoteheadHeavyX)],[97,new De("crash",-2,49,G.NoteheadHeavyX,G.NoteheadHeavyX,G.NoteheadHeavyX,G.ArticStaccatoAbove,V.Bottom)],[57,new De("crash",-1,57,G.NoteheadHeavyX,G.NoteheadHeavyX,G.NoteheadHeavyX)],[98,new De("crash",-1,57,G.NoteheadHeavyX,G.NoteheadHeavyX,G.NoteheadHeavyX,G.ArticStaccatoAbove,V.Bottom)],[99,new De("cowbell",1,56,G.NoteheadTriangleUpBlack,G.NoteheadTriangleUpHalf,G.NoteheadTriangleUpWhole)],[100,new De("cowbell",1,56,G.NoteheadXBlack,G.NoteheadXHalf,G.NoteheadXWhole)],[56,new De("cowbell",0,56,G.NoteheadTriangleUpBlack,G.NoteheadTriangleUpHalf,G.NoteheadTriangleUpWhole)],[101,new De("cowbell",0,56,G.NoteheadXBlack,G.NoteheadXHalf,G.NoteheadXWhole)],[102,new De("cowbell",-1,56,G.NoteheadTriangleUpBlack,G.NoteheadTriangleUpHalf,G.NoteheadTriangleUpWhole)],[103,new De("cowbell",-1,56,G.NoteheadXBlack,G.NoteheadXHalf,G.NoteheadXWhole)],[77,new De("woodblock",-9,77,G.NoteheadTriangleUpBlack,G.NoteheadTriangleUpBlack,G.NoteheadTriangleUpBlack)],[76,new De("woodblock",-10,76,G.NoteheadTriangleUpBlack,G.NoteheadTriangleUpBlack,G.NoteheadTriangleUpBlack)],[60,new De("bongo",-4,60,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[104,new De("bongo",-5,60,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole,G.NoteheadParenthesis,V.Middle)],[105,new De("bongo",-6,60,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[61,new De("bongo",-7,61,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[106,new De("bongo",-8,61,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole,G.NoteheadParenthesis,V.Middle)],[107,new De("bongo",-16,61,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[66,new De("timbale",10,66,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[65,new De("timbale",9,65,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[68,new De("agogo",12,68,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[67,new De("agogo",11,67,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[64,new De("conga",17,64,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[108,new De("conga",16,64,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[109,new De("conga",15,64,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole,G.NoteheadParenthesis,V.Middle)],[63,new De("conga",14,63,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[110,new De("conga",13,63,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[62,new De("conga",19,62,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole,G.NoteheadParenthesis,V.Middle)],[72,new De("whistle",-11,72,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[71,new De("whistle",-17,71,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[73,new De("guiro",38,73,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[74,new De("guiro",37,74,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[86,new De("surdo",36,86,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[87,new De("surdo",35,87,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadParenthesis,V.Middle)],[54,new De("tambourine",3,54,G.NoteheadTriangleUpBlack,G.NoteheadTriangleUpBlack,G.NoteheadTriangleUpBlack)],[111,new De("tambourine",2,54,G.NoteheadTriangleUpBlack,G.NoteheadTriangleUpBlack,G.NoteheadTriangleUpBlack,G.StringsUpBow,V.Bottom)],[112,new De("tambourine",1,54,G.NoteheadTriangleUpBlack,G.NoteheadTriangleUpBlack,G.NoteheadTriangleUpBlack,G.StringsDownBow,V.Bottom)],[113,new De("tambourine",-7,54,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[79,new De("cuica",30,79,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[78,new De("cuica",29,78,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[58,new De("vibraslap",28,58,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[81,new De("triangle",27,81,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[80,new De("triangle",26,80,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadParenthesis,V.Middle)],[114,new De("grancassa",25,43,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[115,new De("piatti",18,49,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[116,new De("piatti",24,49,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[69,new De("cabasa",23,69,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[117,new De("cabasa",22,69,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole,G.StringsUpBow,V.Bottom)],[85,new De("castanets",21,85,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[75,new De("claves",20,75,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[70,new De("maraca",-12,70,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[118,new De("maraca",-13,70,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole,G.StringsUpBow,V.Bottom)],[119,new De("maraca",-14,70,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[120,new De("maraca",-15,70,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole,G.StringsUpBow,V.Bottom)],[82,new De("shaker",-23,54,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[122,new De("shaker",-24,54,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole,G.StringsUpBow,V.Bottom)],[84,new De("bellTree",-18,53,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[123,new De("bellTree",-19,53,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole,G.StringsUpBow,V.Bottom)],[83,new De("jingleBell",-20,53,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[124,new De("unpitched",-21,62,G.NoteheadNull,G.NoteheadNull,G.NoteheadNull,G.GuitarGolpe,V.Top)],[125,new De("unpitched",-22,62,G.NoteheadNull,G.NoteheadNull,G.NoteheadNull,G.GuitarGolpe,V.Bottom)],[39,new De("handClap",3,39,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[40,new De("snare",3,40,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[31,new De("snare",3,40,G.NoteheadSlashedBlack2,G.NoteheadSlashedBlack2,G.NoteheadSlashedBlack2)],[41,new De("tom",5,41,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole)],[59,new De("ride",2,59,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack,G.PictEdgeOfCymbal,V.Bottom)],[126,new De("ride",2,59,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[127,new De("ride",2,59,G.NoteheadDiamondWhite,G.NoteheadDiamondWhite,G.NoteheadDiamondWhite)],[29,new De("ride",2,59,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack,G.ArticStaccatoAbove,V.Top)],[30,new De("crash",-3,49,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[33,new De("snare",3,37,G.NoteheadXBlack,G.NoteheadXBlack,G.NoteheadXBlack)],[34,new De("snare",3,38,G.NoteheadBlack,G.NoteheadBlack,G.NoteheadBlack)]]),Bt.instrumentArticulationNames=new Map([["Ride (choke)",29],["Cymbal (hit)",30],["Snare (side stick)",31],["Snare (side stick) 2",33],["Snare (hit)",34],["Kick (hit)",35],["Kick (hit) 2",36],["Snare (side stick) 3",37],["Snare (hit) 2",38],["Hand Clap (hit)",39],["Snare (hit) 3",40],["Low Floor Tom (hit)",41],["Hi-Hat (closed)",42],["Very Low Tom (hit)",43],["Pedal Hi-Hat (hit)",44],["Low Tom (hit)",45],["Hi-Hat (open)",46],["Mid Tom (hit)",47],["High Tom (hit)",48],["Crash high (hit)",49],["High Floor Tom (hit)",50],["Ride (middle)",51],["China (hit)",52],["Ride (bell)",53],["Tambourine (hit)",54],["Splash (hit)",55],["Cowbell medium (hit)",56],["Crash medium (hit)",57],["Vibraslap (hit)",58],["Ride (edge)",59],["Hand (hit)",60],["Hand (hit)",61],["Conga high (mute)",62],["Conga high (hit)",63],["Conga low (hit)",64],["Timbale high (hit)",65],["Timbale low (hit)",66],["Agogo high (hit)",67],["Agogo tow (hit)",68],["Cabasa (hit)",69],["Left Maraca (hit)",70],["Whistle high (hit)",71],["Whistle low (hit)",72],["Guiro (hit)",73],["Guiro (scrap-return)",74],["Claves (hit)",75],["Woodblock high (hit)",76],["Woodblock low (hit)",77],["Cuica (mute)",78],["Cuica (open)",79],["Triangle (rnute)",80],["Triangle (hit)",81],["Shaker (hit)",82],["Tinkle Bell (hat)",83],["Jingle Bell (hit)",83],["Bell Tree (hit)",84],["Castanets (hit)",85],["Surdo (hit)",86],["Surdo (mute)",87],["Snare (rim shot)",91],["Hi-Hat (half)",92],["Ride (edge) 2",93],["Ride (choke) 2",94],["Splash (choke)",95],["China (choke)",96],["Crash high (choke)",97],["Crash medium (choke)",98],["Cowbell low (hit)",99],["Cowbell low (tip)",100],["Cowbell medium (tip)",101],["Cowbell high (hit)",102],["Cowbell high (tip)",103],["Hand (mute)",104],["Hand (slap)",105],["Hand (mute) 2",106],["Hand (slap) 2",107],["Conga low (slap)",108],["Conga low (mute)",109],["Conga high (slap)",110],["Tambourine (return)",111],["Tambourine (roll)",112],["Tambourine (hand)",113],["Grancassa (hit)",114],["Piatti (hat)",115],["Piatti (hand)",116],["Cabasa (return)",117],["Left Maraca (return)",118],["Right Maraca (hit)",119],["Right Maraca (return)",120],["Shaker (return)",122],["Bell Tee (return)",123],["Golpe (thumb)",124],["Golpe (finger)",125],["Ride (middle) 2",126],["Ride (bell) 2",127]]),function(e){e[e.None=0]="None",e[e.InvertedTurn=1]="InvertedTurn",e[e.Turn=2]="Turn",e[e.UpperMordent=3]="UpperMordent",e[e.LowerMordent=4]="LowerMordent"}(Z||(Z={}));class kt{constructor(){this.tieDestinationNoteId=-1,this.tieOriginNoteId=-1,this.slurDestinationNoteId=-1,this.slurOriginNoteId=-1,this.hammerPullDestinationNoteId=-1,this.hammerPullOriginNoteId=-1,this.slideTargetNoteId=-1,this.slideOriginNoteId=-1}}!function(e){e[e.Effects=0]="Effects",e[e.StandardNotationNoteHead=1]="StandardNotationNoteHead",e[e.StandardNotationAccidentals=2]="StandardNotationAccidentals",e[e.StandardNotationEffects=3]="StandardNotationEffects",e[e.GuitarTabFretNumber=4]="GuitarTabFretNumber",e[e.GuitarTabEffects=5]="GuitarTabEffects",e[e.SlashNoteHead=6]="SlashNoteHead",e[e.SlashEffects=7]="SlashEffects",e[e.NumberedNumber=8]="NumberedNumber",e[e.NumberedAccidentals=9]="NumberedAccidentals",e[e.NumberedEffects=10]="NumberedEffects"}(ee||(ee={}));class Tt extends le{}class Nt{constructor(){this.id=Nt.GlobalNoteId++,this.index=0,this.accentuated=u.None,this.bendType=y.None,this.bendStyle=f.Default,this.bendOrigin=null,this.isContinuedBend=!1,this.bendPoints=null,this.maxBendPoint=null,this.fret=-1,this.string=-1,this.showStringNumber=!1,this.octave=-1,this.tone=-1,this.percussionArticulation=-1,this.isVisible=!0,this.isLeftHandTapped=!1,this.isHammerPullOrigin=!1,this.hammerPullOrigin=null,this.hammerPullDestination=null,this.isSlurDestination=!1,this.slurOrigin=null,this.slurDestination=null,this.harmonicType=H.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=q.None,this.slideOutType=K.None,this.slideTarget=null,this.slideOrigin=null,this.vibrato=j.None,this.tieOrigin=null,this.tieDestination=null,this.isTieDestination=!1,this.leftHandFinger=_.Unknown,this.rightHandFinger=_.Unknown,this.trillValue=-1,this.trillSpeed=D.ThirtySecond,this.durationPercent=1,this.accidentalMode=N.Default,this.dynamics=E.F,this.isEffectSlurOrigin=!1,this.hasEffectSlur=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.ornament=Z.None,this._noteIdBag=null}static resetIds(){Nt.GlobalNoteId=0}get hasBend(){return null!==this.bendPoints&&this.bendType!==y.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?Bt.getElementAndVariation(this)[0]:-1}get variation(){return this.isPercussion?Bt.getElementAndVariation(this)[1]:-1}get isHammerPullDestination(){return!!this.hammerPullOrigin}get isSlurOrigin(){return!!this.slurDestination}get isHarmonic(){return this.harmonicType!==H.None}get isTieOrigin(){return null!==this.tieDestination}get isFingering(){return this.leftHandFinger!==_.Unknown||this.rightHandFinger!==_.Unknown}get trillFret(){return this.trillValue-this.stringTuning}get isTrill(){return this.trillValue>=0}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get stringTuning(){return this.beat.voice.bar.staff.capo+Nt.getStringTuning(this.beat.voice.bar.staff,this.string)}static getStringTuning(e,t){return e.tuning.length>0?e.tuning[e.tuning.length-(t-1)-1]:0}get realValue(){return this.calculateRealValue(!0,!0)}get realValueWithoutHarmonic(){return this.calculateRealValue(!0,!1)}calculateRealValue(e,t){const s=e?this.beat.voice.bar.staff.transpositionPitch:0;if(t){let t=this.calculateRealValue(e,!1);return this.isStringed&&(this.harmonicType===H.Natural?t=this.harmonicPitch+this.stringTuning-s:t+=this.harmonicPitch),t}return this.isPercussion?this.percussionArticulation:this.isStringed?this.fret+this.stringTuning-s:this.isPiano?12*this.octave+this.tone-s:0}get harmonicPitch(){if(this.harmonicType===H.None||!this.isStringed)return 0;const e=this.harmonicValue;return Be.isAlmostEqualTo(e,2.4)?36:Be.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!==H.Natural&&this.harmonicType!==H.None&&(e-=this.harmonicPitch),this.beat.ottava){case o._15ma:e-=24;break;case o._8va:e-=12;break;case o.Regular:break;case o._8vb:e+=12;break;case o._15mb:e+=24}switch(this.beat.voice.bar.clefOttava){case o._15ma:e-=24;break;case o._8va:e-=12;break;case o.Regular:break;case o._8vb:e+=12;break;case o._15mb:e+=24}return e-this.beat.voice.bar.staff.displayTranspositionPitch}get hasQuarterToneOffset(){return this.hasBend?this.bendPoints[0].value%2!=0:this.bendOrigin?this.bendOrigin.bendPoints[this.bendOrigin.bendPoints.length-1].value%2!=0:this.beat.hasWhammyBar?this.beat.whammyBarPoints[0].value%2!=0:!!this.beat.isContinuedWhammy&&this.beat.previousBeat.whammyBarPoints[this.beat.previousBeat.whammyBarPoints.length-1].value%2!=0}addBendPoint(e){let t=this.bendPoints;null===t&&(t=[],this.bendPoints=t),t.push(e),(!this.maxBendPoint||e.value>this.maxBendPoint.value)&&(this.maxBendPoint=e),this.bendType===y.None&&(this.bendType=y.Custom)}finish(e,t=null){const s=new St((()=>Nt.nextNoteOnSameLine(this))),i=e&&e.notation.notationMode===k.SongBook;if(this.isTieDestination&&(this.chain(t),i&&this.tieOrigin&&this.tieOrigin.isLetRing&&(this.isLetRing=!0)),this.isLetRing&&(s.value&&s.value.isLetRing?this.letRingDestination=s.value:this.letRingDestination=this,i&&this.isTieDestination&&!this.tieOrigin.hasBend&&(this.isVisible=!1)),this.isPalmMute&&(s.value&&s.value.isPalmMute?this.palmMuteDestination=s.value:this.palmMuteDestination=this),this.isHammerPullOrigin){const e=Nt.findHammerPullDestination(this);e?(this.hammerPullDestination=e,e.hammerPullOrigin=this):this.isHammerPullOrigin=!1}switch(this.slideOutType){case K.Shift:case K.Legato:this.slideTarget||(this.slideTarget=s.value),this.slideTarget?this.slideTarget.slideOrigin=this:this.slideOutType=K.None}let a=null;this.isHammerPullOrigin&&this.hammerPullDestination?a=this.hammerPullDestination:this.slideOutType===K.Legato&&this.slideTarget&&(a=this.slideTarget),a&&(this.hasEffectSlur=!0,this.effectSlurOrigin&&this.beat.pickStroke===Q.None?(this.effectSlurOrigin.effectSlurDestination=a,this.effectSlurOrigin.effectSlurDestination.effectSlurOrigin=this.effectSlurOrigin,this.effectSlurOrigin=null):(this.isEffectSlurOrigin=!0,this.effectSlurDestination=a,this.effectSlurDestination.effectSlurOrigin=this));const r=this.bendPoints,n=null!=r&&r.length>0;if(n){const e=this.isTieDestination&&this.tieOrigin.hasBend;this.isContinuedBend=e}else this.bendType=y.None;if(n&&this.bendType===y.Custom)if(4===r.length){const e=r[0],t=r[1],s=r[2],i=r[3];t.value===s.value?i.value>e.value?t.value>i.value?this.bendType=y.BendRelease:!this.isContinuedBend&&e.value>0?(this.bendType=y.PrebendBend,r.splice(2,1),r.splice(1,1)):(this.bendType=y.Bend,r.splice(2,1),r.splice(1,1)):i.value<e.value?this.isContinuedBend?(this.bendType=y.Release,r.splice(2,1),r.splice(1,1)):(this.bendType=y.PrebendRelease,r.splice(2,1),r.splice(1,1)):t.value>e.value?this.bendType=y.BendRelease:e.value>0&&!this.isContinuedBend?(this.bendType=y.Prebend,r.splice(2,1),r.splice(1,1)):(this.bendType=y.Hold,r.splice(2,1),r.splice(1,1)):wt.warning("Model","Unsupported bend type detected, fallback to custom",null)}else if(2===r.length){const e=r[0],t=r[1];t.value>e.value?!this.isContinuedBend&&e.value>0?this.bendType=y.PrebendBend:this.bendType=y.Bend:t.value<e.value?this.isContinuedBend?this.bendType=y.Release:this.bendType=y.PrebendRelease:e.value>0&&!this.isContinuedBend?this.bendType=y.Prebend:this.bendType=y.Hold}this.initialBendValue>0&&(this.accidentalMode=N.Default)}static nextNoteOnSameLine(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+Nt.MaxOffsetForSameLineSearch;){const s=t.getNoteOnString(e.string);if(s)return s;t=t.nextBeat}return null}static findHammerPullDestination(e){let t=e.beat.nextBeat;for(;t&&t.voice.bar.index<=e.beat.voice.bar.index+Nt.MaxOffsetForSameLineSearch;){let s=t.getNoteOnString(e.string);if(s)return s;for(let i=e.string;i>0;i--)if(s=t.getNoteOnString(i),s){if(s.isLeftHandTapped)return s;break}for(let i=e.string;i<=e.beat.voice.bar.staff.tuning.length;i++)if(s=t.getNoteOnString(i),s){if(s.isLeftHandTapped)return s;break}t=t.nextBeat}return null}static findTieOrigin(e){let t=e.beat.previousBeat;for(;t&&t.voice.bar.index>=e.beat.voice.bar.index-Nt.MaxOffsetForSameLineSearch;){if(e.isStringed){const s=t.getNoteOnString(e.string);if(s)return s}else if(-1===e.octave&&-1===e.tone){if(e.index<t.notes.length)return t.notes[e.index]}else{const s=t.getNoteWithRealValue(e.realValue);if(s)return s}t=t.previousBeat}return null}chain(e=null){if(null!==e)if(null!==this._noteIdBag){let t;e.has(Nt.NoteIdLookupKey)?t=e.get(Nt.NoteIdLookupKey):(t=new Map,e.set(Nt.NoteIdLookupKey,t)),-1===this._noteIdBag.hammerPullDestinationNoteId&&-1===this._noteIdBag.tieDestinationNoteId&&-1===this._noteIdBag.slurDestinationNoteId&&-1===this._noteIdBag.slideTargetNoteId||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),-1!==this._noteIdBag.slideOriginNoteId&&(this.slideOrigin=t.get(this._noteIdBag.slideOriginNoteId),this.slideOrigin.slideTarget=this),this._noteIdBag=null}else{if(!this.isTieDestination&&null===this.tieOrigin)return;const e=this.tieOrigin??Nt.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),null!==this.slideTarget&&e.set("slidetargetnoteid",this.slideTarget.id),null!==this.slideOrigin&&e.set("slideoriginnoteid",this.slideOrigin.id)}setProperty(e,t){switch(e){case"tiedestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new kt),this._noteIdBag.tieDestinationNoteId=t,!0;case"tieoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new kt),this._noteIdBag.tieOriginNoteId=t,!0;case"slurdestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new kt),this._noteIdBag.slurDestinationNoteId=t,!0;case"sluroriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new kt),this._noteIdBag.slurOriginNoteId=t,!0;case"hammerpulloriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new kt),this._noteIdBag.hammerPullOriginNoteId=t,!0;case"hammerpulldestinationnoteid":return null==this._noteIdBag&&(this._noteIdBag=new kt),this._noteIdBag.hammerPullDestinationNoteId=t,!0;case"slidetargetnoteid":return null==this._noteIdBag&&(this._noteIdBag=new kt),this._noteIdBag.slideTargetNoteId=t,!0;case"slideoriginnoteid":return null==this._noteIdBag&&(this._noteIdBag=new kt),this._noteIdBag.slideOriginNoteId=t,!0}return!1}}Nt.GlobalNoteId=0,Nt.MaxOffsetForSameLineSearch=3,Nt.NoteIdLookupKey="NoteIdLookup";class xt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>xt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;t.set("notehead",e.noteHead),t.set("noteheadcenteronstem",e.noteHeadCenterOnStem);{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),ke.toJson(i))}return t}static setProperty(e,t,s){switch(t){case"notehead":return e.noteHead=Ne.parseEnum(s,G),!0;case"noteheadcenteronstem":return e.noteHeadCenterOnStem=s,!0;case"colors":return e.colors=new Map,Ne.forEach(s,((t,s)=>{e.colors.set(Ne.parseEnum(s,ee),ke.fromJson(t))})),!0}return!1}}class vt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>vt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("accentuated",e.accentuated),t.set("bendtype",e.bendType),t.set("bendstyle",e.bendStyle),t.set("iscontinuedbend",e.isContinuedBend),null!==e.bendPoints&&t.set("bendpoints",e.bendPoints?.map((e=>bt.toJson(e)))),t.set("fret",e.fret),t.set("string",e.string),t.set("showstringnumber",e.showStringNumber),t.set("octave",e.octave),t.set("tone",e.tone),t.set("percussionarticulation",e.percussionArticulation),t.set("isvisible",e.isVisible),t.set("islefthandtapped",e.isLeftHandTapped),t.set("ishammerpullorigin",e.isHammerPullOrigin),t.set("isslurdestination",e.isSlurDestination),t.set("harmonictype",e.harmonicType),t.set("harmonicvalue",e.harmonicValue),t.set("isghost",e.isGhost),t.set("isletring",e.isLetRing),t.set("ispalmmute",e.isPalmMute),t.set("isdead",e.isDead),t.set("isstaccato",e.isStaccato),t.set("slideintype",e.slideInType),t.set("slideouttype",e.slideOutType),t.set("vibrato",e.vibrato),t.set("istiedestination",e.isTieDestination),t.set("lefthandfinger",e.leftHandFinger),t.set("righthandfinger",e.rightHandFinger),t.set("trillvalue",e.trillValue),t.set("trillspeed",e.trillSpeed),t.set("durationpercent",e.durationPercent),t.set("accidentalmode",e.accidentalMode),t.set("dynamics",e.dynamics),t.set("ornament",e.ornament),e.style&&t.set("style",xt.toJson(e.style)),e.toJson(t),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"accentuated":return e.accentuated=Ne.parseEnum(s,u),!0;case"bendtype":return e.bendType=Ne.parseEnum(s,y),!0;case"bendstyle":return e.bendStyle=Ne.parseEnum(s,f),!0;case"iscontinuedbend":return e.isContinuedBend=s,!0;case"bendpoints":if(s){e.bendPoints=[];for(const t of s){const s=new ge;bt.fromJson(s,t),e.addBendPoint(s)}}return!0;case"fret":return e.fret=s,!0;case"string":return e.string=s,!0;case"showstringnumber":return e.showStringNumber=s,!0;case"octave":return e.octave=s,!0;case"tone":return e.tone=s,!0;case"percussionarticulation":return e.percussionArticulation=s,!0;case"isvisible":return e.isVisible=s,!0;case"islefthandtapped":return e.isLeftHandTapped=s,!0;case"ishammerpullorigin":return e.isHammerPullOrigin=s,!0;case"isslurdestination":return e.isSlurDestination=s,!0;case"harmonictype":return e.harmonicType=Ne.parseEnum(s,H),!0;case"harmonicvalue":return e.harmonicValue=s,!0;case"isghost":return e.isGhost=s,!0;case"isletring":return e.isLetRing=s,!0;case"ispalmmute":return e.isPalmMute=s,!0;case"isdead":return e.isDead=s,!0;case"isstaccato":return e.isStaccato=s,!0;case"slideintype":return e.slideInType=Ne.parseEnum(s,q),!0;case"slideouttype":return e.slideOutType=Ne.parseEnum(s,K),!0;case"vibrato":return e.vibrato=Ne.parseEnum(s,j),!0;case"istiedestination":return e.isTieDestination=s,!0;case"lefthandfinger":return e.leftHandFinger=Ne.parseEnum(s,_),!0;case"righthandfinger":return e.rightHandFinger=Ne.parseEnum(s,_),!0;case"trillvalue":return e.trillValue=s,!0;case"trillspeed":return e.trillSpeed=Ne.parseEnum(s,D),!0;case"durationpercent":return e.durationPercent=s,!0;case"accidentalmode":return e.accidentalMode=Ne.parseEnum(s,N),!0;case"dynamics":return e.dynamics=Ne.parseEnum(s,E),!0;case"ornament":return e.ornament=Ne.parseEnum(s,Z),!0;case"style":return s?(e.style=new Tt,xt.fromJson(e.style,s)):e.style=void 0,!0}return e.setProperty(t,s)}}class Pt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>Pt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),ke.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,Ne.forEach(s,((t,s)=>{e.colors.set(Ne.parseEnum(s,ds),ke.fromJson(t))})),!0)}}!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"}(te||(te={})),function(e){e[e.Up=0]="Up",e[e.Down=1]="Down"}(se||(se={})),function(e){e[e.None=0]="None",e[e.Open=1]="Open",e[e.Closed=2]="Closed"}(ie||(ie={})),function(e){e[e.None=0]="None",e[e.Ii=1]="Ii",e[e.Mi=2]="Mi",e[e.MiiTriplet=3]="MiiTriplet",e[e.MiiAnapaest=4]="MiiAnapaest",e[e.PmpTriplet=5]="PmpTriplet",e[e.PmpAnapaest=6]="PmpAnapaest",e[e.PeiTriplet=7]="PeiTriplet",e[e.PeiAnapaest=8]="PeiAnapaest",e[e.PaiTriplet=9]="PaiTriplet",e[e.PaiAnapaest=10]="PaiAnapaest",e[e.AmiTriplet=11]="AmiTriplet",e[e.AmiAnapaest=12]="AmiAnapaest",e[e.Ppp=13]="Ppp",e[e.Amii=14]="Amii",e[e.Amip=15]="Amip",e[e.Eami=16]="Eami",e[e.Eamii=17]="Eamii",e[e.Peami=18]="Peami"}(ae||(ae={}));class Ft{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>Ft.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("notes",e.notes.map((e=>vt.toJson(e)))),t.set("isempty",e.isEmpty),t.set("whammystyle",e.whammyStyle),t.set("ottava",e.ottava),t.set("islegatoorigin",e.isLegatoOrigin),t.set("duration",e.duration),t.set("automations",e.automations.map((e=>gt.toJson(e)))),t.set("dots",e.dots),t.set("fade",e.fade),t.set("lyrics",e.lyrics),t.set("pop",e.pop),t.set("slap",e.slap),t.set("tap",e.tap),t.set("text",e.text),t.set("slashed",e.slashed),t.set("deadslapped",e.deadSlapped),t.set("brushtype",e.brushType),t.set("brushduration",e.brushDuration),t.set("tupletdenominator",e.tupletDenominator),t.set("tupletnumerator",e.tupletNumerator),t.set("iscontinuedwhammy",e.isContinuedWhammy),t.set("whammybartype",e.whammyBarType),null!==e.whammyBarPoints&&t.set("whammybarpoints",e.whammyBarPoints?.map((e=>bt.toJson(e)))),t.set("vibrato",e.vibrato),t.set("chordid",e.chordId),t.set("gracetype",e.graceType),t.set("pickstroke",e.pickStroke),t.set("tremolospeed",e.tremoloSpeed),t.set("crescendo",e.crescendo),t.set("displaystart",e.displayStart),t.set("playbackstart",e.playbackStart),t.set("displayduration",e.displayDuration),t.set("playbackduration",e.playbackDuration),t.set("overridedisplayduration",e.overrideDisplayDuration),t.set("golpe",e.golpe),t.set("dynamics",e.dynamics),t.set("invertbeamdirection",e.invertBeamDirection),t.set("preferredbeamdirection",e.preferredBeamDirection),t.set("beamingmode",e.beamingMode),t.set("wahpedal",e.wahPedal),t.set("barrefret",e.barreFret),t.set("barreshape",e.barreShape),t.set("rasgueado",e.rasgueado),t.set("showtimer",e.showTimer),t.set("timer",e.timer),e.style&&t.set("style",Pt.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"notes":e.notes=[];for(const t of s){const s=new Nt;vt.fromJson(s,t),e.addNote(s)}return!0;case"isempty":return e.isEmpty=s,!0;case"whammystyle":return e.whammyStyle=Ne.parseEnum(s,f),!0;case"ottava":return e.ottava=Ne.parseEnum(s,o),!0;case"islegatoorigin":return e.isLegatoOrigin=s,!0;case"duration":return e.duration=Ne.parseEnum(s,D),!0;case"automations":e.automations=[];for(const t of s){const s=new pe;gt.fromJson(s,t),e.automations.push(s)}return!0;case"dots":return e.dots=s,!0;case"fade":return e.fade=Ne.parseEnum(s,L),!0;case"lyrics":return e.lyrics=s,!0;case"pop":return e.pop=s,!0;case"slap":return e.slap=s,!0;case"tap":return e.tap=s,!0;case"text":return e.text=s,!0;case"slashed":return e.slashed=s,!0;case"deadslapped":return e.deadSlapped=s,!0;case"brushtype":return e.brushType=Ne.parseEnum(s,b),!0;case"brushduration":return e.brushDuration=s,!0;case"tupletdenominator":return e.tupletDenominator=s,!0;case"tupletnumerator":return e.tupletNumerator=s,!0;case"iscontinuedwhammy":return e.isContinuedWhammy=s,!0;case"whammybartype":return e.whammyBarType=Ne.parseEnum(s,te),!0;case"whammybarpoints":if(s){e.whammyBarPoints=[];for(const t of s){const s=new ge;bt.fromJson(s,t),e.addWhammyBarPoint(s)}}return!0;case"vibrato":return e.vibrato=Ne.parseEnum(s,j),!0;case"chordid":return e.chordId=s,!0;case"gracetype":return e.graceType=Ne.parseEnum(s,R),!0;case"pickstroke":return e.pickStroke=Ne.parseEnum(s,Q),!0;case"tremolospeed":return e.tremoloSpeed=Ne.parseEnum(s,D)??null,!0;case"crescendo":return e.crescendo=Ne.parseEnum(s,F),!0;case"displaystart":return e.displayStart=s,!0;case"playbackstart":return e.playbackStart=s,!0;case"displayduration":return e.displayDuration=s,!0;case"playbackduration":return e.playbackDuration=s,!0;case"overridedisplayduration":return e.overrideDisplayDuration=s,!0;case"golpe":return e.golpe=Ne.parseEnum(s,O),!0;case"dynamics":return e.dynamics=Ne.parseEnum(s,E),!0;case"invertbeamdirection":return e.invertBeamDirection=s,!0;case"preferredbeamdirection":return e.preferredBeamDirection=Ne.parseEnum(s,se)??null,!0;case"beamingmode":return e.beamingMode=Ne.parseEnum(s,cs),!0;case"wahpedal":return e.wahPedal=Ne.parseEnum(s,ie),!0;case"barrefret":return e.barreFret=s,!0;case"barreshape":return e.barreShape=Ne.parseEnum(s,m),!0;case"rasgueado":return e.rasgueado=Ne.parseEnum(s,ae),!0;case"showtimer":return e.showTimer=s,!0;case"timer":return e.timer=s,!0;case"style":return s?(e.style=new ps,Pt.fromJson(e.style,s)):e.style=void 0,!0}return!1}}!function(e){e[e.Glyphs=0]="Glyphs"}(re||(re={}));class Ct extends le{}let Dt=class e{constructor(){this._isEmpty=!0,this._isRestOnly=!0,this.id=e._globalVoiceId++,this.index=0,this.beats=[]}static resetIds(){e._globalVoiceId=0}get isEmpty(){return this._isEmpty}forceNonEmpty(){this._isEmpty=!1}get isRestOnly(){return this._isRestOnly}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),e.isRest||(this._isRestOnly=!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){const 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);const t=this.beats[this.beats.length-1];this.beats.splice(this.beats.length-1,1),this.addBeat(e),this.addBeat(t),this._isEmpty=!1,this._isRestOnly=!1}getBeatAtPlaybackStart(e){return this._beatLookup.has(e)?this._beatLookup.get(e):null}finish(e,t=null){this._isEmpty=!0,this._isRestOnly=!0,this._beatLookup=new Map;let s=null;for(let e=0;e<this.beats.length;e++){const i=this.beats[e];i.index=e,this.chain(i,t),i.graceType===R.None?(i.graceGroup=s,s&&(s.isComplete=!0),s=null):(s||(s=new Fe),s.addBeat(i)),i.isEmpty||(this._isEmpty=!1),i.isRest||(this._isRestOnly=!1)}let i=0,a=0;for(let s=0;s<this.beats.length;s++){const r=this.beats[s];if(r.index=s,r.finish(e,t),r.graceType===R.None){if(r.graceGroup){const e=r.graceGroup.beats[0],t=r.graceGroup.beats[r.graceGroup.beats.length-1];if(e.graceType!==R.BendGrace){const s=t.playbackStart+t.playbackDuration-e.playbackStart;switch(e.graceType){case R.BeforeBeat:e.previousBeat?(e.previousBeat.playbackDuration-=s,a=e.previousBeat.voice===this?e.previousBeat.playbackStart+e.previousBeat.playbackDuration:-s):a=-s;for(const e of r.graceGroup.beats)this._beatLookup.delete(e.playbackStart),e.playbackStart=a,this._beatLookup.set(e.playbackStart,r),a+=e.playbackDuration;break;case R.OnBeat:r.playbackDuration-=s,a=t.voice===this?t.playbackStart+t.playbackDuration:-s}}}r.displayStart=i,r.playbackStart=a,r.fermata?this.bar.masterBar.addFermata(r.playbackStart,r.fermata):r.fermata=this.bar.masterBar.getFermata(r),this._beatLookup.set(r.playbackStart,r)}else r.displayStart=i,r.playbackStart=a;r.finishTuplet(),r.graceGroup&&r.graceGroup.finish(),i+=r.displayDuration,a+=r.playbackDuration}}calculateDuration(){if(this.isEmpty||0===this.beats.length)return 0;const e=this.beats[this.beats.length-1],t=this.beats[0];return e.playbackStart+e.playbackDuration-t.playbackStart}};Dt._globalVoiceId=0;class Et{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>Et.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),ke.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,Ne.forEach(s,((t,s)=>{e.colors.set(Ne.parseEnum(s,re),ke.fromJson(t))})),!0)}}class Lt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>Lt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("beats",e.beats.map((e=>Ft.toJson(e)))),e.style&&t.set("style",Et.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"beats":e.beats=[];for(const t of s){const s=new gs;Ft.fromJson(s,t),e.addBeat(s)}return!0;case"style":return s?(e.style=new Ct,Et.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class Mt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>Mt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("ratioposition",e.ratioPosition),t.set("pedaltype",e.pedalType),t}static setProperty(e,t,s){switch(t){case"ratioposition":return e.ratioPosition=s,!0;case"pedaltype":return e.pedalType=Ne.parseEnum(s,l),!0}return!1}}class It{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>It.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),ke.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,Ne.forEach(s,((t,s)=>{e.colors.set(Ne.parseEnum(s,c),ke.fromJson(t))})),!0)}}class At{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>At.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("id",e.id),t.set("clef",e.clef),t.set("clefottava",e.clefOttava),t.set("voices",e.voices.map((e=>Lt.toJson(e)))),t.set("similemark",e.simileMark),t.set("displayscale",e.displayScale),t.set("displaywidth",e.displayWidth),t.set("sustainpedals",e.sustainPedals.map((e=>Mt.toJson(e)))),t.set("barlineleft",e.barLineLeft),t.set("barlineright",e.barLineRight),e.style&&t.set("style",It.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"id":return e.id=s,!0;case"clef":return e.clef=Ne.parseEnum(s,n),!0;case"clefottava":return e.clefOttava=Ne.parseEnum(s,o),!0;case"voices":e.voices=[];for(const t of s){const s=new Dt;Lt.fromJson(s,t),e.addVoice(s)}return!0;case"similemark":return e.simileMark=Ne.parseEnum(s,h),!0;case"displayscale":return e.displayScale=s,!0;case"displaywidth":return e.displayWidth=s,!0;case"sustainpedals":e.sustainPedals=[];for(const t of s){const s=new ce;Mt.fromJson(s,t),e.sustainPedals.push(s)}return!0;case"barlineleft":return e.barLineLeft=Ne.parseEnum(s,d),!0;case"barlineright":return e.barLineRight=Ne.parseEnum(s,d),!0;case"style":return s?(e.style=new de,It.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class Rt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>Rt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("name",e.name),t.set("firstfret",e.firstFret),t.set("strings",e.strings),t.set("barrefrets",e.barreFrets),t.set("showname",e.showName),t.set("showdiagram",e.showDiagram),t.set("showfingering",e.showFingering),t}static setProperty(e,t,s){switch(t){case"name":return e.name=s,!0;case"firstfret":return e.firstFret=s,!0;case"strings":return e.strings=s,!0;case"barrefrets":return e.barreFrets=s,!0;case"showname":return e.showName=s,!0;case"showdiagram":return e.showDiagram=s,!0;case"showfingering":return e.showFingering=s,!0}return!1}}class Ot{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>Ot.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("isstandard",e.isStandard),t.set("name",e.name),t.set("tunings",e.tunings),t}static setProperty(e,t,s){switch(t){case"isstandard":return e.isStandard=s,!0;case"name":return e.name=s,!0;case"tunings":return e.tunings=s,!0}return!1}}class Ht{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>Ht.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("bars",e.bars.map((e=>At.toJson(e)))),null!==e.chords){const s=new Map;t.set("chords",s);for(const[t,i]of e.chords)s.set(t.toString(),Rt.toJson(i))}return t.set("capo",e.capo),t.set("transpositionpitch",e.transpositionPitch),t.set("displaytranspositionpitch",e.displayTranspositionPitch),t.set("stringtuning",Ot.toJson(e.stringTuning)),t.set("showslash",e.showSlash),t.set("shownumbered",e.showNumbered),t.set("showtablature",e.showTablature),t.set("showstandardnotation",e.showStandardNotation),t.set("ispercussion",e.isPercussion),t.set("standardnotationlinecount",e.standardNotationLineCount),t}static setProperty(e,t,s){switch(t){case"bars":e.bars=[];for(const t of s){const s=new ue;At.fromJson(s,t),e.addBar(s)}return!0;case"chords":return e.chords=new Map,Ne.forEach(s,((t,s)=>{const i=new me;Rt.fromJson(i,t),e.addChord(s,i)})),!0;case"capo":return e.capo=s,!0;case"transpositionpitch":return e.transpositionPitch=s,!0;case"displaytranspositionpitch":return e.displayTranspositionPitch=s,!0;case"stringtuning":return Ot.fromJson(e.stringTuning,s),!0;case"showslash":return e.showSlash=s,!0;case"shownumbered":return e.showNumbered=s,!0;case"showtablature":return e.showTablature=s,!0;case"showstandardnotation":return e.showStandardNotation=s,!0;case"ispercussion":return e.isPercussion=s,!0;case"standardnotationlinecount":return e.standardNotationLineCount=s,!0}return!1}}class Wt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>Wt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("volume",e.volume),t.set("balance",e.balance),t.set("port",e.port),t.set("program",e.program),t.set("primarychannel",e.primaryChannel),t.set("secondarychannel",e.secondaryChannel),t.set("ismute",e.isMute),t.set("issolo",e.isSolo),t}static setProperty(e,t,s){switch(t){case"volume":return e.volume=s,!0;case"balance":return e.balance=s,!0;case"port":return e.port=s,!0;case"program":return e.program=s,!0;case"primarychannel":return e.primaryChannel=s,!0;case"secondarychannel":return e.secondaryChannel=s,!0;case"ismute":return e.isMute=s,!0;case"issolo":return e.isSolo=s,!0}return!1}}class Vt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>Vt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("elementtype",e.elementType),t.set("staffline",e.staffLine),t.set("noteheaddefault",e.noteHeadDefault),t.set("noteheadhalf",e.noteHeadHalf),t.set("noteheadwhole",e.noteHeadWhole),t.set("techniquesymbol",e.techniqueSymbol),t.set("techniquesymbolplacement",e.techniqueSymbolPlacement),t.set("outputmidinumber",e.outputMidiNumber),t}static setProperty(e,t,s){switch(t){case"elementtype":return e.elementType=s,!0;case"staffline":return e.staffLine=s,!0;case"noteheaddefault":return e.noteHeadDefault=Ne.parseEnum(s,G),!0;case"noteheadhalf":return e.noteHeadHalf=Ne.parseEnum(s,G),!0;case"noteheadwhole":return e.noteHeadWhole=Ne.parseEnum(s,G),!0;case"techniquesymbol":return e.techniqueSymbol=Ne.parseEnum(s,G),!0;case"techniquesymbolplacement":return e.techniqueSymbolPlacement=Ne.parseEnum(s,V),!0;case"outputmidinumber":return e.outputMidiNumber=s,!0}return!1}}class Gt{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 zt{static getTextForTuning(e,t){const s=zt.getTextPartsForTuning(e);return t?s.join(""):s[0]}static getTextPartsForTuning(e,t=-1){return[["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"][e%12],((e/12|0)+t).toString()]}static getDefaultTuningFor(e){return zt._defaultTunings.has(e)?zt._defaultTunings.get(e):null}static getPresetsFor(e){switch(e){case 7:return zt._sevenStrings;case 6:return zt._sixStrings;case 5:return zt._fiveStrings;case 4:return zt._fourStrings}return[]}static initialize(){zt._defaultTunings.set(7,new zt("Guitar 7 strings",[64,59,55,50,45,40,35],!0)),zt._sevenStrings.push(zt._defaultTunings.get(7)),zt._defaultTunings.set(6,new zt("Guitar Standard Tuning",[64,59,55,50,45,40],!0)),zt._sixStrings.push(zt._defaultTunings.get(6)),zt._sixStrings.push(new zt("Guitar Tune down ½ step",[63,58,54,49,44,39],!1)),zt._sixStrings.push(new zt("Guitar Tune down 1 step",[62,57,53,48,43,38],!1)),zt._sixStrings.push(new zt("Guitar Tune down 2 step",[60,55,51,46,41,36],!1)),zt._sixStrings.push(new zt("Guitar Dropped D Tuning",[64,59,55,50,45,38],!1)),zt._sixStrings.push(new zt("Guitar Dropped D Tuning variant",[64,57,55,50,45,38],!1)),zt._sixStrings.push(new zt("Guitar Double Dropped D Tuning",[62,59,55,50,45,38],!1)),zt._sixStrings.push(new zt("Guitar Dropped E Tuning",[66,61,57,52,47,40],!1)),zt._sixStrings.push(new zt("Guitar Dropped C Tuning",[62,57,53,48,43,36],!1)),zt._sixStrings.push(new zt("Guitar Open C Tuning",[64,60,55,48,43,36],!1)),zt._sixStrings.push(new zt("Guitar Open Cm Tuning",[63,60,55,48,43,36],!1)),zt._sixStrings.push(new zt("Guitar Open C6 Tuning",[64,57,55,48,43,36],!1)),zt._sixStrings.push(new zt("Guitar Open Cmaj7 Tuning",[64,59,55,52,43,36],!1)),zt._sixStrings.push(new zt("Guitar Open D Tuning",[62,57,54,50,45,38],!1)),zt._sixStrings.push(new zt("Guitar Open Dm Tuning",[62,57,53,50,45,38],!1)),zt._sixStrings.push(new zt("Guitar Open D5 Tuning",[62,57,50,50,45,38],!1)),zt._sixStrings.push(new zt("Guitar Open D6 Tuning",[62,59,54,50,45,38],!1)),zt._sixStrings.push(new zt("Guitar Open Dsus4 Tuning",[62,57,55,50,45,38],!1)),zt._sixStrings.push(new zt("Guitar Open E Tuning",[64,59,56,52,47,40],!1)),zt._sixStrings.push(new zt("Guitar Open Em Tuning",[64,59,55,52,47,40],!1)),zt._sixStrings.push(new zt("Guitar Open Esus11 Tuning",[64,59,55,52,45,40],!1)),zt._sixStrings.push(new zt("Guitar Open F Tuning",[65,60,53,48,45,41],!1)),zt._sixStrings.push(new zt("Guitar Open G Tuning",[62,59,55,50,43,38],!1)),zt._sixStrings.push(new zt("Guitar Open Gm Tuning",[62,58,55,50,43,38],!1)),zt._sixStrings.push(new zt("Guitar Open G6 Tuning",[64,59,55,50,43,38],!1)),zt._sixStrings.push(new zt("Guitar Open Gsus4 Tuning",[62,60,55,50,43,38],!1)),zt._sixStrings.push(new zt("Guitar Open A Tuning",[64,61,57,52,45,40],!1)),zt._sixStrings.push(new zt("Guitar Open Am Tuning",[64,60,57,52,45,40],!1)),zt._sixStrings.push(new zt("Guitar Nashville Tuning",[64,59,67,62,57,52],!1)),zt._sixStrings.push(new zt("Bass 6 Strings Tuning",[48,43,38,33,28,23],!1)),zt._sixStrings.push(new zt("Lute or Vihuela Tuning",[64,59,54,50,45,40],!1)),zt._defaultTunings.set(5,new zt("Bass 5 Strings Tuning",[43,38,33,28,23],!0)),zt._fiveStrings.push(zt._defaultTunings.get(5)),zt._fiveStrings.push(new zt("Banjo Dropped C Tuning",[62,59,55,48,67],!1)),zt._fiveStrings.push(new zt("Banjo Open D Tuning",[62,57,54,50,69],!1)),zt._fiveStrings.push(new zt("Banjo Open G Tuning",[62,59,55,50,67],!1)),zt._fiveStrings.push(new zt("Banjo G Minor Tuning",[62,58,55,50,67],!1)),zt._fiveStrings.push(new zt("Banjo G Modal Tuning",[62,57,55,50,67],!1)),zt._defaultTunings.set(4,new zt("Bass Standard Tuning",[43,38,33,28],!0)),zt._fourStrings.push(zt._defaultTunings.get(4)),zt._fourStrings.push(new zt("Bass Tune down ½ step",[42,37,32,27],!1)),zt._fourStrings.push(new zt("Bass Tune down 1 step",[41,36,31,26],!1)),zt._fourStrings.push(new zt("Bass Tune down 2 step",[39,34,29,24],!1)),zt._fourStrings.push(new zt("Bass Dropped D Tuning",[43,38,33,26],!1)),zt._fourStrings.push(new zt("Ukulele C Tuning",[45,40,36,43],!1)),zt._fourStrings.push(new zt("Ukulele G Tuning",[52,47,43,38],!1)),zt._fourStrings.push(new zt("Mandolin Standard Tuning",[64,57,50,43],!1)),zt._fourStrings.push(new zt("Mandolin or Violin Tuning",[76,69,62,55],!1)),zt._fourStrings.push(new zt("Viola Tuning",[69,62,55,48],!1)),zt._fourStrings.push(new zt("Cello Tuning",[57,50,43,36],!1))}static findTuning(e){const t=zt.getPresetsFor(e.length);for(let s=0,i=t.length;s<i;s++){const i=t[s];let a=!0;for(let t=0,s=e.length;t<s;t++)if(e[t]!==i.tunings[t]){a=!1;break}if(a)return i}return null}constructor(e="",t=null,s=!1){this.isStandard=s,this.name=e,this.tunings=t??[]}finish(){const e=zt.findTuning(this.tunings);e&&(this.name=e.name,this.isStandard=e.isStandard),this.name=this.name.trim()}}zt._sevenStrings=[],zt._sixStrings=[],zt._fiveStrings=[],zt._fourStrings=[],zt._defaultTunings=new Map,zt.defaultAccidentals=["","#","","#","","","#","","#","","#",""],zt.defaultSteps=["C","C","D","D","E","F","F","G","G","A","A","B"],zt.initialize();class Ut{constructor(){this.index=0,this.bars=[],this.chords=null,this.capo=0,this.transpositionPitch=0,this.displayTranspositionPitch=0,this.stringTuning=new zt("",[],!1),this.showSlash=!1,this.showNumbered=!1,this.showTablature=!0,this.showStandardNotation=!0,this.isPercussion=!1,this.standardNotationLineCount=Ut.DefaultStandardNotationLineCount}get tuning(){return this.stringTuning.tunings}get tuningName(){return this.stringTuning.name}get isStringed(){return this.stringTuning.tunings.length>0}finish(e,t=null){this.stringTuning.finish();for(let s=0,i=this.bars.length;s<i;s++)this.bars[s].finish(e,t)}addChord(e,t){t.staff=this;let s=this.chords;null===s&&(s=new Map,this.chords=s),s.set(e,t)}hasChord(e){return this.chords?.has(e)??!1}getChord(e){return this.chords?.get(e)??null}addBar(e){const 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)}}var Xt,Jt;Ut.DefaultStandardNotationLineCount=5,function(e){e[e.TrackName=0]="TrackName",e[e.BracesAndBrackets=1]="BracesAndBrackets",e[e.SystemSeparator=2]="SystemSeparator",e[e.StringTuning=3]="StringTuning"}(Xt||(Xt={}));class Yt extends le{}class $t{constructor(){this.index=0,this.staves=[],this.playbackInfo=new Gt,this.color=new ke(200,0,0,255),this.name="",this.isVisibleOnMultiTrack=!0,this.shortName="",this.defaultSystemsLayout=3,this.systemsLayout=[],this.percussionArticulations=[]}addLineBreaks(e){this.lineBreaks||(this.lineBreaks=new Set),this.lineBreaks.add(e)}ensureStaveCount(e){for(;this.staves.length<e;)this.addStaff(new Ut)}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>$t.ShortNameMaxLength&&(this.shortName=this.shortName.substr(0,$t.ShortNameMaxLength)));for(let s=0,i=this.staves.length;s<i;s++)this.staves[s].finish(e,t)}applyLyrics(e){for(const t of e)t.finish();const t=this.staves[0];for(let s=0;s<e.length;s++){const i=e[s];if(i.startBar>=0&&i.startBar<t.bars.length){let a=t.bars[i.startBar].voices[0].beats[0];for(let t=0;t<i.chunks.length&&a;t++){for(;a&&(a.isEmpty||a.isRest);)a=a.nextBeat;a&&(a.lyrics||(a.lyrics=new Array(e.length),a.lyrics.fill("")),a.lyrics[s]=i.chunks[t],a=a.nextBeat)}}}}}$t.ShortNameMaxLength=10;class qt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>qt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),ke.toJson(i))}return t}static setProperty(e,t,s){return"colors"===t&&(e.colors=new Map,Ne.forEach(s,((t,s)=>{e.colors.set(Ne.parseEnum(s,Xt),ke.fromJson(t))})),!0)}}class Kt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>Kt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("staves",e.staves.map((e=>Ht.toJson(e)))),t.set("playbackinfo",Wt.toJson(e.playbackInfo)),t.set("color",ke.toJson(e.color)),t.set("name",e.name),t.set("isvisibleonmultitrack",e.isVisibleOnMultiTrack),t.set("shortname",e.shortName),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),void 0!==e.lineBreaks){const s=[];t.set("linebreaks",s);for(const t of e.lineBreaks)s.push(t)}return t.set("percussionarticulations",e.percussionArticulations.map((e=>Vt.toJson(e)))),e.style&&t.set("style",qt.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"staves":e.staves=[];for(const t of s){const s=new Ut;Ht.fromJson(s,t),e.addStaff(s)}return!0;case"playbackinfo":return Wt.fromJson(e.playbackInfo,s),!0;case"color":return e.color=ke.fromJson(s),!0;case"name":return e.name=s,!0;case"isvisibleonmultitrack":return e.isVisibleOnMultiTrack=s,!0;case"shortname":return e.shortName=s,!0;case"defaultsystemslayout":return e.defaultSystemsLayout=s,!0;case"systemslayout":return e.systemsLayout=s,!0;case"linebreaks":for(const t of s)e.addLineBreaks(t);return!0;case"percussionarticulations":e.percussionArticulations=[];for(const t of s){const s=new De;Vt.fromJson(s,t),e.percussionArticulations.push(s)}return!0;case"style":return s?(e.style=new Yt,qt.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class jt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>jt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;if(t.set("hidedynamics",e.hideDynamics),t.set("bracketextendmode",e.bracketExtendMode),t.set("usesystemsignseparator",e.useSystemSignSeparator),t.set("globaldisplaytuning",e.globalDisplayTuning),null!==e.perTrackDisplayTuning){const s=new Map;t.set("pertrackdisplaytuning",s);for(const[t,i]of e.perTrackDisplayTuning)s.set(t.toString(),i)}if(t.set("globaldisplaychorddiagramsontop",e.globalDisplayChordDiagramsOnTop),null!==e.perTrackChordDiagramsOnTop){const s=new Map;t.set("pertrackchorddiagramsontop",s);for(const[t,i]of e.perTrackChordDiagramsOnTop)s.set(t.toString(),i)}if(t.set("singletracktracknamepolicy",e.singleTrackTrackNamePolicy),t.set("multitracktracknamepolicy",e.multiTrackTrackNamePolicy),t.set("firstsystemtracknamemode",e.firstSystemTrackNameMode),t.set("othersystemstracknamemode",e.otherSystemsTrackNameMode),t.set("firstsystemtracknameorientation",e.firstSystemTrackNameOrientation),t.set("othersystemstracknameorientation",e.otherSystemsTrackNameOrientation),t.set("multitrackmultibarrest",e.multiTrackMultiBarRest),null!==e.perTrackMultiBarRest){const s=[];t.set("pertrackmultibarrest",s);for(const t of e.perTrackMultiBarRest)s.push(t)}return t}static setProperty(e,t,n){switch(t){case"hidedynamics":return e.hideDynamics=n,!0;case"bracketextendmode":return e.bracketExtendMode=Ne.parseEnum(n,s),!0;case"usesystemsignseparator":return e.useSystemSignSeparator=n,!0;case"globaldisplaytuning":return e.globalDisplayTuning=n,!0;case"pertrackdisplaytuning":return e.perTrackDisplayTuning=new Map,Ne.forEach(n,((t,s)=>{e.perTrackDisplayTuning.set(Number.parseInt(s),t)})),!0;case"globaldisplaychorddiagramsontop":return e.globalDisplayChordDiagramsOnTop=n,!0;case"pertrackchorddiagramsontop":return e.perTrackChordDiagramsOnTop=new Map,Ne.forEach(n,((t,s)=>{e.perTrackChordDiagramsOnTop.set(Number.parseInt(s),t)})),!0;case"singletracktracknamepolicy":return e.singleTrackTrackNamePolicy=Ne.parseEnum(n,i),!0;case"multitracktracknamepolicy":return e.multiTrackTrackNamePolicy=Ne.parseEnum(n,i),!0;case"firstsystemtracknamemode":return e.firstSystemTrackNameMode=Ne.parseEnum(n,a),!0;case"othersystemstracknamemode":return e.otherSystemsTrackNameMode=Ne.parseEnum(n,a),!0;case"firstsystemtracknameorientation":return e.firstSystemTrackNameOrientation=Ne.parseEnum(n,r),!0;case"othersystemstracknameorientation":return e.otherSystemsTrackNameOrientation=Ne.parseEnum(n,r),!0;case"multitrackmultibarrest":return e.multiTrackMultiBarRest=n,!0;case"pertrackmultibarrest":return e.perTrackMultiBarRest=new Set(n),!0}return!1}}class Qt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>Qt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("template",e.template),t.set("isvisible",e.isVisible),t.set("textalign",e.textAlign),t}static setProperty(e,t,s){switch(t){case"template":return e.template=s,!0;case"isvisible":return e.isVisible=s,!0;case"textalign":return e.textAlign=Ne.parseEnum(s,W),!0}return!1}}class Zt{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>Zt.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;{const s=new Map;t.set("headerandfooter",s);for(const[t,i]of e.headerAndFooter)s.set(t.toString(),Qt.toJson(i))}{const s=new Map;t.set("colors",s);for(const[t,i]of e.colors)s.set(t.toString(),ke.toJson(i))}return t}static setProperty(e,t,s){switch(t){case"headerandfooter":return e.headerAndFooter=new Map,Ne.forEach(s,((t,s)=>{const i=new Ps;Qt.fromJson(i,t),e.headerAndFooter.set(Ne.parseEnum(s,ws),i)})),!0;case"colors":return e.colors=new Map,Ne.forEach(s,((t,s)=>{e.colors.set(Ne.parseEnum(s,ws),ke.fromJson(t))})),!0}return!1}}class es{static fromJson(e,t){t&&Ne.forEach(t,((t,s)=>es.setProperty(e,s,t)))}static toJson(e){if(!e)return null;const t=new Map;return t.set("album",e.album),t.set("artist",e.artist),t.set("copyright",e.copyright),t.set("instructions",e.instructions),t.set("music",e.music),t.set("notices",e.notices),t.set("subtitle",e.subTitle),t.set("title",e.title),t.set("words",e.words),t.set("tab",e.tab),t.set("tempo",e.tempo),t.set("tempolabel",e.tempoLabel),t.set("masterbars",e.masterBars.map((e=>yt.toJson(e)))),t.set("tracks",e.tracks.map((e=>Kt.toJson(e)))),t.set("defaultsystemslayout",e.defaultSystemsLayout),t.set("systemslayout",e.systemsLayout),t.set("stylesheet",jt.toJson(e.stylesheet)),e.style&&t.set("style",Zt.toJson(e.style)),t}static setProperty(e,t,s){switch(t){case"album":return e.album=s,!0;case"artist":return e.artist=s,!0;case"copyright":return e.copyright=s,!0;case"instructions":return e.instructions=s,!0;case"music":return e.music=s,!0;case"notices":return e.notices=s,!0;case"subtitle":return e.subTitle=s,!0;case"title":return e.title=s,!0;case"words":return e.words=s,!0;case"tab":return e.tab=s,!0;case"tempo":return e.tempo=s,!0;case"tempolabel":return e.tempoLabel=s,!0;case"masterbars":e.masterBars=[];for(const t of s){const s=new Se;yt.fromJson(s,t),e.addMasterBar(s)}return!0;case"tracks":e.tracks=[];for(const t of s){const s=new $t;Kt.fromJson(s,t),e.addTrack(s)}return!0;case"defaultsystemslayout":return e.defaultSystemsLayout=s,!0;case"systemslayout":return e.systemsLayout=s,!0;case"stylesheet":return jt.fromJson(e.stylesheet,s),!0;case"style":return s?(e.style=new Fs,Zt.fromJson(e.style,s)):e.style=void 0,!0}return!1}}class ts{static jsonReplacer(e,t){if(t instanceof Map){if("fromEntries"in Object)return Object.fromEntries(t);const e={};for(const[s,i]of t)e[s]=i;return e}return ArrayBuffer.isView(t)?Array.apply([],[t]):t}static scoreToJson(e){const t=ts.scoreToJsObject(e);return JSON.stringify(t,ts.jsonReplacer)}static jsonToScore(e,t){return ts.jsObjectToScore(JSON.parse(e),t)}static scoreToJsObject(e){return es.toJson(e)}static jsObjectToScore(e,t){const s=new Cs;return es.fromJson(s,e),s.finish(t??new ut),s}static settingsToJson(e){const t=ts.settingsToJsObject(e);return JSON.stringify(t,ts.jsonReplacer)}static jsonToSettings(e){return ts.jsObjectToSettings(JSON.parse(e))}static settingsToJsObject(e){return dt.toJson(e)}static jsObjectToSettings(e){const t=new ut;return dt.fromJson(t,e),t}static jsObjectToMidiFile(e){const t=new Ae;return Ne.forEach(e,((e,s)=>{switch(s){case"division":t.division=e;break;case"tracks":for(const s of e){const e=ts.jsObjectToMidiTrack(s);t.tracks.push(e)}}})),t}static jsObjectToMidiTrack(e){const t=new Ie;return Ne.forEach(e,((e,s)=>{if("events"===s)for(const s of e){const e=ts.jsObjectToMidiEvent(s);t.events.push(e)}})),t}static jsObjectToMidiEvent(e){const t=Ne.getValue(e,"track"),s=Ne.getValue(e,"tick"),i=Ne.getValue(e,"type");switch(i){case U.TimeSignature:return new Oe(t,s,Ne.getValue(e,"numerator"),Ne.getValue(e,"denominatorIndex"),Ne.getValue(e,"midiClocksPerMetronomeClick"),Ne.getValue(e,"thirdySecondNodesInQuarter"));case U.AlphaTabRest:return new Ve(t,s,Ne.getValue(e,"channel"));case U.AlphaTabMetronome:return new We(t,s,Ne.getValue(e,"metronomeNumerator"),Ne.getValue(e,"metronomeDurationInTicks"),Ne.getValue(e,"metronomeDurationInMilliseconds"));case U.NoteOn:return new ze(t,s,Ne.getValue(e,"channel"),Ne.getValue(e,"noteKey"),Ne.getValue(e,"noteVelocity"));case U.NoteOff:return new Ue(t,s,Ne.getValue(e,"channel"),Ne.getValue(e,"noteKey"),Ne.getValue(e,"noteVelocity"));case U.ControlChange:return new Xe(t,s,Ne.getValue(e,"channel"),Ne.getValue(e,"controller"),Ne.getValue(e,"value"));case U.ProgramChange:return new Je(t,s,Ne.getValue(e,"channel"),Ne.getValue(e,"program"));case U.TempoChange:return new Ye(s,Ne.getValue(e,"microSecondsPerQuarterNote"));case U.PitchBend:return new $e(t,s,Ne.getValue(e,"channel"),Ne.getValue(e,"value"));case U.PerNotePitchBend:return new qe(t,s,Ne.getValue(e,"channel"),Ne.getValue(e,"noteKey"),Ne.getValue(e,"value"));case U.EndOfTrack:return new Ke(t,s)}throw new fe(S.Format,`Unknown Midi Event type: ${i}`)}static midiFileToJsObject(e){const t=new Map;t.set("division",e.division);const s=[];for(const t of e.tracks)s.push(ts.midiTrackToJsObject(t));return t.set("tracks",s),t}static midiTrackToJsObject(e){const t=new Map,s=[];for(const t of e.events)s.push(ts.midiEventToJsObject(t));return t.set("events",s),t}static midiEventToJsObject(e){const t=new Map;switch(t.set("track",e.track),t.set("tick",e.tick),t.set("type",e.type),e.type){case U.TimeSignature:t.set("numerator",e.numerator),t.set("denominatorIndex",e.denominatorIndex),t.set("midiClocksPerMetronomeClick",e.midiClocksPerMetronomeClick),t.set("thirdySecondNodesInQuarter",e.thirtySecondNodesInQuarter);break;case U.AlphaTabRest:t.set("channel",e.channel);break;case U.AlphaTabMetronome:t.set("metronomeNumerator",e.metronomeNumerator),t.set("metronomeDurationInMilliseconds",e.metronomeDurationInMilliseconds),t.set("metronomeDurationInTicks",e.metronomeDurationInTicks);break;case U.NoteOn:case U.NoteOff:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("noteVelocity",e.noteVelocity);break;case U.ControlChange:t.set("channel",e.channel),t.set("controller",e.controller),t.set("value",e.value);break;case U.ProgramChange:t.set("channel",e.channel),t.set("program",e.program);break;case U.TempoChange:t.set("microSecondsPerQuarterNote",e.microSecondsPerQuarterNote);break;case U.PitchBend:t.set("channel",e.channel),t.set("value",e.value);break;case U.PerNotePitchBend:t.set("channel",e.channel),t.set("noteKey",e.noteKey),t.set("value",e.value);case U.EndOfTrack:}return t}}!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"}(Jt||(Jt={}));class ss{constructor(){this.startBar=0,this.text=""}finish(e=!1){this.chunks=[],this.parse(this.text,0,this.chunks,e)}parse(e,t,s,i){if(!e)return;let a=Jt.Begin,r=Jt.Begin,n=!1,o=0;for(;t<e.length;){const s=e.charCodeAt(t);switch(a){case Jt.IgnoreSpaces:switch(s){case ss.CharCodeLF:case ss.CharCodeCR:case ss.CharCodeTab:break;case ss.CharCodeSpace:if(!n){a=r;continue}break;default:n=!1,a=r;continue}break;case Jt.Begin:if(s!==ss.CharCodeBrackedOpen){o=t,a=Jt.Text;continue}a=Jt.Comment;break;case Jt.Comment:if(s===ss.CharCodeBrackedClose)a=Jt.Begin;break;case Jt.Text:switch(s){case ss.CharCodeDash:a=Jt.Dash;break;case ss.CharCodeCR:case ss.CharCodeLF:case ss.CharCodeSpace:const s=e.substr(o,t-o);this.addChunk(s,i),a=Jt.IgnoreSpaces,r=Jt.Begin}break;case Jt.Dash:if(s!==ss.CharCodeDash){const s=e.substr(o,t-o);this.addChunk(s,i),n=!0,a=Jt.IgnoreSpaces,r=Jt.Begin;continue}}t+=1}a===Jt.Text&&t!==o&&this.addChunk(e.substr(o,t-o),i)}addChunk(e,t){e=this.prepareChunk(e),(!t||e.length>0&&"-"!==e)&&this.chunks.push(e)}prepareChunk(e){const t=e.split("+").join(" ");let s=t.length;for(;s>0&&"_"===t.charAt(s-1);)s--;return s!==t.length?t.substr(0,s):t}}ss.CharCodeLF=10,ss.CharCodeTab=9,ss.CharCodeCR=13,ss.CharCodeSpace=32,ss.CharCodeBrackedClose=93,ss.CharCodeBrackedOpen=91,ss.CharCodeDash=45;class is{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!==R.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{const e=this.beats[0].tupletNumerator/this.beats[0].tupletDenominator|0;for(const t of is.AllTicks)if(this.totalDuration===t*e){this.isFull=!0;break}}return!0}}is.HalfTicks=1920,is.QuarterTicks=960,is.EighthTicks=480,is.SixteenthTicks=240,is.ThirtySecondTicks=120,is.SixtyFourthTicks=60,is.OneHundredTwentyEighthTicks=30,is.TwoHundredFiftySixthTicks=15,is.AllTicks=[is.HalfTicks,is.QuarterTicks,is.EighthTicks,is.SixteenthTicks,is.ThirtySecondTicks,is.SixtyFourthTicks,is.OneHundredTwentyEighthTicks,is.TwoHundredFiftySixthTicks];const as=Object.freeze(Object.defineProperty({__proto__:null,get AccentuationType(){return u},get AccidentalType(){return p},Automation:pe,get AutomationType(){return g},Bar:ue,BarStyle:de,get BarSubElement(){return c},get BarreShape(){return m},Beat:gs,get BeatBeamingMode(){return cs},BeatStyle:ps,get BeatSubElement(){return ds},BendPoint:ge,get BendStyle(){return f},get BendType(){return y},get BracketExtendMode(){return s},get BrushType(){return b},Chord:me,get Clef(){return n},Color:ke,get CrescendoType(){return F},get Direction(){return C},get Duration(){return D},get DynamicValue(){return E},ElementStyle:le,get FadeType(){return L},Fermata:Te,get FermataType(){return M},get Fingers(){return _},Font:Pe,get FontStyle(){return I},get FontWeight(){return A},get GolpeType(){return O},GraceGroup:Fe,get GraceType(){return R},get HarmonicType(){return H},InstrumentArticulation:De,JsonConverter:ts,get KeySignature(){return x},get KeySignatureType(){return v},Lyrics:ss,MasterBar:Se,get MusicFontSymbol(){return G},Note:Nt,get NoteAccidentalMode(){return N},get NoteOrnament(){return Z},NoteStyle:Tt,get NoteSubElement(){return ee},get Ottavia(){return o},get PickStroke(){return Q},PlaybackInformation:Gt,get Rasgueado(){return ae},RenderStylesheet:oe,RepeatGroup:he,Score:Cs,ScoreStyle:Fs,get ScoreSubElement(){return ws},Section:ft,get SimileMark(){return h},get SlideInType(){return q},get SlideOutType(){return K},Staff:Ut,SustainPedalMarker:ce,get SustainPedalMarkerType(){return l},Track:$t,get TrackNameMode(){return a},get TrackNameOrientation(){return r},get TrackNamePolicy(){return i},TrackStyle:Yt,get TrackSubElement(){return Xt},get TripletFeel(){return P},Tuning:zt,TupletGroup:is,get VibratoType(){return j},Voice:Dt,VoiceStyle:Ct,get VoiceSubElement(){return re},get WahPedal(){return ie},get WhammyType(){return te}},Symbol.toStringTag,{value:"Module"}));class rs{static ticksToMillis(e,t){return e*(6e4/(t*rs.QuarterTime))|0}static millisToTicks(e,t){return e/(6e4/(t*rs.QuarterTime))|0}static toTicks(e){return rs.valueToTicks(e)}static valueToTicks(e){let t=e;return t<0&&(t=1/-t),rs.QuarterTime*(4/t)|0}static applyDot(e,t){return t?e+3*(e/4|0):e+(e/2|0)}static applyTuplet(e,t,s){return e*s/t|0}static removeTuplet(e,t,s){return e*t/s|0}static dynamicToVelocity(e,t=0){let s=1;switch(e){case E.PPP:s=rs.MinVelocity+0*rs.VelocityIncrement;break;case E.PP:s=rs.MinVelocity+1*rs.VelocityIncrement;break;case E.P:s=rs.MinVelocity+2*rs.VelocityIncrement;break;case E.MP:s=rs.MinVelocity+3*rs.VelocityIncrement;break;case E.MF:s=rs.MinVelocity+4*rs.VelocityIncrement;break;case E.F:s=rs.MinVelocity+5*rs.VelocityIncrement;break;case E.FF:s=rs.MinVelocity+6*rs.VelocityIncrement;break;case E.FFF:s=rs.MinVelocity+7*rs.VelocityIncrement;break;case E.PPPP:s=10;break;case E.PPPPP:s=5;break;case E.PPPPPP:s=3;break;case E.FFFF:s=rs.MinVelocity+8*rs.VelocityIncrement;break;case E.FFFFF:s=rs.MinVelocity+9*rs.VelocityIncrement;break;case E.FFFFFF:s=rs.MinVelocity+10*rs.VelocityIncrement;break;case E.SF:case E.SFP:case E.SFZP:case E.SFPP:case E.SFZ:case E.FZ:s=rs.MinVelocity+6*rs.VelocityIncrement;break;case E.FP:case E.RF:case E.RFZ:case E.SFFZ:s=rs.MinVelocity+5*rs.VelocityIncrement;break;case E.N:s=1;break;case E.PF:s=rs.MinVelocity+(4.5*rs.VelocityIncrement|0)}return s+=t*rs.VelocityIncrement,Math.min(Math.max(s,1),127)}}rs.QuarterTime=960,rs.MinVelocity=15,rs.VelocityIncrement=16;class ns{static clone(e){const t=new ge;return t.offset=e.offset,t.value=e.value,t}}class os{static clone(e){const t=new Nt;if(t.index=e.index,t.accentuated=e.accentuated,t.bendType=e.bendType,t.bendStyle=e.bendStyle,t.isContinuedBend=e.isContinuedBend,e.bendPoints){t.bendPoints=[];for(const s of e.bendPoints)t.addBendPoint(ns.clone(s))}return t.fret=e.fret,t.string=e.string,t.showStringNumber=e.showStringNumber,t.octave=e.octave,t.tone=e.tone,t.percussionArticulation=e.percussionArticulation,t.isVisible=e.isVisible,t.isLeftHandTapped=e.isLeftHandTapped,t.isHammerPullOrigin=e.isHammerPullOrigin,t.isSlurDestination=e.isSlurDestination,t.harmonicType=e.harmonicType,t.harmonicValue=e.harmonicValue,t.isGhost=e.isGhost,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.isDead=e.isDead,t.isStaccato=e.isStaccato,t.slideInType=e.slideInType,t.slideOutType=e.slideOutType,t.vibrato=e.vibrato,t.isTieDestination=e.isTieDestination,t.leftHandFinger=e.leftHandFinger,t.rightHandFinger=e.rightHandFinger,t.trillValue=e.trillValue,t.trillSpeed=e.trillSpeed,t.durationPercent=e.durationPercent,t.accidentalMode=e.accidentalMode,t.dynamics=e.dynamics,t.ornament=e.ornament,t}}class hs{static clone(e){const t=new pe;return t.isLinear=e.isLinear,t.type=e.type,t.value=e.value,t.ratioPosition=e.ratioPosition,t.text=e.text,t}}class ls{static clone(e){const t=new gs;t.index=e.index,t.notes=[];for(const s of e.notes)t.addNote(os.clone(s));t.isEmpty=e.isEmpty,t.whammyStyle=e.whammyStyle,t.ottava=e.ottava,t.isLegatoOrigin=e.isLegatoOrigin,t.duration=e.duration,t.isLetRing=e.isLetRing,t.isPalmMute=e.isPalmMute,t.automations=[];for(const s of e.automations)t.automations.push(hs.clone(s));if(t.dots=e.dots,t.fade=e.fade,t.lyrics=e.lyrics?e.lyrics.slice():null,t.pop=e.pop,t.slap=e.slap,t.tap=e.tap,t.text=e.text,t.slashed=e.slashed,t.deadSlapped=e.deadSlapped,t.brushType=e.brushType,t.brushDuration=e.brushDuration,t.tupletDenominator=e.tupletDenominator,t.tupletNumerator=e.tupletNumerator,t.isContinuedWhammy=e.isContinuedWhammy,t.whammyBarType=e.whammyBarType,e.whammyBarPoints){t.whammyBarPoints=[];for(const s of e.whammyBarPoints)t.addWhammyBarPoint(ns.clone(s))}return t.vibrato=e.vibrato,t.chordId=e.chordId,t.graceType=e.graceType,t.pickStroke=e.pickStroke,t.tremoloSpeed=e.tremoloSpeed,t.crescendo=e.crescendo,t.displayStart=e.displayStart,t.playbackStart=e.playbackStart,t.displayDuration=e.displayDuration,t.playbackDuration=e.playbackDuration,t.overrideDisplayDuration=e.overrideDisplayDuration,t.golpe=e.golpe,t.dynamics=e.dynamics,t.invertBeamDirection=e.invertBeamDirection,t.preferredBeamDirection=e.preferredBeamDirection,t.isEffectSlurOrigin=e.isEffectSlurOrigin,t.beamingMode=e.beamingMode,t.wahPedal=e.wahPedal,t.barreFret=e.barreFret,t.barreShape=e.barreShape,t.rasgueado=e.rasgueado,t.showTimer=e.showTimer,t.timer=e.timer,t}}var cs,ds,us;!function(e){e[e.Auto=0]="Auto",e[e.ForceSplitToNext=1]="ForceSplitToNext",e[e.ForceMergeWithNext=2]="ForceMergeWithNext",e[e.ForceSplitOnSecondaryToNext=3]="ForceSplitOnSecondaryToNext"}(cs||(cs={})),function(e){e[e.Effects=0]="Effects",e[e.StandardNotationStem=1]="StandardNotationStem",e[e.StandardNotationFlags=2]="StandardNotationFlags",e[e.StandardNotationBeams=3]="StandardNotationBeams",e[e.StandardNotationTuplet=4]="StandardNotationTuplet",e[e.StandardNotationEffects=5]="StandardNotationEffects",e[e.StandardNotationRests=6]="StandardNotationRests",e[e.GuitarTabStem=7]="GuitarTabStem",e[e.GuitarTabFlags=8]="GuitarTabFlags",e[e.GuitarTabBeams=9]="GuitarTabBeams",e[e.GuitarTabTuplet=10]="GuitarTabTuplet",e[e.GuitarTabEffects=11]="GuitarTabEffects",e[e.GuitarTabRests=12]="GuitarTabRests",e[e.SlashStem=13]="SlashStem",e[e.SlashFlags=14]="SlashFlags",e[e.SlashBeams=15]="SlashBeams",e[e.SlashTuplet=16]="SlashTuplet",e[e.SlashRests=17]="SlashRests",e[e.SlashEffects=18]="SlashEffects",e[e.NumberedDuration=19]="NumberedDuration",e[e.NumberedEffects=20]="NumberedEffects",e[e.NumberedRests=21]="NumberedRests",e[e.NumberedTuplet=22]="NumberedTuplet"}(ds||(ds={}));class ps extends le{}class gs{constructor(){this.id=gs._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=f.Default,this.ottava=o.Regular,this.fermata=null,this.isLegatoOrigin=!1,this.minNote=null,this.maxNote=null,this.maxStringNote=null,this.minStringNote=null,this.duration=D.Quarter,this.isLetRing=!1,this.isPalmMute=!1,this.automations=[],this.dots=0,this.fade=L.None,this.lyrics=null,this.pop=!1,this.slap=!1,this.tap=!1,this.text=null,this.slashed=!1,this.deadSlapped=!1,this.brushType=b.None,this.brushDuration=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.tupletGroup=null,this.isContinuedWhammy=!1,this.whammyBarType=te.None,this.whammyBarPoints=null,this.maxWhammyPoint=null,this.minWhammyPoint=null,this.vibrato=j.None,this.chordId=null,this.graceType=R.None,this.graceGroup=null,this.graceIndex=-1,this.pickStroke=Q.None,this.tremoloSpeed=null,this.crescendo=F.None,this.displayStart=0,this.playbackStart=0,this.displayDuration=0,this.playbackDuration=0,this.golpe=O.None,this.dynamics=E.F,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isEffectSlurOrigin=!1,this.effectSlurOrigin=null,this.effectSlurDestination=null,this.beamingMode=cs.Auto,this.wahPedal=ie.None,this.barreFret=-1,this.barreShape=m.None,this.rasgueado=ae.None,this.showTimer=!1,this.timer=null}static resetIds(){gs._globalBeatId=0}get isLastOfVoice(){return this.index===this.voice.beats.length-1}get isLegatoDestination(){return!!this.previousBeat&&this.previousBeat.isLegatoOrigin}get isRest(){return this.isEmpty||!this.deadSlapped&&0===this.notes.length}get isFullBarRest(){return this.isRest&&1===this.voice.beats.length&&this.duration===D.Whole}get fadeIn(){return this.fade===L.FadeIn}set fadeIn(e){this.fade=e?L.FadeIn:L.None}get hasRasgueado(){return this.rasgueado!==ae.None}get hasTuplet(){return!(-1===this.tupletDenominator&&-1===this.tupletNumerator||1===this.tupletDenominator&&1===this.tupletNumerator)}get hasWhammyBar(){return null!==this.whammyBarPoints&&this.whammyBarType!==te.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 displayEnd(){return this.displayStart+this.displayDuration}get absoluteDisplayStart(){return this.voice.bar.masterBar.start+this.displayStart}get absolutePlaybackStart(){return this.voice.bar.masterBar.start+this.playbackStart}get isEffectSlurDestination(){return!!this.effectSlurOrigin}get isBarre(){return this.barreShape!==m.None&&this.barreFret>=0}addWhammyBarPoint(e){let t=this.whammyBarPoints;null===t&&(t=[],this.whammyBarPoints=t),t.push(e),(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e),(!this.minWhammyPoint||e.value<this.minWhammyPoint.value)&&(this.minWhammyPoint=e),this.whammyBarType===te.None&&(this.whammyBarType=te.Custom)}removeWhammyBarPoint(e){const t=this.whammyBarPoints;if(null===t||e<0||e>=t.length)return;t.splice(e,1);const s=t[e];if(s===this.maxWhammyPoint){this.maxWhammyPoint=null;for(const e of t)(!this.maxWhammyPoint||e.value>this.maxWhammyPoint.value)&&(this.maxWhammyPoint=e)}if(s===this.minWhammyPoint){this.minWhammyPoint=null;for(const 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){const t=this.notes.indexOf(e);t>=0&&(this.notes.splice(t,1),e.isStringed&&this.noteStringLookup.delete(e.string))}getAutomation(e){for(let t=0,s=this.automations.length;t<s;t++){const s=this.automations[t];if(s.type===e)return s}return null}getNoteOnString(e){return this.noteStringLookup.has(e)?this.noteStringLookup.get(e):null}calculateDuration(){if(void 0!==this.overrideDisplayDuration)return this.overrideDisplayDuration;if(this.isFullBarRest)return this.voice.bar.masterBar.calculateDuration();let e=rs.toTicks(this.duration);return 2===this.dots?e=rs.applyDot(e,!0):1===this.dots&&(e=rs.applyDot(e,!1)),this.tupletDenominator>0&&this.tupletNumerator>=0&&(e=rs.applyTuplet(e,this.tupletNumerator,this.tupletDenominator)),e}updateDurations(){const e=this.calculateDuration();switch(this.playbackDuration=e,this.graceType){case R.BeforeBeat:case R.OnBeat:switch(this.duration){case D.Sixteenth:this.playbackDuration=rs.toTicks(D.SixtyFourth);break;case D.ThirtySecond:this.playbackDuration=rs.toTicks(D.OneHundredTwentyEighth);break;default:this.playbackDuration=rs.toTicks(D.ThirtySecond)}this.displayDuration=0;break;case R.BendGrace:this.playbackDuration/=2,this.displayDuration=0;break;default:this.displayDuration=e;const t=this.previousBeat;t&&t.graceType===R.BendGrace&&(this.playbackDuration=t.playbackDuration)}}finishTuplet(){const e=this.previousBeat;let t=e?e.tupletGroup:null;if((this.hasTuplet||this.graceType!==R.None&&t)&&(e&&t&&t.check(this)||(t=new is(this.voice),t.check(this)),this.tupletGroup=t),this.index>0){const e=this.voice.bar.masterBar.calculateDuration(),t=[];for(const s of this.automations)0===s.ratioPosition&&(s.ratioPosition=this.playbackStart/e),s.type!==g.Volume&&t.push(s);this.automations=t}}finish(e,t=null){switch(null===this.getAutomation(g.Instrument)&&0===this.index&&0===this.voice.index&&0===this.voice.bar.index&&0===this.voice.bar.staff.index&&this.automations.push(pe.buildInstrumentAutomation(!1,0,this.voice.bar.staff.track.playbackInfo.program)),this.graceType){case R.OnBeat:case R.BeforeBeat:const e=this.graceGroup.beats.length;this.duration=1===e?D.Eighth:2===e?D.Sixteenth:D.ThirtySecond}const s=e?e.notation.notationMode:k.GuitarPro;let i="grad"===this.text||"grad."===this.text;i&&s===k.SongBook&&(this.text="");let a=!1;this.minNote=null,this.maxNote=null,this.minStringNote=null,this.maxStringNote=null;let r=0,n=!1;for(let o=0,h=this.notes.length;o<h;o++){const h=this.notes[o];if(h.dynamics=this.dynamics,h.finish(e,t),h.isLetRing&&(this.isLetRing=!0),h.isPalmMute&&(this.isPalmMute=!0),s===k.SongBook&&h.hasBend&&this.graceType!==R.BendGrace){if(!h.isTieOrigin)switch(h.bendType){case y.Bend:case y.PrebendRelease:case y.PrebendBend:a=!0}i||h.bendStyle===f.Gradual?(i=!0,h.bendStyle=f.Gradual,a=!1):h.bendStyle=f.Fast}h.isVisible&&(r++,(!this.minNote||h.realValue<this.minNote.realValue)&&(this.minNote=h),(!this.maxNote||h.realValue>this.maxNote.realValue)&&(this.maxNote=h),(!this.minStringNote||h.string<this.minStringNote.string)&&(this.minStringNote=h),(!this.maxStringNote||h.string>this.maxStringNote.string)&&(this.maxStringNote=h),h.hasEffectSlur&&(n=!0))}if(n&&(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===r&&(this.isEmpty=!0),this.isRest||this.isLetRing&&this.isPalmMute)this.isRest&&this.previousBeat&&e&&e.notation.notationMode===k.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 o=this.whammyBarPoints,h=null!==o&&o.length>0;if(h){const e=!!this.previousBeat&&this.previousBeat.hasWhammyBar;this.isContinuedWhammy=e}else this.whammyBarType=te.None;if(h&&this.whammyBarType===te.Custom&&(s===k.SongBook&&(this.whammyStyle=i?f.Gradual:f.Fast),4===o.length)){const e=o[0],t=o[1],i=o[2],a=o[3];t.value===i.value&&(e.value<t.value&&t.value<a.value||e.value>t.value&&t.value>a.value?(0===e.value||this.isContinuedWhammy?this.whammyBarType=te.Dive:this.whammyBarType=te.PrediveDive,o.splice(2,1),o.splice(1,1)):e.value>t.value&&t.value<a.value||e.value<t.value&&t.value>a.value?(this.whammyBarType=te.Dip,t.offset!==i.offset&&s!==k.SongBook||o.splice(2,1)):e.value===t.value&&t.value===a.value&&(0===e.value||this.isContinuedWhammy?this.whammyBarType=te.Hold:this.whammyBarType=te.Predive,o.splice(2,1),o.splice(1,1)))}if(this.updateDurations(),a){const e=ls.clone(this);e.id=gs._globalBeatId++,e.pickStroke=Q.None;for(let t=0,s=e.notes.length;t<s;t++){const s=e.notes[t],i=this.notes[t];if(s.bendType=y.None,s.maxBendPoint=null,s.bendPoints=null,s.bendStyle=f.Default,s.id=Nt.GlobalNoteId++,i.isTieOrigin&&(s.tieDestination=i.tieDestination,i.tieDestination.tieOrigin=s),i.isTieDestination&&(s.tieOrigin=i.tieOrigin?i.tieOrigin:null,i.tieOrigin.tieDestination=s),i.hasBend&&i.isTieOrigin){const e=Nt.findTieOrigin(i);if(e&&e.hasBend){s.bendType=y.Hold;const e=i.bendPoints[i.bendPoints.length-1];s.addBendPoint(new ge(0,e.value)),s.addBendPoint(new ge(ge.MaxPosition,e.value))}}s.isTieDestination=!0}this.graceType=R.BendGrace,this.graceGroup=new Fe,this.graceGroup.addBeat(this),this.graceGroup.isComplete=!0,this.graceGroup.finish(),this.updateDurations(),this.voice.insertBeat(this,e),e.graceGroup=new Fe,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)}}gs._globalBeatId=0;class ms{constructor(e,t,s,i){this.cursorWrapper=e,this.barCursor=t,this.beatCursor=s,this.selectionWrapper=i}}!function(e){e[e.Browser=0]="Browser",e[e.NodeJs=1]="NodeJs",e[e.BrowserModule=2]="BrowserModule"}(us||(us={}));class fs{constructor(e,t){this.characterWidths=e,this.fontSizeToHeight=t}}class ys{static generateFontLookup(e){if(!ys.FontSizeLookupTables.has(e))if(cc.isRunningInWorker||cc.webPlatform===us.NodeJs){const t=new fs(new Uint8Array([8]),1.2);ys.FontSizeLookupTables.set(e,t)}else{const t=document.createElement("canvas").getContext("2d"),s=11;t.font=`${s}px ${e}`;const i=[];let a="";for(let e=ys.ControlChars;e<255;e++){const s=String.fromCharCode(e);a+=s;const r=t.measureText(s);i.push(r.width)}const r=t.measureText(`${a}ÄÖÜÁÈ`),n=0-Math.abs(r.fontBoundingBoxAscent),o=0+Math.abs(r.fontBoundingBoxDescent)-n,h=new fs(new Uint8Array(i),o/s);ys.FontSizeLookupTables.set(e,h)}}static measureString(e,t,s,i,a){let r;let n=t[0];for(let e=0;e<t.length;e++)if(ys.FontSizeLookupTables.has(t[e])){n=t[e];break}ys.FontSizeLookupTables.has(n)||ys.generateFontLookup(n),r=ys.FontSizeLookupTables.get(n);let o=1;i===I.Italic&&(o*=1.1),a===A.Bold&&(o*=1.1);let h=0;for(let t=0;t<e.length;t++){const i=Math.min(r.characterWidths.length-1,e.charCodeAt(t)-ys.ControlChars);i>=0&&(h+=r.characterWidths[i]*s/11)}return o*=1.07,new Ce(h*o,s*r.fontSizeToHeight)}}ys.FontSizeLookupTables=new Map,ys.ControlChars=32;class bs{constructor(){this.buffer="",this._currentPath="",this._currentPathIsEmpty=!0,this.scale=1,this.color=new ke(255,255,255,255),this.lineWidth=1,this.font=new Pe("Arial",10,I.Plain),this.textAlign=W.Left,this.textBaseline=V.Top}destroy(){}beginRender(e,t){this.scale=this.settings.display.scale,this.buffer=`<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="${0|e}px" height="${0|t}px" class="at-surface-svg">\n`,this._currentPath="",this._currentPathIsEmpty=!0,this.textBaseline=V.Top}beginGroup(e){this.buffer+=`<g class="${e}">`}endGroup(){this.buffer+="</g>"}endRender(){return this.buffer+="</svg>",this.buffer}fillRect(e,t,s,i){s>0&&(this.buffer+=`<rect x="${e*this.scale|0}" y="${t*this.scale|0}" width="${s*this.scale}" height="${i*this.scale}" fill="${this.color.rgba}" />\n`)}strokeRect(e,t,s,i){const a=this.lineWidth*this.scale%2==0?0:.5;this.buffer+=`<rect x="${(e*this.scale|0)+a}" y="${(t*this.scale|0)+a}" width="${s*this.scale}" height="${i*this.scale}" stroke="${this.color.rgba}"`,1!==this.lineWidth&&(this.buffer+=` stroke-width="${this.lineWidth*this.scale}"`),this.buffer+=' fill="transparent" />\n'}beginPath(){}closePath(){this._currentPath+=" z"}moveTo(e,t){this._currentPath+=` M${e*this.scale},${t*this.scale}`}lineTo(e,t){this._currentPathIsEmpty=!1,this._currentPath+=` L${e*this.scale},${t*this.scale}`}quadraticCurveTo(e,t,s,i){this._currentPathIsEmpty=!1,this._currentPath+=` Q${e*this.scale},${t*this.scale},${s*this.scale},${i*this.scale}`}bezierCurveTo(e,t,s,i,a,r){this._currentPathIsEmpty=!1,this._currentPath+=` C${e*this.scale},${t*this.scale},${s*this.scale},${i*this.scale},${a*this.scale},${r*this.scale}`}fillCircle(e,t,s){this._currentPathIsEmpty=!1,e*=this.scale,t*=this.scale,s*=this.scale,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.fill()}strokeCircle(e,t,s){this._currentPathIsEmpty=!1,e*=this.scale,t*=this.scale,s*=this.scale,this._currentPath+=` M${e-s},${t} A1,1 0 0,0 ${e+s},${t} A1,1 0 0,0 ${e-s},${t} z`,this.stroke()}fill(){this._currentPathIsEmpty||(this.buffer+=`<path d="${this._currentPath}"`,"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),this.buffer+=' style="stroke: none"/>'),this._currentPath="",this._currentPathIsEmpty=!0}stroke(){if(!this._currentPathIsEmpty){let e=`<path d="${this._currentPath}" stroke="${this.color.rgba}"`;1===this.lineWidth&&1===this.scale||(e+=` stroke-width="${this.lineWidth*this.scale}"`),e+=' style="fill: none" />',this.buffer+=e}this._currentPath="",this._currentPathIsEmpty=!0}fillText(e,t,s){if(""===e)return;let i=`<text x="${t*this.scale|0}" y="${s*this.scale|0}" style='stroke: none; font:${this.font.toCssString(this.settings.display.scale)}; ${this.getSvgBaseLine()}'`;"#000000"!==this.color.rgba&&(i+=` fill="${this.color.rgba}"`),this.textAlign!==W.Left&&(i+=` text-anchor="${this.getSvgTextAlignment(this.textAlign)}"`),i+=`>${bs.escapeText(e)}</text>`,this.buffer+=i}static escapeText(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}getSvgTextAlignment(e){switch(e){case W.Left:return"start";case W.Center:return"middle";case W.Right:return"end"}return""}getSvgBaseLine(){switch(this.textBaseline){case V.Top:return"dominant-baseline: hanging";case V.Bottom:return"dominant-baseline: ideographic";default:return""}}measureText(e){return e?ys.measureString(e,this.font.families,this.font.size*this.scale,this.font.style,this.font.weight):new Ce(0,0)}onRenderFinished(){return null}beginRotate(e,t,s){this.buffer+=`<g transform="translate(${e*this.scale} ,${t*this.scale}) rotate( ${s})">`}endRotate(){this.buffer+="</g>"}}class Ss extends bs{fillMusicFontSymbol(e,t,s,i,a){i!==G.None&&this.fillMusicFontSymbolText(e,t,s,`&#${i};`,a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(const e of i)e!==G.None&&(r+=`&#${e};`);this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){e*=this.scale,t*=this.scale,this.buffer+=`<g transform="translate(${e} ${t})" class="at" ><text`;const r=this.scale*s;this.buffer+=1!==r?` style="font-size: ${100*r}%; stroke:none"`:' style="stroke:none"',"#000000"!==this.color.rgba&&(this.buffer+=` fill="${this.color.rgba}"`),a&&(this.buffer+=` text-anchor="${this.getSvgTextAlignment(W.Center)}"`),this.buffer+=`>${i}</text></g>`}}const _s=Object.freeze(Object.defineProperty({__proto__:null,CssFontSvgCanvas:Ss,Cursors:ms,FontSizeDefinition:fs,FontSizes:ys,MeasuredText:Ce,SvgCanvas:bs,get TextAlign(){return W},get TextBaseline(){return V}},Symbol.toStringTag,{value:"Module"}));var ws,Bs,ks,Ts,Ns,xs,vs;!function(e){e[e.Title=0]="Title",e[e.SubTitle=1]="SubTitle",e[e.Artist=2]="Artist",e[e.Album=3]="Album",e[e.Words=4]="Words",e[e.Music=5]="Music",e[e.WordsAndMusic=6]="WordsAndMusic",e[e.Transcriber=7]="Transcriber",e[e.Copyright=8]="Copyright",e[e.CopyrightSecondLine=9]="CopyrightSecondLine",e[e.ChordDiagramList=10]="ChordDiagramList"}(ws||(ws={}));class Ps{constructor(e="",t=void 0,s=W.Left){this.template=e,this.isVisible=t,this.textAlign=s}buildText(e){let t=!1,s=!1;const i=this.template.replace(Ps.PlaceholderPattern,((i,a)=>{s=!0;let r="";switch(a){case"TITLE":r=e.title;break;case"SUBTITLE":r=e.subTitle;break;case"ARTIST":r=e.artist;break;case"ALBUM":r=e.album;break;case"WORDS":case"WORDSMUSIC":r=e.words;break;case"MUSIC":r=e.music;break;case"TABBER":r=e.tab;break;case"COPYRIGHT":r=e.copyright;break;default:r=""}return r&&(t=!0),r}));return s&&!t?"":i}}Ps.PlaceholderPattern=/%([^%]+)%/g;class Fs extends le{constructor(){super(...arguments),this.headerAndFooter=new Map}}Fs.defaultHeaderAndFooter=new Map([[ws.Title,new Ps("%TITLE%",void 0,W.Center)],[ws.SubTitle,new Ps("%SUBTITLE%",void 0,W.Center)],[ws.Artist,new Ps("%ARTIST%",void 0,W.Center)],[ws.Album,new Ps("%ALBUM%",void 0,W.Center)],[ws.Words,new Ps("Words by %WORDS%",void 0,W.Left)],[ws.Music,new Ps("Music by %MUSIC%",void 0,W.Right)],[ws.WordsAndMusic,new Ps("Words & Music by %MUSIC%",void 0,W.Right)],[ws.Transcriber,new Ps("Tabbed by %TABBER%",!1,W.Right)],[ws.Copyright,new Ps("%COPYRIGHT%",void 0,W.Center)],[ws.CopyrightSecondLine,new Ps("All Rights Reserved - International Copyright Secured",!0,W.Center)]]);class Cs{constructor(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0,this.album="",this.artist="",this.copyright="",this.instructions="",this.music="",this.notices="",this.subTitle="",this.title="",this.words="",this.tab="",this.tempo=120,this.tempoLabel="",this.masterBars=[],this.tracks=[],this.defaultSystemsLayout=3,this.systemsLayout=[],this.stylesheet=new oe}static resetIds(){ue.resetIds(),gs.resetIds(),Dt.resetIds(),Nt.resetIds()}rebuildRepeatGroups(){this._currentRepeatGroup=null,this._openedRepeatGroups=[],this._properlyOpenedRepeatGroups=0;for(const e of this.masterBars)this.addMasterBarToRepeatGroups(e)}addMasterBar(e){e.score=this,e.index=this.masterBars.length,0!==this.masterBars.length&&(e.previousMasterBar=this.masterBars[this.masterBars.length-1],e.previousMasterBar.nextMasterBar=e,e.start=e.previousMasterBar.start+(e.previousMasterBar.isAnacrusis?0:e.previousMasterBar.calculateDuration())),this.addMasterBarToRepeatGroups(e),this.masterBars.push(e)}addMasterBarToRepeatGroups(e){e.isRepeatStart?(this._currentRepeatGroup?.isClosed&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--),this._currentRepeatGroup=new he,this._openedRepeatGroups.push(this._currentRepeatGroup),this._properlyOpenedRepeatGroups++):this._currentRepeatGroup||(this._currentRepeatGroup=new he,this._openedRepeatGroups.push(this._currentRepeatGroup)),this._currentRepeatGroup.addMasterBar(e),e.isRepeatEnd&&this._properlyOpenedRepeatGroups>1&&(this._openedRepeatGroups.pop(),this._properlyOpenedRepeatGroups--,this._currentRepeatGroup=this._openedRepeatGroups.length>0?this._openedRepeatGroups[this._openedRepeatGroups.length-1]:null)}addTrack(e){e.score=this,e.index=this.tracks.length,this.tracks.push(e)}finish(e){const t=new Map;for(let s=0,i=this.tracks.length;s<i;s++)this.tracks[s].finish(e,t)}}class Ds{init(e,t){this.data=e,this.settings=t,Cs.resetIds()}}class Es extends fe{constructor(e=null,t){super(S.Format,e??"Unsupported format",t),Object.setPrototypeOf(this,Es.prototype)}}class Ls{}Ls.DefaultChannelCount=17,Ls.MetronomeChannel=Ls.DefaultChannelCount-1,Ls.MetronomeKey=33,Ls.AudioChannels=2,Ls.MinVolume=0,Ls.MinProgram=0,Ls.MaxProgram=127,Ls.MinPlaybackSpeed=.125,Ls.MaxPlaybackSpeed=8,Ls.PercussionChannel=9,Ls.PercussionBank=128,Ls.MaxPitchWheel=16384,Ls.MaxPitchWheel20=4294967296,Ls.DefaultPitchWheel=Ls.MaxPitchWheel/2,Ls.MicroBufferCount=32,Ls.MicroBufferSize=64,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"}(Bs||(Bs={})),function(e){e[e.KnownStaffMeta=0]="KnownStaffMeta",e[e.UnknownStaffMeta=1]="UnknownStaffMeta",e[e.EndOfMetaDetected=2]="EndOfMetaDetected"}(ks||(ks={}));class Ms extends fe{constructor(e,t,s,i,a,r,n,o=null){super(S.AlphaTex,e),this.position=t,this.line=s,this.col=i,this.nonTerm=a??"",this.expected=r??Bs.No,this.symbol=n??Bs.No,this.symbolData=o,Object.setPrototypeOf(this,Ms.prototype)}static symbolError(e,t,s,i,a,r,n=null){let o=`MalFormed AlphaTex: @${e} (line ${t}, col ${s}): Error on block ${i}`;return a!==r?(o+=`, expected a ${Bs[a]} found a ${Bs[r]}`,null!==n&&(o+=`: '${n}'`)):o+=`, invalid value: '${n}'`,new Ms(o,e,t,s,i,a,r,n)}static errorMessage(e,t,s,i){return new Ms(e=`MalFormed AlphaTex: @${t} (line ${s}, col ${i}): ${e}`,t,s,i,null,null,null,null)}}!function(e){e[e.Auto=0]="Auto",e[e.Explicit=1]="Explicit"}(Ts||(Ts={}));class Is extends Ds{constructor(){super(...arguments),this._trackChannel=0,this._barIndex=0,this._voiceIndex=0,this._input="",this._ch=Is.Eof,this._curChPos=0,this._line=1,this._col=0,this._lastValidSpot=[0,1,0],this._sy=Bs.No,this._syData="",this._allowNegatives=!1,this._allowFloat=!1,this._allowTuning=!1,this._currentDuration=D.QuadrupleWhole,this._currentDynamics=E.PPP,this._currentTuplet=0,this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._percussionArticulationNames=new Map,this._sustainPedalToBeat=new Map,this._slurs=new Map,this._accidentalMode=Ts.Explicit,this.logErrors=!1}get name(){return"AlphaTex"}initFromString(e,t){this.data=Me.empty(),this._input=e,this.settings=t,Cs.resetIds()}readScore(){try{if(this.data.length>0&&(this._input=Le.toString(this.data.readAll(),this.settings.importer.encoding)),this._allowTuning=!0,this._lyrics=new Map,this._sustainPedalToBeat=new Map,this.createDefaultScore(),this._curChPos=0,this._line=1,this._col=0,this.saveValidSpot(),this._currentDuration=D.Quarter,this._currentDynamics=E.F,this._currentTuplet=1,this._ch=this.nextChar(),this._sy=this.newSy(),this._sy===Bs.LowerThan)throw new Es("Unknown start sign '<' (meant to import as XML?)");if(this._sy!==Bs.Eof){const e=this.metaData(),t=this.bars();if(!e&&!t)throw new Es("No alphaTex data found")}this.consolidate(),this._score.finish(this.settings),this._score.rebuildRepeatGroups();for(const[e,t]of this._lyrics)this._score.tracks[e].applyLyrics(t);for(const[e,t]of this._sustainPedalToBeat){const s=t.voice.bar.masterBar.calculateDuration();e.ratioPosition=t.playbackStart/s}return this._score}catch(e){if(e instanceof Ms)throw new Es(e.message,e);throw e}}consolidate(){if(0===this._score.masterBars.length){const e=new Se;this._score.addMasterBar(e);const t=new pe;t.isLinear=!1,t.type=g.Tempo,t.value=this._score.tempo,e.tempoAutomations.push(t);const s=new ue;this._score.tracks[0].staves[0].addBar(s);const i=new Dt;s.addVoice(i);const a=new gs;return a.isEmpty=!0,void i.addBeat(a)}for(const e of this._score.tracks)for(const t of e.staves){for(const e of t.bars)for(const t of e.voices)if(t.isEmpty&&0===t.beats.length){const e=new gs;e.isEmpty=!0,t.addBeat(e)}const e=0===t.bars.length?1:t.bars[0].voices.length;for(;t.bars.length<this._score.masterBars.length;){const s=new ue;t.addBar(s);for(let t=0;t<e;t++){const e=new Dt;s.addVoice(e);const t=new gs;t.isEmpty=!0,e.addBeat(t)}}}}error(e,t,s=!0){let i,a=!1;s?(i=this._sy,i!==Bs.String&&i!==Bs.Number&&i!==Bs.MetaCommand||(a=!0)):i=t;const r=Ms.symbolError(this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2],e,t,i,a?this._syData:null);throw this.logErrors&&wt.error(this.name,r.message),r}errorMessage(e){const t=Ms.errorMessage(e,this._lastValidSpot[0],this._lastValidSpot[1],this._lastValidSpot[2]);throw this.logErrors&&wt.error(this.name,t.message),t}createDefaultScore(){this._score=new Cs,this._score.tempo=120,this._score.tempoLabel="",this.newTrack()}newTrack(){this._currentTrack=new $t,this._currentTrack.ensureStaveCount(1),this._currentTrack.playbackInfo.program=25,this._currentTrack.playbackInfo.primaryChannel=this._trackChannel++,this._currentTrack.playbackInfo.secondaryChannel=this._trackChannel++;const e=this._currentTrack.staves[0];e.displayTranspositionPitch=0,e.stringTuning.tunings=zt.getDefaultTuningFor(6).tunings,this.beginStaff(e),this._score.addTrack(this._currentTrack),this._lyrics.set(this._currentTrack.index,[]),this._currentDynamics=E.F}parseClefFromString(e){switch(e.toLowerCase()){case"g2":case"treble":default:return n.G2;case"f4":case"bass":return n.F4;case"c3":case"tenor":return n.C3;case"c4":case"alto":return n.C4;case"n":case"neutral":return n.Neutral}}parseClefFromInt(e){switch(e){case 43:default:return n.G2;case 65:return n.F4;case 48:return n.C3;case 60:return n.C4}}parseTripletFeelFromString(e){switch(e.toLowerCase()){case"no":case"none":default:return P.NoTripletFeel;case"t16":case"triplet-16th":return P.Triplet16th;case"t8":case"triplet-8th":return P.Triplet8th;case"d16":case"dotted-16th":return P.Dotted16th;case"d8":case"dotted-8th":return P.Dotted8th;case"s16":case"scottish-16th":return P.Scottish16th;case"s8":case"scottish-8th":return P.Scottish8th}}parseTripletFeelFromInt(e){switch(e){case 0:default:return P.NoTripletFeel;case 1:return P.Triplet16th;case 2:return P.Triplet8th;case 3:return P.Dotted16th;case 4:return P.Dotted8th;case 5:return P.Scottish16th;case 6:return P.Scottish8th}}parseKeySignature(e){switch(e.toLowerCase()){case"cb":case"cbmajor":case"abminor":return x.Cb;case"gb":case"gbmajor":case"ebminor":return x.Gb;case"db":case"dbmajor":case"bbminor":return x.Db;case"ab":case"abmajor":case"fminor":return x.Ab;case"eb":case"ebmajor":case"cminor":return x.Eb;case"bb":case"bbmajor":case"gminor":return x.Bb;case"f":case"fmajor":case"dminor":return x.F;case"c":case"cmajor":case"aminor":default:return x.C;case"g":case"gmajor":case"eminor":return x.G;case"d":case"dmajor":case"bminor":return x.D;case"a":case"amajor":case"f#minor":return x.A;case"e":case"emajor":case"c#minor":return x.E;case"b":case"bmajor":case"g#minor":return x.B;case"f#":case"f#major":case"d#minor":return x.FSharp;case"c#":case"c#major":case"a#minor":return x.CSharp}}parseKeySignatureType(e){return e.toLowerCase().endsWith("minor")?v.Minor:v.Major}nextChar(){return this._curChPos<this._input.length?(this._ch=this._input.charCodeAt(this._curChPos++),10===this._ch?(this._line++,this._col=0):this._col++):this._ch=Is.Eof,this._ch}saveValidSpot(){this._lastValidSpot=[this._curChPos,this._line,this._col]}newSy(){for(this.saveValidSpot(),this._sy=Bs.No;this._sy===Bs.No;)if(this._ch===Is.Eof)this._sy=Bs.Eof;else if(Is.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!==Is.Eof;)this._ch=this.nextChar();else if(42===this._ch)for(;this._ch!==Is.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",Bs.String,!1);this.saveValidSpot()}else if(34===this._ch||39===this._ch){const e=this._ch;this._ch=this.nextChar();let t="";for(this._sy=Bs.String;this._ch!==e&&this._ch!==Is.Eof;)92===this._ch?(this._ch=this.nextChar(),92===this._ch?t+="\\":this._ch===e?t+=String.fromCharCode(this._ch):82===this._ch||114===this._ch?t+="\r":78===this._ch||110===this._ch?t+="\n":84===this._ch||116===this._ch?t+="\t":this.errorMessage("Unsupported escape sequence")):t+=String.fromCharCode(this._ch),this._ch=this.nextChar();this._ch===Is.Eof&&this.errorMessage("String opened but never closed"),this._syData=t,this._ch=this.nextChar()}else if(45===this._ch)this._allowNegatives?this.readNumberOrName():(this._sy=Bs.String,this._syData=this.readName());else if(46===this._ch)this._sy=Bs.Dot,this._ch=this.nextChar();else if(58===this._ch)this._sy=Bs.DoubleDot,this._ch=this.nextChar();else if(40===this._ch)this._sy=Bs.LParensis,this._ch=this.nextChar();else if(92===this._ch)this._ch=this.nextChar(),this._sy=Bs.MetaCommand,92===this._ch&&(this._ch=this.nextChar()),this._syData=this.readName();else if(41===this._ch)this._sy=Bs.RParensis,this._ch=this.nextChar();else if(123===this._ch)this._sy=Bs.LBrace,this._ch=this.nextChar();else if(125===this._ch)this._sy=Bs.RBrace,this._ch=this.nextChar();else if(124===this._ch)this._sy=Bs.Pipe,this._ch=this.nextChar();else if(42===this._ch)this._sy=Bs.Multiply,this._ch=this.nextChar();else if(60===this._ch)this._sy=Bs.LowerThan,this._ch=this.nextChar();else if(this.isDigit(this._ch))this.readNumberOrName();else if(Is.isNameLetter(this._ch)){const e=this.readName(),t=this._allowTuning?Be.parseTuning(e):null;t?(this._sy=Bs.Tuning,this._syData=t):(this._sy=Bs.String,this._syData=e)}else this.error("symbol",Bs.String,!1);return this._sy}readNumberOrName(){let e="",t=!0;do{e+=String.fromCharCode(this._ch),this.isDigit(this._ch)||(t=!1),this._ch=this.nextChar()}while(this.isDigit(this._ch)||Is.isNameLetter(this._ch));t?(this._sy=Bs.Number,this._syData=this._allowFloat?Number.parseFloat(e):Number.parseInt(e)):(this._sy=Bs.String,this._syData=e)}static isNameLetter(e){return!Is.isTerminal(e)&&(33<=e&&e<=47||58<=e&&e<=126||128<=e)}static isTerminal(e){return 46===e||123===e||125===e||91===e||93===e||40===e||41===e||124===e||39===e||34===e||42===e||92===e}static isWhiteSpace(e){return 9===e||10===e||11===e||13===e||32===e}isDigit(e){return e>=48&&e<=57||this._allowNegatives&&45===e||this._allowFloat&&46===e}readName(){let e="";do{e+=String.fromCharCode(this._ch),this._ch=this.nextChar()}while(Is.isNameLetter(this._ch)||this.isDigit(this._ch));return e}metaData(){let e=!1,t=!1,s=!0;for(;this._sy===Bs.MetaCommand&&s;){const i=this._syData.toLowerCase();switch(i){case"title":case"subtitle":case"artist":case"album":case"words":case"music":case"copyright":case"instructions":case"notices":case"tab":this._sy=this.newSy(),this._sy!==Bs.String&&this.error(i,Bs.String,!0);const a=this._syData;this._sy=this.newSy(),e=!0;let r=ws.ChordDiagramList;switch(i){case"title":this._score.title=a,r=ws.Title;break;case"subtitle":this._score.subTitle=a,r=ws.SubTitle;break;case"artist":this._score.artist=a,r=ws.Artist;break;case"album":this._score.album=a,r=ws.Album;break;case"words":this._score.words=a,r=ws.Words;break;case"music":this._score.music=a,r=ws.Music;break;case"copyright":this._score.copyright=a,r=ws.Copyright;break;case"instructions":this._score.instructions=a;break;case"notices":this._score.notices=a;break;case"tab":this._score.tab=a,r=ws.Transcriber}r!==ws.ChordDiagramList&&this.headerFooterStyle(r);break;case"copyright2":this._sy=this.newSy(),this._sy!==Bs.String&&this.error(i,Bs.String,!0),this.headerFooterStyle(ws.CopyrightSecondLine),e=!0;break;case"wordsandmusic":this._sy=this.newSy(),this._sy!==Bs.String&&this.error(i,Bs.String,!0),this.headerFooterStyle(ws.WordsAndMusic),e=!0;break;case"tempo":this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy===Bs.Number?this._score.tempo=this._syData:this.error("tempo",Bs.Number,!0),this._sy=this.newSy(),this._sy===Bs.String&&(this._score.tempoLabel=this._syData,this._sy=this.newSy()),e=!0;break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===Bs.Number?(this._score.defaultSystemsLayout=this._syData,this._sy=this.newSy(),e=!0):this.error("default-systems-layout",Bs.Number,!0);break;case"systemslayout":for(this._sy=this.newSy(),e=!0;this._sy===Bs.Number;)this._score.systemsLayout.push(this._syData),this._sy=this.newSy();break;case"hidedynamics":this._score.stylesheet.hideDynamics=!0,this._sy=this.newSy(),e=!0;break;case"showdynamics":this._score.stylesheet.hideDynamics=!1,this._sy=this.newSy(),e=!0;break;case"bracketextendmode":this._sy=this.newSy(),this._sy!==Bs.String&&this.error("bracketExtendMode",Bs.String,!0),this._score.stylesheet.bracketExtendMode=this.parseBracketExtendMode(this._syData),this._sy=this.newSy(),e=!0;break;case"usesystemsignseparator":this._score.stylesheet.useSystemSignSeparator=!0,this._sy=this.newSy(),e=!0;break;case"multibarrest":this._score.stylesheet.multiTrackMultiBarRest=!0,this._sy=this.newSy(),e=!0;break;case"singletracktracknamepolicy":this._sy=this.newSy(),this._sy!==Bs.String&&this.error("singleTrackTrackNamePolicy",Bs.String,!0),this._score.stylesheet.singleTrackTrackNamePolicy=this.parseTrackNamePolicy(this._syData),this._sy=this.newSy(),e=!0;break;case"multitracktracknamepolicy":this._sy=this.newSy(),this._sy!==Bs.String&&this.error("multiTrackTrackNamePolicy",Bs.String,!0),this._score.stylesheet.multiTrackTrackNamePolicy=this.parseTrackNamePolicy(this._syData),this._sy=this.newSy(),e=!0;break;case"firstsystemtracknamemode":this._sy=this.newSy(),this._sy!==Bs.String&&this.error("firstSystemTrackNameMode",Bs.String,!0),this._score.stylesheet.firstSystemTrackNameMode=this.parseTrackNameMode(this._syData),this._sy=this.newSy(),e=!0;break;case"othersystemstracknamemode":this._sy=this.newSy(),this._sy!==Bs.String&&this.error("otherSystemsTrackNameMode",Bs.String,!0),this._score.stylesheet.otherSystemsTrackNameMode=this.parseTrackNameMode(this._syData),this._sy=this.newSy(),e=!0;break;case"firstsystemtracknameorientation":this._sy=this.newSy(),this._sy!==Bs.String&&this.error("firstSystemTrackNameOrientation",Bs.String,!0),this._score.stylesheet.firstSystemTrackNameOrientation=this.parseTrackNameOrientation(this._syData),this._sy=this.newSy(),e=!0;break;case"othersystemstracknameorientation":this._sy=this.newSy(),this._sy!==Bs.String&&this.error("otherSystemsTrackNameOrientation",Bs.String,!0),this._score.stylesheet.otherSystemsTrackNameOrientation=this.parseTrackNameOrientation(this._syData),this._sy=this.newSy(),e=!0;break;default:switch(this.handleStaffMeta()){case ks.KnownStaffMeta:t=!0;break;case ks.UnknownStaffMeta:e||t?this.error("metaDataTags",Bs.String,!1):s=!1;break;case ks.EndOfMetaDetected:s=!1}}}return e?(this._sy!==Bs.Dot&&this.error("song",Bs.Dot,!0),this._sy=this.newSy()):this._sy===Bs.Dot&&(this._sy=this.newSy(),e=!0),e||t}headerFooterStyle(e){const t=Be.getOrCreateHeaderFooterStyle(this._score,e);if(void 0===t.isVisible&&(t.isVisible=!0),this._sy===Bs.String){const e=this._syData;e?t.template=e:t.isVisible=!1,this._sy=this.newSy()}if(this._sy===Bs.String){switch(this._syData.toLowerCase()){case"left":t.textAlign=W.Left;break;case"center":t.textAlign=W.Center;break;case"right":t.textAlign=W.Right}this._sy=this.newSy()}}parseTrackNamePolicy(e){switch(e.toLowerCase()){case"hidden":return i.Hidden;case"allsystems":return i.AllSystems;default:return i.FirstSystem}}parseTrackNameMode(e){return"fullname"===e.toLowerCase()?a.FullName:a.ShortName}parseTrackNameOrientation(e){return"horizontal"===e.toLowerCase()?r.Horizontal:r.Vertical}handleStaffMeta(){switch(this._syData.toLowerCase()){case"capo":return this._sy=this.newSy(),this._sy===Bs.Number?this._currentStaff.capo=this._syData:this.error("capo",Bs.Number,!0),this._sy=this.newSy(),ks.KnownStaffMeta;case"tuning":this._sy=this.newSy();const e=this._currentStaff.tuning.length;switch(this._staffHasExplicitTuning=!0,this._staffTuningApplied=!1,this._sy){case Bs.String:const e=this._syData.toLowerCase();"piano"===e||"none"===e||"voice"===e?this.makeCurrentStaffPitched():this.error("tuning",Bs.Tuning,!0),this._sy=this.newSy();break;case Bs.Tuning:const t=[];do{const e=this._syData;t.push(e.realValue),this._sy=this.newSy()}while(this._sy===Bs.Tuning);this._currentStaff.stringTuning.tunings=t;break;default:this.error("tuning",Bs.Tuning,!0)}return this._sy===Bs.String&&"hide"===this._syData.toLowerCase()&&(this._score.stylesheet.perTrackDisplayTuning||(this._score.stylesheet.perTrackDisplayTuning=new Map),this._score.stylesheet.perTrackDisplayTuning.set(this._currentTrack.index,!1),this._sy=this.newSy()),e!==this._currentStaff.tuning.length&&(this._currentStaff.chords?.size??0)>0&&this.errorMessage("Tuning must be defined before any chord"),ks.KnownStaffMeta;case"instrument":if(this._sy=this.newSy(),this._staffTuningApplied=!1,this._sy===Bs.Number){const e=this._syData;e>=0&&e<=127?this._currentTrack.playbackInfo.program=this._syData:this.error("instrument",Bs.Number,!1)}else if(this._sy===Bs.String){const e=this._syData.toLowerCase();if("percussion"===e){for(const e of this._currentTrack.staves)this.applyPercussionStaff(e);this._currentTrack.playbackInfo.primaryChannel=Ls.PercussionChannel,this._currentTrack.playbackInfo.secondaryChannel=Ls.PercussionChannel}else this._currentTrack.playbackInfo.program=ne.getValue(e)}else this.error("instrument",Bs.Number,!0);return this._sy=this.newSy(),ks.KnownStaffMeta;case"lyrics":this._sy=this.newSy();const t=new ss;return t.startBar=0,t.text="",this._sy===Bs.Number&&(t.startBar=this._syData,this._sy=this.newSy()),this._sy===Bs.String?(t.text=this._syData,this._sy=this.newSy()):this.error("lyrics",Bs.String,!0),this._lyrics.get(this._currentTrack.index).push(t),ks.KnownStaffMeta;case"chord":this._sy=this.newSy();const s=new me;this.chordProperties(s),this._sy===Bs.String?(s.name=this._syData,this._sy=this.newSy()):this.error("chord-name",Bs.String,!0);for(let e=0;e<this._currentStaff.tuning.length;e++)this._sy===Bs.Number?s.strings.push(this._syData):this._sy===Bs.String&&"x"===this._syData.toLowerCase()&&s.strings.push(-1),this._sy=this.newSy();return this._currentStaff.addChord(this.getChordId(this._currentStaff,s.name),s),ks.KnownStaffMeta;case"articulation":this._sy=this.newSy();let i="";if(this._sy===Bs.String?(i=this._syData,this._sy=this.newSy()):this.error("articulation-name",Bs.String,!0),"defaults"===i){for(const[e,t]of Bt.instrumentArticulationNames)this._percussionArticulationNames.set(e.toLowerCase(),t),this._percussionArticulationNames.set(Is.toArticulationId(e),t);return ks.KnownStaffMeta}let a=0;return this._sy===Bs.Number?(a=this._syData,this._sy=this.newSy()):this.error("articulation-number",Bs.Number,!0),Bt.instrumentArticulations.has(a)||this.errorMessage(`Unknown articulation ${a}. Refer to https://www.alphatab.net/docs/alphatex/percussion for available ids`),this._percussionArticulationNames.set(i.toLowerCase(),a),ks.KnownStaffMeta;case"accidentals":return this.handleAccidentalMode(),ks.KnownStaffMeta;case"displaytranspose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===Bs.Number?(this._currentStaff.displayTranspositionPitch=-1*this._syData,this._staffHasExplicitDisplayTransposition=!0):this.error("displaytranspose",Bs.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),ks.KnownStaffMeta;case"transpose":return this._allowNegatives=!0,this._sy=this.newSy(),this._sy===Bs.Number?this._currentStaff.transpositionPitch=-1*this._syData:this.error("transpose",Bs.Number,!0),this._allowNegatives=!1,this._sy=this.newSy(),ks.KnownStaffMeta;case"track":case"staff":return ks.EndOfMetaDetected;case"voice":return this._sy=this.newSy(),this.handleNewVoice()?ks.EndOfMetaDetected:ks.KnownStaffMeta;default:return ks.UnknownStaffMeta}}handleAccidentalMode(){switch(this._sy=this.newSy(),this._sy!==Bs.String&&this.error("accidental-mode",Bs.String,!0),this._syData){case"auto":this._accidentalMode=Ts.Auto;break;case"explicit":this._accidentalMode=Ts.Explicit}this._sy=this.newSy()}makeCurrentStaffPitched(){this._currentStaff.stringTuning.tunings=[],this._staffHasExplicitDisplayTransposition||(this._currentStaff.displayTranspositionPitch=0)}static toArticulationId(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}applyPercussionStaff(e){e.isPercussion=!0,e.showTablature=!1}chordProperties(e){if(this._sy===Bs.LBrace){for(this._sy=this.newSy();this._sy===Bs.String;)switch(this._syData.toLowerCase()){case"firstfret":if(this._sy=this.newSy(),this._sy===Bs.Number)e.firstFret=this._syData;else this.error("chord-firstfret",Bs.Number,!0);this._sy=this.newSy();break;case"showdiagram":switch(this._sy=this.newSy(),this._sy){case Bs.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case Bs.Number:e.showDiagram=0!==this._syData;break;default:this.error("chord-showdiagram",Bs.String,!0)}this._sy=this.newSy();break;case"showfingering":switch(this._sy=this.newSy(),this._sy){case Bs.String:e.showDiagram="false"!==this._syData.toLowerCase();break;case Bs.Number:e.showFingering=0!==this._syData;break;default:this.error("chord-showfingering",Bs.String,!0)}this._sy=this.newSy();break;case"showname":switch(this._sy=this.newSy(),this._sy){case Bs.String:e.showName="false"!==this._syData.toLowerCase();break;case Bs.Number:e.showName=0!==this._syData;break;default:this.error("chord-showname",Bs.String,!0)}this._sy=this.newSy();break;case"barre":for(this._sy=this.newSy();this._sy===Bs.Number;)e.barreFrets.push(this._syData),this._sy=this.newSy();break;default:this.error("chord-properties",Bs.String,!1)}this._sy!==Bs.RBrace&&this.error("chord-properties",Bs.RBrace,!0),this._sy=this.newSy()}}bars(){const e=this.bar();for(;this._sy!==Bs.Eof;)if(this._sy===Bs.Pipe)this._sy=this.newSy(),this.bar();else{if(this._sy!==Bs.MetaCommand)break;this.bar()}return e}trackStaffMeta(){if(this._sy!==Bs.MetaCommand)return!1;if("track"===this._syData.toLowerCase()&&(this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._score.masterBars.length>0&&this.newTrack(),this._sy===Bs.String&&(this._currentTrack.name=this._syData,this._sy=this.newSy()),this._sy===Bs.String&&(this._currentTrack.shortName=this._syData,this._sy=this.newSy()),this.trackProperties()),this._sy===Bs.MetaCommand&&"staff"===this._syData.toLowerCase()){if(this._staffHasExplicitDisplayTransposition=!1,this._staffHasExplicitTuning=!1,this._staffTuningApplied=!1,this._sy=this.newSy(),this._currentTrack.staves[0].bars.length>0){const e=this._currentStaff.isPercussion;this._currentTrack.ensureStaveCount(this._currentTrack.staves.length+1),this.beginStaff(this._currentTrack.staves[this._currentTrack.staves.length-1]),e&&this.applyPercussionStaff(this._currentStaff),this._currentDynamics=E.F}this.staffProperties()}return this._sy===Bs.MetaCommand&&"voice"===this._syData.toLowerCase()&&(this._sy=this.newSy(),this.handleNewVoice()),!0}handleNewVoice(){if(0===this._voiceIndex&&(0===this._currentStaff.bars.length||1===this._currentStaff.bars.length&&this._currentStaff.bars[0].isEmpty))return!1;for(const e of this._currentStaff.bars){const t=new Dt;e.addVoice(t)}return this._voiceIndex++,this._barIndex=0,!0}beginStaff(e){this._currentStaff=e,this._slurs.clear(),this._barIndex=0,this._voiceIndex=0}trackProperties(){if(this._sy===Bs.LBrace){for(this._sy=this.newSy();this._sy===Bs.String;)switch(this._syData.toLowerCase()){case"color":this._sy=this.newSy(),this._sy!==Bs.String&&this.error("track-color",Bs.String,!0),this._currentTrack.color=ke.fromJson(this._syData),this._sy=this.newSy();break;case"defaultsystemslayout":this._sy=this.newSy(),this._sy===Bs.Number?(this._currentTrack.defaultSystemsLayout=this._syData,this._sy=this.newSy()):this.error("default-systems-layout",Bs.Number,!0);break;case"systemslayout":for(this._sy=this.newSy();this._sy===Bs.Number;)this._currentTrack.systemsLayout.push(this._syData),this._sy=this.newSy();break;case"volume":this._sy=this.newSy(),this._sy!==Bs.Number&&this.error("track-volume",Bs.Number,!0),this._currentTrack.playbackInfo.volume=Be.clamp(this._syData,0,16),this._sy=this.newSy();break;case"balance":this._sy=this.newSy(),this._sy!==Bs.Number&&this.error("track-balance",Bs.Number,!0),this._currentTrack.playbackInfo.balance=Be.clamp(this._syData,0,16),this._sy=this.newSy();break;case"mute":this._sy=this.newSy(),this._currentTrack.playbackInfo.isMute=!0;break;case"solo":this._sy=this.newSy(),this._currentTrack.playbackInfo.isSolo=!0;break;case"multibarrest":this._sy=this.newSy(),this._score.stylesheet.perTrackMultiBarRest||(this._score.stylesheet.perTrackMultiBarRest=new Set),this._score.stylesheet.perTrackMultiBarRest.add(this._currentTrack.index);break;default:this.error("track-properties",Bs.String,!1)}this._sy!==Bs.RBrace&&this.error("track-properties",Bs.RBrace,!0),this._sy=this.newSy()}}staffProperties(){if(this._sy!==Bs.LBrace)return;this._sy=this.newSy();let e=!1,t=!1,s=!1,i=!1;for(;this._sy===Bs.String;)switch(this._syData.toLowerCase()){case"score":e=!0,this._sy=this.newSy(),this._sy===Bs.Number&&(this._currentStaff.standardNotationLineCount=this._syData,this._sy=this.newSy());break;case"tabs":t=!0,this._sy=this.newSy();break;case"slash":s=!0,this._sy=this.newSy();break;case"numbered":i=!0,this._sy=this.newSy();break;default:this.error("staff-properties",Bs.String,!1)}(e||t||s||i)&&(this._currentStaff.showStandardNotation=e,this._currentStaff.showTablature=t,this._currentStaff.showSlash=s,this._currentStaff.showNumbered=i),this._sy!==Bs.RBrace&&this.error("staff-properties",Bs.RBrace,!0),this._sy=this.newSy()}bar(){const e=this.trackStaffMeta(),t=this.newBar(this._currentStaff);if(this._currentStaff.bars.length>this._score.masterBars.length){const e=new Se;this._score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.timeSignatureDenominator=e.previousMasterBar.timeSignatureDenominator,e.timeSignatureNumerator=e.previousMasterBar.timeSignatureNumerator,e.tripletFeel=e.previousMasterBar.tripletFeel)}const s=this.barMeta(t),i=this._currentTrack.playbackInfo.program;this._staffTuningApplied||this._staffHasExplicitTuning||(this._currentStaff.stringTuning.tunings=[],15===i||i>=24&&i<=31?this._currentStaff.stringTuning.tunings=zt.getDefaultTuningFor(6).tunings:i>=32&&i<=39?this._currentStaff.stringTuning.tunings=[43,38,33,28]:40===i||44===i||45===i||48===i||49===i||50===i||51===i?this._currentStaff.stringTuning.tunings=[52,57,50,43]:41===i?this._currentStaff.stringTuning.tunings=[57,50,43,36]:42===i?this._currentStaff.stringTuning.tunings=[45,38,31,24]:43===i?this._currentStaff.stringTuning.tunings=[43,38,33,28]:105===i?this._currentStaff.stringTuning.tunings=[50,47,43,38,55]:106===i?this._currentStaff.stringTuning.tunings=[57,52,45]:107===i?this._currentStaff.stringTuning.tunings=[52,45,38,31]:110===i&&(this._currentStaff.stringTuning.tunings=[64,57,50,43]),this._staffTuningApplied=!0),this._staffHasExplicitDisplayTransposition||(this._currentStaff.displayTranspositionPitch=i>=24&&i<=31||i>=32&&i<=39||43===i?-12:0);let a=!1;const r=t.voices[this._voiceIndex];if(!(this._sy===Bs.MetaCommand&&("track"===this._syData.toLowerCase()||"staff"===this._syData.toLowerCase())))for(;this._sy!==Bs.Pipe&&this._sy!==Bs.Eof&&this.beat(r);)a=!0;if(0===r.beats.length){const e=new gs;e.isEmpty=!0,r.addBeat(e)}return e||s||a}newBar(e){if(this._barIndex<e.bars.length){const t=e.bars[this._barIndex];return this._barIndex++,t}const t=0===e.bars.length?1:e.bars[0].voices.length,s=new ue;e.addBar(s),s.previousBar&&(s.clef=s.previousBar.clef,s.clefOttava=s.previousBar.clefOttava),this._barIndex++;for(let e=0;e<t;e++){const e=new Dt;s.addVoice(e)}return s}beat(e){this.beatDuration();const t=new gs;if(e.addBeat(t),this._allowTuning=!this._currentStaff.isPercussion,this._sy===Bs.LParensis){for(this._sy=this.newSy(),this.note(t);this._sy!==Bs.RParensis&&this._sy!==Bs.Eof&&(this._allowTuning=!this._currentStaff.isPercussion,this.note(t)););this._sy!==Bs.RParensis&&this.error("note-list",Bs.RParensis,!0),this._sy=this.newSy()}else if(this._sy===Bs.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===Bs.Dot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==Bs.Number&&this.error("duration",Bs.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||Is.applyTuplet(t,this._currentTuplet);let s=1;this._sy===Bs.Multiply&&(this._sy=this.newSy(),this._sy!==Bs.Number?this.error("multiplier",Bs.Number,!0):s=this._syData,this._sy=this.newSy()),this.beatEffects(t);for(let i=0;i<s-1;i++)e.addBeat(ls.clone(t));return!0}beatDuration(){if(this._sy===Bs.DoubleDot&&(this._allowNegatives=!0,this._sy=this.newSy(),this._allowNegatives=!1,this._sy!==Bs.Number&&this.error("duration",Bs.Number,!0),this._currentDuration=this.parseDuration(this._syData),this._currentTuplet=1,this._sy=this.newSy(),this._sy===Bs.LBrace)){for(this._sy=this.newSy();this._sy===Bs.String;){if("tu"===this._syData.toLowerCase())this._sy=this.newSy(),this._sy!==Bs.Number&&this.error("duration-tuplet",Bs.Number,!0),this._currentTuplet=this._syData,this._sy=this.newSy();else this.error("beat-duration",Bs.String,!1)}this._sy!==Bs.RBrace&&this.error("beat-duration",Bs.RBrace,!0),this._sy=this.newSy()}}beatEffects(e){if(this._sy===Bs.LBrace){for(this._sy=this.newSy();this._sy===Bs.String;)this.applyBeatEffect(e)||this.error("beat-effects",Bs.String,!1);this._sy!==Bs.RBrace&&this.error("beat-effects",Bs.RBrace,!0),this._sy=this.newSy()}}applyBeatEffect(e){const t=this._syData.toLowerCase();if("f"===t)e.fade=L.FadeIn;else if("fo"===t)e.fade=L.FadeOut;else if("vs"===t)e.fade=L.VolumeSwell;else if("v"===t)e.vibrato=j.Slight;else if("vw"===t)e.vibrato=j.Wide;else if("s"===t)e.slap=!0;else if("p"===t)e.pop=!0;else if("tt"===t)e.tap=!0;else if("txt"===t){if(this._sy=this.newSy(),this._sy!==Bs.String)return this.error("beat-text",Bs.String,!0),!1;e.text=this._syData}else if("dd"===t)e.dots=2;else if("d"===t)e.dots=1;else if("su"===t)e.pickStroke=Q.Up;else if("sd"===t)e.pickStroke=Q.Down;else{if("tu"===t){if(this._sy=this.newSy(),this._sy!==Bs.Number)return this.error("tuplet",Bs.Number,!0),!1;const t=this._syData;if(this._sy=this.newSy(),this._sy===Bs.Number){const s=this._syData;this._sy=this.newSy(),e.tupletNumerator=t,e.tupletDenominator=s}else Is.applyTuplet(e,t);return!0}if("tb"===t||"tbe"===t){this._sy=this.newSy();const s="tbe"===t;for(this._sy===Bs.String&&(e.whammyBarType=this.parseWhammyType(this._syData),this._sy=this.newSy()),this._sy===Bs.String&&(e.whammyStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==Bs.LParensis&&this.error("tremolobar-effect",Bs.LParensis,!0),this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy();this._sy!==Bs.RParensis&&this._sy!==Bs.Eof;){let t=0,i=0;s?(this._sy!==Bs.Number&&this.error("tremolobar-effect",Bs.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==Bs.Number&&this.error("tremolobar-effect",Bs.Number,!0),i=this._syData):(this._sy!==Bs.Number&&this.error("tremolobar-effect",Bs.Number,!0),t=0,i=this._syData),e.addWhammyBarPoint(new ge(t,i)),this._sy=this.newSy()}if(null!=e.whammyBarPoints){for(;e.whammyBarPoints.length>60;)e.removeWhammyBarPoint(e.whammyBarPoints.length-1);if(s)e.whammyBarPoints.sort(((e,t)=>e.offset-t.offset));else{const t=e.whammyBarPoints.length,s=60/t|0;let i=0;for(;i<t;)e.whammyBarPoints[i].offset=Math.min(60,i*s),i++}}this._allowNegatives=!1,this._allowFloat=!1,this._sy!==Bs.RParensis&&this.error("tremolobar-effect",Bs.RParensis,!0)}else{if("bu"===t||"bd"===t||"au"===t||"ad"===t){switch(t){case"bu":e.brushType=b.BrushUp;break;case"bd":e.brushType=b.BrushDown;break;case"au":e.brushType=b.ArpeggioUp;break;case"ad":e.brushType=b.ArpeggioDown}return this._sy=this.newSy(),this._sy===Bs.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();const t=this._syData,s=this.getChordId(this._currentStaff,t);if(!this._currentStaff.hasChord(s)){const e=new me;e.showDiagram=!1,e.name=t,this._currentStaff.addChord(s,e)}e.chordId=s}else{if("gr"===t)return this._sy=this.newSy(),"ob"===this._syData.toLowerCase()?(e.graceType=R.OnBeat,this._sy=this.newSy()):"b"===this._syData.toLowerCase()?(e.graceType=R.BendGrace,this._sy=this.newSy()):e.graceType=R.BeforeBeat,!0;if("dy"===t){this._sy=this.newSy();const t=this._syData.toUpperCase();switch(t){case"PPP":case"PP":case"P":case"MP":case"MF":case"F":case"FF":case"FFF":case"PPPP":case"PPPPP":case"PPPPPP":case"FFFF":case"FFFFF":case"FFFFFF":case"SF":case"SFP":case"SFPP":case"FP":case"RF":case"RFZ":case"SFZ":case"SFFZ":case"FZ":case"N":case"PF":case"SFZP":e.dynamics=E[t]}this._currentDynamics=e.dynamics}else if("cre"===t)e.crescendo=F.Crescendo;else if("dec"===t)e.crescendo=F.Decrescendo;else{if("tempo"===t){const t=this.readTempoAutomation();return e.automations.push(t),e.voice.bar.masterBar.tempoAutomations.push(t),!0}if("tp"===t){if(this._sy=this.newSy(),e.tremoloSpeed=D.Eighth,this._sy===Bs.Number){switch(this._syData){case 8:default:e.tremoloSpeed=D.Eighth;break;case 16:e.tremoloSpeed=D.Sixteenth;break;case 32:e.tremoloSpeed=D.ThirtySecond}this._sy=this.newSy()}return!0}if("spd"===t){const t=new ce;return t.pedalType=l.Down,t.ratioPosition=e.voice.bar.sustainPedals.length,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spu"===t){const t=new ce;return t.pedalType=l.Up,t.ratioPosition=e.voice.bar.sustainPedals.length,this._sustainPedalToBeat.set(t,e),e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("spe"===t){const t=new ce;return t.pedalType=l.Up,t.ratioPosition=1,e.voice.bar.sustainPedals.push(t),this._sy=this.newSy(),!0}if("slashed"===t)return e.slashed=!0,this._sy=this.newSy(),!0;if("ds"===t)return e.deadSlapped=!0,this._sy=this.newSy(),!0;if("glpf"===t)return this._sy=this.newSy(),e.golpe=O.Finger,!0;if("glpt"===t)return this._sy=this.newSy(),e.golpe=O.Thumb,!0;if("waho"===t)return this._sy=this.newSy(),e.wahPedal=ie.Open,!0;if("wahc"===t)return this._sy=this.newSy(),e.wahPedal=ie.Closed,!0;if("barre"===t){if(this._sy=this.newSy(),this._sy!==Bs.Number&&this.error("beat-barre",Bs.Number,!0),e.barreFret=this._syData,e.barreShape=m.Full,this._sy=this.newSy(),this._sy===Bs.String)switch(this._syData.toLowerCase()){case"full":e.barreShape=m.Full,this._sy=this.newSy();break;case"half":e.barreShape=m.Half,this._sy=this.newSy()}return!0}if("rasg"===t){switch(this._sy=this.newSy(),this._sy!==Bs.String&&this.error("rasgueado",Bs.String,!0),this._syData.toLowerCase()){case"ii":e.rasgueado=ae.Ii;break;case"mi":e.rasgueado=ae.Mi;break;case"miitriplet":e.rasgueado=ae.MiiTriplet;break;case"miianapaest":e.rasgueado=ae.MiiAnapaest;break;case"pmptriplet":e.rasgueado=ae.PmpTriplet;break;case"pmpanapaest":e.rasgueado=ae.PmpAnapaest;break;case"peitriplet":e.rasgueado=ae.PeiTriplet;break;case"peianapaest":e.rasgueado=ae.PeiAnapaest;break;case"paitriplet":e.rasgueado=ae.PaiTriplet;break;case"paianapaest":e.rasgueado=ae.PaiAnapaest;break;case"amitriplet":e.rasgueado=ae.AmiTriplet;break;case"amianapaest":e.rasgueado=ae.AmiAnapaest;break;case"ppp":e.rasgueado=ae.Ppp;break;case"amii":e.rasgueado=ae.Amii;break;case"amip":e.rasgueado=ae.Amip;break;case"eami":e.rasgueado=ae.Eami;break;case"eamii":e.rasgueado=ae.Eamii;break;case"peami":e.rasgueado=ae.Peami}return this._sy=this.newSy(),!0}if("ot"===t)this._sy=this.newSy(),this._sy!==Bs.String&&this.error("beat-ottava",Bs.String,!0),e.ottava=this.parseClefOttavaFromString(this._syData);else if("legatoorigin"===t)e.isLegatoOrigin=!0;else{if("instrument"!==t){if("fermata"===t){this._sy=this.newSy(),this._sy!==Bs.String&&this.error("fermata",Bs.Number,!0);const t=new Te;return t.type=this.parseFermataFromString(this._syData),this._allowFloat=!0,this._sy=this.newSy(),this._sy===Bs.Number&&(t.length=this._syData,this._sy=this.newSy()),this._allowFloat=!1,e.fermata=t,!0}if("beam"===t){switch(this._sy=this.newSy(),this._sy!==Bs.String&&this.error("beam",Bs.Number,!0),this._syData.toLowerCase()){case"invert":e.invertBeamDirection=!0;break;case"up":e.preferredBeamDirection=se.Up;break;case"down":e.preferredBeamDirection=se.Down;break;case"auto":e.beamingMode=cs.Auto;break;case"split":e.beamingMode=cs.ForceSplitToNext;break;case"merge":e.beamingMode=cs.ForceMergeWithNext;break;case"splitsecondary":e.beamingMode=cs.ForceSplitOnSecondaryToNext}return this._sy=this.newSy(),!0}return"timer"===t&&(e.showTimer=!0,this._sy=this.newSy(),!0)}{this._sy=this.newSy();let t=0;this._sy===Bs.Number?t=this._syData:this._sy===Bs.String?t=ne.getValue(this._syData):this.error("instrument-change",Bs.Number,!0);const s=new pe;s.isLinear=!1,s.type=g.Instrument,s.value=t,e.automations.push(s)}}}}}}return this._sy=this.newSy(),!0}parseBracketExtendMode(e){switch(e.toLowerCase()){case"nobrackets":return s.NoBrackets;case"groupstaves":default:return s.GroupStaves;case"groupsimilarinstruments":return s.GroupSimilarInstruments}}parseFermataFromString(e){switch(e.toLowerCase()){case"short":return M.Short;case"medium":default:return M.Medium;case"long":return M.Long}}parseClefOttavaFromString(e){switch(e.toLowerCase()){case"15ma":return o._15ma;case"8va":return o._8va;case"regular":default:return o.Regular;case"8vb":return o._8vb;case"15mb":return o._15mb}}getChordId(e,t){return t.toLowerCase()+e.index+e.track.index}static applyTuplet(e,t){switch(t){case 3:e.tupletNumerator=3,e.tupletDenominator=2;break;case 5:e.tupletNumerator=5,e.tupletDenominator=4;break;case 6:e.tupletNumerator=6,e.tupletDenominator=4;break;case 7:e.tupletNumerator=7,e.tupletDenominator=4;break;case 9:e.tupletNumerator=9,e.tupletDenominator=8;break;case 10:e.tupletNumerator=10,e.tupletDenominator=8;break;case 11:e.tupletNumerator=11,e.tupletDenominator=8;break;case 12:e.tupletNumerator=12,e.tupletDenominator=8;break;default:e.tupletNumerator=1,e.tupletDenominator=1}}isNoteText(e){return"x"===e||"-"===e||"r"===e}note(e){let t=!1,s=!1,i=-1,a=-1,r=-1,n=N.Default;switch(this._sy){case Bs.Number:i=this._syData,this._currentStaff.isPercussion&&!Bt.instrumentArticulations.has(i)&&this.errorMessage(`Unknown percussion articulation ${i}`);break;case Bs.String:if(this._currentStaff.isPercussion){const e=this._syData.toLowerCase();this._percussionArticulationNames.has(e)?i=this._percussionArticulationNames.get(e):this.errorMessage(`Unknown percussion articulation '${this._syData}'`)}else t="x"===this._syData,s="-"===this._syData,s||t?i=0:this.error("note-fret",Bs.Number,!0);break;case Bs.Tuning:0===e.index&&0===e.voice.index&&0===e.voice.bar.index&&this.makeCurrentStaffPitched();const o=this._syData;a=o.octave,r=o.tone.noteValue,this._accidentalMode===Ts.Explicit&&(n=o.tone.accidentalMode);break;default:return!1}this._sy=this.newSy();const o=-1===a&&this._currentStaff.tuning.length>0&&!this._currentStaff.isPercussion;let h=-1;o&&(this._sy!==Bs.Dot&&this.error("note",Bs.Dot,!0),this._sy=this.newSy(),this._sy!==Bs.Number&&this.error("note-string",Bs.Number,!0),h=this._syData,(h<1||h>this._currentStaff.tuning.length)&&this.error("note-string",Bs.Number,!1),this._sy=this.newSy());const l=new Nt;return o?(l.string=this._currentStaff.tuning.length-(h-1),l.isDead=t,l.isTieDestination=s,s||(l.fret=i)):this._currentStaff.isPercussion?l.percussionArticulation=i:(l.octave=a,l.tone=r,l.accidentalMode=n,l.isTieDestination=s),e.addNote(l),this.noteEffects(l),!0}noteEffects(e){if(this._sy===Bs.LBrace){for(this._sy=this.newSy();this._sy===Bs.String;){const t=this._syData.toLowerCase();if("b"===t||"be"===t){this._sy=this.newSy();const s="be"===t;for(this._sy===Bs.String&&(e.bendType=this.parseBendType(this._syData),this._sy=this.newSy()),this._sy===Bs.String&&(e.bendStyle=this.parseBendStyle(this._syData),this._sy=this.newSy()),this._sy!==Bs.LParensis&&this.error("bend-effect",Bs.LParensis,!0),this._sy=this.newSy();this._sy!==Bs.RParensis&&this._sy!==Bs.Eof;){let t=0,i=0;s?(this._sy!==Bs.Number&&this.error("bend-effect-value",Bs.Number,!0),t=this._syData,this._sy=this.newSy(),this._sy!==Bs.Number&&this.error("bend-effect-value",Bs.Number,!0),i=this._syData):(this._sy!==Bs.Number&&this.error("bend-effect-value",Bs.Number,!0),i=this._syData),e.addBendPoint(new ge(t,i)),this._sy=this.newSy()}const i=e.bendPoints;if(null!=i){for(;i.length>60;)i.splice(i.length-1,1);if(s)i.sort(((e,t)=>e.offset-t.offset));else{const e=i.length,t=60/(e-1)|0;let s=0;for(;s<e;)i[s].offset=Math.min(60,s*t),s++}}this._sy!==Bs.RParensis&&this.error("bend-effect",Bs.RParensis,!0),this._sy=this.newSy()}else if("nh"===t)e.harmonicType=H.Natural,e.harmonicValue=Be.deltaFretToHarmonicValue(e.fret),this._sy=this.newSy();else if("ah"===t)e.harmonicType=H.Artificial,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("th"===t)e.harmonicType=H.Tap,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("ph"===t)e.harmonicType=H.Pinch,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("sh"===t)e.harmonicType=H.Semi,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("fh"===t)e.harmonicType=H.Feedback,e.harmonicValue=this.harmonicValue(e.harmonicValue);else if("tr"===t){this._sy=this.newSy(),this._sy!==Bs.Number&&this.error("trill-effect",Bs.Number,!0);const t=this._syData;this._sy=this.newSy();let s=D.Sixteenth;if(this._sy===Bs.Number){switch(this._syData){case 16:default:s=D.Sixteenth;break;case 32:s=D.ThirtySecond;break;case 64:s=D.SixtyFourth}this._sy=this.newSy()}e.trillValue=t+e.stringTuning,e.trillSpeed=s}else if("v"===t)this._sy=this.newSy(),e.vibrato=j.Slight;else if("sl"===t)this._sy=this.newSy(),e.slideOutType=K.Legato;else if("ss"===t)this._sy=this.newSy(),e.slideOutType=K.Shift;else if("sib"===t)this._sy=this.newSy(),e.slideInType=q.IntoFromBelow;else if("sia"===t)this._sy=this.newSy(),e.slideInType=q.IntoFromAbove;else if("sou"===t)this._sy=this.newSy(),e.slideOutType=K.OutUp;else if("sod"===t)this._sy=this.newSy(),e.slideOutType=K.OutDown;else if("psd"===t)this._sy=this.newSy(),e.slideOutType=K.PickSlideDown;else if("psu"===t)this._sy=this.newSy(),e.slideOutType=K.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=u.Normal;else if("hac"===t)this._sy=this.newSy(),e.accentuated=u.Heavy;else if("ten"===t)this._sy=this.newSy(),e.accentuated=u.Tenuto;else if("pm"===t)this._sy=this.newSy(),e.isPalmMute=!0;else if("st"===t)this._sy=this.newSy(),e.isStaccato=!0;else if("lr"===t)this._sy=this.newSy(),e.isLetRing=!0;else if("x"===t)this._sy=this.newSy(),e.fret=0,e.isDead=!0;else if("-"===t||"t"===t)this._sy=this.newSy(),e.isTieDestination=!0;else if("lf"===t){this._sy=this.newSy();let t=_.Thumb;this._sy===Bs.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.leftHandFinger=t}else if("rf"===t){this._sy=this.newSy();let t=_.Thumb;this._sy===Bs.Number&&(t=this.toFinger(this._syData),this._sy=this.newSy()),e.rightHandFinger=t}else if("acc"===t)this._sy=this.newSy(),this._sy!==Bs.String&&this.error("note-accidental",Bs.String,!0),e.accidentalMode=Be.parseAccidentalMode(this._syData),this._sy=this.newSy();else if("turn"===t)this._sy=this.newSy(),e.ornament=Z.Turn;else if("iturn"===t)this._sy=this.newSy(),e.ornament=Z.InvertedTurn;else if("umordent"===t)this._sy=this.newSy(),e.ornament=Z.UpperMordent;else if("lmordent"===t)this._sy=this.newSy(),e.ornament=Z.LowerMordent;else if("string"===t)this._sy=this.newSy(),e.showStringNumber=!0;else if("hide"===t)this._sy=this.newSy(),e.isVisible=!1;else if("slur"===t){this._sy=this.newSy(),this._sy!==Bs.String&&this.error("slur",Bs.String,!0);const t=this._syData;if(this._slurs.has(t)){const s=this._slurs.get(t);s.slurDestination=e,e.slurOrigin=s,e.isSlurDestination=!0}else this._slurs.set(t,e);this._sy=this.newSy()}else this.applyBeatEffect(e.beat)||this.error(t,Bs.String,!1)}this._sy!==Bs.RBrace&&this.error("note-effect",Bs.RBrace,!1),this._sy=this.newSy()}}harmonicValue(e){return this._allowNegatives=!0,this._allowFloat=!0,this._sy=this.newSy(),this._sy===Bs.Number&&(e=this._syData,this._sy=this.newSy()),this._allowNegatives=!1,this._allowFloat=!1,e}toFinger(e){switch(e){case 1:return _.Thumb;case 2:return _.IndexFinger;case 3:return _.MiddleFinger;case 4:return _.AnnularFinger;case 5:return _.LittleFinger}return _.Thumb}parseDuration(e){switch(e){case-4:return D.QuadrupleWhole;case-2:return D.DoubleWhole;case 1:return D.Whole;case 2:return D.Half;case 4:return D.Quarter;case 8:return D.Eighth;case 16:return D.Sixteenth;case 32:return D.ThirtySecond;case 64:return D.SixtyFourth;case 128:return D.OneHundredTwentyEighth;case 256:return D.TwoHundredFiftySixth;default:return D.Quarter}}parseBendStyle(e){switch(e.toLowerCase()){case"gradual":return f.Gradual;case"fast":return f.Fast;default:return f.Default}}parseBendType(e){switch(e.toLowerCase()){case"none":return y.None;case"custom":default:return y.Custom;case"bend":return y.Bend;case"release":return y.Release;case"bendrelease":return y.BendRelease;case"hold":return y.Hold;case"prebend":return y.Prebend;case"prebendbend":return y.PrebendBend;case"prebendrelease":return y.PrebendRelease}}barMeta(e){let t=!1;const s=e.masterBar;let i=!1;for(;!i&&this._sy===Bs.MetaCommand;){t=!0;const a=this._syData.toLowerCase();if("ts"===a)this._sy=this.newSy(),this._sy===Bs.String?"common"===this._syData.toLowerCase()?(s.timeSignatureCommon=!0,s.timeSignatureNumerator=4,s.timeSignatureDenominator=4,this._sy=this.newSy()):this.error("timesignature-numerator",Bs.String,!0):(this._sy!==Bs.Number&&this.error("timesignature-numerator",Bs.Number,!0),s.timeSignatureNumerator=this._syData,this._sy=this.newSy(),this._sy!==Bs.Number&&this.error("timesignature-denominator",Bs.Number,!0),s.timeSignatureDenominator=this._syData,this._sy=this.newSy());else if("ft"===a)s.isFreeTime=!0,this._sy=this.newSy();else if("ro"===a)s.isRepeatStart=!0,this._sy=this.newSy();else if("rc"===a)this._sy=this.newSy(),this._sy!==Bs.Number&&this.error("repeatclose",Bs.Number,!0),this._syData>2048&&this.error("repeatclose",Bs.Number,!1),s.repeatCount=this._syData,this._sy=this.newSy();else if("ae"===a)if(this._sy=this.newSy(),this._sy===Bs.LParensis){for(this._sy=this.newSy(),this._sy!==Bs.Number&&this.error("alternateending",Bs.Number,!0),this.applyAlternateEnding(s);this._sy===Bs.Number;)this.applyAlternateEnding(s);this._sy!==Bs.RParensis&&this.error("alternateending-list",Bs.RParensis,!0),this._sy=this.newSy()}else this._sy!==Bs.Number&&this.error("alternateending",Bs.Number,!0),this.applyAlternateEnding(s);else if("ks"===a)this._sy=this.newSy(),this._sy!==Bs.String&&this.error("keysignature",Bs.String,!0),s.keySignature=this.parseKeySignature(this._syData),s.keySignatureType=this.parseKeySignatureType(this._syData),this._sy=this.newSy();else if("clef"===a){switch(this._sy=this.newSy(),this._sy){case Bs.String:e.clef=this.parseClefFromString(this._syData);break;case Bs.Number:e.clef=this.parseClefFromInt(this._syData);break;case Bs.Tuning:const t=this._syData;e.clef=this.parseClefFromInt(t.realValue);break;default:this.error("clef",Bs.String,!0)}this._sy=this.newSy()}else if("tempo"===a){const e=this.readTempoAutomation();s.tempoAutomations.push(e)}else if("section"===a){this._sy=this.newSy(),this._sy!==Bs.String&&this.error("section",Bs.String,!0);let e=this._syData;this._sy=this.newSy();let t="";this._sy!==Bs.String||this.isNoteText(this._syData.toLowerCase())||(t=e,e=this._syData,this._sy=this.newSy());const i=new ft;i.marker=t,i.text=e,s.section=i}else if("tf"===a){switch(this._allowTuning=!1,this._sy=this.newSy(),this._allowTuning=!0,this._sy){case Bs.String:s.tripletFeel=this.parseTripletFeelFromString(this._syData);break;case Bs.Number:s.tripletFeel=this.parseTripletFeelFromInt(this._syData);break;default:this.error("triplet-feel",Bs.String,!0)}this._sy=this.newSy()}else if("ac"===a)s.isAnacrusis=!0,this._sy=this.newSy();else if("db"===a)s.isDoubleBar=!0,e.barLineRight=d.LightLight,this._sy=this.newSy();else if("barlineleft"===a)this._sy=this.newSy(),this._sy!==Bs.String&&this.error("barlineleft",Bs.String,!0),e.barLineLeft=this.parseBarLineStyle(this._syData),this._sy=this.newSy();else if("barlineright"===a)this._sy=this.newSy(),this._sy!==Bs.String&&this.error("barlineright",Bs.String,!0),e.barLineRight=this.parseBarLineStyle(this._syData),this._sy=this.newSy();else if("accidentals"===a)this.handleAccidentalMode();else if("jump"===a)this.handleDirections(s);else if("ottava"===a)this._sy=this.newSy(),this._sy!==Bs.String&&this.error("ottava",Bs.String,!0),e.clefOttava=this.parseClefOttavaFromString(this._syData),this._sy=this.newSy();else if("simile"===a)this._sy=this.newSy(),this._sy!==Bs.String&&this.error("simile",Bs.String,!0),e.simileMark=this.parseSimileMarkFromString(this._syData),this._sy=this.newSy();else if("scale"===a)this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==Bs.Number&&this.error("scale",Bs.Number,!0),s.displayScale=this._syData,e.displayScale=this._syData,this._sy=this.newSy();else if("width"===a)this._sy=this.newSy(),this._sy!==Bs.Number&&this.error("width",Bs.Number,!0),s.displayWidth=this._syData,e.displayWidth=this._syData,this._sy=this.newSy();else if(0===e.index)switch(this.handleStaffMeta()){case ks.KnownStaffMeta:break;case ks.UnknownStaffMeta:this.error("measure-effects",Bs.String,!1);break;case ks.EndOfMetaDetected:i=!0}else if(this.handleStaffMeta()===ks.EndOfMetaDetected)i=!0;else this.error("measure-effects",Bs.String,!1)}if(0===s.index&&0===s.tempoAutomations.length){const e=new pe;e.isLinear=!1,e.type=g.Tempo,e.value=this._score.tempo,e.text=this._score.tempoLabel,s.tempoAutomations.push(e)}return t}parseBarLineStyle(e){switch(e.toLowerCase()){case"automatic":return d.Automatic;case"dashed":return d.Dashed;case"dotted":return d.Dotted;case"heavy":return d.Heavy;case"heavyheavy":return d.HeavyHeavy;case"heavylight":return d.HeavyLight;case"lightheavy":return d.LightHeavy;case"lightlight":return d.LightLight;case"none":return d.None;case"regular":return d.Regular;case"short":return d.Short;case"tick":return d.Tick}return d.Automatic}parseSimileMarkFromString(e){switch(e.toLowerCase()){case"none":default:return h.None;case"simple":return h.Simple;case"firstofdouble":return h.FirstOfDouble;case"secondofdouble":return h.SecondOfDouble}}handleDirections(e){switch(this._sy=this.newSy(),this._sy!==Bs.String&&this.error("direction",Bs.String,!0),this._syData.toLowerCase()){case"fine":e.addDirection(C.TargetFine);break;case"segno":e.addDirection(C.TargetSegno);break;case"segnosegno":e.addDirection(C.TargetSegnoSegno);break;case"coda":e.addDirection(C.TargetCoda);break;case"doublecoda":e.addDirection(C.TargetDoubleCoda);break;case"dacapo":e.addDirection(C.JumpDaCapo);break;case"dacapoalcoda":e.addDirection(C.JumpDaCapoAlCoda);break;case"dacapoaldoublecoda":e.addDirection(C.JumpDaCapoAlDoubleCoda);break;case"dacapoalfine":e.addDirection(C.JumpDaCapoAlFine);break;case"dalsegno":e.addDirection(C.JumpDalSegno);break;case"dalsegnoalcoda":e.addDirection(C.JumpDalSegnoAlCoda);break;case"dalsegnoaldoublecoda":e.addDirection(C.JumpDalSegnoAlDoubleCoda);break;case"dalsegnoalfine":e.addDirection(C.JumpDalSegnoAlFine);break;case"dalsegnosegno":e.addDirection(C.JumpDalSegnoSegno);break;case"dalsegnosegnoalcoda":e.addDirection(C.JumpDalSegnoSegnoAlCoda);break;case"dalsegnosegnoaldoublecoda":e.addDirection(C.JumpDalSegnoSegnoAlDoubleCoda);break;case"dalsegnosegnoalfine":e.addDirection(C.JumpDalSegnoSegnoAlFine);break;case"dacoda":e.addDirection(C.JumpDaCoda);break;case"dadoublecoda":e.addDirection(C.JumpDaDoubleCoda);break;default:return void this.errorMessage(`Unexpected direction value: '${this._syData}'`)}this._sy=this.newSy()}readTempoAutomation(){this._allowFloat=!0,this._sy=this.newSy(),this._allowFloat=!1,this._sy!==Bs.Number&&this.error("tempo",Bs.Number,!0);const e=new pe;return e.isLinear=!1,e.type=g.Tempo,e.value=this._syData,this._sy=this.newSy(),this._sy===Bs.String&&(e.text=this._syData,this._sy=this.newSy()),e}applyAlternateEnding(e){const t=this._syData;t<1&&this.error("alternateending",Bs.Number,!0),e.alternateEndings|=1<<t-1,this._sy=this.newSy()}parseWhammyType(e){switch(e.toLowerCase()){case"none":return te.None;case"custom":default:return te.Custom;case"dive":return te.Dive;case"dip":return te.Dip;case"hold":return te.Hold;case"predive":return te.Predive;case"predivedive":return te.PrediveDive}}}Is.Eof=0;class As extends Ds{constructor(){super(...arguments),this._versionNumber=0,this._globalTripletFeel=P.NoTripletFeel,this._lyricsTrack=0,this._lyrics=[],this._barCount=0,this._trackCount=0,this._playbackInfos=[],this._doubleBars=new Set,this._beatTextChunksByTrack=new Map,this._directionLookup=new Map}get name(){return"Guitar Pro 3-5"}readScore(){if(this._directionLookup.clear(),this.readVersion(),this._score=new Cs,this.readScoreInformation(),this._versionNumber<500&&(this._globalTripletFeel=Rs.gpReadBool(this.data)?P.Triplet8th:P.NoTripletFeel),this._versionNumber>=400&&this.readLyrics(),this._versionNumber>=510&&this.data.skip(19),this._versionNumber>=500&&(this.readPageSetup(),this._score.tempoLabel=Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding)),this._score.tempo=Le.readInt32LE(this.data),this._versionNumber>=510&&Rs.gpReadBool(this.data),Le.readInt32LE(this.data),this._versionNumber>=400&&this.data.readByte(),this.readPlaybackInfos(),this._versionNumber>=500&&(this.readDirection(C.TargetCoda),this.readDirection(C.TargetDoubleCoda),this.readDirection(C.TargetSegno),this.readDirection(C.TargetSegnoSegno),this.readDirection(C.TargetFine),this.readDirection(C.JumpDaCapo),this.readDirection(C.JumpDaCapoAlCoda),this.readDirection(C.JumpDaCapoAlDoubleCoda),this.readDirection(C.JumpDaCapoAlFine),this.readDirection(C.JumpDalSegno),this.readDirection(C.JumpDalSegnoAlCoda),this.readDirection(C.JumpDalSegnoAlDoubleCoda),this.readDirection(C.JumpDalSegnoAlFine),this.readDirection(C.JumpDalSegnoSegno),this.readDirection(C.JumpDalSegnoSegnoAlCoda),this.readDirection(C.JumpDalSegnoSegnoAlDoubleCoda),this.readDirection(C.JumpDalSegnoSegnoAlFine),this.readDirection(C.JumpDaCoda),this.readDirection(C.JumpDaDoubleCoda),this.data.skip(4)),this._barCount=Le.readInt32LE(this.data),this._trackCount=Le.readInt32LE(this.data),this.readMasterBars(),this.readTracks(),this.readBars(),this._score.masterBars.length>0){const e=pe.buildTempoAutomation(!1,0,this._score.tempo,2);e.text=this._score.tempoLabel,this._score.masterBars[0].tempoAutomations.push(e)}return this._score.finish(this.settings),this._lyrics&&this._lyricsTrack>=0&&this._score.tracks[this._lyricsTrack].applyLyrics(this._lyrics),this._score}readDirection(e){let t,s=Le.readInt16LE(this.data);-1!==s&&(s--,this._directionLookup.has(s)?t=this._directionLookup.get(s):(t=[],this._directionLookup.set(s,t)),t.push(e))}readVersion(){let e=Rs.gpReadStringByteLength(this.data,30,this.settings.importer.encoding);if(!e.startsWith(As.VersionString))throw new Es("Unsupported format");e=e.substr(As.VersionString.length+1);const t=e.indexOf(String.fromCharCode(46));this._versionNumber=100*Number.parseInt(e.substr(0,t))+Number.parseInt(e.substr(t+1)),wt.debug(this.name,`Guitar Pro version ${e} detected`)}readScoreInformation(){this._score.title=Rs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.subTitle=Rs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.artist=Rs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.album=Rs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.words=Rs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.music=this._versionNumber>=500?Rs.gpReadStringIntUnused(this.data,this.settings.importer.encoding):this._score.words,this._score.copyright=Rs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.tab=Rs.gpReadStringIntUnused(this.data,this.settings.importer.encoding),this._score.instructions=Rs.gpReadStringIntUnused(this.data,this.settings.importer.encoding);const e=Le.readInt32LE(this.data);let t="";for(let s=0;s<e;s++)s>0&&(t+="\r\n"),t+=Rs.gpReadStringIntUnused(this.data,this.settings.importer.encoding)?.toString();this._score.notices=t}readLyrics(){this._lyrics=[],this._lyricsTrack=Le.readInt32LE(this.data)-1;for(let e=0;e<5;e++){const e=new ss;e.startBar=Le.readInt32LE(this.data)-1,e.text=Rs.gpReadStringInt(this.data,this.settings.importer.encoding),this._lyrics.push(e)}}readPageSetup(){this.data.skip(28);const e=Le.readInt16LE(this.data);Be.getOrCreateHeaderFooterStyle(this._score,ws.Title).isVisible=!!(1&e),Be.getOrCreateHeaderFooterStyle(this._score,ws.Title).template=Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding),Be.getOrCreateHeaderFooterStyle(this._score,ws.SubTitle).isVisible=!!(2&e),Be.getOrCreateHeaderFooterStyle(this._score,ws.SubTitle).template=Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding),Be.getOrCreateHeaderFooterStyle(this._score,ws.Artist).isVisible=!!(4&e),Be.getOrCreateHeaderFooterStyle(this._score,ws.Artist).template=Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding),Be.getOrCreateHeaderFooterStyle(this._score,ws.Album).isVisible=!!(8&e),Be.getOrCreateHeaderFooterStyle(this._score,ws.Album).template=Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding),Be.getOrCreateHeaderFooterStyle(this._score,ws.Words).isVisible=!!(16&e),Be.getOrCreateHeaderFooterStyle(this._score,ws.Words).template=Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding),Be.getOrCreateHeaderFooterStyle(this._score,ws.Music).isVisible=!!(32&e),Be.getOrCreateHeaderFooterStyle(this._score,ws.Music).template=Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding),Be.getOrCreateHeaderFooterStyle(this._score,ws.WordsAndMusic).isVisible=!!(64&e),Be.getOrCreateHeaderFooterStyle(this._score,ws.WordsAndMusic).template=Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding),Be.getOrCreateHeaderFooterStyle(this._score,ws.Copyright).isVisible=!!(128&e),Be.getOrCreateHeaderFooterStyle(this._score,ws.Copyright).template=Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding),Be.getOrCreateHeaderFooterStyle(this._score,ws.CopyrightSecondLine).isVisible=!!(128&e),Be.getOrCreateHeaderFooterStyle(this._score,ws.CopyrightSecondLine).template=Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding),Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding)}readPlaybackInfos(){this._playbackInfos=[];for(let e=0;e<64;e++){const t=new Gt;t.primaryChannel=e,t.secondaryChannel=e,t.program=Le.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]);const t=new Se,s=this.data.readByte();if(1&s?t.timeSignatureNumerator=this.data.readByte():e&&(t.timeSignatureNumerator=e.timeSignatureNumerator),2&s?t.timeSignatureDenominator=this.data.readByte():e&&(t.timeSignatureDenominator=e.timeSignatureDenominator),t.isRepeatStart=!!(4&s),8&s&&(t.repeatCount=this.data.readByte()+(this._versionNumber>=500?0:1)),16&s&&this._versionNumber<500){let s=e,i=0;for(;s&&(!s.isRepeatEnd||s===e)&&!s.isRepeatStart;)i|=s.alternateEndings,s=s.previousMasterBar;let a=0;const r=this.data.readByte();for(let e=0;e<8;e++){const t=1<<e;r>e&&!(i&t)&&(a|=t)}t.alternateEndings=a}if(32&s){const e=new ft;e.text=Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding),e.marker="",Rs.gpReadColor(this.data,!1),t.section=e}if(64&s?(t.keySignature=Le.readSInt8(this.data),t.keySignatureType=this.data.readByte()):e&&(t.keySignature=e.keySignature,t.keySignatureType=e.keySignatureType),this._versionNumber>=500&&3&s&&this.data.skip(4),this._versionNumber>=500&&(t.alternateEndings=this.data.readByte()),this._versionNumber>=500){switch(this.data.readByte()){case 1:t.tripletFeel=P.Triplet8th;break;case 2:t.tripletFeel=P.Triplet16th}this.data.readByte()}else t.tripletFeel=this._globalTripletFeel;const i=!!(128&s);t.isDoubleBar=i;const a=this._score.masterBars.length;if(this._directionLookup.has(a))for(const e of this._directionLookup.get(a))t.addDirection(e);this._score.addMasterBar(t),i&&this._doubleBars.add(t.index)}readTracks(){for(let e=0;e<this._trackCount;e++)this.readTrack()}readTrack(){const e=new $t;e.ensureStaveCount(1),this._score.addTrack(e);const t=e.staves[0],s=this.data.readByte();e.name=Rs.gpReadStringByteLength(this.data,40,this.settings.importer.encoding),1&s&&(t.isPercussion=!0),this._versionNumber>=500&&(e.isVisibleOnMultiTrack=!!(8&s)),null===this._score.stylesheet.perTrackDisplayTuning&&(this._score.stylesheet.perTrackDisplayTuning=new Map),this._score.stylesheet.perTrackDisplayTuning.set(e.index,!!(128&s));const i=Le.readInt32LE(this.data),a=[];for(let e=0;e<7;e++){const t=Le.readInt32LE(this.data);i>e&&a.push(t)}t.stringTuning.tunings=a;const r=Le.readInt32LE(this.data),n=Le.readInt32LE(this.data)-1,o=Le.readInt32LE(this.data)-1;if(this.data.skip(4),n>=0&&n<this._playbackInfos.length){const i=this._playbackInfos[n];i.port=r,i.isSolo=!!(16&s),i.isMute=!!(32&s),i.secondaryChannel=o,ne.isGuitar(i.program)&&(t.displayTranspositionPitch=-12),e.playbackInfo=i}if(t.capo=Le.readInt32LE(this.data),e.color=Rs.gpReadColor(this.data,!1),this._versionNumber>=500){const s=this.data.readByte();t.showTablature=!!(1&s),t.showStandardNotation=!!(2&s);const i=!!(100&s);null===this._score.stylesheet.perTrackChordDiagramsOnTop&&(this._score.stylesheet.perTrackChordDiagramsOnTop=new Map),this._score.stylesheet.perTrackChordDiagramsOnTop.set(e.index,i),this.data.readByte(),this.data.skip(43)}this._versionNumber>=510&&(this.data.skip(4),Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding),Rs.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){const t=new ue,s=e.staves[0];s.isPercussion&&(t.clef=n.Neutral),s.addBar(t),this._doubleBars.has(t.index)&&(t.barLineRight=d.LightLight);let i=1;this._versionNumber>=500&&(this.data.readByte(),i=2);for(let s=0;s<i;s++)this.readVoice(e,t)}readVoice(e,t){const s=Le.readInt32LE(this.data);if(0===s)return;const i=new Dt;t.addVoice(i);for(let a=0;a<s;a++)this.readBeat(e,t,i)}readBeat(e,t,s){const i=new gs,a=this.data.readByte();if(1&a&&(i.dots=1),64&a){const e=this.data.readByte();i.isEmpty=!(2&e)}s.addBeat(i);switch(Le.readSInt8(this.data)){case-2:i.duration=D.Whole;break;case-1:i.duration=D.Half;break;case 0:i.duration=D.Quarter;break;case 1:i.duration=D.Eighth;break;case 2:i.duration=D.Sixteenth;break;case 3:i.duration=D.ThirtySecond;break;case 4:i.duration=D.SixtyFourth;break;default:i.duration=D.Quarter}if(32&a)switch(i.tupletNumerator=Le.readInt32LE(this.data),i.tupletNumerator){case 1:i.tupletDenominator=1;break;case 3:i.tupletDenominator=2;break;case 5:case 6:case 7:i.tupletDenominator=4;break;case 9:case 10:case 11:case 12:case 13:i.tupletDenominator=8;break;case 2:case 4:case 8:break;default:i.tupletNumerator=1,i.tupletDenominator=1}2&a&&this.readChord(i);const r=this.settings.importer.beatTextAsLyrics&&e.index!==this._lyricsTrack;if(4&a){const t=Rs.gpReadStringIntUnused(this.data,this.settings.importer.encoding);if(r){const s=new ss;s.text=t.trim(),s.finish(!0);const i=[];for(let e=s.chunks.length-1;e>=0;e--)i.push(s.chunks[e]);this._beatTextChunksByTrack.set(e.index,i)}else i.text=t}let n=H.None;8&a&&(n=this.readBeatEffects(i)),16&a&&this.readMixTableChange(i);const h=this.data.readByte();for(let a=6;a>=0;a--)if(h&1<<a&&6-a<t.staff.tuning.length){const r=this.readNote(e,t,s,i,6-a);n!==H.None&&(r.harmonicType=n,r.harmonicType===H.Natural&&(r.harmonicValue=Be.deltaFretToHarmonicValue(r.fret)))}if(this._versionNumber>=500){const e=Le.readInt16LE(this.data);if(1&e&&i.index>0&&(s.beats[i.index-1].beamingMode=cs.ForceSplitToNext),2&e&&(i.preferredBeamDirection=se.Down),4&e&&i.index>0&&(s.beats[i.index-1].beamingMode=cs.ForceMergeWithNext),8&e&&(i.preferredBeamDirection=se.Up),16&e&&(i.ottava=o._8va),32&e&&(i.ottava=o._8vb),64&e&&(i.ottava=o._15ma),256&e&&(i.ottava=o._15mb),2048&e){const e=0!==this.data.readByte();i.index>0&&e&&(s.beats[i.index-1].beamingMode=cs.ForceSplitOnSecondaryToNext)}}r&&!i.isRest&&this._beatTextChunksByTrack.has(e.index)&&this._beatTextChunksByTrack.get(e.index).length>0&&(i.lyrics=[this._beatTextChunksByTrack.get(e.index).pop()])}readChord(e){const t=new me,s=Be.newGuid();if(this._versionNumber>=500){this.data.skip(17),t.name=Rs.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Le.readInt32LE(this.data);for(let s=0;s<7;s++){const i=Le.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}const s=this.data.readByte(),i=new Uint8Array(5);this.data.read(i,0,i.length);for(let e=0;e<s;e++)t.barreFrets.push(i[e]);this.data.skip(26)}else if(0!==this.data.readByte())if(this._versionNumber>=400){this.data.skip(16),t.name=Rs.gpReadStringByteLength(this.data,21,this.settings.importer.encoding),this.data.skip(4),t.firstFret=Le.readInt32LE(this.data);for(let s=0;s<7;s++){const i=Le.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}const s=this.data.readByte(),i=new Uint8Array(5);this.data.read(i,0,i.length);for(let e=0;e<s;e++)t.barreFrets.push(i[e]);this.data.skip(26)}else{this.data.skip(25),t.name=Rs.gpReadStringByteLength(this.data,34,this.settings.importer.encoding),t.firstFret=Le.readInt32LE(this.data);for(let s=0;s<6;s++){const i=Le.readInt32LE(this.data);s<e.voice.bar.staff.tuning.length&&t.strings.push(i)}this.data.skip(36)}else{const s=this._versionNumber>=406?7:6;if(t.name=Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding),t.firstFret=Le.readInt32LE(this.data),t.firstFret>0)for(let i=0;i<s;i++){const s=Le.readInt32LE(this.data);i<e.voice.bar.staff.tuning.length&&t.strings.push(s)}}t.name&&(e.chordId=s,e.voice.bar.staff.addChord(e.chordId,t))}readBeatEffects(e){const t=this.data.readByte();let s=0;if(this._versionNumber>=400&&(s=this.data.readByte()),16&t&&(e.fade=L.FadeIn),(this._versionNumber<400&&1&t||2&t)&&(e.vibrato=j.Slight),1&s&&(e.rasgueado=ae.Ii),32&t&&this._versionNumber>=400){switch(Le.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}}else if(32&t){switch(Le.readSInt8(this.data)){case 1:e.tap=!0;break;case 2:e.slap=!0;break;case 3:e.pop=!0}this.data.skip(4)}if(4&s&&this.readTremoloBarEffect(e),64&t){let t=0,s=0;this._versionNumber<500?(s=this.data.readByte(),t=this.data.readByte()):(t=this.data.readByte(),s=this.data.readByte()),t>0?(e.brushType=b.BrushUp,e.brushDuration=As.toStrokeValue(t)):s>0&&(e.brushType=b.BrushDown,e.brushDuration=As.toStrokeValue(s))}if(2&s)switch(Le.readSInt8(this.data)){case 0:e.pickStroke=Q.None;break;case 1:e.pickStroke=Q.Up;break;case 2:e.pickStroke=Q.Down}if(this._versionNumber<400){if(4&t)return H.Natural;if(8&t)return H.Artificial}return H.None}readTremoloBarEffect(e){this.data.readByte(),Le.readInt32LE(this.data);const t=Le.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){const t=new ge(0,0);t.offset=Le.readInt32LE(this.data),t.value=Le.readInt32LE(this.data)/As.BendStep|0,Rs.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){const t=new Os;t.instrument=Le.readSInt8(this.data),this._versionNumber>=500&&this.data.skip(16),t.volume=Le.readSInt8(this.data),t.balance=Le.readSInt8(this.data);const s=Le.readSInt8(this.data),i=Le.readSInt8(this.data),a=Le.readSInt8(this.data),r=Le.readSInt8(this.data);if(this._versionNumber>=500&&(t.tempoName=Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.tempo=Le.readInt32LE(this.data),t.volume>=0&&this.data.readByte(),t.balance>=0&&this.data.readByte(),s>=0&&this.data.readByte(),i>=0&&this.data.readByte(),a>=0&&this.data.readByte(),r>=0&&this.data.readByte(),t.tempo>=0&&(t.duration=Le.readSInt8(this.data),this._versionNumber>=510&&this.data.readByte()),this._versionNumber>=400&&this.data.readByte(),this._versionNumber>=500){const t=Le.readSInt8(this.data);t>=100?e.wahPedal=ie.Closed:t>=0&&(e.wahPedal=ie.Open)}if(this._versionNumber>=510&&(Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding),Rs.gpReadStringIntByte(this.data,this.settings.importer.encoding)),t.volume>=0){const s=new pe;s.isLinear=!0,s.type=g.Volume,s.value=t.volume,e.automations.push(s)}if(t.balance>=0){const s=new pe;s.isLinear=!0,s.type=g.Balance,s.value=t.balance,e.automations.push(s)}if(t.instrument>=0){const s=new pe;s.isLinear=!0,s.type=g.Instrument,s.value=t.instrument,e.automations.push(s)}if(t.tempo>=0){const s=new pe;s.isLinear=!0,s.type=g.Tempo,s.value=t.tempo,e.automations.push(s),e.voice.bar.masterBar.tempoAutomations.push(s)}}readNote(e,t,s,i,a){const r=new Nt;r.string=t.staff.tuning.length-a;const n=this.data.readByte();if(2&n?r.accentuated=u.Heavy:64&n&&(r.accentuated=u.Normal),r.isGhost=!!(4&n),32&n){const e=this.data.readByte();3===e?r.isDead=!0:2===e&&(r.isTieDestination=!0)}if(1&n&&this._versionNumber<500&&(this.data.readByte(),this.data.readByte()),16&n){const e=Le.readSInt8(this.data);r.dynamics=this.toDynamicValue(e),i.dynamics=r.dynamics}32&n&&(r.fret=Le.readSInt8(this.data)),128&n&&(r.leftHandFinger=Le.readSInt8(this.data),r.rightHandFinger=Le.readSInt8(this.data));let o=!1;if(this._versionNumber>=500){1&n&&(r.durationPercent=Le.readFloat64BE(this.data));o=!!(2&this.data.readByte())}if(i.addNote(r),8&n&&this.readNoteEffects(e,s,i,r),t.staff.isPercussion&&(r.percussionArticulation=r.fret,r.string=-1,r.fret=-1),o){const e=zt.defaultAccidentals[r.realValueWithoutHarmonic%12];"#"===e?r.accidentalMode=N.ForceFlat:"b"===e&&(r.accidentalMode=N.ForceSharp)}return r}toDynamicValue(e){switch(e){case 1:return E.PPP;case 2:return E.PP;case 3:return E.P;case 4:return E.MP;case 5:return E.MF;case 6:default:return E.F;case 7:return E.FF;case 8:return E.FFF}}readNoteEffects(e,t,s,i){const a=this.data.readByte();let r=0;this._versionNumber>=400&&(r=this.data.readByte()),1&a&&this.readBend(i),16&a&&this.readGrace(t,i),4&r&&this.readTremoloPicking(s),8&r?this.readSlide(i):this._versionNumber<400&&4&a&&(i.slideOutType=K.Shift),16&r&&this.readArtificialHarmonic(i),32&r&&this.readTrill(i),i.isLetRing=!!(8&a),i.isHammerPullOrigin=!!(2&a),64&r&&(i.vibrato=j.Slight),i.isPalmMute=!!(2&r),i.isStaccato=!!(1&r)}readBend(e){this.data.readByte(),Le.readInt32LE(this.data);const t=Le.readInt32LE(this.data);if(t>0)for(let s=0;s<t;s++){const t=new ge(0,0);t.offset=Le.readInt32LE(this.data),t.value=Le.readInt32LE(this.data)/As.BendStep|0,Rs.gpReadBool(this.data),e.addBendPoint(t)}}readGrace(e,t){const s=new gs,i=new Nt;i.string=t.string,i.fret=Le.readSInt8(this.data),s.duration=D.ThirtySecond,s.dynamics=this.toDynamicValue(Le.readSInt8(this.data));switch(Le.readSInt8(this.data)){case 0:case 2:break;case 1:i.slideOutType=K.Legato,i.slideTarget=t;break;case 3:i.isHammerPullOrigin=!0}if(i.dynamics=s.dynamics,this.data.skip(1),this._versionNumber<500)s.graceType=R.BeforeBeat;else{const e=this.data.readByte();i.isDead=!!(1&e),s.graceType=2&e?R.OnBeat:R.BeforeBeat}e.addGraceBeat(s),s.addNote(i)}readTremoloPicking(e){switch(this.data.readByte()){case 1:e.tremoloSpeed=D.Eighth;break;case 2:e.tremoloSpeed=D.Sixteenth;break;case 3:e.tremoloSpeed=D.ThirtySecond}}readSlide(e){if(this._versionNumber>=500){const t=Le.readSInt8(this.data);1&t?e.slideOutType=K.Shift:2&t?e.slideOutType=K.Legato:4&t?e.slideOutType=K.OutDown:8&t&&(e.slideOutType=K.OutUp),16&t?e.slideInType=q.IntoFromBelow:32&t&&(e.slideInType=q.IntoFromAbove)}else{switch(Le.readSInt8(this.data)){case 1:e.slideOutType=K.Shift;break;case 2:e.slideOutType=K.Legato;break;case 3:e.slideOutType=K.OutDown;break;case 4:e.slideOutType=K.OutUp;break;case-1:e.slideInType=q.IntoFromBelow;break;case-2:e.slideInType=q.IntoFromAbove}}}readArtificialHarmonic(e){const t=this.data.readByte();if(this._versionNumber>=500)switch(t){case 1:e.harmonicType=H.Natural,e.harmonicValue=Be.deltaFretToHarmonicValue(e.fret);break;case 2:this.data.readByte(),this.data.readByte(),this.data.readByte(),e.harmonicType=H.Artificial;break;case 3:e.harmonicType=H.Tap,e.harmonicValue=Be.deltaFretToHarmonicValue(this.data.readByte());break;case 4:e.harmonicType=H.Pinch,e.harmonicValue=12;break;case 5:e.harmonicType=H.Semi,e.harmonicValue=12}else if(this._versionNumber>=400)switch(t){case 1:e.harmonicType=H.Natural;break;case 3:e.harmonicType=H.Tap;break;case 4:e.harmonicType=H.Pinch;break;case 5:e.harmonicType=H.Semi;break;case 15:case 17:case 22:e.harmonicType=H.Artificial}}readTrill(e){switch(e.trillValue=this.data.readByte()+e.stringTuning,this.data.readByte()){case 1:e.trillSpeed=D.Sixteenth;break;case 2:e.trillSpeed=D.ThirtySecond;break;case 3:e.trillSpeed=D.SixtyFourth}}}As.VersionString="FICHIER GUITAR PRO ",As.BendStep=25;class Rs{static gpReadColor(e,t=!1){const s=e.readByte(),i=e.readByte(),a=e.readByte();let r=255;return t?r=e.readByte():e.skip(1),new ke(s,i,a,r)}static gpReadBool(e){return 0!==e.readByte()}static gpReadStringIntUnused(e,t){return e.skip(4),Rs.gpReadString(e,e.readByte(),t)}static gpReadStringInt(e,t){return Rs.gpReadString(e,Le.readInt32LE(e),t)}static gpReadStringIntByte(e,t){const s=Le.readInt32LE(e)-1;return e.readByte(),Rs.gpReadString(e,s,t)}static gpReadString(e,t,s){const i=new Uint8Array(t);return e.read(i,0,i.length),Le.toString(i,s)}static gpWriteString(e,t){const s=Le.stringToBytes(t);e.writeByte(t.length),e.write(s,0,s.length)}static gpReadStringByteLength(e,t,s){const i=e.readByte(),a=Rs.gpReadString(e,i,s);return i<t&&e.skip(t-i),a}}class Os{constructor(){this.volume=-1,this.balance=-1,this.instrument=-1,this.tempoName="",this.tempo=-1,this.duration=-1}}class Hs{constructor(){this.x=0,this.y=0,this.w=0,this.h=0}scaleWith(e){this.x*=e,this.y*=e,this.w*=e,this.h*=e}}!function(e){e[e.Boolean=0]="Boolean",e[e.Integer=1]="Integer",e[e.Float=2]="Float",e[e.String=3]="String",e[e.Point=4]="Point",e[e.Size=5]="Size",e[e.Rectangle=6]="Rectangle",e[e.Color=7]="Color"}(Ns||(Ns={}));class Ws{constructor(e){this._types=new Map,this.raw=new Map,e&&this.read(e)}read(e){const t=Me.fromBuffer(e),s=Le.readInt32BE(t);for(let e=0;e<s;e++){const e=Rs.gpReadString(t,t.readByte(),"utf-8"),s=t.readByte();switch(this._types.set(e,s),s){case Ns.Boolean:const s=1===t.readByte();this.addValue(e,s);break;case Ns.Integer:const i=Le.readInt32BE(t);this.addValue(e,i);break;case Ns.Float:const a=Le.readFloat32BE(t);this.addValue(e,a);break;case Ns.String:const r=Rs.gpReadString(t,Le.readInt16BE(t),"utf-8");this.addValue(e,r);break;case Ns.Point:const n=Le.readInt32BE(t),o=Le.readInt32BE(t);this.addValue(e,new ge(n,o));break;case Ns.Size:const h=Le.readInt32BE(t),l=Le.readInt32BE(t);this.addValue(e,new ge(h,l));break;case Ns.Rectangle:const c=new Hs;c.x=Le.readInt32BE(t),c.y=Le.readInt32BE(t),c.w=Le.readInt32BE(t),c.h=Le.readInt32BE(t),this.addValue(e,c);break;case Ns.Color:const d=Rs.gpReadColor(t,!0);this.addValue(e,d)}}}apply(e){for(const[t,s]of this.raw)switch(t){case"StandardNotation/hideDynamics":e.stylesheet.hideDynamics=s;break;case"System/bracketExtendMode":e.stylesheet.bracketExtendMode=s;break;case"Global/useSystemSignSeparator":e.stylesheet.useSystemSignSeparator=s;break;case"Global/DisplayTuning":e.stylesheet.globalDisplayTuning=s;break;case"Global/DrawChords":e.stylesheet.globalDisplayChordDiagramsOnTop=s;break;case"System/showTrackNameSingle":s||(e.stylesheet.singleTrackTrackNamePolicy=i.Hidden);break;case"System/showTrackNameMulti":s||(e.stylesheet.multiTrackTrackNamePolicy=i.Hidden);break;case"System/trackNameModeSingle":if(e.stylesheet.singleTrackTrackNamePolicy!==i.Hidden)switch(s){case 0:case 1:e.stylesheet.singleTrackTrackNamePolicy=i.FirstSystem;break;case 2:e.stylesheet.singleTrackTrackNamePolicy=i.AllSystems}break;case"System/trackNameModeMulti":if(e.stylesheet.multiTrackTrackNamePolicy!==i.Hidden)switch(s){case 0:case 1:e.stylesheet.multiTrackTrackNamePolicy=i.FirstSystem;break;case 2:e.stylesheet.multiTrackTrackNamePolicy=i.AllSystems}break;case"System/shortTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameMode=s?a.ShortName:a.FullName;break;case"System/shortTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameMode=s?a.ShortName:a.FullName;break;case"System/horizontalTrackNameOnFirstSystem":e.stylesheet.firstSystemTrackNameOrientation=s?r.Horizontal:r.Vertical;break;case"System/horizontalTrackNameOnOtherSystems":e.stylesheet.otherSystemsTrackNameOrientation=s?r.Horizontal:r.Vertical;break;case"Header/Title":Be.getOrCreateHeaderFooterStyle(e,ws.Title).template=s;break;case"Header/TitleAlignment":Be.getOrCreateHeaderFooterStyle(e,ws.Title).textAlign=this.toTextAlign(s);break;case"Header/drawTitle":Be.getOrCreateHeaderFooterStyle(e,ws.Title).isVisible=s;break;case"Header/Subtitle":Be.getOrCreateHeaderFooterStyle(e,ws.SubTitle).template=s;break;case"Header/SubtitleAlignment":Be.getOrCreateHeaderFooterStyle(e,ws.SubTitle).textAlign=this.toTextAlign(s);break;case"Header/drawSubtitle":Be.getOrCreateHeaderFooterStyle(e,ws.SubTitle).isVisible=s;break;case"Header/Artist":Be.getOrCreateHeaderFooterStyle(e,ws.Artist).template=s;break;case"Header/ArtistAlignment":Be.getOrCreateHeaderFooterStyle(e,ws.Artist).textAlign=this.toTextAlign(s);break;case"Header/drawArtist":Be.getOrCreateHeaderFooterStyle(e,ws.Artist).isVisible=s;break;case"Header/Album":Be.getOrCreateHeaderFooterStyle(e,ws.Album).template=s;break;case"Header/AlbumAlignment":Be.getOrCreateHeaderFooterStyle(e,ws.Album).textAlign=this.toTextAlign(s);break;case"Header/drawAlbum":Be.getOrCreateHeaderFooterStyle(e,ws.Album).isVisible=s;break;case"Header/Words":Be.getOrCreateHeaderFooterStyle(e,ws.Words).template=s;break;case"Header/WordsAlignment":Be.getOrCreateHeaderFooterStyle(e,ws.Words).textAlign=this.toTextAlign(s);break;case"Header/drawWords":Be.getOrCreateHeaderFooterStyle(e,ws.Words).isVisible=s;break;case"Header/Music":Be.getOrCreateHeaderFooterStyle(e,ws.Music).template=s;break;case"Header/MusicAlignment":Be.getOrCreateHeaderFooterStyle(e,ws.Music).textAlign=this.toTextAlign(s);break;case"Header/drawMusic":Be.getOrCreateHeaderFooterStyle(e,ws.Music).isVisible=s;break;case"Header/WordsAndMusic":Be.getOrCreateHeaderFooterStyle(e,ws.WordsAndMusic).template=s;break;case"Header/WordsAndMusicAlignment":Be.getOrCreateHeaderFooterStyle(e,ws.WordsAndMusic).textAlign=this.toTextAlign(s);break;case"Header/drawWordsAndMusic":Be.getOrCreateHeaderFooterStyle(e,ws.WordsAndMusic).isVisible=s;break;case"Header/Tabber":Be.getOrCreateHeaderFooterStyle(e,ws.Transcriber).template=s;break;case"Header/TabberAlignment":Be.getOrCreateHeaderFooterStyle(e,ws.Transcriber).textAlign=this.toTextAlign(s);break;case"Header/drawTabber":Be.getOrCreateHeaderFooterStyle(e,ws.Transcriber).isVisible=s;break;case"Footer/Copyright":Be.getOrCreateHeaderFooterStyle(e,ws.Copyright).template=s;break;case"Footer/CopyrightAlignment":Be.getOrCreateHeaderFooterStyle(e,ws.Copyright).textAlign=this.toTextAlign(s);break;case"Footer/drawCopyright":Be.getOrCreateHeaderFooterStyle(e,ws.Copyright).isVisible=s;break;case"Footer/Copyright2":Be.getOrCreateHeaderFooterStyle(e,ws.CopyrightSecondLine).template=s;break;case"Footer/Copyright2Alignment":Be.getOrCreateHeaderFooterStyle(e,ws.CopyrightSecondLine).textAlign=this.toTextAlign(s);break;case"Footer/drawCopyright2":Be.getOrCreateHeaderFooterStyle(e,ws.CopyrightSecondLine).isVisible=s}}toTextAlign(e){switch(e){case 0:return W.Left;case 1:return W.Center;case 2:return W.Right}return W.Left}addValue(e,t,s){this.raw.set(e,t),void 0!==s&&this._types.set(e,s)}writeTo(e){Le.writeInt32BE(e,this.raw.size);for(const[t,s]of this.raw){const i=this.getDataType(t,s);switch(Rs.gpWriteString(e,t),e.writeByte(i),i){case Ns.Boolean:e.writeByte(s?1:0);break;case Ns.Integer:Le.writeInt32BE(e,s);break;case Ns.Float:Le.writeFloat32BE(e,s);break;case Ns.String:const t=Le.stringToBytes(s);Le.writeInt16BE(e,t.length),e.write(t,0,t.length);break;case Ns.Point:case Ns.Size:Le.writeInt32BE(e,s.offset),Le.writeInt32BE(e,s.value);break;case Ns.Rectangle:Le.writeInt32BE(e,s.x),Le.writeInt32BE(e,s.y),Le.writeInt32BE(e,s.w),Le.writeInt32BE(e,s.h);break;case Ns.Color:e.writeByte(s.r),e.writeByte(s.g),e.writeByte(s.b),e.writeByte(s.a)}}}getDataType(e,t){if(this._types.has(e))return this._types.get(e);const s=typeof t;switch(typeof t){case"string":return Ns.String;case"number":return t===(0|t)?Ns.Integer:Ns.Float;case"object":if(t instanceof ge)return Ns.Point;if(t instanceof Hs)return Ns.Rectangle;if(t instanceof ke)return Ns.Color}throw new fe(S.General,`Unknown value type in BinaryStylesheet: ${s}`)}static writeForScore(e){const t=new Ws;switch(t.addValue("StandardNotation/hideDynamics",e.stylesheet.hideDynamics,Ns.Boolean),t.addValue("System/bracketExtendMode",e.stylesheet.bracketExtendMode,Ns.Integer),t.addValue("Global/useSystemSignSeparator",e.stylesheet.useSystemSignSeparator,Ns.Boolean),t.addValue("Global/DisplayTuning",e.stylesheet.globalDisplayTuning,Ns.Boolean),t.addValue("Global/DrawChords",e.stylesheet.globalDisplayChordDiagramsOnTop,Ns.Boolean),e.stylesheet.singleTrackTrackNamePolicy){case i.Hidden:t.addValue("System/showTrackNameSingle",!1,Ns.Boolean);break;case i.FirstSystem:t.addValue("System/trackNameModeSingle",0,Ns.Integer);break;case i.AllSystems:t.addValue("System/trackNameModeSingle",2,Ns.Integer)}switch(e.stylesheet.multiTrackTrackNamePolicy){case i.Hidden:t.addValue("System/trackNameModeMulti",!1,Ns.Boolean);break;case i.FirstSystem:t.addValue("System/trackNameModeMulti",0,Ns.Integer);break;case i.AllSystems:t.addValue("System/trackNameModeMulti",2,Ns.Integer)}switch(e.stylesheet.firstSystemTrackNameMode){case a.FullName:t.addValue("System/shortTrackNameOnFirstSystem",!1,Ns.Boolean);break;case a.ShortName:t.addValue("System/shortTrackNameOnFirstSystem",!0,Ns.Boolean)}switch(e.stylesheet.otherSystemsTrackNameMode){case a.FullName:t.addValue("System/shortTrackNameOnOtherSystems",!1,Ns.Boolean);break;case a.ShortName:t.addValue("System/shortTrackNameOnOtherSystems",!0,Ns.Boolean)}switch(e.stylesheet.firstSystemTrackNameOrientation){case r.Horizontal:t.addValue("System/horizontalTrackNameOnFirstSystem",!0,Ns.Boolean);break;case r.Vertical:t.addValue("System/horizontalTrackNameOnFirstSystem",!1,Ns.Boolean)}switch(e.stylesheet.otherSystemsTrackNameOrientation){case r.Horizontal:t.addValue("System/horizontalTrackNameOnOtherSystems",!0,Ns.Boolean);break;case r.Vertical:t.addValue("System/horizontalTrackNameOnOtherSystems",!1,Ns.Boolean)}const s=e.style;if(s)for(const[e,i]of s.headerAndFooter)switch(e){case ws.Title:Ws.addHeaderAndFooter(t,i,"Header/","Title");break;case ws.SubTitle:Ws.addHeaderAndFooter(t,i,"Header/","Subtitle");break;case ws.Artist:Ws.addHeaderAndFooter(t,i,"Header/","Artist");break;case ws.Album:Ws.addHeaderAndFooter(t,i,"Header/","Album");break;case ws.Words:Ws.addHeaderAndFooter(t,i,"Header/","Words");break;case ws.Music:Ws.addHeaderAndFooter(t,i,"Header/","Music");break;case ws.WordsAndMusic:Ws.addHeaderAndFooter(t,i,"Header/","WordsAndMusic");break;case ws.Transcriber:Ws.addHeaderAndFooter(t,i,"Header/","Tabber");break;case ws.Copyright:Ws.addHeaderAndFooter(t,i,"Footer/","Copyright");break;case ws.CopyrightSecondLine:Ws.addHeaderAndFooter(t,i,"Footer/","Copyright2")}const n=Me.withCapacity(128);return t.writeTo(n),n.toArray()}static addHeaderAndFooter(e,t,s,i){void 0!==t.template&&e.addValue(`${s}${i}`,t.template,Ns.String),e.addValue(`${s}${i}Alignment`,t.textAlign,Ns.Integer),void 0!==t.isVisible&&e.addValue(`${s}draw${i}`,t.isVisible,Ns.Boolean)}}!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"}(xs||(xs={}));class Vs{constructor(){this.nodeType=xs.None,this.localName=null,this.value=null,this.childNodes=[],this.attributes=new Map,this.firstChild=null,this.firstElement=null}*childElements(){for(const e of this.childNodes)e.nodeType===xs.Element&&(yield e)}addChild(e){this.childNodes.push(e),this.firstChild=e,e.nodeType!==xs.Element&&e.nodeType!==xs.CDATA||(this.firstElement=e)}getAttribute(e,t=""){return this.attributes.has(e)?this.attributes.get(e):t}getElementsByTagName(e,t=!1){const s=[];return this.searchElementsByTagName(this.childNodes,s,e,t),s}searchElementsByTagName(e,t,s,i=!1){for(const a of e)a&&a.nodeType===xs.Element&&a.localName===s&&t.push(a),i&&this.searchElementsByTagName(a.childNodes,t,s,!0)}findChildElement(e){for(const t of this.childNodes)if(t&&t.nodeType===xs.Element&&t.localName===e)return t;return null}addElement(e){const t=new Vs;return t.nodeType=xs.Element,t.localName=e,this.addChild(t),t}get innerText(){if(this.nodeType===xs.Element||this.nodeType===xs.Document){if(this.firstElement&&this.firstElement.nodeType===xs.CDATA)return this.firstElement.innerText;let e="";for(const t of this.childNodes)e+=t.innerText?.toString();return e.trim()}return this.value??""}set innerText(e){const t=new Vs;t.nodeType=xs.Text,t.value=e,this.childNodes=[t]}setCData(e){const t=new Vs;t.nodeType=xs.CDATA,t.value=e,this.childNodes=[t]}}class Gs extends fe{constructor(e,t,s){super(S.Format,e),this.pos=0,this.xml=t,this.pos=s,Object.setPrototypeOf(this,Gs.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"}(vs||(vs={}));class zs{static parse(e,t,s){let i=e.charCodeAt(t),a=vs.Begin,r=vs.Begin,n=0,o="",h=vs.Begin,l=null,c=null,d=0,u=0;for(;t<e.length;){switch(i=e.charCodeAt(t),a){case vs.IgnoreSpaces:switch(i){case zs.CharCodeLF:case zs.CharCodeCR:case zs.CharCodeTab:case zs.CharCodeSpace:break;default:a=r;continue}break;case vs.Begin:if(i!==zs.CharCodeLowerThan){n=t,a=vs.Pcdata;continue}a=vs.IgnoreSpaces,r=vs.BeginNode;break;case vs.Pcdata:if(i===zs.CharCodeLowerThan){o+=e.substr(n,t-n);const i=new Vs;i.nodeType=xs.Text,i.value=o,o="",s.addChild(i),a=vs.IgnoreSpaces,r=vs.BeginNode}else i===zs.CharCodeAmp&&(o+=e.substr(n,t-n),a=vs.Escape,h=vs.Pcdata,n=t+1);break;case vs.Cdata:if(i===zs.CharCodeBrackedClose&&e.charCodeAt(t+1)===zs.CharCodeBrackedClose&&e.charCodeAt(t+2)===zs.CharCodeGreaterThan){const i=new Vs;i.nodeType=xs.CDATA,i.value=e.substr(n,t-n),s.addChild(i),t+=2,a=vs.Begin}break;case vs.BeginNode:switch(i){case zs.CharCodeExclamation:if(e.charCodeAt(t+1)===zs.CharCodeBrackedOpen){if(t+=2,"CDATA["!==e.substr(t,6).toUpperCase())throw new Gs("Expected <![CDATA[",e,t);t+=5,a=vs.Cdata,n=t+1}else if(e.charCodeAt(t+1)===zs.CharCodeUpperD||e.charCodeAt(t+1)===zs.CharCodeLowerD){if("OCTYPE"!==e.substr(t+2,6).toUpperCase())throw new Gs("Expected <!DOCTYPE",e,t);t+=8,a=vs.Doctype,n=t+1}else{if(e.charCodeAt(t+1)!==zs.CharCodeMinus||e.charCodeAt(t+2)!==zs.CharCodeMinus)throw new Gs("Expected \x3c!--",e,t);t+=2,a=vs.Comment,n=t+1}break;case zs.CharCodeQuestion:a=vs.Header,n=t;break;case zs.CharCodeSlash:if(!s)throw new Gs("Expected node name",e,t);n=t+1,a=vs.IgnoreSpaces,r=vs.Close;break;default:a=vs.TagName,n=t;continue}break;case vs.TagName:if(!zs.isValidChar(i)){if(t===n)throw new Gs("Expected node name",e,t);l=new Vs,l.nodeType=xs.Element,l.localName=e.substr(n,t-n),s.addChild(l),a=vs.IgnoreSpaces,r=vs.Body;continue}break;case vs.Body:switch(i){case zs.CharCodeSlash:a=vs.WaitEnd;break;case zs.CharCodeGreaterThan:a=vs.Childs;break;default:a=vs.AttribName,n=t;continue}break;case vs.AttribName:if(!zs.isValidChar(i)){if(n===t)throw new Gs("Expected attribute name",e,t);if(c=e.substr(n,t-n),l.attributes.has(c))throw new Gs(`Duplicate attribute [${c}]`,e,t);a=vs.IgnoreSpaces,r=vs.Equals;continue}break;case vs.Equals:if(i!==zs.CharCodeEquals)throw new Gs("Expected =",e,t);a=vs.IgnoreSpaces,r=vs.AttvalBegin;break;case vs.AttvalBegin:switch(i){case zs.CharCodeDoubleQuote:case zs.CharCodeSingleQuote:o="",a=vs.AttribVal,n=t+1,u=i}break;case vs.AttribVal:if(i===zs.CharCodeAmp)o+=e.substr(n,t-n),a=vs.Escape,h=vs.AttribVal,n=t+1;else if(i===u){o+=e.substr(n,t-n);const s=o;o="",l.attributes.set(c,s),a=vs.IgnoreSpaces,r=vs.Body}break;case vs.Childs:n=t=zs.parse(e,t,l),a=vs.Begin;break;case vs.WaitEnd:if(i!==zs.CharCodeGreaterThan)throw new Gs("Expected >",e,t);a=vs.Begin;break;case vs.WaitEndRet:if(i===zs.CharCodeGreaterThan)return t;throw new Gs("Expected >",e,t);case vs.Close:if(!zs.isValidChar(i)){if(n===t)throw new Gs("Expected node name",e,t);if(e.substr(n,t-n)!==s.localName)throw new Gs(`Expected </${s.localName}>`,e,t);a=vs.IgnoreSpaces,r=vs.WaitEndRet;continue}break;case vs.Comment:i===zs.CharCodeMinus&&e.charCodeAt(t+1)===zs.CharCodeMinus&&e.charCodeAt(t+2)===zs.CharCodeGreaterThan&&(t+=2,a=vs.Begin);break;case vs.Doctype:if(i===zs.CharCodeBrackedOpen)d++;else if(i===zs.CharCodeBrackedClose)d--;else if(i===zs.CharCodeGreaterThan&&0===d){const i=new Vs;i.nodeType=xs.DocumentType,i.value=e.substr(n,t-n),s.addChild(i),a=vs.Begin}break;case vs.Header:i===zs.CharCodeQuestion&&e.charCodeAt(t+1)===zs.CharCodeGreaterThan&&(t++,a=vs.Begin);break;case vs.Escape:if(i===zs.CharCodeSemi){const s=e.substr(n,t-n);if(s.charCodeAt(0)===zs.CharCodeSharp){const e=s.charCodeAt(1)===zs.CharCodeLowerX?Number.parseInt(`0${s.substr(1,s.length-1)}`):Number.parseInt(s.substr(1,s.length-1));o+=String.fromCharCode(e)}else zs.Escapes.has(s)?o+=zs.Escapes.get(s):o+=`&${s};`?.toString();n=t+1,a=h}else zs.isValidChar(i)||i===zs.CharCodeSharp||(o+="&",o+=e.substr(n,t-n),n=--t+1,a=h)}t++}if(a===vs.Begin&&(n=t,a=vs.Pcdata),a===vs.Pcdata){if(t!==n){o+=e.substr(n,t-n);const i=new Vs;i.nodeType=xs.Text,i.value=o,s.addChild(i)}return t}if(a===vs.Escape&&h===vs.Pcdata){o+="&",o+=e.substr(n,t-n);const i=new Vs;return i.nodeType=xs.Text,i.value=o,s.addChild(i),t}throw new Gs("Unexpected end",e,t)}static isValidChar(e){return e>=zs.CharCodeLowerA&&e<=zs.CharCodeLowerZ||e>=zs.CharCodeUpperA&&e<=zs.CharCodeUpperZ||e>=zs.CharCode0&&e<=zs.CharCode9||e===zs.CharCodeColon||e===zs.CharCodeDot||e===zs.CharCodeUnderscore||e===zs.CharCodeMinus}}zs.CharCodeLF=10,zs.CharCodeTab=9,zs.CharCodeCR=13,zs.CharCodeSpace=32,zs.CharCodeLowerThan=60,zs.CharCodeAmp=38,zs.CharCodeBrackedClose=93,zs.CharCodeBrackedOpen=91,zs.CharCodeGreaterThan=62,zs.CharCodeExclamation=33,zs.CharCodeUpperD=68,zs.CharCodeLowerD=100,zs.CharCodeMinus=45,zs.CharCodeQuestion=63,zs.CharCodeSlash=47,zs.CharCodeEquals=61,zs.CharCodeDoubleQuote=34,zs.CharCodeSingleQuote=39,zs.CharCodeSharp=35,zs.CharCodeLowerX=120,zs.CharCodeLowerA=97,zs.CharCodeLowerZ=122,zs.CharCodeUpperA=65,zs.CharCodeUpperZ=90,zs.CharCode0=48,zs.CharCode9=57,zs.CharCodeColon=58,zs.CharCodeDot=46,zs.CharCodeUnderscore=95,zs.CharCodeSemi=59,zs.Escapes=new Map([["lt","<"],["gt",">"],["amp","&"],["quot",'"'],["apos","'"]]);class Us{static write(e,t,s){const i=new Us(t,s);return i.writeNode(e),i.toString()}constructor(e,t){this._result=[],this._indention=e,this._xmlHeader=t,this._currentIndention="",this._isStartOfLine=!0}writeNode(e){switch(e.nodeType){case xs.None:break;case xs.Element:this._result.length>0&&this.writeLine(),this.write(`<${e.localName}`);for(const[t,s]of e.attributes)this.write(` ${t}="`),this.writeAttributeValue(s),this.write('"');if(0===e.childNodes.length)this.write("/>");else{if(this.write(">"),1!==e.childNodes.length||e.firstElement){this.indent();for(const t of e.childNodes)t.nodeType===xs.Element&&this.writeNode(t);this.unindend(),this.writeLine()}else this.writeNode(e.childNodes[0]);this.write(`</${e.localName}>`)}break;case xs.Text:e.value&&this.write(e.value);break;case xs.CDATA:null!==e.value&&this.write(`<![CDATA[${e.value}]]>`);break;case xs.Document:this._xmlHeader&&this.write('<?xml version="1.0" encoding="utf-8"?>');for(const t of e.childNodes)this.writeNode(t);break;case xs.DocumentType:this.write(`<!DOCTYPE ${e.value}>`)}}unindend(){this._currentIndention=this._currentIndention.substr(0,this._currentIndention.length-this._indention.length)}indent(){this._currentIndention+=this._indention}writeAttributeValue(e){for(let t=0;t<e.length;t++){const s=e.charAt(t);switch(s){case"<":this._result.push("&lt;");break;case">":this._result.push("&gt;");break;case"&":this._result.push("&amp;");break;case"'":this._result.push("&apos;");break;case'"':this._result.push("&quot;");break;default:this._result.push(s)}}}write(e){this._isStartOfLine&&this._result.push(this._currentIndention),this._result.push(e),this._isStartOfLine=!1}writeLine(e=null){e&&this.write(e),this._indention.length>0&&!this._isStartOfLine&&(this._result.push("\n"),this._isStartOfLine=!0)}toString(){return this._result.join("").trimRight()}}class Xs extends Vs{constructor(){super(),this.nodeType=xs.Document}parse(e){zs.parse(e,0,this)}toString(){return this.toFormattedString()}toFormattedString(e="",t=!1){return Us.write(this,e,t)}}class Js{constructor(){this.id="",this.dots=0,this.tupletDenominator=-1,this.tupletNumerator=-1,this.value=D.Quarter}}class Ys{constructor(){this.name="",this.path="",this.role="",this.program=0}get uniqueId(){return`${this.path};${this.name};${this.role}`}}class $s{constructor(){this._hasAnacrusis=!1,this._skipApplyLyrics=!1,this._doubleBars=new Set}parseXml(e,t){this._masterTrackAutomations=new Map,this._automationsPerTrackIdAndBarIndex=new Map,this._sustainPedalsPerTrackIdAndBarIndex=new Map,this._tracksMapping=[],this._tracksById=new Map,this._masterBars=[],this._barsOfMasterBar=[],this._voicesOfBar=new Map,this._barsById=new Map,this._voiceById=new Map,this._beatsOfVoice=new Map,this._beatById=new Map,this._rhythmOfBeat=new Map,this._rhythmById=new Map,this._notesOfBeat=new Map,this._noteById=new Map,this._tappedNotes=new Map,this._lyricsByTrack=new Map,this._soundsByTrack=new Map,this._skipApplyLyrics=!1;const s=new Xs;try{s.parse(e)}catch(e){throw new Es("Could not parse XML",e)}if(this.parseDom(s),this.buildModel(),this.score.finish(t),!this._skipApplyLyrics&&this._lyricsByTrack.size>0)for(const[e,t]of this._lyricsByTrack){this._tracksById.get(e).applyLyrics(t)}}parseDom(e){const t=e.firstElement;if(t){if("GPIF"!==t.localName)throw new Es("Root node of XML was not GPIF");this.score=new Cs;for(const e of t.childElements())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(const t of e.childElements())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){const e=t.firstChild.innerText;e&&!this.score.words&&(this.score.words=e),e&&!this.score.music&&(this.score.music=e)}break;case"Copyright":this.score.copyright=t.firstChild.innerText;break;case"Tabber":this.score.tab=t.firstChild.innerText;break;case"Instructions":this.score.instructions=t.firstChild.innerText;break;case"Notices":this.score.notices=t.firstChild.innerText;break;case"ScoreSystemsDefaultLayout":this.score.defaultSystemsLayout=Number.parseInt(t.innerText);break;case"ScoreSystemsLayout":this.score.systemsLayout=t.innerText.split(" ").map((e=>Number.parseInt(e)))}}parseMasterTrackNode(e){for(const t of e.childElements())switch(t.localName){case"Automations":this.parseAutomations(t,this._masterTrackAutomations,null,null);break;case"Tracks":this._tracksMapping=t.innerText.split(" ");break;case"Anacrusis":this._hasAnacrusis=!0}}parseAutomations(e,t,s,i){for(const a of e.childElements())if("Automation"===a.localName)this.parseAutomation(a,t,s,i)}parseAutomation(e,t,s,i){let a=null,r=!1,n=-1,o=0,h=0,c=null,d=0,u=null;for(const t of e.childElements())switch(t.localName){case"Type":a=t.innerText;break;case"Linear":r="true"===t.innerText.toLowerCase();break;case"Bar":n=Number.parseInt(t.innerText);break;case"Position":o=Number.parseFloat(t.innerText);break;case"Value":if(t.firstElement&&t.firstElement.nodeType===xs.CDATA)c=t.innerText;else{const e=t.innerText.split(" ");1===e.length?(h=Number.parseFloat(e[0]),d=1):(h=Number.parseFloat(e[0]),d=Number.parseInt(e[1]))}break;case"Text":u=t.innerText}if(!a)return;let p=null;switch(a){case"Tempo":p=pe.buildTempoAutomation(r,o,h,d);break;case"Sound":c&&s&&s.has(c)&&(p=pe.buildInstrumentAutomation(r,o,s.get(c).program));break;case"SustainPedal":if(i){let e;i.has(n)?e=i.get(n):(e=[],i.set(n,e));const t=new ce;switch(t.ratioPosition=o,d){case 1:t.pedalType=l.Down;break;case 3:t.pedalType=l.Up}e.push(t)}}p&&(u&&(p.text=u),n>=0&&(t.has(n)||t.set(n,[]),t.get(n).push(p)))}parseTracksNode(e){for(const t of e.childElements())if("Track"===t.localName)this.parseTrack(t)}parseTrack(e){this._articulationByName=new Map;const t=new $t;t.ensureStaveCount(1);t.staves[0].showStandardNotation=!0;const s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Name":t.name=i.innerText;break;case"Color":const e=i.innerText.split(" ");if(e.length>=3){const s=Number.parseInt(e[0]),i=Number.parseInt(e[1]),a=Number.parseInt(e[2]);t.color=new ke(s,i,a,255)}break;case"Instrument":const a=i.getAttribute("ref");(a.endsWith("-gs")||a.endsWith("GrandStaff"))&&(t.ensureStaveCount(2),t.staves[1].showStandardNotation=!0);break;case"InstrumentSet":this.parseInstrumentSet(t,i);break;case"NotationPatch":this.parseNotationPatch(t,i);break;case"ShortName":t.shortName=i.innerText;break;case"SystemsDefautLayout":t.defaultSystemsLayout=Number.parseInt(i.innerText);break;case"SystemsLayout":t.systemsLayout=i.innerText.split(" ").map((e=>Number.parseInt(e)));break;case"Lyrics":this.parseLyrics(s,i);break;case"Properties":this.parseTrackProperties(t,i);break;case"GeneralMidi":case"MidiConnection":case"MIDISettings":this.parseGeneralMidi(t,i);break;case"Sounds":this.parseSounds(s,t,i);break;case"PlaybackState":const r=i.innerText;t.playbackInfo.isSolo="Solo"===r,t.playbackInfo.isMute="Mute"===r;break;case"PartSounding":this.parsePartSounding(t,i);break;case"Staves":this.parseStaves(t,i);break;case"Transpose":this.parseTranspose(t,i);break;case"RSE":this.parseRSE(t,i);break;case"Automations":this.parseTrackAutomations(s,i)}this._tracksById.set(s,t)}parseTrackAutomations(e,t){const s=new Map;this._automationsPerTrackIdAndBarIndex.set(e,s);const i=new Map;this._sustainPedalsPerTrackIdAndBarIndex.set(e,i),this.parseAutomations(t,s,this._soundsByTrack.get(e),i)}parseNotationPatch(e,t){for(const s of t.childElements())switch(s.localName){case"LineCount":const t=Number.parseInt(s.innerText);for(const s of e.staves)s.standardNotationLineCount=t;break;case"Elements":this.parseElements(e,s)}}parseInstrumentSet(e,t){for(const s of t.childElements())switch(s.localName){case"Type":if("drumKit"===s.innerText)for(const t of e.staves)t.isPercussion=!0;if("drumKit"===s.innerText)for(const t of e.staves)t.isPercussion=!0;break;case"Elements":this.parseElements(e,s);break;case"LineCount":const t=Number.parseInt(s.innerText);for(const s of e.staves)s.standardNotationLineCount=t}}parseElements(e,t){for(const s of t.childElements())if("Element"===s.localName)this.parseElement(e,s)}parseElement(e,t){const s=t.findChildElement("Type"),i=s?s.innerText:"";for(const s of t.childElements())switch(s.localName){case"Name":case"Articulations":this.parseArticulations(e,s,i)}}parseArticulations(e,t,s){for(const i of t.childElements())if("Articulation"===i.localName)this.parseArticulation(e,i,s)}parseArticulation(e,t,s){const i=new De;i.outputMidiNumber=-1,i.elementType=s;let a="";for(const e of t.childElements()){const t=e.innerText;switch(e.localName){case"Name":a=e.innerText;break;case"OutputMidiNumber":t.length>0&&(i.outputMidiNumber=Number.parseInt(t));break;case"TechniqueSymbol":i.techniqueSymbol=this.parseTechniqueSymbol(t);break;case"TechniquePlacement":switch(t){case"outside":case"above":i.techniqueSymbolPlacement=V.Bottom;break;case"inside":i.techniqueSymbolPlacement=V.Middle;break;case"below":i.techniqueSymbolPlacement=V.Top}break;case"Noteheads":const s=t.split(" ");s.length>=1&&(i.noteHeadDefault=this.parseNoteHead(s[0])),s.length>=2&&(i.noteHeadHalf=this.parseNoteHead(s[1])),s.length>=3&&(i.noteHeadWhole=this.parseNoteHead(s[2])),i.noteHeadHalf===G.None&&(i.noteHeadHalf=i.noteHeadDefault),i.noteHeadWhole===G.None&&(i.noteHeadWhole=i.noteHeadDefault);break;case"StaffLine":t.length>0&&(i.staffLine=Number.parseInt(t))}}-1!==i.outputMidiNumber?(e.percussionArticulations.push(i),a.length>0&&this._articulationByName.set(a,i)):a.length>0&&this._articulationByName.has(a)&&(this._articulationByName.get(a).staffLine=i.staffLine)}parseTechniqueSymbol(e){switch(e){case"pictEdgeOfCymbal":return G.PictEdgeOfCymbal;case"articStaccatoAbove":return G.ArticStaccatoAbove;case"noteheadParenthesis":return G.NoteheadParenthesis;case"stringsUpBow":return G.StringsUpBow;case"stringsDownBow":return G.StringsDownBow;case"guitarGolpe":return G.GuitarGolpe;default:return G.None}}parseNoteHead(e){switch(e){case"noteheadDoubleWholeSquare":return G.NoteheadDoubleWholeSquare;case"noteheadDoubleWhole":return G.NoteheadDoubleWhole;case"noteheadWhole":return G.NoteheadWhole;case"noteheadHalf":return G.NoteheadHalf;case"noteheadBlack":return G.NoteheadBlack;case"noteheadNull":return G.NoteheadNull;case"noteheadXOrnate":return G.NoteheadXOrnate;case"noteheadTriangleUpWhole":return G.NoteheadTriangleUpWhole;case"noteheadTriangleUpHalf":return G.NoteheadTriangleUpHalf;case"noteheadTriangleUpBlack":return G.NoteheadTriangleUpBlack;case"noteheadDiamondBlackWide":return G.NoteheadDiamondBlackWide;case"noteheadDiamondWhite":return G.NoteheadDiamondWhite;case"noteheadDiamondWhiteWide":return G.NoteheadDiamondWhiteWide;case"noteheadCircleX":return G.NoteheadCircleX;case"noteheadXWhole":return G.NoteheadXWhole;case"noteheadXHalf":return G.NoteheadXHalf;case"noteheadXBlack":return G.NoteheadXBlack;case"noteheadParenthesis":return G.NoteheadParenthesis;case"noteheadSlashedBlack2":return G.NoteheadSlashedBlack2;case"noteheadCircleSlash":return G.NoteheadCircleSlash;case"noteheadHeavyX":return G.NoteheadHeavyX;case"noteheadHeavyXHat":return G.NoteheadHeavyXHat;default:return wt.warning("GPIF","Unknown notehead symbol",e),G.None}}parseStaves(e,t){let s=0;for(const i of t.childElements())if("Staff"===i.localName){e.ensureStaveCount(s+1);const t=e.staves[s];this.parseStaff(t,i),s++}}parseStaff(e,t){for(const s of t.childElements())if("Properties"===s.localName)this.parseStaffProperties(e,s)}parseStaffProperties(e,t){for(const s of t.childElements())if("Property"===s.localName)this.parseStaffProperty(e,s)}parseStaffProperty(e,t){switch(t.getAttribute("name")){case"Tuning":for(const s of t.childElements())switch(s.localName){case"Pitches":const i=t.findChildElement("Pitches").innerText.split(" "),a=new Array(i.length);for(let e=0;e<a.length;e++)a[a.length-1-e]=Number.parseInt(i[e]);e.stringTuning.tunings=a;break;case"Label":e.stringTuning.name=s.innerText}e.isPercussion||(e.showTablature=!0);break;case"DiagramCollection":case"ChordCollection":this.parseDiagramCollectionForStaff(e,t);break;case"CapoFret":const s=Number.parseInt(t.findChildElement("Fret").innerText);e.capo=s}}parseLyrics(e,t){const s=[];for(const e of t.childElements())if("Line"===e.localName)s.push(this.parseLyricsLine(e));this._lyricsByTrack.set(e,s)}parseLyricsLine(e){const t=new ss;for(const s of e.childElements())switch(s.localName){case"Offset":t.startBar=Number.parseInt(s.innerText);break;case"Text":t.text=s.innerText}return t}parseDiagramCollectionForTrack(e,t){const s=t.findChildElement("Items");for(const t of s.childElements())if("Item"===t.localName)this.parseDiagramItemForTrack(e,t)}parseDiagramCollectionForStaff(e,t){const s=t.findChildElement("Items");for(const t of s.childElements())if("Item"===t.localName)this.parseDiagramItemForStaff(e,t)}parseDiagramItemForTrack(e,t){const s=new me,i=t.getAttribute("id");for(const t of e.staves)t.addChord(i,s);this.parseDiagramItemForChord(s,t)}parseDiagramItemForStaff(e,t){const s=new me,i=t.getAttribute("id");e.addChord(i,s),this.parseDiagramItemForChord(s,t)}parseDiagramItemForChord(e,t){e.name=t.getAttribute("name");const s=t.findChildElement("Diagram");if(!s)return e.showDiagram=!1,void(e.showFingering=!1);const i=Number.parseInt(s.getAttribute("stringCount")),a=s.attributes.has("baseFret")?Number.parseInt(s.getAttribute("baseFret")):0;e.firstFret=a+1;for(let t=0;t<i;t++)e.strings.push(-1);for(const t of s.childElements())switch(t.localName){case"Fret":const s=Number.parseInt(t.getAttribute("string"));e.strings[i-s-1]=a+Number.parseInt(t.getAttribute("fret"));break;case"Fingering":const r=new Map;for(const s of t.childElements())if("Position"===s.localName){let t=_.Unknown;const i=a+Number.parseInt(s.getAttribute("fret"));switch(s.getAttribute("finger")){case"Index":t=_.IndexFinger;break;case"Middle":t=_.MiddleFinger;break;case"Rank":t=_.AnnularFinger;break;case"Pinky":t=_.LittleFinger;break;case"Thumb":t=_.Thumb}t!==_.Unknown&&(r.has(t)?e.barreFrets.push(i):r.set(t,!0))}break;case"Property":switch(t.getAttribute("name")){case"ShowName":e.showName="true"===t.getAttribute("value");break;case"ShowDiagram":e.showDiagram="true"===t.getAttribute("value");break;case"ShowFingering":e.showFingering="true"===t.getAttribute("value")}}}parseTrackProperties(e,t){for(const s of t.childElements())if("Property"===s.localName)this.parseTrackProperty(e,s)}parseTrackProperty(e,t){switch(t.getAttribute("name")){case"Tuning":const s=t.findChildElement("Pitches").innerText.split(" "),i=new Array(s.length);for(let e=0;e<i.length;e++)i[i.length-1-e]=Number.parseInt(s[e]);for(const t of e.staves)t.stringTuning.tunings=i,t.showStandardNotation=!0,t.showTablature=!0;break;case"DiagramCollection":case"ChordCollection":this.parseDiagramCollectionForTrack(e,t);break;case"CapoFret":const a=Number.parseInt(t.findChildElement("Fret").innerText);for(const t of e.staves)t.capo=a}}parseGeneralMidi(e,t){for(const s of t.childElements())switch(s.localName){case"Program":e.playbackInfo.program=Number.parseInt(s.innerText);break;case"Port":e.playbackInfo.port=Number.parseInt(s.innerText);break;case"PrimaryChannel":e.playbackInfo.primaryChannel=Number.parseInt(s.innerText);break;case"SecondaryChannel":e.playbackInfo.secondaryChannel=Number.parseInt(s.innerText)}if("Percussion"===t.getAttribute("table"))for(const t of e.staves)t.isPercussion=!0}parseSounds(e,t,s){for(const i of s.childElements())if("Sound"===i.localName)this.parseSound(e,t,i)}parseSound(e,t,s){const i=new Ys;for(const e of s.childElements())switch(e.localName){case"Name":i.name=e.innerText;break;case"Path":i.path=e.innerText;break;case"Role":i.role=e.innerText;break;case"MIDI":this.parseSoundMidi(i,e)}"Factory"!==i.role&&0!==t.playbackInfo.program||(t.playbackInfo.program=i.program),this._soundsByTrack.has(e)||this._soundsByTrack.set(e,new Map),this._soundsByTrack.get(e).set(i.uniqueId,i)}parseSoundMidi(e,t){for(const s of t.childElements())if("Program"===s.localName)e.program=Number.parseInt(s.innerText)}parsePartSounding(e,t){for(const s of t.childElements())if("TranspositionPitch"===s.localName)for(const t of e.staves)t.displayTranspositionPitch=Number.parseInt(s.innerText)}parseTranspose(e,t){let s=0,i=0;for(const e of t.childElements())switch(e.localName){case"Chromatic":i=Number.parseInt(e.innerText);break;case"Octave":s=Number.parseInt(e.innerText)}for(const t of e.staves)t.displayTranspositionPitch=12*s+i}parseRSE(e,t){for(const s of t.childElements())if("ChannelStrip"===s.localName)this.parseChannelStrip(e,s)}parseChannelStrip(e,t){for(const s of t.childElements())if("Parameters"===s.localName)this.parseChannelStripParameters(e,s)}parseChannelStripParameters(e,t){if(t.firstChild&&t.firstChild.value){const s=t.firstChild.value.split(" ");s.length>=12&&(e.playbackInfo.balance=Math.floor(16*Number.parseFloat(s[11])),e.playbackInfo.volume=Math.floor(16*Number.parseFloat(s[12])))}}parseMasterBarsNode(e){for(const t of e.childElements())if("MasterBar"===t.localName)this.parseMasterBar(t)}parseMasterBar(e){const t=new Se;0===this._masterBars.length&&this._hasAnacrusis&&(t.isAnacrusis=!0);for(const s of e.childElements())switch(s.localName){case"Time":const e=s.innerText.split("/");t.timeSignatureNumerator=Number.parseInt(e[0]),t.timeSignatureDenominator=Number.parseInt(e[1]);break;case"FreeTime":t.isFreeTime=!0;break;case"DoubleBar":t.isDoubleBar=!0,this._doubleBars.add(t);break;case"Section":t.section=new ft,t.section.marker=s.findChildElement("Letter").innerText,t.section.text=s.findChildElement("Text").innerText;break;case"Repeat":"true"===s.getAttribute("start").toLowerCase()&&(t.isRepeatStart=!0),"true"===s.getAttribute("end").toLowerCase()&&s.getAttribute("count")&&(t.repeatCount=Number.parseInt(s.getAttribute("count")));break;case"AlternateEndings":const i=s.innerText.split(" ");let a=0;for(let e=0;e<i.length;e++)a|=1<<-1+Number.parseInt(i[e]);t.alternateEndings=a;break;case"Bars":this._barsOfMasterBar.push(s.innerText.split(" "));break;case"TripletFeel":switch(s.innerText){case"NoTripletFeel":t.tripletFeel=P.NoTripletFeel;break;case"Triplet8th":t.tripletFeel=P.Triplet8th;break;case"Triplet16th":t.tripletFeel=P.Triplet16th;break;case"Dotted8th":t.tripletFeel=P.Dotted8th;break;case"Dotted16th":t.tripletFeel=P.Dotted16th;break;case"Scottish8th":t.tripletFeel=P.Scottish8th;break;case"Scottish16th":t.tripletFeel=P.Scottish16th}break;case"Key":t.keySignature=Number.parseInt(s.findChildElement("AccidentalCount").innerText);const r=s.findChildElement("Mode");if(r)switch(r.innerText.toLowerCase()){case"major":t.keySignatureType=v.Major;break;case"minor":t.keySignatureType=v.Minor}break;case"Fermatas":this.parseFermatas(t,s);break;case"XProperties":this.parseMasterBarXProperties(t,s);break;case"Directions":this.parseDirections(t,s)}this._masterBars.push(t)}parseDirections(e,t){for(const s of t.childElements())switch(s.localName){case"Target":switch(s.innerText){case"Coda":e.addDirection(C.TargetCoda);break;case"DoubleCoda":e.addDirection(C.TargetDoubleCoda);break;case"Segno":e.addDirection(C.TargetSegno);break;case"SegnoSegno":e.addDirection(C.TargetSegnoSegno);break;case"Fine":e.addDirection(C.TargetFine)}break;case"Jump":switch(s.innerText){case"DaCapo":e.addDirection(C.JumpDaCapo);break;case"DaCapoAlCoda":e.addDirection(C.JumpDaCapoAlCoda);break;case"DaCapoAlDoubleCoda":e.addDirection(C.JumpDaCapoAlDoubleCoda);break;case"DaCapoAlFine":e.addDirection(C.JumpDaCapoAlFine);break;case"DaSegno":e.addDirection(C.JumpDalSegno);break;case"DaSegnoAlCoda":e.addDirection(C.JumpDalSegnoAlCoda);break;case"DaSegnoAlDoubleCoda":e.addDirection(C.JumpDalSegnoAlDoubleCoda);break;case"DaSegnoAlFine":e.addDirection(C.JumpDalSegnoAlFine);break;case"DaSegnoSegno":e.addDirection(C.JumpDalSegnoSegno);break;case"DaSegnoSegnoAlCoda":e.addDirection(C.JumpDalSegnoSegnoAlCoda);break;case"DaSegnoSegnoAlDoubleCoda":e.addDirection(C.JumpDalSegnoSegnoAlDoubleCoda);break;case"DaSegnoSegnoAlFine":e.addDirection(C.JumpDalSegnoSegnoAlFine);break;case"DaCoda":e.addDirection(C.JumpDaCoda);break;case"DaDoubleCoda":e.addDirection(C.JumpDaDoubleCoda)}}}parseFermatas(e,t){for(const s of t.childElements())if("Fermata"===s.localName)this.parseFermata(e,s)}parseFermata(e,t){let s=0;const i=new Te;for(const e of t.childElements())switch(e.localName){case"Type":switch(e.innerText){case"Short":i.type=M.Short;break;case"Medium":i.type=M.Medium;break;case"Long":i.type=M.Long}break;case"Length":i.length=Number.parseFloat(e.innerText);break;case"Offset":const t=e.innerText.split("/");if(2===t.length){s=Number.parseInt(t[0])/Number.parseInt(t[1])*rs.QuarterTime|0}}e.addFermata(s,i)}parseBars(e){for(const t of e.childElements())if("Bar"===t.localName)this.parseBar(t)}parseBar(e){const t=new ue,s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Voices":this._voicesOfBar.set(s,i.innerText.split(" "));break;case"Clef":switch(i.innerText){case"Neutral":t.clef=n.Neutral;break;case"G2":t.clef=n.G2;break;case"F4":t.clef=n.F4;break;case"C4":t.clef=n.C4;break;case"C3":t.clef=n.C3}break;case"Ottavia":switch(i.innerText){case"8va":t.clefOttava=o._8va;break;case"15ma":t.clefOttava=o._15ma;break;case"8vb":t.clefOttava=o._8vb;break;case"15mb":t.clefOttava=o._15mb}break;case"SimileMark":switch(i.innerText){case"Simple":t.simileMark=h.Simple;break;case"FirstOfDouble":t.simileMark=h.FirstOfDouble;break;case"SecondOfDouble":t.simileMark=h.SecondOfDouble}break;case"XProperties":this.parseBarXProperties(i,t)}this._barsById.set(s,t)}parseVoices(e){for(const t of e.childElements())if("Voice"===t.localName)this.parseVoice(t)}parseVoice(e){const t=new Dt,s=e.getAttribute("id");for(const t of e.childElements())if("Beats"===t.localName)this._beatsOfVoice.set(s,t.innerText.split(" "));this._voiceById.set(s,t)}parseBeats(e){for(const t of e.childElements())if("Beat"===t.localName)this.parseBeat(t)}parseBeat(e){const t=new gs,s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Notes":this._notesOfBeat.set(s,i.innerText.split(" "));break;case"Rhythm":this._rhythmOfBeat.set(s,i.getAttribute("ref"));break;case"Fadding":switch(i.innerText){case"FadeIn":t.fade=L.FadeIn;break;case"FadeOut":t.fade=L.FadeOut;break;case"VolumeSwell":t.fade=L.VolumeSwell}break;case"Tremolo":switch(i.innerText){case"1/2":t.tremoloSpeed=D.Eighth;break;case"1/4":t.tremoloSpeed=D.Sixteenth;break;case"1/8":t.tremoloSpeed=D.ThirtySecond}break;case"Chord":t.chordId=i.innerText;break;case"Hairpin":switch(i.innerText){case"Crescendo":t.crescendo=F.Crescendo;break;case"Decrescendo":t.crescendo=F.Decrescendo}break;case"Arpeggio":"Up"===i.innerText?t.brushType=b.ArpeggioUp:t.brushType=b.ArpeggioDown;break;case"Properties":this.parseBeatProperties(i,t);break;case"XProperties":this.parseBeatXProperties(i,t);break;case"FreeText":t.text=i.innerText;break;case"TransposedPitchStemOrientation":switch(i.innerText){case"Upward":t.preferredBeamDirection=se.Up;break;case"Downward":t.preferredBeamDirection=se.Down}break;case"Dynamic":switch(i.innerText){case"PPP":t.dynamics=E.PPP;break;case"PP":t.dynamics=E.PP;break;case"P":t.dynamics=E.P;break;case"MP":t.dynamics=E.MP;break;case"MF":t.dynamics=E.MF;break;case"F":t.dynamics=E.F;break;case"FF":t.dynamics=E.FF;break;case"FFF":t.dynamics=E.FFF}break;case"GraceNotes":switch(i.innerText){case"OnBeat":t.graceType=R.OnBeat;break;case"BeforeBeat":t.graceType=R.BeforeBeat}break;case"Legato":"true"===i.getAttribute("origin")&&(t.isLegatoOrigin=!0);break;case"Whammy":const e=new ge(0,0);e.value=this.toBendValue(Number.parseFloat(i.getAttribute("originValue"))),e.offset=this.toBendOffset(Number.parseFloat(i.getAttribute("originOffset"))),t.addWhammyBarPoint(e);const a=new ge(0,0);a.value=this.toBendValue(Number.parseFloat(i.getAttribute("middleValue"))),a.offset=this.toBendOffset(Number.parseFloat(i.getAttribute("middleOffset1"))),t.addWhammyBarPoint(a);const r=new ge(0,0);r.value=this.toBendValue(Number.parseFloat(i.getAttribute("middleValue"))),r.offset=this.toBendOffset(Number.parseFloat(i.getAttribute("middleOffset2"))),t.addWhammyBarPoint(r);const n=new ge(0,0);n.value=this.toBendValue(Number.parseFloat(i.getAttribute("destinationValue"))),n.offset=this.toBendOffset(Number.parseFloat(i.getAttribute("destinationOffset"))),t.addWhammyBarPoint(n);break;case"Ottavia":switch(i.innerText){case"8va":t.ottava=o._8va;break;case"8vb":t.ottava=o._8vb;break;case"15ma":t.ottava=o._15ma;break;case"15mb":t.ottava=o._15mb}break;case"Lyrics":t.lyrics=this.parseBeatLyrics(i),this._skipApplyLyrics=!0;break;case"Slashed":t.slashed=!0;break;case"DeadSlapped":t.deadSlapped=!0;break;case"Golpe":switch(i.innerText){case"Finger":t.golpe=O.Finger;break;case"Thumb":t.golpe=O.Thumb}break;case"Wah":switch(i.innerText){case"Open":t.wahPedal=ie.Open;break;case"Closed":t.wahPedal=ie.Closed}break;case"UserTransposedPitchStemOrientation":switch(i.innerText){case"Downward":t.preferredBeamDirection=se.Down;break;case"Upward":t.preferredBeamDirection=se.Up}break;case"Timer":t.showTimer=!0,i.innerText.length>0&&(t.timer=Number.parseInt(i.innerText))}this._beatById.set(s,t)}parseBeatLyrics(e){const t=[];for(const s of e.childElements())if("Line"===s.localName)t.push(s.innerText);return t}parseBeatXProperties(e,t){for(const s of e.childElements())if("XProperty"===s.localName){let e=0;switch(s.getAttribute("id")){case"1124204546":switch(e=Number.parseInt(s.findChildElement("Int").innerText),e){case 1:t.beamingMode=cs.ForceMergeWithNext;break;case 2:t.beamingMode=cs.ForceSplitToNext}break;case"1124204552":if(e=Number.parseInt(s.findChildElement("Int").innerText),1===e)t.beamingMode!==cs.ForceSplitToNext&&(t.beamingMode=cs.ForceSplitOnSecondaryToNext);break;case"1124204545":e=Number.parseInt(s.findChildElement("Int").innerText),t.invertBeamDirection=1===e;break;case"687935489":e=Number.parseInt(s.findChildElement("Int").innerText),t.brushDuration=e}}}parseBarXProperties(e,t){for(const s of e.childElements())if("XProperty"===s.localName){if("1124139520"===s.getAttribute("id")){const e=s.findChildElement("Double")??s.findChildElement("Float");t.displayScale=Number.parseFloat(e.innerText)}}}parseMasterBarXProperties(e,t){for(const s of t.childElements())if("XProperty"===s.localName){if("1124073984"===s.getAttribute("id"))e.displayScale=Number.parseFloat(s.findChildElement("Double").innerText)}}parseBeatProperties(e,t){let s=!1,i=null,a=null,r=null,n=null,o=null;for(const h of e.childElements())if("Property"===h.localName){switch(h.getAttribute("name")){case"Brush":"Up"===h.findChildElement("Direction").innerText?t.brushType=b.BrushUp:t.brushType=b.BrushDown;break;case"PickStroke":"Up"===h.findChildElement("Direction").innerText?t.pickStroke=Q.Up:t.pickStroke=Q.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=j.Wide;break;case"Slight":t.vibrato=j.Slight}break;case"WhammyBar":s=!0;break;case"WhammyBarExtend":break;case"WhammyBarOriginValue":i||(i=new ge(0,0)),i.value=this.toBendValue(Number.parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarOriginOffset":i||(i=new ge(0,0)),i.offset=this.toBendOffset(Number.parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleValue":a=this.toBendValue(Number.parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleOffset1":r=this.toBendOffset(Number.parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarMiddleOffset2":n=this.toBendOffset(Number.parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationValue":o||(o=new ge(ge.MaxPosition,0)),o.value=this.toBendValue(Number.parseFloat(h.findChildElement("Float").innerText));break;case"WhammyBarDestinationOffset":o||(o=new ge(0,0)),o.offset=this.toBendOffset(Number.parseFloat(h.findChildElement("Float").innerText));break;case"BarreFret":t.barreFret=Number.parseInt(h.findChildElement("Fret").innerText);break;case"BarreString":switch(h.findChildElement("String").innerText){case"0":t.barreShape=m.Full;break;case"1":t.barreShape=m.Half}break;case"Rasgueado":switch(h.findChildElement("Rasgueado").innerText){case"ii_1":t.rasgueado=ae.Ii;break;case"mi_1":t.rasgueado=ae.Mi;break;case"mii_1":t.rasgueado=ae.MiiTriplet;break;case"mii_2":t.rasgueado=ae.MiiAnapaest;break;case"pmp_1":t.rasgueado=ae.PmpTriplet;break;case"pmp_2":t.rasgueado=ae.PmpAnapaest;break;case"pei_1":t.rasgueado=ae.PeiTriplet;break;case"pei_2":t.rasgueado=ae.PeiAnapaest;break;case"pai_1":t.rasgueado=ae.PaiTriplet;break;case"pai_2":t.rasgueado=ae.PaiAnapaest;break;case"ami_1":t.rasgueado=ae.AmiTriplet;break;case"ami_2":t.rasgueado=ae.AmiAnapaest;break;case"ppp_1":t.rasgueado=ae.Ppp;break;case"amii_1":t.rasgueado=ae.Amii;break;case"amip_1":t.rasgueado=ae.Amip;break;case"eami_1":t.rasgueado=ae.Eami;break;case"eamii_1":t.rasgueado=ae.Eamii;break;case"peami_1":t.rasgueado=ae.Peami}}}s&&(i||(i=new ge(0,0)),o||(o=new ge(ge.MaxPosition,0)),t.addWhammyBarPoint(i),r&&a&&t.addWhammyBarPoint(new ge(r,a)),n&&a&&t.addWhammyBarPoint(new ge(n,a)),r||n||!a||t.addWhammyBarPoint(new ge(ge.MaxPosition/2|0,a)),t.addWhammyBarPoint(o))}parseNotes(e){for(const t of e.childElements())if("Note"===t.localName)this.parseNote(t)}parseNote(e){const t=new Nt,s=e.getAttribute("id");for(const i of e.childElements())switch(i.localName){case"Properties":this.parseNoteProperties(i,t,s);break;case"AntiAccent":"normal"===i.innerText.toLowerCase()&&(t.isGhost=!0);break;case"LetRing":t.isLetRing=!0;break;case"Trill":t.trillValue=Number.parseInt(i.innerText),t.trillSpeed=D.Sixteenth;break;case"Accent":const e=Number.parseInt(i.innerText);1&e&&(t.isStaccato=!0),4&e&&(t.accentuated=u.Heavy),8&e&&(t.accentuated=u.Normal),16&e&&(t.accentuated=u.Tenuto);break;case"Tie":"true"===i.getAttribute("destination").toLowerCase()&&(t.isTieDestination=!0);break;case"Vibrato":switch(i.innerText){case"Slight":t.vibrato=j.Slight;break;case"Wide":t.vibrato=j.Wide}break;case"LeftFingering":switch(i.innerText){case"P":t.leftHandFinger=_.Thumb;break;case"I":t.leftHandFinger=_.IndexFinger;break;case"M":t.leftHandFinger=_.MiddleFinger;break;case"A":t.leftHandFinger=_.AnnularFinger;break;case"C":t.leftHandFinger=_.LittleFinger}break;case"RightFingering":switch(i.innerText){case"P":t.rightHandFinger=_.Thumb;break;case"I":t.rightHandFinger=_.IndexFinger;break;case"M":t.rightHandFinger=_.MiddleFinger;break;case"A":t.rightHandFinger=_.AnnularFinger;break;case"C":t.rightHandFinger=_.LittleFinger}break;case"InstrumentArticulation":t.percussionArticulation=Number.parseInt(i.innerText);break;case"Ornament":switch(i.innerText){case"Turn":t.ornament=Z.Turn;break;case"InvertedTurn":t.ornament=Z.InvertedTurn;break;case"UpperMordent":t.ornament=Z.UpperMordent;break;case"LowerMordent":t.ornament=Z.LowerMordent}}this._noteById.set(s,t)}parseNoteProperties(e,t,s){let i=!1,a=null,r=null,n=null,o=null,h=null,l=-1,c=-1;for(const d of e.childElements())if("Property"===d.localName){switch(d.getAttribute("name")){case"ShowStringNumber":d.findChildElement("Enable")&&(t.showStringNumber=!0);break;case"String":t.string=Number.parseInt(d.findChildElement("String").innerText)+1;break;case"Fret":t.fret=Number.parseInt(d.findChildElement("Fret").innerText);break;case"Element":l=Number.parseInt(d.findChildElement("Element").innerText);break;case"Variation":c=Number.parseInt(d.findChildElement("Variation").innerText);break;case"Tapped":this._tappedNotes.set(s,!0);break;case"HarmonicType":const e=d.findChildElement("HType");if(e)switch(e.innerText){case"NoHarmonic":t.harmonicType=H.None;break;case"Natural":t.harmonicType=H.Natural;break;case"Artificial":t.harmonicType=H.Artificial;break;case"Pinch":t.harmonicType=H.Pinch;break;case"Tap":t.harmonicType=H.Tap;break;case"Semi":t.harmonicType=H.Semi;break;case"Feedback":t.harmonicType=H.Feedback}break;case"HarmonicFret":const u=d.findChildElement("HFret");u&&(t.harmonicValue=Number.parseFloat(u.innerText));break;case"Muted":d.findChildElement("Enable")&&(t.isDead=!0);break;case"PalmMuted":d.findChildElement("Enable")&&(t.isPalmMute=!0);break;case"Octave":t.octave=Number.parseInt(d.findChildElement("Number").innerText),-1===t.tone&&(t.tone=0);break;case"Tone":t.tone=Number.parseInt(d.findChildElement("Step").innerText);break;case"ConcertPitch":this.parseConcertPitch(d,t);break;case"Bended":i=!0;break;case"BendOriginValue":a||(a=new ge(0,0)),a.value=this.toBendValue(Number.parseFloat(d.findChildElement("Float").innerText));break;case"BendOriginOffset":a||(a=new ge(0,0)),a.offset=this.toBendOffset(Number.parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleValue":r=this.toBendValue(Number.parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleOffset1":n=this.toBendOffset(Number.parseFloat(d.findChildElement("Float").innerText));break;case"BendMiddleOffset2":o=this.toBendOffset(Number.parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationValue":h||(h=new ge(ge.MaxPosition,0)),h.value=this.toBendValue(Number.parseFloat(d.findChildElement("Float").innerText));break;case"BendDestinationOffset":h||(h=new ge(0,0)),h.offset=this.toBendOffset(Number.parseFloat(d.findChildElement("Float").innerText));break;case"HopoOrigin":d.findChildElement("Enable")&&(t.isHammerPullOrigin=!0);break;case"HopoDestination":break;case"LeftHandTapped":t.isLeftHandTapped=!0;break;case"Slide":const p=Number.parseInt(d.findChildElement("Flags").innerText);1&p?t.slideOutType=K.Shift:2&p?t.slideOutType=K.Legato:4&p?t.slideOutType=K.OutDown:8&p&&(t.slideOutType=K.OutUp),16&p?t.slideInType=q.IntoFromBelow:32&p&&(t.slideInType=q.IntoFromAbove),64&p?t.slideOutType=K.PickSlideDown:128&p&&(t.slideOutType=K.PickSlideUp)}}i&&(a||(a=new ge(0,0)),h||(h=new ge(ge.MaxPosition,0)),t.addBendPoint(a),n&&r&&t.addBendPoint(new ge(n,r)),o&&r&&t.addBendPoint(new ge(o,r)),n||o||!r||t.addBendPoint(new ge(ge.MaxPosition/2|0,r)),t.addBendPoint(h)),-1!==l&&-1!==c&&(t.percussionArticulation=Bt.articulationFromElementVariation(l,c))}parseConcertPitch(e,t){const s=e.findChildElement("Pitch");if(s)for(const e of s.childElements())if("Accidental"===e.localName)switch(e.innerText){case"x":t.accidentalMode=N.ForceDoubleSharp;break;case"#":t.accidentalMode=N.ForceSharp;break;case"b":t.accidentalMode=N.ForceFlat;break;case"bb":t.accidentalMode=N.ForceDoubleFlat}}toBendValue(e){return e*$s.BendPointValueFactor|0}toBendOffset(e){return e*$s.BendPointPositionFactor}parseRhythms(e){for(const t of e.childElements())if("Rhythm"===t.localName)this.parseRhythm(t)}parseRhythm(e){const t=new Js,s=e.getAttribute("id");t.id=s;for(const s of e.childElements())switch(s.localName){case"NoteValue":switch(s.innerText){case"Long":t.value=D.QuadrupleWhole;break;case"DoubleWhole":t.value=D.DoubleWhole;break;case"Whole":t.value=D.Whole;break;case"Half":t.value=D.Half;break;case"Quarter":t.value=D.Quarter;break;case"Eighth":t.value=D.Eighth;break;case"16th":t.value=D.Sixteenth;break;case"32nd":t.value=D.ThirtySecond;break;case"64th":t.value=D.SixtyFourth;break;case"128th":t.value=D.OneHundredTwentyEighth;break;case"256th":t.value=D.TwoHundredFiftySixth}break;case"PrimaryTuplet":t.tupletNumerator=Number.parseInt(s.getAttribute("num")),t.tupletDenominator=Number.parseInt(s.getAttribute("den"));break;case"AugmentationDot":t.dots=Number.parseInt(s.getAttribute("count"))}this._rhythmById.set(s,t)}buildModel(){for(let e=0,t=this._masterBars.length;e<t;e++){const t=this._masterBars[e];this.score.addMasterBar(t)}const e=this._masterBars[this._masterBars.length-1];this._doubleBars.has(e)&&(this._doubleBars.delete(e),e.isDoubleBar=!1);for(const e of this._tracksMapping){if(!e)continue;const t=this._tracksById.get(e);this.score.addTrack(t)}for(const e of this._barsOfMasterBar){let t=0;for(let s=0,i=0;s<e.length&&i<this.score.tracks.length;s++){const a=e[s];if(a!==$s.InvalidId){const e=this._barsById.get(a),s=this.score.tracks[i],r=s.staves[t];if(r.addBar(e),this._doubleBars.has(e.masterBar)&&(e.barLineRight=d.LightLight),this._voicesOfBar.has(a))for(const t of this._voicesOfBar.get(a))if(t!==$s.InvalidId){const s=this._voiceById.get(t);if(e.addVoice(s),this._beatsOfVoice.has(t))for(const e of this._beatsOfVoice.get(t))if(e!==$s.InvalidId){const t=ls.clone(this._beatById.get(e));s.addBeat(t);const i=this._rhythmOfBeat.get(e),a=this._rhythmById.get(i);if(t.duration=a.value,t.dots=a.dots,t.tupletNumerator=a.tupletNumerator,t.tupletDenominator=a.tupletDenominator,this._notesOfBeat.has(e))for(const s of this._notesOfBeat.get(e))if(s!==$s.InvalidId){const e=os.clone(this._noteById.get(s));r.isPercussion?(e.fret=-1,e.string=-1):e.percussionArticulation=-1,t.addNote(e),this._tappedNotes.has(s)&&(t.tap=!0)}}}else{const t=new Dt;e.addVoice(t);const s=new gs;s.isEmpty=!0,s.duration=D.Quarter,t.addBeat(s)}t===s.staves.length-1?(i++,t=0):t++}else i++}}for(const e of this._tracksMapping){if(!e)continue;const t=this._tracksById.get(e);let s=!1;for(const e of t.staves)if(e.isPercussion){s=!0;break}if(s||(t.percussionArticulations=[]),this._automationsPerTrackIdAndBarIndex.has(e)){const s=this._automationsPerTrackIdAndBarIndex.get(e);for(const[e,i]of s)if(t.staves.length>0&&e<t.staves[0].bars.length){const s=t.staves[0].bars[e];if(s.voices.length>0&&s.voices[0].beats.length>0){const e=s.voices[0].beats[0];for(const t of i)e.automations.push(t)}}}if(this._sustainPedalsPerTrackIdAndBarIndex.has(e)){const s=this._sustainPedalsPerTrackIdAndBarIndex.get(e);for(const[e,i]of s)if(t.staves.length>0&&e<t.staves[0].bars.length){t.staves[0].bars[e].sustainPedals=i}}}for(const[e,t]of this._masterTrackAutomations){const s=this.score.masterBars[e];for(let i=0,a=t.length;i<a;i++){const a=t[i];a.type===g.Tempo&&(0===e&&(this.score.tempo=0|a.value,a.text&&(this.score.tempoLabel=a.text)),s.tempoAutomations.push(a))}}}}$s.InvalidId="-1",$s.BendPointPositionFactor=ge.MaxPosition/100,$s.BendPointValueFactor=.04;class qs{constructor(){this.isMultiRest=!1,this.trackViewGroups=[]}}class Ks{constructor(){this.showNumbered=!1,this.showSlash=!1,this.showStandardNotation=!1,this.showTablature=!1}}class js{apply(e){if(this.scoreViews.length>0){let t=0;e.stylesheet.multiTrackMultiBarRest=this.scoreViews[0].isMultiRest;for(const s of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){const i=e.tracks[t];for(const e of i.staves)e.showTablature=s.showTablature,e.showStandardNotation=s.showStandardNotation,e.showSlash=s.showSlash,e.showNumbered=s.showNumbered}t++}for(let s=1;s<this.scoreViews.length;s++)this.scoreViews[s].isMultiRest&&(e.stylesheet.perTrackMultiBarRest||(e.stylesheet.perTrackMultiBarRest=new Set),t=s-1,e.stylesheet.perTrackMultiBarRest.add(t))}}constructor(e){this.scoreViews=[];const t=Me.fromBuffer(e),s=Le.readInt32BE(t);for(let e=0;e<s;e++){const e=new qs;this.scoreViews.push(e),e.isMultiRest=Rs.gpReadBool(t);const s=Le.readInt32BE(t);for(let i=0;i<s;i++){let s=t.readByte();0===s&&(s=1);const i=new Ks;i.showStandardNotation=!!(1&s),i.showTablature=!!(2&s),i.showSlash=!!(4&s),i.showNumbered=!!(8&s),e.trackViewGroups.push(i)}}}static writeForScore(e){const t=Me.withCapacity(128),s=[new qs];s[0].isMultiRest=e.stylesheet.multiTrackMultiBarRest;for(const t of e.tracks){const i=new Ks;i.showStandardNotation=t.staves[0].showStandardNotation,i.showTablature=t.staves[0].showTablature,i.showSlash=t.staves[0].showSlash,i.showNumbered=t.staves[0].showNumbered,s[0].trackViewGroups.push(i);const a=new qs;a.isMultiRest=!0===e.stylesheet.perTrackMultiBarRest?.has(t.index),a.trackViewGroups.push(i),s.push(a)}Le.writeInt32BE(t,s.length);for(const e of s){t.writeByte(e.isMultiRest?1:0),Le.writeInt32BE(t,e.trackViewGroups.length);for(const s of e.trackViewGroups){let e=0;s.showStandardNotation&&(e|=1),s.showTablature&&(e|=2),s.showSlash&&(e|=4),s.showNumbered&&(e|=8),t.writeByte(e)}}return Le.writeInt32BE(t,1),t.toArray()}}let Qs=class{};class Zs extends Qs{constructor(e){super(),this.n=e}}class ei extends Qs{constructor(e,t){super(),this.left=e,this.right=t}}class ti extends Qs{constructor(e,t){super(),this.n=e,this.table=t}}class si{static make(e,t,s,i){const a=[],r=[];if(i>32)throw new ye("Invalid huffman");for(let e=0;e<i;e++)a.push(0),r.push(0);for(let r=0;r<s;r++){const s=e[r+t];if(s>=i)throw new ye("Invalid huffman");a[s]++}let n=0;for(let e=1;e<i-1;e++)n=n+a[e]<<1,r[e]=n;const o=new Map;for(let i=0;i<s;i++){const s=e[i+t];if(0!==s){const e=r[s-1];r[s-1]=e+1,o.set(e<<5|s,i)}}return si.treeCompress(new ei(si.treeMake(o,i,0,1),si.treeMake(o,i,1,1)))}static treeMake(e,t,s,i){if(i>t)throw new ye("Invalid huffman");const a=s<<5|i;return e.has(a)?new Zs(e.get(a)):(s<<=1,i+=1,new ei(si.treeMake(e,t,s,i),si.treeMake(e,t,1|s,i)))}static treeCompress(e){const t=si.treeDepth(e);if(0===t)return e;if(1===t){if(e instanceof ei)return new ei(si.treeCompress(e.left),si.treeCompress(e.right));throw new ye("assert")}const s=1<<t,i=[];for(let e=0;e<s;e++)i.push(new Zs(-1));return si.treeWalk(i,0,0,t,e),new ti(t,i)}static treeWalk(e,t,s,i,a){a instanceof ei&&i>0?(si.treeWalk(e,t,s+1,i-1,a.left),si.treeWalk(e,t|1<<s,s+1,i-1,a.right)):e[t]=si.treeCompress(a)}static treeDepth(e){if(e instanceof Zs)return 0;if(e instanceof ti)throw new ye("assert");if(e instanceof ei){const t=si.treeDepth(e.left),s=si.treeDepth(e.right);return 1+(t<s?t:s)}return 0}}var ii,ai;!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"}(ii||(ii={}));class ri{constructor(){this.buffer=new Uint8Array(ri.BufferSize),this.pos=0}slide(){const e=new Uint8Array(ri.BufferSize);this.pos-=ri.Size,e.set(this.buffer.subarray(ri.Size,ri.Size+this.pos),0),this.buffer=e}addBytes(e,t,s){this.pos+s>ri.BufferSize&&this.slide(),this.buffer.set(e.subarray(t,t+s),this.pos),this.pos+=s}addByte(e){this.pos===ri.BufferSize&&this.slide(),this.buffer[this.pos]=e,this.pos++}getLastChar(){return this.buffer[this.pos-1]}available(){return this.pos}}ri.Size=32768,ri.BufferSize=65536;class ni{static buildFixedHuffman(){const e=[];for(let t=0;t<288;t++)e.push(t<=143?8:t<=255?9:t<=279?7:8);return si.make(e,0,288,10)}constructor(e){this._nbits=0,this._bits=0,this._state=ii.Block,this._isFinal=!1,this._huffman=ni._fixedHuffman,this._huffdist=null,this._len=0,this._dist=0,this._needed=0,this._output=null,this._outpos=0,this._lengths=[],this._window=new ri,this._input=e;for(let e=0;e<19;e++)this._lengths.push(-1)}readBytes(e,t,s){if(this._needed=s,this._outpos=t,this._output=e,s>0)for(;this.inflateLoop(););return s-this._needed}inflateLoop(){switch(this._state){case ii.Head:const e=this._input.readByte();if(8!==(15&e))throw new ye("Invalid data");const t=this._input.readByte(),s=!!(32&t);if(((e<<8)+t)%31!=0)throw new ye("Invalid data");if(s)throw new ye("Unsupported dictionary");return this._state=ii.Block,!0;case ii.Crc:return this._state=ii.Done,!0;case ii.Done:return!1;case ii.Block:switch(this._isFinal=this.getBit(),this.getBits(2)){case 0:this._len=Le.readUInt16LE(this._input);if(Le.readUInt16LE(this._input)!==65535-this._len)throw new ye("Invalid data");this._state=ii.Flat;const e=this.inflateLoop();return this.resetBits(),e;case 1:return this._huffman=ni._fixedHuffman,this._huffdist=null,this._state=ii.CData,!0;case 2:const t=this.getBits(5)+257,s=this.getBits(5)+1,i=this.getBits(4)+4;for(let e=0;e<i;e++)this._lengths[ni.CodeLengthsPos[e]]=this.getBits(3);for(let e=i;e<19;e++)this._lengths[ni.CodeLengthsPos[e]]=0;this._huffman=si.make(this._lengths,0,19,8);const a=[];for(let e=0;e<t+s;e++)a.push(0);return this.inflateLengths(a,t+s),this._huffdist=si.make(a,t,s,16),this._huffman=si.make(a,0,t,16),this._state=ii.CData,!0;default:throw new ye("Invalid data")}case ii.Flat:{const e=this._len<this._needed?this._len:this._needed,t=Le.readByteArray(this._input,e);return this._len-=e,this.addBytes(t,0,e),0===this._len&&(this._state=this._isFinal?ii.Crc:ii.Block),this._needed>0}case ii.DistOne:{const e=this._len<this._needed?this._len:this._needed;return this.addDistOne(e),this._len-=e,0===this._len&&(this._state=ii.CData),this._needed>0}case ii.Dist:for(;this._len>0&&this._needed>0;){const 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=ii.CData),this._needed>0;case ii.CData:let i=this.applyHuffman(this._huffman);if(i<256)return this.addByte(i),this._needed>0;if(256===i)return this._state=this._isFinal?ii.Crc:ii.Block,!0;i=i-257&255;let a=ni.LenExtraBitsTbl[i];if(-1===a)throw new ye("Invalid data");this._len=ni.LenBaseValTbl[i]+this.getBits(a);const r=this._huffdist,n=r?this.applyHuffman(r):this.getRevBits(5);if(a=ni.DistExtraBitsTbl[n],-1===a)throw new ye("Invalid data");if(this._dist=ni.DistBaseValTbl[n]+this.getBits(a),this._dist>this._window.available())throw new ye("Invalid data");return this._state=1===this._dist?ii.DistOne:ii.Dist,!0}return!1}addDistOne(e){const t=this._window.getLastChar();for(let s=0;s<e;s++)this.addByte(t)}addByte(e){this._window.addByte(e),this._output[this._outpos]=e,this._needed--,this._outpos++}addDist(e,t){this.addBytes(this._window.buffer,this._window.pos-e,t)}getBit(){0===this._nbits&&(this._nbits=8,this._bits=this._input.readByte());const e=!(1&~this._bits);return this._nbits--,this._bits=this._bits>>1,e}getBits(e){for(;this._nbits<e;)this._bits=this._bits|this._input.readByte()<<this._nbits,this._nbits+=8;const t=this._bits&(1<<e)-1;return this._nbits-=e,this._bits=this._bits>>e,t}getRevBits(e){return 0===e?0:this.getBit()?1<<e-1|this.getRevBits(e-1):this.getRevBits(e-1)}resetBits(){this._bits=0,this._nbits=0}addBytes(e,t,s){this._window.addBytes(e,t,s),this._output.set(e.subarray(t,t+s),this._outpos),this._needed-=s,this._outpos+=s}inflateLengths(e,t){let s=0,i=0;for(;s<t;){const a=this.applyHuffman(this._huffman);switch(a){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:case 15:i=a,e[s]=a,s++;break;case 16:const r=s+3+this.getBits(2);if(r>t)throw new ye("Invalid data");for(;s<r;)e[s]=i,s++;break;case 17:if(s+=3+this.getBits(3),s>t)throw new ye("Invalid data");break;case 18:if(s+=11+this.getBits(7),s>t)throw new ye("Invalid data");break;default:throw new ye("Invalid data")}}}applyHuffman(e){if(e instanceof Zs)return e.n;if(e instanceof ei)return this.applyHuffman(this.getBit()?e.right:e.left);if(e instanceof ti)return this.applyHuffman(e.table[this.getBits(e.n)]);throw new ye("Invalid data")}}ni.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],ni.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],ni.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],ni.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],ni.CodeLengthsPos=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],ni._fixedHuffman=ni.buildFixedHuffman();class oi{constructor(e,t){this.fullName=e;const s=e.lastIndexOf("/");this.fileName=-1===s||s===e.length-1?this.fullName:e.substr(s+1),this.data=t}}oi.OptionalDataDescriptorSignature=134695760,oi.CompressionMethodDeflate=8,oi.LocalFileHeaderSignature=67324752,oi.CentralFileHeaderSignature=33639248,oi.EndOfCentralDirSignature=101010256;class hi{constructor(e){this._readable=e}read(){const e=[];for(;;){const t=this.readEntry();if(!t)break;e.push(t)}return e}readEntry(){const e=this._readable;if(Le.readInt32LE(e)!==oi.LocalFileHeaderSignature)return null;Le.readUInt16LE(e);const t=Le.readUInt16LE(e),s=Le.readUInt16LE(e),i=0!==s;if(i&&s!==oi.CompressionMethodDeflate)return null;Le.readInt16LE(this._readable),Le.readInt16LE(this._readable),Le.readInt32LE(e),Le.readInt32LE(e);const a=Le.readInt32LE(e),r=Le.readInt16LE(e),n=Le.readInt16LE(e),o=Le.toString(Le.readByteArray(e,r),"utf-8");let h;if(e.skip(n),i){const e=Me.empty(),t=new ni(this._readable),s=new Uint8Array(65536);for(;;){const i=t.readBytes(s,0,s.length);if(e.write(s,0,i),i<s.length)break}h=e.toArray()}else h=Le.readByteArray(this._readable,a);if(8&t){Le.readInt32LE(this._readable)===oi.OptionalDataDescriptorSignature&&Le.readInt32LE(this._readable),Le.readInt32LE(this._readable),Le.readInt32LE(this._readable)}return new oi(o,h)}}class li{constructor(){this.trackViewGroups=[]}}class ci{constructor(){this.isVisible=!1}}!function(e){e[e.PageVertical=0]="PageVertical",e[e.PageGrid=1]="PageGrid",e[e.PageParchment=2]="PageParchment",e[e.ScreenVertical=3]="ScreenVertical",e[e.ScreenHorizontal=4]="ScreenHorizontal",e[e.PageHorizontal=5]="PageHorizontal"}(ai||(ai={}));class di{constructor(e,t){this.zoomLevel=4,this.view=ai.PageVertical,this.muiltiVoiceCursor=!1,this.scoreViews=[];const s=Me.fromBuffer(t);this.zoomLevel=Le.readInt32BE(s),this.view=s.readByte(),this.muiltiVoiceCursor=0!==s.readByte();const i=e.scoreViews.length;for(let t=0;t<i;t++){const i=new li;this.scoreViews.push(i);const a=e.scoreViews[t];for(let e=0;e<a.trackViewGroups.length;e++){const e=new ci;e.isVisible=0!==s.readByte(),i.trackViewGroups.push(e)}}}apply(e){if(this.scoreViews.length>0){let t=0;for(const s of this.scoreViews[0].trackViewGroups){if(t<e.tracks.length){e.tracks[t].isVisibleOnMultiTrack=s.isVisible}t++}}}static writeForScore(e){const t=Me.withCapacity(128);Le.writeInt32BE(t,4),t.writeByte(0);const s=e.tracks.length>0&&e.tracks[0].staves[0].bars[0].isMultiVoice;t.writeByte(s?255:0);for(const s of e.tracks)t.writeByte(s.isVisibleOnMultiTrack?255:0);for(const s of e.tracks)t.writeByte(255);return t.toArray()}}class ui extends Ds{get name(){return"Guitar Pro 7-8"}readScore(){wt.debug(this.name,"Loading ZIP entries");const e=new hi(this.data);let t;try{t=e.read()}catch(e){throw new Es("No Zip archive",e)}wt.debug(this.name,"Zip entries loaded");let s=null,i=null,a=null,r=null;for(const e of t)switch(e.fileName){case"score.gpif":s=Le.toString(e.data,this.settings.importer.encoding);break;case"BinaryStylesheet":i=e.data;break;case"PartConfiguration":a=e.data;break;case"LayoutConfiguration":r=e.data}if(!s)throw new Es("No score.gpif found in zip archive");wt.debug(this.name,"Start Parsing score.gpif");const n=new $s;n.parseXml(s,this.settings),wt.debug(this.name,"score.gpif parsed");const o=n.score;if(i){wt.debug(this.name,"Start Parsing BinaryStylesheet");new Ws(i).apply(o),wt.debug(this.name,"BinaryStylesheet parsed")}let h=null;if(a&&(wt.debug(this.name,"Start Parsing Part Configuration"),h=new js(a),h.apply(o),wt.debug(this.name,"Part Configuration parsed")),r&&null!=h){wt.debug(this.name,"Start Parsing Layout Configuration");new di(h,r).apply(o),wt.debug(this.name,"Layout Configuration parsed")}return o}}class pi extends fe{constructor(){super(S.Format,"Unexpected end of data within reader"),Object.setPrototypeOf(this,pi.prototype)}}class gi{constructor(e){this._currentByte=0,this._position=gi.ByteSize,this._source=e}readByte(){return this.readBits(8)}readBytes(e){const t=new Uint8Array(e);for(let s=0;s<e;s++)t[s]=255&this.readByte();return t}readBits(e){let t=0,s=e-1;for(;s>=0;)t|=this.readBit()<<s,s--;return t}readBitsReversed(e){let t=0;for(let s=0;s<e;s++)t|=this.readBit()<<s;return t}readBit(){if(this._position>=8){if(this._currentByte=this._source.readByte(),-1===this._currentByte)throw new pi;this._position=0}const e=this._currentByte>>gi.ByteSize-this._position-1&1;return this._position++,e}readAll(){const e=Me.empty();try{for(;;)e.writeByte(255&this.readByte())}catch(e){if(!(e instanceof pi))throw e}return e.toArray()}}gi.ByteSize=8;class mi{constructor(){this.fileName="",this.fileSize=0,this.data=null}}class fi{constructor(){this.files=[],this.files=[],this.fileFilter=e=>!0}load(e){const t=new gi(e);this.readBlock(t)}readHeader(e){return this.getString(e.readBytes(4),0,4)}decompress(e,t=!1){const s=Me.empty();let i;const a=this.getInteger(e.readBytes(4),0);try{for(;s.length<a;){if(1===e.readBits(1)){const 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{const t=e.readBitsReversed(2);for(let i=0;i<t;i++)s.writeByte(e.readByte())}}}catch(e){if(!(e instanceof pi))throw e}i=s.getBuffer();const 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){const t=this.readHeader(e);if("BCFZ"===t)this.readUncompressedBlock(this.decompress(e,!0));else{if("BCFS"!==t)throw new Es("Unsupported format");this.readUncompressedBlock(e.readAll())}}readUncompressedBlock(e){const t=4096;let s=t;for(;s+3<e.length;){if(2===this.getInteger(e,s)){const i=new mi;i.fileName=this.getString(e,s+4,127),i.fileSize=this.getInteger(e,s+140);const a=!this.fileFilter||this.fileFilter(i.fileName);a&&this.files.push(i);const r=s+148;let n=0,o=0;const h=a?Me.withCapacity(i.fileSize):null;for(;n=this.getInteger(e,r+4*o++),0!==n;)s=n*t,a&&h.write(e,s,t);if(a){i.data=new Uint8Array(Math.min(i.fileSize,h.length));const e=h.toArray();i.data.set(e.subarray(0,0+i.data.length),0)}}s+=t}}getString(e,t,s){let i="";for(let a=0;a<s;a++){const s=255&e[t+a];if(0===s)break;i+=String.fromCharCode(s)}return i}getInteger(e,t){return e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}}fi.HeaderBcFs="BCFS",fi.HeaderBcFz="BCFZ";class yi extends Ds{get name(){return"Guitar Pro 6"}readScore(){wt.debug(this.name,"Loading GPX filesystem");const e=new fi;e.fileFilter=e=>e.endsWith("score.gpif")||e.endsWith("BinaryStylesheet")||e.endsWith("PartConfiguration")||e.endsWith("LayoutConfiguration"),e.load(this.data),wt.debug(this.name,"GPX filesystem loaded");let t=null,s=null,i=null,a=null;for(const r of e.files)switch(r.fileName){case"score.gpif":t=Le.toString(r.data,this.settings.importer.encoding);break;case"BinaryStylesheet":s=r.data;break;case"PartConfiguration":i=r.data;break;case"LayoutConfiguration":a=r.data}if(!t)throw new Es("No score.gpif found in GPX");wt.debug(this.name,"Start Parsing score.gpif");const r=new $s;r.parseXml(t,this.settings),wt.debug(this.name,"score.gpif parsed");const n=r.score;if(s){wt.debug(this.name,"Start Parsing BinaryStylesheet");new Ws(s).apply(n),wt.debug(this.name,"BinaryStylesheet parsed")}let o=null;if(i&&(wt.debug(this.name,"Start Parsing Part Configuration"),o=new js(i),o.apply(n),wt.debug(this.name,"Part Configuration parsed")),a&&null!=o){wt.debug(this.name,"Start Parsing Layout Configuration");new di(o,a).apply(n),wt.debug(this.name,"Layout Configuration parsed")}return n}}class bi{constructor(){this.id=Be.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 Si{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 _i{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 wi{constructor(){this.beats=[]}addBeat(e){e.barBounds=this,this.beats.push(e),this.masterBarBounds.addBeat(e)}findBeatAtPos(e){let t=null;for(const s of this.beats)if(!t||s.realBounds.x<e)t=s;else if(s.realBounds.x>e)break;return t}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.beats.sort(((e,t)=>e.realBounds.x-t.realBounds.x));for(const t of this.beats)t.finish(e)}}class Bi{constructor(){this.onNotesX=0,this.notes=null}addNote(e){this.notes||(this.notes=[]),e.beatBounds=this,this.notes.push(e)}findNoteAtPos(e,t){const s=this.notes;if(!s)return null;for(const i of s){const s=i.noteHeadBounds.y+i.noteHeadBounds.h,a=i.noteHeadBounds.x+i.noteHeadBounds.w;if(i.noteHeadBounds.x<=e&&i.noteHeadBounds.y<=t&&e<=a&&t<=s)return i.note}return null}finish(e=1){if(this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.onNotesX*=e,this.notes)for(const t of this.notes)t.finish(e)}}class ki{constructor(){this.index=0,this.isFirstOfLine=!1,this.bars=[],this.staffSystemBounds=null}get staveGroupBounds(){return this.staffSystemBounds}addBar(e){e.masterBarBounds=this,this.bars.push(e)}findBeatAtPos(e,t){let s=null;for(const t of this.bars){const i=t.findBeatAtPos(e);if(i&&(!s||s.realBounds.x<i.realBounds.x)){const t=Math.abs(i.realBounds.x-e);(!s||t<1e7)&&(s=i)}}return s?s.beat:null}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e),this.lineAlignedBounds.scaleWith(e),this.bars.sort(((e,t)=>e.realBounds.y<t.realBounds.y?-1:e.realBounds.y>t.realBounds.y?1:e.realBounds.x<t.realBounds.x?-1:e.realBounds.x>t.realBounds.x?1:0));for(const t of this.bars)t.finish(e)}addBeat(e){this.staffSystemBounds.boundsLookup.addBeat(e)}}class Ti{finish(e=1){this.noteHeadBounds.scaleWith(e)}}class Ni{constructor(){this.index=0,this.bars=[]}finish(e=1){this.realBounds.scaleWith(e),this.visualBounds.scaleWith(e);for(const t of this.bars)t.finish(e)}addBar(e){this.boundsLookup.addMasterBar(e),e.staffSystemBounds=this,this.bars.push(e)}findBarAtPos(e){let t=null;for(const s of this.bars)if(!t||s.realBounds.x<e)t=s;else if(e>s.realBounds.x+s.realBounds.w)break;return t}}class xi{constructor(){this._beatLookup=new Map,this._masterBarLookup=new Map,this._currentStaffSystem=null,this.staffSystems=[],this.isFinished=!1}toJson(){const e={},t=[];e.staffSystems=t;for(const e of this.staffSystems){const s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.bars=[];for(const t of e.bars){const 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(const s of t.bars){const t={};t.visualBounds=this.boundsToJson(s.visualBounds),t.realBounds=this.boundsToJson(s.realBounds),t.beats=[];for(const e of s.beats){const s={};s.visualBounds=this.boundsToJson(e.visualBounds),s.realBounds=this.boundsToJson(e.realBounds),s.onNotesX=e.onNotesX;const i=s;if(i.beatIndex=e.beat.index,i.voiceIndex=e.beat.voice.index,i.barIndex=e.beat.voice.bar.index,i.staffIndex=e.beat.voice.bar.staff.index,i.trackIndex=e.beat.voice.bar.staff.track.index,e.notes){const t=[];s.notes=t;for(const s of e.notes){const e={};e.index=s.note.index,e.noteHeadBounds=this.boundsToJson(s.noteHeadBounds),t.push(e)}}t.beats.push(s)}e.bars.push(t)}s.bars.push(e)}t.push(s)}return e}static fromJson(e,t){const s=new xi,i=e.staffSystems;for(const e of i){const i=new Ni;i.visualBounds=xi.boundsFromJson(e.visualBounds),i.realBounds=xi.boundsFromJson(e.realBounds),s.addStaffSystem(i);for(const s of e.bars){const e=new ki;e.index=s.index,e.isFirstOfLine=s.isFirstOfLine,e.lineAlignedBounds=xi.boundsFromJson(s.lineAlignedBounds),e.visualBounds=xi.boundsFromJson(s.visualBounds),e.realBounds=xi.boundsFromJson(s.realBounds),i.addBar(e);for(const i of s.bars){const s=new wi;s.visualBounds=xi.boundsFromJson(i.visualBounds),s.realBounds=xi.boundsFromJson(i.realBounds),e.addBar(s);for(const e of i.beats){const i=new Bi;i.visualBounds=xi.boundsFromJson(e.visualBounds),i.realBounds=xi.boundsFromJson(e.realBounds),i.onNotesX=e.onNotesX;const a=e;if(i.beat=t.tracks[a.trackIndex].staves[a.staffIndex].bars[a.barIndex].voices[a.voiceIndex].beats[a.beatIndex],e.notes){i.notes=[];for(const t of e.notes){const e=new Ti,s=t;e.note=i.beat.notes[s.index],e.noteHeadBounds=xi.boundsFromJson(t.noteHeadBounds),i.addNote(e)}}s.addBeat(i)}}}}return s}static boundsFromJson(e){const t=new Hs;return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}boundsToJson(e){const t={};return t.x=e.x,t.y=e.y,t.w=e.w,t.h=e.h,t}finish(e=1){for(const t of this.staffSystems)t.finish(e);this.isFinished=!0}addStaffSystem(e){e.index=this.staffSystems.length,e.boundsLookup=this,this.staffSystems.push(e),this._currentStaffSystem=e}addMasterBar(e){e.staffSystemBounds?this._masterBarLookup.set(e.index,e):(e.staffSystemBounds=this._currentStaffSystem,this._masterBarLookup.set(e.index,e),this._currentStaffSystem.addBar(e))}addBeat(e){this._beatLookup.has(e.beat.id)||this._beatLookup.set(e.beat.id,[]),this._beatLookup.get(e.beat.id)?.push(e)}findMasterBarByIndex(e){return this._masterBarLookup.has(e)?this._masterBarLookup.get(e):null}findMasterBar(e){const 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){const t=e.id;return this._beatLookup.has(t)?this._beatLookup.get(t):null}getBeatAtPos(e,t){let s=0,i=this.staffSystems.length-1,a=-1;for(;s<=i;){const e=(i+s)/2|0,r=this.staffSystems[e];if(t>=r.realBounds.y&&t<=r.realBounds.y+r.realBounds.h){a=e;break}t<r.realBounds.y?i=e-1:s=e+1}if(-1===a)return null;const r=this.staffSystems[a].findBarAtPos(e);return r?r.findBeatAtPos(e,t):null}getNoteAtPos(e,t,s){const i=this.findBeats(e);if(i)for(const e of i){const i=e.findNoteAtPos(t,s);if(i)return i}return null}}class vi{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 _i,this.renderFinished=new _i,this.partialRenderFinished=new _i,this.partialLayoutFinished=new _i,this.postRenderFinished=new Si,this.error=new _i,this.settings=t,this.recreateCanvas(),this.recreateLayout()}destroy(){this.score=null,this.canvas?.destroy(),this.canvas=null,this.layout=null,this.boundsLookup=null,this.tracks=null}recreateCanvas(){return this._currentRenderEngine!==this.settings.core.engine&&(this.canvas?.destroy(),this.canvas=cc.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=cc.getLayoutEngineFactory(this.settings.display.layoutMode).createLayout(this),this._currentLayoutMode=this.settings.display.layoutMode,!0)}renderScore(e,t){try{this.score=e;let s=null;if(null!=e&&null!=t){if(t){s=[];for(const i of t)i>=0&&i<e.tracks.length&&s.push(e.tracks[i])}else s=e.tracks.slice(0);0===s.length&&e.tracks.length>0&&s.push(e.tracks[0])}this.tracks=s,this.render()}catch(e){this.error.trigger(e)}}renderTracks(e){0===e.length?this.score=null:this.score=e[0].score,this.tracks=e,this.render()}updateSettings(e){this.settings=e}renderResult(e){try{const t=this.layout;t?(wt.debug("Rendering",`Request render of lazy partial ${e}`),t.renderLazyPartial(e)):wt.warning("Rendering",`Request render of lazy partial ${e} ignored, no layout exists`)}catch(e){this.error.trigger(e)}}render(){if(0!==this.width)if(this.boundsLookup=new xi,this.recreateCanvas(),this.canvas.lineWidth=1,this.canvas.settings=this.settings,this.tracks&&0!==this.tracks.length&&this.score){wt.debug("Rendering",`Rendering ${this.tracks.length} tracks`);for(let e=0;e<this.tracks.length;e++){const t=this.tracks[e];wt.debug("Rendering",`Track ${e}: ${t.name}`)}this.preRender.trigger(!1),this.recreateLayout(),this.layoutAndRender(),wt.debug("Rendering","Rendering finished")}else wt.debug("Rendering","Clearing rendered tracks because no score or tracks are set"),this.preRender.trigger(!1),this._renderedTracks=null,this.onRenderFinished(),this.postRenderFinished.trigger(),wt.debug("Rendering","Clearing finished");else wt.warning("Rendering","AlphaTab skipped rendering because of width=0 (element invisible)",null)}resizeRender(){this.recreateLayout()||this.recreateCanvas()||this._renderedTracks!==this.tracks||!this.tracks?(wt.debug("Rendering","Starting full rerendering due to layout or canvas change",null),this.render()):this.layout.supportsResize?(wt.debug("Rendering","Starting optimized rerendering for resize"),this.boundsLookup=new xi,this.preRender.trigger(!0),this.canvas.settings=this.settings,this.layout.resize(),this.onRenderFinished(),this.postRenderFinished.trigger()):wt.debug("Rendering","Current layout does not support dynamic resizing, nothing was done",null),wt.debug("Rendering","Resize finished")}layoutAndRender(){wt.debug("Rendering",`Rendering at scale ${this.settings.display.scale} with layout ${this.layout.name}`,null),this.layout.layoutAndRender(),this._renderedTracks=this.tracks,this.onRenderFinished(),this.postRenderFinished.trigger()}onRenderFinished(){this.boundsLookup?.finish(this.settings.display.scale);const e=new bi;e.totalHeight=this.layout.height,e.totalWidth=this.layout.width,e.renderResult=this.canvas.onRenderFinished(),this.renderFinished.trigger(e)}}const Pi=Object.freeze(Object.defineProperty({__proto__:null,BarBounds:wi,get BeamDirection(){return se},BeatBounds:Bi,Bounds:Hs,BoundsLookup:xi,MasterBarBounds:ki,NoteBounds:Ti,RenderFinishedEventArgs:bi,ScoreRenderer:vi,StaffSystemBounds:Ni},Symbol.toStringTag,{value:"Module"}));class Fi{constructor(){this.maxLine=-1e3,this.minLine=-1e3}}class Ci{constructor(e){this._registeredAccidentals=new Map,this._appliedScoreLines=new Map,this._appliedScoreLinesByValue=new Map,this._notesByValue=new Map,this._beatLines=new Map,this.maxLineBeat=null,this.minLineBeat=null,this.maxLine=-1e3,this.minLine=-1e3,this._barRenderer=e,this._bar=e.bar}static getPercussionLine(e,t){return t<e.staff.track.percussionArticulations.length?e.staff.track.percussionArticulations[t].staffLine:Bt.getArticulationByValue(t)?.staffLine??0}static getNoteValue(e){if(e.isPercussion)return e.percussionArticulation;let t=e.displayValue;switch(e.accidentalMode){case N.ForceDoubleFlat:t+=2;break;case N.ForceDoubleSharp:t-=2;break;case N.ForceFlat:t+=1;break;case N.ForceSharp:t-=1}return t}applyAccidental(e){const t=Ci.getNoteValue(e),s=e.hasQuarterToneOffset;return this.getAccidental(t,s,e.beat,!1,e)}applyAccidentalForValue(e,t,s,i){return this.getAccidental(t,s,e,i,null)}static computeLineWithoutAccidentals(e,t){let s=0;const i=Ci.getNoteValue(t);return s=t.isPercussion?Ci.getPercussionLine(e,i):Ci.calculateNoteSteps(e.masterBar.keySignature,e.clef,i),s}static computeAccidental(e,t,s,i,a=null){const r=e+7,n=s%12,o=r<7?p.Flat:p.Sharp,h=Ci.KeySignatureLookup[r][n],l=Ci.AccidentalNotes[n];let c=p.None;if(i)switch(c=l?o:p.Natural,c){case p.Natural:c=p.NaturalQuarterNoteUp;break;case p.Sharp:c=p.SharpQuarterNoteUp;break;case p.Flat:c=p.FlatQuarterNoteUp}else{switch(t){case N.ForceSharp:c=p.Sharp;break;case N.ForceDoubleSharp:c=p.DoubleSharp;break;case N.ForceFlat:c=p.Flat;break;case N.ForceDoubleFlat:c=p.DoubleFlat;break;default:l?c=o:h&&(c=p.Natural)}c!==p.None?null!=a?a===c&&(c=p.None):h&&c===o&&(c=p.None):null!==a&&(c=a===p.Natural?p.None:p.Natural)}return c}getAccidental(e,t,s,i,a=null){let r=0,n=p.None;if(null!=a?a.isPercussion:this._bar.staff.isPercussion)r=Ci.getPercussionLine(this._bar,e);else{const s=a?a.accidentalMode:N.Default;r=Ci.calculateNoteSteps(this._bar.masterBar.keySignature,this._bar.clef,e);const i=this._registeredAccidentals.has(r)?this._registeredAccidentals.get(r):null;n=Ci.computeAccidental(this._bar.masterBar.keySignature,s,e,t,i);let o=!1;switch(n){case p.NaturalQuarterNoteUp:case p.SharpQuarterNoteUp:case p.FlatQuarterNoteUp:break;default:if(a&&a.isTieDestination&&0===a.beat.index){const e=this._barRenderer.scoreRenderer.layout?.getRendererForBar(this._barRenderer.staff.staveId,a.tieOrigin.beat.voice.bar);if(e&&e.staff===this._barRenderer.staff){e.accidentalHelper.getNoteLine(a.tieOrigin)===r&&(o=!0)}}o?n=p.None:n!==p.None&&this._registeredAccidentals.set(r,n)}}return a?(this._appliedScoreLines.set(a.id,r),this._notesByValue.set(e,a)):this._appliedScoreLinesByValue.set(e,r),(-1e3===this.minLine||this.minLine<r)&&(this.minLine=r,this.minLineBeat=s),(-1e3===this.maxLine||this.maxLine>r)&&(this.maxLine=r,this.maxLineBeat=s),i||this.registerLine(s,r),n}registerLine(e,t){let s;this._beatLines.has(e.id)?s=this._beatLines.get(e.id):(s=new Fi,this._beatLines.set(e.id,s)),(-1e3===s.minLine||t<s.minLine)&&(s.minLine=t),(-1e3===s.minLine||t>s.maxLine)&&(s.maxLine=t)}getMaxLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).maxLine:0}getMinLine(e){return this._beatLines.has(e.id)?this._beatLines.get(e.id).minLine:0}static calculateNoteSteps(e,t,s){const i=e,a=t,r=s%12,n=(s/12|0)-1;let o=Ci.OctaveSteps[a];o-=n*Ci.StepsPerOctave;return o-=(Be.keySignatureIsSharp(i)||Be.keySignatureIsNatural(i)?Ci.SharpNoteSteps:Ci.FlatNoteSteps)[r],o}getNoteLine(e){return this._appliedScoreLines.get(e.id)}getNoteLineForValue(e,t=!1){return this._appliedScoreLinesByValue.has(e)?this._appliedScoreLinesByValue.get(e):t&&this._notesByValue.has(e)?this.getNoteLine(this._notesByValue.get(e)):0}}Ci.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]],Ci.AccidentalNotes=[!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!0,!1],Ci.StepsPerOctave=7,Ci.OctaveSteps=[38,32,30,26,38],Ci.SharpNoteSteps=[0,0,1,1,2,3,3,4,4,5,5,6],Ci.FlatNoteSteps=[0,1,1,2,2,3,4,4,5,5,6,6];class Di{constructor(){this.currentDynamics=E.F,this.slideOrigins=new Map,this.transpose=0,this.tieStarts=new Set,this.tieStartIds=new Map,this.slideOrigins=new Map,this.slurStarts=new Map}}class Ei extends De{constructor(){super(...arguments),this.outputMidiChannel=-1,this.outputMidiProgram=-1,this.outputVolume=-1,this.outputBalance=-1}}class Li{constructor(e){this.instruments=new Map,this._instrumentIdToArticulationIndex=new Map,this._lyricsLine=0,this._lyricsLines=new Map,this.track=e}getLyricLine(e){if(this._lyricsLines.has(e))return this._lyricsLines.get(e);const t=this._lyricsLine;return this._lyricsLines.set(e,t),this._lyricsLine++,t}getOrCreateArticulation(e,t){const s=12*t.octave+t.tone,i=`${e}_${s}`;if(this._instrumentIdToArticulationIndex.has(i))return this._instrumentIdToArticulationIndex.get(i);let a;a=this.instruments.has(e)?this.instruments.get(e):Li.defaultNoteArticulation;const r=this.track.percussionArticulations.length,n=t.beat.voice.bar;let o;o=0===s?4:Ci.calculateNoteSteps(n.masterBar.keySignature,n.clef,s);const h=o-(9-(2*t.beat.voice.bar.staff.standardNotationLineCount-1)),l=new De(a.elementType,h,a.outputMidiNumber,a.noteHeadDefault,a.noteHeadHalf,a.noteHeadWhole,a.techniqueSymbol,a.techniqueSymbolPlacement);return this._instrumentIdToArticulationIndex.set(i,r),this.track.percussionArticulations.push(l),r}}Li.defaultNoteArticulation=new De("Default",0,0,G.NoteheadBlack,G.NoteheadHalf,G.NoteheadWhole);class Mi extends Ds{constructor(){super(...arguments),this._idToTrackInfo=new Map,this._indexToTrackInfo=new Map,this._staffToContext=new Map,this._previousMasterBarNumber=-1,this._implicitBars=0,this._divisionsPerQuarterNote=1,this._currentDynamics=E.F,this._musicalPosition=0,this._lastBeat=null,this._nextMasterBarRepeatEnding=0,this._nextBeatAutomations=null,this._nextBeatChord=null,this._nextBeatCrescendo=null,this._nextBeatLetRing=!1,this._nextBeatPalmMute=!1,this._nextBeatOttavia=null,this._nextBeatText=null,this._simileMarkAllStaves=null,this._simileMarkPerStaff=null,this._isBeatSlash=!1,this._currentTrillStep=-1}get name(){return"MusicXML"}readScore(){const e=this.extractMusicXml(),t=new Xs;try{t.parse(e)}catch(e){throw new Es("Unsupported format",e)}return this._score=new Cs,this._score.tempo=120,this._score.stylesheet.hideDynamics=!0,this.parseDom(t),this.consolidate(),this._score.finish(this.settings),this._score.rebuildRepeatGroups(),this._score}consolidate(){const e=new Set([Ls.PercussionChannel]);for(const t of this._score.tracks){if(t.playbackInfo.primaryChannel!==Ls.PercussionChannel)for(;e.has(t.playbackInfo.primaryChannel);)t.playbackInfo.primaryChannel++;if(e.add(t.playbackInfo.primaryChannel),t.playbackInfo.secondaryChannel!==Ls.PercussionChannel)for(;e.has(t.playbackInfo.secondaryChannel);)t.playbackInfo.secondaryChannel++;e.add(t.playbackInfo.secondaryChannel);for(const e of t.staves){for(const t of e.bars)for(const e of t.voices)if(e.isEmpty&&0===e.beats.length){const t=new gs;t.isEmpty=!0,e.addBeat(t)}const t=0===e.bars.length?1:e.bars[0].voices.length;for(;e.bars.length<this._score.masterBars.length;){const s=new ue;e.addBar(s);const i=s.previousBar;i&&(s.clef=i.clef,s.clefOttava=i.clefOttava);for(let e=0;e<t;e++){const e=new Dt;s.addVoice(e);const t=new gs;t.isEmpty=!0,e.addBeat(t)}}}}}extractMusicXml(){const e=new hi(this.data);let t;try{t=e.read()}catch(e){t=[]}if(0===t.length)return this.data.reset(),Le.toString(this.data.readAll(),this.settings.importer.encoding);const s=t.find((e=>"META-INF/container.xml"===e.fullName));if(!s)throw new Es("No compressed MusicXML");const i=new Xs;try{i.parse(Le.toString(s.data,this.settings.importer.encoding))}catch(e){throw new Es("Malformed container.xml, could not parse as XML",e)}const a=i.firstElement;if(!a||"container"!==a.localName)throw new Es("Malformed container.xml, root element not 'container'");const r=a.findChildElement("rootfiles");if(!r)throw new Es("Malformed container.xml, 'container/rootfiles' not found");let n="";for(const e of r.childElements())if("rootfile"===e.localName){n=e.getAttribute("full-path");break}if(!n)throw new Es("Unsupported compressed MusicXML, missing rootfile");const o=t.find((e=>e.fullName===n));if(!o)throw new Es(`Malformed container.xml, '${n}' not contained in zip`);return Le.toString(o.data,this.settings.importer.encoding)}parseDom(e){const t=e.firstElement;if(!t)throw new Es("Unsupported format");switch(t.localName){case"score-partwise":this.parsePartwise(t);break;case"score-timewise":this.parseTimewise(t);break;default:throw new Es("Unsupported format")}}parsePartwise(e){for(const t of e.childElements())switch(t.localName){case"credit":this.parseCredit(t);break;case"identification":this.parseIdentification(t);break;case"movement-title":this.parseMovementTitle(t);break;case"part":this.parsePartwisePart(t);break;case"part-list":this.parsePartList(t);break;case"work":this.parseWork(t)}}parseTimewise(e){for(const t of e.childElements())switch(t.localName){case"credit":this.parseCredit(t);break;case"identification":this.parseIdentification(t);break;case"movement-title":this.parseMovementTitle(t);break;case"part-list":this.parsePartList(t);break;case"work":this.parseWork(t);break;case"measure":this.parseTimewiseMeasure(t)}}parseCredit(e){if("1"!==e.getAttribute("page","1"))return;const t=[];let s=null,i="";for(const a of e.childElements())switch(a.localName){case"credit-type":t.push(a.innerText);break;case"credit-words":null===s&&(s=a),i+=a.innerText}if(t.length>0)for(const e of t)switch(e){case"title":this._score.title=Mi.sanitizeDisplay(i);break;case"subtitle":this._score.subTitle=Mi.sanitizeDisplay(i);break;case"composer":case"arranger":this._score.artist=Mi.sanitizeDisplay(i);break;case"lyricist":this._score.words=Mi.sanitizeDisplay(i);break;case"rights":this._score.copyright=Mi.sanitizeDisplay(i)}else if(s){const e=s.getAttribute("font-size","0"),t=s.getAttribute("font-size","top"),a=s.getAttribute("halign","left");if("top"===t){if(i.includes("copyright")||i.includes("Copyright")||i.includes("©")||i.includes("(c)")||i.includes("(C)"))return void(this._score.copyright=Mi.sanitizeDisplay(i));if("center"===a||"center"===e){if(0===this._score.title.length)return void(this._score.title=Mi.sanitizeDisplay(i));if(0===this._score.subTitle.length)return void(this._score.subTitle=Mi.sanitizeDisplay(i));if(0===this._score.album.length)return void(this._score.album=Mi.sanitizeDisplay(i))}else if(("right"===a||"right"===e)&&0===this._score.music.length)return void(this._score.music=Mi.sanitizeDisplay(i));if(0===this._score.artist.length)return void(this._score.artist=Mi.sanitizeDisplay(i));if(0===this._score.words.length)return void(this._score.words=Mi.sanitizeDisplay(i))}}}static sanitizeDisplay(e){return e.replaceAll("\r","").replaceAll("\n"," ").replaceAll("\t","  ").replaceAll(" "," ")}parseIdentification(e){for(const t of e.childElements())switch(t.localName){case"creator":if(t.attributes.has("type"))switch(t.attributes.get("type")){case"composer":this._score.artist=Mi.sanitizeDisplay(t.innerText);break;case"lyricist":this._score.words=Mi.sanitizeDisplay(t.innerText);break;case"arranger":this._score.music=Mi.sanitizeDisplay(t.innerText)}else this._score.artist=Mi.sanitizeDisplay(t.innerText);break;case"rights":this._score.copyright.length>0&&(this._score.copyright+=", "),this._score.copyright+=t.innerText,t.attributes.has("type")&&(this._score.copyright+=` (${t.attributes.get("type")})`);break;case"encoding":this.parseEncoding(t)}}parseEncoding(e){for(const t of e.childElements())switch(t.localName){case"encoder":this._score.tab.length>0&&(this._score.tab+=", "),this._score.tab+=t.innerText,t.attributes.has("type")&&(this._score.tab+=` (${t.attributes.get("type")})`);break;case"encoding-description":this._score.notices+=Mi.sanitizeDisplay(t.innerText)}}parseMovementTitle(e){0===this._score.title.length?this._score.title=Mi.sanitizeDisplay(e.innerText):this._score.subTitle=Mi.sanitizeDisplay(e.innerText)}parsePartList(e){for(const t of e.childElements())if("score-part"===t.localName)this.parseScorePart(t)}parseScorePart(e){const t=new $t;t.ensureStaveCount(1),this._score.addTrack(t);const s=e.attributes.get("id"),i=new Li(t);this._idToTrackInfo.set(s,i),this._indexToTrackInfo.set(t.index,i);for(const s of e.childElements())switch(s.localName){case"part-name":t.name=Mi.sanitizeDisplay(s.innerText);break;case"part-name-display":t.name=this.parsePartDisplayAsText(s);break;case"part-abbreviation":t.shortName=Mi.sanitizeDisplay(s.innerText);break;case"part-abbreviation-display":t.shortName=this.parsePartDisplayAsText(s);break;case"score-instrument":this.parseScoreInstrument(s,i);break;case"midi-device":s.attributes.has("port")&&(t.playbackInfo.port=Number.parseInt(s.attributes.get("port"),10));break;case"midi-instrument":this.parseScorePartMidiInstrument(s,i)}i.firstArticulation&&(i.firstArticulation.outputMidiProgram>=0&&(t.playbackInfo.program=i.firstArticulation.outputMidiProgram),i.firstArticulation.outputBalance>=0&&(t.playbackInfo.balance=i.firstArticulation.outputBalance),i.firstArticulation.outputVolume>=0&&(t.playbackInfo.volume=i.firstArticulation.outputVolume),i.firstArticulation.outputMidiChannel>=0&&(t.playbackInfo.primaryChannel=i.firstArticulation.outputMidiChannel,t.playbackInfo.secondaryChannel=i.firstArticulation.outputMidiChannel))}parseScoreInstrument(e,t){const s=new Ei;t.firstArticulation||(t.firstArticulation=s),t.instruments.set(e.getAttribute("id",""),s)}parseScorePartMidiInstrument(e,t){const s=e.getAttribute("id","");if(!t.instruments.has(s))return;const i=t.instruments.get(s);for(const t of e.childElements())switch(t.localName){case"midi-channel":i.outputMidiChannel=Number.parseInt(t.innerText)-1;break;case"midi-program":i.outputMidiProgram=Number.parseInt(t.innerText)-1;break;case"midi-unpitched":i.outputMidiNumber=Number.parseInt(t.innerText)-1;break;case"volume":i.outputVolume=Mi.interpolatePercent(Number.parseFloat(t.innerText));break;case"pan":i.outputBalance=Mi.interpolatePan(Number.parseFloat(t.innerText))}}static interpolatePercent(e){return 0|Mi.interpolate(0,100,0,16,e)}static interpolatePan(e){return 0|Mi.interpolate(-90,90,0,16,e)}static interpolate(e,t,s,i,a){return s+(i-s)*((a-e)/(t-e))}parsePartDisplayAsText(e){let t="";for(const s of e.childElements())switch(s.localName){case"display-text":t+=s.innerText;break;case"accidental-text":switch(s.innerText){case"sharp":t+="♯";break;case"natural":t+="♮";break;case"flat":t+="♭";break;case"double-sharp":t+="𝄪";break;case"sharp-sharp":t+="♯♯";break;case"flat-flat":t+="𝄫";break;case"natural-sharp":t+="♮♯";break;case"natural-flat":t+="♮♭";break;case"sharp-down":t+="𝄱";break;case"sharp-up":t+="𝄰";break;case"natural-down":t+="𝄯";break;case"natural-up":t+="𝄮";break;case"flat-down":t+="𝄭";break;case"flat-up":t+="𝄬";break;case"arrow-down":t+="↓";break;case"arrow-up":t+="↑";break;case"triple-sharp":t+="♯𝄪";break;case"triple-flat":t+="𝄬𝄬𝄬";break;case"sharp-1":t+="♯¹";break;case"sharp-2":t+="♯²";break;case"sharp-3":t+="♯³";break;case"sharp-4":t+="♯⁴";break;case"sharp-5":t+="♯⁵";break;case"flat-1":t+="♭¹";break;case"flat-2":t+="♭²";break;case"flat-3":t+="♭³";break;case"flat-4":t+="♭⁴";break;case"flat-5":t+="♭⁵"}}return Mi.sanitizeDisplay(t)}parseWork(e){for(const t of e.childElements())if("work-title"===t.localName)this._score.title=Mi.sanitizeDisplay(t.innerText)}parsePartwisePart(e){const t=e.attributes.get("id");if(!t||!this._idToTrackInfo.has(t))return;const s=this._idToTrackInfo.get(t).track;this._previousMasterBarNumber=-1,this._implicitBars=0;for(const t of e.childElements())if("measure"===t.localName)this.parsePartwiseMeasure(t,s)}parsePartwiseMeasure(e,t){const s=this.getOrCreateMasterBar(e);this.parsePartMeasure(e,s,t)}parseTimewiseMeasure(e){const t=this.getOrCreateMasterBar(e);for(const s of e.childElements())if("part"===s.localName)this.parseTimewisePart(s,t)}getOrCreateMasterBar(e){let t=Number.parseInt(e.attributes.get("number"));const s="yes"===e.attributes.get("implicit");for(Number.isNaN(t)?(t=-1===this._previousMasterBarNumber?1:this._previousMasterBarNumber+1,this._implicitBars++):0===t?(t++,this._implicitBars++):t+=this._implicitBars;this._score.masterBars.length<t;){const e=new Se;s&&(e.isAnacrusis=!0),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)}this._previousMasterBarNumber=t;return this._score.masterBars[t-1]}parseTimewisePart(e,t){const s=e.attributes.get("id");if(!s||!this._idToTrackInfo.has(s))return;const i=this._idToTrackInfo.get(s).track;this.parsePartMeasure(e,t,i)}parsePartMeasure(e,t,s){this._musicalPosition=0,this._lastBeat=null;const i=this.getOrCreateStaff(s,0);this.getOrCreateBar(i,t),t.alternateEndings=this._nextMasterBarRepeatEnding;const a=[];for(const i of e.childElements())switch(i.localName){case"note":this.parseNote(i,t,s);break;case"backup":this.parseBackup(i);break;case"forward":this.parseForward(i);break;case"direction":this.parseDirection(i,t,s);break;case"attributes":this.parseAttributes(i,t,s);break;case"harmony":this.parseHarmony(i,s);break;case"print":this.parsePrint(i,t,s);break;case"sound":this.parseSound(i,t,s);break;case"barline":a.push(i)}for(const e of a)this.parseBarLine(e,t,s);this.applySimileMarks(t,s)}parsePrint(e,t,s){("yes"===e.getAttribute("new-system","no")||"yes"===e.getAttribute("new-page","no"))&&s.addLineBreaks(t.index)}applySimileMarks(e,t){if(null!==this._simileMarkAllStaves){for(const s of t.staves){const t=this.getOrCreateBar(s,e);t.simileMark=this._simileMarkAllStaves,t.simileMark!==h.None&&this.clearBar(t)}this._simileMarkAllStaves===h.FirstOfDouble?this._simileMarkAllStaves=h.SecondOfDouble:this._simileMarkAllStaves=null}if(null!==this._simileMarkPerStaff){const s=Array.from(this._simileMarkPerStaff.keys());for(const i of s){const s=this.getOrCreateStaff(t,i),a=this.getOrCreateBar(s,e);a.simileMark=this._simileMarkPerStaff.get(i),a.simileMark!==h.None&&this.clearBar(a),a.simileMark===h.FirstOfDouble?this._simileMarkPerStaff.set(i,h.SecondOfDouble):this._simileMarkPerStaff.delete(i)}0===this._simileMarkPerStaff.size&&(this._simileMarkPerStaff=null)}}clearBar(e){for(const t of e.voices){const e=new gs;e.isEmpty=!0,t.addBeat(e)}}parseBarLine(e,t,s){for(const i of e.childElements())switch(i.localName){case"bar-style":this.parseBarStyle(i,t,s,e.getAttribute("location","right"));break;case"ending":this.parseEnding(i,t);break;case"repeat":this.parseRepeat(i,t)}}parseRepeat(e,t){const s=e.getAttribute("direction");let i=Number.parseInt(e.getAttribute("times"));(i<0||Number.isNaN(i))&&(i=2),"backward"===s?t.repeatCount=i:"forward"===s&&(t.isRepeatStart=!0)}parseEnding(e,t){const s=e.getAttribute("number").split(",").map((e=>Number.parseInt(e)));let i=0;for(const e of s)i|=1<<e-1&255;switch(t.alternateEndings=i,e.getAttribute("type","")){case"start":this._nextMasterBarRepeatEnding=this._nextMasterBarRepeatEnding|i;break;case"stop":case"discontinue":this._nextMasterBarRepeatEnding=this._nextMasterBarRepeatEnding&~i}}parseBarStyle(e,t,s,i){let a=d.Automatic;switch(e.innerText){case"dashed":a=d.Dashed;break;case"dotted":a=d.Dotted;break;case"heavy":a=d.Heavy;break;case"heavy-heavy":a=d.HeavyHeavy;break;case"heavy-light":a=d.HeavyLight;break;case"light-heavy":a=d.LightHeavy;break;case"light-light":a=d.LightLight;break;case"none":a=d.None;break;case"regular":a=d.Regular;break;case"short":a=d.Short;break;case"tick":a=d.Tick}for(const e of s.staves){const s=this.getOrCreateBar(e,t);switch(i){case"left":s.barLineLeft=a;break;case"right":s.barLineRight=a}}}parseSound(e,t,s){for(const s of e.childElements())switch(s.localName){case"midi-instrument":this.parseSoundMidiInstrument(s,t);break;case"swing":this.parseSwing(s,t)}if(e.attributes.has("coda")&&t.addDirection(C.TargetCoda),e.attributes.has("tocoda")&&t.addDirection(C.JumpDaCoda),e.attributes.has("dacapo")&&t.addDirection(C.JumpDaCapo),e.attributes.has("dalsegno")&&t.addDirection(C.JumpDalSegno),e.attributes.has("fine")&&t.addDirection(C.TargetFine),e.attributes.has("segno")&&t.addDirection(C.TargetSegno),e.attributes.has("pan")){this._nextBeatAutomations||(this._nextBeatAutomations=[]);const t=new pe;t.type=g.Balance,t.value=Mi.interpolatePan(Number.parseFloat(e.attributes.get("pan"))),this._nextBeatAutomations.push(t)}if(e.attributes.has("tempo")){this._nextBeatAutomations||(this._nextBeatAutomations=[]);const t=new pe;t.type=g.Tempo,t.value=Mi.interpolatePercent(Number.parseFloat(e.attributes.get("tempo"))),this._nextBeatAutomations.push(t)}}parseSwing(e,t){let s=0,i=0,a=null;for(const r of e.childElements())switch(r.localName){case"straight":return void(t.tripletFeel=P.NoTripletFeel);case"first":s=Number.parseInt(r.innerText);break;case"second":i=Number.parseInt(r.innerText);break;case"swing-type":a=this.parseBeatDuration(r)}a||(a=D.Eighth),a===D.Eighth?2===s&&1===i?t.tripletFeel=P.Triplet8th:3===s&&1===i?t.tripletFeel=P.Dotted8th:1===s&&3===i&&(t.tripletFeel=P.Scottish8th):a===D.Sixteenth&&(2===s&&1===i?t.tripletFeel=P.Triplet16th:3===s&&1===i?t.tripletFeel=P.Dotted16th:1===s&&3===i&&(t.tripletFeel=P.Scottish16th))}parseSoundMidiInstrument(e,t){let s;for(const t of e.childElements())switch(t.localName){case"midi-program":this._nextBeatAutomations||(this._nextBeatAutomations=[]),s=new pe,s.type=g.Instrument,s.value=Number.parseInt(t.innerText)-1,this._nextBeatAutomations.push(s);break;case"volume":this._nextBeatAutomations||(this._nextBeatAutomations=[]),s=new pe,s.type=g.Volume,s.value=Mi.interpolatePercent(Number.parseFloat(t.innerText)),this._nextBeatAutomations.push(s);break;case"pan":this._nextBeatAutomations||(this._nextBeatAutomations=[]),s=new pe,s.type=g.Balance,s.value=Mi.interpolatePan(Number.parseFloat(t.innerText)),this._nextBeatAutomations.push(s)}}parseHarmony(e,t){const s=new me;let i=!1,a="";for(const t of e.childElements())switch(t.localName){case"root":s.name=this.parseHarmonyRoot(t);break;case"kind":s.name=s.name+this.parseHarmonyKind(t),"yes"===t.getAttribute("parentheses-degrees","no")&&(i=!0);break;case"frame":this.parseHarmonyFrame(t,s);break;case"degree":a+=this.parseDegree(t)}a&&(s.name+=i?`(${a})`:a),null===this._nextBeatChord&&(this._nextBeatChord=s)}parseDegree(e){let t="",s="",i="";for(const a of e.childElements())switch(a.localName){case"degree-value":t=a.innerText;break;case"degree-alter":switch(a.innerText){case"-1":s="♭";break;case"1":s="♯"}break;case"degree-type":i+=a.getAttribute("text","")}return`${i}${s}${t}`}parseHarmonyRoot(e){let t="",s="";for(const i of e.childElements())switch(i.localName){case"root-step":t=i.innerText;break;case"root-alter":switch(Number.parseFloat(i.innerText)){case-2:s="bb";break;case-1:s="b";break;case 0:s="";break;case 1:s="#";break;case 2:s="##"}}return t+s}parseHarmonyKind(e){const t=e.getAttribute("text");let s="";if(t)s=t;else{const t=e.innerText;switch(t){case"major":s="";break;case"minor":s="m";break;case"augmented":s="+";break;case"diminished":s="○";break;case"dominant":s="7";break;case"major-seventh":s="7M";break;case"minor-seventh":s="m7";break;case"diminished-seventh":s="○7";break;case"augmented-seventh":s="+7";break;case"half-diminished":s="⍉";break;case"major-minor":s="mMaj";break;case"major-sixth":s="maj6";break;case"minor-sixth":s="m6";break;case"dominant-ninth":s="9";break;case"major-ninth":s="maj9";break;case"minor-ninth":s="m9";break;case"dominant-11th":s="11";break;case"major-11th":s="maj11";break;case"minor-11th":s="m11";break;case"dominant-13th":s="13";break;case"major-13th":s="maj13";break;case"minor-13th":s="m13";break;case"suspended-second":s="sus2";break;case"suspended-fourth":s="sus4";break;case"Neapolitan":s="♭II";break;case"Italian":s="It⁺⁶";break;case"French":case"German":s="Fr⁺⁶";break;default:s=t}}return s}parseHarmonyFrame(e,t){for(const s of e.childElements())switch(s.localName){case"frame-strings":const e=Number.parseInt(s.innerText);t.strings=new Array(e);for(let s=0;s<e;s++)t.strings[s]=-1;break;case"first-fret":t.firstFret=Number.parseInt(s.innerText);break;case"frame-note":let i=null,a=null;for(const e of s.childElements())switch(e.localName){case"string":i=Number.parseInt(e.innerText);break;case"fret":a=Number.parseInt(e.innerText),i&&a>=0&&(t.strings[i-1]=a);break;case"barre":i&&a&&"start"===e.getAttribute("type")&&t.barreFrets.push(a)}}}parseAttributes(e,t,s){let i,a,r;if(null==this._lastBeat)for(const n of e.childElements())switch(n.localName){case"divisions":this._divisionsPerQuarterNote=Number.parseFloat(n.innerText);break;case"key":this.parseKey(n,t);break;case"time":this.parseTime(n,t);break;case"staves":s.ensureStaveCount(Number.parseInt(n.innerText));break;case"clef":i=Number.parseInt(n.getAttribute("number","1"))-1,a=this.getOrCreateStaff(s,i),r=this.getOrCreateBar(a,t),this.parseClef(n,r);break;case"staff-details":i=Number.parseInt(n.getAttribute("number","1"))-1,a=this.getOrCreateStaff(s,i),this.parseStaffDetails(n,a);break;case"transpose":this.parseTranspose(n,s);break;case"measure-style":this.parseMeasureStyle(n,s,!1)}else for(const t of e.childElements())switch(t.localName){case"divisions":this._divisionsPerQuarterNote=Number.parseFloat(t.innerText);break;case"measure-style":this.parseMeasureStyle(t,s,!0)}}parseMeasureStyle(e,t,s){for(const t of e.childElements())switch(t.localName){case"measure-repeat":if(!s){let s=null;switch(t.getAttribute("type")){case"start":switch(Number.parseInt(t.getAttribute("slashes","1"))){case 1:s=h.Simple;break;case 2:s=h.FirstOfDouble}break;case"stop":s=null}if(e.attributes.has("number")){this._simileMarkPerStaff=this._simileMarkPerStaff??new Map;const t=Number.parseInt(e.attributes.get("number"))-1;null==s?this._simileMarkPerStaff.delete(t):this._simileMarkPerStaff.set(t,s)}else this._simileMarkAllStaves=s}break;case"slash":switch(t.getAttribute("type")){case"start":this._isBeatSlash=!0;break;case"stop":this._isBeatSlash=!1}}}parseTranspose(e,t){let s=0;for(const t of e.childElements())switch(t.localName){case"chromatic":s+=Number.parseFloat(t.innerText);break;case"octave-change":s+=12*Number.parseFloat(t.innerText)}if(e.attributes.has("number")){const i=this.getOrCreateStaff(t,Number.parseInt(e.attributes.get("number"))-1);this.getStaffContext(i).transpose=s,i.displayTranspositionPitch=s}else for(const e of t.staves)this.getStaffContext(e).transpose=s,e.displayTranspositionPitch=s}parseStaffDetails(e,t){for(const s of e.childElements())switch(s.localName){case"staff-lines":t.standardNotationLineCount=Number.parseInt(s.innerText);break;case"staff-tuning":this.parseStaffTuning(s,t);break;case"capo":t.capo=Number.parseInt(s.innerText)}}parseStaffTuning(e,t){0===t.stringTuning.tunings.length&&(t.showTablature=!0,t.showStandardNotation=!1,t.stringTuning.tunings=new Array(t.standardNotationLineCount).fill(0));const s=Number.parseInt(e.getAttribute("line"));let i="C",a="",r=0;for(const t of e.childElements())switch(t.localName){case"tuning-step":i=t.innerText;break;case"tuning-alter":r=Number.parseFloat(t.innerText);break;case"tuning-octave":a=t.innerText}const n=Be.getTuningForText(i+a)+r;t.tuning[t.tuning.length-s]=n}parseClef(e,t){let s="s",i=0;for(const a of e.childElements())switch(a.localName){case"sign":s=a.innerText.toLowerCase();break;case"line":i=Number.parseInt(a.innerText);break;case"clef-octave-change":switch(Number.parseInt(a.innerText)){case-2:t.clefOttava=o._15mb;break;case-1:t.clefOttava=o._8vb;break;case 1:t.clefOttava=o._8va;break;case 2:t.clefOttava=o._15mb}}switch(s){case"g":default:t.clef=n.G2;break;case"f":t.clef=n.F4;break;case"c":t.clef=3===i?n.C3:n.C4;break;case"percussion":t.clef=n.Neutral,t.staff.isPercussion=!0;break;case"tab":t.clef=n.G2,t.staff.showTablature=!0}}parseTime(e,t){let s=!1,i=!1;for(const a of e.childElements()){const e=a.innerText;switch(a.localName){case"beats":s||(-1===e.indexOf("+")?t.timeSignatureNumerator=Number.parseInt(e):t.timeSignatureNumerator=e.split("+").map((e=>Number.parseInt(e))).reduce(((e,t)=>t+e),0),s=!0);break;case"beat-type":i||(-1===e.indexOf("+")?t.timeSignatureDenominator=Number.parseInt(e):t.timeSignatureDenominator=e.split("+").map((e=>Number.parseInt(e))).reduce(((e,t)=>t+e),0),i=!0)}}switch(e.getAttribute("symbol","")){case"common":case"cut":t.timeSignatureCommon=!0}}parseKey(e,t){let s=-x.C,i="";for(const t of e.childElements())switch(t.localName){case"fifths":s=Number.parseInt(t.innerText);break;case"mode":i=t.innerText}t.keySignature=-7<=s&&s<=7?s:x.C,t.keySignatureType="minor"===i?v.Minor:v.Major}parseDirection(e,t,s){const i=[];let a=null,r=-1,n=-1;for(const t of e.childElements())switch(t.localName){case"direction-type":i.push(t.firstElement);break;case"offset":a=Number.parseFloat(t.innerText);break;case"voice":break;case"staff":r=Number.parseInt(t.innerText)-1;break;case"sound":t.attributes.has("tempo")&&(n=Number.parseFloat(t.attributes.get("tempo")))}let o=null;o=r>=0?this.getOrCreateStaff(s,r):null!==this._lastBeat?this._lastBeat.voice.bar.staff:this.getOrCreateStaff(s,0);const h=o?this.getOrCreateBar(o,t):null,c=()=>{let e=this._musicalPosition;null!==a&&(e+=a);return e/t.calculateDuration(!1)};if(n>0){const e=new pe;e.type=g.Tempo,e.value=n,e.ratioPosition=c(),this.hasSameTempo(t,e)||(t.tempoAutomations.push(e),0===t.index&&(t.score.tempo=e.value))}let d="";for(const e of i)switch(e.localName){case"rehearsal":t.section=new ft,t.section.marker=e.innerText;break;case"segno":t.addDirection(C.TargetSegno);break;case"coda":t.addDirection(C.TargetCoda);break;case"words":d=e.innerText;break;case"wedge":switch(e.getAttribute("type")){case"crescendo":this._nextBeatCrescendo=F.Crescendo;break;case"diminuendo":this._nextBeatCrescendo=F.Decrescendo;break;case"stop":this._nextBeatCrescendo=null}break;case"dynamics":const s=this.parseDynamics(e);null!==s&&(this._currentDynamics=s,this._score.stylesheet.hideDynamics=!1);break;case"dashes":const i=e.getAttribute("type","start");switch(d){case"LetRing":this._nextBeatLetRing="start"===i||"continue"===i;break;case"P.M.":this._nextBeatPalmMute="start"===i||"continue"===i}d="";break;case"pedal":const a=this.parsePedal(e);if(a&&h){a.ratioPosition=c();const e=h.sustainPedals.length>0&&h.sustainPedals[h.sustainPedals.length-1].pedalType!==l.Up;(a.pedalType!==l.Up||e)&&h.sustainPedals.push(a)}break;case"metronome":this.parseMetronome(e,t,c());break;case"octave-shift":this._nextBeatOttavia=this.parseOctaveShift(e)}d&&(this._nextBeatText=d)}parseOctaveShift(e){const t=e.getAttribute("type");switch(Number.parseInt(e.getAttribute("size","8"))){case 15:switch(t){case"up":return o._15mb;case"down":return o._15ma;case"stop":return o.Regular;case"continue":return this._nextBeatOttavia}break;case 8:switch(t){case"up":return o._8vb;case"down":return o._8va;case"stop":return o.Regular;case"continue":return this._nextBeatOttavia}}return null}parseMetronome(e,t,s){let i=null,a=-1;for(const t of e.childElements())switch(t.localName){case"beat-unit":i=this.parseBeatDuration(t);break;case"per-minute":a=Number.parseFloat(t.innerText)}if(null!==i&&a>0){const e=new pe;e.type=g.Tempo,e.value=a*(i/4)|0,e.ratioPosition=s,this.hasSameTempo(t,e)||(t.tempoAutomations.push(e),0===t.index&&(t.score.tempo=e.value))}}hasSameTempo(e,t){for(const s of e.tempoAutomations)if(t.ratioPosition===s.ratioPosition&&t.value===s.value)return!0;return!1}parsePedal(e){const t=new ce;switch(e.getAttribute("type")){case"start":t.pedalType=l.Down;break;case"stop":t.pedalType=l.Up;break;case"continue":t.pedalType=l.Hold;break;default:return null}return t}parseDynamics(e){for(const t of e.childElements()){const e=t.localName.toUpperCase();switch(e){case"PPP":case"PP":case"P":case"MP":case"MF":case"F":case"FF":case"FFF":case"PPPP":case"PPPPP":case"PPPPPP":case"FFFF":case"FFFFF":case"FFFFFF":case"SF":case"SFP":case"SFPP":case"FP":case"RF":case"RFZ":case"SFZ":case"SFFZ":case"FZ":case"N":case"PF":case"SFZP":return E[e]}}return null}parseForward(e){for(const t of e.childElements())if("duration"===t.localName)this._musicalPosition+=this.musicXmlDivisionsToAlphaTabTicks(Number.parseFloat(t.innerText))}parseBackup(e){for(const t of e.childElements())if("duration"===t.localName){if(this._lastBeat){let e=this._musicalPosition;e-=this.musicXmlDivisionsToAlphaTabTicks(Number.parseFloat(t.innerText)),e<0&&(e=0),this._musicalPosition=e}}}getOrCreateStaff(e,t){for(;e.staves.length<=t;){const t=new Ut;e.addStaff(t),this._score.masterBars.length>0&&this.getOrCreateBar(t,this._score.masterBars[this._score.masterBars.length-1])}return e.staves[t]}getOrCreateBar(e,t){const s=0===e.bars.length?1:e.bars[0].voices.length;for(;e.bars.length<=t.index;){const t=new ue;e.addBar(t),t.previousBar&&(t.clef=t.previousBar.clef,t.clefOttava=t.previousBar.clefOttava);for(let e=0;e<s;e++){const e=new Dt;t.addVoice(e)}}return e.bars[t.index]}getOrCreateVoice(e,t){let s=!1;for(;e.voices.length<=t;)e.addVoice(new Dt),s=!0;if(s)for(const s of e.staff.bars)for(;s.voices.length<=t;)s.addVoice(new Dt);return e.voices[t]}parseNote(e,t,s){let i=null,a=R.None,r=0,n=cs.ForceSplitToNext,o=!1,h=0,l=0,c=-1,d=null,u=0,p=-1,g=-1,m=null,f=null,y=!1,b=null;const S="no"!==e.getAttribute("print-object","yes"),_=()=>{if(null!==i)return;o&&!this._lastBeat&&(wt.warning("MusicXML","Malformed MusicXML, <chord /> cannot be set on the first note of a measure"),o=!1),o&&!f&&(wt.warning("MusicXML","Cannot mix <chord /> and <rest />"),o=!1);const e=this.getOrCreateStaff(s,h);if(o)return i=this._lastBeat,void i.addNote(f);const _=this.getOrCreateBar(e,t),w=this.getOrCreateVoice(_,l),B=0===w.beats.length?0:w.beats[w.beats.length-1].displayEnd;let k=this._musicalPosition-B;if(k>0){if(this._lastBeat&&this._lastBeat.beamingMode===cs.ForceMergeWithNext&&this._lastBeat.voice.bar.staff.index!==h&&w.beats.length>0&&w.beats[w.beats.length-1].beamingMode===cs.ForceMergeWithNext){const e=w.beats[w.beats.length-1].duration;for(;k>0;){const t=this.createRestForGap(k,e);if(null===t)break;this.insertBeatToVoice(t,w),k-=t.playbackDuration}}if(k>0){const e=new gs;e.dynamics=this._currentDynamics,e.isEmpty=!0,e.duration=D.TwoHundredFiftySixth,e.overrideDisplayDuration=k,e.updateDurations(),this.insertBeatToVoice(e,w)}}else k<0&&wt.error("MusicXML","Unsupported forward/backup detected. Cannot fill new beats into already filled area of voice");c<0&&null!==d&&(c=rs.toTicks(d),u>0&&(c=rs.applyDot(c,2===u)));const T=new gs;i=T,T.beamingMode=n,T.isEmpty=!1,T.dynamics=this._currentDynamics,this._isBeatSlash&&(T.slashed=!0);const N=this._nextBeatAutomations;if(this._nextBeatAutomations=null,null!==N)for(const e of N)T.automations.push(e);const x=this._nextBeatChord;this._nextBeatChord=null,null!==x&&(T.chordId=x.uniqueId,w.bar.staff.hasChord(x.uniqueId)||w.bar.staff.addChord(T.chordId,x));const v=this._nextBeatCrescendo;null!==v&&(T.crescendo=v);const P=this._nextBeatOttavia;if(null!==P&&(T.ottava=P),T.isLetRing=this._nextBeatLetRing,T.isPalmMute=this._nextBeatPalmMute,this._nextBeatText&&(T.text=this._nextBeatText,this._nextBeatText=null),null!==f&&T.addNote(f),this.insertBeatToVoice(T,w),null!==f){f.isVisible=S;const e=this._indexToTrackInfo.get(s.index);null!==b?f.percussionArticulation=e.getOrCreateArticulation(b,f):y||(f.percussionArticulation=e.getOrCreateArticulation("",f))}a!==R.None?(T.graceType=a,this.applyBeatDurationFromTicks(T,r,null,!1)):(T.tupletNumerator=p,T.tupletDenominator=g,T.dots=u,T.preferredBeamDirection=m,this.applyBeatDurationFromTicks(T,c,d,!0)),this._musicalPosition=T.displayEnd,this._lastBeat=T};for(const t of e.childElements())switch(t.localName){case"grace":const e=Number.parseFloat(t.getAttribute("make-time","-1"));e>=0?(r=this.musicXmlDivisionsToAlphaTabTicks(e),a=R.BeforeBeat):a=R.OnBeat,"yes"===t.getAttribute("slash")&&(a=R.BeforeBeat);break;case"chord":o=!0;break;case"cue":return;case"pitch":f=this.parsePitch(t),y=!0;break;case"unpitched":f=this.parseUnpitched(t,s);break;case"rest":f=null,null===d&&(d=D.Whole);break;case"duration":c=this.parseDuration(t);break;case"instrument":null===f?wt.warning("MusicXML","Malformed MusicXML, missing pitch or unpitched for note"):b=t.getAttribute("id","");break;case"voice":l=Number.parseInt(t.innerText),Number.isNaN(l)?(wt.warning("MusicXML","Voices need to be specified as numbers"),l=0):l-=1;break;case"type":d=this.parseBeatDuration(t);break;case"dot":u++;break;case"accidental":null===f?wt.warning("MusicXML","Malformed MusicXML, missing pitch or unpitched for note"):this.parseAccidental(t,f);break;case"time-modification":for(const e of t.childElements())switch(e.localName){case"actual-notes":p=Number.parseInt(e.innerText);break;case"normal-notes":g=Number.parseInt(e.innerText)}break;case"stem":m=this.parseStem(t);break;case"notehead":null===f?wt.warning("MusicXML","Malformed MusicXML, missing pitch or unpitched for note"):this.parseNoteHead(t,f,d??D.Quarter,m??this.estimateBeamDirection(f));break;case"staff":h=Number.parseInt(t.innerText)-1;break;case"beam":if("1"===t.getAttribute("number","1"))switch(t.innerText){case"begin":case"continue":n=cs.ForceMergeWithNext;break;case"end":n=cs.ForceSplitToNext}break;case"notations":_(),this.parseNotations(t,f,i);break;case"lyric":_(),this.parseLyric(t,i,s)}if(y){const e=this.getOrCreateStaff(s,h),t=this.getStaffContext(e).transpose;if(0!==t){const e=12*f.octave+f.tone+t;f.octave=e/12|0,f.tone=e-12*f.octave}}_()}estimateBeamDirection(e){return e.calculateRealValue(!1,!1)<Mi.B4Value?se.Down:se.Up}parseNoteHead(e,t,s,i){"yes"===e.getAttribute("parentheses","no")&&(t.isGhost=!0);const a=e.getAttribute("filled","");let r;switch("yes"===a?r=!0:"no"===a&&(r=!1),t.style=new Tt,e.innerText){case"arrow down":t.style.noteHeadCenterOnStem=!0,this.applyNoteHead(t,s,r,G.NoteheadTriangleDownDoubleWhole,G.NoteheadTriangleDownWhole,G.NoteheadTriangleDownHalf,G.NoteheadTriangleDownBlack);break;case"arrow up":t.style.noteHeadCenterOnStem=!0,this.applyNoteHead(t,s,r,G.NoteheadTriangleUpDoubleWhole,G.NoteheadTriangleUpWhole,G.NoteheadTriangleUpHalf,G.NoteheadTriangleUpBlack);break;case"back slashed":this.applyNoteHead(t,s,r,G.NoteheadSlashedDoubleWhole2,G.NoteheadSlashedWhole2,G.NoteheadSlashedHalf2,G.NoteheadSlashedBlack2);break;case"circle dot":t.style.noteHead=G.NoteheadRoundWhiteWithDot;break;case"circle-x":this.applyNoteHead(t,s,r,G.NoteheadCircleXDoubleWhole,G.NoteheadCircleXWhole,G.NoteheadCircleXHalf,G.NoteheadCircleX);break;case"circled":this.applyNoteHead(t,s,r,G.NoteheadCircledDoubleWhole,G.NoteheadCircledWhole,G.NoteheadCircledHalf,G.NoteheadCircledBlack);break;case"cluster":this.applyNoteHead(t,s,r,G.NoteheadClusterDoubleWhole3rd,G.NoteheadClusterWhole3rd,G.NoteheadClusterHalf3rd,G.NoteheadClusterQuarter3rd);break;case"cross":this.applyNoteHead(t,s,r,G.NoteheadPlusDoubleWhole,G.NoteheadPlusWhole,G.NoteheadPlusHalf,G.NoteheadPlusBlack);break;case"diamond":this.applyNoteHead(t,s,r,G.NoteheadDiamondDoubleWhole,G.NoteheadDiamondWhole,G.NoteheadDiamondHalf,G.NoteheadDiamondBlack);break;case"do":this.applyNoteHead(t,s,r,G.NoteShapeTriangleUpWhite,G.NoteShapeTriangleUpWhite,G.NoteShapeTriangleUpWhite,G.NoteShapeTriangleUpBlack);break;case"fa":i===se.Up?this.applyNoteHead(t,s,r,G.NoteShapeTriangleRightWhite,G.NoteShapeTriangleRightWhite,G.NoteShapeTriangleRightWhite,G.NoteShapeTriangleRightBlack):this.applyNoteHead(t,s,r,G.NoteShapeTriangleLeftWhite,G.NoteShapeTriangleLeftWhite,G.NoteShapeTriangleLeftWhite,G.NoteShapeTriangleLeftBlack);break;case"fa up":this.applyNoteHead(t,s,r,G.NoteShapeTriangleLeftWhite,G.NoteShapeTriangleLeftWhite,G.NoteShapeTriangleLeftWhite,G.NoteShapeTriangleLeftBlack);break;case"inverted triangle":this.applyNoteHead(t,s,r,G.NoteheadTriangleDownDoubleWhole,G.NoteheadTriangleDownWhole,G.NoteheadTriangleDownHalf,G.NoteheadTriangleDownBlack);break;case"la":case"square":this.applyNoteHead(t,s,r,G.NoteShapeSquareWhite,G.NoteShapeSquareWhite,G.NoteShapeSquareWhite,G.NoteShapeSquareBlack);break;case"left triangle":this.applyNoteHead(t,s,r,G.NoteheadTriangleRightWhite,G.NoteheadTriangleRightWhite,G.NoteheadTriangleRightWhite,G.NoteheadTriangleRightBlack);break;case"mi":this.applyNoteHead(t,s,r,G.NoteShapeDiamondWhite,G.NoteShapeDiamondWhite,G.NoteShapeDiamondWhite,G.NoteShapeDiamondBlack);break;case"none":t.style.noteHead=G.NoteheadNull;break;case"normal":this.applyNoteHead(t,s,r,G.NoteheadDoubleWhole,G.NoteheadWhole,G.NoteheadHalf,G.NoteheadBlack);break;case"re":this.applyNoteHead(t,s,r,G.NoteShapeMoonWhite,G.NoteShapeMoonWhite,G.NoteShapeMoonWhite,G.NoteShapeMoonBlack);break;case"rectangle":this.applyNoteHead(t,s,r,G.NoteheadSquareWhite,G.NoteheadSquareWhite,G.NoteheadSquareWhite,G.NoteheadSquareBlack);break;case"slash":this.applyNoteHead(t,s,r,G.NoteheadSlashWhiteWhole,G.NoteheadSlashWhiteWhole,G.NoteheadSlashWhiteHalf,G.NoteheadSlashVerticalEnds);break;case"slashed":this.applyNoteHead(t,s,r,G.NoteheadSlashedDoubleWhole1,G.NoteheadSlashedWhole1,G.NoteheadSlashedHalf1,G.NoteheadSlashedBlack1);break;case"so":this.applyNoteHead(t,s,r,G.NoteShapeRoundWhite,G.NoteShapeRoundWhite,G.NoteShapeRoundWhite,G.NoteShapeRoundBlack);break;case"ti":this.applyNoteHead(t,s,r,G.NoteShapeTriangleRoundWhite,G.NoteShapeTriangleRoundWhite,G.NoteShapeTriangleRoundWhite,G.NoteShapeTriangleRoundBlack);break;case"triangle":this.applyNoteHead(t,s,r,G.NoteheadTriangleUpDoubleWhole,G.NoteheadTriangleUpWhole,G.NoteheadTriangleUpHalf,G.NoteheadTriangleUpBlack);break;case"x":this.applyNoteHead(t,s,r,G.NoteheadXDoubleWhole,G.NoteheadXWhole,G.NoteheadXHalf,G.NoteheadXBlack)}}createRestForGap(e,t){let s=rs.toTicks(t);for(;s>e;){if(t===D.TwoHundredFiftySixth)return null;t*=2,s=rs.toTicks(t)}const i=new gs;return i.dynamics=this._currentDynamics,i.isEmpty=!1,i.duration=t,i.overrideDisplayDuration=s,i.updateDurations(),i}insertBeatToVoice(e,t){if(t.beats.length>0){const s=t.beats[t.beats.length-1];s.nextBeat=e,e.previousBeat=s;let i=s;for(;null!==i&&i.graceType!==R.None;)i=i.index>0?i.previousBeat:null;null!==i&&(e.displayStart=i.displayEnd)}t.addBeat(e)}musicXmlDivisionsToAlphaTabTicks(e){return e*rs.QuarterTime/this._divisionsPerQuarterNote}parseBeatDuration(e){switch(e.innerText){case"1024th":case"512th":case"256th":return D.TwoHundredFiftySixth;case"128th":return D.OneHundredTwentyEighth;case"64th":return D.SixtyFourth;case"32nd":return D.ThirtySecond;case"16th":return D.Sixteenth;case"eighth":return D.Eighth;case"quarter":return D.Quarter;case"half":return D.Half;case"whole":return D.Whole;case"breve":return D.DoubleWhole;case"long":return D.QuadrupleWhole}return null}applyBeatDurationFromTicks(e,t,s,i){if(!s)for(let e=0;e<Mi.allDurations.length;e++){if(!(t>=Mi.allDurationTicks[e]))break;s=Mi.allDurations[e]}e.duration=s??D.Sixteenth,i&&(e.overrideDisplayDuration=t),e.updateDurations()}parseLyric(e,t,s){const i=this._indexToTrackInfo.get(s.index).getLyricLine(e.getAttribute("number",""));for(null===t.lyrics&&(t.lyrics=[]);t.lyrics.length<=i;)t.lyrics.push("");for(const s of e.childElements())switch(s.localName){case"text":t.lyrics[i]?t.lyrics[i]+=` ${s.innerText}`:t.lyrics[i]=s.innerText;break;case"elision":t.lyrics[i]+=s.innerText}}parseNotations(e,t,s){for(const i of e.childElements())switch(i.localName){case"tied":t&&this.parseTied(i,t,s.voice.bar.staff);break;case"slur":t&&this.parseSlur(i,t);break;case"glissando":t&&this.parseGlissando(i,t);break;case"slide":t&&this.parseSlide(i,t);break;case"ornaments":t&&this.parseOrnaments(i,t);break;case"technical":this.parseTechnical(i,t,s);break;case"articulations":t&&this.parseArticulations(i,t);break;case"dynamics":const e=this.parseDynamics(i);null!==e&&(s.dynamics=e,this._currentDynamics=e);break;case"fermata":this.parseFermata(i,s);break;case"arpeggiate":this.parseArpeggiate(i,s)}}getStaffContext(e){if(!this._staffToContext.has(e)){const t=new Di;return this._staffToContext.set(e,t),t}return this._staffToContext.get(e)}parseGlissando(e,t){const s=e.getAttribute("type"),i=e.getAttribute("number","1"),a=this.getStaffContext(t.beat.voice.bar.staff);switch(s){case"start":a.slideOrigins.set(i,t);break;case"stop":if(a.slideOrigins.has(i)){const e=a.slideOrigins.get(i);e.slideTarget=t,t.slideOrigin=e,e.slideOutType=K.Shift}}}parseSlur(e,t){const s=e.getAttribute("number","1"),i=this.getStaffContext(t.beat.voice.bar.staff);switch(e.getAttribute("type")){case"start":i.slurStarts.set(s,t);break;case"stop":if(i.slurStarts.has(s)){t.isSlurDestination=!0;const e=i.slurStarts.get(s);e.slurDestination=t,t.slurOrigin=e,i.slurStarts.delete(s)}}}parseArpeggiate(e,t){switch(e.getAttribute("direction","down")){case"down":t.brushType=b.ArpeggioDown;break;case"up":t.brushType=b.ArpeggioUp}}parseFermata(e,t){let s;switch(e.innerText){case"normal":default:s=M.Medium;break;case"angled":s=M.Short;break;case"square":s=M.Long}t.fermata=new Te,t.fermata.type=s}parseArticulations(e,t){for(const s of e.childElements())switch(s.localName){case"accent":t.accentuated=u.Normal;break;case"strong-accent":t.accentuated=u.Heavy;break;case"staccato":t.isStaccato=!0;break;case"tenuto":t.accentuated=u.Tenuto}}parseTechnical(e,t,s){const i=[];for(const a of e.childElements())switch(a.localName){case"up-bow":s.pickStroke=Q.Up;break;case"down-bow":s.pickStroke=Q.Down;break;case"harmonic":break;case"fingering":t&&(t.leftHandFinger=this.parseFingering(a));break;case"pluck":t&&(t.rightHandFinger=this.parseFingering(a));break;case"fret":t&&(t.fret=Number.parseInt(a.innerText));break;case"string":t&&(t.string=s.voice.bar.staff.tuning.length-Number.parseInt(a.innerText)+1);break;case"hammer-on":case"pull-off":t&&(t.isHammerPullOrigin=!0);break;case"bend":i.push(a);break;case"tap":s.tap=!0;break;case"smear":t&&(t.vibrato=j.Slight);break;case"golpe":switch(a.getAttribute("placement","above")){case"above":s.golpe=O.Finger;break;case"below":s.golpe=O.Thumb}}t&&i.length>0&&this.parseBends(i,t)}parseBends(e,t){const s=ge.MaxPosition/e.length;let i=0,a=0,r=!0;for(const n of e){const e=n.findChildElement("bend-alter");if(e){const o=Math.round(2*Math.abs(Number.parseFloat(e.innerText)));n.findChildElement("pre-bend")?r?(i+=o,t.addBendPoint(new ge(a,i)),a+=s,t.addBendPoint(new ge(a,i)),r=!1):a+=s:n.findChildElement("release")?(r&&(i+=o),t.addBendPoint(new ge(a,i)),a+=s,i-=o,t.addBendPoint(new ge(a,i)),r=!1):(t.addBendPoint(new ge(a,i)),i+=o,a+=s,t.addBendPoint(new ge(a,i)),r=!1)}}}parseFingering(e){switch(e.innerText){case"0":return _.NoOrDead;case"1":case"p":case"t":return _.Thumb;case"2":case"i":return _.IndexFinger;case"3":case"m":return _.MiddleFinger;case"4":case"a":return _.AnnularFinger;case"5":case"c":return _.LittleFinger}return _.Unknown}parseOrnaments(e,t){let s=-1;for(const i of e.childElements())switch(i.localName){case"trill-mark":s=Number.parseInt(i.getAttribute("trill-step","2")),t.isStringed?t.trillValue=t.stringTuning+s:t.isPercussion||(t.trillValue=t.calculateRealValue(!1,!1)+s);break;case"turn":t.ornament=Z.Turn;break;case"inverted-turn":t.ornament=Z.InvertedTurn;break;case"wavy-line":s>0?"start"===i.getAttribute("type")&&(this._currentTrillStep=s):this._currentTrillStep>0?"stop"===i.getAttribute("type")?this._currentTrillStep=-1:t.isStringed?t.trillValue=t.stringTuning+this._currentTrillStep:t.isPercussion||(t.trillValue=t.calculateRealValue(!1,!1)+this._currentTrillStep):t.vibrato=j.Slight;break;case"mordent":t.ornament=Z.LowerMordent;break;case"inverted-mordent":t.ornament=Z.UpperMordent;break;case"tremolo":switch(i.innerText){case"1":t.beat.tremoloSpeed=D.Eighth;break;case"2":t.beat.tremoloSpeed=D.Sixteenth;break;case"3":t.beat.tremoloSpeed=D.ThirtySecond}}}parseSlide(e,t){const s=e.getAttribute("type"),i=e.getAttribute("number","1"),a=this.getStaffContext(t.beat.voice.bar.staff);switch(s){case"start":a.slideOrigins.set(i,t);break;case"stop":if(a.slideOrigins.has(i)){const e=a.slideOrigins.get(i);e.slideTarget=t,t.slideOrigin=e,e.slideOutType=K.Shift}}}parseTied(e,t,s){const i=e.getAttribute("type"),a=e.getAttribute("number",""),r=this.getStaffContext(s);if("start"===i){if(a){if(r.tieStartIds.has(a)){const e=r.tieStartIds.get(a);r.tieStarts.delete(e)}r.tieStartIds.set(a,t)}r.tieStarts.add(t)}else if("stop"===i&&!t.isTieDestination){let e=null;if(a){if(!r.tieStartIds.has(a))return;e=r.tieStartIds.get(a),r.tieStartIds.delete(a),r.tieStarts.delete(t)}else{const s=this.calculatePitchedNoteValue(t);for(const t of r.tieStarts)if(this.calculatePitchedNoteValue(t)===s){e=t,r.tieStarts.delete(e);break}}if(!e)return;t.isTieDestination=!0,t.tieOrigin=e}}parseStem(e){switch(e.innerText){case"down":return se.Down;case"up":return se.Up;default:return null}}parseAccidental(e,t){switch(e.innerText){case"sharp":t.accidentalMode=N.ForceSharp;break;case"natural":t.accidentalMode=N.ForceNatural;break;case"flat":t.accidentalMode=N.ForceFlat;break;case"double-sharp":t.accidentalMode=N.ForceDoubleSharp;break;case"flat-flat":t.accidentalMode=N.ForceDoubleFlat}}calculatePitchedNoteValue(e){return 12*e.octave+e.tone}parseDuration(e){return this.musicXmlDivisionsToAlphaTabTicks(Number.parseFloat(e.innerText))}parseUnpitched(e,t){let s="",i=0;for(const t of e.childElements())switch(t.localName){case"display-step":s=t.innerText;break;case"display-octave":i=Number.parseInt(t.innerText)+1}const a=new Nt;if(""===s)a.octave=0,a.tone=0;else{const e=12*i+Be.getToneForText(s).noteValue;a.octave=e/12|0,a.tone=e-12*a.octave}return a}parsePitch(e){let t="",s=0,i=0;for(const a of e.childElements())switch(a.localName){case"step":t=a.innerText;break;case"alter":s=Number.parseFloat(a.innerText),Number.isNaN(s)&&(s=0);break;case"octave":i=Number.parseInt(a.innerText)+1}s|=0;const a=12*i+Be.getToneForText(t).noteValue+s,r=new Nt;return r.octave=a/12|0,r.tone=a-12*r.octave,r}applyNoteHead(e,t,s,i,a,r,n){if(void 0===s)switch(t){case D.QuadrupleWhole:case D.DoubleWhole:e.style.noteHead=i;break;case D.Whole:e.style.noteHead=a;break;case D.Half:e.style.noteHead=r;break;default:e.style.noteHead=n}else if(!0===s)e.style.noteHead=n;else switch(t){case D.QuadrupleWhole:case D.DoubleWhole:e.style.noteHead=i;break;case D.Whole:e.style.noteHead=a;break;case D.Half:default:e.style.noteHead=r}}}Mi.B4Value=71,Mi.allDurations=[D.TwoHundredFiftySixth,D.OneHundredTwentyEighth,D.SixtyFourth,D.ThirtySecond,D.Sixteenth,D.Eighth,D.Quarter,D.Half,D.Whole,D.DoubleWhole,D.QuadrupleWhole],Mi.allDurationTicks=Mi.allDurations.map((e=>rs.toTicks(e)));class Ii{constructor(e,t){this.time=0,this.eventIndex=e,this.event=t,this.isMetronome=this.event.type===U.AlphaTabMetronome}static newMetronomeEvent(e,t,s,i,a){const r=new We(0,t,s,i,a);return new Ii(e,r)}}class Ai{constructor(e,t,s){this.bpm=e,this.ticks=t,this.time=s}}class Ri{constructor(){this.tempoChanges=[],this.firstProgramEventPerChannel=new Map,this.firstTimeSignatureNumerator=0,this.firstTimeSignatureDenominator=0,this.synthData=[],this.division=rs.QuarterTime,this.eventIndex=0,this.currentTime=0,this.playbackRange=null,this.playbackRangeStartTime=0,this.playbackRangeEndTime=0,this.endTick=0,this.endTime=0}}class Oi{get isPlayingMain(){return this._currentState===this._mainState}get isPlayingOneTimeMidi(){return this._currentState===this._oneTimeState}get isPlayingCountIn(){return this._currentState===this._countInState}constructor(e){this._oneTimeState=null,this._countInState=null,this.isLooping=!1,this.playbackSpeed=1,this.instrumentPrograms=new Set,this.percussionKeys=new Set,this._synthesizer=e,this._mainState=new Ri,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){const e=this._synthesizer.metronomeVolume;this._synthesizer.noteOffAll(!0),this._synthesizer.resetSoft(),this._synthesizer.setupMetronomeChannel(e)}this.mainSilentProcess(e)}}mainSilentProcess(e){if(e<=0)return;const t=Date.now(),s=this._mainState.currentTime+e;if(this.isPlayingMain)for(;this._mainState.currentTime<s;)this.fillMidiEventQueueLimited(s-this._mainState.currentTime)&&this._synthesizer.synthesizeSilent(Ls.MicroBufferSize);this._mainState.currentTime=s;const i=Date.now()-t;wt.debug("Sequencer",`Silent seek finished in ${i}ms (main)`)}loadOneTimeMidi(e){this._oneTimeState=this.createStateFromFile(e),this._currentState=this._oneTimeState}loadMidi(e){this.instrumentPrograms.clear(),this.percussionKeys.clear(),this._mainState=this.createStateFromFile(e),this._currentState=this._mainState}createStateFromFile(e){const t=new Ri;this.percussionKeys.add(Ls.MetronomeKey),t.tempoChanges=[],t.division=e.division,t.eventIndex=0,t.currentTime=0,t.synthData=[];let s=120,i=0,a=0,r=0,n=0,o=0,h=0,l=0,c=0;for(const d of e.events){const u=new Ii(t.synthData.length,d);t.synthData.push(u);const p=d.tick-c;if(i+=p,a+=p*(6e4/(s*e.division)),u.time=a,c=d.tick,n>0)for(;h<i;){const e=Ii.newMetronomeEvent(t.synthData.length,h,Math.floor(h/n)%r,n,o);t.synthData.push(e),e.time=l,h+=n,l+=o}if(d.type===U.TempoChange){s=6e7/d.microSecondsPerQuarterNote,t.tempoChanges.push(new Ai(s,i,a)),o=n*(6e4/(s*e.division))}else if(d.type===U.TimeSignature){const i=d,a=Math.pow(2,i.denominatorIndex);r=i.numerator,n=t.division*(4/a)|0,o=n*(6e4/(s*e.division)),0===t.firstTimeSignatureDenominator&&(t.firstTimeSignatureNumerator=i.numerator,t.firstTimeSignatureDenominator=a)}else if(d.type===U.ProgramChange){const e=d,s=e.channel;t.firstProgramEventPerChannel.has(s)||t.firstProgramEventPerChannel.set(s,u);s===Ls.PercussionChannel||this.instrumentPrograms.add(e.program)}else if(d.type===U.NoteOn){const e=d;e.channel===Ls.PercussionChannel&&this.percussionKeys.add(e.noteKey)}}return t.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),t.endTime=a,t.endTick=i,t}fillMidiEventQueue(){return this.fillMidiEventQueueLimited(-1)}fillMidiEventQueueLimited(e){let t=Ls.MicroBufferSize/this._synthesizer.outSampleRate*1e3*this.playbackSpeed,s=this.internalEndTime;e>0&&(e<t&&(t=e),s=Math.min(this.internalEndTime,this._currentState.currentTime+e));let i=!1;for(this._currentState.currentTime+=t;this._currentState.eventIndex<this._currentState.synthData.length&&this._currentState.synthData[this._currentState.eventIndex].time<this._currentState.currentTime&&this._currentState.currentTime<s;)this._synthesizer.dispatchEvent(this._currentState.synthData[this._currentState.eventIndex]),this._currentState.eventIndex++,i=!0;return i}mainTickPositionToTimePosition(e){return this.tickPositionToTimePositionWithSpeed(this._mainState,e,this.playbackSpeed)}mainTimePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(this._mainState,e,this.playbackSpeed)}currentTimePositionToTickPosition(e){return this.timePositionToTickPositionWithSpeed(this._currentState,e,this.playbackSpeed)}tickPositionToTimePositionWithSpeed(e,t,s){let i=0,a=120,r=0;for(const s of e.tempoChanges){if(t<s.ticks)break;i=s.time,a=s.bpm,r=s.ticks}return i+=(t-=r)*(6e4/(a*e.division)),i/s}timePositionToTickPositionWithSpeed(e,t,s){t*=s;let i=0,a=120,r=0;for(const s of e.tempoChanges){if(t<s.time)break;i=s.ticks,a=s.bpm,r=s.time}return i+=(t-=r)/(6e4/(a*e.division))|0,i+1}get internalEndTime(){return this.isPlayingMain&&this.mainPlaybackRange?this._currentState.playbackRangeEndTime:this._currentState.endTime}get isFinished(){return this._currentState.currentTime>=this.internalEndTime}stop(){this.isPlayingMain&&this.mainPlaybackRange?this._currentState.currentTime=this.mainPlaybackRange.startTick:this._currentState.currentTime=0,this._currentState.eventIndex=0}resetOneTimeMidi(){this._oneTimeState=null,this._currentState=this._mainState}resetCountIn(){this._countInState=null,this._currentState=this._mainState}startCountIn(){this.generateCountInMidi(),this._currentState=this._countInState,this.stop(),this._synthesizer.noteOffAll(!0)}generateCountInMidi(){const e=new Ri;e.division=this._mainState.division;let t=120,s=4,i=4;0===this._mainState.eventIndex?(t=this._mainState.tempoChanges[0].bpm,s=this._mainState.firstTimeSignatureNumerator,i=this._mainState.firstTimeSignatureDenominator):(t=this._synthesizer.currentTempo,s=this._synthesizer.timeSignatureNumerator,i=this._synthesizer.timeSignatureDenominator),e.tempoChanges.push(new Ai(t,0,0));const a=e.division*(4/i)|0,r=a*(6e4/(t*this._mainState.division));let n=0,o=0;for(let t=0;t<s;t++){const s=Ii.newMetronomeEvent(e.synthData.length,n,t,a,r);e.synthData.push(s),s.time=o,n+=a,o+=r}e.synthData.sort(((e,t)=>e.time>t.time?1:e.time<t.time?-1:e.eventIndex-t.eventIndex)),e.endTime=o,e.endTick=n,this._countInState=e}}var Hi,Wi,Vi,Gi,zi,Ui,Xi,Ji,Yi,$i,qi,Ki,ji,Qi,Zi,ea,ta,sa;!function(e){e[e.Paused=0]="Paused",e[e.Playing=1]="Playing"}(Hi||(Hi={}));class ia{constructor(e,t){this.state=e,this.stopped=t}}class aa{constructor(e,t,s,i,a){this.currentTime=e,this.endTime=t,this.currentTick=s,this.endTick=i,this.isSeek=a}}class ra{constructor(){this.id="",this.size=0}static load(e,t,s){if(e&&ra.HeaderSize>e.size)return!1;if(s.position+ra.HeaderSize>=s.length)return!1;if(t.id=Le.read8BitStringLength(s,4),t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)return!1;if(t.size=Le.readUInt32LE(s),e&&ra.HeaderSize+t.size>e.size)return!1;e&&(e.size-=ra.HeaderSize+t.size);const i="RIFF"===t.id,a="LIST"===t.id;return(!i||!e)&&(!i&&!a||(t.id=Le.read8BitStringLength(s,4),!(t.id.charCodeAt(0)<=32||t.id.charCodeAt(0)>=122)&&(t.size-=4,!0)))}}ra.HeaderSize=8;class na{constructor(e,t,s,i){this.packetData=e,this.isBeginningOfStream=t,this.isEndOfStream=s,this.granulePosition=s?i:null}addData(e){const t=this.packetData,s=new Uint8Array(t.length+e.length);s.set(t,0),s.set(e,t.length)}}!function(e){e[e.ContinuesPacket=1]="ContinuesPacket",e[e.BeginningOfStream=2]="BeginningOfStream",e[e.EndOfStream=4]="EndOfStream"}(Wi||(Wi={}));class oa{constructor(e){this._readable=e}read(){const e=[];for(;this.findAndReadPage(e););return e}findAndReadPage(e){return!!this.seekPageHeader()&&this.readPage(e)}seekPageHeader(){for(let e=0;e<65536;e++){if(1399285583===Le.readInt32LE(this._readable))return!0;this._readable.position-=3}return!1}readPage(e){const t=this._readable.readByte();if(-1===t||0!==t)return!1;const s=this._readable.readByte(),i=Le.readInt64LE(this._readable);this._readable.skip(4),this._readable.skip(4),this._readable.skip(4);const a=this._readable.readByte();if(-1===a)return!1;const r=[];let n=0;for(let e=0;e<a;e++){const e=this._readable.readByte();n===r.length&&r.push(0),r[n]+=e,e<255&&n++}for(let t=0;t<r.length;t++){const a=new Uint8Array(r[t]);if(this._readable.read(a,0,a.length)!==a.length)return!1;if(s&Wi.ContinuesPacket){if(0===e.length)throw new fe(S.Format,"OGG: Continuation page without any previous packets");e[e.length-1].addData(a)}else{const n=new na(a,!!(s&Wi.BeginningOfStream)&&0===t,!!(s&Wi.EndOfStream)&&t===r.length-1,i);e.push(n)}}return!0}}class ha{constructor(){this.audioChannels=0,this.audioSampleRate=0,this.samples=new Float32Array(0),this.bitrateMaximum=0,this.bitrateNominal=0,this.bitrateMinimum=0,this.blocksize0=0,this.blocksize1=0}}class la{constructor(){this.value=0,this.bitsRead=0}}class ca{constructor(e){this._bitBucket=0n,this._bitCount=0n,this._overflowBits=0n,this._source=e}readByte(){return this.readBits(ca.ByteSize)}readBit(){return 1===this.readBits(1)}readBytes(e){const t=new Uint8Array(e);for(let s=0;s<e;s++)t[s]=255&this.readByte();return t}readBits(e){if(0===e)return 0;const t=this.tryPeekBits(e);return this.skipBits(e),t.value}tryPeekBits(e){if(e<0||e>32)throw new fe(S.General,"IO: Cannot read more than 32 bits in one go");if(0===e)return new la;const t=new la;for(;this._bitCount<e;){const e=BigInt(this._source.readByte());if(-1n===e)return t.bitsRead=Number(this._bitCount),t.value=Number(this._bitBucket),this._bitBucket=0n,this._bitCount=0n,t;this._bitBucket=(0xffn&e)<<this._bitCount|this._bitBucket,this._bitCount+=8n,this._bitCount>32&&(this._overflowBits=e>>40n-this._bitCount&0xffn)}let s=this._bitBucket;return e<64&&(s&=(1n<<BigInt(e))-1n),t.value=Number(s),t.bitsRead=e,t}skipBits(e){let t=BigInt(e);if(0===e);else if(this._bitCount>t){if(this._bitBucket=e>31?0n:this._bitBucket>>t,this._bitCount>32){const s=this._bitCount-32n;this._bitBucket=this._bitBucket|this._overflowBits<<this._bitCount-t-s,s>e&&(this._overflowBits=this._overflowBits>>t&0xffn)}this._bitCount-=t}else if(this._bitCount===t)this._bitBucket=0n,this._bitCount=0n;else{for(t-=this._bitCount,this._bitCount=0n,this._bitBucket=0n;t>8;){if(-1===this._source.readByte()){t=0n;break}t-=8n}if(t>0){const e=BigInt(this._source.readByte());-1n===e||(this._bitBucket=e>>t,this._bitCount=8n-t)}}}}ca.ByteSize=8;class da{constructor(){this.codebooks=[],this.timeDomainTransforms=[],this.floors=[],this.residues=[],this.mappings=[],this.modes=[]}}class ua{static ilog(e){let t=0;for(;e>0;)++t,e>>=1;return t}static bitReverse(e,t=32){let s=BigInt(e);s=(s&BigInt(2863311530))>>1n|(s&BigInt(1431655765))<<1n,s=(s&BigInt(3435973836))>>2n|(s&BigInt(858993459))<<2n,s=(s&BigInt(4042322160))>>4n|(s&BigInt(252645135))<<4n,s=(s&BigInt(4278255360))>>8n|(s&BigInt(16711935))<<8n,s=(s>>16n|s<<16n)>>32n-BigInt(t);return Number(BigInt.asUintN(32,s))}static convertFromVorbisFloat32(e){const t=BigInt(e);let s=t&BigInt(2097151);const i=t&BigInt(2147483648),a=(t&BigInt(2145386496))>>21n;return 0n!==i&&(s=-s),Number(s)*Math.pow(2,Number(a)-788)}}class pa{constructor(e){this._data=e}get(e){return this._data[e]}}class ga{get(e){return e}}ga.instance=new ga;class ma{constructor(e,t){this._maxBits=0,this._overflowList=null,this._prefixList=null,this._prefixBitLength=0,this.dimensions=0,this.entries=0,this.mapType=0;if(5653314!==e.readBits(24))throw new fe(S.Format,"Vorbis: Book header had invalid signature!");this.dimensions=e.readBits(16),this.entries=e.readBits(24),this._lengths=new Int32Array(this.entries),this.initTree(e,t),this.initLookupTable(e)}get(e,t){return this._lookupTable[e*this.dimensions+t]}decodeScalar(e){let t=e.tryPeekBits(this._prefixBitLength);if(0===t.bitsRead)return-1;let s=this._prefixList[t.value];if(null!=s)return e.skipBits(s.length),s.value;if(t=e.tryPeekBits(this._maxBits),null!==this._overflowList)for(let i=0;i<this._overflowList.length;i++){s=this._overflowList[i];const a=t.value&s.mask;if(s.bits===a)return e.skipBits(s.length),s.value}return-1}initTree(e,t){let s,i,a=0;if(e.readBit()){let t=e.readBits(5)+1;for(let s=0;s<this.entries;){let i=e.readBits(ua.ilog(this.entries-s));for(;--i>=0;)this._lengths[s++]=t;++t}a=0,s=!1,i=t}else{i=-1,s=e.readBit();for(let t=0;t<this.entries;t++)!s||e.readBit()?(this._lengths[t]=e.readBits(5)+1,++a):this._lengths[t]=-1,this._lengths[t]>i&&(i=this._lengths[t])}if(this._maxBits=i,i>-1){let e,i=null;s&&a>=this.entries>>2&&(i=new Int32Array(this.entries),i.set(this._lengths.subarray(0,this.entries),0),s=!1),e=s?a:0;let r=null,n=null;if(s?0!==e&&(i=new Int32Array(e),n=new Int32Array(e),r=new Int32Array(e)):n=new Int32Array(this.entries),!this.computeCodewords(s,n,i,this._lengths,this.entries,r))throw new fe(S.Format,"Vorbis: Failed to compute codewords");const o=null==r?ga.instance:new pa(r);t.generateTable(o,i??this._lengths,n),this._prefixList=t.prefixTree,this._prefixBitLength=t.tableBits,this._overflowList=t.overflowList}}computeCodewords(e,t,s,i,a,r){const n=new Uint32Array(32);let o=0,h=0;for(o=0;o<a&&!(i[o]>0);++o);if(o===a)return!0;this.addEntry(e,t,s,0,o,h++,i[o],r);for(let e=1;e<=i[o];++e)n[e]=1<<32-e;for(let l=o+1;l<a;++l){let a=i[l];if(a<=0)continue;for(;a>0&&0===n[a];)--a;if(0===a)return!1;const o=n[a];if(n[a]=0,this.addEntry(e,t,s,ua.bitReverse(o),l,h++,i[l],r),a!==i[l])for(let e=i[l];e>a;--e)n[e]=o+(1<<32-e)}return!0}addEntry(e,t,s,i,a,r,n,o){e?(t[r]=i,s[r]=n,o[r]=a):t[a]=i}initLookupTable(e){if(this.mapType=e.readBits(4),0===this.mapType)return;const t=ua.convertFromVorbisFloat32(e.readBits(32)),s=ua.convertFromVorbisFloat32(e.readBits(32)),i=e.readBits(4)+1,a=e.readBit();let r=this.entries*this.dimensions;const n=new Float32Array(r);1===this.mapType&&(r=this.lookup1Values());const o=new Uint32Array(r);for(let t=0;t<r;t++)o[t]=e.readBits(i);if(1===this.mapType)for(let e=0;e<this.entries;e++){let i=0,h=1;for(let l=0;l<this.dimensions;l++){const c=o[e/h%r|0]*s+t+i;n[e*this.dimensions+l]=c,a&&(i=c),h*=r}}else for(let e=0;e<this.entries;e++){let i=0,r=e*this.dimensions;for(let h=0;h<this.dimensions;h++){const l=o[r]*s+t+i;n[e*this.dimensions+h]=l,a&&(i=l),++r}}this._lookupTable=n}lookup1Values(){let e=Math.floor(Math.exp(Math.log(this.entries)/this.dimensions));return Math.floor(Math.pow(e+1,this.dimensions))<=this.entries&&++e,e}}class fa{constructor(){this.value=0,this.length=0,this.bits=0,this.mask=0}}class ya{constructor(){this.tableBits=0,this.prefixTree=[],this.overflowList=null}generateTable(e,t,s){const i=new Array(t.length);let a=0;for(let r=0;r<i.length;r++){const n=new fa;n.value=e.get(r),n.length=t[r]<=0?99999:t[r],n.bits=s[r],n.mask=(1<<t[r])-1,i[r]=n,t[r]>0&&a<t[r]&&(a=t[r])}i.sort(((e,t)=>{const s=e.length-t.length;return 0===s?e.bits-t.bits:s}));const r=a>ya.MAX_TABLE_BITS?ya.MAX_TABLE_BITS:a,n=[];let o=null;for(let e=0;e<i.length&&i[e].length<99999;e++){const t=i[e].length;if(t>r)for(o=[];e<i.length&&i[e].length<99999;e++)o.push(i[e]);else{const s=1<<r-t,a=i[e];for(let e=0;e<s;e++){const s=e<<t|a.bits;for(;n.length<=s;)n.push(null);n[s]=a}}}for(;n.length<1<<r;)n.push(null);this.tableBits=r,this.prefixTree=n,this.overflowList=o}}ya.MAX_TABLE_BITS=10;class ba{constructor(e){e.readBits(16)}}class Sa{get executeChannel(){return(this.forceEnergy||this.amp>0)&&!this.forceNoEnergy}constructor(e){this.amp=0,this.forceEnergy=!1,this.forceNoEnergy=!1,this.coeff=e}}class _a{constructor(e,t,s,i){if(this._order=e.readBits(8),this._rate=e.readBits(16),this._bark_map_size=e.readBits(16),this._ampBits=e.readBits(6),this._ampOfs=e.readBits(8),this._books=new Array(e.readBits(4)+1),this._order<1||this._rate<1||this._bark_map_size<1||0===this._books.length)throw new fe(S.Format,"Vorbis: Invalid Floor0 Data");this._ampDiv=(1<<this._ampBits)-1;for(let t=0;t<this._books.length;t++){const s=e.readBits(8);if(s<0||s>=i.length)throw new fe(S.Format,"Vorbis: Invalid Floor0 Data");const a=i[s];if(0===a.mapType||a.dimensions<1)throw new fe(S.Format,"Vorbis: Invalid Floor0 Data");this._books[t]=a}this._bookBits=ua.ilog(this._books.length),this._barkMaps=new Map([[t,this.synthesizeBarkCurve(t/2)],[s,this.synthesizeBarkCurve(s/2)]]),this._wMap=new Map([[t,this.synthesizeWDelMap(t/2)],[s,this.synthesizeWDelMap(s/2)]])}synthesizeBarkCurve(e){const t=this._bark_map_size/_a.toBARK(this._rate/2),s=new Int32Array(e+1);for(let i=0;i<e-1;i++)s[i]=Math.min(this._bark_map_size-1,Math.floor(_a.toBARK(this._rate/2/e*i)*t));return s[e]=-1,s}static toBARK(e){return 13.1*Math.atan(74e-5*e)+2.24*Math.atan(1.85e-8*e*e)+1e-4*e}synthesizeWDelMap(e){const t=Math.PI/this._bark_map_size,s=new Float32Array(e);for(let i=0;i<e;i++)s[i]=2*Math.cos(t*i);return s}unpack(e,t,s){const i=new Sa(new Float32Array(this._order+1));if(i.amp=e.readBits(this._ampBits),i.amp>0){i.amp=i.amp/this._ampDiv*this._ampOfs;const t=e.readBits(this._bookBits);if(t>=this._books.length)return i.amp=0,i;const s=this._books[t];for(let t=0;t<this._order;){const a=s.decodeScalar(e);if(-1===a)return i.amp=0,i;for(let e=0;t<this._order&&e<s.dimensions;e++,t++)i.coeff[t]=s.get(a,e)}let a=0;for(let e=0;e<this._order;){for(let t=0;e<this._order&&t<s.dimensions;e++,t++)i.coeff[e]+=a;a=i.coeff[e-1]}}return i}apply(e,t,s){const i=e,a=t/2;if(i.amp>0){const e=this._barkMaps.get(t),r=this._wMap.get(t);let n=0;for(n=0;n<this._order;n++)i.coeff[n]=2*Math.cos(i.coeff[n]);for(n=0;n<a;){let t=0;const a=e[n];let o=.5,h=.5;const l=r[a];for(t=1;t<this._order;t+=2)h*=l-i.coeff[t-1],o*=l-i.coeff[t];for(t===this._order?(h*=l-i.coeff[t-1],o*=o*(4-l*l),h*=h):(o*=o*(2-l),h*=h*(2+l)),h=i.amp/Math.sqrt(o+h)-this._ampOfs,h=Math.exp(.11512925*h),s[n]*=h;e[++n]===a;)s[n]*=h}}else s.fill(0,0,a)}}class wa{constructor(){this.posts=new Int32Array(64),this.postCount=0,this.forceEnergy=!1,this.forceNoEnergy=!1}get executeChannel(){return(this.forceEnergy||this.postCount>0)&&!this.forceNoEnergy}}class Ba{constructor(e,t){let s=-1;this._partitionClass=new Int32Array(e.readBits(5));for(let t=0;t<this._partitionClass.length;t++)this._partitionClass[t]=e.readBits(4),this._partitionClass[t]>s&&(s=this._partitionClass[t]);++s,this._classDimensions=new Int32Array(s),this._classSubclasses=new Int32Array(s),this._classMasterbooks=new Array(s),this._classMasterBookIndex=new Int32Array(s),this._subclassBooks=new Array(s),this._subclassBookIndex=new Array(s);for(let i=0;i<s;i++){this._classDimensions[i]=e.readBits(3)+1,this._classSubclasses[i]=e.readBits(2),this._classSubclasses[i]>0&&(this._classMasterBookIndex[i]=e.readBits(8),this._classMasterbooks[i]=t[this._classMasterBookIndex[i]]),this._subclassBooks[i]=new Array(1<<this._classSubclasses[i]),this._subclassBookIndex[i]=new Int32Array(this._subclassBooks[i].length);for(let s=0;s<this._subclassBooks[i].length;s++){const a=e.readBits(8)-1;a>=0&&(this._subclassBooks[i][s]=t[a]),this._subclassBookIndex[i][s]=a}}this._multiplier=e.readBits(2),this._range=Ba._rangeLookup[this._multiplier],this._yBits=Ba._yBitsLookup[this._multiplier],++this._multiplier;const i=e.readBits(4),a=[];a.push(0),a.push(1<<i);for(let t=0;t<this._partitionClass.length;t++){const s=this._partitionClass[t];for(let t=0;t<this._classDimensions[s];t++)a.push(e.readBits(i))}this._xList=new Int32Array(a),this._lNeigh=new Int32Array(a.length),this._hNeigh=new Int32Array(a.length),this._sortIdx=new Int32Array(a.length),this._sortIdx[0]=0,this._sortIdx[1]=1;for(let e=2;e<this._lNeigh.length;e++){this._lNeigh[e]=0,this._hNeigh[e]=1,this._sortIdx[e]=e;for(let t=2;t<e;t++){const s=this._xList[t];s<this._xList[e]?s>this._xList[this._lNeigh[e]]&&(this._lNeigh[e]=t):s<this._xList[this._hNeigh[e]]&&(this._hNeigh[e]=t)}}for(let e=0;e<this._sortIdx.length-1;e++)for(let t=e+1;t<this._sortIdx.length;t++){if(this._xList[e]===this._xList[t])throw new fe(S.Format,"Vorbis: Invalid Floor1 Data");if(this._xList[this._sortIdx[e]]>this._xList[this._sortIdx[t]]){const s=this._sortIdx[e];this._sortIdx[e]=this._sortIdx[t],this._sortIdx[t]=s}}}unpack(e,t,s){const i=new wa;if(e.readBit()){let t=2;i.posts[0]=e.readBits(this._yBits),i.posts[1]=e.readBits(this._yBits);for(let s=0;s<this._partitionClass.length;s++){const a=this._partitionClass[s],r=this._classDimensions[a],n=this._classSubclasses[a],o=(1<<n)-1;let h=0;if(n>0&&(h=this._classMasterbooks[a].decodeScalar(e),-1===h)){t=0;break}for(let l=0;l<r;l++){const r=this._subclassBooks[a][h&o];if(h>>=n,null!=r&&(i.posts[t]=r.decodeScalar(e),-1===i.posts[t])){t=0,s=this._partitionClass.length;break}++t}}i.postCount=t}return i}apply(e,t,s){const i=e,a=t/2;if(i.postCount>0){const e=this.unwrapPosts(i);let t=0,r=i.posts[0]*this._multiplier;for(let n=1;n<i.postCount;n++){const o=this._sortIdx[n];if(e[o]){const e=this._xList[o],n=i.posts[o]*this._multiplier;t<a&&this.renderLineMulti(t,r,Math.min(e,a),n,s),t=e,r=n}if(t>=a)break}t<a&&this.renderLineMulti(t,r,a,r,s)}else s.fill(0,0,a)}unwrapPosts(e){const t=new Array(64);t.fill(!1),t[0]=!0,t[1]=!0;const s=new Int32Array(64);s[0]=e.posts[0],s[1]=e.posts[1];for(let i=2;i<e.postCount;i++){const a=this._lNeigh[i],r=this._hNeigh[i],n=this.renderPoint(this._xList[a],s[a],this._xList[r],s[r],this._xList[i]),o=e.posts[i],h=this._range-n,l=n;let c;c=h<l?2*h:2*l,0!==o?(t[a]=!0,t[r]=!0,t[i]=!0,s[i]=o>=c?h>l?o-l+n:n-o+h-1:o%2==1?n-(o+1)/2:n+o/2):(t[i]=!1,s[i]=n)}for(let t=0;t<e.postCount;t++)e.posts[t]=s[t];return t}renderPoint(e,t,s,i,a){const r=i-t,n=s-e,o=Math.abs(r)*(a-e)/n|0;return r<0?t-o:t+o}renderLineMulti(e,t,s,i,a){const r=i-t,n=s-e;let o=Math.abs(r);const h=1-2*(r>>31&1),l=r/n|0;let c=e,d=t,u=-n;for(a[e]*=Ba.inverse_dB_table[t],o-=Math.abs(l)*n;++c<s;)d+=l,u+=o,u>=0&&(u-=n,d+=h),a[c]*=Ba.inverse_dB_table[d]}}Ba._rangeLookup=[256,128,86,64],Ba._yBitsLookup=[8,7,7,6],Ba.inverse_dB_table=new Float32Array([1.0649863e-7,1.1341951e-7,1.2079015e-7,1.2863978e-7,1.3699951e-7,1.4590251e-7,1.5538408e-7,1.6548181e-7,1.7623575e-7,1.8768855e-7,1.9988561e-7,2.128753e-7,2.2670913e-7,2.4144197e-7,2.5713223e-7,2.7384213e-7,2.9163793e-7,3.1059021e-7,3.3077411e-7,3.5226968e-7,3.7516214e-7,3.9954229e-7,4.255068e-7,4.5315863e-7,4.8260743e-7,5.1396998e-7,5.4737065e-7,5.8294187e-7,6.2082472e-7,6.6116941e-7,7.0413592e-7,7.4989464e-7,7.9862701e-7,8.505263e-7,9.0579828e-7,9.6466216e-7,10273513e-13,10941144e-13,11652161e-13,12409384e-13,13215816e-13,14074654e-13,14989305e-13,15963394e-13,17000785e-13,18105592e-13,19282195e-13,20535261e-13,21869758e-13,23290978e-13,24804557e-13,26416497e-13,2813319e-12,29961443e-13,31908506e-13,33982101e-13,36190449e-13,38542308e-13,41047004e-13,4371447e-12,46555282e-13,49580707e-13,5280274e-12,5623416e-12,59888572e-13,63780469e-13,67925283e-13,72339451e-13,77040476e-13,82047e-10,87378876e-13,93057248e-13,99104632e-13,10554501e-12,11240392e-12,11970856e-12,12748789e-12,13577278e-12,14459606e-12,15399272e-12,16400004e-12,17465768e-12,18600792e-12,19809576e-12,21096914e-12,22467911e-12,23928002e-12,25482978e-12,27139006e-12,28902651e-12,30780908e-12,32781225e-12,34911534e-12,37180282e-12,39596466e-12,42169667e-12,4491009e-11,47828601e-12,50936773e-12,54246931e-12,57772202e-12,61526565e-12,65524908e-12,69783085e-12,74317983e-12,79147585e-12,8429104e-11,89768747e-12,95602426e-12,.00010181521,.00010843174,.00011547824,.00012298267,.00013097477,.00013948625,.00014855085,.00015820453,.00016848555,.00017943469,.00019109536,.00020351382,.00021673929,.00023082423,.00024582449,.00026179955,.00027881276,.00029693158,.00031622787,.00033677814,.00035866388,.00038197188,.00040679456,.00043323036,.00046138411,.00049136745,.00052329927,.00055730621,.00059352311,.00063209358,.00067317058,716917e-9,.0007635063,.00081312324,.00086596457,.00092223983,.00098217216,.0010459992,.0011139742,.0011863665,.0012634633,.0013455702,.0014330129,.0015261382,.0016253153,.0017309374,.0018434235,.0019632195,.0020908006,.0022266726,.0023713743,.0025254795,.0026895994,.0028643847,.0030505286,.0032487691,.0034598925,.0036847358,.0039241906,.0041792066,.004450795,.0047400328,.0050480668,.0053761186,.0057254891,.0060975636,.0064938176,.0069158225,.0073652516,.0078438871,.0083536271,.0088964928,.009474637,.010090352,.01074608,.011444421,.012188144,.012980198,.013823725,.014722068,.015678791,.016697687,.017782797,.018938423,.020169149,.021479854,.022875735,.02436233,.025945531,.027631618,.029427276,.031339626,.033376252,.035545228,.037855157,.040315199,.042935108,.045725273,.048696758,.051861348,.055231591,.05882085,.062643361,.066714279,.071049749,.075666962,.080584227,.085821044,.091398179,.097337747,.1036633,.11039993,.11757434,.12521498,.13335215,.14201813,.15124727,.16107617,.1715438,.18269168,.19456402,.20720788,.22067342,.23501402,.25028656,.26655159,.28387361,.30232132,.32196786,.34289114,.36517414,.38890521,.41417847,.44109412,.4697589,.50028648,.53279791,.56742212,.6042964,.64356699,.68538959,.72993007,.77736504,.8278826,.88168307,.9389798,1]);class ka{constructor(e,t,s,i){const a=e.readBits(16);switch(a){case 0:this.floor=new _a(e,t,s,i);break;case 1:this.floor=new Ba(e,i);break;default:throw new fe(S.Format,`Vorbis: Invalid Floor type: ${a}`)}}apply(e,t,s){this.floor.apply(e,t,s)}unpack(e,t,s){return this.floor.unpack(e,t,s)}}class Ta{constructor(e,t,s){this._begin=e.readBits(24),this._end=e.readBits(24),this._partitionSize=e.readBits(24)+1,this._classifications=e.readBits(6)+1,this._classBook=s[e.readBits(8)],this._cascade=new Int32Array(this._classifications);let i=0;for(let t=0;t<this._classifications;t++){const s=e.readBits(3);e.readBit()?this._cascade[t]=e.readBits(5)<<3|s:this._cascade[t]=s,i+=Ta.icount(this._cascade[t])}const a=new Int32Array(i);for(let t=0;t<i;t++)if(a[t]=e.readBits(8),0===s[a[t]].mapType)throw new fe(S.Format,"Vorbis: Invalid Residue 0");const r=this._classBook.entries;let n=this._classBook.dimensions,o=1;for(;n>0;){if(o*=this._classifications,o>r)throw new fe(S.Format,"Vorbis: Invalid Residue 0");--n}this._books=new Array(this._classifications),i=0;let h,l=0;for(let e=0;e<this._classifications;e++)if(h=ua.ilog(this._cascade[e]),this._books[e]=new Array(h),h>0){l=Math.max(l,h);for(let t=0;t<h;t++)(this._cascade[e]&1<<t)>0&&(this._books[e][t]=s[a[i++]])}this._maxStages=l,this._decodeMap=new Array(o);for(let e=0;e<o;e++){let t=e,s=o/this._classifications|0;this._decodeMap[e]=new Int32Array(this._classBook.dimensions);for(let i=0;i<this._classBook.dimensions;i++){const a=t/s|0;t-=a*s,s=s/this._classifications|0,this._decodeMap[e][i]=a}}this._channels=t}static icount(e){let t=0;for(;0!==e;)t+=1&e,e>>=1;return t}decode(e,t,s,i){const a=(this._end<s/2?this._end:s/2)-this._begin;if(a>0&&-1!==t.indexOf(!1)){const t=a/this._partitionSize,s=(t+this._classBook.dimensions-1)/this._classBook.dimensions|0,r=[];for(let e=0;e<this._channels;e++)r.push(new Array(s));for(let s=0;s<this._maxStages;s++)for(let a=0,n=0;a<t;n++){if(0===s)for(let i=0;i<this._channels;i++){const o=this._classBook.decodeScalar(e);if(!(o>=0&&o<this._decodeMap.length)){a=t,s=this._maxStages;break}r[i][n]=this._decodeMap[o]}for(let o=0;a<t&&o<this._classBook.dimensions;o++,a++){const h=this._begin+a*this._partitionSize;for(let l=0;l<this._channels;l++){const c=r[l][n][o];if(this._cascade[c]&1<<s){const r=this._books[c][s];if(r&&this.writeVectors(r,e,i,l,h,this._partitionSize)){a=t,s=this._maxStages;break}}}}}}}writeVectors(e,t,s,i,a,r){const n=s[i],o=r/e.dimensions,h=new Int32Array(o);for(let s=0;s<o;s++)if(h[s]=e.decodeScalar(t),-1===h[s])return!0;for(let t=0;t<e.dimensions;t++)for(let s=0;s<o;s++,a++)n[a]+=e.get(h[s],t);return!1}}class Na extends Ta{writeVectors(e,t,s,i,a,r){const n=s[i];for(let s=0;s<r;){const i=e.decodeScalar(t);if(-1===i)return!0;for(let t=0;t<e.dimensions;s++,t++)n[a+s]+=e.get(i,t)}return!1}}class xa extends Ta{constructor(e,t,s){super(e,1,s),this._realChannels=t}decode(e,t,s,i){super.decode(e,t,s*this._realChannels,i)}writeVectors(e,t,s,i,a,r){let n=0;a/=this._realChannels;for(let i=0;i<r;){const r=e.decodeScalar(t);if(-1===r)return!0;for(let t=0;t<e.dimensions;t++,i++)s[n][a]+=e.get(r,t),++n===this._realChannels&&(n=0,a++)}return!1}}class va{constructor(e,t,s){const i=e.readBits(16);switch(i){case 0:this.residue=new Ta(e,t,s);break;case 1:this.residue=new Na(e,t,s);break;case 2:this.residue=new xa(e,t,s);break;default:throw new fe(S.Format,`Vorbis: Invalid Residue type: ${i}`)}}decode(e,t,s,i){this.residue.decode(e,t,s,i)}}class Pa{constructor(e,t,s,i,a){if(0!==e.readBits(16))throw new fe(S.Format,"Vorbis: Invalid mapping type!");let r=1;e.readBit()&&(r+=e.readBits(4));let n=0;e.readBit()&&(n=e.readBits(8)+1);const o=ua.ilog(t-1);this._couplingAngle=new Int32Array(n),this._couplingMangitude=new Int32Array(n);for(let s=0;s<n;s++){const i=e.readBits(o),a=e.readBits(o);if(i===a||i>t-1||a>t-1)throw new fe(S.Format,"Vorbis: Invalid magnitude or angle in mapping header!");this._couplingAngle[s]=a,this._couplingMangitude[s]=i}if(0!==e.readBits(2))throw new fe(S.Format,"Vorbis: Reserved bits not 0 in mapping header.");const h=new Int32Array(t);if(r>1)for(let s=0;s<t;s++)if(h[s]=e.readBits(4),h[s]>r)throw new fe(S.Format,"Vorbis: Invalid channel mux submap index in mapping header!");this._submapFloor=new Array(r),this._submapResidue=new Array(r);for(let t=0;t<r;t++){e.skipBits(8);const a=e.readBits(8);if(a>=s.length)throw new fe(S.Format,"Vorbis: Invalid floor number in mapping header!");const r=e.readBits(8);if(r>=i.length)throw new fe(S.Format,"Vorbis: Invalid residue number in mapping header!");this._submapFloor[t]=s[a],this._submapResidue[t]=i[r]}this._channelFloor=new Array(t),this._channelResidue=new Array(t);for(let e=0;e<t;e++)this._channelFloor[e]=this._submapFloor[h[e]],this._channelResidue[e]=this._submapResidue[h[e]];this._mdct=a}decodePacket(e,t,s){const i=t>>1,a=new Array(this._channelFloor.length),r=new Array(this._channelFloor.length);r.fill(!1);for(let n=0;n<this._channelFloor.length;n++)a[n]=this._channelFloor[n].unpack(e,t,n),r[n]=!a[n].executeChannel,s[n].fill(0,0,i);for(let e=0;e<this._couplingAngle.length;e++)(a[this._couplingAngle[e]].executeChannel||a[this._couplingMangitude[e]].executeChannel)&&(a[this._couplingAngle[e]].forceEnergy=!0,a[this._couplingMangitude[e]].forceEnergy=!0);for(let i=0;i<this._submapFloor.length;i++){for(let e=0;e<this._channelFloor.length;e++)this._submapFloor[i]===this._channelFloor[e]&&this._submapResidue[i]===this._channelResidue[e]||(a[e].forceNoEnergy=!0);this._submapResidue[i].decode(e,r,t,s)}for(let e=this._couplingAngle.length-1;e>=0;e--)if(a[this._couplingAngle[e]].executeChannel||a[this._couplingMangitude[e]].executeChannel){const t=s[this._couplingMangitude[e]],a=s[this._couplingAngle[e]];for(let e=0;e<i;e++){let s,i;const r=t[e],n=a[e];r>0?n>0?(s=r,i=r-n):(i=r,s=r+n):n>0?(s=r,i=r+n):(i=r,s=r-n),t[e]=s,a[e]=i}}for(let e=0;e<this._channelFloor.length;e++)a[e].executeChannel?(this._channelFloor[e].apply(a[e],t,s[e]),this._mdct.reverse(s[e],t)):s[e].fill(0,i,2*i)}}class Fa{constructor(){this.packetStartIndex=0,this.packetTotalLength=0,this.packetValidLength=0}}class Ca{constructor(){this.overlapInfo=new Fa,this.windowIndex=0}}class Da{constructor(e=null){this.samplePosition=null,this.samplePosition=e}}class Ea{constructor(e,t,s,i,a){if(this._overlapInfo=null,this._channels=t,this._blockFlag=e.readBit(),0!==e.readBits(32))throw new fe(S.Format,"Vorbis: Mode header had invalid window or transform type!");const r=e.readBits(8);if(r>=a.length)throw new fe(S.Format,"Vorbis: Mode header had invalid mapping index!");this._mapping=a[r],this._blockFlag?(this._blockSize=i,this._windows=[Ea.calcWindow(s,i,s),Ea.calcWindow(i,i,s),Ea.calcWindow(s,i,i),Ea.calcWindow(i,i,i)],this._overlapInfo=[Ea.calcOverlap(s,i,s),Ea.calcOverlap(i,i,s),Ea.calcOverlap(s,i,i),Ea.calcOverlap(i,i,i)]):(this._blockSize=s,this._windows=[Ea.calcWindow(s,s,s)])}decode(e,t){const s=this.getPacketInfo(e);this._mapping.decodePacket(e,this._blockSize,t);const i=this._windows[s.windowIndex];for(let e=0;e<this._blockSize;e++)for(let s=0;s<this._channels;s++)t[s][e]*=i[e];return s.overlapInfo}getPacketInfo(e){const t=new Ca;if(this._blockFlag){const s=e.readBit(),i=e.readBit();t.windowIndex=(s?1:0)+(i?2:0);const a=this._overlapInfo[t.windowIndex];t.overlapInfo.packetStartIndex=a.packetStartIndex,t.overlapInfo.packetValidLength=a.packetValidLength,t.overlapInfo.packetTotalLength=a.packetTotalLength}else t.windowIndex=0,t.overlapInfo.packetStartIndex=0,t.overlapInfo.packetValidLength=this._blockSize/2,t.overlapInfo.packetTotalLength=this._blockSize;return t}static calcWindow(e,t,s){const i=new Float32Array(t),a=e/2,r=s/2,n=t/4-a/2,o=t-t/4-r/2;for(let e=0;e<a;e++){let t=Math.sin((e+.5)/a*Ea.M_PI2);t*=t,i[n+e]=Math.sin(t*Ea.M_PI2)}for(let e=n+a;e<o;e++)i[e]=1;for(let e=0;e<r;e++){let t=Math.sin((r-e-.5)/r*Ea.M_PI2);t*=t,i[o+e]=Math.sin(t*Ea.M_PI2)}return i}static calcOverlap(e,t,s){const i=s/4,a=t/4-e/4,r=t/4*3+i,n=r-2*i,o=new Fa;return o.packetStartIndex=a,o.packetValidLength=n,o.packetTotalLength=r,o}}Ea.M_PI2=1.57079632695;class La{constructor(e){this._n=e,this._n2=e>>1,this._n4=this._n2>>1,this._n8=this._n4>>1,this._ld=ua.ilog(e)-1,this._a=new Float32Array(this._n2),this._b=new Float32Array(this._n2),this._c=new Float32Array(this._n4);let t=0,s=0;for(;t<this._n4;++t,s+=2)this._a[s]=Math.cos(4*t*La.M_PI/e),this._a[s+1]=-Math.sin(4*t*La.M_PI/e),this._b[s]=.5*Math.cos((s+1)*La.M_PI/e/2),this._b[s+1]=.5*Math.sin((s+1)*La.M_PI/e/2);for(t=0,s=0;t<this._n8;++t,s+=2)this._c[s]=Math.cos(2*(s+1)*La.M_PI/e),this._c[s+1]=-Math.sin(2*(s+1)*La.M_PI/e);this._bitrev=new Uint16Array(this._n8);for(let e=0;e<this._n8;++e)this._bitrev[e]=Ee.int32ToUint16(ua.bitReverse(e,this._ld-3)<<2)}calcReverse(e){let t,s;const i=new Float32Array(this._n2);{let t=this._n2-2,s=0,a=0;const r=this._n2;for(;a!==r;)i[t+1]=e[a]*this._a[s]-e[a+2]*this._a[s+1],i[t]=e[a]*this._a[s+1]+e[a+2]*this._a[s],t-=2,s+=2,a+=4;for(a=this._n2-3;t>=0;)i[t+1]=-e[a+2]*this._a[s]- -e[a]*this._a[s+1],i[t]=-e[a+2]*this._a[s+1]+-e[a]*this._a[s],t-=2,s+=2,a-=4}t=e,s=i;{let e=this._n2-8,i=this._n4,a=0,r=this._n4,n=0;for(;e>=0;){let o,h;h=s[i+1]-s[a+1],o=s[i]-s[a],t[r+1]=s[i+1]+s[a+1],t[r]=s[i]+s[a],t[n+1]=h*this._a[e+4]-o*this._a[e+5],t[n]=o*this._a[e+4]+h*this._a[e+5],h=s[i+3]-s[a+3],o=s[i+2]-s[a+2],t[r+3]=s[i+3]+s[a+3],t[r+2]=s[i+2]+s[a+2],t[n+3]=h*this._a[e]-o*this._a[e+1],t[n+2]=o*this._a[e]+h*this._a[e+1],e-=8,r+=4,n+=4,i+=4,a+=4}}this.step3_iter0_loop(this._n>>4,t,this._n2-1-0*this._n4,-this._n8),this.step3_iter0_loop(this._n>>4,t,this._n2-1-1*this._n4,-this._n8),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-0*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-1*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-2*this._n8,-(this._n>>4),16),this.step3_inner_r_loop(this._n>>5,t,this._n2-1-3*this._n8,-(this._n>>4),16);let a=2;for(;a<this._ld-3>>1;++a){const e=this._n>>a+2,s=e>>1,i=1<<a+1;for(let r=0;r<i;++r)this.step3_inner_r_loop(this._n>>a+4,t,this._n2-1-e*r,-s,1<<a+3)}for(;a<this._ld-6;++a){const e=this._n>>a+2,s=1<<a+3,i=e>>1,r=this._n>>a+6,n=1<<a+1;let o=this._n2-1,h=0;for(let a=r;a>0;--a)this.step3_inner_s_loop(n,t,o,-i,h,s,e),h+=4*s,o-=8}this.step3_inner_s_loop_ld654(this._n>>5,t,this._n2-1,this._n);{let e=0,i=this._n4-4,a=this._n2-4;for(;i>=0;){let r;r=this._bitrev[e],s[a+3]=t[r],s[a+2]=t[r+1],s[i+3]=t[r+2],s[i+2]=t[r+3],r=this._bitrev[e+1],s[a+1]=t[r],s[a]=t[r+1],s[i+1]=t[r+2],s[i]=t[r+3],i-=4,a-=4,e+=2}}{let e=0,t=0,i=this._n2-4;for(;t<i;){let a,r,n,o,h,l;a=s[t]-s[i+2],r=s[t+1]+s[i+3],n=this._c[e+1]*a+this._c[e]*r,o=this._c[e+1]*r-this._c[e]*a,h=s[t]+s[i+2],l=s[t+1]-s[i+3],s[t]=h+n,s[t+1]=l+o,s[i+2]=h-n,s[i+3]=o-l,a=s[t+2]-s[i],r=s[t+3]+s[i+1],n=this._c[e+3]*a+this._c[e+2]*r,o=this._c[e+3]*r-this._c[e+2]*a,h=s[t+2]+s[i],l=s[t+3]-s[i+1],s[t+2]=h+n,s[t+3]=l+o,s[i]=h-n,s[i+1]=o-l,e+=4,t+=4,i-=4}}{let t=this._n2-8,s=this._n2-8,a=0,r=this._n2-4,n=this._n2,o=this._n-4;for(;s>=0;){let h,l,c,d;d=i[s+6]*this._b[t+7]-i[s+7]*this._b[t+6],c=-i[s+6]*this._b[t+6]-i[s+7]*this._b[t+7],e[a]=d,e[r+3]=-d,e[n]=c,e[o+3]=c,l=i[s+4]*this._b[t+5]-i[s+5]*this._b[t+4],h=-i[s+4]*this._b[t+4]-i[s+5]*this._b[t+5],e[a+1]=l,e[r+2]=-l,e[n+1]=h,e[o+2]=h,d=i[s+2]*this._b[t+3]-i[s+3]*this._b[t+2],c=-i[s+2]*this._b[t+2]-i[s+3]*this._b[t+3],e[a+2]=d,e[r+1]=-d,e[n+2]=c,e[o+1]=c,l=i[s]*this._b[t+1]-i[s+1]*this._b[t],h=-i[s]*this._b[t]-i[s+1]*this._b[t+1],e[a+3]=l,e[r]=-l,e[n+3]=h,e[o]=h,t-=8,s-=8,a+=4,n+=4,r-=4,o-=4}}}step3_inner_r_loop(e,t,s,i,a){let r,n,o=s,h=o+i,l=0;for(let s=e>>2;s>0;--s)r=t[o]-t[h],n=t[o-1]-t[h-1],t[o]+=t[h],t[o-1]+=t[h-1],t[h]=r*this._a[l]-n*this._a[l+1],t[h-1]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-2]-t[h-2],n=t[o-3]-t[h-3],t[o-2]+=t[h-2],t[o-3]+=t[h-3],t[h-2]=r*this._a[l]-n*this._a[l+1],t[h-3]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-4]-t[h-4],n=t[o-5]-t[h-5],t[o-4]+=t[h-4],t[o-5]+=t[h-5],t[h-4]=r*this._a[l]-n*this._a[l+1],t[h-5]=n*this._a[l]+r*this._a[l+1],l+=a,r=t[o-6]-t[h-6],n=t[o-7]-t[h-7],t[o-6]+=t[h-6],t[o-7]+=t[h-7],t[h-6]=r*this._a[l]-n*this._a[l+1],t[h-7]=n*this._a[l]+r*this._a[l+1],l+=a,o-=8,h-=8}step3_iter0_loop(e,t,s,i){let a=s,r=a+i,n=0;for(let s=e>>2;s>0;--s){let e,s;e=t[a]-t[r],s=t[a-1]-t[r-1],t[a]+=t[r],t[a-1]+=t[r-1],t[r]=e*this._a[n]-s*this._a[n+1],t[r-1]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-2]-t[r-2],s=t[a-3]-t[r-3],t[a-2]+=t[r-2],t[a-3]+=t[r-3],t[r-2]=e*this._a[n]-s*this._a[n+1],t[r-3]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-4]-t[r-4],s=t[a-5]-t[r-5],t[a-4]+=t[r-4],t[a-5]+=t[r-5],t[r-4]=e*this._a[n]-s*this._a[n+1],t[r-5]=s*this._a[n]+e*this._a[n+1],n+=8,e=t[a-6]-t[r-6],s=t[a-7]-t[r-7],t[a-6]+=t[r-6],t[a-7]+=t[r-7],t[r-6]=e*this._a[n]-s*this._a[n+1],t[r-7]=s*this._a[n]+e*this._a[n+1],n+=8,a-=8,r-=8}}step3_inner_s_loop(e,t,s,i,a,r,n){const o=this._a[a],h=this._a[a+1],l=this._a[a+r],c=this._a[a+r+1],d=this._a[a+2*r],u=this._a[a+2*r+1],p=this._a[a+3*r],g=this._a[a+3*r+1];let m,f,y=s,b=y+i;for(let s=e;s>0;--s)m=t[y]-t[b],f=t[y-1]-t[b-1],t[y]+=t[b],t[y-1]+=t[b-1],t[b]=m*o-f*h,t[b-1]=f*o+m*h,m=t[y-2]-t[b-2],f=t[y-3]-t[b-3],t[y-2]+=t[b-2],t[y-3]+=t[b-3],t[b-2]=m*l-f*c,t[b-3]=f*l+m*c,m=t[y-4]-t[b-4],f=t[y-5]-t[b-5],t[y-4]+=t[b-4],t[y-5]+=t[b-5],t[b-4]=m*d-f*u,t[b-5]=f*d+m*u,m=t[y-6]-t[b-6],f=t[y-7]-t[b-7],t[y-6]+=t[b-6],t[y-7]+=t[b-7],t[b-6]=m*p-f*g,t[b-7]=f*p+m*g,y-=n,b-=n}step3_inner_s_loop_ld654(e,t,s,i){const a=i>>3,r=this._a[a];let n=s;const o=n-16*e;for(;n>o;){let e,s;e=t[n]-t[n-8],s=t[n-1]-t[n-9],t[n]+=t[n-8],t[n-1]+=t[n-9],t[n-8]=e,t[n-9]=s,e=t[n-2]-t[n-10],s=t[n-3]-t[n-11],t[n-2]+=t[n-10],t[n-3]+=t[n-11],t[n-10]=(e+s)*r,t[n-11]=(s-e)*r,e=t[n-12]-t[n-4],s=t[n-5]-t[n-13],t[n-4]+=t[n-12],t[n-5]+=t[n-13],t[n-12]=s,t[n-13]=e,e=t[n-14]-t[n-6],s=t[n-7]-t[n-15],t[n-6]+=t[n-14],t[n-7]+=t[n-15],t[n-14]=(e+s)*r,t[n-15]=(e-s)*r,this.iter_54(t,n),this.iter_54(t,n-8),n-=16}}iter_54(e,t){const s=e[t]-e[t-4],i=e[t]+e[t-4],a=e[t-2]+e[t-6],r=e[t-2]-e[t-6];e[t]=i+a,e[t-2]=i-a;const n=e[t-3]-e[t-7];e[t-4]=s+n,e[t-6]=s-n;const o=e[t-1]-e[t-5],h=e[t-1]+e[t-5],l=e[t-3]+e[t-7];e[t-1]=h+l,e[t-3]=h-l,e[t-5]=o-r,e[t-7]=o+r}}La.M_PI=3.141592653589793;class Ma{constructor(){this._setupCache=new Map}reverse(e,t){let s;this._setupCache.has(t)?s=this._setupCache.get(t):(s=new La(t),this._setupCache.set(t,s)),s.calcReverse(e)}}class Ia{constructor(e,t,s){this._packetIndex=0,this._stream=e,this._setup=t,this._packets=s,this._currentPosition=0,this._prevPacketBuf=null,this._prevPacketStart=0,this._prevPacketEnd=0,this._prevPacketStop=0,this._nextPacketBuf=null,this._eosFound=!1,this._hasPosition=!1,this._modeFieldBits=ua.ilog(t.modes.length-1)}decode(){let e=new Float32Array(this._packets[this._packets.length-1].granulePosition*this._stream.audioChannels);const t=new Float32Array(.2*this._stream.audioSampleRate*this._stream.audioChannels);let s=0,i=0;for(;s=this.read(t,0,t.length),0!==s;){if(i+s>=e.length){const s=new Float32Array(e.length+t.length);s.set(e,0),e=s}e.set(t.subarray(0,s),i),i+=s}return e.subarray(0,i)}read(e,t,s){if(0===s)return 0;let i=t;const a=t+s;for(;i<a;){if(this._prevPacketStart===this._prevPacketEnd){if(this._eosFound){this._nextPacketBuf=null,this._prevPacketBuf=null;break}const e=this.readNextPacket((i-t)/this._stream.audioChannels);null===e&&(this._prevPacketEnd=this._prevPacketStop),null===e||null===e.samplePosition||this._hasPosition||(this._hasPosition=!0,this._currentPosition=e.samplePosition-(this._prevPacketEnd-this._prevPacketStart)-(i-t)/this._stream.audioChannels)}const s=Math.min((a-i)/this._stream.audioChannels,this._prevPacketEnd-this._prevPacketStart);s>0&&(i+=this.copyBuffer(e,i,s))}return s=i-t,this._currentPosition+=s/this._stream.audioChannels,s}copyBuffer(e,t,s){let i=t;for(;s>0;this._prevPacketStart++,s--)for(let t=0;t<this._stream.audioChannels;t++)e[i++]=this._prevPacketBuf[t][this._prevPacketStart];return i-t}readNextPacket(e){const t=this.decodeNextPacket();if(this._eosFound=this._eosFound||t.isEndOfStream,null==t.curPacket)return null;if(null!==t.samplePosition&&t.isEndOfStream){const s=this._currentPosition+e+t.validLen-t.startIndex,i=t.samplePosition-s;i<0&&(t.validLen+=i,t.validLen<0&&(t.validLen=0))}return this._prevPacketEnd>0?(Ia.overlapBuffers(this._prevPacketBuf,t.curPacket,this._prevPacketStart,this._prevPacketStop,t.startIndex,this._stream.audioChannels),this._prevPacketStart=t.startIndex):null==this._prevPacketBuf&&(this._prevPacketStart=t.validLen),this._nextPacketBuf=this._prevPacketBuf,this._prevPacketEnd=t.validLen,this._prevPacketStop=t.totalLen,this._prevPacketBuf=t.curPacket,new Da(t.samplePosition)}static overlapBuffers(e,t,s,i,a,r){for(;s<i;s++,a++)for(let i=0;i<r;i++)t[i][a]+=e[i][s]}decodeNextPacket(){const e=new Aa;let t=null;if(this._packetIndex>=this._packets.length)e.isEndOfStream=!0;else{t=this._packets[this._packetIndex++];const s=new ca(Me.fromBuffer(t.packetData));if(e.isEndOfStream=t.isEndOfStream,!s.readBit()){const i=this._setup.modes[s.readBits(this._modeFieldBits)];if(null==this._nextPacketBuf){this._nextPacketBuf=new Array(this._stream.audioChannels);for(let e=0;e<this._stream.audioChannels;e++)this._nextPacketBuf[e]=new Float32Array(this._stream.blocksize1)}const a=i.decode(s,this._nextPacketBuf);return e.startIndex=a.packetStartIndex,e.validLen=a.packetValidLength,e.totalLen=a.packetTotalLength,e.samplePosition=t.granulePosition,e.curPacket=this._nextPacketBuf,e}}return e}}class Aa{constructor(){this.curPacket=null,this.startIndex=0,this.validLen=0,this.totalLen=0,this.isEndOfStream=!1,this.samplePosition=null}}!function(e){e[e.IdentificationHeader=1]="IdentificationHeader",e[e.Comment=3]="Comment",e[e.SetupHeader=5]="SetupHeader"}(Vi||(Vi={}));class Ra{constructor(e){this._packetIndex=-1,this._packets=e}read(){let e;for(;;){if(e=this.nextPacket(),null==e)return null;if(e.isBeginningOfStream){const t=this.readStream(e);if(null!=t)return t}}}nextPacket(){return this._packetIndex++,this._packetIndex<this._packets.length?this._packets[this._packetIndex]:null}readStream(e){const t=new ha;if(!this.readIdentificationHeader(t,e))return null;if(!this.readComments(this.nextPacket()))return null;const s=new da;if(!this.readSetupHeader(t,s,this.nextPacket()))return null;const i=[];let a;for(;a=this.nextPacket(),null!=a&&(i.push(a),!a.isEndOfStream););const r=new Ia(t,s,i);return t.samples=r.decode(),t}comonHeaderDecode(e,t){const s=new Uint8Array(7);if(t.read(s,0,s.length),s[0]!==e)return!1;for(let e=0;e<Ra.VorbisHeaderMarker.length;e++)if(s[1+e]!==Ra.VorbisHeaderMarker[e])return!1;return!0}comonHeaderDecodeBit(e,t){const s=t.readBytes(7);if(s[0]!==e)return!1;for(let e=0;e<Ra.VorbisHeaderMarker.length;e++)if(s[1+e]!==Ra.VorbisHeaderMarker[e])return!1;return!0}readIdentificationHeader(e,t){const s=Me.fromBuffer(t.packetData);if(!this.comonHeaderDecode(Vi.IdentificationHeader,s))return!1;if(0!==Le.readUInt32LE(s))return!1;if(e.audioChannels=s.readByte(),e.audioSampleRate=Le.readUInt32LE(s),e.audioChannels<=0||e.audioSampleRate<=0)return!1;e.bitrateMaximum=Le.readInt32LE(s),e.bitrateNominal=Le.readInt32LE(s),e.bitrateMinimum=Le.readInt32LE(s);const i=s.readByte();if(e.blocksize0=1<<(15&i),e.blocksize1=1<<(i>>4),e.blocksize0>e.blocksize1||!Ra.isAllowedBlockSize(e.blocksize0)||!Ra.isAllowedBlockSize(e.blocksize0))return!1;return 0!==s.readByte()}static isAllowedBlockSize(e){switch(e){case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:return!0;default:return!1}}readComments(e){if(null==e)return!1;const t=Me.fromBuffer(e.packetData);if(!this.comonHeaderDecode(Vi.Comment,t))return!1;const s=Le.readUInt32LE(t);t.skip(s);const i=Le.readUInt32LE(t);for(let e=0;e<i;e++){const e=Le.readUInt32LE(t);t.skip(e)}return 0!==t.readByte()}readSetupHeader(e,t,s){if(null==s)return!1;const i=new ca(Me.fromBuffer(s.packetData)),a=new Ma,r=new ya;if(!this.comonHeaderDecodeBit(Vi.SetupHeader,i))return!1;let n=i.readByte()+1;for(let e=0;e<n;e++)t.codebooks.push(new ma(i,r));n=i.readBits(6)+1;for(let e=0;e<n;e++)t.timeDomainTransforms.push(new ba(i));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.floors.push(new ka(i,e.blocksize0,e.blocksize1,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.residues.push(new va(i,e.audioChannels,t.codebooks));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.mappings.push(new Pa(i,e.audioChannels,t.floors,t.residues,a));n=i.readBits(6)+1;for(let s=0;s<n;s++)t.modes.push(new Ea(i,e.audioChannels,e.blocksize0,e.blocksize1,t.mappings));return!!i.readBit()}}Ra.VorbisHeaderMarker=new Uint8Array(["v".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"b".charCodeAt(0),"i".charCodeAt(0),"s".charCodeAt(0)]);class Oa{constructor(e){this.streams=[];const t=new oa(e).read(),s=new Ra(t);for(;;){const e=s.read();if(null==e)break;this.streams.push(e)}}}class Ha{constructor(){this.phdrs=[],this.pbags=[],this.pmods=[],this.pgens=[],this.insts=[],this.ibags=[],this.imods=[],this.igens=[],this.sHdrs=[],this.sampleData=new Uint8Array(0),this._sampleCache=new Map}decodeSamples(e,t,s){const i=`${e}_${t}_${s}`;if(!this._sampleCache.has(i)){let a;const r=this.sampleData.slice(e,t);if(s){a=new Oa(Me.fromBuffer(r)).streams[0].samples}else{const e=new DataView(r.buffer,r.byteOffset,r.length);a=new Float32Array(r.length/2);for(let t=0;t<a.length;t++)a[t]=e.getInt16(2*t,!0)/32767}return this._sampleCache.set(i,a),a}return this._sampleCache.get(i)}load(e){const t=new ra,s=new ra;if(!ra.load(null,t,e)||"sfbk"!==t.id)throw new ye("Soundfont is not a valid Soundfont2 file");for(;ra.load(t,s,e);){const t=new ra;if("pdta"===s.id)for(;ra.load(s,t,e);)switch(t.id){case"phdr":for(let s=0,i=t.size/Ja.SizeInFile|0;s<i;s++)this.phdrs.push(new Ja(e));break;case"pbag":for(let s=0,i=t.size/Ua.SizeInFile|0;s<i;s++)this.pbags.push(new Ua(e));break;case"pmod":for(let s=0,i=t.size/Ya.SizeInFile|0;s<i;s++)this.pmods.push(new Ya(e));break;case"pgen":for(let s=0,i=t.size/Xa.SizeInFile|0;s<i;s++)this.pgens.push(new Xa(e));break;case"inst":for(let s=0,i=t.size/za.SizeInFile|0;s<i;s++)this.insts.push(new za(e));break;case"ibag":for(let s=0,i=t.size/Wa.SizeInFile|0;s<i;s++)this.ibags.push(new Wa(e));break;case"imod":for(let s=0,i=t.size/Va.SizeInFile|0;s<i;s++)this.imods.push(new Va(e));break;case"igen":for(let s=0,i=t.size/Ga.SizeInFile|0;s<i;s++)this.igens.push(new Ga(e));break;case"shdr":for(let s=0,i=t.size/$a.SizeInFile|0;s<i;s++)this.sHdrs.push(new $a(e));break;default:e.position+=t.size}else if("sdta"===s.id)for(;ra.load(s,t,e);)if("smpl"===t.id)this.sampleData=new Uint8Array(t.size),e.read(this.sampleData,0,t.size);else e.position+=t.size;else e.position+=s.size}}}class Wa{constructor(e){this.instGenNdx=Le.readUInt16LE(e),this.instModNdx=Le.readUInt16LE(e)}}Wa.SizeInFile=4;class Va{constructor(e){this.modSrcOper=Le.readUInt16LE(e),this.modDestOper=Le.readUInt16LE(e),this.modAmount=Le.readInt16LE(e),this.modAmtSrcOper=Le.readUInt16LE(e),this.modTransOper=Le.readUInt16LE(e)}}Va.SizeInFile=10;class Ga{constructor(e){this.genOper=Le.readUInt16LE(e),this.genAmount=new qa(e)}}Ga.SizeInFile=4;class za{constructor(e){this.instName=Le.read8BitStringLength(e,20),this.instBagNdx=Le.readUInt16LE(e)}}za.SizeInFile=22;class Ua{constructor(e){this.genNdx=Le.readUInt16LE(e),this.modNdx=Le.readUInt16LE(e)}}Ua.SizeInFile=4;class Xa{constructor(e){this.genOper=Le.readUInt16LE(e),this.genAmount=new qa(e)}}Xa.SizeInFile=4,Xa.GenInstrument=41,Xa.GenKeyRange=43,Xa.GenVelRange=44,Xa.GenSampleId=53;class Ja{constructor(e){this.presetName=Le.read8BitStringLength(e,20),this.preset=Le.readUInt16LE(e),this.bank=Le.readUInt16LE(e),this.presetBagNdx=Le.readUInt16LE(e),this.library=Le.readUInt32LE(e),this.genre=Le.readUInt32LE(e),this.morphology=Le.readUInt32LE(e)}}Ja.SizeInFile=38;class Ya{constructor(e){this.modSrcOper=Le.readUInt16LE(e),this.modDestOper=Le.readUInt16LE(e),this.modAmount=Le.readUInt16LE(e),this.modAmtSrcOper=Le.readUInt16LE(e),this.modTransOper=Le.readUInt16LE(e)}}Ya.SizeInFile=10;class $a{constructor(e){this.sampleName=Le.read8BitStringLength(e,20),this.start=Le.readUInt32LE(e),this.end=Le.readUInt32LE(e),this.startLoop=Le.readUInt32LE(e),this.endLoop=Le.readUInt32LE(e),this.sampleRate=Le.readUInt32LE(e),this.originalPitch=e.readByte(),this.pitchCorrection=Le.readSInt8(e),this.sampleLink=Le.readUInt16LE(e),this.sampleType=Le.readUInt16LE(e)}}$a.SizeInFile=46;class qa{get shortAmount(){return Ee.uint16ToInt16(this.wordAmount)}get lowByteAmount(){return 255&this.wordAmount}get highByteAmount(){return(65280&this.wordAmount)>>8&255}constructor(e){this.wordAmount=Le.readUInt16LE(e)}}class Ka{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 ja{constructor(){this.activeChannel=0,this.channelList=[]}setupVoice(e,t){const s=this.channelList[this.activeChannel],i=t.region.pan+s.panOffset;t.playingChannel=this.activeChannel,t.mixVolume=s.mixVolume,t.noteGainDb+=s.gainDb,t.updatePitchRatio(s,e.outSampleRate),i<=-.5?(t.panFactorLeft=1,t.panFactorRight=0):i>=.5?(t.panFactorLeft=0,t.panFactorRight=1):(t.panFactorLeft=Math.sqrt(.5-i),t.panFactorRight=Math.sqrt(.5+i))}}!function(e){e[e.None=0]="None",e[e.Continuous=1]="Continuous",e[e.Sustain=2]="Sustain"}(Gi||(Gi={})),function(e){e[e.StereoInterleaved=0]="StereoInterleaved",e[e.StereoUnweaved=1]="StereoUnweaved",e[e.Mono=2]="Mono"}(zi||(zi={}));class Qa{constructor(){this.name="",this.presetNumber=0,this.bank=0,this.regions=null}}class Za{static timecents2Secs(e){return Math.pow(2,e/1200)}static decibelsToGain(e){return e>-100?Math.pow(10,.05*e):0}static gainToDecibels(e){return e<=1e-5?-100:20*Math.log10(e)}static cents2Hertz(e){return 8.176*Math.pow(2,e/1200)}}class er{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:Za.timecents2Secs(this.delay),this.attack=this.attack<-11950?0:Za.timecents2Secs(this.attack),this.release=this.release<-11950?0:Za.timecents2Secs(this.release),0===this.keynumToHold&&(this.hold=this.hold<-11950?0:Za.timecents2Secs(this.hold)),0===this.keynumToDecay&&(this.decay=this.decay<-11950?0:Za.timecents2Secs(this.decay)),this.sustain<0?this.sustain=0:this.sustain=e?Za.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"}(Ui||(Ui={}));class tr{constructor(e){this.loopMode=Gi.None,this.samples=tr.NoSamples,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv=new er,this.modEnv=new er,this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,e&&(this.loopMode=e.loopMode,this.samples=e.samples,this.sampleRate=e.sampleRate,this.loKey=e.loKey,this.hiKey=e.hiKey,this.loVel=e.loVel,this.hiVel=e.hiVel,this.group=e.group,this.offset=e.offset,this.end=e.end,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this.transpose=e.transpose,this.tune=e.tune,this.pitchKeyCenter=e.pitchKeyCenter,this.pitchKeyTrack=e.pitchKeyTrack,this.attenuation=e.attenuation,this.pan=e.pan,this.ampEnv=new er(e.ampEnv),this.modEnv=new er(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=Gi.None,this.samples=tr.NoSamples,this.sampleRate=0,this.loKey=0,this.hiKey=0,this.loVel=0,this.hiVel=0,this.group=0,this.offset=0,this.end=0,this.loopStart=0,this.loopEnd=0,this.transpose=0,this.tune=0,this.pitchKeyCenter=0,this.pitchKeyTrack=0,this.attenuation=0,this.pan=0,this.ampEnv.clear(),this.modEnv.clear(),this.initialFilterQ=0,this.initialFilterFc=0,this.modEnvToPitch=0,this.modEnvToFilterFc=0,this.modLfoToFilterFc=0,this.modLfoToVolume=0,this.delayModLFO=0,this.freqModLFO=0,this.modLfoToPitch=0,this.delayVibLFO=0,this.freqVibLFO=0,this.vibLfoToPitch=0,this.hiKey=127,this.hiVel=127,this.pitchKeyCenter=60,e||(this.pitchKeyTrack=100,this.pitchKeyCenter=-1,this.ampEnv.delay=-12e3,this.ampEnv.attack=-12e3,this.ampEnv.hold=-12e3,this.ampEnv.decay=-12e3,this.ampEnv.release=-12e3,this.modEnv.delay=-12e3,this.modEnv.attack=-12e3,this.modEnv.hold=-12e3,this.modEnv.decay=-12e3,this.modEnv.release=-12e3,this.initialFilterFc=13500,this.delayModLFO=-12e3,this.delayVibLFO=-12e3)}operator(e,t){switch(e){case Ui.StartAddrsOffset:this.offset+=Ee.int16ToUint32(t.shortAmount);break;case Ui.EndAddrsOffset:this.end+=Ee.int16ToUint32(t.shortAmount);break;case Ui.StartloopAddrsOffset:this.loopStart+=Ee.int16ToUint32(t.shortAmount);break;case Ui.EndloopAddrsOffset:this.loopEnd+=Ee.int16ToUint32(t.shortAmount);break;case Ui.StartAddrsCoarseOffset:this.offset+=32768*Ee.int16ToUint32(t.shortAmount);break;case Ui.ModLfoToPitch:this.modLfoToPitch=t.shortAmount;break;case Ui.VibLfoToPitch:this.vibLfoToPitch=t.shortAmount;break;case Ui.ModEnvToPitch:this.modEnvToPitch=t.shortAmount;break;case Ui.InitialFilterFc:this.initialFilterFc=t.shortAmount;break;case Ui.InitialFilterQ:this.initialFilterQ=t.shortAmount;break;case Ui.ModLfoToFilterFc:this.modLfoToFilterFc=t.shortAmount;break;case Ui.ModEnvToFilterFc:this.modEnvToFilterFc=t.shortAmount;break;case Ui.EndAddrsCoarseOffset:this.end+=32768*Ee.int16ToUint32(t.shortAmount);break;case Ui.ModLfoToVolume:this.modLfoToVolume=t.shortAmount;break;case Ui.Pan:this.pan=t.shortAmount/1e3;break;case Ui.DelayModLFO:this.delayModLFO=t.shortAmount;break;case Ui.FreqModLFO:this.freqModLFO=t.shortAmount;break;case Ui.DelayVibLFO:this.delayVibLFO=t.shortAmount;break;case Ui.FreqVibLFO:this.freqVibLFO=t.shortAmount;break;case Ui.DelayModEnv:this.modEnv.delay=t.shortAmount;break;case Ui.AttackModEnv:this.modEnv.attack=t.shortAmount;break;case Ui.HoldModEnv:this.modEnv.hold=t.shortAmount;break;case Ui.DecayModEnv:this.modEnv.decay=t.shortAmount;break;case Ui.SustainModEnv:this.modEnv.sustain=t.shortAmount;break;case Ui.ReleaseModEnv:this.modEnv.release=t.shortAmount;break;case Ui.KeynumToModEnvHold:this.modEnv.keynumToHold=t.shortAmount;break;case Ui.KeynumToModEnvDecay:this.modEnv.keynumToDecay=t.shortAmount;break;case Ui.DelayVolEnv:this.ampEnv.delay=t.shortAmount;break;case Ui.AttackVolEnv:this.ampEnv.attack=t.shortAmount;break;case Ui.HoldVolEnv:this.ampEnv.hold=t.shortAmount;break;case Ui.DecayVolEnv:this.ampEnv.decay=t.shortAmount;break;case Ui.SustainVolEnv:this.ampEnv.sustain=t.shortAmount;break;case Ui.ReleaseVolEnv:this.ampEnv.release=t.shortAmount;break;case Ui.KeynumToVolEnvHold:this.ampEnv.keynumToHold=t.shortAmount;break;case Ui.KeynumToVolEnvDecay:this.ampEnv.keynumToDecay=t.shortAmount;break;case Ui.KeyRange:this.loKey=t.lowByteAmount,this.hiKey=t.highByteAmount;break;case Ui.VelRange:this.loVel=t.lowByteAmount,this.hiVel=t.highByteAmount;break;case Ui.StartloopAddrsCoarseOffset:this.loopStart+=32768*Ee.int16ToUint32(t.shortAmount);break;case Ui.InitialAttenuation:this.attenuation+=.1*t.shortAmount;break;case Ui.EndloopAddrsCoarseOffset:this.loopEnd+=32768*Ee.int16ToUint32(t.shortAmount);break;case Ui.CoarseTune:this.transpose+=t.shortAmount;break;case Ui.FineTune:this.tune+=t.shortAmount;break;case Ui.SampleModes:this.loopMode=3&~t.wordAmount?1==(3&t.wordAmount)?Gi.Continuous:Gi.None:Gi.Sustain;break;case Ui.ScaleTuning:this.pitchKeyTrack=t.shortAmount;break;case Ui.ExclusiveClass:this.group=t.wordAmount;break;case Ui.OverridingRootKey:this.pitchKeyCenter=t.shortAmount}}}tr.NoSamples=new Float32Array(0),function(e){e[e.None=0]="None",e[e.Delay=1]="Delay",e[e.Attack=2]="Attack",e[e.Hold=3]="Hold",e[e.Decay=4]="Decay",e[e.Sustain=5]="Sustain",e[e.Release=6]="Release",e[e.Done=7]="Done"}(Xi||(Xi={}));class sr{constructor(){this.level=0,this.slope=0,this.samplesUntilNextSegment=0,this.segment=Xi.None,this.midiVelocity=0,this.parameters=null,this.segmentIsExponential=!1,this.isAmpEnv=!1}nextSegment(e,t){if(this.parameters)for(;;)switch(e){case Xi.None:if(this.samplesUntilNextSegment=this.parameters.delay*t|0,this.samplesUntilNextSegment>0)return this.segment=Xi.Delay,this.segmentIsExponential=!1,this.level=0,void(this.slope=0);e=Xi.Delay;break;case Xi.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=Xi.Attack,this.segmentIsExponential=!1,this.level=0,void(this.slope=1/this.samplesUntilNextSegment);e=Xi.Attack;break;case Xi.Attack:if(this.samplesUntilNextSegment=this.parameters.hold*t|0,this.samplesUntilNextSegment>0)return this.segment=Xi.Hold,this.segmentIsExponential=!1,this.level=1,void(this.slope=0);e=Xi.Hold;break;case Xi.Hold:if(this.samplesUntilNextSegment=this.parameters.decay*t|0,this.samplesUntilNextSegment>0){if(this.segment=Xi.Decay,this.level=1,this.isAmpEnv){const 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=Xi.Decay;break;case Xi.Decay:return this.segment=Xi.Sustain,this.level=this.parameters.sustain,this.slope=0,this.samplesUntilNextSegment=2147483647,void(this.segmentIsExponential=!1);case Xi.Sustain:if(this.segment=Xi.Release,this.samplesUntilNextSegment=(this.parameters.release<=0?sr.FastReleaseTime:this.parameters.release)*t|0,this.isAmpEnv){const 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=Xi.Done,this.segmentIsExponential=!1,this.level=0,this.slope=0,void(this.samplesUntilNextSegment=134217727)}}setup(e,t,s,i,a){this.parameters=new er(e),this.parameters.keynumToHold>0&&(this.parameters.hold+=this.parameters.keynumToHold*(60-t),this.parameters.hold=this.parameters.hold<-1e4?0:Za.timecents2Secs(this.parameters.hold)),this.parameters.keynumToDecay>0&&(this.parameters.decay+=this.parameters.keynumToDecay*(60-t),this.parameters.decay=this.parameters.decay<-1e4?0:Za.timecents2Secs(this.parameters.decay)),this.midiVelocity=0|s,this.isAmpEnv=i,this.nextSegment(Xi.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)}}sr.FastReleaseTime=.01;class ir{constructor(){this.samplesUntil=0,this.level=0,this.delta=0}setup(e,t,s){this.samplesUntil=e*s|0,this.delta=4*Za.cents2Hertz(t)/s,this.level=0}process(e){this.samplesUntil>e?this.samplesUntil-=e:(this.level+=this.delta*e,this.level>1?(this.delta=-this.delta,this.level=2-this.level):this.level<-1&&(this.delta=-this.delta,this.level=-2-this.level))}}class ar{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){const t=Math.tan(Math.PI*e),s=t*t,i=1/(1+t*this.qInv+s);this.a0=s*i,this.a1=2*this.a0,this.b1=2*(s-1)*i,this.b2=(1-t*this.qInv+s)*i}process(e){const 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 rr{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 sr,this.modEnv=new sr,this.lowPass=new ar,this.modLfo=new ir,this.vibLfo=new ir,this.mixVolume=0,this.mute=!1}updatePitchRatio(e,t){let s=e.pitchWheel;e.perNotePitchWheel.has(this.playingKey)&&(s+=e.perNotePitchWheel.get(this.playingKey)-8192);const i=8192===s?e.tuning:s/16383*e.pitchRange*2-e.pitchRange+e.tuning;this.calcPitchRatio(i,t)}calcPitchRatio(e,t){if(!this.region)return;const s=this.playingKey+this.region.transpose+this.region.tune/100;let i=this.region.pitchKeyCenter+(s-this.region.pitchKeyCenter)*(this.region.pitchKeyTrack/100);0!==e&&(i+=e),this.pitchInputTimecents=100*i,this.pitchOutputFactor=this.region.sampleRate/(Za.timecents2Secs(100*this.region.pitchKeyCenter)*t)}end(e){this.region&&(this.ampEnv.nextSegment(Xi.Sustain,e),this.modEnv.nextSegment(Xi.Sustain,e),this.region.loopMode===Gi.Sustain&&(this.loopEnd=this.loopStart))}endQuick(e){this.ampEnv.parameters.release=0,this.ampEnv.nextSegment(Xi.Sustain,e),this.modEnv.parameters.release=0,this.modEnv.nextSegment(Xi.Sustain,e)}render(e,t,s,i,a){if(!this.region)return;const r=this.region,n=r.samples;let o=0,h=e.outputMode===zi.StereoUnweaved?i:-1;const l=0!==r.modEnvToPitch||0!==r.modEnvToFilterFc,c=this.modLfo.delta>0&&(0!==r.modLfoToPitch||0!==r.modLfoToFilterFc||0!==r.modLfoToVolume),d=this.vibLfo.delta>0&&0!==r.vibLfoToPitch,u=this.loopStart<this.loopEnd,p=this.loopStart,g=this.loopEnd,m=r.end,f=g+1;let y=this.sourceSamplePosition;const b=new ar(this.lowPass),S=0!==r.modLfoToFilterFc||0!==r.modEnvToFilterFc;let _=0,w=0,B=0,k=0;const T=0!==r.modLfoToPitch||0!==r.modEnvToPitch||0!==r.vibLfoToPitch;let N=0,x=0,v=0,P=0;const F=0!==r.modLfoToVolume;let C=0,D=0;for(S?(_=e.outSampleRate,w=r.initialFilterFc,B=r.modLfoToFilterFc,k=r.modEnvToFilterFc):(_=0,w=0,B=0,k=0),T?(N=0,x=r.modLfoToPitch,v=r.vibLfoToPitch,P=r.modEnvToPitch):(N=Za.timecents2Secs(this.pitchInputTimecents)*this.pitchOutputFactor,x=0,v=0,P=0),F?D=.1*r.modLfoToVolume:(C=Za.decibelsToGain(this.noteGainDb),D=0);i>0;){let r,E,L=0,M=i>rr.RenderEffectSampleBlock?rr.RenderEffectSampleBlock:i;if(i-=M,S){const e=w+this.modLfo.level*B+this.modEnv.level*k;b.active=e<=13500,b.active&&b.setup(Za.cents2Hertz(e)/_)}switch(T&&(N=Za.timecents2Secs(this.pitchInputTimecents+(this.modLfo.level*x+this.vibLfo.level*v+this.modEnv.level*P))*this.pitchOutputFactor),F&&(C=Za.decibelsToGain(this.noteGainDb+this.modLfo.level*D)),r=C*this.ampEnv.level,a?r=0:r*=this.mixVolume,this.ampEnv.process(M,e.outSampleRate),l&&this.modEnv.process(M,e.outSampleRate),c&&this.modLfo.process(M),d&&this.vibLfo.process(M),e.outputMode){case zi.StereoInterleaved:for(E=r*this.panFactorLeft,L=r*this.panFactorRight;M-- >0&&y<m;){const e=0|y,i=e>=g&&u?p:e+1,a=y-e;let r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*E,o++,t[s+o]+=r*L,o++,y+=N,y>=f&&u&&(y-=g-p+1)}break;case zi.StereoUnweaved:for(E=r*this.panFactorLeft,L=r*this.panFactorRight;M-- >0&&y<m;){const e=0|y,i=e>=g&&u?p:e+1,a=y-e;let r=n[e]*(1-a)+n[i]*a;b.active&&(r=b.process(r)),t[s+o]+=r*E,o++,t[s+h]+=r*L,h++,y+=N,y>=f&&u&&(y-=g-p+1)}break;case zi.Mono:for(;M-- >0&&y<m;){const e=0|y,i=e>=g&&u?p:e+1,a=y-e;let h=n[e]*(1-a)+n[i]*a;b.active&&(h=b.process(h)),t[s+o]=h*r,o++,y+=N,y>=f&&u&&(y-=g-p+1)}}if(y>=m||this.ampEnv.segment===Xi.Done)return void this.kill()}this.sourceSamplePosition=y,(b.active||S)&&(this.lowPass=b)}kill(){this.playingPreset=-1}}rr.RenderEffectSampleBlock=Ls.MicroBufferSize;class nr{constructor(){this._items=[],this._position=0,this.isEmpty=!0}clear(){this._items=[],this._position=0,this.isEmpty=!0}enqueue(e){this.isEmpty=!1,this._items.push(e)}peek(){return this._items[this._position]}dequeue(){const e=this._items[this._position];return this._position++,this._position>=this._items.length/2&&(this._items=this._items.slice(this._position),this._position=0),this.isEmpty=0===this._items.length,e}toArray(){const e=this._items.slice(this._position);return e.reverse(),e}}!function(e){e[e.BankSelectCoarse=0]="BankSelectCoarse",e[e.ModulationCoarse=1]="ModulationCoarse",e[e.DataEntryCoarse=6]="DataEntryCoarse",e[e.VolumeCoarse=7]="VolumeCoarse",e[e.PanCoarse=10]="PanCoarse",e[e.ExpressionControllerCoarse=11]="ExpressionControllerCoarse",e[e.BankSelectFine=32]="BankSelectFine",e[e.ModulationFine=33]="ModulationFine",e[e.DataEntryFine=38]="DataEntryFine",e[e.VolumeFine=39]="VolumeFine",e[e.PanFine=42]="PanFine",e[e.ExpressionControllerFine=43]="ExpressionControllerFine",e[e.HoldPedal=64]="HoldPedal",e[e.LegatoPedal=68]="LegatoPedal",e[e.NonRegisteredParameterFine=98]="NonRegisteredParameterFine",e[e.NonRegisteredParameterCourse=99]="NonRegisteredParameterCourse",e[e.RegisteredParameterFine=100]="RegisteredParameterFine",e[e.RegisteredParameterCourse=101]="RegisteredParameterCourse",e[e.AllSoundOff=120]="AllSoundOff",e[e.ResetControllers=121]="ResetControllers",e[e.AllNotesOff=123]="AllNotesOff"}(Ji||(Ji={}));class or{constructor(e){this._midiEventQueue=new nr,this._mutedChannels=new Map,this._soloChannels=new Map,this._isAnySolo=!1,this._transpositionPitches=new Map,this._liveTranspositionPitches=new Map,this.currentTempo=0,this.timeSignatureNumerator=0,this.timeSignatureDenominator=0,this.presets=null,this._voices=[],this._channels=null,this._voicePlayIndex=0,this.outputMode=zi.StereoInterleaved,this.outSampleRate=0,this.globalGainDb=0,this.outSampleRate=e}synthesize(e,t,s){return this.fillWorkingBuffer(e,t,s)}synthesizeSilent(e){this.fillWorkingBuffer(null,0,e)}channelGetMixVolume(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].mixVolume:1}channelSetMixVolume(e,t){const s=this.channelInit(e);for(const s of this._voices)s.playingChannel===e&&-1!==s.playingPreset&&(s.mixVolume=t);s.mixVolume=t}channelSetMute(e,t){t?this._mutedChannels.set(e,!0):this._mutedChannels.delete(e)}channelSetSolo(e,t){t?this._soloChannels.set(e,!0):this._soloChannels.delete(e),this._isAnySolo=this._soloChannels.size>0}resetChannelStates(){this._mutedChannels=new Map,this._soloChannels=new Map,this._liveTranspositionPitches=new Map,this.applyTranspositionPitches(new Map),this._isAnySolo=!1}setChannelTranspositionPitch(e,t){let s=0;this._liveTranspositionPitches.has(e)&&(s=this._liveTranspositionPitches.get(e)),0===t?this._liveTranspositionPitches.delete(e):this._liveTranspositionPitches.set(e,t);for(const i of this._voices)if(i.playingChannel===e&&9!==i.playingChannel){let e=0;e-=s,e+=t,i.playingKey+=e,this._channels&&i.updatePitchRatio(this._channels.channelList[i.playingChannel],this.outSampleRate)}}applyTranspositionPitches(e){const t=this._transpositionPitches;for(const s of this._voices)if(s.playingChannel>=0&&9!==s.playingChannel){let i=0;t.has(s.playingChannel)&&(i-=t.get(s.playingChannel)),e.has(s.playingChannel)&&(i+=e.get(s.playingChannel)),s.playingKey+=i,this._channels&&s.updatePitchRatio(this._channels.channelList[s.playingChannel],this.outSampleRate)}this._transpositionPitches=e}dispatchEvent(e){this._midiEventQueue.enqueue(e)}fillWorkingBuffer(e,t,s){const i=this._isAnySolo,a=[];for(;!this._midiEventQueue.isEmpty;){const e=this._midiEventQueue.dequeue();e.isMetronome&&this.metronomeVolume>0?(this.channelNoteOff(Ls.MetronomeChannel,Ls.MetronomeKey),this.channelNoteOn(Ls.MetronomeChannel,Ls.MetronomeKey,95/127)):e.event&&this.processMidiMessage(e.event),a.push(e)}for(const a of this._voices)if(-1!==a.playingPreset){const r=a.playingChannel,n=this._mutedChannels.has(r)||i&&r!==Ls.MetronomeChannel&&!this._soloChannels.has(r);e?a.render(this,e,t,s,n):a.kill()}return a}processMidiMessage(e){wt.debug("Midi",`Processing Midi message ${U[e.type]}/${e.tick}`);switch(e.type){case U.TimeSignature:const t=e;this.timeSignatureNumerator=t.numerator,this.timeSignatureDenominator=Math.pow(2,t.denominatorIndex);break;case U.NoteOn:const s=e;this.channelNoteOn(s.channel,s.noteKey,s.noteVelocity/127);break;case U.NoteOff:const i=e;this.channelNoteOff(i.channel,i.noteKey);break;case U.ControlChange:const a=e;this.channelMidiControl(a.channel,a.controller,a.value);break;case U.ProgramChange:const r=e;this.channelSetPresetNumber(r.channel,r.program,9===r.channel);break;case U.TempoChange:const n=e;this.currentTempo=6e7/n.microSecondsPerQuarterNote;break;case U.PitchBend:const o=e;this.channelSetPitchWheel(o.channel,o.value);break;case U.PerNotePitchBend:const h=e;let l=h.value;l=l*Ls.MaxPitchWheel/Ls.MaxPitchWheel20,this.channelSetPerNotePitchWheel(h.channel,h.noteKey,l)}}get metronomeVolume(){return this.channelGetMixVolume(Ls.MetronomeChannel)}set metronomeVolume(e){this.setupMetronomeChannel(e)}setupMetronomeChannel(e){this.channelSetMixVolume(Ls.MetronomeChannel,e),e>0&&(this.channelSetVolume(Ls.MetronomeChannel,1),this.channelSetPresetNumber(Ls.MetronomeChannel,0,!0))}get masterVolume(){return Za.decibelsToGain(this.globalGainDb)}set masterVolume(e){const t=Za.gainToDecibels(e),s=t-this.globalGainDb;if(0!==s){for(const e of this._voices)-1!==e.playingPreset&&(e.noteGainDb+=s);this.globalGainDb=t}}resetSoft(){for(const e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<Xi.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);if(this._channels)for(const e of this._channels.channelList)e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.perNotePitchWheel.clear(),e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0}get presetCount(){return this.presets?.length??0}reset(){for(const e of this._voices)-1!==e.playingPreset&&(e.ampEnv.segment<Xi.Release||0!==e.ampEnv.parameters.release)&&e.endQuick(this.outSampleRate);this._channels=null}setOutput(e,t,s){this.outputMode=e,this.outSampleRate=t>=1?t:44100,this.globalGainDb=s}noteOn(e,t,s){if(!this.presets)return;const i=127*s|0;if(e<0||e>=this.presets.length)return;if(s<=0)return void this.noteOff(e,t);const a=this._voicePlayIndex++;for(const r of this.presets[e].regions){if(t<r.loKey||t>r.hiKey||i<r.loVel||i>r.hiVel)continue;let n=null;if(0!==r.group)for(const t of this._voices)t.playingPreset===e&&t.region.group===r.group?t.endQuick(this.outSampleRate):-1!==t.playingPreset||n||(n=t);else for(const e of this._voices)-1===e.playingPreset&&(n=e);if(!n){for(let e=0;e<4;e++){const e=new rr;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-Za.gainToDecibels(1/s),this._channels?this._channels.setupVoice(this,n):(n.calcPitchRatio(0,this.outSampleRate),n.panFactorLeft=Math.sqrt(.5-r.pan),n.panFactorRight=Math.sqrt(.5+r.pan)),n.sourceSamplePosition=r.offset;const o=r.loopMode!==Gi.None&&r.loopStart<r.loopEnd;n.loopStart=o?r.loopStart:0,n.loopEnd=o?r.loopEnd:0,n.ampEnv.setup(r.ampEnv,t,i,!0,this.outSampleRate),n.modEnv.setup(r.modEnv,t,i,!1,this.outSampleRate);const h=r.initialFilterQ/10;n.lowPass.qInv=1/Math.pow(10,h/20),n.lowPass.z1=0,n.lowPass.z2=0,n.lowPass.active=r.initialFilterFc<=13500,n.lowPass.active&&n.lowPass.setup(Za.cents2Hertz(r.initialFilterFc)/this.outSampleRate),n.modLfo.setup(r.delayModLFO,r.freqModLFO,this.outSampleRate),n.vibLfo.setup(r.delayVibLFO,r.freqVibLFO,this.outSampleRate)}}bankNoteOn(e,t,s,i){const a=this.getPresetIndex(e,t);return-1!==a&&(this.noteOn(a,s,i),!0)}noteOff(e,t){let s=null,i=null;const a=[];for(const r of this._voices)r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=Xi.Release||(!s||r.playIndex<s.playIndex?(s=r,i=r,a.push(r)):r.playIndex===s.playIndex&&(i=r,a.push(r)));if(s)for(const r of a)r!==s&&r!==i&&(r.playIndex!==s.playIndex||r.playingPreset!==e||r.playingKey!==t||r.ampEnv.segment>=Xi.Release)||r.end(this.outSampleRate)}bankNoteOff(e,t,s){const i=this.getPresetIndex(e,t);return-1!==i&&(this.noteOff(i,s),!0)}noteOffAll(e){for(const t of this._voices)-1!==t.playingPreset&&(e?t.endQuick(this.outSampleRate):t.ampEnv.segment<Xi.Release&&t.end(this.outSampleRate))}get activeVoiceCount(){let e=0;for(const t of this._voices)-1!==t.playingPreset&&e++;return e}channelInit(e){if(this._channels&&e<this._channels.channelList.length)return this._channels.channelList[e];this._channels||(this._channels=new ja);for(let t=this._channels.channelList.length;t<=e;t++){const e=new Ka;e.presetIndex=0,e.bank=0,e.pitchWheel=8192,e.midiPan=8192,e.midiVolume=16383,e.midiExpression=16383,e.midiRpn=65535,e.midiData=0,e.panOffset=0,e.gainDb=0,e.pitchRange=2,e.tuning=0,e.mixVolume=1,this._channels.channelList.push(e)}return this._channels.channelList[e]}getPresetIndex(e,t){if(!this.presets)return-1;for(let s=this.presets.length-1;s>=0;s--){const i=this.presets[s];if(i.presetNumber===t&&i.bank===e)return s}return-1}getPresetName(e){return this.presets?e<0||e>=this.presets.length?null:this.presets[e].name:null}bankGetPresetName(e,t){return this.getPresetName(this.getPresetIndex(e,t))}channelNoteOn(e,t,s){!this._channels||e>this._channels.channelList.length||(this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e)),this._channels.activeChannel=e,this.noteOn(this._channels.channelList[e].presetIndex,t,s))}channelNoteOff(e,t){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e));const s=[];let i=null,a=null;for(const r of this._voices)-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=Xi.Release||(!i||r.playIndex<i.playIndex?(i=r,a=r,s.push(r)):r.playIndex===i.playIndex&&(a=r,s.push(r)));if(this.channelInit(e).perNotePitchWheel.delete(t),i)for(const r of s)r!==i&&r!==a&&(r.playIndex!==i.playIndex||-1===r.playingPreset||r.playingChannel!==e||r.playingKey!==t||r.ampEnv.segment>=Xi.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<Xi.Release&&t.end(this.outSampleRate)}channelSoundsOffAll(e){this.channelInit(e).perNotePitchWheel.clear();for(const t of this._voices)-1!==t.playingPreset&&t.playingChannel===e&&(t.ampEnv.segment<Xi.Release||0===t.ampEnv.parameters.release)&&t.endQuick(this.outSampleRate)}channelSetPresetIndex(e,t){this.channelInit(e).presetIndex=Ee.int32ToUint16(t)}channelSetPresetNumber(e,t,s=!1){const i=this.channelInit(e);let a=0;return s?(a=this.getPresetIndex(128|32767&i.bank,t),-1===a&&(a=this.getPresetIndex(128,t)),-1===a&&(a=this.getPresetIndex(128,0)),-1===a&&(a=this.getPresetIndex(2047&i.bank,t))):a=this.getPresetIndex(2047&i.bank,t),i.presetIndex=a,-1!==a}channelSetBank(e,t){this.channelInit(e).bank=Ee.int32ToUint16(t)}channelSetBankPreset(e,t,s){const i=this.channelInit(e),a=this.getPresetIndex(t,s);return-1!==a&&(i.presetIndex=Ee.int32ToUint16(a),i.bank=Ee.int32ToUint16(t),!0)}channelSetPan(e,t){for(const s of this._voices)if(s.playingChannel===e&&-1!==s.playingPreset){const e=s.region.pan+t-.5;e<=-.5?(s.panFactorLeft=1,s.panFactorRight=0):e>=.5?(s.panFactorLeft=0,s.panFactorRight=1):(s.panFactorLeft=Math.sqrt(.5-e),s.panFactorRight=Math.sqrt(.5+e))}this.channelInit(e).panOffset=t-.5}channelSetVolume(e,t){const s=this.channelInit(e),i=Za.gainToDecibels(t),a=i-s.gainDb;if(0!==a){for(const t of this._voices)t.playingChannel===e&&-1!==t.playingPreset&&(t.noteGainDb+=a);s.gainDb=i}}channelSetPitchWheel(e,t){const s=this.channelInit(e);s.pitchWheel!==t&&(s.pitchWheel=Ee.int32ToUint16(t),this.channelApplyPitch(e,s))}channelSetPerNotePitchWheel(e,t,s){this._transpositionPitches.has(e)&&(t+=this._transpositionPitches.get(e)),this._liveTranspositionPitches.has(e)&&(t+=this._liveTranspositionPitches.get(e));const i=this.channelInit(e);i.perNotePitchWheel.has(t)&&i.perNotePitchWheel.get(t)===s||(i.perNotePitchWheel.set(t,s),this.channelApplyPitch(e,i,t))}channelApplyPitch(e,t,s=-1){for(const i of this._voices)i.playingChannel!==e||-1===i.playingPreset||-1!==s&&i.playingKey!==s||i.updatePitchRatio(t,this.outSampleRate)}channelSetPitchRange(e,t){const s=this.channelInit(e);s.pitchRange!==t&&(s.pitchRange=t,8192!==s.pitchWheel&&this.channelApplyPitch(e,s))}channelSetTuning(e,t){const s=this.channelInit(e);s.tuning!==t&&(s.tuning=t,this.channelApplyPitch(e,s))}channelMidiControl(e,t,s){const i=this.channelInit(e);switch(t){case Ji.DataEntryFine:return i.midiData=Ee.int32ToUint16(16256&i.midiData|s),void(0===i.midiRpn?this.channelSetPitchRange(e,(i.midiData>>7)+.01*(127&i.midiData)):1===i.midiRpn?this.channelSetTuning(e,(0|i.tuning)+(i.midiData-8192)/8192):2===i.midiRpn&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Ji.VolumeCoarse:return i.midiVolume=Ee.int32ToUint16(127&i.midiVolume|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Ji.VolumeFine:return i.midiVolume=Ee.int32ToUint16(16256&i.midiVolume|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Ji.ExpressionControllerCoarse:return i.midiExpression=Ee.int32ToUint16(127&i.midiExpression|s<<7),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Ji.ExpressionControllerFine:return i.midiExpression=Ee.int32ToUint16(16256&i.midiExpression|s),void this.channelSetVolume(e,Math.pow(i.midiVolume/16383*(i.midiExpression/16383),3));case Ji.PanCoarse:return i.midiPan=Ee.int32ToUint16(127&i.midiPan|s<<7),void this.channelSetPan(e,i.midiPan/16383);case Ji.PanFine:return i.midiPan=Ee.int32ToUint16(16256&i.midiPan|s),void this.channelSetPan(e,i.midiPan/16383);case Ji.DataEntryCoarse:return i.midiData=Ee.int32ToUint16(127&i.midiData|s<<7),void(0===i.midiRpn?this.channelSetPitchRange(e,(i.midiData>>7)+.01*(127&i.midiData)):1===i.midiRpn?this.channelSetTuning(e,(0|i.tuning)+(i.midiData-8192)/8192):2===i.midiRpn&&t===Ji.DataEntryCoarse&&this.channelSetTuning(e,s-64+(i.tuning-(0|i.tuning))));case Ji.BankSelectCoarse:return void(i.bank=Ee.int32ToUint16(32768|s));case Ji.BankSelectFine:return void(i.bank=Ee.int32ToUint16((32768&i.bank?(127&i.bank)<<7:0)|s));case Ji.RegisteredParameterCourse:return void(i.midiRpn=Ee.int32ToUint16(127&(65535===i.midiRpn?0:i.midiRpn)|s<<7));case Ji.RegisteredParameterFine:return void(i.midiRpn=Ee.int32ToUint16(16256&(65535===i.midiRpn?0:i.midiRpn)|s));case Ji.NonRegisteredParameterFine:case Ji.NonRegisteredParameterCourse:return void(i.midiRpn=65535);case Ji.AllSoundOff:return void this.channelSoundsOffAll(e);case Ji.AllNotesOff:return void this.channelNoteOffAll(e);case Ji.ResetControllers:return i.midiVolume=16383,i.midiExpression=16383,i.midiPan=8192,i.bank=0,this.channelSetVolume(e,1),this.channelSetPan(e,.5),void this.channelSetPitchRange(e,2)}}channelGetPresetIndex(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].presetIndex:0}channelGetPresetBank(e){return this._channels&&e<this._channels.channelList.length?32767&this._channels.channelList[e].bank:0}channelGetPan(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].panOffset-.5:.5}channelGetVolume(e){return this._channels&&e<this._channels.channelList.length?Za.decibelsToGain(this._channels.channelList[e].gainDb):1}channelGetPitchWheel(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchWheel:8192}channelGetPitchRange(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].pitchRange:2}channelGetTuning(e){return this._channels&&e<this._channels.channelList.length?this._channels.channelList[e].tuning:0}resetPresets(){this.presets=[]}loadPresets(e,t,s,i){const a=[];for(let i=0;i<e.phdrs.length-1;i++){const r=e.phdrs[i];let n=0;const o=new Qa;a.push(o),o.name=r.presetName,o.bank=r.bank,o.presetNumber=r.preset;let h=0;for(let t=r.presetBagNdx;t<e.phdrs[i+1].presetBagNdx;t++){let s=0,i=127,a=0,r=127;for(let n=e.pbags[t].genNdx;n<e.pbags[t+1].genNdx;n++){const t=e.pgens[n];if(t.genOper===Xa.GenKeyRange){s=t.genAmount.lowByteAmount,i=t.genAmount.highByteAmount;continue}if(t.genOper===Xa.GenVelRange){a=t.genAmount.lowByteAmount,r=t.genAmount.highByteAmount;continue}if(t.genOper!==Xa.GenInstrument)continue;if(t.genAmount.wordAmount>=e.insts.length)continue;for(let n=e.insts[t.genAmount.wordAmount].instBagNdx;n<e.insts[t.genAmount.wordAmount+1].instBagNdx;n++){let t=0,o=127,l=0,c=127;for(let d=e.ibags[n].instGenNdx;d<e.ibags[n+1].instGenNdx;d++){const n=e.igens[d];n.genOper!==Xa.GenKeyRange?n.genOper!==Xa.GenVelRange?53===n.genOper&&o>=s&&t<=i&&c>=a&&l<=r&&h++:(l=n.genAmount.lowByteAmount,c=n.genAmount.highByteAmount):(t=n.genAmount.lowByteAmount,o=n.genAmount.highByteAmount)}}}}o.regions=new Array(h);let l=new tr;l.clear(!0);for(let a=r.presetBagNdx;a<e.phdrs[i+1].presetBagNdx;a++){const i=e.pbags[a],h=new tr(l);let c=!1;for(let l=i.genNdx;l<e.pbags[a+1].genNdx;l++){const i=e.pgens[l];if(i.genOper===Xa.GenInstrument){const a=i.genAmount.wordAmount;if(a>=e.insts.length)continue;let l=new tr;l.clear(!1);const d=e.insts[a];for(let i=d.instBagNdx;i<e.insts[a+1].instBagNdx;i++){const a=e.ibags[i],c=new tr(l);let u=!1;for(let l=a.instGenNdx;l<e.ibags[i+1].instGenNdx;l++){const i=e.igens[l];if(i.genOper===Xa.GenSampleId){if(c.hiKey<h.loKey||c.loKey>h.hiKey)continue;if(c.hiVel<h.loVel||c.loVel>h.hiVel)continue;h.loKey>c.loKey&&(c.loKey=h.loKey),h.hiKey<c.hiKey&&(c.hiKey=h.hiKey),h.loVel>c.loVel&&(c.loVel=h.loVel),h.hiVel<c.hiVel&&(c.hiVel=h.hiVel),c.offset+=h.offset,c.end+=h.end,c.loopStart+=h.loopStart,c.loopEnd+=h.loopEnd,c.transpose+=h.transpose,c.tune+=h.tune,c.pitchKeyTrack+=h.pitchKeyTrack,c.attenuation+=h.attenuation,c.pan+=h.pan,c.ampEnv.delay+=h.ampEnv.delay,c.ampEnv.attack+=h.ampEnv.attack,c.ampEnv.hold+=h.ampEnv.hold,c.ampEnv.decay+=h.ampEnv.decay,c.ampEnv.sustain+=h.ampEnv.sustain,c.ampEnv.release+=h.ampEnv.release,c.modEnv.delay+=h.modEnv.delay,c.modEnv.attack+=h.modEnv.attack,c.modEnv.hold+=h.modEnv.hold,c.modEnv.decay+=h.modEnv.decay,c.modEnv.sustain+=h.modEnv.sustain,c.modEnv.release+=h.modEnv.release,c.initialFilterQ+=h.initialFilterQ,c.initialFilterFc+=h.initialFilterFc,c.modEnvToPitch+=h.modEnvToPitch,c.modEnvToFilterFc+=h.modEnvToFilterFc,c.delayModLFO+=h.delayModLFO,c.freqModLFO+=h.freqModLFO,c.modLfoToPitch+=h.modLfoToPitch,c.modLfoToFilterFc+=h.modLfoToFilterFc,c.modLfoToVolume+=h.modLfoToVolume,c.delayVibLFO+=h.delayVibLFO,c.freqVibLFO+=h.freqVibLFO,c.vibLfoToPitch+=h.vibLfoToPitch,c.ampEnv.envToSecs(!0),c.modEnv.envToSecs(!1),c.delayModLFO=c.delayModLFO<-11950?0:Za.timecents2Secs(c.delayModLFO),c.delayVibLFO=c.delayVibLFO<-11950?0:Za.timecents2Secs(c.delayVibLFO),c.pan<-.5?c.pan=-.5:c.pan>.5&&(c.pan=.5),(c.initialFilterQ<1500||c.initialFilterQ>13500)&&(c.initialFilterQ=0);const a=e.sHdrs[i.genAmount.wordAmount];c.offset+=a.start,c.end+=a.end,c.loopStart+=a.startLoop,c.loopEnd+=a.endLoop,a.endLoop>0&&(c.loopEnd-=1),-1===c.pitchKeyCenter&&(c.pitchKeyCenter=a.originalPitch),c.tune+=a.pitchCorrection,c.sampleRate=a.sampleRate;const l=r.bank===Ls.PercussionBank;if(l&&or.setContainsRange(s,c.loKey,c.hiKey)||!l&&t.has(r.preset))if(1&a.sampleType){wt.debug("AlphaSynth",`Loading of used sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`);!!(16&a.sampleType)?c.samples=e.decodeSamples(a.start,a.end,!0):(c.samples=e.decodeSamples(2*c.offset,2*c.end,!1),c.loopStart>0&&(c.loopStart-=c.offset),c.loopEnd>0&&(c.loopEnd-=c.offset)),c.offset=0,c.end=c.samples.length-1}else wt.warning("AlphaSynth",`Skipping load of unsupported sample ${a.sampleName} for preset ${r.presetName}, sample type ${a.sampleType} is not supported (bank ${o.bank} program ${o.presetNumber})`),c.samples=new Float32Array(0);else wt.debug("AlphaSynth",`Skipping load of unused sample ${a.sampleName} for preset ${r.presetName} (bank ${o.bank} program ${o.presetNumber})`),c.samples=new Float32Array(0);o.regions[n]=new tr(c),n++,u=!0}else c.operator(i.genOper,i.genAmount)}a!==e.ibags[d.instBagNdx]||u||(l=new tr(c))}c=!0}else h.operator(i.genOper,i.genAmount)}i!==e.pbags[r.presetBagNdx]||c||(l=h)}}if(i&&this.presets)for(const e of a)this.presets.push(e);else this.presets=a}static setContainsRange(e,t,s){for(let i=t;i<=s;i++)if(e.has(i))return!0;return!1}hasSamplesForProgram(e){const t=this.presets;if(!t)return!1;for(const s of t)if(s.presetNumber===e)for(const e of s.regions)if(e.samples.length>0)return!0;return!1}hasSamplesForPercussion(e){const t=this.presets;if(!t)return!1;for(const s of t)if(s.bank===Ls.PercussionBank)for(const t of s.regions)if(t.loKey>=e&&t.hiKey<=e&&t.samples.length>0)return!0;return!1}}class hr{constructor(e){this.events=e}}class lr{constructor(e){this.playbackRange=e}}class cr{get output(){return this._output}get isReadyForPlayback(){return this.isReady&&this._isSoundFontLoaded&&this._isMidiLoaded}get logLevel(){return wt.logLevel}set logLevel(e){wt.logLevel=e}get masterVolume(){return this._synthesizer.masterVolume}set masterVolume(e){e=Math.max(e,Ls.MinVolume),this._synthesizer.masterVolume=e}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Ls.MinVolume),this._metronomeVolume=e,this._synthesizer.metronomeVolume=e}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Ls.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=Be.clamp(e,Ls.MinPlaybackSpeed,Ls.MaxPlaybackSpeed);const 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){wt.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 lr(e))}get isLooping(){return this._sequencer.isLooping}set isLooping(e){this._sequencer.isLooping=e}destroy(){wt.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 nr,this._midiEventsPlayedFilter=new Set,this._notPlayedSamples=0,this._synthStopping=!1,this.isReady=!1,this.state=Hi.Paused,this._loadedSoundFonts=[],this.ready=new Si,this.readyForPlayback=new Si,this.finished=new Si,this.soundFontLoaded=new Si,this.soundFontLoadFailed=new _i,this.midiLoaded=new _i,this.midiLoadFailed=new _i,this.stateChanged=new _i,this.positionChanged=new _i,this.midiEventsPlayed=new _i,this.playbackRangeChanged=new _i,wt.debug("AlphaSynth","Initializing player"),this.state=Hi.Paused,wt.debug("AlphaSynth","Creating output"),this._output=e,wt.debug("AlphaSynth","Creating synthesizer"),this._synthesizer=new or(this.output.sampleRate),this._sequencer=new Oi(this._synthesizer),wt.debug("AlphaSynth","Opening output"),this.output.ready.on((()=>{this.isReady=!0,this.ready.trigger(),this.checkReadyForPlayback()})),this.output.sampleRequest.on((()=>{if(this.state===Hi.Playing&&(!this._sequencer.isFinished||this._synthesizer.activeVoiceCount>0)){let e=new Float32Array(Ls.MicroBufferSize*Ls.MicroBufferCount*Ls.AudioChannels),t=0;for(let s=0;s<Ls.MicroBufferCount;s++){this._sequencer.fillMidiEventQueue();const s=this._synthesizer.synthesize(e,t,Ls.MicroBufferSize);t+=Ls.MicroBufferSize*Ls.AudioChannels;for(const e of s)this._midiEventsPlayedFilter.has(e.event.type)&&this._playedEventsQueue.enqueue(e);if(this._sequencer.isFinished)break}t<e.length&&(e=e.subarray(0,t)),this._notPlayedSamples+=e.length,this.output.addSamples(e)}else{const e=new Float32Array(0);this.output.addSamples(e)}})),this.output.samplesPlayed.on(this.onSamplesPlayed.bind(this)),this.output.open(t)}play(){return!(this.state!==Hi.Paused||!this._isMidiLoaded)&&(this.output.activate(),this.playInternal(),this._countInVolume>0&&(wt.debug("AlphaSynth","Starting countin"),this._sequencer.startCountIn(),this._synthesizer.setupMetronomeChannel(this._countInVolume),this.updateTimePosition(0,!0)),this.output.play(),!0)}playInternal(){this._sequencer.isPlayingOneTimeMidi&&(wt.debug("AlphaSynth","Cancelling one time midi"),this.stopOneTimeMidi()),wt.debug("AlphaSynth","Starting playback"),this._synthesizer.setupMetronomeChannel(this.metronomeVolume),this._synthStopping=!1,this.state=Hi.Playing,this.stateChanged.trigger(new ia(this.state,!1))}pause(){this.state!==Hi.Paused&&this._isMidiLoaded&&(wt.debug("AlphaSynth","Pausing playback"),this.state=Hi.Paused,this.stateChanged.trigger(new ia(this.state,!1)),this.output.pause(),this._synthesizer.noteOffAll(!1))}playPause(){this.state===Hi.Paused&&this._isMidiLoaded?this.play():this.pause()}stop(){this._isMidiLoaded&&(wt.debug("AlphaSynth","Stopping playback"),this.state=Hi.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 ia(this.state,!0)))}playOneTimeMidiFile(e){this._sequencer.isPlayingOneTimeMidi?this.stopOneTimeMidi():this.pause(),this._sequencer.loadOneTimeMidi(e),this._synthesizer.noteOffAll(!0),this.updateTimePosition(0,!0),this._notPlayedSamples=0,this.output.resetSamples(),this.output.play()}resetSoundFonts(){this.stop(),this._synthesizer.resetPresets(),this._loadedSoundFonts=[],this._isSoundFontLoaded=!1,this.soundFontLoaded.trigger()}loadSoundFont(e,t){this.pause();const s=Me.fromBuffer(e);try{wt.debug("AlphaSynth","Loading soundfont from bytes");const e=new Ha;e.load(s),t||(this._loadedSoundFonts=[]),this._loadedSoundFonts.push(e),this._isSoundFontLoaded=!0,this.soundFontLoaded.trigger(),wt.debug("AlphaSynth","soundFont successfully loaded"),this.checkReadyForPlayback()}catch(e){wt.error("AlphaSynth",`Could not load soundfont from bytes ${e}`),this.soundFontLoadFailed.trigger(e)}}checkReadyForPlayback(){if(this.isReadyForPlayback){this._synthesizer.setupMetronomeChannel(this.metronomeVolume);const e=this._sequencer.instrumentPrograms,t=this._sequencer.percussionKeys;let s=!1;for(const i of this._loadedSoundFonts)this._synthesizer.loadPresets(i,e,t,s),s=!0;this.readyForPlayback.trigger()}}loadMidiFile(e){this.stop();try{wt.debug("AlphaSynth","Loading midi from model"),this._sequencer.loadMidi(e),this._isMidiLoaded=!0,this.midiLoaded.trigger(new aa(0,this._sequencer.currentEndTime,0,this._sequencer.currentEndTick,!1)),wt.debug("AlphaSynth","Midi successfully loaded"),this.checkReadyForPlayback(),this.tickPosition=0}catch(e){wt.error("AlphaSynth",`Could not load midi from model ${e}`),this.midiLoadFailed.trigger(e)}}applyTranspositionPitches(e){this._synthesizer.applyTranspositionPitches(e)}setChannelTranspositionPitch(e,t){this._synthesizer.setChannelTranspositionPitch(e,t)}setChannelMute(e,t){this._synthesizer.channelSetMute(e,t)}resetChannelStates(){this._synthesizer.resetChannelStates()}setChannelSolo(e,t){this._synthesizer.channelSetSolo(e,t)}setChannelVolume(e,t){t=Math.max(t,Ls.MinVolume),this._synthesizer.channelSetMixVolume(e,t)}onSamplesPlayed(e){if(0===e)return;const t=e/this._synthesizer.outSampleRate*1e3;this._notPlayedSamples-=e*Ls.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?(wt.debug("AlphaSynth","Finished playback (count-in)"),this._sequencer.resetCountIn(),this.timePosition=this._sequencer.currentTime,this.playInternal(),this.output.resetSamples()):this._sequencer.isPlayingOneTimeMidi?(wt.debug("AlphaSynth","Finished playback (one time)"),this.output.resetSamples(),this.state=Hi.Paused,this.stopOneTimeMidi()):this.isLooping?(wt.debug("AlphaSynth","Finished playback (main looping)"),this.finished.trigger(),this.tickPosition=e,this._synthStopping=!1):this._synthesizer.activeVoiceCount>0?this._synthStopping||(this._synthesizer.noteOffAll(!0),this._synthStopping=!0):(this._synthStopping=!1,wt.debug("AlphaSynth","Finished playback (main)"),this.finished.trigger(),this.stop()))}stopOneTimeMidi(){this.output.pause(),this._synthesizer.noteOffAll(!0),this._sequencer.resetOneTimeMidi(),this.timePosition=this._sequencer.currentTime}updateTimePosition(e,t){let s=e;this._timePosition=s;let i=this._sequencer.currentTimePositionToTickPosition(s);this._tickPosition=i;const a=this._sequencer.currentEndTime,r=this._sequencer.currentEndTick;s>a&&(s=a,i=r);const n=this._sequencer.isPlayingMain?"main":this._sequencer.isPlayingCountIn?"count-in":"one-time";if(wt.debug("AlphaSynth",`Position changed: (time: ${s}/${a}, tick: ${i}/${r}, Active Voices: ${this._synthesizer.activeVoiceCount} (${n})`),this._sequencer.isPlayingMain&&this.positionChanged.trigger(new aa(s,a,i,r,t)),t)this._playedEventsQueue.clear();else{const e=new nr;for(;!this._playedEventsQueue.isEmpty&&this._playedEventsQueue.peek().time<s;){const t=this._playedEventsQueue.dequeue();e.enqueue(t.event)}e.isEmpty||this.midiEventsPlayed.trigger(new hr(e.toArray()))}}hasSamplesForProgram(e){return this._synthesizer.hasSamplesForProgram(e)}hasSamplesForPercussion(e){return this._synthesizer.hasSamplesForPercussion(e)}}class dr{constructor(){this.ready=new Si,this.samplesPlayed=new _i,this.sampleRequest=new Si}get sampleRate(){return dr.preferredSampleRate}open(){wt.debug("AlphaSynth","Initializing synth worker"),this._worker=cc.globalThis,this._worker.addEventListener("message",this.handleMessage.bind(this)),this.ready.trigger()}destroy(){this._worker.postMessage({cmd:"alphaSynth.output.destroy"})}handleMessage(e){const t=e.data;switch(t.cmd){case dr.CmdOutputSampleRequest:this.sampleRequest.trigger();break;case dr.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(){}async enumerateOutputDevices(){return[]}async setOutputDevice(e){}async getOutputDevice(){return null}}dr.CmdOutputPrefix="alphaSynth.output.",dr.CmdOutputAddSamples=`${dr.CmdOutputPrefix}addSamples`,dr.CmdOutputPlay=`${dr.CmdOutputPrefix}play`,dr.CmdOutputPause=`${dr.CmdOutputPrefix}pause`,dr.CmdOutputResetSamples=`${dr.CmdOutputPrefix}resetSamples`,dr.CmdOutputStop=`${dr.CmdOutputPrefix}stop`,dr.CmdOutputSampleRequest=`${dr.CmdOutputPrefix}sampleRequest`,dr.CmdOutputSamplesPlayed=`${dr.CmdOutputPrefix}samplesPlayed`,dr.preferredSampleRate=0;class ur{constructor(e,t){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this)),this._player=new cr(new dr,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(){const e=cc.globalThis;e.addEventListener("message",(t=>{const s=t.data;if("alphaSynth.initialize"===s.cmd)dr.preferredSampleRate=s.sampleRate,wt.logLevel=s.logLevel,cc.globalThis.alphaSynthWebWorker=new ur(e,s.bufferTimeInMilliseconds)}))}handleMessage(e){const t=e.data;switch(t.cmd){case"alphaSynth.setLogLevel":wt.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(ts.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(ts.jsObjectToMidiFile(t.midi));break;case"alphaSynth.setChannelMute":this._player.setChannelMute(t.channel,t.mute);break;case"alphaSynth.setChannelTranspositionPitch":this._player.setChannelTranspositionPitch(t.channel,t.semitones);break;case"alphaSynth.setChannelSolo":this._player.setChannelSolo(t.channel,t.solo);break;case"alphaSynth.setChannelVolume":this._player.setChannelVolume(t.channel,t.volume);break;case"alphaSynth.resetChannelStates":this._player.resetChannelStates();break;case"alphaSynth.destroy":this._player.destroy(),this._main.postMessage({cmd:"alphaSynth.destroyed"});break;case"alphaSynth.applyTranspositionPitches":this._player.applyTranspositionPitches(new Map(JSON.parse(t.transpositionPitches)))}}onPositionChanged(e){this._main.postMessage({cmd:"alphaSynth.positionChanged",currentTime:e.currentTime,endTime:e.endTime,currentTick:e.currentTick,endTick:e.endTick,isSeek:e.isSeek})}onPlayerStateChanged(e){this._main.postMessage({cmd:"alphaSynth.playerStateChanged",state:e.state,stopped:e.stopped})}onFinished(){this._main.postMessage({cmd:"alphaSynth.finished"})}onSoundFontLoaded(){this._main.postMessage({cmd:"alphaSynth.soundFontLoaded"})}onSoundFontLoadFailed(e){this._main.postMessage({cmd:"alphaSynth.soundFontLoadFailed",error:this.serializeException(e)})}serializeException(e){const 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(ts.midiEventToJsObject)})}onPlaybackRangeChanged(e){this._main.postMessage({cmd:"alphaSynth.playbackRangeChanged",playbackRange:e.playbackRange})}}class pr{constructor(e){this._main=e,this._main.addEventListener("message",this.handleMessage.bind(this),!1)}static init(){cc.globalThis.alphaTabWebWorker=new pr(cc.globalThis)}handleMessage(e){const t=e.data;switch(t?t.cmd:""){case"alphaTab.initialize":const e=ts.jsObjectToSettings(t.settings);wt.logLevel=e.core.logLevel,this._renderer=new vi(e),this._renderer.partialRenderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialRenderFinished",result:e})})),this._renderer.partialLayoutFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.partialLayoutFinished",result:e})})),this._renderer.renderFinished.on((e=>{this._main.postMessage({cmd:"alphaTab.renderFinished",result:e})})),this._renderer.postRenderFinished.on((()=>{this._main.postMessage({cmd:"alphaTab.postRenderFinished",boundsLookup:this._renderer.boundsLookup?.toJson()??null})})),this._renderer.preRender.on((e=>{this._main.postMessage({cmd:"alphaTab.preRender",resize:e})})),this._renderer.error.on(this.error.bind(this));break;case"alphaTab.invalidate":this._renderer.render();break;case"alphaTab.resizeRender":this._renderer.resizeRender();break;case"alphaTab.renderResult":this._renderer.renderResult(t.resultId);break;case"alphaTab.setWidth":this._renderer.width=t.width;break;case"alphaTab.renderScore":this.updateFontSizes(t.fontSizes);const s=null==t.score?null:ts.jsObjectToScore(t.score,this._renderer.settings);this.renderMultiple(s,t.trackIndexes);break;case"alphaTab.updateSettings":this.updateSettings(t.settings)}}updateFontSizes(e){if(!(e instanceof Map)){const t=e;e=new Map;for(const s in t)e.set(s,t[s])}if(e){ys.FontSizeLookupTables||(ys.FontSizeLookupTables=new Map);for(const[t,s]of e)ys.FontSizeLookupTables.set(t,s)}}updateSettings(e){dt.fromJson(this._renderer.settings,e)}renderMultiple(e,t){try{this._renderer.renderScore(e,t)}catch(e){this.error(e)}}error(e){wt.error("Worker","An unexpected error occurred in worker",e),this._main.postMessage({cmd:"alphaTab.error",error:e})}}class gr{constructor(){this._canvas=null,this._color=new ke(0,0,0,255),this._font=new Pe("Arial",10,I.Plain),this._lineWidth=0;const e=document.createElement("span");e.classList.add("at"),document.body.appendChild(e);const t=window.getComputedStyle(e);let s=t.fontFamily;(s.startsWith('"')||s.startsWith("'"))&&(s=s.substr(1,s.length-2)),this._musicFont=new Pe(s,Number.parseFloat(t.fontSize),I.Plain),this._measureCanvas=document.createElement("canvas"),this._measureCanvas.width=10,this._measureCanvas.height=10,this._measureCanvas.style.width="10px",this._measureCanvas.style.height="10px",this._measureContext=this._measureCanvas.getContext("2d"),this._measureContext.textBaseline="hanging"}destroy(){}onRenderFinished(){return null}beginRender(e,t){const s=this.settings.display.scale;this._canvas=document.createElement("canvas"),this._canvas.width=e*cc.HighDpiFactor|0,this._canvas.height=t*cc.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(cc.HighDpiFactor*s,cc.HighDpiFactor*s),this._context.lineWidth=this._lineWidth}endRender(){const e=this._canvas;return this._canvas=null,e}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._context.strokeStyle=e.rgba,this._context.fillStyle=e.rgba)}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._context&&(this._context.lineWidth=e)}fillRect(e,t,s,i){s>0&&this._context.fillRect(0|e,0|t,s,i)}strokeRect(e,t,s,i){const a=this.lineWidth%2==0?0:.5;this._context.strokeRect((0|e)+a,(0|t)+a,s,i)}beginPath(){this._context.beginPath()}closePath(){this._context.closePath()}moveTo(e,t){this._context.moveTo(e,t)}lineTo(e,t){this._context.lineTo(e,t)}quadraticCurveTo(e,t,s,i){this._context.quadraticCurveTo(e,t,s,i)}bezierCurveTo(e,t,s,i,a,r){this._context.bezierCurveTo(e,t,s,i,a,r)}fillCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.fill()}strokeCircle(e,t,s){this._context.beginPath(),this._context.arc(e,t,s,0,2*Math.PI,!0),this.stroke()}fill(){this._context.fill(),this._context.beginPath()}stroke(){this._context.stroke(),this._context.beginPath()}get font(){return this._font}set font(e){this._font=e,this._context&&(this._context.font=e.toCssString(1)),this._measureContext.font=e.toCssString(1)}get textAlign(){switch(this._context.textAlign){case"left":default:return W.Left;case"center":return W.Center;case"right":return W.Right}}set textAlign(e){switch(e){case W.Left:this._context.textAlign="left";break;case W.Center:this._context.textAlign="center";break;case W.Right:this._context.textAlign="right"}}get textBaseline(){switch(this._context.textBaseline){case"hanging":default:return V.Top;case"middle":return V.Middle;case"bottom":return V.Bottom}}set textBaseline(e){switch(e){case V.Top:this._context.textBaseline="hanging";break;case V.Middle:this._context.textBaseline="middle";break;case V.Bottom:this._context.textBaseline="bottom"}}beginGroup(e){}endGroup(){}fillText(e,t,s){this._context.fillText(e,t,s)}measureText(e){const t=this._measureContext.measureText(e);return new Ce(t.width,t.actualBoundingBoxDescent-t.actualBoundingBoxAscent)}fillMusicFontSymbol(e,t,s,i,a=!1){i!==G.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a=!1){let r="";for(const e of i)e!==G.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){const r=this._context.textAlign,n=this._context.textBaseline,o=this._context.font;this._context.font=this._musicFont.toCssString(s),this._context.textBaseline="middle",this._context.textAlign=a?"center":"left",this._context.fillText(i,e,t),this._context.textBaseline=n,this._context.font=o,this._context.textAlign=r}beginRotate(e,t,s){this._context.save(),this._context.translate(e,t),this._context.rotate(s*Math.PI/180)}endRotate(){this._context.restore()}}class mr{constructor(e,t=!1){this._midiFile=e,this._smf1Mode=t}addTimeSignature(e,t,s){let i=0,a=s;for(;a>>=1,a>0;)i++;this._midiFile.addEvent(new Oe(0,e,t,i,48,8))}addRest(e,t,s){this._smf1Mode||this._midiFile.addEvent(new Ve(e,t,s))}addNote(e,t,s,i,a,r){this._midiFile.addEvent(new ze(e,t,r,mr.fixValue(i),mr.fixValue(a))),this._midiFile.addEvent(new Ue(e,t+s,r,mr.fixValue(i),mr.fixValue(a)))}static fixValue(e){return e>127?127:e<0?0:e}addControlChange(e,t,s,i,a){this._midiFile.addEvent(new Xe(e,t,s,i,mr.fixValue(a)))}addProgramChange(e,t,s,i){this._midiFile.addEvent(new Je(e,t,s,i))}addTempo(e,t){const s=6e7/t|0;this._midiFile.addEvent(new Ye(e,s))}addBend(e,t,s,i){i=i>=Ls.MaxPitchWheel?Ls.MaxPitchWheel:Math.floor(i),this._midiFile.addEvent(new $e(e,t,s,i))}addNoteBend(e,t,s,i,a){this._smf1Mode?this.addBend(e,t,s,a):(a=a*Ls.MaxPitchWheel20/Ls.MaxPitchWheel,this._midiFile.addEvent(new qe(e,t,s,i,a)))}finishTrack(e,t){this._midiFile.format!==z.MultiTrack&&0!==e||this._midiFile.addEvent(new Ke(e,t))}}class fr{constructor(e,t){this.closingIndex=0,this.group=e,this.opening=t,e.closings=e.closings.sort(((e,t)=>e.index-t.index)),this.iterations=e.closings.map((e=>0))}}!function(e){e[e.PlayingNormally=0]="PlayingNormally",e[e.DirectionJumped=1]="DirectionJumped",e[e.DirectionJumpedAlCoda=2]="DirectionJumpedAlCoda",e[e.DirectionJumpedAlDoubleCoda=3]="DirectionJumpedAlDoubleCoda",e[e.DirectionJumpedAlFine=4]="DirectionJumpedAlFine"}(Yi||(Yi={}));class yr{get finished(){return this.index>=this._score.masterBars.length}constructor(e){this._repeatStack=[],this._groupsOnStack=new Set,this._previousAlternateEndings=0,this._state=Yi.PlayingNormally,this.shouldPlay=!0,this.index=0,this.currentTick=0,this._score=e}processCurrent(){const e=this._score.masterBars[this.index];if(this._state===Yi.PlayingNormally){let t=e.alternateEndings;if(0===t&&(t=this._previousAlternateEndings),e===e.repeatGroup.opening&&e.repeatGroup.isClosed&&!this._groupsOnStack.has(e.repeatGroup)){const s=new fr(e.repeatGroup,e);this._repeatStack.push(s),this._groupsOnStack.add(e.repeatGroup),this._previousAlternateEndings=0,t=e.alternateEndings}if(0===this._repeatStack.length||0===t)this.shouldPlay=!0;else{const e=this._repeatStack[this._repeatStack.length-1],s=e.iterations[e.closingIndex];this._previousAlternateEndings=t,this.shouldPlay=!!(t&1<<s)}}else this.shouldPlay=!0;this.shouldPlay&&(this.currentTick+=e.calculateDuration())}moveNext(){this.moveNextWithDirections()||this.moveNextWithNormalRepeats()}resetRepeats(){this._groupsOnStack.clear(),this._previousAlternateEndings=0,this._repeatStack=[]}handleDaCapo(e,t,s){return!!e.has(t)&&(this.index=0,this._state=s,this.resetRepeats(),!0)}handleDalSegno(e,t,s,i){if(e.has(t)){const e=this.findJumpTarget(i,this.index,!0);return-1!==e&&(this.index=e,this._state=s,this.resetRepeats(),!0)}return!1}handleDaCoda(e,t,s){if(e.has(t)){const e=this.findJumpTarget(s,this.index,!1);return-1===e?(this.index++,!0):(this.index=e,this._state=Yi.PlayingNormally,!0)}return!1}moveNextWithDirections(){const e=this._score.masterBars[this.index],t=null!==e.directions&&e.directions.size>0;if(this._state===Yi.PlayingNormally&&!t)return!1;if(!t)return this.index++,!0;switch(this._state){case Yi.PlayingNormally:return!!(this.handleDaCapo(e.directions,C.JumpDaCapo,Yi.DirectionJumped)||this.handleDaCapo(e.directions,C.JumpDaCapoAlCoda,Yi.DirectionJumpedAlCoda)||this.handleDaCapo(e.directions,C.JumpDaCapoAlDoubleCoda,Yi.DirectionJumpedAlDoubleCoda)||this.handleDaCapo(e.directions,C.JumpDaCapoAlFine,Yi.DirectionJumpedAlFine))||(!!(this.handleDalSegno(e.directions,C.JumpDalSegno,Yi.DirectionJumped,C.TargetSegno)||this.handleDalSegno(e.directions,C.JumpDalSegnoAlCoda,Yi.DirectionJumpedAlCoda,C.TargetSegno)||this.handleDalSegno(e.directions,C.JumpDalSegnoAlDoubleCoda,Yi.DirectionJumpedAlDoubleCoda,C.TargetSegno)||this.handleDalSegno(e.directions,C.JumpDalSegnoAlFine,Yi.DirectionJumpedAlFine,C.TargetSegno))||!!(this.handleDalSegno(e.directions,C.JumpDalSegnoSegno,Yi.DirectionJumped,C.TargetSegnoSegno)||this.handleDalSegno(e.directions,C.JumpDalSegnoSegnoAlCoda,Yi.DirectionJumpedAlCoda,C.TargetSegnoSegno)||this.handleDalSegno(e.directions,C.JumpDalSegnoSegnoAlDoubleCoda,Yi.DirectionJumpedAlDoubleCoda,C.TargetSegnoSegno)||this.handleDalSegno(e.directions,C.JumpDalSegnoSegnoAlFine,Yi.DirectionJumpedAlFine,C.TargetSegnoSegno)));case Yi.DirectionJumped:return this.index++,!0;case Yi.DirectionJumpedAlCoda:return this.handleDaCoda(e.directions,C.JumpDaCoda,C.TargetCoda)||this.index++,!0;case Yi.DirectionJumpedAlDoubleCoda:return this.handleDaCoda(e.directions,C.JumpDaDoubleCoda,C.TargetDoubleCoda)||this.index++,!0;case Yi.DirectionJumpedAlFine:return e.directions.has(C.TargetFine)?(this.index=this._score.masterBars.length,!0):(this.index++,!0)}return!0}findJumpTarget(e,t,s){let i;return s?(i=this.findJumpTargetBackwards(e,t),-1===i&&(i=this.findJumpTargetForwards(e,t)),i):(i=this.findJumpTargetForwards(e,t),-1===i&&(i=this.findJumpTargetBackwards(e,t)),i)}findJumpTargetForwards(e,t){let s=t;for(;s<this._score.masterBars.length;){const t=this._score.masterBars[s].directions;if(t&&t.has(e))return s;s++}return-1}findJumpTargetBackwards(e,t){let s=t;for(;s>=0;){const t=this._score.masterBars[s].directions;if(t&&t.has(e))return s;s--}return-1}moveNextWithNormalRepeats(){const e=this._score.masterBars[this.index].repeatCount-1;if(this._repeatStack.length>0&&e>0){const t=this._repeatStack[this._repeatStack.length-1];if(t.iterations[t.closingIndex]<e){this.index=t.opening.index,t.iterations[t.closingIndex]++;for(let e=0;e<t.closingIndex;e++)t.iterations[e]=0;t.closingIndex=0,this._previousAlternateEndings=0}else t.closingIndex<t.group.closings.length-1?(t.closingIndex++,this.index++):(this._repeatStack.pop(),this._groupsOnStack.delete(t.group),this.index++)}else this.index++}}class br{constructor(e,t){this.beat=e,this.playbackStart=t}}class Sr{get duration(){return this.end-this.start}constructor(e,t){this._highlightedBeats=new Map,this.highlightedBeats=[],this.nextBeat=null,this.previousBeat=null,this.start=e,this.end=t}highlightBeat(e,t){e.isEmpty&&!e.voice.isEmpty||this._highlightedBeats.has(e.id)||(this._highlightedBeats.set(e.id,!0),this.highlightedBeats.push(new br(e,t)))}getVisibleBeatAtStart(e){for(const t of this.highlightedBeats)if(t.playbackStart===this.start&&e.has(t.beat.voice.bar.staff.track.index))return t.beat;return null}}class _r{constructor(e,t){this.tick=e,this.tempo=t}}class wr{constructor(){this.start=0,this.end=0,this.tempoChanges=[],this.firstBeat=null,this.lastBeat=null,this.nextMasterBar=null,this.previousMasterBar=null}get tempo(){return this.tempoChanges[0].tempo}insertAfter(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.nextBeat=e.nextBeat,t.previousBeat=e,e.nextBeat&&(e.nextBeat.previousBeat=t),e.nextBeat=t,e===this.lastBeat&&(this.lastBeat=t))}insertBefore(e,t){null==this.firstBeat||null==e||null==this.lastBeat?(this.firstBeat=t,this.lastBeat=t):(t.previousBeat=e.previousBeat,t.nextBeat=e,e.previousBeat&&(e.previousBeat.nextBeat=t),e.previousBeat=t,e===this.firstBeat&&(this.firstBeat=t))}addBeat(e,t,s,i){const a=s+i;if(null==this.firstBeat){const i=new Sr(s,a);i.highlightBeat(e,t),this.insertAfter(this.firstBeat,i)}else if(s>=this.lastBeat.end){const s=new Sr(this.lastBeat.end,a);s.highlightBeat(e,t),this.insertAfter(this.lastBeat,s)}else{let i=null;if(s<this.firstBeat.start)i=this.firstBeat;else{let e=this.firstBeat;for(;null!=e;){if(s>=e.start&&s<e.end){i=e;break}e=e.nextBeat}if(null===i)throw new fe(S.General,"Error on building lookup, unknown variant")}if(s<i.start)if(a===i.start){const a=new Sr(s,i.start);a.highlightBeat(e,t),this.insertBefore(this.firstBeat,a)}else if(a<i.end){const r=new Sr(s,i.start);r.highlightBeat(e,t),this.insertBefore(i,r);const n=new Sr(i.start,a);for(const e of i.highlightedBeats)n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(e,t),this.insertBefore(i,n),i.start=a}else if(a===i.end){const a=new Sr(s,i.start);a.highlightBeat(e,t),i.highlightBeat(e,t),this.insertBefore(i,a)}else{const r=new Sr(s,i.start);r.highlightBeat(e,t),i.highlightBeat(e,t),this.insertBefore(i,r),this.addBeat(e,t,i.end,a-i.end)}else if(s>i.start)if(a===i.end){const a=new Sr(i.start,s);for(const e of i.highlightedBeats)a.highlightBeat(e.beat,e.playbackStart);i.start=s,i.highlightBeat(e,t),this.insertBefore(i,a)}else if(a<i.end){const r=new Sr(i.start,s);this.insertBefore(i,r);const n=new Sr(s,a);this.insertBefore(i,n);for(const e of i.highlightedBeats)r.highlightBeat(e.beat,e.playbackStart),n.highlightBeat(e.beat,e.playbackStart);n.highlightBeat(e,t),i.start=a}else{const r=new Sr(i.start,s);for(const e of i.highlightedBeats)r.highlightBeat(e.beat,e.playbackStart);i.start=s,i.highlightBeat(e,t),this.insertBefore(i,r),this.addBeat(e,t,i.end,a-i.end)}else if(a===i.end)i.highlightBeat(e,t);else if(a<i.end){const s=new Sr(i.start,a);for(const e of i.highlightedBeats)s.highlightBeat(e.beat,e.playbackStart);s.highlightBeat(e,t),i.start=a,this.insertBefore(i,s)}else i.highlightBeat(e,t),this.addBeat(e,t,i.end,a-i.end)}}}!function(e){e[e.Unknown=0]="Unknown",e[e.ToNextBext=1]="ToNextBext",e[e.ToEndOfBar=2]="ToEndOfBar"}($i||($i={}));class Br{get start(){return this.masterBar.start+this.beatLookup.start}get end(){return this.start+this.tickDuration}constructor(e){this.nextBeat=null,this.tickDuration=0,this.duration=0,this.cursorMode=$i.Unknown,this.masterBar=e}calculateDuration(){if(1===this.masterBar.tempoChanges.length)this.duration=rs.ticksToMillis(this.tickDuration,this.masterBar.tempoChanges[0].tempo);else{let e=0,t=this.start,s=this.masterBar.tempoChanges[0].tempo;const i=this.end;for(const a of this.masterBar.tempoChanges)if(a.tick<t)s=a.tempo;else{if(a.tick>i)break;e+=rs.ticksToMillis(a.tick-t,s),s=a.tempo,t=a.tick}i>t&&(e+=rs.ticksToMillis(i-t,s)),this.duration=e}}}class kr{constructor(){this._currentMasterBar=null,this.masterBarLookup=new Map,this.masterBars=[],this.multiBarRestInfo=null}findBeat(e,t,s=null){let i=null;return s&&(i=this.findBeatFast(e,s,t)),i||(i=this.findBeatSlow(e,s,t,!1)),i}findBeatFast(e,t,s){if(s>=t.start&&s<t.end)return t;if(t.nextBeat&&s>=t.nextBeat.start&&s<t.nextBeat.end){const s=t.nextBeat;return this.fillNextBeat(s,e),s}return null}fillNextBeatMultiBarRest(e,t){const s=this.multiBarRestInfo.get(e.masterBar.masterBar.index);let i=e.masterBar;for(let e=0;e<s.length&&i;e++)i=i.nextMasterBar;i?i.nextMasterBar?(e.nextBeat=this.firstBeatInMasterBar(t,i.nextMasterBar,i.nextMasterBar.start,!0),e.nextBeat?(e.tickDuration=e.nextBeat.start-e.start,e.cursorMode=$i.ToNextBext,e.nextBeat.masterBar.masterBar.index!==i.masterBar.index+1&&(e.nextBeat.masterBar.masterBar.index!==i.masterBar.index||e.nextBeat.beat.playbackStart<=e.beat.playbackStart)&&(e.cursorMode=$i.ToEndOfBar)):(e.tickDuration=i.nextMasterBar.end-e.start,e.cursorMode=$i.ToEndOfBar)):(e.tickDuration=i.end-e.start,e.cursorMode=$i.ToEndOfBar):(wt.warning("Synth","MultiBar Rest Info and the nextMasterBar are out of sync, this is an unexpected error. Please report it as bug. (broken chain fill-next)"),e.tickDuration=(e.masterBar.end-e.masterBar.start)*(s.length+1),e.cursorMode=$i.ToEndOfBar),e.calculateDuration()}fillNextBeat(e,t){this.isMultiBarRestResult(e)?this.fillNextBeatMultiBarRest(e,t):this.fillNextBeatDefault(e,t)}fillNextBeatDefault(e,t){e.nextBeat=this.findBeatInMasterBar(e.masterBar,e.beatLookup.nextBeat,e.end,t,!0),null==e.nextBeat&&(e.nextBeat=this.findBeatSlow(t,e,e.end,!0)),e.nextBeat?(e.tickDuration=e.nextBeat.start-e.start,e.cursorMode=$i.ToNextBext,e.calculateDuration()):(e.tickDuration=e.masterBar.end-e.start,e.cursorMode=$i.ToEndOfBar,e.calculateDuration()),e.nextBeat&&e.nextBeat.masterBar.masterBar.index!==e.masterBar.masterBar.index+1&&(e.nextBeat.masterBar.masterBar.index!==e.masterBar.masterBar.index||e.nextBeat.beat.playbackStart<=e.beat.playbackStart)&&(e.cursorMode=$i.ToEndOfBar)}isMultiBarRestResult(e){return this.internalIsMultiBarRestResult(e.masterBar.masterBar.index,e.beat)}internalIsMultiBarRestResult(e,t){return this.multiBarRestInfo&&this.multiBarRestInfo.has(e)&&t.isRest&&t.voice.bar.isRestOnly}findBeatSlow(e,t,s,i){let a=null;return null!=t&&(t.masterBar.start<=s&&t.masterBar.end>s?a=t.masterBar:t.masterBar.nextMasterBar&&t.masterBar.nextMasterBar.start<=s&&t.masterBar.nextMasterBar.end>s&&(a=t.masterBar.nextMasterBar)),a||(a=this.findMasterBar(s)),a?this.firstBeatInMasterBar(e,a,s,i):null}firstBeatInMasterBar(e,t,s,i){let a=t;for(;a;){if(a.firstBeat){const t=this.findBeatInMasterBar(a,a.firstBeat,s,e,i);if(t)return t}a=a.nextMasterBar}return null}findBeatInMasterBar(e,t,s,i,a){if(!t)return null;let r=null,n=null;const o=s-e.start;for(;null!=t&&null==n;){if((t.start<=o||a&&o<0)&&o<t.end){if(r=t,n=t.getVisibleBeatAtStart(i),!n)if(a){let s=e;for(;null!=s&&null==n;){for(;null!=t;){if(n=t.getVisibleBeatAtStart(i),n){r=t,e=s;break}t=t.nextBeat}n&&r||(s=s.nextMasterBar,t=s?.firstBeat??null)}}else{let s=e;for(;null!=s&&null==n;){for(;null!=t;){if(n=t.getVisibleBeatAtStart(i),n){r=t,e=s;break}t=t.previousBeat}n&&r||(s=s.previousMasterBar,t=s?.firstBeat??null)}}}else if(t.end>o)break;t=t?.nextBeat??null}if(null==n)return null;return this.createResult(e,r,n,a,i)}createResult(e,t,s,i,a){const r=new Br(e);if(r.beat=s,r.beatLookup=t,r.tickDuration=t.end-t.start,i){if(this.isMultiBarRestResult(r)){const s=this.multiBarRestInfo.get(e.masterBar.index);let i=e;for(let e=0;e<s.length&&i;e++)i=i.nextMasterBar;i?i.nextMasterBar?r.tickDuration=i.nextMasterBar.start-t.start:r.tickDuration=i.end-t.start:wt.warning("Synth","MultiBar Rest Info and the nextMasterBar are out of sync, this is an unexpected error. Please report it as bug. (broken chain stretch-result)")}}else this.fillNextBeat(r,a);return r.calculateDuration(),r}findMasterBar(e){const t=this.masterBars;let s=0,i=t.length-1;for(;s<=i;){const a=(i+s)/2|0,r=t[a];if(e>=r.start&&e<r.end)return r;e<r.start?i=a-1:s=a+1}return null}getMasterBar(e){if(!this.masterBarLookup.has(e.index)){const t=new wr;return t.masterBar=e,t}return this.masterBarLookup.get(e.index)}getMasterBarStart(e){return this.masterBarLookup.has(e.index)?this.masterBarLookup.get(e.index).start:0}getBeatStart(e){return this.masterBarLookup.has(e.voice.bar.index)?this.masterBarLookup.get(e.voice.bar.index).start+e.playbackStart:0}addMasterBar(e){this.masterBars.push(e),this._currentMasterBar&&(e.previousMasterBar=this._currentMasterBar,this._currentMasterBar.nextMasterBar=e),this._currentMasterBar=e,this.masterBarLookup.has(e.masterBar.index)||this.masterBarLookup.set(e.masterBar.index,e)}addBeat(e,t,s){const i=this._currentMasterBar;if(i)if(t<0&&i.previousMasterBar){const a=i.previousMasterBar.end-i.previousMasterBar.start,r=a+t,n=r+s;if(i.previousMasterBar.addBeat(e,r,r,s),n>a){const a=s+t;i.addBeat(e,t,0,a)}}else i.addBeat(e,t,t,s)}}class Tr{constructor(){this.noteOnly=0,this.untilTieOrSlideEnd=0,this.letRingEnd=0}}class Nr{constructor(){this.firstBeatDuration=0,this.secondBeatStartOffset=0,this.secondBeatDuration=0}}class xr{constructor(){this.durations=[],this.brushInfos=[]}}class vr{constructor(e,t,s){this._programsPerChannel=new Map,this._currentTime=0,this._calculatedBeatTimers=new Set,this.tickLookup=new kr,this.applyTranspositionPitches=!0,this.transpositionPitches=new Map,this._currentTripletFeel=null,this.vibratoResolution=16,this._score=e,this._settings=t||new ut,this._handler=s}generate(){this.transpositionPitches.clear(),this._calculatedBeatTimers.clear(),this._currentTime=0;for(const e of this._score.tracks)this.generateTrack(e);wt.debug("Midi","Begin midi generation");const e=new yr(this._score);let t=null,s=this._score.tempo;for(;!e.finished;){const i=e.index,a=this._score.masterBars[i],r=e.currentTick;if(e.processCurrent(),e.shouldPlay){this.generateMasterBar(a,t,r,s),a.tempoAutomations.length>0&&(s=a.tempoAutomations[0].value);for(const e of this._score.tracks)for(const t of e.staves)i<t.bars.length&&this.generateBar(t.bars[i],r,s);a.tempoAutomations.length>0&&(s=a.tempoAutomations[a.tempoAutomations.length-1].value)}e.moveNext(),t=a}for(const t of this._score.tracks)this._handler.finishTrack(t.index,e.currentTick);wt.debug("Midi","Midi generation done")}generateTrack(e){this.generateChannel(e,e.playbackInfo.primaryChannel,e.playbackInfo),e.playbackInfo.primaryChannel!==e.playbackInfo.secondaryChannel&&this.generateChannel(e,e.playbackInfo.secondaryChannel,e.playbackInfo)}addProgramChange(e,t,s,i){this._programsPerChannel.has(s)&&this._programsPerChannel.get(s)===i||(this._handler.addProgramChange(e.index,t,s,i),this._programsPerChannel.set(s,i))}static buildTranspositionPitches(e,t){const s=new Map;for(const i of e.tracks){const e=i.index<t.notation.transpositionPitches.length?t.notation.transpositionPitches[i.index]:-i.staves[0].transpositionPitch;s.set(i.playbackInfo.primaryChannel,e),s.set(i.playbackInfo.secondaryChannel,e)}return s}generateChannel(e,t,s){const i=e.index<this._settings.notation.transpositionPitches.length?this._settings.notation.transpositionPitches[e.index]:-e.staves[0].transpositionPitch;this.transpositionPitches.set(t,i);const a=vr.toChannelShort(s.volume),r=vr.toChannelShort(s.balance);this._handler.addControlChange(e.index,0,t,Ji.VolumeCoarse,a),this._handler.addControlChange(e.index,0,t,Ji.PanCoarse,r),this._handler.addControlChange(e.index,0,t,Ji.ExpressionControllerCoarse,127),this._handler.addControlChange(e.index,0,t,Ji.RegisteredParameterFine,0),this._handler.addControlChange(e.index,0,t,Ji.RegisteredParameterCourse,0),this._handler.addControlChange(e.index,0,t,Ji.DataEntryFine,0),this._handler.addControlChange(e.index,0,t,Ji.DataEntryCoarse,vr.PitchBendRangeInSemitones),this.addProgramChange(e,0,t,s.program)}static toChannelShort(e){const t=Math.max(-32768,Math.min(32767,8*e-1));return Math.max(t,-1)+1}generateMasterBar(e,t,s,i){t&&t.timeSignatureDenominator===e.timeSignatureDenominator&&t.timeSignatureNumerator===e.timeSignatureNumerator||this._handler.addTimeSignature(s,e.timeSignatureNumerator,e.timeSignatureDenominator);const a=e.calculateDuration(),r=new wr;if(e.tempoAutomations.length>0){e.tempoAutomations[0].ratioPosition>0&&r.tempoChanges.push(new _r(s,i));for(const t of e.tempoAutomations){const e=s+a*t.ratioPosition;this._handler.addTempo(e,t.value),r.tempoChanges.push(new _r(e,t.value))}}else t?r.tempoChanges.push(new _r(s,i)):(this._handler.addTempo(s,e.score.tempo),r.tempoChanges.push(new _r(s,e.score.tempo)));r.masterBar=e,r.start=s,r.end=r.start+a,this.tickLookup.addMasterBar(r)}generateBar(e,t,s){const i=this.getPlaybackBar(e),a=this._currentTime;for(const r of i.voices)this._currentTime=a,this.generateVoice(r,t,e,s);const r=i.masterBar,n=r.calculateDuration(),o=r.tempoAutomations.slice();if(0===o.length)this._currentTime=a+rs.ticksToMillis(n,s);else{this._currentTime=a;let e=t,i=s;const r=t+n;for(const t of o){const s=n*t.ratioPosition-e;s>0&&(this._currentTime+=rs.ticksToMillis(s,i)),i=t.value,e+=s}const h=r-e;h>0&&(this._currentTime+=rs.ticksToMillis(h,i))}i.id!==e.id&&this.tickLookup.addBeat(e.voices[0].beats[0],0,n)}getPlaybackBar(e){switch(e.simileMark){case h.Simple:e.previousBar&&(e=this.getPlaybackBar(e.previousBar));break;case h.FirstOfDouble:case h.SecondOfDouble:e.previousBar&&e.previousBar.previousBar&&(e=this.getPlaybackBar(e.previousBar.previousBar))}return e}generateVoice(e,t,s,i){if(e.isEmpty&&(!e.bar.isEmpty||0!==e.index))return;const a=s.masterBar.tempoAutomations.slice();let r=i;const n=s.masterBar.calculateDuration();for(const i of e.beats){const e=i.playbackStart/n;for(;a.length>0&&a[0].ratioPosition<=e;)r=a.shift().value;this.generateBeat(i,t,s,r)}}generateBeat(e,t,s,i){let a=e.playbackStart,r=e.playbackDuration;const n=e.voice.bar.masterBar.calculateDuration();e.voice.bar.isEmpty?r=n:e.voice.bar.masterBar.tripletFeel!==P.NoTripletFeel&&this._settings.player.playTripletFeel&&(this._currentTripletFeel?(a-=this._currentTripletFeel.secondBeatStartOffset,r=this._currentTripletFeel.secondBeatDuration,this._currentTripletFeel=null):(this._currentTripletFeel=vr.calculateTripletFeelInfo(a,r,e),this._currentTripletFeel&&(r=this._currentTripletFeel.firstBeatDuration))),e.showTimer&&!this._calculatedBeatTimers.has(e.id)&&(e.timer=this._currentTime,this._calculatedBeatTimers.add(e.id)),this._currentTime+=rs.ticksToMillis(r,i),s===e.voice.bar&&this.tickLookup.addBeat(e,a,r);const o=e.voice.bar.staff.track;for(const s of e.automations)this.generateNonTempoAutomation(e,s,t);if(e.isRest)this._handler.addRest(o.index,t+a,o.playbackInfo.primaryChannel);else if(e.deadSlapped)this.generateDeadSlap(e,t+a);else{const s=this.getBrushInfo(e),n=this.getRasgueadoInfo(e,r);for(const o of e.notes)this.generateNote(o,t+a,r,i,s,n)}if(e.fade!==L.None&&this.generateFade(e,t+a,r),e.vibrato!==j.None){let s=240,i=3;switch(e.vibrato){case j.Slight:s=this._settings.player.vibrato.beatSlightLength,i=this._settings.player.vibrato.beatSlightAmplitude;break;case j.Wide:s=this._settings.player.vibrato.beatWideLength,i=this._settings.player.vibrato.beatWideAmplitude}this.generateVibratorWithParams(t+a,e.playbackDuration,s,0,i,((t,s)=>{this._handler.addBend(e.voice.bar.staff.track.index,t,o.playbackInfo.secondaryChannel,s)}))}}static calculateTripletFeelInfo(e,t,s){let i;switch(s.voice.bar.masterBar.tripletFeel){case P.Triplet8th:case P.Dotted8th:case P.Scottish8th:i=D.Eighth;break;case P.Triplet16th:case P.Dotted16th:case P.Scottish16th:i=D.Sixteenth;break;default:return null}const a=rs.toTicks(i);if(t!==a)return null;if(e%a!=0)return null;if(!s.nextBeat||s.nextBeat.voice!==s.voice||s.playbackDuration!==a)return null;const r=new Nr;switch(s.voice.bar.masterBar.tripletFeel){case P.Triplet8th:r.firstBeatDuration=rs.applyTuplet(rs.toTicks(D.Quarter),3,2),r.secondBeatDuration=rs.applyTuplet(rs.toTicks(D.Eighth),3,2);break;case P.Dotted8th:r.firstBeatDuration=rs.applyDot(rs.toTicks(D.Eighth),!1),r.secondBeatDuration=rs.toTicks(D.Sixteenth);break;case P.Scottish8th:r.firstBeatDuration=rs.toTicks(D.Sixteenth),r.secondBeatDuration=rs.applyDot(rs.toTicks(D.Eighth),!1);break;case P.Triplet16th:r.firstBeatDuration=rs.applyTuplet(rs.toTicks(D.Eighth),3,2),r.secondBeatDuration=rs.applyTuplet(rs.toTicks(D.Sixteenth),3,2);break;case P.Dotted16th:r.firstBeatDuration=rs.applyDot(rs.toTicks(D.Sixteenth),!1),r.secondBeatDuration=rs.toTicks(D.ThirtySecond);break;case P.Scottish16th:r.firstBeatDuration=rs.toTicks(D.ThirtySecond),r.secondBeatDuration=rs.applyDot(rs.toTicks(D.Sixteenth),!1)}return r.secondBeatStartOffset=t-r.firstBeatDuration,r}generateDeadSlap(e,t){const s=rs.toTicks(D.SixtyFourth),i=e.voice.bar.staff;if(i.tuning.length>0)for(const e of i.tuning)this._handler.addNote(i.track.index,t,s,e,rs.dynamicToVelocity(E.F),i.track.playbackInfo.primaryChannel)}needsSecondaryChannel(e){return e.hasBend||e.beat.hasWhammyBar||e.beat.vibrato!==j.None}determineChannel(e,t){if(this.needsSecondaryChannel(t))return e.playbackInfo.secondaryChannel;let s=t;for(;s.isTieDestination;)if(s=s.tieOrigin,this.needsSecondaryChannel(s))return e.playbackInfo.secondaryChannel;for(s=t;s.isTieOrigin;)if(s=s.tieDestination,this.needsSecondaryChannel(s))return e.playbackInfo.secondaryChannel;return e.playbackInfo.primaryChannel}generateNote(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.beat.voice.bar.staff;let h=e.calculateRealValue(this.applyTranspositionPitches,!0);if(e.isPercussion){const t=Bt.getArticulation(e);t&&(h=t.outputMidiNumber)}const l=null==r&&e.isStringed&&e.string<=a.length?a[e.string-1]:0,c=t+l,d=this.getNoteDuration(e,s,i);d.untilTieOrSlideEnd-=l,d.noteOnly-=l,d.letRingEnd-=l;const u=vr.getNoteVelocity(e),p=this.determineChannel(n,e);let g=0;const m=Math.max(d.untilTieOrSlideEnd,d.letRingEnd);g=e.hasBend?vr.getPitchWheel(e.bendPoints[0].value):e.beat.hasWhammyBar?vr.getPitchWheel(e.beat.whammyBarPoints[0].value):e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===K.Legato?-1:vr.getPitchWheel(0),g>=0&&this._handler.addNoteBend(n.index,c,p,h,g),e.beat.hasRasgueado?this.generateRasgueado(n,e,c,h,u,p,r):e.ornament===Z.None?!e.isTrill||o.isPercussion?e.beat.isTremolo?this.generateTremoloPicking(e,c,d,h,u,p):(e.hasBend?this.generateBend(e,c,d,h,p,i):e.beat.hasWhammyBar&&0===e.index?this.generateWhammy(e.beat,c,d,p,i):e.slideInType!==q.None||e.slideOutType!==K.None?this.generateSlide(e,c,d,h,p,i):(e.vibrato!==j.None||e.isTieDestination&&e.tieOrigin.vibrato!==j.None)&&this.generateVibrato(e,c,d,h,p),e.isTieDestination||e.slideOrigin&&e.slideOrigin.slideOutType===K.Legato||this._handler.addNote(n.index,c,m,h,u,p)):this.generateTrill(e,c,d,h,u,p):this.generateOrnament(n,e,c,m,h,u,p)}generateOrnament(e,t,s,i,a,r,n){let o,h;const l=a%12,c=1/3;switch(t.ornament){case Z.Turn:o=[a+vr.OrnamentKeysUp[l],a,a+vr.OrnamentKeysDown[l]],h=[rs.toTicks(D.Sixteenth)*c,rs.toTicks(D.Sixteenth)*c,rs.toTicks(D.Sixteenth)*c];break;case Z.InvertedTurn:o=[a+vr.OrnamentKeysDown[l],a,a+vr.OrnamentKeysUp[l]],h=[rs.toTicks(D.Sixteenth)*c,rs.toTicks(D.Sixteenth)*c,rs.toTicks(D.Sixteenth)*c];break;case Z.UpperMordent:o=[a,a+vr.OrnamentKeysUp[l]],h=[rs.toTicks(D.ThirtySecond),rs.toTicks(D.ThirtySecond)];break;case Z.LowerMordent:o=[a,a+vr.OrnamentKeysDown[l]],h=[rs.toTicks(D.ThirtySecond),rs.toTicks(D.ThirtySecond)];break;default:return}let d=1;i<rs.QuarterTime&&(d=i/rs.QuarterTime),r-=rs.VelocityIncrement;let u=0;for(let t=0;t<o.length;t++){const i=h[t]*d;this._handler.addNote(e.index,s,i,o[t],r,n),s+=i,u+=i}const p=i-u;this._handler.addNote(e.index,s,p,a,r,n)}getNoteDuration(e,t,s){const i=new Tr;if(i.noteOnly=t,i.untilTieOrSlideEnd=t,i.letRingEnd=t,e.isDead)return i.noteOnly=this.applyStaticDuration(vr.DefaultDurationDead,t,s),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isPalmMute)return i.noteOnly=this.applyStaticDuration(vr.DefaultDurationPalmMute,t,s),i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isStaccato)return i.noteOnly=t/2|0,i.untilTieOrSlideEnd=i.noteOnly,i.letRingEnd=i.noteOnly,i;if(e.isTieOrigin){const a=e.tieDestination;if(a)if(e.isTieDestination){const e=this.getNoteDuration(a,a.beat.playbackDuration,s);i.untilTieOrSlideEnd=t+e.untilTieOrSlideEnd}else{const t=e.beat.absolutePlaybackStart,r=this.getNoteDuration(a,a.beat.playbackDuration,s),n=a.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;i.untilTieOrSlideEnd=n-t}}else if(e.slideOutType===K.Legato){const t=e.slideTarget;if(t){const a=e.beat.absolutePlaybackStart,r=this.getNoteDuration(t,t.beat.playbackDuration,s),n=t.beat.absolutePlaybackStart+r.untilTieOrSlideEnd;i.untilTieOrSlideEnd=n-a}}if(e.isLetRing&&this._settings.notation.notationMode===k.GuitarPro){let s=e.beat,a=0;const r=e.beat.voice.bar.masterBar.calculateDuration();for(;s.nextBeat;){const t=s.nextBeat;if(t.isRest)break;if(e.isStringed&&t.hasNoteOnString(e.string))break;if(s=s.nextBeat,a=s.absolutePlaybackStart-e.beat.absolutePlaybackStart+s.playbackDuration,a>r){a=r;break}}s===e.beat?i.letRingEnd=t:i.letRingEnd=a}else i.letRingEnd=i.untilTieOrSlideEnd;return i}applyStaticDuration(e,t,s){const i=s*e/ge.MaxPosition|0;return Math.min(i,t)}static getNoteVelocity(e){let t=0;switch(!e.beat.voice.bar.staff.isPercussion&&e.hammerPullOrigin&&t--,e.isGhost&&t--,e.accentuated){case u.Normal:t++;break;case u.Heavy:t+=2}return rs.dynamicToVelocity(e.dynamics,t)}generateFade(e,t,s){const i=e.voice.bar.staff.track;switch(e.fade){case L.FadeIn:this.generateFadeSteps(i,t,s,0,vr.toChannelShort(i.playbackInfo.volume));break;case L.FadeOut:this.generateFadeSteps(i,t,s,vr.toChannelShort(i.playbackInfo.volume),0);break;case L.VolumeSwell:const e=s/2|0;this.generateFadeSteps(i,t,e,0,vr.toChannelShort(i.playbackInfo.volume)),this.generateFadeSteps(i,t+e,e,vr.toChannelShort(i.playbackInfo.volume),0)}}generateFadeSteps(e,t,s,i,a){const r=(a-i)/(s=.8*s|0),n=s/120+1|0,o=t+s;for(let s=0;s<n;s++){const h=s===n-1,l=h?o:t+120*s,c=h?a:Math.round(i+(l-t)*r);this._handler.addControlChange(e.index,l,e.playbackInfo.primaryChannel,Ji.VolumeCoarse,c),this._handler.addControlChange(e.index,l,e.playbackInfo.secondaryChannel,Ji.VolumeCoarse,c)}}generateVibrato(e,t,s,i,a){let r=0,n=0;switch(e.vibrato!==j.None?e.vibrato:e.isTieDestination?e.tieOrigin.vibrato:j.Slight){case j.Slight:r=this._settings.player.vibrato.noteSlightLength,n=this._settings.player.vibrato.noteSlightAmplitude;break;case j.Wide:r=this._settings.player.vibrato.noteWideLength,n=this._settings.player.vibrato.noteWideAmplitude;break;default:return}const o=e.beat.voice.bar.staff.track;let h=0;if(e.isTieDestination&&e.tieOrigin.hasBend){const t=e.tieOrigin.bendPoints;h=t[t.length-1].value}this.generateVibratorWithParams(t,s.noteOnly,r,h,n,((e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)}))}generateVibratorWithParams(e,t,s,i,a,r){const n=this.vibratoResolution,o=s/2|0,h=e+t;for(;e<h;){let t=0;const l=e+s<h?s:h-e;for(;t<l;){const s=i+a*Math.sin(t*Math.PI/o);r(e+t|0,vr.getPitchWheel(s)),t+=n}e+=s}r(0|h,vr.getPitchWheel(i))}static getPitchWheel(e){return Ls.DefaultPitchWheel+e/2*vr.PitchValuePerSemitone}generateSlide(e,t,s,i,a,r){const n=e.slideOutType===K.Legato?s.noteOnly:s.untilTieOrSlideEnd,o=[],h=e.beat.voice.bar.staff.track,l=this._settings.player.slide.simpleSlidePitchOffset,c=Math.floor(ge.MaxPosition*this._settings.player.slide.simpleSlideDurationRatio),d=Math.floor(ge.MaxPosition*this._settings.player.slide.shiftSlideDurationRatio);switch(e.slideInType){case q.IntoFromAbove:o.push(new ge(0,l)),o.push(new ge(c,0));break;case q.IntoFromBelow:o.push(new ge(0,-l)),o.push(new ge(c,0))}switch(e.slideOutType){case K.Legato:case K.Shift:o.push(new ge(d,0));const t=2*(e.slideTarget.calculateRealValue(this.applyTranspositionPitches,!0)-e.calculateRealValue(this.applyTranspositionPitches,!0));o.push(new ge(ge.MaxPosition,t));break;case K.OutDown:o.push(new ge(ge.MaxPosition-c,0)),o.push(new ge(ge.MaxPosition,-l));break;case K.OutUp:o.push(new ge(ge.MaxPosition-c,0)),o.push(new ge(ge.MaxPosition,l))}this.generateWhammyOrBend(t,n,o,r,((e,t)=>{this._handler.addNoteBend(h.index,e,a,i,t)}))}generateBend(e,t,s,i,a,r){const n=e.bendPoints,o=e.beat.voice.bar.staff.track,h=(e,t)=>{this._handler.addNoteBend(o.index,e,a,i,t)};let l,c=null;if(e.isTieOrigin&&this._settings.notation.extendBendArrowsOnTiedNotes){let t=e;for(;t.isTieOrigin&&!t.tieDestination.hasBend&&t.tieDestination.vibrato===j.None;)t=t.tieDestination;l=t.beat.absolutePlaybackStart-e.beat.absolutePlaybackStart+this.getNoteDuration(t,t.beat.playbackDuration,r).noteOnly}else if(e.isTieOrigin&&e.beat.graceType!==R.None){switch(e.tieDestination.bendType){case y.Bend:case y.BendRelease:case y.PrebendBend:c=e.tieDestination.bendPoints[1].value;break;case y.Prebend:case y.PrebendRelease:c=e.tieDestination.bendPoints[0].value}l=Math.max(s.noteOnly,rs.millisToTicks(this._settings.player.songBookBendDuration,r))}else l=s.noteOnly;n[0].value>0&&!e.isContinuedBend&&t>0&&t--;const d=Math.min(l,rs.millisToTicks(this._settings.player.songBookBendDuration,r));let u=[];switch(e.bendType){case y.Custom:u=n;break;case y.Bend:case y.Release:switch(e.bendStyle){case f.Default:u=n;break;case f.Gradual:u.push(new ge(0,e.bendPoints[0].value)),(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),u.push(new ge(ge.MaxPosition,c));break;case f.Fast:return(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),void(e.beat.graceType===R.BendGrace?this.generateSongBookWhammyOrBend(t,l,!0,[e.bendPoints[0].value,c],d,r,h):this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,c],d,r,h))}break;case y.BendRelease:switch(e.bendStyle){case f.Default:u=n;break;case f.Gradual:u.push(new ge(0,e.bendPoints[0].value)),u.push(new ge(ge.MaxPosition/2|0,e.bendPoints[1].value)),u.push(new ge(ge.MaxPosition,e.bendPoints[2].value));break;case f.Fast:return void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,e.bendPoints[1].value,e.bendPoints[2].value],d,r,h)}break;case y.Hold:case y.Prebend:u=n;break;case y.PrebendBend:switch(e.bendStyle){case f.Default:u=n;break;case f.Gradual:u.push(new ge(0,e.bendPoints[0].value)),u.push(new ge(ge.MaxPosition,e.bendPoints[1].value));break;case f.Fast:return h(t,0|vr.getPitchWheel(e.bendPoints[0].value)),(!c||c<e.bendPoints[1].value)&&(c=e.bendPoints[1].value),void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,c],d,r,h)}break;case y.PrebendRelease:switch(e.bendStyle){case f.Default:u=n;break;case f.Gradual:u.push(new ge(0,e.bendPoints[0].value)),u.push(new ge(ge.MaxPosition,e.bendPoints[1].value));break;case f.Fast:return h(t,0|vr.getPitchWheel(e.bendPoints[0].value)),void this.generateSongBookWhammyOrBend(t,l,!1,[e.bendPoints[0].value,e.bendPoints[1].value],d,r,h)}}this.generateWhammyOrBend(t,l,u,r,h)}generateSongBookWhammyOrBend(e,t,s,i,a,r,n){const o=s?e:e+t-a,h=a/(i.length-1);for(let e=0;e<i.length-1;e++){const t=vr.getPitchWheel(i[e]),s=vr.getPitchWheel(i[e+1]),a=o+h*e;this.generateBendValues(a,h,t,s,r,n)}}generateWhammy(e,t,s,i,a){const r=e.whammyBarPoints,n=e.voice.bar.staff.track,o=s.noteOnly;r[0].value>0&&!e.isContinuedWhammy&&t--;const h=(e,t)=>{this._handler.addBend(n.index,e,i,t)};let l=[];switch(e.whammyBarType){case te.Custom:l=r;break;case te.Dive:switch(e.whammyStyle){case f.Default:l=r;break;case f.Gradual:l.push(new ge(0,r[0].value)),l.push(new ge(ge.MaxPosition,r[1].value));break;case f.Fast:const e=Math.min(o,rs.millisToTicks(this._settings.player.songBookBendDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!1,[r[0].value,r[1].value],e,a,h)}break;case te.Dip:switch(e.whammyStyle){case f.Default:l=r;break;case f.Gradual:l.push(new ge(0,r[0].value)),l.push(new ge(ge.MaxPosition/2|0,r[1].value)),l.push(new ge(ge.MaxPosition,r[2].value));break;case f.Fast:const e=Math.min(o,rs.millisToTicks(this._settings.player.songBookDipDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!0,[r[0].value,r[1].value,r[2].value],e,a,h)}break;case te.Hold:case te.Predive:l=r;break;case te.PrediveDive:switch(e.whammyStyle){case f.Default:l=r;break;case f.Gradual:l.push(new ge(0,r[0].value)),l.push(new ge(ge.MaxPosition/2|0,r[0].value)),l.push(new ge(ge.MaxPosition,r[1].value));break;case f.Fast:const e=vr.getPitchWheel(r[0].value);this._handler.addBend(n.index,t,i,0|e);const s=Math.min(o,rs.millisToTicks(this._settings.player.songBookBendDuration,a));return void this.generateSongBookWhammyOrBend(t,o,!1,[r[0].value,r[1].value],s,a,h)}}this.generateWhammyOrBend(t,o,l,a,h)}generateWhammyOrBend(e,t,s,i,a){const r=t/ge.MaxPosition;for(let t=0;t<s.length-1;t++){const n=s[t],o=s[t+1],h=vr.getPitchWheel(n.value),l=vr.getPitchWheel(o.value),c=r*(o.offset-n.offset),d=e+r*n.offset;this.generateBendValues(d,c,h,l,i,a)}}generateBendValues(e,t,s,i,a,r){const n=rs.ticksToMillis(t,a),o=Math.abs(i-s)/vr.PitchValuePerSemitone,h=Math.max(vr.MinBreakpointsPerSemitone*o,n/vr.MillisecondsPerBreakpoint),l=t/h,c=(i-s)/h,d=e+t;for(let t=0;t<h;t++)r(0|e,Math.round(s)),s+=c,e+=l;r(0|d,i)}generateRasgueado(e,t,s,i,a,r,n){let o=s;for(let s=0;s<n.durations.length;s++){const h=n.brushInfos[s],l=t.isStringed&&t.string<=h.length?h[t.string-1]:0,c=n.durations[s];this._handler.addNote(e.index,o+l,c-l,i,a,r),o+=c}}generateTrill(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track,o=e.stringTuning+e.trillFret;let h=rs.toTicks(e.trillSpeed),l=!0,c=t;const d=t+s.untilTieOrSlideEnd;for(;c+10<d;)c+h>=d&&(h=d-c),this._handler.addNote(n.index,c,h,l?o:i,a,r),l=!l,c+=h}generateTremoloPicking(e,t,s,i,a,r){const n=e.beat.voice.bar.staff.track;let o=rs.toTicks(e.beat.tremoloSpeed),h=t;const l=t+s.untilTieOrSlideEnd;for(;h+10<l;)h+o>=l&&(o=l-h),this._handler.addNote(n.index,h,o,i,a,r),h+=o}getRasgueadoInfo(e,t){if(!e.hasRasgueado)return null;const s=new xr,i=vr.RasgueadoDurations.get(e.rasgueado).reduce(((e,t)=>e+t),0);s.durations=vr.RasgueadoDurations.get(e.rasgueado).map((e=>t*e/i)),s.brushInfos=new Array(s.durations.length);const a=rs.toTicks(D.Sixteenth);let r=0,n=0;for(const t of e.notes)t.isTieDestination||(r|=1<<t.string-1,n++);const o=vr.RasgueadoDirections.get(e.rasgueado);for(let t=0;t<s.durations.length;t++){const i=s.durations[t]*a/rs.QuarterTime,h=new Int32Array(e.voice.bar.staff.tuning.length);s.brushInfos[t]=h;const l=o[t];l!==b.None&&this.fillBrushInfo(e,h,l===b.ArpeggioDown||l===b.BrushDown,r,n,i)}return s}getBrushInfo(e){const t=new Int32Array(e.voice.bar.staff.tuning.length);if(e.brushType){let s=0,i=0;for(const t of e.notes)t.isTieDestination||(s|=1<<t.string-1,i++);this.fillBrushInfo(e,t,e.brushType===b.ArpeggioDown||e.brushType===b.BrushDown,s,i,e.brushDuration)}return t}fillBrushInfo(e,t,s,i,a,r){if(e.notes.length>0){let n=0;const o=r/(a-1)|0;for(let a=0;a<e.voice.bar.staff.tuning.length;a++){const e=s?a:t.length-1-a;i&1<<e&&(t[e]=n,n+=o)}}return t}generateNonTempoAutomation(e,t,s){switch(t.type){case g.Instrument:this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,255&t.value),this.addProgramChange(e.voice.bar.staff.track,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,255&t.value);break;case g.Balance:const i=vr.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Ji.PanCoarse,i),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Ji.PanCoarse,i);break;case g.Volume:const a=vr.toChannelShort(t.value);this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.primaryChannel,Ji.VolumeCoarse,a),this._handler.addControlChange(e.voice.bar.staff.track.index,e.playbackStart+s,e.voice.bar.staff.track.playbackInfo.secondaryChannel,Ji.VolumeCoarse,a)}}prepareSingleBeat(e){let t=-1,s=-1,i=e;for(;i&&(-1===t||-1===s);){for(const i of e.automations)switch(i.type){case g.Instrument:s=i.value;break;case g.Tempo:t=i.value}i=i.previousBeat}const a=e.voice.bar.staff.track,r=e.voice.bar.masterBar;-1===t&&(t=r.score.tempo);const n=e.playbackStart/r.calculateDuration();for(const e of r.tempoAutomations){if(!(e.ratioPosition<=n))break;t=e.value}-1===s&&(s=a.playbackInfo.program);const o=a.playbackInfo.volume;this.generateTrack(a),this._handler.addTimeSignature(0,r.timeSignatureNumerator,r.timeSignatureDenominator),this._handler.addTempo(0,t);const h=vr.toChannelShort(o);return this._handler.addControlChange(0,0,a.playbackInfo.primaryChannel,Ji.VolumeCoarse,h),this._handler.addControlChange(0,0,a.playbackInfo.secondaryChannel,Ji.VolumeCoarse,h),t}generateSingleBeat(e){const t=this.prepareSingleBeat(e);this.generateBeat(e,-e.playbackStart,e.voice.bar,t)}generateSingleNote(e){const t=this.prepareSingleBeat(e.beat);this.generateNote(e,0,e.beat.playbackDuration,t,new Int32Array(e.beat.voice.bar.staff.tuning.length),null)}}vr.DefaultDurationDead=30,vr.DefaultDurationPalmMute=80,vr.OrnamentKeysUp=[2,2,2,1,1,2,2,2,2,2,1,1],vr.OrnamentKeysDown=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],vr.PitchBendRangeInSemitones=16,vr.PitchValuePerSemitone=Ls.DefaultPitchWheel/vr.PitchBendRangeInSemitones,vr.MinBreakpointsPerSemitone=6,vr.MillisecondsPerBreakpoint=150,vr.RasgueadoDirections=new Map([[ae.Ii,[b.BrushDown,b.BrushUp]],[ae.Mi,[b.BrushDown,b.BrushDown]],[ae.MiiTriplet,[b.BrushDown,b.BrushDown,b.BrushUp]],[ae.MiiAnapaest,[b.BrushDown,b.BrushDown,b.BrushUp]],[ae.PmpTriplet,[b.BrushUp,b.BrushDown,b.BrushDown]],[ae.PmpAnapaest,[b.BrushUp,b.BrushDown,b.BrushDown]],[ae.PeiTriplet,[b.BrushUp,b.BrushDown,b.BrushDown]],[ae.PeiAnapaest,[b.BrushUp,b.BrushDown,b.BrushDown]],[ae.PaiTriplet,[b.BrushUp,b.BrushDown,b.BrushDown]],[ae.PaiAnapaest,[b.BrushUp,b.BrushDown,b.BrushDown]],[ae.AmiTriplet,[b.BrushDown,b.BrushDown,b.BrushDown]],[ae.AmiAnapaest,[b.BrushDown,b.BrushDown,b.BrushDown]],[ae.Ppp,[b.None,b.BrushDown,b.BrushUp]],[ae.Amii,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushUp]],[ae.Amip,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushUp]],[ae.Eami,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushDown]],[ae.Eamii,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushDown,b.BrushUp]],[ae.Peami,[b.BrushDown,b.BrushDown,b.BrushDown,b.BrushDown,b.BrushUp]]]),vr.RasgueadoDurations=new Map([[ae.Ii,[rs.toTicks(D.Eighth),rs.toTicks(D.Eighth)]],[ae.Mi,[rs.toTicks(D.Eighth),rs.toTicks(D.Eighth)]],[ae.MiiTriplet,[rs.toTicks(D.Eighth)/3,rs.toTicks(D.Eighth)/3,rs.toTicks(D.Eighth)/3]],[ae.MiiAnapaest,[rs.toTicks(D.Sixteenth),rs.toTicks(D.Sixteenth),rs.toTicks(D.Eighth)]],[ae.PmpTriplet,[rs.toTicks(D.Eighth)/3,rs.toTicks(D.Eighth)/3,rs.toTicks(D.Eighth)/3]],[ae.PmpAnapaest,[rs.toTicks(D.Sixteenth)/3,rs.toTicks(D.Sixteenth)/3,rs.toTicks(D.Eighth)/3]],[ae.PeiTriplet,[rs.toTicks(D.Eighth)/3,rs.toTicks(D.Eighth)/3,rs.toTicks(D.Eighth)/3]],[ae.PeiAnapaest,[rs.toTicks(D.Sixteenth),rs.toTicks(D.Sixteenth),rs.toTicks(D.Eighth)]],[ae.PaiTriplet,[rs.toTicks(D.Eighth)/3,rs.toTicks(D.Eighth)/3,rs.toTicks(D.Eighth)/3]],[ae.PaiAnapaest,[rs.toTicks(D.Sixteenth),rs.toTicks(D.Sixteenth),rs.toTicks(D.Eighth)]],[ae.AmiTriplet,[rs.toTicks(D.Eighth)/3,rs.toTicks(D.Eighth)/3,rs.toTicks(D.Eighth)/3]],[ae.AmiAnapaest,[rs.toTicks(D.Sixteenth)/3,rs.toTicks(D.Sixteenth)/3,rs.toTicks(D.Eighth)/3]],[ae.Ppp,[rs.toTicks(D.Sixteenth)/3,rs.toTicks(D.Sixteenth)/3,rs.toTicks(D.Eighth)/3]],[ae.Amii,[rs.toTicks(D.Sixteenth)/3,rs.toTicks(D.Sixteenth)/3,rs.toTicks(D.Sixteenth)/3,rs.toTicks(D.Eighth)]],[ae.Amip,[rs.toTicks(D.Sixteenth)/3,rs.toTicks(D.Sixteenth)/3,rs.toTicks(D.Sixteenth)/3,rs.toTicks(D.Eighth)]],[ae.Eami,[rs.toTicks(D.Sixteenth),rs.toTicks(D.Sixteenth),rs.toTicks(D.Sixteenth),rs.toTicks(D.Sixteenth)]],[ae.Eamii,[rs.toTicks(D.Sixteenth)/5,rs.toTicks(D.Sixteenth)/5,rs.toTicks(D.Sixteenth)/5,rs.toTicks(D.Sixteenth)/5,rs.toTicks(D.Sixteenth)/5]],[ae.Peami,[rs.toTicks(D.Sixteenth)/5,rs.toTicks(D.Sixteenth)/5,rs.toTicks(D.Sixteenth)/5,rs.toTicks(D.Sixteenth)/5,rs.toTicks(D.Sixteenth)/5]]]);class Pr{constructor(){this.startTick=0,this.endTick=0}}class Fr{constructor(e,t){this.width=0,this.height=0,this.x=e,this.y=t}doLayout(){}paint(e,t,s){}}class Cr extends Fr{constructor(e=0,t=0){super(e,t),this.beat=null,this.nextGlyph=null,this.previousGlyph=null}}class Dr{}Dr.Widths=new Map([[G.Brace,3],[G.BracketTop,0],[G.BracketBottom,0],[G.SystemDivider,0],[G.GClef,28],[G.CClef,28],[G.FClef,28],[G.UnpitchedPercussionClef1,15],[G.SixStringTabClef,28],[G.FourStringTabClef,28],[G.TimeSig0,14],[G.TimeSig1,10],[G.TimeSig2,14],[G.TimeSig3,14],[G.TimeSig4,14],[G.TimeSig5,14],[G.TimeSig6,14],[G.TimeSig7,14],[G.TimeSig8,14],[G.TimeSig9,14],[G.TimeSigCommon,14],[G.TimeSigCutCommon,14],[G.NoteheadDoubleWholeSquare,14],[G.NoteheadDoubleWhole,14],[G.NoteheadWhole,14],[G.NoteheadHalf,9],[G.NoteheadBlack,9],[G.NoteheadNull,9],[G.NoteheadXOrnate,9],[G.NoteheadPlusDoubleWhole,16],[G.NoteheadPlusWhole,10],[G.NoteheadPlusHalf,10],[G.NoteheadPlusBlack,10],[G.NoteheadSquareWhite,11],[G.NoteheadSquareBlack,11],[G.NoteheadTriangleUpDoubleWhole,16],[G.NoteheadTriangleUpWhole,11],[G.NoteheadTriangleUpHalf,11],[G.NoteheadTriangleUpBlack,11],[G.NoteheadTriangleRightWhite,11],[G.NoteheadTriangleRightBlack,11],[G.NoteheadTriangleDownDoubleWhole,16],[G.NoteheadTriangleDownWhole,11],[G.NoteheadTriangleDownHalf,11],[G.NoteheadTriangleDownBlack,11],[G.NoteheadDiamondDoubleWhole,16],[G.NoteheadDiamondWhole,9],[G.NoteheadDiamondHalf,9],[G.NoteheadDiamondBlack,9],[G.NoteheadDiamondBlackWide,10],[G.NoteheadDiamondWhite,9],[G.NoteheadDiamondWhiteWide,9],[G.NoteheadCircleXDoubleWhole,16],[G.NoteheadCircleXWhole,9],[G.NoteheadCircleXHalf,9],[G.NoteheadCircleX,9],[G.NoteheadXDoubleWhole,16],[G.NoteheadXWhole,9],[G.NoteheadXHalf,9],[G.NoteheadXBlack,9],[G.NoteheadParenthesis,9],[G.NoteheadSlashedBlack1,9],[G.NoteheadSlashedBlack2,9],[G.NoteheadSlashedHalf1,9],[G.NoteheadSlashedHalf2,9],[G.NoteheadSlashedWhole1,9],[G.NoteheadSlashedWhole2,9],[G.NoteheadSlashedDoubleWhole1,16],[G.NoteheadSlashedDoubleWhole2,16],[G.NoteheadCircledBlack,9],[G.NoteheadCircledHalf,9],[G.NoteheadCircledWhole,9],[G.NoteheadCircledDoubleWhole,16],[G.NoteheadCircleSlash,9],[G.NoteheadHeavyX,13],[G.NoteheadHeavyXHat,13],[G.NoteheadSlashVerticalEnds,12],[G.NoteheadSlashWhiteWhole,32],[G.NoteheadSlashWhiteHalf,25],[G.NoteheadRoundWhiteWithDot,9],[G.NoteheadSquareBlackLarge,9],[G.NoteheadSquareBlackWhite,9],[G.NoteheadClusterDoubleWhole3rd,16],[G.NoteheadClusterWhole3rd,12],[G.NoteheadClusterHalf3rd,12],[G.NoteheadClusterQuarter3rd,12],[G.NoteShapeRoundWhite,9],[G.NoteShapeRoundBlack,9],[G.NoteShapeSquareWhite,12],[G.NoteShapeSquareBlack,12],[G.NoteShapeTriangleRightWhite,12],[G.NoteShapeTriangleRightBlack,12],[G.NoteShapeTriangleLeftWhite,12],[G.NoteShapeTriangleLeftBlack,12],[G.NoteShapeDiamondWhite,9],[G.NoteShapeDiamondBlack,9],[G.NoteShapeTriangleUpWhite,12],[G.NoteShapeTriangleUpBlack,12],[G.NoteShapeMoonWhite,12],[G.NoteShapeMoonBlack,12],[G.NoteShapeTriangleRoundWhite,12],[G.NoteShapeTriangleRoundBlack,12],[G.NoteQuarterUp,10],[G.NoteEighthUp,10],[G.TextBlackNoteLongStem,0],[G.TextBlackNoteFrac8thLongStem,0],[G.TextBlackNoteFrac16thLongStem,0],[G.TextBlackNoteFrac32ndLongStem,0],[G.TextCont8thBeamLongStem,0],[G.TextCont16thBeamLongStem,0],[G.TextCont32ndBeamLongStem,0],[G.TextAugmentationDot,0],[G.TextTupletBracketStartLongStem,0],[G.TextTuplet3LongStem,0],[G.TextTupletBracketEndLongStem,0],[G.Tremolo3,12],[G.Tremolo2,12],[G.Tremolo1,12],[G.FlagEighthUp,0],[G.FlagEighthDown,0],[G.FlagSixteenthUp,0],[G.FlagSixteenthDown,0],[G.FlagThirtySecondUp,0],[G.FlagThirtySecondDown,0],[G.FlagSixtyFourthUp,0],[G.FlagSixtyFourthDown,0],[G.FlagOneHundredTwentyEighthUp,0],[G.FlagOneHundredTwentyEighthDown,0],[G.FlagTwoHundredFiftySixthUp,0],[G.FlagTwoHundredFiftySixthDown,0],[G.AccidentalFlat,8],[G.AccidentalNatural,8],[G.AccidentalSharp,8],[G.AccidentalDoubleSharp,8],[G.AccidentalDoubleFlat,18],[G.AccidentalQuarterToneFlatArrowUp,8],[G.AccidentalQuarterToneSharpArrowUp,8],[G.AccidentalQuarterToneNaturalArrowUp,8],[G.Segno,0],[G.Coda,0],[G.ArticAccentAbove,9],[G.ArticAccentBelow,9],[G.ArticStaccatoAbove,9],[G.ArticStaccatoBelow,9],[G.ArticTenutoAbove,9],[G.ArticTenutoBelow,9],[G.ArticMarcatoAbove,9],[G.ArticMarcatoBelow,9],[G.FermataAbove,23],[G.FermataShortAbove,23],[G.FermataLongAbove,23],[G.RestLonga,9],[G.RestDoubleWhole,9],[G.RestWhole,9],[G.RestHalf,9],[G.RestQuarter,9],[G.RestEighth,9],[G.RestSixteenth,9],[G.RestThirtySecond,12],[G.RestSixtyFourth,14],[G.RestOneHundredTwentyEighth,14],[G.RestTwoHundredFiftySixth,14],[G.RestHBarLeft,0],[G.RestHBarMiddle,0],[G.RestHBarRight,0],[G.Repeat1Bar,0],[G.Repeat2Bars,0],[G.Ottava,0],[G.OttavaAlta,32],[G.OttavaBassaVb,29],[G.Quindicesima,23],[G.QuindicesimaAlta,46],[G.DynamicPPPPPP,0],[G.DynamicPPPPP,0],[G.DynamicPPPP,0],[G.DynamicPPP,0],[G.DynamicPP,0],[G.DynamicPiano,0],[G.DynamicMP,0],[G.DynamicMF,0],[G.DynamicPF,0],[G.DynamicForte,0],[G.DynamicFF,0],[G.DynamicFFF,0],[G.DynamicFFFF,0],[G.DynamicFFFFF,0],[G.DynamicFFFFFF,0],[G.DynamicFortePiano,0],[G.DynamicNiente,0],[G.DynamicSforzando1,0],[G.DynamicSforzandoPiano,0],[G.DynamicSforzandoPianissimo,0],[G.DynamicSforzato,0],[G.DynamicSforzatoPiano,0],[G.DynamicSforzatoFF,0],[G.DynamicRinforzando1,0],[G.DynamicRinforzando2,0],[G.DynamicForzando,0],[G.OrnamentTrill,20],[G.OrnamentTurn,26],[G.OrnamentTurnInverted,26],[G.OrnamentShortTrill,0],[G.OrnamentMordent,26],[G.StringsDownBow,9],[G.StringsUpBow,9],[G.KeyboardPedalPed,35],[G.KeyboardPedalUp,16],[G.PictEdgeOfCymbal,44],[G.GuitarString0,20],[G.GuitarString1,20],[G.GuitarString2,20],[G.GuitarString3,20],[G.GuitarString4,20],[G.GuitarString5,20],[G.GuitarString6,20],[G.GuitarString7,20],[G.GuitarString8,20],[G.GuitarString9,20],[G.GuitarOpenPedal,11],[G.GuitarClosePedal,11],[G.GuitarGolpe,13.4],[G.GuitarFadeIn,13],[G.GuitarFadeOut,13],[G.GuitarVolumeSwell,26],[G.FretboardX,0],[G.FretboardO,0],[G.WiggleTrill,9],[G.WiggleVibratoMediumFast,10],[G.OctaveBaselineM,13],[G.OctaveBaselineB,9]]),Dr.Heights=new Map([[G.Brace,34],[G.BracketTop,0],[G.BracketBottom,0],[G.SystemDivider,0],[G.GClef,0],[G.CClef,0],[G.FClef,0],[G.UnpitchedPercussionClef1,0],[G.SixStringTabClef,0],[G.FourStringTabClef,0],[G.TimeSig0,0],[G.TimeSig1,0],[G.TimeSig2,0],[G.TimeSig3,0],[G.TimeSig4,0],[G.TimeSig5,0],[G.TimeSig6,0],[G.TimeSig7,0],[G.TimeSig8,0],[G.TimeSig9,0],[G.TimeSigCommon,0],[G.TimeSigCutCommon,0],[G.NoteheadDoubleWholeSquare,8],[G.NoteheadDoubleWhole,8],[G.NoteheadWhole,8],[G.NoteheadHalf,8],[G.NoteheadBlack,8],[G.NoteheadNull,8],[G.NoteheadXOrnate,8],[G.NoteheadPlusDoubleWhole,8],[G.NoteheadPlusWhole,8],[G.NoteheadPlusHalf,8],[G.NoteheadPlusBlack,8],[G.NoteheadSquareWhite,8],[G.NoteheadSquareBlack,8],[G.NoteheadTriangleUpDoubleWhole,8],[G.NoteheadTriangleUpWhole,8],[G.NoteheadTriangleUpHalf,8],[G.NoteheadTriangleUpBlack,8],[G.NoteheadTriangleRightWhite,8],[G.NoteheadTriangleRightBlack,8],[G.NoteheadTriangleDownDoubleWhole,8],[G.NoteheadTriangleDownWhole,8],[G.NoteheadTriangleDownHalf,8],[G.NoteheadTriangleDownBlack,8],[G.NoteheadDiamondDoubleWhole,8],[G.NoteheadDiamondWhole,8],[G.NoteheadDiamondHalf,8],[G.NoteheadDiamondBlack,8],[G.NoteheadDiamondBlackWide,9],[G.NoteheadDiamondWhite,9],[G.NoteheadDiamondWhiteWide,9],[G.NoteheadCircleXDoubleWhole,8],[G.NoteheadCircleXWhole,8],[G.NoteheadCircleXHalf,8],[G.NoteheadCircleX,8],[G.NoteheadXDoubleWhole,8],[G.NoteheadXWhole,8],[G.NoteheadXHalf,8],[G.NoteheadXBlack,8],[G.NoteheadParenthesis,8],[G.NoteheadSlashedBlack1,8],[G.NoteheadSlashedBlack2,8],[G.NoteheadSlashedHalf1,8],[G.NoteheadSlashedHalf2,8],[G.NoteheadSlashedWhole1,8],[G.NoteheadSlashedWhole2,8],[G.NoteheadSlashedDoubleWhole1,8],[G.NoteheadSlashedDoubleWhole2,8],[G.NoteheadCircledBlack,8],[G.NoteheadCircledHalf,8],[G.NoteheadCircledWhole,8],[G.NoteheadCircledDoubleWhole,8],[G.NoteheadCircleSlash,8],[G.NoteheadHeavyX,8],[G.NoteheadHeavyXHat,8],[G.NoteheadSlashVerticalEnds,17],[G.NoteheadSlashWhiteWhole,17],[G.NoteheadSlashWhiteHalf,17],[G.NoteheadRoundWhiteWithDot,8],[G.NoteheadSquareBlackLarge,8],[G.NoteheadSquareBlackWhite,8],[G.NoteheadClusterDoubleWhole3rd,8],[G.NoteheadClusterWhole3rd,8],[G.NoteheadClusterHalf3rd,8],[G.NoteheadClusterQuarter3rd,8],[G.NoteShapeRoundWhite,8],[G.NoteShapeRoundBlack,8],[G.NoteShapeSquareWhite,8],[G.NoteShapeSquareBlack,8],[G.NoteShapeTriangleRightWhite,8],[G.NoteShapeTriangleRightBlack,8],[G.NoteShapeTriangleLeftWhite,8],[G.NoteShapeTriangleLeftBlack,8],[G.NoteShapeDiamondWhite,8],[G.NoteShapeDiamondBlack,8],[G.NoteShapeTriangleUpWhite,8],[G.NoteShapeTriangleUpBlack,8],[G.NoteShapeMoonWhite,8],[G.NoteShapeMoonBlack,8],[G.NoteShapeTriangleRoundWhite,8],[G.NoteShapeTriangleRoundBlack,8],[G.NoteQuarterUp,8],[G.NoteEighthUp,8],[G.TextBlackNoteLongStem,0],[G.TextBlackNoteFrac8thLongStem,0],[G.TextBlackNoteFrac16thLongStem,0],[G.TextBlackNoteFrac32ndLongStem,0],[G.TextCont8thBeamLongStem,0],[G.TextCont16thBeamLongStem,0],[G.TextCont32ndBeamLongStem,0],[G.TextAugmentationDot,0],[G.TextTupletBracketStartLongStem,0],[G.TextTuplet3LongStem,0],[G.TextTupletBracketEndLongStem,0],[G.Tremolo3,0],[G.Tremolo2,0],[G.Tremolo1,0],[G.FlagEighthUp,0],[G.FlagEighthDown,0],[G.FlagSixteenthUp,0],[G.FlagSixteenthDown,0],[G.FlagThirtySecondUp,0],[G.FlagThirtySecondDown,0],[G.FlagSixtyFourthUp,0],[G.FlagSixtyFourthDown,0],[G.FlagOneHundredTwentyEighthUp,0],[G.FlagOneHundredTwentyEighthDown,0],[G.FlagTwoHundredFiftySixthUp,0],[G.FlagTwoHundredFiftySixthDown,0],[G.AccidentalFlat,0],[G.AccidentalNatural,0],[G.AccidentalSharp,0],[G.AccidentalDoubleSharp,0],[G.AccidentalDoubleFlat,0],[G.AccidentalQuarterToneFlatArrowUp,0],[G.AccidentalQuarterToneSharpArrowUp,0],[G.AccidentalQuarterToneNaturalArrowUp,0],[G.Segno,0],[G.Coda,0],[G.ArticAccentAbove,9],[G.ArticAccentBelow,9],[G.ArticStaccatoAbove,9],[G.ArticStaccatoBelow,9],[G.ArticTenutoAbove,9],[G.ArticTenutoBelow,9],[G.ArticMarcatoAbove,9],[G.ArticMarcatoBelow,9],[G.FermataAbove,12],[G.FermataShortAbove,12],[G.FermataLongAbove,12],[G.RestLonga,0],[G.RestDoubleWhole,0],[G.RestWhole,0],[G.RestHalf,0],[G.RestQuarter,0],[G.RestEighth,0],[G.RestSixteenth,0],[G.RestThirtySecond,0],[G.RestSixtyFourth,0],[G.RestOneHundredTwentyEighth,0],[G.RestTwoHundredFiftySixth,0],[G.RestHBarLeft,0],[G.RestHBarMiddle,0],[G.RestHBarRight,0],[G.Repeat1Bar,0],[G.Repeat2Bars,0],[G.Ottava,13],[G.OttavaAlta,13],[G.OttavaBassaVb,13],[G.Quindicesima,13],[G.QuindicesimaAlta,13],[G.DynamicPPPPPP,28.4],[G.DynamicPPPPP,28.4],[G.DynamicPPPP,28.4],[G.DynamicPPP,28.4],[G.DynamicPP,28.4],[G.DynamicPiano,28.4],[G.DynamicMP,28.4],[G.DynamicMF,28.4],[G.DynamicPF,28.4],[G.DynamicForte,28.4],[G.DynamicFF,28.4],[G.DynamicFFF,28.4],[G.DynamicFFFF,28.4],[G.DynamicFFFFF,28.4],[G.DynamicFFFFFF,28.4],[G.DynamicFortePiano,28.4],[G.DynamicNiente,28.4],[G.DynamicSforzando1,28.4],[G.DynamicSforzandoPiano,28.4],[G.DynamicSforzandoPianissimo,28.4],[G.DynamicSforzato,28.4],[G.DynamicSforzatoPiano,28.4],[G.DynamicSforzatoFF,28.4],[G.DynamicRinforzando1,28.4],[G.DynamicRinforzando2,28.4],[G.DynamicForzando,28.4],[G.OrnamentTrill,24],[G.OrnamentTurn,18],[G.OrnamentTurnInverted,18],[G.OrnamentShortTrill,18],[G.OrnamentMordent,18],[G.StringsDownBow,13/.75],[G.StringsUpBow,13/.75],[G.KeyboardPedalPed,19],[G.KeyboardPedalUp,16],[G.PictEdgeOfCymbal,30],[G.GuitarString0,20],[G.GuitarString1,20],[G.GuitarString2,20],[G.GuitarString3,20],[G.GuitarString4,20],[G.GuitarString5,20],[G.GuitarString6,20],[G.GuitarString7,20],[G.GuitarString8,20],[G.GuitarString9,20],[G.GuitarOpenPedal,11],[G.GuitarClosePedal,11],[G.GuitarGolpe,13.4],[G.GuitarFadeIn,13],[G.GuitarFadeOut,13],[G.GuitarVolumeSwell,13],[G.FretboardX,0],[G.FretboardO,0],[G.WiggleTrill,6],[G.WiggleVibratoMediumFast,10],[G.OctaveBaselineM,0],[G.OctaveBaselineB,0]]);class Er extends Cr{constructor(e,t,s,i){super(e,t),this.glyphScale=0,this.center=!1,this.glyphScale=s,this.symbol=i}doLayout(){this.width=Dr.Widths.has(this.symbol)?Dr.Widths.get(this.symbol)*this.glyphScale:0,this.height=Dr.Heights.has(this.symbol)?Dr.Heights.get(this.symbol)*this.glyphScale:0}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride),s.fillMusicFontSymbol(e+this.x,t+this.y,this.glyphScale,this.symbol,this.center),s.color=i}}class Lr extends Er{constructor(e,t,s,i){super(e,t,i?Lr.GraceScale:1,Lr.getSymbol(s)),this.centerOnStem=!1,this._isGrace=i}paint(e,t,s){const i=this._isGrace?1:0;this.centerOnStem&&(this.center=!0),super.paint(e,t+i,s)}static getSymbol(e){switch(e){case D.QuadrupleWhole:return G.NoteheadDoubleWholeSquare;case D.DoubleWhole:return G.NoteheadDoubleWhole;case D.Whole:return G.NoteheadWhole;case D.Half:return G.NoteheadHalf;default:return G.NoteheadBlack}}}Lr.GraceScale=.75;class Mr extends Er{constructor(e,t,s,i,a){super(e,t,a?Lr.GraceScale:1,Mr.getSymbol(s,i,a))}static getSymbol(e,t,s){if(s&&(e=D.Eighth),t===se.Up)switch(e){case D.Eighth:return G.FlagEighthUp;case D.Sixteenth:return G.FlagSixteenthUp;case D.ThirtySecond:return G.FlagThirtySecondUp;case D.SixtyFourth:return G.FlagSixtyFourthUp;case D.OneHundredTwentyEighth:return G.FlagOneHundredTwentyEighthUp;case D.TwoHundredFiftySixth:return G.FlagTwoHundredFiftySixthUp;default:return G.FlagEighthUp}switch(e){case D.Eighth:return G.FlagEighthDown;case D.Sixteenth:return G.FlagSixteenthDown;case D.ThirtySecond:return G.FlagThirtySecondDown;case D.SixtyFourth:return G.FlagSixtyFourthDown;case D.OneHundredTwentyEighth:case D.TwoHundredFiftySixth:return G.FlagOneHundredTwentyEighthDown;default:return G.FlagEighthDown}}}Mr.FlagWidth=11;class Ir extends Fr{get onTimeX(){return this.onNotes.x+this.onNotes.centerX}constructor(e,t){super(0,0),this.ties=[],this.minWidth=0,this.beat=e,this.ties=[],this.voiceContainer=t}addTie(e){e.renderer=this.renderer,this.ties.push(e)}drawBeamHelperAsFlags(e){return e.hasFlag(!1,void 0)}registerLayoutingInfo(e){const t=this.preNotes.computedWidth+this.onNotes.centerX;let s=this.onNotes.computedWidth-this.onNotes.centerX;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);this.beat.graceType!==R.None?1===this.beat.graceGroup.beats.length?s+=Mr.FlagWidth*Lr.GraceScale:this.beat.graceIndex<this.beat.graceGroup.beats.length-1?s+=7:s+=Ir.GraceBeatPadding:i&&this.drawBeamHelperAsFlags(i)&&(s+=Mr.FlagWidth);for(const e of this.ties)s+=e.width;e.addBeatSpring(this.beat,t,s)}applyLayoutingInfo(e){this.onNotes.updateBeamingHelper(),this.updateWidth()}doLayout(){this.preNotes.x=0,this.preNotes.renderer=this.renderer,this.preNotes.container=this,this.preNotes.doLayout(),this.onNotes.x=this.preNotes.x+this.preNotes.width,this.onNotes.renderer=this.renderer,this.onNotes.container=this,this.onNotes.doLayout();let e=this.beat.notes.length-1;for(;e>=0;)this.createTies(this.beat.notes[e--]);this.renderer.registerTies(this.ties),this.updateWidth()}updateWidth(){if(this.minWidth=this.preNotes.width+this.onNotes.width,!this.beat.isRest)if(1===this.onNotes.beamingHelper.beats.length)this.beat.duration>=D.Eighth&&(this.minWidth+=20);else switch(this.beat.duration){case D.OneHundredTwentyEighth:case D.TwoHundredFiftySixth:this.minWidth+=10}let e=0;for(const t of this.ties)t.width>e&&(e=t.width);this.minWidth+=e,this.width=this.minWidth}scaleToWidth(e){this.onNotes.updateBeamingHelper(),this.width=e}createTies(e){}static getGroupId(e){return`b${e.id}`}paint(e,t,s){if(this.preNotes.isEmpty&&this.onNotes.isEmpty&&0===this.ties.length)return;s.beginGroup(Ir.getGroupId(this.beat)),this.preNotes.paint(e+this.x,t+this.y,s),this.onNotes.paint(e+this.x,t+this.y,s);const i=e-this.voiceContainer.x-this.renderer.x,a=t-this.voiceContainer.y-this.renderer.y;for(let e=0,t=this.ties.length;e<t;e++){const t=this.ties[e];t.renderer=this.renderer,t.paint(i,a,s)}s.endGroup()}buildBoundingsLookup(e,t,s,i){const a=new Bi;if(a.beat=this.beat,this.beat.isEmpty)a.visualBounds=new Hs,a.visualBounds.x=t+this.x,a.visualBounds.y=e.visualBounds.y,a.visualBounds.w=this.width,a.visualBounds.h=e.visualBounds.h,a.realBounds=new Hs,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,a.onNotesX=t+this.x+this.onNotes.centerX;else{a.visualBounds=new Hs,a.visualBounds.x=t+this.x,this.preNotes.isEmpty?this.onNotes.isEmpty?a.visualBounds.x=t+this.x:a.visualBounds.x=t+this.x+this.onNotes.x:a.visualBounds.x=t+this.x+this.preNotes.x;let s=0;s=this.onNotes.isEmpty?this.preNotes.isEmpty?t+this.x+this.width:t+this.x+this.preNotes.x+this.preNotes.width:t+this.x+this.onNotes.x+this.onNotes.width,a.visualBounds.w=s-a.visualBounds.x;const i=this.renderer.helpers.getBeamingHelperForBeat(this.beat);(i&&this.drawBeamHelperAsFlags(i)||this.beat.graceType!==R.None)&&(a.visualBounds.w+=Mr.FlagWidth*(this.beat.graceType!==R.None?Lr.GraceScale:1)),a.visualBounds.y=e.visualBounds.y,a.visualBounds.h=e.visualBounds.h,a.realBounds=new Hs,a.realBounds.x=t+this.x,a.realBounds.y=e.realBounds.y,a.realBounds.w=this.width,a.realBounds.h=e.realBounds.h,a.onNotesX=t+this.x+this.onNotes.x+this.onNotes.centerX}e.addBeat(a),this.renderer.settings.core.includeNoteBounds&&this.onNotes.buildBoundingsLookup(a,t+this.x,s+this.y)}}Ir.GraceBeatPadding=3;class Ar{constructor(){this.oldWidth=0,this.newWidth=0,this.settings=null}core(){return this.settings&&this.causeIssue()?this.settings.core:new dc}causeIssue(){return this.settings=null,!0}}class Rr{constructor(e){this.activeBeats=e}}class Or{constructor(e){this.bounds=null,this.beat=e}}class Hr{get score(){return this._score}get tracks(){return this._tracks}constructor(e,t){this._startTime=0,this._trackIndexes=null,this._trackIndexLookup=null,this._isDestroyed=!1,this._score=null,this._tracks=[],this._tickCache=null,this.player=null,this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null,this._previousTick=0,this._playerState=Hi.Paused,this._currentBeat=null,this._currentBarBounds=null,this._previousStateForCursor=Hi.Paused,this._previousCursorCache=null,this._lastScroll=0,this.playedBeatChanged=new _i,this.activeBeatsChanged=new _i,this._beatMouseDown=!1,this._noteMouseDown=!1,this._selectionStart=null,this._selectionEnd=null,this.beatMouseDown=new _i,this.beatMouseMove=new _i,this.beatMouseUp=new _i,this.noteMouseDown=new _i,this.noteMouseMove=new _i,this.noteMouseUp=new _i,this.scoreLoaded=new _i,this.resize=new _i,this.renderStarted=new _i,this.renderFinished=new _i,this.postRenderFinished=new Si,this.error=new _i,this.playerReady=new Si,this.playerFinished=new Si,this.soundFontLoaded=new Si,this.midiLoad=new _i,this.midiLoaded=new _i,this.playerStateChanged=new _i,this.playerPositionChanged=new _i,this.midiEventsPlayed=new _i,this.playbackRangeChanged=new _i,this.settingsUpdated=new Si,this.uiFacade=e,this.container=e.rootContainer,e.initialize(this,t),wt.logLevel=this.settings.core.logLevel,cc.printEnvironmentInfo(!1),this.canvasElement=e.createCanvasElement(),this.container.appendChild(this.canvasElement),this.settings.core.useWorkers&&this.uiFacade.areWorkersSupported&&cc.getRenderEngineFactory(this.settings.core.engine).supportsWorkers?this.renderer=this.uiFacade.createWorkerRenderer():this.renderer=new vi(this.settings),this.container.resize.on(cc.throttle((()=>{this._isDestroyed||this.container.width!==this.renderer.width&&this.triggerResize()}),e.resizeThrottle));const s=new Ar;s.oldWidth=this.renderer.width,s.newWidth=0|this.container.width,s.settings=this.settings,this.onResize(s),this.renderer.preRender.on(this.onRenderStarted.bind(this)),this.renderer.renderFinished.on((e=>{this.onRenderFinished(e)})),this.renderer.postRenderFinished.on((()=>{const e=Date.now()-this._startTime;wt.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&&Be.applyPitchOffsets(this.settings,e),this.renderer.updateSettings(this.settings),this.settings.player.enablePlayer?(this.setupPlayer(),e&&this.player?.applyTranspositionPitches(vr.buildTranspositionPitches(e,this.settings))):this.destroyPlayer(),this.onSettingsUpdated()}load(e,t){try{return this.uiFacade.load(e,(e=>{this.renderScore(e,t)}),(e=>{this.onError(e)}))}catch(e){return this.onError(e),!1}}renderScore(e,t){const s=[];if(t)if(0===t.length)e.tracks.length>0&&s.push(e.tracks[0]);else if(1===t.length&&-1===t[0])for(const t of e.tracks)s.push(t);else for(const i of t)i>=0&&i<=e.tracks.length&&s.push(e.tracks[i]);else e.tracks.length>0&&s.push(e.tracks[0]);this.internalRenderTracks(e,s)}renderTracks(e){if(e.length>0){const t=e[0].score;for(const s of e)if(s.score!==t)return void this.onError(new fe(S.General,"All rendered tracks must belong to the same score."));this.internalRenderTracks(t,e)}}internalRenderTracks(e,t){if(Be.applyPitchOffsets(this.settings,e),e!==this.score){this._score=e,this._tracks=t,this._tickCache=null,this._trackIndexes=[];for(const e of t)this._trackIndexes.push(e.index);this._trackIndexLookup=new Set(this._trackIndexes),this.onScoreLoaded(e),this.loadMidiForScore(),this.render()}else{this._tracks=t;const s=Be.computeFirstDisplayedBarIndex(e,this.settings),i=Be.computeLastDisplayedBarIndex(e,this.settings,s);this._tickCache&&(this._tickCache.multiBarRestInfo=Be.buildMultiBarRestInfo(this.tracks,s,i)),this._trackIndexes=[];for(const e of t)this._trackIndexes.push(e.index);this._trackIndexLookup=new Set(this._trackIndexes),this.render()}}triggerResize(){if(this.container.isVisible){const e=new Ar;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 wt.warning("Rendering","AlphaTab container was invisible while autosizing, waiting for element to become visible",null),this.uiFacade.rootContainerBecameVisible.on((()=>{wt.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{const s=new Is;s.logErrors=!0,s.initFromString(e,this.settings);const i=s.readScore();this.renderScore(i,t)}catch(e){this.onError(e)}}loadSoundFont(e,t=!1){return!!this.player&&this.uiFacade.loadSoundFont(e,t)}resetSoundFonts(){this.player&&this.player.resetSoundFonts()}render(){this.renderer&&(this.uiFacade.canRender?(this.renderer.width=this.container.width,this.renderer.renderScore(this.score,this._trackIndexes)):this.uiFacade.canRenderChanged.on((()=>this.render())))}get tickCache(){return this._tickCache}get boundsLookup(){return this.renderer.boundsLookup}get isReadyForPlayback(){return!!this.player&&this.player.isReadyForPlayback}get playerState(){return this.player?this.player.state:Hi.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=Hi.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(const e of this.tracks){const t=e.playbackInfo.volume/16;this.player.setChannelVolume(e.playbackInfo.primaryChannel,t),this.player.setChannelVolume(e.playbackInfo.secondaryChannel,t)}})),this.player.soundFontLoaded.on(this.onSoundFontLoaded.bind(this)),this.player.soundFontLoadFailed.on((e=>{this.onError(e)})),this.player.midiLoaded.on(this.onMidiLoaded.bind(this)),this.player.midiLoadFailed.on((e=>{this.onError(e)})),this.player.stateChanged.on(this.onPlayerStateChanged.bind(this)),this.player.positionChanged.on(this.onPlayerPositionChanged.bind(this)),this.player.midiEventsPlayed.on(this.onMidiEventsPlayed.bind(this)),this.player.playbackRangeChanged.on(this.onPlaybackRangeChanged.bind(this)),this.player.finished.on(this.onPlayerFinished.bind(this)),this.setupPlayerEvents()))}loadMidiForScore(){if(!this.score)return;const e=this.score;wt.debug("AlphaTab","Generating Midi");const t=new Ae,s=new mr(t),i=new vr(e,this.settings,s),a=Be.computeFirstDisplayedBarIndex(e,this.settings),r=Be.computeLastDisplayedBarIndex(e,this.settings,a);i.tickLookup.multiBarRestInfo=Be.buildMultiBarRestInfo(this.tracks,a,r),i.applyTranspositionPitches=!1,i.generate(),this._tickCache=i.tickLookup,this.onMidiLoad(t);const n=this.player;n&&(n.loadMidiFile(t),n.applyTranspositionPitches(i.transpositionPitches))}changeTrackVolume(e,t){if(this.player)for(const s of e)this.player.setChannelVolume(s.playbackInfo.primaryChannel,t),this.player.setChannelVolume(s.playbackInfo.secondaryChannel,t)}changeTrackSolo(e,t){if(this.player)for(const s of e)this.player.setChannelSolo(s.playbackInfo.primaryChannel,t),this.player.setChannelSolo(s.playbackInfo.secondaryChannel,t)}changeTrackMute(e,t){if(this.player)for(const s of e)this.player.setChannelMute(s.playbackInfo.primaryChannel,t),this.player.setChannelMute(s.playbackInfo.secondaryChannel,t)}changeTrackTranspositionPitch(e,t){if(this.player)for(const s of e)this.player.setChannelTranspositionPitch(s.playbackInfo.primaryChannel,t),this.player.setChannelTranspositionPitch(s.playbackInfo.secondaryChannel,t)}play(){return!!this.player&&this.player.play()}pause(){this.player&&this.player.pause()}playPause(){this.player&&this.player.playPause()}stop(){this.player&&this.player.stop()}playBeat(e){if(!this.player)return;const t=new Ae,s=new mr(t);new vr(e.voice.bar.staff.track.score,this.settings,s).generateSingleBeat(e),this.player.playOneTimeMidiFile(t)}playNote(e){if(!this.player)return;const t=new Ae,s=new mr(t);new vr(e.beat.voice.bar.staff.track.score,this.settings,s).generateSingleNote(e),this.player.playOneTimeMidiFile(t)}destroyCursors(){this._cursorWrapper&&(this.uiFacade.destroyCursors(),this._cursorWrapper=null,this._barCursor=null,this._beatCursor=null,this._selectionWrapper=null)}updateCursors(){if(this.settings.player.enableCursor&&!this._cursorWrapper){const 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=Hi.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,!1,e.isSeek)}))})),this.player.stateChanged.on((e=>{if(this._playerState=e.state,!e.stopped&&e.state===Hi.Paused){const e=this._currentBeat,t=this._tickCache;e&&t&&(this.player.tickPosition=t.getBeatStart(e.beat))}})))}cursorUpdateTick(e,t,s=!1,i=!1){const a=this._tickCache;if(a){const r=this._trackIndexLookup;if(null!=r&&r.size>0){const n=a.findBeat(r,e,this._currentBeat);n&&this.cursorUpdateBeat(n,t,s,i||this.playerState===Hi.Paused)}}}cursorUpdateBeat(e,t,s,i=!1){const a=e.beat,r=e.nextBeat?.beat??null,n=e.duration,o=e.beatLookup.highlightedBeats;if(!a)return;const h=this.renderer.boundsLookup;if(!h)return;const l=this._currentBeat,c=this._previousCursorCache,d=this._previousStateForCursor;if(!i&&a===l?.beat&&h===c&&d===this._playerState&&l?.start===e.start)return;const u=h.findBeat(a);u&&(this._currentBeat=e,this._previousCursorCache=h,this._previousStateForCursor=this._playerState,this.uiFacade.beginInvoke((()=>{this.internalCursorUpdateBeat(a,r,n,t,o,h,u,s,e.cursorMode)})))}scrollToCursor(){const e=this._currentBarBounds;e&&this.internalScrollToCursor(e)}internalScrollToCursor(e){const t=this.uiFacade.getScrollContainer(),s=cc.getLayoutEngineFactory(this.settings.display.layoutMode).vertical,i=this.settings.player.scrollMode;if(s){const s=e.realBounds.y+this.settings.player.scrollOffsetY;if(s!==this._lastScroll)switch(this._lastScroll=s,i){case J.Continuous:const i=this.uiFacade.getOffset(t,this.container);this.uiFacade.scrollToY(t,i.y+s,this.settings.player.scrollSpeed);break;case J.OffScreen:const a=t.scrollTop+this.uiFacade.getOffset(null,t).h;if(e.visualBounds.y+e.visualBounds.h>=a||e.visualBounds.y<t.scrollTop){const s=e.realBounds.y+this.settings.player.scrollOffsetY;this.uiFacade.scrollToY(t,s,this.settings.player.scrollSpeed)}}}else{const s=e.visualBounds.x;if(s!==this._lastScroll)switch(this._lastScroll=s,i){case J.Continuous:const s=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,s,this.settings.player.scrollSpeed);break;case J.OffScreen:const i=t.scrollLeft+this.uiFacade.getOffset(null,t).w;if(e.visualBounds.x+e.visualBounds.w>=i||e.visualBounds.x<t.scrollLeft){const s=e.realBounds.x+this.settings.player.scrollOffsetX;this._lastScroll=e.visualBounds.x,this.uiFacade.scrollToX(t,s,this.settings.player.scrollSpeed)}}}}internalCursorUpdateBeat(e,t,s,i,a,r,n,o,h){const l=this._barCursor,c=this._beatCursor,d=n.barBounds.masterBarBounds,u=d.visualBounds;this._currentBarBounds=d,l&&l.setBounds(u.x,u.y,u.w,u.h),c&&(this.settings.player.enableAnimatedBeatCursor&&c.stopAnimation(),c.setBounds(n.onNotesX,u.y,1,u.h)),this.settings.player.enableElementHighlighting&&this.uiFacade.removeHighlights();let p=!1;const g=this._playerState===Hi.Playing&&!i;if(g){if(this.settings.player.enableElementHighlighting)for(const t of a){const s=Ir.getGroupId(t.beat);this.uiFacade.highlightElements(s,e.voice.bar.index)}o=!i,p=!0}if(this.settings.player.enableAnimatedBeatCursor&&c){let e=d.visualBounds.x+d.visualBounds.w;if(t&&h===$i.ToNextBext){const s=r.findBeat(t);s&&s.barBounds.masterBarBounds.staffSystemBounds===d.staffSystemBounds&&(e=s.onNotesX)}g&&this.uiFacade.beginInvoke((()=>{c.transitionToX(s/this.playbackSpeed,e)}))}o&&!this._beatMouseDown&&this.settings.player.scrollMode!==J.Off&&this.internalScrollToCursor(d),p&&(this.onPlayedBeatChanged(e),this.onActiveBeatsChanged(new Rr(a.map((e=>e.beat)))))}onPlayedBeatChanged(e){this._isDestroyed||(this.playedBeatChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"playedBeatChanged",e))}onActiveBeatsChanged(e){this._isDestroyed||(this.activeBeatsChanged.trigger(e),this.uiFacade.triggerEvent(this.container,"activeBeatsChanged",e))}onBeatMouseDown(e,t){this._isDestroyed||(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&(this._selectionStart=new Or(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 Or(t),this.cursorSelectRange(this._selectionStart,this._selectionEnd))),this.beatMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseMove",t,e))}onNoteMouseMove(e,t){this._isDestroyed||(this.noteMouseMove.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseMove",t,e))}onBeatMouseUp(e,t){if(!this._isDestroyed){if(this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction){if(this._selectionEnd){const e=this._tickCache?.getBeatStart(this._selectionStart.beat)??this._selectionStart.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(this._selectionEnd.beat)??this._selectionEnd.beat.absolutePlaybackStart)<e){const e=this._selectionStart;this._selectionStart=this._selectionEnd,this._selectionEnd=e}}if(this._selectionStart&&this._tickCache){const e=this._tickCache,t=e.getMasterBarStart(this._selectionStart.beat.voice.bar.masterBar);if(this._currentBeat=null,this._playerState===Hi.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){const s=e.getMasterBarStart(this._selectionEnd.beat.voice.bar.masterBar),i=new Pr;i.startTick=t+this._selectionStart.beat.playbackStart,i.endTick=s+this._selectionEnd.beat.playbackStart+this._selectionEnd.beat.playbackDuration-50,this.playbackRange=i}else this._selectionStart=null,this.playbackRange=null,this.cursorSelectRange(this._selectionStart,this._selectionEnd)}}this.beatMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"beatMouseUp",t,e),this._beatMouseDown=!1}}onNoteMouseUp(e,t){this._isDestroyed||(this.noteMouseUp.trigger(t),this.uiFacade.triggerEvent(this.container,"noteMouseUp",t,e),this._noteMouseDown=!1)}updateSelectionCursor(e){if(this._tickCache)if(e){const t=this._tickCache.findBeat(this._trackIndexLookup,e.startTick),s=this._tickCache.findBeat(this._trackIndexLookup,e.endTick);if(t&&s){const e=new Or(t.beat),i=new Or(s.beat);this.cursorSelectRange(e,i)}}else this.cursorSelectRange(null,null)}setupClickHandling(){this.canvasElement.mouseDown.on((e=>{if(!e.isLeftMouseButton)return;this.settings.player.enableUserInteraction&&e.preventDefault();const t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(i&&(this.onBeatMouseDown(e,i),this.settings.core.includeNoteBounds)){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s);a&&this.onNoteMouseDown(e,a)}})),this.canvasElement.mouseMove.on((e=>{if(!this._beatMouseDown)return;const t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(i&&(this.onBeatMouseMove(e,i),this._noteMouseDown)){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s);a&&this.onNoteMouseMove(e,a)}})),this.canvasElement.mouseUp.on((e=>{if(!this._beatMouseDown)return;this.settings.player.enableUserInteraction&&e.preventDefault();const t=e.getX(this.canvasElement),s=e.getY(this.canvasElement),i=this.renderer.boundsLookup?.getBeatAtPos(t,s)??null;if(this.onBeatMouseUp(e,i),this._noteMouseDown)if(i){const a=this.renderer.boundsLookup?.getNoteAtPos(i,t,s)??null;this.onNoteMouseUp(e,a)}else this.onNoteMouseUp(e,null)})),this.renderer.postRenderFinished.on((()=>{this._selectionStart&&this.settings.player.enablePlayer&&this.settings.player.enableCursor&&this.settings.player.enableUserInteraction&&this.cursorSelectRange(this._selectionStart,this._selectionEnd)}))}cursorSelectRange(e,t){const s=this.renderer.boundsLookup;if(!s)return;const i=this._selectionWrapper;if(!i)return;if(i.clear(),!e||!t||e.beat===t.beat)return;e.bounds||(e.bounds=s.findBeat(e.beat)),t.bounds||(t.bounds=s.findBeat(t.beat));const a=this._tickCache?.getBeatStart(e.beat)??e.beat.absolutePlaybackStart;if((this._tickCache?.getBeatStart(t.beat)??t.beat.absolutePlaybackStart)<a){const s=e;e=t,t=s}const r=e.bounds.realBounds.x;let n=t.bounds.realBounds.x+t.bounds.realBounds.w;if(t.beat.index===t.beat.voice.beats.length-1&&(n=t.bounds.barBounds.masterBarBounds.realBounds.x+t.bounds.barBounds.masterBarBounds.realBounds.w),e.bounds.barBounds.masterBarBounds.staffSystemBounds!==t.bounds.barBounds.masterBarBounds.staffSystemBounds){const a=e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.x,o=e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.x+e.bounds.barBounds.masterBarBounds.staffSystemBounds.visualBounds.w,h=this.uiFacade.createSelectionElement();h.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,o-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(h);const l=e.bounds.barBounds.masterBarBounds.staffSystemBounds.index+1,c=t.bounds.barBounds.masterBarBounds.staffSystemBounds.index;for(let e=l;e<c;e++){const t=s.staffSystems[e],r=this.uiFacade.createSelectionElement();r.setBounds(a,t.visualBounds.y,o-a,t.visualBounds.h),i.appendChild(r)}const d=this.uiFacade.createSelectionElement();d.setBounds(a,t.bounds.barBounds.masterBarBounds.visualBounds.y,n-a,t.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(d)}else{const t=this.uiFacade.createSelectionElement();t.setBounds(r,e.bounds.barBounds.masterBarBounds.visualBounds.y,n-r,e.bounds.barBounds.masterBarBounds.visualBounds.h),i.appendChild(t)}}onScoreLoaded(e){this._isDestroyed||(this.scoreLoaded.trigger(e),this.uiFacade.triggerEvent(this.container,"scoreLoaded",e))}onResize(e){this._isDestroyed||(this.resize.trigger(e),this.uiFacade.triggerEvent(this.container,"resize",e))}onRenderStarted(e){this._isDestroyed||(this.renderStarted.trigger(e),this.uiFacade.triggerEvent(this.container,"renderStarted",e))}onRenderFinished(e){this._isDestroyed||(this.renderFinished.trigger(e),this.uiFacade.triggerEvent(this.container,"renderFinished",e))}onPostRenderFinished(){this._isDestroyed||(this.postRenderFinished.trigger(),this.uiFacade.triggerEvent(this.container,"postRenderFinished",null))}onError(e){this._isDestroyed||(wt.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))}async enumerateOutputDevices(){return this.player?await this.player.output.enumerateOutputDevices():[]}async setOutputDevice(e){this.player&&await this.player.output.setOutputDevice(e)}async getOutputDevice(){return this.player?await this.player.output.getOutputDevice():null}}class Wr extends fe{constructor(e,t){super(S.General,e),this.xhr=t,Object.setPrototypeOf(this,Wr.prototype)}}class Vr{static loadScoreAsync(e,t,s,i){const a=new XMLHttpRequest;a.open("GET",e,!0,null,null),a.responseType="arraybuffer",a.onreadystatechange=()=>{if(a.readyState===XMLHttpRequest.DONE){const e=a.response;if(200===a.status||0===a.status&&e)try{const e=a.response,s=new Uint8Array(e),r=Vr.loadScoreFromBytes(s,i);t(r)}catch(e){s(e)}else 0===a.status?s(new Wr("You are offline!!\n Please Check Your Network.",a)):404===a.status?s(new Wr("Requested URL not found.",a)):500===a.status?s(new Wr("Internel Server Error.",a)):"parsererror"===a.statusText?s(new Wr("Error.\nParsing JSON Request failed.",a)):"timeout"===a.statusText?s(new Wr("Request Time out.",a)):s(new Wr(`Unknow Error: ${a.responseText}`,a))}},a.send()}static loadScoreFromBytes(e,t){t||(t=new ut);const s=cc.buildImporters();wt.debug("ScoreLoader",`Loading score from ${e.length} bytes using ${s.length} importers`);let i=null;const a=Me.fromBuffer(e);for(const e of s){a.reset();try{wt.debug("ScoreLoader",`Importing using importer ${e.name}`),e.init(a,t),i=e.readScore(),wt.debug("ScoreLoader",`Score imported using ${e.name}`);break}catch(t){if(!(t instanceof Es))throw wt.error("ScoreLoader","Score import failed due to unexpected error: ",t),t;wt.debug("ScoreLoader",`${e.name} does not support the file`)}}if(i)return i;throw new Es("No compatible importer found for file")}}class Gr{get isLeftMouseButton(){return 0===this.mouseEvent.button}getX(e){const t=e.element,s=t.getBoundingClientRect().left+t.ownerDocument.defaultView.pageXOffset;return this.mouseEvent.pageX-s}getY(e){const t=e.element,s=t.getBoundingClientRect().top+t.ownerDocument.defaultView.pageYOffset;return this.mouseEvent.pageY-s}preventDefault(){this.mouseEvent.preventDefault()}constructor(e){this.mouseEvent=e}}class zr{get width(){return this.element.offsetWidth}set width(e){this.element.style.width=`${e}px`}get scrollLeft(){return this.element.scrollLeft}set scrollLeft(e){this.element.scrollLeft=e}get scrollTop(){return this.element.scrollTop}set scrollTop(e){this.element.scrollTop=e}get height(){return this.element.offsetHeight}set height(e){this.element.style.height=e>=0?`${e}px`:"100%"}get isVisible(){return!!this.element.offsetWidth||!!this.element.offsetHeight||!!this.element.getClientRects().length}constructor(e){this._resizeListeners=0,this.lastBounds=new Hs,this.element=e,this.mouseDown={on:e=>{this.element.addEventListener("mousedown",(t=>{e(new Gr(t))}),!0)},off:e=>{}},this.mouseUp={on:e=>{this.element.addEventListener("mouseup",(t=>{e(new Gr(t))}),!0)},off:e=>{}},this.mouseMove={on:e=>{this.element.addEventListener("mousemove",(t=>{e(new Gr(t))}),!0)},off:e=>{}},this.resize={on:e=>{0===this._resizeListeners&&zr.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,zr.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,Number.NaN,Number.NaN,Number.NaN)}setBounds(e,t,s,i){Number.isNaN(e)&&(e=this.lastBounds.x),Number.isNaN(t)&&(t=this.lastBounds.y),Number.isNaN(s)&&(s=this.lastBounds.w),Number.isNaN(i)&&(i=this.lastBounds.h),this.element.style.transform=`translate(${e}px, ${t}px) scale(${s}, ${i})`,this.element.style.transformOrigin="top left",this.lastBounds.x=e,this.lastBounds.y=t,this.lastBounds.w=s,this.lastBounds.h=i}appendChild(e){this.element.appendChild(e.element)}clear(){this.element.innerHTML=""}}zr.resizeObserver=new St((()=>new ResizeObserver((e=>{for(const t of e){const e=new CustomEvent("resize",{detail:t});t.target.dispatchEvent(e)}}))));class Ur{constructor(e){this._isStarted=!1,this.isFontLoaded=!1,this.fontLoaded=new _i,this._originalFamilies=e,this._families=e}checkForFontAvailability(){if(cc.isRunningInWorker)return void(this.isFontLoaded=!1);if(this._isStarted)return;this._isStarted=!0;let e=0;const t=window.setInterval((()=>{wt.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);wt.debug("Font",`Start checking for font availablility: ${this._families.join(", ")}`);const s=e=>{this._families.length>1?(wt.debug("Font",`[${this._families[0]}] Loading Failed, switching to ${this._families[1]}`,e),this._families.shift(),window.setTimeout((()=>{a()}),0)):(wt.error("Font",`[${this._originalFamilies.join(",")}] Loading Failed, rendering cannot start`,e),window.clearInterval(t))},i=e=>{wt.debug("Font",`[${e}] Font API signaled available`),this.isFontLoaded=!0,window.clearInterval(t),this.fontLoaded.trigger(this._families[0])},a=async()=>{for(const e of this._families)if(await this.isFontAvailable(e,!1))return void i(e);try{await document.fonts.load(`1em ${this._families[0]}`)}catch(e){s(e)}return wt.debug("Font",`[${this._families[0]}] Font API signaled loaded`),await this.isFontAvailable(this._families[0],!0)?i(this._families[0]):s("Font not available"),!0};document.fonts.ready.then((()=>{a()}))}isFontAvailable(e,t){return new Promise((s=>{const i=`1em ${e}`;if(document.fonts.check(i))s(!0);else if(t){wt.debug("Font",`Font ${e} not available, creating test element to trigger load`);const t=document.createElement("div");t.style.font=i,t.style.opacity="0",t.style.position="absolute",t.style.top="0",t.style.left="0",t.innerText=`Trigger ${e} load`,document.body.appendChild(t),setTimeout((()=>{document.body.removeChild(t),document.fonts.check(i)?s(!0):s(!1)}),200)}else s(!1)}))}}class Xr{constructor(e){this._writePosition=0,this._readPosition=0,this.count=0,this._buffer=new Float32Array(e)}clear(){this._readPosition=0,this._writePosition=0,this.count=0,this._buffer=new Float32Array(this._buffer.length)}write(e,t,s){let i=0;s>this._buffer.length-this.count&&(s=this._buffer.length-this.count);const a=Math.min(this._buffer.length-this._writePosition,s);return this._buffer.set(e.subarray(t,t+a),this._writePosition),this._writePosition+=a,this._writePosition%=this._buffer.length,i+=a,i<s&&(this._buffer.set(e.subarray(t+i,t+i+s-i),this._writePosition),this._writePosition+=s-i,i=s),this.count+=i,i}read(e,t,s){s>this.count&&(s=this.count);let i=0;const a=Math.min(this._buffer.length-this._readPosition,s);return e.set(this._buffer.subarray(this._readPosition,this._readPosition+a),t),i+=a,this._readPosition+=a,this._readPosition%=this._buffer.length,i<s&&(e.set(this._buffer.subarray(this._readPosition,this._readPosition+s-i),t+i),this._readPosition+=s-i,i=s),this.count-=i,i}}class Jr{constructor(e){this.isDefault=!1,this.device=e}get deviceId(){return this.device.deviceId}get label(){return this.device.label}}class Yr{constructor(){this._context=null,this._buffer=null,this._source=null,this.ready=new Si,this.samplesPlayed=new _i,this.sampleRequest=new Si,this._knownDevices=[]}get sampleRate(){return this._context?this._context.sampleRate:Yr.PreferredSampleRate}activate(e){this._context||(this._context=this.createAudioContext()),"suspended"!==this._context.state&&"interrupted"!==this._context.state||(wt.debug("WebAudio","Audio Context is suspended, trying resume"),this._context.resume().then((()=>{wt.debug("WebAudio",`Audio Context resume success: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}`),e&&e()}),(e=>{wt.warning("WebAudio",`Audio Context resume failed: state=${this._context?.state}, sampleRate:${this._context?.sampleRate}, reason=${e}`)})))}patchIosSampleRate(){const e=navigator.userAgent;if(-1!==e.indexOf("iPhone")||-1!==e.indexOf("iPad")){const e=this.createAudioContext(),t=e.createBuffer(1,1,Yr.PreferredSampleRate),s=e.createBufferSource();s.buffer=t,s.connect(e.destination),s.start(0),s.disconnect(0),e.close()}}createAudioContext(){if("AudioContext"in cc.globalThis)return new AudioContext;if("webkitAudioContext"in cc.globalThis)return new webkitAudioContext;throw new fe(S.General,"AudioContext not found")}open(e){this.patchIosSampleRate(),this._context=this.createAudioContext();"suspended"===this._context.state&&this.registerResumeHandler()}registerResumeHandler(){this._resumeHandler=(()=>{this.activate((()=>{this.unregisterResumeHandler()}))}).bind(this),document.body.addEventListener("touchend",this._resumeHandler,!1),document.body.addEventListener("click",this._resumeHandler,!1)}unregisterResumeHandler(){const e=this._resumeHandler;e&&(document.body.removeEventListener("touchend",e,!1),document.body.removeEventListener("click",e,!1))}play(){const e=this._context;this.activate(),this._buffer=e.createBuffer(2,Yr.BufferSize,e.sampleRate),this._source=e.createBufferSource(),this._source.buffer=this._buffer,this._source.loop=!0}pause(){this._source&&(this._source.stop(0),this._source.disconnect()),this._source=null}destroy(){this.pause(),this._context?.close(),this._context=null,this.unregisterResumeHandler()}onSamplesPlayed(e){this.samplesPlayed.trigger(e)}onSampleRequest(){this.sampleRequest.trigger()}onReady(){this.ready.trigger()}async checkSinkIdSupport(){return"setSinkId"in(this._context??this.createAudioContext())||(wt.warning("WebAudio","Browser does not support changing the output device"),!1)}async enumerateOutputDevices(){try{if(!await this.checkSinkIdSupport())return[];try{await navigator.mediaDevices.getUserMedia({audio:!0})}catch(e){wt.warning("WebAudio","Output device permission rejected",e)}const e=await navigator.mediaDevices.enumerateDevices();let t="",s="";const i=new Map;for(const a of e)"audiooutput"===a.kind&&(i.set(a.groupId,new Jr(a)),"default"!==a.deviceId&&""!==a.deviceId||(t=a.groupId,s=a.deviceId));const a=Array.from(i.values());let r=a.find((e=>e.deviceId===s));return r||(r=a.find((e=>e.device.groupId===t))),!r&&a.length>0&&(r=a[0]),r&&(r.isDefault=!0),this._knownDevices=a,a}catch(e){return wt.error("WebAudio","Failed to enumerate output devices",e),[]}}async setOutputDevice(e){await this.checkSinkIdSupport()&&(e?await this._context.setSinkId(e.deviceId):await this._context.setSinkId(""))}async getOutputDevice(){if(!await this.checkSinkIdSupport())return null;const e=this._context.sinkId;if("string"!=typeof e||""===e||"default"===e)return null;let t=this._knownDevices.find((t=>t.deviceId===e));if(t)return t;const s=await this.enumerateOutputDevices();return t=s.find((t=>t.deviceId===e)),t||(wt.warning("WebAudio","Could not find output device in device list",e,s),null)}}Yr.BufferSize=4096,Yr.PreferredSampleRate=44100;class $r extends Yr{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/Yr.BufferSize),this._circularBuffer=new Xr(Yr.BufferSize*this._bufferCount),this.onReady()}play(){super.play();const 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,t=e*Yr.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*Yr.BufferSize<t){for(let t=0;t<e;t++)this.onSampleRequest();this._requestedBufferCount+=e}}generateSound(e){const t=e.outputBuffer.getChannelData(0),s=e.outputBuffer.getChannelData(1),i=t.length+s.length;let a=this._outputBuffer;a.length!==i&&(a=new Float32Array(i),this._outputBuffer=a);const r=this._circularBuffer.read(a,0,Math.min(a.length,this._circularBuffer.count));let n=0;const o=Math.min(t.length,r);for(let e=0;e<o;e++)t[e]=a[n++],s[e]=a[n++];if(r<t.length)for(let e=r;e<t.length;e++)t[e]=0,s[e]=0;this.onSamplesPlayed(r/Ls.AudioChannels),this.requestBuffers()}}class qr{constructor(e,t){this.loaded=e,this.total=t}}class Kr{get output(){return this._output}get isReady(){return this._workerIsReady&&this._outputIsReady}get isReadyForPlayback(){return this._workerIsReadyForPlayback}get state(){return this._state}get logLevel(){return wt.logLevel}set logLevel(e){wt.logLevel=e,this._synth.postMessage({cmd:"alphaSynth.setLogLevel",value:e})}get masterVolume(){return this._masterVolume}set masterVolume(e){e=Math.max(e,Ls.MinVolume),this._masterVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMasterVolume",value:e})}get metronomeVolume(){return this._metronomeVolume}set metronomeVolume(e){e=Math.max(e,Ls.MinVolume),this._metronomeVolume=e,this._synth.postMessage({cmd:"alphaSynth.setMetronomeVolume",value:e})}get countInVolume(){return this._countInVolume}set countInVolume(e){e=Math.max(e,Ls.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=Be.clamp(e,Ls.MinPlaybackSpeed,Ls.MaxPlaybackSpeed),this._playbackSpeed=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackSpeed",value:e})}get tickPosition(){return this._tickPosition}set tickPosition(e){e<0&&(e=0),this._tickPosition=e,this._synth.postMessage({cmd:"alphaSynth.setTickPosition",value:e})}get timePosition(){return this._timePosition}set timePosition(e){e<0&&(e=0),this._timePosition=e,this._synth.postMessage({cmd:"alphaSynth.setTimePosition",value:e})}get isLooping(){return this._isLooping}set isLooping(e){this._isLooping=e,this._synth.postMessage({cmd:"alphaSynth.setIsLooping",value:e})}get playbackRange(){return this._playbackRange}set playbackRange(e){e&&(e.startTick<0&&(e.startTick=0),e.endTick<0&&(e.endTick=0)),this._playbackRange=e,this._synth.postMessage({cmd:"alphaSynth.setPlaybackRange",value:e})}constructor(e,t){this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Hi.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 Si,this.readyForPlayback=new Si,this.finished=new Si,this.soundFontLoaded=new Si,this.soundFontLoadFailed=new _i,this.midiLoaded=new _i,this.midiLoadFailed=new _i,this.stateChanged=new _i,this.positionChanged=new _i,this.midiEventsPlayed=new _i,this.playbackRangeChanged=new _i,this._workerIsReadyForPlayback=!1,this._workerIsReady=!1,this._outputIsReady=!1,this._state=Hi.Paused,this._masterVolume=0,this._metronomeVolume=0,this._playbackSpeed=0,this._tickPosition=0,this._timePosition=0,this._isLooping=!1,this._playbackRange=null,this._output=e,this._output.ready.on(this.onOutputReady.bind(this)),this._output.samplesPlayed.on(this.onOutputSamplesPlayed.bind(this)),this._output.sampleRequest.on(this.onOutputSampleRequest.bind(this)),this._output.open(t.player.bufferTimeInMilliseconds);try{this._synth=cc.createWebWorker(t)}catch(e){wt.error("AlphaSynth",`Failed to create WebWorker: ${e}`)}this._synth.addEventListener("message",this.handleWorkerMessage.bind(this),!1),this._synth.postMessage({cmd:"alphaSynth.initialize",sampleRate:this._output.sampleRate,logLevel:t.core.logLevel,bufferTimeInMilliseconds:t.player.bufferTimeInMilliseconds}),this.masterVolume=1,this.playbackSpeed=1,this.metronomeVolume=0}destroy(){this._synth.postMessage({cmd:"alphaSynth.destroy"})}play(){return this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.play"}),!0}pause(){this._synth.postMessage({cmd:"alphaSynth.pause"})}playPause(){this._output.activate(),this._synth.postMessage({cmd:"alphaSynth.playPause"})}stop(){this._synth.postMessage({cmd:"alphaSynth.stop"})}playOneTimeMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.playOneTimeMidiFile",midi:ts.midiFileToJsObject(e)})}loadSoundFont(e,t){this._synth.postMessage({cmd:"alphaSynth.loadSoundFontBytes",data:e,append:t})}loadSoundFontFromUrl(e,t,s){wt.debug("AlphaSynth",`Start loading Soundfont from url ${e}`);const i=new XMLHttpRequest;i.open("GET",e,!0,null,null),i.responseType="arraybuffer",i.onload=e=>{const s=new Uint8Array(i.response);this.loadSoundFont(s,t)},i.onerror=e=>{wt.error("AlphaSynth",`Loading failed: ${e.message}`),this.soundFontLoadFailed.trigger(new Wr(e.message,i))},i.onprogress=e=>{wt.debug("AlphaSynth",`Soundfont downloading: ${e.loaded}/${e.total} bytes`),s(new qr(e.loaded,e.total))},i.send()}resetSoundFonts(){this._synth.postMessage({cmd:"alphaSynth.resetSoundFonts"})}loadMidiFile(e){this._synth.postMessage({cmd:"alphaSynth.loadMidi",midi:ts.midiFileToJsObject(e)})}applyTranspositionPitches(e){this._synth.postMessage({cmd:"alphaSynth.applyTranspositionPitches",transpositionPitches:JSON.stringify(Array.from(e.entries()))})}setChannelTranspositionPitch(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelTranspositionPitch",channel:e,semitones:t})}setChannelMute(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelMute",channel:e,mute:t})}resetChannelStates(){this._synth.postMessage({cmd:"alphaSynth.resetChannelStates"})}setChannelSolo(e,t){this._synth.postMessage({cmd:"alphaSynth.setChannelSolo",channel:e,solo:t})}setChannelVolume(e,t){t=Math.max(t,Ls.MinVolume),this._synth.postMessage({cmd:"alphaSynth.setChannelVolume",channel:e,volume:t})}handleWorkerMessage(e){const 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 aa(t.currentTime,t.endTime,t.currentTick,t.endTick,t.isSeek));break;case"alphaSynth.midiEventsPlayed":this.midiEventsPlayed.trigger(new hr(t.events.map(ts.jsObjectToMidiEvent)));break;case"alphaSynth.playerStateChanged":this._state=t.state,this.stateChanged.trigger(new ia(t.state,t.stopped));break;case"alphaSynth.playbackRangeChanged":this._playbackRange=t.playbackRange,this.playbackRangeChanged.trigger(new lr(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 aa(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 jr{constructor(e,t){this._width=0,this.boundsLookup=null,this.preRender=new _i,this.partialRenderFinished=new _i,this.partialLayoutFinished=new _i,this.renderFinished=new _i,this.postRenderFinished=new Si,this.error=new _i,this._api=e;try{this._worker=cc.createWebWorker(t)}catch(e){return void wt.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=ts.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){const t=e.data;switch(t.cmd){case"alphaTab.preRender":this.preRender.trigger(t.resize);break;case"alphaTab.partialRenderFinished":this.partialRenderFinished.trigger(t.result);break;case"alphaTab.partialLayoutFinished":this.partialLayoutFinished.trigger(t.result);break;case"alphaTab.renderFinished":this.renderFinished.trigger(t.result);break;case"alphaTab.postRenderFinished":this.boundsLookup=xi.fromJson(t.boundsLookup,this._api.score),this.boundsLookup.finish(),this.postRenderFinished.trigger();break;case"alphaTab.error":this.error.trigger(t.error)}}renderScore(e,t){const s=null==e?null:ts.scoreToJsObject(e);this._worker.postMessage({cmd:"alphaTab.renderScore",score:s,trackIndexes:t,fontSizes:ys.FontSizeLookupTables})}}class Qr{static init(){var e;Qr._isRegistered||(Qr._isRegistered=!0,registerProcessor("alphatab",((e=class extends AudioWorkletProcessor{constructor(t){super(t),this._outputBuffer=new Float32Array(0),this._bufferCount=0,this._requestedBufferCount=0,this._isStopped=!1,wt.debug("WebAudio","creating processor"),this._bufferCount=Math.floor(t.processorOptions.bufferTimeInMilliseconds*sampleRate/1e3/e.BufferSize),this._circularBuffer=new Xr(e.BufferSize*this._bufferCount),this.port.onmessage=this.handleMessage.bind(this)}handleMessage(e){const t=e.data;switch(t.cmd){case dr.CmdOutputAddSamples:const e=t.samples;this._circularBuffer.write(e,0,e.length),this._requestedBufferCount--;break;case dr.CmdOutputResetSamples:this._circularBuffer.clear();break;case dr.CmdOutputStop:this._isStopped=!0}}process(e,t,s){if(1!==t.length&&2!==t[0].length)return!1;const i=t[0][0],a=t[0][1];if(!i||!a)return!0;const r=i.length+a.length;let n=this._outputBuffer;n.length!==r&&(n=new Float32Array(r),this._outputBuffer=n);const o=this._circularBuffer.read(n,0,Math.min(n.length,this._circularBuffer.count));let h=0;const l=Math.min(i.length,o);for(let e=0;e<l;e++)i[e]=n[h++],a[e]=n[h++];if(o<i.length)for(let e=o;e<i.length;e++)i[e]=0,a[e]=0;return this.port.postMessage({cmd:dr.CmdOutputSamplesPlayed,samples:o/Ls.AudioChannels}),this.requestBuffers(),this._circularBuffer.count>0||!this._isStopped}requestBuffers(){const t=this._bufferCount/2|0,s=t*e.BufferSize;if(this._circularBuffer.count+this._requestedBufferCount*e.BufferSize<s){for(let e=0;e<t;e++)this.port.postMessage({cmd:dr.CmdOutputSampleRequest});this._requestedBufferCount+=t}}}).BufferSize=4096,e)))}}Qr._isRegistered=!1;class Zr extends Yr{constructor(e){super(),this._worklet=null,this._bufferTimeInMilliseconds=0,this._settings=e}open(e){super.open(e),this._bufferTimeInMilliseconds=e,this.onReady()}play(){super.play();const e=this._context;cc.createAudioWorklet(e,this._settings).then((()=>{this._worklet=new AudioWorkletNode(e,"alphatab",{numberOfOutputs:1,outputChannelCount:[2],processorOptions:{bufferTimeInMilliseconds:this._bufferTimeInMilliseconds}}),this._worklet.port.onmessage=this.handleMessage.bind(this),this._source.connect(this._worklet),this._source.start(0),this._worklet.connect(e.destination)}),(e=>{wt.error("WebAudio",`Audio Worklet creation failed: reason=${e}`)}))}handleMessage(e){const t=e.data;switch(t.cmd){case dr.CmdOutputSamplesPlayed:this.onSamplesPlayed(t.samples);break;case dr.CmdOutputSampleRequest:this.onSampleRequest()}}pause(){super.pause(),this._worklet&&(this._worklet.port.postMessage({cmd:dr.CmdOutputStop}),this._worklet.port.onmessage=null,this._worklet.disconnect()),this._worklet=null}addSamples(e){this._worklet?.port.postMessage({cmd:dr.CmdOutputAddSamples,samples:e})}resetSamples(){this._worklet?.port.postMessage({cmd:dr.CmdOutputResetSamples})}}class en extends zr{constructor(e,t,s){super(e),this._xscale=t,this._yscale=s}get width(){return this.element.offsetWidth/this._xscale}set width(e){this.element.style.width=e*this._xscale+"px"}get height(){return this.element.offsetHeight/this._yscale}set height(e){this.element.style.height=e>=0?e*this._yscale+"px":"100%"}setBounds(e,t,s,i){Number.isNaN(e)&&(e=this.lastBounds.x),Number.isNaN(t)&&(t=this.lastBounds.y),Number.isNaN(s)?s=this.lastBounds.w:s/=this._xscale,Number.isNaN(i)?i=this.lastBounds.h:i/=this._yscale,this.element.style.transform=`translate(${e}px, ${t}px) scale(${s}, ${i})`,this.element.style.transformOrigin="top left",this.lastBounds.x=e,this.lastBounds.y=t,this.lastBounds.w=s,this.lastBounds.h=i}}!function(e){e[e.LayoutDone=0]="LayoutDone",e[e.RenderRequested=1]="RenderRequested",e[e.RenderDone=2]="RenderDone",e[e.Detached=3]="Detached"}(qi||(qi={}));class tn{get resizeThrottle(){return 10}get canRender(){return this.areAllFontsLoaded()}areAllFontsLoaded(){if(cc.bravuraFontChecker.checkForFontAvailability(),!cc.bravuraFontChecker.isFontLoaded)return!1;let e=!1;for(const t of this._fontCheckers.values())t.isFontLoaded||(e=!0);return!e&&(wt.debug("Font",`All fonts loaded: ${this._fontCheckers.size}`),!0)}onFontLoaded(e){ys.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 Si,this.canRenderChanged=new Si,this._highlightedElements=[],this._scrollContainer=null,cc.webPlatform!==us.Browser&&cc.webPlatform!==us.BrowserModule)throw new fe(S.General,"Usage of AlphaTabApi is only possible in browser environments. For usage in node use the Low Level APIs");e.classList.add("alphaTab"),this.rootContainer=new zr(e),this.areWorkersSupported="Worker"in window,cc.bravuraFontChecker.fontLoaded.on(this.onFontLoaded.bind(this)),this._intersectionObserver=new IntersectionObserver(this.onElementVisibilityChanged.bind(this),{threshold:[0,.01,1]}),this._intersectionObserver.observe(e)}onElementVisibilityChanged(e){for(const t of e){const e=t.target;if(e===this.rootContainer.element)t.isIntersecting&&(this.rootContainerBecameVisible.trigger(),this._intersectionObserver.unobserve(this.rootContainer.element));else if("layoutResultId"in e&&this._api.settings.core.enableLazyLoading){const s=e;t.isIntersecting?s.renderedResultId!==s.layoutResultId?this._resultIdToElementLookup.has(s.layoutResultId)?s.resultState!==qi.RenderRequested&&(s.resultState=qi.RenderRequested,this._api.renderer.renderResult(s.layoutResultId)):e.replaceChildren():s.resultState===qi.Detached&&(e.replaceChildren(...s.renderedResult),s.resultState=qi.RenderDone):s.resultState===qi.RenderDone&&(s.resultState=qi.Detached,s.replaceChildren())}}}createWorkerRenderer(){return new jr(this._api,this._api.settings)}initialize(e,t){let s;this._api=e,s=t instanceof ut?t:ts.jsObjectToSettings(t);const i=this.getDataAttributes();dt.fromJson(s,i),s.notation.notationMode===k.SongBook&&s.setSongBookModeSettings(),e.settings=s,this.setupFontCheckers(s),this._initialTrackIndexes=this.parseTracks(s.core.tracks),this._contents="";const a=e.container;s.core.tex&&(this._contents=a.element.innerHTML,a.element.innerHTML=""),this.createStyleElement(s),this._file=s.core.file}setupFontCheckers(e){this.registerFontChecker(e.display.resources.copyrightFont),this.registerFontChecker(e.display.resources.effectFont),this.registerFontChecker(e.display.resources.fingeringFont),this.registerFontChecker(e.display.resources.graceFont),this.registerFontChecker(e.display.resources.markerFont),this.registerFontChecker(e.display.resources.tablatureFont),this.registerFontChecker(e.display.resources.titleFont),this.registerFontChecker(e.display.resources.wordsFont),this.registerFontChecker(e.display.resources.barNumberFont),this.registerFontChecker(e.display.resources.fretboardNumberFont),this.registerFontChecker(e.display.resources.subTitleFont)}registerFontChecker(e){if(!this._fontCheckers.has(e.families.join(", "))){const t=new Ur(e.families);this._fontCheckers.set(e.families.join(", "),t),t.fontLoaded.on(this.onFontLoaded.bind(this)),t.checkForFontAvailability()}}destroy(){this.rootContainer.element.innerHTML=""}createCanvasElement(){const 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 zr(e)}triggerEvent(e,t,s=null,i){const a=e.element;t=`alphaTab.${t}`;const r=document.createEvent("CustomEvent"),n=i?i.mouseEvent:null;if(r.initCustomEvent(t,!1,!1,s),n&&(r.originalEvent=n),a.dispatchEvent(r),window&&"jQuery"in window){const e=window.jQuery,i=[];i.push(s),n&&i.push(n),e(a).trigger(t,i)}}load(e,t,s){if(e instanceof Cs)return t(e),!0;if(e instanceof ArrayBuffer){const s=new Uint8Array(e);return t(Vr.loadScoreFromBytes(s,this._api.settings)),!0}return e instanceof Uint8Array?(t(Vr.loadScoreFromBytes(e,this._api.settings)),!0):"string"==typeof e&&(Vr.loadScoreAsync(e,t,s,this._api.settings),!0)}loadSoundFont(e,t){return!!this._api.player&&(e instanceof ArrayBuffer?(this._api.player.loadSoundFont(new Uint8Array(e),t),!0):e instanceof Uint8Array?(this._api.player.loadSoundFont(e,t),!0):"string"==typeof e&&(this._api.loadSoundFontFromUrl(e,t),!0))}initialRender(){this._api.renderer.preRender.on((e=>{this._totalResultCount=0,this._resultIdToElementLookup.clear(),this._barToElementLookup.clear()}));const e=()=>{this._api.renderer.width=0|this.rootContainer.width,this._api.renderer.updateSettings(this._api.settings),this._contents?(this._api.tex(this._contents,this._initialTrackIndexes??void 0),this._initialTrackIndexes=null):this._file&&Vr.loadScoreAsync(this._file,(e=>{this._api.renderScore(e,this._initialTrackIndexes??void 0),this._initialTrackIndexes=null}),(e=>{this._api.onError(e)}),this._api.settings)};this.rootContainer.isVisible?e():this.rootContainerBecameVisible.on(e)}createStyleElement(e){const t=this._api.container.element.ownerDocument;cc.createStyleElement(t,e.core.fontDirectory)}parseTracks(e){if(!e)return[];const 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){const s=e.length,i=e;for(let e=0;e<s;e++){const s=i[e];let a=0;a="number"==typeof s?s:"index"in s?s.index:Number.parseInt(s.toString()),(a>=0||-1===a)&&t.push(a)}}else"index"in e&&t.push(e.index);return t}getDataAttributes(){const e=new Map,t=this._api.container.element;if(t.dataset)for(const s of Object.keys(t.dataset)){let i=t.dataset[s];try{const e=i;i=JSON.parse(e)}catch(e){""===i&&(i=null)}e.set(s,i)}else for(let s=0;s<t.attributes.length;s++){const i=t.attributes.item(s),a=i.nodeName;if(a.startsWith("data-")){const t=a.substr(5).split("-");let s=t[0];for(let e=1;e<t.length;e++)s+=t[e].substr(0,1).toUpperCase()+t[e].substr(1);let r=i.nodeValue;try{r=JSON.parse(r)}catch(e){""===r&&(r=null)}e.set(s,r)}}return e}beginUpdateRenderResults(e){if(!this._resultIdToElementLookup.has(e.id))return;const t=this._resultIdToElementLookup.get(e.id),s=e.renderResult;"string"==typeof s?t.innerHTML=s:"nodeType"in s&&t.replaceChildren(s),t.resultState=qi.RenderDone,t.renderedResultId=e.id,t.renderedResult=Array.from(t.children)}beginAppendRenderResults(e){const t=this._api.canvasElement.element;if(e){let s;this._totalResultCount<t.childElementCount?s=t.childNodes.item(this._totalResultCount):(s=document.createElement("div"),t.appendChild(s)),s.style.zIndex="1",s.style.position="absolute",s.style.left=`${e.x}px`,s.style.top=`${e.y}px`,s.style.width=`${e.width}px`,s.style.height=`${e.height}px`,s.style.display="inline-block",s.layoutResultId=e.id,s.resultState=qi.LayoutDone,s.renderedResultId=void 0,s.renderedResult=void 0,this._resultIdToElementLookup.set(e.id,s);for(let t=e.firstMasterBarIndex;t<=e.lastMasterBarIndex;t++)t>=0&&this._barToElementLookup.set(t,s);this._api.settings.core.enableLazyLoading&&(this._intersectionObserver.unobserve(s),this._intersectionObserver.observe(s)),this._totalResultCount++}else for(;t.childElementCount>this._totalResultCount;)this._api.settings.core.enableLazyLoading&&this._intersectionObserver.unobserve(t.lastChild),t.removeChild(t.lastElementChild)}createWorkerPlayer(){let e=null;const t="ScriptProcessorNode"in window;return window.isSecureContext&&"AudioWorkletNode"in window&&this._api.settings.player.outputMode===Y.WebAudioAudioWorklets?(wt.debug("Player","Will use webworkers for synthesizing and web audio api with worklets for playback"),e=new Kr(new Zr(this._api.settings),this._api.settings)):t&&(wt.debug("Player","Will use webworkers for synthesizing and web audio api with ScriptProcessor for playback"),e=new Kr(new $r,this._api.settings)),e?e.ready.on((()=>{this._api.settings.player.soundFont&&this._api.loadSoundFontFromUrl(this._api.settings.player.soundFont,!1)})):wt.error("Player","Player requires webworkers and web audio api, browser unsupported",null),e}beginInvoke(e){window.requestAnimationFrame((()=>{e()}))}highlightElements(e,t){const s=this._barToElementLookup.get(t);if(s){const t=s.getElementsByClassName(e);for(let e=0;e<t.length;e++)t.item(e).classList.add("at-highlight"),this._highlightedElements.push(t.item(e))}}removeHighlights(){const e=this._highlightedElements;if(e){for(const t of e)t.classList.remove("at-highlight");this._highlightedElements=[]}}destroyCursors(){const e=this._api.container.element,t=e.querySelector(".at-cursors");e.removeChild(t)}createCursors(){const e=this._api.container.element,t=document.createElement("div");t.classList.add("at-cursors");const s=document.createElement("div");s.classList.add("at-selection");const i=this.createScalingElement(),a=this.createScalingElement(),r=i.element;r.classList.add("at-cursor-bar");const n=a.element;return n.classList.add("at-cursor-beat"),e.style.position="relative",e.style.textAlign="left",t.style.position="absolute",t.style.zIndex="1000",t.style.display="inline",t.style.pointerEvents="none",s.style.position="absolute",r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.willChange="transform",i.width=1,i.height=1,i.setBounds(0,0,1,1),n.style.position="absolute",n.style.transition="all 0s linear",n.style.left="0",n.style.top="0",n.style.willChange="transform",a.width=3,a.height=1,a.setBounds(0,0,1,1),e.insertBefore(t,e.firstChild),t.appendChild(s),t.appendChild(r),t.appendChild(n),new ms(new zr(t),i,a,new zr(s))}getOffset(e,t){const s=t.element,i=s.getBoundingClientRect();let a=i.top+s.ownerDocument.defaultView.pageYOffset,r=i.left+s.ownerDocument.defaultView.pageXOffset;if(e){const t=e.element,s=t.nodeName.toLowerCase();if("html"!==s&&"body"!==s){const s=this.getOffset(null,e);a=a+t.scrollTop-s.y,r=r+t.scrollLeft-s.x}}const n=new Hs;return n.x=r,n.y=a,n.w=i.width,n.h=i.height,n}getScrollContainer(){if(this._scrollContainer)return this._scrollContainer;let e="string"==typeof this._api.settings.player.scrollElement?document.querySelector(this._api.settings.player.scrollElement):this._api.settings.player.scrollElement;const 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 zr(e),this._scrollContainer}createSelectionElement(){return this.createScalingElement()}createScalingElement(){const e=document.createElement("div");e.style.position="absolute";const t=new en(e,100,100);return t.width=1,t.height=1,t.setBounds(0,0,1,1),t}scrollToY(e,t,s){this.internalScrollToY(e.element,t,s)}scrollToX(e,t,s){this.internalScrollToX(e.element,t,s)}internalScrollToY(e,t,s){if(this._api.settings.player.nativeBrowserSmoothScroll)e.scrollTo({top:t,behavior:"smooth"});else{const i=e.scrollTop,a=t-i;let r=0;const n=t=>{0===r&&(r=t);const o=t-r,h=Math.min(o/s,1);e.scrollTop=i+a*h|0,o<s&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}internalScrollToX(e,t,s){if(this._api.settings.player.nativeBrowserSmoothScroll)e.scrollTo({left:t,behavior:"smooth"});else{const i=e.scrollLeft,a=t-i;let r=0;const n=t=>{0===r&&(r=t);const o=t-r,h=Math.min(o/s,1);e.scrollLeft=i+a*h|0,o<s&&window.requestAnimationFrame(n)};window.requestAnimationFrame(n)}}}class sn extends Hr{constructor(e,t){super(new tn(e),t),this.soundFontLoad=new _i}tex(e,t){const s=this.uiFacade;super.tex(e,s.parseTracks(t))}print(t,s=null){const i=window.open("","","width=0,height=0"),a=i.document.createElement("div");t?a.style.width=t:this.settings.display.layoutMode===e.Horizontal?a.style.width="297mm":a.style.width="210mm",i.document.write("\n <!DOCTYPE html>\n <html>\n <head>\n <style>\n .at-surface {\n width: auto !important;\n height: auto !important;\n }\n .at-surface > div {\n position: relative!important;\n left: auto !important;\n top: auto !important;\n break-inside: avoid;\n }\n </style>\n </head>\n <body></body>\n </html>\n ");const r=this.score;r&&(r.artist&&r.title?i.document.title=`${r.title} - ${r.artist}`:r.title&&(i.document.title=`${r.title}`)),i.document.body.appendChild(a);const n=void 0!==window.screenLeft?window.screenLeft:window.left,o=void 0!==window.screenTop?window.screenTop:window.top,h="innerWidth"in window?window.innerWidth:"clientWidth"in document.documentElement?document.documentElement.clientWidth:window.screen.width,l="innerHeight"in window?window.innerHeight:"clientHeight"in document.documentElement?document.documentElement.clientHeight:window.screen.height,c=a.offsetWidth+50,d=window.innerHeight,u=(h/2|0)-(c/2|0)+n,p=(l/2|0)-(d/2|0)+o;i.resizeTo(c,d),i.moveTo(u,p),i.focus();const g=ts.jsObjectToSettings(ts.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,dt.fromJson(g,s);const m=new sn(a,g);i.onunload=()=>{m.destroy()},m.renderer.postRenderFinished.on((()=>{i.print()})),m.renderTracks(this.tracks)}downloadMidi(e=z.SingleTrackMultiChannel){if(!this.score)return;const t=new Ae;t.format=e;const s=new mr(t,!0);new vr(this.score,this.settings,s).generate();const i=t.toBinary(),a=this.score.title?`${this.score.title}.mid`:"File.mid",r=document.createElement("a");r.download=a;const n=new Blob([i],{type:"audio/midi"}),o=URL.createObjectURL(n);r.href=o,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}changeTrackMute(e,t){const s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackMute(s,t)}changeTrackSolo(e,t){const s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackSolo(s,t)}changeTrackVolume(e,t){const s=this.trackIndexesToTracks(this.uiFacade.parseTracks(e));super.changeTrackVolume(s,t)}trackIndexesToTracks(e){if(!this.score)return[];const t=[];if(1===e.length&&-1===e[0])for(const e of this.score.tracks)t.push(e);else for(const s of e)s>=0&&s<this.score.tracks.length&&t.push(this.score.tracks[s]);return t}loadSoundFontFromUrl(e,t){this.player&&this.player.loadSoundFontFromUrl(e,t,(e=>{this.soundFontLoad.trigger(e),this.uiFacade.triggerEvent(this.container,"soundFontLoad",e)}))}}class an{constructor(){this._initListeners=[]}exec(e,t,s){if("string"!=typeof t&&(s=[t],t="init"),95===t.charCodeAt(0)||"exec"===t)return null;const i=new jQuery(e),a=i.data("alphaTab");if("destroy"===t&&!a)return null;if("init"!==t&&!a)throw new Error("alphaTab not initialized");const r=this[t];if(r){const e=[i,a].concat(s);return r.apply(this,e)}return wt.error("Api",`Method '${t}' does not exist on jQuery.alphaTab`),null}init(e,t,s){if(!t){t=new sn(e[0],s),e.data("alphaTab",t);for(const i of this._initListeners)i(e,t,s)}}destroy(e,t){e.removeData("alphaTab"),t.destroy()}print(e,t,s,i){t.print(s,i)}load(e,t,s,i){return t.load(s,i)}render(e,t){t.render()}renderScore(e,t,s,i){t.renderScore(s,i)}renderTracks(e,t,s){t.renderTracks(s)}invalidate(e,t){t.render()}tex(e,t,s,i){t.tex(s,i)}muteTrack(e,t,s,i){t.changeTrackMute(s,i)}soloTrack(e,t,s,i){t.changeTrackSolo(s,i)}trackVolume(e,t,s,i){t.changeTrackVolume(s,i)}loadSoundFont(e,t,s,i){t.loadSoundFont(s,i)}resetSoundFonts(e,t){t.resetSoundFonts()}pause(e,t){t.pause()}play(e,t){return t.play()}playPause(e,t){t.playPause()}stop(e,t){t.stop()}api(e,t){return t}player(e,t){return t.player}isReadyForPlayback(e,t){return t.isReadyForPlayback}playerState(e,t){return t.playerState}masterVolume(e,t,s){return"number"==typeof s&&(t.masterVolume=s),t.masterVolume}metronomeVolume(e,t,s){return"number"==typeof s&&(t.metronomeVolume=s),t.metronomeVolume}countInVolume(e,t,s){return"number"==typeof s&&(t.countInVolume=s),t.countInVolume}midiEventsPlayedFilter(e,t,s){return Array.isArray(s)&&(t.midiEventsPlayedFilter=s),t.midiEventsPlayedFilter}playbackSpeed(e,t,s){return"number"==typeof s&&(t.playbackSpeed=s),t.playbackSpeed}tickPosition(e,t,s){return"number"==typeof s&&(t.tickPosition=s),t.tickPosition}timePosition(e,t,s){return"number"==typeof s&&(t.timePosition=s),t.timePosition}loop(e,t,s){return"boolean"==typeof s&&(t.isLooping=s),t.isLooping}renderer(e,t){return t.renderer}score(e,t){return t.score}settings(e,t){return t.settings}tracks(e,t){return t.tracks}_oninit(e){this._initListeners.push(e)}static restore(e){new jQuery(e).empty().removeData("alphaTab")}}class rn{constructor(){this.isInsideBracket=!0,this.isRelevantForBoundsLookup=!0,this.hideOnMultiTrack=!1,this.hideOnPercussionTrack=!1}canCreate(e,t){return!this.hideOnPercussionTrack||!t.isPercussion}}!function(e){e[e.PreNotes=0]="PreNotes",e[e.OnNotes=1]="OnNotes",e[e.MiddleNotes=2]="MiddleNotes",e[e.Stem=3]="Stem",e[e.PostNotes=4]="PostNotes",e[e.EndBeat=5]="EndBeat"}(Ki||(Ki={}));class nn extends Fr{constructor(){super(...arguments),this.glyphs=null}get isEmpty(){return!this.glyphs||0===this.glyphs.length}doLayout(){if(!this.glyphs||0===this.glyphs.length)return void(this.width=0);let e=0;for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t];s.renderer=this.renderer,s.doLayout(),e=Math.max(e,s.width)}this.width=e}addGlyph(e){this.glyphs||(this.glyphs=[]),this.renderer&&(e.renderer=this.renderer),this.glyphs.push(e)}paint(e,t,s){const i=this.glyphs;if(i&&0!==i.length)for(const a of i)a.paint(e+this.x,t+this.y,s)}}class on extends nn{constructor(){super(0,0),this.glyphs=[]}doLayout(){}addGlyph(e){e.x=this.width,e.renderer=this.renderer,e.doLayout(),this.width=e.x+e.width,super.addGlyph(e)}}class hn{static score(e,t,s,i=!1){if(!s.style&&!i)return;const a=hn.scoreDefaultColor(e.settings.display.resources,t);return new ln(e,t,s.style,a)}static scoreColor(e,t,s){const i=hn.scoreDefaultColor(e,t);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static scoreDefaultColor(e,t){return e.mainGlyphColor}static bar(e,t,s,i=!1){if(!s.style&&!i)return;let a=e.settings.display.resources.mainGlyphColor;switch(t){case c.StandardNotationRepeats:case c.GuitarTabsRepeats:case c.SlashRepeats:case c.NumberedRepeats:case c.StandardNotationClef:case c.GuitarTabsClef:case c.StandardNotationKeySignature:case c.NumberedKeySignature:case c.StandardNotationTimeSignature:case c.GuitarTabsTimeSignature:case c.SlashTimeSignature:case c.NumberedTimeSignature:break;case c.StandardNotationBarLines:case c.GuitarTabsBarLines:case c.SlashBarLines:case c.NumberedBarLines:a=e.settings.display.resources.barSeparatorColor;break;case c.StandardNotationBarNumber:case c.SlashBarNumber:case c.NumberedBarNumber:case c.GuitarTabsBarNumber:a=e.settings.display.resources.barNumberColor;break;case c.StandardNotationStaffLine:case c.GuitarTabsStaffLine:case c.SlashStaffLine:case c.NumberedStaffLine:a=e.settings.display.resources.staffLineColor}return new ln(e,t,s.style,a)}static voice(e,t,s,i=!1){if(!s.style&&!i)return;const a=0===s.index?e.settings.display.resources.mainGlyphColor:e.settings.display.resources.secondaryGlyphColor;return new ln(e,t,s.style,a)}static trackColor(e,t,s){const i=hn.trackDefaultColor(e,t);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static trackDefaultColor(e,t){let s=e.mainGlyphColor;switch(t){case Xt.TrackName:case Xt.SystemSeparator:case Xt.StringTuning:break;case Xt.BracesAndBrackets:s=e.barSeparatorColor}return s}static track(e,t,s,i=!1){if(!s.style&&!i)return;const a=hn.trackDefaultColor(e.settings.display.resources,t);return new ln(e,t,s.style,a)}static beatColor(e,t,s){const i=hn.beatDefaultColor(e,t,s);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static beatDefaultColor(e,t,s){return 0===s.voice.index?e.mainGlyphColor:e.secondaryGlyphColor}static beat(e,t,s,i=!1){if(!s.style&&!i)return;const a=hn.beatDefaultColor(e.settings.display.resources,t,s);return new ln(e,t,s.style,a)}static noteColor(e,t,s){const i=hn.noteDefaultColor(e,t,s);if(s.style&&s.style.colors.has(t))return s.style.colors.get(t)??i}static noteDefaultColor(e,t,s){return 0===s.beat.voice.index?e.mainGlyphColor:e.secondaryGlyphColor}static note(e,t,s,i=!1){if(!s.style&&!i)return;const a=0===s.beat.voice.index?e.settings.display.resources.mainGlyphColor:e.settings.display.resources.secondaryGlyphColor;return new ln(e,t,s.style,a)}}class ln{constructor(e,t,s,i){this._canvas=e,s&&s.colors.has(t)?(this._previousColor=e.color,e.color=s.colors.get(t)??i):s||(this._previousColor=e.color,e.color=i)}[Symbol.dispose](){this._previousColor&&(this._canvas.color=this._previousColor)}}class cn extends nn{constructor(e,t,s){super(e,t),this.voice=s,this.beatGlyphs=[],this.tupletGroups=[]}scaleToWidth(e){const t=this.renderer.layoutingInfo.spaceToForce(e);this.scaleToForce(t)}scaleToForce(e){this.width=this.renderer.layoutingInfo.calculateVoiceWidth(e);const t=this.renderer.layoutingInfo.buildOnTimePositions(e),s=this.beatGlyphs;for(let e=0,i=s.length;e<i;e++){const a=s[e];if(a.beat.graceType===R.None)a.x=t.get(a.beat.absoluteDisplayStart)-a.onTimeX;else{const i=a.beat.graceGroup.beats[0].absoluteDisplayStart,r=a.beat.graceGroup.id;if(a.beat.graceGroup.isComplete&&t.has(i)){a.x=t.get(i)-a.onTimeX;const e=this.renderer.layoutingInfo.allGraceRods.get(r),s=a.beat.graceGroup.beats[a.beat.graceGroup.beats.length-1].nextBeat,n=s?this.renderer.layoutingInfo.getPreBeatSize(s)+Ir.GraceBeatPadding:0;a.x-=n,a.x-=e[a.beat.graceIndex].postSpringWidth,a.x+=e[a.beat.graceIndex].graceBeatWidth;const o=e[a.beat.graceGroup.beats.length-1];a.x-=o.graceBeatWidth}else{const t=this.renderer.layoutingInfo.incompleteGraceRods.get(r),i=t[a.beat.graceIndex].postSpringWidth-t[a.beat.graceIndex].preSpringWidth;e>0?0===a.beat.graceIndex?a.x=s[e-1].x+s[e-1].width:a.x=s[e-1].x+t[a.beat.graceIndex-1].postSpringWidth-t[a.beat.graceIndex-1].preSpringWidth-i:a.x=-i}}if(e>0){const t=a.x-s[e-1].x;s[e-1].scaleToWidth(t)}if(e===i-1){const e=this.width-s[s.length-1].x;a.scaleToWidth(e)}}}registerLayoutingInfo(e){const t=this.beatGlyphs;for(const s of t)s.registerLayoutingInfo(e)}applyLayoutingInfo(e){const t=this.beatGlyphs;for(const s of t)s.applyLayoutingInfo(e);this.scaleToForce(Math.max(this.renderer.settings.display.stretchForce,e.minStretchForce))}addGlyph(e){const t=e;e.x=0===this.beatGlyphs.length?0:this.beatGlyphs[this.beatGlyphs.length-1].x+this.beatGlyphs[this.beatGlyphs.length-1].width,e.renderer=this.renderer,e.doLayout(),this.beatGlyphs.push(t),this.width=e.x+e.width,t.beat.hasTuplet&&t.beat.tupletGroup.beats[0].id===t.beat.id&&this.tupletGroups.push(t.beat.tupletGroup)}doLayout(){}paint(e,t,s){const i=hn.voice(s,re.Glyphs,this.voice,!0);try{for(let i=0,a=this.beatGlyphs.length;i<a;i++)this.beatGlyphs[i].paint(e+this.x,t+this.y,s)}finally{i?.[Symbol.dispose]?.()}}}cn.KeySizeBeat="Beat";class dn{constructor(){this.staffId="",this.up=0,this.down=0}}class un{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 pn{get isRestBeamHelper(){return 1===this.beats.length&&this.beats[0].isRest}hasLine(e,t){return e&&this.beatHasLine(t)||!e&&1===this.beats.length&&this.beatHasLine(t)}beatHasLine(e){return e.duration>D.Whole}hasFlag(e,t){return e&&this.beatHasFlag(t)||!e&&1===this.beats.length&&this.beatHasFlag(this.beats[0])}beatHasFlag(e){return!e.deadSlapped&&!e.isRest&&(e.duration>D.Quarter||e.graceType!==R.None)}constructor(e,t){this._beatLineXPositions=new Map,this._firstNonRestBeat=null,this._lastNonRestBeat=null,this.voice=null,this.beats=[],this.shortestDuration=D.QuadrupleWhole,this.hasTuplet=!1,this.slashBeats=[],this._firstBeatLowestNoteCompareValue=-1,this._firstBeatHighestNoteCompareValue=-1,this._lastBeatLowestNoteCompareValue=-1,this._lastBeatHighestNoteCompareValue=-1,this.lowestNoteInHelper=null,this._lowestNoteCompareValueInHelper=-1,this.highestNoteInHelper=null,this._highestNoteCompareValueInHelper=-1,this.invertBeamDirection=!1,this.preferredBeamDirection=null,this.isGrace=!1,this.minRestLine=null,this.beatOfMinRestLine=null,this.maxRestLine=null,this.beatOfMaxRestLine=null,this.direction=se.Up,this.drawingInfos=new Map,this._staff=e,this._renderer=t,this.beats=[]}getBeatLineX(e,t){return t=t??this.direction,this.hasBeatLineX(e)?t===se.Up?this._beatLineXPositions.get(e.index).up:this._beatLineXPositions.get(e.index).down:0}hasBeatLineX(e){return this._beatLineXPositions.has(e.index)}registerBeatLineX(e,t,s,i){const a=this.getOrCreateBeatPositions(t);a.staffId=e,a.up=s,a.down=i;for(const e of this.drawingInfos.values())e.startBeat===t?e.startX=this.getBeatLineX(t):e.endBeat===t&&(e.endX=this.getBeatLineX(t))}getOrCreateBeatPositions(e){return this._beatLineXPositions.has(e.index)||this._beatLineXPositions.set(e.index,new dn),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(se.Down):(this.voice.bar.isMultiVoice||this.beats[0].graceType!==R.None)&&(e=this.invert(se.Up)):e=se.Up,this.highestNoteInHelper&&this.lowestNoteInHelper){const t=this._renderer.getNoteY(this.highestNoteInHelper,Qi.Center),s=this._renderer.getNoteY(this.lowestNoteInHelper,Qi.Center);if(null===e){const i=(t+s)/2;e=this.invert(this._renderer.middleYPosition<i?se.Up:se.Down)}this._renderer.completeBeamingHelper(this)}else e=this.invert(se.Up),this._renderer.completeBeamingHelper(this);return e}static computeLineHeightsForRest(e){switch(e){case D.QuadrupleWhole:case D.DoubleWhole:return[2,2];case D.Whole:return[0,1];case D.Half:return[1,0];case D.Quarter:return[3,3];case D.Eighth:return[2,2];case D.Sixteenth:return[2,4];case D.ThirtySecond:return[4,4];case D.SixtyFourth:return[4,6];case D.OneHundredTwentyEighth:return[6,6];case D.TwoHundredFiftySixth:return[6,8]}return[0,0]}applyRest(e,t){if(this._lastNonRestBeat&&e.index>=this._lastNonRestBeat.index||this._firstNonRestBeat&&e.index<=this._firstNonRestBeat.index)return;let s=t,i=t;const a=pn.computeLineHeightsForRest(e.duration);s-=a[0],i+=a[1];const r=this.minRestLine,n=this.maxRestLine;(null===r||r>s)&&(this.minRestLine=s,this.beatOfMinRestLine=e),(null===n||n<i)&&(this.maxRestLine=i,this.beatOfMaxRestLine=e)}invert(e){return this.invertBeamDirection?e===se.Down?se.Up:se.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 cs.Auto:case cs.ForceSplitOnSecondaryToNext:t=pn.canJoin(this.beats[this.beats.length-1],e);break;case cs.ForceSplitToNext:t=!1;break;case cs.ForceMergeWithNext:t=!0}return t&&(null==this.preferredBeamDirection&&null!==e.preferredBeamDirection&&(this.preferredBeamDirection=e.preferredBeamDirection),e.hasTuplet&&(this.hasTuplet=!0),e.graceType!==R.None&&(this.isGrace=!0),e.isRest?0===this.beats.length&&this.beats.push(e):(this.isRestBeamHelper&&(this.beats=[]),this.beats.push(e),this.checkNote(e.minNote),this.checkNote(e.maxNote),this.shortestDuration<e.duration&&(this.shortestDuration=e.duration),this._firstNonRestBeat||(this._firstNonRestBeat=e),this._lastNonRestBeat=e),e.slashed&&this.slashBeats.push(e)),t}checkNote(e){if(!e)return;let t,s;this.voice&&e.isPercussion?(t=-Ci.getPercussionLine(this.voice.bar,Ci.getNoteValue(e)),s=t):(t=Ci.getNoteValue(e),s=t,e.harmonicType!==H.None&&e.harmonicType!==H.Natural&&(s=e.realValue-this._staff.displayTranspositionPitch)),1===this.beats.length&&this.beats[0]===e.beat&&((-1===this._firstBeatLowestNoteCompareValue||t<this._firstBeatLowestNoteCompareValue)&&(this._firstBeatLowestNoteCompareValue=t),(-1===this._firstBeatHighestNoteCompareValue||s>this._firstBeatHighestNoteCompareValue)&&(this._firstBeatHighestNoteCompareValue=s)),(-1===this._lastBeatLowestNoteCompareValue||t<this._lastBeatLowestNoteCompareValue)&&(this._lastBeatLowestNoteCompareValue=t),(-1===this._lastBeatHighestNoteCompareValue||s>this._lastBeatHighestNoteCompareValue)&&(this._lastBeatHighestNoteCompareValue=s),(!this.lowestNoteInHelper||t<this._lowestNoteCompareValueInHelper)&&(this.lowestNoteInHelper=e,this._lowestNoteCompareValueInHelper=t),(!this.highestNoteInHelper||s>this._highestNoteCompareValueInHelper)&&(this.highestNoteInHelper=e,this._highestNoteCompareValueInHelper=s)}static canJoin(e,t){if(!e||!t||e.graceType!==t.graceType||e.graceType===R.BendGrace||t.graceType===R.BendGrace||e.deadSlapped||t.deadSlapped)return!1;if(e.graceType!==R.None&&t.graceType!==R.None)return!0;const s=e.voice.bar;if(s!==t.voice.bar)return!1;const i=e.playbackStart,a=t.playbackStart;if(!pn.canJoinDuration(e.duration)||!pn.canJoinDuration(t.duration))return i===a;if(e.tupletGroup!==t.tupletGroup)return!1;if(e.hasTuplet&&t.hasTuplet&&e.tupletGroup===t.tupletGroup&&e.tupletGroup.isFull)return!0;let r=rs.QuarterTime;if(8===s.masterBar.timeSignatureDenominator)s.masterBar.timeSignatureNumerator%3==0&&(r+=rs.QuarterTime/2|0);return((r+i)/r|0)===((r+a)/r|0)}static canJoinDuration(e){switch(e){case D.Whole:case D.Half:case D.Quarter:return!1;default:return!0}}static isFullBarJoin(e,t,s){return Be.getIndex(e.duration)-2-s>0&&Be.getIndex(t.duration)-2-s>0}get beatOfLowestNote(){return this.lowestNoteInHelper.beat}get beatOfHighestNote(){return this.highestNoteInHelper.beat}isPositionFrom(e,t){return!this._beatLineXPositions.has(t.index)||(this._beatLineXPositions.get(t.index).staffId===e||!this._beatLineXPositions.get(t.index).staffId)}}class gn{constructor(e,t){this.topY=0,this.bottomY=0,this.topY=e,this.bottomY=t}}class mn{constructor(e){this.topY=-1e3,this.bottomY=-1e3,this.slots=[],this.beat=e}addSlot(e,t){if(this.slots.push(new gn(e,t)),-1e3===this.topY)this.topY=e,this.bottomY=t;else{const s=Math.min(e,t),i=Math.max(e,t);s<this.topY&&(this.topY=s),i>this.bottomY&&(this.bottomY=i)}}}class fn{constructor(){this.reservedLayoutAreasByDisplayTime=new Map,this.restDurationsByDisplayTime=new Map}getBeatMinMaxY(){let e=-1e3,t=-1e3;for(const s of this.reservedLayoutAreasByDisplayTime.values())-1e3===e?(e=s.topY,t=s.bottomY):(e>s.topY&&(e=s.topY),t<s.bottomY&&(t=s.bottomY));return-1e3===e?[0,0]:[e,t]}reserveBeatSlot(e,t,s){t!==s&&(this.reservedLayoutAreasByDisplayTime.has(e.displayStart)||this.reservedLayoutAreasByDisplayTime.set(e.displayStart,new mn(e)),this.reservedLayoutAreasByDisplayTime.get(e.displayStart).addSlot(t,s),e.isRest&&this.registerRest(e))}registerRest(e){this.restDurationsByDisplayTime.has(e.displayStart)||this.restDurationsByDisplayTime.set(e.displayStart,new Map),this.restDurationsByDisplayTime.get(e.displayStart).has(e.playbackDuration)||this.restDurationsByDisplayTime.get(e.displayStart).set(e.playbackDuration,e.id)}applyRestCollisionOffset(e,t,s){if(e.voice.index>0&&this.reservedLayoutAreasByDisplayTime.has(e.playbackStart)){const i=pn.computeLineHeightsForRest(e.duration).map((e=>e*s)),a=t-i[0],r=t+i[1];let n=a;const o=this.reservedLayoutAreasByDisplayTime.get(e.playbackStart);let h=!1;for(const e of o.slots)if(a>=e.topY&&a<=e.bottomY||r>=e.topY&&r<=e.bottomY){h=!0;break}if(h){n=1===e.voice.index?o.topY-i[1]-i[0]:o.bottomY;const t=n+i[0]+i[1],r=2*s,h=Math.ceil(Math.abs(n-a)/r);return o.addSlot(n,t),n<a?h*-r:h*r}}return 0}}class yn{constructor(e){this.beamHelpers=[],this.beamHelperLookup=[],this.preferredBeamDirection=null,this._renderer=e,this.collisionHelper=new fn}initialize(){const e=this._renderer,t=this._renderer.bar;let s=null,i=null;for(let a=0,r=t.voices.length;a<r;a++){const r=t.voices[a];this.beamHelpers.push([]),this.beamHelperLookup.push(new Map);for(let a=0,n=r.beats.length;a<n;a++){const n=r.beats[a];let o;n.graceType!==R.None?o=i:(o=s,i=null),o&&o.checkBeat(n)||(o&&o.finish(),o=new pn(t.staff,e),o.preferredBeamDirection=this.preferredBeamDirection,o.checkBeat(n),n.graceType!==R.None?i=o:s=o,this.beamHelpers[r.index].push(o)),this.beamHelperLookup[r.index].set(n.index,o)}s&&s.finish(),i&&i.finish(),s=null,i=null}}getBeamingHelperForBeat(e){return this.beamHelperLookup[e.voice.index].get(e.index)}}class bn extends Cr{constructor(e,t,s){super(e,t),this._textRow=0,this._fretRow=0,this._firstFretSpacing=0,this._chord=s}doLayout(){super.doLayout();const e=this.renderer.resources;this._textRow=1.5*e.effectFont.size,this._fretRow=1.5*e.effectFont.size,this._chord.firstFret>1?this._firstFretSpacing=bn.FretSpacing:this._firstFretSpacing=0,this.height=this._textRow+this._fretRow+bn.Frets*bn.FretSpacing+2*bn.Padding[1],this.width=this._firstFretSpacing+(this._chord.strings.length-1)*bn.StringSpacing+2*bn.Padding[0]}paint(e,t,s){e+=this.x+bn.Padding[0]+this._firstFretSpacing,t+=this.y;const i=bn.StringSpacing,a=bn.FretSpacing,r=this.renderer.resources,n=bn.CircleRadius,o=this.width-2*bn.Padding[0]-this._firstFretSpacing,h=s.textAlign,l=s.textBaseline;s.font=r.effectFont,s.textAlign=W.Center,s.textBaseline=V.Top,this._chord.showName&&s.fillText(this._chord.name,e+o/2,t+r.effectFont.size/2),t+=this._textRow,s.font=r.fretboardNumberFont,s.textBaseline=V.Middle;for(let a=0;a<this._chord.strings.length;a++){const r=e+a*i,n=t+this._fretRow/2;let o=this._chord.strings[this._chord.strings.length-a-1];o<0?s.fillMusicFontSymbol(r,n,1,G.FretboardX,!0):0===o?s.fillMusicFontSymbol(r,n,1,G.FretboardO,!0):(o-=this._chord.firstFret-1,s.fillText(o.toString(),r,n))}t+=this._fretRow;for(let r=0;r<this._chord.strings.length;r++){const n=e+r*i;s.fillRect(n,t,1,a*bn.Frets+1)}this._chord.firstFret>1&&(s.textAlign=W.Left,s.fillText(this._chord.firstFret.toString(),e-this._firstFretSpacing,t+a/2)),s.fillRect(e,t-1,o,2);for(let i=0;i<=bn.Frets;i++){const r=t+i*a;s.fillRect(e,r,o,1)}const c=new Map;for(const e of this._chord.barreFrets){const t=[-1,-1];c.set(e-this._chord.firstFret,t)}for(let r=0;r<this._chord.strings.length;r++){let o=this._chord.strings[r];if(o>0){if(o-=this._chord.firstFret,c.has(o)){const e=c.get(o);(-1===e[0]||r<e[0])&&(e[0]=r),(-1===e[1]||r>e[1])&&(e[1]=r)}const h=t+o*a+a/2+.5,l=e+(this._chord.strings.length-r-1)*i;s.fillCircle(l,h,n)}}for(const[r,o]of c){const h=t+r*a+a/2+.5,l=e+(this._chord.strings.length-o[1]-1)*i,c=e+(this._chord.strings.length-o[0]-1)*i;s.fillRect(l,h-n,c-l,2*n)}s.textAlign=h,s.textBaseline=l}}bn.Padding=[5,2],bn.Frets=5,bn.CircleRadius=2.5,bn.StringSpacing=10,bn.FretSpacing=12;class Sn extends nn{constructor(e,t,s=W.Center){super(e,t),this._glyphWidth=0,this.glyphs=[],this._align=s}doLayout(){let e=0;switch(this._align){case W.Left:e=0;break;case W.Center:e=(this.width-this._glyphWidth)/2;break;case W.Right:e=this.width-this._glyphWidth}for(const 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 _n extends nn{constructor(e,t,s=W.Center){super(e,t),this._rows=[],this.height=0,this.glyphs=[],this._align=s}doLayout(){let e=0,t=0;const s=_n.Padding;this._rows=[];let i=new Sn(e,t,this._align);i.width=this.width;for(const a of this.glyphs)e+a.width<this.width?(i.addGlyphToRow(a),e+=a.width):(i.isEmpty||(i.doLayout(),this._rows.push(i),t+=i.height+s),e=0,i=new Sn(e,t,this._align),i.width=this.width,i.addGlyphToRow(a),e+=a.width);i.isEmpty||(i.doLayout(),this._rows.push(i),t+=i.height+s),this.height=t}paint(e,t,s){for(const i of this._rows)i.paint(e+this.x,t+this.y,s)}}_n.Padding=3;class wn extends _n{addChord(e){if(e.strings.length>0){const t=new bn(0,0,e);t.renderer=this.renderer,t.doLayout(),this.glyphs.push(t)}}paint(e,t,s){if(this.glyphs.length>0){const i=hn.score(s,ws.ChordDiagramList,this.renderer.scoreRenderer.score);try{super.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}}}class Bn extends Cr{constructor(e,t,s,i,a=W.Left,r=null,n){super(e,t),this._lineHeights=null,this._lines=s.split("\n"),this.font=i,this.textAlign=a,this.textBaseline=r,this.colorOverride=n}doLayout(){super.doLayout(),this._lineHeights=[];const e=this.renderer.scoreRenderer.canvas;for(const t of this._lines){e.font=this.font;const s=e.measureText(t),i=s.height;this._lineHeights.push(i),this.height+=i,this.width=Math.max(this.width,s.width)}}paint(e,t,s){const i=s.color;s.color=this.colorOverride??i,s.font=this.font;const a=s.textAlign,r=s.textBaseline;s.textAlign=this.textAlign,null!==this.textBaseline&&(s.textBaseline=this.textBaseline);let n=t+this.y;for(let t=0;t<this._lines.length;t++)s.fillText(this._lines[t],e+this.x,n),n+=this._lineHeights[t];s.textAlign=a,s.textBaseline=r,s.color=i}}class kn{get staveId(){return this._factory.staffId}get contentTop(){return this.y+this.staveTop+this.topSpacing+this.topOverflow}get contentBottom(){return this.y+this.topSpacing+this.topOverflow+this.staveBottom}constructor(e,t,s){this._sharedLayoutData=new Map,this.barRenderers=[],this.x=0,this.y=0,this.height=0,this.index=0,this.staffIndex=0,this.isFirstInSystem=!1,this.trackIndex=0,this.staveTop=0,this.topSpacing=0,this.bottomSpacing=0,this.staveBottom=0,this._factory=s,this.trackIndex=e,this.modelStaff=t}getSharedLayoutData(e,t){return this._sharedLayoutData.has(e)?this._sharedLayoutData.get(e):t}setSharedLayoutData(e,t){this._sharedLayoutData.set(e,t)}get isInsideBracket(){return this._factory.isInsideBracket}get isRelevantForBoundsLookup(){return this._factory.isRelevantForBoundsLookup}registerStaffTop(e){this.staveTop=e}registerStaffBottom(e){this.staveBottom=e}addBarRenderer(e){e.staff=this,e.index=this.barRenderers.length,e.reLayout(),this.barRenderers.push(e),this.system.layout.registerBarRenderer(this.staveId,e)}addBar(e,t,s){const i=this._factory.create(this.system.layout.renderer,e);i.additionalMultiRestBars=s,i.staff=this,i.index=this.barRenderers.length,i.layoutingInfo=t,i.doLayout(),i.registerLayoutingInfo();const a=i.barDisplayWidth;a>0&&this.system.layout.systemsLayoutMode===ji.FromModelWithWidths&&(i.width=a),this.barRenderers.push(i),e&&this.system.layout.registerBarRenderer(this.staveId,i)}revertLastBar(){const e=this.barRenderers[this.barRenderers.length-1];this.barRenderers.splice(this.barRenderers.length-1,1),this.system.layout.unregisterBarRenderer(this.staveId,e);for(const e of this.barRenderers)e.applyLayoutingInfo();return e}scaleToWidth(e){this._sharedLayoutData=new Map;const t=this.topOverflow;let s=0;switch(this.system.layout.systemsLayoutMode){case ji.Automatic:const i=(e-this.system.computedWidth)/this.barRenderers.length;for(const e of this.barRenderers){e.x=s,e.y=this.topSpacing+t;const a=e.computedWidth+i;e.scaleToWidth(a),s+=e.width}break;case ji.FromModelWithScale:e-=this.system.accoladeWidth;const a=this.system.totalBarDisplayScale;for(const i of this.barRenderers){i.x=s,i.y=this.topSpacing+t;const r=i.barDisplayScale*e/a;i.scaleToWidth(r),s+=i.width}break;case ji.FromModelWithWidths:for(const e of this.barRenderers){e.x=s,e.y=this.topSpacing+t;const i=e.barDisplayWidth;i>0?e.scaleToWidth(i):e.scaleToWidth(e.computedWidth),s+=e.width}}}get topOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){const s=this.barRenderers[t];s.topOverflow>e&&(e=s.topOverflow)}return e}get bottomOverflow(){let e=0;for(let t=0,s=this.barRenderers.length;t<s;t++){const s=this.barRenderers[t];s.bottomOverflow>e&&(e=s.bottomOverflow)}return e}calculateHeightForAccolade(){this.topSpacing=this._factory.getStaffPaddingTop(this),this.bottomSpacing=this._factory.getStaffPaddingBottom(this),this.height=this.barRenderers.length>0?this.barRenderers[0].height:0,this.height>0&&(this.height+=this.topSpacing+this.topOverflow+this.bottomOverflow+this.bottomSpacing)}finalizeStaff(){this.topSpacing=this._factory.getStaffPaddingTop(this),this.bottomSpacing=this._factory.getStaffPaddingBottom(this),this.height=0;let e=!1,t=this.topOverflow;for(let s=0;s<this.barRenderers.length;s++)this.barRenderers[s].y=this.topSpacing+t,this.height=Math.max(this.height,this.barRenderers[s].height),this.barRenderers[s].finalizeRenderer()&&(e=!0);if(e){t=this.topOverflow;for(let e=0;e<this.barRenderers.length;e++)this.barRenderers[e].y=this.topSpacing+t;for(let e=0;e<this.barRenderers.length;e++)this.barRenderers[e].finalizeRenderer()}this.height>0&&(this.height+=this.topSpacing+t+this.bottomOverflow+this.bottomSpacing)}paint(e,t,s,i,a){if(0!==this.height&&0!==a)for(let r=i,n=Math.min(i+a,this.barRenderers.length);r<n;r++)this.barRenderers[r].paint(e+this.x,t+this.y,s)}}class Tn{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 Nn{constructor(){this._timeSortedSprings=[],this._minTime=-1,this._onTimePositionsForce=0,this._onTimePositions=new Map,this._incompleteGraceRodsWidth=0,this._minDuration=Nn.MinDuration,this.version=0,this.preBeatSize=0,this.postBeatSize=0,this.minStretchForce=0,this.totalSpringConstant=0,this.incompleteGraceRods=new Map,this.allGraceRods=new Map,this.springs=new Map,this.height=0}updateMinStretchForce(e){this.minStretchForce<e&&(this.minStretchForce=e)}getPreBeatSize(e){if(e.graceType!==R.None){const t=e.graceGroup.id;return this.allGraceRods.get(t)[e.graceIndex].preBeatWidth}const t=e.absoluteDisplayStart;return this.springs.has(t)?this.springs.get(t).preBeatWidth:0}getPostBeatSize(e){if(e.graceType!==R.None){const t=e.graceGroup.id;return this.allGraceRods.get(t)[e.graceIndex].postSpringWidth}const t=e.absoluteDisplayStart;return this.springs.has(t)?this.springs.get(t).postSpringWidth:0}addSpring(e,t,s,i,a){let r;if(this.version++,this.springs.has(e))r=this.springs.get(e),r.postSpringWidth<a&&(r.postSpringWidth=a),r.graceBeatWidth<s&&(r.graceBeatWidth=s),r.preBeatWidth<i&&(r.preBeatWidth=i),t<r.smallestDuration&&(r.smallestDuration=t),t>r.longestDuration&&(r.longestDuration=t),r.allDurations.add(t);else{if(r=new Tn,r.timePosition=e,r.allDurations.add(t),this._timeSortedSprings.length>0){const e=this._timeSortedSprings[this._timeSortedSprings.length-1];for(const t of e.allDurations)e.timePosition;t<this._minDuration&&(this._minDuration=t)}r.longestDuration=t,r.postSpringWidth=a,r.graceBeatWidth=s,r.preBeatWidth=i,this.springs.set(e,r);const n=this._timeSortedSprings;let o=n.length-1;for(;o>0&&n[o].timePosition>e;)o--;this._timeSortedSprings.splice(o+1,0,r)}return(-1===this._minTime||this._minTime>e)&&(this._minTime=e),r}addBeatSpring(e,t,s){const i=e.absoluteDisplayStart;if(e.graceType!==R.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));const r=this.allGraceRods.get(a)[e.graceIndex];if(r)r.postSpringWidth<s&&(r.postSpringWidth=s),r.preBeatWidth<t&&(r.preBeatWidth=t);else{const r=new Tn;r.timePosition=i,r.postSpringWidth=s,r.preBeatWidth=t,e.graceGroup.isComplete||(this.incompleteGraceRods.get(a)[e.graceIndex]=r),this.allGraceRods.get(a)[e.graceIndex]=r}}else{let a=0;if(e.graceGroup&&this.allGraceRods.has(e.graceGroup.id))for(const t of this.allGraceRods.get(e.graceGroup.id))a+=t.springWidth;this.addSpring(i,e.displayDuration,a,t,s)}}finish(){for(const[e,t]of this.allGraceRods){let e=0;for(const s of t)e+=s.preBeatWidth,s.graceBeatWidth=e,e+=s.postSpringWidth}this._incompleteGraceRodsWidth=0;for(const e of this.incompleteGraceRods.values())for(const t of e)this._incompleteGraceRodsWidth+=t.preBeatWidth+t.postSpringWidth;this.calculateSpringConstants(),this.version++}calculateSpringConstants(){let e=0;const t=this._timeSortedSprings;if(0===t.length)return this.totalSpringConstant=-1,void(this.minStretchForce=-1);for(let s=0;s<t.length;s++){const i=t[s];let a=0;if(s===t.length-1)a=i.longestDuration;else{const e=t[s+1];a=Math.abs(e.timePosition-i.timePosition)}i.springConstant=this.calculateSpringConstant(i,a),e+=1/i.springConstant}this.totalSpringConstant=1/e,this.minStretchForce=0;for(let e=0;e<t.length;e++){const s=t[e];let i=0;if(e===t.length-1)i=s.postSpringWidth;else{const a=t[e+1];i=s.postSpringWidth+a.preSpringWidth}0===e&&(i+=s.preSpringWidth);const a=i*s.springConstant;this.updateMinStretchForce(a)}}paint(e,t,s){}calculateSpringConstant(e,t){t<=0&&(t=rs.toTicks(D.TwoHundredFiftySixth)),0===e.smallestDuration&&(e.smallestDuration=t);const s=e.smallestDuration,i=this._minDuration,a=Nn.MinDurationWidth;return s/t*(1/((1+.85*Math.log2(t/i))*a))}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(Be.isAlmostEqualTo(this._onTimePositionsForce,e)&&this._onTimePositions)return this._onTimePositions;this._onTimePositionsForce=e;const t=new Map;this._onTimePositions=t;const s=this._timeSortedSprings;if(0===s.length)return t;let i=s[0].preSpringWidth;for(let a=0;a<s.length;a++)t.set(s[a].timePosition,i),i+=this.calculateWidth(e,s[a].springConstant);return t}}Nn.MinDuration=30,Nn.MinDurationWidth=7;class xn{constructor(){this.width=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.additionalMultiBarRestIndexes=null,this.renderers=[]}get lastMasterBarIndex(){return this.additionalMultiBarRestIndexes?this.additionalMultiBarRestIndexes[this.additionalMultiBarRestIndexes.length-1]:this.masterBar.index}}class vn{constructor(e,t){this.staves=[],this.stavesRelevantForBoundsLookup=[],this.firstStaffInBracket=null,this.lastStaffInBracket=null,this.bracket=null,this.staffSystem=e,this.track=t}addStaff(e){this.staves.push(e),e.isRelevantForBoundsLookup&&this.stavesRelevantForBoundsLookup.push(e)}}class Pn{constructor(){this.firstStaffInBracket=null,this.lastStaffInBracket=null,this.drawAsBrace=!1,this.braceScale=1,this.width=0,this.index=0}finalizeBracket(){if(this.firstStaffInBracket===this.lastStaffInBracket)return void(this.width=0);const e=Dr.Heights.get(G.Brace),t=Dr.Widths.get(G.Brace);if(this.width=t,!this.drawAsBrace||!this.firstStaffInBracket||!this.lastStaffInBracket)return;const s=this.firstStaffInBracket.contentTop,i=(this.lastStaffInBracket.contentBottom-s)/e;this.braceScale=i,this.width=t*this.braceScale}}class Fn extends Pn{constructor(e){super(),this.track=e,this.drawAsBrace=Fn.isTrackDrawAsBrace(e)}includesStaff(e){return e.modelStaff.track===this.track}static isTrackDrawAsBrace(e){return e.staves.filter((e=>e.showStandardNotation)).length>1}}class Cn extends Fn{includesStaff(e){return e.modelStaff.track===this.track||!this.drawAsBrace&&this.track.playbackInfo.program===e.modelStaff.track.playbackInfo.program}}class Dn{constructor(e){this._allStaves=[],this._firstStaffInBrackets=null,this._lastStaffInBrackets=null,this._accoladeSpacingCalculated=!1,this._brackets=[],this._hasSystemSeparator=!1,this.x=0,this.y=0,this.index=0,this.accoladeWidth=0,this.isFull=!1,this.width=0,this.computedWidth=0,this.totalBarDisplayScale=0,this.isLast=!1,this.masterBarsRenderers=[],this.staves=[],this.layout=e,this.topPadding=e.renderer.settings.display.systemPaddingTop,this.bottomPadding=e.renderer.settings.display.systemPaddingBottom}get firstBarIndex(){return this.masterBarsRenderers[0].masterBar.index}get lastBarIndex(){return this.masterBarsRenderers[this.masterBarsRenderers.length-1].masterBar.index}addMasterBarRenderers(e,t){if(0===e.length)return null;this.masterBarsRenderers.push(t),t.layoutingInfo.preBeatSize=0;let s=0;for(let e=0,i=this.staves.length;e<i;e++){const i=this.staves[e];for(let e=0,a=i.staves.length;e<a;e++){const a=i.staves[e],r=t.renderers[s++];a.addBarRenderer(r)}}return this.calculateAccoladeSpacing(e),this.updateWidthFromLastBar(),t}addBars(e,t,s){const i=new xn;i.additionalMultiBarRestIndexes=s,i.layoutingInfo=new Nn,i.masterBar=e[0].score.masterBars[t],this.masterBarsRenderers.push(i);const a=i.layoutingInfo;for(const e of this.staves)for(const r of e.staves){const n=e.track.staves[r.modelStaff.index].bars[t],o=null==s?null:s.map((t=>e.track.staves[r.modelStaff.index].bars[t]));r.addBar(n,a,o);const h=r.barRenderers[r.barRenderers.length-1];i.renderers.push(h),h.isLinkedToPrevious&&(i.isLinkedToPrevious=!0),h.canWrap||(i.canWrap=!1)}return this.calculateAccoladeSpacing(e),a.finish(),i.width=this.updateWidthFromLastBar(),i}revertLastBar(){if(this.masterBarsRenderers.length>1){const e=this.masterBarsRenderers[this.masterBarsRenderers.length-1];this.masterBarsRenderers.splice(this.masterBarsRenderers.length-1,1);let t=0,s=0;for(let e=0,i=this._allStaves.length;e<i;e++){const i=this._allStaves[e].revertLastBar(),a=i.computedWidth;a>t&&(t=a);const r=i.barDisplayScale;r>s&&(s=r)}return this.width-=t,this.computedWidth-=t,this.totalBarDisplayScale-=s,e}return null}updateWidthFromLastBar(){let e=0,t=0;for(let s=0,i=this._allStaves.length;s<i;s++){const i=this._allStaves[s],a=i.barRenderers[i.barRenderers.length-1];a.applyLayoutingInfo(),a.computedWidth>e&&(e=a.computedWidth);const r=a.barDisplayScale;r>t&&(t=r)}return this.width+=e,this.computedWidth+=e,this.totalBarDisplayScale+=t,e}calculateAccoladeSpacing(e){const t=this.layout.renderer.settings;if(!this._accoladeSpacingCalculated){this._accoladeSpacingCalculated=!0,this.accoladeWidth=0;const s=this.layout.renderer.score.stylesheet;if(this.layout.renderer.settings.notation.isNotationElementVisible(T.TrackNames)){const n=1===this.layout.renderer.tracks.length?s.singleTrackTrackNamePolicy:s.multiTrackTrackNamePolicy,o=0===this.index?s.firstSystemTrackNameMode:s.otherSystemsTrackNameMode,h=0===this.index?s.firstSystemTrackNameOrientation:s.otherSystemsTrackNameOrientation;let l=!1;switch(n){case i.Hidden:break;case i.FirstSystem:l=0===this.index;break;case i.AllSystems:l=!0}let c=!1;if(l){const s=this.layout.renderer.canvas,i=t.display.resources.effectFont;s.font=i;for(const t of e){let e="";switch(o){case a.FullName:e=t.name;break;case a.ShortName:e=t.shortName}if(e.length>0){c=!0;const t=s.measureText(e);switch(h){case r.Horizontal:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,t.width));break;case r.Vertical:this.accoladeWidth=Math.ceil(Math.max(this.accoladeWidth,t.height))}}}c&&(this.accoladeWidth+=t.display.systemLabelPaddingLeft,this.accoladeWidth+=t.display.systemLabelPaddingRight)}}let n=0;for(const e of this._allStaves)e.y=n,e.calculateHeightForAccolade(),n+=e.height;let o=0;for(const e of this._brackets)e.finalizeBracket(),o=Math.max(o,e.width);this.accoladeWidth+=o,this.width+=this.accoladeWidth,this.computedWidth+=this.accoladeWidth}}getStaffTrackGroup(e){for(let t=0,s=this.staves.length;t<s;t++){const s=this.staves[t];if(s.track===e)return s}return null}addStaff(e,t){let i=this.getStaffTrackGroup(e);if(i||(i=new vn(this,e),this.staves.push(i)),t.staffTrackGroup=i,t.system=this,t.index=this._allStaves.length,this._allStaves.push(t),i.addStaff(t),t.isInsideBracket){this._firstStaffInBrackets||(this._firstStaffInBrackets=t,t.isFirstInSystem=!0),i.firstStaffInBracket||(i.firstStaffInBracket=t),this._lastStaffInBrackets=t,i.lastStaffInBracket=t;let a=this._brackets.find((e=>e.includesStaff(t)));if(!a)switch(e.score.stylesheet.bracketExtendMode){case s.NoBrackets:break;case s.GroupStaves:a=new Fn(e),a.index=this._brackets.length,this._brackets.push(a);break;case s.GroupSimilarInstruments:a=new Cn(e),a.index=this._brackets.length,this._brackets.push(a)}a&&(a.firstStaffInBracket||(a.firstStaffInBracket=t),a.lastStaffInBracket=t,i.bracket=a)}}get height(){return 0===this._allStaves.length?0:this._allStaves[this._allStaves.length-1].y+this._allStaves[this._allStaves.length-1].height+this.topPadding+this.bottomPadding}scaleToWidth(e){for(let t=0,s=this._allStaves.length;t<s;t++)this._allStaves[t].scaleToWidth(e);this.width=e}paint(e,t,s){if(t+=this.topPadding,this.paintPartial(e+this.x,t+this.y,s,0,this.masterBarsRenderers.length),this._hasSystemSeparator){const i=hn.track(s,Xt.SystemSeparator,this._allStaves[0].modelStaff.track);try{s.fillMusicFontSymbol(e+this.x,t+this.y+this.height-10,1,G.SystemDivider,!1),s.fillMusicFontSymbol(e+this.x+this.width-Dn.SystemSignSeparatorWidth,t+this.y+this.height-Dn.SystemSignSeparatorPadding,1,G.SystemDivider,!1)}finally{i?.[Symbol.dispose]?.()}}}paintPartial(e,t,s,n,o){for(let i=0,a=this._allStaves.length;i<a;i++)this._allStaves[i].paint(e,t,s,n,o);const h=this.layout.renderer.settings.display.resources;if(this.staves.length>0&&0===n){s.color=h.barSeparatorColor;const n=this.layout.renderer.settings,o=this.layout.renderer.settings.notation.isNotationElementVisible(T.TrackNames);if(s.font=h.effectFont,o){const o=this.layout.renderer.score.stylesheet,h=1===this.layout.renderer.tracks.length?o.singleTrackTrackNamePolicy:o.multiTrackTrackNamePolicy,l=0===this.index?o.firstSystemTrackNameMode:o.otherSystemsTrackNameMode,c=0===this.index?o.firstSystemTrackNameOrientation:o.otherSystemsTrackNameOrientation;let d=!1;switch(h){case i.Hidden:break;case i.FirstSystem:d=0===this.index;break;case i.AllSystems:d=!0}if(d){const i=s.textBaseline,o=s.textAlign;for(const i of this.staves)if(i.firstStaffInBracket&&i.lastStaffInBracket){const o=t+i.firstStaffInBracket.contentTop,h=t+i.lastStaffInBracket.contentBottom;let d="";switch(l){case a.FullName:d=i.track.name;break;case a.ShortName:d=i.track.shortName}const u=hn.track(s,Xt.TrackName,i.track);try{if(d.length>0){const t=e+i.firstStaffInBracket.x-n.display.accoladeBarPaddingRight-(i.bracket?.width??0)-n.display.systemLabelPaddingRight;switch(c){case r.Horizontal:s.textBaseline=V.Middle,s.textAlign=W.Right,s.fillText(d,t,(o+h)/2);break;case r.Vertical:s.textBaseline=V.Bottom,s.textAlign=W.Center;const e=.1;s.beginRotate(t,(o+h)/2,-90-e),s.fillText(d,0,0),s.endRotate()}}}finally{u?.[Symbol.dispose]?.()}}s.textBaseline=i,s.textAlign=o}}if(this._allStaves.length>0){let i=null;for(const a of this._allStaves)if(a.isInsideBracket){if(null!==i){const r=i.contentBottom,n=a.contentTop,o=e+i.x,h=i.barRenderers[0],l=hn.bar(s,h.staffLineBarSubElement,h.bar);try{const e=Math.ceil(n-r);s.fillRect(o,t+r,1,e)}finally{l?.[Symbol.dispose]?.()}}i=a}}for(const i of this._brackets)if(i.firstStaffInBracket&&i.lastStaffInBracket){const a=e+i.firstStaffInBracket.x,r=i.width,o=n.display.accoladeBarPaddingRight;let h=t+i.firstStaffInBracket.contentTop,l=t+i.lastStaffInBracket.contentBottom;if(i.drawAsBrace)s.fillMusicFontSymbol(a-o-r,l,i.braceScale,G.Brace);else if(i.firstStaffInBracket!==i.lastStaffInBracket){const e=r/2;h-=e,l+=2*e,s.fillRect(a-o-r,h,r,Math.ceil(l-h));const t=a-o-r-.5;s.fillMusicFontSymbol(t,h,1,G.BracketTop),s.fillMusicFontSymbol(t,Math.floor(l),1,G.BracketBottom)}}}}finalizeSystem(){const e=this.layout.renderer.settings;0===this.index&&(this.topPadding=e.display.firstSystemPaddingTop),this.isLast?this.bottomPadding=e.display.lastSystemPaddingBottom:this.layout.renderer.score.stylesheet.useSystemSignSeparator&&this.layout.renderer.tracks.length>1&&(this.bottomPadding+=Dn.SystemSignSeparatorHeight,this._hasSystemSeparator=!0);let t=0;for(const e of this._allStaves)e.x=this.accoladeWidth,e.y=t,e.finalizeStaff(),t+=e.height;for(const e of this._brackets)e.finalizeBracket()}buildBoundingsLookup(e,t){if(this.layout.renderer.boundsLookup.isFinished)return;const s=this._firstStaffInBrackets,i=this._lastStaffInBrackets;if(!s||!i)return;t+=this.topPadding;const a=this._allStaves[this._allStaves.length-1],r=t+this.y+s.y,n=t+this.y+i.y+i.height,o=t+this.y+this._allStaves[0].y,h=t+this.y+a.y+a.height,l=t+this.y+s.y+s.topSpacing+s.topOverflow+(s.barRenderers.length>0?s.barRenderers[0].topPadding:0),c=n-r,d=t+this.y+a.y+a.height-a.bottomSpacing-a.bottomOverflow-(a.barRenderers.length>0?a.barRenderers[0].bottomPadding:0)-l,u=h-o,p=this.x+s.x,g=new Ni;g.visualBounds=new Hs,g.visualBounds.x=e+this.x,g.visualBounds.y=t+this.y,g.visualBounds.w=this.width,g.visualBounds.h=this.height-this.topPadding-this.bottomPadding,g.realBounds=new Hs,g.realBounds.x=e+this.x,g.realBounds.y=t+this.y,g.realBounds.w=this.width,g.realBounds.h=this.height,this.layout.renderer.boundsLookup.addStaffSystem(g);const m=new Map;for(let e=0;e<this.staves.length;e++)for(const s of this.staves[e].stavesRelevantForBoundsLookup)for(const e of s.barRenderers){let i;m.has(e.bar.masterBar.index)?i=m.get(e.bar.masterBar.index):(i=new ki,i.index=e.bar.masterBar.index,i.isFirstOfLine=e.isFirstOfLine,i.realBounds=new Hs,i.realBounds.x=p+e.x,i.realBounds.y=o,i.realBounds.w=e.width,i.realBounds.h=u,i.visualBounds=new Hs,i.visualBounds.x=p+e.x,i.visualBounds.y=r,i.visualBounds.w=e.width,i.visualBounds.h=c,i.lineAlignedBounds=new Hs,i.lineAlignedBounds.x=p+e.x,i.lineAlignedBounds.y=l,i.lineAlignedBounds.w=e.width,i.lineAlignedBounds.h=d,this.layout.renderer.boundsLookup.addMasterBar(i),m.set(i.index,i)),e.buildBoundingsLookup(i,p,t+this.y+s.y)}}getBarX(e){if(!this._firstStaffInBrackets||0===this.layout.renderer.tracks.length)return 0;const t=this.layout.renderer.tracks[0].staves[0].bars[e];return this.layout.getRendererForBar(this._firstStaffInBrackets.staveId,t).x}}Dn.SystemSignSeparatorHeight=40,Dn.SystemSignSeparatorPadding=10,Dn.SystemSignSeparatorWidth=36;class En extends _n{constructor(e,t){super(e,t,W.Left)}}class Ln extends nn{constructor(e,t,s,i){super(e,t),this._tuning=s,this._trackLabel=i,this.glyphs=[]}doLayout(){if(!(this.glyphs.length>0)){this.createGlyphs(this._tuning);for(const e of this.glyphs)e.renderer=this.renderer,e.doLayout()}}paint(e,t,s){s.textBaseline=V.Middle;const i=s.color;this.colorOverride&&(s.color=this.colorOverride),super.paint(e,t,s),s.color=i}createGlyphs(e){const t=this.renderer.resources;this.height=0;if(this._trackLabel.length>0){const e=new Bn(0,this.height,this._trackLabel,t.effectFont,W.Left);e.renderer=this.renderer,e.doLayout(),this.height+=e.height,e.y+=e.height/2,this.addGlyph(e)}const s=new Bn(0,this.height,e.name,t.effectFont,W.Left);s.renderer=this.renderer,s.doLayout(),this.height+=s.height,s.y+=s.height/2,this.addGlyph(s);if(this.renderer.scoreRenderer.canvas.font=t.effectFont,this.width=Math.max(this.renderer.scoreRenderer.canvas.measureText(this._trackLabel).width,Math.max(this.renderer.scoreRenderer.canvas.measureText(e.name).width,128)),!e.isStandard){this.height+=15;const s=Ln.CircleNumberScale,i=Dr.Heights.get(G.GuitarString0)*s,a=0|Math.ceil(e.tunings.length/2);let r=0,n=this.height;for(let o=0,h=e.tunings.length;o<h;o++){const h=G.GuitarString0+(o+1);this.addGlyph(new Er(r,n+i/2.5,s,h));const l=`= ${zt.getTextForTuning(e.tunings[o],!1)}`;this.addGlyph(new Bn(r+i+1,n,l,t.effectFont,W.Left)),n+=15,o===a-1&&(n=this.height,r+=64)}this.height+=15*a}this.width+=15}}Ln.CircleNumberScale=.7;class Mn{constructor(e,t){this.args=e,this.renderCallback=t}}!function(e){e[e.Automatic=0]="Automatic",e[e.FromModelWithScale=1]="FromModelWithScale",e[e.FromModelWithWidths=2]="FromModelWithWidths"}(ji||(ji={}));class In{get scaledWidth(){return Math.round(this.width/this.renderer.settings.display.scale)}constructor(e){this._barRendererLookup=new Map,this.pagePadding=null,this.width=0,this.height=0,this.multiBarRestInfo=null,this.headerGlyphs=new Map,this.footerGlyphs=new Map,this.chordDiagrams=null,this.tuningGlyph=null,this.systemsLayoutMode=ji.Automatic,this._lazyPartials=new Map,this.firstBarIndex=0,this.lastBarIndex=0,this.renderer=e}resize(){this._lazyPartials.clear(),this.doResize()}layoutAndRender(){this._lazyPartials.clear();const e=this.renderer.score;this.firstBarIndex=Be.computeFirstDisplayedBarIndex(e,this.renderer.settings),this.lastBarIndex=Be.computeLastDisplayedBarIndex(e,this.renderer.settings,this.firstBarIndex),this.multiBarRestInfo=Be.buildMultiBarRestInfo(this.renderer.tracks,this.firstBarIndex,this.lastBarIndex),this.pagePadding=this.renderer.settings.display.padding.map((e=>e/this.renderer.settings.display.scale)),this.pagePadding||(this.pagePadding=[0,0,0,0]),1===this.pagePadding.length?this.pagePadding=[this.pagePadding[0],this.pagePadding[0],this.pagePadding[0],this.pagePadding[0]]:2===this.pagePadding.length&&(this.pagePadding=[this.pagePadding[0],this.pagePadding[1],this.pagePadding[0],this.pagePadding[1]]),this.createScoreInfoGlyphs(),this.doLayoutAndRender()}registerPartial(e,t){if(0===e.height)return;const s=this.renderer.settings.display.scale;e.x*=s,e.y*=s,e.width*=s,e.height*=s,e.totalWidth*=s,e.totalHeight*=s,this.renderer.settings.core.enableLazyLoading?(this._lazyPartials.set(e.id,new Mn(e,t)),this.renderer.partialLayoutFinished.trigger(e)):(this.renderer.partialLayoutFinished.trigger(e),this.internalRenderLazyPartial(e,t))}internalRenderLazyPartial(e,t){const s=this.renderer.canvas;s.beginRender(e.width,e.height),t(s),e.renderResult=s.endRender(),this.renderer.partialRenderFinished.trigger(e)}renderLazyPartial(e){if(this._lazyPartials.has(e)){const t=this._lazyPartials.get(e);this.internalRenderLazyPartial(t.args,t.renderCallback)}}createHeaderFooterGlyph(e,t,s,i){switch(s){case ws.WordsAndMusic:if(t.words!==t.music)return;break;case ws.Words:case ws.Music:if(t.words===t.music)return;break;case ws.CopyrightSecondLine:if(!this.headerGlyphs.has(ws.Copyright))return}const a=e.display.resources,r=e.notation,n=t.style&&t.style.headerAndFooter.has(s)?t.style.headerAndFooter.get(s):Fs.defaultHeaderAndFooter.get(s);let o=void 0===n.isVisible||n.isVisible;if(void 0!==i&&(o=r.isNotationElementVisible(i)),!o)return;const h=n.buildText(t);return h?new Bn(0,0,h,a.getFontForElement(s),n.textAlign,void 0,hn.scoreColor(a,s,t)):void 0}createScoreInfoGlyphs(){wt.debug("ScoreLayout","Creating score info glyphs");const e=this.renderer.settings,t=this.renderer.score;this.headerGlyphs=new Map,this.footerGlyphs=new Map;const s=new Vn(this.renderer,this.renderer.tracks[0].staves[0].bars[0]);for(const[i,a]of In.HeaderElements.value){const r=this.createHeaderFooterGlyph(e,t,i,a);r&&(r.renderer=s,r.doLayout(),this.headerGlyphs.set(i,r))}for(const[i,a]of In.FooterElements.value){const r=this.createHeaderFooterGlyph(e,t,i,a);r&&(r.renderer=s,r.doLayout(),this.footerGlyphs.set(i,r))}const i=e.notation,a=e.display.resources;if(i.isNotationElementVisible(T.GuitarTuning)){const e=[];for(const s of this.renderer.tracks)for(const i of s.staves){let a=!i.isPercussion&&i.isStringed&&i.tuning.length>0&&i.showTablature;if(t.stylesheet.perTrackDisplayTuning&&t.stylesheet.perTrackDisplayTuning.has(s.index)&&!1===t.stylesheet.perTrackDisplayTuning.get(s.index)&&(a=!1),a){e.push(i);break}}if(e.length>0&&t.stylesheet.globalDisplayTuning){this.tuningGlyph=new En(0,0),this.tuningGlyph.renderer=s;for(const t of e)if(t.stringTuning.tunings.length>0){const i=e.length>1?t.track.name:"",r=new Ln(0,0,t.stringTuning,i);r.colorOverride=hn.trackColor(a,Xt.StringTuning,t.track),r.renderer=s,r.doLayout(),this.tuningGlyph.addGlyph(r)}}}if(i.isNotationElementVisible(T.ChordDiagrams)){this.chordDiagrams=new wn(0,0),this.chordDiagrams.renderer=s;const e=new Set;for(const s of this.renderer.tracks){if(t.stylesheet.globalDisplayChordDiagramsOnTop&&(null==t.stylesheet.perTrackChordDiagramsOnTop||!t.stylesheet.perTrackChordDiagramsOnTop.has(s.index)||t.stylesheet.perTrackChordDiagramsOnTop.get(s.index)))for(const t of s.staves){const s=t.chords;if(s)for(const[,t]of s)e.has(t.uniqueId)||t.showDiagram&&(e.add(t.uniqueId),this.chordDiagrams.addChord(t))}}}}createEmptyStaffSystem(){const e=new Dn(this);for(let t=0;t<this.renderer.tracks.length;t++){const s=this.renderer.tracks[t];for(let i=0;i<s.staves.length;i++){const a=s.staves[i],r=cc.staveProfiles.get(this.renderer.settings.display.staveProfile);for(const i of r)i.canCreate(s,a)&&e.addStaff(s,new kn(t,a,i))}}return e}registerBarRenderer(e,t){if(this._barRendererLookup.has(e)||this._barRendererLookup.set(e,new Map),this._barRendererLookup.get(e).set(t.bar.id,t),t.additionalMultiRestBars)for(const s of t.additionalMultiRestBars)this._barRendererLookup.get(e).set(s.id,t)}unregisterBarRenderer(e,t){if(this._barRendererLookup.has(e)){const s=this._barRendererLookup.get(e);if(s.delete(t.bar.id),t.additionalMultiRestBars)for(const e of t.additionalMultiRestBars)s.delete(e.id)}}getRendererForBar(e,t){const s=t.id;return this._barRendererLookup.has(e)&&this._barRendererLookup.get(e).has(s)?this._barRendererLookup.get(e).get(s):null}layoutAndRenderBottomScoreInfo(e){e=Math.round(e);const t=new bi;t.x=0,t.y=e;let s=0;const i=this.renderer.settings.display.resources,a=[];let r=0;for(const[e,t]of In.FooterElements.value)if(this.footerGlyphs.has(e)){const t=this.footerGlyphs.get(e);t.y=s,this.alignScoreInfoGlyph(t),s+=1.2*t.font.size,a.push(t),r=Math.max(r,Math.round(t.x+t.width))}return s=Math.round(s),a.length>0&&(t.width=r,t.height=s,t.totalWidth=this.scaledWidth,t.totalHeight=e+t.height,this.registerPartial(t,(e=>{e.color=i.scoreInfoColor,e.textAlign=W.Left,e.textBaseline=V.Top;for(const t of a)t.paint(0,0,e)}))),e+s}alignScoreInfoGlyph(e){if(cc.getLayoutEngineFactory(this.renderer.settings.display.layoutMode).vertical)switch(e.textAlign){case W.Left:e.x=this.pagePadding[0];break;case W.Center:e.x=this.scaledWidth/2;break;case W.Right:e.x=this.scaledWidth-this.pagePadding[2]}else e.x=this.firstBarX,e.textAlign=W.Left}layoutAndRenderAnnotation(e){const t=this.renderer.settings.display.resources,s=Pe.withFamilyList(t.copyrightFont.families,12,I.Plain,A.Bold),i=new Vn(this.renderer,this.renderer.tracks[0].staves[0].bars[0]),a=new Bn(0,0,"rendered by alphaTab",s,W.Center,void 0,t.mainGlyphColor);a.renderer=i,a.doLayout(),this.alignScoreInfoGlyph(a);const r=new bi;return r.width=a.x+a.width,r.x=0,r.height=12,r.y=e,r.totalWidth=this.scaledWidth,r.totalHeight=e+12,r.firstMasterBarIndex=-1,r.lastMasterBarIndex=-1,this.registerPartial(r,(e=>{e.color=t.mainGlyphColor,e.font=s,e.textAlign=W.Left,e.textBaseline=V.Top,a.paint(0,0,e)})),e+12}}In.HeaderElements=new St((()=>new Map([[ws.Title,T.ScoreTitle],[ws.SubTitle,T.ScoreSubTitle],[ws.Artist,T.ScoreArtist],[ws.Album,T.ScoreAlbum],[ws.Words,T.ScoreWords],[ws.Music,T.ScoreMusic],[ws.WordsAndMusic,T.ScoreWordsAndMusic],[ws.Transcriber,void 0]]))),In.FooterElements=new St((()=>new Map([[ws.Copyright,T.ScoreCopyright],[ws.CopyrightSecondLine,void 0]])));class An extends nn{constructor(){super(0,0),this._effectGlyphs=[],this._normalGlyphs=[],this.computedWidth=0}doLayout(){let e=0;if(this.glyphs)for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t];s.x=e,s.renderer=this.renderer,s.doLayout(),e+=s.width}this.width=e,this.computedWidth=e}noteLoop(e){for(let t=this.container.beat.notes.length-1;t>=0;t--)e(this.container.beat.notes[t])}addEffect(e){super.addGlyph(e),this._effectGlyphs.push(e)}addNormal(e){super.addGlyph(e),this._normalGlyphs.push(e)}get effectElement(){}paint(e,t,s){this.paintEffects(e,t,s),this.paintNormal(e,t,s)}paintNormal(e,t,s){for(const i of this._normalGlyphs)i.paint(e+this.x,t+this.y,s)}paintEffects(e,t,s){const i=this.effectElement?hn.beat(s,this.effectElement,this.container.beat):void 0;try{for(const i of this._effectGlyphs)i.paint(e+this.x,t+this.y,s)}finally{i?.[Symbol.dispose]?.()}}}class Rn extends An{constructor(){super(...arguments),this.centerX=0}updateBeamingHelper(){}buildBoundingsLookup(e,t,s){}getNoteX(e,t){return 0}getNoteY(e,t){return 0}}class On extends Fr{constructor(e,t,s,i=1){super(e,t),this._scale=0,this._symbols=[],this._symbols=On.getSymbols(s),this._scale=i}static getSymbols(e){const t=[];for(;e>0;){const s=e%10;t.unshift(On.getSymbol(s)),e=e/10|0}return t}static getSymbol(e){switch(e){case 0:return G.TimeSig0;case 1:return G.TimeSig1;case 2:return G.TimeSig2;case 3:return G.TimeSig3;case 4:return G.TimeSig4;case 5:return G.TimeSig5;case 6:return G.TimeSig6;case 7:return G.TimeSig7;case 8:return G.TimeSig8;case 9:return G.TimeSig9;default:return G.None}}doLayout(){let e=0;for(const t of this._symbols)e+=Dr.Widths.get(t);this.width=e}paint(e,t,s){s.fillMusicFontSymbols(e+this.x,t+this.y,this._scale,this._symbols)}}On.numberHeight=18;class Hn extends Fr{constructor(){super(0,0),this._numberGlyph=[]}doLayout(){this.width=70,this.renderer.registerOverflowTop(this.renderer.getLineHeight(1));const e=this.renderer.additionalMultiRestBars.length+1;this._numberGlyph=On.getSymbols(e)}paint(e,t,s){s.fillMusicFontSymbols(e+this.x,t+this.y+this.renderer.height/2,1,[G.RestHBarLeft,G.RestHBarMiddle,G.RestHBarMiddle,G.RestHBarMiddle,G.RestHBarRight]);const i=this.renderer.getLineY(-1.5);s.fillMusicFontSymbols(e+this.x+Hn.BarWidth/2,t+this.y+i|0,1,this._numberGlyph,!0)}}Hn.BarWidth=60;class Wn extends Ir{constructor(e){super(Wn.getOrCreatePlaceholderBeat(e),e),this.preNotes=new An,this.onNotes=new Rn}doLayout(){this.renderer.showMultiBarRest&&this.onNotes.addNormal(new Hn),super.doLayout()}static getOrCreatePlaceholderBeat(e){if(e.voice.beats.length>1)return e.voice.beats[0];const t=new gs;return t.voice=e.voice,t}}!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"}(Qi||(Qi={})),function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Zi||(Zi={}));class Vn{get nextRenderer(){return this.bar&&this.bar.nextBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.nextBar):null}get previousRenderer(){return this.bar&&this.bar.previousBar?this.scoreRenderer.layout.getRendererForBar(this.staff.staveId,this.bar.previousBar):null}get lastBar(){return this.additionalMultiRestBars?this.additionalMultiRestBars[this.additionalMultiRestBars.length-1]:this.bar}get showMultiBarRest(){return!1}constructor(e,t){this._preBeatGlyphs=new on,this._voiceContainers=new Map,this._postBeatGlyphs=new on,this._ties=[],this.additionalMultiRestBars=null,this.x=0,this.y=0,this.width=0,this.computedWidth=0,this.height=0,this.index=0,this.topOverflow=0,this.bottomOverflow=0,this.isLinkedToPrevious=!1,this.canWrap=!0,this.wasFirstOfLine=!1,this._appliedLayoutingInfo=0,this.isFinalized=!1,this.topPadding=0,this.bottomPadding=0,this.scoreRenderer=e,this.bar=t,t&&(this.helpers=new yn(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){const t=e-this._preBeatGlyphs.width-this._postBeatGlyphs.width;for(const e of this._voiceContainers.values())e.scaleToWidth(t);this._postBeatGlyphs.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width+t,this.width=e}get resources(){return this.settings.display.resources}get settings(){return this.scoreRenderer.settings}get barDisplayScale(){return this.staff.system.staves.length>1?this.bar.masterBar.displayScale:this.bar.displayScale}get barDisplayWidth(){return this.staff.system.staves.length>1?this.bar.masterBar.displayWidth:this.bar.displayWidth}get isFirstOfLine(){return 0===this.index}get isLast(){return!this.bar||this.bar.index===this.scoreRenderer.layout.lastBarIndex}registerLayoutingInfo(){const e=this.layoutingInfo,t=this._preBeatGlyphs.width;e.preBeatSize<t&&(e.preBeatSize=t);for(const t of this._voiceContainers.values())t.registerLayoutingInfo(e),t.x,t.width;const s=this._postBeatGlyphs.width;e.postBeatSize<s&&(e.postBeatSize=s)}applyLayoutingInfo(){if(this._appliedLayoutingInfo>=this.layoutingInfo.version)return!1;this._appliedLayoutingInfo=this.layoutingInfo.version,this._preBeatGlyphs.width=this.layoutingInfo.preBeatSize;let e=this._preBeatGlyphs.x+this._preBeatGlyphs.width;for(const t of this._voiceContainers.values()){t.x=this._preBeatGlyphs.x+this._preBeatGlyphs.width,t.applyLayoutingInfo(this.layoutingInfo);const s=t.x+t.width;e<s&&(e=s)}this._postBeatGlyphs.x=Math.floor(e),this._postBeatGlyphs.width=this.layoutingInfo.postBeatSize,this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.computedWidth=this.width;const t=this.barDisplayWidth;return t>0&&this.scoreRenderer.layout.systemsLayoutMode===ji.FromModelWithWidths&&(this.width=t,this.computedWidth=t),!0}finalizeRenderer(){this.isFinalized=!0;let e=!1;const t=this.y-this.staff.topSpacing,s=this.y+this.height+this.staff.bottomSpacing;for(const i of this._ties)if(i.doLayout(),i.height>0){const a=i.y+i.height-s;a>0&&this.registerOverflowBottom(a)&&(e=!0);const r=i.y-t;r<0&&this.registerOverflowTop(-1*r)&&(e=!0)}return e}doLayout(){if(this.bar){this.helpers.initialize(),this._ties=[],this._preBeatGlyphs=new on,this._preBeatGlyphs.renderer=this,this._voiceContainers.clear(),this._postBeatGlyphs=new on,this._postBeatGlyphs.renderer=this;for(let e=0;e<this.bar.voices.length;e++){const t=this.bar.voices[e];if(this.hasVoiceContainer(t)){const s=new cn(0,0,t);s.renderer=this,this._voiceContainers.set(this.bar.voices[e].index,s)}}if(this.bar.simileMark===h.SecondOfDouble&&(this.canWrap=!1),this.createPreBeatGlyphs(),this.additionalMultiRestBars){const e=new Wn(this.getVoiceContainer(this.bar.voices[0]));this.addBeatGlyph(e)}else this.createBeatGlyphs();this.createPostBeatGlyphs(),this.updateSizes();for(const e of this.helpers.beamHelpers)for(const t of e)t.finish();this.computedWidth=this.width}}hasVoiceContainer(e){return!(!this.additionalMultiRestBars&&0!==e.index)||!e.isEmpty}updateSizes(){this.staff.registerStaffTop(this.topPadding),this.staff.registerStaffBottom(this.height-this.bottomPadding);const e=this._voiceContainers,t=this.beatGlyphsStart;let s=t;for(const i of e.values()){i.x=t,i.doLayout();const e=i.x+i.width;s<e&&(s=e)}this._postBeatGlyphs.x=Math.floor(s),this.width=Math.ceil(this._postBeatGlyphs.x+this._postBeatGlyphs.width),this.height+=this.layoutingInfo.height}addPreBeatGlyph(e){e.renderer=this,this._preBeatGlyphs.addGlyph(e)}addBeatGlyph(e){e.renderer=this,e.preNotes.renderer=this,e.onNotes.renderer=this,e.onNotes.beamingHelper=this.helpers.beamHelperLookup[e.beat.voice.index].get(e.beat.index),this.getVoiceContainer(e.beat.voice).addGlyph(e)}getVoiceContainer(e){return this._voiceContainers.has(e.index)?this._voiceContainers.get(e.index):void 0}getBeatContainer(e){return this.getVoiceContainer(e.voice)?.beatGlyphs?.[e.index]}getPreNotesGlyphForBeat(e){return this.getBeatContainer(e)?.preNotes}getOnNotesGlyphForBeat(e){return this.getBeatContainer(e)?.onNotes}paint(e,t,s){this.paintBackground(e,t,s),s.color=this.resources.mainGlyphColor,this._preBeatGlyphs.paint(e+this.x,t+this.y,s);for(const i of this._voiceContainers.values())i.paint(e+this.x,t+this.y,s);s.color=this.resources.mainGlyphColor,this._postBeatGlyphs.paint(e+this.x,t+this.y,s)}paintBackground(e,t,s){this.layoutingInfo.paint(e+this.x+this._preBeatGlyphs.x+this._preBeatGlyphs.width,t+this.y+this.height,s)}buildBoundingsLookup(e,t,s){const i=new wi;i.bar=this.bar,i.visualBounds=new Hs,i.visualBounds.x=t+this.x,i.visualBounds.y=s+this.y+this.topPadding,i.visualBounds.w=this.width,i.visualBounds.h=this.height-this.topPadding-this.bottomPadding,i.realBounds=new Hs,i.realBounds.x=t+this.x,i.realBounds.y=s+this.y,i.realBounds.w=this.width,i.realBounds.h=this.height,e.addBar(i);for(const[e,a]of this._voiceContainers){const r=this.bar.isEmpty&&0===e;if(!a.voice.isEmpty||r)for(let e=0,n=a.beatGlyphs.length;e<n;e++){a.beatGlyphs[e].buildBoundingsLookup(i,t+this.x+a.x,s+this.y+a.y,r)}}}addPostBeatGlyph(e){this._postBeatGlyphs.addGlyph(e)}createPreBeatGlyphs(){this.wasFirstOfLine=this.isFirstOfLine}createBeatGlyphs(){for(const e of this.bar.voices)this.hasVoiceContainer(e)&&this.createVoiceGlyphs(e)}createVoiceGlyphs(e){}createPostBeatGlyphs(){}get beatGlyphsStart(){return this._preBeatGlyphs.x+this._preBeatGlyphs.width}get postBeatGlyphsStart(){return this._postBeatGlyphs.x}getBeatX(e,t=Ki.PreNotes){const s=this.getBeatContainer(e);if(s)switch(t){case Ki.PreNotes:return s.voiceContainer.x+s.x;case Ki.OnNotes:return s.voiceContainer.x+s.x+s.onNotes.x;case Ki.MiddleNotes:return s.voiceContainer.x+s.x+s.onTimeX;case Ki.Stem:const t=s.onNotes.beamingHelper?s.onNotes.beamingHelper.getBeatLineX(e):s.onNotes.x+s.onNotes.width/2;return s.voiceContainer.x+t;case Ki.PostNotes:return s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.width;case Ki.EndBeat:return s.voiceContainer.x+s.x+s.width}return 0}getRatioPositionX(e){const t=this.bar.isEmpty?this.beatGlyphsStart:this.getBeatX(this.bar.voices[0].beats[0],Ki.OnNotes);return t+(this.postBeatGlyphsStart-t)*e}getNoteX(e,t){const s=this.getBeatContainer(e.beat);return s?s.voiceContainer.x+s.x+s.onNotes.x+s.onNotes.getNoteX(e,t):0}getNoteY(e,t){const s=this.getOnNotesGlyphForBeat(e.beat);return s?s.getNoteY(e,t):Number.NaN}reLayout(){(this.wasFirstOfLine&&!this.isFirstOfLine||!this.wasFirstOfLine&&this.isFirstOfLine)&&this.recreatePreBeatGlyphs(),this.updateSizes(),this.registerLayoutingInfo()}recreatePreBeatGlyphs(){this._preBeatGlyphs=new on,this._preBeatGlyphs.renderer=this,this.createPreBeatGlyphs()}paintSimileMark(e,t,s){const i=hn.voice(s,re.Glyphs,this.bar.voices[0],!0);try{switch(this.bar.simileMark){case h.Simple:s.beginGroup(Ir.getGroupId(this.bar.voices[0].beats[0])),s.fillMusicFontSymbol(e+this.x+(this.width-20)/2,t+this.y+this.height/2,1,G.Repeat1Bar,!1),s.endGroup();break;case h.SecondOfDouble:s.beginGroup(Ir.getGroupId(this.bar.voices[0].beats[0])),s.beginGroup(Ir.getGroupId(this.bar.previousBar.voices[0].beats[0])),s.fillMusicFontSymbol(e+this.x-14,t+this.y+this.height/2,1,G.Repeat2Bars,!1),s.endGroup(),s.endGroup()}}finally{i?.[Symbol.dispose]?.()}}completeBeamingHelper(e){}getBeatDirection(e){return this.helpers.getBeamingHelperForBeat(e).direction}}Vn.RawLineSpacing=8,Vn.StemWidth=.12*Vn.RawLineSpacing,Vn.StaffLineThickness=.13*Vn.RawLineSpacing,Vn.BeamThickness=.5*Vn.RawLineSpacing,Vn.BeamSpacing=.25*Vn.RawLineSpacing,function(e){e[e.SinglePreBeat=0]="SinglePreBeat",e[e.SingleOnBeat=1]="SingleOnBeat",e[e.SingleOnBeatToEnd=2]="SingleOnBeatToEnd",e[e.GroupedOnBeat=3]="GroupedOnBeat",e[e.GroupedOnBeatToEnd=4]="GroupedOnBeatToEnd",e[e.FullBar=5]="FullBar"}(ea||(ea={}));class Gn extends Fr{constructor(e,t){super(0,0),this._uniqueEffectGlyphs=[],this._effectGlyphs=[],this.isEmpty=!0,this.previousBand=null,this.isLinkedToPrevious=!1,this.firstBeat=null,this.lastBeat=null,this.height=0,this.originalHeight=0,this.slot=null,this.voice=e,this.info=t}doLayout(){super.doLayout();for(let e=0;e<this.renderer.bar.voices.length;e++)this._effectGlyphs.push(new Map),this._uniqueEffectGlyphs.push([])}createGlyph(e){if(e.voice===this.voice&&this.info.shouldCreateGlyph(this.renderer.settings,e)&&(!this.info.hideOnMultiTrack||0===this.renderer.staff.trackIndex)){if(this.isEmpty=!1,this.firstBeat&&!e.isBefore(this.firstBeat)||(this.firstBeat=e),!this.lastBeat||e.isAfter(this.lastBeat))switch(this.lastBeat=e,this.info.sizingMode){case ea.SingleOnBeatToEnd:case ea.GroupedOnBeatToEnd:this.lastBeat.nextBeat&&(this.lastBeat=this.lastBeat.nextBeat)}const t=this.createOrResizeGlyph(this.info.sizingMode,e);t.height>this.height&&(this.height=t.height,this.originalHeight=t.height)}}resetHeight(){this.height=this.originalHeight}createOrResizeGlyph(e,t){let s;switch(e){case ea.FullBar:case ea.SinglePreBeat:case ea.SingleOnBeat:case ea.SingleOnBeatToEnd:return s=this.info.createNewGlyph(this.renderer,t),s.renderer=this.renderer,s.beat=t,s.doLayout(),this._effectGlyphs[t.voice.index].set(t.index,s),this._uniqueEffectGlyphs[t.voice.index].push(s),s;case ea.GroupedOnBeat:case ea.GroupedOnBeatToEnd:const i=e===ea.GroupedOnBeat?ea.SingleOnBeat:ea.SingleOnBeatToEnd;if(t.index>0||this.renderer.index>0){const e=t.previousBeat;if(this.info.shouldCreateGlyph(this.renderer.settings,e)){let s=null;if(t.index>0&&this._effectGlyphs[t.voice.index].has(e.index))s=this._effectGlyphs[t.voice.index].get(e.index);else if(this.renderer.index>0){const t=this.renderer.previousRenderer.getBand(e.voice,this.info.effectId);if(t){const i=t._effectGlyphs[e.voice.index];i.has(e.index)&&(s=i.get(e.index))}}const a=this.createOrResizeGlyph(i,t);return s&&this.info.canExpand(e,t)&&(s.nextGlyph=a,a.previousGlyph=s,this.isLinkedToPrevious=!0),a}return this.createOrResizeGlyph(i,t)}return this.createOrResizeGlyph(i,t);default:return this.createOrResizeGlyph(ea.SingleOnBeat,t)}}paint(e,t,s){super.paint(e,t,s);for(let i=0,a=this._uniqueEffectGlyphs.length;i<a;i++){const a=this._uniqueEffectGlyphs[i];for(let i=0,r=a.length;i<r;i++){const r=a[i],n=hn.beat(s,ds.Effects,r.beat,!1);try{r.paint(e+this.x,t+this.y,s)}finally{n?.[Symbol.dispose]?.()}}}}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){const s=this._effectGlyphs[t.voice.index].get(t.index),i=this.renderer.getBeatContainer(t);switch(e){case ea.SinglePreBeat:const e=this.renderer.layoutingInfo.getPreBeatSize(t);s.x=this.renderer.beatGlyphsStart+i.x-e;break;case ea.SingleOnBeat:case ea.GroupedOnBeat:s.x=this.renderer.beatGlyphsStart+i.x;break;case ea.SingleOnBeatToEnd:case ea.GroupedOnBeatToEnd:if(s.x=this.renderer.beatGlyphsStart+i.x,i.beat.isLastOfVoice)s.width=this.renderer.width-s.x;else{const e=this.renderer.layoutingInfo.getPostBeatSize(t);s.width=e}break;case ea.FullBar:s.width=this.renderer.width}}}class zn{constructor(){this.uniqueEffectId=null,this.y=0,this.height=0,this.firstBeat=null,this.lastBeat=null}}class Un{constructor(){this.bands=[],this.shared=new zn}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 Xn{constructor(){this.slots=[],this._effectSlot=new Map}getOrCreateSlot(e){if(this._effectSlot.has(e.info.effectId)){const t=this._effectSlot.get(e.info.effectId);if(t.canBeUsed(e))return t}for(const t of this.slots)if(t.canBeUsed(e))return t;const t=new Un;return this.slots.push(t),t}register(e){const t=this.getOrCreateSlot(e);t.update(e),this._effectSlot.set(e.info.effectId,t)}}class Jn extends Vn{constructor(e,t,s){super(e,t),this._bands=[],this._bandLookup=new Map,this.sizingInfo=null,this._infos=s}updateSizes(){this.topOverflow=0,this.bottomOverflow=0,this.topPadding=0,this.bottomPadding=0,this.updateHeight(),super.updateSizes()}finalizeRenderer(){let e=super.finalizeRenderer();return this.updateHeight()&&(e=!0),e}updateHeight(){if(!this.sizingInfo)return!1;let e=0;for(const t of this.sizingInfo.slots){t.shared.y=e;for(const s of t.bands)s.y=e,s.height=t.shared.height;e+=t.shared.height}return e!==this.height&&(this.height=e,!0)}applyLayoutingInfo(){const e=!super.applyLayoutingInfo();if(this.index>0){const e=this.previousRenderer;this.sizingInfo=e.sizingInfo}else this.sizingInfo=new Xn;for(const e of this._bands)e.resetHeight(),e.alignGlyphs(),e.isEmpty||this.sizingInfo.register(e);return this.updateHeight(),e}scaleToWidth(e){super.scaleToWidth(e);for(const e of this._bands)e.alignGlyphs()}createBeatGlyphs(){this._bands=[],this._bandLookup=new Map;for(const e of this.bar.voices)if(this.hasVoiceContainer(e))for(const t of this._infos){const s=new Gn(e,t);s.renderer=this,s.doLayout(),this._bands.push(s),this._bandLookup.set(`${e.index}.${t.effectId}`,s)}super.createBeatGlyphs();for(const e of this._bands)e.isLinkedToPrevious&&(this.isLinkedToPrevious=!0)}createVoiceGlyphs(e){for(const t of e.beats){const s=new Ir(t,this.getVoiceContainer(e));s.preNotes=new An,s.onNotes=new Rn,this.addBeatGlyph(s);for(const e of this._bands)e.createGlyph(t)}}paint(e,t,s){this.paintBackground(e,t,s);for(const i of this._bands)s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isEmpty||i.paint(e+this.x,t+this.y,s)}getBand(e,t){const s=`${e.index}.${t}`;return this._bandLookup.has(s)?this._bandLookup.get(s):null}}class Yn extends rn{get staffId(){return this._staffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.effectStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.effectStaffPaddingBottom}constructor(e,t,s=null){super(),this.infos=t,this._staffId=e,this.isInsideBracket=!1,this.isRelevantForBoundsLookup=!1,this.shouldShow=s}canCreate(e,t){const s=this.shouldShow;return super.canCreate(e,t)&&(!s||s(e,t))}create(e,t){return new Jn(e,t,this.infos.filter((t=>e.settings.notation.isNotationElementVisible(t.notationElement))))}}class $n extends Cr{constructor(e,t,s,i,a){super(e,t),this._endingsString="",this._endings=Be.getAlternateEndingsList(s),this._openLine=i,this._closeLine=a}doLayout(){super.doLayout(),this.height=this.renderer.resources.wordsFont.size+($n.Padding+2);let e="";for(let t=0,s=this._endings.length;t<s;t++)e+=this._endings[t]+1,e+=". ";this._endingsString=e}paint(e,t,s){const i=this._closeLine?this.width-4:this.width;if(e=.5+(0|e),t=.5+(0|t),this._openLine?(s.moveTo(e+this.x,t+this.y+this.height),s.lineTo(e+this.x,t+this.y)):s.moveTo(e+this.x,t+this.y),s.lineTo(e+this.x+i,t+this.y),this._closeLine&&s.lineTo(e+this.x+i,t+this.y+this.height),s.stroke(),this._openLine){const i=s.textBaseline;s.textBaseline=V.Top;const a=this.renderer.resources;s.font=a.wordsFont,s.fillText(this._endingsString,e+this.x+$n.Padding,t+this.y),s.textBaseline=i}}}$n.Padding=3;class qn{get effectId(){return this.notationElement.toString()}}class Kn extends qn{get notationElement(){return T.EffectAlternateEndings}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return ea.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&0!==t.voice.bar.masterBar.alternateEndings}createNewGlyph(e,t){const s=t.voice.bar.masterBar,i=null===s.previousMasterBar||s.alternateEndings!==s.previousMasterBar.alternateEndings;let a=s.isRepeatEnd||null===s.nextMasterBar||s.alternateEndings!==s.nextMasterBar.alternateEndings;return s.repeatGroup.closings.some((e=>e.index>=s.index))||(a=!1),new $n(0,0,s.alternateEndings,i,a)}canExpand(e,t){return!0}}class jn extends qn{get notationElement(){return T.EffectCapo}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return ea.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.index&&0===t.voice.bar.index&&0!==t.voice.bar.staff.capo}createNewGlyph(e,t){return new Bn(0,0,`Capo. fret ${t.voice.bar.staff.capo}`,e.resources.effectFont,W.Left)}canExpand(e,t){return!1}}class Qn extends qn{get notationElement(){return T.EffectChordNames}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ea.SingleOnBeat}shouldCreateGlyph(e,t){return t.hasChord}createNewGlyph(e,t){return new Bn(0,0,t.chord.name,e.resources.effectFont,W.Center)}canExpand(e,t){return!1}}class Zn extends Cr{constructor(e){super(),this.forceGroupedRendering=!1,this.endOnBarLine=!1,this.endPosition=e}get isLinkedWithPrevious(){return!!this.previousGlyph&&this.previousGlyph.renderer.staff.system===this.renderer.staff.system}get isLinkedWithNext(){return!!this.nextGlyph&&this.nextGlyph.renderer.isFinalized&&this.nextGlyph.renderer.staff.system===this.renderer.staff.system}paint(e,t,s){if(this.isLinkedWithPrevious)return;if(!this.isLinkedWithNext&&!this.forceGroupedRendering)return void this.paintNonGrouped(e,t,s);let i;if(!this.isLinkedWithNext&&this.forceGroupedRendering)i=this;else for(i=this.nextGlyph;i.isLinkedWithNext;)i=i.nextGlyph;const a=i.renderer,r=i.beat,n=this.endPosition,o=e-this.renderer.x,h=this.calculateEndX(a,r,o,n);this.paintGrouped(e,t,h,s)}calculateEndX(e,t,s,i){return t?s+e.x+e.getBeatX(t,i):s+e.x+this.x+this.width}paintNonGrouped(e,t,s){const i=e-this.renderer.x,a=this.calculateEndX(this.renderer,this.beat,i,this.endPosition);this.paintGrouped(e,t,a,s)}}class eo extends Zn{constructor(e,t,s){super(Ki.EndBeat),this._crescendo=F.None,this._crescendo=s,this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=17}paintGrouped(e,t,s,i){const a=e+this.x,r=this.height,n=Dr.Widths.get(G.NoteheadBlack)/2;i.beginPath(),this._crescendo===F.Crescendo?(s-=n,i.moveTo(s,t+this.y),i.lineTo(a,t+this.y+r/2),i.lineTo(s,t+this.y+r)):(s-=n,i.moveTo(a,t+this.y),i.lineTo(s,t+this.y+r/2),i.lineTo(a,t+this.y+r)),i.stroke()}}class to extends qn{get notationElement(){return T.EffectCrescendo}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ea.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.crescendo!==F.None}createNewGlyph(e,t){return new eo(0,0,t.crescendo)}canExpand(e,t){return e.crescendo===t.crescendo}}class so extends Er{constructor(e,t,s){super(e,t,.6,so.getSymbol(s)),this.center=!0}doLayout(){super.doLayout(),this.y+=this.height/2}static getSymbol(e){switch(e){case E.PPP:return G.DynamicPPP;case E.PP:return G.DynamicPP;case E.P:return G.DynamicPiano;case E.MP:return G.DynamicMP;case E.MF:return G.DynamicMF;case E.F:return G.DynamicForte;case E.FF:return G.DynamicFF;case E.FFF:return G.DynamicFFF;case E.PPPP:return G.DynamicPPPP;case E.PPPPP:case E.PPPPPP:return G.DynamicPPPPP;case E.FFFF:return G.DynamicFFFF;case E.FFFFF:return G.DynamicFFFFF;case E.FFFFFF:return G.DynamicFFFFFF;case E.SF:return G.DynamicSforzando1;case E.SFP:return G.DynamicSforzandoPiano;case E.SFPP:return G.DynamicSforzandoPianissimo;case E.FP:return G.DynamicFortePiano;case E.RF:return G.DynamicRinforzando1;case E.RFZ:return G.DynamicRinforzando2;case E.SFZ:return G.DynamicSforzando1;case E.SFFZ:return G.DynamicSforzatoFF;case E.FZ:return G.DynamicForzando;case E.N:return G.DynamicNiente;case E.PF:return G.DynamicPF;case E.SFZP:return G.DynamicSforzatoPiano;default:return G.None}}}class io extends qn{get notationElement(){return T.EffectDynamics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return ea.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)return!1;const t=this.getPreviousDynamicsBeat(e);let s=0===e.voice.index&&!t||e.dynamics!==t?.dynamics;if(s&&e.voice.index>0)for(const t of e.voice.bar.voices)if(t.index<e.voice.index){const i=t.getBeatAtPlaybackStart(e.playbackStart);i&&e.dynamics===i.dynamics&&this.internalShouldCreateGlyph(i)&&(s=!1)}return s}getPreviousDynamicsBeat(e){let t=e.previousBeat;for(;null!=t;){if(!t.isRest)return t;t=t.previousBeat}return null}createNewGlyph(e,t){return new so(0,0,t.dynamics)}canExpand(e,t){return!0}}class ao extends Er{constructor(e){super(0,0,1,ao.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case L.FadeIn:return G.GuitarFadeIn;case L.FadeOut:return G.GuitarFadeOut;case L.VolumeSwell:return G.GuitarVolumeSwell}return G.None}paint(e,t,s){super.paint(e,t+this.height,s)}}class ro extends qn{get notationElement(){return T.EffectFadeIn}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ea.SingleOnBeat}shouldCreateGlyph(e,t){return t.fade!==L.None}createNewGlyph(e,t){return new ao(t.fade)}canExpand(e,t){return!0}}class no extends Er{constructor(e,t,s){super(e,t,1,no.getSymbol(s))}static getSymbol(e){switch(e){case M.Short:return G.FermataShortAbove;case M.Medium:return G.FermataAbove;case M.Long:return G.FermataLongAbove;default:return G.None}}paint(e,t,s){super.paint(e-this.width/2,t+this.height,s)}}class oo extends qn{get notationElement(){return T.EffectFermata}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return ea.SingleOnBeat}shouldCreateGlyph(e,t){return 0===t.voice.index&&!!t.fermata}createNewGlyph(e,t){return new no(0,0,t.fermata.type)}canExpand(e,t){return!0}}class ho extends qn{get notationElement(){return T.EffectFingering}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ea.SingleOnBeat}shouldCreateGlyph(e,t){return!(0!==t.voice.index||t.isRest||e.notation.fingeringMode!==B.SingleNoteEffectBand&&e.notation.fingeringMode!==B.SingleNoteEffectBandForcePiano)&&(1===t.notes.length&&t.notes[0].isFingering)}createNewGlyph(e,t){let s=_.Unknown,i=!1;const a=t.notes[0];a.leftHandFinger!==_.Unknown?(s=a.leftHandFinger,i=!0):a.rightHandFinger!==_.Unknown&&(s=a.rightHandFinger);const r=Be.fingerToString(e.settings,t,s,i)??"";return new Bn(0,0,r,e.resources.fingeringFont,W.Left)}canExpand(e,t){return!0}}class lo extends qn{constructor(){super(...arguments),this.lastCreateInfo=null}shouldCreateGlyph(e,t){this.lastCreateInfo=[];for(let e=0,s=t.notes.length;e<s;e++){const s=t.notes[e];this.shouldCreateGlyphForNote(s)&&this.lastCreateInfo.push(s)}return this.lastCreateInfo.length>0}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}canExpand(e,t){return!0}}class co extends Zn{constructor(e,t=!0){super(Ki.OnNotes),this._label=e,this._dashed=t}doLayout(){this.renderer.settings.notation.extendLineEffectsToBeatEnd&&(this.endPosition=Ki.EndBeat,this.forceGroupedRendering=!0),super.doLayout(),this.height=this.renderer.resources.effectFont.size}paintNonGrouped(e,t,s){const i=this.renderer.resources;s.font=i.effectFont;const a=s.textAlign;s.textAlign=W.Center,s.fillText(this._label,e+this.x,t+this.y),s.textAlign=a}paintGrouped(e,t,s,i){this.paintNonGrouped(e,t,i);const a=i.measureText(this._label).width,r=e+this.x+a/2+3,n=t+this.y+4;if(this._dashed){if(s>r){let e=r;for(;e<s;)i.beginPath(),i.moveTo(e,0|n),i.lineTo(Math.min(e+8,s),0|n),e+=11,i.stroke();i.beginPath(),i.moveTo(s,n-5|0),i.lineTo(s,n+5|0),i.stroke()}}else i.beginPath(),i.moveTo(r,0|n),i.lineTo(s,0|n),i.lineTo(s,n+5|0),i.stroke()}}co.LineSpacing=3,co.LineTopPadding=4,co.LineTopOffset=5,co.LineSize=8;class uo extends lo{get effectId(){return this._effectId}get notationElement(){return T.EffectHarmonics}constructor(e){switch(super(),this._beat=null,this._harmonicType=e,e){case H.None:this._effectId="harmonics-none";break;case H.Natural:this._effectId="harmonics-natural";break;case H.Artificial:this._effectId="harmonics-artificial";break;case H.Pinch:this._effectId="harmonics-pinch";break;case H.Tap:this._effectId="harmonics-tap";break;case H.Semi:this._effectId="harmonics-semi";break;case H.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 ea.GroupedOnBeat}createNewGlyph(e,t){return new co(uo.harmonicToString(this._harmonicType))}static harmonicToString(e){switch(e){case H.Natural:return"N.H.";case H.Artificial:return"A.H.";case H.Pinch:return"P.H.";case H.Tap:return"T.H.";case H.Semi:return"S.H.";case H.Feedback:return"Fdbk."}return""}}class po extends qn{get notationElement(){return T.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isLetRing}get sizingMode(){return ea.GroupedOnBeat}createNewGlyph(e,t){return new co("LetRing")}canExpand(e,t){return!0}}class go extends Cr{constructor(e,t,s,i,a=W.Center){super(e,t),this._lines=s,this.font=i,this.textAlign=a}doLayout(){super.doLayout(),this.height=this.font.size*this._lines.length}paint(e,t,s){s.font=this.font;const i=s.textAlign;s.textAlign=this.textAlign;for(let i=0;i<this._lines.length;i++)this._lines[i]&&s.fillText(this._lines[i],e+this.x,t+this.y+i*this.font.size);s.textAlign=i}}class mo extends qn{get notationElement(){return T.EffectLyrics}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return ea.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.lyrics}createNewGlyph(e,t){return new go(0,0,t.lyrics,e.resources.effectFont,W.Center)}canExpand(e,t){return!0}}class fo extends qn{get notationElement(){return T.EffectMarker}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return ea.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 Bn(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,W.Left)}canExpand(e,t){return!0}}class yo extends Zn{constructor(e,t){super(Ki.PostNotes),this._ottava=e,this._aboveStaff=t}doLayout(){super.doLayout(),this.height=Dr.Heights.get(G.QuindicesimaAlta)}paintNonGrouped(e,t,s){this.paintOttava(e,t,s)}paintOttava(e,t,s){let i=0;switch(this._ottava){case o._15ma:i=.8*Dr.Widths.get(G.QuindicesimaAlta),s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,G.QuindicesimaAlta,!1);break;case o._8va:i=.8*Dr.Widths.get(G.OttavaAlta),s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,G.OttavaAlta,!1);break;case o._8vb:i=.8*Dr.Widths.get(G.OttavaBassaVb),s.fillMusicFontSymbol(e+this.x-i/2,t+this.y+this.height,.8,G.OttavaBassaVb,!1);break;case o._15mb:i=.8*(Dr.Widths.get(G.Quindicesima)+Dr.Widths.get(G.OctaveBaselineM)+Dr.Widths.get(G.OctaveBaselineB)),s.fillMusicFontSymbols(e+this.x-i/2,t+this.y+this.height,.8,[G.Quindicesima,G.OctaveBaselineM,G.OctaveBaselineB],!1)}return i/2}paintGrouped(e,t,s,i){const a=this.paintOttava(e,t,i),r=e+this.x+a+3;let n=t+this.y;n+=this._aboveStaff?2:this.height-2;if(s>r){let e=r;for(;e<s;)i.beginPath(),i.moveTo(e,0|n),i.lineTo(Math.min(e+8,s),0|n),e+=11,i.stroke();i.beginPath(),this._aboveStaff?(i.moveTo(s,n),i.lineTo(s,t+this.y+this.height)):(i.moveTo(s,n),i.lineTo(s,t+this.y)),i.stroke()}}}class bo extends qn{get effectId(){return"ottavia-"+(this._aboveStaff?"above":"below")}get notationElement(){return T.EffectOttavia}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ea.GroupedOnBeat}constructor(e){super(),this._aboveStaff=e}shouldCreateGlyph(e,t){switch(t.ottava){case o._15ma:case o._8va:return this._aboveStaff;case o._8vb:case o._15mb:return!this._aboveStaff}return!1}createNewGlyph(e,t){return new yo(t.ottava,this._aboveStaff)}canExpand(e,t){return e.ottava===t.ottava}}class So extends lo{get notationElement(){return T.EffectPalmMute}shouldCreateGlyphForNote(e){return e.isPalmMute}get sizingMode(){return ea.GroupedOnBeat}createNewGlyph(e,t){return new co("P.M.")}}class _o extends lo{get notationElement(){return T.EffectPickSlide}shouldCreateGlyphForNote(e){return e.slideOutType===K.PickSlideDown||e.slideOutType===K.PickSlideUp}get sizingMode(){return ea.GroupedOnBeat}createNewGlyph(e,t){return new co("P.S.")}}class wo extends Er{constructor(e,t,s){super(e,t,Lr.GraceScale,wo.getSymbol(s))}paint(e,t,s){super.paint(e,t+this.height,s)}static getSymbol(e){switch(e){case Q.Up:return G.StringsUpBow;case Q.Down:return G.StringsDownBow;default:return G.None}}}class Bo extends qn{get notationElement(){return T.EffectPickStroke}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ea.SingleOnBeat}shouldCreateGlyph(e,t){return t.pickStroke!==Q.None}createNewGlyph(e,t){return new wo(0,0,t.pickStroke)}canExpand(e,t){return!0}}class ko extends Zn{constructor(e){super(Ki.EndBeat),this._stepSize=0,this._type=e}doLayout(){switch(super.doLayout(),this._type){case j.Slight:this._stepSize=12;break;case j.Wide:this._stepSize=23}this.height=18}paintGrouped(e,t,s,i){let a=e+this.x;const r=s-a,n=Math.max(1,r/this._stepSize);i.beginPath(),i.moveTo(a,t+this.y);for(let e=0;e<n;e++)i.lineTo(a+this._stepSize/2,t+this.y+this.height),i.lineTo(a+this._stepSize,t+this.y),a+=this._stepSize;i.stroke()}}class To extends qn{get notationElement(){return T.EffectSlightBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ea.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===j.Slight}createNewGlyph(e,t){return new ko(j.Slight)}canExpand(e,t){return!0}}class No extends Zn{constructor(e,t,s,i=1.2,a=!1){super(Ki.EndBeat),this._scale=0,this._symbol=G.None,this._symbolSize=0,this._type=s,this._scale=i,this.x=e,this.y=t,this._partialWaves=a}doLayout(){switch(super.doLayout(),this._type){case j.Slight:this._symbol=G.WiggleTrill;break;case j.Wide:this._symbol=G.WiggleVibratoMediumFast}this._symbolSize=Dr.Widths.get(this._symbol)*this._scale,this.height=Dr.Heights.get(this._symbol)*this._scale}paintGrouped(e,t,s,i){const a=s-(e+this.x),r=this._symbolSize;let n=a/r;this._partialWaves||(n=Math.floor(n)),n<1&&(n=1);let o=0;for(let s=0;s<n;s++)i.fillMusicFontSymbol(e+this.x+o,t+this.y+2*this.height,this._scale,this._symbol,!1),o+=r}}class xo extends lo{get notationElement(){return T.EffectSlightNoteVibrato}shouldCreateGlyphForNote(e){let t=e.vibrato===j.Slight||e.isTieDestination&&e.tieOrigin.vibrato===j.Slight;return this._hideOnTiedBend&&t&&e.isTieDestination&&e.tieOrigin.hasBend&&(t=!1),t}get sizingMode(){return ea.GroupedOnBeatToEnd}createNewGlyph(e,t){return new No(0,0,j.Slight,1.2)}constructor(e){super(),this._hideOnTiedBend=e}}class vo extends qn{get notationElement(){return T.EffectTap}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ea.SingleOnBeat}shouldCreateGlyph(e,t){return t.slap||t.pop||t.tap}createNewGlyph(e,t){const s=e.resources;return t.slap?new Bn(0,0,"S",s.effectFont,W.Left):t.pop?new Bn(0,0,"P",s.effectFont,W.Left):new Bn(0,0,"T",s.effectFont,W.Left)}canExpand(e,t){return!0}}class Po extends Cr{constructor(e){super(0,0),this.tempoAutomations=e}doLayout(){super.doLayout(),this.height=25}paint(e,t,s){for(const i of this.tempoAutomations){let a=e+this.renderer.getRatioPositionX(i.ratioPosition);const r=this.renderer.resources;if(s.font=r.markerFont,s.textBaseline=V.Top,i.text){const e=s.measureText(i.text);s.fillText(i.text,a,t+this.y+s.font.size/2),a+=e.width+.7*s.font.size}s.fillMusicFontSymbol(a,t+this.y+.8*this.height,.5,G.NoteQuarterUp,!0),s.fillText(`= ${i.value.toString()}`,a+.5*Dr.Widths.get(G.NoteQuarterUp)+3,t+this.y+s.font.size/2)}}}class Fo extends qn{get notationElement(){return T.EffectTempo}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return ea.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&t.voice.bar.masterBar.tempoAutomations.length>0}createNewGlyph(e,t){return new Po(t.voice.bar.masterBar.tempoAutomations)}canExpand(e,t){return!0}}class Co extends qn{get notationElement(){return T.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return ea.SingleOnBeat}shouldCreateGlyph(e,t){return!!t.text}createNewGlyph(e,t){return new Bn(0,0,t.text,e.resources.effectFont,W.Left)}canExpand(e,t){return!0}}class Do extends Zn{constructor(e,t){super(Ki.EndBeat),this.x=e,this.y=t}doLayout(){super.doLayout(),this.height=Dr.Heights.get(G.OrnamentTrill)/2}paintGrouped(e,t,s,i){let a=e+this.x;i.fillMusicFontSymbol(a,t+this.y+this.height,1,G.OrnamentTrill,!0),a+=Dr.Widths.get(G.OrnamentTrill)/2;const r=1.2*Dr.Widths.get(G.WiggleTrill),n=Math.floor((s-a)/r),o=t+this.y+1.37*this.height;let h=a;for(let e=0;e<n;e++)i.fillMusicFontSymbol(h,o,1.2,G.WiggleTrill,!1),h+=r}}class Eo extends lo{get notationElement(){return T.EffectTrill}shouldCreateGlyphForNote(e){return e.isTrill}get sizingMode(){return ea.GroupedOnBeatToEnd}createNewGlyph(e,t){return new Do(0,0)}}!function(e){e[e.Full=0]="Full",e[e.PartialLeft=1]="PartialLeft",e[e.PartialRight=2]="PartialRight"}(ta||(ta={}));class Lo extends Cr{constructor(e){super(0,0),this._tripletFeel=e}doLayout(){super.doLayout(),this.height=25}paint(e,t,s){e+=this.x;const i=(t+=this.y)+this.height*Lr.GraceScale,a=i+8;s.font=this.renderer.resources.effectFont,s.fillText("(",e,t+.3*this.height);const r=e+10,n=e+40;let o=[],h=[],l=[],c=[];switch(this._tripletFeel){case P.NoTripletFeel:o=[G.TextBlackNoteLongStem,G.TextCont8thBeamLongStem,G.TextBlackNoteFrac8thLongStem],l=[G.TextBlackNoteLongStem,G.TextCont8thBeamLongStem,G.TextBlackNoteFrac8thLongStem];break;case P.Triplet8th:o=[G.TextBlackNoteLongStem,G.TextCont8thBeamLongStem,G.TextBlackNoteFrac8thLongStem],l=[G.TextBlackNoteLongStem,G.Space,G.NoteEighthUp],c=[G.TextTupletBracketStartLongStem,G.TextTuplet3LongStem,G.TextTupletBracketEndLongStem];break;case P.Triplet16th:o=[G.TextBlackNoteLongStem,G.TextCont8thBeamLongStem,G.TextBlackNoteFrac8thLongStem],l=[G.TextBlackNoteLongStem,G.TextCont8thBeamLongStem,G.TextBlackNoteFrac16thLongStem],c=[G.TextTupletBracketStartLongStem,G.TextTuplet3LongStem,G.TextTupletBracketEndLongStem];break;case P.Dotted8th:o=[G.TextBlackNoteLongStem,G.TextCont8thBeamLongStem,G.TextBlackNoteFrac8thLongStem],h=[G.TextAugmentationDot],l=[G.TextBlackNoteLongStem,G.TextCont8thBeamLongStem,G.TextBlackNoteFrac16thLongStem];break;case P.Dotted16th:o=[G.TextBlackNoteLongStem,G.TextCont16thBeamLongStem,G.TextBlackNoteFrac16thLongStem],h=[G.TextAugmentationDot],l=[G.TextBlackNoteLongStem,G.TextCont16thBeamLongStem,G.TextBlackNoteFrac32ndLongStem],s.fillCircle(n+9,i,1);break;case P.Scottish8th:o=[G.TextBlackNoteLongStem,G.TextCont8thBeamLongStem,G.TextBlackNoteFrac8thLongStem],l=[G.TextBlackNoteLongStem,G.TextCont16thBeamLongStem,G.TextBlackNoteFrac8thLongStem,G.TextAugmentationDot];break;case P.Scottish16th:o=[G.TextBlackNoteLongStem,G.TextCont16thBeamLongStem,G.TextBlackNoteFrac16thLongStem],l=[G.TextBlackNoteLongStem,G.TextCont32ndBeamLongStem,G.TextBlackNoteFrac16thLongStem,G.TextAugmentationDot]}s.fillMusicFontSymbols(r,i,Lo.NoteScale,o,!1),s.fillText("=",e+32,t+5),s.fillMusicFontSymbols(n,i,Lo.NoteScale,l,!1),h.length>0&&s.fillMusicFontSymbols(n+7,i,Lo.NoteScale,h,!1),c.length>0&&s.fillMusicFontSymbols(n,a,Lo.TupletScale,c,!1),s.fillText(")",e+65,t+.3*this.height)}}Lo.NoteScale=.5,Lo.TupletScale=.7;class Mo extends qn{get notationElement(){return T.EffectTripletFeel}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return ea.SinglePreBeat}shouldCreateGlyph(e,t){return 0===t.index&&(0===t.voice.bar.masterBar.index&&t.voice.bar.masterBar.tripletFeel!==P.NoTripletFeel||t.voice.bar.masterBar.index>0&&t.voice.bar.masterBar.tripletFeel!==t.voice.bar.masterBar.previousMasterBar.tripletFeel)}createNewGlyph(e,t){return new Lo(t.voice.bar.masterBar.tripletFeel)}canExpand(e,t){return!0}}class Io extends qn{get notationElement(){return T.EffectWhammyBar}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return ea.GroupedOnBeat}shouldCreateGlyph(e,t){return t.hasWhammyBar}createNewGlyph(e,t){return new co("w/bar")}canExpand(e,t){return!0}}class Ao extends qn{get notationElement(){return T.EffectWideBeatVibrato}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ea.GroupedOnBeatToEnd}shouldCreateGlyph(e,t){return t.vibrato===j.Wide}createNewGlyph(e,t){return new ko(j.Wide)}canExpand(e,t){return!0}}class Ro extends lo{get notationElement(){return T.EffectWideNoteVibrato}shouldCreateGlyphForNote(e){return e.vibrato===j.Wide||e.isTieDestination&&e.tieOrigin.vibrato===j.Wide}get sizingMode(){return ea.GroupedOnBeatToEnd}createNewGlyph(e,t){return new No(0,0,j.Wide,1.2)}}class Oo{constructor(){this.x=0,this.width=0,this.masterBars=[]}}class Ho extends In{constructor(){super(...arguments),this._system=null}get name(){return"HorizontalScreen"}get supportsResize(){return!1}get firstBarX(){let e=this.pagePadding[0];return this._system&&(e+=this._system.accoladeWidth),e}doResize(){}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case X.Automatic:this.systemsLayoutMode=ji.Automatic;break;case X.UseModelLayout:this.systemsLayoutMode=ji.FromModelWithWidths}const e=this.renderer.score;let t=this.renderer.settings.display.startBar;t--,t=Math.min(e.masterBars.length-1,Math.max(0,t));let s=t,i=this.renderer.settings.display.barCount;i<=0&&(i=e.masterBars.length),i=t+i-1,i=Math.min(e.masterBars.length-1,Math.max(0,i)),this._system=this.createEmptyStaffSystem(),this._system.isLast=!0,this._system.x=this.pagePadding[0],this._system.y=this.pagePadding[1];const a=this.renderer.settings.display.barCountPerPartial,r=[];let n=new Oo,o=0;for(;s<=i;){const t=this.multiBarRestInfo,i=null!==t&&t.has(s)?t.get(s):null,h=this._system.addBars(this.renderer.tracks,s,i);if(0===n.masterBars.length&&h.isLinkedToPrevious&&r.length>0){const t=r[r.length-1];t.masterBars.push(e.masterBars[s]),t.width+=h.width,o+=h.width,n.x+=o}else n.masterBars.push(e.masterBars[s]),n.width+=h.width,n.masterBars.length>=a&&(0===r.length&&(n.width+=this._system.accoladeWidth+this.pagePadding[0]),o+=n.width,r.push(n),wt.debug(this.name,`Finished partial from bar ${n.masterBars[0].index} to ${n.masterBars[n.masterBars.length-1].index}`,null),n=new Oo,n.x=o);s++}n.masterBars.length>0&&(0===r.length&&(n.width+=this._system.accoladeWidth+this.pagePadding[0]),r.push(n),wt.debug(this.name,`Finished partial from bar ${n.masterBars[0].index} to ${n.masterBars[n.masterBars.length-1].index}`,null)),this.finalizeStaffSystem();const h=this.renderer.settings.display.scale;this.height=Math.floor(this._system.y+this._system.height)*h,this.width=(this._system.x+this._system.width+this.pagePadding[2])*h,s=0;let l=0;for(let e=0;e<r.length;e++){const t=r[e],i=new bi;i.x=l,i.y=0,i.totalWidth=this.width/h,i.totalHeight=this.height/h,i.width=t.width,i.height=this.height/h,i.firstMasterBarIndex=t.masterBars[0].index,i.lastMasterBarIndex=t.masterBars[t.masterBars.length-1].index,l+=t.width;const a=s,n=e;this._system.buildBoundingsLookup(0,0),this.registerPartial(i,(e=>{let s=this._system.getBarX(t.masterBars[0].index)+this._system.accoladeWidth;0===n&&(s-=this._system.x+this._system.accoladeWidth),e.color=this.renderer.settings.display.resources.mainGlyphColor,e.textAlign=W.Left,wt.debug(this.name,`Rendering partial from bar ${t.masterBars[0].index} to ${t.masterBars[t.masterBars.length-1].index}`,null),this._system.paintPartial(-s,this._system.y,e,a,t.masterBars.length)})),s+=t.masterBars.length}this.height=this.layoutAndRenderBottomScoreInfo(this.height),this.height=this.layoutAndRenderAnnotation(this.height),this.height+=this.pagePadding[3]}finalizeStaffSystem(){this._system.scaleToWidth(this._system.width),this._system.finalizeSystem()}}class Wo extends In{constructor(){super(...arguments),this._systems=[],this._allMasterBarRenderers=[],this._barsFromPreviousSystem=[]}get name(){return"PageView"}doLayoutAndRender(){switch(this.renderer.settings.display.systemsLayoutMode){case X.Automatic:this.systemsLayoutMode=ji.Automatic;break;case X.UseModelLayout:this.systemsLayoutMode=ji.FromModelWithScale}let e=this.pagePadding[1];this.width=this.renderer.width,this._allMasterBarRenderers=[],e=this.layoutAndRenderScoreInfo(e,-1),e=this.layoutAndRenderTunings(e,-1),e=this.layoutAndRenderChordDiagrams(e,-1),e=this.layoutAndRenderScore(e),e=this.layoutAndRenderBottomScoreInfo(e),e=this.layoutAndRenderAnnotation(e),this.height=(e+this.pagePadding[3])*this.renderer.settings.display.scale}get supportsResize(){return!0}get firstBarX(){let e=this.pagePadding[0];return this._systems.length>0&&(e+=this._systems[0].accoladeWidth),e}doResize(){let e=this.pagePadding[1];this.width=this.renderer.width;const 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.layoutAndRenderBottomScoreInfo(e),e=this.layoutAndRenderAnnotation(e),this.height=(e+this.pagePadding[3])*this.renderer.settings.display.scale}layoutAndRenderTunings(e,t=-1){if(!this.tuningGlyph)return e;const s=this.renderer.settings.display.resources;this.tuningGlyph.x=this.pagePadding[0],this.tuningGlyph.width=this.scaledWidth,this.tuningGlyph.doLayout();const i=Math.round(this.tuningGlyph.height),a=new bi;return a.x=0,a.y=e,a.width=this.scaledWidth,a.height=i,a.totalWidth=this.scaledWidth,a.totalHeight=t<0?e+a.height:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=W.Center,this.tuningGlyph.paint(0,0,e)})),e+i}layoutAndRenderChordDiagrams(e,t=-1){if(!this.chordDiagrams)return e;const s=this.renderer.settings.display.resources;this.chordDiagrams.width=this.scaledWidth,this.chordDiagrams.doLayout();const i=Math.round(this.chordDiagrams.height),a=new bi;return a.x=0,a.y=e,a.width=this.scaledWidth,a.height=i,a.totalWidth=this.scaledWidth,a.totalHeight=t<0?e+i:t,this.registerPartial(a,(e=>{e.color=s.scoreInfoColor,e.textAlign=W.Center,this.chordDiagrams.paint(0,0,e)})),e+i}layoutAndRenderScoreInfo(e,t=-1){wt.debug(this.name,"Layouting score info");const s=new bi;s.x=0,s.y=e;let i=0;const a=this.renderer.settings.display.resources,r=[];for(const[e,t]of In.HeaderElements.value)if(this.headerGlyphs.has(e)){const t=this.headerGlyphs.get(e);t.y=i,this.alignScoreInfoGlyph(t);let s=t.font.size;if(e===ws.Words&&this.headerGlyphs.has(ws.Music)){this.headerGlyphs.get(ws.Music).textAlign!==t.textAlign&&(s=0)}i+=s,r.push(t)}return r.length>0&&(i=Math.floor(i+17),s.width=this.scaledWidth,s.height=i,s.totalWidth=this.scaledWidth,s.totalHeight=t<0?e+s.height:t,this.registerPartial(s,(e=>{e.color=a.scoreInfoColor,e.textAlign=W.Center;for(const t of r)t.paint(0,0,e)}))),e+i}resizeAndRenderScore(e,t){if(this.renderer.settings.display.barsPerRow>0||this.systemsLayoutMode===ji.FromModelWithScale)for(let s=0;s<this._systems.length;s++){const i=this._systems[s];this.fitSystem(i),e+=this.paintSystem(i,t)}else{this._systems=[];let s=0;const i=this.maxWidth;let a=this.createEmptyStaffSystem();for(a.index=this._systems.length,a.x=this.pagePadding[0],a.y=e;s<this._allMasterBarRenderers.length;){let r=this._allMasterBarRenderers[s];if(a.width+r.width<=i||0===a.masterBarsRenderers.length)a.addMasterBarRenderers(this.renderer.tracks,r),s++;else{for(;r&&!r.canWrap&&a.masterBarsRenderers.length>1;)r=a.revertLastBar(),s--;a.isFull=!0,a.isLast=this.lastBarIndex===a.lastBarIndex,this._systems.push(a),this.fitSystem(a),e+=this.paintSystem(a,t),a=this.createEmptyStaffSystem(),a.index=this._systems.length,a.x=this.pagePadding[0],a.y=e}}a.isLast=this.lastBarIndex===a.lastBarIndex,this.fitSystem(a),e+=this.paintSystem(a,t)}return e}layoutAndRenderScore(e){let t=this.firstBarIndex;const s=this.lastBarIndex;for(this._systems=[];t<=s;){const i=this.createStaffSystem(t,s);this._systems.push(i),i.x=this.pagePadding[0],i.y=e,t=i.lastBarIndex+1,this.fitSystem(i),wt.debug(this.name,`Rendering partial from bar ${i.firstBarIndex} to ${i.lastBarIndex}`,null),e+=this.paintSystem(i,e)}return e}paintSystem(e,t){const s=Math.floor(e.height),i=new bi;return i.x=0,i.y=e.y,i.totalWidth=this.scaledWidth,i.totalHeight=t,i.width=this.scaledWidth,i.height=s,i.firstMasterBarIndex=e.firstBarIndex,i.lastMasterBarIndex=e.lastBarIndex,e.buildBoundingsLookup(0,0),this.registerPartial(i,(t=>{this.renderer.canvas.color=this.renderer.settings.display.resources.mainGlyphColor,this.renderer.canvas.textAlign=W.Left,e.paint(0,-i.y/this.renderer.settings.display.scale,t)})),s}fitSystem(e){e.isFull||e.width>this.maxWidth||this.renderer.settings.display.justifyLastSystem?e.scaleToWidth(this.maxWidth):e.scaleToWidth(e.width),e.finalizeSystem()}getBarsPerSystem(e){let t=this.renderer.settings.display.barsPerRow;if(this.systemsLayoutMode===ji.FromModelWithScale){let s,i;this.renderer.tracks.length>1?(s=this.renderer.score.defaultSystemsLayout,i=this.renderer.score.systemsLayout):(s=this.renderer.tracks[0].defaultSystemsLayout,i=this.renderer.tracks[0].systemsLayout),t=e<i.length?i[e]:s}return t}createStaffSystem(e,t){const s=this.createEmptyStaffSystem();s.index=this._systems.length;const i=this.getBarsPerSystem(s.index),a=this.maxWidth,r=t+1;let n=e;for(;n<r;){if(this._barsFromPreviousSystem.length>0)for(const e of this._barsFromPreviousSystem)s.addMasterBarRenderers(this.renderer.tracks,e),n=e.lastMasterBarIndex;else{const e=this.multiBarRestInfo,t=null!==e&&e.has(n)?e.get(n):null,i=s.addBars(this.renderer.tracks,n,t);this._allMasterBarRenderers.push(i),n=i.lastMasterBarIndex}this._barsFromPreviousSystem=[];let e=!1;if((-1===i&&s.width>=a&&0!==s.masterBarsRenderers.length||s.masterBarsRenderers.length===i+1)&&(e=!0),e){let e=s.revertLastBar();if(e)for(this._barsFromPreviousSystem.push(e);e&&!e.canWrap&&s.masterBarsRenderers.length>1;)e=s.revertLastBar(),e&&this._barsFromPreviousSystem.push(e);return s.isFull=!0,s.isLast=!1,this._barsFromPreviousSystem.reverse(),s}let t=!1,r=!0;for(const e of this.renderer.tracks)e.lineBreaks&&e.lineBreaks.has(n+1)?t=!0:r=!1;if(t&&r)return s.isFull=!0,s.isLast=!1,s;s.x=0,n++}return s.isLast=t===s.lastBarIndex,s}get maxWidth(){return this.scaledWidth-this.pagePadding[0]-this.pagePadding[2]}}class Vo extends Er{constructor(e,t,s,i){super(e,t,i,Vo.getMusicSymbol(s))}static getMusicSymbol(e){switch(e){case p.Natural:return G.AccidentalNatural;case p.Sharp:return G.AccidentalSharp;case p.Flat:return G.AccidentalFlat;case p.NaturalQuarterNoteUp:return G.AccidentalQuarterToneNaturalArrowUp;case p.SharpQuarterNoteUp:return G.AccidentalQuarterToneSharpArrowUp;case p.FlatQuarterNoteUp:return G.AccidentalQuarterToneFlatArrowUp;case p.DoubleSharp:return G.AccidentalDoubleSharp;case p.DoubleFlat:return G.AccidentalDoubleFlat}return G.None}}class Go extends Er{constructor(e,t,s,i){super(e,t,1,Go.getSymbol(s)),this._clef=s,this._clefOttava=i}static getSymbol(e){switch(e){case n.Neutral:return G.UnpitchedPercussionClef1;case n.C3:case n.C4:return G.CClef;case n.F4:return G.FClef;case n.G2:return G.GClef;default:return G.None}}paint(e,t,s){const i=hn.bar(s,c.StandardNotationClef,this.renderer.bar);try{let i;super.paint(e,t,s);let a=!1;switch(this._clefOttava){case o._15ma:i=new Er(-4,0,.5,G.Quindicesima),a=!0;break;case o._8va:i=new Er(-2,0,.5,G.Ottava),a=!0;break;case o._8vb:i=new Er(-6,0,.5,G.Ottava);break;case o._15mb:i=new Er(-8,0,.5,G.Quindicesima);break;default:return}let r=0,h=0;switch(this._clef){case n.Neutral:r=a?-12:15,h=0;break;case n.C3:case n.C4:r=a?-19:27,h=0;break;case n.F4:r=a?-9:27,h=-4;break;case n.G2:r=a?-37:30,h=0;break;default:return}i.renderer=this.renderer,i.doLayout();const l=this.width/2;i.paint(e+this.x+l+h,t+this.y+r,s)}finally{i?.[Symbol.dispose]?.()}}}class zo extends Cr{constructor(e,t,s){super(e,t),this._note=s}static getSymbol(e,t){switch(e){case u.None:return G.None;case u.Normal:return t?G.ArticAccentAbove:G.ArticAccentBelow;case u.Heavy:return t?G.ArticMarcatoAbove:G.ArticMarcatoBelow;case u.Tenuto:return t?G.ArticTenutoAbove:G.ArticTenutoBelow;default:return G.None}}doLayout(){this.width=Dr.Widths.get(G.ArticAccentAbove),this.height=Dr.Heights.get(G.ArticAccentAbove)}paint(e,t,s){const i=this.renderer.getBeatDirection(this._note.beat),a=zo.getSymbol(this._note.accentuated,i===se.Down),r=i===se.Up?t+this.y:t+this.y+this.height-2;s.fillMusicFontSymbol(e+this.x-2,r,1,a,!1)}}class Uo extends Fr{constructor(e,t,s){super(e,t),this._size=0,this._size=s}doLayout(){this.width=this._size+3}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride),s.fillCircle(e+this.x,t+this.y,this._size),s.color=i}}class Xo extends Er{constructor(e,t,s){super(e,t,s?Lr.GraceScale:1,G.NoteheadXOrnate)}}class Jo extends Er{constructor(e,t,s,i){super(e,t,i?Lr.GraceScale:1,Jo.getSymbol(s))}static getSymbol(e){switch(e){case D.QuadrupleWhole:case D.DoubleWhole:case D.Whole:case D.Half:return G.NoteheadDiamondWhiteWide;default:return G.NoteheadDiamondBlackWide}}}class Yo extends Fr{constructor(e,t,s){super(0,0),this.yOffset=0,this.startNoteRenderer=null,this.endNoteRenderer=null,this.tieDirection=se.Up,this._startX=0,this._startY=0,this._endX=0,this._endY=0,this._tieHeight=0,this._shouldDraw=!1,this.startBeat=e,this.endBeat=t,this.forEnd=s}doLayout(){if(this.width=0,!this.endBeat)return void(this._shouldDraw=!1);const e=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar);this.startNoteRenderer=e;const t=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.endBeat.voice.bar);if(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)if(this.y=Math.min(this._startY,this._endY),this.shouldDrawBendSlur())this._tieHeight=0;else{this._tieHeight=this.getTieHeight(this._startX,this._startY,this._endX,this._endY);const e=Yo.calculateActualTieHeight(1,this._startX,this._startY,this._endX,this._endY,this.tieDirection===se.Down,this._tieHeight,4);if(this.height=e.h,this.tieDirection===se.Up){const t=this.y-e.y;t>0&&(this.y-=t)}}}paint(e,t,s){this._shouldDraw&&(this.shouldDrawBendSlur()?Yo.drawBendSlur(s,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===se.Down,1):Yo.paintTie(s,1,e+this._startX,t+this._startY,e+this._endX,t+this._endY,this.tieDirection===se.Down,this._tieHeight,4))}shouldDrawBendSlur(){return!1}getTieHeight(e,t,s,i){return 22}getBeamDirection(e,t){return se.Down}getStartY(){return 0}getEndY(){return 0}getStartX(){return 0}getEndX(){return 0}static calculateActualTieHeight(e,t,s,i,a,r,n,o){const h=Yo.computeBezierControlPoints(e,t,s,i,a,r,n,o);t=h[0],s=h[1];const l=h[2],c=h[3];i=h[6],a=h[7];const d=(t-l)/(t-2*l+i),u=Yo.calculateExtrema(t,s,l,c,i,a,d),p=u.length>0?Math.min(t,i,u[0]):Math.min(t,i),g=u.length>0?Math.max(t,i,u[0]):Math.max(t,i),m=(s-c)/(s-2*c+a),f=Yo.calculateExtrema(t,s,l,c,i,a,m),y=f.length>0?Math.min(s,a,f[1]):Math.min(s,a),b=f.length>0?Math.max(s,a,f[1]):Math.max(s,a),S=new Hs;return S.x=p,S.y=y,S.w=g-p,S.h=b-y,S}static calculateExtrema(e,t,s,i,a,r,n){if(n<=0||1<=n)return[];const o=e+(s-e)*n,h=t+(i-t)*n;return[o+(s+(a-s)*n-o)*n,h+(i+(r-i)*n-h)*n]}static computeBezierControlPoints(e,t,s,i,a,r,n,o){if(t===i&&s===a)return[];if(i<t){let e=t;t=i,i=e,e=s,s=a,a=e}n*=e,o*=e;let h=a-s,l=i-t;const c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;const d=(i+t)/2,u=(a+s)/2;return[t,s,d+n*h,u+n*l,d+(n-o)*h,u+(n-o)*l,i,a]}static paintTie(e,t,s,i,a,r,n=!1,o=22,h=4){const l=Yo.computeBezierControlPoints(t,s,i,a,r,n,o,h);e.beginPath(),e.moveTo(l[0],l[1]),e.quadraticCurveTo(l[2],l[3],l[6],l[7]),e.quadraticCurveTo(l[4],l[5],l[0],l[1]),e.closePath(),e.fill()}static drawBendSlur(e,t,s,i,a,r,n,o){let h=a-s,l=i-t;const c=Math.sqrt(h*h+l*l);r?h*=-1:l*=-1,h/=c,l/=c;const d=(i+t)/2,u=(a+s)/2;let p=Yo.BendSlurHeight*n;i-t<20&&(p/=2);const g=d+p*h,m=u+p*l;if(e.beginPath(),e.moveTo(t,s),e.lineTo(g,m),e.lineTo(i,a),e.stroke(),o){const t=e.measureText(o).width,s=r?0:-e.font.size;e.fillText(o,g-t/2,m+s)}}}Yo.BendSlurHeight=11;class $o extends Fr{constructor(e){super(0,0),this._isOpen=e}doLayout(){super.doLayout(),this.width=$o.Size}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride),this._isOpen?Yo.paintTie(s,1,e+this.x+this.width,t+this.y+this.height,e+this.x+this.width,t+this.y,!1,6,3):Yo.paintTie(s,1,e+this.x,t+this.y,e+this.x,t+this.y+this.height,!1,6,3),s.color=i}}$o.Size=6;class qo{constructor(e,t,s){this.line=0,this.line=e,this.isGhost=t,this.color=s}}class Ko extends Fr{constructor(e){super(0,0),this._infos=[],this._glyphs=[],this.isEmpty=!0,this._isOpen=e}addParenthesis(e){const t=this.renderer,s=t.getNoteLine(e),i=e.isGhost||this.isTiedBend(e)&&t.settings.notation.isNotationElementVisible(T.ParenthesisOnTiedBends),a=hn.noteColor(t.resources,ee.Effects,e);this.add(new qo(s,i,a))}addParenthesisOnLine(e,t){const s=new qo(e,t,void 0);this.add(s)}add(e){this._infos.push(e),e.isGhost&&(this.isEmpty=!1)}isTiedBend(e){return!!e.isTieDestination&&(!!e.tieOrigin.hasBend||this.isTiedBend(e.tieOrigin))}doLayout(){const e=this.renderer;this._infos.sort(((e,t)=>e.line-t.line));let t=null;const s=e.getScoreHeight(1);for(let i=0,a=this._infos.length;i<a;i++){let a;if(this._infos[i].isGhost)if(t){const a=e.getScoreY(this._infos[i].line)+s;t.height=a-t.y}else a=new $o(this._isOpen),a.colorOverride=this._infos[i].color,a.renderer=this.renderer,a.y=e.getScoreY(this._infos[i].line)-s,a.height=2*s,a.doLayout(),this._glyphs.push(a),t=a;else t=null}this.width=this._glyphs.length>0?this._glyphs[0].width:0}paint(e,t,s){super.paint(e,t,s);for(const i of this._glyphs)i.paint(e+this.x,t+this.y,s)}}class jo{constructor(e,t){this.steps=0,this.glyph=e,this.steps=t}}class Qo extends Fr{constructor(){super(0,0),this._infos=[],this._noteHeadPadding=0,this.minNote=null,this.maxNote=null,this.spacingChanged=new Si,this.upLineX=0,this.downLineX=0,this.displacedX=0,this.noteStartX=0}add(e,t){const s=new jo(e,t);this._infos.push(s),(!this.minNote||this.minNote.steps>s.steps)&&(this.minNote=s),(!this.maxNote||this.maxNote.steps<s.steps)&&(this.maxNote=s)}doLayout(){this._infos.sort(((e,t)=>t.steps-e.steps));let e=0,t=!1,s=0,i=!1;const a=this.direction;let r=0;for(let n=0,o=this._infos.length;n<o;n++){const o=this._infos[n].glyph;o.renderer=this.renderer,o.doLayout();let h=!1;0===n?e=o.width:Math.abs(s-this._infos[n].steps)<=1?t?t=!1:(h=!0,o.x=e,i=!0,t=!0):t=!1,a===se.Down?o.x=h?0:e:o.x=h?e:0,o.x+=this.noteStartX,s=this._infos[n].steps,r=Math.max(r,o.x+o.width),o instanceof Lr&&o.centerOnStem&&(o.x=e)}i?(this._noteHeadPadding=0,this.upLineX=e,this.downLineX=e):(this._noteHeadPadding=a===se.Down?-e:0,r+=this._noteHeadPadding,this.upLineX=r,this.downLineX=0),this.displacedX=e,this.width=r}paint(e,t,s){e+=this.x,t+=this.y,this.paintLedgerLines(e,t,s);const i=this._infos,a=e+this._noteHeadPadding;for(const e of i)e.glyph.renderer=this.renderer,e.glyph.paint(a,t,s)}paintLedgerLines(e,t,s){if(!this.minNote)return;const i=this.renderer,a=hn.bar(s,c.StandardNotationStaffLine,i.bar,!0);try{const a=3,r=this.width-this.noteStartX+2*a,n=i.getLineHeight(1),o=i.getLineY(-1),h=i.getLineY(i.drawnLineCount),l=i.getLineY(this.minNote.steps/2),c=i.getLineY(this.maxNote.steps/2);let d=o;for(;d>=l;)s.fillRect(e-a+this.noteStartX,t+d|0,r,Vn.StaffLineThickness),d-=n;for(d=h;d<=c;)s.fillRect(e-a+this.noteStartX,t+d|0,r,Vn.StaffLineThickness),d+=n}finally{a?.[Symbol.dispose]?.()}}}class Zo extends Er{constructor(e,t,s){super(e,t,1,Zo.getSymbol(s))}static getSymbol(e){switch(e){case D.ThirtySecond:return G.Tremolo3;case D.Sixteenth:return G.Tremolo2;case D.Eighth:return G.Tremolo1;default:return G.None}}}class eh extends Fr{constructor(){super(0,0)}doLayout(){this.width=26}paint(e,t,s){const i=this.renderer,a=i.getLineHeight(i.heightLineCount-1),r=i.getLineY(0)+i.getLineHeight(i.drawnLineCount-1)/2-a/2,n=s.lineWidth;s.lineWidth=2,s.moveTo(e+this.x,t+r),s.lineTo(e+this.x+this.width,t+r+a),s.moveTo(e+this.x,t+r+a),s.lineTo(e+this.x+this.width,t+r),s.stroke(),s.lineWidth=n}}class th extends Qo{constructor(){super(...arguments),this._noteGlyphLookup=new Map,this._notes=[],this._deadSlapped=null,this._tremoloPicking=null,this.aboveBeatEffects=new Map,this.belowBeatEffects=new Map}get direction(){return this.beamingHelper.direction}getNoteX(e,t){if(this._noteGlyphLookup.has(e.id)){const s=this._noteGlyphLookup.get(e.id);let i=this.x+s.x+this._noteHeadPadding;switch(t){case Zi.Left:break;case Zi.Center:i+=s.width/2;break;case Zi.Right:i+=s.width}return i}return 0}getNoteY(e,t){if(this._noteGlyphLookup.has(e.id)){const s=this._noteGlyphLookup.get(e.id);let i=this.y+s.y;switch(t){case Qi.TopWithStem:i-=this.renderer.getStemSize(this.beamingHelper);break;case Qi.Top:i-=s.height/2;break;case Qi.Center:break;case Qi.Bottom:i+=s.height/2;break;case Qi.BottomWithStem:i+=this.renderer.getStemSize(this.beamingHelper)}return i}return 0}addNoteGlyph(e,t,s){super.add(e,s),this._noteGlyphLookup.set(t.id,e),this._notes.push(t)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.upLineX,e+this.x+this.downLineX)}doLayout(){super.doLayout();const e=this.renderer;this.beat.deadSlapped&&(this._deadSlapped=new eh,this._deadSlapped.renderer=this.renderer,this._deadSlapped.doLayout(),this.width=this._deadSlapped.width);const t=this.direction;let s=0,i=0,a=1,r=-a,n=!1,o=!1;this.beat.deadSlapped?(i=e.getScoreY(0),s=e.getScoreY(e.heightLineCount)):this.direction===se.Up?(n=!1,o=!0,i=e.getScoreY(this.maxNote.steps+2),s=e.getScoreY(this.minNote.steps)-e.getStemSize(this.beamingHelper,!0)):(n=!0,o=!1,i=e.getScoreY(this.minNote.steps-1),a*=-1,r*=-1,s=e.getScoreY(this.maxNote.steps)+e.getStemSize(this.beamingHelper,!0));let h=null,l=null;for(const e of this.aboveBeatEffects.values())e.renderer=this.renderer,e.doLayout(),o&&(s+=r*e.height),e.y=s,(null===h||h>s)&&(h=s),(null===l||l<s)&&(l=s),o||(s+=r*e.height);for(const e of this.belowBeatEffects.values())e.renderer=this.renderer,e.doLayout(),n&&(i+=a*e.height),e.y=i,(null===h||h>i)&&(h=i),(null===l||l<i)&&(l=i),n||(i+=a*e.height);if(null!==h&&e.registerBeatEffectOverflows(h,l??0),this.beat.isTremolo&&!this.beat.deadSlapped){let e=0;const s=t===se.Up?this.minNote:this.maxNote;let i=t===se.Up?this.upLineX:this.downLineX;const a=this.beat.tremoloSpeed;switch(a){case D.ThirtySecond:e=t===se.Up?-15:15;break;case D.Sixteenth:e=t===se.Up?-12:15;break;case D.Eighth:e=t===se.Up?-10:10;break;default:e=t===se.Up?-10:15}this.beat.duration<D.Half&&(i=this.width/2),this._tremoloPicking=new Zo(i,s.glyph.y+e,a),this._tremoloPicking.renderer=this.renderer,this._tremoloPicking.doLayout()}}buildBoundingsLookup(e,t,s){for(const i of this._notes)if(this._noteGlyphLookup.has(i.id)){const a=this._noteGlyphLookup.get(i.id),r=new Ti;r.note=i,r.noteHeadBounds=new Hs,r.noteHeadBounds.x=t+this.x+this._noteHeadPadding+a.x,r.noteHeadBounds.y=s+this.y+a.y-a.height/2,r.noteHeadBounds.w=a.width,r.noteHeadBounds.h=a.height,e.addNote(r)}}paint(e,t,s){this.paintEffects(e,t,s),super.paint(e,t,s)}paintEffects(e,t,s){const i=hn.beat(s,ds.StandardNotationEffects,this.beat);try{for(const i of this.aboveBeatEffects.values())i.paint(e+this.x+2,t+this.y,s);for(const i of this.belowBeatEffects.values())i.paint(e+this.x+2,t+this.y,s);this._tremoloPicking&&this._tremoloPicking.paint(e,t,s),this._deadSlapped&&this._deadSlapped.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}}class sh extends Er{constructor(e,t,s){super(e,t,1,sh.getSymbol(s))}static getSymbol(e){switch(e){case D.QuadrupleWhole:return G.RestLonga;case D.DoubleWhole:return G.RestDoubleWhole;case D.Whole:return G.RestWhole;case D.Half:return G.RestHalf;case D.Quarter:return G.RestQuarter;case D.Eighth:return G.RestEighth;case D.Sixteenth:return G.RestSixteenth;case D.ThirtySecond:return G.RestThirtySecond;case D.SixtyFourth:return G.RestSixtyFourth;case D.OneHundredTwentyEighth:return G.RestOneHundredTwentyEighth;case D.TwoHundredFiftySixth:return G.RestTwoHundredFiftySixth;default:return G.None}}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("score",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){this.internalPaint(e,t,s,ds.StandardNotationRests)}internalPaint(e,t,s,i){const a=hn.beat(s,i,this.beat);try{super.paint(e,t,s)}finally{a?.[Symbol.dispose]?.()}}}class ih{constructor(){this.x=0,this.y=-3e3,this.width=0}}class ah extends nn{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));const e=[];e.push(new ih);for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t];s.renderer=this.renderer,s.doLayout();let i=0;for(;e[i].y>s.y;)i++,i===e.length&&e.push(new ih);s.x=i,e[i].y=s.y+21,e[i].width<s.width&&(e[i].width=s.width)}this.width=0;for(const t of e)this.width+=t.width,t.x=this.width;for(let t=0,s=this.glyphs.length;t<s;t++){const s=this.glyphs[t],i=e[s.x];s.x=this.width-i.x}}}class rh extends Qo{get direction(){return se.Up}constructor(e,t=!1){super(),this._showParenthesis=!1,this._noteValueLookup=new Map,this._accidentals=new ah,this._preNoteParenthesis=null,this._postNoteParenthesis=null,this.isEmpty=!0,this.noteHeadOffset=0,this._beat=e,this._showParenthesis=t,t&&(this._preNoteParenthesis=new Ko(!0),this._postNoteParenthesis=new Ko(!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,s){const i=this.renderer,a=new Lr(0,0,D.Quarter,!0),r=i.accidentalHelper.applyAccidentalForValue(this._beat,e,t,!0),n=i.accidentalHelper.getNoteLineForValue(e,!1);if(a.y=i.getScoreY(n),this._showParenthesis&&(this._preNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.renderer=this.renderer,this._preNoteParenthesis.addParenthesisOnLine(n,!0),this._postNoteParenthesis.addParenthesisOnLine(n,!0)),r!==p.None){const e=new Vo(0,a.y,r,Lr.GraceScale);e.renderer=this.renderer,this._accidentals.renderer=this.renderer,this._accidentals.addGlyph(e)}this._noteValueLookup.set(e,a),this.add(a,n),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+rh.ElementPadding),this._accidentals.isEmpty||(e+=this._accidentals.width+rh.ElementPadding,this._accidentals.x=e,this._accidentals.renderer=this.renderer,this._accidentals.doLayout(),e+=this._accidentals.width+rh.ElementPadding),this.noteStartX=e,super.doLayout(),this.noteHeadOffset=this.noteStartX+(this.width-this.noteStartX)/2,this._showParenthesis&&(this._postNoteParenthesis.x=this.width+rh.ElementPadding,this._postNoteParenthesis.renderer=this.renderer,this._postNoteParenthesis.doLayout(),this.width+=this._postNoteParenthesis.width+rh.ElementPadding)}paint(e,t,s){this._accidentals.isEmpty||this._accidentals.paint(e+this.x,t+this.y,s),this._showParenthesis&&(this._preNoteParenthesis.paint(e+this.x,t+this.y,s),this._postNoteParenthesis.paint(e+this.x,t+this.y,s)),super.paint(e,t,s)}}rh.ElementPadding=2;class nh extends Fr{constructor(){super(...arguments),this.BendNoteHeads=[]}drawBendSlur(e,t,s,i,a,r,n,o){Yo.drawBendSlur(e,t,s,i,a,r,n,o)}doLayout(){super.doLayout(),this.width=0;for(const e of this.BendNoteHeads)e.doLayout(),this.width+=e.width+10}getTieDirection(e,t){return t.getBeatDirection(e)===se.Up?se.Down:se.Up}}nh.EndPadding=8;class oh extends ge{constructor(e=0,t=0){super(e,t),this.lineValue=0,this.lineValue=t}}class hh extends Fr{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);const t=this.createRenderingPoints(e);this._renderPoints.set(e.id,t),(-1===this._maxBendValue||this._maxBendValue<e.maxBendPoint.value)&&(this._maxBendValue=e.maxBendPoint.value);let s=0;switch(e.bendType){case y.Bend:s=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||s<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=s):(-1===this._bendEndMinValue||s<this._bendEndMinValue)&&(this._bendEndMinValue=s);break;case y.Release:s=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s);break;case y.BendRelease:s=t[1].value,(-1===this._bendMiddleMinValue||s<this._bendMiddleMinValue)&&(this._bendMiddleMinValue=s),s=t[2].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s);break;case y.Prebend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s);break;case y.PrebendBend:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s),s=t[1].value,e.isTieOrigin?(-1===this._bendEndContinuedMinValue||s<this._bendEndContinuedMinValue)&&(this._bendEndContinuedMinValue=s):(-1===this._bendEndMinValue||s<this._bendEndMinValue)&&(this._bendEndMinValue=s);break;case y.PrebendRelease:s=t[0].value,(-1===this._preBendMinValue||s<this._preBendMinValue)&&(this._preBendMinValue=s),s=t[1].value,e.isTieOrigin?(-1===this._releaseContinuedMinValue||s<this._releaseContinuedMinValue)&&(this._releaseContinuedMinValue=s):s>0&&(-1===this._releaseMinValue||s<this._releaseMinValue)&&(this._releaseMinValue=s)}}doLayout(){super.doLayout();const e=this._maxBendValue*hh.BendValueHeight;this.renderer.registerOverflowTop(e);let t=0;for(const e of this._notes){const s=this._renderPoints.get(e.id);switch(e.bendType){case y.Bend:s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case y.Release:t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t);break;case y.BendRelease:s[1].lineValue=this._bendMiddleMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[2].lineValue=t);break;case y.Prebend:s[0].lineValue=this._preBendMinValue;break;case y.PrebendBend:s[0].lineValue=this._preBendMinValue,s[1].lineValue=e.isTieOrigin?this._bendEndContinuedMinValue:this._bendEndMinValue;break;case y.PrebendRelease:s[0].lineValue=this._preBendMinValue,t=e.isTieOrigin?this._releaseContinuedMinValue:this._releaseMinValue,t>=0&&(s[1].lineValue=t)}}this.width=0,this._notes.sort(((e,t)=>e.isStringed?e.string-t.string:e.realValue-t.realValue))}createRenderingPoints(e){const t=[];switch(e.bendType){case y.Custom:for(const s of e.bendPoints)t.push(new oh(s.offset,s.value));break;case y.BendRelease:t.push(new oh(0,e.bendPoints[0].value)),t.push(new oh(ge.MaxPosition/2|0,e.bendPoints[1].value)),t.push(new oh(ge.MaxPosition,e.bendPoints[3].value));break;case y.Bend:case y.Hold:case y.Prebend:case y.PrebendBend:case y.PrebendRelease:case y.Release:t.push(new oh(0,e.bendPoints[0].value)),t.push(new oh(ge.MaxPosition,e.bendPoints[1].value))}return t}paint(e,t,s){const i=s.color;this._notes.length>1&&(s.color=this.renderer.resources.secondaryGlyphColor);for(const a of this._notes){const r=this._renderPoints.get(a.id),n=this.renderer;let o=a,h=!1,l=null,c=!1;const d=a.bendStyle===f.Gradual?"grad.":"";let u=null;for(;o.isTieOrigin;){const e=o.tieDestination;if(l=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,e.beat.voice.bar),!l||n.staff!==l.staff)break;if(o=e,h=!0,o.hasBend||!this.renderer.settings.notation.extendBendArrowsOnTiedNotes||o.vibrato!==j.None){c=!0;break}}u=o.beat,l=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,u.voice.bar),u.isLastOfVoice&&!o.hasBend&&this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&(u=null);let p=0,g=0;const m=t+n.y;p=e+n.x,r[0].value>0||a.isContinuedBend?p+=n.getBeatX(a.beat,Ki.MiddleNotes):p+=n.getNoteX(a,Zi.Right),g=!u||u.isLastOfVoice&&!c?e+l.x+l.postBeatGlyphsStart:c||!u.nextBeat?e+l.x+l.getBeatX(u,Ki.MiddleNotes):a.bendType===y.Hold?e+l.x+l.getBeatX(u.nextBeat,Ki.OnNotes):e+l.x+l.getBeatX(u.nextBeat,Ki.PreNotes),h||(g-=hh.ArrowSize);const b=(g-p)/ge.MaxPosition;s.beginPath();for(let e=0,t=r.length-1;e<t;e++){const t=r[e];let i=r[e+1];0!==e||0===t.value||a.isTieDestination||this.paintBend(a,new oh(0,0),t,p,m,b,d,s),a.bendType!==y.Prebend?(0===e&&(p+=2),this.paintBend(a,t,i,p,m,b,d,s)):a.isTieOrigin&&a.tieDestination.hasBend&&(i=new oh(ge.MaxPosition,t.value),i.lineValue=t.lineValue,this.paintBend(a,t,i,p,m,b,d,s))}if(o.vibrato!==j.None){const i=g-e+hh.ArrowSize-l.x,a=m-t-hh.BendValueHeight*r[r.length-1].lineValue,n=new No(i,a,o.vibrato,1.2);n.beat=o.beat,n.renderer=l,n.doLayout(),n.paint(e+l.x,t,s)}s.color=i}}paintBend(e,t,s,i,a,r,n,o){const h=this.renderer,l=this.renderer.resources,c=h.lineOffset/2,d=i+r*t.offset,u=hh.BendValueHeight;let p=a-u*t.lineValue;0===t.value?s.offset===t.offset?p+=h.getNoteY(e.beat.maxStringNote,Qi.Top):p+=h.getNoteY(e,Qi.Center):p+=c;const g=i+r*s.offset;let m=a-u*s.lineValue;0===s.lineValue?m+=h.getNoteY(e,Qi.Center):m+=c;let f=0;const y=hh.ArrowSize;if(s.value>t.value?(m+y>p&&(m=p-y),o.beginPath(),o.moveTo(g,m),o.lineTo(g-.5*y,m+y),o.lineTo(g+.5*y,m+y),o.closePath(),o.fill(),f=y):s.value!==t.value&&(m<p&&(m=p+y),o.beginPath(),o.moveTo(g,m),o.lineTo(g-.5*y,m-y),o.lineTo(g+.5*y,m-y),o.closePath(),o.fill(),f=-y),o.beginPath(),t.value===s.value){if(t.lineValue>0){let e=g;const t=hh.DashSize,s=d+t;if((e-d)/(2*t)<1)o.moveTo(e,p),o.lineTo(d,p);else for(;e>s;)o.moveTo(e,p),o.lineTo(e-t,p),e-=2*t;o.stroke()}}else g>d?(o.moveTo(d,p),o.bezierCurveTo((d+g)/2,p,g,p,g,m+f),o.stroke()):(o.moveTo(d,p),o.lineTo(g,m),o.stroke());if(n&&t.offset<s.offset){o.font=l.graceFont;const e=o.measureText(n).width;let t=0,s=0;if(p>m){const i=Math.abs(p-m);t=i>1.3*o.font.size?p-i/2:p,s=(d+g-e)/2}else t=p,s=g-e;o.fillText(n,s,t)}if(0!==s.value&&t.value!==s.value){let e=s.value;const i=s.value>t.value;e=Math.abs(e);let r="";if(4===e)r="full",e-=4;else if(e>=4||e<=-4){const t=e/4|0;r+=t,e-=4*t}if(e>0&&(r+=hh.getFractionSign(e)),""!==r){m=a-u*s.value;let e=m;i||(e=p+1*Math.abs(m-p)/3),o.font=l.tablatureFont;const t=o.measureText(r).width,n=e-.5*l.tablatureFont.size-2,h=g-t/2;o.fillText(r,h,n)}}}static getFractionSign(e){switch(e){case 1:return"¼";case 2:return"½";case 3:return"¾";default:return`${e}/ 4`}}}hh.ArrowSize=6,hh.DashSize=3,hh.BendValueHeight=6;class lh extends Fr{constructor(e){super(0,0),this._isSimpleDip=!1,this._beat=e,this._renderPoints=this.createRenderingPoints(e)}createRenderingPoints(e){if(e.whammyBarType===te.Custom)return e.whammyBarPoints;const t=[];switch(e.whammyBarType){case te.Dive:case te.Hold:case te.PrediveDive:case te.Predive:t.push(new ge(0,e.whammyBarPoints[0].value)),t.push(new ge(ge.MaxPosition,e.whammyBarPoints[1].value));break;case te.Dip:t.push(new ge(0,e.whammyBarPoints[0].value)),t.push(new ge(ge.MaxPosition/2|0,e.whammyBarPoints[1].value)),t.push(new ge(ge.MaxPosition,e.whammyBarPoints[e.whammyBarPoints.length-1].value))}return t}doLayout(){super.doLayout(),this._isSimpleDip=this.renderer.settings.notation.notationMode===k.SongBook&&this._beat.whammyBarType===te.Dip;let e=null,t=null,s=this._beat;for(;s&&s.hasWhammyBar;)(!e||e.value>s.minWhammyPoint.value)&&(e=s.minWhammyPoint),(!t||t.value<s.maxWhammyPoint.value)&&(t=s.maxWhammyPoint),s=s.nextBeat;let i=t.value>0?Math.abs(this.getOffset(t.value)):0;(i>0||0!==this._beat.whammyBarPoints[0].value||this.renderer.settings.notation.isNotationElementVisible(T.ZerosOnDiveWhammys))&&(i+=2*this.renderer.resources.tablatureFont.size);const a=e.value<0?Math.abs(this.getOffset(e.value)):0;this.renderer.registerOverflowTop(i+a);i>this.renderer.staff.getSharedLayoutData(lh.TopOffsetSharedDataKey,-1)&&this.renderer.staff.setSharedLayoutData(lh.TopOffsetSharedDataKey,i)}getOffset(e){if(0===e)return 0;let t=lh.PerHalfSize+Math.log2(Math.abs(e)/2)*lh.PerHalfSize;return e<0&&(t=-t),t}paint(e,t,s){const i=hn.beat(s,ds.StandardNotationEffects,this._beat);try{const i=this.renderer;let a=this._beat.nextBeat,r=null,n=Ki.PreNotes;a&&(r=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,a.voice.bar),r&&r.staff===i.staff&&(r===i||a.hasWhammyBar)?n=!a.hasWhammyBar||i.settings.notation.notationMode===k.SongBook&&a.whammyBarType===te.Dip?Ki.PreNotes:Ki.MiddleNotes:(a=null,r=null));let o=0,h=0;this._isSimpleDip?(o=e+i.x+i.getBeatX(this._beat,Ki.OnNotes)-2,h=e+i.x+i.getBeatX(this._beat,Ki.PostNotes)+2):(o=e+i.x+i.getBeatX(this._beat,Ki.MiddleNotes),h=r?e+r.x+r.getBeatX(a,n):e+i.x+i.width-2);const l=s.textAlign;if(s.textAlign=W.Center,this._renderPoints.length>=2){const e=(h-o)/ge.MaxPosition;s.beginPath();const i=t+this.renderer.staff.getSharedLayoutData(lh.TopOffsetSharedDataKey,0);let a=this._beat.whammyStyle===f.Gradual?"grad.":"";for(let t=0,r=this._renderPoints.length-1;t<r;t++){const n=this._renderPoints[t],h=this._renderPoints[t+1],l=t<r-2?this._renderPoints[t+2]:null;let c=0===t;0!==t||0===n.value||this._beat.isContinuedWhammy||(this.paintWhammy(!1,new ge(0,0),n,h,o,i,e,s),c=!1),this.paintWhammy(c,n,h,l,o,i,e,s,a),a=""}s.stroke()}s.textAlign=l}finally{i?.[Symbol.dispose]?.()}}paintWhammy(e,t,s,i,a,r,n,o,h){const l=a+n*t.offset,c=a+n*s.offset,d=r-this.getOffset(t.value),u=r-this.getOffset(s.value);if(t.offset===s.offset){const e=lh.DashSize;if(Math.abs(u-d)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{const t=Math.max(d,u);let s=Math.min(d,u);for(;t>s;)o.moveTo(l,s),o.lineTo(l,s+e),s+=2*e}o.stroke()}else if(t.value===s.value){const e=lh.DashSize;if(Math.abs(c-l)/(2*e)<1)o.moveTo(l,d),o.lineTo(c,u);else{let t=Math.max(l,c);const s=Math.min(l,c);for(;t>s;)o.moveTo(t,d),o.lineTo(t-e,d),t-=2*e}o.stroke()}else o.moveTo(l,d),o.lineTo(c,u);const p=this.renderer.resources;if(e&&!this._beat.isContinuedWhammy&&!this._isSimpleDip){let e=d;e-=p.tablatureFont.size+2,this.renderer.settings.notation.isNotationElementVisible(T.ZerosOnDiveWhammys)&&o.fillText("0",l,e),h&&(e-=p.tablatureFont.size+2,o.fillText(h,l,e))}let g=Math.abs(s.value);if((0!==g||this.renderer.settings.notation.isNotationElementVisible(T.ZerosOnDiveWhammys)&&!this._isSimpleDip)&&t.value!==s.value){let e="";if(s.value<0&&(e+="-"),g>=4){const t=g/4|0;e+=t,g-=4*t}else 0===g&&(e+="0");g>0&&(e+=hh.getFractionSign(g));let a=0;this._isSimpleDip?a=Math.min(d,u)-p.tablatureFont.size-2:(a=t.offset===s.offset?Math.min(d,u):u,a-=p.tablatureFont.size+2,i&&i.value>s.value&&(a-=2));const r=c;o.fillText(e,r,a)}}}lh.TopOffsetSharedDataKey="tab.whammy.topoffset",lh.PerHalfSize=6,lh.DashSize=3;class ch extends nh{constructor(e){super(0,0),this._beat=e}doLayout(){const e=this.renderer.settings.notation.notationMode;switch(this._beat.whammyBarType){case te.None:case te.Custom:case te.Hold:return;case te.Dive:case te.PrediveDive:{const e=new rh(this._beat,!1);e.renderer=this.renderer;const t=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(const s of this._beat.notes)s.isTieOrigin||e.addGlyph(this.getBendNoteValue(s,t),t.value%2!=0,void 0);e.doLayout(),this.BendNoteHeads.push(e)}break;case te.Dip:if(e===k.SongBook){const e=this.renderer.resources;this.renderer.simpleWhammyOverflow=1.5*e.tablatureFont.size+ch.SimpleDipHeight+ch.SimpleDipPadding}else{const e=new rh(this._beat,!1);if(e.renderer=this.renderer,this.renderer.settings.notation.notationMode===k.GuitarPro){const t=this._beat.whammyBarPoints[1];for(const s of this._beat.notes)e.addGlyph(this.getBendNoteValue(s,this._beat.whammyBarPoints[1]),t.value%2!=0,void 0)}e.doLayout(),this.BendNoteHeads.push(e);const t=new rh(this._beat,!1);if(t.renderer=this.renderer,this.renderer.settings.notation.notationMode===k.GuitarPro){const e=this._beat.whammyBarPoints[this._beat.whammyBarPoints.length-1];for(const s of this._beat.notes)t.addGlyph(this.getBendNoteValue(s,e),e.value%2!=0,void 0)}t.doLayout(),this.BendNoteHeads.push(t)}case te.Predive:}super.doLayout()}paint(e,t,s){const i=this._beat;switch(i.whammyBarType){case te.None:case te.Custom:return}const a=this.renderer.settings.notation.notationMode,r=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,i.voice.bar),n=hn.beat(s,ds.StandardNotationEffects,i);try{const n=e+r.x+r.getBeatX(i,Ki.MiddleNotes),o=this.getTieDirection(i,r);let h=1===this._beat.notes.length?o:se.Up;const l=s.textAlign,c=Dr.Heights.get(G.NoteheadBlack);for(let l=0;l<i.notes.length;l++){const d=i.notes[l],u=hn.note(s,ee.StandardNotationEffects,d);try{let u=t+r.y;l>0&&l>=(this._beat.notes.length/2|0)&&(h=se.Down),h===se.Down?u+=r.getNoteY(d,Qi.Bottom):u+=r.getNoteY(d,Qi.Top);let p=e+r.x;i.isLastOfVoice?p+=r.width:p+=r.getBeatX(i,Ki.EndBeat),p-=8;const g=i.whammyStyle===f.Gradual&&0===l?"grad.":"";let m=null;d.isTieOrigin&&(m=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,d.tieDestination.beat.voice.bar),m&&m.staff===r.staff?p=e+m.x+m.getBeatX(d.tieDestination.beat,Ki.MiddleNotes):m=null);let y=c*Lr.GraceScale*.5;h===se.Up&&(y=-y);const b=i.whammyBarPoints.length>0?this.getBendNoteValue(d,i.whammyBarPoints[i.whammyBarPoints.length-1]):0;let S=0,_=!1;switch(this.BendNoteHeads.length>0&&this.BendNoteHeads[0].containsNoteValue(b)?(S=this.BendNoteHeads[0].getNoteValueY(b)+y,_=!0):m&&(d.isTieOrigin&&d.tieDestination.beat.hasWhammyBar||d.beat.isContinuedWhammy)?(S=t+m.y+m.getNoteY(d.tieDestination,Qi.Top),_=!0,h===se.Down&&(S+=c)):d.isTieOrigin&&(S=m?t+m.y+m.getNoteY(d.tieDestination,Qi.Top):u,h===se.Down&&(S+=c)),i.whammyBarType){case te.Hold:d.isTieOrigin&&Yo.paintTie(s,1,n,u,p,S,o===se.Down,22,4);break;case te.Dive:if(0===l){this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset;const e=this.BendNoteHeads[0].y;this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.BendNoteHeads[0].containsNoteValue(b)&&(S-=e,S+=this.BendNoteHeads[0].y)}_?this.drawBendSlur(s,n,u,p,S,h===se.Down,1,g):d.isTieOrigin&&Yo.paintTie(s,1,n,u,p,S,o===se.Down,22,4);break;case te.Dip:if(a===k.SongBook){if(0===l){const i=e+r.x+r.getBeatX(this._beat,Ki.OnNotes)-2,a=e+r.x+r.getBeatX(this._beat,Ki.PostNotes)+2,n=(i+a)/2,o=((this._beat.whammyBarPoints[1].value-this._beat.whammyBarPoints[0].value)/4|0).toString();s.font=this.renderer.resources.tablatureFont,s.fillText(o,n,t+this.y);const h=t+this.y+s.font.size+2,l=h+ch.SimpleDipHeight;this._beat.whammyBarPoints[1].value>this._beat.whammyBarPoints[0].value?(s.moveTo(i,l),s.lineTo(n,h),s.lineTo(a,l)):(s.moveTo(i,h),s.lineTo(n,l),s.lineTo(a,h)),s.stroke()}d.isTieOrigin&&Yo.paintTie(s,1,n,u,p,S,o===se.Down,22,4)}else{const e=(n+p)/2;this.BendNoteHeads[0].x=e-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s);const a=this.getBendNoteValue(d,i.whammyBarPoints[1]),o=this.BendNoteHeads[0].getNoteValueY(a)+y;this.drawBendSlur(s,n,u,e,o,h===se.Down,1,g),this.BendNoteHeads[1].x=p-this.BendNoteHeads[1].noteHeadOffset,this.BendNoteHeads[1].y=t+r.y,this.BendNoteHeads[1].paint(0,0,s),S=this.BendNoteHeads[1].getNoteValueY(b)+y,this.drawBendSlur(s,e,o,p,S,h===se.Down,1,g)}break;case te.PrediveDive:case te.Predive:let c=e+r.x+r.getBeatX(d.beat,Ki.PreNotes);c+=r.getPreNotesGlyphForBeat(d.beat).prebendNoteHeadOffset;const m=t+r.y+r.getScoreY(r.accidentalHelper.getNoteLineForValue(d.displayValue-(d.beat.whammyBarPoints[0].value/2|0),!1))+y;this.drawBendSlur(s,c,m,n,u,h===se.Down,1,g),this.BendNoteHeads.length>0&&(this.BendNoteHeads[0].x=p-this.BendNoteHeads[0].noteHeadOffset,this.BendNoteHeads[0].y=t+r.y,this.BendNoteHeads[0].paint(0,0,s),this.drawBendSlur(s,n,u,p,S,h===se.Down,1,g))}}finally{u?.[Symbol.dispose]?.()}}s.textAlign=l}finally{n?.[Symbol.dispose]?.()}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}ch.SimpleDipHeight=2*lh.PerHalfSize,ch.SimpleDipPadding=2;class dh extends Fr{constructor(e,t,s){super(e,t),this.width=s}}class uh extends Er{constructor(e,t,s,i,a){super(e,t,a?Lr.GraceScale:1,s.getSymbol(i)),this._isGrace=a,this._articulation=s}paint(e,t,s){const i=s.color;this.colorOverride&&(s.color=this.colorOverride);const a=this._isGrace?1:0;s.fillMusicFontSymbol(e+this.x,t+this.y+a,this.glyphScale,this.symbol,!1),this._articulation.techniqueSymbol!==G.None&&this._articulation.techniqueSymbolPlacement===V.Middle&&s.fillMusicFontSymbol(e+this.x,t+this.y+a,this.glyphScale,this._articulation.techniqueSymbol,!1),s.color=i}doLayout(){super.doLayout(),0===this.width&&(this.height=Dr.Widths.get(G.NoteheadBlack)),0===this.height&&(this.height=Dr.Heights.get(G.NoteheadBlack))}}class ph extends Er{constructor(e,t){super(e,t,Lr.GraceScale,G.ArticStaccatoAbove)}paint(e,t,s){super.paint(e+3,t+5,s)}}class gh extends Er{constructor(e,t){super(e,t,.5,G.PictEdgeOfCymbal)}paint(e,t,s){super.paint(e-3,t+this.height,s)}}class mh extends Er{constructor(e,t,s=!1){super(e,t,Lr.GraceScale,G.GuitarGolpe),this.center=s}paint(e,t,s){super.paint(e,t+this.height,s)}}class fh extends Cr{constructor(){super(...arguments),this._strings=new Set}addString(e){this._strings.add(e)}doLayout(){const e=Dr.Widths.get(G.GuitarString0)*Ln.CircleNumberScale;this.height=(e+3)*this._strings.size,this.width=e}paint(e,t,s){const i=this.renderer.bar.staff.tuning.length;let a=0;const r=Dr.Widths.get(G.GuitarString0)*Ln.CircleNumberScale,n=Dr.Heights.get(G.NoteheadBlack);for(const o of this._strings){const h=i-o,l=G.GuitarString1+h;s.fillMusicFontSymbol(e+this.x+n/2,t+this.y+r+a,Ln.CircleNumberScale,l,!0),a+=r+3}}}class yh extends Cr{constructor(e,t,s,i,a){super(e,t),this.beatEffects=new Map,this.noteHeadElement=ee.SlashNoteHead,this.effectElement=ds.SlashEffects,this._isGrace=i,this._symbol=yh.getSymbol(s),this.beat=a}paint(e,t,s){const i=0===this.beat.notes.length?void 0:hn.note(s,this.noteHeadElement,this.beat.notes[0]);try{const i=this._isGrace?1:0,a=this._isGrace?Lr.GraceScale:1;s.fillMusicFontSymbol(e+this.x,t+this.y+i,a,this._symbol,!1),this.paintEffects(e,t,s)}finally{i?.[Symbol.dispose]?.()}}paintEffects(e,t,s){const i=hn.beat(s,this.effectElement,this.beat);try{for(const i of this.beatEffects.values())i.paint(e+this.x,t+this.y,s)}finally{i?.[Symbol.dispose]?.()}}doLayout(){const e=this._isGrace?Lr.GraceScale:1;this.width=Dr.Widths.get(this._symbol)*e,this.height=Dr.Heights.get(this._symbol)*e;let t=Dr.Heights.get(this._symbol);for(const e of this.beatEffects.values())e.y+=t,e.x+=this.width/2,e.renderer=this.renderer,t+=7,e.doLayout()}static getSymbol(e){switch(e){case D.QuadrupleWhole:case D.DoubleWhole:case D.Whole:return G.NoteheadSlashWhiteWhole;case D.Half:return G.NoteheadSlashWhiteHalf;default:return G.NoteheadSlashVerticalEnds}}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width,e+this.x)}}class bh extends Rn{constructor(){super(...arguments),this._collisionOffset=-1e3,this._skipPaint=!1,this.slash=null,this.noteHeads=null,this.restGlyph=null}get effectElement(){return ds.StandardNotationEffects}getNoteX(e,t){return this.noteHeads?this.noteHeads.getNoteX(e,t):0}buildBoundingsLookup(e,t,s){this.noteHeads&&this.noteHeads.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteY(e,t){return this.noteHeads?this.noteHeads.getNoteY(e,t):0}updateBeamingHelper(){if(this.noteHeads)this.noteHeads.updateBeamingHelper(this.container.x+this.x);else if(this.restGlyph){if(this.restGlyph.updateBeamingHelper(this.container.x+this.x),this.renderer.bar.isMultiVoice&&-1e3===this._collisionOffset){this._collisionOffset=this.renderer.helpers.collisionHelper.applyRestCollisionOffset(this.container.beat,this.restGlyph.y,this.renderer.getScoreHeight(1)),this.y+=this._collisionOffset;const e=this.renderer.helpers.collisionHelper.restDurationsByDisplayTime;e.has(this.container.beat.playbackStart)&&e.get(this.container.beat.playbackStart).has(this.container.beat.playbackDuration)&&e.get(this.container.beat.playbackStart).get(this.container.beat.playbackDuration)!==this.container.beat.id&&(this._skipPaint=!0)}}else this.slash&&this.slash.updateBeamingHelper(this.container.x+this.x)}paint(e,t,s){this._skipPaint||super.paint(e,t,s)}doLayout(){const 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===D.Whole&&1!==this.renderer.bar.staff.standardNotationLineCount&&3!==this.renderer.bar.staff.standardNotationLineCount&&(t-=2);const s=new sh(0,e.getScoreY(t),this.container.beat.duration);if(this.restGlyph=s,s.beat=this.container.beat,s.beamingHelper=this.beamingHelper,this.addNormal(s),this.renderer.bar.isMultiVoice)if(0===this.container.beat.voice.index){const t=pn.computeLineHeightsForRest(this.container.beat.duration),i=s.y-e.getScoreHeight(t[0]),a=s.y+e.getScoreHeight(t[1]);this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,i,a)}else this.renderer.helpers.collisionHelper.registerRest(this.container.beat);if(this.beamingHelper&&this.beamingHelper.applyRest(this.container.beat,t),this.container.beat.dots>0){this.addNormal(new dh(0,0,5));for(let e=0;e<this.container.beat.dots;e++){const e=new nn(0,0);e.renderer=this.renderer,this.createBeatDot(t,e),this.addEffect(e)}}}else{if(this.container.beat.slashed){const t=this.container.beat.graceType!==R.None,s=(e.heightLineCount-1)/2,i=e.getLineY(s),a=new yh(0,i,this.container.beat.duration,t,this.container.beat);a.noteHeadElement=ee.StandardNotationNoteHead,a.effectElement=ds.StandardNotationEffects,this.slash=a,a.beat=this.container.beat,a.beamingHelper=this.beamingHelper,this.addNormal(a)}else{const e=new th;this.noteHeads=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;const t=new Ko(!1);t.renderer=this.renderer;for(const e of this.container.beat.notes)e.isVisible&&(this.createNoteGlyph(e),t.addParenthesis(e));this.addNormal(e),t.isEmpty||(this.addNormal(new dh(0,0,4*(this.container.beat.graceType!==R.None?Lr.GraceScale:1))),this.addEffect(t))}if(this.container.beat.hasWhammyBar){const e=new ch(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.dots>0){this.addNormal(new dh(0,0,5));for(let t=0;t<this.container.beat.dots;t++){const t=new nn(0,0);t.renderer=this.renderer;for(const s of this.container.beat.notes){this.createBeatDot(e.getNoteLine(s),t).colorOverride=hn.noteColor(e.resources,ee.StandardNotationEffects,s)}this.addEffect(t)}}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.slash&&(this.centerX=this.slash.x+this.slash.width/2)}createBeatDot(e,t){const s=this.renderer,i=new Uo(0,s.getScoreY(e),1.5);return t.addGlyph(i),i}createNoteHeadGlyph(e){const t=this.container.beat.graceType!==R.None,s=e.style;if(void 0!==s?.noteHead){const i=new Lr(0,0,e.beat.duration,t);return i.symbol=s.noteHead,s.noteHeadCenterOnStem&&(i.centerOnStem=!0),i}if(e.beat.voice.bar.staff.isPercussion){const s=Bt.getArticulation(e);if(s)return new uh(0,0,s,e.beat.duration,t);wt.warning("Rendering",`No articulation found for percussion instrument ${e.percussionArticulation}`)}return e.isDead?new Xo(0,0,t):e.beat.graceType===R.BendGrace?new Lr(0,0,D.Quarter,!0):e.harmonicType===H.Natural?new Jo(0,0,e.beat.duration,t):new Lr(0,0,e.beat.duration,t)}createNoteGlyph(e){if(e.beat.graceType===R.BendGrace&&!e.hasBend)return;const t=this.renderer,s=this.createNoteHeadGlyph(e);s.colorOverride=hn.noteColor(t.resources,ee.StandardNotationNoteHead,e);let i=t.getNoteLine(e);if(s.y=t.getScoreY(i),this.noteHeads.addNoteGlyph(s,e,i),e.harmonicType!==H.None&&e.harmonicType!==H.Natural){const a=e.displayValue+e.harmonicPitch,r=new Jo(0,0,e.beat.duration,this.container.beat.graceType!==R.None);r.colorOverride=s.colorOverride,i=t.accidentalHelper.getNoteLineForValue(a,!1),r.y=t.getScoreY(i),this.noteHeads.addNoteGlyph(r,e,i)}const a=this.noteHeads.belowBeatEffects,r=this.noteHeads.aboveBeatEffects;if(e.isStaccato&&!a.has("Staccato")&&a.set("Staccato",new ph(0,0)),e.accentuated!==u.Normal||a.has("Accent")||a.set("Accent",new zo(0,0,e)),e.accentuated!==u.Heavy||a.has("HAccent")||a.set("HAccent",new zo(0,0,e)),e.accentuated!==u.Tenuto||a.has("Tenuto")||a.set("Tenuto",new zo(0,0,e)),e.showStringNumber&&e.isStringed){let t;r.has("StringNumber")?t=r.get("StringNumber"):(t=new fh(0,0),r.set("StringNumber",t)),t.addString(e.string)}if(e.isPercussion){const t=Bt.getArticulation(e);if(t&&t.techniqueSymbolPlacement!==V.Middle){const e=t.techniqueSymbolPlacement===V.Top?this.noteHeads.aboveBeatEffects:this.noteHeads.belowBeatEffects;switch(t.techniqueSymbol){case G.PictEdgeOfCymbal:e.set("PictEdgeOfCymbal",new gh(0,0));break;case G.ArticStaccatoAbove:e.set("ArticStaccatoAbove",new ph(0,0));break;case G.StringsUpBow:e.set("StringsUpBow",new wo(0,0,Q.Up));break;case G.StringsDownBow:e.set("StringsDownBow",new wo(0,0,Q.Down));break;case G.GuitarGolpe:e.set("GuitarGolpe",new mh(0,0))}}}}}class Sh extends Fr{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=this._beat.brushType===b.ArpeggioUp||this._beat.brushType===b.ArpeggioDown?10:0}paint(e,t,s){if(this._beat.brushType===b.ArpeggioUp||this._beat.brushType===b.ArpeggioDown){const i=this.renderer,a=i.lineOffset,r=t+this.y+(i.getNoteY(this._beat.maxNote,Qi.Bottom)-a),n=t+this.y+i.getNoteY(this._beat.minNote,Qi.Top)+a,o=e+this.x+this.width/2,h=8,l=new No(0,0,j.Slight,1.2,!0);l.renderer=this.renderer,l.doLayout();const c=-l.height/2;if(this._beat.brushType===b.ArpeggioUp){const t=r+h,i=n-h;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5,i,-90),l.paint(0,c,s),s.endRotate(),s.beginPath(),s.moveTo(o,n),s.lineTo(o+h/2,n-h),s.lineTo(o-h/2,n-h),s.closePath(),s.fill()}else if(this._beat.brushType===b.ArpeggioDown){const t=r+h,i=n;l.width=Math.abs(i-t),s.beginRotate(e+this.x+5,t,90),l.paint(0,c,s),s.endRotate(),s.beginPath(),s.moveTo(o,r),s.lineTo(o+h/2,r+h),s.lineTo(o-h/2,r+h),s.closePath(),s.fill()}}}}class _h{constructor(e,t){this.line=0,this.line=e,this.text=t}}class wh extends nn{constructor(){super(0,0),this._infos=new Map}get isEmpty(){return 0===this._infos.size}addFingers(e){const t=this.renderer.settings;if(t.notation.fingeringMode!==B.ScoreDefault&&t.notation.fingeringMode!==B.ScoreForcePiano)return;const s=Be.fingerToString(this.renderer.settings,e.beat,e.leftHandFinger,!0);s&&this.addFinger(e,s);const i=Be.fingerToString(this.renderer.settings,e.beat,e.rightHandFinger,!1);i&&this.addFinger(e,i)}addFinger(e,t){const s=this.renderer,i=s.getNoteLine(e);if(this._infos.has(i)){this._infos.get(i).text+=t}else{const a=new _h(i,t);a.color=hn.noteColor(s.resources,ee.StandardNotationEffects,e),this._infos.set(i,a)}}doLayout(){const e=this.renderer;for(const[t,s]of this._infos){const t=new Bn(0,0,s.text,e.resources.inlineFingeringFont,W.Left,V.Middle);t.colorOverride=s.color,t.renderer=e,t.y=e.getScoreY(s.line),t.doLayout(),this.addGlyph(t),this.width=Math.max(this.width,t.width)}}}class Bh extends An{constructor(){super(...arguments),this._prebends=null,this.accidentals=null}get prebendNoteHeadOffset(){return this._prebends?this._prebends.x+this._prebends.noteHeadOffset:0}get effectElement(){return ds.StandardNotationEffects}doLayout(){if(!this.container.beat.isRest){const e=new ah;e.renderer=this.renderer;const t=new wh;t.renderer=this.renderer;const s=new Ko(!0);s.renderer=this.renderer;const i=new rh(this.container.beat,!0);this._prebends=i,i.renderer=this.renderer;for(const a of this.container.beat.notes){const r=hn.noteColor(this.renderer.resources,ee.StandardNotationEffects,a);if(a.isVisible){if(a.hasBend)switch(a.bendType){case y.PrebendBend:case y.Prebend:case y.PrebendRelease:i.addGlyph(a.displayValue-(a.bendPoints[0].value/2|0),!1,r)}else if(a.beat.hasWhammyBar)switch(a.beat.whammyBarType){case te.PrediveDive:case te.Predive:this._prebends.addGlyph(a.displayValue-(a.beat.whammyBarPoints[0].value/2|0),!1,r)}this.createAccidentalGlyph(a,e),s.addParenthesis(a),t.addFingers(a)}}i.isEmpty||(this.addEffect(i),this.addNormal(new dh(0,0,4*(this.container.beat.graceType!==R.None?Lr.GraceScale:1)))),this.container.beat.brushType!==b.None&&(this.addEffect(new Sh(this.container.beat)),this.addNormal(new dh(0,0,4))),t.isEmpty||(this.isEmpty||this.addNormal(new dh(0,0,2*(this.container.beat.graceType!==R.None?Lr.GraceScale:1))),this.addEffect(t),this.addNormal(new dh(0,0,2*(this.container.beat.graceType!==R.None?Lr.GraceScale:1)))),s.isEmpty||(this.addEffect(s),this.addNormal(new dh(0,0,4*(this.container.beat.graceType!==R.None?Lr.GraceScale:1)))),e.isEmpty||(this.accidentals=e,this.isEmpty||this.addNormal(new dh(0,0,2*(this.container.beat.graceType!==R.None?Lr.GraceScale:1))),this.addNormal(e),this.addNormal(new dh(0,0,2*(this.container.beat.graceType!==R.None?Lr.GraceScale:1))))}super.doLayout()}createAccidentalGlyph(e,t){const s=this.renderer;let i=s.accidentalHelper.applyAccidental(e),a=s.getNoteLine(e);const r=this.container.beat.graceType!==R.None,n=hn.noteColor(s.resources,ee.StandardNotationAccidentals,e),o=r?Lr.GraceScale:1;if(i!==p.None){const e=new Vo(0,s.getScoreY(a),i,o);e.colorOverride=n,e.renderer=this.renderer,t.addGlyph(e)}if(e.harmonicType!==H.None&&e.harmonicType!==H.Natural){const h=e.displayValue+e.harmonicPitch;i=s.accidentalHelper.applyAccidentalForValue(e.beat,h,r,!1),a=s.accidentalHelper.getNoteLineForValue(h,!1);const l=new Vo(0,s.getScoreY(a),i,o);l.colorOverride=n,l.renderer=this.renderer,t.addGlyph(l)}}}class kh extends nn{constructor(e,t,s,i,a,r){super(e,t),this._numerator=0,this._denominator=0,this.barSubElement=c.StandardNotationTimeSignature,this._numerator=s,this._denominator=i,this._isCommon=a,this._isFreeTime=r}paint(e,t,s){const i=hn.bar(s,this.barSubElement,this.renderer.bar);try{super.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}doLayout(){let e=0;const t=On.numberHeight;if(this._isFreeTime){const s=new $o(!0);s.renderer=this.renderer,s.y=-t,s.height=2*t,s.doLayout(),this.addGlyph(s),e+=s.width+10}if(this._isCommon&&2===this._numerator&&2===this._denominator){const t=new Er(e,0,this.commonScale,G.TimeSigCutCommon);this.addGlyph(t),super.doLayout()}else if(this._isCommon&&4===this._numerator&&4===this._denominator){const t=new Er(e,0,this.commonScale,G.TimeSigCommon);this.addGlyph(t),super.doLayout()}else{const s=new On(e,-t/2,this._numerator,this.numberScale),i=new On(e,t/2,this._denominator,this.numberScale);this.addGlyph(s),this.addGlyph(i),super.doLayout();const a=this.width-e;s.x=e+(a-s.width)/2,i.x=e+(a-i.width)/2}if(this._isFreeTime){const e=new $o(!1);e.renderer=this.renderer,e.x=this.width+13,e.y=-t,e.height=2*t,e.doLayout(),this.addGlyph(e),this.width=e.x+e.width}}}class Th extends kh{get commonScale(){return 1}get numberScale(){return 1}}class Nh extends nh{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)return;const t=hn.noteColor(this.renderer.resources,ee.StandardNotationEffects,e);switch(e.bendType){case y.Bend:case y.PrebendRelease:case y.PrebendBend:{let s=this._endNoteGlyph;s||(s=new rh(e.beat,!1),s.renderer=this.renderer,this._endNoteGlyph=s,this.BendNoteHeads.push(s));const i=e.bendPoints[e.bendPoints.length-1];s.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0,t)}break;case y.Release:if(!e.isTieOrigin){let s=this._endNoteGlyph;s||(s=new rh(e.beat,!1),s.renderer=this.renderer,this._endNoteGlyph=s,this.BendNoteHeads.push(s));const i=e.bendPoints[e.bendPoints.length-1];s.addGlyph(this.getBendNoteValue(e,i),i.value%2!=0,t)}break;case y.BendRelease:{let s=this._middleNoteGlyph;s||(s=new rh(e.beat,!1),this._middleNoteGlyph=s,s.renderer=this.renderer,this.BendNoteHeads.push(s));const i=e.bendPoints[1];s.addGlyph(this.getBendNoteValue(e,e.bendPoints[1]),i.value%2!=0,t);let a=this._endNoteGlyph;a||(a=new rh(e.beat,!1),a.renderer=this.renderer,this._endNoteGlyph=a,this.BendNoteHeads.push(a));const r=e.bendPoints[e.bendPoints.length-1];a.addGlyph(this.getBendNoteValue(e,r),r.value%2!=0,t)}}}paint(e,t,s){const i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._beat.voice.bar),a=e+i.x+i.getBeatX(this._beat,Ki.MiddleNotes);let r=e+i.x;this._beat.isLastOfVoice?r+=i.postBeatGlyphsStart:r+=i.getBeatX(this._beat.nextBeat,Ki.PreNotes),r-=8;const n=(a+r)/2;this._middleNoteGlyph&&(this._middleNoteGlyph.x=n-this._middleNoteGlyph.noteHeadOffset,this._middleNoteGlyph.y=t+i.y,this._middleNoteGlyph.paint(0,0,s)),this._endNoteGlyph&&(this._endNoteGlyph.x=r-this._endNoteGlyph.noteHeadOffset,this._endNoteGlyph.y=t+i.y,this._endNoteGlyph.paint(0,0,s)),this._notes.sort(((e,t)=>t.displayValue-e.displayValue));const o=this._beat.graceType===R.BendGrace?this._beat.nextBeat:this._beat;let h=1===this._notes.length?this.getTieDirection(o,i):se.Up;const l=Dr.Heights.get(G.NoteheadBlack);for(let o=0;o<this._notes.length;o++){const c=this._notes[o],d=hn.note(s,ee.StandardNotationEffects,c);try{o>0&&o>=(this._notes.length/2|0)&&(h=se.Down);let d=t+i.y+i.getNoteY(c,Qi.Top),u=l*Lr.GraceScale*.5;h===se.Down&&(d+=l);const p=c.bendStyle===f.Gradual?"grad.":"";if(c.isTieOrigin){const r=c.tieDestination,n=r?this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,r.beat.voice.bar):null;if(n&&n.staff===i.staff){const i=e+n.x+n.getBeatX(r.beat,Ki.MiddleNotes);let o=t+n.y+n.getNoteY(r,Qi.Top);h===se.Down&&(o+=l),c.bendType===y.Hold||c.bendType===y.Prebend?Yo.paintTie(s,1,a,d,i,o,h===se.Down,22,4):this.drawBendSlur(s,a,d,i,o,h===se.Down,1,p)}else{const r=e+i.x+i.width,n=c.tieDestination.realValue;i.accidentalHelper.applyAccidentalForValue(c.beat,n,!1,!0);const o=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(n,!1));c.bendType===y.Hold||c.bendType===y.Prebend?Yo.paintTie(s,1,a,d,r,o,h===se.Down,22,4):this.drawBendSlur(s,a,d,r,o,h===se.Down,1,p)}switch(c.bendType){case y.Prebend:case y.PrebendBend:case y.PrebendRelease:let r=e+i.x+i.getBeatX(c.beat,Ki.PreNotes);r+=i.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;const n=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+u;this.drawBendSlur(s,r,n,a,d,h===se.Down,1)}}else{h===se.Up&&(u=-u);let o=0,l=0;switch(c.bendType){case y.Bend:o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+u,this.drawBendSlur(s,a,d,r,l,h===se.Down,1,p);break;case y.BendRelease:const g=this.getBendNoteValue(c,c.bendPoints[1]),m=this._middleNoteGlyph.getNoteValueY(g)+u;this.drawBendSlur(s,a,d,n,m,h===se.Down,1,p),o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this._endNoteGlyph.getNoteValueY(o)+u,this.drawBendSlur(s,n,m,r,l,h===se.Down,1,p);break;case y.Release:this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+u,this.drawBendSlur(s,a,d,r,l,h===se.Down,1,p));break;case y.Prebend:case y.PrebendBend:case y.PrebendRelease:let f=e+i.x+i.getBeatX(c.beat,Ki.PreNotes);f+=i.getPreNotesGlyphForBeat(c.beat).prebendNoteHeadOffset;const b=t+i.y+i.getScoreY(i.accidentalHelper.getNoteLineForValue(c.displayValue-(c.bendPoints[0].value/2|0),!1))+u;this.drawBendSlur(s,f,b,a,d,h===se.Down,1),this.BendNoteHeads.length>0&&(o=this.getBendNoteValue(c,c.bendPoints[c.bendPoints.length-1]),l=this.BendNoteHeads[0].getNoteValueY(o)+u,this.drawBendSlur(s,a,d,r,l,h===se.Down,1,p))}}}finally{d?.[Symbol.dispose]?.()}}}getBendNoteValue(e,t){return e.displayValueWithoutBend+(t.value/2|0)}}class xh extends Yo{constructor(e,t,s=!1){super(e,t,s)}doLayout(){super.doLayout()}getBeamDirection(e,t){return e.isRest?se.Up:t.getBeatDirection(e)===se.Up?se.Down:se.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===se.Up?this.startNoteRenderer.getNoteY(this.startBeat.maxNote,Qi.Top):this.startNoteRenderer.getNoteY(this.startBeat.minNote,Qi.Bottom)}getEndY(){const e=this.endNoteRenderer;if(this.endBeat.isRest)return this.tieDirection===se.Up?e.getScoreY(9):e.getScoreY(0);const t=this.startNoteRenderer.getBeatDirection(this.startBeat),s=e.getBeatDirection(this.endBeat);return t!==s&&this.startBeat.graceType===R.None?s===this.tieDirection?this.tieDirection===se.Up?e.getNoteY(this.endBeat.maxNote,Qi.TopWithStem):e.getNoteY(this.endBeat.minNote,Qi.BottomWithStem):this.tieDirection===se.Up?e.getNoteY(this.endBeat.maxNote,Qi.BottomWithStem):e.getNoteY(this.endBeat.minNote,Qi.TopWithStem):this.tieDirection===se.Up?e.getNoteY(this.endBeat.maxNote,Qi.Top):e.getNoteY(this.endBeat.minNote,Qi.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startBeat,Ki.MiddleNotes)}getEndX(){const e=this.endNoteRenderer.getBeatDirection(this.endBeat);return this.endNoteRenderer.getBeatX(this.endBeat,this.endBeat.duration>D.Whole&&e===this.tieDirection?Ki.Stem:Ki.MiddleNotes)}}class vh extends Fr{constructor(e,t,s,i){super(0,0),this._outType=t,this._inType=e,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.drawSlideOut(e,t,s)}paintSlideIn(e,t,s){const i=this.renderer;let a=e+i.x+i.getNoteX(this._startNote,Zi.Left)-2;const r=t+i.y+i.getNoteY(this._startNote,Qi.Center);let n=a-12,o=t+i.y;switch(this._inType){case q.IntoFromBelow:o+=i.getNoteY(this._startNote,Qi.Bottom);break;case q.IntoFromAbove:o+=i.getNoteY(this._startNote,Qi.Top);break;default:return}const h=this.getAccidentalsWidth(i,this._startNote.beat);n-=h,a-=h,this.paintSlideLine(s,!1,n,a,o,r)}getAccidentalsWidth(e,t){const s=e.getPreNotesGlyphForBeat(t);return s&&s.accidentals?s.accidentals.width:0}drawSlideOut(e,t,s){const i=this.renderer;let a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case K.Shift:case K.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,Ki.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,Qi.Center),this._startNote.slideTarget){const s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,Ki.PreNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,Qi.Center)):(n=e+i.x+i.width,o=r),this._startNote.slideTarget.realValue>this._startNote.realValue?(r+=2,o-=2):(r-=2,o+=2)}else n=e+i.x+this._parent.x,o=r;break;case K.OutUp:a=e+i.x+i.getNoteX(this._startNote,Zi.Right)+2,r=t+i.y+i.getNoteY(this._startNote,Qi.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,Qi.Top);break;case K.OutDown:a=e+i.x+i.getNoteX(this._startNote,Zi.Right)+2,r=t+i.y+i.getNoteY(this._startNote,Qi.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,Qi.Bottom);break;case K.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,Zi.Right)+4,r=t+i.y+i.getNoteY(this._startNote,Qi.Center),o=t+i.y+i.getNoteY(this._startNote,Qi.Top),n=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Ki.PreNotes)),h=!0;break;case K.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,Zi.Right)+4,r=t+i.y+i.getNoteY(this._startNote,Qi.Center),o=t+i.y+i.getNoteY(this._startNote,Qi.Bottom),n=e+i.x+i.width,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Ki.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){const t=new No(0,0,j.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;const n=i-s,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;const l=Math.asin(o/h)*(180/Math.PI);e.beginRotate(s,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(s,a),e.lineTo(i,r),e.stroke()}}class Ph extends xh{constructor(e,t,s=!1){super(e.beat,t.beat,s),this._startNote=e,this._endNote=t}getTieHeight(e,t,s,i){return Math.log2(s-e+1)*this.renderer.settings.notation.slurHeight}getStartY(){return this.isStartCentered()?this.tieDirection===se.Up?this.startNoteRenderer.getNoteY(this._startNote,Qi.Top):this.startNoteRenderer.getNoteY(this._startNote,Qi.Bottom):this.startNoteRenderer.getNoteY(this._startNote,Qi.Center)}getEndY(){return this.isEndCentered()?this.isEndOnStem()?this.tieDirection===se.Up?this.endNoteRenderer.getNoteY(this._endNote,Qi.TopWithStem):this.endNoteRenderer.getNoteY(this._endNote,Qi.BottomWithStem):this.tieDirection===se.Up?this.endNoteRenderer.getNoteY(this._endNote,Qi.Top):this.endNoteRenderer.getNoteY(this._endNote,Qi.Bottom):this.endNoteRenderer.getNoteY(this._endNote,Qi.Center)}isStartCentered(){return this._startNote===this._startNote.beat.maxNote&&this.tieDirection===se.Up||this._startNote===this._startNote.beat.minNote&&this.tieDirection===se.Down}isEndCentered(){return this._startNote.beat.graceType===R.None&&(this._endNote===this._endNote.beat.maxNote&&this.tieDirection===se.Up||this._endNote===this._endNote.beat.minNote&&this.tieDirection===se.Down)}isEndOnStem(){const e=this.endNoteRenderer;return this.startNoteRenderer.getBeatDirection(this.startBeat)!==e.getBeatDirection(this.endBeat)&&this.startBeat.graceType===R.None}getStartX(){return this.isStartCentered()?this.startNoteRenderer.getBeatX(this._startNote.beat,Ki.MiddleNotes):this.startNoteRenderer.getNoteX(this._startNote,Zi.Right)}getEndX(){return this.isEndCentered()?this.isEndOnStem()?this.endNoteRenderer.getBeatX(this._endNote.beat,Ki.Stem):this.endNoteRenderer.getNoteX(this._endNote,Zi.Center):this.endNoteRenderer.getBeatX(this._endNote.beat,Ki.PreNotes)}}class Fh extends Yo{constructor(e,t,s=!1){super(e?e.beat:null,t?t.beat:null,s),this.startNote=e,this.endNote=t}shouldDrawBendSlur(){return this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&!!this.startNote.bendOrigin&&this.startNote.isTieOrigin}doLayout(){super.doLayout()}getBeamDirection(e,t){return t.getBeatDirection(e)===se.Up?se.Down:se.Up}getStartY(){return this.startBeat.isRest?this.startNoteRenderer.getScoreY(9):this.tieDirection===se.Up?this.startNoteRenderer.getNoteY(this.startNote,Qi.Top):this.startNoteRenderer.getNoteY(this.startNote,Qi.Bottom)}getEndY(){const e=this.endNoteRenderer;return this.endBeat.isRest?this.tieDirection===se.Up?e.getScoreY(9):e.getScoreY(0):this.tieDirection===se.Up?e.getNoteY(this.endNote,Qi.Top):e.getNoteY(this.endNote,Qi.Bottom)}getStartX(){return this.startNoteRenderer.getBeatX(this.startNote.beat,Ki.PostNotes)}getEndX(){return this.endNoteRenderer.getBeatX(this.endNote.beat,Ki.PreNotes)}}class Ch extends Ir{constructor(){super(...arguments),this._bend=null,this._effectSlur=null,this._effectEndSlur=null}doLayout(){this._effectSlur=null,this._effectEndSlur=null,super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(e.isVisible){if(e.isTieOrigin&&!e.hasBend&&!e.beat.hasWhammyBar&&e.beat.graceType!==R.BendGrace&&e.tieDestination&&e.tieDestination.isVisible){const t=new Fh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&!e.tieOrigin.hasBend&&!e.beat.hasWhammyBar){const t=new Fh(e.tieOrigin,e,!0);this.addTie(t)}if(e.slideInType!==q.None||e.slideOutType!==K.None){const t=new vh(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.isSlurOrigin&&e.slurDestination&&e.slurDestination.isVisible){const t=new Ph(e,e.slurDestination,!1);this.addTie(t)}if(e.isSlurDestination){const t=new Ph(e.slurOrigin,e,!0);this.addTie(t)}if(!this._effectSlur&&e.isEffectSlurOrigin&&e.effectSlurDestination){const t=new Ph(e,e.effectSlurDestination,!1);this._effectSlur=t,this.addTie(t)}if(!this._effectEndSlur&&e.beat.isEffectSlurDestination&&e.beat.effectSlurOrigin){const t=this.onNotes.beamingHelper.direction,s=t===se.Up?e.beat.effectSlurOrigin.minNote:e.beat.effectSlurOrigin.maxNote,i=t===se.Up?e.beat.minNote:e.beat.maxNote,a=new Ph(s,i,!0);this._effectEndSlur=a,this.addTie(a)}if(e.hasBend){if(!this._bend){const t=new Nh(e.beat);this._bend=t,t.renderer=this.renderer,this.addTie(t)}this._bend.addBends(e)}if(this.beat.isLegatoOrigin){if(!this.beat.previousBeat||!this.beat.previousBeat.isLegatoOrigin){let e=this.beat.nextBeat;for(;e.nextBeat&&e.nextBeat.isLegatoDestination;)e=e.nextBeat;this.addTie(new xh(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 xh(e,this.beat,!0))}}}}class Dh extends Fr{doLayout(){this.width=1}paint(e,t,s){const i=e+this.x,a=t+this.y+this.renderer.topPadding,r=t+this.y+this.renderer.height-this.renderer.bottomPadding-a;this.paintInternal(i,a,r,s)}}class Eh extends Dh{paintInternal(e,t,s,i){i.fillRect(e,t,1,s)}}class Lh extends Dh{paintInternal(e,t,s,i){const a=e,r=this.renderer.getLineHeight(1);let n=t+.5*r+1;const o=t+s;for(;n<o;)i.fillCircle(a,n,1),n+=r}}class Mh extends Dh{paintInternal(e,t,s,i){const a=Mh.DashSize,r=e+.5,n=Math.ceil(s/2/a),o=t+s;if(i.beginPath(),n<1)i.moveTo(r,t),i.lineTo(r,o);else{let e=t;const h=(s-n*a)/(n-1);for(;e<o;)i.moveTo(r,e),i.lineTo(r,e+a),e+=a+h}i.stroke()}}Mh.DashSize=4;class Ih extends Dh{doLayout(){this.width=4}paintInternal(e,t,s,i){i.fillRect(e,t,this.width,s)}}class Ah extends Dh{paintInternal(e,t,s,i){const a=1.5,r=(t+(t+s))/2;i.fillCircle(e,r-4.5,a),i.fillCircle(e,r+4.5,a)}}class Rh extends Dh{paintInternal(e,t,s,i){const a=this.renderer,r=a.drawnLineCount-1;if(r<=2)return;const n=a.getLineHeight(1),o=2*n,h=r/2*n-o/2;i.fillRect(e,t+h,1,o)}}class Oh extends Dh{paintInternal(e,t,s,i){const a=this.renderer.getLineHeight(1),r=-a/2+1;i.fillRect(e,t+r,1,a)}}class Hh extends on{constructor(e){super(),this._isRight=e}doLayout(){const e=this.renderer.bar,t=e.masterBar,s=this._isRight?e.getActualBarLineRight():e.getActualBarLineLeft(0===this.renderer.index);let i=d.Automatic;if(!this._isRight){const e=this.renderer.previousRenderer;if(e&&e.staff===this.renderer.staff&&(i=e.bar.getActualBarLineRight(),s===i))return}switch(this._isRight&&t.isRepeatEnd&&(this.addGlyph(new Ah(0,0)),this.width+=3),s){case d.Dashed:this.addGlyph(new Mh(0,0));break;case d.Dotted:this.addGlyph(new Lh(0,0));break;case d.Heavy:i!==d.LightHeavy&&i!==d.HeavyHeavy&&this.addGlyph(new Ih(0,0));break;case d.HeavyHeavy:i!==d.LightHeavy&&i!==d.Heavy&&this.addGlyph(new Ih(0,0)),this.width+=3,this.addGlyph(new Ih(0,0));break;case d.HeavyLight:i!==d.LightHeavy&&i!==d.Heavy&&i!==d.HeavyHeavy&&this.addGlyph(new Ih(0,0)),this.width+=3,this.addGlyph(new Eh(0,0));break;case d.LightHeavy:i!==d.HeavyLight&&i!==d.Regular&&i!==d.LightLight&&this.addGlyph(new Eh(0,0)),this.width+=3,this.addGlyph(new Ih(0,0));break;case d.LightLight:i!==d.HeavyLight&&i!==d.Regular&&this.addGlyph(new Eh(0,0)),this.width+=3,this.addGlyph(new Eh(0,0));break;case d.None:break;case d.Regular:i!==d.HeavyLight&&i!==d.LightLight&&this.addGlyph(new Eh(0,0));break;case d.Short:this.addGlyph(new Rh(0,0));break;case d.Tick:this.addGlyph(new Oh(0,0))}this._isRight||t.isRepeatStart&&(this.width+=3,this.addGlyph(new Ah(0,0)))}paint(e,t,s){const i=this.renderer,a=hn.bar(s,i.barLineBarSubElement,this.renderer.bar,!0);try{super.paint(e,t,s)}finally{a?.[Symbol.dispose]?.()}}}class Wh extends Fr{constructor(e,t,s){super(e,t),this._count=0,this._count=0,this._count=s}doLayout(){this.width=0}paint(e,t,s){const i=hn.bar(s,this.renderer.repeatsBarSubElement,this.renderer.bar);try{const i=this.renderer.resources,a=s.textAlign;s.font=i.barNumberFont,s.textAlign=W.Right;const r=`x${this._count}`,n=s.measureText(r).width/1.5;s.fillText(r,e+this.x-n,t+this.y),s.textAlign=a}finally{i?.[Symbol.dispose]?.()}}}class Vh extends Fr{constructor(e,t,s){super(e,t),this._number=0,this._number=s}doLayout(){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.barNumberFont,this.width=this.renderer.scoreRenderer.canvas.measureText(this._number.toString()).width+5}paint(e,t,s){if(!this.renderer.staff.isFirstInSystem)return;const i=hn.bar(s,this.renderer.barNumberBarSubElement,this.renderer.bar,!0);try{const i=this.renderer.resources,a=s.textBaseline;s.textBaseline=V.Top,s.font=i.barNumberFont,s.fillText(this._number.toString(),e+this.x,t+this.y),s.textBaseline=a}finally{i?.[Symbol.dispose]?.()}}}class Gh extends Vn{constructor(){super(...arguments),this.firstLineY=0,this._startSpacing=!1,this.tupletSize=0}get lineOffset(){return this.lineSpacing+1}get tupletOffset(){return 10}get topGlyphOverflow(){const e=this.resources;return e.tablatureFont.size/2+.2*e.tablatureFont.size}get bottomGlyphOverflow(){const e=this.resources;return e.tablatureFont.size/2+.2*e.tablatureFont.size}initLineBasedSizes(){this.topPadding=this.topGlyphOverflow,this.bottomPadding=this.bottomGlyphOverflow,this.height=this.lineOffset*(this.heightLineCount-1)+this.topPadding+this.bottomPadding}updateSizes(){this.initLineBasedSizes(),this.adjustSizes(),this.updateFirstLineY(),super.updateSizes()}adjustSizes(){}updateFirstLineY(){const e=this.lineOffset*(this.heightLineCount-1),t=(this.drawnLineCount-1)*this.lineOffset;this.firstLineY=this.topPadding+(e-t)/2}doLayout(){this.initLineBasedSizes(),this.updateFirstLineY(),this.tupletSize=15+.3*this.resources.effectFont.size,super.doLayout()}getLineY(e){return this.firstLineY+this.getLineHeight(e)}getLineHeight(e){return this.lineOffset*e}paintBackground(e,t,s){super.paintBackground(e,t,s),this.paintStaffLines(e,t,s),this.paintSimileMark(e,t,s)}paintStaffLines(e,t,s){const i=hn.bar(s,this.staffLineBarSubElement,this.bar,!0);try{const i=[];for(let e=0,t=this.drawnLineCount;e<t;e++)i.push([]);this.additionalMultiRestBars||this.collectSpaces(i);for(const e of i)e.sort(((e,t)=>e[0]>t[0]?1:e[0]<t[0]?-1:0));const a=Math.ceil(this.width);for(let r=0;r<this.drawnLineCount;r++){const n=this.getLineY(r);let o=0;for(const a of i[r])s.fillRect(e+this.x+o,t+this.y+n|0,a[0]-o,Vn.StaffLineThickness),o=a[0]+a[1];s.fillRect(e+this.x+o,t+this.y+n|0,a-o,Vn.StaffLineThickness)}}finally{i?.[Symbol.dispose]?.()}}collectSpaces(e){}createStartSpacing(){if(this._startSpacing)return;const e=0===this.index?this.settings.display.firstStaffPaddingLeft:this.settings.display.staffPaddingLeft;this.addPreBeatGlyph(new dh(0,0,e)),this._startSpacing=!0}paintTuplets(e,t,s,i,a=!1){for(const r of this.bar.voices)if(this.hasVoiceContainer(r)){const n=this.getVoiceContainer(r);for(const r of n.tupletGroups)this.paintTupletHelper(e+this.beatGlyphsStart,t,s,r,i,a)}}getTupletBeamDirection(e){return this.getBeamDirection(e)}paintTupletHelper(e,t,s,i,a,r){const n=this.resources,o=s.textAlign,h=s.textBaseline;let l;s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,s.textAlign=W.Center,s.textBaseline=V.Middle;const c=i.beats[0].tupletNumerator,d=i.beats[0].tupletDenominator;l=2===c&&3===d?"2":3===c&&2===d?"3":4===c&&6===d?"4":5===c&&4===d?"5":6===c&&4===d?"6":7===c&&4===d?"7":9===c&&8===d?"9":10===c&&8===d?"10":11===c&&8===d?"11":12===c&&8===d?"12":13===c&&8===d?"13":`${c}:${d}`;let u=this.tupletOffset,p=5;const g=hn.beat(s,a,i.beats[0]);try{if(1!==i.beats.length&&i.isFull){const a=i.beats[0],o=i.beats[i.beats.length-1];let h=null,c=null;for(let e=0;e<i.beats.length;e++)if(!i.beats[e].isRest){h=i.beats[e];break}for(let e=i.beats.length-1;e>=0;e--)if(!i.beats[e].isRest){c=i.beats[e];break}let d=!1;h||(h=a,d=!0),c||(c=o);const g=this.helpers.beamHelperLookup[i.voice.index].get(a.index),m=this.helpers.beamHelperLookup[i.voice.index].get(o.index),f=g.getBeatLineX(a),y=m.getBeatLineX(o),b=this.helpers.beamHelperLookup[i.voice.index].get(h.index),S=this.helpers.beamHelperLookup[i.voice.index].get(c.index),_=this.getTupletBeamDirection(g);let w=this.calculateBeamYWithDirection(b,f,_),B=this.calculateBeamYWithDirection(S,y,_);d&&(w=Math.max(w,B),B=w),s.font=n.effectFont;const k=s.measureText(l).width,T=3,N=(f+y)/2,x=N-k/2-T,v=N+k/2+T,P=(B-w)/(y-f),F=w-P*f,C=P*x+F,D=P*N+F,E=P*v+F;_===se.Down&&(u*=-1,p*=-1),s.beginPath(),s.moveTo(e+this.x+f,t+this.y+w-u|0),r?s.quadraticCurveTo(e+this.x+(x+f)/2,t+this.y+C-u-p|0,e+this.x+x,t+this.y+C-u-p|0):(s.lineTo(e+this.x+f,t+this.y+w-u-p|0),s.lineTo(e+this.x+x,t+this.y+C-u-p|0)),s.stroke(),s.beginPath(),s.moveTo(e+this.x+v,t+this.y+E-u-p|0),r?s.quadraticCurveTo(e+this.x+(y+v)/2,t+this.y+E-u-p|0,e+this.x+y,t+this.y+B-u|0):(s.lineTo(e+this.x+y,t+this.y+B-u-p|0),s.lineTo(e+this.x+y,t+this.y+B-u|0)),s.stroke(),s.fillText(l,e+this.x+N,t+this.y+D-u-p)}else for(const a of i.beats){const r=this.helpers.beamHelperLookup[i.voice.index].get(a.index);if(!r)continue;const o=this.getTupletBeamDirection(r),h=r.getBeatLineX(a);let c=this.calculateBeamYWithDirection(r,h,o);o===se.Down?c+=u+p:c-=u+p,s.font=n.effectFont,s.fillText(l,e+this.x+h,t+this.y+c)}s.textAlign=o,s.textBaseline=h}finally{g?.[Symbol.dispose]?.()}}paintBeams(e,t,s,i,a){for(const r of this.helpers.beamHelpers)for(const n of r)this.paintBeamHelper(e+this.beatGlyphsStart,t,s,n,i,a)}drawBeamHelperAsFlags(e){return 1===e.beats.length}paintBeamHelper(e,t,s,i,a,r){s.color=0===i.voice.index?this.resources.mainGlyphColor:this.resources.secondaryGlyphColor,i.isRestBeamHelper||(this.drawBeamHelperAsFlags(i)?this.paintFlag(e,t,s,i,a):this.paintBar(e,t,s,i,r))}shouldPaintFlag(e,t){return e.graceType!==R.BendGrace&&(!e.deadSlapped&&(!!t.hasBeatLineX(e)&&((e.graceType===R.None||this.settings.notation.notationMode!==k.SongBook)&&(e.duration!==D.Whole&&e.duration!==D.DoubleWhole&&e.duration!==D.QuadrupleWhole))))}paintFlag(e,t,s,i,a){for(const r of i.beats){if(!this.shouldPaintFlag(r,i))continue;const n=r.graceType!==R.None,o=n?Lr.GraceScale:1,h=this.getFlagStemSize(i.shortestDuration),l=i.getBeatLineX(r),c=this.getBeamDirection(i);let d=this.getFlagTopY(r,c),u=this.getFlagBottomY(r,c),p=0;if(c===se.Down?(u+=h*o,p=u):(d-=h*o,p=d),!i.hasLine(!0,r))continue;this.paintBeamingStem(r,t+this.y,e+this.x+l,t+this.y+d,t+this.y+u,s);const g=hn.beat(s,a,r);try{if(r.graceType===R.BeforeBeat){const i=15,a=12;s.beginPath(),c===se.Down?(s.moveTo(e+this.x+l-a/2,t+this.y+u-i),s.lineTo(e+this.x+l+a/2,t+this.y+u)):(s.moveTo(e+this.x+l-a/2,t+this.y+d+i),s.lineTo(e+this.x+l+a/2,t+this.y+d)),s.stroke()}if(i.hasFlag(!0,r)){const i=new Mr(l-.5,p,r.duration,c,n);i.renderer=this,i.doLayout(),i.paint(e+this.x,t+this.y,s)}}finally{g?.[Symbol.dispose]?.()}}}getFlagStemSize(e,t=!1){let s=0;switch(e){case D.QuadrupleWhole:case D.Half:case D.Quarter:case D.Eighth:case D.Sixteenth:case D.ThirtySecond:case D.SixtyFourth:case D.OneHundredTwentyEighth:case D.TwoHundredFiftySixth:s=3;break;default:s=t?3:0}return this.getLineHeight(s)}recreatePreBeatGlyphs(){this._startSpacing=!1,super.recreatePreBeatGlyphs()}calculateBeamY(e,t){return this.calculateBeamYWithDirection(e,t,this.getBeamDirection(e))}createPreBeatGlyphs(){super.createPreBeatGlyphs(),this.addPreBeatGlyph(new Hh(!1)),this.createLinePreBeatGlyphs(),this.addPreBeatGlyph(new Vh(0,this.getLineHeight(-.25),this.bar.index+1))}createPostBeatGlyphs(){super.createPostBeatGlyphs();const e=this.lastBar;this.addPostBeatGlyph(new Hh(!0)),e.masterBar.isRepeatEnd&&e.masterBar.repeatCount>2&&this.addPostBeatGlyph(new Wh(0,this.getLineHeight(-.25),this.bar.masterBar.repeatCount))}paintBar(e,t,s,i,a){for(let r=0,n=i.beats.length;r<n;r++){const n=i.beats[r];if(!i.hasBeatLineX(n)||n.deadSlapped)continue;const o=n.graceType!==R.None?Lr.GraceScale:1,h=i.getBeatLineX(n),l=this.getBeamDirection(i),c=t+this.y+this.getBarLineStart(n,l),d=t+this.y+this.calculateBeamY(i,h);this.paintBeamingStem(n,t+this.y,e+this.x+h,c,d,s);const u=hn.beat(s,a,n);try{let a=d;l===se.Down?a+=2*s.font.size:0!==r&&(a-=1.5*s.font.size);const c=6*o;let u=(Vn.BeamSpacing+Vn.BeamThickness)*o,p=Vn.BeamThickness*o;const g=Be.getIndex(n.duration)-2,m=t+this.y;l===se.Down&&(u=-u,p=-p);for(let t=0;t<g;t++){let a=0,o=0,l=0,d=0;const f=m+t*u;if(r<i.beats.length-1){const u=pn.isFullBarJoin(n,i.beats[r+1],t);if(t===g-1&&u&&n.beamingMode===cs.ForceSplitOnSecondaryToNext)a=h,o=a+c,l=f+this.calculateBeamY(i,a),d=f+this.calculateBeamY(i,o),Gh.paintSingleBar(s,e+this.x+a,l,e+this.x+o,d,p),o=i.getBeatLineX(i.beats[r+1]),a=o-c,l=f+this.calculateBeamY(i,a),d=f+this.calculateBeamY(i,o),Gh.paintSingleBar(s,e+this.x+a,l,e+this.x+o,d,p);else{if(u)a=h,o=i.getBeatLineX(i.beats[r+1]);else{if(0!==r&&pn.isFullBarJoin(i.beats[r-1],n,t))continue;a=h,o=a+c}l=f+this.calculateBeamY(i,a),d=f+this.calculateBeamY(i,o),Gh.paintSingleBar(s,e+this.x+a,l,e+this.x+o,d,p)}}else r>0&&!pn.isFullBarJoin(n,i.beats[r-1],t)&&(a=h-c,o=h,l=f+this.calculateBeamY(i,a),d=f+this.calculateBeamY(i,o),Gh.paintSingleBar(s,e+this.x+a,l,e+this.x+o,d,p))}}finally{u?.[Symbol.dispose]?.()}}}static paintSingleBar(e,t,s,i,a,r){e.beginPath(),e.moveTo(t,s),e.lineTo(i,a),e.lineTo(i,a+r),e.lineTo(t,s+r),e.closePath(),e.fill()}}class zh extends on{paint(e,t,s){const i=hn.bar(s,c.StandardNotationKeySignature,this.renderer.bar);try{super.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}}class Uh extends Gh{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.beatEffectsMinY=null,this.beatEffectsMaxY=null,this.accidentalHelper=new Ci(this)}get repeatsBarSubElement(){return c.StandardNotationRepeats}get barNumberBarSubElement(){return c.StandardNotationBarNumber}get barLineBarSubElement(){return c.StandardNotationBarLines}get staffLineBarSubElement(){return c.StandardNotationStaffLine}get showMultiBarRest(){return!0}get lineSpacing(){return Vn.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return this.bar.staff.standardNotationLineCount}registerBeatEffectOverflows(e,t){const s=this.beatEffectsMinY;(null==s||e<s)&&(this.beatEffectsMinY=e);const i=this.beatEffectsMaxY;(null==i||t>i)&&(this.beatEffectsMaxY=t)}getScoreY(e){return super.getLineY(e/2)}getScoreHeight(e){return super.getLineHeight(e/2)}doLayout(){if(super.doLayout(),!this.bar.isEmpty&&this.accidentalHelper.maxLineBeat){const e=this.getScoreY(-2),t=this.getScoreY(10),s=this.simpleWhammyOverflow,i=this.beatEffectsMinY;if(null!==i){const t=e-i;t>0&&this.registerOverflowTop(t)}const a=this.beatEffectsMaxY;if(null!==a){const e=a-t;e>0&&this.registerOverflowBottom(e)}this.registerOverflowTop(s);let r=this.getScoreY(this.accidentalHelper.maxLine);const n=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.maxLineBeat);n.direction===se.Up&&(r-=this.getStemSize(n),n.hasTuplet&&(r-=this.tupletSize)),r<e&&this.registerOverflowTop(Math.abs(r)+s);let o=this.getScoreY(this.accidentalHelper.minLine);const h=this.helpers.getBeamingHelperForBeat(this.accidentalHelper.minLineBeat);h.direction===se.Down&&(o+=this.getStemSize(h),h.hasTuplet&&(o+=this.tupletSize)),o>t&&this.registerOverflowBottom(Math.abs(o)-t)}}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s,ds.StandardNotationFlags,ds.StandardNotationBeams),this.paintTuplets(e,t,s,ds.StandardNotationTuplet)}getSlashFlagY(e,t){let s=(this.heightLineCount-1)/2,i=0;switch(e){case D.QuadrupleWhole:case D.DoubleWhole:case D.Whole:i+=2;break;default:i+=1}t===se.Down?s+=i:s-=i;return this.getLineY(s)}getFlagTopY(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):this.getScoreY(this.accidentalHelper.getMinLine(e))}getFlagBottomY(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):this.getScoreY(this.accidentalHelper.getMaxLine(e))}getBeamDirection(e){return e.direction}getStemSize(e,t=!1){let s=1===e.beats.length?this.getFlagStemSize(e.shortestDuration,t):this.getBarStemSize(e.shortestDuration);return e.isGrace&&(s*=Lr.GraceScale),s}getBarStemSize(e){let t=0;switch(e){case D.QuadrupleWhole:case D.Half:case D.Quarter:case D.Eighth:case D.Sixteenth:t=6;break;case D.ThirtySecond:t=8;break;case D.SixtyFourth:case D.OneHundredTwentyEighth:t=9;break;case D.TwoHundredFiftySixth:t=10;break;default:t=0}return this.getScoreHeight(t)}get middleYPosition(){return this.getScoreY(this.bar.staff.standardNotationLineCount-1)}getNoteY(e,t){if(e.beat.slashed){const e=(this.heightLineCount-1)/2;return this.getLineY(e)}let s=super.getNoteY(e,t);if(Number.isNaN(s)){const t=Ci.computeLineWithoutAccidentals(this.bar,e);s=this.getScoreY(t)}return s}applyLayoutingInfo(){const e=super.applyLayoutingInfo();if(e&&this.bar.isMultiVoice){const e=this.getScoreY(-2),t=this.getScoreY(10),s=this.helpers.collisionHelper.getBeatMinMaxY();s[0]<e&&this.registerOverflowTop(Math.abs(s[0])),s[1]>t&&this.registerOverflowBottom(Math.abs(s[1])-t)}return e}calculateBeamYWithDirection(e,t,s){const i=this.getStemSize(e);if(!e.drawingInfos.has(s)){const t=new un;e.drawingInfos.set(s,t);const a=e.beats[0],r=e.beats[e.beats.length-1],n=e.isRestBeamHelper;t.startBeat=a,t.startX=e.getBeatLineX(a),t.startY=n?s===se.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===se.Up?this.getFlagTopY(a,s)-i:this.getFlagBottomY(a,s)+i,t.endBeat=r,t.endX=e.getBeatLineX(r),t.endY=n?s===se.Up?this.getScoreY(e.minRestLine):this.getScoreY(e.maxRestLine):s===se.Up?this.getFlagTopY(r,s)-i:this.getFlagBottomY(r,s)+i;const o=10;if(s===se.Down&&t.startY>t.endY&&t.startY-t.endY>o&&(t.endY=t.startY-o),s===se.Down&&t.endY>t.startY&&t.endY-t.startY>o&&(t.startY=t.endY-o),s===se.Up&&t.startY<t.endY&&t.endY-t.startY>o&&(t.endY=t.startY+o),s===se.Up&&t.endY<t.startY&&t.startY-t.endY>o&&(t.startY=t.endY+o),e.beats.length>1){if(s===se.Up){const s=this.getScoreY(this.accidentalHelper.getMinLine(e.beatOfHighestNote))-i,a=t.calcY(e.getBeatLineX(e.beatOfHighestNote))-s;a>0&&(t.startY-=a,t.endY-=a)}else{const s=this.getScoreY(this.accidentalHelper.getMaxLine(e.beatOfLowestNote))+i-t.calcY(e.getBeatLineX(e.beatOfLowestNote));s>0&&(t.startY+=s,t.endY+=s)}if(null!==e.minRestLine||null!==e.maxRestLine){const i=Be.getIndex(e.shortestDuration)-2,a=e.isGrace?Lr.GraceScale:1;let r=i*(Vn.BeamSpacing+Vn.BeamThickness)*a;if(r+=Vn.BeamSpacing,s===se.Up&&null!==e.minRestLine){const s=this.getScoreY(e.minRestLine)-r,i=t.calcY(e.getBeatLineX(e.beatOfMinRestLine))-s;i>0&&(t.startY-=i,t.endY-=i)}else if(s===se.Down&&null!==e.maxRestLine){const s=this.getScoreY(e.maxRestLine)+r-t.calcY(e.getBeatLineX(e.beatOfMaxRestLine));s>0&&(t.startY+=s,t.endY+=s)}}if(e.slashBeats.length>0)for(const a of e.slashBeats){const r=t.calcY(e.getBeatLineX(a));let n=this.getSlashFlagY(a.duration,s);s===se.Up?n-=i:s===se.Down&&(n+=i);const o=n-r;o>0&&(t.startY+=o,t.endY+=o)}}}return e.drawingInfos.get(s).calcY(t)}getBarLineStart(e,t){return e.slashed?this.getSlashFlagY(e.duration,t):t===se.Up?this.getScoreY(this.accidentalHelper.getMaxLine(e)):this.getScoreY(this.accidentalHelper.getMinLine(e))}createLinePreBeatGlyphs(){let e=!1;if(this.isFirstOfLine||this.bar.clef!==this.bar.previousBar.clef||this.bar.clefOttava!==this.bar.previousBar.clefOttava){let t=0;switch(this.bar.clef){case n.Neutral:t=this.bar.staff.standardNotationLineCount-1;break;case n.F4:t=2;break;case n.C3:t=4;break;case n.C4:t=2;break;case n.G2:t=6}this.createStartSpacing(),this.addPreBeatGlyph(new Go(0,this.getScoreY(t)+.5*Vn.StaffLineThickness,this.bar.clef,this.bar.clefOttava)),e=!0}(e||0===this.index&&this.bar.masterBar.keySignature!==x.C||this.bar.previousBar&&this.bar.masterBar.keySignature!==this.bar.previousBar.masterBar.keySignature)&&(this.createStartSpacing(),this.createKeySignatureGlyphs()),(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createKeySignatureGlyphs(){let e=0;const t=this.bar.masterBar.keySignature,s=this.bar.previousBar?this.bar.previousBar.masterBar.keySignature:0;switch(this.bar.clef){case n.Neutral:e=0;break;case n.G2:e=1;break;case n.F4:e=3;break;case n.C3:e=2;break;case n.C4:e=0}const i=new zh;i.renderer=this;const a=new Map,r=[];if(Be.keySignatureIsSharp(t))for(let s=0;s<Math.abs(t);s++){const t=Uh.SharpKsSteps[s]+e;r.push(new Vo(0,this.getScoreY(t),p.Sharp,1)),a.set(t,!0)}else for(let s=0;s<Math.abs(t);s++){const t=Uh.FlatKsSteps[s]+e;r.push(new Vo(0,this.getScoreY(t),p.Flat,1)),a.set(t,!0)}if(this.bar.masterBar.keySignature===x.C){const t=Math.abs(s),r=Be.keySignatureIsSharp(s)?Uh.SharpKsSteps:Uh.FlatKsSteps;for(let s=0;s<t;s++){const t=r[s]+e;a.has(t)||i.addGlyph(new Vo(0,this.getScoreY(r[s]+e),p.Natural,1))}}for(const e of r)i.addGlyph(e);this.addPreBeatGlyph(i)}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new dh(0,0,5));const e=this.bar.staff.standardNotationLineCount-1;this.addPreBeatGlyph(new Th(0,this.getScoreY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon,this.bar.masterBar.isFreeTime))}createVoiceGlyphs(e){for(const t of e.beats){const s=new Ch(t,this.getVoiceContainer(e));s.preNotes=new Bh,s.onNotes=new bh,this.addBeatGlyph(s)}}getNoteLine(e){return this.accidentalHelper.getNoteLine(e)}completeBeamingHelper(e){if(this.bar.isMultiVoice&&e.highestNoteInHelper&&e.lowestNoteInHelper){let t=this.getNoteY(e.highestNoteInHelper,Qi.Center),s=this.getNoteY(e.lowestNoteInHelper,Qi.Center),i=this.getStemSize(e);e.hasTuplet&&(i+=2*this.resources.effectFont.size),e.direction===se.Up?t-=i:s+=i;for(const i of e.beats)this.helpers.collisionHelper.reserveBeatSlot(i,t,s)}}paintBeamingStem(e,t,s,i,a,r){const n=hn.beat(r,ds.StandardNotationStem,e);try{r.lineWidth=Vn.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}finally{n?.[Symbol.dispose]?.()}}}Uh.StaffId="score",Uh.SharpKsSteps=[-1,2,-2,1,4,0,3],Uh.FlatKsSteps=[3,0,4,1,5,2,6];class Xh extends rn{get staffId(){return Uh.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new Uh(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showStandardNotation}}class Jh extends Fr{constructor(e,t,s,i){super(0,0),this._inType=e,this._outType=t,this._startNote=s,this._parent=i}doLayout(){this.width=0}paint(e,t,s){this.paintSlideIn(e,t,s),this.paintSlideOut(e,t,s)}paintSlideIn(e,t,s){const i=this.renderer;let a=0,r=0,n=0,o=0;switch(this._inType){case q.IntoFromBelow:n=e+i.x+i.getNoteX(this._startNote,Zi.Left)-2,o=t+i.y+i.getNoteY(this._startNote,Qi.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,Qi.Center)+3;break;case q.IntoFromAbove:n=e+i.x+i.getNoteX(this._startNote,Zi.Left)-2,o=t+i.y+i.getNoteY(this._startNote,Qi.Center),a=n-12,r=t+i.y+i.getNoteY(this._startNote,Qi.Center)-3;break;default:return}this.paintSlideLine(s,!1,a,n,r,o)}paintSlideOut(e,t,s){const i=this.renderer;let a=0,r=0,n=0,o=0,h=!1;switch(this._outType){case K.Shift:case K.Legato:if(a=e+i.x+i.getBeatX(this._startNote.beat,Ki.PostNotes)+2,r=t+i.y+i.getNoteY(this._startNote,Qi.Center),this._startNote.slideTarget){const s=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this._startNote.slideTarget.beat.voice.bar);s&&s.staff===i.staff?(n=e+s.x+s.getBeatX(this._startNote.slideTarget.beat,Ki.OnNotes)-2,o=t+s.y+s.getNoteY(this._startNote.slideTarget,Qi.Center)):(n=e+i.x+i.width,o=r),this._startNote.slideTarget.fret>this._startNote.fret?(r+=3,o-=3):(r-=3,o+=3)}else n=e+i.x+this._parent.x,o=r;break;case K.OutUp:a=e+i.x+i.getNoteX(this._startNote,Zi.Right)+2,r=t+i.y+i.getNoteY(this._startNote,Qi.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,Qi.Center)-3;break;case K.OutDown:a=e+i.x+i.getNoteX(this._startNote,Zi.Right)+2,r=t+i.y+i.getNoteY(this._startNote,Qi.Center),n=a+12,o=t+i.y+i.getNoteY(this._startNote,Qi.Center)+3;break;case K.PickSlideDown:a=e+i.x+i.getNoteX(this._startNote,Zi.Right)+4,r=t+i.y+i.getNoteY(this._startNote,Qi.Center),n=e+i.x+i.width,o=r+9,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Ki.PreNotes)),h=!0;break;case K.PickSlideUp:a=e+i.x+i.getNoteX(this._startNote,Zi.Right)+4,r=t+i.y+i.getNoteY(this._startNote,Qi.Center),n=e+i.x+i.width,o=r-9,this._startNote.beat.nextBeat&&this._startNote.beat.nextBeat.voice===this._startNote.beat.voice&&(n=e+i.x+i.getBeatX(this._startNote.beat.nextBeat,Ki.PreNotes)),h=!0;break;default:return}this.paintSlideLine(s,h,a,n,r,o)}paintSlideLine(e,t,s,i,a,r){if(t){const t=new No(0,0,j.Slight,1.2);t.renderer=this.renderer,t.doLayout(),a-=t.height/2;const n=i-s,o=(r-=t.height/2)-a,h=Math.sqrt(Math.pow(o,2)+Math.pow(n,2));t.width=n;const l=Math.asin(o/h)*(180/Math.PI);e.beginRotate(s,a,l),t.paint(0,0,e),e.endRotate()}else e.beginPath(),e.moveTo(s,a),e.lineTo(i,r),e.stroke()}}class Yh extends Yo{constructor(e,t,s=!1){super(e.beat,t.beat,s),this.startNote=e,this.endNote=t}getTieHeight(e,t,s,i){return this.startNote===this.endNote?15:super.getTieHeight(e,t,s,i)}getBeamDirection(e,t){return this.startNote===this.endNote?se.Up:Yh.getBeamDirectionForNote(this.startNote)}static getBeamDirectionForNote(e){return e.string>3?se.Up:se.Down}getStartY(){return this.startNote===this.endNote?this.startNoteRenderer.getNoteY(this.startNote,Qi.Center):this.tieDirection===se.Up?this.startNoteRenderer.getNoteY(this.startNote,Qi.Top):this.startNoteRenderer.getNoteY(this.startNote,Qi.Bottom)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Zi.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,Zi.Left):this.endNoteRenderer.getNoteX(this.endNote,Zi.Center)}}class $h extends Yh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=Yh.getBeamDirectionForNote(e),this._forSlide=s}getTieHeight(e,t,s,i){return Math.log(s-e+1)*this.renderer.settings.notation.slurHeight}tryExpand(e,t,s,i){if(this._forSlide!==s)return!1;if(this.forEnd!==i)return!1;if(this.startNote.beat.id!==e.beat.id)return!1;if(this.endNote.beat.id!==t.beat.id)return!1;if(this._direction!==Yh.getBeamDirectionForNote(e))return!1;switch(this._direction){case se.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 se.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,s){const i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar),a=this.getBeamDirection(this.startBeat,i),r=`tab.slur.${this.startNote.beat.id}.${this.endNote.beat.id}.${a}`,n=this.renderer;n.staff.getSharedLayoutData(r,!1)||(n.staff.setSharedLayoutData(r,!0),super.paint(e,t,s))}}class qh extends Ir{constructor(){super(...arguments),this._bend=null,this._effectSlurs=[]}drawBeamHelperAsFlags(e){return e.hasFlag(this.renderer.drawBeamHelperAsFlags(e),this.beat)}doLayout(){this._effectSlurs=[],super.doLayout(),this._bend&&(this._bend.renderer=this.renderer,this._bend.doLayout(),this.updateWidth())}createTies(e){if(!e.isVisible)return;const t=this.renderer;if(e.isTieOrigin&&t.showTiedNotes&&e.tieDestination.isVisible){const t=new Yh(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination&&t.showTiedNotes){const t=new Yh(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){const t=new Yh(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){const t=new $h(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){const t=new $h(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}if(e.slideInType!==q.None||e.slideOutType!==K.None){const t=new Jh(e.slideInType,e.slideOutType,e,this);this.addTie(t)}if(e.hasBend){if(!this._bend){const e=new hh;this._bend=e,e.renderer=this.renderer,this.addTie(e)}this._bend.addBends(e)}}}class Kh extends Fr{constructor(e,t,s){super(e,t),this._noteString=null,this._trillNoteString=null,this._trillNoteStringWidth=0,this.isEmpty=!1,this.noteStringWidth=0,this._note=s}doLayout(){const e=this._note;let t=e.fret-e.beat.voice.bar.staff.transpositionPitch;if(e.harmonicType===H.Natural&&0!==e.harmonicValue&&(t=e.harmonicValue-e.beat.voice.bar.staff.transpositionPitch),e.isTieDestination)0===e.beat.index&&this.renderer.settings.notation.notationMode===k.GuitarPro||(e.bendType===y.Bend||e.bendType===y.BendRelease)&&this.renderer.settings.notation.isNotationElementVisible(T.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===H.Natural){const 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(Be.isAlmostEqualTo(e.harmonicValue,0))this._trillNoteString="";else switch(e.harmonicType){case H.Artificial:case H.Pinch:case H.Tap:case H.Semi:case H.Feedback:let s=(t+e.harmonicValue).toString();const i=s.indexOf(String.fromCharCode(46));i>=0&&(s=s.substr(0,i+2)),this._trillNoteString=`<${s}>`;break;default:this._trillNoteString=""}if(this.isEmpty=!this._noteString,!this.isEmpty){this.renderer.scoreRenderer.canvas.font=this.renderer.resources.tablatureFont,this.noteStringWidth=this.renderer.scoreRenderer.canvas.measureText(this._noteString).width,this.width=this.noteStringWidth,this.height=this.renderer.scoreRenderer.canvas.font.size;!!this._trillNoteString&&(this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,this._trillNoteStringWidth=3+this.renderer.scoreRenderer.canvas.measureText(this._trillNoteString).width,this.width+=this._trillNoteStringWidth)}}paint(e,t,s){if(this.isEmpty)return;const i=this.noteStringWidth+this._trillNoteStringWidth,a=e+this.x+(this.width-i)/2;this.paintTrill(a,t,s);const r=hn.note(s,ee.GuitarTabFretNumber,this._note);try{s.fillText(this._noteString,a,t+this.y)}finally{r?.[Symbol.dispose]?.()}}paintTrill(e,t,s){const i=hn.note(s,ee.GuitarTabFretNumber,this._note);try{const i=this.renderer.scoreRenderer.canvas.font;this.renderer.scoreRenderer.canvas.font=this.renderer.resources.graceFont,s.fillText(this._trillNoteString,e+this.noteStringWidth+3,t+this.y),this.renderer.scoreRenderer.canvas.font=i}finally{i?.[Symbol.dispose]?.()}}buildBoundingsLookup(e,t,s){const i=new Ti;i.note=this._note,i.noteHeadBounds=new Hs,i.noteHeadBounds.x=t+this.x,i.noteHeadBounds.y=s+this.y-this.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}class jh extends Fr{constructor(e,t,s){super(e,t),this._notes=[],this._deadSlapped=null,this.minStringNote=null,this.beatEffects=new Map,this.notesPerString=new Map,this.noteStringWidth=0,this._isGrace=s}buildBoundingsLookup(e,t,s){for(const i of this._notes)i.buildBoundingsLookup(e,t+this.x,s+this.y)}getNoteX(e,t){if(this.notesPerString.has(e.string)){const s=this.notesPerString.get(e.string);let i=this.x+s.x;switch(t){case Zi.Left:break;case Zi.Center:i+=s.noteStringWidth/2;break;case Zi.Right:i+=s.width}return i}return 0}getNoteY(e,t){if(this.notesPerString.has(e.string)){const s=this.notesPerString.get(e.string);let i=this.y+s.y;switch(t){case Qi.Top:case Qi.TopWithStem:i-=s.height/2+2;break;case Qi.Center:break;case Qi.Bottom:case Qi.BottomWithStem:i+=s.height/2}return i}return 0}doLayout(){let e=0;if(this.beat.deadSlapped)this._deadSlapped=new eh,this._deadSlapped.renderer=this.renderer,this._deadSlapped.doLayout(),e=this._deadSlapped.width,this.noteStringWidth=e;else{let t=0;for(let s=0,i=this._notes.length;s<i;s++){const i=this._notes[s];i.renderer=this.renderer,i.doLayout(),i.width>e&&(e=i.width),i.noteStringWidth>t&&(t=i.noteStringWidth)}this.noteStringWidth=t;const s=this.renderer.resources.tablatureFont.size;let i=this.getNoteY(this.minStringNote,Qi.Center)+s/2;const a=7;for(const e of this.beatEffects.values())e.y+=i,e.x+=this.width/2,e.renderer=this.renderer,i+=a,e.doLayout()}this.width=e}addNoteGlyph(e,t){this._notes.push(e),this.notesPerString.set(t.string,e),(!this.minStringNote||t.string<this.minStringNote.string)&&(this.minStringNote=t)}paint(e,t,s){if(e+=this.x,t+=this.y,this.beat.deadSlapped)this._deadSlapped?.paint(e,t,s);else{const i=this.renderer.resources,a=s.textBaseline;s.textBaseline=V.Middle,s.font=this._isGrace?i.graceFont:i.tablatureFont;const r=this._notes,n=this.width;for(const i of r)i.renderer=this.renderer,i.width=n,i.paint(e,t,s);s.textBaseline=a;const o=hn.beat(s,ds.GuitarTabEffects,this.beat);try{for(const i of this.beatEffects.values())i.paint(e,t,s)}finally{o?.[Symbol.dispose]?.()}}}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 Qh extends Er{constructor(e,t,s,i){super(e,t,1,sh.getSymbol(i)),this._isVisibleRest=s}doLayout(){super.doLayout(),this._isVisibleRest||(this.width=10)}updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.isPositionFrom("tab",this.beat)&&this.beamingHelper.registerBeatLineX("tab",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){if(this._isVisibleRest){const i=hn.beat(s,ds.GuitarTabRests,this.beat);try{super.paint(e,t,s)}finally{i?.[Symbol.dispose]?.()}}}}class Zh extends Rn{constructor(){super(...arguments),this.slash=null,this.noteNumbers=null,this.restGlyph=null}get effectElement(){return ds.GuitarTabEffects}getNoteX(e,t){return this.noteNumbers?this.noteNumbers.getNoteX(e,t):0}getNoteY(e,t){return this.noteNumbers?this.noteNumbers.getNoteY(e,t):0}buildBoundingsLookup(e,t,s){this.noteNumbers&&this.noteNumbers.buildBoundingsLookup(e,t+this.x,s+this.y)}doLayout(){const e=this.renderer;if(this.container.beat.isRest){const t=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),s=e.getTabY(t),i=new Qh(0,s,e.showRests,this.container.beat.duration);if(this.restGlyph=i,i.beat=this.container.beat,i.beamingHelper=this.beamingHelper,this.addNormal(i),this.container.beat.dots>0&&e.showRests){this.addNormal(new dh(0,0,5));for(let e=0;e<this.container.beat.dots;e++)this.addEffect(new Uo(0,s,1.5))}}else{const t=this.renderer.settings.notation.smallGraceTabNotes&&this.container.beat.graceType!==R.None;let s;if(this.container.beat.slashed&&!this.container.beat.notes.some((e=>e.isTieDestination))){const i=Math.floor((this.renderer.bar.staff.tuning.length-1)/2),a=e.getLineY(i),r=new yh(0,a,this.container.beat.duration,t,this.container.beat);r.noteHeadElement=ee.GuitarTabFretNumber,r.effectElement=ds.GuitarTabEffects,this.slash=r,r.beat=this.container.beat,r.beamingHelper=this.beamingHelper,this.addNormal(r),s=r.beatEffects}else{const e=new jh(0,0,t);this.noteNumbers=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper;for(const e of this.container.beat.notes)e.isVisible&&this.createNoteGlyph(e);this.addNormal(e),s=e.beatEffects}if(this.container.beat.hasWhammyBar){const e=new lh(this.container.beat);e.renderer=this.renderer,e.doLayout(),this.container.ties.push(e)}if(this.container.beat.isTremolo&&!s.has("tremolo")){let e=0;const t=this.container.beat.tremoloSpeed;let i=5;switch(t){case D.ThirtySecond:e=10;break;case D.Sixteenth:e=5;break;case D.Eighth:e=0}this.container.beat.duration<D.Half&&(i=0),s.set("tremolo",new Zo(i,e,t))}if(this.container.beat.dots>0&&e.rhythmMode!==w.Hidden){this.addNormal(new dh(0,0,5));for(let t=0;t<this.container.beat.dots;t++)this.addEffect(new Uo(0,e.lineOffset*e.bar.staff.tuning.length+e.settings.notation.rhythmHeight,1.5))}}if(this.isEmpty)return;let t=0;for(let e=0,s=this.glyphs.length;e<s;e++){const s=this.glyphs[e];s.x=t,s.renderer=this.renderer,s.doLayout(),t+=s.width}this.width=t,this.computedWidth=t,this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteNumbers?this.centerX=this.noteNumbers.x+this.noteNumbers.noteStringWidth/2:this.slash&&(this.centerX=this.slash.x+this.slash.width/2)}updateBeamingHelper(){this.noteNumbers?this.noteNumbers.updateBeamingHelper(this.container.x+this.x):this.restGlyph?this.restGlyph.updateBeamingHelper(this.container.x+this.x):this.slash&&this.slash.updateBeamingHelper(this.container.x+this.x)}createNoteGlyph(e){const t=this.renderer,s=new Kh(0,0,e),i=e.beat.voice.bar.staff.tuning.length-e.string;s.y=t.getTabY(i),s.renderer=this.renderer,s.doLayout(),this.noteNumbers.addNoteGlyph(s,e);const a=s.y-s.height/2,r=a+s.height;this.renderer.helpers.collisionHelper.reserveBeatSlot(this.container.beat,a,r)}}class el extends Fr{constructor(e){super(0,0),this._beat=e}doLayout(){this.width=10}paint(e,t,s){const i=this.renderer,a=t+this.x+i.getNoteY(this._beat.maxStringNote,Qi.Top),r=t+this.y+i.getNoteY(this._beat.minStringNote,Qi.Bottom),n=e+this.x+this.width/2|0;if(this._beat.brushType!==b.None){if(this._beat.brushType===b.BrushUp||this._beat.brushType===b.BrushDown)s.beginPath(),s.moveTo(n,a),s.lineTo(n,r),s.stroke();else if(this._beat.brushType===b.ArpeggioUp){const t=new No(0,0,j.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();const i=a,n=r-8;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4,n,-90),t.paint(0,-t.height/2,s),s.endRotate()}else if(this._beat.brushType===b.ArpeggioDown){const t=new No(0,0,j.Slight,1.2,!0);t.renderer=this.renderer,t.doLayout();const i=a+8,n=r;t.width=Math.abs(n-i),s.beginRotate(e+this.x+4,i,90),t.paint(0,-t.height/2,s),s.endRotate()}this._beat.brushType===b.BrushUp||this._beat.brushType===b.ArpeggioUp?(s.beginPath(),s.moveTo(n,r),s.lineTo(n+4,r-8),s.lineTo(n-4,r-8),s.closePath(),s.fill()):(s.beginPath(),s.moveTo(n,a),s.lineTo(n+4,a+8),s.lineTo(n-4,a+8),s.closePath(),s.fill())}}}class tl extends An{doLayout(){this.container.beat.brushType===b.None||this.container.beat.isRest||(this.addEffect(new el(this.container.beat)),this.addNormal(new dh(0,0,4))),super.doLayout()}get effectElement(){return ds.GuitarTabEffects}}class sl extends Fr{doLayout(){this.width=Dr.Widths.get(G.SixStringTabClef)}paint(e,t,s){const i=hn.bar(s,c.GuitarTabsClef,this.renderer.bar);try{const i=this.renderer.bar.staff.tuning.length,a=i<=4?G.FourStringTabClef:G.SixStringTabClef,r=i<=4?i/4.5:i/6.5;s.fillMusicFontSymbol(e+this.x+5,t+this.y,r,a,!1)}finally{i?.[Symbol.dispose]?.()}}}class il extends kh{doLayout(){this.barSubElement=c.GuitarTabsTimeSignature,super.doLayout()}get commonScale(){return 1}get numberScale(){return this.renderer.bar.staff.tuning.length<=4?Lr.GraceScale:1}}class al extends Gh{get showMultiBarRest(){return this._showMultiBarRest}get repeatsBarSubElement(){return c.GuitarTabsRepeats}get barNumberBarSubElement(){return c.GuitarTabsBarNumber}get barLineBarSubElement(){return c.GuitarTabsBarLines}get staffLineBarSubElement(){return c.GuitarTabsStaffLine}constructor(e,t){super(e,t),this._hasTuplets=!1,this.showTimeSignature=!1,this.showRests=!1,this.showTiedNotes=!1,this._showMultiBarRest=!1,t.staff.showStandardNotation||(this.showTimeSignature=!0,this.showRests=!0,this.showTiedNotes=!0,this._showMultiBarRest=!0)}get lineSpacing(){return al.TabLineSpacing}get heightLineCount(){return this.bar.staff.tuning.length}get drawnLineCount(){return this.bar.staff.tuning.length}get rhythmMode(){let e=this.settings.notation.rhythmMode;return e===w.Automatic&&(e=this.bar.staff.showStandardNotation?w.Hidden:w.ShowWithBars),e}getTabY(e){return super.getLineY(e)}getTabHeight(e){return super.getLineHeight(e)}collectSpaces(e){for(const t of this.bar.voices)if(this.hasVoiceContainer(t)){const s=this.getVoiceContainer(t);for(const t of s.beatGlyphs){const i=t.onNotes,a=i.noteNumbers;if(a)for(const[r,n]of a.notesPerString)n.isEmpty||e[this.bar.staff.tuning.length-r].push(new Float32Array([s.x+t.x+i.x+a.x,a.width+1]))}}}adjustSizes(){this.rhythmMode!==w.Hidden&&(this.height+=this.settings.notation.rhythmHeight,this.bottomPadding+=this.settings.notation.rhythmHeight)}doLayout(){if(super.doLayout(),this.rhythmMode!==w.Hidden){this._hasTuplets=!1;for(const e of this.bar.voices)if(this.hasVoiceContainer(e)){if(this.getVoiceContainer(e).tupletGroups.length>0){this._hasTuplets=!0;break}}this._hasTuplets&&this.registerOverflowBottom(this.tupletSize)}}createLinePreBeatGlyphs(){if(this.isFirstOfLine){const e=(this.bar.staff.tuning.length-1)/2;this.addPreBeatGlyph(new sl(5,this.getTabY(e)))}this.showTimeSignature&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new dh(0,0,5));const e=(this.bar.staff.tuning.length+1)/2-1;this.addPreBeatGlyph(new il(0,this.getTabY(e),this.bar.masterBar.timeSignatureNumerator,this.bar.masterBar.timeSignatureDenominator,this.bar.masterBar.timeSignatureCommon,this.bar.masterBar.isFreeTime))}createVoiceGlyphs(e){if(this.additionalMultiRestBars){const t=new Wn(this.getVoiceContainer(e));this.addBeatGlyph(t)}else for(const t of e.beats){const s=new qh(t,this.getVoiceContainer(e));s.preNotes=new tl,s.onNotes=new Zh,this.addBeatGlyph(s)}}paint(e,t,s){super.paint(e,t,s),this.rhythmMode!==w.Hidden&&(this.paintBeams(e,t,s,ds.GuitarTabFlags,ds.GuitarTabBeams),this.paintTuplets(e,t,s,ds.GuitarTabTuplet))}drawBeamHelperAsFlags(e){return super.drawBeamHelperAsFlags(e)||this.rhythmMode===w.ShowWithBeams}getFlagTopY(e,t){const s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==D.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,Qi.Bottom):this.height-this.settings.notation.rhythmHeight-this.tupletSize}getFlagBottomY(e,t){return this.getFlagAndBarPos()}getFlagStemSize(e,t=!1){return 0}getBarLineStart(e,t){const s=this.getOnNotesGlyphForBeat(e);return s.noteNumbers&&e.duration!==D.Half?s.noteNumbers.getNoteY(s.noteNumbers.minStringNote,Qi.Bottom)+this.lineOffset/2:this.height-this.settings.notation.rhythmHeight-this.tupletSize}getBeamDirection(e){return se.Down}getFlagAndBarPos(){return this.height-(this._hasTuplets?this.tupletSize/2:0)}calculateBeamYWithDirection(e,t,s){return this.getFlagAndBarPos()}shouldPaintFlag(e,t){return!!super.shouldPaintFlag(e,t)&&(e.graceType===R.None&&this.drawBeamHelperAsFlags(t))}paintBeamingStem(e,t,s,i,a,r){if(a<i){const e=a;a=i,i=e}const n=hn.beat(r,ds.GuitarTabStem,e);try{r.lineWidth=Vn.StemWidth,r.beginPath();let n=[];this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.has(e.displayStart)&&(n=this.helpers.collisionHelper.reservedLayoutAreasByDisplayTime.get(e.displayStart).slots.slice(),n.sort(((e,t)=>e.topY-t.topY)));let o=a;for(;o>i;){r.moveTo(s,o);let e=i;if(!(n.length>0&&n[n.length-1].bottomY>e)){r.lineTo(s,e);break}{const i=n.pop();e=t+i.bottomY,r.lineTo(s,e),o=t+i.topY}}r.stroke(),r.lineWidth=1}finally{n?.[Symbol.dispose]?.()}}}al.StaffId="tab",al.TabLineSpacing=10;class rl extends rn{get staffId(){return al.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}constructor(){super(),this.showTimeSignature=null,this.showRests=null,this.showTiedNotes=null,this.hideOnPercussionTrack=!0}canCreate(e,t){return t.showTablature&&t.tuning.length>0&&super.canCreate(e,t)}create(e,t){const s=new al(e,t);return null!==this.showRests&&(s.showRests=this.showRests),null!==this.showTimeSignature&&(s.showTimeSignature=this.showTimeSignature),null!==this.showTiedNotes&&(s.showTiedNotes=this.showTiedNotes),s}}class nl extends Cr{constructor(){super(0,0)}doLayout(){super.doLayout();const e=this.renderer.resources.effectFont;this.height=e.size+nl.Padding}paint(e,t,s){const i=this.renderer.resources;s.font=i.effectFont;const a=s.textAlign;s.textAlign=W.Center,s.fillText("T",e+this.x,t+this.y+s.font.size/2),s.textAlign=a,s.strokeCircle(e+this.x,t+this.y+s.font.size/2+(nl.Padding-1),s.font.size/1.6)}}nl.Padding=4;class ol extends lo{get notationElement(){return T.EffectTap}get sizingMode(){return ea.SingleOnBeat}shouldCreateGlyphForNote(e){return e.isLeftHandTapped}createNewGlyph(e,t){return new nl}}class hl{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"}(sa||(sa={}));class ll extends hl{constructor(){super(...arguments),this.align=W.Left,this.frame=sa.None,this.text="",this.fontFace="",this.weight=0,this.height=0}}class cl extends hl{constructor(){super(...arguments),this.chord=new me}}class dl extends hl{}class ul extends hl{}class pl extends hl{constructor(){super(...arguments),this.number=0}}class gl extends hl{constructor(){super(...arguments),this.decrescendo=!1}}class ml extends hl{constructor(){super(...arguments),this.allNumbers=!1,this.firstNumber=0,this.lastNumber=0}}class fl extends hl{constructor(){super(...arguments),this.octave=1}}class yl extends hl{}class bl{constructor(){this.defaultClef=n.G2,this.description="",this.percussion=!1,this.instrument=0,this.volume=0,this.transpose=0,this.index=0}}class Sl{constructor(){this.from=0,this.to=0,this.curly=!1}}class _l{constructor(){this.currentBarIndex=-1,this.currentBarComplete=!0,this.currentBarDuration=0,this.currentPosition=0,this.voiceStemDir=null,this.repeatCount=0,this.repeatEnd=null}}class wl{constructor(){this._trackChannel=0,this._beamingMode=cs.Auto,this._isFirstSystem=!0,this._staffLookup=new Map,this._brackets=[],this._staffLayoutLookup=new Map,this._staffLayouts=[],this._timeSignature=new Se,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;const s=new Xs;try{s.parse(e)}catch(e){throw new Es("Could not parse XML",e)}this.parseDom(s),this.consolidate(),this.score.finish(t)}consolidate(){for(const e of this.score.tracks){const t=this._voiceCounts.get(e.index);for(const s of e.staves){for(;s.bars.length<this.score.masterBars.length;)this.addNewBar(s);for(const e of s.bars){for(;e.voices.length<t;)e.addVoice(new Dt);for(const t of e.voices)if(0===t.beats.length){const e=new gs;e.isEmpty=!0,t.addBeat(e)}}}}wl.applyEffectRange(this._slurs,((e,t)=>{t.isLegatoOrigin=!0})),wl.applyEffectRange(this._crescendo,((e,t)=>{t.crescendo=e.decrescendo?F.Decrescendo:F.Crescendo}))}static applyEffectRange(e,t){for(const[s,i]of e){const e=i.noteRange;let a=s;for(let s=0;s<e;s++)if(t(i,a),a.index+1<a.voice.beats.length)a=a.voice.beats[a.index+1];else{if(!(a.voice.bar.index+1<a.voice.bar.staff.bars.length))break;a=a.voice.bar.staff.bars[a.voice.bar.index+1].voices[a.voice.index].beats[0]}}}parseDom(e){const t=e.firstElement;if(!t)throw new Es("No valid XML");if("score"!==t.localName)throw new Es('Root node of XML was not "score"');this.score=new Cs,this.score.tempo=120;for(const e of t.childElements())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(const t of e.childElements())switch(t.localName){case"staves":this.parseLayoutStaves(t);break;case"brackets":this.parseBrackets(t)}const t=this._brackets.filter((e=>!!e.curly));t.sort(((e,t)=>e.from-t.from));let s=0,i=null;for(let e=0;e<this._staffLayouts.length;e++){const a=this._staffLayouts[e];for(;s<t.length&&e>t[s].to;)s++;i&&s<t.length&&e>t[s].from&&e<=t[s].to?i.ensureStaveCount(i.staves.length+1):(i=new $t,i.ensureStaveCount(1),i.name=a.description,i.playbackInfo.volume=Math.floor(a.volume/128*16),i.playbackInfo.program=a.instrument,a.percussion?(i.playbackInfo.primaryChannel=9,i.playbackInfo.secondaryChannel=9):(i.playbackInfo.primaryChannel=this._trackChannel++,i.playbackInfo.secondaryChannel=this._trackChannel++),this.score.addTrack(i));const r=i.staves[i.staves.length-1];r.isPercussion=a.percussion,r.transpositionPitch=a.transpose,r.displayTranspositionPitch=0,r.showTablature=!1,this._staffLookup.set(a.index,r)}}parseBrackets(e){for(const t of e.childElements())if("bracket"===t.localName)this.parseBracket(t)}parseBracket(e){const t=new Sl;t.from=Number.parseInt(e.getAttribute("from")),t.to=Number.parseInt(e.getAttribute("to")),e.attributes.has("curly")&&(t.curly="true"===e.attributes.get("curly")),this._brackets.push(t)}parseLayoutStaves(e){for(const t of e.childElements())if("staffLayout"===t.localName)this.parseStaffLayout(t)}parseStaffLayout(e){const t=new bl;t.description=e.getAttribute("description");for(const s of e.childElements())switch(s.localName){case"notation":s.attributes.has("defaultClef")&&(t.defaultClef=this.parseClef(s.attributes.get("defaultClef")));break;case"sound":s.attributes.has("percussion")&&(t.percussion="true"===s.attributes.get("percussion")),s.attributes.has("instr")&&(t.instrument=Number.parseInt(s.attributes.get("instr"))),s.attributes.has("volume")&&(t.volume=Number.parseInt(s.attributes.get("volume"))),s.attributes.has("transpose")&&(t.transpose=Number.parseInt(s.attributes.get("transpose")))}this._staffLayoutLookup.set(t.description,t),t.index=this._staffLayouts.length,this._staffLayouts.push(t)}parseClef(e){switch(e){case"treble":return n.G2;case"bass":return n.F4;case"alto":case"tenor":return n.C4}return n.G2}parseClefOttava(e){return e.endsWith("-")?o._8vb:e.endsWith("+")?o._8va:o.Regular}parseSystems(e){for(const t of e.childElements())if("system"===t.localName)this.parseSystem(t)}parseSystem(e){e.attributes.has("tempo")&&0===this.score.masterBars.length&&(this.score.tempo=Number.parseInt(e.attributes.get("tempo"))),"0"===e.getAttribute("beamGrouping")&&(this._beamingMode=cs.ForceSplitToNext);for(const t of e.childElements())if("staves"===t.localName)this.parseStaves(e,t);this._isFirstSystem=!1}parseStaves(e,t){const s=this.score.masterBars.length;for(const i of t.childElements())if("staff"===i.localName)this.parseStaff(e,s,i)}parseStaff(e,t,s){const i=s.getAttribute("layout");this._currentStaffLayout=this._staffLayoutLookup.get(i),this._timeSignature.timeSignatureNumerator=4,this._timeSignature.timeSignatureDenominator=4,this._timeSignature.timeSignatureCommon=!1,this.parseTime(s.getAttribute("defaultTime"));const a=this._staffLookup.get(this._currentStaffLayout.index);for(;a.bars.length<t;)this.addNewBar(a);for(const r of s.childElements())if("voices"===r.localName)this.parseVoices(i,a,e,t,r)}parseTime(e){switch(e){case"allaBreve":case"C":this._timeSignature.timeSignatureNumerator=2,this._timeSignature.timeSignatureDenominator=2,this._timeSignature.timeSignatureCommon=!0;break;case"longAllaBreve":this._timeSignature.timeSignatureNumerator=4,this._timeSignature.timeSignatureDenominator=4,this._timeSignature.timeSignatureCommon=!0;break;default:if(e.indexOf("/")>0){const t=e.split("/");this._timeSignature.timeSignatureNumerator=Number.parseInt(t[0]),this._timeSignature.timeSignatureDenominator=Number.parseInt(t[1]),this._timeSignature.timeSignatureCommon=!1}}}parseVoices(e,t,s,i,a){let r=0;for(const n of a.childElements())if("voice"===n.localName)this.parseVoice(e,t,s,r,i,n),r++}getOrCreateBar(e,t){return t<e.bars.length?e.bars[t]:this.addNewBar(e)}addNewBar(e){const t=new ue;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){const e=new Se;this.score.addMasterBar(e),e.index>0&&(e.keySignature=e.previousMasterBar.keySignature,e.keySignatureType=e.previousMasterBar.keySignatureType,e.tripletFeel=e.previousMasterBar.tripletFeel),e.timeSignatureDenominator=this._timeSignature.timeSignatureDenominator,e.timeSignatureNumerator=this._timeSignature.timeSignatureNumerator,e.timeSignatureCommon=this._timeSignature.timeSignatureCommon}return t}newBar(e,t){this._currentVoiceState.currentBarIndex++,this._currentBar=this.getOrCreateBar(e,this._currentVoiceState.currentBarIndex),this._currentVoiceState.currentBarDuration=this._currentBar.masterBar.calculateDuration(!1),this._currentVoiceState.currentBarComplete=!1,this._currentVoiceState.currentPosition=0,this.ensureVoice(e,t)}parseVoice(e,t,s,i,a,r){const n=`${e}_${i}`;if(this._currentVoiceState&&!this._currentVoiceState.currentBarComplete&&(this._currentBar.masterBar.isAnacrusis=!0),this._voiceStates.has(n)?(this._currentVoiceState=this._voiceStates.get(n),this._currentBar=this.getOrCreateBar(t,this._currentVoiceState.currentBarIndex),this.ensureVoice(t,i)):(this._currentVoiceState=new _l,this._currentVoiceState.currentBarIndex=a-1,this._voiceStates.set(n,this._currentVoiceState),this.newBar(t,i)),r.attributes.has("stemDir"))switch(r.attributes.get("stemDir")){case"up":this._currentVoiceState.voiceStemDir=se.Up;break;case"down":this._currentVoiceState.voiceStemDir=se.Down;break;default:this._currentVoiceState.voiceStemDir=null}else this._currentVoiceState.voiceStemDir=null;const o=r.findChildElement("noteObjects");if(s.attributes.has("tempo")){const e=new pe;e.isLinear=!0,e.type=g.Tempo,e.value=Number.parseInt(s.attributes.get("tempo")),e.ratioPosition=this._currentVoiceState.currentPosition/this._currentVoiceState.currentBarDuration,this._currentBar.masterBar.tempoAutomations.push(e)}if(o)for(const e of o.childElements())switch(this._currentVoiceState.currentBarComplete&&"barline"!==e.localName&&this.newBar(t,i),e.localName){case"clefSign":this._currentBar.clef=this.parseClef(e.getAttribute("clef")),this._currentBar.clefOttava=this.parseClefOttava(e.getAttribute("clef"));break;case"keySign":this._currentBar.masterBar.keySignature=Number.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.barLineRight=d.LightLight,this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0;break;case"end":this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0);break;case"repEnd":this._currentVoiceState.repeatEnd=this._currentBar.masterBar,this._currentBar.masterBar.repeatCount<this._currentVoiceState.repeatCount&&(this._currentBar.masterBar.repeatCount=this._currentVoiceState.repeatCount),this.parseBarDrawObject(e),this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0;break;case"repBegin":this.newBar(t,i),this._currentBar.masterBar.isRepeatStart=!0,this._currentVoiceState.repeatEnd=null,this._currentVoiceState.repeatCount=0;break;case"repEndBegin":this._currentVoiceState.repeatEnd=this._currentBar.masterBar,this._currentBar.masterBar.repeatCount<this._currentVoiceState.repeatCount&&(this._currentBar.masterBar.repeatCount=this._currentVoiceState.repeatCount),this.parseBarDrawObject(e),this.newBar(t,i),this._currentBar.masterBar.isRepeatStart=!0;break;default:this._currentVoiceState.currentBarComplete||(this._currentBar.masterBar.isAnacrusis=!0),this._currentVoiceState.currentBarComplete=!0}break;case"chord":const s=new gs;this.initFromPreviousBeat(s,this._currentVoice),s.beamingMode=this._beamingMode,this._currentVoiceState.voiceStemDir&&(s.preferredBeamDirection=this._currentVoiceState.voiceStemDir),this.parseDuration(this._currentBar,s,e.findChildElement("duration")),s.updateDurations(),this._currentVoiceState.currentPosition+=s.playbackDuration,this._currentVoice.addBeat(s),this.parseChord(s,e),this._currentVoiceState.currentPosition>=this._currentVoiceState.currentBarDuration&&(this._currentVoiceState.currentBarComplete=!0);break;case"rest":const a=this.parseRestDurations(this._currentBar,e.findChildElement("duration"));a&&(this.initFromPreviousBeat(a,this._currentVoice),a.updateDurations(),this._currentVoiceState.currentPosition+=a.playbackDuration,this._currentVoice.addBeat(a),this._currentVoiceState.currentPosition>=this._currentVoiceState.currentBarDuration&&(this._currentVoiceState.currentBarComplete=!0))}}initFromPreviousBeat(e,t){const s=this.getLastBeat(t);s&&(e.dynamics=s.dynamics)}getLastBeat(e){if(e.beats.length>0)return e.beats[e.beats.length-1];if(e.bar.index>0){const t=e.bar.staff.bars[e.bar.index-1];if(e.index<t.voices.length){const s=t.voices[e.index];return this.getLastBeat(s)}}return null}ensureVoice(e,t){for(;this._currentBar.voices.length<t+1;)this._currentBar.addVoice(new Dt);(!this._voiceCounts.has(e.track.index)||this._voiceCounts.get(e.track.index)<this._currentBar.voices.length)&&this._voiceCounts.set(e.track.index,this._currentBar.voices.length),this._currentVoice=this._currentBar.voices[t]}parseChord(e,t){const s=new Nt;for(const i of t.childElements())switch(i.localName){case"stem":switch(i.getAttribute("dir")){case"up":e.preferredBeamDirection=se.Up;break;case"down":e.preferredBeamDirection=se.Down}break;case"articulation":switch(i.getAttribute("type")){case"staccato":s.isStaccato=!0;break;case"normalAccent":s.accentuated=u.Normal;break;case"strongAccent":s.accentuated=u.Heavy}break;case"lyric":this.parseLyric(e,i);break;case"drawObjects":this.parseBeatDrawObject(e,i);break;case"heads":this.parseHeads(e,s,i);break;case"beam":switch(i.getAttribute("group")){case"force":e.beamingMode=cs.ForceMergeWithNext;break;case"divide":e.beamingMode=cs.ForceSplitToNext}}}parseHeads(e,t,s){for(const i of s.childElements())if("head"===i.localName)this.parseHead(e,t,i)}parseHead(e,t,s){const i=new Nt,a=Be.parseTuning(s.getAttribute("pitch"));i.octave=a.octave-1,i.tone=a.tone.noteValue,i.isStaccato=t.isStaccato,i.accentuated=t.accentuated,e.addNote(i);for(const e of s.childElements())switch(e.localName){case"alter":e.attributes.has("step")&&(i.tone+=Number.parseInt(e.attributes.get("step")));break;case"tie":e.attributes.has("begin")?this._tieStartIds.has(i.id)||(this._tieStartIds.set(i.id,!0),this._tieStarts.push(i)):e.attributes.has("end")&&this._tieStarts.length>0&&!i.isTieDestination&&(i.isTieDestination=!0,i.tieOrigin=this._tieStarts[0],this._tieStarts.splice(0,1),this._tieStartIds.delete(i.id))}}parseBeatDrawObject(e,t){for(const s of t.childElements())if("drawObj"===s.localName){const t=this.parseDrawObj(s);if(t)if(t instanceof ll)t.fontFace.startsWith("capella")?"u"===t.text?(e.fermata=new Te,e.fermata.type=M.Medium):"f"===t.text?e.dynamics=E.F:"j"===t.text&&(e.dynamics=E.MF):this._isFirstSystem&&""===this.score.title&&t.align===W.Center&&t.height>16&&t.weight>400?this.score.title=t.text:this._isFirstSystem&&""===this.score.artist&&t.align===W.Center&&t.y<0?this.score.artist=t.text:this._isFirstSystem&&""===this.score.music&&t.align===W.Right&&t.y<0?this.score.music=t.text:t.text.startsWith("by capella")||(e.text=t.text);else if(t instanceof cl);else if(t instanceof ul)e.vibrato=j.Slight;else if(t instanceof gl)e.crescendo=t.decrescendo?F.Decrescendo:F.Crescendo,t.noteRange++,this._crescendo.set(e,t);else if(t instanceof dl){const s=t;this._slurs.set(e,s)}else t instanceof ml&&this.applyVolta(t)}}parseBarDrawObject(e){for(const t of e.childElements())if("drawObj"===t.localName){const e=this.parseDrawObj(t);e&&e instanceof ml&&this.applyVolta(e)}}applyVolta(e){if(e.lastNumber>0?(this._currentVoiceState.repeatCount=e.lastNumber,this._currentVoiceState.repeatEnd&&this._currentVoiceState.repeatEnd.repeatCount<this._currentVoiceState.repeatCount&&(this._currentVoiceState.repeatEnd.repeatCount=this._currentVoiceState.repeatCount)):e.firstNumber>0&&(this._currentVoiceState.repeatCount=e.firstNumber,this._currentVoiceState.repeatEnd&&this._currentVoiceState.repeatEnd.repeatCount<this._currentVoiceState.repeatCount&&(this._currentVoiceState.repeatEnd.repeatCount=this._currentVoiceState.repeatCount)),e.lastNumber>0&&e.firstNumber>0){let t=0;for(let s=e.firstNumber;s<=e.lastNumber;s++)t|=1<<s-1;this._currentBar.masterBar.alternateEndings=t}else e.lastNumber>0?this._currentBar.masterBar.alternateEndings=1<<e.lastNumber-1:e.firstNumber>0&&(this._currentBar.masterBar.alternateEndings=1<<e.firstNumber-1)}parseLyric(e,t){for(const s of t.childElements())if("verse"===s.localName){e.lyrics||(e.lyrics=[]);let t=s.innerText;"true"===s.getAttribute("hyphen")&&(t+="-"),e.lyrics.push(t)}}parseRestDurations(e,t){const s=t.getAttribute("base");if(-1!==s.indexOf("/")){const s=new gs;return s.beamingMode=this._beamingMode,this.parseDuration(e,s,t),s}if(1===Number.parseInt(s)){const e=new gs;return e.beamingMode=this._beamingMode,e.duration=D.Whole,e}return wt.warning("Importer","Multi-Bar rests are not supported"),null}parseDurationValue(e){switch(e){case"2/1":return D.DoubleWhole;case"1/1":return D.Whole;case"1/2":return D.Half;case"1/4":return D.Quarter;case"1/8":return D.Eighth;case"1/16":return D.Sixteenth;case"1/32":return D.ThirtySecond;case"1/64":return D.SixtyFourth;case"1/128":return D.OneHundredTwentyEighth;default:return wt.warning("Importer","Unsupported duration"),D.Quarter}}parseDuration(e,t,s){const i=s.getAttribute("base");t.duration=this.parseDurationValue(i),s.attributes.has("dots")&&(t.dots=Number.parseInt(s.attributes.get("dots")));const a=s.findChildElement("tuplet");if(a){t.tupletNumerator=Number.parseInt(a.getAttribute("count"));const e="true"===a.getAttribute("tripartite")?3:1,s="true"===a.getAttribute("prolong")?0:1;let i=0;for(;e*Math.pow(2,i+s)<t.tupletNumerator;)i++;t.tupletDenominator=e*Math.pow(2,i)}}parsePageObjects(e){for(const t of e.childElements())if("drawObj"===t.localName){const e=this.parseDrawObj(t);if(e&&e instanceof ll)switch(e.align){case W.Center:this.score.title?this.score.subTitle||(this.score.subTitle=t.innerText):this.score.title=t.innerText;break;case W.Right:this.score.artist||(this.score.artist=t.innerText)}}}parseGallery(e){for(const t of e.childElements())if("drawObj"===t.localName){const e=this.parseDrawObj(t);e&&this._galleryObjects.set(t.getAttribute("name"),e)}}parseDrawObj(e){let t=null,s=1;for(const i of e.childElements())switch(i.localName){case"text":t=this.parseText(i);break;case"guitar":t=this.parseGuitar(i);break;case"slur":t=this.parseSlur(i);break;case"wavyLine":t=this.parseWavyLine(i);break;case"bracket":t=this.parseTupletBracket(i);break;case"wedge":t=this.parseWedge(i);break;case"volta":t=this.parseVolta(i);break;case"octaveClef":t=this.parseOctaveClef(i);break;case"trill":t=this.parseTrill(i);break;case"basic":i.attributes.has("noteRange")&&(s=Number.parseInt(i.attributes.get("noteRange")))}return t&&(t.noteRange=s),t}parseTrill(e){return new yl}parseOctaveClef(e){const t=new fl;return e.attributes.has("octave")&&(t.octave=Number.parseInt(e.attributes.get("octave"))),t}parseVolta(e){const t=new ml;return t.allNumbers="true"===e.attributes.get("allNumbers"),e.attributes.has("firstNumber")&&(t.firstNumber=Number.parseInt(e.attributes.get("firstNumber"))),e.attributes.has("lastNumber")&&(t.lastNumber=Number.parseInt(e.attributes.get("lastNumber"))),t}parseWedge(e){const t=new gl;return t.decrescendo="true"===e.attributes.get("decrescendo"),t}parseTupletBracket(e){const t=new pl;return e.attributes.has("number")&&(t.number=Number.parseInt(e.attributes.get("number"))),t}parseWavyLine(e){return new ul}parseSlur(e){return new dl}parseGuitar(e){const t=new cl,s=e.innerText.trim();for(let e=0;e<s.length;e++)"/"===s.charAt(e)?t.chord.strings.push(0):t.chord.strings.push(Number.parseInt(s.charAt(e)));return t}parseText(e){const t=new ll;switch(e.attributes.has("x")&&(t.x=Number.parseFloat(e.attributes.get("x"))),e.attributes.has("x")&&(t.y=Number.parseFloat(e.attributes.get("y"))),e.getAttribute("align")){case"left":t.align=W.Left;break;case"center":t.align=W.Center;break;case"right":t.align=W.Right}switch(e.getAttribute("frame")){case"rectangle":t.frame=sa.Rectangle;break;case"ellipse":t.frame=sa.Ellipse;break;case"circle":t.frame=sa.Circle;break;case"none":t.frame=sa.None}if(e.firstElement)for(const s of e.childElements())switch(s.localName){case"font":t.fontFace=s.getAttribute("face"),s.attributes.has("weight")&&(t.weight=Number.parseInt(s.attributes.get("weight"))),s.attributes.has("height")&&(t.height=Number.parseInt(s.attributes.get("height")));break;case"content":t.text=s.innerText}else t.text=e.innerText;return t}parseInfo(e){for(const t of e.childElements())switch(t.localName){case"author":this.score.tab=t.firstChild.innerText;break;case"comment":this.score.notices=t.firstChild.innerText}}}class Bl extends Ds{get name(){return"Capella"}readScore(){wt.debug(this.name,"Loading ZIP entries");let e,t=null;if(e=new hi(this.data).read(),wt.debug(this.name,"Zip entries loaded"),e.length>0){for(const s of e)if("score.xml"===s.fileName)t=Le.toString(s.data,this.settings.importer.encoding)}else this.data.reset(),t=Le.toString(this.data.readAll(),this.settings.importer.encoding);if(!t)throw new Es("No valid capella file");wt.debug(this.name,"Start Parsing score.xml");try{const e=new wl;e.parseXml(t,this.settings),wt.debug(this.name,"score.xml parsed");return e.score}catch(e){throw new Es("Failed to parse CapXML",e)}}}class kl{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 Tl{constructor(e){this._elements=[];let t=null;const s=this.check.bind(this);this.check=()=>{t||(t=setTimeout((()=>{s(),t=null}),100))},this._callback=e,window.addEventListener("resize",this.check,!0),document.addEventListener("scroll",this.check,!0)}observe(e){this._elements.indexOf(e)>=0||(this._elements.push(e),this.check())}unobserve(e){this._elements=this._elements.filter((t=>t!==e))}check(){const e=[];for(const t of this._elements){const s=t.getBoundingClientRect();s.top+s.height>=0&&s.top<=window.innerHeight&&s.left+s.width>=0&&s.left<=window.innerWidth&&e.push({target:t,isIntersecting:!0})}e.length&&this._callback(e,this)}}function Nl(e,t,s){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var i,a;if(s){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=t[Symbol.asyncDispose]}if(void 0===i){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=t[Symbol.dispose],s&&(a=i)}if("function"!=typeof i)throw new TypeError("Object not disposable.");a&&(i=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:i,async:s})}else s&&e.stack.push({async:!0});return t}var xl="function"==typeof SuppressedError?SuppressedError:function(e,t,s){var i=new Error(s);return i.name="SuppressedError",i.error=e,i.suppressed=t,i};function vl(e){function t(t){e.error=e.hasError?new xl(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var s,i=0;return function a(){for(;s=e.stack.pop();)try{if(!s.async&&1===i)return i=0,e.stack.push(s),Promise.resolve().then(a);if(s.dispose){var r=s.dispose.call(s.value);if(s.async)return i|=2,Promise.resolve(r).then(a,(function(e){return t(e),a()}))}else i|=1}catch(e){t(e)}if(1===i)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}class Pl{static enable(e,t){Pl.alphaSkia=t,Pl.initializeMusicFont(Pl.alphaSkia.AlphaSkiaTypeface.register(e))}static initializeMusicFont(e){Pl.musicFont=e}static registerFont(e,t){const s=Pl.alphaSkia.AlphaSkiaTypeface.register(e.buffer);t||(t=Pe.withFamilyList([s.familyName],12,s.isItalic?I.Italic:I.Plain,s.isBold?A.Bold:A.Regular));for(const e of t.families)Pl.customTypeFaces.set(Pl.customTypefaceKey(e,t.isBold,t.isItalic),s);return t}static customTypefaceKey(e,t,s){return`${e.toLowerCase()}_${t}_${s}`}getTypeFace(){if(this._typeFaceCache!==this.font.toCssString(this._scale)){if(this._typeFaceIsSystem){const e={stack:[],error:void 0,hasError:!1};try{Nl(e,this._typeFace,!1)}catch(t){e.error=t,e.hasError=!0}finally{vl(e)}}for(const e of this.font.families){const t=Pl.customTypefaceKey(e,this.font.isBold,this.font.isItalic);Pl.customTypeFaces.has(t)?(this._typeFaceIsSystem=!1,this._typeFace=Pl.customTypeFaces.get(t)):(this._typeFaceIsSystem=!0,this._typeFace=Pl.alphaSkia.AlphaSkiaTypeface.create(e,this.font.isBold,this.font.isItalic))}this._typeFaceCache=this.font.toCssString(this._scale)}return this._typeFace}constructor(){this._color=new ke(0,0,0,0),this._lineWidth=0,this._typeFaceCache="",this._typeFaceIsSystem=!1,this._typeFace=null,this._scale=1,this.font=new Pe("Arial",10,I.Plain),this.textAlign=W.Left,this.textBaseline=V.Top,this._initialMeasure=!0,this._canvas=new Pl.alphaSkia.AlphaSkiaCanvas,this.color=new ke(0,0,0,255)}destroy(){const e={stack:[],error:void 0,hasError:!1};try{Nl(e,this._canvas,!1)}catch(t){e.error=t,e.hasError=!0}finally{vl(e)}}onRenderFinished(){return null}beginRender(e,t){this._scale=this.settings.display.scale,this._canvas.beginRender(e,t,cc.HighDpiFactor)}endRender(){return this._canvas.endRender()}get color(){return this._color}set color(e){this._color.rgba!==e.rgba&&(this._color=e,this._canvas.color=Pl.alphaSkia.AlphaSkiaCanvas.rgbaToColor(e.r,e.g,e.b,e.a))}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e,this._canvas.lineWidth=e}fillRect(e,t,s,i){s>0&&this._canvas.fillRect(e*this._scale|0,t*this._scale|0,s*this._scale,i*this._scale)}strokeRect(e,t,s,i){const a=this.lineWidth%2==0?0:.5;this._canvas.strokeRect((e*this._scale|0)+a,(t*this._scale|0)+a,s*this._scale,i*this._scale)}beginPath(){this._canvas.beginPath()}closePath(){this._canvas.closePath()}moveTo(e,t){this._canvas.moveTo(e*this._scale,t*this._scale)}lineTo(e,t){this._canvas.lineTo(e*this._scale,t*this._scale)}quadraticCurveTo(e,t,s,i){this._canvas.quadraticCurveTo(e*this._scale,t*this._scale,s*this._scale,i*this._scale)}bezierCurveTo(e,t,s,i,a,r){this._canvas.bezierCurveTo(e*this._scale,t*this._scale,s*this._scale,i*this._scale,a*this._scale,r*this._scale)}fillCircle(e,t,s){this._canvas.fillCircle(e*this._scale,t*this._scale,s*this._scale)}strokeCircle(e,t,s){this._canvas.strokeCircle(e*this._scale,t*this._scale,s*this._scale)}fill(){this._canvas.fill()}stroke(){this._canvas.stroke()}beginGroup(e){}endGroup(){}fillText(e,t,s){if(0===e.length)return;let i=Pl.alphaSkia.AlphaSkiaTextAlign.Left;switch(this.textAlign){case W.Left:i=Pl.alphaSkia.AlphaSkiaTextAlign.Left;break;case W.Center:i=Pl.alphaSkia.AlphaSkiaTextAlign.Center;break;case W.Right:i=Pl.alphaSkia.AlphaSkiaTextAlign.Right}let a=Pl.alphaSkia.AlphaSkiaTextBaseline.Top;switch(this.textBaseline){case V.Top:a=Pl.alphaSkia.AlphaSkiaTextBaseline.Top;break;case V.Middle:a=Pl.alphaSkia.AlphaSkiaTextBaseline.Middle;break;case V.Bottom:a=Pl.alphaSkia.AlphaSkiaTextBaseline.Bottom}this._canvas.fillText(e,this.getTypeFace(),this.font.size*this._scale,t*this._scale|0,s*this._scale|0,i,a)}measureText(e){return this._initialMeasure&&(this._canvas.measureText(e,this.getTypeFace(),this.font.size),this._initialMeasure=!1),new Ce(this._canvas.measureText(e,this.getTypeFace(),this.font.size),this.font.size*Pl.FontSizeToLineHeight)}fillMusicFontSymbol(e,t,s,i,a){i!==G.None&&this.fillMusicFontSymbolText(e,t,s,String.fromCharCode(i),a)}fillMusicFontSymbols(e,t,s,i,a){let r="";for(const e of i)e!==G.None&&(r+=String.fromCharCode(e));this.fillMusicFontSymbolText(e,t,s,r,a)}fillMusicFontSymbolText(e,t,s,i,a){this._canvas.fillText(i,Pl.musicFont,cc.MusicFontSize*this._scale*s,e*this._scale,t*this._scale,a?Pl.alphaSkia.AlphaSkiaTextAlign.Center:Pl.alphaSkia.AlphaSkiaTextAlign.Left,Pl.alphaSkia.AlphaSkiaTextBaseline.Alphabetic)}beginRotate(e,t,s){this._canvas.beginRotate(e*this._scale,t*this._scale,s)}endRotate(){this._canvas.endRotate()}}Pl.musicFont=null,Pl.customTypeFaces=new Map,Pl.FontSizeToLineHeight=1.2;class Fl extends Yo{constructor(e,t,s=!1){super(e.beat,t.beat,s),this.startNote=e,this.endNote=t}getTieHeight(e,t,s,i){return this.startNote===this.endNote?15:super.getTieHeight(e,t,s,i)}getBeamDirection(e,t){return se.Down}static getBeamDirectionForNote(e){return se.Down}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,Qi.Center)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Zi.Right)}getEndX(){return this.endNoteRenderer.getNoteX(this.endNote,Zi.Left)}}class Cl extends Ir{constructor(){super(...arguments),this._tiedNoteTie=null}createTies(e){if(e.isVisible){if(!this._tiedNoteTie&&e.isTieOrigin&&e.tieDestination.isVisible){const t=new Fl(e,e.tieDestination,!1);this._tiedNoteTie=t,this.addTie(t)}if(!this._tiedNoteTie&&e.isTieDestination){const t=new Fl(e.tieOrigin,e,!0);this._tiedNoteTie=t,this.addTie(t)}}}}class Dl extends sh{updateBeamingHelper(e){this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.beat,e+this.x+this.width/2,e+this.x+this.width/2)}paint(e,t,s){super.internalPaint(e,t,s,ds.SlashRests)}}class El extends Rn{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.restGlyph=null}get effectElement(){return ds.SlashEffects}getNoteX(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=s.x;switch(t){case Zi.Left:break;case Zi.Center:e+=s.width/2;break;case Zi.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new Ti;i.note=this.container.beat.notes[0],i.noteHeadBounds=new Hs,i.noteHeadBounds.x=t+this.x+this.noteHeads.x,i.noteHeadBounds.y=s+this.y+this.noteHeads.y-this.noteHeads.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}getNoteY(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=this.y+s.y;switch(t){case Qi.Top:case Qi.TopWithStem:e-=s.height/2+2;break;case Qi.Center:break;case Qi.Bottom:case Qi.BottomWithStem:e+=s.height/2}return e}return 0}updateBeamingHelper(){this.noteHeads?this.noteHeads.updateBeamingHelper(this.container.x+this.x):this.deadSlapped?this.beamingHelper&&this.beamingHelper.registerBeatLineX("slash",this.container.beat,this.container.x+this.x+this.deadSlapped.x+this.width,this.container.x+this.x+this.deadSlapped.x):this.restGlyph&&this.restGlyph.updateBeamingHelper(this.container.x+this.x)}doLayout(){const e=this.renderer,t=e.getNoteLine(),s=e.getLineY(t);if(this.container.beat.deadSlapped){const e=new eh;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addEffect(e)}else if(!this.container.beat.isEmpty)if(this.container.beat.isRest){const e=new Dl(0,s,this.container.beat.duration);this.restGlyph=e,e.beat=this.container.beat,e.beamingHelper=this.beamingHelper,this.addNormal(e),this.beamingHelper&&this.beamingHelper.applyRest(this.container.beat,0)}else{const e=this.container.beat.graceType!==R.None,t=new yh(0,s,this.container.beat.duration,e,this.container.beat);this.noteHeads=t,t.beat=this.container.beat,t.beamingHelper=this.beamingHelper,this.addNormal(t)}if(this.container.beat.dots>0){this.addNormal(new dh(0,0,5));for(let t=0;t<this.container.beat.dots;t++)this.addEffect(new Uo(0,e.getLineY(e.getNoteLine())-e.getLineHeight(.5),1.5))}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.restGlyph?this.centerX=this.restGlyph.x+this.restGlyph.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.deadSlapped&&(this.centerX=this.deadSlapped.x+this.deadSlapped.width/2)}}class Ll extends Gh{constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this._isOnlySlash=!t.staff.showTablature&&!t.staff.showStandardNotation,this.helpers.preferredBeamDirection=se.Up}get repeatsBarSubElement(){return c.SlashRepeats}get barNumberBarSubElement(){return c.SlashBarNumber}get barLineBarSubElement(){return c.SlashBarLines}get staffLineBarSubElement(){return c.SlashStaffLine}get lineSpacing(){return Vn.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return 1}get bottomGlyphOverflow(){return 0}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s,ds.SlashFlags,ds.SlashBeams),this.paintTuplets(e,t,s,ds.SlashTuplet)}doLayout(){super.doLayout();let e=!1;for(const t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}e&&this.registerOverflowTop(this.tupletSize)}getNoteLine(){return 0}getFlagTopY(e,t){const s=Dr.Heights.get(G.NoteheadSlashWhiteHalf);return this.getLineY(0)-s/2}getFlagBottomY(e,t){const s=Dr.Heights.get(G.NoteheadSlashWhiteHalf);return this.getLineY(0)-s/2}getBeamDirection(e){return se.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return Number.isNaN(s)&&(s=this.getLineY(0)),s}calculateBeamYWithDirection(e,t,s){return this.getLineY(0)-this.getFlagStemSize(e.shortestDuration)}getBarLineStart(e,t){const s=Dr.Heights.get(G.NoteheadSlashWhiteHalf);return this.getLineY(0)-s/2}createLinePreBeatGlyphs(){this._isOnlySlash&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new dh(0,0,5));const e=this.bar.masterBar,t=new Th(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime));t.barSubElement=c.SlashTimeSignature,this.addPreBeatGlyph(t)}createVoiceGlyphs(e){for(const t of e.beats){const s=new Cl(t,this.getVoiceContainer(e));s.preNotes=new An,s.onNotes=0===e.index?new El:new Rn,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){const n=hn.beat(r,ds.SlashStem,e);try{r.lineWidth=Vn.StemWidth,r.beginPath(),r.moveTo(s,i),r.lineTo(s,a),r.stroke(),r.lineWidth=1}finally{n?.[Symbol.dispose]?.()}}}Ll.StaffId="slash";class Ml extends rn{get staffId(){return Ll.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new Ll(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showSlash}}class Il extends Yo{constructor(e,t,s=!1){super(e?e.beat:null,t?t.beat:null,s),this.startNote=e,this.endNote=t}shouldDrawBendSlur(){return this.renderer.settings.notation.extendBendArrowsOnTiedNotes&&!!this.startNote.bendOrigin&&this.startNote.isTieOrigin}doLayout(){super.doLayout()}getBeamDirection(e,t){return se.Up}getStartY(){return this.startNoteRenderer.getNoteY(this.startNote,Qi.Top)}getEndY(){return this.getStartY()}getStartX(){return this.startNote===this.endNote?this.getEndX()-20:this.startNoteRenderer.getNoteX(this.startNote,Zi.Center)}getEndX(){return this.startNote===this.endNote?this.endNoteRenderer.getNoteX(this.endNote,Zi.Left):this.endNoteRenderer.getNoteX(this.endNote,Zi.Center)}}class Al extends Yh{constructor(e,t,s,i=!1){super(e,t,i),this._direction=se.Up,this._forSlide=s}getTieHeight(e,t,s,i){return Math.log(s-e+1)*this.renderer.settings.notation.slurHeight}tryExpand(e,t,s,i){if(this._forSlide!==s)return!1;if(this.forEnd!==i)return!1;if(this.startNote.beat.id!==e.beat.id)return!1;if(this.endNote.beat.id!==t.beat.id)return!1;switch(this._direction){case se.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 se.Down:e.realValue<this.startNote.realValue&&(this.startNote=e,this.startBeat=e.beat),t.realValue<this.endNote.realValue&&(this.endNote=t,this.endBeat=t.beat)}return!0}paint(e,t,s){const i=this.renderer.scoreRenderer.layout.getRendererForBar(this.renderer.staff.staveId,this.startBeat.voice.bar),a=this.getBeamDirection(this.startBeat,i),r=`numbered.slur.${this.startNote.beat.id}.${this.endNote.beat.id}.${a}`,n=this.renderer;n.staff.getSharedLayoutData(r,!1)||(n.staff.setSharedLayoutData(r,!0),super.paint(e,t,s))}}class Rl extends Ir{constructor(){super(...arguments),this._effectSlurs=[]}createTies(e){if(e.isVisible){if(e.isTieOrigin&&e.tieDestination.isVisible){const t=new Il(e,e.tieDestination,!1);this.addTie(t)}if(e.isTieDestination){const t=new Il(e.tieOrigin,e,!0);this.addTie(t)}if(e.isLeftHandTapped&&!e.isHammerPullDestination){const t=new Il(e,e,!1);this.addTie(t)}if(e.isEffectSlurOrigin&&e.effectSlurDestination){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e,e.effectSlurDestination,!1,!1)){t=!0;break}if(!t){const t=new Al(e,e.effectSlurDestination,!1,!1);this._effectSlurs.push(t),this.addTie(t)}}if(e.isEffectSlurDestination&&e.effectSlurOrigin){let t=!1;for(const s of this._effectSlurs)if(s.tryExpand(e.effectSlurOrigin,e,!1,!0)){t=!0;break}if(!t){const t=new Al(e.effectSlurOrigin,e,!1,!0);this._effectSlurs.push(t),this.addTie(t)}}}}}class Ol extends Fr{constructor(e,t,s,i,a){super(e,t),this._isGrace=i,this._number=s,this._beat=a}paint(e,t,s){const i=this._beat.isRest?hn.beat(s,ds.NumberedRests,this._beat):this._beat.notes.length>0?hn.note(s,ee.NumberedNumber,this._beat.notes[0]):void 0;try{const i=this.renderer.resources;s.font=this._isGrace?i.numberedNotationGraceFont:i.numberedNotationFont,s.textBaseline=V.Middle,s.textAlign=W.Left,s.fillText(this._number.toString(),e+this.x,t+this.y)}finally{i?.[Symbol.dispose]?.()}}doLayout(){const e=this._isGrace?Lr.GraceScale:1;this.width=Ol.NoteHeadWidth*e,this.height=Ol.NoteHeadHeight*e}}Ol.NoteHeadHeight=17,Ol.NoteHeadWidth=12;class Hl extends Fr{constructor(e,t,s){super(e,t),this._beat=s}doLayout(){this.width=14+Hl.Padding,this.height=zl.BarSize}paint(e,t,s){const i=hn.beat(s,ds.NumberedDuration,this._beat);try{const i=Hl.Padding;s.fillRect(e+this.x,t+this.y,this.width-i,this.height)}finally{i?.[Symbol.dispose]?.()}}}Hl.Padding=3;class Wl extends An{constructor(){super(...arguments),this.isNaturalizeAccidental=!1,this.accidental=p.None}get effectElement(){return ds.NumberedEffects}doLayout(){if(!this.container.beat.isRest&&!this.container.beat.isEmpty){const e=new ah;if(e.renderer=this.renderer,this.container.beat.notes.length>0){const t=this.container.beat.notes[0],s=t?t.accidentalMode:N.Default,i=Ci.getNoteValue(t);let a=Ci.computeAccidental(this.renderer.bar.masterBar.keySignature,s,i,t.hasQuarterToneOffset);if(a===p.Natural){a=this.renderer.bar.masterBar.keySignature+7<7?p.Sharp:p.Flat,this.isNaturalizeAccidental=!0}if(a!==p.None){this.accidental=a;const s=this.renderer,i=hn.noteColor(s.resources,ee.NumberedAccidentals,t),r=new Vo(0,s.getLineY(0),a,t.beat.graceType!==R.None?Lr.GraceScale*Lr.GraceScale:Lr.GraceScale);r.colorOverride=i,r.renderer=this.renderer,e.addGlyph(r),this.addNormal(e),this.addNormal(new dh(0,0,4))}}}super.doLayout()}}class Vl extends Rn{constructor(){super(...arguments),this.noteHeads=null,this.deadSlapped=null,this.octaveDots=0}get effectElement(){return ds.NumberedEffects}getNoteX(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=s.x;switch(t){case Zi.Left:break;case Zi.Center:e+=s.width/2;break;case Zi.Right:e+=s.width}return e}return 0}buildBoundingsLookup(e,t,s){if(this.noteHeads&&this.container.beat.notes.length>0){const i=new Ti;i.note=this.container.beat.notes[0],i.noteHeadBounds=new Hs,i.noteHeadBounds.x=t+this.x+this.noteHeads.x,i.noteHeadBounds.y=s+this.y+this.noteHeads.y-this.noteHeads.height/2,i.noteHeadBounds.w=this.width,i.noteHeadBounds.h=this.height,e.addNote(i)}}getNoteY(e,t){let s=null;if(this.noteHeads?s=this.noteHeads:this.deadSlapped&&(s=this.deadSlapped),s){let e=this.y+s.y;switch(t){case Qi.Top:case Qi.TopWithStem:e-=s.height/2+2;break;case Qi.Center:break;case Qi.Bottom:case Qi.BottomWithStem:e+=s.height/2}return e}return 0}updateBeamingHelper(){if(this.beamingHelper){let e=null;this.noteHeads?e=this.noteHeads:this.deadSlapped&&(e=this.deadSlapped),e&&this.beamingHelper.registerBeatLineX("numbered",this.container.beat,this.container.x+this.x+e.x,this.container.x+this.x+e.x+e.width)}}doLayout(){const e=this.renderer;e.shortestDuration<this.container.beat.duration&&(e.shortestDuration=this.container.beat.duration);const t=e.getLineY(e.getNoteLine());if(!this.container.beat.isEmpty){let s="0";if(this.container.beat.notes.length>0){const t=this.renderer.bar.masterBar.keySignatureType,i=this.renderer.bar.masterBar.keySignature,a=i+7,r=(t===v.Minor?Vl.MinorKeySignatureOneValues:Vl.MajorKeySignatureOneValues)[a],n=this.container.beat.notes[0];if(n.isDead)s="X";else{const t=n.displayValue-r,o=t<0?(t%12+12)%12:t%12;let h=t<0?(Math.abs(t)+12)/12|0:t/12|0;t<0&&(h*=-1),this.octaveDots=h,e.registerOctave(h);let l=(Be.keySignatureIsSharp(i)||Be.keySignatureIsNatural(i)?Ci.FlatNoteSteps:Ci.SharpNoteSteps)[o]+1;Ci.AccidentalNotes[o]&&!this.container.preNotes.isNaturalizeAccidental&&(a<7?l++:l--),s=l.toString()}}if(this.container.beat.deadSlapped){const e=new eh;e.renderer=this.renderer,e.doLayout(),this.deadSlapped=e,this.addEffect(e)}else{const e=this.container.beat.graceType!==R.None,i=new Ol(0,t,s,e,this.container.beat);this.noteHeads=i,this.addNormal(i)}if(this.container.beat.dots>0&&this.container.beat.duration>=D.Quarter){this.addNormal(new dh(0,0,5));for(let t=0;t<this.container.beat.dots;t++){const t=new Uo(0,e.getLineY(0),1.5);t.renderer=this.renderer,this.addEffect(t)}}let i=0;switch(this.container.beat.duration){case D.QuadrupleWhole:i=16;break;case D.DoubleWhole:i=8;break;case D.Whole:i=4;break;case D.Half:i=2}let a=i;for(let e=0;e<this.container.beat.dots;e++)a=a/2|0,i+=a;for(let t=0;t<i-1;t++){const t=new Hl(0,e.getLineY(0),this.container.beat);t.renderer=this.renderer,this.addNormal(t)}}super.doLayout(),this.container.beat.isEmpty?this.centerX=this.width/2:this.noteHeads?this.centerX=this.noteHeads.x+this.noteHeads.width/2:this.deadSlapped&&(this.centerX=this.deadSlapped.x+this.deadSlapped.width/2)}}Vl.MajorKeySignatureOneValues=[59,66,61,68,63,58,65,60,67,62,69,64,71,66,61],Vl.MinorKeySignatureOneValues=[71,66,73,68,63,70,65,72,67,74,69,64,71,66,73];class Gl extends Fr{constructor(e,t,s,i){super(e,t),this._text="",this._accidental=p.None,this._accidentalOffset=0,this._keySignature=s,this._keySignatureType=i}doLayout(){super.doLayout();const e="1 = ";let t="",s=p.None;switch(this._keySignatureType){case v.Major:switch(this._keySignature){case x.Cb:t=" C",s=p.Flat;break;case x.Gb:t=" G",s=p.Flat;break;case x.Db:t=" D",s=p.Flat;break;case x.Ab:t=" A",s=p.Flat;break;case x.Eb:t=" E",s=p.Flat;break;case x.Bb:t=" B",s=p.Flat;break;case x.F:t="F";break;case x.C:t="C",s=p.None;break;case x.G:t="G",s=p.None;break;case x.D:t="D",s=p.None;break;case x.A:t="A",s=p.None;break;case x.E:t="E",s=p.None;break;case x.B:t="B",s=p.None;break;case x.FSharp:t=" F",s=p.Sharp;break;case x.CSharp:t=" C",s=p.Sharp}break;case v.Minor:switch(this._keySignature){case x.Cb:t=" a",s=p.Flat;break;case x.Gb:t=" e",s=p.Flat;break;case x.Db:t=" b",s=p.Flat;break;case x.Ab:t="f",s=p.None;break;case x.Eb:t="c",s=p.None;break;case x.Bb:t="g",s=p.None;break;case x.F:t="d";break;case x.C:t="a",s=p.None;break;case x.G:t="e",s=p.None;break;case x.D:t="b",s=p.None;break;case x.A:t=" f",s=p.Sharp;break;case x.E:t=" c",s=p.Sharp;break;case x.B:t=" g",s=p.Sharp;break;case x.FSharp:t=" d",s=p.Sharp;break;case x.CSharp:t=" a",s=p.Sharp}}this._text=e+t,this._accidental=s;const i=this.renderer.scoreRenderer.canvas,a=this.renderer.resources;i.font=a.numberedNotationFont,this._accidentalOffset=i.measureText(e).width,this.width=i.measureText(e+t).width}paint(e,t,s){const i=hn.bar(s,c.NumberedKeySignature,this.renderer.bar);try{const i=this.renderer.resources;s.font=i.numberedNotationFont,s.textBaseline=V.Middle,s.fillText(this._text,e+this.x,t+this.y),this._accidental!==p.None&&s.fillMusicFontSymbol(e+this.x+this._accidentalOffset,t+this.y,.7,Vo.getMusicSymbol(this._accidental),!1)}finally{i?.[Symbol.dispose]?.()}}}class zl extends Gh{registerOctave(e){null===this.lowestOctave?(this.lowestOctave=e,this.highestOctave=e):(e<this.lowestOctave&&(this.lowestOctave=e),e>this.highestOctave&&(this.highestOctave=e))}get repeatsBarSubElement(){return c.NumberedRepeats}get barNumberBarSubElement(){return c.NumberedBarNumber}get barLineBarSubElement(){return c.NumberedBarLines}get staffLineBarSubElement(){return c.NumberedStaffLine}constructor(e,t){super(e,t),this.simpleWhammyOverflow=0,this.shortestDuration=D.QuadrupleWhole,this.lowestOctave=null,this.highestOctave=null,this._isOnlyNumbered=!t.staff.showSlash&&!t.staff.showTablature&&!t.staff.showStandardNotation}get lineSpacing(){return Vn.RawLineSpacing}get heightLineCount(){return 5}get drawnLineCount(){return 0}get bottomGlyphOverflow(){return 0}paint(e,t,s){super.paint(e,t,s),this.paintBeams(e,t,s,ds.NumberedDuration,ds.NumberedDuration),this.paintTuplets(e,t,s,ds.NumberedTuplet,!0)}doLayout(){super.doLayout();let e=!1;for(const t of this.bar.voices)if(this.hasVoiceContainer(t)){if(this.getVoiceContainer(t).tupletGroups.length>0){e=!0;break}}if(e&&this.registerOverflowTop(this.tupletSize),!this.bar.isEmpty){const e=Be.getIndex(this.shortestDuration)-2;if(e>0){const t=(e-1)*zl.BarSpacing+zl.BarSize;let s=0;const i=this.lowestOctave;null!==i&&(s=Math.abs(i)*zl.DotSpacing+zl.DotSize),this.registerOverflowBottom(t+s)}const t=this.highestOctave;if(null!==t){const e=Math.abs(t)*zl.DotSpacing+zl.DotSize;this.registerOverflowTop(e)}}}paintFlag(e,t,s,i,a){this.paintBar(e,t,s,i,a)}paintBar(e,t,s,i,a){if(0===i.beats.length)return;const r=this.resources;for(let n=0,o=i.beats.length;n<o;n++){const o=i.beats[n],h=hn.beat(s,a,o);try{const a=zl.BarSpacing,h=zl.BarSize,l=Be.getIndex(o.duration)-2,c=t+this.y,d=this.getBeatX(o,Ki.PreNotes)-this.beatGlyphsStart,u=this.calculateBeamY(i,d);for(let t=0;t<l;t++){let r=0,l=0,p=0;const g=c+t*a;n===i.beats.length-1?(r=d,l=this.getBeatX(o,Ki.PostNotes)-this.beatGlyphsStart):(r=d,l=this.getBeatX(i.beats[n+1],Ki.PreNotes)-this.beatGlyphsStart),p=g+u|0,Gh.paintSingleBar(s,e+this.x+r,p,e+this.x+l,p,h)}const p=this.getBeatContainer(o).onNotes;let g=p instanceof Vl?p.octaveDots:0,m=0,f=0;g>0?(m=c+this.getLineY(0)-r.numberedNotationFont.size/1.5,f=-1*zl.DotSpacing):g<0&&(m=c+u+l*a,f=zl.DotSpacing);const y=this.getBeatX(o,Ki.OnNotes)+4-this.beatGlyphsStart;g=Math.abs(g);for(let t=0;t<g;t++)s.fillCircle(e+this.x+y,m,zl.DotSize),m+=f}finally{h?.[Symbol.dispose]?.()}}}getNoteLine(){return 0}get tupletOffset(){return super.tupletOffset+this.resources.numberedNotationFont.size}getFlagTopY(e,t){const s=Dr.Heights.get(G.NoteheadBlack);return this.getLineY(0)-s/2}getFlagBottomY(e,t){const s=Dr.Heights.get(G.NoteheadBlack);return this.getLineY(0)-s/2}getBeamDirection(e){return se.Down}getTupletBeamDirection(e){return se.Up}getNoteY(e,t){let s=super.getNoteY(e,t);return Number.isNaN(s)&&(s=this.getLineY(0)),s}calculateBeamYWithDirection(e,t,s){const i=this.resources.numberedNotationFont;return this.getLineY(0)+i.size}getBarLineStart(e,t){const s=Dr.Heights.get(G.NoteheadBlack);return this.getLineY(0)-s/2}createPreBeatGlyphs(){this.wasFirstOfLine=this.isFirstOfLine,(0===this.index||this.bar.masterBar.isRepeatStart&&this._isOnlyNumbered)&&this.addPreBeatGlyph(new Hh(!1)),this.createLinePreBeatGlyphs(),this.addPreBeatGlyph(new Vh(0,this.getLineHeight(-.25),this.bar.index+1))}createLinePreBeatGlyphs(){this.bar.previousBar&&this.bar.masterBar.keySignature===this.bar.previousBar.masterBar.keySignature||(this.createStartSpacing(),this.createKeySignatureGlyphs()),this._isOnlyNumbered&&(!this.bar.previousBar||this.bar.previousBar&&this.bar.masterBar.timeSignatureNumerator!==this.bar.previousBar.masterBar.timeSignatureNumerator||this.bar.previousBar&&this.bar.masterBar.timeSignatureDenominator!==this.bar.previousBar.masterBar.timeSignatureDenominator||this.bar.previousBar&&this.bar.masterBar.isFreeTime&&this.bar.masterBar.isFreeTime!==this.bar.previousBar.masterBar.isFreeTime)&&(this.createStartSpacing(),this.createTimeSignatureGlyphs())}createKeySignatureGlyphs(){this.addPreBeatGlyph(new Gl(0,this.getLineY(0),this.bar.masterBar.keySignature,this.bar.masterBar.keySignatureType))}createTimeSignatureGlyphs(){this.addPreBeatGlyph(new dh(0,0,5));const e=this.bar.masterBar,t=new Th(0,this.getLineY(0),e.timeSignatureNumerator,e.timeSignatureDenominator,e.timeSignatureCommon,e.isFreeTime&&(null==e.previousMasterBar||e.isFreeTime!==e.previousMasterBar.isFreeTime));t.barSubElement=c.NumberedTimeSignature,this.addPreBeatGlyph(t)}createPostBeatGlyphs(){this._isOnlyNumbered&&super.createPostBeatGlyphs()}createVoiceGlyphs(e){for(const t of e.beats){const s=new Rl(t,this.getVoiceContainer(e));s.preNotes=0===e.index?new Wl:new An,s.onNotes=0===e.index?new Vl:new Rn,this.addBeatGlyph(s)}}paintBeamingStem(e,t,s,i,a,r){}}zl.StaffId="numbered",zl.BarSpacing=Vn.BeamSpacing+Vn.BeamThickness,zl.BarSize=2,zl.DotSpacing=5,zl.DotSize=2;class Ul extends rn{get staffId(){return Ll.StaffId}getStaffPaddingTop(e){return e.system.layout.renderer.settings.display.notationStaffPaddingTop}getStaffPaddingBottom(e){return e.system.layout.renderer.settings.display.notationStaffPaddingBottom}create(e,t){return new zl(e,t)}canCreate(e,t){return super.canCreate(e,t)&&t.showNumbered}}class Xl extends qn{get notationElement(){return T.EffectText}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ea.SinglePreBeat}shouldCreateGlyph(e,t){const s=t.voice.bar.masterBar;return 0===t.voice.bar.staff.index&&0===t.voice.index&&0===t.index&&s.isFreeTime&&(0===s.index||s.isFreeTime!==s.previousMasterBar.isFreeTime)}createNewGlyph(e,t){return new Bn(0,0,"Free time",e.resources.effectFont,W.Left)}canExpand(e,t){return!0}}class Jl extends Cr{constructor(){super(0,0)}doLayout(){super.doLayout(),this.height=Dr.Heights.get(G.KeyboardPedalPed)}paint(e,t,s){const i=this.renderer,a=t+this.y,r=this.height,n=i.bar.sustainPedals,o=Dr.Widths.get(G.KeyboardPedalPed),h=Dr.Widths.get(G.KeyboardPedalUp);let c=0;for(;c<n.length;){let t=n[c];for(;null!=t;){const i=e+this.renderer.getRatioPositionX(t.ratioPosition);let d=0;if(t.pedalType===l.Down?(s.fillMusicFontSymbol(i,a+r,1,G.KeyboardPedalPed,!0),d=o/2+Jl.TextLinePadding):t.pedalType===l.Up&&(s.fillMusicFontSymbol(i,a+r,1,G.KeyboardPedalUp,!0),d=h/2+Jl.StarLinePadding),t.nextPedalMarker)if(t.nextPedalMarker.bar===t.bar){let n=e+this.renderer.getRatioPositionX(t.nextPedalMarker.ratioPosition);switch(t.nextPedalMarker.pedalType){case l.Down:n-=o/2;break;case l.Hold:break;case l.Up:n-=h/2}const c=i+d;n>c&&s.fillRect(c,a+r-1,n-c,1)}else{const t=e+this.x+this.width,n=i+d;s.fillRect(n,a+r-1,t-n,1)}if(0===c&&t.previousPedalMarker){const t=e+this.x,n=i-d;s.fillRect(t,a+r-1,n-t,1)}c++,null!=t.nextPedalMarker&&t.nextPedalMarker.bar!==t.bar?(t=null,c=n.length):t=t.nextPedalMarker}}}}Jl.TextLinePadding=3,Jl.StarLinePadding=3;class Yl extends qn{get notationElement(){return T.EffectSustainPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!1}get sizingMode(){return ea.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&t.voice.bar.sustainPedals.length>0}createNewGlyph(e,t){return new Jl}canExpand(e,t){return!0}}class $l extends qn{constructor(e,t){super(),this._type=e,this._shouldCreate=t}get notationElement(){return T.EffectGolpe}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ea.SingleOnBeat}shouldCreateGlyph(e,t){const s=this._shouldCreate;return t.golpe===this._type&&(!s||s(e,t))}createNewGlyph(e,t){return new mh(0,0,!0)}canExpand(e,t){return!1}}class ql extends Er{constructor(e){super(0,0,1,ql.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case ie.Open:return G.GuitarOpenPedal;case ie.Closed:return G.GuitarClosePedal}return G.None}paint(e,t,s){super.paint(e,t+this.height,s)}}class Kl extends qn{get notationElement(){return T.EffectWahPedal}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ea.SingleOnBeat}shouldCreateGlyph(e,t){return t.wahPedal!==ie.None}createNewGlyph(e,t){return new ql(t.wahPedal)}canExpand(e,t){return!1}}class jl extends qn{get notationElement(){return T.EffectLetRing}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.isBarre}get sizingMode(){return ea.GroupedOnBeat}createNewGlyph(e,t){let s="";switch(t.barreShape){case m.None:case m.Full:break;case m.Half:s+="1/2"}return s+=`B ${jl.toRoman(t.barreFret)}`,new co(s,!1)}static toRoman(e){let t="";if(e>0)for(const[s,i]of jl.RomanLetters){const a=Math.floor(e/i);e-=a*i,t+=s.repeat(a)}return t}canExpand(e,t){return e.barreFret===t.barreFret&&e.barreShape===t.barreShape}}jl.RomanLetters=new Map([["L",50],["XL",40],["X",10],["IX",9],["V",5],["IV",4],["I",1]]);class Ql extends Er{constructor(e){super(0,0,1,Ql.getSymbol(e)),this.center=!0}static getSymbol(e){switch(e){case Z.InvertedTurn:return G.OrnamentTurnInverted;case Z.Turn:return G.OrnamentTurn;case Z.UpperMordent:return G.OrnamentShortTrill;case Z.LowerMordent:return G.OrnamentMordent}return G.None}paint(e,t,s){super.paint(e,t+this.height-4,s)}}class Zl extends qn{get notationElement(){return T.EffectNoteOrnament}get hideOnMultiTrack(){return!1}get canShareBand(){return!0}get sizingMode(){return ea.SingleOnBeat}shouldCreateGlyph(e,t){return t.notes.some((e=>e.ornament!==Z.None))}createNewGlyph(e,t){return new Ql(t.notes.find((e=>e.ornament!==Z.None)).ornament)}canExpand(e,t){return!1}}class ec extends qn{get notationElement(){return T.EffectRasgueado}get canShareBand(){return!1}get hideOnMultiTrack(){return!1}shouldCreateGlyph(e,t){return t.hasRasgueado}get sizingMode(){return ea.GroupedOnBeat}createNewGlyph(e,t){return new co("rasg.")}canExpand(e,t){return!0}}class tc extends Fr{constructor(e){super(0,0),this._symbols=e}doLayout(){this.height=27}paint(e,t,s){s.fillMusicFontSymbols(e+this.x,t+this.y+this.height,.8,this._symbols,!0)}}class sc extends Fr{constructor(e){super(0,0),this._text=e}doLayout(){this.height=1.5*this.renderer.resources.directionsFont.size}paint(e,t,s){const i=s.font,a=s.textBaseline,r=s.textAlign;s.font=this.renderer.resources.directionsFont,s.textBaseline=V.Middle,s.textAlign=W.Right,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=i,s.textBaseline=a,s.textAlign=r}}class ic extends Cr{constructor(e,t,s){super(e,t),this._barBeginGlyphs=[],this._barEndGlyphs=[],this._directions=s}doLayout(){const e=this._directions;e.has(C.TargetSegnoSegno)&&this._barBeginGlyphs.push(new tc([G.Segno,G.Segno])),e.has(C.TargetSegno)&&this._barBeginGlyphs.push(new tc([G.Segno])),e.has(C.TargetDoubleCoda)&&this._barBeginGlyphs.push(new tc([G.Coda,G.Coda])),e.has(C.TargetCoda)&&this._barBeginGlyphs.push(new tc([G.Coda])),e.has(C.TargetFine)&&this._barEndGlyphs.push(new sc("Fine")),e.has(C.JumpDaDoubleCoda)&&this._barEndGlyphs.push(new sc("To Double Coda")),e.has(C.JumpDaCoda)&&this._barEndGlyphs.push(new sc("To Coda")),e.has(C.JumpDalSegnoSegno)&&this._barEndGlyphs.push(new sc("D.S.S.")),e.has(C.JumpDalSegnoSegnoAlCoda)&&this._barEndGlyphs.push(new sc("D.S.S. al Coda")),e.has(C.JumpDalSegnoSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new sc("D.S.S. al Double Coda")),e.has(C.JumpDalSegnoSegnoAlFine)&&this._barEndGlyphs.push(new sc("D.S.S. al Fine")),e.has(C.JumpDalSegno)&&this._barEndGlyphs.push(new sc("D.S.")),e.has(C.JumpDalSegnoAlCoda)&&this._barEndGlyphs.push(new sc("D.S. al Coda")),e.has(C.JumpDalSegnoAlDoubleCoda)&&this._barEndGlyphs.push(new sc("D.S. al Double Coda")),e.has(C.JumpDalSegnoAlFine)&&this._barEndGlyphs.push(new sc("D.S. al Fine")),e.has(C.JumpDaCapo)&&this._barEndGlyphs.push(new sc("D.C.")),e.has(C.JumpDaCapoAlCoda)&&this._barEndGlyphs.push(new sc("D.C. al Coda")),e.has(C.JumpDaCapoAlDoubleCoda)&&this._barEndGlyphs.push(new sc("D.C. al Double Coda")),e.has(C.JumpDaCapoAlFine)&&this._barEndGlyphs.push(new sc("D.C. al Fine"));const t=this.doSideLayout(this._barBeginGlyphs),s=this.doSideLayout(this._barEndGlyphs);this.height=Math.max(t,s)}doSideLayout(e){let t=0;for(const s of e)s.y=t,s.renderer=this.renderer,s.doLayout(),t+=s.height+3;return t}paint(e,t,s){for(const i of this._barBeginGlyphs)i.paint(e+this.x,t+this.y,s);for(const i of this._barEndGlyphs)i.paint(e+this.x+this.width,t+this.y,s)}}class ac extends qn{get notationElement(){return T.EffectDirections}get hideOnMultiTrack(){return!0}get canShareBand(){return!1}get sizingMode(){return ea.FullBar}shouldCreateGlyph(e,t){return 0===t.voice.index&&0===t.index&&null!==t.voice.bar.masterBar.directions&&t.voice.bar.masterBar.directions.size>0}createNewGlyph(e,t){return new ic(0,0,t.voice.bar.masterBar.directions)}canExpand(e,t){return!0}}class rc extends Cr{constructor(e){super(0,0),this._text="",this._textWidth=0,this._textHeight=0,this._timer=e}doLayout(){const e=this._timer/6e4|0,t=(this._timer-6e4*e)/1e3|0;this._text=`${e}:${t.toString().padStart(2,"0")}`;const s=this.renderer.scoreRenderer.canvas;s.font=this.renderer.resources.timerFont;const i=s.measureText(this._text);this._textHeight=s.font.size+2*rc.PaddingY,this._textWidth=i.width+2*rc.PaddingX,this.height=this._textHeight+2*rc.MarginY}paint(e,t,s){const i=this._textWidth/2|0;s.strokeRect(e+this.x-i,t+this.y+rc.MarginY,this._textWidth,this._textHeight);const a=s.font,r=s.textBaseline,n=s.textAlign;s.font=this.renderer.resources.timerFont,s.textBaseline=V.Middle,s.textAlign=W.Center,s.fillText(this._text,e+this.x,t+this.y+this.height/2),s.font=a,s.textBaseline=r,s.textAlign=n}}rc.PaddingX=2,rc.PaddingY=2,rc.MarginY=2;class nc extends qn{get notationElement(){return T.EffectBeatTimer}get hideOnMultiTrack(){return!0}get canShareBand(){return!0}get sizingMode(){return ea.SingleOnBeat}shouldCreateGlyph(e,t){return t.showTimer}createNewGlyph(e,t){return new rc(t.timer??0)}canExpand(e,t){return!0}}class oc{static print(e){e(`alphaTab ${oc.version}`),e(`commit: ${oc.commit}`),e(`build date: ${oc.date}`)}}oc.version="1.5.0-alpha.1377",oc.date="2025-04-16T02:03:16.243Z",oc.commit="9567c0b4ba99e9bdd087f408e2904537e78f2757";class hc{constructor(e,t){this.vertical=e,this.createLayout=t}}class lc{constructor(e,t){this.supportsWorkers=e,this.createCanvas=t}}class cc{static createStyleElement(e,t){let s=e.getElementById("alphaTabStyle");if(!s){if(!t)return void wt.error("AlphaTab","Font directory could not be detected, cannot create style element");s=e.createElement("style"),s.id="alphaTabStyle";const i=`\n @font-face {\n font-display: block;\n font-family: 'alphaTab';\n src: url('${t}Bravura.eot');\n src: url('${t}Bravura.eot?#iefix') format('embedded-opentype')\n , url('${t}Bravura.woff') format('woff')\n , url('${t}Bravura.otf') format('opentype')\n , url('${t}Bravura.svg#Bravura') format('svg');\n font-weight: normal;\n font-style: normal;\n }\n .at-surface * {\n cursor: default;\n vertical-align: top;\n overflow: visible;\n }\n .at-surface-svg text {\n dominant-baseline: central;\n white-space:pre;\n }\n .at {\n font-family: 'alphaTab';\n speak: none;\n font-style: normal;\n font-weight: normal;\n font-variant: normal;\n text-transform: none;\n line-height: 1;\n line-height: 1;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n font-size: ${cc.MusicFontSize}px;\n overflow: visible !important;\n }`;s.innerHTML=i,e.getElementsByTagName("head").item(0).appendChild(s),cc.bravuraFontChecker.checkForFontAvailability()}}static get globalThis(){if(void 0===cc._globalThis){try{cc._globalThis=globalThis}catch(e){}void 0===cc._globalThis&&(cc._globalThis=self),void 0===cc._globalThis&&(cc._globalThis=global),void 0===cc._globalThis&&(cc._globalThis=window),void 0===cc._globalThis&&(cc._globalThis=Function("return this")())}return cc._globalThis}static get isRunningInWorker(){return"WorkerGlobalScope"in cc.globalThis}static get isRunningInAudioWorklet(){return"AudioWorkletGlobalScope"in cc.globalThis}static throttle(e,t){let s=0;return()=>{cc.globalThis.clearTimeout(s),s=cc.globalThis.setTimeout(e,t)}}static detectScriptFile(){if(!cc.isRunningInWorker&&cc.globalThis.ALPHATAB_ROOT){let e=cc.globalThis.ALPHATAB_ROOT;return e=cc.ensureFullUrl(e),e=cc.appendScriptName(e),e}try{const e=import.meta.url;if(e&&-1===e.indexOf("file://"))return e}catch(e){}return"document"in cc.globalThis&&document.currentScript?document.currentScript.src:null}static ensureFullUrl(e){if(!e)return"";if(!e.startsWith("http")&&!e.startsWith("https")&&!e.startsWith("file")){let t="";const s=cc.globalThis.location;if(t+=s.protocol?.toString(),t+="//"?.toString(),s.hostname&&(t+=s.hostname?.toString()),s.port&&(t+=":"?.toString(),t+=s.port?.toString()),!e.startsWith("/")){const e=s.pathname.split("/").slice(0,-1).join("/");e.length>0&&(e.startsWith("/")||(t+="/"?.toString()),t+=e?.toString())}return e.startsWith("/")||(t+="/"?.toString()),t+=e?.toString(),t}return e}static appendScriptName(e){return e&&!e.endsWith(".js")&&(e.endsWith("/")||(e+="/"),e+="alphaTab.js"),e}static detectFontDirectory(){if(!cc.isRunningInWorker&&cc.globalThis.ALPHATAB_FONT)return cc.ensureFullUrl(cc.globalThis.ALPHATAB_FONT);const e=cc.scriptFile;if(e){const t=e.lastIndexOf(String.fromCharCode(47));if(t>=0)return`${e.substr(0,t)}/font/`}return null}static registerJQueryPlugin(){if(!cc.isRunningInWorker&&cc.globalThis&&"jQuery"in cc.globalThis){const e=cc.globalThis.jQuery,t=new an;e.fn.alphaTab=function(e){const s=Array.prototype.slice.call(arguments,1);return 1===this.length?t.exec(this[0],e,s):this.each(((i,a)=>{t.exec(a,e,s)}))},e.alphaTab={restore:an.restore},e.fn.alphaTab.fn=t}}static getRenderEngineFactory(e){return e&&cc.renderEngines.has(e)?cc.renderEngines.get(e):cc.renderEngines.get("default")}static getLayoutEngineFactory(t){return t&&cc.layoutEngines.has(t)?cc.layoutEngines.get(t):cc.layoutEngines.get(e.Page)}static buildImporters(){return[new As,new yi,new ui,new Mi,new Bl,new Is]}static createDefaultRenderEngines(){const e=new Map;return e.set("svg",new lc(!0,(()=>new Ss))),e.set("default",e.get("svg")),e.set("skia",new lc(!1,(()=>new Pl))),cc.createPlatformSpecificRenderEngines(e),e}static enableAlphaSkia(e,t){Pl.enable(e,t)}static registerAlphaSkiaCustomFont(e,t){return Pl.registerFont(e,t)}static createPlatformSpecificRenderEngines(e){e.set("html5",new lc(!1,(()=>new gr)))}static createDefaultRenderers(){return[new Yn(cc.StaffIdBeforeSlashAlways,[new Fo,new Mo,new fo,new ac,new Kn,new Xl,new Co,new nc,new Qn]),new Ml,new Yn(cc.StaffIdBeforeScoreAlways,[new oo,new jl,new Zl,new ec,new Kl]),new Yn(cc.StaffIdBeforeScoreHideable,[new Io,new Eo,new bo(!0),new Ao,new To,new Ro,new xo(!1),new ol,new $l(O.Finger)],((e,t)=>t.showStandardNotation)),new Xh,new Yn(cc.StaffIdBeforeNumberedAlways,[new to,new bo(!1),new io,new $l(O.Thumb,((e,t)=>t.voice.bar.staff.showStandardNotation)),new Yl]),new Ul,new Yn(cc.StaffIdBeforeTabAlways,[new mo]),new Yn(cc.StaffIdBeforeTabHideable,[new Eo,new Ao,new To,new Ro,new xo(!0),new vo,new ro,new uo(H.Natural),new uo(H.Artificial),new uo(H.Pinch),new uo(H.Tap),new uo(H.Semi),new uo(H.Feedback),new po,new jn,new ho,new So,new Bo,new _o,new ol,new $l(O.Finger,((e,t)=>!t.voice.bar.staff.showStandardNotation))],((e,t)=>t.showTablature)),new rl,new Yn(cc.StaffIdBeforeEndAlways,[new $l(O.Thumb,((e,t)=>!t.voice.bar.staff.showStandardNotation))])]}static createDefaultStaveProfiles(){const e=new Map,s=cc.createDefaultRenderers();e.set(t.Default,s),e.set(t.ScoreTab,s);const i=new Set([cc.StaffIdBeforeSlashAlways,cc.StaffIdBeforeScoreAlways,cc.StaffIdBeforeNumberedAlways,cc.StaffIdBeforeTabAlways,Uh.StaffId,cc.StaffIdBeforeEndAlways]);e.set(t.Score,s.filter((e=>i.has(e.staffId))));const a=new Set([cc.StaffIdBeforeSlashAlways,cc.StaffIdBeforeScoreAlways,cc.StaffIdBeforeNumberedAlways,cc.StaffIdBeforeTabAlways,al.StaffId,cc.StaffIdBeforeEndAlways]);return e.set(t.Tab,cc.createDefaultRenderers().filter((e=>{if(e instanceof rl){const t=e;t.showTimeSignature=!0,t.showRests=!0,t.showTiedNotes=!0}return a.has(e.staffId)}))),e.set(t.TabMixed,cc.createDefaultRenderers().filter((e=>{if(e instanceof rl){const t=e;t.showTimeSignature=!1,t.showRests=!1,t.showTiedNotes=!1}return a.has(e.staffId)}))),e}static createDefaultLayoutEngines(){const t=new Map;return t.set(e.Page,new hc(!0,(e=>new Wo(e)))),t.set(e.Horizontal,new hc(!1,(e=>new Ho(e)))),t}static initializeMain(e,t){cc.isRunningInWorker||cc.isRunningInAudioWorklet||(cc.webPlatform!==us.Browser&&cc.webPlatform!==us.BrowserModule||(cc.registerJQueryPlugin(),cc.HighDpiFactor=window.devicePixelRatio,"ResizeObserver"in cc.globalThis||(cc.globalThis.ResizeObserver=kl),"IntersectionObserver"in cc.globalThis||(cc.globalThis.IntersectionObserver=Tl),"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)})),cc.createWebWorker=e,cc.createAudioWorklet=t)}static get alphaTabWorker(){return cc.globalThis.Worker}static get alphaTabUrl(){return cc.globalThis.URL}static initializeWorker(){if(!cc.isRunningInWorker)throw new fe(S.General,"Not running in worker, cannot run worker initialization");pr.init(),ur.init(),cc.createWebWorker=e=>{throw new fe(S.General,"Nested workers are not supported")}}static initializeAudioWorklet(){if(!cc.isRunningInAudioWorklet)throw new fe(S.General,"Not running in audio worklet, cannot run worklet initialization");Qr.init()}static detectWebPack(){try{if("function"==typeof __webpack_require__)return!0}catch(e){}return!1}static detectVite(){try{if("string"==typeof __BASE__)return!0}catch(e){}return!1}static detectWebPlatform(){try{if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return us.NodeJs}catch(e){}try{const e=import.meta.url;if(e&&"string"==typeof e&&!e.startsWith("file://"))return us.BrowserModule}catch(e){}return us.Browser}static printEnvironmentInfo(e=!0){const t=e?e=>{wt.log.debug("VersionInfo",e)}:e=>{wt.debug("VersionInfo",e)};oc.print(t),t(`High DPI: ${cc.HighDpiFactor}`),cc.printPlatformInfo(t)}static printPlatformInfo(e){e(`Browser: ${navigator.userAgent}`),e(`Platform: ${us[cc.webPlatform]}`),e(`WebPack: ${cc.isWebPackBundled}`),e(`Vite: ${cc.isViteBundled}`),cc.webPlatform!==us.NodeJs&&(e(`Window Size: ${window.outerWidth}x${window.outerHeight}`),e(`Screen Size: ${window.screen.width}x${window.screen.height}`))}}cc.StaffIdBeforeSlashAlways="before-slash-always",cc.StaffIdBeforeScoreAlways="before-score-always",cc.StaffIdBeforeScoreHideable="before-score-hideable",cc.StaffIdBeforeNumberedAlways="before-numbered-always",cc.StaffIdBeforeTabAlways="before-tab-always",cc.StaffIdBeforeTabHideable="before-tab-hideable",cc.StaffIdBeforeEndAlways="before-end-always",cc.MusicFontSize=34,cc.HighDpiFactor=1,cc._globalThis=void 0,cc.webPlatform=cc.detectWebPlatform(),cc.isWebPackBundled=cc.detectWebPack(),cc.isViteBundled=cc.detectVite(),cc.scriptFile=cc.detectScriptFile(),cc.fontDirectory=cc.detectFontDirectory(),cc.bravuraFontChecker=new Ur(["alphaTab"]),cc.renderEngines=cc.createDefaultRenderEngines(),cc.layoutEngines=cc.createDefaultLayoutEngines(),cc.staveProfiles=cc.createDefaultStaveProfiles();class dc{constructor(){this.scriptFile=null,this.fontDirectory=null,this.file=null,this.tex=!1,this.tracks=null,this.enableLazyLoading=!0,this.engine="default",this.logLevel=$.Info,this.useWorkers=!0,this.includeNoteBounds=!1,this.scriptFile=cc.scriptFile,this.fontDirectory=cc.fontDirectory}}const uc=Object.freeze(Object.defineProperty({__proto__:null,ScoreImporter:Ds,ScoreLoader:Vr,UnsupportedFormatError:Es},Symbol.toStringTag,{value:"Module"})),pc=Object.freeze(Object.defineProperty({__proto__:null,ByteBuffer:Me,IOHelper:Le},Symbol.toStringTag,{value:"Module"}));class gc{init(e,t){this.data=e,this.settings=t}export(e,t=null){const s=Me.withCapacity(1024);return this.init(s,t??new ut),this.writeScore(e),s.toArray()}}var mc;!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"}(mc||(mc={}));class fc{constructor(e,t,s=null){if(this.icon=mc.Piano,this.icon=e,this.instrumentSetName=t,s)this.instrumentSetType=s;else{const e=t.split(" ");e[0]=e[0].substr(0,1).toLowerCase()+e[0].substr(1),this.instrumentSetType=e.join("")}}}class yc{constructor(){this._rhythmIdLookup=new Map}writeXml(e){const t=new Xs;return this._rhythmIdLookup=new Map,this.writeDom(t,e),t.toFormattedString("",!0)}writeDom(e,t){const s=e.addElement("GPIF");s.addElement("GPVersion").innerText="7";const i=s.addElement("GPRevision");i.innerText="7",i.attributes.set("required","12021"),i.attributes.set("recommended","12023"),i.innerText="12025",s.addElement("Encoding").addElement("EncodingDescription").innerText="GP7",this.writeScoreNode(s,t),this.writeMasterTrackNode(s,t),this.writeAudioTracksNode(s,t),this.writeTracksNode(s,t),this.writeMasterBarsNode(s,t);const a=s.addElement("Bars"),r=s.addElement("Voices"),n=s.addElement("Beats"),o=s.addElement("Notes"),h=s.addElement("Rhythms");for(const e of t.tracks)for(const t of e.staves)for(const e of t.bars){this.writeBarNode(a,e);for(const t of e.voices){this.writeVoiceNode(r,t);for(const e of t.beats){this.writeBeatNode(n,e,h);for(const t of e.notes)this.writeNoteNode(o,t)}}}}writeNoteNode(e,t){const s=e.addElement("Note");s.attributes.set("id",t.id.toString()),this.writeNoteProperties(s,t),t.isGhost&&(s.addElement("AntiAccent").innerText="normal"),t.isLetRing&&s.addElement("LetRing"),t.isTrill&&(s.addElement("Trill").innerText=t.trillValue.toString());let i=0;switch(t.isStaccato&&(i|=1),t.accentuated){case u.Normal:i|=8;break;case u.Heavy:i|=4;break;case u.Tenuto:i|=16}if(i>0&&(s.addElement("Accent").innerText=i.toString()),t.isTieOrigin||t.isTieDestination){const e=s.addElement("Tie");e.attributes.set("origin",t.isTieOrigin?"true":"false"),e.attributes.set("destination",t.isTieDestination?"true":"false")}switch(t.vibrato){case j.Slight:s.addElement("Vibrato").innerText="Slight";break;case j.Wide:s.addElement("Vibrato").innerText="Wide"}if(t.isFingering){switch(t.leftHandFinger){case _.Thumb:s.addElement("LeftFingering").innerText="P";break;case _.IndexFinger:s.addElement("LeftFingering").innerText="I";break;case _.MiddleFinger:s.addElement("LeftFingering").innerText="M";break;case _.AnnularFinger:s.addElement("LeftFingering").innerText="A";break;case _.LittleFinger:s.addElement("LeftFingering").innerText="C"}switch(t.rightHandFinger){case _.Thumb:s.addElement("RightFingering").innerText="P";break;case _.IndexFinger:s.addElement("RightFingering").innerText="I";break;case _.MiddleFinger:s.addElement("RightFingering").innerText="M";break;case _.AnnularFinger:s.addElement("RightFingering").innerText="A";break;case _.LittleFinger:s.addElement("RightFingering").innerText="C"}}t.percussionArticulation>=0?s.addElement("InstrumentArticulation").innerText=t.percussionArticulation.toString():s.addElement("InstrumentArticulation").innerText="0",t.ornament!==Z.None&&(s.addElement("Ornament").innerText=Z[t.ornament])}writeNoteProperties(e,t){const s=e.addElement("Properties");if(this.writeConcertPitch(s,t),this.writeTransposedPitch(s,t),t.isStringed&&(this.writeSimplePropertyNode(s,"String","String",(t.string-1).toString()),this.writeSimplePropertyNode(s,"Fret","Fret",t.fret.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString()),t.showStringNumber&&this.writeSimplePropertyNode(s,"ShowStringNumber","Enable",null)),t.isPiano&&(this.writeSimplePropertyNode(s,"Octave","Number",t.octave.toString()),this.writeSimplePropertyNode(s,"Tone","Step",t.tone.toString()),this.writeSimplePropertyNode(s,"Midi","Number",t.realValue.toString())),t.beat.tap&&this.writeSimplePropertyNode(s,"Tapped","Enable",null),t.harmonicType!==H.None){switch(t.harmonicType){case H.Natural:this.writeSimplePropertyNode(s,"HarmonicType","HType","Natural");break;case H.Artificial:this.writeSimplePropertyNode(s,"HarmonicType","HType","Artificial");break;case H.Pinch:this.writeSimplePropertyNode(s,"HarmonicType","HType","Pinch");break;case H.Tap:this.writeSimplePropertyNode(s,"HarmonicType","HType","Tap");break;case H.Semi:this.writeSimplePropertyNode(s,"HarmonicType","HType","Semi");break;case H.Feedback:this.writeSimplePropertyNode(s,"HarmonicType","HType","Feedback")}0!==t.harmonicValue&&this.writeSimplePropertyNode(s,"HarmonicFret","HFret",t.harmonicValue.toString())}t.isDead&&this.writeSimplePropertyNode(s,"Muted","Enable",null),t.isPalmMute&&this.writeSimplePropertyNode(s,"PalmMuted","Enable",null),t.hasBend&&this.writeBend(s,t),t.isHammerPullOrigin&&this.writeSimplePropertyNode(s,"HopoOrigin","Enable",null),t.isHammerPullDestination&&this.writeSimplePropertyNode(s,"HopoDestination","Enable",null),t.isLeftHandTapped&&this.writeSimplePropertyNode(s,"LeftHandTapped","Enable",null);let i=0;switch(t.slideInType){case q.IntoFromAbove:i|=32;break;case q.IntoFromBelow:i|=16}switch(t.slideOutType){case K.Shift:i|=1;break;case K.Legato:i|=2;break;case K.OutDown:i|=4;break;case K.OutUp:i|=8;break;case K.PickSlideDown:i|=64;break;case K.PickSlideUp:i|=128}i>0&&this.writeSimplePropertyNode(s,"Slide","Flags",i.toString())}writeTransposedPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"TransposedPitch",t.displayValueWithoutBend,t.accidentalMode)}writeConcertPitch(e,t){t.isPercussion?this.writePitch(e,"ConcertPitch","C","-1",""):this.writePitchForValue(e,"ConcertPitch",t.realValueWithoutHarmonic,t.accidentalMode)}writePitchForValue(e,t,s,i){let a=0,r=0,n="",o="";const h=()=>{a=s%12,r=s/12|0,n=zt.defaultSteps[a],o=zt.defaultAccidentals[a]};switch(h(),i){case N.Default:break;case N.ForceNone:case N.ForceNatural:o="";break;case N.ForceSharp:o="#";break;case N.ForceDoubleSharp:"#"===o&&(s-=2,h()),o="x";break;case N.ForceFlat:"#"===o&&(s+=1,h()),o="b";break;case N.ForceDoubleFlat:"#"===o&&(s+=2,h()),o="bb"}this.writePitch(e,t,n,r.toString(),o)}writePitch(e,t,s,i,a){const r=e.addElement("Property");r.attributes.set("name",t);const n=r.addElement("Pitch");n.addElement("Step").innerText=s,n.addElement("Accidental").innerText=a,n.addElement("Octave").innerText=i}writeBend(e,t){t.hasBend&&t.bendPoints.length<=4&&this.writeStandardBend(e,t.bendPoints)}writeStandardBend(e,t){this.writeSimplePropertyNode(e,"Bended","Enable",null);const s=t[0],i=t[t.length-1];let a,r;switch(t.length){case 4:a=t[1],r=t[2];break;case 3:a=t[1],r=t[1];break;default:a=new ge((s.offset+i.offset)/2,(s.value+i.value)/2),r=a}this.writeSimplePropertyNode(e,"BendDestinationOffset","Float",this.toBendOffset(i.offset).toString()),this.writeSimplePropertyNode(e,"BendDestinationValue","Float",this.toBendValue(i.value).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset1","Float",this.toBendOffset(a.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleOffset2","Float",this.toBendOffset(r.offset).toString()),this.writeSimplePropertyNode(e,"BendMiddleValue","Float",this.toBendValue(a.value).toString()),this.writeSimplePropertyNode(e,"BendOriginOffset","Float",this.toBendOffset(s.offset).toString()),this.writeSimplePropertyNode(e,"BendOriginValue","Float",this.toBendValue(s.value).toString())}toBendValue(e){return 25*e}toBendOffset(e){return e/ge.MaxPosition*100}writeBeatNode(e,t,s){const i=e.addElement("Beat");if(i.attributes.set("id",t.id.toString()),i.addElement("Dynamic").innerText=E[t.dynamics],t.fade!==L.None&&(i.addElement("Fadding").innerText=L[t.fade]),t.isTremolo)switch(t.tremoloSpeed){case D.Eighth:i.addElement("Tremolo").innerText="1/2";break;case D.Sixteenth:i.addElement("Tremolo").innerText="1/4";break;case D.ThirtySecond:i.addElement("Tremolo").innerText="1/8"}switch(t.hasChord&&i.addElement("Chord").setCData(t.chordId),t.crescendo!==F.None&&(i.addElement("Hairpin").innerText=F[t.crescendo]),t.brushType){case b.ArpeggioUp:i.addElement("Arpeggio").innerText="Up";break;case b.ArpeggioDown:i.addElement("Arpeggio").innerText="Down"}switch(t.text&&i.addElement("FreeText").setCData(t.text),t.graceType){case R.OnBeat:case R.BeforeBeat:i.addElement("GraceNotes").innerText=R[t.graceType]}if(t.ottava!==o.Regular&&(i.addElement("Ottavia").innerText=o[t.ottava].substr(1)),t.hasWhammyBar&&this.writeWhammyNode(i,t),t.isLegatoOrigin||t.isLegatoDestination){const e=i.addElement("Legato");e.attributes.set("origin",t.isLegatoOrigin?"true":"false"),e.attributes.set("destination",t.isLegatoDestination?"true":"false")}if(this.writeRhythm(i,t,s),null!==t.preferredBeamDirection)switch(t.preferredBeamDirection){case se.Up:i.addElement("TransposedPitchStemOrientation").innerText="Upward",i.addElement("UserTransposedPitchStemOrientation").innerText="Upward";break;case se.Down:i.addElement("TransposedPitchStemOrientation").innerText="Downward",i.addElement("UserTransposedPitchStemOrientation").innerText="Downward"}i.addElement("ConcertPitchStemOrientation").innerText="Undefined",t.slashed&&i.addElement("Slashed"),t.deadSlapped&&i.addElement("DeadSlapped"),t.notes.length>0&&(i.addElement("Notes").innerText=t.notes.map((e=>e.id)).join(" ")),t.golpe!==O.None&&(i.addElement("Golpe").innerText=O[t.golpe]),t.wahPedal!==ie.None&&(i.addElement("Wah").innerText=ie[t.wahPedal]),t.showTimer&&(i.addElement("Timer").innerText=(t.timer??0).toString()),this.writeBeatProperties(i,t),this.writeBeatXProperties(i,t),t.lyrics&&t.lyrics.length>0&&this.writeBeatLyrics(i,t.lyrics)}writeBeatLyrics(e,t){const s=e.addElement("Lyrics");for(const e of t){s.addElement("Line").setCData(e)}}writeBeatXProperties(e,t){const s=e.addElement("XProperties");switch(t.brushDuration>0&&this.writeSimpleXPropertyNode(s,"687935489","Int",t.brushDuration.toString()),t.beamingMode){case cs.ForceSplitToNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","2");break;case cs.ForceMergeWithNext:this.writeSimpleXPropertyNode(s,"1124204546","Int","1");break;case cs.ForceSplitOnSecondaryToNext:this.writeSimpleXPropertyNode(s,"1124204552","Int","1")}}writeBeatProperties(e,t){const s=e.addElement("Properties");switch(t.brushType){case b.BrushUp:this.writeSimplePropertyNode(s,"Brush","Direction","Up");break;case b.BrushDown:this.writeSimplePropertyNode(s,"Brush","Direction","Down")}switch(t.pickStroke){case Q.Up:this.writeSimplePropertyNode(s,"PickStroke","Direction","Up");break;case Q.Down:this.writeSimplePropertyNode(s,"PickStroke","Direction","Down")}switch(t.slap&&this.writeSimplePropertyNode(s,"Slapped","Enable",null),t.pop&&this.writeSimplePropertyNode(s,"Popped","Enable",null),t.vibrato){case j.Wide:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Wide");break;case j.Slight:this.writeSimplePropertyNode(s,"VibratoWTremBar","Strength","Slight")}if(t.isBarre)switch(this.writeSimplePropertyNode(s,"BarreFret","Fret",t.barreFret.toString()),t.barreShape){case m.Full:this.writeSimplePropertyNode(s,"BarreString","String","0");break;case m.Half:this.writeSimplePropertyNode(s,"BarreString","String","1")}if(t.rasgueado!==ae.None){let e="";switch(t.rasgueado){case ae.Ii:e="ii_1";break;case ae.Mi:e="mi_1";break;case ae.MiiTriplet:e="mii_1";break;case ae.MiiAnapaest:e="mii_2";break;case ae.PmpTriplet:e="pmp_1";break;case ae.PmpAnapaest:e="pmp_2";break;case ae.PeiTriplet:e="pei_1";break;case ae.PeiAnapaest:e="pei_2";break;case ae.PaiTriplet:e="pai_1";break;case ae.PaiAnapaest:e="pai_2";break;case ae.AmiTriplet:e="ami_1";break;case ae.AmiAnapaest:e="ami_2";break;case ae.Ppp:e="ppp_1";break;case ae.Amii:e="amii_1";break;case ae.Amip:e="amip_1";break;case ae.Eami:e="eami_1";break;case ae.Eamii:e="eamii_1";break;case ae.Peami:e="peami_1"}this.writeSimplePropertyNode(s,"Rasgueado","Rasgueado",e)}}writeRhythm(e,t,s){const i=`${t.duration}_${t.dots}_${t.tupletNumerator}_${t.tupletDenominator}';`;let a;if(this._rhythmIdLookup.has(i))a=this._rhythmIdLookup.get(i);else{a=this._rhythmIdLookup.size.toString(),this._rhythmIdLookup.set(i,a);const e=s.addElement("Rhythm");if(e.attributes.set("id",a),t.hasTuplet){const s=e.addElement("PrimaryTuplet");s.attributes.set("num",t.tupletNumerator.toString()),s.attributes.set("den",t.tupletDenominator.toString())}t.dots>0&&e.addElement("AugmentationDot").attributes.set("count",t.dots.toString());let r="Quarter";switch(t.duration){case D.QuadrupleWhole:r="Long";break;case D.DoubleWhole:r="DoubleWhole";break;case D.Whole:r="Whole";break;case D.Half:r="Half";break;case D.Quarter:r="Quarter";break;case D.Eighth:r="Eighth";break;case D.Sixteenth:r="16th";break;case D.ThirtySecond:r="32nd";break;case D.SixtyFourth:r="64th";break;case D.OneHundredTwentyEighth:r="128th";break;case D.TwoHundredFiftySixth:r="256th"}e.addElement("NoteValue").innerText=r}e.addElement("Rhythm").attributes.set("ref",a)}writeWhammyNode(e,t){t.hasWhammyBar&&t.whammyBarPoints.length<=4&&this.writeStandardWhammy(e,t.whammyBarPoints)}writeStandardWhammy(e,t){const s=e.addElement("Whammy"),i=t[0],a=t[t.length-1];let r,n;switch(t.length){case 4:r=t[1],n=t[2];break;case 3:r=t[1],n=t[1];break;default:r=new ge((i.offset+a.offset)/2,(i.value+a.value)/2),n=r}s.attributes.set("destinationOffset",this.toBendOffset(a.offset).toString()),s.attributes.set("destinationValue",this.toBendValue(a.value).toString()),s.attributes.set("middleOffset1",this.toBendOffset(r.offset).toString()),s.attributes.set("middleOffset2",this.toBendOffset(n.offset).toString()),s.attributes.set("middleValue",this.toBendValue(r.value).toString()),s.attributes.set("originOffset",this.toBendOffset(i.offset).toString()),s.attributes.set("originValue",this.toBendValue(i.value).toString())}writeScoreNode(e,t){const s=e.addElement("Score");s.addElement("Title").setCData(t.title),s.addElement("SubTitle").setCData(t.subTitle),s.addElement("Artist").setCData(t.artist),s.addElement("Album").setCData(t.album),s.addElement("Words").setCData(t.words),s.addElement("Music").setCData(t.music),s.addElement("WordsAndMusic").setCData(t.words===t.music?t.words:""),s.addElement("Copyright").setCData(t.copyright),s.addElement("Tabber").setCData(t.tab),s.addElement("Instructions").setCData(t.instructions),s.addElement("Notices").setCData(t.notices),s.addElement("FirstPageHeader").setCData(""),s.addElement("FirstPageFooter").setCData(""),s.addElement("PageHeader").setCData(""),s.addElement("PageFooter").setCData(""),s.addElement("ScoreSystemsDefaultLayout").setCData(t.defaultSystemsLayout.toString()),s.addElement("ScoreSystemsLayout").setCData(t.systemsLayout.join(" ")),s.addElement("ScoreZoomPolicy").innerText="Value",s.addElement("ScoreZoom").innerText="1",s.addElement("MultiVoice").innerText="1>"}writeMasterTrackNode(e,t){const s=e.addElement("MasterTrack");s.addElement("Tracks").innerText=t.tracks.map((e=>e.index)).join(" ");const i=s.addElement("Automations");if(t.masterBars.length>0&&t.masterBars[0].isAnacrusis&&s.addElement("Anacrusis"),0===t.masterBars[0].tempoAutomations.length){const e=i.addElement("Automation");e.addElement("Type").innerText="Tempo",e.addElement("Linear").innerText="false",e.addElement("Bar").innerText="0",e.addElement("Position").innerText="0",e.addElement("Visible").innerText="true",e.addElement("Value").innerText=`${t.tempo} 2`,t.tempoLabel&&(e.addElement("Text").innerText=t.tempoLabel)}for(const e of t.masterBars)for(const t of e.tempoAutomations){const s=i.addElement("Automation");s.addElement("Type").innerText="Tempo",s.addElement("Linear").innerText=t.isLinear?"true":"false",s.addElement("Bar").innerText=e.index.toString(),s.addElement("Position").innerText=t.ratioPosition.toString(),s.addElement("Visible").innerText="true",s.addElement("Value").innerText=`${t.value} 2`,t.text&&(s.addElement("Text").innerText=t.text)}}writeAudioTracksNode(e,t){e.addElement("AudioTracks")}writeTracksNode(e,t){const s=e.addElement("Tracks");for(const e of t.tracks)this.writeTrackNode(s,e)}writeTrackNode(e,t){const s=e.addElement("Track");s.attributes.set("id",t.index.toString()),s.addElement("Name").setCData(t.name),s.addElement("ShortName").setCData(t.shortName),s.addElement("Color").innerText=`${t.color.r} ${t.color.g} ${t.color.b}`,s.addElement("SystemsDefautLayout").innerText=t.defaultSystemsLayout.toString(),s.addElement("SystemsLayout").innerText=t.systemsLayout.join(" "),s.addElement("AutoBrush"),s.addElement("PalmMute").innerText="0",s.addElement("PlayingStyle").innerText=ne.isGuitar(t.playbackInfo.program)?"StringedPick":"Default",s.addElement("UseOneChannelPerString"),s.addElement("IconId").innerText=yc.getIconId(t.playbackInfo).toString(),this.writeInstrumentSetNode(s,t),this.writeTransposeNode(s,t),this.writeRseNode(s,t),s.addElement("ForcedSound").innerText="-1",this.writeMidiConnectionNode(s,t),t.playbackInfo.isSolo?s.addElement("PlaybackState").innerText="Solo":t.playbackInfo.isMute?s.addElement("PlaybackState").innerText="Mute":s.addElement("PlaybackState").innerText="Default",s.addElement("AudioEngineState").innerText="MIDI",this.writeLyricsNode(s,t),this.writeStavesNode(s,t),this.writeSoundsAndAutomations(s,t)}static getIconId(e){return 9===e.primaryChannel?yc.DrumKitProgramInfo.icon:yc.MidiProgramInfoLookup.has(e.program)?yc.MidiProgramInfoLookup.get(e.program).icon:mc.SteelGuitar}writeSoundAndAutomation(e,t,s,i,a,r,n,o=0){const h=e.addElement("Sound");h.addElement("Name").setCData(s),h.addElement("Label").setCData(s),h.addElement("Path").setCData(i),h.addElement("Role").setCData(a);const l=h.addElement("MIDI");l.addElement("LSB").innerText="0",l.addElement("MSB").innerText="0",l.addElement("Program").innerText=n.toString();const c=t.addElement("Automation");c.addElement("Type").innerText="Sound",c.addElement("Linear").innerText="false",c.addElement("Bar").innerText=r.toString(),c.addElement("Position").innerText=o.toString(),c.addElement("Visible").innerText="true",c.addElement("Value").setCData(`${i};${s};${a}`)}writeSoundsAndAutomations(e,t){const s=e.addElement("Sounds"),i=e.addElement("Automations");if(t.staves.length>0&&t.staves[0].bars.length>0){const e=`Track_${t.index}_Initial`,a=`Midi/${t.playbackInfo.program}`,r="Factory";let n=!1;for(const o of t.staves)for(const h of o.bars)for(const o of h.voices)for(const l of o.beats){const o=l.getAutomation(g.Instrument),c=0===h.index&&0===l.index;if(o){const d=c?e:`ProgramChange_${l.id}`,u=c?a:`Midi/${o.value}`,p=c?r:"User";c||n||(this.writeSoundAndAutomation(s,i,e,a,r,t.staves[0].bars[0].index,t.playbackInfo.program),n=!0),this.writeSoundAndAutomation(s,i,d,u,p,h.index,o.value,o.ratioPosition),c&&(n=!0)}}}for(const e of t.staves)for(const t of e.bars)for(const e of t.sustainPedals)if(e.pedalType!==l.Hold){const s=i.addElement("Automation");switch(s.addElement("Type").innerText="SustainPedal",s.addElement("Linear").innerText="false",s.addElement("Bar").innerText=t.index.toString(),s.addElement("Position").innerText=e.ratioPosition.toString(),s.addElement("Visible").innerText="true",e.pedalType){case l.Down:s.addElement("Value").innerText="0 1";break;case l.Up:s.addElement("Value").innerText="0 3"}}}writeMidiConnectionNode(e,t){const s=e.addElement("MidiConnection");s.addElement("Port").innerText=t.playbackInfo.port.toString(),s.addElement("PrimaryChannel").innerText=t.playbackInfo.primaryChannel.toString(),s.addElement("SecondaryChannel").innerText=t.playbackInfo.secondaryChannel.toString(),s.addElement("ForeOneChannelPerString").innerText="false"}writeRseNode(e,t){const s=e.addElement("RSE").addElement("ChannelStrip");s.attributes.set("version","E56");s.addElement("Parameters").innerText=`0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1 0.5 ${t.playbackInfo.balance/16} ${t.playbackInfo.volume/16} 0.5 0.5 0.5`}writeStavesNode(e,t){const s=e.addElement("Staves");for(const e of t.staves)this.writeStaffNode(s,e)}writeStaffNode(e,t){const s=e.addElement("Staff").addElement("Properties");if(this.writeSimplePropertyNode(s,"CapoFret","Fret",t.capo.toString()),this.writeSimplePropertyNode(s,"FretCount","Fret","24"),t.tuning.length>0){const e=s.addElement("Property");switch(e.attributes.set("name","Tuning"),e.addElement("Pitches").innerText=t.tuning.slice().reverse().join(" "),e.addElement("Label").setCData(t.tuningName),e.addElement("LabelVisible").innerText=t.tuningName?"true":"false",e.addElement("Flat"),t.tuning.length){case 3:e.addElement("Instrument").innerText="Shamisen";break;case 4:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":42===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Cello":43===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Contrabass":40===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Violin":41===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Viola":e.addElement("Instrument").innerText="Bass";break;case 5:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":e.addElement("Instrument").innerText="Bass";break;case 6:105===t.track.playbackInfo.program?e.addElement("Instrument").innerText="Banjo":t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;case 7:t.track.playbackInfo.program<=39?e.addElement("Instrument").innerText="Bass":e.addElement("Instrument").innerText="Guitar";break;default:e.addElement("Instrument").innerText="Guitar"}}this.writeSimplePropertyNode(s,"PartialCapoFret","Fret","0"),this.writeSimplePropertyNode(s,"PartialCapoStringFlags","Bitset",t.tuning.map((e=>"0")).join("")),this.writeSimplePropertyNode(s,"TuningFlat","Enable",null),this.writeDiagramCollection(s,t,"DiagramCollection"),this.writeDiagramCollection(s,t,"DiagramWorkingSet")}writeDiagramCollection(e,t,s){const i=e.addElement("Property");i.attributes.set("name",s);const a=i.addElement("Items"),r=t.chords;if(r)for(const[e,t]of r){const s=a.addElement("Item");s.attributes.set("id",e),s.attributes.set("name",t.name);const i=s.addElement("Diagram");i.attributes.set("stringCount",t.strings.length.toString()),i.attributes.set("fretCount","5"),i.attributes.set("baseFret",(t.firstFret-1).toString()),i.attributes.set("barStates",t.strings.map((e=>"1")).join(" "));const r=[],n=new Map;for(let e=0;e<t.strings.length;e++){const s=t.strings[e];if(-1!==s){const a=i.addElement("Fret"),o=t.strings.length-1-e;a.attributes.set("string",o.toString()),a.attributes.set("fret",(s-t.firstFret+1).toString()),n.has(s)||(n.set(s,[]),r.push(s)),n.get(s).push(o)}}r.sort();const o=i.addElement("Fingering");if(t.barreFrets.length>0){const e=[_.LittleFinger,_.AnnularFinger,_.MiddleFinger,_.IndexFinger];for(const s of r){const i=n.get(s);if(i.length>1&&t.barreFrets.indexOf(s)>=0){const a=e.length>0?e.pop():_.IndexFinger;for(const e of i){const i=o.addElement("Position");switch(a){case _.LittleFinger:i.attributes.set("finger","Pinky");break;case _.AnnularFinger:i.attributes.set("finger","Ring");break;case _.MiddleFinger:i.attributes.set("finger","Middle");break;case _.IndexFinger:i.attributes.set("finger","Index")}i.attributes.set("fret",(s-t.firstFret+1).toString()),i.attributes.set("string",e.toString())}}}}const h=i.addElement("Property");h.attributes.set("name","ShowName"),h.attributes.set("type","bool"),h.attributes.set("value",t.showName?"true":"false");const l=i.addElement("Property");l.attributes.set("name","ShowDiagram"),l.attributes.set("type","bool"),l.attributes.set("value",t.showDiagram?"true":"false");const c=i.addElement("Property");c.attributes.set("name","ShowFingering"),c.attributes.set("type","bool"),c.attributes.set("value",t.showFingering?"true":"false");const d=i.addElement("Chord"),u=d.addElement("KeyNote");u.attributes.set("step","C"),u.attributes.set("accidental","Natural");const p=d.addElement("BassNote");p.attributes.set("step","C"),p.attributes.set("accidental","Natural");const g=d.addElement("Degree");g.attributes.set("interval","Third"),g.attributes.set("alteration","Major"),g.attributes.set("omitted","false");const m=d.addElement("Degree");m.attributes.set("interval","Fifth"),m.attributes.set("alteration","Perfect"),m.attributes.set("omitted","false")}}writeSimplePropertyNode(e,t,s,i){const a=e.addElement("Property");a.attributes.set("name",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeSimpleXPropertyNode(e,t,s,i){const a=e.addElement("XProperty");a.attributes.set("id",t);const r=a.addElement(s);return null!==i&&(r.innerText=i),a}writeLyricsNode(e,t){const s=e.addElement("Lyrics");s.attributes.set("dispatched","true");const i=[];for(const e of t.staves[0].bars)for(const t of e.voices)if(!t.isEmpty)for(const s of t.beats)if(s.lyrics)for(let t=0;t<s.lyrics.length;t++){for(;t>=i.length;){const t=new ss;t.startBar=e.index,t.text="[Empty]",i.push(t)}const a=i[t];a.text="[Empty]"===a.text?s.lyrics[t]:`${a.text} ${s.lyrics[t].split(" ").join("+")}`}for(let e=0;e<i.length;e++){const t=s.addElement("Line");t.addElement("Text").setCData(i[e].text),t.addElement("Offset").innerText=i[e].startBar.toString()}}writeTransposeNode(e,t){const s=e.addElement("Transpose"),i=Math.floor(t.staves[0].displayTranspositionPitch/12),a=t.staves[0].displayTranspositionPitch-12*i;s.addElement("Chromatic").innerText=a.toString(),s.addElement("Octave").innerText=i.toString()}writeInstrumentSetNode(e,t){const s=e.addElement("InstrumentSet"),i=t.staves[0];if(s.addElement("LineCount").innerText=i.standardNotationLineCount.toString(),t.percussionArticulations.length>0||i.isPercussion){const e=t.percussionArticulations.length>0?t.percussionArticulations:Array.from(Bt.instrumentArticulations.values());s.addElement("Name").innerText=yc.DrumKitProgramInfo.instrumentSetName,s.addElement("Type").innerText=yc.DrumKitProgramInfo.instrumentSetType;let i="",a=new Vs;const r=new Map,n=s.addElement("Elements");for(const t of e){{const e=n.addElement("Element");let s=t.elementType;if(r.has(s)){const e=r.get(s);s+=` ${e}`,r.set(s,e+1)}else r.set(s,1);i=s,e.addElement("Name").innerText=s,e.addElement("Type").innerText=t.elementType,a=e.addElement("Articulations")}const e=a.addElement("Articulation");switch(e.addElement("Name").innerText=`${i} ${a.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 V.Top:e.addElement("TechniquePlacement").innerText="below";break;case V.Middle:e.addElement("TechniquePlacement").innerText="inside";break;case V.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=yc.MidiProgramInfoLookup.has(t.playbackInfo.program)?yc.MidiProgramInfoLookup.get(t.playbackInfo.program):yc.MidiProgramInfoLookup.get(0);s.addElement("Name").innerText=e.instrumentSetName,s.addElement("Type").innerText=e.instrumentSetType;const i=s.addElement("Elements").addElement("Element");i.addElement("Pitched").innerText="Pitched",i.addElement("Type").innerText="pitched",i.addElement("SoundbankName").innerText="";const a=i.addElement("Articulations").addElement("Articulation");a.addElement("Name").innerText="",a.addElement("StaffLine").innerText="0",a.addElement("Noteheads").innerText="noteheadBlack noteheadHalf noteheadWhole",a.addElement("TechniquePlacement").innerText="outside",a.addElement("TechniqueSymbol").innerText="",a.addElement("InputMidiNumbers").innerText="",a.addElement("OutputRSESound").innerText="",a.addElement("OutputMidiNumber").innerText="0"}}mapMusicSymbol(e){if(e===G.None)return"";const t=G[e];return t.substring(0,1).toLowerCase()+t.substring(1)}writeMasterBarsNode(e,t){const s=e.addElement("MasterBars");for(const e of t.masterBars)this.writeMasterBarNode(s,e)}writeMasterBarNode(e,t){const s=e.addElement("MasterBar"),i=s.addElement("Key");i.addElement("AccidentalCount").innerText=t.keySignature.toString(),i.addElement("Mode").innerText=v[t.keySignatureType],i.addElement("Sharps").innerText="Sharps",s.addElement("Time").innerText=`${t.timeSignatureNumerator}/${t.timeSignatureDenominator}`,t.isFreeTime&&s.addElement("FreeTime");const a=[];for(const e of t.score.tracks)for(const s of e.staves)a.push(s.bars[t.index].id.toString());if(s.addElement("Bars").innerText=a.join(" "),t.isDoubleBar&&s.addElement("DoubleBar"),t.isSectionStart){const e=s.addElement("Section");e.addElement("Letter").setCData(t.section.marker),e.addElement("Text").setCData(t.section.text)}if(t.isRepeatStart||t.isRepeatEnd){const e=s.addElement("Repeat");e.attributes.set("start",t.isRepeatStart?"true":"false"),e.attributes.set("end",t.isRepeatEnd?"true":"false"),t.isRepeatEnd&&e.attributes.set("count",t.repeatCount.toString())}if(t.alternateEndings>0){let e=t.alternateEndings;const i=[];let a=0;for(;e>0;)1==(e>>a&1)&&(i.push(a+1),e&=~(1<<a)),a++;s.addElement("AlternateEndings").innerText=i.join(" ")}if(t.tripletFeel!==P.NoTripletFeel&&(s.addElement("TripletFeel").innerText=P[t.tripletFeel]),t.directions&&t.directions.size>0){const e=s.addElement("Directions");for(const s of t.directions)switch(s){case C.TargetFine:e.addElement("Target").innerText="Fine";break;case C.TargetSegno:e.addElement("Target").innerText="Segno";break;case C.TargetSegnoSegno:e.addElement("Target").innerText="SegnoSegno";break;case C.TargetCoda:e.addElement("Target").innerText="Coda";break;case C.TargetDoubleCoda:e.addElement("Target").innerText="DoubleCoda";break;case C.JumpDaCapo:e.addElement("Jump").innerText="DaCapo";break;case C.JumpDaCapoAlCoda:e.addElement("Jump").innerText="DaCapoAlCoda";break;case C.JumpDaCapoAlDoubleCoda:e.addElement("Jump").innerText="DaCapoAlDoubleCoda";break;case C.JumpDaCapoAlFine:e.addElement("Jump").innerText="DaCapoAlFine";break;case C.JumpDalSegno:e.addElement("Jump").innerText="DaSegno";break;case C.JumpDalSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoAlCoda";break;case C.JumpDalSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoAlDoubleCoda";break;case C.JumpDalSegnoAlFine:e.addElement("Jump").innerText="DaSegnoAlFine";break;case C.JumpDalSegnoSegno:e.addElement("Jump").innerText="DaSegnoSegno";break;case C.JumpDalSegnoSegnoAlCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlCoda";break;case C.JumpDalSegnoSegnoAlDoubleCoda:e.addElement("Jump").innerText="DaSegnoSegnoAlDoubleCoda";break;case C.JumpDalSegnoSegnoAlFine:e.addElement("Jump").innerText="DaSegnoSegnoAlFine";break;case C.JumpDaCoda:e.addElement("Jump").innerText="DaCoda";break;case C.JumpDaDoubleCoda:e.addElement("Jump").innerText="DaDoubleCoda"}}this.writeFermatas(s,t)}writeFermatas(e,t){const s=t.fermata?.size??0;if(0!==s&&s>0){const s=e.addElement("Fermatas");for(const[e,i]of t.fermata)this.writeFermata(s,e,i)}}writeFermata(e,t,s){let i=-1,a=1;if(t>0)for(;a<10&&(i=t/rs.QuarterTime*a,i!==Math.floor(i));)i=-1,a++;else i=0,a=1;if(-1===i)return;const r=e.addElement("Fermata");r.addElement("Type").innerText=M[s.type],r.addElement("Length").innerText=s.length.toString(),r.addElement("Offset").innerText=`${i}/${a}`}writeBarNode(e,t){const s=e.addElement("Bar");s.attributes.set("id",t.id.toString()),s.addElement("Voices").innerText=t.voices.map((e=>e.isEmpty?"-1":e.id.toString())).join(" "),s.addElement("Clef").innerText=n[t.clef],t.clefOttava!==o.Regular&&(s.addElement("Ottavia").innerText=o[t.clefOttava].substr(1)),t.simileMark!==h.None&&(s.addElement("SimileMark").innerText=h[t.simileMark])}writeVoiceNode(e,t){if(t.isEmpty)return;const s=e.addElement("Voice");s.attributes.set("id",t.id.toString()),s.addElement("Beats").innerText=t.beats.map((e=>e.id)).join(" ")}}yc.MidiProgramInfoLookup=new Map([[0,new fc(mc.Piano,"Acoustic Piano")],[1,new fc(mc.Piano,"Acoustic Piano")],[2,new fc(mc.Piano,"Electric Piano")],[3,new fc(mc.Piano,"Acoustic Piano")],[4,new fc(mc.Piano,"Electric Piano")],[5,new fc(mc.Piano,"Electric Piano")],[6,new fc(mc.Piano,"Harpsichord")],[7,new fc(mc.Piano,"Harpsichord")],[8,new fc(mc.PitchedIdiophone,"Celesta")],[9,new fc(mc.PitchedIdiophone,"Vibraphone")],[10,new fc(mc.PitchedIdiophone,"Vibraphone")],[11,new fc(mc.PitchedIdiophone,"Vibraphone")],[12,new fc(mc.PitchedIdiophone,"Xylophone")],[13,new fc(mc.PitchedIdiophone,"Xylophone")],[14,new fc(mc.PitchedIdiophone,"Vibraphone")],[15,new fc(mc.Banjo,"Banjo")],[16,new fc(mc.Piano,"Electric Organ")],[17,new fc(mc.Piano,"Electric Organ")],[18,new fc(mc.Piano,"Electric Organ")],[19,new fc(mc.Piano,"Electric Organ")],[20,new fc(mc.Piano,"Electric Organ")],[21,new fc(mc.Piano,"Electric Organ")],[22,new fc(mc.Woodwind,"Recorder")],[23,new fc(mc.Piano,"Electric Organ")],[24,new fc(mc.ClassicalGuitar,"Nylon Guitar")],[25,new fc(mc.SteelGuitar,"Steel Guitar")],[26,new fc(mc.SteelGuitar,"Electric Guitar")],[27,new fc(mc.ElectricGuitar,"Electric Guitar")],[28,new fc(mc.ElectricGuitar,"Electric Guitar")],[29,new fc(mc.ElectricGuitar,"Electric Guitar")],[30,new fc(mc.SteelGuitar,"Electric Guitar")],[31,new fc(mc.SteelGuitar,"Electric Guitar")],[32,new fc(mc.Bass,"Acoustic Bass")],[33,new fc(mc.Bass,"Electric Bass")],[34,new fc(mc.Bass,"Electric Bass")],[35,new fc(mc.Bass,"Acoustic Bass")],[36,new fc(mc.Bass,"Electric Bass")],[37,new fc(mc.Bass,"Electric Bass")],[38,new fc(mc.Synth,"Synth Bass")],[39,new fc(mc.Synth,"Synth Bass")],[40,new fc(mc.Strings,"Violin")],[41,new fc(mc.Strings,"Viola")],[42,new fc(mc.Strings,"Cello")],[43,new fc(mc.Strings,"Contrabass")],[44,new fc(mc.Strings,"Violin")],[45,new fc(mc.Strings,"Violin")],[46,new fc(mc.Piano,"Harp")],[47,new fc(mc.Membraphone,"Timpani")],[48,new fc(mc.Strings,"Violin")],[49,new fc(mc.Strings,"Violin")],[50,new fc(mc.Strings,"Violin")],[51,new fc(mc.Strings,"Violin")],[52,new fc(mc.Vocal,"Voice")],[53,new fc(mc.Vocal,"Voice")],[54,new fc(mc.Vocal,"Voice")],[55,new fc(mc.Synth,"Pad Synthesizer")],[56,new fc(mc.Brass,"Trumpet")],[57,new fc(mc.Brass,"Trombone")],[58,new fc(mc.Brass,"Tuba")],[59,new fc(mc.Brass,"Trumpet")],[60,new fc(mc.Brass,"French Horn")],[61,new fc(mc.Brass,"Trumpet")],[62,new fc(mc.Brass,"Trumpet")],[63,new fc(mc.Brass,"Trumpet")],[64,new fc(mc.Reed,"Saxophone")],[65,new fc(mc.Reed,"Saxophone")],[66,new fc(mc.Reed,"Saxophone")],[67,new fc(mc.Reed,"Saxophone")],[68,new fc(mc.Reed,"Oboe")],[69,new fc(mc.Reed,"English Horn")],[70,new fc(mc.Reed,"Bassoon")],[71,new fc(mc.Reed,"Clarinet")],[72,new fc(mc.Reed,"Piccolo")],[73,new fc(mc.Woodwind,"Flute")],[74,new fc(mc.Woodwind,"Recorder")],[75,new fc(mc.Woodwind,"Flute")],[76,new fc(mc.Woodwind,"Recorder")],[77,new fc(mc.Woodwind,"Flute")],[78,new fc(mc.Woodwind,"Recorder")],[79,new fc(mc.Woodwind,"Flute")],[80,new fc(mc.Synth,"Lead Synthesizer")],[81,new fc(mc.Synth,"Lead Synthesizer")],[82,new fc(mc.Synth,"Lead Synthesizer")],[83,new fc(mc.Synth,"Lead Synthesizer")],[84,new fc(mc.Synth,"Lead Synthesizer")],[85,new fc(mc.Synth,"Lead Synthesizer")],[86,new fc(mc.Synth,"Lead Synthesizer")],[87,new fc(mc.Synth,"Lead Synthesizer")],[88,new fc(mc.Synth,"Pad Synthesizer")],[89,new fc(mc.Synth,"Pad Synthesizer")],[90,new fc(mc.Synth,"Pad Synthesizer")],[91,new fc(mc.Synth,"Pad Synthesizer")],[92,new fc(mc.Synth,"Pad Synthesizer")],[93,new fc(mc.Synth,"Pad Synthesizer")],[94,new fc(mc.Synth,"Pad Synthesizer")],[95,new fc(mc.Synth,"Pad Synthesizer")],[96,new fc(mc.Fx,"Pad Synthesizer")],[97,new fc(mc.Fx,"Pad Synthesizer")],[98,new fc(mc.Fx,"Pad Synthesizer")],[99,new fc(mc.Fx,"Pad Synthesizer")],[100,new fc(mc.Fx,"Lead Synthesizer")],[101,new fc(mc.Fx,"Lead Synthesizer")],[102,new fc(mc.Fx,"Lead Synthesizer")],[103,new fc(mc.Fx,"Trumpet")],[104,new fc(mc.ElectricGuitar,"Banjo")],[105,new fc(mc.Banjo,"Banjo")],[106,new fc(mc.Ukulele,"Ukulele")],[107,new fc(mc.Banjo,"Banjo")],[108,new fc(mc.PitchedIdiophone,"Xylophone")],[109,new fc(mc.Reed,"Bassoon")],[110,new fc(mc.Strings,"Violin")],[111,new fc(mc.Woodwind,"Flute")],[112,new fc(mc.PitchedIdiophone,"Xylophone")],[113,new fc(mc.Idiophone,"Celesta")],[114,new fc(mc.PitchedIdiophone,"Vibraphone")],[115,new fc(mc.Idiophone,"Xylophone")],[116,new fc(mc.Membraphone,"Xylophone")],[117,new fc(mc.Membraphone,"Xylophone")],[118,new fc(mc.Membraphone,"Xylophone")],[119,new fc(mc.Idiophone,"Celesta")],[120,new fc(mc.Fx,"Steel Guitar")],[121,new fc(mc.Fx,"Recorder")],[122,new fc(mc.Fx,"Recorder")],[123,new fc(mc.Fx,"Recorder")],[124,new fc(mc.Fx,"Recorder")],[125,new fc(mc.Fx,"Recorder")],[126,new fc(mc.Fx,"Recorder")],[127,new fc(mc.Fx,"Timpani")]]),yc.DrumKitProgramInfo=new fc(mc.PercussionKit,"Drums","drumKit");class bc{static buildCrc32Lookup(){const e=new Uint32Array(256);for(let t=0;t<e.length;t++){let s=t;for(let e=0;e<8;e++)s=1&~s?s>>>1:s>>>1^3988292384;e[t]=s}return e}get value(){return~this._checkValue}constructor(){this._checkValue=bc.CrcInit,this.reset()}update(e,t,s){for(let i=0;i<s;i++)this._checkValue=bc.Crc32Lookup[255&(this._checkValue^e[t+i])]^this._checkValue>>>8}reset(){this._checkValue=bc.CrcInit}}bc.Crc32Lookup=bc.buildCrc32Lookup(),bc.CrcInit=4294967295;class Sc{}Sc.MAX_WBITS=15,Sc.WSIZE=1<<Sc.MAX_WBITS,Sc.WMASK=Sc.WSIZE-1,Sc.MIN_MATCH=3,Sc.MAX_MATCH=258,Sc.DEFAULT_MEM_LEVEL=8,Sc.PENDING_BUF_SIZE=1<<Sc.DEFAULT_MEM_LEVEL+8,Sc.HASH_BITS=Sc.DEFAULT_MEM_LEVEL+7,Sc.HASH_SIZE=1<<Sc.HASH_BITS,Sc.HASH_SHIFT=(Sc.HASH_BITS+Sc.MIN_MATCH-1)/Sc.MIN_MATCH,Sc.HASH_MASK=Sc.HASH_SIZE-1,Sc.MIN_LOOKAHEAD=Sc.MAX_MATCH+Sc.MIN_MATCH+1,Sc.MAX_DIST=Sc.WSIZE-Sc.MIN_LOOKAHEAD;class _c{constructor(e,t,s,i){this.length=null,this.numCodes=0,this.codes=null,this.huffman=e,this.minNumCodes=s,this.maxLength=i,this.freqs=new Int16Array(t),this.bitLengthCounts=new Int32Array(i)}reset(){for(let e=0;e<this.freqs.length;e++)this.freqs[e]=0;this.codes=null,this.length=null}buildTree(){const e=this.freqs.length,t=new Int32Array(e);let s=0,i=0;for(let a=0;a<e;a++){const e=this.freqs[a];if(0!==e){let r=s++;for(;r>0;){const s=Math.floor((r-1)/2);if(!(this.freqs[t[s]]>e))break;t[r]=t[s],r=s}t[r]=a,i=a}}for(;s<2;){const e=i<2?++i:0;t[s++]=e}this.numCodes=Math.max(i+1,this.minNumCodes);const a=s,r=new Int32Array(4*s-2),n=new Int32Array(2*s-1);let o=a;for(let e=0;e<s;e++){const s=t[e];r[2*e]=s,r[2*e+1]=-1,n[e]=this.freqs[s]<<8,t[e]=e}do{const e=t[0];let i=t[--s],a=0,h=1;for(;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*h+1;let l=n[i];for(;h=a,a>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i;const c=t[0];i=o++,r[2*i]=e,r[2*i+1]=c;const d=Math.min(255&n[e],255&n[c]);for(l=n[e]+n[c]-d+1,n[i]=l,a=0,h=1;h<s;)h+1<s&&n[t[h]]>n[t[h+1]]&&h++,t[a]=t[h],a=h,h=2*a+1;for(;h=a,h>0&&(a=Math.floor((h-1)/2),n[t[a]]>l);)t[h]=t[a];t[h]=i}while(s>1);this.buildLength(r)}buildLength(e){this.length=new Uint8Array(this.freqs.length);const t=Math.floor(e.length/2),s=Math.floor((t+1)/2);let i=0;for(let e=0;e<this.maxLength;e++)this.bitLengthCounts[e]=0;const a=new Int32Array(t);a[t-1]=0;for(let s=t-1;s>=0;s--)if(-1!==e[2*s+1]){let t=a[s]+1;t>this.maxLength&&(t=this.maxLength,i++),a[e[2*s]]=t,a[e[2*s+1]]=t}else{const t=a[s];this.bitLengthCounts[t-1]++,this.length[e[2*s]]=a[s]}if(0===i)return;let r=this.maxLength-1;do{for(;0===this.bitLengthCounts[--r];);do{this.bitLengthCounts[r]--,this.bitLengthCounts[++r]++,i-=1<<this.maxLength-1-r}while(i>0&&r<this.maxLength-1)}while(i>0);this.bitLengthCounts[this.maxLength-1]+=i,this.bitLengthCounts[this.maxLength-2]-=i;let n=2*s;for(let t=this.maxLength;0!==t;t--){let s=this.bitLengthCounts[t-1];for(;s>0;){const i=2*e[n++];-1===e[i+1]&&(this.length[e[i]]=t,s--)}}}getEncodedLength(){let e=0;for(let t=0;t<this.freqs.length;t++)e+=this.freqs[t]*this.length[t];return e}calcBLFreq(e){let t,s,i,a=-1,r=0;for(;r<this.numCodes;){i=1;const n=this.length[r];for(0===n?(t=138,s=3):(t=6,s=3,a!==n&&(e.freqs[n]++,i=0)),a=n,r++;r<this.numCodes&&a===this.length[r]&&(r++,!(++i>=t)););i<s?e.freqs[a]+=i:0!==a?e.freqs[_c.Repeat3To6]++:i<=10?e.freqs[_c.Repeat3To10]++:e.freqs[_c.Repeat11To138]++}}setStaticCodes(e,t){this.codes=e,this.length=t}buildCodes(){const e=new Int32Array(this.maxLength);let t=0;this.codes=new Int16Array(this.freqs.length);for(let s=0;s<this.maxLength;s++)e[s]=t,t+=this.bitLengthCounts[s]<<15-s;for(let t=0;t<this.numCodes;t++){const s=this.length[t];s>0&&(this.codes[t]=wc.bitReverse(e[s-1]),e[s-1]+=1<<16-s)}}writeTree(e){let t,s,i,a=-1,r=0;for(;r<this.numCodes;){i=1;const n=this.length[r];for(0===n?(t=138,s=3):(t=6,s=3,a!==n&&(e.writeSymbol(n),i=0)),a=n,r++;r<this.numCodes&&a===this.length[r]&&(r++,!(++i>=t)););if(i<s)for(;i-- >0;)e.writeSymbol(a);else 0!==a?(e.writeSymbol(_c.Repeat3To6),this.huffman.pending.writeBits(i-3,2)):i<=10?(e.writeSymbol(_c.Repeat3To10),this.huffman.pending.writeBits(i-3,3)):(e.writeSymbol(_c.Repeat11To138),this.huffman.pending.writeBits(i-11,7))}}writeSymbol(e){this.huffman.pending.writeBits(65535&this.codes[e],this.length[e])}}_c.Repeat3To6=16,_c.Repeat3To10=17,_c.Repeat11To138=18;class wc{static staticInit(){let e=0;for(;e<144;)wc.staticLCodes[e]=wc.bitReverse(48+e<<8),wc.staticLLength[e++]=8;for(;e<256;)wc.staticLCodes[e]=wc.bitReverse(256+e<<7),wc.staticLLength[e++]=9;for(;e<280;)wc.staticLCodes[e]=wc.bitReverse(-256+e<<9),wc.staticLLength[e++]=7;for(;e<wc.LITERAL_NUM;)wc.staticLCodes[e]=wc.bitReverse(-88+e<<8),wc.staticLLength[e++]=8;for(e=0;e<wc.DIST_NUM;e++)wc.staticDCodes[e]=wc.bitReverse(e<<11),wc.staticDLength[e]=5}static bitReverse(e){return wc.bit4Reverse[15&e]<<12|wc.bit4Reverse[e>>4&15]<<8|wc.bit4Reverse[e>>8&15]<<4|wc.bit4Reverse[e>>12]}constructor(e){this.last_lit=0,this.extra_bits=0,this.pending=e,this.literalTree=new _c(this,wc.LITERAL_NUM,257,15),this.distTree=new _c(this,wc.DIST_NUM,1,15),this.blTree=new _c(this,wc.BITLEN_NUM,4,7),this.d_buf=new Int16Array(wc.BUFSIZE),this.l_buf=new Uint8Array(wc.BUFSIZE)}isFull(){return this.last_lit>=wc.BUFSIZE}reset(){this.last_lit=0,this.extra_bits=0,this.literalTree.reset(),this.distTree.reset(),this.blTree.reset()}flushStoredBlock(e,t,s,i){this.pending.writeBits((wc.STORED_BLOCK<<1)+(i?1:0),3),this.pending.alignToByte(),this.pending.writeShort(s),this.pending.writeShort(~s),this.pending.writeBlock(e,t,s),this.reset()}flushBlock(e,t,s,i){this.literalTree.freqs[wc.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[wc.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<wc.LITERAL_NUM;e++)n+=this.literalTree.freqs[e]*wc.staticLLength[e];for(let e=0;e<wc.DIST_NUM;e++)n+=this.distTree.freqs[e]*wc.staticDLength[e];r>=n&&(r=n),t>=0&&s+4<r>>3?this.flushStoredBlock(e,t,s,i):r===n?(this.pending.writeBits((wc.STATIC_TREES<<1)+(i?1:0),3),this.literalTree.setStaticCodes(wc.staticLCodes,wc.staticLLength),this.distTree.setStaticCodes(wc.staticDCodes,wc.staticDLength),this.compressBlock(),this.reset()):(this.pending.writeBits((wc.DYN_TREES<<1)+(i?1:0),3),this.sendAllTrees(a),this.compressBlock(),this.reset())}sendAllTrees(e){this.blTree.buildCodes(),this.literalTree.buildCodes(),this.distTree.buildCodes(),this.pending.writeBits(this.literalTree.numCodes-257,5),this.pending.writeBits(this.distTree.numCodes-1,5),this.pending.writeBits(e-4,4);for(let t=0;t<e;t++)this.pending.writeBits(this.blTree.length[wc.BL_ORDER[t]],3);this.literalTree.writeTree(this.blTree),this.distTree.writeTree(this.blTree)}compressBlock(){for(let e=0;e<this.last_lit;e++){const t=255&this.l_buf[e];let s=this.d_buf[e];if(0!=s--){const e=wc.Lcode(t);this.literalTree.writeSymbol(e);let i=Math.floor((e-261)/4);i>0&&i<=5&&this.pending.writeBits(t&(1<<i)-1,i);const a=wc.Dcode(s);this.distTree.writeSymbol(a),i=Math.floor(a/2)-1,i>0&&this.pending.writeBits(s&(1<<i)-1,i)}else this.literalTree.writeSymbol(t)}this.literalTree.writeSymbol(wc.EOF_SYMBOL)}tallyDist(e,t){this.d_buf[this.last_lit]=e,this.l_buf[this.last_lit++]=t-3;const s=wc.Lcode(t-3);this.literalTree.freqs[s]++,s>=265&&s<285&&(this.extra_bits+=Math.floor((s-261)/4));const i=wc.Dcode(e-1);return this.distTree.freqs[i]++,i>=4&&(this.extra_bits+=Math.floor(i/2)-1),this.isFull()}tallyLit(e){return this.d_buf[this.last_lit]=0,this.l_buf[this.last_lit++]=e,this.literalTree.freqs[e]++,this.isFull()}static Lcode(e){if(255===e)return 285;let t=257;for(;e>=8;)t+=4,e>>=1;return t+e}static Dcode(e){let t=0;for(;e>=4;)t+=2,e>>=1;return t+e}}wc.BUFSIZE=1<<Sc.DEFAULT_MEM_LEVEL+6,wc.LITERAL_NUM=286,wc.STORED_BLOCK=0,wc.STATIC_TREES=1,wc.DYN_TREES=2,wc.DIST_NUM=30,wc.staticLCodes=new Int16Array(wc.LITERAL_NUM),wc.staticLLength=new Uint8Array(wc.LITERAL_NUM),wc.staticDCodes=new Int16Array(wc.DIST_NUM),wc.staticDLength=new Uint8Array(wc.DIST_NUM),wc.BL_ORDER=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],wc.bit4Reverse=new Uint8Array([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]),wc.BITLEN_NUM=19,wc.EOF_SYMBOL=256,wc.staticInit();class Bc{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 wc(e),this.inputCrc=new bc,this.window=new Uint8Array(2*Sc.WSIZE),this.head=new Int16Array(Sc.HASH_SIZE),this.prev=new Int16Array(Sc.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=Sc.MIN_MATCH-1;for(let e=0;e<Sc.HASH_SIZE;e++)this.head[e]=0;for(let e=0;e<Sc.WSIZE;e++)this.prev[e]=0}updateHash(){this.insertHashIndex=this.window[this.strstart]<<Sc.HASH_SHIFT^this.window[this.strstart+1]}needsInput(){return this.inputEnd===this.inputOff}setInput(e,t,s){const i=t+s;this.inputBuf=e,this.inputOff=t,this.inputEnd=i}deflate(e,t){let s;do{this.fillWindow();const i=e&&this.inputOff===this.inputEnd;s=this.deflateSlow(i,t)}while(this.pending.isFlushed&&s);return s}deflateSlow(e,t){if(this.lookahead<Sc.MIN_LOOKAHEAD&&!e)return!1;for(;this.lookahead>=Sc.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*Sc.WSIZE-Sc.MIN_LOOKAHEAD&&this.slideWindow();const e=this.matchStart;let s=this.matchLen;if(this.lookahead>=Sc.MIN_MATCH){const e=this.insertString();0!==e&&this.strstart-e<=Sc.MAX_DIST&&this.findLongestMatch(e)&&this.matchLen===Sc.MIN_MATCH&&this.strstart-this.matchStart>Bc.TooFar&&(this.matchLen=Sc.MIN_MATCH-1)}if(s>=Sc.MIN_MATCH&&this.matchLen<=s){this.huffman.tallyDist(this.strstart-1-e,s),s-=2;do{this.strstart++,this.lookahead--,this.lookahead>=Sc.MIN_MATCH&&this.insertString()}while(--s>0);this.strstart++,this.lookahead--,this.prevAvailable=!1,this.matchLen=Sc.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--;const s=t&&0===this.lookahead&&!this.prevAvailable;return this.huffman.flushBlock(this.window,this.blockStart,e,s),this.blockStart+=e,!s}}return!0}findLongestMatch(e){let t,s=this.strstart;const i=s+Math.min(Sc.MAX_MATCH,this.lookahead)-1,a=Math.max(s-Sc.MAX_DIST,0),r=this.window,n=this.prev;let o=this.maxChain;const h=Math.min(this.niceLength,this.lookahead);if(this.matchLen=Math.max(this.matchLen,Sc.MIN_MATCH-1),s+this.matchLen>i)return!1;let l=r[s+this.matchLen-1],c=r[s+this.matchLen];this.matchLen>=this.goodLength&&(o>>=2);do{if(t=e,s=this.strstart,r[t+this.matchLen]===c&&r[t+this.matchLen-1]===l&&r[t]===r[s]&&r[++t]===r[++s]){switch((i-s)%8){case 1:if(r[++s]===r[++t])break;break;case 2:if(r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 3:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 4:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 5:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 6:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break;break;case 7:if(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t])break}if(r[s]===r[t])do{if(s===i){++s,++t;break}}while(r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]&&r[++s]===r[++t]);if(s-this.strstart>this.matchLen){if(this.matchStart=e,this.matchLen=s-this.strstart,this.matchLen>=h)break;l=r[s-1],c=r[s]}e=65535&n[e&Sc.WMASK]}}while(e>a&&0!=--o);return this.matchLen>=Sc.MIN_MATCH}insertString(){const e=(this.insertHashIndex<<Sc.HASH_SHIFT^this.window[this.strstart+(Sc.MIN_MATCH-1)])&Sc.HASH_MASK,t=this.head[e];return this.prev[this.strstart&Sc.WMASK]=t,this.head[e]=this.strstart,this.insertHashIndex=e,65535&t}fillWindow(){if(this.strstart>=Sc.WSIZE+Sc.MAX_DIST&&this.slideWindow(),this.lookahead<Sc.MIN_LOOKAHEAD&&this.inputOff<this.inputEnd){let e=2*Sc.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>=Sc.MIN_MATCH&&this.updateHash()}slideWindow(){this.window.set(this.window.subarray(Sc.WSIZE,Sc.WSIZE+Sc.WSIZE),0),this.matchStart-=Sc.WSIZE,this.strstart-=Sc.WSIZE,this.blockStart-=Sc.WSIZE;for(let e=0;e<Sc.HASH_SIZE;++e){const t=65535&this.head[e];this.head[e]=t>=Sc.WSIZE?t-Sc.WSIZE:0}for(let e=0;e<Sc.WSIZE;e++){const t=65535&this.prev[e];this.prev[e]=t>=Sc.WSIZE?t-Sc.WSIZE:0}}}Bc.TooFar=4096;class kc{get isFlushed(){return 0===this._end}constructor(e){this._start=0,this._end=0,this._bits=0,this.bitCount=0,this._buffer=new Uint8Array(e)}reset(){this._start=0,this._end=0,this.bitCount=0}writeShortMSB(e){this._buffer[this._end++]=e>>8&255,this._buffer[this._end++]=255&e}writeShort(e){this._buffer[this._end++]=e,this._buffer[this._end++]=e>>8}writeBlock(e,t,s){this._buffer.set(e.subarray(t,t+s),this._end),this._end+=s}flush(e,t,s){return this.bitCount>=8&&(this._buffer[this._end++]=255&this._bits,this._bits>>=8,this.bitCount-=8),s>this._end-this._start?(s=this._end-this._start,e.set(this._buffer.subarray(this._start,this._start+s),t),this._start=0,this._end=0):(e.set(this._buffer.subarray(this._start,this._start+s),t),this._start+=s),s}writeBits(e,t){this._bits|=e<<this.bitCount,this.bitCount+=t,this.bitCount>=16&&(this._buffer[this._end++]=255&this._bits,this._buffer[this._end++]=this._bits>>8&255,this._bits>>=16,this.bitCount-=16)}alignToByte(){this.bitCount>0&&(this._buffer[this._end++]=255&this._bits,this.bitCount>8&&(this._buffer[this._end++]=this._bits>>8&255)),this._bits=0,this.bitCount=0}}class Tc{get inputCrc(){return this._engine.inputCrc.value}constructor(){this._state=0,this._pending=new kc(Sc.PENDING_BUF_SIZE),this._engine=new Bc(this._pending),this.reset()}get isNeedingInput(){return this._engine.needsInput()}get isFinished(){return this._state===Tc.FinishedState&&this._pending.isFlushed}reset(){this._state=Tc.BusyState,this._pending.reset(),this._engine.reset()}setInput(e,t,s){this._engine.setInput(e,t,s)}deflate(e,t,s){const i=s;for(;;){const a=this._pending.flush(e,t,s);if(t+=a,0===(s-=a)||this._state===Tc.FinishedState)break;if(!this._engine.deflate(!!(this._state&Tc.IsFlushing),!!(this._state&Tc.IsFinishing)))switch(this._state){case Tc.BusyState:return i-s;case Tc.FlushingState:let e=8+(7&-this._pending.bitCount);for(;e>0;)this._pending.writeBits(2,10),e-=10;this._state=Tc.BusyState;break;case Tc.FinishingState:this._pending.alignToByte(),this._state=Tc.FinishedState}}return i-s}finish(){this._state|=Tc.IsFlushing|Tc.IsFinishing}}Tc.IsFlushing=4,Tc.IsFinishing=8,Tc.BusyState=16,Tc.FlushingState=20,Tc.FinishingState=28,Tc.FinishedState=30;class Nc{constructor(e,t,s,i,a){this.entry=e,this.crc32=t,this.localHeaderOffset=s,this.compressionMode=i,this.compressedSize=a}}class xc{constructor(e){this._centralDirectoryHeaders=[],this._deflater=new Tc,this._data=e}writeEntry(e){const t=oi.CompressionMethodDeflate,s=Me.empty(),i=this.compress(s,e.data,t),a=s.toArray(),r=new Nc(e,i,this._data.bytesWritten,t,s.length);this._centralDirectoryHeaders.push(r),Le.writeInt32LE(this._data,oi.LocalFileHeaderSignature),Le.writeUInt16LE(this._data,10),Le.writeUInt16LE(this._data,2048),Le.writeUInt16LE(this._data,t),Le.writeInt16LE(this._data,0),Le.writeInt16LE(this._data,0),Le.writeInt32LE(this._data,i),Le.writeInt32LE(this._data,a.length),Le.writeInt32LE(this._data,e.data.length),Le.writeInt16LE(this._data,e.fullName.length),Le.writeInt16LE(this._data,0);const n=Le.stringToBytes(e.fullName);this._data.write(n,0,n.length),this._data.write(a,0,a.length)}compress(e,t,s){if(s!==oi.CompressionMethodDeflate){const s=new bc;return s.update(t,0,t.length),e.write(t,0,t.length),s.value}const 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){Le.writeInt32LE(this._data,oi.EndOfCentralDirSignature),Le.writeInt16LE(this._data,0),Le.writeInt16LE(this._data,0),Le.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Le.writeInt16LE(this._data,this._centralDirectoryHeaders.length),Le.writeInt32LE(this._data,t-e),Le.writeInt32LE(this._data,e),Le.writeInt16LE(this._data,0)}writeCentralDirectoryHeader(e){Le.writeInt32LE(this._data,oi.CentralFileHeaderSignature),Le.writeUInt16LE(this._data,10),Le.writeUInt16LE(this._data,10),Le.writeUInt16LE(this._data,2048),Le.writeUInt16LE(this._data,e.compressionMode),Le.writeInt16LE(this._data,0),Le.writeInt16LE(this._data,0),Le.writeInt32LE(this._data,e.crc32),Le.writeInt32LE(this._data,e.compressedSize),Le.writeInt32LE(this._data,e.entry.data.length),Le.writeInt16LE(this._data,e.entry.fullName.length),Le.writeInt16LE(this._data,0),Le.writeInt16LE(this._data,0),Le.writeInt16LE(this._data,0),Le.writeInt16LE(this._data,0),Le.writeInt32LE(this._data,0),Le.writeInt32LE(this._data,e.localHeaderOffset);const t=Le.stringToBytes(e.entry.fullName);this._data.write(t,0,t.length)}}const vc=Object.freeze(Object.defineProperty({__proto__:null,Gp7Exporter:class extends gc{get name(){return"Guitar Pro 7"}writeScore(e){wt.debug(this.name,"Writing data entries");const t=(new yc).writeXml(e),s=Ws.writeForScore(e),i=js.writeForScore(e),a=di.writeForScore(e);wt.debug(this.name,"Writing ZIP entries");const r=new xc(this.data);r.writeEntry(new oi("VERSION",Le.stringToBytes("7.0"))),r.writeEntry(new oi("Content/",new Uint8Array(0))),r.writeEntry(new oi("Content/BinaryStylesheet",s)),r.writeEntry(new oi("Content/PartConfiguration",i)),r.writeEntry(new oi("Content/LayoutConfiguration",a)),r.writeEntry(new oi("Content/score.gpif",Le.stringToBytes(t))),r.end()}},ScoreExporter:gc},Symbol.toStringTag,{value:"Module"}));class Pc extends Re{constructor(){super(0,0,U.EndOfTrack)}writeTo(e){throw new fe(S.General,"Deprecated event, serialization not supported")}}var Fc,Cc,Dc;!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"}(Fc||(Fc={}));class Ec extends Pc{get metaStatus(){return Fc.EndOfTrack}}!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"}(Cc||(Cc={}));class Lc extends Pc{}!function(e){e[e.MetronomeTick=0]="MetronomeTick",e[e.Rest=1]="Rest"}(Dc||(Dc={}));class Mc extends Lc{constructor(){super(...arguments),this.data=new Uint8Array}get isMetronome(){return!1}get metronomeNumerator(){return-1}get metronomeDurationInTicks(){return-1}get metronomeDurationInMilliseconds(){return-1}get isRest(){return!1}get manufacturerId(){return 0}}Mc.AlphaTabManufacturerId=125;const Ic=Object.freeze(Object.defineProperty({__proto__:null,AlphaSynthMidiFileHandler:mr,AlphaTabMetronomeEvent:We,AlphaTabRestEvent:Ve,AlphaTabSysExEvent:He,get AlphaTabSystemExclusiveEvents(){return Dc},BeatTickLookup:Sr,BeatTickLookupItem:br,ControlChangeEvent:Xe,get ControllerType(){return Ji},DeprecatedMidiEvent:Pc,EndOfTrackEvent:Ke,MasterBarTickLookup:wr,MasterBarTickLookupTempoChange:_r,MetaDataEvent:class extends Ec{constructor(){super(...arguments),this.data=new Uint8Array}},MetaEvent:Ec,get MetaEventType(){return Fc},MetaNumberEvent:class extends Ec{constructor(){super(...arguments),this.value=0}},Midi20PerNotePitchBendEvent:class extends Pc{constructor(){super(...arguments),this.noteKey=0,this.pitch=0}},MidiEvent:Re,get MidiEventType(){return U},MidiFile:Ae,get MidiFileFormat(){return z},MidiFileGenerator:vr,MidiTickLookup:kr,MidiTickLookupFindBeatResult:Br,get MidiTickLookupFindBeatResultCursorMode(){return $i},MidiTrack:Ie,NoteBendEvent:qe,NoteEvent:Ge,NoteOffEvent:Ue,NoteOnEvent:ze,PitchBendEvent:$e,ProgramChangeEvent:Je,SystemCommonEvent:Lc,get SystemCommonType(){return Cc},SystemExclusiveEvent:Mc,TempoChangeEvent:Ye,TimeSignatureEvent:Oe},Symbol.toStringTag,{value:"Module"})),Ac=Object.freeze(Object.defineProperty({__proto__:null,ActiveBeatsChangedEventArgs:Rr,AlphaSynth:cr,AlphaSynthAudioWorkletOutput:Zr,AlphaSynthScriptProcessorOutput:$r,AlphaSynthWebAudioOutputBase:Yr,AlphaSynthWebWorkerApi:Kr,CircularSampleBuffer:Xr,MidiEventsPlayedEventArgs:hr,PlaybackRange:Pr,PlaybackRangeChangedEventArgs:lr,get PlayerState(){return Hi},PlayerStateChangedEventArgs:ia,PositionChangedEventArgs:aa},Symbol.toStringTag,{value:"Module"})),Rc=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{sn as AlphaTabApi,Hr as AlphaTabApiBase,fe as AlphaTabError,S as AlphaTabErrorType,_t as ConsoleLogger,dc as CoreSettings,Qe as DisplaySettings,cc as Environment,Wr as FileLoadError,B as FingeringMode,ye as FormatError,Ze as ImporterSettings,e as LayoutMode,$ as LogLevel,wt as Logger,T as NotationElement,k as NotationMode,be as NotationSettings,Y as PlayerOutputMode,st as PlayerSettings,qr as ProgressEventArgs,lc as RenderEngineFactory,je as RenderingResources,Ar as ResizeEventArgs,J as ScrollMode,ut as Settings,tt as SlidePlaybackSettings,t as StaveProfile,X as SystemsLayoutMode,w as TabRhythmMode,et as VibratoPlaybackSettings,us as WebPlatform,vc as exporter,uc as importer,pc as io,Rc as json,oc as meta,Ic as midi,as as model,_s as platform,Pi as rendering,Ac as synth};